crypto_mbedtls.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /*************************************************************************/
  2. /* crypto_mbedtls.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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/os/file_access.h"
  32. #include "core/engine.h"
  33. #include "core/io/certs_compressed.gen.h"
  34. #include "core/io/compression.h"
  35. #include "core/project_settings.h"
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
  40. #define PEM_END_CRT "-----END CERTIFICATE-----\n"
  41. #include "mbedtls/pem.h"
  42. #include <mbedtls/debug.h>
  43. CryptoKey *CryptoKeyMbedTLS::create() {
  44. return memnew(CryptoKeyMbedTLS);
  45. }
  46. Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) {
  47. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
  48. PackedByteArray out;
  49. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  50. ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'.");
  51. int flen = f->get_len();
  52. out.resize(flen + 1);
  53. f->get_buffer(out.ptrw(), flen);
  54. out.write[flen] = 0; // string terminator
  55. memdelete(f);
  56. int ret = 0;
  57. if (p_public_only) {
  58. ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size());
  59. } else {
  60. ret = mbedtls_pk_parse_key(&pkey, out.ptr(), out.size(), nullptr, 0);
  61. }
  62. // We MUST zeroize the memory for safety!
  63. mbedtls_platform_zeroize(out.ptrw(), out.size());
  64. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
  65. public_only = p_public_only;
  66. return OK;
  67. }
  68. Error CryptoKeyMbedTLS::save(String p_path, bool p_public_only) {
  69. FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
  70. ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'.");
  71. unsigned char w[16000];
  72. memset(w, 0, sizeof(w));
  73. int ret = 0;
  74. if (p_public_only) {
  75. ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
  76. } else {
  77. ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
  78. }
  79. if (ret != 0) {
  80. memdelete(f);
  81. mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written.
  82. ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'.");
  83. }
  84. size_t len = strlen((char *)w);
  85. f->store_buffer(w, len);
  86. memdelete(f);
  87. mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer.
  88. return OK;
  89. }
  90. Error CryptoKeyMbedTLS::load_from_string(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 = mbedtls_pk_parse_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size(), nullptr, 0);
  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. X509Certificate *X509CertificateMbedTLS::create() {
  118. return memnew(X509CertificateMbedTLS);
  119. }
  120. Error X509CertificateMbedTLS::load(String p_path) {
  121. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use");
  122. PackedByteArray out;
  123. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  124. ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'.");
  125. int flen = f->get_len();
  126. out.resize(flen + 1);
  127. f->get_buffer(out.ptrw(), flen);
  128. out.write[flen] = 0; // string terminator
  129. memdelete(f);
  130. int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());
  131. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret));
  132. return OK;
  133. }
  134. Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {
  135. ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use");
  136. int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);
  137. ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing certificates: " + itos(ret));
  138. return OK;
  139. }
  140. Error X509CertificateMbedTLS::save(String p_path) {
  141. FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
  142. ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save X509CertificateMbedTLS file '" + p_path + "'.");
  143. mbedtls_x509_crt *crt = &cert;
  144. while (crt) {
  145. unsigned char w[4096];
  146. size_t wrote = 0;
  147. int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
  148. if (ret != 0 || wrote == 0) {
  149. memdelete(f);
  150. ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'.");
  151. }
  152. f->store_buffer(w, wrote - 1); // don't write the string terminator
  153. crt = crt->next;
  154. }
  155. memdelete(f);
  156. return OK;
  157. }
  158. Crypto *CryptoMbedTLS::create() {
  159. return memnew(CryptoMbedTLS);
  160. }
  161. void CryptoMbedTLS::initialize_crypto() {
  162. #ifdef DEBUG_ENABLED
  163. mbedtls_debug_set_threshold(1);
  164. #endif
  165. Crypto::_create = create;
  166. Crypto::_load_default_certificates = load_default_certificates;
  167. X509CertificateMbedTLS::make_default();
  168. CryptoKeyMbedTLS::make_default();
  169. }
  170. void CryptoMbedTLS::finalize_crypto() {
  171. Crypto::_create = nullptr;
  172. Crypto::_load_default_certificates = nullptr;
  173. if (default_certs) {
  174. memdelete(default_certs);
  175. default_certs = nullptr;
  176. }
  177. X509CertificateMbedTLS::finalize();
  178. CryptoKeyMbedTLS::finalize();
  179. }
  180. CryptoMbedTLS::CryptoMbedTLS() {
  181. mbedtls_ctr_drbg_init(&ctr_drbg);
  182. mbedtls_entropy_init(&entropy);
  183. int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);
  184. if (ret != 0) {
  185. ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
  186. }
  187. }
  188. CryptoMbedTLS::~CryptoMbedTLS() {
  189. mbedtls_ctr_drbg_free(&ctr_drbg);
  190. mbedtls_entropy_free(&entropy);
  191. }
  192. X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr;
  193. X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {
  194. return default_certs;
  195. }
  196. void CryptoMbedTLS::load_default_certificates(String p_path) {
  197. ERR_FAIL_COND(default_certs != nullptr);
  198. default_certs = memnew(X509CertificateMbedTLS);
  199. ERR_FAIL_COND(default_certs == nullptr);
  200. if (p_path != "") {
  201. // Use certs defined in project settings.
  202. default_certs->load(p_path);
  203. }
  204. #ifdef BUILTIN_CERTS_ENABLED
  205. else {
  206. // Use builtin certs only if user did not override it in project settings.
  207. PackedByteArray out;
  208. out.resize(_certs_uncompressed_size + 1);
  209. Compression::decompress(out.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
  210. out.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
  211. #ifdef DEBUG_ENABLED
  212. print_verbose("Loaded builtin certs");
  213. #endif
  214. default_certs->load_from_memory(out.ptr(), out.size());
  215. }
  216. #endif
  217. }
  218. Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
  219. Ref<CryptoKeyMbedTLS> out;
  220. out.instance();
  221. int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
  222. ERR_FAIL_COND_V(ret != 0, nullptr);
  223. ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
  224. out->public_only = false;
  225. ERR_FAIL_COND_V(ret != 0, nullptr);
  226. return out;
  227. }
  228. Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) {
  229. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  230. ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument.");
  231. mbedtls_x509write_cert crt;
  232. mbedtls_x509write_crt_init(&crt);
  233. mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
  234. mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
  235. mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
  236. mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
  237. mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
  238. mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
  239. mbedtls_mpi serial;
  240. mbedtls_mpi_init(&serial);
  241. uint8_t rand_serial[20];
  242. mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, 20);
  243. ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), nullptr);
  244. mbedtls_x509write_crt_set_serial(&crt, &serial);
  245. mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
  246. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
  247. mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
  248. unsigned char buf[4096];
  249. memset(buf, 0, 4096);
  250. Ref<X509CertificateMbedTLS> out;
  251. out.instance();
  252. mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
  253. int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096);
  254. if (err != 0) {
  255. mbedtls_mpi_free(&serial);
  256. mbedtls_x509write_crt_free(&crt);
  257. ERR_PRINT("Generated invalid certificate: " + itos(err));
  258. return nullptr;
  259. }
  260. mbedtls_mpi_free(&serial);
  261. mbedtls_x509write_crt_free(&crt);
  262. return out;
  263. }
  264. PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
  265. PackedByteArray out;
  266. out.resize(p_bytes);
  267. mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw(), p_bytes);
  268. return out;
  269. }
  270. mbedtls_md_type_t CryptoMbedTLS::_md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {
  271. switch (p_hash_type) {
  272. case HashingContext::HASH_MD5:
  273. r_size = 16;
  274. return MBEDTLS_MD_MD5;
  275. case HashingContext::HASH_SHA1:
  276. r_size = 20;
  277. return MBEDTLS_MD_SHA1;
  278. case HashingContext::HASH_SHA256:
  279. r_size = 32;
  280. return MBEDTLS_MD_SHA256;
  281. default:
  282. r_size = 0;
  283. ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");
  284. }
  285. }
  286. Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key) {
  287. int size;
  288. mbedtls_md_type_t type = _md_type_from_hashtype(p_hash_type, size);
  289. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");
  290. ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));
  291. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  292. ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
  293. ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");
  294. size_t sig_size = 0;
  295. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  296. Vector<uint8_t> out;
  297. int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf, &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);
  298. ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));
  299. out.resize(sig_size);
  300. copymem(out.ptrw(), buf, sig_size);
  301. return out;
  302. }
  303. bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key) {
  304. int size;
  305. mbedtls_md_type_t type = _md_type_from_hashtype(p_hash_type, size);
  306. ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");
  307. ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));
  308. Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
  309. ERR_FAIL_COND_V_MSG(!key.is_valid(), false, "Invalid key provided.");
  310. return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;
  311. }