Path: blob/main/contrib/bearssl/inc/bearssl_rand.h
39586 views
/*1* Copyright (c) 2016 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#ifndef BR_BEARSSL_RAND_H__25#define BR_BEARSSL_RAND_H__2627#include <stddef.h>28#include <stdint.h>2930#include "bearssl_block.h"31#include "bearssl_hash.h"3233#ifdef __cplusplus34extern "C" {35#endif3637/** \file bearssl_rand.h38*39* # Pseudo-Random Generators40*41* A PRNG is a state-based engine that outputs pseudo-random bytes on42* demand. It is initialized with an initial seed, and additional seed43* bytes can be added afterwards. Bytes produced depend on the seeds and44* also on the exact sequence of calls (including sizes requested for45* each call).46*47*48* ## Procedural and OOP API49*50* For the PRNG of name "`xxx`", two API are provided. The _procedural_51* API defined a context structure `br_xxx_context` and three functions:52*53* - `br_xxx_init()`54*55* Initialise the context with an initial seed.56*57* - `br_xxx_generate()`58*59* Produce some pseudo-random bytes.60*61* - `br_xxx_update()`62*63* Inject some additional seed.64*65* The initialisation function sets the first context field (`vtable`)66* to a pointer to the vtable that supports the OOP API. The OOP API67* provides access to the same functions through function pointers,68* named `init()`, `generate()` and `update()`.69*70* Note that the context initialisation method may accept additional71* parameters, provided as a 'const void *' pointer at API level. These72* additional parameters depend on the implemented PRNG.73*74*75* ## HMAC_DRBG76*77* HMAC_DRBG is defined in [NIST SP 800-90A Revision78* 1](http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf).79* It uses HMAC repeatedly, over some configurable underlying hash80* function. In BearSSL, it is implemented under the "`hmac_drbg`" name.81* The "extra parameters" pointer for context initialisation should be82* set to a pointer to the vtable for the underlying hash function (e.g.83* pointer to `br_sha256_vtable` to use HMAC_DRBG with SHA-256).84*85* According to the NIST standard, each request shall produce up to86* 2<sup>19</sup> bits (i.e. 64 kB of data); moreover, the context shall87* be reseeded at least once every 2<sup>48</sup> requests. This88* implementation does not maintain the reseed counter (the threshold is89* too high to be reached in practice) and does not object to producing90* more than 64 kB in a single request; thus, the code cannot fail,91* which corresponds to the fact that the API has no room for error92* codes. However, this implies that requesting more than 64 kB in one93* `generate()` request, or making more than 2<sup>48</sup> requests94* without reseeding, is formally out of NIST specification. There is95* no currently known security penalty for exceeding the NIST limits,96* and, in any case, HMAC_DRBG usage in implementing SSL/TLS always97* stays much below these thresholds.98*99*100* ## AESCTR_DRBG101*102* AESCTR_DRBG is a custom PRNG based on AES-128 in CTR mode. This is103* meant to be used only in situations where you are desperate for104* speed, and have an hardware-optimized AES/CTR implementation. Whether105* this will yield perceptible improvements depends on what you use the106* pseudorandom bytes for, and how many you want; for instance, RSA key107* pair generation uses a substantial amount of randomness, and using108* AESCTR_DRBG instead of HMAC_DRBG yields a 15 to 20% increase in key109* generation speed on a recent x86 CPU (Intel Core i7-6567U at 3.30 GHz).110*111* Internally, it uses CTR mode with successive counter values, starting112* at zero (counter value expressed over 128 bits, big-endian convention).113* The counter is not allowed to reach 32768; thus, every 32768*16 bytes114* at most, the `update()` function is run (on an empty seed, if none is115* provided). The `update()` function computes the new AES-128 key by116* applying a custom hash function to the concatenation of a state-dependent117* word (encryption of an all-one block with the current key) and the new118* seed. The custom hash function uses Hirose's construction over AES-256;119* see the comments in `aesctr_drbg.c` for details.120*121* This DRBG does not follow an existing standard, and thus should be122* considered as inadequate for production use until it has been properly123* analysed.124*/125126/**127* \brief Class type for PRNG implementations.128*129* A `br_prng_class` instance references the methods implementing a PRNG.130* Constant instances of this structure are defined for each implemented131* PRNG. Such instances are also called "vtables".132*/133typedef struct br_prng_class_ br_prng_class;134struct br_prng_class_ {135/**136* \brief Size (in bytes) of the context structure appropriate for137* running this PRNG.138*/139size_t context_size;140141/**142* \brief Initialisation method.143*144* The context to initialise is provided as a pointer to its145* first field (the vtable pointer); this function sets that146* first field to a pointer to the vtable.147*148* The extra parameters depend on the implementation; each149* implementation defines what kind of extra parameters it150* expects (if any).151*152* Requirements on the initial seed depend on the implemented153* PRNG.154*155* \param ctx PRNG context to initialise.156* \param params extra parameters for the PRNG.157* \param seed initial seed.158* \param seed_len initial seed length (in bytes).159*/160void (*init)(const br_prng_class **ctx, const void *params,161const void *seed, size_t seed_len);162163/**164* \brief Random bytes generation.165*166* This method produces `len` pseudorandom bytes, in the `out`167* buffer. The context is updated accordingly.168*169* \param ctx PRNG context.170* \param out output buffer.171* \param len number of pseudorandom bytes to produce.172*/173void (*generate)(const br_prng_class **ctx, void *out, size_t len);174175/**176* \brief Inject additional seed bytes.177*178* The provided seed bytes are added into the PRNG internal179* entropy pool.180*181* \param ctx PRNG context.182* \param seed additional seed.183* \param seed_len additional seed length (in bytes).184*/185void (*update)(const br_prng_class **ctx,186const void *seed, size_t seed_len);187};188189/**190* \brief Context for HMAC_DRBG.191*192* The context contents are opaque, except the first field, which193* supports OOP.194*/195typedef struct {196/**197* \brief Pointer to the vtable.198*199* This field is set with the initialisation method/function.200*/201const br_prng_class *vtable;202#ifndef BR_DOXYGEN_IGNORE203unsigned char K[64];204unsigned char V[64];205const br_hash_class *digest_class;206#endif207} br_hmac_drbg_context;208209/**210* \brief Statically allocated, constant vtable for HMAC_DRBG.211*/212extern const br_prng_class br_hmac_drbg_vtable;213214/**215* \brief HMAC_DRBG initialisation.216*217* The context to initialise is provided as a pointer to its first field218* (the vtable pointer); this function sets that first field to a219* pointer to the vtable.220*221* The `seed` value is what is called, in NIST terminology, the222* concatenation of the "seed", "nonce" and "personalization string", in223* that order.224*225* The `digest_class` parameter defines the underlying hash function.226* Formally, the NIST standard specifies that the hash function shall227* be only SHA-1 or one of the SHA-2 functions. This implementation also228* works with any other implemented hash function (such as MD5), but229* this is non-standard and therefore not recommended.230*231* \param ctx HMAC_DRBG context to initialise.232* \param digest_class vtable for the underlying hash function.233* \param seed initial seed.234* \param seed_len initial seed length (in bytes).235*/236void br_hmac_drbg_init(br_hmac_drbg_context *ctx,237const br_hash_class *digest_class, const void *seed, size_t seed_len);238239/**240* \brief Random bytes generation with HMAC_DRBG.241*242* This method produces `len` pseudorandom bytes, in the `out`243* buffer. The context is updated accordingly. Formally, requesting244* more than 65536 bytes in one request falls out of specification245* limits (but it won't fail).246*247* \param ctx HMAC_DRBG context.248* \param out output buffer.249* \param len number of pseudorandom bytes to produce.250*/251void br_hmac_drbg_generate(br_hmac_drbg_context *ctx, void *out, size_t len);252253/**254* \brief Inject additional seed bytes in HMAC_DRBG.255*256* The provided seed bytes are added into the HMAC_DRBG internal257* entropy pool. The process does not _replace_ existing entropy,258* thus pushing non-random bytes (i.e. bytes which are known to the259* attackers) does not degrade the overall quality of generated bytes.260*261* \param ctx HMAC_DRBG context.262* \param seed additional seed.263* \param seed_len additional seed length (in bytes).264*/265void br_hmac_drbg_update(br_hmac_drbg_context *ctx,266const void *seed, size_t seed_len);267268/**269* \brief Get the hash function implementation used by a given instance of270* HMAC_DRBG.271*272* This calls MUST NOT be performed on a context which was not273* previously initialised.274*275* \param ctx HMAC_DRBG context.276* \return the hash function vtable.277*/278static inline const br_hash_class *279br_hmac_drbg_get_hash(const br_hmac_drbg_context *ctx)280{281return ctx->digest_class;282}283284/**285* \brief Type for a provider of entropy seeds.286*287* A "seeder" is a function that is able to obtain random values from288* some source and inject them as entropy seed in a PRNG. A seeder289* shall guarantee that the total entropy of the injected seed is large290* enough to seed a PRNG for purposes of cryptographic key generation291* (i.e. at least 128 bits).292*293* A seeder may report a failure to obtain adequate entropy. Seeders294* shall endeavour to fix themselves transient errors by trying again;295* thus, callers may consider reported errors as permanent.296*297* \param ctx PRNG context to seed.298* \return 1 on success, 0 on error.299*/300typedef int (*br_prng_seeder)(const br_prng_class **ctx);301302/**303* \brief Get a seeder backed by the operating system or hardware.304*305* Get a seeder that feeds on RNG facilities provided by the current306* operating system or hardware. If no such facility is known, then 0307* is returned.308*309* If `name` is not `NULL`, then `*name` is set to a symbolic string310* that identifies the seeder implementation. If no seeder is returned311* and `name` is not `NULL`, then `*name` is set to a pointer to the312* constant string `"none"`.313*314* \param name receiver for seeder name, or `NULL`.315* \return the system seeder, if available, or 0.316*/317br_prng_seeder br_prng_seeder_system(const char **name);318319/**320* \brief Context for AESCTR_DRBG.321*322* The context contents are opaque, except the first field, which323* supports OOP.324*/325typedef struct {326/**327* \brief Pointer to the vtable.328*329* This field is set with the initialisation method/function.330*/331const br_prng_class *vtable;332#ifndef BR_DOXYGEN_IGNORE333br_aes_gen_ctr_keys sk;334uint32_t cc;335#endif336} br_aesctr_drbg_context;337338/**339* \brief Statically allocated, constant vtable for AESCTR_DRBG.340*/341extern const br_prng_class br_aesctr_drbg_vtable;342343/**344* \brief AESCTR_DRBG initialisation.345*346* The context to initialise is provided as a pointer to its first field347* (the vtable pointer); this function sets that first field to a348* pointer to the vtable.349*350* The internal AES key is first set to the all-zero key; then, the351* `br_aesctr_drbg_update()` function is called with the provided `seed`.352* The call is performed even if the seed length (`seed_len`) is zero.353*354* The `aesctr` parameter defines the underlying AES/CTR implementation.355*356* \param ctx AESCTR_DRBG context to initialise.357* \param aesctr vtable for the AES/CTR implementation.358* \param seed initial seed (can be `NULL` if `seed_len` is zero).359* \param seed_len initial seed length (in bytes).360*/361void br_aesctr_drbg_init(br_aesctr_drbg_context *ctx,362const br_block_ctr_class *aesctr, const void *seed, size_t seed_len);363364/**365* \brief Random bytes generation with AESCTR_DRBG.366*367* This method produces `len` pseudorandom bytes, in the `out`368* buffer. The context is updated accordingly.369*370* \param ctx AESCTR_DRBG context.371* \param out output buffer.372* \param len number of pseudorandom bytes to produce.373*/374void br_aesctr_drbg_generate(br_aesctr_drbg_context *ctx,375void *out, size_t len);376377/**378* \brief Inject additional seed bytes in AESCTR_DRBG.379*380* The provided seed bytes are added into the AESCTR_DRBG internal381* entropy pool. The process does not _replace_ existing entropy,382* thus pushing non-random bytes (i.e. bytes which are known to the383* attackers) does not degrade the overall quality of generated bytes.384*385* \param ctx AESCTR_DRBG context.386* \param seed additional seed.387* \param seed_len additional seed length (in bytes).388*/389void br_aesctr_drbg_update(br_aesctr_drbg_context *ctx,390const void *seed, size_t seed_len);391392#ifdef __cplusplus393}394#endif395396#endif397398399