crypto.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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)() = nullptr;
  36. CryptoKey *CryptoKey::create() {
  37. if (_create) {
  38. return _create();
  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)() = nullptr;
  50. X509Certificate *X509Certificate::create() {
  51. if (_create) {
  52. return _create();
  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->trusted_ca_chain = p_trusted_chain;
  67. opts->common_name = p_common_name_override;
  68. opts->verify_mode = TLS_VERIFY_FULL;
  69. return opts;
  70. }
  71. Ref<TLSOptions> TLSOptions::client_unsafe(Ref<X509Certificate> p_trusted_chain) {
  72. Ref<TLSOptions> opts;
  73. opts.instantiate();
  74. opts->trusted_ca_chain = p_trusted_chain;
  75. if (p_trusted_chain.is_null()) {
  76. opts->verify_mode = TLS_VERIFY_NONE;
  77. } else {
  78. opts->verify_mode = TLS_VERIFY_CERT;
  79. }
  80. return opts;
  81. }
  82. Ref<TLSOptions> TLSOptions::server(Ref<CryptoKey> p_own_key, Ref<X509Certificate> p_own_certificate) {
  83. Ref<TLSOptions> opts;
  84. opts.instantiate();
  85. opts->server_mode = true;
  86. opts->own_certificate = p_own_certificate;
  87. opts->private_key = p_own_key;
  88. opts->verify_mode = TLS_VERIFY_NONE;
  89. return opts;
  90. }
  91. void TLSOptions::_bind_methods() {
  92. ClassDB::bind_static_method("TLSOptions", D_METHOD("client", "trusted_chain", "common_name_override"), &TLSOptions::client, DEFVAL(Ref<X509Certificate>()), DEFVAL(String()));
  93. ClassDB::bind_static_method("TLSOptions", D_METHOD("client_unsafe", "trusted_chain"), &TLSOptions::client_unsafe, DEFVAL(Ref<X509Certificate>()));
  94. ClassDB::bind_static_method("TLSOptions", D_METHOD("server", "key", "certificate"), &TLSOptions::server);
  95. }
  96. /// HMACContext
  97. void HMACContext::_bind_methods() {
  98. ClassDB::bind_method(D_METHOD("start", "hash_type", "key"), &HMACContext::start);
  99. ClassDB::bind_method(D_METHOD("update", "data"), &HMACContext::update);
  100. ClassDB::bind_method(D_METHOD("finish"), &HMACContext::finish);
  101. }
  102. HMACContext *(*HMACContext::_create)() = nullptr;
  103. HMACContext *HMACContext::create() {
  104. if (_create) {
  105. return _create();
  106. }
  107. ERR_FAIL_V_MSG(nullptr, "HMACContext is not available when the mbedtls module is disabled.");
  108. }
  109. /// Crypto
  110. void (*Crypto::_load_default_certificates)(String p_path) = nullptr;
  111. Crypto *(*Crypto::_create)() = nullptr;
  112. Crypto *Crypto::create() {
  113. if (_create) {
  114. return _create();
  115. }
  116. ERR_FAIL_V_MSG(nullptr, "Crypto is not available when the mbedtls module is disabled.");
  117. }
  118. void Crypto::load_default_certificates(String p_path) {
  119. if (_load_default_certificates) {
  120. _load_default_certificates(p_path);
  121. }
  122. }
  123. PackedByteArray Crypto::hmac_digest(HashingContext::HashType p_hash_type, PackedByteArray p_key, PackedByteArray p_msg) {
  124. Ref<HMACContext> ctx = Ref<HMACContext>(HMACContext::create());
  125. ERR_FAIL_COND_V_MSG(ctx.is_null(), PackedByteArray(), "HMAC is not available without mbedtls module.");
  126. Error err = ctx->start(p_hash_type, p_key);
  127. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  128. err = ctx->update(p_msg);
  129. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  130. return ctx->finish();
  131. }
  132. // Compares two HMACS for equality without leaking timing information in order to prevent timing attacks.
  133. // @see: https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy
  134. bool Crypto::constant_time_compare(PackedByteArray p_trusted, PackedByteArray p_received) {
  135. const uint8_t *t = p_trusted.ptr();
  136. const uint8_t *r = p_received.ptr();
  137. int tlen = p_trusted.size();
  138. int rlen = p_received.size();
  139. // If the lengths are different then nothing else matters.
  140. if (tlen != rlen) {
  141. return false;
  142. }
  143. uint8_t v = 0;
  144. for (int i = 0; i < tlen; i++) {
  145. v |= t[i] ^ r[i];
  146. }
  147. return v == 0;
  148. }
  149. void Crypto::_bind_methods() {
  150. ClassDB::bind_method(D_METHOD("generate_random_bytes", "size"), &Crypto::generate_random_bytes);
  151. ClassDB::bind_method(D_METHOD("generate_rsa", "size"), &Crypto::generate_rsa);
  152. 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"));
  153. ClassDB::bind_method(D_METHOD("sign", "hash_type", "hash", "key"), &Crypto::sign);
  154. ClassDB::bind_method(D_METHOD("verify", "hash_type", "hash", "signature", "key"), &Crypto::verify);
  155. ClassDB::bind_method(D_METHOD("encrypt", "key", "plaintext"), &Crypto::encrypt);
  156. ClassDB::bind_method(D_METHOD("decrypt", "key", "ciphertext"), &Crypto::decrypt);
  157. ClassDB::bind_method(D_METHOD("hmac_digest", "hash_type", "key", "msg"), &Crypto::hmac_digest);
  158. ClassDB::bind_method(D_METHOD("constant_time_compare", "trusted", "received"), &Crypto::constant_time_compare);
  159. }
  160. /// Resource loader/saver
  161. 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) {
  162. String el = p_path.get_extension().to_lower();
  163. if (el == "crt") {
  164. X509Certificate *cert = X509Certificate::create();
  165. if (cert) {
  166. cert->load(p_path);
  167. }
  168. return cert;
  169. } else if (el == "key") {
  170. CryptoKey *key = CryptoKey::create();
  171. if (key) {
  172. key->load(p_path, false);
  173. }
  174. return key;
  175. } else if (el == "pub") {
  176. CryptoKey *key = CryptoKey::create();
  177. if (key) {
  178. key->load(p_path, true);
  179. }
  180. return key;
  181. }
  182. return nullptr;
  183. }
  184. void ResourceFormatLoaderCrypto::get_recognized_extensions(List<String> *p_extensions) const {
  185. p_extensions->push_back("crt");
  186. p_extensions->push_back("key");
  187. p_extensions->push_back("pub");
  188. }
  189. bool ResourceFormatLoaderCrypto::handles_type(const String &p_type) const {
  190. return p_type == "X509Certificate" || p_type == "CryptoKey";
  191. }
  192. String ResourceFormatLoaderCrypto::get_resource_type(const String &p_path) const {
  193. String el = p_path.get_extension().to_lower();
  194. if (el == "crt") {
  195. return "X509Certificate";
  196. } else if (el == "key" || el == "pub") {
  197. return "CryptoKey";
  198. }
  199. return "";
  200. }
  201. Error ResourceFormatSaverCrypto::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  202. Error err;
  203. Ref<X509Certificate> cert = p_resource;
  204. Ref<CryptoKey> key = p_resource;
  205. if (cert.is_valid()) {
  206. err = cert->save(p_path);
  207. } else if (key.is_valid()) {
  208. String el = p_path.get_extension().to_lower();
  209. err = key->save(p_path, el == "pub");
  210. } else {
  211. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  212. }
  213. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save Crypto resource to file '" + p_path + "'.");
  214. return OK;
  215. }
  216. void ResourceFormatSaverCrypto::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  217. const X509Certificate *cert = Object::cast_to<X509Certificate>(*p_resource);
  218. const CryptoKey *key = Object::cast_to<CryptoKey>(*p_resource);
  219. if (cert) {
  220. p_extensions->push_back("crt");
  221. }
  222. if (key) {
  223. if (!key->is_public_only()) {
  224. p_extensions->push_back("key");
  225. }
  226. p_extensions->push_back("pub");
  227. }
  228. }
  229. bool ResourceFormatSaverCrypto::recognize(const Ref<Resource> &p_resource) const {
  230. return Object::cast_to<X509Certificate>(*p_resource) || Object::cast_to<CryptoKey>(*p_resource);
  231. }