summaryrefslogtreecommitdiff
path: root/crypto/apr_crypto_prng.c
blob: 820c11bafcb9221d3cbce3f88ba447e8fe501ba1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Cryptographic Pseudo Random Number Generator (CPRNG), based on
 * "Fast-key-erasure random-number generators" from D.J. Bernstein ([1]),
 * and public domain implementation in libpqcrypto's randombytes() ([2]).
 *
 * The CPRNG key is changed as soon as it's used to initialize the stream
 * cipher, so it never resides in memory at the same time as the keystream
 * it produced (a.k.a. the random bytes, which for efficiency are pooled).
 *
 * Likewise, the keystream is always cleared from the internal state before
 * being returned to the user, thus there is no way to recover the produced
 * random bytes afterward (e.g. from a memory/core dump after a crash).
 *
 * IOW, this CPRNG ensures forward secrecy, one may want to run it in a process
 * and/or environment protected from live memory eavesdropping, thus keep the
 * pooled/future random bytes secret by design, and use it as a replacement
 * for some blocking/inefficient system RNG. The random bytes could then be
 * serviced through a named pipe/socket, RPC, or any specific API. This is
 * outside the scope of this/below code, though.
 *
 * [1] https://blog.cr.yp.to/20170723-random.html
 * [2] https://libpqcrypto.org/
 */

#include "apu.h"

#include "apr_crypto.h"
#include "apr_crypto_internal.h"

#include "apr_strings.h"

#if APU_HAVE_CRYPTO
#if APU_HAVE_CRYPTO_PRNG

#include "apr_ring.h"
#include "apr_pools.h"
#include "apr_thread_mutex.h"
#include "apr_thread_proc.h"

#include <stdlib.h> /* for malloc() */

#if APU_HAVE_OPENSSL
/** Recommended prng driver for this platform */
#define APU_CRYPTO_PRNG_RECOMMENDED_DRIVER "openssl"
#endif

/* Be consistent with the .h (the seed is xor-ed with key on reseed). */
#if CPRNG_KEY_SIZE != APR_CRYPTO_PRNG_SEED_SIZE
#error apr_crypto_prng handles stream ciphers with 256bit keys only
#endif

#define CPRNG_BUF_SIZE_MIN (CPRNG_KEY_SIZE * (8 - 1))
#define CPRNG_BUF_SIZE_DEF (CPRNG_KEY_SIZE * (24 - 1))

APR_TYPEDEF_STRUCT(apr_crypto_t,
    apr_pool_t *pool;
    apr_crypto_driver_t *provider;
)

struct apr_crypto_prng_t {
    APR_RING_ENTRY(apr_crypto_prng_t) link;
    apr_pool_t *pool;
    apr_crypto_t *crypto;
    cprng_stream_ctx_t *ctx;
#if APR_HAS_THREADS
    apr_thread_mutex_t *mutex;
#endif
    unsigned char *key, *buf;
    apr_size_t len, pos;
    int flags;
    apr_crypto_cipher_e cipher;
};

static apr_crypto_prng_t *cprng_global = NULL;
static APR_RING_HEAD(apr_cprng_ring, apr_crypto_prng_t) *cprng_ring;

#if APR_HAS_THREADS
static apr_thread_mutex_t *cprng_ring_mutex;

static apr_threadkey_t *cprng_thread_key = NULL;

#define cprng_lock(g) \
    if ((g)->mutex) \
        apr_thread_mutex_lock((g)->mutex)

#define cprng_unlock(g) \
    if ((g)->mutex) \
        apr_thread_mutex_unlock((g)->mutex)

#define cprng_ring_lock() \
    if (cprng_ring_mutex) \
        apr_thread_mutex_lock(cprng_ring_mutex)

#define cprng_ring_unlock() \
    if (cprng_ring_mutex) \
        apr_thread_mutex_unlock(cprng_ring_mutex)

static void cprng_thread_destroy(void *cprng)
{
    apr_threadkey_private_set(NULL, cprng_thread_key);
    if (cprng) {
        apr_crypto_prng_destroy(cprng);
    }
    if (!cprng_global) {
        apr_threadkey_private_delete(cprng_thread_key);
        cprng_thread_key = NULL;
    }
}

#else  /* !APR_HAS_THREADS */
#define cprng_lock(g)
#define cprng_unlock(g)
#define cprng_ring_lock()
#define cprng_ring_unlock()
#endif /* !APR_HAS_THREADS */

APR_DECLARE(apr_status_t) apr_crypto_prng_init(apr_pool_t *pool, apr_crypto_t *crypto,
        apr_crypto_cipher_e cipher, apr_size_t bufsize, const unsigned char seed[], int flags)
{
    apr_status_t rv;

    if (cprng_global) {
        return APR_EREINIT;
    }

    cprng_ring = apr_palloc(pool, sizeof(*cprng_ring));
    if (!cprng_ring) {
        return APR_ENOMEM;
    }
    APR_RING_INIT(cprng_ring, apr_crypto_prng_t, link);

    if (flags & APR_CRYPTO_PRNG_PER_THREAD) {
#if !APR_HAS_THREADS
        return APR_ENOTIMPL;
#else
        rv = apr_threadkey_private_create(&cprng_thread_key,
                                          cprng_thread_destroy, pool);
        if (rv != APR_SUCCESS) {
            return rv;
        }
#endif
    }

#if APR_HAS_THREADS
    rv = apr_thread_mutex_create(&cprng_ring_mutex, APR_THREAD_MUTEX_DEFAULT,
                                 pool);
    if (rv != APR_SUCCESS) {
        if (flags & APR_CRYPTO_PRNG_PER_THREAD) {
            apr_threadkey_private_delete(cprng_thread_key);
            cprng_thread_key = NULL;
        }
        return rv;
    }

    /* Global CPRNG is locked (and obviously not per-thread) */
    flags = (flags | APR_CRYPTO_PRNG_LOCKED) & ~APR_CRYPTO_PRNG_PER_THREAD;
#endif

    rv = apr_crypto_prng_create(&cprng_global, crypto, cipher, bufsize, flags,
                                seed, pool);
    if (rv != APR_SUCCESS) {
        if (flags & APR_CRYPTO_PRNG_PER_THREAD) {
            apr_threadkey_private_delete(cprng_thread_key);
            cprng_thread_key = NULL;
        }
        return rv;
    }

    return APR_SUCCESS;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_term(void)
{
    if (!cprng_global) {
        return APR_EINIT;
    }

    apr_crypto_prng_destroy(cprng_global);
    cprng_global = NULL;

    return APR_SUCCESS;
}

APR_DECLARE(apr_status_t) apr_crypto_random_bytes(void *buf, apr_size_t len)
{
    if (!cprng_global) {
        return APR_EINIT;
    }

    return apr_crypto_prng_bytes(cprng_global, buf, len);
}

#if APR_HAS_THREADS
APR_DECLARE(apr_status_t) apr_crypto_random_thread_bytes(void *buf,
                                                         apr_size_t len)
{
    apr_status_t rv;
    apr_crypto_prng_t *cprng;
    void *private = NULL;

    if (!cprng_thread_key || !cprng_global) {
        return APR_EINIT;
    }

    rv = apr_threadkey_private_get(&private, cprng_thread_key);
    if (rv != APR_SUCCESS) {
        return rv;
    }

    cprng = private;
    if (!cprng) {
        rv = apr_crypto_prng_create(&cprng, cprng_global->crypto, cprng_global->cipher, 0,
                APR_CRYPTO_PRNG_PER_THREAD, NULL, NULL);
        if (rv != APR_SUCCESS) {
            return rv;
        }

        rv = apr_threadkey_private_set(cprng, cprng_thread_key);
        if (rv != APR_SUCCESS) {
            apr_crypto_prng_destroy(cprng);
            return rv;
        }
    }

    return apr_crypto_prng_bytes(cprng, buf, len);
}
#endif

static apr_status_t cprng_cleanup(void *arg)
{
    apr_crypto_prng_t *cprng = arg;

    if (cprng == cprng_global) {
        cprng_global = NULL;
#if APR_HAS_THREADS
        cprng_ring_mutex = NULL;
#endif
        cprng_ring = NULL;
    }
    else if (cprng_global && !(cprng->flags & APR_CRYPTO_PRNG_PER_THREAD)) {
        cprng_ring_lock();
        APR_RING_REMOVE(cprng, link);
        cprng_ring_unlock();
    }

    if (cprng->ctx) {
        cprng->crypto->provider->cprng_stream_ctx_free(cprng->ctx);
    }

    if (cprng->key) {
        apr_memzero_explicit(cprng->key, CPRNG_KEY_SIZE + cprng->len);
    }

    if (!cprng->pool) {
        free(cprng->key);
        free(cprng);
    }

    return APR_SUCCESS;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_create(apr_crypto_prng_t **pcprng,
        apr_crypto_t *crypto, apr_crypto_cipher_e cipher, apr_size_t bufsize, int flags,
        const unsigned char seed[], apr_pool_t *pool)
{
    apr_status_t rv;
    apr_crypto_prng_t *cprng;

    *pcprng = NULL;

    if (!cprng_global && pcprng != &cprng_global) {
        return APR_EINIT;
    }

    if (bufsize > APR_INT32_MAX - CPRNG_KEY_SIZE
            || (flags & APR_CRYPTO_PRNG_LOCKED && !pool)
            || (flags & ~APR_CRYPTO_PRNG_MASK)) {
        return APR_EINVAL;
    }

#if !APR_HAS_THREADS
    if (flags & (APR_CRYPTO_PRNG_LOCKED | APR_CRYPTO_PRNG_PER_THREAD)) {
        return APR_ENOTIMPL;
    }
#endif

    if (pool) {
        cprng = apr_pcalloc(pool, sizeof(*cprng));
    }
    else {
        cprng = calloc(1, sizeof(*cprng));
    }
    if (!cprng) {
        return APR_ENOMEM;
    }
    cprng->cipher = cipher;
    cprng->flags = flags;
    cprng->pool = pool;

    if (bufsize == 0) {
        bufsize = CPRNG_BUF_SIZE_DEF;
    }
    else if (bufsize < CPRNG_BUF_SIZE_MIN) {
        bufsize = CPRNG_BUF_SIZE_MIN;
    }
    else if (bufsize % CPRNG_KEY_SIZE) {
        bufsize += CPRNG_KEY_SIZE;
        bufsize -= bufsize % CPRNG_KEY_SIZE;
    }
    if (pool) {
        cprng->key = apr_palloc(pool, CPRNG_KEY_SIZE + bufsize);
    }
    else {
        cprng->key = malloc(CPRNG_KEY_SIZE + bufsize);
    }
    if (!cprng->key) {
        cprng_cleanup(cprng);
        return APR_ENOMEM;
    }
    cprng->buf = cprng->key + CPRNG_KEY_SIZE;
    cprng->len = bufsize;

    if (crypto) {
        cprng->crypto = crypto;
    }
    else if (cprng_global && cprng_global->crypto) {
        cprng->crypto = cprng_global->crypto;
    }
#ifdef APU_CRYPTO_PRNG_RECOMMENDED_DRIVER
    else {
        const apr_crypto_driver_t *driver = NULL;
        if (!pool) {
            return APR_EINVAL;
        }

        rv = apr_crypto_init(pool);
        if (rv != APR_SUCCESS) {
            cprng_cleanup(cprng);
            return rv;
        }

        rv = apr_crypto_get_driver(&driver, APU_CRYPTO_PRNG_RECOMMENDED_DRIVER,
                NULL, NULL, pool);
        if (rv != APR_SUCCESS) {
            cprng_cleanup(cprng);
            return rv;
        }

        rv = apr_crypto_make(&cprng->crypto, driver, NULL, pool);
        if (rv != APR_SUCCESS) {
            cprng_cleanup(cprng);
            return rv;
        }
    }
#else
    else {
        return APR_ENOTIMPL;
    }
#endif

    rv = cprng->crypto->provider->cprng_stream_ctx_make(&cprng->ctx,
            cprng->crypto, cprng->cipher, pool);
    if (rv != APR_SUCCESS) {
        cprng_cleanup(cprng);
        return rv;
    }

    if (seed) {
        memset(cprng->key, 0, CPRNG_KEY_SIZE);
    }
    rv = apr_crypto_prng_reseed(cprng, seed);
    if (rv != APR_SUCCESS) {
        cprng_cleanup(cprng);
        return rv;
    }

#if APR_HAS_THREADS
    if (flags & APR_CRYPTO_PRNG_LOCKED) {
        rv = apr_thread_mutex_create(&cprng->mutex, APR_THREAD_MUTEX_DEFAULT,
                                     pool);
        if (rv != APR_SUCCESS) {
            cprng_cleanup(cprng);
            return rv;
        }
    }
#endif

    if (cprng_global && !(flags & APR_CRYPTO_PRNG_PER_THREAD)) {
        cprng_ring_lock();
        APR_RING_INSERT_TAIL(cprng_ring, cprng, apr_crypto_prng_t, link);
        cprng_ring_unlock();
    }
    else {
        APR_RING_ELEM_INIT(cprng, link);
    }

    if (pool) {
        apr_pool_cleanup_register(pool, cprng, cprng_cleanup,
                                  apr_pool_cleanup_null);
    }

    *pcprng = cprng;
    return APR_SUCCESS;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_destroy(apr_crypto_prng_t *cprng)
{
    if (!cprng->pool) {
        return cprng_cleanup(cprng);
    }

    return apr_pool_cleanup_run(cprng->pool, cprng, cprng_cleanup);
}

static apr_status_t cprng_stream_bytes(apr_crypto_prng_t *cprng,
                                       void *to, apr_size_t len)
{
    apr_status_t rv;

    rv = cprng->crypto->provider->cprng_stream_ctx_bytes(&cprng->ctx,
            cprng->key, to, len, cprng->buf);
    if (rv != APR_SUCCESS && len) {
        apr_memzero_explicit(to, len);
    }
    return rv;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_reseed(apr_crypto_prng_t *cprng,
                                                 const unsigned char seed[])
{
    apr_status_t rv = APR_SUCCESS;

    if (!cprng) {
        /* Fall through with global CPRNG. */
        cprng = cprng_global;
        if (!cprng) {
            return APR_EINIT;
        }
    }

    cprng_lock(cprng);

    cprng->pos = cprng->len;
    apr_memzero_explicit(cprng->buf, cprng->len);
    if (seed) {
        apr_size_t n = 0;
        do {
            cprng->key[n] ^= seed[n];
        } while (++n < CPRNG_KEY_SIZE);
    }
    else if (cprng_global && cprng_global != cprng) {
        /* Use the global CPRNG: no need for more than the initial entropy. */
        rv = apr_crypto_random_bytes(cprng->key, CPRNG_KEY_SIZE);
    }
    else {
        /* Use the system entropy, i.e. one of "/dev/[u]random", getrandom(),
         * arc4random()... This may block but still we really want to wait for
         * the system to gather enough entropy for these 32 initial bytes, much
         * more than we want non-random bytes, and that's once and for all!
         */
        rv = apr_generate_random_bytes(cprng->key, CPRNG_KEY_SIZE);
    }
    if (rv == APR_SUCCESS) {
        /* Init/set the stream with the new key, without buffering for now
         * so that the buffer and/or the next random bytes won't be generated
         * directly from this key but from the first stream bytes it generates,
         * i.e. the next key is always extracted from the stream cipher state
         * and cleared upon use.
         */
        rv = cprng_stream_bytes(cprng, NULL, 0);
    }

    cprng_unlock(cprng);

    return rv;
}

static apr_status_t cprng_bytes(apr_crypto_prng_t *cprng,
                                void *buf, apr_size_t len)
{
    unsigned char *ptr = buf;
    apr_status_t rv;
    apr_size_t n;

    while (len) {
        n = cprng->len - cprng->pos;
        if (n == 0) {
            n = cprng->len;
            if (len >= n) {
                do {
                    rv = cprng_stream_bytes(cprng, ptr, n);
                    if (rv != APR_SUCCESS) {
                        return rv;
                    }
                    ptr += n;
                    len -= n;
                } while (len >= n);
                if (!len) {
                    break;
                }
            }
            rv = cprng_stream_bytes(cprng, cprng->buf, n);
            if (rv != APR_SUCCESS) {
                return rv;
            }
            cprng->pos = 0;
        }
        if (n > len) {
            n = len;
        }

        /* Random bytes are consumed then zero-ed to ensure
         * both forward secrecy and cleared next mixed data.
         */
        memcpy(ptr, cprng->buf + cprng->pos, n);
        apr_memzero_explicit(cprng->buf + cprng->pos, n);
        cprng->pos += n;

        ptr += n;
        len -= n;
    }

    return APR_SUCCESS;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_bytes(apr_crypto_prng_t *cprng,
                                                void *buf, apr_size_t len)
{
    apr_status_t rv;

    if (!cprng) {
        /* Fall through with global CPRNG. */
        cprng = cprng_global;
        if (!cprng) {
            return APR_EINIT;
        }
    }

    cprng_lock(cprng);

    rv = cprng_bytes(cprng, buf, len);

    cprng_unlock(cprng);

    return rv;
}

APR_DECLARE(apr_status_t) apr_crypto_prng_rekey(apr_crypto_prng_t *cprng)
{
    apr_status_t rv;

    if (!cprng) {
        /* Fall through with global CPRNG. */
        cprng = cprng_global;
        if (!cprng) {
            return APR_EINIT;
        }
    }

    cprng_lock(cprng);

    /* Clear state and renew the key. */
    cprng->pos = cprng->len;
    apr_memzero_explicit(cprng->buf, cprng->len);
    rv = cprng_stream_bytes(cprng, NULL, 0);

    cprng_unlock(cprng);

    if (cprng == cprng_global) {
        /* Forward to all maintained CPRNGs. */
        cprng_ring_lock();
        for (cprng = APR_RING_FIRST(cprng_ring);
             cprng != APR_RING_SENTINEL(cprng_ring, apr_crypto_prng_t, link);
             cprng = APR_RING_NEXT(cprng, link)) {
            apr_status_t rt = apr_crypto_prng_rekey(cprng);
            if (rt != APR_SUCCESS && rv == APR_SUCCESS) {
                rv = rt;
            }
        }
        cprng_ring_unlock();
    }

    return rv;
}

#if APR_HAS_FORK
APR_DECLARE(apr_status_t) apr_crypto_prng_after_fork(apr_crypto_prng_t *cprng,
                                                     int flags)
{
    apr_status_t rv = APR_SUCCESS;
    int is_child = flags & APR_CRYPTO_FORK_INCHILD;

    if (!cprng) {
        /* Fall through with global CPRNG. */
        cprng = cprng_global;
        if (!cprng) {
            return APR_EINIT;
        }
    }

    cprng_lock(cprng);

    /* Make sure the parent and child processes never share the same state,
     * and that further fork()s from either process will not either.
     * This is done by rekeying (and clearing the buffers) in both processes,
     * and by rekeying a second time in the parent process to ensure both that
     * keys are different and that after apr_crypto_prng_after_fork() is called
     * the keys are unknown to each other processes.
     * The new key to be used by the parent process is generated in the same
     * pass as the rekey, and since cprng_stream_bytes() is designed to burn
     * and never reuse keys we are sure that this key is unique to the parent,
     * and that nothing is left over from the initial state in both processes.
     */
    cprng->pos = cprng->len;
    apr_memzero_explicit(cprng->buf, cprng->len);
    if (!is_child) {
        rv = cprng_stream_bytes(cprng, cprng->key, CPRNG_KEY_SIZE);
    }
    if (rv == APR_SUCCESS) {
        rv = cprng_stream_bytes(cprng, NULL, 0);
    }

    cprng_unlock(cprng);

    if (cprng == cprng_global) {
        /* Forward to all maintained CPRNGs. */
        cprng_ring_lock();
        for (cprng = APR_RING_FIRST(cprng_ring);
             cprng != APR_RING_SENTINEL(cprng_ring, apr_crypto_prng_t, link);
             cprng = APR_RING_NEXT(cprng, link)) {
            apr_status_t rt = apr_crypto_prng_after_fork(cprng, flags);
            if (rt != APR_SUCCESS && rv == APR_SUCCESS) {
                rv = rt;
            }
        }
        cprng_ring_unlock();
    }

    return rv;
}
#endif /* APR_HAS_FORK */

#endif /* APU_HAVE_CRYPTO_PRNG */
#endif /* APU_HAVE_CRYPTO */