No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

crypt.cpp 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. #include "crypt.h"
  23. #include <framework/stdext/math.h>
  24. #include <framework/core/logger.h>
  25. #include <framework/core/resourcemanager.h>
  26. #include <framework/platform/platform.h>
  27. #include <framework/core/application.h>
  28. #include <boost/uuid/uuid_generators.hpp>
  29. #include <boost/uuid/uuid_io.hpp>
  30. #include <boost/functional/hash.hpp>
  31. #include <openssl/rsa.h>
  32. #include <openssl/sha.h>
  33. #include <openssl/md5.h>
  34. #include <openssl/bn.h>
  35. #include <openssl/err.h>
  36. static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  37. static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); }
  38. Crypt g_crypt;
  39. Crypt::Crypt()
  40. {
  41. m_rsa = RSA_new();
  42. }
  43. Crypt::~Crypt()
  44. {
  45. RSA_free(m_rsa);
  46. }
  47. std::string Crypt::base64Encode(const std::string& decoded_string)
  48. {
  49. std::string ret;
  50. int i = 0;
  51. int j = 0;
  52. uint8 char_array_3[3];
  53. uint8 char_array_4[4];
  54. int pos = 0;
  55. int len = decoded_string.size();
  56. while(len--) {
  57. char_array_3[i++] = decoded_string[pos++];
  58. if(i == 3) {
  59. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  60. char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  61. char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  62. char_array_4[3] = char_array_3[2] & 0x3f;
  63. for(i = 0; (i <4) ; i++)
  64. ret += base64_chars[char_array_4[i]];
  65. i = 0;
  66. }
  67. }
  68. if(i) {
  69. for(j = i; j < 3; j++)
  70. char_array_3[j] = '\0';
  71. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  72. char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  73. char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  74. char_array_4[3] = char_array_3[2] & 0x3f;
  75. for(j = 0; (j < i + 1); j++)
  76. ret += base64_chars[char_array_4[j]];
  77. while((i++ < 3))
  78. ret += '=';
  79. }
  80. return ret;
  81. }
  82. std::string Crypt::base64Decode(const std::string& encoded_string)
  83. {
  84. int len = encoded_string.size();
  85. int i = 0;
  86. int j = 0;
  87. int in_ = 0;
  88. uint8 char_array_4[4], char_array_3[3];
  89. std::string ret;
  90. while(len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  91. char_array_4[i++] = encoded_string[in_]; in_++;
  92. if(i ==4) {
  93. for(i = 0; i <4; i++)
  94. char_array_4[i] = base64_chars.find(char_array_4[i]);
  95. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  96. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  97. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  98. for(i = 0; (i < 3); i++)
  99. ret += char_array_3[i];
  100. i = 0;
  101. }
  102. }
  103. if(i) {
  104. for(j = i; j <4; j++)
  105. char_array_4[j] = 0;
  106. for(j = 0; j <4; j++)
  107. char_array_4[j] = base64_chars.find(char_array_4[j]);
  108. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  109. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  110. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  111. for(j = 0; (j < i - 1); j++)
  112. ret += char_array_3[j];
  113. }
  114. return ret;
  115. }
  116. std::string Crypt::xorCrypt(const std::string& buffer, const std::string& key)
  117. {
  118. std::string out;
  119. out.resize(buffer.size());
  120. size_t i, j=0;
  121. for(i=0;i<buffer.size();++i) {
  122. out[i] = buffer[i] ^ key[j++];
  123. if(j >= key.size())
  124. j = 0;
  125. }
  126. return out;
  127. }
  128. std::string Crypt::genUUID()
  129. {
  130. boost::uuids::random_generator gen;
  131. boost::uuids::uuid u = gen();
  132. return boost::uuids::to_string(u);
  133. }
  134. bool Crypt::setMachineUUID(std::string uuidstr)
  135. {
  136. if(uuidstr.empty())
  137. return false;
  138. uuidstr = _decrypt(uuidstr, false);
  139. if(uuidstr.length() != 16)
  140. return false;
  141. std::copy(uuidstr.begin(), uuidstr.end(), m_machineUUID.begin());
  142. return true;
  143. }
  144. std::string Crypt::getMachineUUID()
  145. {
  146. if(m_machineUUID.is_nil()) {
  147. boost::uuids::random_generator gen;
  148. m_machineUUID = gen();
  149. }
  150. return _encrypt(std::string(m_machineUUID.begin(), m_machineUUID.end()), false);
  151. }
  152. std::string Crypt::getCryptKey(bool useMachineUUID)
  153. {
  154. boost::hash<boost::uuids::uuid> uuid_hasher;
  155. boost::uuids::uuid uuid;
  156. if(useMachineUUID) {
  157. uuid = m_machineUUID;
  158. } else {
  159. boost::uuids::nil_generator nilgen;
  160. uuid = nilgen();
  161. }
  162. boost::uuids::name_generator namegen(uuid);
  163. boost::uuids::uuid u = namegen(g_app.getCompactName() + g_platform.getCPUName() + g_platform.getOSName() + g_resources.getUserDir());
  164. std::size_t hash = uuid_hasher(u);
  165. std::string key;
  166. key.assign((const char *)&hash, sizeof(hash));
  167. return key;
  168. }
  169. std::string Crypt::_encrypt(const std::string& decrypted_string, bool useMachineUUID)
  170. {
  171. std::string tmp = "0000" + decrypted_string;
  172. uint32 sum = stdext::adler32((const uint8*)decrypted_string.c_str(), decrypted_string.size());
  173. stdext::writeULE32((uint8*)&tmp[0], sum);
  174. std::string encrypted = base64Encode(xorCrypt(tmp, getCryptKey(useMachineUUID)));
  175. return encrypted;
  176. }
  177. std::string Crypt::_decrypt(const std::string& encrypted_string, bool useMachineUUID)
  178. {
  179. std::string decoded = base64Decode(encrypted_string);
  180. std::string tmp = xorCrypt(decoded, getCryptKey(useMachineUUID));
  181. if(tmp.length() >= 4) {
  182. uint32 readsum = stdext::readULE32((const uint8*)tmp.c_str());
  183. std::string decrypted_string = tmp.substr(4);
  184. uint32 sum = stdext::adler32((const uint8*)decrypted_string.c_str(), decrypted_string.size());
  185. if(readsum == sum)
  186. return decrypted_string;
  187. }
  188. return std::string();
  189. }
  190. std::string Crypt::md5Encode(const std::string& decoded_string, bool upperCase)
  191. {
  192. MD5_CTX c;
  193. MD5_Init(&c);
  194. MD5_Update(&c, decoded_string.c_str(), decoded_string.length());
  195. uint8_t md[MD5_DIGEST_LENGTH];
  196. MD5_Final(md, &c);
  197. char output[(MD5_DIGEST_LENGTH << 1) + 1];
  198. for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
  199. sprintf(output + (i << 1), "%.2X", md[i]);
  200. std::string result = output;
  201. if(upperCase)
  202. return result;
  203. std::transform(result.begin(), result.end(), result.begin(), tolower);
  204. return result;
  205. }
  206. std::string Crypt::sha1Encode(const std::string& decoded_string, bool upperCase)
  207. {
  208. SHA_CTX c;
  209. SHA1_Init(&c);
  210. SHA1_Update(&c, decoded_string.c_str(), decoded_string.length());
  211. uint8_t md[SHA_DIGEST_LENGTH];
  212. SHA1_Final(md, &c);
  213. char output[(SHA_DIGEST_LENGTH << 1) + 1];
  214. for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
  215. sprintf(output + (i << 1), "%.2X", md[i]);
  216. std::string result = output;
  217. if(upperCase)
  218. return result;
  219. std::transform(result.begin(), result.end(), result.begin(), tolower);
  220. return result;
  221. }
  222. std::string Crypt::sha256Encode(const std::string& decoded_string, bool upperCase)
  223. {
  224. SHA256_CTX c;
  225. SHA256_Init(&c);
  226. SHA256_Update(&c, decoded_string.c_str(), decoded_string.length());
  227. uint8_t md[SHA256_DIGEST_LENGTH];
  228. SHA256_Final(md, &c);
  229. char output[(SHA256_DIGEST_LENGTH << 1) + 1];
  230. for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
  231. sprintf(output + (i << 1), "%.2X", md[i]);
  232. std::string result = output;
  233. if(upperCase)
  234. return result;
  235. std::transform(result.begin(), result.end(), result.begin(), tolower);
  236. return result;
  237. }
  238. std::string Crypt::sha512Encode(const std::string& decoded_string, bool upperCase)
  239. {
  240. SHA512_CTX c;
  241. SHA512_Init(&c);
  242. SHA512_Update(&c, decoded_string.c_str(), decoded_string.length());
  243. uint8_t md[SHA512_DIGEST_LENGTH];
  244. SHA512_Final(md, &c);
  245. char output[(SHA512_DIGEST_LENGTH << 1) + 1];
  246. for(int32_t i = 0; i < (int32_t)sizeof(md); ++i)
  247. sprintf(output + (i << 1), "%.2X", md[i]);
  248. std::string result = output;
  249. if(upperCase)
  250. return result;
  251. std::transform(result.begin(), result.end(), result.begin(), tolower);
  252. return result;
  253. }
  254. void Crypt::rsaGenerateKey(int bits, int e)
  255. {
  256. // disabled because new OpenSSL changes broke
  257. /*
  258. RSA *rsa = RSA_new();
  259. BIGNUM *ebn = BN_new();
  260. BN_set_word(ebn, e);
  261. RSA_generate_key_ex(rsa, bits, ebn, nullptr);
  262. g_logger.info(stdext::format("%d bits (%d bytes) RSA key generated", bits, bits / 8));
  263. g_logger.info(std::string("p = ") + BN_bn2dec(m_rsa->p));
  264. g_logger.info(std::string("q = ") + BN_bn2dec(m_rsa->q));
  265. g_logger.info(std::string("d = ") + BN_bn2dec(m_rsa->d));
  266. g_logger.info(std::string("n = ") + BN_bn2dec(m_rsa->n));
  267. g_logger.info(std::string("e = ") + BN_bn2dec(m_rsa->e));
  268. BN_clear_free(ebn);
  269. RSA_free(rsa);
  270. */
  271. }
  272. void Crypt::rsaSetPublicKey(const std::string& n, const std::string& e)
  273. {
  274. #if OPENSSL_VERSION_NUMBER < 0x10100005L
  275. BN_dec2bn(&m_rsa->n, n.c_str());
  276. BN_dec2bn(&m_rsa->e, e.c_str());
  277. // clear rsa cache
  278. if (m_rsa->_method_mod_n)
  279. {
  280. BN_MONT_CTX_free(m_rsa->_method_mod_n);
  281. m_rsa->_method_mod_n = NULL;
  282. }
  283. #else
  284. {
  285. BIGNUM *bn=NULL;
  286. BIGNUM *be=NULL;
  287. BN_dec2bn(&bn, n.c_str());
  288. BN_dec2bn(&be, e.c_str());
  289. RSA_set0_key(m_rsa,bn,be,NULL);
  290. // note, not supposed to free bn/be here, that's m_rsa's destructor's job
  291. }
  292. #endif
  293. }
  294. void Crypt::rsaSetPrivateKey(const std::string& p, const std::string& q, const std::string& d)
  295. {
  296. #if OPENSSL_VERSION_NUMBER < 0x10100005L
  297. BN_dec2bn(&m_rsa->p, p.c_str());
  298. BN_dec2bn(&m_rsa->q, q.c_str());
  299. BN_dec2bn(&m_rsa->d, d.c_str());
  300. // clear rsa cache
  301. if (m_rsa->_method_mod_p)
  302. {
  303. BN_MONT_CTX_free(m_rsa->_method_mod_p);
  304. m_rsa->_method_mod_p = NULL;
  305. }
  306. if (m_rsa->_method_mod_q)
  307. {
  308. BN_MONT_CTX_free(m_rsa->_method_mod_q);
  309. m_rsa->_method_mod_q = NULL;
  310. }
  311. #else
  312. {
  313. if(d.length()> 0)
  314. {
  315. BIGNUM *bd=NULL;
  316. BN_dec2bn(&bd, d.c_str());
  317. RSA_set0_key(m_rsa,NULL,NULL,bd);
  318. }
  319. BIGNUM *bp=NULL;
  320. BIGNUM *bq=NULL;
  321. BN_dec2bn(&bp, p.c_str());
  322. BN_dec2bn(&bq, q.c_str());
  323. RSA_set0_factors(m_rsa,bp,bq);
  324. // note, not supposed to free bp/bq/bd here, that's m_rsa's destructor's job
  325. }
  326. #endif
  327. }
  328. bool Crypt::rsaCheckKey()
  329. {
  330. // only used by server, that sets both public and private
  331. if(RSA_check_key(m_rsa)) {
  332. BN_CTX *ctx = BN_CTX_new();
  333. BN_CTX_start(ctx);
  334. BIGNUM *r1 = BN_CTX_get(ctx), *r2 = BN_CTX_get(ctx);
  335. #if OPENSSL_VERSION_NUMBER < 0x10100005L
  336. BN_mod(m_rsa->dmp1, m_rsa->d, r1, ctx);
  337. BN_mod(m_rsa->dmq1, m_rsa->d, r2, ctx);
  338. BN_mod_inverse(m_rsa->iqmp, m_rsa->q, m_rsa->p, ctx);
  339. #else
  340. {
  341. const BIGNUM *dmp1_c=NULL;
  342. const BIGNUM *d=NULL;
  343. const BIGNUM *dmq1_c=NULL;
  344. const BIGNUM *iqmp_c=NULL;
  345. const BIGNUM *q=NULL;
  346. const BIGNUM *p=NULL;
  347. RSA_get0_key(m_rsa,NULL, NULL, &d);
  348. RSA_get0_factors(m_rsa, &p, &q);
  349. RSA_get0_crt_params(m_rsa,&dmp1_c,&dmq1_c,&iqmp_c);
  350. BIGNUM *dmp1=BN_dup(dmp1_c);
  351. BIGNUM *dmq1=BN_dup(dmq1_c);
  352. BIGNUM *iqmp=BN_dup(iqmp_c);
  353. BN_mod(dmp1, d, r1, ctx);
  354. BN_mod(dmq1, d, r2, ctx);
  355. BN_mod_inverse(iqmp, q, p, ctx);
  356. RSA_set0_crt_params(m_rsa, dmp1, dmq1, iqmp);
  357. }
  358. #endif
  359. return true;
  360. }
  361. else {
  362. ERR_load_crypto_strings();
  363. g_logger.error(stdext::format("RSA check failed - %s", ERR_error_string(ERR_get_error(), NULL)));
  364. return false;
  365. }
  366. }
  367. bool Crypt::rsaEncrypt(unsigned char *msg, int size)
  368. {
  369. if(size != RSA_size(m_rsa))
  370. return false;
  371. return RSA_public_encrypt(size, msg, msg, m_rsa, RSA_NO_PADDING) != -1;
  372. }
  373. bool Crypt::rsaDecrypt(unsigned char *msg, int size)
  374. {
  375. if(size != RSA_size(m_rsa))
  376. return false;
  377. return RSA_private_decrypt(size, msg, msg, m_rsa, RSA_NO_PADDING) != -1;
  378. }
  379. int Crypt::rsaGetSize()
  380. {
  381. return RSA_size(m_rsa);
  382. }