diff --git a/random/Makefile.am b/random/Makefile.am index c9d587a2..e073fa4b 100644 --- a/random/Makefile.am +++ b/random/Makefile.am @@ -1,51 +1,52 @@ # Makefile for cipher modules # Copyright (C) 2008 Free Software Foundation, Inc. # # This file is part of Libgcrypt. # # Libgcrypt is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of # the License, or (at your option) any later version. # # Libgcrypt is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . # Process this file with automake to produce Makefile.in # Need to include ../src in addition to top_srcdir because gcrypt.h is # a built header. AM_CPPFLAGS = -I../src -I$(top_srcdir)/src AM_CFLAGS = $(GPG_ERROR_CFLAGS) noinst_LTLIBRARIES = librandom.la GCRYPT_MODULES = @GCRYPT_RANDOM@ librandom_la_DEPENDENCIES = $(GCRYPT_MODULES) librandom_la_LIBADD = $(GCRYPT_MODULES) librandom_la_SOURCES = \ random.c random.h \ rand-internal.h \ random-csprng.c \ random-fips.c \ +drbg.c \ random-system.c \ rndhw.c if USE_RANDOM_DAEMON librandom_la_SOURCES += random-daemon.c endif USE_RANDOM_DAEMON EXTRA_librandom_la_SOURCES = \ rndlinux.c \ rndegd.c \ rndunix.c \ rndw32.c \ rndw32ce.c diff --git a/random/drbg.c b/random/drbg.c new file mode 100644 index 00000000..752eb652 --- /dev/null +++ b/random/drbg.c @@ -0,0 +1,2340 @@ +/* + * DRBG: Deterministic Random Bits Generator + * Based on NIST Recommended DRBG from NIST SP800-90A with the following + * properties: + * * CTR DRBG with DF with AES-128, AES-192, AES-256 cores + * * Hash DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores + * * HMAC DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores + * * with and without prediction resistance + * + * Copyright Stephan Mueller , 2014 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * LGPLv2+, in which case the provisions of the LGPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the LGPL and + * the restrictions contained in a BSD-style copyright.) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * + * gcry_control GCRYCTL_DRBG_REINIT + * ================================ + * This control request re-initializes the DRBG completely, i.e. the entire + * state of the DRBG is zeroized (with two exceptions listed in + * GCRYCTL_DRBG_SET_ENTROPY). + * + * The control request takes the following values which influences how the DRBG + * is re-initialized: + * * u32 flags: This variable specifies the DRBG type to be used for the + * next initialization. If set to 0, the previous DRBG type is + * used for the initialization. The DRBG type is an OR of the + * mandatory flags of the requested DRBG strength and DRBG + * cipher type. Optionally, the prediction resistance flag + * can be ORed into the flags variable. For example: + * - CTR-DRBG with AES-128 without prediction resistance: + * DRBG_CTRAES128 + * - HMAC-DRBG with SHA-512 with prediction resistance: + * DRBG_HMACSHA512 | DRBG_PREDICTION_RESIST + * * struct gcry_drbg_string *pers: personalization string to be used for + * initialization. + * The variable of flags is independent from the pers/perslen variables. If + * flags is set to 0 and perslen is set to 0, the current DRBG type is + * completely reset without using a personalization string. + * + * DRBG Usage + * ========== + * The SP 800-90A DRBG allows the user to specify a personalization string + * for initialization as well as an additional information string for each + * random number request. The following code fragments show how a caller + * uses the kernel crypto API to use the full functionality of the DRBG. + * + * Usage without any additional data + * --------------------------------- + * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); + * + * + * Usage with personalization string during initialization + * ------------------------------------------------------- + * struct gcry_drbg_string pers; + * char personalization[11] = "some-string"; + * + * gcry_drbg_string_fill(&pers, personalization, strlen(personalization)); + * // The reset completely re-initializes the DRBG with the provided + * // personalization string without changing the DRBG type + * ret = gcry_control(GCRYCTL_DRBG_REINIT, 0, &pers); + * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); + * + * + * Usage with additional information string during random number request + * --------------------------------------------------------------------- + * struct gcry_drbg_string addtl; + * char addtl_string[11] = "some-string"; + * + * gcry_drbg_string_fill(&addtl, addtl_string, strlen(addtl_string)); + * // The following call is a wrapper to gcry_randomize() and returns + * // the same error codes. + * gcry_randomize_drbg(outbuf, OUTLEN, GCRY_STRONG_RANDOM, &addtl); + * + * + * Usage with personalization and additional information strings + * ------------------------------------------------------------- + * Just mix both scenarios above. + * + * + * Switch the DRBG type to some other type + * --------------------------------------- + * // Switch to CTR DRBG AES-128 without prediction resistance + * ret = gcry_control(GCRYCTL_DRBG_REINIT, DRBG_NOPR_CTRAES128, NULL); + * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); + */ + +#include +#include +#include +#include +#include + +#include + +#include "g10lib.h" +#include "random.h" +#include "rand-internal.h" +#include "../cipher/bithelp.h" + +/****************************************************************** + * Common data structures + ******************************************************************/ + +struct gcry_drbg_state; + +struct gcry_drbg_core +{ + u32 flags; /* flags for the cipher */ + ushort statelen; /* maximum state length */ + ushort blocklen_bytes; /* block size of output in bytes */ + int backend_cipher; /* libgcrypt backend cipher */ +}; + +struct gcry_drbg_state_ops +{ + gpg_err_code_t (*update) (struct gcry_drbg_state * drbg, + struct gcry_drbg_string * seed, int reseed); + gpg_err_code_t (*generate) (struct gcry_drbg_state * drbg, + unsigned char *buf, unsigned int buflen, + struct gcry_drbg_string * addtl); +}; + +/* DRBG test data */ +struct gcry_drbg_test_data +{ + struct gcry_drbg_string *testentropy; /* TEST PARAMETER: test entropy */ + int fail_seed_source:1; /* if set, the seed function will return an error */ +}; + + +struct gcry_drbg_state +{ + unsigned char *V; /* internal state 10.1.1.1 1a) */ + unsigned char *C; /* hash: static value 10.1.1.1 1b) + * hmac / ctr: key */ + size_t reseed_ctr; /* Number of RNG requests since last reseed -- + * 10.1.1.1 1c) */ + unsigned char *scratchpad; /* some memory the DRBG can use for its + * operation -- allocated during init */ + int seeded:1; /* DRBG fully seeded? */ + int pr:1; /* Prediction resistance enabled? */ + /* Taken from libgcrypt ANSI X9.31 DRNG: We need to keep track of the + * process which did the initialization so that we can detect a fork. + * The volatile modifier is required so that the compiler does not + * optimize it away in case the getpid function is badly attributed. */ + pid_t seed_init_pid; + const struct gcry_drbg_state_ops *d_ops; + const struct gcry_drbg_core *core; + struct gcry_drbg_test_data *test_data; +}; + +enum gcry_drbg_prefixes +{ + DRBG_PREFIX0 = 0x00, + DRBG_PREFIX1, + DRBG_PREFIX2, + DRBG_PREFIX3 +}; + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + +/*************************************************************** + * Backend cipher definitions available to DRBG + ***************************************************************/ + +static const struct gcry_drbg_core gcry_drbg_cores[] = { + /* Hash DRBGs */ + {GCRY_DRBG_HASHSHA1, 55, 20, GCRY_MD_SHA1}, + {GCRY_DRBG_HASHSHA256, 55, 32, GCRY_MD_SHA256}, + {GCRY_DRBG_HASHSHA384, 111, 48, GCRY_MD_SHA384}, + {GCRY_DRBG_HASHSHA512, 111, 64, GCRY_MD_SHA512}, + /* HMAC DRBGs */ + {GCRY_DRBG_HASHSHA1 | GCRY_DRBG_HMAC, 20, 20, GCRY_MD_SHA1}, + {GCRY_DRBG_HASHSHA256 | GCRY_DRBG_HMAC, 32, 32, GCRY_MD_SHA256}, + {GCRY_DRBG_HASHSHA384 | GCRY_DRBG_HMAC, 48, 48, GCRY_MD_SHA384}, + {GCRY_DRBG_HASHSHA512 | GCRY_DRBG_HMAC, 64, 64, GCRY_MD_SHA512}, + /* block ciphers */ + {GCRY_DRBG_CTRAES | GCRY_DRBG_SYM128, 32, 16, GCRY_CIPHER_AES128}, + {GCRY_DRBG_CTRAES | GCRY_DRBG_SYM192, 40, 16, GCRY_CIPHER_AES192}, + {GCRY_DRBG_CTRAES | GCRY_DRBG_SYM256, 48, 16, GCRY_CIPHER_AES256}, +}; + +static gpg_err_code_t gcry_drbg_sym (struct gcry_drbg_state *drbg, + const unsigned char *key, + unsigned char *outval, + const struct gcry_drbg_string *buf); +static gpg_err_code_t gcry_drbg_hmac (struct gcry_drbg_state *drbg, + const unsigned char *key, + unsigned char *outval, + const struct gcry_drbg_string *buf); + +/****************************************************************** + ****************************************************************** + ****************************************************************** + * Generic DRBG code + ****************************************************************** + ****************************************************************** + ******************************************************************/ + +/****************************************************************** + * Generic helper functions + ******************************************************************/ + +#if 0 +#define dbg(x) do { log_debug x; } while(0) +#else +#define dbg(x) +#endif + +static inline ushort +gcry_drbg_statelen (struct gcry_drbg_state *drbg) +{ + if (drbg && drbg->core) + return drbg->core->statelen; + return 0; +} + +static inline ushort +gcry_drbg_blocklen (struct gcry_drbg_state *drbg) +{ + if (drbg && drbg->core) + return drbg->core->blocklen_bytes; + return 0; +} + +static inline ushort +gcry_drbg_keylen (struct gcry_drbg_state *drbg) +{ + if (drbg && drbg->core) + return (drbg->core->statelen - drbg->core->blocklen_bytes); + return 0; +} + +static inline size_t +gcry_drbg_max_request_bytes (void) +{ + /* SP800-90A requires the limit 2**19 bits, but we return bytes */ + return (1 << 16); +} + +static inline size_t +gcry_drbg_max_addtl (void) +{ + /* SP800-90A requires 2**35 bytes additional info str / pers str */ +#ifdef __LP64__ + return (1UL << 35); +#else + /* + * SP800-90A allows smaller maximum numbers to be returned -- we + * return SIZE_MAX - 1 to allow the verification of the enforcement + * of this value in gcry_drbg_healthcheck_sanity. + */ + return (SIZE_MAX - 1); +#endif +} + +static inline size_t +gcry_drbg_max_requests (void) +{ + /* SP800-90A requires 2**48 maximum requests before reseeding */ +#ifdef __LP64__ + return (1UL << 48); +#else + return SIZE_MAX; +#endif +} + +/* + * Return strength of DRBG according to SP800-90A section 8.4 + * + * flags: DRBG flags reference + * + * Return: normalized strength value or 32 as a default to counter + * programming errors + */ +static inline unsigned short +gcry_drbg_sec_strength (u32 flags) +{ + if ((flags & GCRY_DRBG_HASHSHA1) || (flags & GCRY_DRBG_SYM128)) + return 16; + else if (flags & GCRY_DRBG_SYM192) + return 24; + else if ((flags & GCRY_DRBG_SYM256) || (flags & GCRY_DRBG_HASHSHA256) || + (flags & GCRY_DRBG_HASHSHA384) || (flags & GCRY_DRBG_HASHSHA512)) + return 32; + else + return 32; +} + +/* + * Convert an integer into a byte representation of this integer. + * The byte representation is big-endian + * + * @val value to be converted + * @buf buffer holding the converted integer -- caller must ensure that + * buffer size is at least 32 bit + */ +static inline void +gcry_drbg_cpu_to_be32 (u32 val, unsigned char *buf) +{ + struct s + { + u32 conv; + }; + struct s *conversion = (struct s *) buf; + + conversion->conv = be_bswap32 (val); +} + +static void +gcry_drbg_add_buf (unsigned char *dst, size_t dstlen, + unsigned char *add, size_t addlen) +{ + /* implied: dstlen > addlen */ + unsigned char *dstptr, *addptr; + unsigned int remainder = 0; + size_t len = addlen; + + dstptr = dst + (dstlen - 1); + addptr = add + (addlen - 1); + while (len) + { + remainder += *dstptr + *addptr; + *dstptr = remainder & 0xff; + remainder >>= 8; + len--; + dstptr--; + addptr--; + } + len = dstlen - addlen; + while (len && remainder > 0) + { + remainder = *dstptr + 1; + *dstptr = remainder & 0xff; + remainder >>= 8; + len--; + dstptr--; + } +} + +/* Helper variables for read_cb(). + * + * The _gcry_rnd*_gather_random interface does not allow to provide a + * data pointer. Thus we need to use a global variable for + * communication. However, the then required locking is anyway a good + * idea because it does not make sense to have several readers of (say + * /dev/random). It is easier to serve them one after the other. */ +static unsigned char *read_cb_buffer; /* The buffer. */ +static size_t read_cb_size; /* Size of the buffer. */ +static size_t read_cb_len; /* Used length. */ + +/* Callback for generating seed from kernel device. */ +static void +gcry_drbg_read_cb (const void *buffer, size_t length, + enum random_origins origin) +{ + const unsigned char *p = buffer; + + (void) origin; + gcry_assert (read_cb_buffer); + + /* Note that we need to protect against gatherers returning more + * than the requested bytes (e.g. rndw32). */ + while (length-- && read_cb_len < read_cb_size) + read_cb_buffer[read_cb_len++] = *p++; +} + +static inline int +gcry_drbg_get_entropy (struct gcry_drbg_state *drbg, unsigned char *buffer, + size_t len) +{ + int rc = 0; + + /* Perform testing as defined in 11.3.2 */ + if (drbg->test_data && drbg->test_data->fail_seed_source) + return -1; + + read_cb_buffer = buffer; + read_cb_size = len; + read_cb_len = 0; +#if USE_RNDLINUX + rc = _gcry_rndlinux_gather_random (gcry_drbg_read_cb, 0, len, + GCRY_VERY_STRONG_RANDOM); +#elif USE_RNDUNIX + rc = _gcry_rndunix_gather_random (read_cb, 0, length, + GCRY_VERY_STRONG_RANDOM); +#elif USE_RNDW32 + do + { + rc = _gcry_rndw32_gather_random (read_cb, 0, length, + GCRY_VERY_STRONG_RANDOM); + } + while (rc >= 0 && read_cb_len < read_cb_size); +#else + rc = -1; +#endif + return rc; +} + +/****************************************************************** + * CTR DRBG callback functions + ******************************************************************/ + +/* BCC function for CTR DRBG as defined in 10.4.3 */ +static gpg_err_code_t +gcry_drbg_ctr_bcc (struct gcry_drbg_state *drbg, + unsigned char *out, const unsigned char *key, + struct gcry_drbg_string *in) +{ + gpg_err_code_t ret = GPG_ERR_GENERAL; + struct gcry_drbg_string *curr = in; + size_t inpos = curr->len; + const unsigned char *pos = curr->buf; + struct gcry_drbg_string data; + + gcry_drbg_string_fill (&data, out, gcry_drbg_blocklen (drbg)); + + /* 10.4.3 step 1 */ + memset (out, 0, gcry_drbg_blocklen (drbg)); + + /* 10.4.3 step 2 / 4 */ + while (inpos) + { + short cnt = 0; + /* 10.4.3 step 4.1 */ + for (cnt = 0; cnt < gcry_drbg_blocklen (drbg); cnt++) + { + out[cnt] ^= *pos; + pos++; + inpos--; + /* the following branch implements the linked list + * iteration. If we are at the end of the current data + * set, we have to start using the next data set if + * available -- the inpos value always points to the + * current byte and will be zero if we have processed + * the last byte of the last linked list member */ + if (0 == inpos) + { + curr = curr->next; + if (NULL != curr) + { + pos = curr->buf; + inpos = curr->len; + } + else + { + inpos = 0; + break; + } + } + } + /* 10.4.3 step 4.2 */ + ret = gcry_drbg_sym (drbg, key, out, &data); + if (ret) + return ret; + /* 10.4.3 step 2 */ + } + return 0; +} + + +/* + * scratchpad usage: gcry_drbg_ctr_update is interlinked with gcry_drbg_ctr_df + * (and gcry_drbg_ctr_bcc, but this function does not need any temporary buffers), + * the scratchpad is used as follows: + * gcry_drbg_ctr_update: + * temp + * start: drbg->scratchpad + * length: gcry_drbg_statelen(drbg) + gcry_drbg_blocklen(drbg) + * note: the cipher writing into this variable works + * blocklen-wise. Now, when the statelen is not a multiple + * of blocklen, the generateion loop below "spills over" + * by at most blocklen. Thus, we need to give sufficient + * memory. + * df_data + * start: drbg->scratchpad + + * gcry_drbg_statelen(drbg) + + * gcry_drbg_blocklen(drbg) + * length: gcry_drbg_statelen(drbg) + * + * gcry_drbg_ctr_df: + * pad + * start: df_data + gcry_drbg_statelen(drbg) + * length: gcry_drbg_blocklen(drbg) + * iv + * start: pad + gcry_drbg_blocklen(drbg) + * length: gcry_drbg_blocklen(drbg) + * temp + * start: iv + gcry_drbg_blocklen(drbg) + * length: gcry_drbg_satelen(drbg) + gcry_drbg_blocklen(drbg) + * note: temp is the buffer that the BCC function operates + * on. BCC operates blockwise. gcry_drbg_statelen(drbg) + * is sufficient when the DRBG state length is a multiple + * of the block size. For AES192 (and maybe other ciphers) + * this is not correct and the length for temp is + * insufficient (yes, that also means for such ciphers, + * the final output of all BCC rounds are truncated). + * Therefore, add gcry_drbg_blocklen(drbg) to cover all + * possibilities. + */ + +/* Derivation Function for CTR DRBG as defined in 10.4.2 */ +static gpg_err_code_t +gcry_drbg_ctr_df (struct gcry_drbg_state *drbg, unsigned char *df_data, + size_t bytes_to_return, struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = GPG_ERR_GENERAL; + unsigned char L_N[8]; + /* S3 is input */ + struct gcry_drbg_string S1, S2, S4, cipherin; + struct gcry_drbg_string *tempstr = addtl; + unsigned char *pad = df_data + gcry_drbg_statelen (drbg); + unsigned char *iv = pad + gcry_drbg_blocklen (drbg); + unsigned char *temp = iv + gcry_drbg_blocklen (drbg); + size_t padlen = 0; + unsigned int templen = 0; + /* 10.4.2 step 7 */ + unsigned int i = 0; + /* 10.4.2 step 8 */ + const unsigned char *K = (unsigned char *) + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"; + unsigned char *X; + size_t generated_len = 0; + size_t inputlen = 0; + + memset (pad, 0, gcry_drbg_blocklen (drbg)); + memset (iv, 0, gcry_drbg_blocklen (drbg)); + memset (temp, 0, gcry_drbg_statelen (drbg)); + + /* 10.4.2 step 1 is implicit as we work byte-wise */ + + /* 10.4.2 step 2 */ + if ((512 / 8) < bytes_to_return) + return GPG_ERR_INV_ARG; + + /* 10.4.2 step 2 -- calculate the entire length of all input data */ + for (; NULL != tempstr; tempstr = tempstr->next) + inputlen += tempstr->len; + gcry_drbg_cpu_to_be32 (inputlen, &L_N[0]); + + /* 10.4.2 step 3 */ + gcry_drbg_cpu_to_be32 (bytes_to_return, &L_N[4]); + + /* 10.4.2 step 5: length is size of L_N, input_string, one byte, padding */ + padlen = (inputlen + sizeof (L_N) + 1) % (gcry_drbg_blocklen (drbg)); + /* wrap the padlen appropriately */ + if (padlen) + padlen = gcry_drbg_blocklen (drbg) - padlen; + /* pad / padlen contains the 0x80 byte and the following zero bytes, so + * add one for byte for 0x80 */ + padlen++; + pad[0] = 0x80; + + /* 10.4.2 step 4 -- first fill the linked list and then order it */ + gcry_drbg_string_fill (&S1, iv, gcry_drbg_blocklen (drbg)); + gcry_drbg_string_fill (&S2, L_N, sizeof (L_N)); + gcry_drbg_string_fill (&S4, pad, padlen); + S1.next = &S2; + S2.next = addtl; + + /* Splice in addtl between S2 and S4 -- we place S4 at the end of the + * input data chain. As this code is only triggered when addtl is not + * NULL, no NULL checks are necessary.*/ + tempstr = addtl; + while (tempstr->next) + tempstr = tempstr->next; + tempstr->next = &S4; + + /* 10.4.2 step 9 */ + while (templen < (gcry_drbg_keylen (drbg) + (gcry_drbg_blocklen (drbg)))) + { + /* 10.4.2 step 9.1 - the padding is implicit as the buffer + * holds zeros after allocation -- even the increment of i + * is irrelevant as the increment remains within length of i */ + gcry_drbg_cpu_to_be32 (i, iv); + /* 10.4.2 step 9.2 -- BCC and concatenation with temp */ + ret = gcry_drbg_ctr_bcc (drbg, temp + templen, K, &S1); + if (ret) + goto out; + /* 10.4.2 step 9.3 */ + i++; + templen += gcry_drbg_blocklen (drbg); + } + + /* 10.4.2 step 11 */ + /* implicit key len with seedlen - blocklen according to table 3 */ + X = temp + (gcry_drbg_keylen (drbg)); + gcry_drbg_string_fill (&cipherin, X, gcry_drbg_blocklen (drbg)); + + /* 10.4.2 step 12: overwriting of outval */ + + /* 10.4.2 step 13 */ + while (generated_len < bytes_to_return) + { + short blocklen = 0; + /* 10.4.2 step 13.1 */ + /* the truncation of the key length is implicit as the key + * is only gcry_drbg_blocklen in size -- check for the implementation + * of the cipher function callback */ + ret = gcry_drbg_sym (drbg, temp, X, &cipherin); + if (ret) + goto out; + blocklen = (gcry_drbg_blocklen (drbg) < + (bytes_to_return - generated_len)) ? + gcry_drbg_blocklen (drbg) : (bytes_to_return - generated_len); + /* 10.4.2 step 13.2 and 14 */ + memcpy (df_data + generated_len, X, blocklen); + generated_len += blocklen; + } + + ret = 0; + +out: + memset (iv, 0, gcry_drbg_blocklen (drbg)); + memset (temp, 0, gcry_drbg_statelen (drbg)); + memset (pad, 0, gcry_drbg_blocklen (drbg)); + return ret; +} + +/* + * update function of CTR DRBG as defined in 10.2.1.2 + * + * The reseed variable has an enhanced meaning compared to the update + * functions of the other DRBGs as follows: + * 0 => initial seed from initialization + * 1 => reseed via gcry_drbg_seed + * 2 => first invocation from gcry_drbg_ctr_update when addtl is present. In + * this case, the df_data scratchpad is not deleted so that it is + * available for another calls to prevent calling the DF function + * again. + * 3 => second invocation from gcry_drbg_ctr_update. When the update function + * was called with addtl, the df_data memory already contains the + * DFed addtl information and we do not need to call DF again. + */ +static gpg_err_code_t +gcry_drbg_ctr_update (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *addtl, int reseed) +{ + gpg_err_code_t ret = GPG_ERR_GENERAL; + /* 10.2.1.2 step 1 */ + unsigned char *temp = drbg->scratchpad; + unsigned char *df_data = drbg->scratchpad + + gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg); + unsigned char *temp_p, *df_data_p; /* pointer to iterate over buffers */ + unsigned int len = 0; + struct gcry_drbg_string cipherin; + unsigned char prefix = DRBG_PREFIX1; + + memset (temp, 0, gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg)); + if (3 > reseed) + memset (df_data, 0, gcry_drbg_statelen (drbg)); + + /* 10.2.1.3.2 step 2 and 10.2.1.4.2 step 2 */ + /* TODO use reseed variable to avoid re-doing DF operation */ + (void) reseed; + if (addtl && 0 < addtl->len) + { + ret = + gcry_drbg_ctr_df (drbg, df_data, gcry_drbg_statelen (drbg), addtl); + if (ret) + goto out; + } + + gcry_drbg_string_fill (&cipherin, drbg->V, gcry_drbg_blocklen (drbg)); + /* 10.2.1.3.2 step 2 and 3 -- are already covered as we memset(0) + * all memory during initialization */ + while (len < (gcry_drbg_statelen (drbg))) + { + /* 10.2.1.2 step 2.1 */ + gcry_drbg_add_buf (drbg->V, gcry_drbg_blocklen (drbg), &prefix, 1); + /* 10.2.1.2 step 2.2 */ + /* using target of temp + len: 10.2.1.2 step 2.3 and 3 */ + ret = gcry_drbg_sym (drbg, drbg->C, temp + len, &cipherin); + if (ret) + goto out; + /* 10.2.1.2 step 2.3 and 3 */ + len += gcry_drbg_blocklen (drbg); + } + + /* 10.2.1.2 step 4 */ + temp_p = temp; + df_data_p = df_data; + for (len = 0; len < gcry_drbg_statelen (drbg); len++) + { + *temp_p ^= *df_data_p; + df_data_p++; + temp_p++; + } + + /* 10.2.1.2 step 5 */ + memcpy (drbg->C, temp, gcry_drbg_keylen (drbg)); + /* 10.2.1.2 step 6 */ + memcpy (drbg->V, temp + gcry_drbg_keylen (drbg), gcry_drbg_blocklen (drbg)); + ret = 0; + +out: + memset (temp, 0, gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg)); + if (2 != reseed) + memset (df_data, 0, gcry_drbg_statelen (drbg)); + return ret; +} + +/* + * scratchpad use: gcry_drbg_ctr_update is called independently from + * gcry_drbg_ctr_extract_bytes. Therefore, the scratchpad is reused + */ +/* Generate function of CTR DRBG as defined in 10.2.1.5.2 */ +static gpg_err_code_t +gcry_drbg_ctr_generate (struct gcry_drbg_state *drbg, + unsigned char *buf, unsigned int buflen, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + unsigned int len = 0; + struct gcry_drbg_string data; + unsigned char prefix = DRBG_PREFIX1; + + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + + /* 10.2.1.5.2 step 2 */ + if (addtl && 0 < addtl->len) + { + addtl->next = NULL; + ret = gcry_drbg_ctr_update (drbg, addtl, 2); + if (ret) + return ret; + } + + /* 10.2.1.5.2 step 4.1 */ + gcry_drbg_add_buf (drbg->V, gcry_drbg_blocklen (drbg), &prefix, 1); + gcry_drbg_string_fill (&data, drbg->V, gcry_drbg_blocklen (drbg)); + while (len < buflen) + { + unsigned int outlen = 0; + /* 10.2.1.5.2 step 4.2 */ + ret = gcry_drbg_sym (drbg, drbg->C, drbg->scratchpad, &data); + if (ret) + goto out; + outlen = (gcry_drbg_blocklen (drbg) < (buflen - len)) ? + gcry_drbg_blocklen (drbg) : (buflen - len); + /* 10.2.1.5.2 step 4.3 */ + memcpy (buf + len, drbg->scratchpad, outlen); + len += outlen; + /* 10.2.1.5.2 step 6 */ + if (len < buflen) + gcry_drbg_add_buf (drbg->V, gcry_drbg_blocklen (drbg), &prefix, 1); + } + + /* 10.2.1.5.2 step 6 */ + if (addtl) + addtl->next = NULL; + ret = gcry_drbg_ctr_update (drbg, addtl, 3); + +out: + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + return ret; +} + +static struct gcry_drbg_state_ops gcry_drbg_ctr_ops = { + gcry_drbg_ctr_update, + gcry_drbg_ctr_generate, +}; + +/****************************************************************** + * HMAC DRBG callback functions + ******************************************************************/ + +static gpg_err_code_t +gcry_drbg_hmac_update (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *seed, int reseed) +{ + gpg_err_code_t ret = GPG_ERR_GENERAL; + int i = 0; + struct gcry_drbg_string seed1, seed2, cipherin; + + if (!reseed) + /* 10.1.2.3 step 2 already implicitly covered with + * the initial memset(0) of drbg->C */ + memset (drbg->V, 1, gcry_drbg_statelen (drbg)); + + /* build linked list which implements the concatenation and fill + * first part*/ + gcry_drbg_string_fill (&seed1, drbg->V, gcry_drbg_statelen (drbg)); + /* buffer will be filled in for loop below with one byte */ + gcry_drbg_string_fill (&seed2, NULL, 1); + seed1.next = &seed2; + /* seed may be NULL */ + seed2.next = seed; + + gcry_drbg_string_fill (&cipherin, drbg->V, gcry_drbg_statelen (drbg)); + /* we execute two rounds of V/K massaging */ + for (i = 2; 0 < i; i--) + { + /* first round uses 0x0, second 0x1 */ + unsigned char prefix = DRBG_PREFIX0; + if (1 == i) + prefix = DRBG_PREFIX1; + /* 10.1.2.2 step 1 and 4 -- concatenation and HMAC for key */ + seed2.buf = &prefix; + ret = gcry_drbg_hmac (drbg, drbg->C, drbg->C, &seed1); + if (ret) + return ret; + + /* 10.1.2.2 step 2 and 5 -- HMAC for V */ + ret = gcry_drbg_hmac (drbg, drbg->C, drbg->V, &cipherin); + if (ret) + return ret; + + /* 10.1.2.2 step 3 */ + if (!seed || 0 == seed->len) + return ret; + } + return 0; +} + +/* generate function of HMAC DRBG as defined in 10.1.2.5 */ +static gpg_err_code_t +gcry_drbg_hmac_generate (struct gcry_drbg_state *drbg, + unsigned char *buf, + unsigned int buflen, struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + unsigned int len = 0; + struct gcry_drbg_string data; + + /* 10.1.2.5 step 2 */ + if (addtl && 0 < addtl->len) + { + addtl->next = NULL; + ret = gcry_drbg_hmac_update (drbg, addtl, 1); + if (ret) + return ret; + } + + gcry_drbg_string_fill (&data, drbg->V, gcry_drbg_statelen (drbg)); + while (len < buflen) + { + unsigned int outlen = 0; + /* 10.1.2.5 step 4.1 */ + ret = gcry_drbg_hmac (drbg, drbg->C, drbg->V, &data); + if (ret) + return ret; + outlen = (gcry_drbg_blocklen (drbg) < (buflen - len)) ? + gcry_drbg_blocklen (drbg) : (buflen - len); + + /* 10.1.2.5 step 4.2 */ + memcpy (buf + len, drbg->V, outlen); + len += outlen; + } + + /* 10.1.2.5 step 6 */ + if (addtl) + addtl->next = NULL; + ret = gcry_drbg_hmac_update (drbg, addtl, 1); + + return ret; +} + +static struct gcry_drbg_state_ops gcry_drbg_hmac_ops = { + gcry_drbg_hmac_update, + gcry_drbg_hmac_generate, +}; + +/****************************************************************** + * Hash DRBG callback functions + ******************************************************************/ + +/* + * scratchpad usage: as gcry_drbg_hash_update and gcry_drbg_hash_df are used + * interlinked, the scratchpad is used as follows: + * gcry_drbg_hash_update + * start: drbg->scratchpad + * length: gcry_drbg_statelen(drbg) + * gcry_drbg_hash_df: + * start: drbg->scratchpad + gcry_drbg_statelen(drbg) + * length: gcry_drbg_blocklen(drbg) + */ +/* Derivation Function for Hash DRBG as defined in 10.4.1 */ +static gpg_err_code_t +gcry_drbg_hash_df (struct gcry_drbg_state *drbg, + unsigned char *outval, size_t outlen, + struct gcry_drbg_string *entropy) +{ + gpg_err_code_t ret = 0; + size_t len = 0; + unsigned char input[5]; + unsigned char *tmp = drbg->scratchpad + gcry_drbg_statelen (drbg); + struct gcry_drbg_string data1; + + memset (tmp, 0, gcry_drbg_blocklen (drbg)); + + /* 10.4.1 step 3 */ + input[0] = 1; + gcry_drbg_cpu_to_be32 ((outlen * 8), &input[1]); + + /* 10.4.1 step 4.1 -- concatenation of data for input into hash */ + gcry_drbg_string_fill (&data1, input, 5); + data1.next = entropy; + + /* 10.4.1 step 4 */ + while (len < outlen) + { + short blocklen = 0; + /* 10.4.1 step 4.1 */ + ret = gcry_drbg_hmac (drbg, NULL, tmp, &data1); + if (ret) + goto out; + /* 10.4.1 step 4.2 */ + input[0]++; + blocklen = (gcry_drbg_blocklen (drbg) < (outlen - len)) ? + gcry_drbg_blocklen (drbg) : (outlen - len); + memcpy (outval + len, tmp, blocklen); + len += blocklen; + } + +out: + memset (tmp, 0, gcry_drbg_blocklen (drbg)); + return ret; +} + +/* update function for Hash DRBG as defined in 10.1.1.2 / 10.1.1.3 */ +static gpg_err_code_t +gcry_drbg_hash_update (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *seed, int reseed) +{ + gpg_err_code_t ret = 0; + struct gcry_drbg_string data1, data2; + unsigned char *V = drbg->scratchpad; + unsigned char prefix = DRBG_PREFIX1; + + memset (drbg->scratchpad, 0, gcry_drbg_statelen (drbg)); + if (!seed) + return GPG_ERR_INV_ARG; + + if (reseed) + { + /* 10.1.1.3 step 1: string length is concatenation of + * 1 byte, V and seed (which is concatenated entropy/addtl + * input) + */ + memcpy (V, drbg->V, gcry_drbg_statelen (drbg)); + gcry_drbg_string_fill (&data1, &prefix, 1); + gcry_drbg_string_fill (&data2, V, gcry_drbg_statelen (drbg)); + data1.next = &data2; + data2.next = seed; + } + else + { + gcry_drbg_string_fill (&data1, seed->buf, seed->len); + data1.next = seed->next; + } + + /* 10.1.1.2 / 10.1.1.3 step 2 and 3 */ + ret = gcry_drbg_hash_df (drbg, drbg->V, gcry_drbg_statelen (drbg), &data1); + if (ret) + goto out; + + /* 10.1.1.2 / 10.1.1.3 step 4 -- concatenation */ + prefix = DRBG_PREFIX0; + gcry_drbg_string_fill (&data1, &prefix, 1); + gcry_drbg_string_fill (&data2, drbg->V, gcry_drbg_statelen (drbg)); + data1.next = &data2; + /* 10.1.1.2 / 10.1.1.3 step 4 -- df operation */ + ret = gcry_drbg_hash_df (drbg, drbg->C, gcry_drbg_statelen (drbg), &data1); + +out: + memset (drbg->scratchpad, 0, gcry_drbg_statelen (drbg)); + return ret; +} + +/* processing of additional information string for Hash DRBG */ +static gpg_err_code_t +gcry_drbg_hash_process_addtl (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + struct gcry_drbg_string data1, data2; + struct gcry_drbg_string *data3; + unsigned char prefix = DRBG_PREFIX2; + + /* this is value w as per documentation */ + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + + /* 10.1.1.4 step 2 */ + if (!addtl || 0 == addtl->len) + return 0; + + /* 10.1.1.4 step 2a -- concatenation */ + gcry_drbg_string_fill (&data1, &prefix, 1); + gcry_drbg_string_fill (&data2, drbg->V, gcry_drbg_statelen (drbg)); + data3 = addtl; + data1.next = &data2; + data2.next = data3; + data3->next = NULL; + /* 10.1.1.4 step 2a -- cipher invocation */ + ret = gcry_drbg_hmac (drbg, NULL, drbg->scratchpad, &data1); + if (ret) + goto out; + + /* 10.1.1.4 step 2b */ + gcry_drbg_add_buf (drbg->V, gcry_drbg_statelen (drbg), + drbg->scratchpad, gcry_drbg_blocklen (drbg)); + +out: + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + return ret; +} + +/* + * Hashgen defined in 10.1.1.4 + */ +static gpg_err_code_t +gcry_drbg_hash_hashgen (struct gcry_drbg_state *drbg, + unsigned char *buf, unsigned int buflen) +{ + gpg_err_code_t ret = 0; + unsigned int len = 0; + unsigned char *src = drbg->scratchpad; + unsigned char *dst = drbg->scratchpad + gcry_drbg_statelen (drbg); + struct gcry_drbg_string data; + unsigned char prefix = DRBG_PREFIX1; + + /* use the scratchpad as a lookaside buffer */ + memset (src, 0, gcry_drbg_statelen (drbg)); + memset (dst, 0, gcry_drbg_blocklen (drbg)); + + /* 10.1.1.4 step hashgen 2 */ + memcpy (src, drbg->V, gcry_drbg_statelen (drbg)); + + gcry_drbg_string_fill (&data, src, gcry_drbg_statelen (drbg)); + while (len < buflen) + { + unsigned int outlen = 0; + /* 10.1.1.4 step hashgen 4.1 */ + ret = gcry_drbg_hmac (drbg, NULL, dst, &data); + if (ret) + goto out; + outlen = (gcry_drbg_blocklen (drbg) < (buflen - len)) ? + gcry_drbg_blocklen (drbg) : (buflen - len); + /* 10.1.1.4 step hashgen 4.2 */ + memcpy (buf + len, dst, outlen); + len += outlen; + /* 10.1.1.4 hashgen step 4.3 */ + if (len < buflen) + gcry_drbg_add_buf (src, gcry_drbg_statelen (drbg), &prefix, 1); + } + +out: + memset (drbg->scratchpad, 0, + (gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg))); + return ret; +} + +/* generate function for Hash DRBG as defined in 10.1.1.4 */ +static gpg_err_code_t +gcry_drbg_hash_generate (struct gcry_drbg_state *drbg, + unsigned char *buf, unsigned int buflen, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + unsigned char prefix = DRBG_PREFIX3; + struct gcry_drbg_string data1, data2; + union + { + unsigned char req[8]; + u64 req_int; + } u; + + /* + * scratchpad usage: gcry_drbg_hash_process_addtl uses the scratchpad, but + * fully completes before returning. Thus, we can reuse the scratchpad + */ + /* 10.1.1.4 step 2 */ + ret = gcry_drbg_hash_process_addtl (drbg, addtl); + if (ret) + return ret; + /* 10.1.1.4 step 3 -- invocation of the Hashgen function defined in + * 10.1.1.4 */ + ret = gcry_drbg_hash_hashgen (drbg, buf, buflen); + if (ret) + return ret; + + /* this is the value H as documented in 10.1.1.4 */ + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + /* 10.1.1.4 step 4 */ + gcry_drbg_string_fill (&data1, &prefix, 1); + gcry_drbg_string_fill (&data2, drbg->V, gcry_drbg_statelen (drbg)); + data1.next = &data2; + ret = gcry_drbg_hmac (drbg, NULL, drbg->scratchpad, &data1); + if (ret) + goto out; + + /* 10.1.1.4 step 5 */ + gcry_drbg_add_buf (drbg->V, gcry_drbg_statelen (drbg), + drbg->scratchpad, gcry_drbg_blocklen (drbg)); + gcry_drbg_add_buf (drbg->V, gcry_drbg_statelen (drbg), drbg->C, + gcry_drbg_statelen (drbg)); + u.req_int = be_bswap64 (drbg->reseed_ctr); + gcry_drbg_add_buf (drbg->V, gcry_drbg_statelen (drbg), u.req, + sizeof (u.req)); + +out: + memset (drbg->scratchpad, 0, gcry_drbg_blocklen (drbg)); + return ret; +} + +/* + * scratchpad usage: as update and generate are used isolated, both + * can use the scratchpad + */ +static struct gcry_drbg_state_ops gcry_drbg_hash_ops = { + gcry_drbg_hash_update, + gcry_drbg_hash_generate, +}; + +/****************************************************************** + * Functions common for DRBG implementations + ******************************************************************/ + +/* + * Seeding or reseeding of the DRBG + * + * @drbg: DRBG state struct + * @pers: personalization / additional information buffer + * @reseed: 0 for initial seed process, 1 for reseeding + * + * return: + * 0 on success + * error value otherwise + */ +static gpg_err_code_t +gcry_drbg_seed (struct gcry_drbg_state *drbg, struct gcry_drbg_string *pers, + int reseed) +{ + gpg_err_code_t ret = 0; + unsigned char *entropy = NULL; + size_t entropylen = 0; + struct gcry_drbg_string data1; + + /* 9.1 / 9.2 / 9.3.1 step 3 */ + if (pers && pers->len > (gcry_drbg_max_addtl ())) + { + dbg (("DRBG: personalization string too long %lu\n", pers->len)); + return GPG_ERR_INV_ARG; + } + if (drbg->test_data && drbg->test_data->testentropy) + { + gcry_drbg_string_fill (&data1, drbg->test_data->testentropy->buf, + drbg->test_data->testentropy->len); + dbg (("DRBG: using test entropy\n")); + } + else + { + /* Gather entropy equal to the security strength of the DRBG. + * With a derivation function, a nonce is required in addition + * to the entropy. A nonce must be at least 1/2 of the security + * strength of the DRBG in size. Thus, entropy * nonce is 3/2 + * of the strength. The consideration of a nonce is only + * applicable during initial seeding. */ + entropylen = gcry_drbg_sec_strength (drbg->core->flags); + if (!entropylen) + return GPG_ERR_GENERAL; + if (0 == reseed) + /* make sure we round up strength/2 in + * case it is not divisible by 2 */ + entropylen = ((entropylen + 1) / 2) * 3; + dbg (("DRBG: (re)seeding with %lu bytes of entropy\n", entropylen)); + entropy = xcalloc_secure (1, entropylen); + if (!entropy) + return GPG_ERR_ENOMEM; + ret = gcry_drbg_get_entropy (drbg, entropy, entropylen); + if (ret) + goto out; + gcry_drbg_string_fill (&data1, entropy, entropylen); + } + + /* concatenation of entropy with personalization str / addtl input) + * the variable pers is directly handed by the caller, check its + * contents whether it is appropriate */ + if (pers && pers->buf && 0 < pers->len && NULL == pers->next) + { + data1.next = pers; + dbg (("DRBG: using personalization string\n")); + } + + ret = drbg->d_ops->update (drbg, &data1, reseed); + dbg (("DRBG: state updated with seed\n")); + if (ret) + goto out; + drbg->seeded = 1; + /* 10.1.1.2 / 10.1.1.3 step 5 */ + drbg->reseed_ctr = 1; + +out: + xfree (entropy); + return ret; +} + +/************************************************************************* + * exported interfaces + *************************************************************************/ + +/* + * DRBG generate function as required by SP800-90A - this function + * generates random numbers + * + * @drbg DRBG state handle + * @buf Buffer where to store the random numbers -- the buffer must already + * be pre-allocated by caller + * @buflen Length of output buffer - this value defines the number of random + * bytes pulled from DRBG + * @addtl Additional input that is mixed into state, may be NULL -- note + * the entropy is pulled by the DRBG internally unconditionally + * as defined in SP800-90A. The additional input is mixed into + * the state in addition to the pulled entropy. + * + * return: generated number of bytes + */ +static gpg_err_code_t +gcry_drbg_generate (struct gcry_drbg_state *drbg, + unsigned char *buf, unsigned int buflen, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = GPG_ERR_INV_ARG; + + if (0 == buflen || !buf) + { + dbg (("DRBG: no buffer provided\n")); + return ret; + } + if (addtl && NULL == addtl->buf && 0 < addtl->len) + { + dbg (("DRBG: wrong format of additional information\n")); + return ret; + } + + /* 9.3.1 step 2 */ + if (buflen > (gcry_drbg_max_request_bytes ())) + { + dbg (("DRBG: requested random numbers too large %u\n", buflen)); + return ret; + } + /* 9.3.1 step 3 is implicit with the chosen DRBG */ + /* 9.3.1 step 4 */ + if (addtl && addtl->len > (gcry_drbg_max_addtl ())) + { + dbg (("DRBG: additional information string too long %lu\n", + addtl->len)); + return ret; + } + /* 9.3.1 step 5 is implicit with the chosen DRBG */ + /* 9.3.1 step 6 and 9 supplemented by 9.3.2 step c -- the spec is a + * bit convoluted here, we make it simpler */ + if ((gcry_drbg_max_requests ()) < drbg->reseed_ctr) + drbg->seeded = 0; + + if (drbg->pr || !drbg->seeded) + { + dbg (("DRBG: reseeding before generation (prediction resistance: %s, state %s)\n", drbg->pr ? "true" : "false", drbg->seeded ? "seeded" : "unseeded")); + /* 9.3.1 steps 7.1 through 7.3 */ + ret = gcry_drbg_seed (drbg, addtl, 1); + if (ret) + return ret; + /* 9.3.1 step 7.4 */ + addtl = NULL; + } + + if (addtl && addtl->buf) + { + dbg (("DRBG: using additional information string\n")); + } + + /* 9.3.1 step 8 and 10 */ + ret = drbg->d_ops->generate (drbg, buf, buflen, addtl); + + /* 10.1.1.4 step 6, 10.1.2.5 step 7, 10.2.1.5.2 step 7 */ + drbg->reseed_ctr++; + if (ret) + return ret; + + /* 11.3.3 -- re-perform self tests after some generated random + * numbers, the chosen value after which self test is performed + * is arbitrary, but it should be reasonable */ + /* Here we do not perform the self tests because of the following + * reasons: it is mathematically impossible that the initial self tests + * were successfully and the following are not. If the initial would + * pass and the following would not, the system integrity is violated. + * In this case, the entire system operation is questionable and it + * is unlikely that the integrity violation only affects to the + * correct operation of the DRBG. + */ +#if 0 + if (drbg->reseed_ctr && !(drbg->reseed_ctr % 4096)) + { + dbg (("DRBG: start to perform self test\n")); + ret = gcry_drbg_healthcheck (); + if (ret) + { + log_fatal (("DRBG: self test failed\n")); + return ret; + } + else + { + dbg (("DRBG: self test successful\n")); + } + } +#endif + + return ret; +} + +/* + * Wrapper around gcry_drbg_generate which can pull arbitrary long strings + * from the DRBG without hitting the maximum request limitation. + * + * Parameters: see gcry_drbg_generate + * Return codes: see gcry_drbg_generate -- if one gcry_drbg_generate request fails, + * the entire gcry_drbg_generate_long request fails + */ +static gpg_err_code_t +gcry_drbg_generate_long (struct gcry_drbg_state *drbg, + unsigned char *buf, unsigned int buflen, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + unsigned int slice = 0; + unsigned char *buf_p = buf; + unsigned len = 0; + do + { + unsigned int chunk = 0; + slice = ((buflen - len) / gcry_drbg_max_request_bytes ()); + chunk = slice ? gcry_drbg_max_request_bytes () : (buflen - len); + ret = gcry_drbg_generate (drbg, buf_p, chunk, addtl); + if (ret) + return ret; + buf_p += chunk; + len += chunk; + } + while (slice > 0 && (len < buflen)); + return ret; +} + +/* + * DRBG uninstantiate function as required by SP800-90A - this function + * frees all buffers and the DRBG handle + * + * @drbg DRBG state handle + * + * return + * 0 on success + */ +static gpg_err_code_t +gcry_drbg_uninstantiate (struct gcry_drbg_state *drbg) +{ + if (!drbg) + return GPG_ERR_INV_ARG; + xfree (drbg->V); + drbg->V = NULL; + xfree (drbg->C); + drbg->C = NULL; + drbg->reseed_ctr = 0; + xfree (drbg->scratchpad); + drbg->scratchpad = NULL; + drbg->seeded = 0; + drbg->pr = 0; + drbg->seed_init_pid = 0; + return 0; +} + +/* + * DRBG instantiation function as required by SP800-90A - this function + * sets up the DRBG handle, performs the initial seeding and all sanity + * checks required by SP800-90A + * + * @drbg memory of state -- if NULL, new memory is allocated + * @pers Personalization string that is mixed into state, may be NULL -- note + * the entropy is pulled by the DRBG internally unconditionally + * as defined in SP800-90A. The additional input is mixed into + * the state in addition to the pulled entropy. + * @coreref reference to core + * @flags Flags defining the requested DRBG type and cipher type. The flags + * are defined in drbg.h and may be XORed. Beware, if you XOR multiple + * cipher types together, the code picks the core on a first come first + * serve basis as it iterates through the available cipher cores and + * uses the one with the first match. The minimum required flags are: + * cipher type flag + * + * return + * 0 on success + * error value otherwise + */ +static gpg_err_code_t +gcry_drbg_instantiate (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *pers, int coreref, int pr) +{ + gpg_err_code_t ret = GPG_ERR_ENOMEM; + unsigned int sb_size = 0; + + if (!drbg) + return GPG_ERR_INV_ARG; + + dbg (("DRBG: Initializing DRBG core %d with prediction resistance %s\n", + coreref, pr ? "enabled" : "disabled")); + drbg->core = &gcry_drbg_cores[coreref]; + drbg->pr = pr; + drbg->seeded = 0; + if (drbg->core->flags & GCRY_DRBG_HMAC) + drbg->d_ops = &gcry_drbg_hmac_ops; + else if (drbg->core->flags & GCRY_DRBG_HASH_MASK) + drbg->d_ops = &gcry_drbg_hash_ops; + else if (drbg->core->flags & GCRY_DRBG_CTR_MASK) + drbg->d_ops = &gcry_drbg_ctr_ops; + else + return GPG_ERR_GENERAL; + /* 9.1 step 1 is implicit with the selected DRBG type -- see + * gcry_drbg_sec_strength() */ + + /* 9.1 step 2 is implicit as caller can select prediction resistance + * and the flag is copied into drbg->flags -- + * all DRBG types support prediction resistance */ + + /* 9.1 step 4 is implicit in gcry_drbg_sec_strength */ + + /* no allocation of drbg as this is done by the kernel crypto API */ + drbg->V = xcalloc_secure (1, gcry_drbg_statelen (drbg)); + if (!drbg->V) + goto err; + drbg->C = xcalloc_secure (1, gcry_drbg_statelen (drbg)); + if (!drbg->C) + goto err; + /* scratchpad is only generated for CTR and Hash */ + if (drbg->core->flags & GCRY_DRBG_HMAC) + sb_size = 0; + else if (drbg->core->flags & GCRY_DRBG_CTR_MASK) + sb_size = gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg) + /* temp */ + gcry_drbg_statelen (drbg) + /* df_data */ + gcry_drbg_blocklen (drbg) + /* pad */ + gcry_drbg_blocklen (drbg) + /* iv */ + gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg); /* temp */ + else + sb_size = gcry_drbg_statelen (drbg) + gcry_drbg_blocklen (drbg); + + if (0 < sb_size) + { + drbg->scratchpad = xcalloc_secure (1, sb_size); + if (!drbg->scratchpad) + goto err; + } + dbg (("DRBG: state allocated with scratchpad size %u bytes\n", sb_size)); + + /* 9.1 step 6 through 11 */ + ret = gcry_drbg_seed (drbg, pers, 0); + if (ret) + goto err; + + dbg (("DRBG: core %d %s prediction resistance successfully initialized\n", + coreref, pr ? "with" : "without")); + return 0; + +err: + gcry_drbg_uninstantiate (drbg); + return ret; +} + +/* + * DRBG reseed function as required by SP800-90A + * + * @drbg DRBG state handle + * @addtl Additional input that is mixed into state, may be NULL -- note + * the entropy is pulled by the DRBG internally unconditionally + * as defined in SP800-90A. The additional input is mixed into + * the state in addition to the pulled entropy. + * + * return + * 0 on success + * error value otherwise + */ +static gpg_err_code_t +gcry_drbg_reseed (struct gcry_drbg_state *drbg, + struct gcry_drbg_string *addtl) +{ + gpg_err_code_t ret = 0; + ret = gcry_drbg_seed (drbg, addtl, 1); + return ret; +} + +/****************************************************************** + ****************************************************************** + ****************************************************************** + * libgcrypt integration code + ****************************************************************** + ****************************************************************** + ******************************************************************/ + +/*************************************************************** + * libgcrypt backend functions to the RNG API code + ***************************************************************/ + +/* global state variable holding the current instance of the DRBG -- the + * default DRBG type is defined in _gcry_gcry_drbg_init */ +static struct gcry_drbg_state *gcry_drbg = NULL; + +/* This is the lock we use to serialize access to this RNG. */ +GPGRT_LOCK_DEFINE(drbg_lock); + +static inline void +gcry_drbg_lock (void) +{ + gpg_err_code_t my_errno; + + my_errno = gpgrt_lock_lock (&drbg_lock); + if (my_errno) + log_fatal ("failed to acquire the RNG lock: %s\n", strerror (my_errno)); +} + +static inline void +gcry_drbg_unlock (void) +{ + gpg_err_code_t my_errno; + + my_errno = gpgrt_lock_unlock (&drbg_lock); + if (my_errno) + log_fatal ("failed to release the RNG lock: %s\n", strerror (my_errno)); +} + +/* Basic initialization is required to initialize mutexes and + do a few checks on the implementation. */ +static void +basic_initialization (void) +{ + static int initialized; + + if (initialized) + return; + initialized = 1; + + /* Make sure that we are still using the values we have + traditionally used for the random levels. */ + gcry_assert (GCRY_WEAK_RANDOM == 0 + && GCRY_STRONG_RANDOM == 1 + && GCRY_VERY_STRONG_RANDOM == 2); +} + +/****** helper functions where lock must be held by caller *****/ + +/* Check whether given flags are known to point to an applicable DRBG */ +static gpg_err_code_t +gcry_drbg_algo_available (u32 flags, int *coreref) +{ + int i = 0; + for (i = 0; ARRAY_SIZE (gcry_drbg_cores) > i; i++) + { + if ((gcry_drbg_cores[i].flags & GCRY_DRBG_CIPHER_MASK) == + (flags & GCRY_DRBG_CIPHER_MASK)) + { + *coreref = i; + return 0; + } + } + return GPG_ERR_GENERAL; +} + +static gpg_err_code_t +_gcry_drbg_init_internal (u32 flags, struct gcry_drbg_string *pers) +{ + gpg_err_code_t ret = 0; + static u32 oldflags = 0; + int coreref = 0; + int pr = 0; + + /* If a caller provides 0 as flags, use the flags of the previous + * initialization, otherwise use the current flags and remember them + * for the next invocation + */ + if (0 == flags) + flags = oldflags; + else + oldflags = flags; + + ret = gcry_drbg_algo_available (flags, &coreref); + if (ret) + return ret; + + if (NULL != gcry_drbg) + { + gcry_drbg_uninstantiate (gcry_drbg); + } + else + { + gcry_drbg = xcalloc_secure (1, sizeof (struct gcry_drbg_state)); + if (!gcry_drbg) + return GPG_ERR_ENOMEM; + } + if (flags & GCRY_DRBG_PREDICTION_RESIST) + pr = 1; + ret = gcry_drbg_instantiate (gcry_drbg, pers, coreref, pr); + if (ret) + fips_signal_error ("DRBG cannot be initialized"); + else + gcry_drbg->seed_init_pid = getpid (); + return ret; +} + +/************* calls available to common RNG code **************/ + +/* + * Initialize one DRBG invoked by the libgcrypt API + */ +void +_gcry_drbg_init (int full) +{ + /* default DRBG */ + u32 flags = GCRY_DRBG_NOPR_HMACSHA256; + basic_initialization (); + if (!full) + return; + gcry_drbg_lock (); + if (NULL == gcry_drbg) + _gcry_drbg_init_internal (flags, NULL); + gcry_drbg_unlock (); +} + +/* + * Backend handler function for GCRYCTL_DRBG_REINIT + * + * Select a different DRBG type and initialize it. + * Function checks whether requested DRBG type exists and returns an error in + * case it does not. In case of an error, the previous instantiated DRBG is + * left untouched and alive. Thus, in case of an error, a DRBG is always + * available, even if it is not the chosen one. + * + * Re-initialization will be performed in any case regardless whether flags + * or personalization string are set. + * + * If flags == 0, do not change current DRBG + * If personalization string is NULL or its length is 0, re-initialize without + * personalization string + */ +gpg_err_code_t +_gcry_drbg_reinit (u32 flags, struct gcry_drbg_string *pers) +{ + gpg_err_code_t ret = GPG_ERR_GENERAL; + dbg (("DRBG: reinitialize internal DRBG state with flags %u\n", flags)); + gcry_drbg_lock (); + ret = _gcry_drbg_init_internal (flags, pers); + gcry_drbg_unlock (); + return ret; +} + +/* Try to close the FDs of the random gather module. This is + * currently only implemented for rndlinux. */ +void +_gcry_drbg_close_fds (void) +{ +#if USE_RNDLINUX + gcry_drbg_lock (); + _gcry_rndlinux_gather_random (NULL, 0, 0, 0); + gcry_drbg_unlock (); +#endif +} + +/* Print some statistics about the RNG. */ +void +_gcry_drbg_dump_stats (void) +{ + /* Not yet implemented. */ + /* Maybe dumping of reseed counter? */ +} + +/* This function returns true if no real RNG is available or the + * quality of the RNG has been degraded for test purposes. */ +int +_gcry_drbg_is_faked (void) +{ + return 0; /* Faked random is not allowed. */ +} + +/* Add BUFLEN bytes from BUF to the internal random pool. QUALITY + * should be in the range of 0..100 to indicate the goodness of the + * entropy added, or -1 for goodness not known. */ +gcry_error_t +_gcry_drbg_add_bytes (const void *buf, size_t buflen, int quality) +{ + gpg_err_code_t ret = 0; + struct gcry_drbg_string seed; + (void) quality; + _gcry_drbg_init(1); /* Auto-initialize if needed */ + if (NULL == gcry_drbg) + return GPG_ERR_GENERAL; + gcry_drbg_string_fill (&seed, (unsigned char *) buf, buflen); + gcry_drbg_lock (); + ret = gcry_drbg_reseed (gcry_drbg, &seed); + gcry_drbg_unlock (); + return ret; +} + +/* This function is to be used for all types of random numbers, including + * nonces + */ +void +_gcry_drbg_randomize (void *buffer, size_t length, + enum gcry_random_level level) +{ + (void) level; + _gcry_drbg_init(1); /* Auto-initialize if needed */ + gcry_drbg_lock (); + if (NULL == gcry_drbg) + { + fips_signal_error ("DRBG is not initialized"); + goto bailout; + } + + /* As reseeding changes the entire state of the DRBG, including any + * key, either a re-init or a reseed is sufficient for a fork */ + if (gcry_drbg->seed_init_pid != getpid ()) + { + /* We are in a child of us. Perform a reseeding. */ + if (gcry_drbg_reseed (gcry_drbg, NULL)) + { + fips_signal_error ("reseeding upon fork failed"); + log_fatal ("severe error getting random\n"); + goto bailout; + } + } + /* potential integer overflow is covered by gcry_drbg_generate which + * ensures that length cannot overflow an unsigned int */ + if (0 < length) + { + if (!buffer) + goto bailout; + if (gcry_drbg_generate_long + (gcry_drbg, buffer, (unsigned int) length, NULL)) + log_fatal ("No random numbers generated\n"); + } + else + { + struct gcry_drbg_gen *data = (struct gcry_drbg_gen *) buffer; + /* catch NULL pointer */ + if (!data || !data->outbuf) + { + fips_signal_error ("No output buffer provided"); + goto bailout; + } + if (gcry_drbg_generate_long (gcry_drbg, data->outbuf, data->outlen, + data->addtl)) + log_fatal ("No random numbers generated\n"); + } +bailout: + gcry_drbg_unlock (); + return; + +} + +/*************************************************************** + * Self-test code + ***************************************************************/ + +/* + * Test vectors from + * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/drbgtestvectors.zip + */ +struct gcry_drbg_test_vector gcry_drbg_test_pr[] = { + { + .flags = (GCRY_DRBG_PR_HASHSHA256), + .entropy = (unsigned char *) + "\x5d\xf2\x14\xbc\xf6\xb5\x4e\x0b\xf0\x0d\x6f\x2d" + "\xe2\x01\x66\x7b\xd0\xa4\x73\xa4\x21\xdd\xb0\xc0" + "\x51\x79\x09\xf4\xea\xa9\x08\xfa\xa6\x67\xe0\xe1" + "\xd1\x88\xa8\xad\xee\x69\x74\xb3\x55\x06\x9b\xf6", + .entropylen = 48, + .entpra = (unsigned char *) + "\xef\x48\x06\xa2\xc2\x45\xf1\x44\xfa\x34\x2c\xeb" + "\x8d\x78\x3c\x09\x8f\x34\x72\x20\xf2\xe7\xfd\x13" + "\x76\x0a\xf6\xdc\x3c\xf5\xc0\x15", + .entprb = (unsigned char *) + "\x4b\xbe\xe5\x24\xed\x6a\x2d\x0c\xdb\x73\x5e\x09" + "\xf9\xad\x67\x7c\x51\x47\x8b\x6b\x30\x2a\xc6\xde" + "\x76\xaa\x55\x04\x8b\x0a\x72\x95", + .entprlen = 32, + .expected = (unsigned char *) + "\x3b\x14\x71\x99\xa1\xda\xa0\x42\xe6\xc8\x85\x32" + "\x70\x20\x32\x53\x9a\xbe\xd1\x1e\x15\xef\xfb\x4c" + "\x25\x6e\x19\x3a\xf0\xb9\xcb\xde\xf0\x3b\xc6\x18" + "\x4d\x85\x5a\x9b\xf1\xe3\xc2\x23\x03\x93\x08\xdb" + "\xa7\x07\x4b\x33\x78\x40\x4d\xeb\x24\xf5\x6e\x81" + "\x4a\x1b\x6e\xa3\x94\x52\x43\xb0\xaf\x2e\x21\xf4" + "\x42\x46\x8e\x90\xed\x34\x21\x75\xea\xda\x67\xb6" + "\xe4\xf6\xff\xc6\x31\x6c\x9a\x5a\xdb\xb3\x97\x13" + "\x09\xd3\x20\x98\x33\x2d\x6d\xd7\xb5\x6a\xa8\xa9" + "\x9a\x5b\xd6\x87\x52\xa1\x89\x2b\x4b\x9c\x64\x60" + "\x50\x47\xa3\x63\x81\x16\xaf\x19", + .expectedlen = 128, + .addtla = (unsigned char *) + "\xbe\x13\xdb\x2a\xe9\xa8\xfe\x09\x97\xe1\xce\x5d" + "\xe8\xbb\xc0\x7c\x4f\xcb\x62\x19\x3f\x0f\xd2\xad" + "\xa9\xd0\x1d\x59\x02\xc4\xff\x70", + .addtlb = (unsigned char *) + "\x6f\x96\x13\xe2\xa7\xf5\x6c\xfe\xdf\x66\xe3\x31" + "\x63\x76\xbf\x20\x27\x06\x49\xf1\xf3\x01\x77\x41" + "\x9f\xeb\xe4\x38\xfe\x67\x00\xcd", + .addtllen = 32, + .pers = NULL, + .perslen = 0, + }, + { + .flags = (GCRY_DRBG_PR_HMACSHA256), + .entropy = (unsigned char *) + "\x13\x54\x96\xfc\x1b\x7d\x28\xf3\x18\xc9\xa7\x89" + "\xb6\xb3\xc8\x72\xac\x00\xd4\x59\x36\x25\x05\xaf" + "\xa5\xdb\x96\xcb\x3c\x58\x46\x87\xa5\xaa\xbf\x20" + "\x3b\xfe\x23\x0e\xd1\xc7\x41\x0f\x3f\xc9\xb3\x67", + .entropylen = 48, + .entpra = (unsigned char *) + "\xe2\xbd\xb7\x48\x08\x06\xf3\xe1\x93\x3c\xac\x79" + "\xa7\x2b\x11\xda\xe3\x2e\xe1\x91\xa5\x02\x19\x57" + "\x20\x28\xad\xf2\x60\xd7\xcd\x45", + .entprb = (unsigned char *) + "\x8b\xd4\x69\xfc\xff\x59\x95\x95\xc6\x51\xde\x71" + "\x68\x5f\xfc\xf9\x4a\xab\xec\x5a\xcb\xbe\xd3\x66" + "\x1f\xfa\x74\xd3\xac\xa6\x74\x60", + .entprlen = 32, + .expected = (unsigned char *) + "\x1f\x9e\xaf\xe4\xd2\x46\xb7\x47\x41\x4c\x65\x99" + "\x01\xe9\x3b\xbb\x83\x0c\x0a\xb0\xc1\x3a\xe2\xb3" + "\x31\x4e\xeb\x93\x73\xee\x0b\x26\xc2\x63\xa5\x75" + "\x45\x99\xd4\x5c\x9f\xa1\xd4\x45\x87\x6b\x20\x61" + "\x40\xea\x78\xa5\x32\xdf\x9e\x66\x17\xaf\xb1\x88" + "\x9e\x2e\x23\xdd\xc1\xda\x13\x97\x88\xa5\xb6\x5e" + "\x90\x14\x4e\xef\x13\xab\x5c\xd9\x2c\x97\x9e\x7c" + "\xd7\xf8\xce\xea\x81\xf5\xcd\x71\x15\x49\x44\xce" + "\x83\xb6\x05\xfb\x7d\x30\xb5\x57\x2c\x31\x4f\xfc" + "\xfe\x80\xb6\xc0\x13\x0c\x5b\x9b\x2e\x8f\x3d\xfc" + "\xc2\xa3\x0c\x11\x1b\x80\x5f\xf3", + .expectedlen = 128, + .addtla = NULL, + .addtlb = NULL, + .addtllen = 0, + .pers = (unsigned char *) + "\x64\xb6\xfc\x60\xbc\x61\x76\x23\x6d\x3f\x4a\x0f" + "\xe1\xb4\xd5\x20\x9e\x70\xdd\x03\x53\x6d\xbf\xce" + "\xcd\x56\x80\xbc\xb8\x15\xc8\xaa", + .perslen = 32, + }, + { + .flags = (GCRY_DRBG_PR_CTRAES128), + .entropy = (unsigned char *) + "\x92\x89\x8f\x31\xfa\x1c\xff\x6d\x18\x2f\x26\x06" + "\x43\xdf\xf8\x18\xc2\xa4\xd9\x72\xc3\xb9\xb6\x97", + .entropylen = 24, + .entpra = (unsigned char *) + "\x20\x72\x8a\x06\xf8\x6f\x8d\xd4\x41\xe2\x72\xb7" + "\xc4\x2c\xe8\x10", + .entprb = (unsigned char *) + "\x3d\xb0\xf0\x94\xf3\x05\x50\x33\x17\x86\x3e\x22" + "\x08\xf7\xa5\x01", + .entprlen = 16, + .expected = (unsigned char *) + "\x5a\x35\x39\x87\x0f\x4d\x22\xa4\x09\x24\xee\x71" + "\xc9\x6f\xac\x72\x0a\xd6\xf0\x88\x82\xd0\x83\x28" + "\x73\xec\x3f\x93\xd8\xab\x45\x23\xf0\x7e\xac\x45" + "\x14\x5e\x93\x9f\xb1\xd6\x76\x43\x3d\xb6\xe8\x08" + "\x88\xf6\xda\x89\x08\x77\x42\xfe\x1a\xf4\x3f\xc4" + "\x23\xc5\x1f\x68", + .expectedlen = 64, + .addtla = (unsigned char *) + "\x1a\x40\xfa\xe3\xcc\x6c\x7c\xa0\xf8\xda\xba\x59" + "\x23\x6d\xad\x1d", + .addtlb = (unsigned char *) + "\x9f\x72\x76\x6c\xc7\x46\xe5\xed\x2e\x53\x20\x12" + "\xbc\x59\x31\x8c", + .addtllen = 16, + .pers = (unsigned char *) + "\xea\x65\xee\x60\x26\x4e\x7e\xb6\x0e\x82\x68\xc4" + "\x37\x3c\x5c\x0b", + .perslen = 16, + }, +}; + +struct gcry_drbg_test_vector gcry_drbg_test_nopr[] = { + { + .flags = GCRY_DRBG_NOPR_HASHSHA256, + .entropy = (unsigned char *) + "\x73\xd3\xfb\xa3\x94\x5f\x2b\x5f\xb9\x8f\xf6\x9c" + "\x8a\x93\x17\xae\x19\xc3\x4c\xc3\xd6\xca\xa3\x2d" + "\x16\xfc\x42\xd2\x2d\xd5\x6f\x56\xcc\x1d\x30\xff" + "\x9e\x06\x3e\x09\xce\x58\xe6\x9a\x35\xb3\xa6\x56", + .entropylen = 48, + .expected = (unsigned char *) + "\x71\x7b\x93\x46\x1a\x40\xaa\x35\xa4\xaa\xc5\xe7" + "\x6d\x5b\x5b\x8a\xa0\xdf\x39\x7d\xae\x71\x58\x5b" + "\x3c\x7c\xb4\xf0\x89\xfa\x4a\x8c\xa9\x5c\x54\xc0" + "\x40\xdf\xbc\xce\x26\x81\x34\xf8\xba\x7d\x1c\xe8" + "\xad\x21\xe0\x74\xcf\x48\x84\x30\x1f\xa1\xd5\x4f" + "\x81\x42\x2f\xf4\xdb\x0b\x23\xf8\x73\x27\xb8\x1d" + "\x42\xf8\x44\x58\xd8\x5b\x29\x27\x0a\xf8\x69\x59" + "\xb5\x78\x44\xeb\x9e\xe0\x68\x6f\x42\x9a\xb0\x5b" + "\xe0\x4e\xcb\x6a\xaa\xe2\xd2\xd5\x33\x25\x3e\xe0" + "\x6c\xc7\x6a\x07\xa5\x03\x83\x9f\xe2\x8b\xd1\x1c" + "\x70\xa8\x07\x59\x97\xeb\xf6\xbe", + .expectedlen = 128, + .addtla = (unsigned char *) + "\xf4\xd5\x98\x3d\xa8\xfc\xfa\x37\xb7\x54\x67\x73" + "\xc7\xc3\xdd\x47\x34\x71\x02\x5d\xc1\xa0\xd3\x10" + "\xc1\x8b\xbd\xf5\x66\x34\x6f\xdd", + .addtlb = (unsigned char *) + "\xf7\x9e\x6a\x56\x0e\x73\xe9\xd9\x7a\xd1\x69\xe0" + "\x6f\x8c\x55\x1c\x44\xd1\xce\x6f\x28\xcc\xa4\x4d" + "\xa8\xc0\x85\xd1\x5a\x0c\x59\x40", + .addtllen = 32, + .pers = NULL, + .perslen = 0, + }, + { + .flags = GCRY_DRBG_NOPR_HMACSHA256, + .entropy = (unsigned char *) + "\x8d\xf0\x13\xb4\xd1\x03\x52\x30\x73\x91\x7d\xdf" + "\x6a\x86\x97\x93\x05\x9e\x99\x43\xfc\x86\x54\x54" + "\x9e\x7a\xb2\x2f\x7c\x29\xf1\x22\xda\x26\x25\xaf" + "\x2d\xdd\x4a\xbc\xce\x3c\xf4\xfa\x46\x59\xd8\x4e", + .entropylen = 48, + .expected = (unsigned char *) + "\xb9\x1c\xba\x4c\xc8\x4f\xa2\x5d\xf8\x61\x0b\x81" + "\xb6\x41\x40\x27\x68\xa2\x09\x72\x34\x93\x2e\x37" + "\xd5\x90\xb1\x15\x4c\xbd\x23\xf9\x74\x52\xe3\x10" + "\xe2\x91\xc4\x51\x46\x14\x7f\x0d\xa2\xd8\x17\x61" + "\xfe\x90\xfb\xa6\x4f\x94\x41\x9c\x0f\x66\x2b\x28" + "\xc1\xed\x94\xda\x48\x7b\xb7\xe7\x3e\xec\x79\x8f" + "\xbc\xf9\x81\xb7\x91\xd1\xbe\x4f\x17\x7a\x89\x07" + "\xaa\x3c\x40\x16\x43\xa5\xb6\x2b\x87\xb8\x9d\x66" + "\xb3\xa6\x0e\x40\xd4\xa8\xe4\xe9\xd8\x2a\xf6\xd2" + "\x70\x0e\x6f\x53\x5c\xdb\x51\xf7\x5c\x32\x17\x29" + "\x10\x37\x41\x03\x0c\xcc\x3a\x56", + .expectedlen = 128, + .addtla = NULL, + .addtlb = NULL, + .addtllen = 0, + .pers = (unsigned char *) + "\xb5\x71\xe6\x6d\x7c\x33\x8b\xc0\x7b\x76\xad\x37" + "\x57\xbb\x2f\x94\x52\xbf\x7e\x07\x43\x7a\xe8\x58" + "\x1c\xe7\xbc\x7c\x3a\xc6\x51\xa9", + .perslen = 32, + }, + { + .flags = GCRY_DRBG_NOPR_CTRAES128, + .entropy = (unsigned char *) + "\xc0\x70\x1f\x92\x50\x75\x8f\xcd\xf2\xbe\x73\x98" + "\x80\xdb\x66\xeb\x14\x68\xb4\xa5\x87\x9c\x2d\xa6", + .entropylen = 24, + .expected = (unsigned char *) + "\x97\xc0\xc0\xe5\xa0\xcc\xf2\x4f\x33\x63\x48\x8a" + "\xdb\x13\x0a\x35\x89\xbf\x80\x65\x62\xee\x13\x95" + "\x7c\x33\xd3\x7d\xf4\x07\x77\x7a\x2b\x65\x0b\x5f" + "\x45\x5c\x13\xf1\x90\x77\x7f\xc5\x04\x3f\xcc\x1a" + "\x38\xf8\xcd\x1b\xbb\xd5\x57\xd1\x4a\x4c\x2e\x8a" + "\x2b\x49\x1e\x5c", + .expectedlen = 64, + .addtla = (unsigned char *) + "\xf9\x01\xf8\x16\x7a\x1d\xff\xde\x8e\x3c\x83\xe2" + "\x44\x85\xe7\xfe", + .addtlb = (unsigned char *) + "\x17\x1c\x09\x38\xc2\x38\x9f\x97\x87\x60\x55\xb4" + "\x82\x16\x62\x7f", + .addtllen = 16, + .pers = (unsigned char *) + "\x80\x08\xae\xe8\xe9\x69\x40\xc5\x08\x73\xc7\x9f" + "\x8e\xcf\xe0\x02", + .perslen = 16, + }, + { + .flags = GCRY_DRBG_NOPR_HASHSHA1, + .entropy = (unsigned char *) + "\x16\x10\xb8\x28\xcc\xd2\x7d\xe0\x8c\xee\xa0\x32" + "\xa2\x0e\x92\x08\x49\x2c\xf1\x70\x92\x42\xf6\xb5", + .entropylen = 24, + .expected = (unsigned char *) + "\x56\xf3\x3d\x4f\xdb\xb9\xa5\xb6\x4d\x26\x23\x44" + "\x97\xe9\xdc\xb8\x77\x98\xc6\x8d\x08\xf7\xc4\x11" + "\x99\xd4\xbd\xdf\x97\xeb\xbf\x6c\xb5\x55\x0e\x5d" + "\x14\x9f\xf4\xd5\xbd\x0f\x05\xf2\x5a\x69\x88\xc1" + "\x74\x36\x39\x62\x27\x18\x4a\xf8\x4a\x56\x43\x35" + "\x65\x8e\x2f\x85\x72\xbe\xa3\x33\xee\xe2\xab\xff" + "\x22\xff\xa6\xde\x3e\x22\xac\xa2", + .expectedlen = 80, + .addtla = NULL, + .addtlb = NULL, + .addtllen = 0, + .pers = NULL, + .perslen = 0, + .entropyreseed = (unsigned char *) + "\x72\xd2\x8c\x90\x8e\xda\xf9\xa4\xd1\xe5\x26\xd8" + "\xf2\xde\xd5\x44", + .entropyreseed_len = 16, + .addtl_reseed = NULL, + .addtl_reseed_len = 0, + }, + { + .flags = GCRY_DRBG_NOPR_HASHSHA1, + .entropy = (unsigned char *) + "\xd9\xba\xb5\xce\xdc\xa9\x6f\x61\x78\xd6\x45\x09" + "\xa0\xdf\xdc\x5e\xda\xd8\x98\x94\x14\x45\x0e\x01", + .entropylen = 24, + .expected = (unsigned char *) + "\xc4\x8b\x89\xf9\xda\x3f\x74\x82\x45\x55\x5d\x5d" + "\x03\x3b\x69\x3d\xd7\x1a\x4d\xf5\x69\x02\x05\xce" + "\xfc\xd7\x20\x11\x3c\xc2\x4e\x09\x89\x36\xff\x5e" + "\x77\xb5\x41\x53\x58\x70\xb3\x39\x46\x8c\xdd\x8d" + "\x6f\xaf\x8c\x56\x16\x3a\x70\x0a\x75\xb2\x3e\x59" + "\x9b\x5a\xec\xf1\x6f\x3b\xaf\x6d\x5f\x24\x19\x97" + "\x1f\x24\xf4\x46\x72\x0f\xea\xbe", + .expectedlen = 80, + .addtla = (unsigned char *) + "\x04\xfa\x28\x95\xaa\x5a\x6f\x8c\x57\x43\x34\x3b" + "\x80\x5e\x5e\xa4", + .addtlb = (unsigned char *) + "\xdf\x5d\xc4\x59\xdf\xf0\x2a\xa2\xf0\x52\xd7\x21" + "\xec\x60\x72\x30", + .addtllen = 16, + .pers = NULL, + .perslen = 0, + .entropyreseed = (unsigned char *) + "\xc6\xba\xd0\x74\xc5\x90\x67\x86\xf5\xe1\xf3\x20" + "\x99\xf5\xb4\x91", + .entropyreseed_len = 16, + .addtl_reseed = (unsigned char *) + "\x3e\x6b\xf4\x6f\x4d\xaa\x38\x25\xd7\x19\x4e\x69" + "\x4e\x77\x52\xf7", + .addtl_reseed_len = 16, + }, +}; + + +/* + * Tests implement the CAVS test approach as documented in + * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/DRBGVS.pdf + */ + +/* + * CAVS test + * + * This function is not static as it is needed for as a private API + * call for the CAVS test tool. + */ +gpg_err_code_t +gcry_drbg_cavs_test (struct gcry_drbg_test_vector *test, unsigned char *buf) +{ + gpg_err_code_t ret = 0; + struct gcry_drbg_state *drbg = NULL; + struct gcry_drbg_test_data test_data; + struct gcry_drbg_string addtl, pers, testentropy; + int coreref = 0; + int pr = 0; + + ret = gcry_drbg_algo_available (test->flags, &coreref); + if (ret) + goto outbuf; + + drbg = xcalloc_secure (1, sizeof (struct gcry_drbg_state)); + if (!drbg) + { + ret = GPG_ERR_ENOMEM; + goto outbuf; + } + + if (test->flags & GCRY_DRBG_PREDICTION_RESIST) + pr = 1; + + test_data.testentropy = &testentropy; + gcry_drbg_string_fill (&testentropy, test->entropy, test->entropylen); + drbg->test_data = &test_data; + gcry_drbg_string_fill (&pers, test->pers, test->perslen); + ret = gcry_drbg_instantiate (drbg, &pers, coreref, pr); + if (ret) + goto outbuf; + + if (test->entropyreseed) + { + gcry_drbg_string_fill (&testentropy, test->entropyreseed, + test->entropyreseed_len); + gcry_drbg_string_fill (&addtl, test->addtl_reseed, + test->addtl_reseed_len); + if (gcry_drbg_reseed (drbg, &addtl)) + goto outbuf; + } + + gcry_drbg_string_fill (&addtl, test->addtla, test->addtllen); + if (test->entpra) + { + gcry_drbg_string_fill (&testentropy, test->entpra, test->entprlen); + drbg->test_data = &test_data; + } + gcry_drbg_generate_long (drbg, buf, test->expectedlen, &addtl); + + gcry_drbg_string_fill (&addtl, test->addtlb, test->addtllen); + if (test->entprb) + { + gcry_drbg_string_fill (&testentropy, test->entprb, test->entprlen); + drbg->test_data = &test_data; + } + gcry_drbg_generate_long (drbg, buf, test->expectedlen, &addtl); + gcry_drbg_uninstantiate (drbg); + +outbuf: + xfree (drbg); + return ret; +} + +/* + * Invoke the CAVS test and perform the final check whether the + * calculated random value matches the expected one. + * + * This function is not static as it is needed for as a private API + * call for the CAVS test tool. + */ +gpg_err_code_t +gcry_drbg_healthcheck_one (struct gcry_drbg_test_vector * test) +{ + gpg_err_code_t ret = GPG_ERR_ENOMEM; + unsigned char *buf = xcalloc_secure (1, test->expectedlen); + if (!buf) + return GPG_ERR_ENOMEM; + + ret = gcry_drbg_cavs_test (test, buf); + ret = memcmp (test->expected, buf, test->expectedlen); + + xfree (buf); + return ret; +} + +/* + * Tests as defined in 11.3.2 in addition to the cipher tests: testing + * of the error handling. + * + * Note, testing the reseed counter is not done as an automatic reseeding + * is performed in gcry_drbg_generate when the reseed counter is too large. + */ +static gpg_err_code_t +gcry_drbg_healthcheck_sanity (struct gcry_drbg_test_vector *test) +{ + unsigned int len = 0; + struct gcry_drbg_state *drbg = NULL; + gpg_err_code_t ret = GPG_ERR_GENERAL; + gpg_err_code_t tmpret = GPG_ERR_GENERAL; + struct gcry_drbg_test_data test_data; + struct gcry_drbg_string addtl, testentropy; + int coreref = 0; + unsigned char *buf = NULL; + size_t max_addtllen, max_request_bytes; + + /* only perform test in FIPS mode */ + if (0 == fips_mode ()) + return 0; + + buf = xcalloc_secure (1, test->expectedlen); + if (!buf) + return GPG_ERR_ENOMEM; + tmpret = gcry_drbg_algo_available (test->flags, &coreref); + if (tmpret) + goto outbuf; + drbg = xcalloc_secure (1, sizeof (struct gcry_drbg_state)); + if (!drbg) + goto outbuf; + + /* if the following tests fail, it is likely that there is a buffer + * overflow and we get a SIGSEV */ + ret = gcry_drbg_instantiate (drbg, NULL, coreref, 1); + if (ret) + goto outbuf; + max_addtllen = gcry_drbg_max_addtl (); + max_request_bytes = gcry_drbg_max_request_bytes (); + /* overflow addtllen with additonal info string */ + gcry_drbg_string_fill (&addtl, test->addtla, (max_addtllen + 1)); + len = gcry_drbg_generate (drbg, buf, test->expectedlen, &addtl); + if (len) + goto outdrbg; + + /* overflow max_bits */ + len = gcry_drbg_generate (drbg, buf, (max_request_bytes + 1), NULL); + if (len) + goto outdrbg; + gcry_drbg_uninstantiate (drbg); + + /* test failing entropy source as defined in 11.3.2 */ + test_data.testentropy = NULL; + test_data.fail_seed_source = 1; + drbg->test_data = &test_data; + tmpret = gcry_drbg_instantiate (drbg, NULL, coreref, 0); + if (!tmpret) + goto outdrbg; + test_data.fail_seed_source = 0; + + test_data.testentropy = &testentropy; + gcry_drbg_string_fill (&testentropy, test->entropy, test->entropylen); + /* overflow max addtllen with personalization string */ + tmpret = gcry_drbg_instantiate (drbg, &addtl, coreref, 0); + if (!tmpret) + goto outdrbg; + + dbg (("DRBG: Sanity tests for failure code paths successfully completed\n")); + ret = 0; + +outdrbg: + gcry_drbg_uninstantiate (drbg); +outbuf: + xfree (buf); + xfree (drbg); + return ret; +} + +/* + * DRBG Healthcheck function as required in SP800-90A + * + * return: + * 0 on success (all tests pass) + * >0 on error (return code indicate the number of failures) + */ +static int +gcry_drbg_healthcheck (void) +{ + int ret = 0; + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_nopr[0]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_nopr[1]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_nopr[2]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_nopr[3]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_nopr[4]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_pr[0]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_pr[1]); + ret += gcry_drbg_healthcheck_one (&gcry_drbg_test_pr[2]); + ret += gcry_drbg_healthcheck_sanity (&gcry_drbg_test_nopr[0]); + return ret; +} + +/* Run the self-tests. */ +gcry_error_t +_gcry_drbg_selftest (selftest_report_func_t report) +{ + gcry_err_code_t ec; + const char *errtxt = NULL; + gcry_drbg_lock (); + if (0 != gcry_drbg_healthcheck ()) + errtxt = "RNG output does not match known value"; + gcry_drbg_unlock (); + if (report && errtxt) + report ("random", 0, "KAT", errtxt); + ec = errtxt ? GPG_ERR_SELFTEST_FAILED : 0; + return gpg_error (ec); +} + +/*************************************************************** + * Cipher invocations requested by DRBG + ***************************************************************/ + +static gpg_err_code_t +gcry_drbg_hmac (struct gcry_drbg_state *drbg, const unsigned char *key, + unsigned char *outval, const struct gcry_drbg_string *buf) +{ + gpg_error_t err; + gcry_md_hd_t hd; + + if (key) + { + err = + _gcry_md_open (&hd, drbg->core->backend_cipher, GCRY_MD_FLAG_HMAC); + if (err) + return err; + err = _gcry_md_setkey (hd, key, gcry_drbg_statelen (drbg)); + if (err) + return err; + } + else + { + err = _gcry_md_open (&hd, drbg->core->backend_cipher, 0); + if (err) + return err; + } + for (; NULL != buf; buf = buf->next) + _gcry_md_write (hd, buf->buf, buf->len); + _gcry_md_final (hd); + memcpy (outval, _gcry_md_read (hd, drbg->core->backend_cipher), + gcry_drbg_blocklen (drbg)); + _gcry_md_close (hd); + return 0; +} + +static gpg_err_code_t +gcry_drbg_sym (struct gcry_drbg_state *drbg, const unsigned char *key, + unsigned char *outval, const struct gcry_drbg_string *buf) +{ + gpg_error_t err; + gcry_cipher_hd_t hd; + + err = + _gcry_cipher_open (&hd, drbg->core->backend_cipher, GCRY_CIPHER_MODE_ECB, + 0); + if (err) + return err; + if (gcry_drbg_blocklen (drbg) != + _gcry_cipher_get_algo_blklen (drbg->core->backend_cipher)) + return -GPG_ERR_NO_ERROR; + if (gcry_drbg_blocklen (drbg) < buf->len) + return -GPG_ERR_NO_ERROR; + err = _gcry_cipher_setkey (hd, key, gcry_drbg_keylen (drbg)); + if (err) + return err; + /* in is only component */ + _gcry_cipher_encrypt (hd, outval, gcry_drbg_blocklen (drbg), buf->buf, + buf->len); + _gcry_cipher_close (hd); + return 0; +} diff --git a/random/rand-internal.h b/random/rand-internal.h index 79b23ace..62eecdec 100644 --- a/random/rand-internal.h +++ b/random/rand-internal.h @@ -1,152 +1,161 @@ /* rand-internal.h - header to glue the random functions * Copyright (C) 1998, 2002 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser general Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #ifndef G10_RAND_INTERNAL_H #define G10_RAND_INTERNAL_H #include "../src/cipher-proto.h" /* Constants used to define the origin of random added to the pool. The code is sensitive to the order of the values. */ enum random_origins { RANDOM_ORIGIN_INIT = 0, /* Used only for initialization. */ RANDOM_ORIGIN_EXTERNAL = 1, /* Added from an external source. */ RANDOM_ORIGIN_FASTPOLL = 2, /* Fast random poll function. */ RANDOM_ORIGIN_SLOWPOLL = 3, /* Slow poll function. */ RANDOM_ORIGIN_EXTRAPOLL = 4 /* Used to mark an extra pool seed due to a GCRY_VERY_STRONG_RANDOM random request. */ }; /*-- random.c --*/ void _gcry_random_progress (const char *what, int printchar, int current, int total); /*-- random-csprng.c --*/ void _gcry_rngcsprng_initialize (int full); void _gcry_rngcsprng_close_fds (void); void _gcry_rngcsprng_dump_stats (void); void _gcry_rngcsprng_secure_alloc (void); void _gcry_rngcsprng_enable_quick_gen (void); void _gcry_rngcsprng_set_daemon_socket (const char *socketname); int _gcry_rngcsprng_use_daemon (int onoff); int _gcry_rngcsprng_is_faked (void); gcry_error_t _gcry_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality); void *_gcry_rngcsprng_get_bytes (size_t nbytes, enum gcry_random_level level); void *_gcry_rngcsprng_get_bytes_secure (size_t nbytes, enum gcry_random_level level); void _gcry_rngcsprng_randomize (void *buffer, size_t length, enum gcry_random_level level); void _gcry_rngcsprng_set_seed_file (const char *name); void _gcry_rngcsprng_update_seed_file (void); void _gcry_rngcsprng_fast_poll (void); /*-- random-fips.c --*/ void _gcry_rngfips_initialize (int full); void _gcry_rngfips_close_fds (void); void _gcry_rngfips_dump_stats (void); int _gcry_rngfips_is_faked (void); gcry_error_t _gcry_rngfips_add_bytes (const void *buf, size_t buflen, int quality); void _gcry_rngfips_randomize (void *buffer, size_t length, enum gcry_random_level level); void _gcry_rngfips_create_nonce (void *buffer, size_t length); gcry_error_t _gcry_rngfips_selftest (selftest_report_func_t report); gcry_err_code_t _gcry_rngfips_init_external_test (void **r_context, unsigned int flags, const void *key, size_t keylen, const void *seed, size_t seedlen, const void *dt, size_t dtlen); gcry_err_code_t _gcry_rngfips_run_external_test (void *context, char *buffer, size_t buflen); void _gcry_rngfips_deinit_external_test (void *context); +/*-- drbg.c --*/ +void _gcry_drbg_init(int full); +void _gcry_drbg_close_fds(void); +void _gcry_drbg_dump_stats(void); +int _gcry_drbg_is_faked (void); +gcry_error_t _gcry_drbg_add_bytes (const void *buf, size_t buflen, int quality); +void _gcry_drbg_randomize (void *buffer, size_t length, + enum gcry_random_level level); +gcry_error_t _gcry_drbg_selftest (selftest_report_func_t report); /*-- random-system.c --*/ void _gcry_rngsystem_initialize (int full); void _gcry_rngsystem_close_fds (void); void _gcry_rngsystem_dump_stats (void); int _gcry_rngsystem_is_faked (void); gcry_error_t _gcry_rngsystem_add_bytes (const void *buf, size_t buflen, int quality); void _gcry_rngsystem_randomize (void *buffer, size_t length, enum gcry_random_level level); /*-- rndlinux.c --*/ int _gcry_rndlinux_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, size_t length, int level); /*-- rndunix.c --*/ int _gcry_rndunix_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, size_t length, int level); /*-- rndelg.c --*/ int _gcry_rndegd_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, size_t length, int level); int _gcry_rndegd_connect_socket (int nofail); /*-- rndw32.c --*/ int _gcry_rndw32_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, size_t length, int level); void _gcry_rndw32_gather_random_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin ); /*-- rndw32ce.c --*/ int _gcry_rndw32ce_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, size_t length, int level); void _gcry_rndw32ce_gather_random_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin ); /*-- rndhw.c --*/ int _gcry_rndhw_failed_p (void); void _gcry_rndhw_poll_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin); size_t _gcry_rndhw_poll_slow (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin); #endif /*G10_RAND_INTERNAL_H*/ diff --git a/random/random.c b/random/random.c index 41d4cb36..4475d3c7 100644 --- a/random/random.c +++ b/random/random.c @@ -1,546 +1,507 @@ /* random.c - Random number switch * Copyright (C) 2003, 2006, 2008, 2012 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ /* This module switches between different implementations of random number generators and provides a few help functions. */ #include #include #include #include #include #include #include #include "g10lib.h" #include "random.h" #include "rand-internal.h" #include "cipher.h" /* For _gcry_sha1_hash_buffer(). */ /* If not NULL a progress function called from certain places and the opaque value passed along. Registered by _gcry_register_random_progress (). */ static void (*progress_cb) (void *,const char*,int,int, int ); static void *progress_cb_data; /* Flags indicating the requested RNG types. */ static struct { int standard; int fips; int system; } rng_types; /* This is the lock we use to protect the buffer used by the nonce generation. */ GPGRT_LOCK_DEFINE (nonce_buffer_lock); /* --- Functions --- */ /* Used to register a progress callback. This needs to be called before any threads are created. */ void _gcry_register_random_progress (void (*cb)(void *,const char*,int,int,int), void *cb_data ) { progress_cb = cb; progress_cb_data = cb_data; } /* This progress function is currently used by the random modules to give hints on how much more entropy is required. */ void _gcry_random_progress (const char *what, int printchar, int current, int total) { if (progress_cb) progress_cb (progress_cb_data, what, printchar, current, total); } /* Set the preferred RNG type. This may be called at any time even before gcry_check_version. Thus we can't assume any thread system initialization. A type of 0 is used to indicate that any Libgcrypt initialization has been done.*/ void _gcry_set_preferred_rng_type (int type) { static int any_init; if (!type) { any_init = 1; } else if (type == GCRY_RNG_TYPE_STANDARD) { rng_types.standard = 1; } else if (any_init) { /* After any initialization has been done we only allow to upgrade to the standard RNG (handled above). All other requests are ignored. The idea is that the application needs to declare a preference for a weaker RNG as soon as possible and before any library sets a preference. We assume that a library which uses Libgcrypt calls an init function very early. This way --- even if the library gets initialized early by the application --- it is unlikely that it can select a lower priority RNG. This scheme helps to ensure that existing unmodified applications (e.g. gpg2), which don't known about the new RNG selection system, will continue to use the standard RNG and not be tricked by some library to use a lower priority RNG. There are some loopholes here but at least most GnuPG stuff should be save because it calls src_c{gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);} quite early and thus inhibits switching to a low priority RNG. */ } else if (type == GCRY_RNG_TYPE_FIPS) { rng_types.fips = 1; } else if (type == GCRY_RNG_TYPE_SYSTEM) { rng_types.system = 1; } } /* Initialize this random subsystem. If FULL is false, this function merely calls the basic initialization of the module and does not do anything more. Doing this is not really required but when running in a threaded environment we might get a race condition otherwise. */ void _gcry_random_initialize (int full) { if (fips_mode ()) - _gcry_rngfips_initialize (full); + _gcry_drbg_init(full); else if (rng_types.standard) _gcry_rngcsprng_initialize (full); else if (rng_types.fips) - _gcry_rngfips_initialize (full); + _gcry_drbg_init(full); else if (rng_types.system) _gcry_rngsystem_initialize (full); else _gcry_rngcsprng_initialize (full); } /* If possible close file descriptors used by the RNG. */ void _gcry_random_close_fds (void) { /* Note that we can't do that directly because each random system has its own lock functions which need to be used for accessing the entropy gatherer. */ if (fips_mode ()) - _gcry_rngfips_close_fds (); + _gcry_drbg_close_fds (); else if (rng_types.standard) _gcry_rngcsprng_close_fds (); else if (rng_types.fips) - _gcry_rngfips_close_fds (); + _gcry_drbg_close_fds (); else if (rng_types.system) _gcry_rngsystem_close_fds (); else _gcry_rngcsprng_close_fds (); } /* Return the current RNG type. IGNORE_FIPS_MODE is a flag used to skip the test for FIPS. This is useful, so that we are able to return the type of the RNG even before we have setup FIPS mode (note that FIPS mode is enabled by default until it is switched off by the initialization). This is mostly useful for the regression test. */ int _gcry_get_rng_type (int ignore_fips_mode) { if (!ignore_fips_mode && fips_mode ()) return GCRY_RNG_TYPE_FIPS; else if (rng_types.standard) return GCRY_RNG_TYPE_STANDARD; else if (rng_types.fips) return GCRY_RNG_TYPE_FIPS; else if (rng_types.system) return GCRY_RNG_TYPE_SYSTEM; else return GCRY_RNG_TYPE_STANDARD; } void _gcry_random_dump_stats (void) { if (fips_mode ()) - _gcry_rngfips_dump_stats (); + _gcry_drbg_dump_stats (); else _gcry_rngcsprng_dump_stats (); } /* This function should be called during initialization and before initialization of this module to place the random pools into secure memory. */ void _gcry_secure_random_alloc (void) { if (fips_mode ()) ; /* Not used; the FIPS RNG is always in secure mode. */ else _gcry_rngcsprng_secure_alloc (); } /* This may be called before full initialization to degrade the quality of the RNG for the sake of a faster running test suite. */ void _gcry_enable_quick_random_gen (void) { if (fips_mode ()) ; /* Not used. */ else _gcry_rngcsprng_enable_quick_gen (); } void _gcry_set_random_daemon_socket (const char *socketname) { if (fips_mode ()) ; /* Not used. */ else _gcry_rngcsprng_set_daemon_socket (socketname); } /* With ONOFF set to 1, enable the use of the daemon. With ONOFF set to 0, disable the use of the daemon. With ONOF set to -1, return whether the daemon has been enabled. */ int _gcry_use_random_daemon (int onoff) { if (fips_mode ()) return 0; /* Never enabled in fips mode. */ else return _gcry_rngcsprng_use_daemon (onoff); } /* This function returns true if no real RNG is available or the quality of the RNG has been degraded for test purposes. */ int _gcry_random_is_faked (void) { if (fips_mode ()) - return _gcry_rngfips_is_faked (); + return _gcry_drbg_is_faked (); else return _gcry_rngcsprng_is_faked (); } /* Add BUFLEN bytes from BUF to the internal random pool. QUALITY should be in the range of 0..100 to indicate the goodness of the entropy added, or -1 for goodness not known. */ gcry_err_code_t _gcry_random_add_bytes (const void *buf, size_t buflen, int quality) { if (fips_mode ()) return 0; /* No need for this in fips mode. */ else if (rng_types.standard) return gpg_err_code (_gcry_rngcsprng_add_bytes (buf, buflen, quality)); else if (rng_types.fips) return 0; else if (rng_types.system) return 0; else /* default */ return gpg_err_code (_gcry_rngcsprng_add_bytes (buf, buflen, quality)); } /* Helper function. */ static void do_randomize (void *buffer, size_t length, enum gcry_random_level level) { if (fips_mode ()) - _gcry_rngfips_randomize (buffer, length, level); + _gcry_drbg_randomize (buffer, length, level); else if (rng_types.standard) _gcry_rngcsprng_randomize (buffer, length, level); else if (rng_types.fips) - _gcry_rngfips_randomize (buffer, length, level); + _gcry_drbg_randomize (buffer, length, level); else if (rng_types.system) _gcry_rngsystem_randomize (buffer, length, level); else /* default */ _gcry_rngcsprng_randomize (buffer, length, level); } /* The public function to return random data of the quality LEVEL. Returns a pointer to a newly allocated and randomized buffer of LEVEL and NBYTES length. Caller must free the buffer. */ void * _gcry_random_bytes (size_t nbytes, enum gcry_random_level level) { void *buffer; buffer = xmalloc (nbytes); do_randomize (buffer, nbytes, level); return buffer; } /* The public function to return random data of the quality LEVEL; this version of the function returns the random in a buffer allocated in secure memory. Caller must free the buffer. */ void * _gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level) { void *buffer; /* Historical note (1.3.0--1.4.1): The buffer was only allocated in secure memory if the pool in random-csprng.c was also set to use secure memory. */ buffer = xmalloc_secure (nbytes); do_randomize (buffer, nbytes, level); return buffer; } /* Public function to fill the buffer with LENGTH bytes of cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is not very strong, GCRY_STRONG_RANDOM is strong enough for most usage, GCRY_VERY_STRONG_RANDOM is good for key generation stuff but may be very slow. */ void _gcry_randomize (void *buffer, size_t length, enum gcry_random_level level) { do_randomize (buffer, length, level); } /* This function may be used to specify the file to be used as a seed file for the PRNG. This function should be called prior to the initialization of the random module. NAME may not be NULL. */ void _gcry_set_random_seed_file (const char *name) { if (fips_mode ()) ; /* No need for this in fips mode. */ else if (rng_types.standard) _gcry_rngcsprng_set_seed_file (name); else if (rng_types.fips) ; else if (rng_types.system) ; else /* default */ _gcry_rngcsprng_set_seed_file (name); } /* If a seed file has been setup, this function may be used to write back the random numbers entropy pool. */ void _gcry_update_random_seed_file (void) { if (fips_mode ()) ; /* No need for this in fips mode. */ else if (rng_types.standard) _gcry_rngcsprng_update_seed_file (); else if (rng_types.fips) ; else if (rng_types.system) ; else /* default */ _gcry_rngcsprng_update_seed_file (); } /* The fast random pool function as called at some places in libgcrypt. This is merely a wrapper to make sure that this module is initialized and to lock the pool. Note, that this function is a NOP unless a random function has been used or _gcry_initialize (1) has been used. We use this hack so that the internal use of this function in cipher_open and md_open won't start filling up the random pool, even if no random will be required by the process. */ void _gcry_fast_random_poll (void) { if (fips_mode ()) ; /* No need for this in fips mode. */ else if (rng_types.standard) _gcry_rngcsprng_fast_poll (); else if (rng_types.fips) ; else if (rng_types.system) ; else /* default */ _gcry_rngcsprng_fast_poll (); } /* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ void _gcry_create_nonce (void *buffer, size_t length) { static unsigned char nonce_buffer[20+8]; static int nonce_buffer_initialized = 0; static volatile pid_t my_pid; /* The volatile is there to make sure the compiler does not optimize the code away in case the getpid function is badly attributed. */ volatile pid_t apid; unsigned char *p; size_t n; int err; /* First check whether we shall use the FIPS nonce generator. This is only done in FIPS mode, in all other modes, we use our own nonce generator which is seeded by the RNG actual in use. */ if (fips_mode ()) { - _gcry_rngfips_create_nonce (buffer, length); + _gcry_drbg_randomize (buffer, length, GCRY_WEAK_RANDOM); return; } /* This is the nonce generator, which formerly lived in random-csprng.c. It is now used by all RNG types except when in FIPS mode (not that this means it is also used if the FIPS RNG has been selected but we are not in fips mode). */ /* Make sure we are initialized. */ _gcry_random_initialize (1); /* Acquire the nonce buffer lock. */ err = gpgrt_lock_lock (&nonce_buffer_lock); if (err) log_fatal ("failed to acquire the nonce buffer lock: %s\n", gpg_strerror (err)); apid = getpid (); /* The first time initialize our buffer. */ if (!nonce_buffer_initialized) { time_t atime = time (NULL); pid_t xpid = apid; my_pid = apid; if ((sizeof apid + sizeof atime) > sizeof nonce_buffer) BUG (); /* Initialize the first 20 bytes with a reasonable value so that a failure of gcry_randomize won't affect us too much. Don't care about the uninitialized remaining bytes. */ p = nonce_buffer; memcpy (p, &xpid, sizeof xpid); p += sizeof xpid; memcpy (p, &atime, sizeof atime); /* Initialize the never changing private part of 64 bits. */ _gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM); nonce_buffer_initialized = 1; } else if ( my_pid != apid ) { /* We forked. Need to reseed the buffer - doing this for the private part should be sufficient. */ do_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM); /* Update the pid so that we won't run into here again and again. */ my_pid = apid; } /* Create the nonce by hashing the entire buffer, returning the hash and updating the first 20 bytes of the buffer with this hash. */ for (p = buffer; length > 0; length -= n, p += n) { _gcry_sha1_hash_buffer (nonce_buffer, nonce_buffer, sizeof nonce_buffer); n = length > 20? 20 : length; memcpy (p, nonce_buffer, n); } /* Release the nonce buffer lock. */ err = gpgrt_lock_unlock (&nonce_buffer_lock); if (err) log_fatal ("failed to release the nonce buffer lock: %s\n", gpg_strerror (err)); } /* Run the self-tests for the RNG. This is currently only implemented for the FIPS generator. */ gpg_error_t _gcry_random_selftest (selftest_report_func_t report) { if (fips_mode ()) - return _gcry_rngfips_selftest (report); + return _gcry_drbg_selftest (report); else return 0; /* No selftests yet. */ } - - -/* Create a new test context for an external RNG test driver. On - success the test context is stored at R_CONTEXT; on failure NULL is - stored at R_CONTEXT and an error code is returned. */ -gcry_err_code_t -_gcry_random_init_external_test (void **r_context, - unsigned int flags, - const void *key, size_t keylen, - const void *seed, size_t seedlen, - const void *dt, size_t dtlen) -{ - (void)flags; - if (fips_mode ()) - return _gcry_rngfips_init_external_test (r_context, flags, key, keylen, - seed, seedlen, - dt, dtlen); - else - return GPG_ERR_NOT_SUPPORTED; -} - -/* Get BUFLEN bytes from the RNG using the test CONTEXT and store them - at BUFFER. Return 0 on success or an error code. */ -gcry_err_code_t -_gcry_random_run_external_test (void *context, char *buffer, size_t buflen) -{ - if (fips_mode ()) - return _gcry_rngfips_run_external_test (context, buffer, buflen); - else - return GPG_ERR_NOT_SUPPORTED; -} - -/* Release the test CONTEXT. */ -void -_gcry_random_deinit_external_test (void *context) -{ - if (fips_mode ()) - _gcry_rngfips_deinit_external_test (context); -} diff --git a/random/random.h b/random/random.h index 2bc8cabc..96239718 100644 --- a/random/random.h +++ b/random/random.h @@ -1,69 +1,95 @@ /* random.h - random functions * Copyright (C) 1998, 2002, 2006 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #ifndef G10_RANDOM_H #define G10_RANDOM_H #include "types.h" /*-- random.c --*/ void _gcry_register_random_progress (void (*cb)(void *,const char*,int,int,int), void *cb_data ); void _gcry_set_preferred_rng_type (int type); void _gcry_random_initialize (int full); void _gcry_random_close_fds (void); int _gcry_get_rng_type (int ignore_fips_mode); void _gcry_random_dump_stats(void); void _gcry_secure_random_alloc(void); void _gcry_enable_quick_random_gen (void); int _gcry_random_is_faked(void); void _gcry_set_random_daemon_socket (const char *socketname); int _gcry_use_random_daemon (int onoff); void _gcry_set_random_seed_file (const char *name); void _gcry_update_random_seed_file (void); byte *_gcry_get_random_bits( size_t nbits, int level, int secure ); void _gcry_fast_random_poll( void ); gcry_err_code_t _gcry_random_init_external_test (void **r_context, unsigned int flags, const void *key, size_t keylen, const void *seed, size_t seedlen, const void *dt, size_t dtlen); gcry_err_code_t _gcry_random_run_external_test (void *context, char *buffer, size_t buflen); void _gcry_random_deinit_external_test (void *context); +/*-- drbg.c --*/ +gpg_err_code_t _gcry_drbg_reinit (u32 flags, struct gcry_drbg_string *pers); +/* private interfaces for testing of DRBG */ +struct gcry_drbg_test_vector +{ + u32 flags; + unsigned char *entropy; + size_t entropylen; + unsigned char *entpra; + unsigned char *entprb; + size_t entprlen; + unsigned char *addtla; + unsigned char *addtlb; + size_t addtllen; + unsigned char *pers; + size_t perslen; + unsigned char *expected; + size_t expectedlen; + unsigned char *entropyreseed; + size_t entropyreseed_len; + unsigned char *addtl_reseed; + size_t addtl_reseed_len; +}; +gpg_err_code_t gcry_drbg_cavs_test (struct gcry_drbg_test_vector *test, + unsigned char *buf); +gpg_err_code_t gcry_drbg_healthcheck_one (struct gcry_drbg_test_vector *test); /*-- rndegd.c --*/ gpg_error_t _gcry_rndegd_set_socket_name (const char *name); /*-- random-daemon.c (only used from random.c) --*/ #ifdef USE_RANDOM_DAEMON void _gcry_daemon_initialize_basics (void); int _gcry_daemon_randomize (const char *socketname, void *buffer, size_t length, enum gcry_random_level level); #endif /*USE_RANDOM_DAEMON*/ #endif /*G10_RANDOM_H*/ diff --git a/src/gcrypt.h.in b/src/gcrypt.h.in index f48f04fb..f1f13919 100644 --- a/src/gcrypt.h.in +++ b/src/gcrypt.h.in @@ -1,1737 +1,1845 @@ /* gcrypt.h - GNU Cryptographic Library Interface -*- c -*- * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, * 2006, 2007, 2008, 2009, 2010, 2011, * 2012 Free Software Foundation, Inc. * Copyright (C) 2012, 2013 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * * File: @configure_input@ */ #ifndef _GCRYPT_H #define _GCRYPT_H #include #include #include #include #include #if defined _WIN32 || defined __WIN32__ # include # include # include # ifndef __GNUC__ typedef long ssize_t; typedef int pid_t; # endif /*!__GNUC__*/ #else # include # include #@INSERT_SYS_SELECT_H@ #endif /*!_WIN32*/ @FALLBACK_SOCKLEN_T@ /* This is required for error code compatibility. */ #define _GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GCRYPT #ifdef __cplusplus extern "C" { #if 0 /* (Keep Emacsens' auto-indent happy.) */ } #endif #endif /* The version of this header should match the one of the library. It should not be used by a program because gcry_check_version() should return the same version. The purpose of this macro is to let autoconf (using the AM_PATH_GCRYPT macro) check that this header matches the installed library. */ #define GCRYPT_VERSION "@VERSION@" /* The version number of this header. It may be used to handle minor API incompatibilities. */ #define GCRYPT_VERSION_NUMBER @VERSION_NUMBER@ /* Internal: We can't use the convenience macros for the multi precision integer functions when building this library. */ #ifdef _GCRYPT_IN_LIBGCRYPT #ifndef GCRYPT_NO_MPI_MACROS #define GCRYPT_NO_MPI_MACROS 1 #endif #endif /* We want to use gcc attributes when possible. Warning: Don't use these macros in your programs: As indicated by the leading underscore they are subject to change without notice. */ #ifdef __GNUC__ #define _GCRY_GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if _GCRY_GCC_VERSION >= 30100 #define _GCRY_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__)) #endif #if _GCRY_GCC_VERSION >= 29600 #define _GCRY_GCC_ATTR_PURE __attribute__ ((__pure__)) #endif #if _GCRY_GCC_VERSION >= 30200 #define _GCRY_GCC_ATTR_MALLOC __attribute__ ((__malloc__)) #endif #define _GCRY_GCC_ATTR_PRINTF(f,a) __attribute__ ((format (printf,f,a))) #if _GCRY_GCC_VERSION >= 40000 #define _GCRY_GCC_ATTR_SENTINEL(a) __attribute__ ((sentinel(a))) #endif #endif /*__GNUC__*/ #ifndef _GCRY_GCC_ATTR_DEPRECATED #define _GCRY_GCC_ATTR_DEPRECATED #endif #ifndef _GCRY_GCC_ATTR_PURE #define _GCRY_GCC_ATTR_PURE #endif #ifndef _GCRY_GCC_ATTR_MALLOC #define _GCRY_GCC_ATTR_MALLOC #endif #ifndef _GCRY_GCC_ATTR_PRINTF #define _GCRY_GCC_ATTR_PRINTF(f,a) #endif #ifndef _GCRY_GCC_ATTR_SENTINEL #define _GCRY_GCC_ATTR_SENTINEL(a) #endif /* Make up an attribute to mark functions and types as deprecated but allow internal use by Libgcrypt. */ #ifdef _GCRYPT_IN_LIBGCRYPT #define _GCRY_ATTR_INTERNAL #else #define _GCRY_ATTR_INTERNAL _GCRY_GCC_ATTR_DEPRECATED #endif /* Wrappers for the libgpg-error library. */ typedef gpg_error_t gcry_error_t; typedef gpg_err_code_t gcry_err_code_t; typedef gpg_err_source_t gcry_err_source_t; static GPG_ERR_INLINE gcry_error_t gcry_err_make (gcry_err_source_t source, gcry_err_code_t code) { return gpg_err_make (source, code); } /* The user can define GPG_ERR_SOURCE_DEFAULT before including this file to specify a default source for gpg_error. */ #ifndef GCRY_ERR_SOURCE_DEFAULT #define GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_USER_1 #endif static GPG_ERR_INLINE gcry_error_t gcry_error (gcry_err_code_t code) { return gcry_err_make (GCRY_ERR_SOURCE_DEFAULT, code); } static GPG_ERR_INLINE gcry_err_code_t gcry_err_code (gcry_error_t err) { return gpg_err_code (err); } static GPG_ERR_INLINE gcry_err_source_t gcry_err_source (gcry_error_t err) { return gpg_err_source (err); } /* Return a pointer to a string containing a description of the error code in the error value ERR. */ const char *gcry_strerror (gcry_error_t err); /* Return a pointer to a string containing a description of the error source in the error value ERR. */ const char *gcry_strsource (gcry_error_t err); /* Retrieve the error code for the system error ERR. This returns GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report this). */ gcry_err_code_t gcry_err_code_from_errno (int err); /* Retrieve the system error for the error code CODE. This returns 0 if CODE is not a system error code. */ int gcry_err_code_to_errno (gcry_err_code_t code); /* Return an error value with the error source SOURCE and the system error ERR. */ gcry_error_t gcry_err_make_from_errno (gcry_err_source_t source, int err); /* Return an error value with the system error ERR. */ gcry_err_code_t gcry_error_from_errno (int err); /* NOTE: Since Libgcrypt 1.6 the thread callbacks are not anymore used. However we keep it to allow for some source code compatibility if used in the standard way. */ /* Constants defining the thread model to use. Used with the OPTION field of the struct gcry_thread_cbs. */ #define GCRY_THREAD_OPTION_DEFAULT 0 #define GCRY_THREAD_OPTION_USER 1 #define GCRY_THREAD_OPTION_PTH 2 #define GCRY_THREAD_OPTION_PTHREAD 3 /* The version number encoded in the OPTION field of the struct gcry_thread_cbs. */ #define GCRY_THREAD_OPTION_VERSION 1 /* Wrapper for struct ath_ops. */ struct gcry_thread_cbs { /* The OPTION field encodes the thread model and the version number of this structure. Bits 7 - 0 are used for the thread model Bits 15 - 8 are used for the version number. */ unsigned int option; } _GCRY_ATTR_INTERNAL; #define GCRY_THREAD_OPTION_PTH_IMPL \ static struct gcry_thread_cbs gcry_threads_pth = { \ (GCRY_THREAD_OPTION_PTH | (GCRY_THREAD_OPTION_VERSION << 8))} #define GCRY_THREAD_OPTION_PTHREAD_IMPL \ static struct gcry_thread_cbs gcry_threads_pthread = { \ (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8))} /* A generic context object as used by some functions. */ struct gcry_context; typedef struct gcry_context *gcry_ctx_t; /* The data objects used to hold multi precision integers. */ struct gcry_mpi; typedef struct gcry_mpi *gcry_mpi_t; struct gcry_mpi_point; typedef struct gcry_mpi_point *gcry_mpi_point_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_mpi *GCRY_MPI _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_mpi *GcryMPI _GCRY_GCC_ATTR_DEPRECATED; #endif /* A structure used for scatter gather hashing. */ typedef struct { size_t size; /* The allocated size of the buffer or 0. */ size_t off; /* Offset into the buffer. */ size_t len; /* The used length of the buffer. */ void *data; /* The buffer. */ } gcry_buffer_t; /* Check that the library fulfills the version requirement. */ const char *gcry_check_version (const char *req_version); /* Codes for function dispatchers. */ /* Codes used with the gcry_control function. */ enum gcry_ctl_cmds { /* Note: 1 .. 2 are not anymore used. */ GCRYCTL_CFB_SYNC = 3, GCRYCTL_RESET = 4, /* e.g. for MDs */ GCRYCTL_FINALIZE = 5, GCRYCTL_GET_KEYLEN = 6, GCRYCTL_GET_BLKLEN = 7, GCRYCTL_TEST_ALGO = 8, GCRYCTL_IS_SECURE = 9, GCRYCTL_GET_ASNOID = 10, GCRYCTL_ENABLE_ALGO = 11, GCRYCTL_DISABLE_ALGO = 12, GCRYCTL_DUMP_RANDOM_STATS = 13, GCRYCTL_DUMP_SECMEM_STATS = 14, GCRYCTL_GET_ALGO_NPKEY = 15, GCRYCTL_GET_ALGO_NSKEY = 16, GCRYCTL_GET_ALGO_NSIGN = 17, GCRYCTL_GET_ALGO_NENCR = 18, GCRYCTL_SET_VERBOSITY = 19, GCRYCTL_SET_DEBUG_FLAGS = 20, GCRYCTL_CLEAR_DEBUG_FLAGS = 21, GCRYCTL_USE_SECURE_RNDPOOL= 22, GCRYCTL_DUMP_MEMORY_STATS = 23, GCRYCTL_INIT_SECMEM = 24, GCRYCTL_TERM_SECMEM = 25, GCRYCTL_DISABLE_SECMEM_WARN = 27, GCRYCTL_SUSPEND_SECMEM_WARN = 28, GCRYCTL_RESUME_SECMEM_WARN = 29, GCRYCTL_DROP_PRIVS = 30, GCRYCTL_ENABLE_M_GUARD = 31, GCRYCTL_START_DUMP = 32, GCRYCTL_STOP_DUMP = 33, GCRYCTL_GET_ALGO_USAGE = 34, GCRYCTL_IS_ALGO_ENABLED = 35, GCRYCTL_DISABLE_INTERNAL_LOCKING = 36, GCRYCTL_DISABLE_SECMEM = 37, GCRYCTL_INITIALIZATION_FINISHED = 38, GCRYCTL_INITIALIZATION_FINISHED_P = 39, GCRYCTL_ANY_INITIALIZATION_P = 40, GCRYCTL_SET_CBC_CTS = 41, GCRYCTL_SET_CBC_MAC = 42, /* Note: 43 is not anymore used. */ GCRYCTL_ENABLE_QUICK_RANDOM = 44, GCRYCTL_SET_RANDOM_SEED_FILE = 45, GCRYCTL_UPDATE_RANDOM_SEED_FILE = 46, GCRYCTL_SET_THREAD_CBS = 47, GCRYCTL_FAST_POLL = 48, GCRYCTL_SET_RANDOM_DAEMON_SOCKET = 49, GCRYCTL_USE_RANDOM_DAEMON = 50, GCRYCTL_FAKED_RANDOM_P = 51, GCRYCTL_SET_RNDEGD_SOCKET = 52, GCRYCTL_PRINT_CONFIG = 53, GCRYCTL_OPERATIONAL_P = 54, GCRYCTL_FIPS_MODE_P = 55, GCRYCTL_FORCE_FIPS_MODE = 56, GCRYCTL_SELFTEST = 57, /* Note: 58 .. 62 are used internally. */ GCRYCTL_DISABLE_HWF = 63, GCRYCTL_SET_ENFORCED_FIPS_FLAG = 64, GCRYCTL_SET_PREFERRED_RNG_TYPE = 65, GCRYCTL_GET_CURRENT_RNG_TYPE = 66, GCRYCTL_DISABLE_LOCKED_SECMEM = 67, GCRYCTL_DISABLE_PRIV_DROP = 68, GCRYCTL_SET_CCM_LENGTHS = 69, GCRYCTL_CLOSE_RANDOM_DEVICE = 70, GCRYCTL_INACTIVATE_FIPS_FLAG = 71, GCRYCTL_REACTIVATE_FIPS_FLAG = 72, GCRYCTL_SET_SBOX = 73, GCRYCTL_DRBG_REINIT = 74, GCRYCTL_SET_TAGLEN = 75 }; /* Perform various operations defined by CMD. */ gcry_error_t gcry_control (enum gcry_ctl_cmds CMD, ...); /* S-expression management. */ /* The object to represent an S-expression as used with the public key functions. */ struct gcry_sexp; typedef struct gcry_sexp *gcry_sexp_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_sexp *GCRY_SEXP _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_sexp *GcrySexp _GCRY_GCC_ATTR_DEPRECATED; #endif /* The possible values for the S-expression format. */ enum gcry_sexp_format { GCRYSEXP_FMT_DEFAULT = 0, GCRYSEXP_FMT_CANON = 1, GCRYSEXP_FMT_BASE64 = 2, GCRYSEXP_FMT_ADVANCED = 3 }; /* Create an new S-expression object from BUFFER of size LENGTH and return it in RETSEXP. With AUTODETECT set to 0 the data in BUFFER is expected to be in canonized format. */ gcry_error_t gcry_sexp_new (gcry_sexp_t *retsexp, const void *buffer, size_t length, int autodetect); /* Same as gcry_sexp_new but allows to pass a FREEFNC which has the effect to transfer ownership of BUFFER to the created object. */ gcry_error_t gcry_sexp_create (gcry_sexp_t *retsexp, void *buffer, size_t length, int autodetect, void (*freefnc) (void *)); /* Scan BUFFER and return a new S-expression object in RETSEXP. This function expects a printf like string in BUFFER. */ gcry_error_t gcry_sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, const char *buffer, size_t length); /* Same as gcry_sexp_sscan but expects a string in FORMAT and can thus only be used for certain encodings. */ gcry_error_t gcry_sexp_build (gcry_sexp_t *retsexp, size_t *erroff, const char *format, ...); /* Like gcry_sexp_build, but uses an array instead of variable function arguments. */ gcry_error_t gcry_sexp_build_array (gcry_sexp_t *retsexp, size_t *erroff, const char *format, void **arg_list); /* Release the S-expression object SEXP */ void gcry_sexp_release (gcry_sexp_t sexp); /* Calculate the length of an canonized S-expresion in BUFFER and check for a valid encoding. */ size_t gcry_sexp_canon_len (const unsigned char *buffer, size_t length, size_t *erroff, gcry_error_t *errcode); /* Copies the S-expression object SEXP into BUFFER using the format specified in MODE. */ size_t gcry_sexp_sprint (gcry_sexp_t sexp, int mode, void *buffer, size_t maxlength); /* Dumps the S-expression object A in a format suitable for debugging to Libgcrypt's logging stream. */ void gcry_sexp_dump (const gcry_sexp_t a); gcry_sexp_t gcry_sexp_cons (const gcry_sexp_t a, const gcry_sexp_t b); gcry_sexp_t gcry_sexp_alist (const gcry_sexp_t *array); gcry_sexp_t gcry_sexp_vlist (const gcry_sexp_t a, ...); gcry_sexp_t gcry_sexp_append (const gcry_sexp_t a, const gcry_sexp_t n); gcry_sexp_t gcry_sexp_prepend (const gcry_sexp_t a, const gcry_sexp_t n); /* Scan the S-expression for a sublist with a type (the car of the list) matching the string TOKEN. If TOKLEN is not 0, the token is assumed to be raw memory of this length. The function returns a newly allocated S-expression consisting of the found sublist or `NULL' when not found. */ gcry_sexp_t gcry_sexp_find_token (gcry_sexp_t list, const char *tok, size_t toklen); /* Return the length of the LIST. For a valid S-expression this should be at least 1. */ int gcry_sexp_length (const gcry_sexp_t list); /* Create and return a new S-expression from the element with index NUMBER in LIST. Note that the first element has the index 0. If there is no such element, `NULL' is returned. */ gcry_sexp_t gcry_sexp_nth (const gcry_sexp_t list, int number); /* Create and return a new S-expression from the first element in LIST; this called the "type" and should always exist and be a string. `NULL' is returned in case of a problem. */ gcry_sexp_t gcry_sexp_car (const gcry_sexp_t list); /* Create and return a new list form all elements except for the first one. Note, that this function may return an invalid S-expression because it is not guaranteed, that the type exists and is a string. However, for parsing a complex S-expression it might be useful for intermediate lists. Returns `NULL' on error. */ gcry_sexp_t gcry_sexp_cdr (const gcry_sexp_t list); gcry_sexp_t gcry_sexp_cadr (const gcry_sexp_t list); /* This function is used to get data from a LIST. A pointer to the actual data with index NUMBER is returned and the length of this data will be stored to DATALEN. If there is no data at the given index or the index represents another list, `NULL' is returned. *Note:* The returned pointer is valid as long as LIST is not modified or released. */ const char *gcry_sexp_nth_data (const gcry_sexp_t list, int number, size_t *datalen); /* This function is used to get data from a LIST. A malloced buffer to the data with index NUMBER is returned and the length of this data will be stored to RLENGTH. If there is no data at the given index or the index represents another list, `NULL' is returned. */ void *gcry_sexp_nth_buffer (const gcry_sexp_t list, int number, size_t *rlength); /* This function is used to get and convert data from a LIST. The data is assumed to be a Nul terminated string. The caller must release the returned value using `gcry_free'. If there is no data at the given index, the index represents a list or the value can't be converted to a string, `NULL' is returned. */ char *gcry_sexp_nth_string (gcry_sexp_t list, int number); /* This function is used to get and convert data from a LIST. This data is assumed to be an MPI stored in the format described by MPIFMT and returned as a standard Libgcrypt MPI. The caller must release this returned value using `gcry_mpi_release'. If there is no data at the given index, the index represents a list or the value can't be converted to an MPI, `NULL' is returned. */ gcry_mpi_t gcry_sexp_nth_mpi (gcry_sexp_t list, int number, int mpifmt); /* Convenience function to extract parameters from an S-expression * using a list of single letter parameters. */ gpg_error_t gcry_sexp_extract_param (gcry_sexp_t sexp, const char *path, const char *list, ...) _GCRY_GCC_ATTR_SENTINEL(0); /******************************************* * * * Multi Precision Integer Functions * * * *******************************************/ /* Different formats of external big integer representation. */ enum gcry_mpi_format { GCRYMPI_FMT_NONE= 0, GCRYMPI_FMT_STD = 1, /* Twos complement stored without length. */ GCRYMPI_FMT_PGP = 2, /* As used by OpenPGP (unsigned only). */ GCRYMPI_FMT_SSH = 3, /* As used by SSH (like STD but with length). */ GCRYMPI_FMT_HEX = 4, /* Hex format. */ GCRYMPI_FMT_USG = 5, /* Like STD but unsigned. */ GCRYMPI_FMT_OPAQUE = 8 /* Opaque format (some functions only). */ }; /* Flags used for creating big integers. */ enum gcry_mpi_flag { GCRYMPI_FLAG_SECURE = 1, /* Allocate the number in "secure" memory. */ GCRYMPI_FLAG_OPAQUE = 2, /* The number is not a real one but just a way to store some bytes. This is useful for encrypted big integers. */ GCRYMPI_FLAG_IMMUTABLE = 4, /* Mark the MPI as immutable. */ GCRYMPI_FLAG_CONST = 8, /* Mark the MPI as a constant. */ GCRYMPI_FLAG_USER1 = 0x0100,/* User flag 1. */ GCRYMPI_FLAG_USER2 = 0x0200,/* User flag 2. */ GCRYMPI_FLAG_USER3 = 0x0400,/* User flag 3. */ GCRYMPI_FLAG_USER4 = 0x0800 /* User flag 4. */ }; /* Macros to return pre-defined MPI constants. */ #define GCRYMPI_CONST_ONE (_gcry_mpi_get_const (1)) #define GCRYMPI_CONST_TWO (_gcry_mpi_get_const (2)) #define GCRYMPI_CONST_THREE (_gcry_mpi_get_const (3)) #define GCRYMPI_CONST_FOUR (_gcry_mpi_get_const (4)) #define GCRYMPI_CONST_EIGHT (_gcry_mpi_get_const (8)) /* Allocate a new big integer object, initialize it with 0 and initially allocate memory for a number of at least NBITS. */ gcry_mpi_t gcry_mpi_new (unsigned int nbits); /* Same as gcry_mpi_new() but allocate in "secure" memory. */ gcry_mpi_t gcry_mpi_snew (unsigned int nbits); /* Release the number A and free all associated resources. */ void gcry_mpi_release (gcry_mpi_t a); /* Create a new number with the same value as A. */ gcry_mpi_t gcry_mpi_copy (const gcry_mpi_t a); /* Store the big integer value U in W and release U. */ void gcry_mpi_snatch (gcry_mpi_t w, gcry_mpi_t u); /* Store the big integer value U in W. */ gcry_mpi_t gcry_mpi_set (gcry_mpi_t w, const gcry_mpi_t u); /* Store the unsigned integer value U in W. */ gcry_mpi_t gcry_mpi_set_ui (gcry_mpi_t w, unsigned long u); /* Swap the values of A and B. */ void gcry_mpi_swap (gcry_mpi_t a, gcry_mpi_t b); /* Return 1 if A is negative; 0 if zero or positive. */ int gcry_mpi_is_neg (gcry_mpi_t a); /* W = - U */ void gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u); /* W = [W] */ void gcry_mpi_abs (gcry_mpi_t w); /* Compare the big integer number U and V returning 0 for equality, a positive value for U > V and a negative for U < V. */ int gcry_mpi_cmp (const gcry_mpi_t u, const gcry_mpi_t v); /* Compare the big integer number U with the unsigned integer V returning 0 for equality, a positive value for U > V and a negative for U < V. */ int gcry_mpi_cmp_ui (const gcry_mpi_t u, unsigned long v); /* Convert the external representation of an integer stored in BUFFER with a length of BUFLEN into a newly create MPI returned in RET_MPI. If NSCANNED is not NULL, it will receive the number of bytes actually scanned after a successful operation. */ gcry_error_t gcry_mpi_scan (gcry_mpi_t *ret_mpi, enum gcry_mpi_format format, const void *buffer, size_t buflen, size_t *nscanned); /* Convert the big integer A into the external representation described by FORMAT and store it in the provided BUFFER which has been allocated by the user with a size of BUFLEN bytes. NWRITTEN receives the actual length of the external representation unless it has been passed as NULL. */ gcry_error_t gcry_mpi_print (enum gcry_mpi_format format, unsigned char *buffer, size_t buflen, size_t *nwritten, const gcry_mpi_t a); /* Convert the big integer A into the external representation described by FORMAT and store it in a newly allocated buffer which address will be put into BUFFER. NWRITTEN receives the actual lengths of the external representation. */ gcry_error_t gcry_mpi_aprint (enum gcry_mpi_format format, unsigned char **buffer, size_t *nwritten, const gcry_mpi_t a); /* Dump the value of A in a format suitable for debugging to Libgcrypt's logging stream. Note that one leading space but no trailing space or linefeed will be printed. It is okay to pass NULL for A. */ void gcry_mpi_dump (const gcry_mpi_t a); /* W = U + V. */ void gcry_mpi_add (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U + V. V is an unsigned integer. */ void gcry_mpi_add_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v); /* W = U + V mod M. */ void gcry_mpi_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U - V. */ void gcry_mpi_sub (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U - V. V is an unsigned integer. */ void gcry_mpi_sub_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); /* W = U - V mod M */ void gcry_mpi_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U * V. */ void gcry_mpi_mul (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U * V. V is an unsigned integer. */ void gcry_mpi_mul_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); /* W = U * V mod M. */ void gcry_mpi_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U * (2 ^ CNT). */ void gcry_mpi_mul_2exp (gcry_mpi_t w, gcry_mpi_t u, unsigned long cnt); /* Q = DIVIDEND / DIVISOR, R = DIVIDEND % DIVISOR, Q or R may be passed as NULL. ROUND should be negative or 0. */ void gcry_mpi_div (gcry_mpi_t q, gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor, int round); /* R = DIVIDEND % DIVISOR */ void gcry_mpi_mod (gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor); /* W = B ^ E mod M. */ void gcry_mpi_powm (gcry_mpi_t w, const gcry_mpi_t b, const gcry_mpi_t e, const gcry_mpi_t m); /* Set G to the greatest common divisor of A and B. Return true if the G is 1. */ int gcry_mpi_gcd (gcry_mpi_t g, gcry_mpi_t a, gcry_mpi_t b); /* Set X to the multiplicative inverse of A mod M. Return true if the value exists. */ int gcry_mpi_invm (gcry_mpi_t x, gcry_mpi_t a, gcry_mpi_t m); /* Create a new point object. NBITS is usually 0. */ gcry_mpi_point_t gcry_mpi_point_new (unsigned int nbits); /* Release the object POINT. POINT may be NULL. */ void gcry_mpi_point_release (gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z. */ void gcry_mpi_point_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z and release POINT. */ void gcry_mpi_point_snatch_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates X, Y, and Z into POINT. */ gcry_mpi_point_t gcry_mpi_point_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Store the projective coordinates X, Y, and Z into POINT and release X, Y, and Z. */ gcry_mpi_point_t gcry_mpi_point_snatch_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Allocate a new context for elliptic curve operations based on the parameters given by KEYPARAM or using CURVENAME. */ gpg_error_t gcry_mpi_ec_new (gcry_ctx_t *r_ctx, gcry_sexp_t keyparam, const char *curvename); /* Get a named MPI from an elliptic curve context. */ gcry_mpi_t gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy); /* Get a named point from an elliptic curve context. */ gcry_mpi_point_t gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy); /* Store a named MPI into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx); /* Store a named point into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx); /* Decode and store VALUE into RESULT. */ gpg_error_t gcry_mpi_ec_decode_point (gcry_mpi_point_t result, gcry_mpi_t value, gcry_ctx_t ctx); /* Store the affine coordinates of POINT into X and Y. */ int gcry_mpi_ec_get_affine (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_point_t point, gcry_ctx_t ctx); /* W = 2 * U. */ void gcry_mpi_ec_dup (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_ctx_t ctx); /* W = U + V. */ void gcry_mpi_ec_add (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = U - V. */ void gcry_mpi_ec_sub (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = N * U. */ void gcry_mpi_ec_mul (gcry_mpi_point_t w, gcry_mpi_t n, gcry_mpi_point_t u, gcry_ctx_t ctx); /* Return true if POINT is on the curve described by CTX. */ int gcry_mpi_ec_curve_point (gcry_mpi_point_t w, gcry_ctx_t ctx); /* Return the number of bits required to represent A. */ unsigned int gcry_mpi_get_nbits (gcry_mpi_t a); /* Return true when bit number N (counting from 0) is set in A. */ int gcry_mpi_test_bit (gcry_mpi_t a, unsigned int n); /* Set bit number N in A. */ void gcry_mpi_set_bit (gcry_mpi_t a, unsigned int n); /* Clear bit number N in A. */ void gcry_mpi_clear_bit (gcry_mpi_t a, unsigned int n); /* Set bit number N in A and clear all bits greater than N. */ void gcry_mpi_set_highbit (gcry_mpi_t a, unsigned int n); /* Clear bit number N in A and all bits greater than N. */ void gcry_mpi_clear_highbit (gcry_mpi_t a, unsigned int n); /* Shift the value of A by N bits to the right and store the result in X. */ void gcry_mpi_rshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n); /* Shift the value of A by N bits to the left and store the result in X. */ void gcry_mpi_lshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n); /* Store NBITS of the value P points to in A and mark A as an opaque value. On success A received the the ownership of the value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits); /* Store NBITS of the value P points to in A and mark A as an opaque value. The function takes a copy of the provided value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque_copy (gcry_mpi_t a, const void *p, unsigned int nbits); /* Return a pointer to an opaque value stored in A and return its size in NBITS. Note that the returned pointer is still owned by A and that the function should never be used for an non-opaque MPI. */ void *gcry_mpi_get_opaque (gcry_mpi_t a, unsigned int *nbits); /* Set the FLAG for the big integer A. Currently only the flag GCRYMPI_FLAG_SECURE is allowed to convert A into an big intger stored in "secure" memory. */ void gcry_mpi_set_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Clear FLAG for the big integer A. Note that this function is currently useless as no flags are allowed. */ void gcry_mpi_clear_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Return true if the FLAG is set for A. */ int gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Private function - do not use. */ gcry_mpi_t _gcry_mpi_get_const (int no); /* Unless the GCRYPT_NO_MPI_MACROS is used, provide a couple of convenience macros for the big integer functions. */ #ifndef GCRYPT_NO_MPI_MACROS #define mpi_new(n) gcry_mpi_new( (n) ) #define mpi_secure_new( n ) gcry_mpi_snew( (n) ) #define mpi_release(a) \ do \ { \ gcry_mpi_release ((a)); \ (a) = NULL; \ } \ while (0) #define mpi_copy( a ) gcry_mpi_copy( (a) ) #define mpi_snatch( w, u) gcry_mpi_snatch( (w), (u) ) #define mpi_set( w, u) gcry_mpi_set( (w), (u) ) #define mpi_set_ui( w, u) gcry_mpi_set_ui( (w), (u) ) #define mpi_abs( w ) gcry_mpi_abs( (w) ) #define mpi_neg( w, u) gcry_mpi_neg( (w), (u) ) #define mpi_cmp( u, v ) gcry_mpi_cmp( (u), (v) ) #define mpi_cmp_ui( u, v ) gcry_mpi_cmp_ui( (u), (v) ) #define mpi_is_neg( a ) gcry_mpi_is_neg ((a)) #define mpi_add_ui(w,u,v) gcry_mpi_add_ui((w),(u),(v)) #define mpi_add(w,u,v) gcry_mpi_add ((w),(u),(v)) #define mpi_addm(w,u,v,m) gcry_mpi_addm ((w),(u),(v),(m)) #define mpi_sub_ui(w,u,v) gcry_mpi_sub_ui ((w),(u),(v)) #define mpi_sub(w,u,v) gcry_mpi_sub ((w),(u),(v)) #define mpi_subm(w,u,v,m) gcry_mpi_subm ((w),(u),(v),(m)) #define mpi_mul_ui(w,u,v) gcry_mpi_mul_ui ((w),(u),(v)) #define mpi_mul_2exp(w,u,v) gcry_mpi_mul_2exp ((w),(u),(v)) #define mpi_mul(w,u,v) gcry_mpi_mul ((w),(u),(v)) #define mpi_mulm(w,u,v,m) gcry_mpi_mulm ((w),(u),(v),(m)) #define mpi_powm(w,b,e,m) gcry_mpi_powm ( (w), (b), (e), (m) ) #define mpi_tdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), 0) #define mpi_fdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), -1) #define mpi_mod(r,a,m) gcry_mpi_mod ((r), (a), (m)) #define mpi_gcd(g,a,b) gcry_mpi_gcd ( (g), (a), (b) ) #define mpi_invm(g,a,b) gcry_mpi_invm ( (g), (a), (b) ) #define mpi_point_new(n) gcry_mpi_point_new((n)) #define mpi_point_release(p) \ do \ { \ gcry_mpi_point_release ((p)); \ (p) = NULL; \ } \ while (0) #define mpi_point_get(x,y,z,p) gcry_mpi_point_get((x),(y),(z),(p)) #define mpi_point_snatch_get(x,y,z,p) gcry_mpi_point_snatch_get((x),(y),(z),(p)) #define mpi_point_set(p,x,y,z) gcry_mpi_point_set((p),(x),(y),(z)) #define mpi_point_snatch_set(p,x,y,z) gcry_mpi_point_snatch_set((p),(x),(y),(z)) #define mpi_get_nbits(a) gcry_mpi_get_nbits ((a)) #define mpi_test_bit(a,b) gcry_mpi_test_bit ((a),(b)) #define mpi_set_bit(a,b) gcry_mpi_set_bit ((a),(b)) #define mpi_set_highbit(a,b) gcry_mpi_set_highbit ((a),(b)) #define mpi_clear_bit(a,b) gcry_mpi_clear_bit ((a),(b)) #define mpi_clear_highbit(a,b) gcry_mpi_clear_highbit ((a),(b)) #define mpi_rshift(a,b,c) gcry_mpi_rshift ((a),(b),(c)) #define mpi_lshift(a,b,c) gcry_mpi_lshift ((a),(b),(c)) #define mpi_set_opaque(a,b,c) gcry_mpi_set_opaque( (a), (b), (c) ) #define mpi_get_opaque(a,b) gcry_mpi_get_opaque( (a), (b) ) #endif /* GCRYPT_NO_MPI_MACROS */ /************************************ * * * Symmetric Cipher Functions * * * ************************************/ /* The data object used to hold a handle to an encryption object. */ struct gcry_cipher_handle; typedef struct gcry_cipher_handle *gcry_cipher_hd_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_cipher_handle *GCRY_CIPHER_HD _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_cipher_handle *GcryCipherHd _GCRY_GCC_ATTR_DEPRECATED; #endif /* All symmetric encryption algorithms are identified by their IDs. More IDs may be registered at runtime. */ enum gcry_cipher_algos { GCRY_CIPHER_NONE = 0, GCRY_CIPHER_IDEA = 1, GCRY_CIPHER_3DES = 2, GCRY_CIPHER_CAST5 = 3, GCRY_CIPHER_BLOWFISH = 4, GCRY_CIPHER_SAFER_SK128 = 5, GCRY_CIPHER_DES_SK = 6, GCRY_CIPHER_AES = 7, GCRY_CIPHER_AES192 = 8, GCRY_CIPHER_AES256 = 9, GCRY_CIPHER_TWOFISH = 10, /* Other cipher numbers are above 300 for OpenPGP reasons. */ GCRY_CIPHER_ARCFOUR = 301, /* Fully compatible with RSA's RC4 (tm). */ GCRY_CIPHER_DES = 302, /* Yes, this is single key 56 bit DES. */ GCRY_CIPHER_TWOFISH128 = 303, GCRY_CIPHER_SERPENT128 = 304, GCRY_CIPHER_SERPENT192 = 305, GCRY_CIPHER_SERPENT256 = 306, GCRY_CIPHER_RFC2268_40 = 307, /* Ron's Cipher 2 (40 bit). */ GCRY_CIPHER_RFC2268_128 = 308, /* Ron's Cipher 2 (128 bit). */ GCRY_CIPHER_SEED = 309, /* 128 bit cipher described in RFC4269. */ GCRY_CIPHER_CAMELLIA128 = 310, GCRY_CIPHER_CAMELLIA192 = 311, GCRY_CIPHER_CAMELLIA256 = 312, GCRY_CIPHER_SALSA20 = 313, GCRY_CIPHER_SALSA20R12 = 314, GCRY_CIPHER_GOST28147 = 315, GCRY_CIPHER_CHACHA20 = 316 }; /* The Rijndael algorithm is basically AES, so provide some macros. */ #define GCRY_CIPHER_AES128 GCRY_CIPHER_AES #define GCRY_CIPHER_RIJNDAEL GCRY_CIPHER_AES #define GCRY_CIPHER_RIJNDAEL128 GCRY_CIPHER_AES128 #define GCRY_CIPHER_RIJNDAEL192 GCRY_CIPHER_AES192 #define GCRY_CIPHER_RIJNDAEL256 GCRY_CIPHER_AES256 /* The supported encryption modes. Note that not all of them are supported for each algorithm. */ enum gcry_cipher_modes { GCRY_CIPHER_MODE_NONE = 0, /* Not yet specified. */ GCRY_CIPHER_MODE_ECB = 1, /* Electronic codebook. */ GCRY_CIPHER_MODE_CFB = 2, /* Cipher feedback. */ GCRY_CIPHER_MODE_CBC = 3, /* Cipher block chaining. */ GCRY_CIPHER_MODE_STREAM = 4, /* Used with stream ciphers. */ GCRY_CIPHER_MODE_OFB = 5, /* Outer feedback. */ GCRY_CIPHER_MODE_CTR = 6, /* Counter. */ GCRY_CIPHER_MODE_AESWRAP = 7, /* AES-WRAP algorithm. */ GCRY_CIPHER_MODE_CCM = 8, /* Counter with CBC-MAC. */ GCRY_CIPHER_MODE_GCM = 9, /* Galois Counter Mode. */ GCRY_CIPHER_MODE_POLY1305 = 10, /* Poly1305 based AEAD mode. */ GCRY_CIPHER_MODE_OCB = 11 /* OCB3 mode. */ }; /* Flags used with the open function. */ enum gcry_cipher_flags { GCRY_CIPHER_SECURE = 1, /* Allocate in secure memory. */ GCRY_CIPHER_ENABLE_SYNC = 2, /* Enable CFB sync mode. */ GCRY_CIPHER_CBC_CTS = 4, /* Enable CBC cipher text stealing (CTS). */ GCRY_CIPHER_CBC_MAC = 8 /* Enable CBC message auth. code (MAC). */ }; /* GCM works only with blocks of 128 bits */ #define GCRY_GCM_BLOCK_LEN (128 / 8) /* CCM works only with blocks of 128 bits. */ #define GCRY_CCM_BLOCK_LEN (128 / 8) /* OCB works only with blocks of 128 bits. */ #define GCRY_OCB_BLOCK_LEN (128 / 8) /* Create a handle for algorithm ALGO to be used in MODE. FLAGS may be given as an bitwise OR of the gcry_cipher_flags values. */ gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags); /* Close the cioher handle H and release all resource. */ void gcry_cipher_close (gcry_cipher_hd_t h); /* Perform various operations on the cipher object H. */ gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen); /* Retrieve various information about the cipher object H. */ gcry_error_t gcry_cipher_info (gcry_cipher_hd_t h, int what, void *buffer, size_t *nbytes); /* Retrieve various information about the cipher algorithm ALGO. */ gcry_error_t gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the cipher algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this function returns "?". */ const char *gcry_cipher_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm name NAME to an cipher algorithm ID. Return 0 if the algorithm name is not known. */ int gcry_cipher_map_name (const char *name) _GCRY_GCC_ATTR_PURE; /* Given an ASN.1 object identifier in standard IETF dotted decimal format in STRING, return the encryption mode associated with that OID or 0 if not known or applicable. */ int gcry_cipher_mode_from_oid (const char *string) _GCRY_GCC_ATTR_PURE; /* Encrypt the plaintext of size INLEN in IN using the cipher handle H into the buffer OUT which has an allocated length of OUTSIZE. For most algorithms it is possible to pass NULL for in and 0 for INLEN and do a in-place decryption of the data provided in OUT. */ gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen); /* The counterpart to gcry_cipher_encrypt. */ gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen); /* Set KEY of length KEYLEN bytes for the cipher handle HD. */ gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen); /* Set initialization vector IV of length IVLEN for the cipher handle HD. */ gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen); /* Provide additional authentication data for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf, size_t abuflen); /* Get authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen); /* Check authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen); /* Reset the handle to the state after open. */ #define gcry_cipher_reset(h) gcry_cipher_ctl ((h), GCRYCTL_RESET, NULL, 0) /* Perform the OpenPGP sync operation if this is enabled for the cipher handle H. */ #define gcry_cipher_sync(h) gcry_cipher_ctl( (h), GCRYCTL_CFB_SYNC, NULL, 0) /* Enable or disable CTS in future calls to gcry_encrypt(). CBC mode only. */ #define gcry_cipher_cts(h,on) gcry_cipher_ctl( (h), GCRYCTL_SET_CBC_CTS, \ NULL, on ) #define gcry_cipher_set_sbox(h,oid) gcry_cipher_ctl( (h), GCRYCTL_SET_SBOX, \ (oid), 0); /* Indicate to the encrypt and decrypt functions that the next call provides the final data. Only used with some modes. e */ #define gcry_cipher_final(a) \ gcry_cipher_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) /* Set counter for CTR mode. (CTR,CTRLEN) must denote a buffer of block size length, or (NULL,0) to set the CTR to the all-zero block. */ gpg_error_t gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen); /* Retrieve the key length in bytes used with algorithm A. */ size_t gcry_cipher_get_algo_keylen (int algo); /* Retrieve the block length in bytes used with algorithm A. */ size_t gcry_cipher_get_algo_blklen (int algo); /* Return 0 if the algorithm A is available for use. */ #define gcry_cipher_test_algo(a) \ gcry_cipher_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /************************************ * * * Asymmetric Cipher Functions * * * ************************************/ /* The algorithms and their IDs we support. */ enum gcry_pk_algos { GCRY_PK_RSA = 1, /* RSA */ GCRY_PK_RSA_E = 2, /* (deprecated: use 1). */ GCRY_PK_RSA_S = 3, /* (deprecated: use 1). */ GCRY_PK_ELG_E = 16, /* (deprecated: use 20). */ GCRY_PK_DSA = 17, /* Digital Signature Algorithm. */ GCRY_PK_ECC = 18, /* Generic ECC. */ GCRY_PK_ELG = 20, /* Elgamal */ GCRY_PK_ECDSA = 301, /* (only for external use). */ GCRY_PK_ECDH = 302, /* (only for external use). */ GCRY_PK_EDDSA = 303 /* (only for external use). */ }; /* Flags describing usage capabilities of a PK algorithm. */ #define GCRY_PK_USAGE_SIGN 1 /* Good for signatures. */ #define GCRY_PK_USAGE_ENCR 2 /* Good for encryption. */ #define GCRY_PK_USAGE_CERT 4 /* Good to certify other keys. */ #define GCRY_PK_USAGE_AUTH 8 /* Good for authentication. */ #define GCRY_PK_USAGE_UNKN 128 /* Unknown usage flag. */ /* Modes used with gcry_pubkey_get_sexp. */ #define GCRY_PK_GET_PUBKEY 1 #define GCRY_PK_GET_SECKEY 2 /* Encrypt the DATA using the public key PKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_encrypt (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t pkey); /* Decrypt the DATA using the private key SKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_decrypt (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t skey); /* Sign the DATA using the private key SKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_sign (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t skey); /* Check the signature SIGVAL on DATA using the public key PKEY. */ gcry_error_t gcry_pk_verify (gcry_sexp_t sigval, gcry_sexp_t data, gcry_sexp_t pkey); /* Check that private KEY is sane. */ gcry_error_t gcry_pk_testkey (gcry_sexp_t key); /* Generate a new key pair according to the parameters given in S_PARMS. The new key pair is returned in as an S-expression in R_KEY. */ gcry_error_t gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms); /* Catch all function for miscellaneous operations. */ gcry_error_t gcry_pk_ctl (int cmd, void *buffer, size_t buflen); /* Retrieve information about the public key algorithm ALGO. */ gcry_error_t gcry_pk_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the public key algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this functions returns "?". */ const char *gcry_pk_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm NAME to a public key algorithm Id. Return 0 if the algorithm name is not known. */ int gcry_pk_map_name (const char* name) _GCRY_GCC_ATTR_PURE; /* Return what is commonly referred as the key length for the given public or private KEY. */ unsigned int gcry_pk_get_nbits (gcry_sexp_t key) _GCRY_GCC_ATTR_PURE; /* Return the so called KEYGRIP which is the SHA-1 hash of the public key parameters expressed in a way depending on the algorithm. */ unsigned char *gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array); /* Return the name of the curve matching KEY. */ const char *gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits); /* Return an S-expression with the parameters of the named ECC curve NAME. ALGO must be set to an ECC algorithm. */ gcry_sexp_t gcry_pk_get_param (int algo, const char *name); /* Return 0 if the public key algorithm A is available for use. */ #define gcry_pk_test_algo(a) \ gcry_pk_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /* Return an S-expression representing the context CTX. */ gcry_error_t gcry_pubkey_get_sexp (gcry_sexp_t *r_sexp, int mode, gcry_ctx_t ctx); /************************************ * * * Cryptograhic Hash Functions * * * ************************************/ /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ enum gcry_md_algos { GCRY_MD_NONE = 0, GCRY_MD_MD5 = 1, GCRY_MD_SHA1 = 2, GCRY_MD_RMD160 = 3, GCRY_MD_MD2 = 5, GCRY_MD_TIGER = 6, /* TIGER/192 as used by gpg <= 1.3.2. */ GCRY_MD_HAVAL = 7, /* HAVAL, 5 pass, 160 bit. */ GCRY_MD_SHA256 = 8, GCRY_MD_SHA384 = 9, GCRY_MD_SHA512 = 10, GCRY_MD_SHA224 = 11, GCRY_MD_MD4 = 301, GCRY_MD_CRC32 = 302, GCRY_MD_CRC32_RFC1510 = 303, GCRY_MD_CRC24_RFC2440 = 304, GCRY_MD_WHIRLPOOL = 305, GCRY_MD_TIGER1 = 306, /* TIGER fixed. */ GCRY_MD_TIGER2 = 307, /* TIGER2 variant. */ GCRY_MD_GOSTR3411_94 = 308, /* GOST R 34.11-94. */ GCRY_MD_STRIBOG256 = 309, /* GOST R 34.11-2012, 256 bit. */ GCRY_MD_STRIBOG512 = 310, /* GOST R 34.11-2012, 512 bit. */ GCRY_MD_GOSTR3411_CP = 311, /* GOST R 34.11-94 with CryptoPro-A S-Box. */ GCRY_MD_SHA3_224 = 312, GCRY_MD_SHA3_256 = 313, GCRY_MD_SHA3_384 = 314, GCRY_MD_SHA3_512 = 315, GCRY_MD_SHAKE128 = 316, GCRY_MD_SHAKE256 = 317 }; /* Flags used with the open function. */ enum gcry_md_flags { GCRY_MD_FLAG_SECURE = 1, /* Allocate all buffers in "secure" memory. */ GCRY_MD_FLAG_HMAC = 2, /* Make an HMAC out of this algorithm. */ GCRY_MD_FLAG_BUGEMU1 = 0x0100 }; /* (Forward declaration.) */ struct gcry_md_context; /* This object is used to hold a handle to a message digest object. This structure is private - only to be used by the public gcry_md_* macros. */ typedef struct gcry_md_handle { /* Actual context. */ struct gcry_md_context *ctx; /* Buffer management. */ int bufpos; int bufsize; unsigned char buf[1]; } *gcry_md_hd_t; /* Compatibility types, do not use them. */ #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_md_handle *GCRY_MD_HD _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_md_handle *GcryMDHd _GCRY_GCC_ATTR_DEPRECATED; #endif /* Create a message digest object for algorithm ALGO. FLAGS may be given as an bitwise OR of the gcry_md_flags values. ALGO may be given as 0 if the algorithms to be used are later set using gcry_md_enable. */ gcry_error_t gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags); /* Release the message digest object HD. */ void gcry_md_close (gcry_md_hd_t hd); /* Add the message digest algorithm ALGO to the digest object HD. */ gcry_error_t gcry_md_enable (gcry_md_hd_t hd, int algo); /* Create a new digest object as an exact copy of the object HD. */ gcry_error_t gcry_md_copy (gcry_md_hd_t *bhd, gcry_md_hd_t ahd); /* Reset the digest object HD to its initial state. */ void gcry_md_reset (gcry_md_hd_t hd); /* Perform various operations on the digest object HD. */ gcry_error_t gcry_md_ctl (gcry_md_hd_t hd, int cmd, void *buffer, size_t buflen); /* Pass LENGTH bytes of data in BUFFER to the digest object HD so that it can update the digest values. This is the actual hash function. */ void gcry_md_write (gcry_md_hd_t hd, const void *buffer, size_t length); /* Read out the final digest from HD return the digest value for algorithm ALGO. */ unsigned char *gcry_md_read (gcry_md_hd_t hd, int algo); /* Read more output from algorithm ALGO to BUFFER of size LENGTH from * digest object HD. Algorithm needs to be 'expendable-output function'. */ gpg_error_t gcry_md_extract (gcry_md_hd_t hd, int algo, void *buffer, size_t length); /* Convenience function to calculate the hash from the data in BUFFER of size LENGTH using the algorithm ALGO avoiding the creating of a hash object. The hash is returned in the caller provided buffer DIGEST which must be large enough to hold the digest of the given algorithm. */ void gcry_md_hash_buffer (int algo, void *digest, const void *buffer, size_t length); /* Convenience function to hash multiple buffers. */ gpg_error_t gcry_md_hash_buffers (int algo, unsigned int flags, void *digest, const gcry_buffer_t *iov, int iovcnt); /* Retrieve the algorithm used with HD. This does not work reliable if more than one algorithm is enabled in HD. */ int gcry_md_get_algo (gcry_md_hd_t hd); /* Retrieve the length in bytes of the digest yielded by algorithm ALGO. */ unsigned int gcry_md_get_algo_dlen (int algo); /* Return true if the the algorithm ALGO is enabled in the digest object A. */ int gcry_md_is_enabled (gcry_md_hd_t a, int algo); /* Return true if the digest object A is allocated in "secure" memory. */ int gcry_md_is_secure (gcry_md_hd_t a); /* Retrieve various information about the object H. */ gcry_error_t gcry_md_info (gcry_md_hd_t h, int what, void *buffer, size_t *nbytes); /* Retrieve various information about the algorithm ALGO. */ gcry_error_t gcry_md_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the digest algorithm id ALGO to a string representation of the algorithm name. For unknown algorithms this function returns "?". */ const char *gcry_md_algo_name (int algo) _GCRY_GCC_ATTR_PURE; /* Map the algorithm NAME to a digest algorithm Id. Return 0 if the algorithm name is not known. */ int gcry_md_map_name (const char* name) _GCRY_GCC_ATTR_PURE; /* For use with the HMAC feature, the set MAC key to the KEY of KEYLEN bytes. */ gcry_error_t gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen); /* Start or stop debugging for digest handle HD; i.e. create a file named dbgmd-. while hashing. If SUFFIX is NULL, debugging stops and the file will be closed. */ void gcry_md_debug (gcry_md_hd_t hd, const char *suffix); /* Update the hash(s) of H with the character C. This is a buffered version of the gcry_md_write function. */ #define gcry_md_putc(h,c) \ do { \ gcry_md_hd_t h__ = (h); \ if( (h__)->bufpos == (h__)->bufsize ) \ gcry_md_write( (h__), NULL, 0 ); \ (h__)->buf[(h__)->bufpos++] = (c) & 0xff; \ } while(0) /* Finalize the digest calculation. This is not really needed because gcry_md_read() does this implicitly. */ #define gcry_md_final(a) \ gcry_md_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) /* Return 0 if the algorithm A is available for use. */ #define gcry_md_test_algo(a) \ gcry_md_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /* Return an DER encoded ASN.1 OID for the algorithm A in buffer B. N must point to size_t variable with the available size of buffer B. After return it will receive the actual size of the returned OID. */ #define gcry_md_get_asnoid(a,b,n) \ gcry_md_algo_info((a), GCRYCTL_GET_ASNOID, (b), (n)) /********************************************** * * * Message Authentication Code Functions * * * **********************************************/ /* The data object used to hold a handle to an encryption object. */ struct gcry_mac_handle; typedef struct gcry_mac_handle *gcry_mac_hd_t; /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ enum gcry_mac_algos { GCRY_MAC_NONE = 0, GCRY_MAC_HMAC_SHA256 = 101, GCRY_MAC_HMAC_SHA224 = 102, GCRY_MAC_HMAC_SHA512 = 103, GCRY_MAC_HMAC_SHA384 = 104, GCRY_MAC_HMAC_SHA1 = 105, GCRY_MAC_HMAC_MD5 = 106, GCRY_MAC_HMAC_MD4 = 107, GCRY_MAC_HMAC_RMD160 = 108, GCRY_MAC_HMAC_TIGER1 = 109, /* The fixed TIGER variant */ GCRY_MAC_HMAC_WHIRLPOOL = 110, GCRY_MAC_HMAC_GOSTR3411_94 = 111, GCRY_MAC_HMAC_STRIBOG256 = 112, GCRY_MAC_HMAC_STRIBOG512 = 113, GCRY_MAC_HMAC_MD2 = 114, GCRY_MAC_HMAC_SHA3_224 = 115, GCRY_MAC_HMAC_SHA3_256 = 116, GCRY_MAC_HMAC_SHA3_384 = 117, GCRY_MAC_HMAC_SHA3_512 = 118, GCRY_MAC_CMAC_AES = 201, GCRY_MAC_CMAC_3DES = 202, GCRY_MAC_CMAC_CAMELLIA = 203, GCRY_MAC_CMAC_CAST5 = 204, GCRY_MAC_CMAC_BLOWFISH = 205, GCRY_MAC_CMAC_TWOFISH = 206, GCRY_MAC_CMAC_SERPENT = 207, GCRY_MAC_CMAC_SEED = 208, GCRY_MAC_CMAC_RFC2268 = 209, GCRY_MAC_CMAC_IDEA = 210, GCRY_MAC_CMAC_GOST28147 = 211, GCRY_MAC_GMAC_AES = 401, GCRY_MAC_GMAC_CAMELLIA = 402, GCRY_MAC_GMAC_TWOFISH = 403, GCRY_MAC_GMAC_SERPENT = 404, GCRY_MAC_GMAC_SEED = 405, GCRY_MAC_POLY1305 = 501, GCRY_MAC_POLY1305_AES = 502, GCRY_MAC_POLY1305_CAMELLIA = 503, GCRY_MAC_POLY1305_TWOFISH = 504, GCRY_MAC_POLY1305_SERPENT = 505, GCRY_MAC_POLY1305_SEED = 506 }; /* Flags used with the open function. */ enum gcry_mac_flags { GCRY_MAC_FLAG_SECURE = 1 /* Allocate all buffers in "secure" memory. */ }; /* Create a MAC handle for algorithm ALGO. FLAGS may be given as an bitwise OR of the gcry_mac_flags values. CTX maybe NULL or gcry_ctx_t object to be associated with HANDLE. */ gcry_error_t gcry_mac_open (gcry_mac_hd_t *handle, int algo, unsigned int flags, gcry_ctx_t ctx); /* Close the MAC handle H and release all resource. */ void gcry_mac_close (gcry_mac_hd_t h); /* Perform various operations on the MAC object H. */ gcry_error_t gcry_mac_ctl (gcry_mac_hd_t h, int cmd, void *buffer, size_t buflen); /* Retrieve various information about the MAC algorithm ALGO. */ gcry_error_t gcry_mac_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Set KEY of length KEYLEN bytes for the MAC handle HD. */ gcry_error_t gcry_mac_setkey (gcry_mac_hd_t hd, const void *key, size_t keylen); /* Set initialization vector IV of length IVLEN for the MAC handle HD. */ gcry_error_t gcry_mac_setiv (gcry_mac_hd_t hd, const void *iv, size_t ivlen); /* Pass LENGTH bytes of data in BUFFER to the MAC object HD so that it can update the MAC values. */ gcry_error_t gcry_mac_write (gcry_mac_hd_t hd, const void *buffer, size_t length); /* Read out the final authentication code from the MAC object HD to BUFFER. */ gcry_error_t gcry_mac_read (gcry_mac_hd_t hd, void *buffer, size_t *buflen); /* Verify the final authentication code from the MAC object HD with BUFFER. */ gcry_error_t gcry_mac_verify (gcry_mac_hd_t hd, const void *buffer, size_t buflen); /* Retrieve the algorithm used with MAC. */ int gcry_mac_get_algo (gcry_mac_hd_t hd); /* Retrieve the length in bytes of the MAC yielded by algorithm ALGO. */ unsigned int gcry_mac_get_algo_maclen (int algo); /* Retrieve the default key length in bytes used with algorithm A. */ unsigned int gcry_mac_get_algo_keylen (int algo); /* Map the MAC algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this function returns "?". */ const char *gcry_mac_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm name NAME to an MAC algorithm ID. Return 0 if the algorithm name is not known. */ int gcry_mac_map_name (const char *name) _GCRY_GCC_ATTR_PURE; /* Reset the handle to the state after open/setkey. */ #define gcry_mac_reset(h) gcry_mac_ctl ((h), GCRYCTL_RESET, NULL, 0) /* Return 0 if the algorithm A is available for use. */ #define gcry_mac_test_algo(a) \ gcry_mac_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /****************************** * * * Key Derivation Functions * * * ******************************/ /* Algorithm IDs for the KDFs. */ enum gcry_kdf_algos { GCRY_KDF_NONE = 0, GCRY_KDF_SIMPLE_S2K = 16, GCRY_KDF_SALTED_S2K = 17, GCRY_KDF_ITERSALTED_S2K = 19, GCRY_KDF_PBKDF1 = 33, GCRY_KDF_PBKDF2 = 34, GCRY_KDF_SCRYPT = 48 }; /* Derive a key from a passphrase. */ gpg_error_t gcry_kdf_derive (const void *passphrase, size_t passphraselen, int algo, int subalgo, const void *salt, size_t saltlen, unsigned long iterations, size_t keysize, void *keybuffer); /************************************ * * * Random Generating Functions * * * ************************************/ /* The type of the random number generator. */ enum gcry_rng_types { GCRY_RNG_TYPE_STANDARD = 1, /* The default CSPRNG generator. */ GCRY_RNG_TYPE_FIPS = 2, /* The FIPS X9.31 AES generator. */ GCRY_RNG_TYPE_SYSTEM = 3 /* The system's native generator. */ }; /* The possible values for the random quality. The rule of thumb is to use STRONG for session keys and VERY_STRONG for key material. WEAK is usually an alias for STRONG and should not be used anymore (except with gcry_mpi_randomize); use gcry_create_nonce instead. */ typedef enum gcry_random_level { GCRY_WEAK_RANDOM = 0, GCRY_STRONG_RANDOM = 1, GCRY_VERY_STRONG_RANDOM = 2 } gcry_random_level_t; /* Fill BUFFER with LENGTH bytes of random, using random numbers of quality LEVEL. */ void gcry_randomize (void *buffer, size_t length, enum gcry_random_level level); /* Add the external random from BUFFER with LENGTH bytes into the pool. QUALITY should either be -1 for unknown or in the range of 0 to 100 */ gcry_error_t gcry_random_add_bytes (const void *buffer, size_t length, int quality); /* If random numbers are used in an application, this macro should be called from time to time so that new stuff gets added to the internal pool of the RNG. */ #define gcry_fast_random_poll() gcry_control (GCRYCTL_FAST_POLL, NULL) /* Return NBYTES of allocated random using a random numbers of quality LEVEL. */ void *gcry_random_bytes (size_t nbytes, enum gcry_random_level level) _GCRY_GCC_ATTR_MALLOC; /* Return NBYTES of allocated random using a random numbers of quality LEVEL. The random numbers are created returned in "secure" memory. */ void *gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level) _GCRY_GCC_ATTR_MALLOC; /* Set the big integer W to a random value of NBITS using a random generator with quality LEVEL. Note that by using a level of GCRY_WEAK_RANDOM gcry_create_nonce is used internally. */ void gcry_mpi_randomize (gcry_mpi_t w, unsigned int nbits, enum gcry_random_level level); /* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ void gcry_create_nonce (void *buffer, size_t length); /*******************************/ /* */ /* Prime Number Functions */ /* */ /*******************************/ /* Mode values passed to a gcry_prime_check_func_t. */ #define GCRY_PRIME_CHECK_AT_FINISH 0 #define GCRY_PRIME_CHECK_AT_GOT_PRIME 1 #define GCRY_PRIME_CHECK_AT_MAYBE_PRIME 2 /* The function should return 1 if the operation shall continue, 0 to reject the prime candidate. */ typedef int (*gcry_prime_check_func_t) (void *arg, int mode, gcry_mpi_t candidate); /* Flags for gcry_prime_generate(): */ /* Allocate prime numbers and factors in secure memory. */ #define GCRY_PRIME_FLAG_SECRET (1 << 0) /* Make sure that at least one prime factor is of size `FACTOR_BITS'. */ #define GCRY_PRIME_FLAG_SPECIAL_FACTOR (1 << 1) /* Generate a new prime number of PRIME_BITS bits and store it in PRIME. If FACTOR_BITS is non-zero, one of the prime factors of (prime - 1) / 2 must be FACTOR_BITS bits long. If FACTORS is non-zero, allocate a new, NULL-terminated array holding the prime factors and store it in FACTORS. FLAGS might be used to influence the prime number generation process. */ gcry_error_t gcry_prime_generate (gcry_mpi_t *prime, unsigned int prime_bits, unsigned int factor_bits, gcry_mpi_t **factors, gcry_prime_check_func_t cb_func, void *cb_arg, gcry_random_level_t random_level, unsigned int flags); /* Find a generator for PRIME where the factorization of (prime-1) is in the NULL terminated array FACTORS. Return the generator as a newly allocated MPI in R_G. If START_G is not NULL, use this as the start for the search. */ gcry_error_t gcry_prime_group_generator (gcry_mpi_t *r_g, gcry_mpi_t prime, gcry_mpi_t *factors, gcry_mpi_t start_g); /* Convenience function to release the FACTORS array. */ void gcry_prime_release_factors (gcry_mpi_t *factors); /* Check wether the number X is prime. */ gcry_error_t gcry_prime_check (gcry_mpi_t x, unsigned int flags); /************************************ * * * Miscellaneous Stuff * * * ************************************/ /* Release the context object CTX. */ void gcry_ctx_release (gcry_ctx_t ctx); /* Log data using Libgcrypt's own log interface. */ void gcry_log_debug (const char *fmt, ...) _GCRY_GCC_ATTR_PRINTF(1,2); void gcry_log_debughex (const char *text, const void *buffer, size_t length); void gcry_log_debugmpi (const char *text, gcry_mpi_t mpi); void gcry_log_debugpnt (const char *text, gcry_mpi_point_t point, gcry_ctx_t ctx); void gcry_log_debugsxp (const char *text, gcry_sexp_t sexp); /* Log levels used by the internal logging facility. */ enum gcry_log_levels { GCRY_LOG_CONT = 0, /* (Continue the last log line.) */ GCRY_LOG_INFO = 10, GCRY_LOG_WARN = 20, GCRY_LOG_ERROR = 30, GCRY_LOG_FATAL = 40, GCRY_LOG_BUG = 50, GCRY_LOG_DEBUG = 100 }; /* Type for progress handlers. */ typedef void (*gcry_handler_progress_t) (void *, const char *, int, int, int); /* Type for memory allocation handlers. */ typedef void *(*gcry_handler_alloc_t) (size_t n); /* Type for secure memory check handlers. */ typedef int (*gcry_handler_secure_check_t) (const void *); /* Type for memory reallocation handlers. */ typedef void *(*gcry_handler_realloc_t) (void *p, size_t n); /* Type for memory free handlers. */ typedef void (*gcry_handler_free_t) (void *); /* Type for out-of-memory handlers. */ typedef int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int); /* Type for fatal error handlers. */ typedef void (*gcry_handler_error_t) (void *, int, const char *); /* Type for logging handlers. */ typedef void (*gcry_handler_log_t) (void *, int, const char *, va_list); /* Certain operations can provide progress information. This function is used to register a handler for retrieving these information. */ void gcry_set_progress_handler (gcry_handler_progress_t cb, void *cb_data); /* Register a custom memory allocation functions. */ void gcry_set_allocation_handler ( gcry_handler_alloc_t func_alloc, gcry_handler_alloc_t func_alloc_secure, gcry_handler_secure_check_t func_secure_check, gcry_handler_realloc_t func_realloc, gcry_handler_free_t func_free); /* Register a function used instead of the internal out of memory handler. */ void gcry_set_outofcore_handler (gcry_handler_no_mem_t h, void *opaque); /* Register a function used instead of the internal fatal error handler. */ void gcry_set_fatalerror_handler (gcry_handler_error_t fnc, void *opaque); /* Register a function used instead of the internal logging facility. */ void gcry_set_log_handler (gcry_handler_log_t f, void *opaque); /* Reserved for future use. */ void gcry_set_gettext_handler (const char *(*f)(const char*)); /* Libgcrypt uses its own memory allocation. It is important to use gcry_free () to release memory allocated by libgcrypt. */ void *gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_malloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_calloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_realloc (void *a, size_t n); char *gcry_strdup (const char *string) _GCRY_GCC_ATTR_MALLOC; void *gcry_xmalloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_xcalloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_xmalloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_xcalloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_xrealloc (void *a, size_t n); char *gcry_xstrdup (const char * a) _GCRY_GCC_ATTR_MALLOC; void gcry_free (void *a); /* Return true if A is allocated in "secure" memory. */ int gcry_is_secure (const void *a) _GCRY_GCC_ATTR_PURE; /* Return true if Libgcrypt is in FIPS mode. */ #define gcry_fips_mode_active() !!gcry_control (GCRYCTL_FIPS_MODE_P, 0) +/* DRBG input data structure for DRBG generate with additional information + * string */ +struct gcry_drbg_gen +{ + unsigned char *outbuf; /* output buffer for random numbers */ + unsigned int outlen; /* size of output buffer */ + struct gcry_drbg_string *addtl; /* input buffer for + * additional information string */ +}; + +/* + * Concatenation Helper and string operation helper + * + * SP800-90A requires the concatenation of different data. To avoid copying + * buffers around or allocate additional memory, the following data structure + * is used to point to the original memory with its size. In addition, it + * is used to build a linked list. The linked list defines the concatenation + * of individual buffers. The order of memory block referenced in that + * linked list determines the order of concatenation. + */ +/* DRBG string definition */ +struct gcry_drbg_string +{ + const unsigned char *buf; + size_t len; + struct gcry_drbg_string *next; +}; + +static inline void gcry_drbg_string_fill(struct gcry_drbg_string *string, + const unsigned char *buf, size_t len) +{ + string->buf = buf; + string->len = len; + string->next = NULL; +} + +/* this is a wrapper function for users of libgcrypt */ +static inline void gcry_randomize_drbg(void *outbuf, size_t outlen, + enum gcry_random_level level, + struct gcry_drbg_string *addtl) +{ + struct gcry_drbg_gen genbuf; + genbuf.outbuf = (unsigned char *)outbuf; + genbuf.outlen = outlen; + genbuf.addtl = addtl; + gcry_randomize(&genbuf, 0, level); +} + +/* + * DRBG flags bitmasks + * + * 31 (B) 28 19 (A) 0 + * +-+-+-+--------+---+-----------+-----+ + * |~|~|u|~~~~~~~~| 3 | 2 | 1 | + * +-+-+-+--------+- -+-----------+-----+ + * ctl flg| |drbg use selection flags + * + */ + +/* internal state control flags (B) */ +#define GCRY_DRBG_PREDICTION_RESIST ((u_int32_t)1<<28) + +/* CTR type modifiers (A.1)*/ +#define GCRY_DRBG_CTRAES ((u_int32_t)1<<0) +#define GCRY_DRBG_CTRSERPENT ((u_int32_t)1<<1) +#define GCRY_DRBG_CTRTWOFISH ((u_int32_t)1<<2) +#define GCRY_DRBG_CTR_MASK (GCRY_DRBG_CTRAES | GCRY_DRBG_CTRSERPENT | GCRY_DRBG_CTRTWOFISH) + +/* HASH type modifiers (A.2)*/ +#define GCRY_DRBG_HASHSHA1 ((u_int32_t)1<<4) +#define GCRY_DRBG_HASHSHA224 ((u_int32_t)1<<5) +#define GCRY_DRBG_HASHSHA256 ((u_int32_t)1<<6) +#define GCRY_DRBG_HASHSHA384 ((u_int32_t)1<<7) +#define GCRY_DRBG_HASHSHA512 ((u_int32_t)1<<8) +#define GCRY_DRBG_HASH_MASK (GCRY_DRBG_HASHSHA1 | GCRY_DRBG_HASHSHA224 | \ + GCRY_DRBG_HASHSHA256 | GCRY_DRBG_HASHSHA384 | \ + GCRY_DRBG_HASHSHA512) +/* type modifiers (A.3)*/ +#define GCRY_DRBG_HMAC ((u_int32_t)1<<12) +#define GCRY_DRBG_SYM128 ((u_int32_t)1<<13) +#define GCRY_DRBG_SYM192 ((u_int32_t)1<<14) +#define GCRY_DRBG_SYM256 ((u_int32_t)1<<15) +#define GCRY_DRBG_TYPE_MASK (GCRY_DRBG_HMAC | GCRY_DRBG_SYM128 | GCRY_DRBG_SYM192 | \ + GCRY_DRBG_SYM256) +#define GCRY_DRBG_CIPHER_MASK (GCRY_DRBG_CTR_MASK | GCRY_DRBG_HASH_MASK | GCRY_DRBG_TYPE_MASK) + +#define GCRY_DRBG_PR_CTRAES128 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_CTRAES | GCRY_DRBG_SYM128) +#define GCRY_DRBG_PR_CTRAES192 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_CTRAES | GCRY_DRBG_SYM192) +#define GCRY_DRBG_PR_CTRAES256 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_CTRAES | GCRY_DRBG_SYM256) +#define GCRY_DRBG_NOPR_CTRAES128 (GCRY_DRBG_CTRAES | GCRY_DRBG_SYM128) +#define GCRY_DRBG_NOPR_CTRAES192 (GCRY_DRBG_CTRAES | GCRY_DRBG_SYM192) +#define GCRY_DRBG_NOPR_CTRAES256 (GCRY_DRBG_CTRAES | GCRY_DRBG_SYM256) +#define GCRY_DRBG_PR_HASHSHA1 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA1) +#define GCRY_DRBG_PR_HASHSHA256 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA256) +#define GCRY_DRBG_PR_HASHSHA384 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA384) +#define GCRY_DRBG_PR_HASHSHA512 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA512) +#define GCRY_DRBG_NOPR_HASHSHA1 (GCRY_DRBG_HASHSHA1) +#define GCRY_DRBG_NOPR_HASHSHA256 (GCRY_DRBG_HASHSHA256) +#define GCRY_DRBG_NOPR_HASHSHA384 (GCRY_DRBG_HASHSHA384) +#define GCRY_DRBG_NOPR_HASHSHA512 (GCRY_DRBG_HASHSHA512) +#define GCRY_DRBG_PR_HMACSHA1 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA1 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_PR_HMACSHA256 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA256 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_PR_HMACSHA384 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA384 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_PR_HMACSHA512 (GCRY_DRBG_PREDICTION_RESIST | GCRY_DRBG_HASHSHA512 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_NOPR_HMACSHA1 (GCRY_DRBG_HASHSHA1 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_NOPR_HMACSHA256 (GCRY_DRBG_HASHSHA256 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_NOPR_HMACSHA384 (GCRY_DRBG_HASHSHA384 | GCRY_DRBG_HMAC) +#define GCRY_DRBG_NOPR_HMACSHA512 (GCRY_DRBG_HASHSHA512 | GCRY_DRBG_HMAC) #if 0 /* (Keep Emacsens' auto-indent happy.) */ { #endif #ifdef __cplusplus } #endif #endif /* _GCRYPT_H */ /* @emacs_local_vars_begin@ @emacs_local_vars_read_only@ @emacs_local_vars_end@ */ diff --git a/src/global.c b/src/global.c index 889de4c4..e14d8c44 100644 --- a/src/global.c +++ b/src/global.c @@ -1,1163 +1,1156 @@ /* global.c - global control functions * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2004, 2005, 2006, 2008, 2011, * 2012 Free Software Foundation, Inc. * Copyright (C) 2013, 2014 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser general Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYSLOG # include #endif /*HAVE_SYSLOG*/ #include "g10lib.h" #include "cipher.h" #include "stdmem.h" /* our own memory allocator */ #include "secmem.h" /* our own secmem allocator */ /**************** * flag bits: 0 : general cipher debug * 1 : general MPI debug */ static unsigned int debug_flags; /* gcry_control (GCRYCTL_SET_FIPS_MODE), sets this flag so that the initialization code switched fips mode on. */ static int force_fips_mode; /* Controlled by global_init(). */ static int any_init_done; /* Memory management. */ static gcry_handler_alloc_t alloc_func; static gcry_handler_alloc_t alloc_secure_func; static gcry_handler_secure_check_t is_secure_func; static gcry_handler_realloc_t realloc_func; static gcry_handler_free_t free_func; static gcry_handler_no_mem_t outofcore_handler; static void *outofcore_handler_value; static int no_secure_memory; /* Prototypes. */ static gpg_err_code_t external_lock_test (int cmd); /* This is our handmade constructor. It gets called by any function likely to be called at startup. The suggested way for an application to make sure that this has been called is by using gcry_check_version. */ static void global_init (void) { gcry_error_t err = 0; if (any_init_done) return; any_init_done = 1; /* Tell the random module that we have seen an init call. */ _gcry_set_preferred_rng_type (0); /* See whether the system is in FIPS mode. This needs to come as early as possible but after ATH has been initialized. */ _gcry_initialize_fips_mode (force_fips_mode); /* Before we do any other initialization we need to test available hardware features. */ _gcry_detect_hw_features (); /* Initialize the modules - this is mainly allocating some memory and creating mutexes. */ err = _gcry_cipher_init (); if (err) goto fail; err = _gcry_md_init (); if (err) goto fail; err = _gcry_pk_init (); if (err) goto fail; err = _gcry_primegen_init (); if (err) goto fail; err = _gcry_secmem_module_init (); if (err) goto fail; err = _gcry_mpi_init (); if (err) goto fail; return; fail: BUG (); } /* This function is called by the macro fips_is_operational and makes sure that the minimal initialization has been done. This is far from a perfect solution and hides problems with an improper initialization but at least in single-threaded mode it should work reliable. The reason we need this is that a lot of applications don't use Libgcrypt properly by not running any initialization code at all. They just call a Libgcrypt function and that is all what they want. Now with the FIPS mode, that has the side effect of entering FIPS mode (for security reasons, FIPS mode is the default if no initialization has been done) and bailing out immediately because the FSM is in the wrong state. If we always run the init code, Libgcrypt can test for FIPS mode and at least if not in FIPS mode, it will behave as before. Note that this on-the-fly initialization is only done for the cryptographic functions subject to FIPS mode and thus not all API calls will do such an initialization. */ int _gcry_global_is_operational (void) { if (!any_init_done) { #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_WARNING, "Libgcrypt warning: " "missing initialization - please fix the application"); #endif /*HAVE_SYSLOG*/ global_init (); } return _gcry_fips_is_operational (); } /* Version number parsing. */ /* This function parses the first portion of the version number S and stores it in *NUMBER. On success, this function returns a pointer into S starting with the first character, which is not part of the initial number portion; on failure, NULL is returned. */ static const char* parse_version_number( const char *s, int *number ) { int val = 0; if( *s == '0' && isdigit(s[1]) ) return NULL; /* leading zeros are not allowed */ for ( ; isdigit(*s); s++ ) { val *= 10; val += *s - '0'; } *number = val; return val < 0? NULL : s; } /* This function breaks up the complete string-representation of the version number S, which is of the following struture: ... The major, minor and micro number components will be stored in *MAJOR, *MINOR and *MICRO. On success, the last component, the patch level, will be returned; in failure, NULL will be returned. */ static const char * parse_version_string( const char *s, int *major, int *minor, int *micro ) { s = parse_version_number( s, major ); if( !s || *s != '.' ) return NULL; s++; s = parse_version_number( s, minor ); if( !s || *s != '.' ) return NULL; s++; s = parse_version_number( s, micro ); if( !s ) return NULL; return s; /* patchlevel */ } /* If REQ_VERSION is non-NULL, check that the version of the library is at minimum the requested one. Returns the string representation of the library version if the condition is satisfied; return NULL if the requested version is newer than that of the library. If a NULL is passed to this function, no check is done, but the string representation of the library is simply returned. */ const char * _gcry_check_version (const char *req_version) { const char *ver = VERSION; int my_major, my_minor, my_micro; int rq_major, rq_minor, rq_micro; const char *my_plvl; if (req_version && req_version[0] == 1 && req_version[1] == 1) return _gcry_compat_identification (); /* Initialize library. */ global_init (); if ( !req_version ) /* Caller wants our version number. */ return ver; /* Parse own version number. */ my_plvl = parse_version_string( ver, &my_major, &my_minor, &my_micro ); if ( !my_plvl ) /* very strange our own version is bogus. Shouldn't we use assert() here and bail out in case this happens? -mo. */ return NULL; /* Parse requested version number. */ if (!parse_version_string (req_version, &rq_major, &rq_minor, &rq_micro)) return NULL; /* req version string is invalid, this can happen. */ /* Compare version numbers. */ if ( my_major > rq_major || (my_major == rq_major && my_minor > rq_minor) || (my_major == rq_major && my_minor == rq_minor && my_micro > rq_micro) || (my_major == rq_major && my_minor == rq_minor && my_micro == rq_micro)) { return ver; } return NULL; } static void print_config ( int (*fnc)(FILE *fp, const char *format, ...), FILE *fp) { unsigned int hwfeatures, afeature; int i; const char *s; fnc (fp, "version:%s:\n", VERSION); fnc (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS); fnc (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS); fnc (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS); fnc (fp, "rnd-mod:" #if USE_RNDEGD "egd:" #endif #if USE_RNDLINUX "linux:" #endif #if USE_RNDUNIX "unix:" #endif #if USE_RNDW32 "w32:" #endif "\n"); fnc (fp, "cpu-arch:" #if defined(HAVE_CPU_ARCH_X86) "x86" #elif defined(HAVE_CPU_ARCH_ALPHA) "alpha" #elif defined(HAVE_CPU_ARCH_SPARC) "sparc" #elif defined(HAVE_CPU_ARCH_MIPS) "mips" #elif defined(HAVE_CPU_ARCH_M68K) "m68k" #elif defined(HAVE_CPU_ARCH_PPC) "ppc" #elif defined(HAVE_CPU_ARCH_ARM) "arm" #endif ":\n"); fnc (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ()); hwfeatures = _gcry_get_hw_features (); fnc (fp, "hwflist:"); for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++) if ((hwfeatures & afeature)) fnc (fp, "%s:", s); fnc (fp, "\n"); /* We use y/n instead of 1/0 for the simple reason that Emacsen's compile error parser would accidentally flag that line when printed during "make check" as an error. */ fnc (fp, "fips-mode:%c:%c:\n", fips_mode ()? 'y':'n', _gcry_enforced_fips_mode ()? 'y':'n' ); /* The currently used RNG type. */ { i = _gcry_get_rng_type (0); switch (i) { case GCRY_RNG_TYPE_STANDARD: s = "standard"; break; case GCRY_RNG_TYPE_FIPS: s = "fips"; break; case GCRY_RNG_TYPE_SYSTEM: s = "system"; break; default: BUG (); } fnc (fp, "rng-type:%s:%d:\n", s, i); } } /* Command dispatcher function, acting as general control function. */ gcry_err_code_t _gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr) { static int init_finished = 0; gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_ENABLE_M_GUARD: _gcry_private_enable_m_guard (); break; case GCRYCTL_ENABLE_QUICK_RANDOM: _gcry_set_preferred_rng_type (0); _gcry_enable_quick_random_gen (); break; case GCRYCTL_FAKED_RANDOM_P: /* Return an error if the RNG is faked one (e.g. enabled by ENABLE_QUICK_RANDOM. */ if (_gcry_random_is_faked ()) rc = GPG_ERR_GENERAL; /* Use as TRUE value. */ break; case GCRYCTL_DUMP_RANDOM_STATS: _gcry_random_dump_stats (); break; case GCRYCTL_DUMP_MEMORY_STATS: /*m_print_stats("[fixme: prefix]");*/ break; case GCRYCTL_DUMP_SECMEM_STATS: _gcry_secmem_dump_stats (); break; case GCRYCTL_DROP_PRIVS: global_init (); _gcry_secmem_init (0); break; case GCRYCTL_DISABLE_SECMEM: global_init (); no_secure_memory = 1; break; case GCRYCTL_INIT_SECMEM: global_init (); _gcry_secmem_init (va_arg (arg_ptr, unsigned int)); if ((_gcry_secmem_get_flags () & GCRY_SECMEM_FLAG_NOT_LOCKED)) rc = GPG_ERR_GENERAL; break; case GCRYCTL_TERM_SECMEM: global_init (); _gcry_secmem_term (); break; case GCRYCTL_DISABLE_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_WARNING)); break; case GCRYCTL_SUSPEND_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_SUSPEND_WARNING)); break; case GCRYCTL_RESUME_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () & ~GCRY_SECMEM_FLAG_SUSPEND_WARNING)); break; case GCRYCTL_USE_SECURE_RNDPOOL: global_init (); _gcry_secure_random_alloc (); /* Put random number into secure memory. */ break; case GCRYCTL_SET_RANDOM_SEED_FILE: _gcry_set_preferred_rng_type (0); _gcry_set_random_seed_file (va_arg (arg_ptr, const char *)); break; case GCRYCTL_UPDATE_RANDOM_SEED_FILE: _gcry_set_preferred_rng_type (0); if ( fips_is_operational () ) _gcry_update_random_seed_file (); break; case GCRYCTL_SET_VERBOSITY: _gcry_set_preferred_rng_type (0); _gcry_set_log_verbosity (va_arg (arg_ptr, int)); break; case GCRYCTL_SET_DEBUG_FLAGS: debug_flags |= va_arg (arg_ptr, unsigned int); break; case GCRYCTL_CLEAR_DEBUG_FLAGS: debug_flags &= ~va_arg (arg_ptr, unsigned int); break; case GCRYCTL_DISABLE_INTERNAL_LOCKING: /* Not used anymore. */ global_init (); break; case GCRYCTL_ANY_INITIALIZATION_P: if (any_init_done) rc = GPG_ERR_GENERAL; break; case GCRYCTL_INITIALIZATION_FINISHED_P: if (init_finished) rc = GPG_ERR_GENERAL; /* Yes. */ break; case GCRYCTL_INITIALIZATION_FINISHED: /* This is a hook which should be used by an application after all initialization has been done and right before any threads are started. It is not really needed but the only way to be really sure that all initialization for thread-safety has been done. */ if (! init_finished) { global_init (); /* Do only a basic random initialization, i.e. init the mutexes. */ _gcry_random_initialize (0); init_finished = 1; /* Force us into operational state if in FIPS mode. */ (void)fips_is_operational (); } break; case GCRYCTL_SET_THREAD_CBS: /* This is now a dummy call. We used to install our own thread library here. */ _gcry_set_preferred_rng_type (0); global_init (); break; case GCRYCTL_FAST_POLL: _gcry_set_preferred_rng_type (0); /* We need to do make sure that the random pool is really initialized so that the poll function is not a NOP. */ _gcry_random_initialize (1); if ( fips_is_operational () ) _gcry_fast_random_poll (); break; case GCRYCTL_SET_RNDEGD_SOCKET: #if USE_RNDEGD _gcry_set_preferred_rng_type (0); rc = _gcry_rndegd_set_socket_name (va_arg (arg_ptr, const char *)); #else rc = GPG_ERR_NOT_SUPPORTED; #endif break; case GCRYCTL_SET_RANDOM_DAEMON_SOCKET: _gcry_set_preferred_rng_type (0); _gcry_set_random_daemon_socket (va_arg (arg_ptr, const char *)); break; case GCRYCTL_USE_RANDOM_DAEMON: /* We need to do make sure that the random pool is really initialized so that the poll function is not a NOP. */ _gcry_set_preferred_rng_type (0); _gcry_random_initialize (1); _gcry_use_random_daemon (!! va_arg (arg_ptr, int)); break; case GCRYCTL_CLOSE_RANDOM_DEVICE: _gcry_random_close_fds (); break; /* This command dumps information pertaining to the configuration of libgcrypt to the given stream. It may be used before the initialization has been finished but not before a gcry_version_check. */ case GCRYCTL_PRINT_CONFIG: { FILE *fp = va_arg (arg_ptr, FILE *); _gcry_set_preferred_rng_type (0); print_config (fp?fprintf:_gcry_log_info_with_dummy_fp, fp); } break; case GCRYCTL_OPERATIONAL_P: /* Returns true if the library is in an operational state. This is always true for non-fips mode. */ _gcry_set_preferred_rng_type (0); if (_gcry_fips_test_operational ()) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ break; case GCRYCTL_FIPS_MODE_P: if (fips_mode () && !_gcry_is_fips_mode_inactive () && !no_secure_memory) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ break; case GCRYCTL_FORCE_FIPS_MODE: /* Performing this command puts the library into fips mode. If the library has already been initialized into fips mode, a selftest is triggered. It is not possible to put the libraty into fips mode after having passed the initialization. */ _gcry_set_preferred_rng_type (0); if (!any_init_done) { /* Not yet intialized at all. Set a flag so that we are put into fips mode during initialization. */ force_fips_mode = 1; } else { /* Already initialized. If we are already operational we run a selftest. If not we use the is_operational call to force us into operational state if possible. */ if (_gcry_fips_test_error_or_operational ()) _gcry_fips_run_selftests (1); if (_gcry_fips_is_operational ()) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ } break; case GCRYCTL_SELFTEST: /* Run a selftest. This works in fips mode as well as in standard mode. In contrast to the power-up tests, we use an extended version of the selftests. Returns 0 on success or an error code. */ global_init (); rc = _gcry_fips_run_selftests (1); break; #if _GCRY_GCC_VERSION >= 40600 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wswitch" #endif case 58: /* Init external random test. */ - { - void **rctx = va_arg (arg_ptr, void **); - unsigned int flags = va_arg (arg_ptr, unsigned int); - const void *key = va_arg (arg_ptr, const void *); - size_t keylen = va_arg (arg_ptr, size_t); - const void *seed = va_arg (arg_ptr, const void *); - size_t seedlen = va_arg (arg_ptr, size_t); - const void *dt = va_arg (arg_ptr, const void *); - size_t dtlen = va_arg (arg_ptr, size_t); - if (!fips_is_operational ()) - rc = fips_not_operational (); - else - rc = _gcry_random_init_external_test (rctx, flags, key, keylen, - seed, seedlen, dt, dtlen); - } + rc = GPG_ERR_NOT_SUPPORTED; break; - case 59: /* Run external random test. */ + case 59: /* Run external DRBG test. */ { - void *ctx = va_arg (arg_ptr, void *); - void *buffer = va_arg (arg_ptr, void *); - size_t buflen = va_arg (arg_ptr, size_t); - if (!fips_is_operational ()) - rc = fips_not_operational (); + struct gcry_drbg_test_vector *test = + va_arg (arg_ptr, struct gcry_drbg_test_vector *); + unsigned char *buf = va_arg (arg_ptr, unsigned char *); + + if (buf) + rc = gcry_drbg_cavs_test (test, buf); else - rc = _gcry_random_run_external_test (ctx, buffer, buflen); + rc = gcry_drbg_healthcheck_one (test); } break; case 60: /* Deinit external random test. */ - { - void *ctx = va_arg (arg_ptr, void *); - _gcry_random_deinit_external_test (ctx); - } + rc = GPG_ERR_NOT_SUPPORTED; break; case 61: /* Run external lock test */ rc = external_lock_test (va_arg (arg_ptr, int)); break; case 62: /* RFU */ break; #if _GCRY_GCC_VERSION >= 40600 # pragma GCC diagnostic pop #endif case GCRYCTL_DISABLE_HWF: { const char *name = va_arg (arg_ptr, const char *); rc = _gcry_disable_hw_feature (name); } break; case GCRYCTL_SET_ENFORCED_FIPS_FLAG: if (!any_init_done) { /* Not yet initialized at all. Set the enforced fips mode flag */ _gcry_set_preferred_rng_type (0); _gcry_set_enforced_fips_mode (); } else rc = GPG_ERR_GENERAL; break; case GCRYCTL_SET_PREFERRED_RNG_TYPE: /* This may be called before gcry_check_version. */ { int i = va_arg (arg_ptr, int); /* Note that we may not pass 0 to _gcry_set_preferred_rng_type. */ if (i > 0) _gcry_set_preferred_rng_type (i); } break; case GCRYCTL_GET_CURRENT_RNG_TYPE: { int *ip = va_arg (arg_ptr, int*); if (ip) *ip = _gcry_get_rng_type (!any_init_done); } break; case GCRYCTL_DISABLE_LOCKED_SECMEM: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_MLOCK)); break; case GCRYCTL_DISABLE_PRIV_DROP: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_PRIV_DROP)); break; case GCRYCTL_INACTIVATE_FIPS_FLAG: case GCRYCTL_REACTIVATE_FIPS_FLAG: rc = GPG_ERR_NOT_IMPLEMENTED; break; + case GCRYCTL_DRBG_REINIT: + { + u32 flags = va_arg (arg_ptr, u32); + struct gcry_drbg_string *pers = va_arg (arg_ptr, + struct gcry_drbg_string *); + rc = _gcry_drbg_reinit(flags, pers); + } + break; + default: _gcry_set_preferred_rng_type (0); rc = GPG_ERR_INV_OP; } return rc; } /* Set custom allocation handlers. This is in general not useful * because the libgcrypt allocation functions are guaranteed to * provide proper allocation handlers which zeroize memory if needed. * NOTE: All 5 functions should be set. */ void _gcry_set_allocation_handler (gcry_handler_alloc_t new_alloc_func, gcry_handler_alloc_t new_alloc_secure_func, gcry_handler_secure_check_t new_is_secure_func, gcry_handler_realloc_t new_realloc_func, gcry_handler_free_t new_free_func) { global_init (); if (fips_mode ()) { /* We do not want to enforce the fips mode, but merely set a flag so that the application may check whether it is still in fips mode. */ _gcry_inactivate_fips_mode ("custom allocation handler"); } alloc_func = new_alloc_func; alloc_secure_func = new_alloc_secure_func; is_secure_func = new_is_secure_func; realloc_func = new_realloc_func; free_func = new_free_func; } /**************** * Set an optional handler which is called in case the xmalloc functions * ran out of memory. This handler may do one of these things: * o free some memory and return true, so that the xmalloc function * tries again. * o Do whatever it like and return false, so that the xmalloc functions * use the default fatal error handler. * o Terminate the program and don't return. * * The handler function is called with 3 arguments: The opaque value set with * this function, the requested memory size, and a flag with these bits * currently defined: * bit 0 set = secure memory has been requested. */ void _gcry_set_outofcore_handler (int (*f)(void*, size_t, unsigned int), void *value) { global_init (); if (fips_mode () ) { log_info ("out of core handler ignored in FIPS mode\n"); return; } outofcore_handler = f; outofcore_handler_value = value; } /* Return the no_secure_memory flag. */ static int get_no_secure_memory (void) { if (!no_secure_memory) return 0; if (_gcry_enforced_fips_mode ()) { no_secure_memory = 0; return 0; } return no_secure_memory; } static gcry_err_code_t do_malloc (size_t n, unsigned int flags, void **mem) { gcry_err_code_t err = 0; void *m; if ((flags & GCRY_ALLOC_FLAG_SECURE) && !get_no_secure_memory ()) { if (alloc_secure_func) m = (*alloc_secure_func) (n); else m = _gcry_private_malloc_secure (n); } else { if (alloc_func) m = (*alloc_func) (n); else m = _gcry_private_malloc (n); } if (!m) { /* Make sure that ERRNO has been set in case a user supplied memory handler didn't it correctly. */ if (!errno) gpg_err_set_errno (ENOMEM); err = gpg_err_code_from_errno (errno); } else *mem = m; return err; } void * _gcry_malloc (size_t n) { void *mem = NULL; do_malloc (n, 0, &mem); return mem; } void * _gcry_malloc_secure (size_t n) { void *mem = NULL; do_malloc (n, GCRY_ALLOC_FLAG_SECURE, &mem); return mem; } int _gcry_is_secure (const void *a) { if (get_no_secure_memory ()) return 0; if (is_secure_func) return is_secure_func (a) ; return _gcry_private_is_secure (a); } void _gcry_check_heap( const void *a ) { (void)a; /* FIXME: implement this*/ #if 0 if( some_handler ) some_handler(a) else _gcry_private_check_heap(a) #endif } void * _gcry_realloc (void *a, size_t n) { void *p; /* To avoid problems with non-standard realloc implementations and our own secmem_realloc, we divert to malloc and free here. */ if (!a) return _gcry_malloc (n); if (!n) { xfree (a); return NULL; } if (realloc_func) p = realloc_func (a, n); else p = _gcry_private_realloc (a, n); if (!p && !errno) gpg_err_set_errno (ENOMEM); return p; } void _gcry_free (void *p) { int save_errno; if (!p) return; /* In case ERRNO is set we better save it so that the free machinery may not accidentally change ERRNO. We restore it only if it was already set to comply with the usual C semantic for ERRNO. */ save_errno = errno; if (free_func) free_func (p); else _gcry_private_free (p); if (save_errno) gpg_err_set_errno (save_errno); } void * _gcry_calloc (size_t n, size_t m) { size_t bytes; void *p; bytes = n * m; /* size_t is unsigned so the behavior on overflow is defined. */ if (m && bytes / m != n) { gpg_err_set_errno (ENOMEM); return NULL; } p = _gcry_malloc (bytes); if (p) memset (p, 0, bytes); return p; } void * _gcry_calloc_secure (size_t n, size_t m) { size_t bytes; void *p; bytes = n * m; /* size_t is unsigned so the behavior on overflow is defined. */ if (m && bytes / m != n) { gpg_err_set_errno (ENOMEM); return NULL; } p = _gcry_malloc_secure (bytes); if (p) memset (p, 0, bytes); return p; } /* Create and return a copy of the null-terminated string STRING. If it is contained in secure memory, the copy will be contained in secure memory as well. In an out-of-memory condition, NULL is returned. */ char * _gcry_strdup (const char *string) { char *string_cp = NULL; size_t string_n = 0; string_n = strlen (string); if (_gcry_is_secure (string)) string_cp = _gcry_malloc_secure (string_n + 1); else string_cp = _gcry_malloc (string_n + 1); if (string_cp) strcpy (string_cp, string); return string_cp; } void * _gcry_xmalloc( size_t n ) { void *p; while ( !(p = _gcry_malloc( n )) ) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, 0) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL); } } return p; } void * _gcry_xrealloc( void *a, size_t n ) { void *p; while ( !(p = _gcry_realloc( a, n )) ) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, _gcry_is_secure(a)? 3:2)) { _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL ); } } return p; } void * _gcry_xmalloc_secure( size_t n ) { void *p; while ( !(p = _gcry_malloc_secure( n )) ) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, 1) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), _("out of core in secure memory")); } } return p; } void * _gcry_xcalloc( size_t n, size_t m ) { size_t nbytes; void *p; nbytes = n * m; if (m && nbytes / m != n) { gpg_err_set_errno (ENOMEM); _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); } p = _gcry_xmalloc ( nbytes ); memset ( p, 0, nbytes ); return p; } void * _gcry_xcalloc_secure( size_t n, size_t m ) { size_t nbytes; void *p; nbytes = n * m; if (m && nbytes / m != n) { gpg_err_set_errno (ENOMEM); _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); } p = _gcry_xmalloc_secure ( nbytes ); memset ( p, 0, nbytes ); return p; } char * _gcry_xstrdup (const char *string) { char *p; while ( !(p = _gcry_strdup (string)) ) { size_t n = strlen (string); int is_sec = !!_gcry_is_secure (string); if (fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, is_sec) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), is_sec? _("out of core in secure memory"):NULL); } } return p; } int _gcry_get_debug_flag (unsigned int mask) { if ( fips_mode () ) return 0; return (debug_flags & mask); } /* It is often useful to get some feedback of long running operations. This function may be used to register a handler for this. The callback function CB is used as: void cb (void *opaque, const char *what, int printchar, int current, int total); Where WHAT is a string identifying the the type of the progress output, PRINTCHAR the character usually printed, CURRENT the amount of progress currently done and TOTAL the expected amount of progress. A value of 0 for TOTAL indicates that there is no estimation available. Defined values for WHAT: "need_entropy" X 0 number-of-bytes-required When running low on entropy "primegen" '\n' 0 0 Prime generated '!' Need to refresh the prime pool '<','>' Number of bits adjusted '^' Looking for a generator '.' Fermat tests on 10 candidates failed ':' Restart with a new random value '+' Rabin Miller test passed "pk_elg" '+','-','.','\n' 0 0 Only used in debugging mode. "pk_dsa" Only used in debugging mode. */ void _gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int), void *cb_data) { #if USE_DSA _gcry_register_pk_dsa_progress (cb, cb_data); #endif #if USE_ELGAMAL _gcry_register_pk_elg_progress (cb, cb_data); #endif _gcry_register_primegen_progress (cb, cb_data); _gcry_register_random_progress (cb, cb_data); } /* This is a helper for the regression test suite to test Libgcrypt's locks. It works using a one test lock with CMD controlling what to do: 30111 - Allocate and init lock 30112 - Take lock 30113 - Release lock 30114 - Destroy lock. This function is used by tests/t-lock.c - it is not part of the public API! */ static gpg_err_code_t external_lock_test (int cmd) { GPGRT_LOCK_DEFINE (testlock); gpg_err_code_t rc = 0; switch (cmd) { case 30111: /* Init Lock. */ rc = gpgrt_lock_init (&testlock); break; case 30112: /* Take Lock. */ rc = gpgrt_lock_lock (&testlock); break; case 30113: /* Release Lock. */ rc = gpgrt_lock_unlock (&testlock); break; case 30114: /* Destroy Lock. */ rc = gpgrt_lock_destroy (&testlock); break; default: rc = GPG_ERR_INV_OP; break; } return rc; }