crypto.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**************************************************************************/
  2. /* crypto.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "crypto.h"
  31. #include "core/config/engine.h"
  32. #include "core/io/certs_compressed.gen.h"
  33. #include "core/io/compression.h"
  34. /// Resources
  35. CryptoKey *(*CryptoKey::_create)(bool p_notify_postinitialize) = nullptr;
  36. CryptoKey *CryptoKey::create(bool p_notify_postinitialize) {
  37. if (_create) {
  38. return _create(p_notify_postinitialize);
  39. }
  40. return nullptr;
  41. }
  42. void CryptoKey::_bind_methods() {
  43. ClassDB::bind_method(D_METHOD("save", "path", "public_only"), &CryptoKey::save, DEFVAL(false));
  44. ClassDB::bind_method(D_METHOD("load", "path", "public_only"), &CryptoKey::load, DEFVAL(false));
  45. ClassDB::bind_method(D_METHOD("is_public_only"), &CryptoKey::is_public_only);
  46. ClassDB::bind_method(D_METHOD("save_to_string", "public_only"), &CryptoKey::save_to_string, DEFVAL(false));
  47. ClassDB::bind_method(D_METHOD("load_from_string", "string_key", "public_only"), &CryptoKey::load_from_string, DEFVAL(false));
  48. }
  49. X509Certificate *(*X509Certificate::_create)(bool p_notify_postinitialize) = nullptr;
  50. X509Certificate *X509Certificate::create(bool p_notify_postinitialize) {
  51. if (_create) {
  52. return _create(p_notify_postinitialize);
  53. }
  54. return nullptr;
  55. }
  56. void X509Certificate::_bind_methods() {
  57. ClassDB::bind_method(D_METHOD("save", "path"), &X509Certificate::save);
  58. ClassDB::bind_method(D_METHOD("load", "path"), &X509Certificate::load);
  59. ClassDB::bind_method(D_METHOD("save_to_string"), &X509Certificate::save_to_string);
  60. ClassDB::bind_method(D_METHOD("load_from_string", "string"), &X509Certificate::load_from_string);
  61. }
  62. /// TLSOptions
  63. Ref<TLSOptions> TLSOptions::client(Ref<X509Certificate> p_trusted_chain, const String &p_common_name_override) {
  64. Ref<TLSOptions> opts;
  65. opts.instantiate();
  66. opts->mode = MODE_CLIENT;
  67. opts->trusted_ca_chain = p_trusted_chain;
  68. opts->common_name = p_common_name_override;
  69. return opts;
  70. }
  71. Ref<TLSOptions> TLSOptions::client_unsafe(Ref<X509Certificate> p_trusted_chain) {
  72. Ref<TLSOptions> opts;
  73. opts.instantiate();
  74. opts->mode = MODE_CLIENT_UNSAFE;
  75. opts->trusted_ca_chain = p_trusted_chain;
  76. return opts;
  77. }
  78. Ref<TLSOptions> TLSOptions::server(Ref<CryptoKey> p_own_key, Ref<X509Certificate> p_own_certificate) {
  79. Ref<TLSOptions> opts;
  80. opts.instantiate();
  81. opts->mode = MODE_SERVER;
  82. opts->own_certificate = p_own_certificate;
  83. opts->private_key = p_own_key;
  84. return opts;
  85. }
  86. void TLSOptions::_bind_methods() {
  87. ClassDB::bind_static_method("TLSOptions", D_METHOD("client", "trusted_chain", "common_name_override"), &TLSOptions::client, DEFVAL(Ref<X509Certificate>()), DEFVAL(String()));
  88. ClassDB::bind_static_method("TLSOptions", D_METHOD("client_unsafe", "trusted_chain"), &TLSOptions::client_unsafe, DEFVAL(Ref<X509Certificate>()));
  89. ClassDB::bind_static_method("TLSOptions", D_METHOD("server", "key", "certificate"), &TLSOptions::server);
  90. ClassDB::bind_method(D_METHOD("is_server"), &TLSOptions::is_server);
  91. ClassDB::bind_method(D_METHOD("is_unsafe_client"), &TLSOptions::is_unsafe_client);
  92. ClassDB::bind_method(D_METHOD("get_common_name_override"), &TLSOptions::get_common_name_override);
  93. ClassDB::bind_method(D_METHOD("get_trusted_ca_chain"), &TLSOptions::get_trusted_ca_chain);
  94. ClassDB::bind_method(D_METHOD("get_private_key"), &TLSOptions::get_private_key);
  95. ClassDB::bind_method(D_METHOD("get_own_certificate"), &TLSOptions::get_own_certificate);
  96. }
  97. /// HMACContext
  98. void HMACContext::_bind_methods() {
  99. ClassDB::bind_method(D_METHOD("start", "hash_type", "key"), &HMACContext::start);
  100. ClassDB::bind_method(D_METHOD("update", "data"), &HMACContext::update);
  101. ClassDB::bind_method(D_METHOD("finish"), &HMACContext::finish);
  102. }
  103. HMACContext *(*HMACContext::_create)(bool p_notify_postinitialize) = nullptr;
  104. HMACContext *HMACContext::create(bool p_notify_postinitialize) {
  105. if (_create) {
  106. return _create(p_notify_postinitialize);
  107. }
  108. ERR_FAIL_V_MSG(nullptr, "HMACContext is not available when the mbedtls module is disabled.");
  109. }
  110. /// Crypto
  111. void (*Crypto::_load_default_certificates)(const String &p_path) = nullptr;
  112. Crypto *(*Crypto::_create)(bool p_notify_postinitialize) = nullptr;
  113. Crypto *Crypto::create(bool p_notify_postinitialize) {
  114. if (_create) {
  115. return _create(p_notify_postinitialize);
  116. }
  117. ERR_FAIL_V_MSG(nullptr, "Crypto is not available when the mbedtls module is disabled.");
  118. }
  119. void Crypto::load_default_certificates(const String &p_path) {
  120. if (_load_default_certificates) {
  121. _load_default_certificates(p_path);
  122. }
  123. }
  124. PackedByteArray Crypto::hmac_digest(HashingContext::HashType p_hash_type, const PackedByteArray &p_key, const PackedByteArray &p_msg) {
  125. Ref<HMACContext> ctx = Ref<HMACContext>(HMACContext::create());
  126. ERR_FAIL_COND_V_MSG(ctx.is_null(), PackedByteArray(), "HMAC is not available without mbedtls module.");
  127. Error err = ctx->start(p_hash_type, p_key);
  128. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  129. err = ctx->update(p_msg);
  130. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  131. return ctx->finish();
  132. }
  133. // Compares two HMACS for equality without leaking timing information in order to prevent timing attacks.
  134. // @see: https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy
  135. bool Crypto::constant_time_compare(const PackedByteArray &p_trusted, const PackedByteArray &p_received) {
  136. const uint8_t *t = p_trusted.ptr();
  137. const uint8_t *r = p_received.ptr();
  138. int tlen = p_trusted.size();
  139. int rlen = p_received.size();
  140. // If the lengths are different then nothing else matters.
  141. if (tlen != rlen) {
  142. return false;
  143. }
  144. uint8_t v = 0;
  145. for (int i = 0; i < tlen; i++) {
  146. v |= t[i] ^ r[i];
  147. }
  148. return v == 0;
  149. }
  150. void Crypto::_bind_methods() {
  151. ClassDB::bind_method(D_METHOD("generate_random_bytes", "size"), &Crypto::generate_random_bytes);
  152. ClassDB::bind_method(D_METHOD("generate_rsa", "size"), &Crypto::generate_rsa);
  153. 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"));
  154. ClassDB::bind_method(D_METHOD("sign", "hash_type", "hash", "key"), &Crypto::sign);
  155. ClassDB::bind_method(D_METHOD("verify", "hash_type", "hash", "signature", "key"), &Crypto::verify);
  156. ClassDB::bind_method(D_METHOD("encrypt", "key", "plaintext"), &Crypto::encrypt);
  157. ClassDB::bind_method(D_METHOD("decrypt", "key", "ciphertext"), &Crypto::decrypt);
  158. ClassDB::bind_method(D_METHOD("hmac_digest", "hash_type", "key", "msg"), &Crypto::hmac_digest);
  159. ClassDB::bind_method(D_METHOD("constant_time_compare", "trusted", "received"), &Crypto::constant_time_compare);
  160. }
  161. /// Resource loader/saver
  162. Ref<Resource> ResourceFormatLoaderCrypto::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  163. String el = p_path.get_extension().to_lower();
  164. if (el == "crt") {
  165. X509Certificate *cert = X509Certificate::create();
  166. if (cert) {
  167. cert->load(p_path);
  168. }
  169. return cert;
  170. } else if (el == "key") {
  171. CryptoKey *key = CryptoKey::create();
  172. if (key) {
  173. key->load(p_path, false);
  174. }
  175. return key;
  176. } else if (el == "pub") {
  177. CryptoKey *key = CryptoKey::create();
  178. if (key) {
  179. key->load(p_path, true);
  180. }
  181. return key;
  182. }
  183. return nullptr;
  184. }
  185. void ResourceFormatLoaderCrypto::get_recognized_extensions(List<String> *p_extensions) const {
  186. p_extensions->push_back("crt");
  187. p_extensions->push_back("key");
  188. p_extensions->push_back("pub");
  189. }
  190. bool ResourceFormatLoaderCrypto::handles_type(const String &p_type) const {
  191. return p_type == "X509Certificate" || p_type == "CryptoKey";
  192. }
  193. String ResourceFormatLoaderCrypto::get_resource_type(const String &p_path) const {
  194. String el = p_path.get_extension().to_lower();
  195. if (el == "crt") {
  196. return "X509Certificate";
  197. } else if (el == "key" || el == "pub") {
  198. return "CryptoKey";
  199. }
  200. return "";
  201. }
  202. Error ResourceFormatSaverCrypto::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  203. Error err;
  204. Ref<X509Certificate> cert = p_resource;
  205. Ref<CryptoKey> key = p_resource;
  206. if (cert.is_valid()) {
  207. err = cert->save(p_path);
  208. } else if (key.is_valid()) {
  209. String el = p_path.get_extension().to_lower();
  210. err = key->save(p_path, el == "pub");
  211. } else {
  212. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  213. }
  214. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Cannot save Crypto resource to file '%s'.", p_path));
  215. return OK;
  216. }
  217. void ResourceFormatSaverCrypto::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  218. const X509Certificate *cert = Object::cast_to<X509Certificate>(*p_resource);
  219. const CryptoKey *key = Object::cast_to<CryptoKey>(*p_resource);
  220. if (cert) {
  221. p_extensions->push_back("crt");
  222. }
  223. if (key) {
  224. if (!key->is_public_only()) {
  225. p_extensions->push_back("key");
  226. }
  227. p_extensions->push_back("pub");
  228. }
  229. }
  230. bool ResourceFormatSaverCrypto::recognize(const Ref<Resource> &p_resource) const {
  231. return Object::cast_to<X509Certificate>(*p_resource) || Object::cast_to<CryptoKey>(*p_resource);
  232. }