1 /*
2 * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include "internal/cryptlib.h"
11 #include <openssl/opensslconf.h>
12 #include "crypto/rand_pool.h"
13 #include "prov/seeding.h"
14
15
16 #ifdef OPENSSL_RAND_SEED_RDCPU
17 #include "crypto/arm_arch.h"
18
19 size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len);
20
21 static size_t get_hardware_random_value(unsigned char *buf, size_t len);
22
23 /*
24 * Acquire entropy using Arm-specific cpu instructions
25 *
26 * Uses the RNDRRS instruction. RNDR is never needed since
27 * RNDRRS will always be available if RNDR is an available
28 * instruction.
29 *
30 * Returns the total entropy count, if it exceeds the requested
31 * entropy count. Otherwise, returns an entropy count of 0.
32 */
ossl_prov_acquire_entropy_from_cpu(RAND_POOL * pool)33 size_t ossl_prov_acquire_entropy_from_cpu(RAND_POOL *pool)
34 {
35 size_t bytes_needed;
36 unsigned char *buffer;
37
38 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
39 if (bytes_needed > 0) {
40 buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
41
42 if (buffer != NULL) {
43 if (get_hardware_random_value(buffer, bytes_needed) == bytes_needed)
44 ossl_rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
45 else
46 ossl_rand_pool_add_end(pool, 0, 0);
47 }
48 }
49
50 return ossl_rand_pool_entropy_available(pool);
51 }
52
get_hardware_random_value(unsigned char * buf,size_t len)53 static size_t get_hardware_random_value(unsigned char *buf, size_t len)
54 {
55 /* Always use RNDRRS or nothing */
56 if (OPENSSL_armcap_P & ARMV8_RNG) {
57 if (OPENSSL_rndrrs_bytes(buf, len) != len)
58 return 0;
59 } else {
60 return 0;
61 }
62 return len;
63 }
64
65 #else
66 NON_EMPTY_TRANSLATION_UNIT
67 #endif /* OPENSSL_RAND_SEED_RDCPU */
68