Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
crypto.cpp
Go to the documentation of this file.
1
5// lib includes
6#include <openssl/pem.h>
7#include <openssl/rsa.h>
8
9// local includes
10#include "crypto.h"
11
12namespace crypto {
13 using asn1_string_t = util::safe_ptr<ASN1_STRING, ASN1_STRING_free>;
14
15 cert_chain_t::cert_chain_t():
16 _certs {}, _cert_ctx { X509_STORE_CTX_new() } {
17 }
18 void cert_chain_t::add(p_named_cert_t& named_cert_p) {
19 x509_store_t x509_store { X509_STORE_new() };
20
21 X509_STORE_add_cert(x509_store.get(), x509(named_cert_p->cert).get());
22 _certs.emplace_back(std::make_pair(named_cert_p, std::move(x509_store)));
23 }
24
25 void cert_chain_t::clear() {
26 _certs.clear();
27 }
28
29 static int openssl_verify_cb(int ok, X509_STORE_CTX *ctx) {
30 int err_code = X509_STORE_CTX_get_error(ctx);
31
32 switch (err_code) {
33 // Expired or not-yet-valid certificates are fine. Sometimes Moonlight is running on embedded devices
34 // that don't have accurate clocks (or haven't yet synchronized by the time Moonlight first runs).
35 // This behavior also matches what GeForce Experience does.
36 case X509_V_ERR_CERT_NOT_YET_VALID:
37 case X509_V_ERR_CERT_HAS_EXPIRED:
38 return 1;
39
40 default:
41 return ok;
42 }
43 }
44
55 const char * cert_chain_t::verify(x509_t::element_type *cert, p_named_cert_t& named_cert_out) {
56 int err_code = 0;
57 for (auto &[named_cert_p, x509_store] : _certs) {
58 auto fg = util::fail_guard([this]() {
59 X509_STORE_CTX_cleanup(_cert_ctx.get());
60 });
61
62 X509_STORE_CTX_init(_cert_ctx.get(), x509_store.get(), cert, nullptr);
63 X509_STORE_CTX_set_verify_cb(_cert_ctx.get(), openssl_verify_cb);
64
65 // We don't care to validate the entire chain for the purposes of client auth.
66 // Some versions of clients forked from Moonlight Embedded produce client certs
67 // that OpenSSL doesn't detect as self-signed due to some X509v3 extensions.
68 X509_STORE_CTX_set_flags(_cert_ctx.get(), X509_V_FLAG_PARTIAL_CHAIN);
69
70 auto err = X509_verify_cert(_cert_ctx.get());
71
72 if (err == 1) {
73 named_cert_out = named_cert_p;
74 return nullptr;
75 }
76
77 err_code = X509_STORE_CTX_get_error(_cert_ctx.get());
78
79 if (err_code != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && err_code != X509_V_ERR_INVALID_CA) {
80 return X509_verify_cert_error_string(err_code);
81 }
82 }
83
84 return X509_verify_cert_error_string(err_code);
85 }
86
87 namespace cipher {
88
89 static int init_decrypt_gcm(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) {
90 ctx.reset(EVP_CIPHER_CTX_new());
91
92 if (!ctx) {
93 return -1;
94 }
95
96 if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_128_gcm(), nullptr, nullptr, nullptr) != 1) {
97 return -1;
98 }
99
100 if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, iv->size(), nullptr) != 1) {
101 return -1;
102 }
103
104 if (EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, key->data(), iv->data()) != 1) {
105 return -1;
106 }
107 EVP_CIPHER_CTX_set_padding(ctx.get(), padding);
108
109 return 0;
110 }
111
112 static int init_encrypt_gcm(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) {
113 ctx.reset(EVP_CIPHER_CTX_new());
114
115 // Gen 7 servers use 128-bit AES ECB
116 if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_gcm(), nullptr, nullptr, nullptr) != 1) {
117 return -1;
118 }
119
120 if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, iv->size(), nullptr) != 1) {
121 return -1;
122 }
123
124 if (EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key->data(), iv->data()) != 1) {
125 return -1;
126 }
127 EVP_CIPHER_CTX_set_padding(ctx.get(), padding);
128
129 return 0;
130 }
131
132 static int init_encrypt_cbc(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) {
133 ctx.reset(EVP_CIPHER_CTX_new());
134
135 // Gen 7 servers use 128-bit AES ECB
136 if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_cbc(), nullptr, key->data(), iv->data()) != 1) {
137 return -1;
138 }
139
140 EVP_CIPHER_CTX_set_padding(ctx.get(), padding);
141
142 return 0;
143 }
144
145 int gcm_t::decrypt(const std::string_view &tagged_cipher, std::vector<std::uint8_t> &plaintext, aes_t *iv) {
146 if (!decrypt_ctx && init_decrypt_gcm(decrypt_ctx, &key, iv, padding)) {
147 return -1;
148 }
149
150 // Calling with cipher == nullptr results in a parameter change
151 // without requiring a reallocation of the internal cipher ctx.
152 if (EVP_DecryptInit_ex(decrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) {
153 return false;
154 }
155
156 auto cipher = tagged_cipher.substr(tag_size);
157 auto tag = tagged_cipher.substr(0, tag_size);
158
159 plaintext.resize(round_to_pkcs7_padded(cipher.size()));
160
161 int update_outlen, final_outlen;
162
163 if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), cipher.size()) != 1) {
164 return -1;
165 }
166
167 if (EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, tag.size(), const_cast<char *>(tag.data())) != 1) {
168 return -1;
169 }
170
171 if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) {
172 return -1;
173 }
174
175 plaintext.resize(update_outlen + final_outlen);
176 return 0;
177 }
178
184 int gcm_t::encrypt(const std::string_view &plaintext, std::uint8_t *tag, std::uint8_t *ciphertext, aes_t *iv) {
185 if (!encrypt_ctx && init_encrypt_gcm(encrypt_ctx, &key, iv, padding)) {
186 return -1;
187 }
188
189 // Calling with cipher == nullptr results in a parameter change
190 // without requiring a reallocation of the internal cipher ctx.
191 if (EVP_EncryptInit_ex(encrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) {
192 return -1;
193 }
194
195 int update_outlen, final_outlen;
196
197 // Encrypt into the caller's buffer
198 if (EVP_EncryptUpdate(encrypt_ctx.get(), ciphertext, &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) {
199 return -1;
200 }
201
202 // GCM encryption won't ever fill ciphertext here but we have to call it anyway
203 if (EVP_EncryptFinal_ex(encrypt_ctx.get(), ciphertext + update_outlen, &final_outlen) != 1) {
204 return -1;
205 }
206
207 if (EVP_CIPHER_CTX_ctrl(encrypt_ctx.get(), EVP_CTRL_GCM_GET_TAG, tag_size, tag) != 1) {
208 return -1;
209 }
210
211 return update_outlen + final_outlen;
212 }
213
214 int gcm_t::encrypt(const std::string_view &plaintext, std::uint8_t *tagged_cipher, aes_t *iv) {
215 // This overload handles the common case of [GCM tag][cipher text] buffer layout
216 return encrypt(plaintext, tagged_cipher, tagged_cipher + tag_size, iv);
217 }
218
219 int ecb_t::decrypt(const std::string_view &cipher, std::vector<std::uint8_t> &plaintext) {
220 auto fg = util::fail_guard([this]() {
221 EVP_CIPHER_CTX_reset(decrypt_ctx.get());
222 });
223
224 // Gen 7 servers use 128-bit AES ECB
225 if (EVP_DecryptInit_ex(decrypt_ctx.get(), EVP_aes_128_ecb(), nullptr, key.data(), nullptr) != 1) {
226 return -1;
227 }
228
229 EVP_CIPHER_CTX_set_padding(decrypt_ctx.get(), padding);
230 plaintext.resize(round_to_pkcs7_padded(cipher.size()));
231
232 int update_outlen, final_outlen;
233
234 if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), cipher.size()) != 1) {
235 return -1;
236 }
237
238 if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) {
239 return -1;
240 }
241
242 plaintext.resize(update_outlen + final_outlen);
243 return 0;
244 }
245
246 int ecb_t::encrypt(const std::string_view &plaintext, std::vector<std::uint8_t> &cipher) {
247 auto fg = util::fail_guard([this]() {
248 EVP_CIPHER_CTX_reset(encrypt_ctx.get());
249 });
250
251 // Gen 7 servers use 128-bit AES ECB
252 if (EVP_EncryptInit_ex(encrypt_ctx.get(), EVP_aes_128_ecb(), nullptr, key.data(), nullptr) != 1) {
253 return -1;
254 }
255
256 EVP_CIPHER_CTX_set_padding(encrypt_ctx.get(), padding);
257 cipher.resize(round_to_pkcs7_padded(plaintext.size()));
258
259 int update_outlen, final_outlen;
260
261 // Encrypt into the caller's buffer
262 if (EVP_EncryptUpdate(encrypt_ctx.get(), cipher.data(), &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) {
263 return -1;
264 }
265
266 if (EVP_EncryptFinal_ex(encrypt_ctx.get(), cipher.data() + update_outlen, &final_outlen) != 1) {
267 return -1;
268 }
269
270 cipher.resize(update_outlen + final_outlen);
271 return 0;
272 }
273
279 int cbc_t::encrypt(const std::string_view &plaintext, std::uint8_t *cipher, aes_t *iv) {
280 if (!encrypt_ctx && init_encrypt_cbc(encrypt_ctx, &key, iv, padding)) {
281 return -1;
282 }
283
284 // Calling with cipher == nullptr results in a parameter change
285 // without requiring a reallocation of the internal cipher ctx.
286 if (EVP_EncryptInit_ex(encrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) {
287 return false;
288 }
289
290 int update_outlen, final_outlen;
291
292 // Encrypt into the caller's buffer
293 if (EVP_EncryptUpdate(encrypt_ctx.get(), cipher, &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) {
294 return -1;
295 }
296
297 if (EVP_EncryptFinal_ex(encrypt_ctx.get(), cipher + update_outlen, &final_outlen) != 1) {
298 return -1;
299 }
300
301 return update_outlen + final_outlen;
302 }
303
304 int cbc_t::decrypt(const std::string_view &cipher, std::vector<std::uint8_t> &plaintext, aes_t *iv) {
305 if (!decrypt_ctx) {
306 decrypt_ctx.reset(EVP_CIPHER_CTX_new());
307 if (EVP_DecryptInit_ex(decrypt_ctx.get(), EVP_aes_128_cbc(), nullptr, key.data(), iv->data()) != 1) {
308 decrypt_ctx.reset();
309 return -1;
310 }
311 EVP_CIPHER_CTX_set_padding(decrypt_ctx.get(), padding);
312 }
313
314 if (EVP_DecryptInit_ex(decrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) {
315 return -1;
316 }
317
318 // Padding only shrinks the plaintext, and a final block is up to one block.
319 plaintext.resize(cipher.size() + 16);
320
321 int update_outlen, final_outlen;
322 if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), cipher.size()) != 1) {
323 return -1;
324 }
325
326 if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) {
327 return -1;
328 }
329
330 plaintext.resize(update_outlen + final_outlen);
331 return 0;
332 }
333
334 ecb_t::ecb_t(const aes_t &key, bool padding):
335 cipher_t {EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_new(), key, padding} {
336 }
337
338 cbc_t::cbc_t(const aes_t &key, bool padding):
339 cipher_t {nullptr, nullptr, key, padding} {
340 }
341
342 gcm_t::gcm_t(const crypto::aes_t &key, bool padding):
343 cipher_t {nullptr, nullptr, key, padding} {
344 }
345
346 } // namespace cipher
347
348 aes_t gen_aes_key(const std::array<uint8_t, 16> &salt, const std::string_view &pin) {
349 aes_t key(16);
350
351 std::string salt_pin;
352 salt_pin.reserve(salt.size() + pin.size());
353
354 salt_pin.insert(std::end(salt_pin), std::begin(salt), std::end(salt));
355 salt_pin.insert(std::end(salt_pin), std::begin(pin), std::end(pin));
356
357 auto hsh = hash(salt_pin);
358
359 std::copy(std::begin(hsh), std::begin(hsh) + key.size(), std::begin(key));
360
361 return key;
362 }
363
364 sha256_t hash(const std::string_view &plaintext) {
365 sha256_t hsh;
366 EVP_Digest(plaintext.data(), plaintext.size(), hsh.data(), nullptr, EVP_sha256(), nullptr);
367 return hsh;
368 }
369
370 x509_t x509(const std::string_view &x) {
371 bio_t io {BIO_new(BIO_s_mem())};
372
373 BIO_write(io.get(), x.data(), x.size());
374
375 x509_t p;
376 PEM_read_bio_X509(io.get(), &p, nullptr, nullptr);
377
378 return p;
379 }
380
381 pkey_t pkey(const std::string_view &k) {
382 bio_t io {BIO_new(BIO_s_mem())};
383
384 BIO_write(io.get(), k.data(), k.size());
385
386 pkey_t p = nullptr;
387 PEM_read_bio_PrivateKey(io.get(), &p, nullptr, nullptr);
388
389 return p;
390 }
391
392 std::string pem(x509_t &x509) {
393 bio_t bio {BIO_new(BIO_s_mem())};
394
395 PEM_write_bio_X509(bio.get(), x509.get());
396 BUF_MEM *mem_ptr;
397 BIO_get_mem_ptr(bio.get(), &mem_ptr);
398
399 return {mem_ptr->data, mem_ptr->length};
400 }
401
402 std::string pem(pkey_t &pkey) {
403 bio_t bio {BIO_new(BIO_s_mem())};
404
405 PEM_write_bio_PrivateKey(bio.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr);
406 BUF_MEM *mem_ptr;
407 BIO_get_mem_ptr(bio.get(), &mem_ptr);
408
409 return {mem_ptr->data, mem_ptr->length};
410 }
411
412 std::string_view signature(const x509_t &x) {
413 // X509_ALGOR *_ = nullptr;
414
415 const ASN1_BIT_STRING *asn1 = nullptr;
416 X509_get0_signature(&asn1, nullptr, x.get());
417
418#if OPENSSL_VERSION_NUMBER >= 0x40100000L
419 const auto length = ASN1_STRING_get_length(asn1);
420#else
421 const auto length = (std::size_t) ASN1_STRING_length(asn1);
422#endif
423 return {(const char *) ASN1_STRING_get0_data(asn1), length};
424 }
425
426 std::string rand(std::size_t bytes) {
427 std::string r;
428 r.resize(bytes);
429
430 RAND_bytes((uint8_t *) r.data(), r.size());
431
432 return r;
433 }
434
435 std::vector<uint8_t> sign(const pkey_t &pkey, const std::string_view &data, const EVP_MD *md) {
436 md_ctx_t ctx {EVP_MD_CTX_create()};
437
438 if (EVP_DigestSignInit(ctx.get(), nullptr, md, nullptr, (EVP_PKEY *) pkey.get()) != 1) {
439 return {};
440 }
441
442 if (EVP_DigestSignUpdate(ctx.get(), data.data(), data.size()) != 1) {
443 return {};
444 }
445
446 std::size_t slen;
447 if (EVP_DigestSignFinal(ctx.get(), nullptr, &slen) != 1) {
448 return {};
449 }
450
451 std::vector<uint8_t> digest(slen);
452 if (EVP_DigestSignFinal(ctx.get(), digest.data(), &slen) != 1) {
453 return {};
454 }
455
456 return digest;
457 }
458
459 creds_t gen_creds(const std::string_view &cn, std::uint32_t key_bits) {
460 x509_t x509 {X509_new()};
461 pkey_ctx_t ctx {EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr)};
462 pkey_t pkey;
463
464 EVP_PKEY_keygen_init(ctx.get());
465 EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), key_bits);
466 EVP_PKEY_keygen(ctx.get(), &pkey);
467
468 X509_set_version(x509.get(), 2);
469
470 // Generate a real serial number to avoid SEC_ERROR_REUSED_ISSUER_AND_SERIAL with Firefox
471 bignum_t serial {BN_new()};
472 BN_rand(serial.get(), 159, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); // 159 bits to fit in 20 bytes in DER format
473 BN_set_negative(serial.get(), 0); // Serial numbers must be positive
474 BN_to_ASN1_INTEGER(serial.get(), X509_get_serialNumber(x509.get()));
475
476 constexpr auto year = 60 * 60 * 24 * 365;
477#if OPENSSL_VERSION_NUMBER < 0x10100000L
478 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
479 X509_gmtime_adj(X509_get_notAfter(x509.get()), 20 * year);
480#else
481 asn1_string_t not_before {ASN1_STRING_dup(X509_get0_notBefore(x509.get()))};
482 asn1_string_t not_after {ASN1_STRING_dup(X509_get0_notAfter(x509.get()))};
483
484 X509_gmtime_adj(not_before.get(), 0);
485 X509_gmtime_adj(not_after.get(), 20 * year);
486
487 X509_set1_notBefore(x509.get(), not_before.get());
488 X509_set1_notAfter(x509.get(), not_after.get());
489#endif
490
491 X509_set_pubkey(x509.get(), pkey.get());
492
493 util::safe_ptr<X509_NAME, X509_NAME_free> name {X509_NAME_new()};
494 if (!name || X509_NAME_add_entry_by_txt(name.get(), "CN", MBSTRING_ASC, (const std::uint8_t *) cn.data(), cn.size(), -1, 0) != 1 ||
495 X509_set_subject_name(x509.get(), name.get()) != 1) {
496 return {};
497 }
498
499 X509_set_issuer_name(x509.get(), name.get());
500 X509_sign(x509.get(), pkey.get(), EVP_sha256());
501
502 return {pem(x509), pem(pkey)};
503 }
504
505 std::vector<uint8_t> sign256(const pkey_t &pkey, const std::string_view &data) {
506 return sign(pkey, data, EVP_sha256());
507 }
508
509 bool verify(const x509_t &x509, const std::string_view &data, const std::string_view &signature, const EVP_MD *md) {
510 auto pkey = X509_get0_pubkey(x509.get());
511
512 md_ctx_t ctx {EVP_MD_CTX_create()};
513
514 if (EVP_DigestVerifyInit(ctx.get(), nullptr, md, nullptr, pkey) != 1) {
515 return false;
516 }
517
518 if (EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size()) != 1) {
519 return false;
520 }
521
522 if (EVP_DigestVerifyFinal(ctx.get(), (const uint8_t *) signature.data(), signature.size()) != 1) {
523 return false;
524 }
525
526 return true;
527 }
528
529 bool verify256(const x509_t &x509, const std::string_view &data, const std::string_view &signature) {
530 return verify(x509, data, signature, EVP_sha256());
531 }
532
533 void md_ctx_destroy(EVP_MD_CTX *ctx) {
534 EVP_MD_CTX_destroy(ctx);
535 }
536
537 std::string rand_alphabet(std::size_t bytes, const std::string_view &alphabet) {
538 auto value = rand(bytes);
539
540 for (std::size_t i = 0; i != value.size(); ++i) {
541 value[i] = alphabet[value[i] % alphabet.length()];
542 }
543 return value;
544 }
545
546} // namespace crypto
const char * verify(x509_t::element_type *cert, p_named_cert_t &named_cert_out)
Verify the certificate chain. When certificates from two or more instances of Moonlight have been add...
Definition crypto.cpp:55
int encrypt(const std::string_view &plaintext, std::uint8_t *cipher, aes_t *iv)
Encrypts the plaintext using AES CBC mode. length of cipher must be at least: round_to_pkcs7_padded(p...
Definition crypto.cpp:279
int decrypt(const std::string_view &cipher, std::vector< std::uint8_t > &plaintext, aes_t *iv)
Decrypts the ciphertext using AES CBC mode.
Definition crypto.cpp:304
int encrypt(const std::string_view &plaintext, std::uint8_t *tag, std::uint8_t *ciphertext, aes_t *iv)
Encrypts the plaintext using AES GCM mode.
Definition crypto.cpp:184
@ ok
Success.
Definition common.h:436
sha256_t hash(const std::string_view &plaintext)
Hashes the given plaintext using SHA-256.
Definition crypto.cpp:364
Declarations for cryptography functions.
bool pin(std::string pin, std::string name)
Compare the user supplied pin to the Moonlight pin.
Definition nvhttp.cpp:1026