summaryrefslogtreecommitdiff
path: root/crypto/apr_crypto_prng.c
blob: 178f581649f984c7b7266df4f29a23958caee1e6 (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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/* 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"

#if APU_HAVE_CRYPTO
#if APU_HAVE_CRYPTO_PRNG

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

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

#define CPRNG_KEY_SIZE 32

/* 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))

#if APU_HAVE_OPENSSL

#include <openssl/evp.h>
#include <openssl/sha.h>

/* We only handle Chacha20 and AES256-CTR stream ciphers, for now.
 * AES256-CTR should be in any openssl version of this century but is used
 * only if Chacha20 is missing (openssl < 1.1). This is because Chacha20 is
 * fast (enough) in software and timing attacks safe, though AES256-CTR can
 * be faster and constant-time but only when the CPU (aesni) or some crypto
 * hardware are in the place.
 */
#include <openssl/obj_mac.h> /* for NID_* */
#if !defined(NID_chacha20) && !defined(NID_aes_256_ctr)
/* XXX: APU_HAVE_CRYPTO_PRNG && APU_HAVE_OPENSSL shoudn't be defined! */
#error apr_crypto_prng needs OpenSSL implementation for Chacha20 or AES256-CTR
#endif

typedef EVP_CIPHER_CTX cprng_stream_ctx_t;

static apr_status_t cprng_lib_init(apr_pool_t *pool)
{
    return apr_crypto_lib_init("openssl", NULL, NULL, pool);
}

static apr_status_t cprng_stream_ctx_make(cprng_stream_ctx_t **pctx)
{
    EVP_CIPHER_CTX *ctx;
    const EVP_CIPHER *cipher;

    ctx = EVP_CIPHER_CTX_new();
    if (!ctx) {
        return APR_ENOMEM;
    }

#if defined(NID_chacha20)
    cipher = EVP_chacha20();
#else
    cipher = EVP_aes_256_ctr();
#endif
    if (EVP_EncryptInit_ex(ctx, cipher, NULL, NULL, NULL) <= 0) {
        EVP_CIPHER_CTX_free(ctx);
        return APR_ENOMEM;
    }

    *pctx = ctx;
    return APR_SUCCESS;
}

static APR_INLINE
void cprng_stream_ctx_free(cprng_stream_ctx_t *ctx)
{
    EVP_CIPHER_CTX_free(ctx);
}

static APR_INLINE
void cprng_stream_setkey(cprng_stream_ctx_t *ctx,
                         const unsigned char *key,
                         const unsigned char *iv)
{
#if defined(NID_chacha20)
    /* With CHACHA20, iv=NULL is the same as zeros but it's faster
     * to (re-)init; use that for efficiency.
     */
    EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL);
#else
    /* With AES256-CTR, iv=NULL seems to peek up and random one (for
     * the initial CTR), while we can live with zeros (fixed CTR);
     * efficiency still.
     */
    EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv);
#endif
}

static APR_INLINE
apr_status_t cprng_stream_ctx_bytes(cprng_stream_ctx_t **pctx,
                                    unsigned char *key, int rekey,
                                    unsigned char *to, apr_size_t n,
                                    const unsigned char *z)
{
    cprng_stream_ctx_t *ctx = *pctx;
    int len;

    /* We never encrypt twice with the same key, so no IV is needed (can
     * be zeros). When EVP_EncryptInit() is called multiple times it clears
     * its previous resources approprietly, and since we don't want the key
     * and its keystream to reside in memory at the same time, we have to
     * EVP_EncryptInit() twice: firstly to set the key and then finally to
     * overwrite the key (with zeros) after the keystream is produced.
     * As for EVP_EncryptFinish(), we don't need it either because padding
     * is disabled (irrelevant for a stream cipher).
     */
    cprng_stream_setkey(ctx, key, z);
    EVP_CIPHER_CTX_set_padding(ctx, 0);
    if (rekey) {
        memset(key, 0, CPRNG_KEY_SIZE);
        EVP_EncryptUpdate(ctx, key, &len, key, CPRNG_KEY_SIZE);
    }
    if (n) {
        EVP_EncryptUpdate(ctx, to, &len, z, n);
    }
    cprng_stream_setkey(ctx, z, z);

    return APR_SUCCESS;
}

#else /* APU_HAVE_OPENSSL */

/* XXX: APU_HAVE_CRYPTO_PRNG shoudn't be defined! */
#error apr_crypto_prng implemented with OpenSSL only for now

#endif /* APU_HAVE_OPENSSL */

struct apr_crypto_prng_t {
    APR_RING_ENTRY(apr_crypto_prng_t) link;
    apr_pool_t *pool;
    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;
};

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)
{
    if (!cprng_global) {
        apr_threadkey_private_delete(cprng_thread_key);
        cprng_thread_key = NULL;
    }
    apr_crypto_prng_destroy(cprng);
}

#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_size_t bufsize,
                                               const unsigned char seed[],
                                               int flags)
{
    apr_status_t rv;

    if (cprng_global) {
        return APR_EREINIT;
    }

    rv = cprng_lib_init(pool);
    if (rv != APR_SUCCESS && rv != APR_EREINIT) {
        return rv;
    }

    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
    }

    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 APR_HAS_THREADS
    rv = apr_thread_mutex_create(&cprng_ring_mutex, APR_THREAD_MUTEX_DEFAULT,
                                 pool);
    if (rv != APR_SUCCESS) {
        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

    return apr_crypto_prng_create(&cprng_global, bufsize, flags, seed, pool);
}

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) {
        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, 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_stream_ctx_free(cprng->ctx);
    }

    if (cprng->key) {
        apr_crypto_memzero(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_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->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;

    rv = cprng_stream_ctx_make(&cprng->ctx);
    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, size_t len,
                                       int rekey)
{
    apr_status_t rv;

    rv = cprng_stream_ctx_bytes(&cprng->ctx, cprng->key, rekey,
                                to, len, cprng->buf);
    if (rv != APR_SUCCESS && len) {
        apr_crypto_memzero(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_crypto_memzero(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, 1);
    }

    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, 1);
                    if (rv != APR_SUCCESS) {
                        return rv;
                    }
                    ptr += n;
                    len -= n;
                } while (len >= n);
                if (!len) {
                    break;
                }
            }
            rv = cprng_stream_bytes(cprng, cprng->buf, n, 1);
            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_crypto_memzero(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;
}

/* Reset the buffer and use the next stream bytes as the new key. */
static apr_status_t cprng_newkey(apr_crypto_prng_t *cprng, int rekey)
{
    cprng->pos = cprng->len;
    apr_crypto_memzero(cprng->buf, cprng->len);
    return cprng_stream_bytes(cprng, cprng->key, CPRNG_KEY_SIZE, rekey);
}

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);

    /* Renew and apply the new key. */
    rv = cprng_newkey(cprng, 1);

    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 in_child)
{
    apr_status_t rv;

    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, so
     * renew the key first (also clears the buffer) for both parent and child,
     * so that further fork()s (from parent or child) won't use the same state.
     * For the parent process only, renew a second time to ensure that key
     * material is different from the child. Finally parent and child keys will
     * be different and unknown to each other processes.
     */
    rv = cprng_newkey(cprng, in_child);
    if (rv == APR_SUCCESS && !in_child) {
        rv = cprng_stream_bytes(cprng, cprng->key, CPRNG_KEY_SIZE, 1);
    }

    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, in_child);
            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 */