Update embedded jsoncpp from unk version to 0.10.6 + move libs to lib/ instead of...
[oweals/minetest.git] / src / util / srp.cpp
1 /*
2  * Secure Remote Password 6a implementation
3  * https://github.com/est31/csrp-gmp
4  *
5  * The MIT License (MIT)
6  *
7  * Copyright (c) 2010, 2013 Tom Cocagne, 2015 est31 <MTest31@outlook.com>
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy of
10  * this software and associated documentation files (the "Software"), to deal in
11  * the Software without restriction, including without limitation the rights to
12  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13  * of the Software, and to permit persons to whom the Software is furnished to do
14  * so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in all
17  * copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  *
27  */
28
29 // clang-format off
30 #ifdef WIN32
31         #include <windows.h>
32         #include <wincrypt.h>
33 #else
34         #include <time.h>
35 #endif
36 // clang-format on
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <stdio.h>
41
42 #include <config.h>
43
44 #if USE_SYSTEM_GMP || defined (__ANDROID__) || defined (ANDROID)
45         #include <gmp.h>
46 #else
47         #include <mini-gmp.h>
48 #endif
49
50 #include <util/sha2.h>
51
52 #include "srp.h"
53 //#define CSRP_USE_SHA1
54 #define CSRP_USE_SHA256
55
56 #define srp_dbg_data(data, datalen, prevtext) ;
57 /*void srp_dbg_data(unsigned char * data, size_t datalen, char * prevtext)
58 {
59         printf(prevtext);
60         size_t i;
61         for (i = 0; i < datalen; i++)
62         {
63                 printf("%02X", data[i]);
64         }
65         printf("\n");
66 }*/
67
68 static int g_initialized = 0;
69
70 #define RAND_BUFF_MAX 128
71 static unsigned int g_rand_idx;
72 static unsigned char g_rand_buff[RAND_BUFF_MAX];
73
74 void *(*srp_alloc)(size_t) = &malloc;
75 void *(*srp_realloc)(void *, size_t) = &realloc;
76 void (*srp_free)(void *) = &free;
77
78 // clang-format off
79 void srp_set_memory_functions(
80                 void *(*new_srp_alloc)(size_t),
81                 void *(*new_srp_realloc)(void *, size_t),
82                 void (*new_srp_free)(void *))
83 {
84         srp_alloc = new_srp_alloc;
85         srp_realloc = new_srp_realloc;
86         srp_free = new_srp_free;
87 }
88 // clang-format on
89
90 typedef struct {
91         mpz_t N;
92         mpz_t g;
93 } NGConstant;
94
95 struct NGHex {
96         const char *n_hex;
97         const char *g_hex;
98 };
99
100 /* All constants here were pulled from Appendix A of RFC 5054 */
101 static struct NGHex global_Ng_constants[] = {
102         {/* 1024 */
103                 "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C"
104                 "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4"
105                 "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29"
106                 "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A"
107                 "FD5138FE8376435B9FC61D2FC0EB06E3",
108                 "2"},
109         {/* 2048 */
110                 "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294"
111                 "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D"
112                 "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB"
113                 "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74"
114                 "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A"
115                 "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D"
116                 "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73"
117                 "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6"
118                 "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F"
119                 "9E4AFF73",
120                 "2"},
121         {/* 4096 */
122                 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
123                 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
124                 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
125                 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
126                 "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
127                 "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
128                 "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
129                 "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
130                 "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
131                 "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
132                 "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
133                 "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
134                 "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
135                 "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
136                 "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
137                 "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
138                 "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
139                 "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
140                 "FFFFFFFFFFFFFFFF",
141                 "5"},
142         {/* 8192 */
143                 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
144                 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
145                 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
146                 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
147                 "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
148                 "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
149                 "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
150                 "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
151                 "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
152                 "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
153                 "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
154                 "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
155                 "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
156                 "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
157                 "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
158                 "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
159                 "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
160                 "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
161                 "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
162                 "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
163                 "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
164                 "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
165                 "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
166                 "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
167                 "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
168                 "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
169                 "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
170                 "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA"
171                 "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C"
172                 "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
173                 "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886"
174                 "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6"
175                 "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5"
176                 "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268"
177                 "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6"
178                 "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
179                 "60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
180                 "13"},
181         {0, 0} /* null sentinel */
182 };
183
184 static void delete_ng(NGConstant *ng)
185 {
186         if (ng) {
187                 mpz_clear(ng->N);
188                 mpz_clear(ng->g);
189                 srp_free(ng);
190         }
191 }
192
193 static NGConstant *new_ng(SRP_NGType ng_type, const char *n_hex, const char *g_hex)
194 {
195         NGConstant *ng = (NGConstant *)srp_alloc(sizeof(NGConstant));
196
197         if (!ng) return 0;
198
199         mpz_init(ng->N);
200         mpz_init(ng->g);
201
202         if (ng_type != SRP_NG_CUSTOM) {
203                 n_hex = global_Ng_constants[ng_type].n_hex;
204                 g_hex = global_Ng_constants[ng_type].g_hex;
205         }
206
207         int rv = 0;
208         rv = mpz_set_str(ng->N, n_hex, 16);
209         rv = rv | mpz_set_str(ng->g, g_hex, 16);
210
211         if (rv) {
212                 delete_ng(ng);
213                 return 0;
214         }
215
216         return ng;
217 }
218
219 typedef union {
220         SHA_CTX sha;
221         SHA256_CTX sha256;
222         // SHA512_CTX sha512;
223 } HashCTX;
224
225 struct SRPVerifier {
226         SRP_HashAlgorithm hash_alg;
227         NGConstant *ng;
228
229         char *username;
230         unsigned char *bytes_B;
231         int authenticated;
232
233         unsigned char M[SHA512_DIGEST_LENGTH];
234         unsigned char H_AMK[SHA512_DIGEST_LENGTH];
235         unsigned char session_key[SHA512_DIGEST_LENGTH];
236 };
237
238 struct SRPUser {
239         SRP_HashAlgorithm hash_alg;
240         NGConstant *ng;
241
242         mpz_t a;
243         mpz_t A;
244         mpz_t S;
245
246         unsigned char *bytes_A;
247         int authenticated;
248
249         char *username;
250         char *username_verifier;
251         unsigned char *password;
252         size_t password_len;
253
254         unsigned char M[SHA512_DIGEST_LENGTH];
255         unsigned char H_AMK[SHA512_DIGEST_LENGTH];
256         unsigned char session_key[SHA512_DIGEST_LENGTH];
257 };
258
259 // clang-format off
260 static int hash_init(SRP_HashAlgorithm alg, HashCTX *c)
261 {
262         switch (alg) {
263 #ifdef CSRP_USE_SHA1
264                 case SRP_SHA1: return SHA1_Init(&c->sha);
265 #endif
266                 /*
267                 case SRP_SHA224: return SHA224_Init(&c->sha256);
268                 */
269 #ifdef CSRP_USE_SHA256
270                 case SRP_SHA256: return SHA256_Init(&c->sha256);
271 #endif
272                 /*
273                 case SRP_SHA384: return SHA384_Init(&c->sha512);
274                 case SRP_SHA512: return SHA512_Init(&c->sha512);
275                 */
276                 default: return -1;
277         };
278 }
279 static int hash_update( SRP_HashAlgorithm alg, HashCTX *c, const void *data, size_t len )
280 {
281         switch (alg) {
282 #ifdef CSRP_USE_SHA1
283                 case SRP_SHA1: return SHA1_Update(&c->sha, data, len);
284 #endif
285                 /*
286                 case SRP_SHA224: return SHA224_Update(&c->sha256, data, len);
287                 */
288 #ifdef CSRP_USE_SHA256
289                 case SRP_SHA256: return SHA256_Update(&c->sha256, data, len);
290 #endif
291                 /*
292                 case SRP_SHA384: return SHA384_Update(&c->sha512, data, len);
293                 case SRP_SHA512: return SHA512_Update(&c->sha512, data, len);
294                 */
295                 default: return -1;
296         };
297 }
298 static int hash_final( SRP_HashAlgorithm alg, HashCTX *c, unsigned char *md )
299 {
300         switch (alg) {
301 #ifdef CSRP_USE_SHA1
302                 case SRP_SHA1: return SHA1_Final(md, &c->sha);
303 #endif
304                 /*
305                 case SRP_SHA224: return SHA224_Final(md, &c->sha256);
306                 */
307 #ifdef CSRP_USE_SHA256
308                 case SRP_SHA256: return SHA256_Final(md, &c->sha256);
309 #endif
310                 /*
311                 case SRP_SHA384: return SHA384_Final(md, &c->sha512);
312                 case SRP_SHA512: return SHA512_Final(md, &c->sha512);
313                 */
314                 default: return -1;
315         };
316 }
317 static unsigned char *hash(SRP_HashAlgorithm alg, const unsigned char *d, size_t n, unsigned char *md)
318 {
319         switch (alg) {
320 #ifdef CSRP_USE_SHA1
321                 case SRP_SHA1: return SHA1(d, n, md);
322 #endif
323                 /*
324                 case SRP_SHA224: return SHA224( d, n, md );
325                 */
326 #ifdef CSRP_USE_SHA256
327                 case SRP_SHA256: return SHA256(d, n, md);
328 #endif
329                 /*
330                 case SRP_SHA384: return SHA384( d, n, md );
331                 case SRP_SHA512: return SHA512( d, n, md );
332                 */
333                 default: return 0;
334         };
335 }
336 static size_t hash_length(SRP_HashAlgorithm alg)
337 {
338         switch (alg) {
339 #ifdef CSRP_USE_SHA1
340                 case SRP_SHA1: return SHA_DIGEST_LENGTH;
341 #endif
342                 /*
343                 case SRP_SHA224: return SHA224_DIGEST_LENGTH;
344                 */
345 #ifdef CSRP_USE_SHA256
346                 case SRP_SHA256: return SHA256_DIGEST_LENGTH;
347 #endif
348                 /*
349                 case SRP_SHA384: return SHA384_DIGEST_LENGTH;
350                 case SRP_SHA512: return SHA512_DIGEST_LENGTH;
351                 */
352                 default: return -1;
353         };
354 }
355 // clang-format on
356
357 inline static int mpz_num_bytes(const mpz_t op)
358 {
359         return (mpz_sizeinbase(op, 2) + 7) / 8;
360 }
361
362 inline static void mpz_to_bin(const mpz_t op, unsigned char *to)
363 {
364         mpz_export(to, NULL, 1, 1, 1, 0, op);
365 }
366
367 inline static void mpz_from_bin(const unsigned char *s, size_t len, mpz_t ret)
368 {
369         mpz_import(ret, len, 1, 1, 1, 0, s);
370 }
371
372 // set op to (op1 * op2) mod d, using tmp for the calculation
373 inline static void mpz_mulm(
374         mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
375 {
376         mpz_mul(tmp, op1, op2);
377         mpz_mod(op, tmp, d);
378 }
379
380 // set op to (op1 + op2) mod d, using tmp for the calculation
381 inline static void mpz_addm(
382         mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
383 {
384         mpz_add(tmp, op1, op2);
385         mpz_mod(op, tmp, d);
386 }
387
388 // set op to (op1 - op2) mod d, using tmp for the calculation
389 inline static void mpz_subm(
390         mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp)
391 {
392         mpz_sub(tmp, op1, op2);
393         mpz_mod(op, tmp, d);
394 }
395
396 static SRP_Result H_nn(
397         mpz_t result, SRP_HashAlgorithm alg, const mpz_t N, const mpz_t n1, const mpz_t n2)
398 {
399         unsigned char buff[SHA512_DIGEST_LENGTH];
400         size_t len_N = mpz_num_bytes(N);
401         size_t len_n1 = mpz_num_bytes(n1);
402         size_t len_n2 = mpz_num_bytes(n2);
403         size_t nbytes = len_N + len_N;
404         unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
405         if (!bin) return SRP_ERR;
406         if (len_n1 > len_N || len_n2 > len_N) {
407                 srp_free(bin);
408                 return SRP_ERR;
409         }
410         memset(bin, 0, nbytes);
411         mpz_to_bin(n1, bin + (len_N - len_n1));
412         mpz_to_bin(n2, bin + (len_N + len_N - len_n2));
413         hash(alg, bin, nbytes, buff);
414         srp_free(bin);
415         mpz_from_bin(buff, hash_length(alg), result);
416         return SRP_OK;
417 }
418
419 static SRP_Result H_ns(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *n,
420         size_t len_n, const unsigned char *bytes, size_t len_bytes)
421 {
422         unsigned char buff[SHA512_DIGEST_LENGTH];
423         size_t nbytes = len_n + len_bytes;
424         unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
425         if (!bin) return SRP_ERR;
426         memcpy(bin, n, len_n);
427         memcpy(bin + len_n, bytes, len_bytes);
428         hash(alg, bin, nbytes, buff);
429         srp_free(bin);
430         mpz_from_bin(buff, hash_length(alg), result);
431         return SRP_OK;
432 }
433
434 static int calculate_x(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *salt,
435         size_t salt_len, const char *username, const unsigned char *password,
436         size_t password_len)
437 {
438         unsigned char ucp_hash[SHA512_DIGEST_LENGTH];
439         HashCTX ctx;
440         hash_init(alg, &ctx);
441
442         srp_dbg_data((char *)username, strlen(username), "Username for x: ");
443         srp_dbg_data((char *)password, password_len, "Password for x: ");
444         hash_update(alg, &ctx, username, strlen(username));
445         hash_update(alg, &ctx, ":", 1);
446         hash_update(alg, &ctx, password, password_len);
447
448         hash_final(alg, &ctx, ucp_hash);
449
450         return H_ns(result, alg, salt, salt_len, ucp_hash, hash_length(alg));
451 }
452
453 static SRP_Result update_hash_n(SRP_HashAlgorithm alg, HashCTX *ctx, const mpz_t n)
454 {
455         size_t len = mpz_num_bytes(n);
456         unsigned char *n_bytes = (unsigned char *)srp_alloc(len);
457         if (!n_bytes) return SRP_ERR;
458         mpz_to_bin(n, n_bytes);
459         hash_update(alg, ctx, n_bytes, len);
460         srp_free(n_bytes);
461         return SRP_OK;
462 }
463
464 static SRP_Result hash_num(SRP_HashAlgorithm alg, const mpz_t n, unsigned char *dest)
465 {
466         int nbytes = mpz_num_bytes(n);
467         unsigned char *bin = (unsigned char *)srp_alloc(nbytes);
468         if (!bin) return SRP_ERR;
469         mpz_to_bin(n, bin);
470         hash(alg, bin, nbytes, dest);
471         srp_free(bin);
472         return SRP_OK;
473 }
474
475 static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned char *dest,
476         const char *I, const unsigned char *s_bytes, size_t s_len, const mpz_t A,
477         const mpz_t B, const unsigned char *K)
478 {
479         unsigned char H_N[SHA512_DIGEST_LENGTH];
480         unsigned char H_g[SHA512_DIGEST_LENGTH];
481         unsigned char H_I[SHA512_DIGEST_LENGTH];
482         unsigned char H_xor[SHA512_DIGEST_LENGTH];
483         HashCTX ctx;
484         size_t i = 0;
485         size_t hash_len = hash_length(alg);
486
487         if (!hash_num(alg, ng->N, H_N)) return SRP_ERR;
488         if (!hash_num(alg, ng->g, H_g)) return SRP_ERR;
489
490         hash(alg, (const unsigned char *)I, strlen(I), H_I);
491
492         for (i = 0; i < hash_len; i++)
493                 H_xor[i] = H_N[i] ^ H_g[i];
494
495         hash_init(alg, &ctx);
496
497         hash_update(alg, &ctx, H_xor, hash_len);
498         hash_update(alg, &ctx, H_I, hash_len);
499         hash_update(alg, &ctx, s_bytes, s_len);
500         if (!update_hash_n(alg, &ctx, A)) return SRP_ERR;
501         if (!update_hash_n(alg, &ctx, B)) return SRP_ERR;
502         hash_update(alg, &ctx, K, hash_len);
503
504         hash_final(alg, &ctx, dest);
505         return SRP_OK;
506 }
507
508 static SRP_Result calculate_H_AMK(SRP_HashAlgorithm alg, unsigned char *dest,
509         const mpz_t A, const unsigned char *M, const unsigned char *K)
510 {
511         HashCTX ctx;
512
513         hash_init(alg, &ctx);
514
515         if (!update_hash_n(alg, &ctx, A)) return SRP_ERR;
516         hash_update(alg, &ctx, M, hash_length(alg));
517         hash_update(alg, &ctx, K, hash_length(alg));
518
519         hash_final(alg, &ctx, dest);
520         return SRP_OK;
521 }
522
523 static SRP_Result fill_buff()
524 {
525         g_rand_idx = 0;
526
527 #ifdef WIN32
528         HCRYPTPROV wctx;
529 #else
530         FILE *fp = 0;
531 #endif
532
533 #ifdef WIN32
534
535         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
536                 return SRP_ERR;
537         if (!CryptGenRandom(wctx, sizeof(g_rand_buff), (BYTE *)g_rand_buff)) return SRP_ERR;
538         if (!CryptReleaseContext(wctx, 0)) return SRP_ERR;
539
540 #else
541         fp = fopen("/dev/urandom", "r");
542
543         if (!fp) return SRP_ERR;
544
545         if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { fclose(fp); return SRP_ERR; }
546         if (fclose(fp)) return SRP_ERR;
547 #endif
548         return SRP_OK;
549 }
550
551 static SRP_Result mpz_fill_random(mpz_t num)
552 {
553         // was call: BN_rand(num, 256, -1, 0);
554         if (RAND_BUFF_MAX - g_rand_idx < 32)
555                 if (fill_buff() != SRP_OK) return SRP_ERR;
556         mpz_from_bin((const unsigned char *)(&g_rand_buff[g_rand_idx]), 32, num);
557         g_rand_idx += 32;
558         return SRP_OK;
559 }
560
561 static SRP_Result init_random()
562 {
563         if (g_initialized) return SRP_OK;
564         SRP_Result ret = fill_buff();
565         g_initialized = (ret == SRP_OK);
566         return ret;
567 }
568
569 #define srp_dbg_num(num, text) ;
570 /*void srp_dbg_num(mpz_t num, char * prevtext)
571 {
572         int len_num = mpz_num_bytes(num);
573         char *bytes_num = (char*) srp_alloc(len_num);
574         mpz_to_bin(num, (unsigned char *) bytes_num);
575         srp_dbg_data(bytes_num, len_num, prevtext);
576         srp_free(bytes_num);
577
578 }*/
579
580 /***********************************************************************************************************
581  *
582  *  Exported Functions
583  *
584  ***********************************************************************************************************/
585
586 // clang-format off
587 SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg,
588         SRP_NGType ng_type, const char *username_for_verifier,
589         const unsigned char *password, size_t len_password,
590         unsigned char **bytes_s,  size_t *len_s,
591         unsigned char **bytes_v, size_t *len_v,
592         const char *n_hex, const char *g_hex )
593 {
594         SRP_Result ret = SRP_OK;
595
596         mpz_t v; mpz_init(v);
597         mpz_t x; mpz_init(x);
598         // clang-format on
599
600         NGConstant *ng = new_ng(ng_type, n_hex, g_hex);
601
602         if (!ng) goto error_and_exit;
603
604         if (init_random() != SRP_OK) /* Only happens once */
605                 goto error_and_exit;
606
607         if (*bytes_s == NULL) {
608                 size_t size_to_fill = 16;
609                 *len_s = size_to_fill;
610                 if (RAND_BUFF_MAX - g_rand_idx < size_to_fill)
611                         if (fill_buff() != SRP_OK) goto error_and_exit;
612                 *bytes_s = (unsigned char *)srp_alloc(size_to_fill);
613                 if (!*bytes_s) goto error_and_exit;
614                 memcpy(*bytes_s, &g_rand_buff + g_rand_idx, size_to_fill);
615                 g_rand_idx += size_to_fill;
616         }
617
618         if (!calculate_x(
619                         x, alg, *bytes_s, *len_s, username_for_verifier, password, len_password))
620                 goto error_and_exit;
621
622         srp_dbg_num(x, "Server calculated x: ");
623
624         mpz_powm(v, ng->g, x, ng->N);
625
626         *len_v = mpz_num_bytes(v);
627
628         *bytes_v = (unsigned char *)srp_alloc(*len_v);
629
630         if (!*bytes_v) goto error_and_exit;
631
632         mpz_to_bin(v, *bytes_v);
633
634 cleanup_and_exit:
635         delete_ng(ng);
636         mpz_clear(v);
637         mpz_clear(x);
638         return ret;
639 error_and_exit:
640         ret = SRP_ERR;
641         goto cleanup_and_exit;
642 }
643
644 // clang-format off
645
646 /* Out: bytes_B, len_B.
647  *
648  * On failure, bytes_B will be set to NULL and len_B will be set to 0
649  */
650 struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg,
651         SRP_NGType ng_type, const char *username,
652         const unsigned char *bytes_s, size_t len_s,
653         const unsigned char *bytes_v, size_t len_v,
654         const unsigned char *bytes_A, size_t len_A,
655         const unsigned char *bytes_b, size_t len_b,
656         unsigned char **bytes_B, size_t *len_B,
657         const char *n_hex, const char *g_hex )
658 {
659         mpz_t v; mpz_init(v); mpz_from_bin(bytes_v, len_v, v);
660         mpz_t A; mpz_init(A); mpz_from_bin(bytes_A, len_A, A);
661         mpz_t u; mpz_init(u);
662         mpz_t B; mpz_init(B);
663         mpz_t S; mpz_init(S);
664         mpz_t b; mpz_init(b);
665         mpz_t k; mpz_init(k);
666         mpz_t tmp1; mpz_init(tmp1);
667         mpz_t tmp2; mpz_init(tmp2);
668         mpz_t tmp3; mpz_init(tmp3);
669         // clang-format on
670         size_t ulen = strlen(username) + 1;
671         NGConstant *ng = new_ng(ng_type, n_hex, g_hex);
672         struct SRPVerifier *ver = 0;
673
674         *len_B = 0;
675         *bytes_B = 0;
676
677         if (!ng) goto cleanup_and_exit;
678
679         ver = (struct SRPVerifier *)srp_alloc(sizeof(struct SRPVerifier));
680
681         if (!ver) goto cleanup_and_exit;
682
683         if (init_random() != SRP_OK) { /* Only happens once */
684                 srp_free(ver);
685                 ver = 0;
686                 goto cleanup_and_exit;
687         }
688
689         ver->username = (char *)srp_alloc(ulen);
690         ver->hash_alg = alg;
691         ver->ng = ng;
692
693         if (!ver->username) {
694                 srp_free(ver);
695                 ver = 0;
696                 goto cleanup_and_exit;
697         }
698
699         memcpy((char *)ver->username, username, ulen);
700
701         ver->authenticated = 0;
702
703         /* SRP-6a safety check */
704         mpz_mod(tmp1, A, ng->N);
705         if (mpz_sgn(tmp1) != 0) {
706                 if (bytes_b) {
707                         mpz_from_bin(bytes_b, len_b, b);
708                 } else {
709                         if (!mpz_fill_random(b)) goto ver_cleanup_and_exit;
710                 }
711
712                 if (!H_nn(k, alg, ng->N, ng->N, ng->g)) goto ver_cleanup_and_exit;
713
714                 /* B = kv + g^b */
715                 mpz_mulm(tmp1, k, v, ng->N, tmp3);
716                 mpz_powm(tmp2, ng->g, b, ng->N);
717                 mpz_addm(B, tmp1, tmp2, ng->N, tmp3);
718
719                 if (!H_nn(u, alg, ng->N, A, B)) goto ver_cleanup_and_exit;
720
721                 srp_dbg_num(u, "Server calculated u: ");
722
723                 /* S = (A *(v^u)) ^ b */
724                 mpz_powm(tmp1, v, u, ng->N);
725                 mpz_mulm(tmp2, A, tmp1, ng->N, tmp3);
726                 mpz_powm(S, tmp2, b, ng->N);
727
728                 if (!hash_num(alg, S, ver->session_key)) goto ver_cleanup_and_exit;
729
730                 if (!calculate_M(
731                                 alg, ng, ver->M, username, bytes_s, len_s, A, B, ver->session_key)) {
732                         goto ver_cleanup_and_exit;
733                 }
734                 if (!calculate_H_AMK(alg, ver->H_AMK, A, ver->M, ver->session_key)) {
735                         goto ver_cleanup_and_exit;
736                 }
737
738                 *len_B = mpz_num_bytes(B);
739                 *bytes_B = (unsigned char *)srp_alloc(*len_B);
740
741                 if (!*bytes_B) {
742                         *len_B = 0;
743                         goto ver_cleanup_and_exit;
744                 }
745
746                 mpz_to_bin(B, *bytes_B);
747
748                 ver->bytes_B = *bytes_B;
749         } else {
750                 srp_free(ver);
751                 ver = 0;
752         }
753
754 cleanup_and_exit:
755         mpz_clear(v);
756         mpz_clear(A);
757         mpz_clear(u);
758         mpz_clear(k);
759         mpz_clear(B);
760         mpz_clear(S);
761         mpz_clear(b);
762         mpz_clear(tmp1);
763         mpz_clear(tmp2);
764         mpz_clear(tmp3);
765         return ver;
766 ver_cleanup_and_exit:
767         srp_free(ver->username);
768         srp_free(ver);
769         ver = 0;
770         goto cleanup_and_exit;
771 }
772
773 void srp_verifier_delete(struct SRPVerifier *ver)
774 {
775         if (ver) {
776                 delete_ng(ver->ng);
777                 srp_free(ver->username);
778                 srp_free(ver->bytes_B);
779                 memset(ver, 0, sizeof(*ver));
780                 srp_free(ver);
781         }
782 }
783
784 int srp_verifier_is_authenticated(struct SRPVerifier *ver)
785 {
786         return ver->authenticated;
787 }
788
789 const char *srp_verifier_get_username(struct SRPVerifier *ver)
790 {
791         return ver->username;
792 }
793
794 const unsigned char *srp_verifier_get_session_key(
795         struct SRPVerifier *ver, size_t *key_length)
796 {
797         if (key_length) *key_length = hash_length(ver->hash_alg);
798         return ver->session_key;
799 }
800
801 size_t srp_verifier_get_session_key_length(struct SRPVerifier *ver)
802 {
803         return hash_length(ver->hash_alg);
804 }
805
806 /* user_M must be exactly SHA512_DIGEST_LENGTH bytes in size */
807 void srp_verifier_verify_session(
808         struct SRPVerifier *ver, const unsigned char *user_M, unsigned char **bytes_HAMK)
809 {
810         if (memcmp(ver->M, user_M, hash_length(ver->hash_alg)) == 0) {
811                 ver->authenticated = 1;
812                 *bytes_HAMK = ver->H_AMK;
813         } else
814                 *bytes_HAMK = NULL;
815 }
816
817 /*******************************************************************************/
818
819 struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type,
820         const char *username, const char *username_for_verifier,
821         const unsigned char *bytes_password, size_t len_password, const char *n_hex,
822         const char *g_hex)
823 {
824         struct SRPUser *usr = (struct SRPUser *)srp_alloc(sizeof(struct SRPUser));
825         size_t ulen = strlen(username) + 1;
826         size_t uvlen = strlen(username_for_verifier) + 1;
827
828         if (!usr) goto err_exit;
829
830         if (init_random() != SRP_OK) /* Only happens once */
831                 goto err_exit;
832
833         usr->hash_alg = alg;
834         usr->ng = new_ng(ng_type, n_hex, g_hex);
835
836         mpz_init(usr->a);
837         mpz_init(usr->A);
838         mpz_init(usr->S);
839
840         if (!usr->ng) goto err_exit;
841
842         usr->username = (char *)srp_alloc(ulen);
843         usr->username_verifier = (char *)srp_alloc(uvlen);
844         usr->password = (unsigned char *)srp_alloc(len_password);
845         usr->password_len = len_password;
846
847         if (!usr->username || !usr->password || !usr->username_verifier) goto err_exit;
848
849         memcpy(usr->username, username, ulen);
850         memcpy(usr->username_verifier, username_for_verifier, uvlen);
851         memcpy(usr->password, bytes_password, len_password);
852
853         usr->authenticated = 0;
854
855         usr->bytes_A = 0;
856
857         return usr;
858
859 err_exit:
860         if (usr) {
861                 mpz_clear(usr->a);
862                 mpz_clear(usr->A);
863                 mpz_clear(usr->S);
864                 if (usr->ng) delete_ng(usr->ng);
865                 srp_free(usr->username);
866                 srp_free(usr->username_verifier);
867                 if (usr->password) {
868                         memset(usr->password, 0, usr->password_len);
869                         srp_free(usr->password);
870                 }
871                 srp_free(usr);
872         }
873
874         return 0;
875 }
876
877 void srp_user_delete(struct SRPUser *usr)
878 {
879         if (usr) {
880                 mpz_clear(usr->a);
881                 mpz_clear(usr->A);
882                 mpz_clear(usr->S);
883
884                 delete_ng(usr->ng);
885
886                 memset(usr->password, 0, usr->password_len);
887
888                 srp_free(usr->username);
889                 srp_free(usr->username_verifier);
890                 srp_free(usr->password);
891
892                 if (usr->bytes_A) srp_free(usr->bytes_A);
893
894                 memset(usr, 0, sizeof(*usr));
895                 srp_free(usr);
896         }
897 }
898
899 int srp_user_is_authenticated(struct SRPUser *usr)
900 {
901         return usr->authenticated;
902 }
903
904 const char *srp_user_get_username(struct SRPUser *usr)
905 {
906         return usr->username;
907 }
908
909 const unsigned char *srp_user_get_session_key(struct SRPUser *usr, size_t *key_length)
910 {
911         if (key_length) *key_length = hash_length(usr->hash_alg);
912         return usr->session_key;
913 }
914
915 size_t srp_user_get_session_key_length(struct SRPUser *usr)
916 {
917         return hash_length(usr->hash_alg);
918 }
919
920 // clang-format off
921 /* Output: username, bytes_A, len_A */
922 SRP_Result srp_user_start_authentication(struct SRPUser *usr, char **username,
923         const unsigned char *bytes_a, size_t len_a,
924         unsigned char **bytes_A, size_t *len_A)
925 {
926         // clang-format on
927         if (bytes_a) {
928                 mpz_from_bin(bytes_a, len_a, usr->a);
929         } else {
930                 if (!mpz_fill_random(usr->a)) goto error_and_exit;
931         }
932
933         mpz_powm(usr->A, usr->ng->g, usr->a, usr->ng->N);
934
935         *len_A = mpz_num_bytes(usr->A);
936         *bytes_A = (unsigned char *)srp_alloc(*len_A);
937
938         if (!*bytes_A) goto error_and_exit;
939
940         mpz_to_bin(usr->A, *bytes_A);
941
942         usr->bytes_A = *bytes_A;
943         if (username) *username = usr->username;
944
945         return SRP_OK;
946
947 error_and_exit:
948         *len_A = 0;
949         *bytes_A = 0;
950         *username = 0;
951         return SRP_ERR;
952 }
953
954 // clang-format off
955 /* Output: bytes_M. Buffer length is SHA512_DIGEST_LENGTH */
956 void  srp_user_process_challenge(struct SRPUser *usr,
957         const unsigned char *bytes_s, size_t len_s,
958         const unsigned char *bytes_B, size_t len_B,
959         unsigned char **bytes_M, size_t *len_M)
960 {
961         mpz_t B; mpz_init(B); mpz_from_bin(bytes_B, len_B, B);
962         mpz_t u; mpz_init(u);
963         mpz_t x; mpz_init(x);
964         mpz_t k; mpz_init(k);
965         mpz_t v; mpz_init(v);
966         mpz_t tmp1; mpz_init(tmp1);
967         mpz_t tmp2; mpz_init(tmp2);
968         mpz_t tmp3; mpz_init(tmp3);
969         mpz_t tmp4; mpz_init(tmp4);
970         // clang-format on
971
972         *len_M = 0;
973         *bytes_M = 0;
974
975         if (!H_nn(u, usr->hash_alg, usr->ng->N, usr->A, B)) goto cleanup_and_exit;
976
977         srp_dbg_num(u, "Client calculated u: ");
978
979         if (!calculate_x(x, usr->hash_alg, bytes_s, len_s, usr->username_verifier,
980                         usr->password, usr->password_len))
981                 goto cleanup_and_exit;
982
983         srp_dbg_num(x, "Client calculated x: ");
984
985         if (!H_nn(k, usr->hash_alg, usr->ng->N, usr->ng->N, usr->ng->g))
986                 goto cleanup_and_exit;
987
988         /* SRP-6a safety check */
989         if (mpz_sgn(B) != 0 && mpz_sgn(u) != 0) {
990                 mpz_powm(v, usr->ng->g, x, usr->ng->N);
991
992                 srp_dbg_num(v, "Client calculated v: ");
993
994                 // clang-format off
995                 /* S = (B - k*(g^x)) ^ (a + ux) */
996                 mpz_mul(tmp1, u, x);
997                 mpz_add(tmp2, usr->a, tmp1);               /* tmp2 = (a + ux)      */
998                 mpz_powm(tmp1, usr->ng->g, x, usr->ng->N); /* tmp1 = g^x           */
999                 mpz_mulm(tmp3, k, tmp1, usr->ng->N, tmp4); /* tmp3 = k*(g^x)       */
1000                 mpz_subm(tmp1, B, tmp3, usr->ng->N, tmp4); /* tmp1 = (B - K*(g^x)) */
1001                 mpz_powm(usr->S, tmp1, tmp2, usr->ng->N);
1002                 // clang-format on
1003
1004                 if (!hash_num(usr->hash_alg, usr->S, usr->session_key)) goto cleanup_and_exit;
1005
1006                 if (!calculate_M(usr->hash_alg, usr->ng, usr->M, usr->username, bytes_s, len_s,
1007                                 usr->A, B, usr->session_key))
1008                         goto cleanup_and_exit;
1009                 if (!calculate_H_AMK(usr->hash_alg, usr->H_AMK, usr->A, usr->M, usr->session_key))
1010                         goto cleanup_and_exit;
1011
1012                 *bytes_M = usr->M;
1013                 if (len_M) *len_M = hash_length(usr->hash_alg);
1014         } else {
1015                 *bytes_M = NULL;
1016                 if (len_M) *len_M = 0;
1017         }
1018
1019 cleanup_and_exit:
1020         mpz_clear(B);
1021         mpz_clear(u);
1022         mpz_clear(x);
1023         mpz_clear(k);
1024         mpz_clear(v);
1025         mpz_clear(tmp1);
1026         mpz_clear(tmp2);
1027         mpz_clear(tmp3);
1028         mpz_clear(tmp4);
1029 }
1030
1031 void srp_user_verify_session(struct SRPUser *usr, const unsigned char *bytes_HAMK)
1032 {
1033         if (memcmp(usr->H_AMK, bytes_HAMK, hash_length(usr->hash_alg)) == 0)
1034                 usr->authenticated = 1;
1035 }