diff options
Diffstat (limited to 'modules/mbedtls')
-rw-r--r-- | modules/mbedtls/crypto_mbedtls.cpp | 285 | ||||
-rw-r--r-- | modules/mbedtls/crypto_mbedtls.h | 124 | ||||
-rwxr-xr-x | modules/mbedtls/register_types.cpp | 6 | ||||
-rw-r--r-- | modules/mbedtls/ssl_context_mbedtls.cpp | 151 | ||||
-rw-r--r-- | modules/mbedtls/ssl_context_mbedtls.h | 73 | ||||
-rwxr-xr-x | modules/mbedtls/stream_peer_mbedtls.cpp (renamed from modules/mbedtls/stream_peer_mbed_tls.cpp) | 99 | ||||
-rwxr-xr-x | modules/mbedtls/stream_peer_mbedtls.h (renamed from modules/mbedtls/stream_peer_mbed_tls.h) | 22 |
7 files changed, 672 insertions, 88 deletions
diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp new file mode 100644 index 0000000000..1e02084ae2 --- /dev/null +++ b/modules/mbedtls/crypto_mbedtls.cpp @@ -0,0 +1,285 @@ +/*************************************************************************/ +/* crypto_mbedtls.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "crypto_mbedtls.h" + +#include "core/os/file_access.h" + +#include "core/engine.h" +#include "core/io/certs_compressed.gen.h" +#include "core/io/compression.h" +#include "core/project_settings.h" + +#ifdef TOOLS_ENABLED +#include "editor/editor_settings.h" +#endif +#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n" +#define PEM_END_CRT "-----END CERTIFICATE-----\n" + +#include "mbedtls/pem.h" +#include <mbedtls/debug.h> + +CryptoKey *CryptoKeyMbedTLS::create() { + return memnew(CryptoKeyMbedTLS); +} + +Error CryptoKeyMbedTLS::load(String p_path) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use"); + + PoolByteArray out; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER); + + int flen = f->get_len(); + out.resize(flen + 1); + { + PoolByteArray::Write w = out.write(); + f->get_buffer(w.ptr(), flen); + w[flen] = 0; //end f string + } + memdelete(f); + + int ret = mbedtls_pk_parse_key(&pkey, out.read().ptr(), out.size(), NULL, 0); + // We MUST zeroize the memory for safety! + mbedtls_platform_zeroize(out.write().ptr(), out.size()); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing private key: " + itos(ret)); + + return OK; +} + +Error CryptoKeyMbedTLS::save(String p_path) { + FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER); + + unsigned char w[16000]; + memset(w, 0, sizeof(w)); + + int ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w)); + if (ret != 0) { + memdelete(f); + memset(w, 0, sizeof(w)); // Zeroize anything we might have written. + ERR_FAIL_V_MSG(FAILED, "Error writing key: " + itos(ret)); + } + + size_t len = strlen((char *)w); + f->store_buffer(w, len); + memdelete(f); + memset(w, 0, sizeof(w)); // Zeroize temporary buffer. + return OK; +} + +X509Certificate *X509CertificateMbedTLS::create() { + return memnew(X509CertificateMbedTLS); +} + +Error X509CertificateMbedTLS::load(String p_path) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); + + PoolByteArray out; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER); + + int flen = f->get_len(); + out.resize(flen + 1); + { + PoolByteArray::Write w = out.write(); + f->get_buffer(w.ptr(), flen); + w[flen] = 0; //end f string + } + memdelete(f); + + int ret = mbedtls_x509_crt_parse(&cert, out.read().ptr(), out.size()); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret)); + + return OK; +} + +Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); + + int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing certificates: " + itos(ret)); + return OK; +} + +Error X509CertificateMbedTLS::save(String p_path) { + FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER); + + mbedtls_x509_crt *crt = &cert; + while (crt) { + unsigned char w[4096]; + size_t wrote = 0; + int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote); + if (ret != 0 || wrote == 0) { + memdelete(f); + ERR_FAIL_V_MSG(FAILED, "Error writing certificate: " + itos(ret)); + } + + f->store_buffer(w, wrote - 1); // don't write the string terminator + crt = crt->next; + } + memdelete(f); + return OK; +} + +Crypto *CryptoMbedTLS::create() { + return memnew(CryptoMbedTLS); +} + +void CryptoMbedTLS::initialize_crypto() { + +#ifdef DEBUG_ENABLED + mbedtls_debug_set_threshold(1); +#endif + + Crypto::_create = create; + Crypto::_load_default_certificates = load_default_certificates; + X509CertificateMbedTLS::make_default(); + CryptoKeyMbedTLS::make_default(); +} + +void CryptoMbedTLS::finalize_crypto() { + Crypto::_create = NULL; + Crypto::_load_default_certificates = NULL; + if (default_certs) { + memdelete(default_certs); + default_certs = NULL; + } + X509CertificateMbedTLS::finalize(); + CryptoKeyMbedTLS::finalize(); +} + +CryptoMbedTLS::CryptoMbedTLS() { + mbedtls_ctr_drbg_init(&ctr_drbg); + mbedtls_entropy_init(&entropy); + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); + if (ret != 0) { + ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + } +} + +CryptoMbedTLS::~CryptoMbedTLS() { + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&entropy); +} + +X509CertificateMbedTLS *CryptoMbedTLS::default_certs = NULL; + +X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() { + return default_certs; +} + +void CryptoMbedTLS::load_default_certificates(String p_path) { + ERR_FAIL_COND(default_certs != NULL); + + default_certs = memnew(X509CertificateMbedTLS); + ERR_FAIL_COND(default_certs == NULL); + + String certs_path = GLOBAL_DEF("network/ssl/certificates", ""); + + if (p_path != "") { + // Use certs defined in project settings. + default_certs->load(p_path); + } +#ifdef BUILTIN_CERTS_ENABLED + else { + // Use builtin certs only if user did not override it in project settings. + PoolByteArray out; + out.resize(_certs_uncompressed_size + 1); + PoolByteArray::Write w = out.write(); + Compression::decompress(w.ptr(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE); + w[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator +#ifdef DEBUG_ENABLED + print_verbose("Loaded builtin certs"); +#endif + default_certs->load_from_memory(out.read().ptr(), out.size()); + } +#endif +} + +Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) { + Ref<CryptoKeyMbedTLS> out; + out.instance(); + int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)); + ERR_FAIL_COND_V(ret != 0, NULL); + ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537); + ERR_FAIL_COND_V(ret != 0, NULL); + return out; +} + +Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) { + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS> >(p_key); + mbedtls_x509write_cert crt; + mbedtls_x509write_crt_init(&crt); + + mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey)); + mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey)); + mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data()); + mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data()); + mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3); + mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256); + + mbedtls_mpi serial; + mbedtls_mpi_init(&serial); + uint8_t rand_serial[20]; + mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, 20); + ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), NULL); + mbedtls_x509write_crt_set_serial(&crt, &serial); + + mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data()); + mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1); + mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0); + + unsigned char buf[4096]; + memset(buf, 0, 4096); + Ref<X509CertificateMbedTLS> out; + out.instance(); + mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg); + + int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096); + if (err != 0) { + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&crt); + ERR_PRINTS("Generated invalid certificate: " + itos(err)); + return NULL; + } + + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&crt); + return out; +} + +PoolByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) { + PoolByteArray out; + out.resize(p_bytes); + mbedtls_ctr_drbg_random(&ctr_drbg, out.write().ptr(), p_bytes); + return out; +} diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h new file mode 100644 index 0000000000..06b3ecd234 --- /dev/null +++ b/modules/mbedtls/crypto_mbedtls.h @@ -0,0 +1,124 @@ +/*************************************************************************/ +/* crypto_mbedtls.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef CRYPTO_MBEDTLS_H +#define CRYPTO_MBEDTLS_H + +#include "core/crypto/crypto.h" +#include "core/resource.h" + +#include <mbedtls/ctr_drbg.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ssl.h> + +class CryptoMbedTLS; +class SSLContextMbedTLS; +class CryptoKeyMbedTLS : public CryptoKey { + +private: + mbedtls_pk_context pkey; + int locks; + +public: + static CryptoKey *create(); + static void make_default() { CryptoKey::_create = create; } + static void finalize() { CryptoKey::_create = NULL; } + + virtual Error load(String p_path); + virtual Error save(String p_path); + + CryptoKeyMbedTLS() { + mbedtls_pk_init(&pkey); + locks = 0; + } + ~CryptoKeyMbedTLS() { + mbedtls_pk_free(&pkey); + } + + _FORCE_INLINE_ void lock() { locks++; } + _FORCE_INLINE_ void unlock() { locks--; } + + friend class CryptoMbedTLS; + friend class SSLContextMbedTLS; +}; + +class X509CertificateMbedTLS : public X509Certificate { + +private: + mbedtls_x509_crt cert; + int locks; + +public: + static X509Certificate *create(); + static void make_default() { X509Certificate::_create = create; } + static void finalize() { X509Certificate::_create = NULL; } + + virtual Error load(String p_path); + virtual Error load_from_memory(const uint8_t *p_buffer, int p_len); + virtual Error save(String p_path); + + X509CertificateMbedTLS() { + mbedtls_x509_crt_init(&cert); + locks = 0; + } + ~X509CertificateMbedTLS() { + mbedtls_x509_crt_free(&cert); + } + + _FORCE_INLINE_ void lock() { locks++; } + _FORCE_INLINE_ void unlock() { locks--; } + + friend class CryptoMbedTLS; + friend class SSLContextMbedTLS; +}; + +class CryptoMbedTLS : public Crypto { + +private: + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + static X509CertificateMbedTLS *default_certs; + +public: + static Crypto *create(); + static void initialize_crypto(); + static void finalize_crypto(); + static X509CertificateMbedTLS *get_default_certificates(); + static void load_default_certificates(String p_path); + + virtual PoolByteArray generate_random_bytes(int p_bytes); + virtual Ref<CryptoKey> generate_rsa(int p_bytes); + virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after); + + CryptoMbedTLS(); + ~CryptoMbedTLS(); +}; + +#endif // CRYPTO_MBEDTLS_H diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp index 121ed5eb02..f7dc6c785f 100755 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -30,15 +30,17 @@ #include "register_types.h" -#include "stream_peer_mbed_tls.h" +#include "crypto_mbedtls.h" +#include "stream_peer_mbedtls.h" void register_mbedtls_types() { - ClassDB::register_class<StreamPeerMbedTLS>(); + CryptoMbedTLS::initialize_crypto(); StreamPeerMbedTLS::initialize_ssl(); } void unregister_mbedtls_types() { StreamPeerMbedTLS::finalize_ssl(); + CryptoMbedTLS::finalize_crypto(); } diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp new file mode 100644 index 0000000000..97b5e23f58 --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.cpp @@ -0,0 +1,151 @@ +/*************************************************************************/ +/* ssl_context_mbed_tls.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "ssl_context_mbedtls.h" + +static void my_debug(void *ctx, int level, + const char *file, int line, + const char *str) { + + printf("%s:%04d: %s", file, line, str); + fflush(stdout); +} + +Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) { + ERR_FAIL_COND_V_MSG(inited, ERR_ALREADY_IN_USE, "This SSL context is already active"); + + mbedtls_ssl_init(&ssl); + mbedtls_ssl_config_init(&conf); + mbedtls_ctr_drbg_init(&ctr_drbg); + mbedtls_entropy_init(&entropy); + inited = true; + + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); + if (ret != 0) { + clear(); // Never leave unusable resources around. + ERR_FAIL_V_MSG(FAILED, "mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + } + + ret = mbedtls_ssl_config_defaults(&conf, p_endpoint, p_transport, MBEDTLS_SSL_PRESET_DEFAULT); + if (ret != 0) { + clear(); + ERR_FAIL_V_MSG(FAILED, "mbedtls_ssl_config_defaults returned an error" + itos(ret)); + } + mbedtls_ssl_conf_authmode(&conf, p_authmode); + mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); + mbedtls_ssl_conf_dbg(&conf, my_debug, stdout); + return OK; +} + +Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert) { + ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER); + + Error err = _setup(MBEDTLS_SSL_IS_SERVER, p_transport, p_authmode); + ERR_FAIL_COND_V(err != OK, err); + + // Locking key and certificate(s) + pkey = p_pkey; + certs = p_cert; + if (pkey.is_valid()) + pkey->lock(); + if (certs.is_valid()) + certs->lock(); + + // Adding key and certificate + int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey)); + if (ret != 0) { + clear(); + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid cert/key combination " + itos(ret)); + } + // Adding CA chain if available. + if (certs->cert.next) { + mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, NULL); + } + mbedtls_ssl_setup(&ssl, &conf); + return OK; +} + +Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) { + Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode); + ERR_FAIL_COND_V(err != OK, err); + + X509CertificateMbedTLS *cas = NULL; + + if (p_valid_cas.is_valid()) { + // Locking CA certificates + certs = p_valid_cas; + certs->lock(); + cas = certs.ptr(); + } else { + // Fall back to default certificates (no need to lock those). + cas = CryptoMbedTLS::get_default_certificates(); + if (cas == NULL) { + clear(); + ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "SSL module failed to initialize!"); + } + } + + // Set valid CAs + mbedtls_ssl_conf_ca_chain(&conf, &(cas->cert), NULL); + mbedtls_ssl_setup(&ssl, &conf); + return OK; +} + +void SSLContextMbedTLS::clear() { + if (!inited) + return; + mbedtls_ssl_free(&ssl); + mbedtls_ssl_config_free(&conf); + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&entropy); + + // Unlock and key and certificates + if (certs.is_valid()) + certs->unlock(); + certs = Ref<X509Certificate>(); + if (pkey.is_valid()) + pkey->unlock(); + pkey = Ref<CryptoKeyMbedTLS>(); + inited = false; +} + +mbedtls_ssl_context *SSLContextMbedTLS::get_context() { + ERR_FAIL_COND_V(!inited, NULL); + return &ssl; +} + +SSLContextMbedTLS::SSLContextMbedTLS() { + inited = false; +} + +SSLContextMbedTLS::~SSLContextMbedTLS() { + clear(); +} diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h new file mode 100644 index 0000000000..b78ee37b03 --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.h @@ -0,0 +1,73 @@ +/*************************************************************************/ +/* ssl_context_mbed_tls.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef SSL_CONTEXT_MBED_TLS_H +#define SSL_CONTEXT_MBED_TLS_H + +#include "crypto_mbedtls.h" + +#include "core/os/file_access.h" +#include "core/pool_vector.h" +#include "core/reference.h" + +#include <mbedtls/config.h> +#include <mbedtls/ctr_drbg.h> +#include <mbedtls/debug.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ssl.h> + +class SSLContextMbedTLS : public Reference { + +protected: + bool inited; + + static PoolByteArray _read_file(String p_path); + +public: + Ref<X509CertificateMbedTLS> certs; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + + Ref<CryptoKeyMbedTLS> pkey; + + Error _setup(int p_endpoint, int p_transport, int p_authmode); + Error init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert); + Error init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas); + void clear(); + + mbedtls_ssl_context *get_context(); + + SSLContextMbedTLS(); + ~SSLContextMbedTLS(); +}; + +#endif // SSL_CONTEXT_MBED_TLS_H diff --git a/modules/mbedtls/stream_peer_mbed_tls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index 4bb7557150..e2eb19fc74 100755 --- a/modules/mbedtls/stream_peer_mbed_tls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -28,19 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "stream_peer_mbed_tls.h" +#include "stream_peer_mbedtls.h" #include "core/io/stream_peer_tcp.h" #include "core/os/file_access.h" -static void my_debug(void *ctx, int level, - const char *file, int line, - const char *str) { - - printf("%s:%04d: %s", file, line, str); - fflush(stdout); -} - void _print_error(int ret) { printf("mbedtls error: returned -0x%x\n\n", -ret); fflush(stdout); @@ -86,18 +78,14 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { void StreamPeerMbedTLS::_cleanup() { - mbedtls_ssl_free(&ssl); - mbedtls_ssl_config_free(&conf); - mbedtls_ctr_drbg_free(&ctr_drbg); - mbedtls_entropy_free(&entropy); - + ssl_ctx->clear(); base = Ref<StreamPeer>(); status = STATUS_DISCONNECTED; } Error StreamPeerMbedTLS::_do_handshake() { int ret = 0; - while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) { + while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { // An error occurred. ERR_PRINTS("TLS handshake error: " + itos(ret)); @@ -118,7 +106,7 @@ Error StreamPeerMbedTLS::_do_handshake() { return OK; } -Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) { +Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) { ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); @@ -126,31 +114,11 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida int ret = 0; int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE; - mbedtls_ssl_init(&ssl); - mbedtls_ssl_config_init(&conf); - mbedtls_ctr_drbg_init(&ctr_drbg); - mbedtls_entropy_init(&entropy); - - ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); - if (ret != 0) { - ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); - _cleanup(); - return FAILED; - } + Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs); + ERR_FAIL_COND_V(err != OK, err); - mbedtls_ssl_config_defaults(&conf, - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); - - mbedtls_ssl_conf_authmode(&conf, authmode); - mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL); - mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); - mbedtls_ssl_conf_dbg(&conf, my_debug, stdout); - mbedtls_ssl_setup(&ssl, &conf); - mbedtls_ssl_set_hostname(&ssl, p_for_hostname.utf8().get_data()); - - mbedtls_ssl_set_bio(&ssl, this, bio_send, bio_recv, NULL); + mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data()); + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL); status = STATUS_HANDSHAKING; @@ -162,11 +130,26 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida return OK; } -Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base) { +Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) { + + ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); + + Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert); + ERR_FAIL_COND_V(err != OK, err); + + base = p_base; + + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL); + + status = STATUS_HANDSHAKING; + + if ((err = _do_handshake()) != OK) { + return FAILED; + } + status = STATUS_CONNECTED; return OK; } - Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); @@ -197,7 +180,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in if (p_bytes == 0) return OK; - int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes); + int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Non blocking IO ret = 0; @@ -243,7 +226,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r r_received = 0; - int ret = mbedtls_ssl_read(&ssl, p_buffer, p_bytes); + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), p_buffer, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = 0; // non blocking io } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { @@ -273,7 +256,7 @@ void StreamPeerMbedTLS::poll() { // We could pass NULL as second parameter, but some behaviour sanitizers doesn't seem to like that. // Passing a 1 byte buffer to workaround it. uint8_t byte; - int ret = mbedtls_ssl_read(&ssl, &byte, 0); + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Nothing to read/write (non blocking IO) @@ -298,10 +281,11 @@ int StreamPeerMbedTLS::get_available_bytes() const { ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); - return mbedtls_ssl_get_bytes_avail(&ssl); + return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)); } StreamPeerMbedTLS::StreamPeerMbedTLS() { + ssl_ctx.instance(); status = STATUS_DISCONNECTED; } @@ -317,7 +301,7 @@ void StreamPeerMbedTLS::disconnect_from_stream() { Ref<StreamPeerTCP> tcp = base; if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) { // We are still connected on the socket, try to send close notify. - mbedtls_ssl_close_notify(&ssl); + mbedtls_ssl_close_notify(ssl_ctx->get_context()); } _cleanup(); @@ -333,28 +317,9 @@ StreamPeerSSL *StreamPeerMbedTLS::_create_func() { return memnew(StreamPeerMbedTLS); } -mbedtls_x509_crt StreamPeerMbedTLS::cacert; - -void StreamPeerMbedTLS::_load_certs(const PoolByteArray &p_array) { - int arr_len = p_array.size(); - PoolByteArray::Read r = p_array.read(); - int err = mbedtls_x509_crt_parse(&cacert, &r[0], arr_len); - if (err != 0) { - WARN_PRINTS("Error parsing some certificates: " + itos(err)); - } -} - void StreamPeerMbedTLS::initialize_ssl() { _create = _create_func; - load_certs_func = _load_certs; - - mbedtls_x509_crt_init(&cacert); - -#ifdef DEBUG_ENABLED - mbedtls_debug_set_threshold(1); -#endif - available = true; } @@ -362,6 +327,4 @@ void StreamPeerMbedTLS::finalize_ssl() { available = false; _create = NULL; - load_certs_func = NULL; - mbedtls_x509_crt_free(&cacert); } diff --git a/modules/mbedtls/stream_peer_mbed_tls.h b/modules/mbedtls/stream_peer_mbedtls.h index ab87b779c1..060e76b4f3 100755 --- a/modules/mbedtls/stream_peer_mbed_tls.h +++ b/modules/mbedtls/stream_peer_mbedtls.h @@ -32,15 +32,7 @@ #define STREAM_PEER_OPEN_SSL_H #include "core/io/stream_peer_ssl.h" - -#include <mbedtls/config.h> -#include <mbedtls/ctr_drbg.h> -#include <mbedtls/debug.h> -#include <mbedtls/entropy.h> -#include <mbedtls/ssl.h> - -#include <stdio.h> -#include <stdlib.h> +#include "ssl_context_mbedtls.h" class StreamPeerMbedTLS : public StreamPeerSSL { private: @@ -50,19 +42,13 @@ private: Ref<StreamPeer> base; static StreamPeerSSL *_create_func(); - static void _load_certs(const PoolByteArray &p_array); static int bio_recv(void *ctx, unsigned char *buf, size_t len); static int bio_send(void *ctx, const unsigned char *buf, size_t len); void _cleanup(); protected: - static mbedtls_x509_crt cacert; - - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; - mbedtls_ssl_config conf; + Ref<SSLContextMbedTLS> ssl_ctx; static void _bind_methods(); @@ -70,8 +56,8 @@ protected: public: virtual void poll(); - virtual Error accept_stream(Ref<StreamPeer> p_base); - virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()); + virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>()); + virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>()); virtual Status get_status() const; virtual void disconnect_from_stream(); |