crypto.cpp 11 KB

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