2 * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
12 * Implementation of the FIPS 140-2 section 4.9.2 Conditional Tests.
16 #include "internal/rand_int.h"
17 #include "internal/thread_once.h"
20 static RAND_POOL
*crngt_pool
;
21 static unsigned char *crngt_prev
;
23 int (*crngt_get_entropy
)(unsigned char *) = &rand_crngt_get_entropy_cb
;
25 int rand_crngt_get_entropy_cb(unsigned char *buf
)
30 while ((n
= rand_pool_acquire_entropy(crngt_pool
)) != 0)
31 if (n
>= CRNGT_BUFSIZ
) {
32 p
= rand_pool_detach(crngt_pool
);
33 memcpy(crngt_prev
, p
, CRNGT_BUFSIZ
);
34 rand_pool_reattach(crngt_pool
, p
);
40 void rand_crngt_cleanup(void)
42 rand_pool_free(crngt_pool
);
43 OPENSSL_secure_free(crngt_prev
);
48 int rand_crngt_init(void)
50 if ((crngt_pool
= rand_pool_new(0, CRNGT_BUFSIZ
, CRNGT_BUFSIZ
)) == NULL
)
52 if ((crngt_prev
= OPENSSL_secure_malloc(CRNGT_BUFSIZ
)) != NULL
53 && crngt_get_entropy(crngt_prev
))
59 static CRYPTO_ONCE rand_crngt_init_flag
= CRYPTO_ONCE_STATIC_INIT
;
60 DEFINE_RUN_ONCE_STATIC(do_rand_crngt_init
)
62 return OPENSSL_init_crypto(0, NULL
)
64 && OPENSSL_atexit(&rand_crngt_cleanup
);
67 int rand_crngt_single_init(void)
69 return RUN_ONCE(&rand_crngt_init_flag
, do_rand_crngt_init
);
72 size_t rand_crngt_get_entropy(RAND_DRBG
*drbg
,
74 int entropy
, size_t min_len
, size_t max_len
,
75 int prediction_resistance
)
77 unsigned char buf
[CRNGT_BUFSIZ
];
79 size_t q
, r
= 0, s
, t
= 0;
82 if (!RUN_ONCE(&rand_crngt_init_flag
, do_rand_crngt_init
))
85 if ((pool
= rand_pool_new(entropy
, min_len
, max_len
)) == NULL
)
88 while ((q
= rand_pool_bytes_needed(pool
, 1)) > 0 && attempts
-- > 0) {
89 s
= q
> sizeof(buf
) ? sizeof(buf
) : q
;
90 if (!crngt_get_entropy(buf
)
91 || memcmp(crngt_prev
, buf
, CRNGT_BUFSIZ
) == 0
92 || !rand_pool_add(pool
, buf
, s
, s
* 8))
94 memcpy(crngt_prev
, buf
, CRNGT_BUFSIZ
);
99 *pout
= rand_pool_detach(pool
);
101 rand_pool_free(pool
);
105 void rand_crngt_cleanup_entropy(RAND_DRBG
*drbg
,
106 unsigned char *out
, size_t outlen
)
108 OPENSSL_secure_clear_free(out
, outlen
);