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