crypto_mbedtls.cpp 20 KB

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