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