From 5cb41faece5969314ed69e0292d0a51f0425c53a Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Thu, 11 Jul 2019 13:20:27 +0200 Subject: Fix CryptoCore signatures, add SHA1 context. Fix hash size in SHA256 signature Fix source parameter in hash context update function to be const. Add SHA1 hash context. --- core/math/crypto_core.cpp | 32 +++++++++++++++++++++++++++++--- core/math/crypto_core.h | 20 +++++++++++++++++--- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/core/math/crypto_core.cpp b/core/math/crypto_core.cpp index d7ba54e469..51c2e3c9e5 100644 --- a/core/math/crypto_core.cpp +++ b/core/math/crypto_core.cpp @@ -52,7 +52,7 @@ Error CryptoCore::MD5Context::start() { return ret ? FAILED : OK; } -Error CryptoCore::MD5Context::update(uint8_t *p_src, size_t p_len) { +Error CryptoCore::MD5Context::update(const uint8_t *p_src, size_t p_len) { int ret = mbedtls_md5_update_ret((mbedtls_md5_context *)ctx, p_src, p_len); return ret ? FAILED : OK; } @@ -62,6 +62,32 @@ Error CryptoCore::MD5Context::finish(unsigned char r_hash[16]) { return ret ? FAILED : OK; } +// SHA1 +CryptoCore::SHA1Context::SHA1Context() { + ctx = memalloc(sizeof(mbedtls_sha1_context)); + mbedtls_sha1_init((mbedtls_sha1_context *)ctx); +} + +CryptoCore::SHA1Context::~SHA1Context() { + mbedtls_sha1_free((mbedtls_sha1_context *)ctx); + memfree((mbedtls_sha1_context *)ctx); +} + +Error CryptoCore::SHA1Context::start() { + int ret = mbedtls_sha1_starts_ret((mbedtls_sha1_context *)ctx); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA1Context::update(const uint8_t *p_src, size_t p_len) { + int ret = mbedtls_sha1_update_ret((mbedtls_sha1_context *)ctx, p_src, p_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA1Context::finish(unsigned char r_hash[20]) { + int ret = mbedtls_sha1_finish_ret((mbedtls_sha1_context *)ctx, r_hash); + return ret ? FAILED : OK; +} + // SHA256 CryptoCore::SHA256Context::SHA256Context() { ctx = memalloc(sizeof(mbedtls_sha256_context)); @@ -78,12 +104,12 @@ Error CryptoCore::SHA256Context::start() { return ret ? FAILED : OK; } -Error CryptoCore::SHA256Context::update(uint8_t *p_src, size_t p_len) { +Error CryptoCore::SHA256Context::update(const uint8_t *p_src, size_t p_len) { int ret = mbedtls_sha256_update_ret((mbedtls_sha256_context *)ctx, p_src, p_len); return ret ? FAILED : OK; } -Error CryptoCore::SHA256Context::finish(unsigned char r_hash[16]) { +Error CryptoCore::SHA256Context::finish(unsigned char r_hash[32]) { int ret = mbedtls_sha256_finish_ret((mbedtls_sha256_context *)ctx, r_hash); return ret ? FAILED : OK; } diff --git a/core/math/crypto_core.h b/core/math/crypto_core.h index e28cb5a792..c859d612d4 100644 --- a/core/math/crypto_core.h +++ b/core/math/crypto_core.h @@ -46,10 +46,24 @@ public: ~MD5Context(); Error start(); - Error update(uint8_t *p_src, size_t p_len); + Error update(const uint8_t *p_src, size_t p_len); Error finish(unsigned char r_hash[16]); }; + class SHA1Context { + + private: + void *ctx; // To include, or not to include... + + public: + SHA1Context(); + ~SHA1Context(); + + Error start(); + Error update(const uint8_t *p_src, size_t p_len); + Error finish(unsigned char r_hash[20]); + }; + class SHA256Context { private: @@ -60,8 +74,8 @@ public: ~SHA256Context(); Error start(); - Error update(uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[16]); + Error update(const uint8_t *p_src, size_t p_len); + Error finish(unsigned char r_hash[32]); }; class AESContext { -- cgit v1.2.3 From c19871af6d6ae7faef0d4052b3a27e59814abcf1 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Thu, 11 Jul 2019 15:21:47 +0200 Subject: Move CryptoCore to it's own folder. Crypto classes will be placed in core/crypto. --- core/SCsub | 1 + core/bind/core_bind.cpp | 2 +- core/crypto/crypto_core.cpp | 183 +++++++++++++++++++++++++++ core/crypto/crypto_core.h | 104 +++++++++++++++ core/io/file_access_encrypted.cpp | 2 +- core/math/SCsub | 33 +---- core/math/crypto_core.cpp | 183 --------------------------- core/math/crypto_core.h | 104 --------------- core/os/file_access.cpp | 2 +- core/ustring.cpp | 2 +- core/variant_call.cpp | 2 +- editor/editor_export.cpp | 2 +- editor/import/editor_scene_importer_gltf.cpp | 2 +- modules/websocket/wsl_peer.cpp | 2 +- platform/uwp/export/export.cpp | 2 +- 15 files changed, 298 insertions(+), 328 deletions(-) create mode 100644 core/crypto/crypto_core.cpp create mode 100644 core/crypto/crypto_core.h delete mode 100644 core/math/crypto_core.cpp delete mode 100644 core/math/crypto_core.h diff --git a/core/SCsub b/core/SCsub index 85e5f1b089..ed9a0a231d 100644 --- a/core/SCsub +++ b/core/SCsub @@ -159,6 +159,7 @@ env.CommandNoCache('#core/license.gen.h', ["../COPYRIGHT.txt", "../LICENSE.txt"] # Chain load SCsubs SConscript('os/SCsub') SConscript('math/SCsub') +SConscript('crypto/SCsub') SConscript('io/SCsub') SConscript('bind/SCsub') diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp index 56369a3cc6..8e0d156438 100644 --- a/core/bind/core_bind.cpp +++ b/core/bind/core_bind.cpp @@ -30,11 +30,11 @@ #include "core_bind.h" +#include "core/crypto/crypto_core.h" #include "core/io/file_access_compressed.h" #include "core/io/file_access_encrypted.h" #include "core/io/json.h" #include "core/io/marshalls.h" -#include "core/math/crypto_core.h" #include "core/math/geometry.h" #include "core/os/keyboard.h" #include "core/os/os.h" diff --git a/core/crypto/crypto_core.cpp b/core/crypto/crypto_core.cpp new file mode 100644 index 0000000000..51c2e3c9e5 --- /dev/null +++ b/core/crypto/crypto_core.cpp @@ -0,0 +1,183 @@ +/*************************************************************************/ +/* crypto_core.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_core.h" + +#include +#include +#include +#include +#include + +// MD5 +CryptoCore::MD5Context::MD5Context() { + ctx = memalloc(sizeof(mbedtls_md5_context)); + mbedtls_md5_init((mbedtls_md5_context *)ctx); +} + +CryptoCore::MD5Context::~MD5Context() { + mbedtls_md5_free((mbedtls_md5_context *)ctx); + memfree((mbedtls_md5_context *)ctx); +} + +Error CryptoCore::MD5Context::start() { + int ret = mbedtls_md5_starts_ret((mbedtls_md5_context *)ctx); + return ret ? FAILED : OK; +} + +Error CryptoCore::MD5Context::update(const uint8_t *p_src, size_t p_len) { + int ret = mbedtls_md5_update_ret((mbedtls_md5_context *)ctx, p_src, p_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::MD5Context::finish(unsigned char r_hash[16]) { + int ret = mbedtls_md5_finish_ret((mbedtls_md5_context *)ctx, r_hash); + return ret ? FAILED : OK; +} + +// SHA1 +CryptoCore::SHA1Context::SHA1Context() { + ctx = memalloc(sizeof(mbedtls_sha1_context)); + mbedtls_sha1_init((mbedtls_sha1_context *)ctx); +} + +CryptoCore::SHA1Context::~SHA1Context() { + mbedtls_sha1_free((mbedtls_sha1_context *)ctx); + memfree((mbedtls_sha1_context *)ctx); +} + +Error CryptoCore::SHA1Context::start() { + int ret = mbedtls_sha1_starts_ret((mbedtls_sha1_context *)ctx); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA1Context::update(const uint8_t *p_src, size_t p_len) { + int ret = mbedtls_sha1_update_ret((mbedtls_sha1_context *)ctx, p_src, p_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA1Context::finish(unsigned char r_hash[20]) { + int ret = mbedtls_sha1_finish_ret((mbedtls_sha1_context *)ctx, r_hash); + return ret ? FAILED : OK; +} + +// SHA256 +CryptoCore::SHA256Context::SHA256Context() { + ctx = memalloc(sizeof(mbedtls_sha256_context)); + mbedtls_sha256_init((mbedtls_sha256_context *)ctx); +} + +CryptoCore::SHA256Context::~SHA256Context() { + mbedtls_sha256_free((mbedtls_sha256_context *)ctx); + memfree((mbedtls_sha256_context *)ctx); +} + +Error CryptoCore::SHA256Context::start() { + int ret = mbedtls_sha256_starts_ret((mbedtls_sha256_context *)ctx, 0); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA256Context::update(const uint8_t *p_src, size_t p_len) { + int ret = mbedtls_sha256_update_ret((mbedtls_sha256_context *)ctx, p_src, p_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::SHA256Context::finish(unsigned char r_hash[32]) { + int ret = mbedtls_sha256_finish_ret((mbedtls_sha256_context *)ctx, r_hash); + return ret ? FAILED : OK; +} + +// AES256 +CryptoCore::AESContext::AESContext() { + ctx = memalloc(sizeof(mbedtls_aes_context)); + mbedtls_aes_init((mbedtls_aes_context *)ctx); +} + +CryptoCore::AESContext::~AESContext() { + mbedtls_aes_free((mbedtls_aes_context *)ctx); + memfree((mbedtls_aes_context *)ctx); +} + +Error CryptoCore::AESContext::set_encode_key(const uint8_t *p_key, size_t p_bits) { + int ret = mbedtls_aes_setkey_enc((mbedtls_aes_context *)ctx, p_key, p_bits); + return ret ? FAILED : OK; +} + +Error CryptoCore::AESContext::set_decode_key(const uint8_t *p_key, size_t p_bits) { + int ret = mbedtls_aes_setkey_dec((mbedtls_aes_context *)ctx, p_key, p_bits); + return ret ? FAILED : OK; +} + +Error CryptoCore::AESContext::encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { + int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_ENCRYPT, p_src, r_dst); + return ret ? FAILED : OK; +} + +Error CryptoCore::AESContext::decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { + int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_DECRYPT, p_src, r_dst); + return ret ? FAILED : OK; +} + +// CryptoCore +String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) { + int b64len = p_src_len / 3 * 4 + 4 + 1; + PoolVector b64buff; + b64buff.resize(b64len); + PoolVector::Write w64 = b64buff.write(); + size_t strlen = 0; + int ret = b64_encode(&w64[0], b64len, &strlen, p_src, p_src_len); + w64[strlen] = 0; + return ret ? String() : (const char *)&w64[0]; +} + +Error CryptoCore::b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { + int ret = mbedtls_base64_encode(r_dst, p_dst_len, r_len, p_src, p_src_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { + int ret = mbedtls_base64_decode(r_dst, p_dst_len, r_len, p_src, p_src_len); + return ret ? FAILED : OK; +} + +Error CryptoCore::md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]) { + int ret = mbedtls_md5_ret(p_src, p_src_len, r_hash); + return ret ? FAILED : OK; +} + +Error CryptoCore::sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]) { + int ret = mbedtls_sha1_ret(p_src, p_src_len, r_hash); + return ret ? FAILED : OK; +} + +Error CryptoCore::sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]) { + int ret = mbedtls_sha256_ret(p_src, p_src_len, r_hash, 0); + return ret ? FAILED : OK; +} diff --git a/core/crypto/crypto_core.h b/core/crypto/crypto_core.h new file mode 100644 index 0000000000..c859d612d4 --- /dev/null +++ b/core/crypto/crypto_core.h @@ -0,0 +1,104 @@ +/*************************************************************************/ +/* crypto_core.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_CORE_H +#define CRYPTO_CORE_H + +#include "core/reference.h" + +class CryptoCore { + +public: + class MD5Context { + + private: + void *ctx; // To include, or not to include... + + public: + MD5Context(); + ~MD5Context(); + + Error start(); + Error update(const uint8_t *p_src, size_t p_len); + Error finish(unsigned char r_hash[16]); + }; + + class SHA1Context { + + private: + void *ctx; // To include, or not to include... + + public: + SHA1Context(); + ~SHA1Context(); + + Error start(); + Error update(const uint8_t *p_src, size_t p_len); + Error finish(unsigned char r_hash[20]); + }; + + class SHA256Context { + + private: + void *ctx; // To include, or not to include... + + public: + SHA256Context(); + ~SHA256Context(); + + Error start(); + Error update(const uint8_t *p_src, size_t p_len); + Error finish(unsigned char r_hash[32]); + }; + + class AESContext { + + private: + void *ctx; // To include, or not to include... + + public: + AESContext(); + ~AESContext(); + + Error set_encode_key(const uint8_t *p_key, size_t p_bits); + Error set_decode_key(const uint8_t *p_key, size_t p_bits); + Error encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); + Error decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); + }; + + static String b64_encode_str(const uint8_t *p_src, int p_src_len); + static Error b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); + static Error b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); + + static Error md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]); + static Error sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]); + static Error sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]); +}; +#endif // CRYPTO_CORE_H diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp index 1452c61d1a..77decc107d 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -30,7 +30,7 @@ #include "file_access_encrypted.h" -#include "core/math/crypto_core.h" +#include "core/crypto/crypto_core.h" #include "core/os/copymem.h" #include "core/print_string.h" #include "core/variant.h" diff --git a/core/math/SCsub b/core/math/SCsub index 0995298a4b..be438fcfbe 100644 --- a/core/math/SCsub +++ b/core/math/SCsub @@ -2,37 +2,6 @@ Import('env') -env_math = env.Clone() # Maybe make one specific for crypto? - -is_builtin = env["builtin_mbedtls"] -has_module = env["module_mbedtls_enabled"] - -if is_builtin or not has_module: - # Use our headers for builtin or if the module is not going to be compiled. - # We decided not to depend on system mbedtls just for these few files that can - # be easily extracted. - env_math.Prepend(CPPPATH=["#thirdparty/mbedtls/include"]) - -# MbedTLS core functions (for CryptoCore). -# If the mbedtls module is compiled we don't need to add the .c files with our -# custom config since they will be built by the module itself. -# Only if the module is not enabled, we must compile here the required sources -# to make a "light" build with only the necessary mbedtls files. -if not has_module: - env_thirdparty = env_math.Clone() - env_thirdparty.disable_warnings() - # Custom config file - env_thirdparty.Append(CPPDEFINES=[('MBEDTLS_CONFIG_FILE', '\\"thirdparty/mbedtls/include/godot_core_mbedtls_config.h\\"')]) - thirdparty_mbedtls_dir = "#thirdparty/mbedtls/library/" - thirdparty_mbedtls_sources = [ - "aes.c", - "base64.c", - "md5.c", - "sha1.c", - "sha256.c", - "godot_core_mbedtls_platform.c" - ] - thirdparty_mbedtls_sources = [thirdparty_mbedtls_dir + file for file in thirdparty_mbedtls_sources] - env_thirdparty.add_source_files(env.core_sources, thirdparty_mbedtls_sources) +env_math = env.Clone() env_math.add_source_files(env.core_sources, "*.cpp") diff --git a/core/math/crypto_core.cpp b/core/math/crypto_core.cpp deleted file mode 100644 index 51c2e3c9e5..0000000000 --- a/core/math/crypto_core.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/*************************************************************************/ -/* crypto_core.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_core.h" - -#include -#include -#include -#include -#include - -// MD5 -CryptoCore::MD5Context::MD5Context() { - ctx = memalloc(sizeof(mbedtls_md5_context)); - mbedtls_md5_init((mbedtls_md5_context *)ctx); -} - -CryptoCore::MD5Context::~MD5Context() { - mbedtls_md5_free((mbedtls_md5_context *)ctx); - memfree((mbedtls_md5_context *)ctx); -} - -Error CryptoCore::MD5Context::start() { - int ret = mbedtls_md5_starts_ret((mbedtls_md5_context *)ctx); - return ret ? FAILED : OK; -} - -Error CryptoCore::MD5Context::update(const uint8_t *p_src, size_t p_len) { - int ret = mbedtls_md5_update_ret((mbedtls_md5_context *)ctx, p_src, p_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::MD5Context::finish(unsigned char r_hash[16]) { - int ret = mbedtls_md5_finish_ret((mbedtls_md5_context *)ctx, r_hash); - return ret ? FAILED : OK; -} - -// SHA1 -CryptoCore::SHA1Context::SHA1Context() { - ctx = memalloc(sizeof(mbedtls_sha1_context)); - mbedtls_sha1_init((mbedtls_sha1_context *)ctx); -} - -CryptoCore::SHA1Context::~SHA1Context() { - mbedtls_sha1_free((mbedtls_sha1_context *)ctx); - memfree((mbedtls_sha1_context *)ctx); -} - -Error CryptoCore::SHA1Context::start() { - int ret = mbedtls_sha1_starts_ret((mbedtls_sha1_context *)ctx); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA1Context::update(const uint8_t *p_src, size_t p_len) { - int ret = mbedtls_sha1_update_ret((mbedtls_sha1_context *)ctx, p_src, p_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA1Context::finish(unsigned char r_hash[20]) { - int ret = mbedtls_sha1_finish_ret((mbedtls_sha1_context *)ctx, r_hash); - return ret ? FAILED : OK; -} - -// SHA256 -CryptoCore::SHA256Context::SHA256Context() { - ctx = memalloc(sizeof(mbedtls_sha256_context)); - mbedtls_sha256_init((mbedtls_sha256_context *)ctx); -} - -CryptoCore::SHA256Context::~SHA256Context() { - mbedtls_sha256_free((mbedtls_sha256_context *)ctx); - memfree((mbedtls_sha256_context *)ctx); -} - -Error CryptoCore::SHA256Context::start() { - int ret = mbedtls_sha256_starts_ret((mbedtls_sha256_context *)ctx, 0); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA256Context::update(const uint8_t *p_src, size_t p_len) { - int ret = mbedtls_sha256_update_ret((mbedtls_sha256_context *)ctx, p_src, p_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA256Context::finish(unsigned char r_hash[32]) { - int ret = mbedtls_sha256_finish_ret((mbedtls_sha256_context *)ctx, r_hash); - return ret ? FAILED : OK; -} - -// AES256 -CryptoCore::AESContext::AESContext() { - ctx = memalloc(sizeof(mbedtls_aes_context)); - mbedtls_aes_init((mbedtls_aes_context *)ctx); -} - -CryptoCore::AESContext::~AESContext() { - mbedtls_aes_free((mbedtls_aes_context *)ctx); - memfree((mbedtls_aes_context *)ctx); -} - -Error CryptoCore::AESContext::set_encode_key(const uint8_t *p_key, size_t p_bits) { - int ret = mbedtls_aes_setkey_enc((mbedtls_aes_context *)ctx, p_key, p_bits); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::set_decode_key(const uint8_t *p_key, size_t p_bits) { - int ret = mbedtls_aes_setkey_dec((mbedtls_aes_context *)ctx, p_key, p_bits); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { - int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_ENCRYPT, p_src, r_dst); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { - int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_DECRYPT, p_src, r_dst); - return ret ? FAILED : OK; -} - -// CryptoCore -String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) { - int b64len = p_src_len / 3 * 4 + 4 + 1; - PoolVector b64buff; - b64buff.resize(b64len); - PoolVector::Write w64 = b64buff.write(); - size_t strlen = 0; - int ret = b64_encode(&w64[0], b64len, &strlen, p_src, p_src_len); - w64[strlen] = 0; - return ret ? String() : (const char *)&w64[0]; -} - -Error CryptoCore::b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { - int ret = mbedtls_base64_encode(r_dst, p_dst_len, r_len, p_src, p_src_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { - int ret = mbedtls_base64_decode(r_dst, p_dst_len, r_len, p_src, p_src_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]) { - int ret = mbedtls_md5_ret(p_src, p_src_len, r_hash); - return ret ? FAILED : OK; -} - -Error CryptoCore::sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]) { - int ret = mbedtls_sha1_ret(p_src, p_src_len, r_hash); - return ret ? FAILED : OK; -} - -Error CryptoCore::sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]) { - int ret = mbedtls_sha256_ret(p_src, p_src_len, r_hash, 0); - return ret ? FAILED : OK; -} diff --git a/core/math/crypto_core.h b/core/math/crypto_core.h deleted file mode 100644 index c859d612d4..0000000000 --- a/core/math/crypto_core.h +++ /dev/null @@ -1,104 +0,0 @@ -/*************************************************************************/ -/* crypto_core.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_CORE_H -#define CRYPTO_CORE_H - -#include "core/reference.h" - -class CryptoCore { - -public: - class MD5Context { - - private: - void *ctx; // To include, or not to include... - - public: - MD5Context(); - ~MD5Context(); - - Error start(); - Error update(const uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[16]); - }; - - class SHA1Context { - - private: - void *ctx; // To include, or not to include... - - public: - SHA1Context(); - ~SHA1Context(); - - Error start(); - Error update(const uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[20]); - }; - - class SHA256Context { - - private: - void *ctx; // To include, or not to include... - - public: - SHA256Context(); - ~SHA256Context(); - - Error start(); - Error update(const uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[32]); - }; - - class AESContext { - - private: - void *ctx; // To include, or not to include... - - public: - AESContext(); - ~AESContext(); - - Error set_encode_key(const uint8_t *p_key, size_t p_bits); - Error set_decode_key(const uint8_t *p_key, size_t p_bits); - Error encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); - Error decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); - }; - - static String b64_encode_str(const uint8_t *p_src, int p_src_len); - static Error b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); - static Error b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); - - static Error md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]); - static Error sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]); - static Error sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]); -}; -#endif // CRYPTO_CORE_H diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp index ba94e87da6..9a8315a3bb 100644 --- a/core/os/file_access.cpp +++ b/core/os/file_access.cpp @@ -30,9 +30,9 @@ #include "file_access.h" +#include "core/crypto/crypto_core.h" #include "core/io/file_access_pack.h" #include "core/io/marshalls.h" -#include "core/math/crypto_core.h" #include "core/os/os.h" #include "core/project_settings.h" diff --git a/core/ustring.cpp b/core/ustring.cpp index ed401c3763..4e9ab7be6b 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -31,7 +31,7 @@ #include "ustring.h" #include "core/color.h" -#include "core/math/crypto_core.h" +#include "core/crypto/crypto_core.h" #include "core/math/math_funcs.h" #include "core/os/memory.h" #include "core/print_string.h" diff --git a/core/variant_call.cpp b/core/variant_call.cpp index 9ea2fed5ae..a3803d8701 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -32,8 +32,8 @@ #include "core/color_names.inc" #include "core/core_string_names.h" +#include "core/crypto/crypto_core.h" #include "core/io/compression.h" -#include "core/math/crypto_core.h" #include "core/object.h" #include "core/os/os.h" #include "core/script_language.h" diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp index cb1754bb10..e2a750cf08 100644 --- a/editor/editor_export.cpp +++ b/editor/editor_export.cpp @@ -30,11 +30,11 @@ #include "editor_export.h" +#include "core/crypto/crypto_core.h" #include "core/io/config_file.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/zip_io.h" -#include "core/math/crypto_core.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/project_settings.h" diff --git a/editor/import/editor_scene_importer_gltf.cpp b/editor/import/editor_scene_importer_gltf.cpp index 84dd1aa866..9ea7c86e0c 100644 --- a/editor/import/editor_scene_importer_gltf.cpp +++ b/editor/import/editor_scene_importer_gltf.cpp @@ -29,8 +29,8 @@ /*************************************************************************/ #include "editor_scene_importer_gltf.h" +#include "core/crypto/crypto_core.h" #include "core/io/json.h" -#include "core/math/crypto_core.h" #include "core/math/math_defs.h" #include "core/os/file_access.h" #include "core/os/os.h" diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp index b11bd2b70f..f94f3dfff7 100644 --- a/modules/websocket/wsl_peer.cpp +++ b/modules/websocket/wsl_peer.cpp @@ -35,7 +35,7 @@ #include "wsl_client.h" #include "wsl_server.h" -#include "core/math/crypto_core.h" +#include "core/crypto/crypto_core.h" #include "core/math/random_number_generator.h" #include "core/os/os.h" diff --git a/platform/uwp/export/export.cpp b/platform/uwp/export/export.cpp index 662ee49935..ea110b11ca 100644 --- a/platform/uwp/export/export.cpp +++ b/platform/uwp/export/export.cpp @@ -30,9 +30,9 @@ #include "export.h" #include "core/bind/core_bind.h" +#include "core/crypto/crypto_core.h" #include "core/io/marshalls.h" #include "core/io/zip_io.h" -#include "core/math/crypto_core.h" #include "core/object.h" #include "core/os/dir_access.h" #include "core/os/file_access.h" -- cgit v1.2.3 From 1b36aa662cb8df7b9236963c7b8eb9e9424395ca Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Thu, 11 Jul 2019 15:26:44 +0200 Subject: Add Crypto custom class --- core/crypto/SCsub | 38 ++++++++++ core/crypto/crypto.cpp | 170 +++++++++++++++++++++++++++++++++++++++++++ core/crypto/crypto.h | 105 ++++++++++++++++++++++++++ core/register_core_types.cpp | 22 ++++++ 4 files changed, 335 insertions(+) create mode 100644 core/crypto/SCsub create mode 100644 core/crypto/crypto.cpp create mode 100644 core/crypto/crypto.h diff --git a/core/crypto/SCsub b/core/crypto/SCsub new file mode 100644 index 0000000000..0a3f05d87a --- /dev/null +++ b/core/crypto/SCsub @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +Import('env') + +env_crypto = env.Clone() + +is_builtin = env["builtin_mbedtls"] +has_module = env["module_mbedtls_enabled"] + +if is_builtin or not has_module: + # Use our headers for builtin or if the module is not going to be compiled. + # We decided not to depend on system mbedtls just for these few files that can + # be easily extracted. + env_crypto.Prepend(CPPPATH=["#thirdparty/mbedtls/include"]) + +# MbedTLS core functions (for CryptoCore). +# If the mbedtls module is compiled we don't need to add the .c files with our +# custom config since they will be built by the module itself. +# Only if the module is not enabled, we must compile here the required sources +# to make a "light" build with only the necessary mbedtls files. +if not has_module: + env_thirdparty = env_crypto.Clone() + env_thirdparty.disable_warnings() + # Custom config file + env_thirdparty.Append(CPPDEFINES=[('MBEDTLS_CONFIG_FILE', '\\"thirdparty/mbedtls/include/godot_core_mbedtls_config.h\\"')]) + thirdparty_mbedtls_dir = "#thirdparty/mbedtls/library/" + thirdparty_mbedtls_sources = [ + "aes.c", + "base64.c", + "md5.c", + "sha1.c", + "sha256.c", + "godot_core_mbedtls_platform.c" + ] + thirdparty_mbedtls_sources = [thirdparty_mbedtls_dir + file for file in thirdparty_mbedtls_sources] + env_thirdparty.add_source_files(env.core_sources, thirdparty_mbedtls_sources) + +env_crypto.add_source_files(env.core_sources, "*.cpp") diff --git a/core/crypto/crypto.cpp b/core/crypto/crypto.cpp new file mode 100644 index 0000000000..925a01b36a --- /dev/null +++ b/core/crypto/crypto.cpp @@ -0,0 +1,170 @@ +/*************************************************************************/ +/* crypto.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.h" + +#include "core/engine.h" +#include "core/io/certs_compressed.gen.h" +#include "core/io/compression.h" + +/// Resources + +CryptoKey *(*CryptoKey::_create)() = NULL; +CryptoKey *CryptoKey::create() { + if (_create) + return _create(); + return NULL; +} + +void CryptoKey::_bind_methods() { + ClassDB::bind_method(D_METHOD("save", "path"), &CryptoKey::save); + ClassDB::bind_method(D_METHOD("load", "path"), &CryptoKey::load); +} + +X509Certificate *(*X509Certificate::_create)() = NULL; +X509Certificate *X509Certificate::create() { + if (_create) + return _create(); + return NULL; +} + +void X509Certificate::_bind_methods() { + ClassDB::bind_method(D_METHOD("save", "path"), &X509Certificate::save); + ClassDB::bind_method(D_METHOD("load", "path"), &X509Certificate::load); +} + +/// Crypto + +void (*Crypto::_load_default_certificates)(String p_path) = NULL; +Crypto *(*Crypto::_create)() = NULL; +Crypto *Crypto::create() { + if (_create) + return _create(); + return memnew(Crypto); +} + +void Crypto::load_default_certificates(String p_path) { + + if (_load_default_certificates) + _load_default_certificates(p_path); +} + +void Crypto::_bind_methods() { + ClassDB::bind_method(D_METHOD("generate_random_bytes", "size"), &Crypto::generate_random_bytes); + ClassDB::bind_method(D_METHOD("generate_rsa", "size"), &Crypto::generate_rsa); + ClassDB::bind_method(D_METHOD("generate_self_signed_certificate", "key", "issuer_name", "not_before", "not_after"), &Crypto::generate_self_signed_certificate, DEFVAL("CN=myserver,O=myorganisation,C=IT"), DEFVAL("20140101000000"), DEFVAL("20340101000000")); +} + +PoolByteArray Crypto::generate_random_bytes(int p_bytes) { + ERR_FAIL_V_MSG(PoolByteArray(), "generate_random_bytes is not available when mbedtls module is disabled."); +} + +Ref Crypto::generate_rsa(int p_bytes) { + ERR_FAIL_V_MSG(NULL, "generate_rsa is not available when mbedtls module is disabled."); +} + +Ref Crypto::generate_self_signed_certificate(Ref p_key, String p_issuer_name, String p_not_before, String p_not_after) { + ERR_FAIL_V_MSG(NULL, "generate_self_signed_certificate is not available when mbedtls module is disabled."); +} + +Crypto::Crypto() { +} + +/// Resource loader/saver + +RES ResourceFormatLoaderCrypto::load(const String &p_path, const String &p_original_path, Error *r_error) { + + String el = p_path.get_extension().to_lower(); + if (el == "crt") { + X509Certificate *cert = X509Certificate::create(); + if (cert) + cert->load(p_path); + return cert; + } else if (el == "key") { + CryptoKey *key = CryptoKey::create(); + if (key) + key->load(p_path); + return key; + } + return NULL; +} + +void ResourceFormatLoaderCrypto::get_recognized_extensions(List *p_extensions) const { + + p_extensions->push_back("crt"); + p_extensions->push_back("key"); +} + +bool ResourceFormatLoaderCrypto::handles_type(const String &p_type) const { + + return p_type == "X509Certificate" || p_type == "CryptoKey"; +} + +String ResourceFormatLoaderCrypto::get_resource_type(const String &p_path) const { + + String el = p_path.get_extension().to_lower(); + if (el == "crt") + return "X509Certificate"; + else if (el == "key") + return "CryptoKey"; + return ""; +} + +Error ResourceFormatSaverCrypto::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { + + Error err; + Ref cert = p_resource; + Ref key = p_resource; + if (cert.is_valid()) { + err = cert->save(p_path); + } else if (key.is_valid()) { + err = key->save(p_path); + } else { + ERR_FAIL_V(ERR_INVALID_PARAMETER); + } + ERR_FAIL_COND_V(err != OK, err); + return OK; +} + +void ResourceFormatSaverCrypto::get_recognized_extensions(const RES &p_resource, List *p_extensions) const { + + const X509Certificate *cert = Object::cast_to(*p_resource); + const CryptoKey *key = Object::cast_to(*p_resource); + if (cert) { + p_extensions->push_back("crt"); + } + if (key) { + p_extensions->push_back("key"); + } +} +bool ResourceFormatSaverCrypto::recognize(const RES &p_resource) const { + + return Object::cast_to(*p_resource) || Object::cast_to(*p_resource); +} diff --git a/core/crypto/crypto.h b/core/crypto/crypto.h new file mode 100644 index 0000000000..2de81f5b57 --- /dev/null +++ b/core/crypto/crypto.h @@ -0,0 +1,105 @@ +/*************************************************************************/ +/* crypto.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_H +#define CRYPTO_H + +#include "core/reference.h" +#include "core/resource.h" + +#include "core/io/resource_loader.h" +#include "core/io/resource_saver.h" + +class CryptoKey : public Resource { + GDCLASS(CryptoKey, Resource); + +protected: + static void _bind_methods(); + static CryptoKey *(*_create)(); + +public: + static CryptoKey *create(); + virtual Error load(String p_path) = 0; + virtual Error save(String p_path) = 0; +}; + +class X509Certificate : public Resource { + GDCLASS(X509Certificate, Resource); + +protected: + static void _bind_methods(); + static X509Certificate *(*_create)(); + +public: + static X509Certificate *create(); + virtual Error load(String p_path) = 0; + virtual Error load_from_memory(const uint8_t *p_buffer, int p_len) = 0; + virtual Error save(String p_path) = 0; +}; + +class Crypto : public Reference { + GDCLASS(Crypto, Reference); + +protected: + static void _bind_methods(); + static Crypto *(*_create)(); + static void (*_load_default_certificates)(String p_path); + +public: + static Crypto *create(); + static void load_default_certificates(String p_path); + + virtual PoolByteArray generate_random_bytes(int p_bytes); + virtual Ref generate_rsa(int p_bytes); + virtual Ref generate_self_signed_certificate(Ref p_key, String p_issuer_name, String p_not_before, String p_not_after); + + Crypto(); +}; + +class ResourceFormatLoaderCrypto : public ResourceFormatLoader { + GDCLASS(ResourceFormatLoaderCrypto, ResourceFormatLoader); + +public: + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); + virtual void get_recognized_extensions(List *p_extensions) const; + virtual bool handles_type(const String &p_type) const; + virtual String get_resource_type(const String &p_path) const; +}; + +class ResourceFormatSaverCrypto : public ResourceFormatSaver { + GDCLASS(ResourceFormatSaverCrypto, ResourceFormatSaver); + +public: + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual void get_recognized_extensions(const RES &p_resource, List *p_extensions) const; + virtual bool recognize(const RES &p_resource) const; +}; + +#endif // CRYPTO_H diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index e442546124..6c05f3d54c 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -34,6 +34,7 @@ #include "core/class_db.h" #include "core/compressed_translation.h" #include "core/core_string_names.h" +#include "core/crypto/crypto.h" #include "core/engine.h" #include "core/func_ref.h" #include "core/input_map.h" @@ -70,6 +71,8 @@ static Ref resource_loader_binary; static Ref resource_format_importer; static Ref resource_format_image; static Ref resource_format_po; +static Ref resource_format_saver_crypto; +static Ref resource_format_loader_crypto; static _ResourceLoader *_resource_loader = NULL; static _ResourceSaver *_resource_saver = NULL; @@ -151,7 +154,18 @@ void register_core_types() { ClassDB::register_class(); ClassDB::register_class(); ClassDB::register_class(); + + // Crypto + ClassDB::register_custom_instance_class(); + ClassDB::register_custom_instance_class(); + ClassDB::register_custom_instance_class(); ClassDB::register_custom_instance_class(); + + resource_format_saver_crypto.instance(); + ResourceSaver::add_resource_format_saver(resource_format_saver_crypto); + resource_format_loader_crypto.instance(); + ResourceLoader::add_resource_format_loader(resource_format_loader_crypto); + ClassDB::register_virtual_class(); ClassDB::register_virtual_class(); ClassDB::register_class(); @@ -211,6 +225,9 @@ void register_core_settings() { ProjectSettings::get_singleton()->set_custom_property_info("network/limits/tcp/connect_timeout_seconds", PropertyInfo(Variant::INT, "network/limits/tcp/connect_timeout_seconds", PROPERTY_HINT_RANGE, "1,1800,1")); GLOBAL_DEF_RST("network/limits/packet_peer_stream/max_buffer_po2", (16)); ProjectSettings::get_singleton()->set_custom_property_info("network/limits/packet_peer_stream/max_buffer_po2", PropertyInfo(Variant::INT, "network/limits/packet_peer_stream/max_buffer_po2", PROPERTY_HINT_RANGE, "0,64,1,or_greater")); + + GLOBAL_DEF("network/ssl/certificates", ""); + ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt")); } void register_core_singletons() { @@ -272,6 +289,11 @@ void unregister_core_types() { ResourceLoader::remove_resource_format_loader(resource_format_po); resource_format_po.unref(); + ResourceSaver::remove_resource_format_saver(resource_format_saver_crypto); + resource_format_saver_crypto.unref(); + ResourceLoader::remove_resource_format_loader(resource_format_loader_crypto); + resource_format_loader_crypto.unref(); + if (ip) memdelete(ip); -- cgit v1.2.3 From 3495d1bfa04606062a1ffa3b58eb3bdf51bb673c Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 19 Jul 2019 10:33:31 +0200 Subject: Add hex_encode function to PoolByteArray --- core/variant_call.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/variant_call.cpp b/core/variant_call.cpp index a3803d8701..02c6cd73d8 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -606,6 +606,13 @@ struct _VariantCall { r_ret = s; } + static void _call_PoolByteArray_hex_encode(Variant &r_ret, Variant &p_self, const Variant **p_args) { + PoolByteArray *ba = reinterpret_cast(p_self._data._mem); + PoolByteArray::Read r = ba->read(); + String s = String::hex_encode_buffer(&r[0], ba->size()); + r_ret = s; + } + VCALL_LOCALMEM0R(PoolByteArray, size); VCALL_LOCALMEM2(PoolByteArray, set); VCALL_LOCALMEM1R(PoolByteArray, get); @@ -1763,6 +1770,7 @@ void register_variant_methods() { ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_ascii, varray()); ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_utf8, varray()); ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, sha256_string, varray()); + ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, hex_encode, varray()); ADDFUNC1R(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, compress, INT, "compression_mode", varray(0)); ADDFUNC2R(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, decompress, INT, "buffer_size", INT, "compression_mode", varray(0)); -- cgit v1.2.3 From cb31b8797e72fc427a1987047aa885645c4e2c90 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 19 Jul 2019 15:06:43 +0200 Subject: Add hashing context class --- core/crypto/hashing_context.cpp | 137 ++++++++++++++++++++++++++++++++++++++++ core/crypto/hashing_context.h | 66 +++++++++++++++++++ core/register_core_types.cpp | 2 + 3 files changed, 205 insertions(+) create mode 100644 core/crypto/hashing_context.cpp create mode 100644 core/crypto/hashing_context.h diff --git a/core/crypto/hashing_context.cpp b/core/crypto/hashing_context.cpp new file mode 100644 index 0000000000..bdccb258dd --- /dev/null +++ b/core/crypto/hashing_context.cpp @@ -0,0 +1,137 @@ +/*************************************************************************/ +/* hashing_context.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 "hashing_context.h" + +#include "core/crypto/crypto_core.h" + +Error HashingContext::start(HashType p_type) { + ERR_FAIL_COND_V(ctx != NULL, ERR_ALREADY_IN_USE); + _create_ctx(p_type); + ERR_FAIL_COND_V(ctx == NULL, ERR_UNAVAILABLE); + switch (type) { + case HASH_MD5: + return ((CryptoCore::MD5Context *)ctx)->start(); + case HASH_SHA1: + return ((CryptoCore::SHA1Context *)ctx)->start(); + case HASH_SHA256: + return ((CryptoCore::SHA256Context *)ctx)->start(); + } + return ERR_UNAVAILABLE; +} + +Error HashingContext::update(PoolByteArray p_chunk) { + ERR_FAIL_COND_V(ctx == NULL, ERR_UNCONFIGURED); + size_t len = p_chunk.size(); + PoolByteArray::Read r = p_chunk.read(); + switch (type) { + case HASH_MD5: + return ((CryptoCore::MD5Context *)ctx)->update(&r[0], len); + case HASH_SHA1: + return ((CryptoCore::SHA1Context *)ctx)->update(&r[0], len); + case HASH_SHA256: + return ((CryptoCore::SHA256Context *)ctx)->update(&r[0], len); + } + return ERR_UNAVAILABLE; +} + +PoolByteArray HashingContext::finish() { + ERR_FAIL_COND_V(ctx == NULL, PoolByteArray()); + PoolByteArray out; + Error err = FAILED; + switch (type) { + case HASH_MD5: + out.resize(16); + err = ((CryptoCore::MD5Context *)ctx)->finish(out.write().ptr()); + break; + case HASH_SHA1: + out.resize(20); + err = ((CryptoCore::SHA1Context *)ctx)->finish(out.write().ptr()); + break; + case HASH_SHA256: + out.resize(32); + err = ((CryptoCore::SHA256Context *)ctx)->finish(out.write().ptr()); + break; + } + _delete_ctx(); + ERR_FAIL_COND_V(err != OK, PoolByteArray()); + return out; +} + +void HashingContext::_create_ctx(HashType p_type) { + type = p_type; + switch (type) { + case HASH_MD5: + ctx = memnew(CryptoCore::MD5Context); + break; + case HASH_SHA1: + ctx = memnew(CryptoCore::SHA1Context); + break; + case HASH_SHA256: + ctx = memnew(CryptoCore::SHA256Context); + break; + default: + ctx = NULL; + } +} + +void HashingContext::_delete_ctx() { + return; + switch (type) { + case HASH_MD5: + memdelete((CryptoCore::MD5Context *)ctx); + break; + case HASH_SHA1: + memdelete((CryptoCore::SHA1Context *)ctx); + break; + case HASH_SHA256: + memdelete((CryptoCore::SHA256Context *)ctx); + break; + } + ctx = NULL; +} + +void HashingContext::_bind_methods() { + ClassDB::bind_method(D_METHOD("start", "type"), &HashingContext::start); + ClassDB::bind_method(D_METHOD("update", "chunk"), &HashingContext::update); + ClassDB::bind_method(D_METHOD("finish"), &HashingContext::finish); + BIND_ENUM_CONSTANT(HASH_MD5); + BIND_ENUM_CONSTANT(HASH_SHA1); + BIND_ENUM_CONSTANT(HASH_SHA256); +} + +HashingContext::HashingContext() { + ctx = NULL; +} + +HashingContext::~HashingContext() { + if (ctx != NULL) + _delete_ctx(); +} diff --git a/core/crypto/hashing_context.h b/core/crypto/hashing_context.h new file mode 100644 index 0000000000..aa69636f2c --- /dev/null +++ b/core/crypto/hashing_context.h @@ -0,0 +1,66 @@ +/*************************************************************************/ +/* hashing_context.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 HASHING_CONTEXT_H +#define HASHING_CONTEXT_H + +#include "core/reference.h" + +class HashingContext : public Reference { + GDCLASS(HashingContext, Reference); + +public: + enum HashType { + HASH_MD5, + HASH_SHA1, + HASH_SHA256 + }; + +private: + void *ctx; + HashType type; + +protected: + static void _bind_methods(); + void _create_ctx(HashType p_type); + void _delete_ctx(); + +public: + Error start(HashType p_type); + Error update(PoolByteArray p_chunk); + PoolByteArray finish(); + + HashingContext(); + ~HashingContext(); +}; + +VARIANT_ENUM_CAST(HashingContext::HashType); + +#endif // HASHING_CONTEXT_H diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index 6c05f3d54c..efc77bde48 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -35,6 +35,7 @@ #include "core/compressed_translation.h" #include "core/core_string_names.h" #include "core/crypto/crypto.h" +#include "core/crypto/hashing_context.h" #include "core/engine.h" #include "core/func_ref.h" #include "core/input_map.h" @@ -156,6 +157,7 @@ void register_core_types() { ClassDB::register_class(); // Crypto + ClassDB::register_class(); ClassDB::register_custom_instance_class(); ClassDB::register_custom_instance_class(); ClassDB::register_custom_instance_class(); -- cgit v1.2.3 From dd8107caa43b8e9eca8dfcf144bbbd88ccde462f Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 19 Jul 2019 15:17:22 +0200 Subject: New CryptoMbedTLS Crypto implementation. Allows random bytes, RSA keys, and X509 certificates generation. --- modules/mbedtls/crypto_mbedtls.cpp | 285 +++++++++++++++++++++++++++++++++++++ modules/mbedtls/crypto_mbedtls.h | 124 ++++++++++++++++ modules/mbedtls/register_types.cpp | 4 +- 3 files changed, 412 insertions(+), 1 deletion(-) create mode 100644 modules/mbedtls/crypto_mbedtls.cpp create mode 100644 modules/mbedtls/crypto_mbedtls.h diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp new file mode 100644 index 0000000000..9c8eb40ca4 --- /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 + +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 some certificates: " + 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 CryptoMbedTLS::generate_rsa(int p_bytes) { + Ref 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 CryptoMbedTLS::generate_self_signed_certificate(Ref p_key, String p_issuer_name, String p_not_before, String p_not_after) { + Ref key = static_cast >(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 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 +#include +#include + +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 generate_rsa(int p_bytes); + virtual Ref generate_self_signed_certificate(Ref 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..88f8155336 100755 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -30,15 +30,17 @@ #include "register_types.h" +#include "crypto_mbedtls.h" #include "stream_peer_mbed_tls.h" void register_mbedtls_types() { - ClassDB::register_class(); + CryptoMbedTLS::initialize_crypto(); StreamPeerMbedTLS::initialize_ssl(); } void unregister_mbedtls_types() { StreamPeerMbedTLS::finalize_ssl(); + CryptoMbedTLS::finalize_crypto(); } -- cgit v1.2.3 From ce5a3f56a608dcafd33aed6a9f262ed7ca9f01e8 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 19 Jul 2019 15:29:57 +0200 Subject: Rewrite StreamPeerSSL with SSLContext helper class connect_to_stream now accepts optional parameter to specify which certificates to trust. Implement accept_stream (SSL server) with key/cert parameters to specify the RSA key and X509 certificate resources. --- core/io/stream_peer_ssl.cpp | 68 +----- core/io/stream_peer_ssl.h | 13 +- editor/editor_settings.cpp | 3 +- main/main.cpp | 17 +- modules/mbedtls/register_types.cpp | 2 +- modules/mbedtls/ssl_context_mbedtls.cpp | 148 +++++++++++++ modules/mbedtls/ssl_context_mbedtls.h | 74 +++++++ modules/mbedtls/stream_peer_mbed_tls.cpp | 367 ------------------------------- modules/mbedtls/stream_peer_mbed_tls.h | 94 -------- modules/mbedtls/stream_peer_mbedtls.cpp | 326 +++++++++++++++++++++++++++ modules/mbedtls/stream_peer_mbedtls.h | 89 ++++++++ 11 files changed, 653 insertions(+), 548 deletions(-) create mode 100644 modules/mbedtls/ssl_context_mbedtls.cpp create mode 100644 modules/mbedtls/ssl_context_mbedtls.h delete mode 100755 modules/mbedtls/stream_peer_mbed_tls.cpp delete mode 100755 modules/mbedtls/stream_peer_mbed_tls.h create mode 100755 modules/mbedtls/stream_peer_mbedtls.cpp create mode 100755 modules/mbedtls/stream_peer_mbedtls.h diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp index ccce48ccd7..f2eaf57acc 100644 --- a/core/io/stream_peer_ssl.cpp +++ b/core/io/stream_peer_ssl.cpp @@ -30,10 +30,7 @@ #include "stream_peer_ssl.h" -#include "core/io/certs_compressed.gen.h" -#include "core/io/compression.h" -#include "core/os/file_access.h" -#include "core/project_settings.h" +#include "core/engine.h" StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL; @@ -44,22 +41,8 @@ StreamPeerSSL *StreamPeerSSL::create() { return NULL; } -StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL; bool StreamPeerSSL::available = false; -void StreamPeerSSL::load_certs_from_memory(const PoolByteArray &p_memory) { - if (load_certs_func) - load_certs_func(p_memory); -} - -void StreamPeerSSL::load_certs_from_file(String p_path) { - if (p_path != "") { - PoolByteArray certs = get_cert_file_as_array(p_path); - if (certs.size() > 0) - load_certs_func(certs); - } -} - bool StreamPeerSSL::is_available() { return available; } @@ -72,56 +55,11 @@ bool StreamPeerSSL::is_blocking_handshake_enabled() const { return blocking_handshake; } -PoolByteArray StreamPeerSSL::get_cert_file_as_array(String p_path) { - - PoolByteArray out; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (f) { - int flen = f->get_len(); - out.resize(flen + 1); - PoolByteArray::Write w = out.write(); - f->get_buffer(w.ptr(), flen); - w[flen] = 0; // Make sure it ends with string terminator - memdelete(f); -#ifdef DEBUG_ENABLED - print_verbose(vformat("Loaded certs from '%s'.", p_path)); -#endif - } - - return out; -} - -PoolByteArray StreamPeerSSL::get_project_cert_array() { - - PoolByteArray out; - String certs_path = GLOBAL_DEF("network/ssl/certificates", ""); - ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt")); - - if (certs_path != "") { - // Use certs defined in project settings. - return get_cert_file_as_array(certs_path); - } -#ifdef BUILTIN_CERTS_ENABLED - else { - // Use builtin certs only if user did not override it in project settings. - 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 - } -#endif - - return out; -} - void StreamPeerSSL::_bind_methods() { ClassDB::bind_method(D_METHOD("poll"), &StreamPeerSSL::poll); - ClassDB::bind_method(D_METHOD("accept_stream", "base"), &StreamPeerSSL::accept_stream); - ClassDB::bind_method(D_METHOD("connect_to_stream", "stream", "validate_certs", "for_hostname"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String())); + ClassDB::bind_method(D_METHOD("accept_stream", "stream", "private_key", "certificate", "chain"), &StreamPeerSSL::accept_stream, DEFVAL(Ref())); + ClassDB::bind_method(D_METHOD("connect_to_stream", "stream", "validate_certs", "for_hostname", "valid_certificate"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String()), DEFVAL(Ref())); ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerSSL::get_status); ClassDB::bind_method(D_METHOD("disconnect_from_stream"), &StreamPeerSSL::disconnect_from_stream); ClassDB::bind_method(D_METHOD("set_blocking_handshake_enabled", "enabled"), &StreamPeerSSL::set_blocking_handshake_enabled); diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h index 482576c4c6..dedc35b9ac 100644 --- a/core/io/stream_peer_ssl.h +++ b/core/io/stream_peer_ssl.h @@ -31,19 +31,16 @@ #ifndef STREAM_PEER_SSL_H #define STREAM_PEER_SSL_H +#include "core/crypto/crypto.h" #include "core/io/stream_peer.h" class StreamPeerSSL : public StreamPeer { GDCLASS(StreamPeerSSL, StreamPeer); -public: - typedef void (*LoadCertsFromMemory)(const PoolByteArray &p_certs); - protected: static StreamPeerSSL *(*_create)(); static void _bind_methods(); - static LoadCertsFromMemory load_certs_func; static bool available; bool blocking_handshake; @@ -61,18 +58,14 @@ public: bool is_blocking_handshake_enabled() const; virtual void poll() = 0; - virtual Error accept_stream(Ref p_base) = 0; - virtual Error connect_to_stream(Ref p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0; + virtual Error accept_stream(Ref p_base, Ref p_key, Ref p_cert, Ref p_ca_chain = Ref()) = 0; + virtual Error connect_to_stream(Ref p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref p_valid_cert = Ref()) = 0; virtual Status get_status() const = 0; virtual void disconnect_from_stream() = 0; static StreamPeerSSL *create(); - static PoolByteArray get_cert_file_as_array(String p_path); - static PoolByteArray get_project_cert_array(); - static void load_certs_from_file(String p_path); - static void load_certs_from_memory(const PoolByteArray &p_memory); static bool is_available(); StreamPeerSSL(); diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index cb3bfa3a49..ca1387007e 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -1022,7 +1022,8 @@ void EditorSettings::setup_network() { add_property_hint(PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1")); // Editor SSL certificates override - _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); + String certs = has_setting("network/ssl/editor_ssl_certificates") ? get("network/ssl/editor_ssl_certificates") : _SYSTEM_CERTS_PATH; + _initial_set("network/ssl/editor_ssl_certificates", certs); add_property_hint(PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem")); } diff --git a/main/main.cpp b/main/main.cpp index 027273c4f4..582df4e866 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -30,6 +30,7 @@ #include "main.h" +#include "core/crypto/crypto.h" #include "core/input_map.h" #include "core/io/file_access_network.h" #include "core/io/file_access_pack.h" @@ -37,8 +38,6 @@ #include "core/io/image_loader.h" #include "core/io/ip.h" #include "core/io/resource_loader.h" -#include "core/io/stream_peer_ssl.h" -#include "core/io/stream_peer_tcp.h" #include "core/message_queue.h" #include "core/os/dir_access.h" #include "core/os/os.h" @@ -1741,7 +1740,7 @@ bool Main::start() { if (!project_manager && !editor) { // game // Load SSL Certificates from Project Settings (or builtin). - StreamPeerSSL::load_certs_from_memory(StreamPeerSSL::get_project_cert_array()); + Crypto::load_default_certificates(GLOBAL_DEF("network/ssl/certificates", "")); if (game_path != "") { Node *scene = NULL; @@ -1793,17 +1792,15 @@ bool Main::start() { } if (project_manager || editor) { - // Load SSL Certificates from Editor Settings (or builtin). - String certs = EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String(); - if (certs != "") - StreamPeerSSL::load_certs_from_file(certs); - else - StreamPeerSSL::load_certs_from_memory(StreamPeerSSL::get_project_cert_array()); - // Hide console window if requested (Windows-only). bool hide_console = EditorSettings::get_singleton()->get_setting("interface/editor/hide_console_window"); OS::get_singleton()->set_console_visible(!hide_console); } + + if (project_manager || editor) { + // Load SSL Certificates from Editor Settings (or builtin) + Crypto::load_default_certificates(EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String()); + } #endif } diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp index 88f8155336..f7dc6c785f 100755 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -31,7 +31,7 @@ #include "register_types.h" #include "crypto_mbedtls.h" -#include "stream_peer_mbed_tls.h" +#include "stream_peer_mbedtls.h" void register_mbedtls_types() { diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp new file mode 100644 index 0000000000..014a201f9c --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.cpp @@ -0,0 +1,148 @@ +/*************************************************************************/ +/* 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 p_pkey, Ref 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 p_valid_cas) { + X509CertificateMbedTLS *cas = NULL; + + if (certs.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(); + ERR_FAIL_COND_V(cas == NULL, ERR_UNCONFIGURED); + } + + Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode); + ERR_FAIL_COND_V(err != OK, err); + + // 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(); + if (pkey.is_valid()) + pkey->unlock(); + pkey = Ref(); + 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..8a072fd6eb --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.h @@ -0,0 +1,74 @@ +/*************************************************************************/ +/* 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 +#include +#include +#include +#include +#include + +class SSLContextMbedTLS : public Reference { + +protected: + bool inited; + + static PoolByteArray _read_file(String p_path); + +public: + Ref certs; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + + Ref pkey; + + Error _setup(int p_endpoint, int p_transport, int p_authmode); + Error init_server(int p_transport, int p_authmode, Ref p_pkey, Ref p_cert); + Error init_client(int p_transport, int p_authmode, Ref 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_mbed_tls.cpp deleted file mode 100755 index 4bb7557150..0000000000 --- a/modules/mbedtls/stream_peer_mbed_tls.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/*************************************************************************/ -/* stream_peer_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 "stream_peer_mbed_tls.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); -} - -int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { - - if (buf == NULL || len <= 0) return 0; - - StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; - - ERR_FAIL_COND_V(sp == NULL, 0); - - int sent; - Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent); - if (err != OK) { - return MBEDTLS_ERR_SSL_INTERNAL_ERROR; - } - if (sent == 0) { - return MBEDTLS_ERR_SSL_WANT_WRITE; - } - return sent; -} - -int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { - - if (buf == NULL || len <= 0) return 0; - - StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; - - ERR_FAIL_COND_V(sp == NULL, 0); - - int got; - Error err = sp->base->get_partial_data((uint8_t *)buf, len, got); - if (err != OK) { - return MBEDTLS_ERR_SSL_INTERNAL_ERROR; - } - if (got == 0) { - return MBEDTLS_ERR_SSL_WANT_READ; - } - return got; -} - -void StreamPeerMbedTLS::_cleanup() { - - mbedtls_ssl_free(&ssl); - mbedtls_ssl_config_free(&conf); - mbedtls_ctr_drbg_free(&ctr_drbg); - mbedtls_entropy_free(&entropy); - - base = Ref(); - status = STATUS_DISCONNECTED; -} - -Error StreamPeerMbedTLS::_do_handshake() { - int ret = 0; - while ((ret = mbedtls_ssl_handshake(&ssl)) != 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); - disconnect_from_stream(); - status = STATUS_ERROR; - return FAILED; - } - - // Handshake is still in progress. - if (!blocking_handshake) { - // Will retry via poll later - return OK; - } - } - - status = STATUS_CONNECTED; - return OK; -} - -Error StreamPeerMbedTLS::connect_to_stream(Ref p_base, bool p_validate_certs, const String &p_for_hostname) { - - ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); - - base = p_base; - 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; - } - - 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); - - status = STATUS_HANDSHAKING; - - if ((ret = _do_handshake()) != OK) { - status = STATUS_ERROR_HOSTNAME_MISMATCH; - return FAILED; - } - - return OK; -} - -Error StreamPeerMbedTLS::accept_stream(Ref p_base) { - - return OK; -} - -Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { - - ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); - - Error err; - int sent = 0; - - while (p_bytes > 0) { - err = put_partial_data(p_data, p_bytes, sent); - - if (err != OK) { - return err; - } - - p_data += sent; - p_bytes -= sent; - } - - return OK; -} - -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) - return OK; - - int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes); - if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { - // Non blocking IO - ret = 0; - } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { - // Clean close - disconnect_from_stream(); - return ERR_FILE_EOF; - } else if (ret <= 0) { - _print_error(ret); - disconnect_from_stream(); - return ERR_CONNECTION_ERROR; - } - - r_sent = ret; - return OK; -} - -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) { - return err; - } - - p_buffer += got; - p_bytes -= got; - } - - return OK; -} - -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; - - int ret = mbedtls_ssl_read(&ssl, 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) { - // Clean close - disconnect_from_stream(); - return ERR_FILE_EOF; - } else if (ret <= 0) { - _print_error(ret); - disconnect_from_stream(); - return ERR_CONNECTION_ERROR; - } - - r_received = ret; - return OK; -} - -void StreamPeerMbedTLS::poll() { - - ERR_FAIL_COND(status != STATUS_CONNECTED && status != STATUS_HANDSHAKING); - ERR_FAIL_COND(!base.is_valid()); - - if (status == STATUS_HANDSHAKING) { - _do_handshake(); - return; - } - - // 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); - - if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { - // Nothing to read/write (non blocking IO) - } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { - // Clean close (disconnect) - disconnect_from_stream(); - return; - } else if (ret < 0) { - _print_error(ret); - disconnect_from_stream(); - return; - } - - Ref tcp = base; - if (tcp.is_valid() && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) { - disconnect_from_stream(); - return; - } -} - -int StreamPeerMbedTLS::get_available_bytes() const { - - ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); - - return mbedtls_ssl_get_bytes_avail(&ssl); -} -StreamPeerMbedTLS::StreamPeerMbedTLS() { - - status = STATUS_DISCONNECTED; -} - -StreamPeerMbedTLS::~StreamPeerMbedTLS() { - disconnect_from_stream(); -} - -void StreamPeerMbedTLS::disconnect_from_stream() { - - if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) - return; - - Ref 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); - } - - _cleanup(); -} - -StreamPeerMbedTLS::Status StreamPeerMbedTLS::get_status() const { - - return status; -} - -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; -} - -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_mbed_tls.h deleted file mode 100755 index ab87b779c1..0000000000 --- a/modules/mbedtls/stream_peer_mbed_tls.h +++ /dev/null @@ -1,94 +0,0 @@ -/*************************************************************************/ -/* stream_peer_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 STREAM_PEER_OPEN_SSL_H -#define STREAM_PEER_OPEN_SSL_H - -#include "core/io/stream_peer_ssl.h" - -#include -#include -#include -#include -#include - -#include -#include - -class StreamPeerMbedTLS : public StreamPeerSSL { -private: - Status status; - String hostname; - - Ref 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; - - static void _bind_methods(); - - Error _do_handshake(); - -public: - virtual void poll(); - virtual Error accept_stream(Ref p_base); - virtual Error connect_to_stream(Ref p_base, bool p_validate_certs = false, const String &p_for_hostname = String()); - virtual Status get_status() const; - - virtual void disconnect_from_stream(); - - virtual Error put_data(const uint8_t *p_data, int p_bytes); - virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent); - - virtual Error get_data(uint8_t *p_buffer, int p_bytes); - virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received); - - virtual int get_available_bytes() const; - - static void initialize_ssl(); - static void finalize_ssl(); - - StreamPeerMbedTLS(); - ~StreamPeerMbedTLS(); -}; - -#endif // STREAM_PEER_SSL_H diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp new file mode 100755 index 0000000000..a9acfbef02 --- /dev/null +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -0,0 +1,326 @@ +/*************************************************************************/ +/* stream_peer_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 "stream_peer_mbedtls.h" + +#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; + + StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; + + ERR_FAIL_COND_V(sp == NULL, 0); + + int sent; + Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent); + if (err != OK) { + return MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } + if (sent == 0) { + return MBEDTLS_ERR_SSL_WANT_WRITE; + } + return sent; +} + +int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { + + if (buf == NULL || len <= 0) return 0; + + StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; + + ERR_FAIL_COND_V(sp == NULL, 0); + + int got; + Error err = sp->base->get_partial_data((uint8_t *)buf, len, got); + if (err != OK) { + return MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } + if (got == 0) { + return MBEDTLS_ERR_SSL_WANT_READ; + } + return got; +} + +void StreamPeerMbedTLS::_cleanup() { + + ssl_ctx->clear(); + base = Ref(); + status = STATUS_DISCONNECTED; +} + +Error StreamPeerMbedTLS::_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) { + // An error occurred. + ERR_PRINTS("TLS handshake error: " + itos(ret)); + _print_error(ret); + disconnect_from_stream(); + status = STATUS_ERROR; + return FAILED; + } + + // Handshake is still in progress. + if (!blocking_handshake) { + // Will retry via poll later + return OK; + } + } + + status = STATUS_CONNECTED; + return OK; +} + +Error StreamPeerMbedTLS::connect_to_stream(Ref p_base, bool p_validate_certs, const String &p_for_hostname, Ref p_ca_certs) { + + 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_STREAM, 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, NULL); + + status = STATUS_HANDSHAKING; + + if ((ret = _do_handshake()) != OK) { + status = STATUS_ERROR_HOSTNAME_MISMATCH; + return FAILED; + } + + return OK; +} + +Error StreamPeerMbedTLS::accept_stream(Ref p_base, Ref p_key, Ref p_cert, Ref p_ca_chain) { + + 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); + + Error err; + int sent = 0; + + while (p_bytes > 0) { + err = put_partial_data(p_data, p_bytes, sent); + + if (err != OK) { + return err; + } + + p_data += sent; + p_bytes -= sent; + } + + return OK; +} + +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) + 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) { + // Non blocking IO + ret = 0; + } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // Clean close + disconnect_from_stream(); + return ERR_FILE_EOF; + } else if (ret <= 0) { + _print_error(ret); + disconnect_from_stream(); + return ERR_CONNECTION_ERROR; + } + + r_sent = ret; + return OK; +} + +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) { + return err; + } + + p_buffer += got; + p_bytes -= got; + } + + return OK; +} + +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; + + 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) { + // Clean close + disconnect_from_stream(); + return ERR_FILE_EOF; + } else if (ret <= 0) { + _print_error(ret); + disconnect_from_stream(); + return ERR_CONNECTION_ERROR; + } + + r_received = ret; + return OK; +} + +void StreamPeerMbedTLS::poll() { + + ERR_FAIL_COND(status != STATUS_CONNECTED && status != STATUS_HANDSHAKING); + ERR_FAIL_COND(!base.is_valid()); + + if (status == STATUS_HANDSHAKING) { + _do_handshake(); + return; + } + + // 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_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) + } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // Clean close (disconnect) + disconnect_from_stream(); + return; + } else if (ret < 0) { + _print_error(ret); + disconnect_from_stream(); + return; + } + + Ref tcp = base; + if (tcp.is_valid() && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) { + disconnect_from_stream(); + return; + } +} + +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() { + + ssl_ctx.instance(); + status = STATUS_DISCONNECTED; +} + +StreamPeerMbedTLS::~StreamPeerMbedTLS() { + disconnect_from_stream(); +} + +void StreamPeerMbedTLS::disconnect_from_stream() { + + if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) + return; + + Ref 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_ctx->get_context()); + } + + _cleanup(); +} + +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; +} diff --git a/modules/mbedtls/stream_peer_mbedtls.h b/modules/mbedtls/stream_peer_mbedtls.h new file mode 100755 index 0000000000..179d1d37e1 --- /dev/null +++ b/modules/mbedtls/stream_peer_mbedtls.h @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* stream_peer_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 STREAM_PEER_OPEN_SSL_H +#define STREAM_PEER_OPEN_SSL_H + +#include "core/io/stream_peer_ssl.h" +#include "ssl_context_mbedtls.h" + +#include +#include +#include +#include +#include + +#include +#include + +class StreamPeerMbedTLS : public StreamPeerSSL { +private: + Status status; + String hostname; + + Ref base; + + static StreamPeerSSL *_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 ssl_ctx; + + static void _bind_methods(); + + Error _do_handshake(); + +public: + virtual void poll(); + virtual Error accept_stream(Ref p_base, Ref p_key, Ref p_cert, Ref p_ca_chain = Ref()); + virtual Error connect_to_stream(Ref p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref p_valid_cert = Ref()); + virtual Status get_status() const; + + virtual void disconnect_from_stream(); + + virtual Error put_data(const uint8_t *p_data, int p_bytes); + virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent); + + virtual Error get_data(uint8_t *p_buffer, int p_bytes); + virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received); + + virtual int get_available_bytes() const; + + static void initialize_ssl(); + static void finalize_ssl(); + + StreamPeerMbedTLS(); + ~StreamPeerMbedTLS(); +}; + +#endif // STREAM_PEER_SSL_H -- cgit v1.2.3 From fc411115f5ddb214c19b23499400f10266095e5f Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Wed, 21 Aug 2019 17:05:06 +0200 Subject: Fix Network Editor Settings setup. --- editor/editor_settings.cpp | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index ca1387007e..2925e7a496 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -608,6 +608,18 @@ void EditorSettings::_load_defaults(Ref p_extra_config) { _initial_set("run/output/always_open_output_on_play", true); _initial_set("run/output/always_close_output_on_stop", false); + /* Network */ + + // Debug + _initial_set("network/debug/remote_host", "127.0.0.1"); // Hints provided in setup_network + + _initial_set("network/debug/remote_port", 6007); + hints["network/debug/remote_port"] = PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1"); + + // SSL + _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH); + hints["network/ssl/editor_ssl_certificates"] = PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"); + /* Extra config */ _initial_set("project_manager/sorting_order", 0); @@ -993,11 +1005,11 @@ void EditorSettings::setup_network() { List local_ip; IP::get_singleton()->get_local_addresses(&local_ip); - String lip = "127.0.0.1"; String hint; String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : ""; - int port = has_setting("network/debug/remote_port") ? (int)get("network/debug/remote_port") : 6007; + String selected = "127.0.0.1"; + // Check that current remote_host is a valid interface address and populate hints. for (List::Element *E = local_ip.front(); E; E = E->next()) { String ip = E->get(); @@ -1008,23 +1020,18 @@ void EditorSettings::setup_network() { // Same goes for IPv4 link-local (APIPA) addresses. if (ip.begins_with("169.254.")) // 169.254.0.0/16 continue; + // Select current IP (found) if (ip == current) - lip = current; //so it saves + selected = ip; if (hint != "") hint += ","; hint += ip; } - _initial_set("network/debug/remote_host", lip); + // Add hints with valid IP addresses to remote_host property. add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint)); - - _initial_set("network/debug/remote_port", port); - add_property_hint(PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1")); - - // Editor SSL certificates override - String certs = has_setting("network/ssl/editor_ssl_certificates") ? get("network/ssl/editor_ssl_certificates") : _SYSTEM_CERTS_PATH; - _initial_set("network/ssl/editor_ssl_certificates", certs); - add_property_hint(PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem")); + // Fix potentially invalid remote_host due to network change. + set("network/debug/remote_host", selected); } void EditorSettings::save() { -- cgit v1.2.3