crypto_mbedtls.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. if (p_public_only) {
  88. ret = mbedtls_pk_parse_public_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size());
  89. } else {
  90. ret = _parse_key((unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size());
  91. }
  92. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
  93. public_only = p_public_only;
  94. return OK;
  95. }
  96. String CryptoKeyMbedTLS::save_to_string(bool p_public_only) {
  97. unsigned char w[16000];
  98. memset(w, 0, sizeof(w));
  99. int ret = 0;
  100. if (p_public_only) {
  101. ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
  102. } else {
  103. ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
  104. }
  105. if (ret != 0) {
  106. mbedtls_platform_zeroize(w, sizeof(w));
  107. ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'.");
  108. }
  109. String s = String::utf8((char *)w);
  110. return s;
  111. }
  112. int CryptoKeyMbedTLS::_parse_key(const uint8_t *p_buf, int p_size) {
  113. #if MBEDTLS_VERSION_MAJOR >= 3
  114. mbedtls_entropy_context rng_entropy;
  115. mbedtls_ctr_drbg_context rng_drbg;
  116. mbedtls_ctr_drbg_init(&rng_drbg);
  117. mbedtls_entropy_init(&rng_entropy);
  118. int ret = mbedtls_ctr_drbg_seed(&rng_drbg, mbedtls_entropy_func, &rng_entropy, nullptr, 0);
  119. ERR_FAIL_COND_V_MSG(ret != 0, ret, vformat("mbedtls_ctr_drbg_seed returned -0x%x\n", (unsigned int)-ret));
  120. ret = mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0, mbedtls_ctr_drbg_random, &rng_drbg);
  121. mbedtls_ctr_drbg_free(&rng_drbg);
  122. mbedtls_entropy_free(&rng_entropy);
  123. return ret;
  124. #else
  125. return mbedtls_pk_parse_key(&pkey, p_buf, p_size, nullptr, 0);
  126. #endif
  127. }
  128. X509Certificate *X509CertificateMbedTLS::create(bool p_notify_postinitialize) {
  129. return static_cast<X509Certificate *>(ClassDB::creator<X509CertificateMbedTLS>(p_notify_postinitialize));
  130. }
  131. Error X509CertificateMbedTLS::load(const String &p_path) {
  132. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  133. PackedByteArray out;
  134. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  135. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot open X509CertificateMbedTLS file '%s'.", p_path));
  136. uint64_t flen = f->get_length();
  137. out.resize(flen + 1);
  138. f->get_buffer(out.ptrw(), flen);
  139. out.write[flen] = 0; // string terminator
  140. int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());
  141. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates from file '%s': %d.", p_path, ret));
  142. if (ret > 0) { // Some certs parsed fine, don't error.
  143. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed from file '%s' (%d certificates skipped).", p_path, ret));
  144. }
  145. return OK;
  146. }
  147. Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {
  148. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  149. int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);
  150. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
  151. if (ret > 0) { // Some certs parsed fine, don't error.
  152. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
  153. }
  154. return OK;
  155. }
  156. Error X509CertificateMbedTLS::save(const String &p_path) {
  157. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
  158. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot save X509CertificateMbedTLS file '%s'.", p_path));
  159. mbedtls_x509_crt *crt = &cert;
  160. while (crt) {
  161. unsigned char w[4096];
  162. size_t wrote = 0;
  163. int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
  164. if (ret != 0 || wrote == 0) {
  165. ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'.");
  166. }
  167. f->store_buffer(w, wrote - 1); // don't write the string terminator
  168. crt = crt->next;
  169. }
  170. return OK;
  171. }
  172. String X509CertificateMbedTLS::save_to_string() {
  173. String buffer;
  174. mbedtls_x509_crt *crt = &cert;
  175. while (crt) {
  176. unsigned char w[4096];
  177. size_t wrote = 0;
  178. int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
  179. ERR_FAIL_COND_V_MSG(ret != 0 || wrote == 0, String(), "Error saving the certificate.");
  180. buffer += String((char *)w, wrote);
  181. crt = crt->next;
  182. }
  183. if (buffer.length() <= PEM_MIN_SIZE) {
  184. // When the returned value of variable 'buffer' would consist of no Base-64 data, return an empty String instead.
  185. return String();
  186. }
  187. return buffer;
  188. }
  189. Error X509CertificateMbedTLS::load_from_string(const String &p_string_key) {
  190. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is already in use.");
  191. CharString cs = p_string_key.utf8();
  192. int ret = mbedtls_x509_crt_parse(&cert, (const unsigned char *)cs.get_data(), cs.size());
  193. ERR_FAIL_COND_V_MSG(ret < 0, FAILED, vformat("Error parsing X509 certificates: %d.", ret));
  194. if (ret > 0) { // Some certs parsed fine, don't error.
  195. print_verbose(vformat("MbedTLS: Some X509 certificates could not be parsed (%d certificates skipped).", ret));
  196. }
  197. return OK;
  198. }
  199. bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {
  200. switch (p_md_type) {
  201. case MBEDTLS_MD_SHA1:
  202. case MBEDTLS_MD_SHA256:
  203. return true;
  204. default:
  205. return false;
  206. }
  207. }
  208. HMACContext *HMACContextMbedTLS::create(bool p_notify_postinitialize) {
  209. return static_cast<HMACContext *>(ClassDB::creator<HMACContextMbedTLS>(p_notify_postinitialize));
  210. }
  211. Error HMACContextMbedTLS::start(HashingContext::HashType p_hash_type, const PackedByteArray &p_key) {
  212. ERR_FAIL_COND_V_MSG(ctx != nullptr, ERR_FILE_ALREADY_IN_USE, "HMACContext already started.");
  213. // HMAC keys can be any size.
  214. ERR_FAIL_COND_V_MSG(p_key.is_empty(), ERR_INVALID_PARAMETER, "Key must not be empty.");
  215. hash_type = p_hash_type;
  216. mbedtls_md_type_t ht = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, hash_len);
  217. bool allowed = HMACContextMbedTLS::is_md_type_allowed(ht);
  218. ERR_FAIL_COND_V_MSG(!allowed, ERR_INVALID_PARAMETER, "Unsupported hash type.");
  219. ctx = memalloc(sizeof(mbedtls_md_context_t));
  220. mbedtls_md_init((mbedtls_md_context_t *)ctx);
  221. mbedtls_md_setup((mbedtls_md_context_t *)ctx, mbedtls_md_info_from_type((mbedtls_md_type_t)ht), 1);
  222. int ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, (const uint8_t *)p_key.ptr(), (size_t)p_key.size());
  223. return ret ? FAILED : OK;
  224. }
  225. Error HMACContextMbedTLS::update(const PackedByteArray &p_data) {
  226. ERR_FAIL_NULL_V_MSG(ctx, ERR_INVALID_DATA, "Start must be called before update.");
  227. ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_PARAMETER, "Src must not be empty.");
  228. int ret = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, (const uint8_t *)p_data.ptr(), (size_t)p_data.size());
  229. return ret ? FAILED : OK;
  230. }
  231. PackedByteArray HMACContextMbedTLS::finish() {
  232. ERR_FAIL_NULL_V_MSG(ctx, PackedByteArray(), "Start must be called before finish.");
  233. ERR_FAIL_COND_V_MSG(hash_len == 0, PackedByteArray(), "Unsupported hash type.");
  234. PackedByteArray out;
  235. out.resize(hash_len);
  236. unsigned char *out_ptr = (unsigned char *)out.ptrw();
  237. int ret = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out_ptr);
  238. mbedtls_md_free((mbedtls_md_context_t *)ctx);
  239. memfree((mbedtls_md_context_t *)ctx);
  240. ctx = nullptr;
  241. hash_len = 0;
  242. ERR_FAIL_COND_V_MSG(ret, PackedByteArray(), "Error received while finishing HMAC");
  243. return out;
  244. }
  245. HMACContextMbedTLS::~HMACContextMbedTLS() {
  246. if (ctx != nullptr) {
  247. mbedtls_md_free((mbedtls_md_context_t *)ctx);
  248. memfree((mbedtls_md_context_t *)ctx);
  249. }
  250. }
  251. Crypto *CryptoMbedTLS::create(bool p_notify_postinitialize) {
  252. return static_cast<Crypto *>(ClassDB::creator<CryptoMbedTLS>(p_notify_postinitialize));
  253. }
  254. void CryptoMbedTLS::initialize_crypto() {
  255. Crypto::_create = create;
  256. Crypto::_load_default_certificates = load_default_certificates;
  257. X509CertificateMbedTLS::make_default();
  258. CryptoKeyMbedTLS::make_default();
  259. HMACContextMbedTLS::make_default();
  260. }
  261. void CryptoMbedTLS::finalize_crypto() {
  262. Crypto::_create = nullptr;
  263. Crypto::_load_default_certificates = nullptr;
  264. if (default_certs) {
  265. memdelete(default_certs);
  266. default_certs = nullptr;
  267. }
  268. X509CertificateMbedTLS::finalize();
  269. CryptoKeyMbedTLS::finalize();
  270. HMACContextMbedTLS::finalize();
  271. }
  272. CryptoMbedTLS::CryptoMbedTLS() {
  273. mbedtls_ctr_drbg_init(&ctr_drbg);
  274. mbedtls_entropy_init(&entropy);
  275. int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);
  276. if (ret != 0) {
  277. ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
  278. }
  279. }
  280. CryptoMbedTLS::~CryptoMbedTLS() {
  281. mbedtls_ctr_drbg_free(&ctr_drbg);
  282. mbedtls_entropy_free(&entropy);
  283. }
  284. X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr;
  285. X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {
  286. return default_certs;
  287. }
  288. void CryptoMbedTLS::load_default_certificates(const String &p_path) {
  289. ERR_FAIL_COND(default_certs != nullptr);
  290. default_certs = memnew(X509CertificateMbedTLS);
  291. ERR_FAIL_NULL(default_certs);
  292. if (!p_path.is_empty()) {
  293. // Use certs defined in project settings.
  294. default_certs->load(p_path);
  295. } else {
  296. // Try to use system certs otherwise.
  297. String system_certs = OS::get_singleton()->get_system_ca_certificates();
  298. if (!system_certs.is_empty()) {
  299. CharString cs = system_certs.utf8();
  300. default_certs->load_from_memory((const uint8_t *)cs.get_data(), cs.size());
  301. print_verbose("Loaded system CA certificates");
  302. }
  303. #ifdef BUILTIN_CERTS_ENABLED
  304. else {
  305. // Use builtin certs if there are no system certs.
  306. PackedByteArray certs;
  307. certs.resize(_certs_uncompressed_size + 1);
  308. Compression::decompress(certs.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
  309. certs.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
  310. default_certs->load_from_memory(certs.ptr(), certs.size());
  311. print_verbose("Loaded builtin CA certificates");
  312. }
  313. #endif
  314. }
  315. }
  316. Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
  317. Ref<CryptoKeyMbedTLS> out;
  318. out.instantiate();
  319. int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
  320. ERR_FAIL_COND_V(ret != 0, nullptr);
  321. ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
  322. out->public_only = false;
  323. ERR_FAIL_COND_V(ret != 0, nullptr);
  324. return out;
  325. }
  326. 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) {
  327. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  328. ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument.");
  329. mbedtls_x509write_cert crt;
  330. mbedtls_x509write_crt_init(&crt);
  331. mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
  332. mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
  333. mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
  334. mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
  335. mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
  336. mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
  337. uint8_t rand_serial[20];
  338. mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, sizeof(rand_serial));
  339. #if MBEDTLS_VERSION_MAJOR >= 3
  340. mbedtls_x509write_crt_set_serial_raw(&crt, rand_serial, sizeof(rand_serial));
  341. #else
  342. mbedtls_mpi serial;
  343. mbedtls_mpi_init(&serial);
  344. ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, sizeof(rand_serial)), nullptr);
  345. mbedtls_x509write_crt_set_serial(&crt, &serial);
  346. #endif
  347. mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
  348. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
  349. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
  350. unsigned char buf[4096];
  351. memset(buf, 0, 4096);
  352. int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
  353. #if MBEDTLS_VERSION_MAJOR < 3
  354. mbedtls_mpi_free(&serial);
  355. #endif
  356. mbedtls_x509write_crt_free(&crt);
  357. ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret));
  358. buf[4095] = '\0'; // Make sure strlen can't fail.
  359. Ref<X509CertificateMbedTLS> out;
  360. out.instantiate();
  361. out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size.
  362. return out;
  363. }
  364. PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
  365. ERR_FAIL_COND_V(p_bytes < 0, PackedByteArray());
  366. PackedByteArray out;
  367. out.resize(p_bytes);
  368. int left = p_bytes;
  369. int pos = 0;
  370. // Ensure we generate random in chunks of no more than MBEDTLS_CTR_DRBG_MAX_REQUEST bytes or mbedtls_ctr_drbg_random will fail.
  371. while (left > 0) {
  372. int to_read = MIN(left, MBEDTLS_CTR_DRBG_MAX_REQUEST);
  373. int ret = mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw() + pos, to_read);
  374. ERR_FAIL_COND_V_MSG(ret != 0, PackedByteArray(), vformat("Failed to generate %d random bytes(s). Error: %d.", p_bytes, ret));
  375. left -= to_read;
  376. pos += to_read;
  377. }
  378. return out;
  379. }
  380. mbedtls_md_type_t CryptoMbedTLS::md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {
  381. switch (p_hash_type) {
  382. case HashingContext::HASH_MD5:
  383. r_size = 16;
  384. return MBEDTLS_MD_MD5;
  385. case HashingContext::HASH_SHA1:
  386. r_size = 20;
  387. return MBEDTLS_MD_SHA1;
  388. case HashingContext::HASH_SHA256:
  389. r_size = 32;
  390. return MBEDTLS_MD_SHA256;
  391. default:
  392. r_size = 0;
  393. ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");
  394. }
  395. }
  396. Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, Ref<CryptoKey> p_key) {
  397. int size;
  398. mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
  399. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");
  400. ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));
  401. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  402. ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
  403. ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");
  404. size_t sig_size = 0;
  405. #if MBEDTLS_VERSION_MAJOR >= 3
  406. unsigned char buf[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
  407. #else
  408. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  409. #endif
  410. Vector<uint8_t> out;
  411. int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf,
  412. #if MBEDTLS_VERSION_MAJOR >= 3
  413. sizeof(buf),
  414. #endif
  415. &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);
  416. ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));
  417. out.resize(sig_size);
  418. memcpy(out.ptrw(), buf, sig_size);
  419. return out;
  420. }
  421. bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, const Vector<uint8_t> &p_hash, const Vector<uint8_t> &p_signature, Ref<CryptoKey> p_key) {
  422. int size;
  423. mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
  424. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");
  425. ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));
  426. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  427. ERR_FAIL_COND_V_MSG(!key.is_valid(), false, "Invalid key provided.");
  428. return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;
  429. }
  430. Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_plaintext) {
  431. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  432. ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
  433. uint8_t buf[1024];
  434. size_t size;
  435. Vector<uint8_t> out;
  436. int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
  437. ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret));
  438. out.resize(size);
  439. memcpy(out.ptrw(), buf, size);
  440. return out;
  441. }
  442. Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, const Vector<uint8_t> &p_ciphertext) {
  443. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  444. ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
  445. ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key.");
  446. uint8_t buf[2048];
  447. size_t size;
  448. Vector<uint8_t> out;
  449. int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
  450. ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret));
  451. out.resize(size);
  452. memcpy(out.ptrw(), buf, size);
  453. return out;
  454. }