diff options
Diffstat (limited to 'modules/mbedtls')
| -rwxr-xr-x | modules/mbedtls/SCsub | 8 | ||||
| -rwxr-xr-x | modules/mbedtls/config.py | 1 | ||||
| -rw-r--r-- | modules/mbedtls/crypto_mbedtls.cpp | 212 | ||||
| -rw-r--r-- | modules/mbedtls/crypto_mbedtls.h | 24 | ||||
| -rw-r--r-- | modules/mbedtls/dtls_server_mbedtls.cpp | 76 | ||||
| -rw-r--r-- | modules/mbedtls/dtls_server_mbedtls.h | 57 | ||||
| -rw-r--r-- | modules/mbedtls/packet_peer_mbed_dtls.cpp | 288 | ||||
| -rwxr-xr-x | modules/mbedtls/packet_peer_mbed_dtls.h | 88 | ||||
| -rw-r--r--[-rwxr-xr-x] | modules/mbedtls/register_types.cpp | 8 | ||||
| -rwxr-xr-x | modules/mbedtls/register_types.h | 5 | ||||
| -rw-r--r-- | modules/mbedtls/ssl_context_mbedtls.cpp | 90 | ||||
| -rw-r--r-- | modules/mbedtls/ssl_context_mbedtls.h | 30 | ||||
| -rw-r--r--[-rwxr-xr-x] | modules/mbedtls/stream_peer_mbedtls.cpp | 59 |
13 files changed, 821 insertions, 125 deletions
diff --git a/modules/mbedtls/SCsub b/modules/mbedtls/SCsub index 0c6c703e16..5f5d25a3ee 100755 --- a/modules/mbedtls/SCsub +++ b/modules/mbedtls/SCsub @@ -1,11 +1,11 @@ #!/usr/bin/env python -Import('env') -Import('env_modules') +Import("env") +Import("env_modules") env_mbed_tls = env_modules.Clone() -if env['builtin_mbedtls']: +if env["builtin_mbedtls"]: # Thirdparty source files thirdparty_sources = [ "aes.c", @@ -86,7 +86,7 @@ if env['builtin_mbedtls']: "x509_csr.c", "x509write_crt.c", "x509write_csr.c", - "xtea.c" + "xtea.c", ] thirdparty_dir = "#thirdparty/mbedtls/library/" diff --git a/modules/mbedtls/config.py b/modules/mbedtls/config.py index 1c8cd12a2d..d22f9454ed 100755 --- a/modules/mbedtls/config.py +++ b/modules/mbedtls/config.py @@ -1,5 +1,6 @@ def can_build(env, platform): return True + def configure(env): pass diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp index 9b072785af..12a982df6e 100644 --- a/modules/mbedtls/crypto_mbedtls.cpp +++ b/modules/mbedtls/crypto_mbedtls.cpp @@ -43,58 +43,97 @@ #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n" #define PEM_END_CRT "-----END CERTIFICATE-----\n" -#include "mbedtls/pem.h" #include <mbedtls/debug.h> +#include <mbedtls/pem.h> CryptoKey *CryptoKeyMbedTLS::create() { return memnew(CryptoKeyMbedTLS); } -Error CryptoKeyMbedTLS::load(String p_path) { +Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) { ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use"); - PoolByteArray out; + PackedByteArray out; FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'."); 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 - } + f->get_buffer(out.ptrw(), flen); + out.write[flen] = 0; // string terminator memdelete(f); - int ret = mbedtls_pk_parse_key(&pkey, out.read().ptr(), out.size(), NULL, 0); + int ret = 0; + if (p_public_only) { + ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size()); + } else { + ret = mbedtls_pk_parse_key(&pkey, out.ptr(), out.size(), nullptr, 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) + "'."); + mbedtls_platform_zeroize(out.ptrw(), out.size()); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'."); + public_only = p_public_only; return OK; } -Error CryptoKeyMbedTLS::save(String p_path) { +Error CryptoKeyMbedTLS::save(String p_path, bool p_public_only) { FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'."); unsigned char w[16000]; memset(w, 0, sizeof(w)); - int ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w)); + int ret = 0; + if (p_public_only) { + ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w)); + } else { + 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. + mbedtls_platform_zeroize(w, 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. + mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer. + return OK; +} + +Error CryptoKeyMbedTLS::load_from_string(String p_string_key, bool p_public_only) { + int ret = 0; + if (p_public_only) { + ret = mbedtls_pk_parse_public_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size()); + } else { + ret = mbedtls_pk_parse_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size(), nullptr, 0); + } + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'."); + + public_only = p_public_only; return OK; } +String CryptoKeyMbedTLS::save_to_string(bool p_public_only) { + unsigned char w[16000]; + memset(w, 0, sizeof(w)); + + int ret = 0; + if (p_public_only) { + ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w)); + } else { + ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w)); + } + if (ret != 0) { + mbedtls_platform_zeroize(w, sizeof(w)); + ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'."); + } + String s = String::utf8((char *)w); + return s; +} + X509Certificate *X509CertificateMbedTLS::create() { return memnew(X509CertificateMbedTLS); } @@ -102,20 +141,17 @@ X509Certificate *X509CertificateMbedTLS::create() { Error X509CertificateMbedTLS::load(String p_path) { ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); - PoolByteArray out; + PackedByteArray out; FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'."); 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 - } + f->get_buffer(out.ptrw(), flen); + out.write[flen] = 0; // string terminator memdelete(f); - int ret = mbedtls_x509_crt_parse(&cert, out.read().ptr(), out.size()); + int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size()); ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret)); return OK; @@ -155,7 +191,6 @@ Crypto *CryptoMbedTLS::create() { } void CryptoMbedTLS::initialize_crypto() { - #ifdef DEBUG_ENABLED mbedtls_debug_set_threshold(1); #endif @@ -167,11 +202,11 @@ void CryptoMbedTLS::initialize_crypto() { } void CryptoMbedTLS::finalize_crypto() { - Crypto::_create = NULL; - Crypto::_load_default_certificates = NULL; + Crypto::_create = nullptr; + Crypto::_load_default_certificates = nullptr; if (default_certs) { memdelete(default_certs); - default_certs = NULL; + default_certs = nullptr; } X509CertificateMbedTLS::finalize(); CryptoKeyMbedTLS::finalize(); @@ -180,9 +215,9 @@ void CryptoMbedTLS::finalize_crypto() { 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); + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0); if (ret != 0) { - ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + ERR_PRINT(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); } } @@ -191,17 +226,17 @@ CryptoMbedTLS::~CryptoMbedTLS() { mbedtls_entropy_free(&entropy); } -X509CertificateMbedTLS *CryptoMbedTLS::default_certs = NULL; +X509CertificateMbedTLS *CryptoMbedTLS::default_certs = nullptr; X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() { return default_certs; } void CryptoMbedTLS::load_default_certificates(String p_path) { - ERR_FAIL_COND(default_certs != NULL); + ERR_FAIL_COND(default_certs != nullptr); default_certs = memnew(X509CertificateMbedTLS); - ERR_FAIL_COND(default_certs == NULL); + ERR_FAIL_COND(default_certs == nullptr); if (p_path != "") { // Use certs defined in project settings. @@ -210,15 +245,14 @@ void CryptoMbedTLS::load_default_certificates(String p_path) { #ifdef BUILTIN_CERTS_ENABLED else { // Use builtin certs only if user did not override it in project settings. - PoolByteArray out; + PackedByteArray 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 + Compression::decompress(out.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE); + out.write[_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()); + default_certs->load_from_memory(out.ptr(), out.size()); } #endif } @@ -227,15 +261,16 @@ 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); + ERR_FAIL_COND_V(ret != 0, nullptr); 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); + out->public_only = false; + ERR_FAIL_COND_V(ret != 0, nullptr); 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); - ERR_FAIL_COND_V_MSG(key.is_null(), NULL, "Invalid private key argument."); + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key); + ERR_FAIL_COND_V_MSG(key.is_null(), nullptr, "Invalid private key argument."); mbedtls_x509write_cert crt; mbedtls_x509write_crt_init(&crt); @@ -250,7 +285,7 @@ Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoK 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); + ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), nullptr); 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()); @@ -259,26 +294,93 @@ Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoK unsigned char buf[4096]; memset(buf, 0, 4096); + int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg); + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&crt); + ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret)); + buf[4095] = '\0'; // Make sure strlen can't fail. + 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; + out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size. + return out; +} + +PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) { + PackedByteArray out; + out.resize(p_bytes); + mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw(), p_bytes); + return out; +} + +mbedtls_md_type_t CryptoMbedTLS::_md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) { + switch (p_hash_type) { + case HashingContext::HASH_MD5: + r_size = 16; + return MBEDTLS_MD_MD5; + case HashingContext::HASH_SHA1: + r_size = 20; + return MBEDTLS_MD_SHA1; + case HashingContext::HASH_SHA256: + r_size = 32; + return MBEDTLS_MD_SHA256; + default: + r_size = 0; + ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type."); } +} - mbedtls_mpi_free(&serial); - mbedtls_x509write_crt_free(&crt); +Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key) { + int size; + mbedtls_md_type_t type = _md_type_from_hashtype(p_hash_type, size); + ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type."); + ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size)); + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key); + ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided."); + ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys."); + size_t sig_size = 0; + unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; + Vector<uint8_t> out; + int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf, &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg); + ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret)); + out.resize(sig_size); + copymem(out.ptrw(), buf, sig_size); 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); +bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key) { + int size; + mbedtls_md_type_t type = _md_type_from_hashtype(p_hash_type, size); + ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type."); + ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size)); + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key); + ERR_FAIL_COND_V_MSG(!key.is_valid(), false, "Invalid key provided."); + return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0; +} + +Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext) { + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key); + ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided."); + uint8_t buf[1024]; + size_t size; + Vector<uint8_t> out; + int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg); + ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret)); + out.resize(size); + copymem(out.ptrw(), buf, size); + return out; +} + +Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext) { + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key); + ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided."); + ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key."); + uint8_t buf[2048]; + size_t size; + Vector<uint8_t> out; + int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg); + ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret)); + out.resize(size); + copymem(out.ptrw(), buf, size); return out; } diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h index edb5841761..2a446f9d48 100644 --- a/modules/mbedtls/crypto_mbedtls.h +++ b/modules/mbedtls/crypto_mbedtls.h @@ -41,18 +41,21 @@ class CryptoMbedTLS; class SSLContextMbedTLS; class CryptoKeyMbedTLS : public CryptoKey { - private: mbedtls_pk_context pkey; - int locks; + int locks = 0; + bool public_only = true; public: static CryptoKey *create(); static void make_default() { CryptoKey::_create = create; } - static void finalize() { CryptoKey::_create = NULL; } + static void finalize() { CryptoKey::_create = nullptr; } - virtual Error load(String p_path); - virtual Error save(String p_path); + virtual Error load(String p_path, bool p_public_only); + virtual Error save(String p_path, bool p_public_only); + virtual String save_to_string(bool p_public_only); + virtual Error load_from_string(String p_string_key, bool p_public_only); + virtual bool is_public_only() const { return public_only; }; CryptoKeyMbedTLS() { mbedtls_pk_init(&pkey); @@ -70,7 +73,6 @@ public: }; class X509CertificateMbedTLS : public X509Certificate { - private: mbedtls_x509_crt cert; int locks; @@ -78,7 +80,7 @@ private: public: static X509Certificate *create(); static void make_default() { X509Certificate::_create = create; } - static void finalize() { X509Certificate::_create = NULL; } + static void finalize() { X509Certificate::_create = nullptr; } virtual Error load(String p_path); virtual Error load_from_memory(const uint8_t *p_buffer, int p_len); @@ -100,11 +102,11 @@ public: }; class CryptoMbedTLS : public Crypto { - private: mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; static X509CertificateMbedTLS *default_certs; + mbedtls_md_type_t _md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size); public: static Crypto *create(); @@ -113,9 +115,13 @@ public: static X509CertificateMbedTLS *get_default_certificates(); static void load_default_certificates(String p_path); - virtual PoolByteArray generate_random_bytes(int p_bytes); + virtual PackedByteArray 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); + virtual Vector<uint8_t> sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key); + virtual bool verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key); + virtual Vector<uint8_t> encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext); + virtual Vector<uint8_t> decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext); CryptoMbedTLS(); ~CryptoMbedTLS(); diff --git a/modules/mbedtls/dtls_server_mbedtls.cpp b/modules/mbedtls/dtls_server_mbedtls.cpp new file mode 100644 index 0000000000..d9961b026f --- /dev/null +++ b/modules/mbedtls/dtls_server_mbedtls.cpp @@ -0,0 +1,76 @@ +/*************************************************************************/ +/* dtls_server_mbedtls.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 "dtls_server_mbedtls.h" +#include "packet_peer_mbed_dtls.h" + +Error DTLSServerMbedTLS::setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) { + ERR_FAIL_COND_V(_cookies->setup() != OK, ERR_ALREADY_IN_USE); + _key = p_key; + _cert = p_cert; + _ca_chain = p_ca_chain; + return OK; +} + +void DTLSServerMbedTLS::stop() { + _cookies->clear(); +} + +Ref<PacketPeerDTLS> DTLSServerMbedTLS::take_connection(Ref<PacketPeerUDP> p_udp_peer) { + Ref<PacketPeerMbedDTLS> out; + out.instance(); + + ERR_FAIL_COND_V(!out.is_valid(), out); + ERR_FAIL_COND_V(!p_udp_peer.is_valid(), out); + out->accept_peer(p_udp_peer, _key, _cert, _ca_chain, _cookies); + return out; +} + +DTLSServer *DTLSServerMbedTLS::_create_func() { + return memnew(DTLSServerMbedTLS); +} + +void DTLSServerMbedTLS::initialize() { + _create = _create_func; + available = true; +} + +void DTLSServerMbedTLS::finalize() { + _create = nullptr; + available = false; +} + +DTLSServerMbedTLS::DTLSServerMbedTLS() { + _cookies.instance(); +} + +DTLSServerMbedTLS::~DTLSServerMbedTLS() { + stop(); +} diff --git a/modules/mbedtls/dtls_server_mbedtls.h b/modules/mbedtls/dtls_server_mbedtls.h new file mode 100644 index 0000000000..d93553bf7f --- /dev/null +++ b/modules/mbedtls/dtls_server_mbedtls.h @@ -0,0 +1,57 @@ +/*************************************************************************/ +/* dtls_server_mbedtls.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 MBED_DTLS_SERVER_H +#define MBED_DTLS_SERVER_H + +#include "core/io/dtls_server.h" +#include "ssl_context_mbedtls.h" + +class DTLSServerMbedTLS : public DTLSServer { +private: + static DTLSServer *_create_func(); + Ref<CryptoKey> _key; + Ref<X509Certificate> _cert; + Ref<X509Certificate> _ca_chain; + Ref<CookieContextMbedTLS> _cookies; + +public: + static void initialize(); + static void finalize(); + + virtual Error setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>()); + virtual void stop(); + virtual Ref<PacketPeerDTLS> take_connection(Ref<PacketPeerUDP> p_peer); + + DTLSServerMbedTLS(); + ~DTLSServerMbedTLS(); +}; + +#endif // MBED_DTLS_SERVER_H diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp new file mode 100644 index 0000000000..8206d739ae --- /dev/null +++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp @@ -0,0 +1,288 @@ +/*************************************************************************/ +/* packet_peer_mbed_dtls.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 "packet_peer_mbed_dtls.h" +#include "mbedtls/platform_util.h" + +#include "core/io/stream_peer_ssl.h" +#include "core/os/file_access.h" + +int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { + if (buf == nullptr || len <= 0) { + return 0; + } + + PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx; + + ERR_FAIL_COND_V(sp == nullptr, 0); + + Error err = sp->base->put_packet((const uint8_t *)buf, len); + if (err == ERR_BUSY) { + return MBEDTLS_ERR_SSL_WANT_WRITE; + } else if (err != OK) { + ERR_FAIL_V(MBEDTLS_ERR_SSL_INTERNAL_ERROR); + } + return len; +} + +int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { + if (buf == nullptr || len <= 0) { + return 0; + } + + PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx; + + ERR_FAIL_COND_V(sp == nullptr, 0); + + int pc = sp->base->get_available_packet_count(); + if (pc == 0) { + return MBEDTLS_ERR_SSL_WANT_READ; + } else if (pc < 0) { + ERR_FAIL_V(MBEDTLS_ERR_SSL_INTERNAL_ERROR); + } + + const uint8_t *buffer; + int buffer_size = 0; + Error err = sp->base->get_packet(&buffer, buffer_size); + if (err != OK) { + return MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } + copymem(buf, buffer, buffer_size); + return buffer_size; +} + +void PacketPeerMbedDTLS::_cleanup() { + ssl_ctx->clear(); + base = Ref<PacketPeer>(); + status = STATUS_DISCONNECTED; +} + +int PacketPeerMbedDTLS::_set_cookie() { + // Setup DTLS session cookie for this client + uint8_t client_id[18]; + IP_Address addr = base->get_packet_address(); + uint16_t port = base->get_packet_port(); + copymem(client_id, addr.get_ipv6(), 16); + copymem(&client_id[16], (uint8_t *)&port, 2); + return mbedtls_ssl_set_client_transport_id(ssl_ctx->get_context(), client_id, 18); +} + +Error PacketPeerMbedDTLS::_do_handshake() { + int ret = 0; + while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + if (ret != MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) { + ERR_PRINT("TLS handshake error: " + itos(ret)); + SSLContextMbedTLS::print_mbedtls_error(ret); + } + _cleanup(); + status = STATUS_ERROR; + return FAILED; + } + // Will retry via poll later + return OK; + } + + status = STATUS_CONNECTED; + return OK; +} + +Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) { + ERR_FAIL_COND_V(!p_base.is_valid() || !p_base->is_connected_to_host(), ERR_INVALID_PARAMETER); + + base = p_base; + int ret = 0; + int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE; + + Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_DATAGRAM, authmode, p_ca_certs); + ERR_FAIL_COND_V(err != OK, err); + + 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, nullptr); + mbedtls_ssl_set_timer_cb(ssl_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); + + status = STATUS_HANDSHAKING; + + if ((ret = _do_handshake()) != OK) { + status = STATUS_ERROR_HOSTNAME_MISMATCH; + return FAILED; + } + + return OK; +} + +Error PacketPeerMbedDTLS::accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain, Ref<CookieContextMbedTLS> p_cookies) { + Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert, p_cookies); + ERR_FAIL_COND_V(err != OK, err); + + base = p_base; + base->set_blocking_mode(false); + + mbedtls_ssl_session_reset(ssl_ctx->get_context()); + + int ret = _set_cookie(); + if (ret != 0) { + _cleanup(); + ERR_FAIL_V_MSG(FAILED, "Error setting DTLS client cookie"); + } + + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); + mbedtls_ssl_set_timer_cb(ssl_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); + + status = STATUS_HANDSHAKING; + + if ((ret = _do_handshake()) != OK) { + status = STATUS_ERROR; + return FAILED; + } + + return OK; +} + +Error PacketPeerMbedDTLS::put_packet(const uint8_t *p_buffer, int p_bytes) { + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); + + if (p_bytes == 0) { + return OK; + } + + int ret = mbedtls_ssl_write(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 <= 0) { + SSLContextMbedTLS::print_mbedtls_error(ret); + _cleanup(); + return ERR_CONNECTION_ERROR; + } + + return OK; +} + +Error PacketPeerMbedDTLS::get_packet(const uint8_t **r_buffer, int &r_bytes) { + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); + + r_bytes = 0; + + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), packet_buffer, PACKET_BUFFER_SIZE); + if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + ret = 0; // non blocking io + } else if (ret <= 0) { + if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // Also send close notify back + disconnect_from_peer(); + } else { + _cleanup(); + status = STATUS_ERROR; + SSLContextMbedTLS::print_mbedtls_error(ret); + } + return ERR_CONNECTION_ERROR; + } + *r_buffer = packet_buffer; + r_bytes = ret; + + return OK; +} + +void PacketPeerMbedDTLS::poll() { + if (status == STATUS_HANDSHAKING) { + _do_handshake(); + return; + } else if (status != STATUS_CONNECTED) { + return; + } + + ERR_FAIL_COND(!base.is_valid()); + + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), nullptr, 0); + + if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // Also send close notify back + disconnect_from_peer(); + } else { + _cleanup(); + status = STATUS_ERROR; + SSLContextMbedTLS::print_mbedtls_error(ret); + } + } +} + +int PacketPeerMbedDTLS::get_available_packet_count() const { + ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); + + return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)) > 0 ? 1 : 0; +} + +int PacketPeerMbedDTLS::get_max_packet_size() const { + return 488; // 512 (UDP in Godot) - 24 (DTLS header) +} + +PacketPeerMbedDTLS::PacketPeerMbedDTLS() { + ssl_ctx.instance(); + status = STATUS_DISCONNECTED; +} + +PacketPeerMbedDTLS::~PacketPeerMbedDTLS() { + disconnect_from_peer(); +} + +void PacketPeerMbedDTLS::disconnect_from_peer() { + if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) { + return; + } + + if (status == STATUS_CONNECTED) { + int ret = 0; + // Send SSL close notification, blocking, but ignore other errors. + do { + ret = mbedtls_ssl_close_notify(ssl_ctx->get_context()); + } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE); + } + + _cleanup(); +} + +PacketPeerMbedDTLS::Status PacketPeerMbedDTLS::get_status() const { + return status; +} + +PacketPeerDTLS *PacketPeerMbedDTLS::_create_func() { + return memnew(PacketPeerMbedDTLS); +} + +void PacketPeerMbedDTLS::initialize_dtls() { + _create = _create_func; + available = true; +} + +void PacketPeerMbedDTLS::finalize_dtls() { + _create = nullptr; + available = false; +} diff --git a/modules/mbedtls/packet_peer_mbed_dtls.h b/modules/mbedtls/packet_peer_mbed_dtls.h new file mode 100755 index 0000000000..b958fa3b95 --- /dev/null +++ b/modules/mbedtls/packet_peer_mbed_dtls.h @@ -0,0 +1,88 @@ +/*************************************************************************/ +/* packet_peer_mbed_dtls.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 PACKET_PEER_MBED_DTLS_H +#define PACKET_PEER_MBED_DTLS_H + +#include "core/io/packet_peer_dtls.h" +#include "ssl_context_mbedtls.h" + +#include <mbedtls/timing.h> + +class PacketPeerMbedDTLS : public PacketPeerDTLS { +private: + enum { + PACKET_BUFFER_SIZE = 65536 + }; + + uint8_t packet_buffer[PACKET_BUFFER_SIZE]; + + Status status; + String hostname; + + Ref<PacketPeerUDP> base; + + static PacketPeerDTLS *_create_func(); + + 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: + Ref<SSLContextMbedTLS> ssl_ctx; + mbedtls_timing_delay_context timer; + + static void _bind_methods(); + + Error _do_handshake(); + int _set_cookie(); + +public: + virtual void poll(); + virtual Error accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert = Ref<X509Certificate>(), Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>(), Ref<CookieContextMbedTLS> p_cookies = Ref<CookieContextMbedTLS>()); + virtual Error connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_validate_certs = true, const String &p_for_hostname = String(), Ref<X509Certificate> p_ca_certs = Ref<X509Certificate>()); + virtual Status get_status() const; + + virtual void disconnect_from_peer(); + + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); + + virtual int get_available_packet_count() const; + virtual int get_max_packet_size() const; + + static void initialize_dtls(); + static void finalize_dtls(); + + PacketPeerMbedDTLS(); + ~PacketPeerMbedDTLS(); +}; + +#endif // PACKET_PEER_MBED_DTLS_H diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp index 8f9e2c370b..84a27c29bd 100755..100644 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -31,16 +31,20 @@ #include "register_types.h" #include "crypto_mbedtls.h" +#include "dtls_server_mbedtls.h" +#include "packet_peer_mbed_dtls.h" #include "stream_peer_mbedtls.h" void register_mbedtls_types() { - CryptoMbedTLS::initialize_crypto(); StreamPeerMbedTLS::initialize_ssl(); + PacketPeerMbedDTLS::initialize_dtls(); + DTLSServerMbedTLS::initialize(); } void unregister_mbedtls_types() { - + DTLSServerMbedTLS::finalize(); + PacketPeerMbedDTLS::finalize_dtls(); StreamPeerMbedTLS::finalize_ssl(); CryptoMbedTLS::finalize_crypto(); } diff --git a/modules/mbedtls/register_types.h b/modules/mbedtls/register_types.h index f179d39438..90c81b1682 100755 --- a/modules/mbedtls/register_types.h +++ b/modules/mbedtls/register_types.h @@ -28,5 +28,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef MBEDTLS_REGISTER_TYPES_H +#define MBEDTLS_REGISTER_TYPES_H + void register_mbedtls_types(); void unregister_mbedtls_types(); + +#endif // MBEDTLS_REGISTER_TYPES_H diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp index 82584e3494..a2200e0644 100644 --- a/modules/mbedtls/ssl_context_mbedtls.cpp +++ b/modules/mbedtls/ssl_context_mbedtls.cpp @@ -33,11 +33,58 @@ 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 SSLContextMbedTLS::print_mbedtls_error(int p_ret) { + printf("mbedtls error: returned -0x%x\n\n", -p_ret); + fflush(stdout); +} + +/// CookieContextMbedTLS + +Error CookieContextMbedTLS::setup() { + ERR_FAIL_COND_V_MSG(inited, ERR_ALREADY_IN_USE, "This cookie context is already in use"); + + mbedtls_ctr_drbg_init(&ctr_drbg); + mbedtls_entropy_init(&entropy); + mbedtls_ssl_cookie_init(&cookie_ctx); + inited = true; + + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 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_cookie_setup(&cookie_ctx, mbedtls_ctr_drbg_random, &ctr_drbg); + if (ret != 0) { + clear(); + ERR_FAIL_V_MSG(FAILED, "mbedtls_ssl_cookie_setup returned an error " + itos(ret)); + } + return OK; +} + +void CookieContextMbedTLS::clear() { + if (!inited) { + return; + } + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&entropy); + mbedtls_ssl_cookie_free(&cookie_ctx); +} + +CookieContextMbedTLS::CookieContextMbedTLS() { + inited = false; +} + +CookieContextMbedTLS::~CookieContextMbedTLS() { + clear(); +} + +/// SSLContextMbedTLS + 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"); @@ -47,10 +94,10 @@ Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) mbedtls_entropy_init(&entropy); inited = true; - int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0); if (ret != 0) { clear(); // Never leave unusable resources around. - ERR_FAIL_V_MSG(FAILED, "mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + 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); @@ -64,7 +111,7 @@ Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) return OK; } -Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert) { +Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert, Ref<CookieContextMbedTLS> p_cookies) { ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER); @@ -74,10 +121,12 @@ Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<Crypto // Locking key and certificate(s) pkey = p_pkey; certs = p_cert; - if (pkey.is_valid()) + if (pkey.is_valid()) { pkey->lock(); - if (certs.is_valid()) + } + if (certs.is_valid()) { certs->lock(); + } // Adding key and certificate int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey)); @@ -87,7 +136,16 @@ Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<Crypto } // Adding CA chain if available. if (certs->cert.next) { - mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, NULL); + mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, nullptr); + } + // DTLS Cookies + if (p_transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) { + if (p_cookies.is_null() || !p_cookies->inited) { + clear(); + ERR_FAIL_V(ERR_BUG); + } + cookies = p_cookies; + mbedtls_ssl_conf_dtls_cookies(&conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &(cookies->cookie_ctx)); } mbedtls_ssl_setup(&ssl, &conf); return OK; @@ -97,7 +155,7 @@ Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509Ce Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode); ERR_FAIL_COND_V(err != OK, err); - X509CertificateMbedTLS *cas = NULL; + X509CertificateMbedTLS *cas = nullptr; if (p_valid_cas.is_valid()) { // Locking CA certificates @@ -107,38 +165,42 @@ Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509Ce } else { // Fall back to default certificates (no need to lock those). cas = CryptoMbedTLS::get_default_certificates(); - if (cas == NULL) { + if (cas == nullptr) { 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_conf_ca_chain(&conf, &(cas->cert), nullptr); mbedtls_ssl_setup(&ssl, &conf); return OK; } void SSLContextMbedTLS::clear() { - if (!inited) + 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()) + if (certs.is_valid()) { certs->unlock(); + } certs = Ref<X509Certificate>(); - if (pkey.is_valid()) + if (pkey.is_valid()) { pkey->unlock(); + } pkey = Ref<CryptoKeyMbedTLS>(); + cookies = Ref<CookieContextMbedTLS>(); inited = false; } mbedtls_ssl_context *SSLContextMbedTLS::get_context() { - ERR_FAIL_COND_V(!inited, NULL); + ERR_FAIL_COND_V(!inited, nullptr); return &ssl; } diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h index 9145e0fd72..baaeb6eb85 100644 --- a/modules/mbedtls/ssl_context_mbedtls.h +++ b/modules/mbedtls/ssl_context_mbedtls.h @@ -34,7 +34,7 @@ #include "crypto_mbedtls.h" #include "core/os/file_access.h" -#include "core/pool_vector.h" + #include "core/reference.h" #include <mbedtls/config.h> @@ -42,25 +42,47 @@ #include <mbedtls/debug.h> #include <mbedtls/entropy.h> #include <mbedtls/ssl.h> +#include <mbedtls/ssl_cookie.h> -class SSLContextMbedTLS : public Reference { +class SSLContextMbedTLS; + +class CookieContextMbedTLS : public Reference { + friend class SSLContextMbedTLS; protected: bool inited; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_cookie_ctx cookie_ctx; - static PoolByteArray _read_file(String p_path); +public: + Error setup(); + void clear(); + + CookieContextMbedTLS(); + ~CookieContextMbedTLS(); +}; + +class SSLContextMbedTLS : public Reference { +protected: + bool inited; + + static PackedByteArray _read_file(String p_path); public: + static void print_mbedtls_error(int p_ret); + Ref<X509CertificateMbedTLS> certs; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ssl_context ssl; mbedtls_ssl_config conf; + Ref<CookieContextMbedTLS> cookies; 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_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert, Ref<CookieContextMbedTLS> p_cookies = Ref<CookieContextMbedTLS>()); Error init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas); void clear(); diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index b88d9e48a4..e9a610b7ee 100755..100644 --- a/modules/mbedtls/stream_peer_mbedtls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -33,18 +33,14 @@ #include "core/io/stream_peer_tcp.h" #include "core/os/file_access.h" -void _print_error(int ret) { - printf("mbedtls error: returned -0x%x\n\n", -ret); - fflush(stdout); -} - int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { - - if (buf == NULL || len <= 0) return 0; + if (buf == nullptr || len <= 0) { + return 0; + } StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; - ERR_FAIL_COND_V(sp == NULL, 0); + ERR_FAIL_COND_V(sp == nullptr, 0); int sent; Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent); @@ -58,12 +54,13 @@ int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) } int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { - - if (buf == NULL || len <= 0) return 0; + if (buf == nullptr || len <= 0) { + return 0; + } StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; - ERR_FAIL_COND_V(sp == NULL, 0); + ERR_FAIL_COND_V(sp == nullptr, 0); int got; Error err = sp->base->get_partial_data((uint8_t *)buf, len, got); @@ -77,7 +74,6 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { } void StreamPeerMbedTLS::_cleanup() { - ssl_ctx->clear(); base = Ref<StreamPeer>(); status = STATUS_DISCONNECTED; @@ -88,8 +84,8 @@ Error StreamPeerMbedTLS::_do_handshake() { 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)); - _print_error(ret); + ERR_PRINT("TLS handshake error: " + itos(ret)); + SSLContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); status = STATUS_ERROR; return FAILED; @@ -107,7 +103,6 @@ Error StreamPeerMbedTLS::_do_handshake() { } 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); base = p_base; @@ -117,7 +112,7 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida ERR_FAIL_COND_V(err != OK, err); 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); + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); status = STATUS_HANDSHAKING; @@ -130,7 +125,6 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida } 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); @@ -138,7 +132,7 @@ Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_ base = p_base; - mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL); + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); status = STATUS_HANDSHAKING; @@ -149,8 +143,8 @@ Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_ status = STATUS_CONNECTED; return OK; } -Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { +Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); Error err; @@ -171,13 +165,13 @@ Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { } Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) { - ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); r_sent = 0; - if (p_bytes == 0) + if (p_bytes == 0) { return OK; + } 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) { @@ -188,7 +182,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in disconnect_from_stream(); return ERR_FILE_EOF; } else if (ret <= 0) { - _print_error(ret); + SSLContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return ERR_CONNECTION_ERROR; } @@ -198,14 +192,12 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in } Error StreamPeerMbedTLS::get_data(uint8_t *p_buffer, int p_bytes) { - ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); Error err; int got = 0; while (p_bytes > 0) { - err = get_partial_data(p_buffer, p_bytes, got); if (err != OK) { @@ -220,7 +212,6 @@ Error StreamPeerMbedTLS::get_data(uint8_t *p_buffer, int p_bytes) { } Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) { - ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); r_received = 0; @@ -233,7 +224,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r disconnect_from_stream(); return ERR_FILE_EOF; } else if (ret <= 0) { - _print_error(ret); + SSLContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return ERR_CONNECTION_ERROR; } @@ -243,7 +234,6 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r } void StreamPeerMbedTLS::poll() { - ERR_FAIL_COND(status != STATUS_CONNECTED && status != STATUS_HANDSHAKING); ERR_FAIL_COND(!base.is_valid()); @@ -264,7 +254,7 @@ void StreamPeerMbedTLS::poll() { disconnect_from_stream(); return; } else if (ret < 0) { - _print_error(ret); + SSLContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return; } @@ -277,13 +267,12 @@ void StreamPeerMbedTLS::poll() { } int StreamPeerMbedTLS::get_available_bytes() const { - ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)); } -StreamPeerMbedTLS::StreamPeerMbedTLS() { +StreamPeerMbedTLS::StreamPeerMbedTLS() { ssl_ctx.instance(); status = STATUS_DISCONNECTED; } @@ -293,9 +282,9 @@ StreamPeerMbedTLS::~StreamPeerMbedTLS() { } void StreamPeerMbedTLS::disconnect_from_stream() { - - if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) + if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) { return; + } Ref<StreamPeerTCP> tcp = base; if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) { @@ -307,23 +296,19 @@ void StreamPeerMbedTLS::disconnect_from_stream() { } StreamPeerMbedTLS::Status StreamPeerMbedTLS::get_status() const { - return status; } StreamPeerSSL *StreamPeerMbedTLS::_create_func() { - return memnew(StreamPeerMbedTLS); } void StreamPeerMbedTLS::initialize_ssl() { - _create = _create_func; available = true; } void StreamPeerMbedTLS::finalize_ssl() { - available = false; - _create = NULL; + _create = nullptr; } |