crypto_mbedtls.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /**************************************************************************/
  2. /* crypto_mbedtls.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "crypto_mbedtls.h"
  31. #include "core/io/certs_compressed.gen.h"
  32. #include "core/io/compression.h"
  33. #include "core/io/file_access.h"
  34. #include "core/os/os.h"
  35. #include <mbedtls/debug.h>
  36. #include <mbedtls/md.h>
  37. #include <mbedtls/pem.h>
  38. #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
  39. #define PEM_END_CRT "-----END CERTIFICATE-----\n"
  40. #define PEM_MIN_SIZE 54
  41. CryptoKey *CryptoKeyMbedTLS::create(bool p_notify_postinitialize) {
  42. return static_cast<CryptoKey *>(ClassDB::creator<CryptoKeyMbedTLS>(p_notify_postinitialize));
  43. }
  44. Error CryptoKeyMbedTLS::load(const String &p_path, bool p_public_only) {
  45. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
  46. PackedByteArray out;
  47. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  48. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'.");
  49. uint64_t flen = f->get_length();
  50. out.resize(flen + 1);
  51. f->get_buffer(out.ptrw(), flen);
  52. out.write[flen] = 0; // string terminator
  53. int ret = 0;
  54. if (p_public_only) {
  55. ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size());
  56. } else {
  57. ret = _parse_key(out.ptr(), out.size());
  58. }
  59. // We MUST zeroize the memory for safety!
  60. mbedtls_platform_zeroize(out.ptrw(), out.size());
  61. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
  62. public_only = p_public_only;
  63. return OK;
  64. }
  65. Error CryptoKeyMbedTLS::save(const String &p_path, bool p_public_only) {
  66. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
  67. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'.");
  68. unsigned char w[16000];
  69. memset(w, 0, sizeof(w));
  70. int ret = 0;
  71. if (p_public_only) {
  72. ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
  73. } else {
  74. ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
  75. }
  76. if (ret != 0) {
  77. mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written.
  78. ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'.");
  79. }
  80. size_t len = strlen((char *)w);
  81. f->store_buffer(w, len);
  82. mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer.
  83. return OK;
  84. }
  85. Error CryptoKeyMbedTLS::load_from_string(const String &p_string_key, bool p_public_only) {
  86. int ret = 0;
  87. const CharString string_key_utf8 = p_string_key.utf8();
  88. if (p_public_only) {
  89. ret = mbedtls_pk_parse_public_key(&pkey, (const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());
  90. } else {
  91. ret = _parse_key((const unsigned char *)string_key_utf8.get_data(), string_key_utf8.size());
  92. }
  93. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
  94. public_only = p_public_only;
  95. return OK;
  96. }
  97. String CryptoKeyMbedTLS::save_to_string(bool p_public_only) {
  98. unsigned char w[16000];
  99. memset(w, 0, sizeof(w));
  100. int ret = 0;
  101. if (p_public_only) {
  102. ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
  103. } else {
  104. ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
  105. }
  106. if (ret != 0) {
  107. mbedtls_platform_zeroize(w, sizeof(w));
  108. ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'.");
  109. }
  110. String s = String::utf8((char *)w);
  111. return s;
  112. }
  113. int CryptoKeyMbedTLS::_parse_key(const uint8_t *p_buf, int p_size) {
  114. #if MBEDTLS_VERSION_MAJOR >= 3
  115. mbedtls_entropy_context rng_entropy;
  116. mbedtls_ctr_drbg_context rng_drbg;
  117. mbedtls_ctr_drbg_init(&rng_drbg);
  118. mbedtls_entropy_init(&rng_entropy);
  119. int ret = mbedtls_ctr_drbg_seed(&rng_drbg, mbedtls_entropy_func, &rng_entropy, nullptr, 0);
  120. ERR_FAIL_COND_V_MSG(ret != 0, ret, vformat("mbedtls_ctr_drbg_seed returned -0x%x\n", (unsigned int)-ret));
  121. ret = mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0, mbedtls_ctr_drbg_random, &rng_drbg);
  122. mbedtls_ctr_drbg_free(&rng_drbg);
  123. mbedtls_entropy_free(&rng_entropy);
  124. return ret;
  125. #else
  126. return mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0);
  127. #endif
  128. }
  129. X509Certificate *X509CertificateMbedTLS::create(bool p_notify_postinitialize) {
  130. return static_cast<X509Certificate *>(ClassDB::creator<X509CertificateMbedTLS>(p_notify_postinitialize));
  131. }
  132. Error X509CertificateMbedTLS::load(const String &p_path) {
  133. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  134. PackedByteArray out;
  135. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  136. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot open X509CertificateMbedTLS file '%s'.", p_path));
  137. uint64_t flen = f->get_length();
  138. out.resize(flen + 1);
  139. f->get_buffer(out.ptrw(), flen);
  140. out.write[flen] = 0; // string terminator
  141. int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());
  142. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates from file '%s': %d.", p_path, ret));
  143. if (ret > 0) { // Some certs parsed fine, don't error.
  144. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed from file '%s' (%d certificates skipped).", p_path, ret));
  145. }
  146. return OK;
  147. }
  148. Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {
  149. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  150. int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);
  151. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
  152. if (ret > 0) { // Some certs parsed fine, don't error.
  153. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
  154. }
  155. return OK;
  156. }
  157. Error X509CertificateMbedTLS::save(const String &p_path) {
  158. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
  159. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot save X509CertificateMbedTLS file '%s'.", p_path));
  160. mbedtls_x509_crt *crt = &cert;
  161. while (crt) {
  162. unsigned char w[4096];
  163. size_t wrote = 0;
  164. int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
  165. if (ret != 0 || wrote == 0) {
  166. ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'.");
  167. }
  168. f->store_buffer(w, wrote - 1); // don't write the string terminator
  169. crt = crt->next;
  170. }
  171. return OK;
  172. }
  173. String X509CertificateMbedTLS::save_to_string() {
  174. String buffer;
  175. mbedtls_x509_crt *crt = &cert;
  176. while (crt) {
  177. unsigned char w[4096];
  178. size_t wrote = 0;
  179. int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
  180. ERR_FAIL_COND_V_MSG(ret != 0 || wrote == 0, String(), "Error saving the certificate.");
  181. buffer += String((char *)w, wrote);
  182. crt = crt->next;
  183. }
  184. if (buffer.length() <= PEM_MIN_SIZE) {
  185. // When the returned value of variable 'buffer' would consist of no Base-64 data, return an empty String instead.
  186. return String();
  187. }
  188. return buffer;
  189. }
  190. Error X509CertificateMbedTLS::load_from_string(const String &p_string_key) {
  191. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  192. CharString cs = p_string_key.utf8();
  193. int ret = mbedtls_x509_crt_parse(&cert, (const unsigned char *)cs.get_data(), cs.size());
  194. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
  195. if (ret > 0) { // Some certs parsed fine, don't error.
  196. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
  197. }
  198. return OK;
  199. }
  200. bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {
  201. switch (p_md_type) {
  202. case MBEDTLS_MD_SHA1:
  203. case MBEDTLS_MD_SHA256:
  204. return true;
  205. default:
  206. return false;
  207. }
  208. }
  209. HMACContext *HMACContextMbedTLS::create(bool p_notify_postinitialize) {
  210. return static_cast<HMACContext *>(ClassDB::creator<HMACContextMbedTLS>(p_notify_postinitialize));
  211. }
  212. Error HMACContextMbedTLS::start(HashingContext::HashType p_hash_type, const PackedByteArray &p_key) {
  213. ERR_FAIL_COND_V_MSG(ctx != nullptr, ERR_FILE_ALREADY_IN_USE, "HMACContext already started.");
  214. // HMAC keys can be any size.
  215. ERR_FAIL_COND_V_MSG(p_key.is_empty(), ERR_INVALID_PARAMETER, "Key must not be empty.");
  216. hash_type = p_hash_type;
  217. mbedtls_md_type_t ht = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, hash_len);
  218. bool allowed = HMACContextMbedTLS::is_md_type_allowed(ht);
  219. ERR_FAIL_COND_V_MSG(!allowed, ERR_INVALID_PARAMETER, "Unsupported hash type.");
  220. ctx = memalloc(sizeof(mbedtls_md_context_t));
  221. mbedtls_md_init((mbedtls_md_context_t *)ctx);
  222. mbedtls_md_setup((mbedtls_md_context_t *)ctx, mbedtls_md_info_from_type((mbedtls_md_type_t)ht), 1);
  223. int ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, (const uint8_t *)p_key.ptr(), (size_t)p_key.size());
  224. return ret ? FAILED : OK;
  225. }
  226. Error HMACContextMbedTLS::update(const PackedByteArray &p_data) {
  227. ERR_FAIL_NULL_V_MSG(ctx, ERR_INVALID_DATA, "Start must be called before update.");
  228. ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_PARAMETER, "Src must not be empty.");
  229. int ret = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, (const uint8_t *)p_data.ptr(), (size_t)p_data.size());
  230. return ret ? FAILED : OK;
  231. }
  232. PackedByteArray HMACContextMbedTLS::finish() {
  233. ERR_FAIL_NULL_V_MSG(ctx, PackedByteArray(), "Start must be called before finish.");
  234. ERR_FAIL_COND_V_MSG(hash_len == 0, PackedByteArray(), "Unsupported hash type.");
  235. PackedByteArray out;
  236. out.resize(hash_len);
  237. unsigned char *out_ptr = (unsigned char *)out.ptrw();
  238. int ret = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out_ptr);
  239. mbedtls_md_free((mbedtls_md_context_t *)ctx);
  240. memfree((mbedtls_md_context_t *)ctx);
  241. ctx = nullptr;
  242. hash_len = 0;
  243. ERR_FAIL_COND_V_MSG(ret, PackedByteArray(), "Error received while finishing HMAC");
  244. return out;
  245. }
  246. HMACContextMbedTLS::~HMACContextMbedTLS() {
  247. if (ctx != nullptr) {
  248. mbedtls_md_free((mbedtls_md_context_t *)ctx);
  249. memfree((mbedtls_md_context_t *)ctx);
  250. }
  251. }
  252. Crypto *CryptoMbedTLS::create(bool p_notify_postinitialize) {
  253. return static_cast<Crypto *>(ClassDB::creator<CryptoMbedTLS>(p_notify_postinitialize));
  254. }
  255. void CryptoMbedTLS::initialize_crypto() {
  256. Crypto::_create = create;
  257. Crypto::_load_default_certificates = load_default_certificates;
  258. X509CertificateMbedTLS::make_default();
  259. CryptoKeyMbedTLS::make_default();
  260. HMACContextMbedTLS::make_default();
  261. }
  262. void CryptoMbedTLS::finalize_crypto() {
  263. Crypto::_create = nullptr;
  264. Crypto::_load_default_certificates = nullptr;
  265. if (default_certs) {
  266. memdelete(default_certs);
  267. default_certs = nullptr;
  268. }
  269. X509CertificateMbedTLS::finalize();
  270. CryptoKeyMbedTLS::finalize();
  271. HMACContextMbedTLS::finalize();
  272. }
  273. CryptoMbedTLS::CryptoMbedTLS() {
  274. mbedtls_ctr_drbg_init(&ctr_drbg);
  275. mbedtls_entropy_init(&entropy);
  276. int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);
  277. if (ret != 0) {
  278. ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
  279. }
  280. }
  281. CryptoMbedTLS::~CryptoMbedTLS() {
  282. mbedtls_ctr_drbg_free(&ctr_drbg);
  283. mbedtls_entropy_free(&entropy);
  284. }
  285. X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr;
  286. X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {
  287. return default_certs;
  288. }
  289. void CryptoMbedTLS::load_default_certificates(const String &p_path) {
  290. ERR_FAIL_COND(default_certs != nullptr);
  291. default_certs = memnew(X509CertificateMbedTLS);
  292. ERR_FAIL_NULL(default_certs);
  293. if (!p_path.is_empty()) {
  294. // Use certs defined in project settings.
  295. default_certs->load(p_path);
  296. } else {
  297. // Try to use system certs otherwise.
  298. String system_certs = OS::get_singleton()->get_system_ca_certificates();
  299. if (!system_certs.is_empty()) {
  300. CharString cs = system_certs.utf8();
  301. default_certs->load_from_memory((const uint8_t *)cs.get_data(), cs.size());
  302. print_verbose("Loaded system CA certificates");
  303. }
  304. #ifdef BUILTIN_CERTS_ENABLED
  305. else {
  306. // Use builtin certs if there are no system certs.
  307. PackedByteArray certs;
  308. certs.resize(_certs_uncompressed_size + 1);
  309. Compression::decompress(certs.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
  310. certs.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
  311. default_certs->load_from_memory(certs.ptr(), certs.size());
  312. print_verbose("Loaded builtin CA certificates");
  313. }
  314. #endif
  315. }
  316. }
  317. Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
  318. Ref<CryptoKeyMbedTLS> out;
  319. out.instantiate();
  320. int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
  321. ERR_FAIL_COND_V(ret != 0, nullptr);
  322. ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
  323. out->public_only = false;
  324. ERR_FAIL_COND_V(ret != 0, nullptr);
  325. return out;
  326. }
  327. Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, const String &p_issuer_name, const String &p_not_before, const String &p_not_after) {
  328. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  329. ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument.");
  330. mbedtls_x509write_cert crt;
  331. mbedtls_x509write_crt_init(&crt);
  332. mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
  333. mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
  334. mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
  335. mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
  336. mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
  337. mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
  338. uint8_t rand_serial[20];
  339. mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, sizeof(rand_serial));
  340. #if MBEDTLS_VERSION_MAJOR >= 3
  341. mbedtls_x509write_crt_set_serial_raw(&crt, rand_serial, sizeof(rand_serial));
  342. #else
  343. mbedtls_mpi serial;
  344. mbedtls_mpi_init(&serial);
  345. ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, sizeof(rand_serial)), nullptr);
  346. mbedtls_x509write_crt_set_serial(&crt, &serial);
  347. #endif
  348. mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
  349. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
  350. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
  351. unsigned char buf[4096];
  352. memset(buf, 0, 4096);
  353. int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
  354. #if MBEDTLS_VERSION_MAJOR < 3
  355. mbedtls_mpi_free(&serial);
  356. #endif
  357. mbedtls_x509write_crt_free(&crt);
  358. ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret));
  359. buf[4095] = '\0'; // Make sure strlen can't fail.
  360. Ref<X509CertificateMbedTLS> out;
  361. out.instantiate();
  362. out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size.
  363. return out;
  364. }
  365. PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
  366. ERR_FAIL_COND_V(p_bytes < 0, PackedByteArray());
  367. PackedByteArray out;
  368. out.resize(p_bytes);
  369. int left = p_bytes;
  370. int pos = 0;
  371. // Ensure we generate random in chunks of no more than MBEDTLS_CTR_DRBG_MAX_REQUEST bytes or mbedtls_ctr_drbg_random will fail.
  372. while (left > 0) {
  373. int to_read = MIN(left, MBEDTLS_CTR_DRBG_MAX_REQUEST);
  374. int ret = mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw() + pos, to_read);
  375. ERR_FAIL_COND_V_MSG(ret != 0, PackedByteArray(), vformat("Failed to generate %d random bytes(s). Error: %d.", p_bytes, ret));
  376. left -= to_read;
  377. pos += to_read;
  378. }
  379. return out;
  380. }
  381. mbedtls_md_type_t CryptoMbedTLS::md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {
  382. switch (p_hash_type) {
  383. case HashingContext::HASH_MD5:
  384. r_size = 16;
  385. return MBEDTLS_MD_MD5;
  386. case HashingContext::HASH_SHA1:
  387. r_size = 20;
  388. return MBEDTLS_MD_SHA1;
  389. case HashingContext::HASH_SHA256:
  390. r_size = 32;
  391. return MBEDTLS_MD_SHA256;
  392. default:
  393. r_size = 0;
  394. ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");
  395. }
  396. }
  397. Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, Ref<CryptoKey> p_key) {
  398. int size;
  399. mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
  400. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");
  401. ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));
  402. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  403. ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
  404. ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");
  405. size_t sig_size = 0;
  406. #if MBEDTLS_VERSION_MAJOR >= 3
  407. unsigned char buf[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
  408. #else
  409. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  410. #endif
  411. Vector<uint8_t> out;
  412. int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf,
  413. #if MBEDTLS_VERSION_MAJOR >= 3
  414. sizeof(buf),
  415. #endif
  416. &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);
  417. ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));
  418. out.resize(sig_size);
  419. memcpy(out.ptrw(), buf, sig_size);
  420. return out;
  421. }
  422. bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, const Vector<uint8_t> &p_signature, Ref<CryptoKey> p_key) {
  423. int size;
  424. mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
  425. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");
  426. ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));
  427. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  428. ERR_FAIL_COND_V_MSG(key.is_null(), false, "Invalid key provided.");
  429. return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;
  430. }
  431. Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_plaintext) {
  432. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  433. ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
  434. uint8_t buf[1024];
  435. size_t size;
  436. Vector<uint8_t> out;
  437. int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
  438. ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret));
  439. out.resize(size);
  440. memcpy(out.ptrw(), buf, size);
  441. return out;
  442. }
  443. Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_ciphertext) {
  444. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  445. ERR_FAIL_COND_V_MSG(key.is_null(), Vector<uint8_t>(), "Invalid key provided.");
  446. ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key.");
  447. uint8_t buf[2048];
  448. size_t size;
  449. Vector<uint8_t> out;
  450. int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
  451. ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret));
  452. out.resize(size);
  453. memcpy(out.ptrw(), buf, size);
  454. return out;
  455. }