]> de.git.xonotic.org Git - xonotic/d0_blind_id.git/blob - d0_bignum-openssl.c
implement RNG seeding and mutexes for OpenSSL, they may be slower than necessary...
[xonotic/d0_blind_id.git] / d0_bignum-openssl.c
1 /*
2  * FILE:        d0_bignum-openssl.c
3  * AUTHOR:      Rudolf Polzer - divVerent@xonotic.org
4  * 
5  * Copyright (c) 2010, Rudolf Polzer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the copyright holder nor the names of contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  * 
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Format:commit %H$
33  * $Id$
34  */
35
36 /* NOTE: this file links against openssl (http://www.openssl.org), which is
37  * under the OpenSSL License. You may have to abide to its terms too if you use
38  * this file.
39  * To alternatively link to GMP, provide the option --without-openssl to
40  * ./configure.
41  */
42
43 #include "d0_bignum.h"
44
45 #include <assert.h>
46 #include <string.h>
47 #include <openssl/bn.h>
48 #include <openssl/crypto.h>
49
50 // for stupid OpenSSL versions in Mac OS X
51 #ifndef BN_is_negative
52 #define BN_is_negative(a) ((a)->neg != 0)
53 #define BN_set_negative(a,n) ((a)->neg = ((n) && !BN_is_zero(a)))
54 #endif
55
56 struct d0_bignum_s
57 {
58         BIGNUM z;
59 };
60
61 static d0_bignum_t temp;
62 static BN_CTX *ctx;
63 static void *tempmutex = NULL; // hold this mutex when using ctx or temp
64
65 #include <time.h>
66 #include <stdio.h>
67
68 static void **locks;
69
70 void locking_function(int mode, int l, const char *file, int line)
71 {
72         void *m = locks[l];
73         if(mode & CRYPTO_LOCK)
74                 d0_lockmutex(m);
75         else
76                 d0_unlockmutex(m);
77 }
78
79 typedef struct CRYPTO_dynlock_value
80 {
81         void *m;
82 };
83
84 struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
85 {
86         return (struct CRYPTO_dynlock_value *) d0_createmutex();
87 }
88
89 void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
90 {
91         void *m = (void *) l;
92         if(mode & CRYPTO_LOCK)
93                 d0_lockmutex(m);
94         else
95                 d0_unlockmutex(m);
96 }
97
98 void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
99 {
100         void *m = (void *) l;
101         d0_destroymutex(l);
102 }
103
104 D0_WARN_UNUSED_RESULT D0_BOOL d0_bignum_INITIALIZE(void)
105 {
106         FILE *f;
107         D0_BOOL ret = 1;
108         unsigned char buf[256];
109         int i, n;
110
111         tempmutex = d0_createmutex();
112         d0_lockmutex(tempmutex);
113
114         n = CRYPTO_num_locks();
115         locks = d0_malloc(n * sizeof(*locks));
116         for(i = 0; i < n; ++i)
117                 locks[i] = d0_createmutex();
118
119         CRYPTO_set_locking_callback(locking_function);
120         CRYPTO_set_dynlock_create_callback(dyn_create_function);
121         CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
122         CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
123
124         ctx = BN_CTX_new();
125         d0_bignum_init(&temp);
126
127 #ifdef WIN32
128         {
129                 HCRYPTPROV hCryptProv;
130                 if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
131                 {
132                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
133                         {
134                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
135                                 ret = 0;
136                         }
137                         CryptReleaseContext(hCryptProv, 0);
138                 }
139                 else if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET))
140                 {
141                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
142                         {
143                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
144                                 ret = 0;
145                         }
146                         CryptReleaseContext(hCryptProv, 0);
147                 }
148                 else
149                 {
150                         fprintf(stderr, "WARNING: could not initialize random number generator (CryptAcquireContext failed)\n");
151                         ret = 0;
152                 }
153         }
154 #else
155         f = fopen("/dev/urandom", "rb");
156         if(!f)
157                 f = fopen("/dev/random", "rb");
158         if(f)
159         {
160                 setbuf(f, NULL);
161                 if(fread(buf, sizeof(buf), 1, f) != 1)
162                 {
163                         fprintf(stderr, "WARNING: could not initialize random number generator (read from random device failed)\n");
164                         ret = 0;
165                 }
166                 fclose(f);
167         }
168         else
169         {
170                 fprintf(stderr, "WARNING: could not initialize random number generator (no random device found)\n");
171                 ret = 0;
172         }
173 #endif
174         RAND_add(buf, sizeof(buf), sizeof(buf));
175
176         d0_unlockmutex(tempmutex);
177
178         return 1;
179         // FIXME initialize the RNG on Windows on UNIX it is done right already
180 }
181
182 void d0_bignum_SHUTDOWN(void)
183 {
184         int i, n;
185
186         d0_lockmutex(tempmutex);
187
188         d0_bignum_clear(&temp);
189         BN_CTX_free(ctx);
190         ctx = NULL;
191
192         n = CRYPTO_num_locks();
193         for(i = 0; i < n; ++i)
194                 d0_destroymutex(locks[i]);
195         d0_free(locks);
196
197         d0_unlockmutex(tempmutex);
198         d0_destroymutex(tempmutex);
199         tempmutex = NULL;
200 }
201
202 D0_BOOL d0_iobuf_write_bignum(d0_iobuf_t *buf, const d0_bignum_t *bignum)
203 {
204         static __thread unsigned char numbuf[65536];
205         size_t count = 0;
206         numbuf[0] = BN_is_zero(&bignum->z) ? 0 : BN_is_negative(&bignum->z) ? 3 : 1;
207         if((numbuf[0] & 3) != 0) // nonzero
208         {
209                 count = BN_num_bytes(&bignum->z);
210                 if(count > sizeof(numbuf) - 1)
211                         return 0;
212                 BN_bn2bin(&bignum->z, numbuf+1);
213         }
214         return d0_iobuf_write_packet(buf, numbuf, count + 1);
215 }
216
217 d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum)
218 {
219         static __thread unsigned char numbuf[65536];
220         size_t count = sizeof(numbuf);
221         if(!d0_iobuf_read_packet(buf, numbuf, &count))
222                 return NULL;
223         if(count < 1)
224                 return NULL;
225         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
226         if(numbuf[0] & 3) // nonzero
227         {
228                 BN_bin2bn(numbuf+1, count-1, &bignum->z);
229                 if(numbuf[0] & 2) // negative
230                         BN_set_negative(&bignum->z, 1);
231         }
232         else // zero
233         {
234                 BN_zero(&bignum->z);
235         }
236         return bignum;
237 }
238
239 ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize)
240 {
241         size_t count;
242         count = BN_num_bytes(&bignum->z);
243         if(count > bufsize)
244                 return -1;
245         if(bufsize > count)
246         {
247                 // pad from left (big endian numbers!)
248                 memset(buf, 0, bufsize - count);
249                 buf += bufsize - count;
250         }
251         BN_bn2bin(&bignum->z, buf);
252         return bufsize;
253 }
254
255 d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize)
256 {
257         size_t count;
258         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
259         BN_bin2bn(buf, bufsize, &bignum->z);
260         return bignum;
261 }
262
263 d0_bignum_t *d0_bignum_new(void)
264 {
265         d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t));
266         BN_init(&b->z);
267         return b;
268 }
269
270 void d0_bignum_free(d0_bignum_t *a)
271 {
272         BN_free(&a->z);
273         d0_free(a);
274 }
275
276 void d0_bignum_init(d0_bignum_t *b)
277 {
278         BN_init(&b->z);
279 }
280
281 void d0_bignum_clear(d0_bignum_t *a)
282 {
283         BN_free(&a->z);
284 }
285
286 size_t d0_bignum_size(const d0_bignum_t *r)
287 {
288         return BN_num_bits(&r->z);
289 }
290
291 int d0_bignum_cmp(const d0_bignum_t *a, const d0_bignum_t *b)
292 {
293         return BN_cmp(&a->z, &b->z);
294 }
295
296 d0_bignum_t *d0_bignum_rand_range(d0_bignum_t *r, const d0_bignum_t *min, const d0_bignum_t *max)
297 {
298         if(!r) r = d0_bignum_new(); if(!r) return NULL;
299         d0_lockmutex(tempmutex);
300         BN_sub(&temp.z, &max->z, &min->z);
301         BN_rand_range(&r->z, &temp.z);
302         d0_unlockmutex(tempmutex);
303         BN_add(&r->z, &r->z, &min->z);
304         return r;
305 }
306
307 d0_bignum_t *d0_bignum_rand_bit_atmost(d0_bignum_t *r, size_t n)
308 {
309         if(!r) r = d0_bignum_new(); if(!r) return NULL;
310         BN_rand(&r->z, n, -1, 0);
311         return r;
312 }
313
314 d0_bignum_t *d0_bignum_rand_bit_exact(d0_bignum_t *r, size_t n)
315 {
316         if(!r) r = d0_bignum_new(); if(!r) return NULL;
317         BN_rand(&r->z, n, 0, 0);
318         return r;
319 }
320
321 d0_bignum_t *d0_bignum_zero(d0_bignum_t *r)
322 {
323         if(!r) r = d0_bignum_new(); if(!r) return NULL;
324         BN_zero(&r->z);
325         return r;
326 }
327
328 d0_bignum_t *d0_bignum_one(d0_bignum_t *r)
329 {
330         if(!r) r = d0_bignum_new(); if(!r) return NULL;
331         BN_one(&r->z);
332         return r;
333 }
334
335 d0_bignum_t *d0_bignum_int(d0_bignum_t *r, int n)
336 {
337         if(!r) r = d0_bignum_new(); if(!r) return NULL;
338         BN_set_word(&r->z, n);
339         return r;
340 }
341
342 d0_bignum_t *d0_bignum_mov(d0_bignum_t *r, const d0_bignum_t *a)
343 {
344         if(r == a)
345                 return r; // trivial
346         if(!r) r = d0_bignum_new(); if(!r) return NULL;
347         BN_copy(&r->z, &a->z);
348         return r;
349 }
350
351 d0_bignum_t *d0_bignum_neg(d0_bignum_t *r, const d0_bignum_t *a)
352 {
353         if(!r) r = d0_bignum_new(); if(!r) return NULL;
354         if(r != a)
355                 BN_copy(&r->z, &a->z);
356         BN_set_negative(&r->z, !BN_is_negative(&r->z));
357         return r;
358 }
359
360 d0_bignum_t *d0_bignum_shl(d0_bignum_t *r, const d0_bignum_t *a, ssize_t n)
361 {
362         if(!r) r = d0_bignum_new(); if(!r) return NULL;
363         if(n > 0)
364                 BN_lshift(&r->z, &a->z, n);
365         else if(n < 0)
366                 BN_rshift(&r->z, &a->z, -n);
367         else if(r != a)
368                 BN_copy(&r->z, &a->z);
369         return r;
370 }
371
372 d0_bignum_t *d0_bignum_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
373 {
374         if(!r) r = d0_bignum_new(); if(!r) return NULL;
375         BN_add(&r->z, &a->z, &b->z);
376         return r;
377 }
378
379 d0_bignum_t *d0_bignum_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
380 {
381         if(!r) r = d0_bignum_new(); if(!r) return NULL;
382         BN_sub(&r->z, &a->z, &b->z);
383         return r;
384 }
385
386 d0_bignum_t *d0_bignum_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
387 {
388         if(!r) r = d0_bignum_new(); if(!r) return NULL;
389         d0_lockmutex(tempmutex);
390         BN_mul(&r->z, &a->z, &b->z, ctx);
391         d0_unlockmutex(tempmutex);
392         return r;
393 }
394
395 d0_bignum_t *d0_bignum_divmod(d0_bignum_t *q, d0_bignum_t *m, const d0_bignum_t *a, const d0_bignum_t *b)
396 {
397         if(!q && !m)
398                 m = d0_bignum_new();
399         d0_lockmutex(tempmutex);
400         if(q)
401         {
402                 if(m)
403                         BN_div(&q->z, &m->z, &a->z, &b->z, ctx);
404                 else
405                         BN_div(&q->z, NULL, &a->z, &b->z, ctx);
406                 assert(!"I know this code is broken (rounds towards zero), need handle negative correctly");
407         }
408         else
409                 BN_nnmod(&m->z, &a->z, &b->z, ctx);
410         d0_unlockmutex(tempmutex);
411         if(m)
412                 return m;
413         else
414                 return q;
415 }
416
417 d0_bignum_t *d0_bignum_mod_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
418 {
419         if(!r) r = d0_bignum_new(); if(!r) return NULL;
420         d0_lockmutex(tempmutex);
421         BN_mod_add(&r->z, &a->z, &b->z, &m->z, ctx);
422         d0_unlockmutex(tempmutex);
423         return r;
424 }
425
426 d0_bignum_t *d0_bignum_mod_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
427 {
428         if(!r) r = d0_bignum_new(); if(!r) return NULL;
429         d0_lockmutex(tempmutex);
430         BN_mod_sub(&r->z, &a->z, &b->z, &m->z, ctx);
431         d0_unlockmutex(tempmutex);
432         return r;
433 }
434
435 d0_bignum_t *d0_bignum_mod_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
436 {
437         if(!r) r = d0_bignum_new(); if(!r) return NULL;
438         d0_lockmutex(tempmutex);
439         BN_mod_mul(&r->z, &a->z, &b->z, &m->z, ctx);
440         d0_unlockmutex(tempmutex);
441         return r;
442 }
443
444 d0_bignum_t *d0_bignum_mod_pow(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
445 {
446         if(!r) r = d0_bignum_new(); if(!r) return NULL;
447         d0_lockmutex(tempmutex);
448         BN_mod_exp(&r->z, &a->z, &b->z, &m->z, ctx);
449         d0_unlockmutex(tempmutex);
450         return r;
451 }
452
453 D0_BOOL d0_bignum_mod_inv(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *m)
454 {
455         // here, r MUST be set, as otherwise we cannot return error state!
456         int ret;
457         d0_lockmutex(tempmutex);
458         ret = !!BN_mod_inverse(&r->z, &a->z, &m->z, ctx);
459         d0_unlockmutex(tempmutex);
460         return ret;
461 }
462
463 int d0_bignum_isprime(const d0_bignum_t *r, int param)
464 {
465         int ret;
466         d0_lockmutex(tempmutex);
467         if(param <= 0)
468                 ret = BN_is_prime_fasttest(&r->z, 1, NULL, ctx, NULL, 1);
469         else
470                 ret = BN_is_prime(&r->z, param, NULL, ctx, NULL);
471         d0_unlockmutex(tempmutex);
472         return ret;
473 }
474
475 d0_bignum_t *d0_bignum_gcd(d0_bignum_t *r, d0_bignum_t *s, d0_bignum_t *t, const d0_bignum_t *a, const d0_bignum_t *b)
476 {
477         if(!r) r = d0_bignum_new(); if(!r) return NULL;
478         if(s)
479                 assert(!"Extended gcd not implemented");
480         else if(t)
481                 assert(!"Extended gcd not implemented");
482         else
483         {
484                 d0_lockmutex(tempmutex);
485                 BN_gcd(&r->z, &a->z, &b->z, ctx);
486                 d0_unlockmutex(tempmutex);
487         }
488         return r;
489 }
490
491 char *d0_bignum_tostring(const d0_bignum_t *x, unsigned int base)
492 {
493         if(base == 10)
494                 return BN_bn2dec(&x->z);
495         else if(base == 16)
496                 return BN_bn2hex(&x->z);
497         else
498                 assert(!"Other bases not implemented");
499 }