Browse Source

Merge pull request #29871 from Faless/crypto/initial_pr

More Crypto, SSL server, crt/key as Resource, HashingContext
Rémi Verschelde 6 years ago
parent
commit
99980d856b

+ 1 - 0
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')
 

+ 1 - 1
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"

+ 38 - 0
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")

+ 170 - 0
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<CryptoKey> Crypto::generate_rsa(int p_bytes) {
+	ERR_FAIL_V_MSG(NULL, "generate_rsa is not available when mbedtls module is disabled.");
+}
+
+Ref<X509Certificate> Crypto::generate_self_signed_certificate(Ref<CryptoKey> 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<String> *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<X509Certificate> cert = p_resource;
+	Ref<CryptoKey> 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<String> *p_extensions) const {
+
+	const X509Certificate *cert = Object::cast_to<X509Certificate>(*p_resource);
+	const CryptoKey *key = Object::cast_to<CryptoKey>(*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<X509Certificate>(*p_resource) || Object::cast_to<CryptoKey>(*p_resource);
+}

+ 105 - 0
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<CryptoKey> generate_rsa(int p_bytes);
+	virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
+
+	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<String> *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<String> *p_extensions) const;
+	virtual bool recognize(const RES &p_resource) const;
+};
+
+#endif // CRYPTO_H

+ 29 - 3
core/math/crypto_core.cpp → core/crypto/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;
 }

+ 17 - 3
core/math/crypto_core.h → core/crypto/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 {

+ 137 - 0
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();
+}

+ 66 - 0
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

+ 1 - 1
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"

+ 3 - 65
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<X509Certificate>()));
+	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<X509Certificate>()));
 	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);

+ 3 - 10
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<StreamPeer> p_base) = 0;
-	virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0;
+	virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>()) = 0;
+	virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>()) = 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();

+ 1 - 32
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")

+ 1 - 1
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"
 

+ 24 - 0
core/register_core_types.cpp

@@ -34,6 +34,8 @@
 #include "core/class_db.h"
 #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"
@@ -70,6 +72,8 @@ static Ref<ResourceFormatLoaderBinary> resource_loader_binary;
 static Ref<ResourceFormatImporter> resource_format_importer;
 static Ref<ResourceFormatLoaderImage> resource_format_image;
 static Ref<TranslationLoaderPO> resource_format_po;
+static Ref<ResourceFormatSaverCrypto> resource_format_saver_crypto;
+static Ref<ResourceFormatLoaderCrypto> resource_format_loader_crypto;
 
 static _ResourceLoader *_resource_loader = NULL;
 static _ResourceSaver *_resource_saver = NULL;
@@ -151,7 +155,19 @@ void register_core_types() {
 	ClassDB::register_class<StreamPeerTCP>();
 	ClassDB::register_class<TCP_Server>();
 	ClassDB::register_class<PacketPeerUDP>();
+
+	// Crypto
+	ClassDB::register_class<HashingContext>();
+	ClassDB::register_custom_instance_class<X509Certificate>();
+	ClassDB::register_custom_instance_class<CryptoKey>();
+	ClassDB::register_custom_instance_class<Crypto>();
 	ClassDB::register_custom_instance_class<StreamPeerSSL>();
+
+	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<IP>();
 	ClassDB::register_virtual_class<PacketPeer>();
 	ClassDB::register_class<PacketPeerStream>();
@@ -211,6 +227,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 +291,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);
 

+ 1 - 1
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"

+ 9 - 1
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"
@@ -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<PoolByteArray *>(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));
 

+ 1 - 1
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"

+ 19 - 11
editor/editor_settings.cpp

@@ -608,6 +608,18 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> 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<IP_Address> 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<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) {
 
 		String ip = E->get();
@@ -1008,22 +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
-	_initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH);
-	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() {

+ 1 - 1
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"

+ 7 - 10
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
 	}
 

+ 285 - 0
modules/mbedtls/crypto_mbedtls.cpp

@@ -0,0 +1,285 @@
+/*************************************************************************/
+/*  crypto_mbedtls.cpp                                                   */
+/*************************************************************************/
+/*                       This file is part of:                           */
+/*                           GODOT ENGINE                                */
+/*                      https://godotengine.org                          */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
+/*                                                                       */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the       */
+/* "Software"), to deal in the Software without restriction, including   */
+/* without limitation the rights to use, copy, modify, merge, publish,   */
+/* distribute, sublicense, and/or sell copies of the Software, and to    */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions:                                             */
+/*                                                                       */
+/* The above copyright notice and this permission notice shall be        */
+/* included in all copies or substantial portions of the Software.       */
+/*                                                                       */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
+/*************************************************************************/
+
+#include "crypto_mbedtls.h"
+
+#include "core/os/file_access.h"
+
+#include "core/engine.h"
+#include "core/io/certs_compressed.gen.h"
+#include "core/io/compression.h"
+#include "core/project_settings.h"
+
+#ifdef TOOLS_ENABLED
+#include "editor/editor_settings.h"
+#endif
+#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
+#define PEM_END_CRT "-----END CERTIFICATE-----\n"
+
+#include "mbedtls/pem.h"
+#include <mbedtls/debug.h>
+
+CryptoKey *CryptoKeyMbedTLS::create() {
+	return memnew(CryptoKeyMbedTLS);
+}
+
+Error CryptoKeyMbedTLS::load(String p_path) {
+	ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
+
+	PoolByteArray out;
+	FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+	ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
+
+	int flen = f->get_len();
+	out.resize(flen + 1);
+	{
+		PoolByteArray::Write w = out.write();
+		f->get_buffer(w.ptr(), flen);
+		w[flen] = 0; //end f string
+	}
+	memdelete(f);
+
+	int ret = mbedtls_pk_parse_key(&pkey, out.read().ptr(), out.size(), NULL, 0);
+	// We MUST zeroize the memory for safety!
+	mbedtls_platform_zeroize(out.write().ptr(), out.size());
+	ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing 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<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
+	Ref<CryptoKeyMbedTLS> out;
+	out.instance();
+	int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
+	ERR_FAIL_COND_V(ret != 0, NULL);
+	ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
+	ERR_FAIL_COND_V(ret != 0, NULL);
+	return out;
+}
+
+Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) {
+	Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS> >(p_key);
+	mbedtls_x509write_cert crt;
+	mbedtls_x509write_crt_init(&crt);
+
+	mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
+	mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
+	mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
+	mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
+	mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
+	mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
+
+	mbedtls_mpi serial;
+	mbedtls_mpi_init(&serial);
+	uint8_t rand_serial[20];
+	mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, 20);
+	ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), NULL);
+	mbedtls_x509write_crt_set_serial(&crt, &serial);
+
+	mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
+	mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
+	mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
+
+	unsigned char buf[4096];
+	memset(buf, 0, 4096);
+	Ref<X509CertificateMbedTLS> out;
+	out.instance();
+	mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
+
+	int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096);
+	if (err != 0) {
+		mbedtls_mpi_free(&serial);
+		mbedtls_x509write_crt_free(&crt);
+		ERR_PRINTS("Generated invalid certificate: " + itos(err));
+		return NULL;
+	}
+
+	mbedtls_mpi_free(&serial);
+	mbedtls_x509write_crt_free(&crt);
+	return out;
+}
+
+PoolByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
+	PoolByteArray out;
+	out.resize(p_bytes);
+	mbedtls_ctr_drbg_random(&ctr_drbg, out.write().ptr(), p_bytes);
+	return out;
+}

+ 124 - 0
modules/mbedtls/crypto_mbedtls.h

@@ -0,0 +1,124 @@
+/*************************************************************************/
+/*  crypto_mbedtls.h                                                     */
+/*************************************************************************/
+/*                       This file is part of:                           */
+/*                           GODOT ENGINE                                */
+/*                      https://godotengine.org                          */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
+/*                                                                       */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the       */
+/* "Software"), to deal in the Software without restriction, including   */
+/* without limitation the rights to use, copy, modify, merge, publish,   */
+/* distribute, sublicense, and/or sell copies of the Software, and to    */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions:                                             */
+/*                                                                       */
+/* The above copyright notice and this permission notice shall be        */
+/* included in all copies or substantial portions of the Software.       */
+/*                                                                       */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
+/*************************************************************************/
+
+#ifndef CRYPTO_MBEDTLS_H
+#define CRYPTO_MBEDTLS_H
+
+#include "core/crypto/crypto.h"
+#include "core/resource.h"
+
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/ssl.h>
+
+class CryptoMbedTLS;
+class SSLContextMbedTLS;
+class CryptoKeyMbedTLS : public CryptoKey {
+
+private:
+	mbedtls_pk_context pkey;
+	int locks;
+
+public:
+	static CryptoKey *create();
+	static void make_default() { CryptoKey::_create = create; }
+	static void finalize() { CryptoKey::_create = NULL; }
+
+	virtual Error load(String p_path);
+	virtual Error save(String p_path);
+
+	CryptoKeyMbedTLS() {
+		mbedtls_pk_init(&pkey);
+		locks = 0;
+	}
+	~CryptoKeyMbedTLS() {
+		mbedtls_pk_free(&pkey);
+	}
+
+	_FORCE_INLINE_ void lock() { locks++; }
+	_FORCE_INLINE_ void unlock() { locks--; }
+
+	friend class CryptoMbedTLS;
+	friend class SSLContextMbedTLS;
+};
+
+class X509CertificateMbedTLS : public X509Certificate {
+
+private:
+	mbedtls_x509_crt cert;
+	int locks;
+
+public:
+	static X509Certificate *create();
+	static void make_default() { X509Certificate::_create = create; }
+	static void finalize() { X509Certificate::_create = NULL; }
+
+	virtual Error load(String p_path);
+	virtual Error load_from_memory(const uint8_t *p_buffer, int p_len);
+	virtual Error save(String p_path);
+
+	X509CertificateMbedTLS() {
+		mbedtls_x509_crt_init(&cert);
+		locks = 0;
+	}
+	~X509CertificateMbedTLS() {
+		mbedtls_x509_crt_free(&cert);
+	}
+
+	_FORCE_INLINE_ void lock() { locks++; }
+	_FORCE_INLINE_ void unlock() { locks--; }
+
+	friend class CryptoMbedTLS;
+	friend class SSLContextMbedTLS;
+};
+
+class CryptoMbedTLS : public Crypto {
+
+private:
+	mbedtls_entropy_context entropy;
+	mbedtls_ctr_drbg_context ctr_drbg;
+	static X509CertificateMbedTLS *default_certs;
+
+public:
+	static Crypto *create();
+	static void initialize_crypto();
+	static void finalize_crypto();
+	static X509CertificateMbedTLS *get_default_certificates();
+	static void load_default_certificates(String p_path);
+
+	virtual PoolByteArray generate_random_bytes(int p_bytes);
+	virtual Ref<CryptoKey> generate_rsa(int p_bytes);
+	virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
+
+	CryptoMbedTLS();
+	~CryptoMbedTLS();
+};
+
+#endif // CRYPTO_MBEDTLS_H

+ 4 - 2
modules/mbedtls/register_types.cpp

@@ -30,15 +30,17 @@
 
 #include "register_types.h"
 
-#include "stream_peer_mbed_tls.h"
+#include "crypto_mbedtls.h"
+#include "stream_peer_mbedtls.h"
 
 void register_mbedtls_types() {
 
-	ClassDB::register_class<StreamPeerMbedTLS>();
+	CryptoMbedTLS::initialize_crypto();
 	StreamPeerMbedTLS::initialize_ssl();
 }
 
 void unregister_mbedtls_types() {
 
 	StreamPeerMbedTLS::finalize_ssl();
+	CryptoMbedTLS::finalize_crypto();
 }

+ 148 - 0
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<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert) {
+	ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER);
+	ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER);
+
+	Error err = _setup(MBEDTLS_SSL_IS_SERVER, p_transport, p_authmode);
+	ERR_FAIL_COND_V(err != OK, err);
+
+	// Locking key and certificate(s)
+	pkey = p_pkey;
+	certs = p_cert;
+	if (pkey.is_valid())
+		pkey->lock();
+	if (certs.is_valid())
+		certs->lock();
+
+	// Adding key and certificate
+	int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey));
+	if (ret != 0) {
+		clear();
+		ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid cert/key combination " + itos(ret));
+	}
+	// Adding CA chain if available.
+	if (certs->cert.next) {
+		mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, NULL);
+	}
+	mbedtls_ssl_setup(&ssl, &conf);
+	return OK;
+}
+
+Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) {
+	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<X509Certificate>();
+	if (pkey.is_valid())
+		pkey->unlock();
+	pkey = Ref<CryptoKeyMbedTLS>();
+	inited = false;
+}
+
+mbedtls_ssl_context *SSLContextMbedTLS::get_context() {
+	ERR_FAIL_COND_V(!inited, NULL);
+	return &ssl;
+}
+
+SSLContextMbedTLS::SSLContextMbedTLS() {
+	inited = false;
+}
+
+SSLContextMbedTLS::~SSLContextMbedTLS() {
+	clear();
+}

+ 74 - 0
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 <mbedtls/config.h>
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/debug.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/net.h>
+#include <mbedtls/ssl.h>
+
+class SSLContextMbedTLS : public Reference {
+
+protected:
+	bool inited;
+
+	static PoolByteArray _read_file(String p_path);
+
+public:
+	Ref<X509CertificateMbedTLS> certs;
+	mbedtls_entropy_context entropy;
+	mbedtls_ctr_drbg_context ctr_drbg;
+	mbedtls_ssl_context ssl;
+	mbedtls_ssl_config conf;
+
+	Ref<CryptoKeyMbedTLS> pkey;
+
+	Error _setup(int p_endpoint, int p_transport, int p_authmode);
+	Error init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert);
+	Error init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas);
+	void clear();
+
+	mbedtls_ssl_context *get_context();
+
+	SSLContextMbedTLS();
+	~SSLContextMbedTLS();
+};
+
+#endif // SSL_CONTEXT_MBED_TLS_H

+ 29 - 70
modules/mbedtls/stream_peer_mbed_tls.cpp → modules/mbedtls/stream_peer_mbedtls.cpp

@@ -28,19 +28,11 @@
 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
 /*************************************************************************/
 
-#include "stream_peer_mbed_tls.h"
+#include "stream_peer_mbedtls.h"
 
 #include "core/io/stream_peer_tcp.h"
 #include "core/os/file_access.h"
 
-static void my_debug(void *ctx, int level,
-		const char *file, int line,
-		const char *str) {
-
-	printf("%s:%04d: %s", file, line, str);
-	fflush(stdout);
-}
-
 void _print_error(int ret) {
 	printf("mbedtls error: returned -0x%x\n\n", -ret);
 	fflush(stdout);
@@ -86,18 +78,14 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
 
 void StreamPeerMbedTLS::_cleanup() {
 
-	mbedtls_ssl_free(&ssl);
-	mbedtls_ssl_config_free(&conf);
-	mbedtls_ctr_drbg_free(&ctr_drbg);
-	mbedtls_entropy_free(&entropy);
-
+	ssl_ctx->clear();
 	base = Ref<StreamPeer>();
 	status = STATUS_DISCONNECTED;
 }
 
 Error StreamPeerMbedTLS::_do_handshake() {
 	int ret = 0;
-	while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
+	while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) {
 		if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
 			// An error occurred.
 			ERR_PRINTS("TLS handshake error: " + itos(ret));
@@ -118,39 +106,17 @@ Error StreamPeerMbedTLS::_do_handshake() {
 	return OK;
 }
 
-Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
-
-	ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
+Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) {
 
 	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);
+	Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs);
+	ERR_FAIL_COND_V(err != OK, err);
 
-	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);
+	mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data());
+	mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL);
 
 	status = STATUS_HANDSHAKING;
 
@@ -162,11 +128,24 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
 	return OK;
 }
 
-Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base) {
+Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) {
+
+	Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert);
+	ERR_FAIL_COND_V(err != OK, err);
+
+	base = p_base;
+
+	mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL);
 
+	status = STATUS_HANDSHAKING;
+
+	if ((err = _do_handshake()) != OK) {
+		return FAILED;
+	}
+
+	status = STATUS_CONNECTED;
 	return OK;
 }
-
 Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
 
 	ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
@@ -197,7 +176,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in
 	if (p_bytes == 0)
 		return OK;
 
-	int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes);
+	int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes);
 	if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
 		// Non blocking IO
 		ret = 0;
@@ -243,7 +222,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r
 
 	r_received = 0;
 
-	int ret = mbedtls_ssl_read(&ssl, p_buffer, p_bytes);
+	int ret = mbedtls_ssl_read(ssl_ctx->get_context(), p_buffer, p_bytes);
 	if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
 		ret = 0; // non blocking io
 	} else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
@@ -273,7 +252,7 @@ void StreamPeerMbedTLS::poll() {
 	// We could pass NULL as second parameter, but some behaviour sanitizers doesn't seem to like that.
 	// Passing a 1 byte buffer to workaround it.
 	uint8_t byte;
-	int ret = mbedtls_ssl_read(&ssl, &byte, 0);
+	int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0);
 
 	if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
 		// Nothing to read/write (non blocking IO)
@@ -298,10 +277,11 @@ int StreamPeerMbedTLS::get_available_bytes() const {
 
 	ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0);
 
-	return mbedtls_ssl_get_bytes_avail(&ssl);
+	return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl));
 }
 StreamPeerMbedTLS::StreamPeerMbedTLS() {
 
+	ssl_ctx.instance();
 	status = STATUS_DISCONNECTED;
 }
 
@@ -317,7 +297,7 @@ void StreamPeerMbedTLS::disconnect_from_stream() {
 	Ref<StreamPeerTCP> tcp = base;
 	if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
 		// We are still connected on the socket, try to send close notify.
-		mbedtls_ssl_close_notify(&ssl);
+		mbedtls_ssl_close_notify(ssl_ctx->get_context());
 	}
 
 	_cleanup();
@@ -333,28 +313,9 @@ StreamPeerSSL *StreamPeerMbedTLS::_create_func() {
 	return memnew(StreamPeerMbedTLS);
 }
 
-mbedtls_x509_crt StreamPeerMbedTLS::cacert;
-
-void StreamPeerMbedTLS::_load_certs(const PoolByteArray &p_array) {
-	int arr_len = p_array.size();
-	PoolByteArray::Read r = p_array.read();
-	int err = mbedtls_x509_crt_parse(&cacert, &r[0], arr_len);
-	if (err != 0) {
-		WARN_PRINTS("Error parsing some certificates: " + itos(err));
-	}
-}
-
 void StreamPeerMbedTLS::initialize_ssl() {
 
 	_create = _create_func;
-	load_certs_func = _load_certs;
-
-	mbedtls_x509_crt_init(&cacert);
-
-#ifdef DEBUG_ENABLED
-	mbedtls_debug_set_threshold(1);
-#endif
-
 	available = true;
 }
 
@@ -362,6 +323,4 @@ void StreamPeerMbedTLS::finalize_ssl() {
 
 	available = false;
 	_create = NULL;
-	load_certs_func = NULL;
-	mbedtls_x509_crt_free(&cacert);
 }

+ 4 - 9
modules/mbedtls/stream_peer_mbed_tls.h → modules/mbedtls/stream_peer_mbedtls.h

@@ -32,6 +32,7 @@
 #define STREAM_PEER_OPEN_SSL_H
 
 #include "core/io/stream_peer_ssl.h"
+#include "ssl_context_mbedtls.h"
 
 #include <mbedtls/config.h>
 #include <mbedtls/ctr_drbg.h>
@@ -50,19 +51,13 @@ private:
 	Ref<StreamPeer> base;
 
 	static StreamPeerSSL *_create_func();
-	static void _load_certs(const PoolByteArray &p_array);
 
 	static int bio_recv(void *ctx, unsigned char *buf, size_t len);
 	static int bio_send(void *ctx, const unsigned char *buf, size_t len);
 	void _cleanup();
 
 protected:
-	static mbedtls_x509_crt cacert;
-
-	mbedtls_entropy_context entropy;
-	mbedtls_ctr_drbg_context ctr_drbg;
-	mbedtls_ssl_context ssl;
-	mbedtls_ssl_config conf;
+	Ref<SSLContextMbedTLS> ssl_ctx;
 
 	static void _bind_methods();
 
@@ -70,8 +65,8 @@ protected:
 
 public:
 	virtual void poll();
-	virtual Error accept_stream(Ref<StreamPeer> p_base);
-	virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String());
+	virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>());
+	virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>());
 	virtual Status get_status() const;
 
 	virtual void disconnect_from_stream();

+ 1 - 1
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"
 

+ 1 - 1
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"