crypt.cpp

main 527 lines · 15.1 KB Raw
Alex Alex Commit Client Upload Part 2 19/10/2026 00:06
1/*
2 * Copyright (c) 2010-2017 OTClient <https://github.com/edubart/otclient>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#include "crypt.h"
24#include <framework/stdext/math.h>
25#include <framework/core/logger.h>
26#include <framework/core/resourcemanager.h>
27#include <framework/platform/platform.h>
28#include <framework/core/application.h>
29
30#include <boost/uuid/uuid_generators.hpp>
31#include <boost/uuid/uuid_io.hpp>
32#include <boost/functional/hash.hpp>
33
34#ifndef __EMSCRIPTEN__
35#include <openssl/rsa.h>
36#include <openssl/sha.h>
37#include <openssl/md5.h>
38#include <openssl/bn.h>
39#include <openssl/err.h>
40#endif
41#include <zlib.h>
42
43static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
44static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
45
46Crypt g_crypt;
47
48Crypt::Crypt()
49{
50#ifndef __EMSCRIPTEN__
51 m_rsa = RSA_new();
52#endif
53}
54
55Crypt::~Crypt()
56{
57#ifndef __EMSCRIPTEN__
58 RSA_free(m_rsa);
59#endif
60}
61
62std::string Crypt::base64Encode(const std::string& decoded_string)
63{
64 std::string ret;
65 int i = 0;
66 int j = 0;
67 uint8 char_array_3[3];
68 uint8 char_array_4[4];
69 int pos = 0;
70 int len = decoded_string.size();
71
72 while(len--) {
73 char_array_3[i++] = decoded_string[pos++];
74 if(i == 3) {
75 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
76 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
77 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
78 char_array_4[3] = char_array_3[2] & 0x3f;
79
80 for(i = 0; (i <4) ; i++)
81 ret += base64_chars[char_array_4[i]];
82 i = 0;
83 }
84 }
85
86 if(i) {
87 for(j = i; j < 3; j++)
88 char_array_3[j] = '\0';
89
90 char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
91 char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
92 char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
93 char_array_4[3] = char_array_3[2] & 0x3f;
94
95 for(j = 0; (j < i + 1); j++)
96 ret += base64_chars[char_array_4[j]];
97
98 while((i++ < 3))
99 ret += '=';
100 }
101
102 return ret;
103}
104
105std::string Crypt::base64Decode(const std::string& encoded_string)
106{
107 int len = encoded_string.size();
108 int i = 0;
109 int j = 0;
110 int in_ = 0;
111 uint8 char_array_4[4], char_array_3[3];
112 std::string ret;
113
114 while(len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
115 char_array_4[i++] = encoded_string[in_]; in_++;
116 if(i ==4) {
117 for(i = 0; i <4; i++)
118 char_array_4[i] = base64_chars.find(char_array_4[i]);
119
120 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
121 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
122 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
123
124 for(i = 0; (i < 3); i++)
125 ret += char_array_3[i];
126 i = 0;
127 }
128 }
129
130 if(i) {
131 for(j = i; j <4; j++)
132 char_array_4[j] = 0;
133
134 for(j = 0; j <4; j++)
135 char_array_4[j] = base64_chars.find(char_array_4[j]);
136
137 char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
138 char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
139 char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
140
141 for(j = 0; (j < i - 1); j++)
142 ret += char_array_3[j];
143 }
144
145 return ret;
146}
147
148std::string Crypt::xorCrypt(const std::string& buffer, const std::string& key)
149{
150 std::string out;
151 out.resize(buffer.size());
152 size_t i, j=0;
153 for(i=0;i<buffer.size();++i) {
154 out[i] = buffer[i] ^ key[j++];
155 if(j >= key.size())
156 j = 0;
157 }
158 return out;
159}
160
161std::string Crypt::genUUID()
162{
163 boost::uuids::random_generator gen;
164 boost::uuids::uuid u = gen();
165 return boost::uuids::to_string(u);
166}
167
168bool Crypt::setMachineUUID(std::string uuidstr)
169{
170 if(uuidstr.empty())
171 return false;
172 uuidstr = _decrypt(uuidstr, false);
173 if(uuidstr.length() != 16)
174 return false;
175 std::copy(uuidstr.begin(), uuidstr.end(), m_machineUUID.begin());
176 return true;
177}
178
179std::string Crypt::getMachineUUID()
180{
181 if(m_machineUUID.is_nil()) {
182 boost::uuids::random_generator gen;
183 m_machineUUID = gen();
184 }
185 return _encrypt(std::string(m_machineUUID.begin(), m_machineUUID.end()), false);
186}
187
188std::string Crypt::getCryptKey(bool useMachineUUID)
189{
190 boost::hash<boost::uuids::uuid> uuid_hasher;
191 boost::uuids::uuid uuid;
192 if(useMachineUUID) {
193 uuid = m_machineUUID;
194 } else {
195 boost::uuids::nil_generator nilgen;
196 uuid = nilgen();
197 }
198 boost::uuids::name_generator namegen(uuid);
199 boost::uuids::uuid u = namegen(g_app.getCompactName() + g_platform.getCPUName() + g_platform.getOSName());
200 std::size_t hash = uuid_hasher(u);
201 std::string key;
202 key.assign((const char *)&hash, sizeof(hash));
203 return key;
204}
205
206std::string Crypt::_encrypt(const std::string& decrypted_string, bool useMachineUUID)
207{
208 std::string tmp = std::string("0000") + decrypted_string;
209 uint32 sum = stdext::adler32((const uint8*)decrypted_string.c_str(), decrypted_string.size());
210 stdext::writeULE32((uint8*)&tmp[0], sum);
211 std::string encrypted = base64Encode(xorCrypt(tmp, getCryptKey(useMachineUUID)));
212 return encrypted;
213}
214
215std::string Crypt::_decrypt(const std::string& encrypted_string, bool useMachineUUID)
216{
217 std::string decoded = base64Decode(encrypted_string);
218 std::string tmp = xorCrypt(decoded, getCryptKey(useMachineUUID));
219 if(tmp.length() >= 4) {
220 uint32 readsum = stdext::readULE32((const uint8*)tmp.c_str());
221 std::string decrypted_string = tmp.substr(4);
222 uint32 sum = stdext::adler32((const uint8*)decrypted_string.c_str(), decrypted_string.size());
223 if(readsum == sum)
224 return decrypted_string;
225 }
226 return std::string();
227}
228
229std::string Crypt::md5Encode(const std::string& decoded_string, bool upperCase)
230{
231#ifndef __EMSCRIPTEN__
232 MD5_CTX c;
233 MD5_Init(&c);
234 MD5_Update(&c, decoded_string.c_str(), decoded_string.length());
235
236 uint8_t md[MD5_DIGEST_LENGTH];
237 MD5_Final(md, &c);
238
239 char output[(MD5_DIGEST_LENGTH << 1) + 1];
240 for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
241 sprintf(output + (i << 1), "%.2X", md[i]);
242
243 std::string result = output;
244 if(upperCase)
245 return result;
246
247 std::transform(result.begin(), result.end(), result.begin(), tolower);
248 return result;
249#else
250 return "";
251#endif
252}
253
254std::string Crypt::sha1Encode(const std::string& decoded_string, bool upperCase)
255{
256#ifndef __EMSCRIPTEN__
257 SHA_CTX c;
258 SHA1_Init(&c);
259 SHA1_Update(&c, decoded_string.c_str(), decoded_string.length());
260
261 uint8_t md[SHA_DIGEST_LENGTH];
262 SHA1_Final(md, &c);
263
264 char output[(SHA_DIGEST_LENGTH << 1) + 1];
265 for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
266 sprintf(output + (i << 1), "%.2X", md[i]);
267
268 std::string result = output;
269 if(upperCase)
270 return result;
271
272 std::transform(result.begin(), result.end(), result.begin(), tolower);
273 return result;
274#else
275 return "";
276#endif
277}
278
279std::string Crypt::sha256Encode(const std::string& decoded_string, bool upperCase)
280{
281#ifndef __EMSCRIPTEN__
282 SHA256_CTX c;
283 SHA256_Init(&c);
284 SHA256_Update(&c, decoded_string.c_str(), decoded_string.length());
285
286 uint8_t md[SHA256_DIGEST_LENGTH];
287 SHA256_Final(md, &c);
288
289 char output[(SHA256_DIGEST_LENGTH << 1) + 1];
290 for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
291 sprintf(output + (i << 1), "%.2X", md[i]);
292
293 std::string result = output;
294 if(upperCase)
295 return result;
296
297 std::transform(result.begin(), result.end(), result.begin(), tolower);
298 return result;
299#else
300 return "";
301#endif
302}
303
304std::string Crypt::sha512Encode(const std::string& decoded_string, bool upperCase)
305{
306#ifndef __EMSCRIPTEN__
307 SHA512_CTX c;
308 SHA512_Init(&c);
309 SHA512_Update(&c, decoded_string.c_str(), decoded_string.length());
310
311 uint8_t md[SHA512_DIGEST_LENGTH];
312 SHA512_Final(md, &c);
313
314 char output[(SHA512_DIGEST_LENGTH << 1) + 1];
315 for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
316 sprintf(output + (i << 1), "%.2X", md[i]);
317
318 std::string result = output;
319 if(upperCase)
320 return result;
321
322 std::transform(result.begin(), result.end(), result.begin(), tolower);
323 return result;
324#else
325 return "";
326#endif
327}
328
329std::string Crypt::crc32(const std::string& decoded_string, bool upperCase)
330{
331 uint32_t crc = ::crc32(0, Z_NULL, 0);
332 crc = ::crc32(crc, (const Bytef*)decoded_string.c_str(), decoded_string.size());
333 std::string result = stdext::dec_to_hex(crc);
334 if (upperCase)
335 std::transform(result.begin(), result.end(), result.begin(), toupper);
336 else
337 std::transform(result.begin(), result.end(), result.begin(), tolower);
338 return result;
339}
340
341
342void Crypt::rsaGenerateKey(int bits, int e)
343{
344 // disabled because new OpenSSL changes broke
345 /*
346 RSA *rsa = RSA_new();
347 BIGNUM *ebn = BN_new();
348 BN_set_word(ebn, e);
349 RSA_generate_key_ex(rsa, bits, ebn, nullptr);
350 g_logger.info(stdext::format("%d bits (%d bytes) RSA key generated", bits, bits / 8));
351 g_logger.info(std::string("p = ") + BN_bn2dec(m_rsa->p));
352 g_logger.info(std::string("q = ") + BN_bn2dec(m_rsa->q));
353 g_logger.info(std::string("d = ") + BN_bn2dec(m_rsa->d));
354 g_logger.info(std::string("n = ") + BN_bn2dec(m_rsa->n));
355 g_logger.info(std::string("e = ") + BN_bn2dec(m_rsa->e));
356 BN_clear_free(ebn);
357 RSA_free(rsa);
358 */
359}
360
361void Crypt::rsaSetPublicKey(const std::string& n, const std::string& e)
362{
363#ifndef __EMSCRIPTEN__
364#if OPENSSL_VERSION_NUMBER < 0x10100005L
365 BN_dec2bn(&m_rsa->n, n.c_str());
366 BN_dec2bn(&m_rsa->e, e.c_str());
367 // clear rsa cache
368 if(m_rsa->_method_mod_n) {
369 BN_MONT_CTX_free(m_rsa->_method_mod_n);
370 m_rsa->_method_mod_n = nullptr;
371 }
372#else
373 BIGNUM *bn = nullptr, *be = nullptr;
374 BN_dec2bn(&bn, n.c_str());
375 BN_dec2bn(&be, e.c_str());
376 RSA_set0_key(m_rsa, bn, be, nullptr);
377#endif
378#endif
379}
380
381void Crypt::rsaSetPrivateKey(const std::string& p, const std::string& q, const std::string& d)
382{
383#ifndef __EMSCRIPTEN__
384#if OPENSSL_VERSION_NUMBER < 0x10100005L
385 BN_dec2bn(&m_rsa->p, p.c_str());
386 BN_dec2bn(&m_rsa->q, q.c_str());
387 BN_dec2bn(&m_rsa->d, d.c_str());
388 // clear rsa cache
389 if(m_rsa->_method_mod_p) {
390 BN_MONT_CTX_free(m_rsa->_method_mod_p);
391 m_rsa->_method_mod_p = nullptr;
392 }
393 if(m_rsa->_method_mod_q) {
394 BN_MONT_CTX_free(m_rsa->_method_mod_q);
395 m_rsa->_method_mod_q = nullptr;
396 }
397#else
398 BIGNUM *bp = nullptr, *bq = nullptr, *bd = nullptr;
399 BN_dec2bn(&bp, p.c_str());
400 BN_dec2bn(&bq, q.c_str());
401 BN_dec2bn(&bd, d.c_str());
402 RSA_set0_key(m_rsa, nullptr, nullptr, bd);
403 RSA_set0_factors(m_rsa, bp, bq);
404#endif
405#endif
406}
407
408bool Crypt::rsaCheckKey()
409{
410#ifndef __EMSCRIPTEN__
411 // only used by server, that sets both public and private
412 if(RSA_check_key(m_rsa)) {
413 BN_CTX *ctx = BN_CTX_new();
414 BN_CTX_start(ctx);
415
416 BIGNUM *r1 = BN_CTX_get(ctx), *r2 = BN_CTX_get(ctx);
417#if OPENSSL_VERSION_NUMBER < 0x10100005L
418 BN_mod(m_rsa->dmp1, m_rsa->d, r1, ctx);
419 BN_mod(m_rsa->dmq1, m_rsa->d, r2, ctx);
420 BN_mod_inverse(m_rsa->iqmp, m_rsa->q, m_rsa->p, ctx);
421#else
422 const BIGNUM *dmp1_c = nullptr, *d = nullptr, *dmq1_c = nullptr, *iqmp_c = nullptr, *q = nullptr, *p = nullptr;
423
424 RSA_get0_key(m_rsa, nullptr, nullptr, &d);
425 RSA_get0_factors(m_rsa, &p, &q);
426 RSA_get0_crt_params(m_rsa, &dmp1_c, &dmq1_c, &iqmp_c);
427
428 BIGNUM *dmp1 = BN_dup(dmp1_c), *dmq1 = BN_dup(dmq1_c), *iqmp = BN_dup(iqmp_c);
429
430 BN_mod(dmp1, d, r1, ctx);
431 BN_mod(dmq1, d, r2, ctx);
432 BN_mod_inverse(iqmp, q, p, ctx);
433 RSA_set0_crt_params(m_rsa, dmp1, dmq1, iqmp);
434#endif
435 return true;
436 }
437 else {
438 ERR_load_crypto_strings();
439 g_logger.error(stdext::format("RSA check failed - %s", ERR_error_string(ERR_get_error(), nullptr)));
440 return false;
441 }
442#else
443 return false;
444#endif
445}
446
447bool Crypt::rsaEncrypt(unsigned char *msg, int size)
448{
449#ifndef __EMSCRIPTEN__
450 if(size != RSA_size(m_rsa))
451 return false;
452 return RSA_public_encrypt(size, msg, msg, m_rsa, RSA_NO_PADDING) != -1;
453#else
454 return false;
455#endif
456}
457
458bool Crypt::rsaDecrypt(unsigned char *msg, int size)
459{
460#ifndef __EMSCRIPTEN__
461 if(size != RSA_size(m_rsa))
462 return false;
463 return RSA_private_decrypt(size, msg, msg, m_rsa, RSA_NO_PADDING) != -1;
464#else
465 return false;
466#endif
467}
468
469int Crypt::rsaGetSize()
470{
471#ifndef __EMSCRIPTEN__
472 return RSA_size(m_rsa);
473#else
474 return 0;
475#endif
476}
477
478#define DELTA 0x9e3779b9
479#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (key[(p&3)^e] ^ z)))
480#ifdef WITH_ENCRYPTION
481void Crypt::bencrypt(uint8_t* buffer, int len, uint64_t k) {
482 uint32_t const key[4] = { (uint32_t)(k >> 32), (uint32_t)(k & 0xFFFFFFFF), 0xDEADDEAD, 0xB00BEEEF };
483 uint32_t y, z, sum;
484 uint32_t *v = (uint32_t*)buffer;
485 unsigned rounds, e;
486 int p, n = (len - len % 4) / 4;
487 if (n < 2)
488 return;
489 rounds = 6 + 52 / n;
490 sum = 0;
491 z = v[n - 1];
492 do {
493 sum += DELTA;
494 e = (sum >> 2) & 3;
495 for (p = 0; p < n - 1; p++) {
496 y = v[p + 1];
497 z = v[p] += MX;
498 }
499 y = v[0];
500 z = v[n - 1] += MX;
501 } while (--rounds);
502}
503#endif
504
505void Crypt::bdecrypt(uint8_t* buffer, int len, uint64_t k) {
506 uint32_t const key[4] = { (uint32_t)(k >> 32), (uint32_t)(k & 0xFFFFFFFF), 0xDEADDEAD, 0xB00BEEEF };
507 uint32_t y, z, sum;
508 uint32_t *v = (uint32_t*)buffer;
509 unsigned p, rounds, e;
510 int n = (len - len % 4) / 4;
511 if (n < 2)
512 return;
513 rounds = 6 + 52 / n;
514 sum = rounds * DELTA;
515 y = v[0];
516 do {
517 e = (sum >> 2) & 3;
518 for (p = n - 1; p > 0; p--) {
519 z = v[p - 1];
520 y = v[p] -= MX;
521 }
522 z = v[n - 1];
523 y = v[0] -= MX;
524 sum -= DELTA;
525 } while (--rounds);
526}
527
Top