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