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