crypto.cpp 8.7 KB

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