diff --git a/cipher/cipher-aeswrap.c b/cipher/cipher-aeswrap.c index 50ac1073..698742df 100644 --- a/cipher/cipher-aeswrap.c +++ b/cipher/cipher-aeswrap.c @@ -1,210 +1,209 @@ /* cipher-aeswrap.c - Generic AESWRAP mode implementation * Copyright (C) 2009, 2011 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" /* Perform the AES-Wrap algorithm as specified by RFC3394. We implement this as a mode usable with any cipher algorithm of blocksize 128. */ gcry_err_code_t _gcry_cipher_aeswrap_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen ) { int j, x; size_t n, i; unsigned char *r, *a, *b; unsigned char t[8]; unsigned int burn, nburn; #if MAX_BLOCKSIZE < 8 #error Invalid block size #endif /* We require a cipher with a 128 bit block length. */ if (c->spec->blocksize != 16) return GPG_ERR_INV_LENGTH; /* The output buffer must be able to hold the input data plus one additional block. */ if (outbuflen < inbuflen + 8) return GPG_ERR_BUFFER_TOO_SHORT; /* Input data must be multiple of 64 bits. */ if (inbuflen % 8) return GPG_ERR_INV_ARG; n = inbuflen / 8; /* We need at least two 64 bit blocks. */ if (n < 2) return GPG_ERR_INV_ARG; burn = 0; r = outbuf; a = outbuf; /* We store A directly in OUTBUF. */ b = c->u_ctr.ctr; /* B is also used to concatenate stuff. */ /* If an IV has been set we use that IV as the Alternative Initial Value; if it has not been set we use the standard value. */ if (c->marks.iv) memcpy (a, c->u_iv.iv, 8); else memset (a, 0xa6, 8); /* Copy the inbuf to the outbuf. */ memmove (r+8, inbuf, inbuflen); memset (t, 0, sizeof t); /* t := 0. */ for (j = 0; j <= 5; j++) { for (i = 1; i <= n; i++) { /* B := AES_k( A | R[i] ) */ memcpy (b, a, 8); memcpy (b+8, r+i*8, 8); nburn = c->spec->encrypt (&c->context.c, b, b); burn = nburn > burn ? nburn : burn; /* t := t + 1 */ for (x = 7; x >= 0; x--) { t[x]++; if (t[x]) break; } /* A := MSB_64(B) ^ t */ buf_xor(a, b, t, 8); /* R[i] := LSB_64(B) */ memcpy (r+i*8, b+8, 8); } } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } /* Perform the AES-Unwrap algorithm as specified by RFC3394. We implement this as a mode usable with any cipher algorithm of blocksize 128. */ gcry_err_code_t _gcry_cipher_aeswrap_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { int j, x; size_t n, i; unsigned char *r, *a, *b; unsigned char t[8]; unsigned int burn, nburn; #if MAX_BLOCKSIZE < 8 #error Invalid block size #endif /* We require a cipher with a 128 bit block length. */ if (c->spec->blocksize != 16) return GPG_ERR_INV_LENGTH; /* The output buffer must be able to hold the input data minus one additional block. Fixme: The caller has more restrictive checks - we may want to fix them for this mode. */ if (outbuflen + 8 < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; /* Input data must be multiple of 64 bits. */ if (inbuflen % 8) return GPG_ERR_INV_ARG; n = inbuflen / 8; /* We need at least three 64 bit blocks. */ if (n < 3) return GPG_ERR_INV_ARG; burn = 0; r = outbuf; a = c->lastiv; /* We use c->LASTIV as buffer for A. */ b = c->u_ctr.ctr; /* B is also used to concatenate stuff. */ /* Copy the inbuf to the outbuf and save A. */ memcpy (a, inbuf, 8); memmove (r, inbuf+8, inbuflen-8); n--; /* Reduce to actual number of data blocks. */ /* t := 6 * n */ i = n * 6; /* The range is valid because: n = inbuflen / 8 - 1. */ for (x=0; x < 8 && x < sizeof (i); x++) t[7-x] = i >> (8*x); for (; x < 8; x++) t[7-x] = 0; for (j = 5; j >= 0; j--) { for (i = n; i >= 1; i--) { /* B := AES_k^1( (A ^ t)| R[i] ) */ buf_xor(b, a, t, 8); memcpy (b+8, r+(i-1)*8, 8); nburn = c->spec->decrypt (&c->context.c, b, b); burn = nburn > burn ? nburn : burn; /* t := t - 1 */ for (x = 7; x >= 0; x--) { t[x]--; if (t[x] != 0xff) break; } /* A := MSB_64(B) */ memcpy (a, b, 8); /* R[i] := LSB_64(B) */ memcpy (r+(i-1)*8, b+8, 8); } } /* If an IV has been set we compare against this Alternative Initial Value; if it has not been set we compare against the standard IV. */ if (c->marks.iv) j = memcmp (a, c->u_iv.iv, 8); else { for (j=0, x=0; x < 8; x++) if (a[x] != 0xa6) { j=1; break; } } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return j? GPG_ERR_CHECKSUM : 0; } diff --git a/cipher/cipher-cbc.c b/cipher/cipher-cbc.c index 4b929daa..67814b76 100644 --- a/cipher/cipher-cbc.c +++ b/cipher/cipher-cbc.c @@ -1,205 +1,204 @@ /* cipher-cbc.c - Generic CBC mode implementation * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "./cipher-internal.h" #include "bufhelp.h" gcry_err_code_t _gcry_cipher_cbc_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { size_t n; unsigned char *ivp; int i; size_t blocksize = c->spec->blocksize; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; size_t nblocks = inbuflen / blocksize; unsigned int burn, nburn; if (outbuflen < ((c->flags & GCRY_CIPHER_CBC_MAC)? blocksize : inbuflen)) return GPG_ERR_BUFFER_TOO_SHORT; if ((inbuflen % blocksize) && !(inbuflen > blocksize && (c->flags & GCRY_CIPHER_CBC_CTS))) return GPG_ERR_INV_LENGTH; burn = 0; if ((c->flags & GCRY_CIPHER_CBC_CTS) && inbuflen > blocksize) { if ((inbuflen % blocksize) == 0) nblocks--; } if (c->bulk.cbc_enc) { c->bulk.cbc_enc (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks, (c->flags & GCRY_CIPHER_CBC_MAC)); inbuf += nblocks * blocksize; if (!(c->flags & GCRY_CIPHER_CBC_MAC)) outbuf += nblocks * blocksize; } else { ivp = c->u_iv.iv; for (n=0; n < nblocks; n++ ) { buf_xor (outbuf, inbuf, ivp, blocksize); nburn = enc_fn ( &c->context.c, outbuf, outbuf ); burn = nburn > burn ? nburn : burn; ivp = outbuf; inbuf += blocksize; if (!(c->flags & GCRY_CIPHER_CBC_MAC)) outbuf += blocksize; } if (ivp != c->u_iv.iv) buf_cpy (c->u_iv.iv, ivp, blocksize ); } if ((c->flags & GCRY_CIPHER_CBC_CTS) && inbuflen > blocksize) { /* We have to be careful here, since outbuf might be equal to inbuf. */ size_t restbytes; unsigned char b; if ((inbuflen % blocksize) == 0) restbytes = blocksize; else restbytes = inbuflen % blocksize; outbuf -= blocksize; for (ivp = c->u_iv.iv, i = 0; i < restbytes; i++) { b = inbuf[i]; outbuf[blocksize + i] = outbuf[i]; outbuf[i] = b ^ *ivp++; } for (; i < blocksize; i++) outbuf[i] = 0 ^ *ivp++; nburn = enc_fn (&c->context.c, outbuf, outbuf); burn = nburn > burn ? nburn : burn; buf_cpy (c->u_iv.iv, outbuf, blocksize); } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } gcry_err_code_t _gcry_cipher_cbc_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { size_t n; int i; size_t blocksize = c->spec->blocksize; gcry_cipher_decrypt_t dec_fn = c->spec->decrypt; size_t nblocks = inbuflen / blocksize; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if ((inbuflen % blocksize) && !(inbuflen > blocksize && (c->flags & GCRY_CIPHER_CBC_CTS))) return GPG_ERR_INV_LENGTH; burn = 0; if ((c->flags & GCRY_CIPHER_CBC_CTS) && inbuflen > blocksize) { nblocks--; if ((inbuflen % blocksize) == 0) nblocks--; buf_cpy (c->lastiv, c->u_iv.iv, blocksize); } if (c->bulk.cbc_dec) { c->bulk.cbc_dec (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); inbuf += nblocks * blocksize; outbuf += nblocks * blocksize; } else { for (n=0; n < nblocks; n++ ) { /* Because outbuf and inbuf might be the same, we must not overwrite the original ciphertext block. We use LASTIV as intermediate storage here because it is not used otherwise. */ nburn = dec_fn ( &c->context.c, c->lastiv, inbuf ); burn = nburn > burn ? nburn : burn; buf_xor_n_copy_2(outbuf, c->lastiv, c->u_iv.iv, inbuf, blocksize); inbuf += blocksize; outbuf += blocksize; } } if ((c->flags & GCRY_CIPHER_CBC_CTS) && inbuflen > blocksize) { size_t restbytes; if ((inbuflen % blocksize) == 0) restbytes = blocksize; else restbytes = inbuflen % blocksize; buf_cpy (c->lastiv, c->u_iv.iv, blocksize ); /* Save Cn-2. */ buf_cpy (c->u_iv.iv, inbuf + blocksize, restbytes ); /* Save Cn. */ nburn = dec_fn ( &c->context.c, outbuf, inbuf ); burn = nburn > burn ? nburn : burn; buf_xor(outbuf, outbuf, c->u_iv.iv, restbytes); buf_cpy (outbuf + blocksize, outbuf, restbytes); for(i=restbytes; i < blocksize; i++) c->u_iv.iv[i] = outbuf[i]; nburn = dec_fn (&c->context.c, outbuf, c->u_iv.iv); burn = nburn > burn ? nburn : burn; buf_xor(outbuf, outbuf, c->lastiv, blocksize); /* c->lastiv is now really lastlastiv, does this matter? */ } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } diff --git a/cipher/cipher-ccm.c b/cipher/cipher-ccm.c index 9d0bf0a2..3d5f2209 100644 --- a/cipher/cipher-ccm.c +++ b/cipher/cipher-ccm.c @@ -1,442 +1,441 @@ /* cipher-ccm.c - CTR mode with CBC-MAC mode implementation * Copyright (C) 2013 Jussi Kivilinna * * 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 "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" /* We need a 64 bit type for this code. */ #ifdef HAVE_U64_TYPEDEF #define set_burn(burn, nburn) do { \ unsigned int __nburn = (nburn); \ (burn) = (burn) > __nburn ? (burn) : __nburn; } while (0) static unsigned int do_cbc_mac (gcry_cipher_hd_t c, const unsigned char *inbuf, size_t inlen, int do_padding) { const unsigned int blocksize = 16; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; unsigned char tmp[blocksize]; unsigned int burn = 0; unsigned int unused = c->u_mode.ccm.mac_unused; size_t nblocks; if (inlen == 0 && (unused == 0 || !do_padding)) return 0; do { if (inlen + unused < blocksize || unused > 0) { for (; inlen && unused < blocksize; inlen--) c->u_mode.ccm.macbuf[unused++] = *inbuf++; } if (!inlen) { if (!do_padding) break; while (unused < blocksize) c->u_mode.ccm.macbuf[unused++] = 0; } if (unused > 0) { /* Process one block from macbuf. */ buf_xor(c->u_iv.iv, c->u_iv.iv, c->u_mode.ccm.macbuf, blocksize); set_burn (burn, enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv )); unused = 0; } if (c->bulk.cbc_enc) { nblocks = inlen / blocksize; c->bulk.cbc_enc (&c->context.c, c->u_iv.iv, tmp, inbuf, nblocks, 1); inbuf += nblocks * blocksize; inlen -= nblocks * blocksize; wipememory (tmp, sizeof(tmp)); } else { while (inlen >= blocksize) { buf_xor(c->u_iv.iv, c->u_iv.iv, inbuf, blocksize); set_burn (burn, enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv )); inlen -= blocksize; inbuf += blocksize; } } } while (inlen > 0); c->u_mode.ccm.mac_unused = unused; if (burn) burn += 4 * sizeof(void *); return burn; } gcry_err_code_t _gcry_cipher_ccm_set_nonce (gcry_cipher_hd_t c, const unsigned char *nonce, size_t noncelen) { size_t L = 15 - noncelen; size_t L_; L_ = L - 1; if (!nonce) return GPG_ERR_INV_ARG; /* Length field must be 2, 3, ..., or 8. */ if (L < 2 || L > 8) return GPG_ERR_INV_LENGTH; /* Reset state */ memset (&c->u_mode, 0, sizeof(c->u_mode)); memset (&c->marks, 0, sizeof(c->marks)); memset (&c->u_iv, 0, sizeof(c->u_iv)); memset (&c->u_ctr, 0, sizeof(c->u_ctr)); memset (c->lastiv, 0, sizeof(c->lastiv)); c->unused = 0; /* Setup CTR */ c->u_ctr.ctr[0] = L_; memcpy (&c->u_ctr.ctr[1], nonce, noncelen); memset (&c->u_ctr.ctr[1 + noncelen], 0, L); /* Setup IV */ c->u_iv.iv[0] = L_; memcpy (&c->u_iv.iv[1], nonce, noncelen); /* Add (8 * M_ + 64 * flags) to iv[0] and set iv[noncelen + 1 ... 15] later in set_aad. */ memset (&c->u_iv.iv[1 + noncelen], 0, L); c->u_mode.ccm.nonce = 1; return GPG_ERR_NO_ERROR; } gcry_err_code_t _gcry_cipher_ccm_set_lengths (gcry_cipher_hd_t c, u64 encryptlen, u64 aadlen, u64 taglen) { unsigned int burn = 0; unsigned char b0[16]; size_t noncelen = 15 - (c->u_iv.iv[0] + 1); u64 M = taglen; u64 M_; int i; M_ = (M - 2) / 2; /* Authentication field must be 4, 6, 8, 10, 12, 14 or 16. */ if ((M_ * 2 + 2) != M || M < 4 || M > 16) return GPG_ERR_INV_LENGTH; if (!c->u_mode.ccm.nonce || c->marks.tag) return GPG_ERR_INV_STATE; if (c->u_mode.ccm.lengths) return GPG_ERR_INV_STATE; c->u_mode.ccm.authlen = taglen; c->u_mode.ccm.encryptlen = encryptlen; c->u_mode.ccm.aadlen = aadlen; /* Complete IV setup. */ c->u_iv.iv[0] += (aadlen > 0) * 64 + M_ * 8; for (i = 16 - 1; i >= 1 + noncelen; i--) { c->u_iv.iv[i] = encryptlen & 0xff; encryptlen >>= 8; } memcpy (b0, c->u_iv.iv, 16); memset (c->u_iv.iv, 0, 16); set_burn (burn, do_cbc_mac (c, b0, 16, 0)); if (aadlen == 0) { /* Do nothing. */ } else if (aadlen > 0 && aadlen <= (unsigned int)0xfeff) { b0[0] = (aadlen >> 8) & 0xff; b0[1] = aadlen & 0xff; set_burn (burn, do_cbc_mac (c, b0, 2, 0)); } else if (aadlen > 0xfeff && aadlen <= (unsigned int)0xffffffff) { b0[0] = 0xff; b0[1] = 0xfe; buf_put_be32(&b0[2], aadlen); set_burn (burn, do_cbc_mac (c, b0, 6, 0)); } else if (aadlen > (unsigned int)0xffffffff) { b0[0] = 0xff; b0[1] = 0xff; buf_put_be64(&b0[2], aadlen); set_burn (burn, do_cbc_mac (c, b0, 10, 0)); } /* Generate S_0 and increase counter. */ set_burn (burn, c->spec->encrypt ( &c->context.c, c->u_mode.ccm.s0, c->u_ctr.ctr )); c->u_ctr.ctr[15]++; if (burn) _gcry_burn_stack (burn + sizeof(void *) * 5); c->u_mode.ccm.lengths = 1; return GPG_ERR_NO_ERROR; } gcry_err_code_t _gcry_cipher_ccm_authenticate (gcry_cipher_hd_t c, const unsigned char *abuf, size_t abuflen) { unsigned int burn; if (abuflen > 0 && !abuf) return GPG_ERR_INV_ARG; if (!c->u_mode.ccm.nonce || !c->u_mode.ccm.lengths || c->marks.tag) return GPG_ERR_INV_STATE; if (abuflen > c->u_mode.ccm.aadlen) return GPG_ERR_INV_LENGTH; c->u_mode.ccm.aadlen -= abuflen; burn = do_cbc_mac (c, abuf, abuflen, c->u_mode.ccm.aadlen == 0); if (burn) _gcry_burn_stack (burn + sizeof(void *) * 5); return GPG_ERR_NO_ERROR; } gcry_err_code_t _gcry_cipher_ccm_tag (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, int check) { unsigned int burn; if (!outbuf || outbuflen == 0) return GPG_ERR_INV_ARG; /* Tag length must be same as initial authlen. */ if (c->u_mode.ccm.authlen != outbuflen) return GPG_ERR_INV_LENGTH; if (!c->u_mode.ccm.nonce || !c->u_mode.ccm.lengths || c->u_mode.ccm.aadlen > 0) return GPG_ERR_INV_STATE; /* Initial encrypt length must match with length of actual data processed. */ if (c->u_mode.ccm.encryptlen > 0) return GPG_ERR_UNFINISHED; if (!c->marks.tag) { burn = do_cbc_mac (c, NULL, 0, 1); /* Perform final padding. */ /* Add S_0 */ buf_xor (c->u_iv.iv, c->u_iv.iv, c->u_mode.ccm.s0, 16); wipememory (c->u_ctr.ctr, 16); wipememory (c->u_mode.ccm.s0, 16); wipememory (c->u_mode.ccm.macbuf, 16); if (burn) _gcry_burn_stack (burn + sizeof(void *) * 5); c->marks.tag = 1; } if (!check) { memcpy (outbuf, c->u_iv.iv, outbuflen); return GPG_ERR_NO_ERROR; } else { return buf_eq_const(outbuf, c->u_iv.iv, outbuflen) ? GPG_ERR_NO_ERROR : GPG_ERR_CHECKSUM; } } gcry_err_code_t _gcry_cipher_ccm_get_tag (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen) { return _gcry_cipher_ccm_tag (c, outtag, taglen, 0); } gcry_err_code_t _gcry_cipher_ccm_check_tag (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen) { return _gcry_cipher_ccm_tag (c, (unsigned char *)intag, taglen, 1); } gcry_err_code_t _gcry_cipher_ccm_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { unsigned int burn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (!c->u_mode.ccm.nonce || c->marks.tag || !c->u_mode.ccm.lengths || c->u_mode.ccm.aadlen > 0) return GPG_ERR_INV_STATE; if (inbuflen > c->u_mode.ccm.encryptlen) return GPG_ERR_INV_LENGTH; c->u_mode.ccm.encryptlen -= inbuflen; burn = do_cbc_mac (c, inbuf, inbuflen, 0); if (burn) _gcry_burn_stack (burn + sizeof(void *) * 5); return _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); } gcry_err_code_t _gcry_cipher_ccm_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { gcry_err_code_t err; unsigned int burn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (!c->u_mode.ccm.nonce || c->marks.tag || !c->u_mode.ccm.lengths || c->u_mode.ccm.aadlen > 0) return GPG_ERR_INV_STATE; if (inbuflen > c->u_mode.ccm.encryptlen) return GPG_ERR_INV_LENGTH; err = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); if (err) return err; c->u_mode.ccm.encryptlen -= inbuflen; burn = do_cbc_mac (c, outbuf, inbuflen, 0); if (burn) _gcry_burn_stack (burn + sizeof(void *) * 5); return err; } #else /* * Provide dummy functions so that we avoid adding too much #ifdefs in * cipher.c. */ gcry_err_code_t _gcry_cipher_ccm_encrypt(gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { (void)c; (void)outbuf; (void)outbuflen; (void)inbuf; (void)inbuflen; return GPG_ERR_NOT_SUPPORTED; } gcry_err_code_t _gcry_cipher_ccm_decrypt(gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { (void)c; (void)outbuf; (void)outbuflen; (void)inbuf; (void)inbuflen; return GPG_ERR_NOT_SUPPORTED; } gcry_err_code_t _gcry_cipher_ccm_set_nonce(gcry_cipher_hd_t c, const unsigned char *nonce, size_t noncelen) { (void)c; (void)nonce; (void)noncelen; return GPG_ERR_NOT_SUPPORTED; } gcry_err_code_t _gcry_cipher_ccm_authenticate(gcry_cipher_hd_t c, const unsigned char *abuf, size_t abuflen) { (void)c; (void)abuf; (void)abuflen; return GPG_ERR_NOT_SUPPORTED; } gcry_err_code_t _gcry_cipher_ccm_get_tag(gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen) { (void)c; (void)outtag; (void)taglen; return GPG_ERR_NOT_SUPPORTED; } gcry_err_code_t _gcry_cipher_ccm_check_tag(gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen) { (void)c; (void)intag; (void)taglen; return GPG_ERR_NOT_SUPPORTED; } #endif /*HAVE_U64_TYPEDEF*/ diff --git a/cipher/cipher-cfb.c b/cipher/cipher-cfb.c index 8539f548..f289ed38 100644 --- a/cipher/cipher-cfb.c +++ b/cipher/cipher-cfb.c @@ -1,226 +1,225 @@ /* cipher-cfb.c - Generic CFB mode implementation * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" gcry_err_code_t _gcry_cipher_cfb_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { unsigned char *ivp; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; size_t blocksize = c->spec->blocksize; size_t blocksize_x_2 = blocksize + blocksize; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if ( inbuflen <= c->unused ) { /* Short enough to be encoded by the remaining XOR mask. */ /* XOR the input with the IV and store input into IV. */ ivp = c->u_iv.iv + blocksize - c->unused; buf_xor_2dst(outbuf, ivp, inbuf, inbuflen); c->unused -= inbuflen; return 0; } burn = 0; if ( c->unused ) { /* XOR the input with the IV and store input into IV */ inbuflen -= c->unused; ivp = c->u_iv.iv + blocksize - c->unused; buf_xor_2dst(outbuf, ivp, inbuf, c->unused); outbuf += c->unused; inbuf += c->unused; c->unused = 0; } /* Now we can process complete blocks. We use a loop as long as we have at least 2 blocks and use conditions for the rest. This also allows to use a bulk encryption function if available. */ if (inbuflen >= blocksize_x_2 && c->bulk.cfb_enc) { size_t nblocks = inbuflen / blocksize; c->bulk.cfb_enc (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); outbuf += nblocks * blocksize; inbuf += nblocks * blocksize; inbuflen -= nblocks * blocksize; } else { while ( inbuflen >= blocksize_x_2 ) { /* Encrypt the IV. */ nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; /* XOR the input with the IV and store input into IV. */ buf_xor_2dst(outbuf, c->u_iv.iv, inbuf, blocksize); outbuf += blocksize; inbuf += blocksize; inbuflen -= blocksize; } } if ( inbuflen >= blocksize ) { /* Save the current IV and then encrypt the IV. */ buf_cpy( c->lastiv, c->u_iv.iv, blocksize ); nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; /* XOR the input with the IV and store input into IV */ buf_xor_2dst(outbuf, c->u_iv.iv, inbuf, blocksize); outbuf += blocksize; inbuf += blocksize; inbuflen -= blocksize; } if ( inbuflen ) { /* Save the current IV and then encrypt the IV. */ buf_cpy( c->lastiv, c->u_iv.iv, blocksize ); nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; c->unused = blocksize; /* Apply the XOR. */ c->unused -= inbuflen; buf_xor_2dst(outbuf, c->u_iv.iv, inbuf, inbuflen); outbuf += inbuflen; inbuf += inbuflen; inbuflen = 0; } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } gcry_err_code_t _gcry_cipher_cfb_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { unsigned char *ivp; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; size_t blocksize = c->spec->blocksize; size_t blocksize_x_2 = blocksize + blocksize; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (inbuflen <= c->unused) { /* Short enough to be encoded by the remaining XOR mask. */ /* XOR the input with the IV and store input into IV. */ ivp = c->u_iv.iv + blocksize - c->unused; buf_xor_n_copy(outbuf, ivp, inbuf, inbuflen); c->unused -= inbuflen; return 0; } burn = 0; if (c->unused) { /* XOR the input with the IV and store input into IV. */ inbuflen -= c->unused; ivp = c->u_iv.iv + blocksize - c->unused; buf_xor_n_copy(outbuf, ivp, inbuf, c->unused); outbuf += c->unused; inbuf += c->unused; c->unused = 0; } /* Now we can process complete blocks. We use a loop as long as we have at least 2 blocks and use conditions for the rest. This also allows to use a bulk encryption function if available. */ if (inbuflen >= blocksize_x_2 && c->bulk.cfb_dec) { size_t nblocks = inbuflen / blocksize; c->bulk.cfb_dec (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); outbuf += nblocks * blocksize; inbuf += nblocks * blocksize; inbuflen -= nblocks * blocksize; } else { while (inbuflen >= blocksize_x_2 ) { /* Encrypt the IV. */ nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; /* XOR the input with the IV and store input into IV. */ buf_xor_n_copy(outbuf, c->u_iv.iv, inbuf, blocksize); outbuf += blocksize; inbuf += blocksize; inbuflen -= blocksize; } } if (inbuflen >= blocksize ) { /* Save the current IV and then encrypt the IV. */ buf_cpy ( c->lastiv, c->u_iv.iv, blocksize); nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; /* XOR the input with the IV and store input into IV */ buf_xor_n_copy(outbuf, c->u_iv.iv, inbuf, blocksize); outbuf += blocksize; inbuf += blocksize; inbuflen -= blocksize; } if (inbuflen) { /* Save the current IV and then encrypt the IV. */ buf_cpy ( c->lastiv, c->u_iv.iv, blocksize ); nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; c->unused = blocksize; /* Apply the XOR. */ c->unused -= inbuflen; buf_xor_n_copy(outbuf, c->u_iv.iv, inbuf, inbuflen); outbuf += inbuflen; inbuf += inbuflen; inbuflen = 0; } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } diff --git a/cipher/cipher-ctr.c b/cipher/cipher-ctr.c index 1e7133c9..4bbfaaeb 100644 --- a/cipher/cipher-ctr.c +++ b/cipher/cipher-ctr.c @@ -1,111 +1,110 @@ /* cipher-ctr.c - Generic CTR mode implementation * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" gcry_err_code_t _gcry_cipher_ctr_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { size_t n; int i; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; unsigned int blocksize = c->spec->blocksize; size_t nblocks; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; burn = 0; /* First process a left over encrypted counter. */ if (c->unused) { gcry_assert (c->unused < blocksize); i = blocksize - c->unused; n = c->unused > inbuflen ? inbuflen : c->unused; buf_xor(outbuf, inbuf, &c->lastiv[i], n); c->unused -= n; inbuf += n; outbuf += n; inbuflen -= n; } /* Use a bulk method if available. */ nblocks = inbuflen / blocksize; if (nblocks && c->bulk.ctr_enc) { c->bulk.ctr_enc (&c->context.c, c->u_ctr.ctr, outbuf, inbuf, nblocks); inbuf += nblocks * blocksize; outbuf += nblocks * blocksize; inbuflen -= nblocks * blocksize; } /* If we don't have a bulk method use the standard method. We also use this method for the a remaining partial block. */ if (inbuflen) { unsigned char tmp[MAX_BLOCKSIZE]; do { nburn = enc_fn (&c->context.c, tmp, c->u_ctr.ctr); burn = nburn > burn ? nburn : burn; for (i = blocksize; i > 0; i--) { c->u_ctr.ctr[i-1]++; if (c->u_ctr.ctr[i-1] != 0) break; } n = blocksize < inbuflen ? blocksize : inbuflen; buf_xor(outbuf, inbuf, tmp, n); inbuflen -= n; outbuf += n; inbuf += n; } while (inbuflen); /* Save the unused bytes of the counter. */ c->unused = blocksize - n; if (c->unused) buf_cpy (c->lastiv+n, tmp+n, c->unused); wipememory (tmp, sizeof tmp); } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } diff --git a/cipher/cipher-gcm.c b/cipher/cipher-gcm.c index cdd35ad8..05347616 100644 --- a/cipher/cipher-gcm.c +++ b/cipher/cipher-gcm.c @@ -1,1180 +1,1179 @@ /* cipher-gcm.c - Generic Galois Counter Mode implementation * Copyright (C) 2013 Dmitry Eremin-Solenikov * Copyright (C) 2013 Jussi Kivilinna * * 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 "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" #ifdef GCM_USE_TABLES static const u16 gcmR[256] = { 0x0000, 0x01c2, 0x0384, 0x0246, 0x0708, 0x06ca, 0x048c, 0x054e, 0x0e10, 0x0fd2, 0x0d94, 0x0c56, 0x0918, 0x08da, 0x0a9c, 0x0b5e, 0x1c20, 0x1de2, 0x1fa4, 0x1e66, 0x1b28, 0x1aea, 0x18ac, 0x196e, 0x1230, 0x13f2, 0x11b4, 0x1076, 0x1538, 0x14fa, 0x16bc, 0x177e, 0x3840, 0x3982, 0x3bc4, 0x3a06, 0x3f48, 0x3e8a, 0x3ccc, 0x3d0e, 0x3650, 0x3792, 0x35d4, 0x3416, 0x3158, 0x309a, 0x32dc, 0x331e, 0x2460, 0x25a2, 0x27e4, 0x2626, 0x2368, 0x22aa, 0x20ec, 0x212e, 0x2a70, 0x2bb2, 0x29f4, 0x2836, 0x2d78, 0x2cba, 0x2efc, 0x2f3e, 0x7080, 0x7142, 0x7304, 0x72c6, 0x7788, 0x764a, 0x740c, 0x75ce, 0x7e90, 0x7f52, 0x7d14, 0x7cd6, 0x7998, 0x785a, 0x7a1c, 0x7bde, 0x6ca0, 0x6d62, 0x6f24, 0x6ee6, 0x6ba8, 0x6a6a, 0x682c, 0x69ee, 0x62b0, 0x6372, 0x6134, 0x60f6, 0x65b8, 0x647a, 0x663c, 0x67fe, 0x48c0, 0x4902, 0x4b44, 0x4a86, 0x4fc8, 0x4e0a, 0x4c4c, 0x4d8e, 0x46d0, 0x4712, 0x4554, 0x4496, 0x41d8, 0x401a, 0x425c, 0x439e, 0x54e0, 0x5522, 0x5764, 0x56a6, 0x53e8, 0x522a, 0x506c, 0x51ae, 0x5af0, 0x5b32, 0x5974, 0x58b6, 0x5df8, 0x5c3a, 0x5e7c, 0x5fbe, 0xe100, 0xe0c2, 0xe284, 0xe346, 0xe608, 0xe7ca, 0xe58c, 0xe44e, 0xef10, 0xeed2, 0xec94, 0xed56, 0xe818, 0xe9da, 0xeb9c, 0xea5e, 0xfd20, 0xfce2, 0xfea4, 0xff66, 0xfa28, 0xfbea, 0xf9ac, 0xf86e, 0xf330, 0xf2f2, 0xf0b4, 0xf176, 0xf438, 0xf5fa, 0xf7bc, 0xf67e, 0xd940, 0xd882, 0xdac4, 0xdb06, 0xde48, 0xdf8a, 0xddcc, 0xdc0e, 0xd750, 0xd692, 0xd4d4, 0xd516, 0xd058, 0xd19a, 0xd3dc, 0xd21e, 0xc560, 0xc4a2, 0xc6e4, 0xc726, 0xc268, 0xc3aa, 0xc1ec, 0xc02e, 0xcb70, 0xcab2, 0xc8f4, 0xc936, 0xcc78, 0xcdba, 0xcffc, 0xce3e, 0x9180, 0x9042, 0x9204, 0x93c6, 0x9688, 0x974a, 0x950c, 0x94ce, 0x9f90, 0x9e52, 0x9c14, 0x9dd6, 0x9898, 0x995a, 0x9b1c, 0x9ade, 0x8da0, 0x8c62, 0x8e24, 0x8fe6, 0x8aa8, 0x8b6a, 0x892c, 0x88ee, 0x83b0, 0x8272, 0x8034, 0x81f6, 0x84b8, 0x857a, 0x873c, 0x86fe, 0xa9c0, 0xa802, 0xaa44, 0xab86, 0xaec8, 0xaf0a, 0xad4c, 0xac8e, 0xa7d0, 0xa612, 0xa454, 0xa596, 0xa0d8, 0xa11a, 0xa35c, 0xa29e, 0xb5e0, 0xb422, 0xb664, 0xb7a6, 0xb2e8, 0xb32a, 0xb16c, 0xb0ae, 0xbbf0, 0xba32, 0xb874, 0xb9b6, 0xbcf8, 0xbd3a, 0xbf7c, 0xbebe, }; #ifdef GCM_TABLES_USE_U64 static void bshift (u64 * b0, u64 * b1) { u64 t[2], mask; t[0] = *b0; t[1] = *b1; mask = t[1] & 1 ? 0xe1 : 0; mask <<= 56; *b1 = (t[1] >> 1) ^ (t[0] << 63); *b0 = (t[0] >> 1) ^ mask; } static void do_fillM (unsigned char *h, u64 *M) { int i, j; M[0 + 0] = 0; M[0 + 16] = 0; M[8 + 0] = buf_get_be64 (h + 0); M[8 + 16] = buf_get_be64 (h + 8); for (i = 4; i > 0; i /= 2) { M[i + 0] = M[2 * i + 0]; M[i + 16] = M[2 * i + 16]; bshift (&M[i], &M[i + 16]); } for (i = 2; i < 16; i *= 2) for (j = 1; j < i; j++) { M[(i + j) + 0] = M[i + 0] ^ M[j + 0]; M[(i + j) + 16] = M[i + 16] ^ M[j + 16]; } } static inline unsigned int do_ghash (unsigned char *result, const unsigned char *buf, const u64 *gcmM) { u64 V[2]; u64 tmp[2]; const u64 *M; u64 T; u32 A; int i; buf_xor (V, result, buf, 16); V[0] = be_bswap64 (V[0]); V[1] = be_bswap64 (V[1]); /* First round can be manually tweaked based on fact that 'tmp' is zero. */ i = 15; M = &gcmM[(V[1] & 0xf)]; V[1] >>= 4; tmp[0] = (M[0] >> 4) ^ ((u64) gcmR[(M[16] & 0xf) << 4] << 48); tmp[1] = (M[16] >> 4) ^ (M[0] << 60); tmp[0] ^= gcmM[(V[1] & 0xf) + 0]; tmp[1] ^= gcmM[(V[1] & 0xf) + 16]; V[1] >>= 4; --i; while (1) { M = &gcmM[(V[1] & 0xf)]; V[1] >>= 4; A = tmp[1] & 0xff; T = tmp[0]; tmp[0] = (T >> 8) ^ ((u64) gcmR[A] << 48) ^ gcmM[(V[1] & 0xf) + 0]; tmp[1] = (T << 56) ^ (tmp[1] >> 8) ^ gcmM[(V[1] & 0xf) + 16]; tmp[0] ^= (M[0] >> 4) ^ ((u64) gcmR[(M[16] & 0xf) << 4] << 48); tmp[1] ^= (M[16] >> 4) ^ (M[0] << 60); if (i == 0) break; else if (i == 8) V[1] = V[0]; else V[1] >>= 4; --i; } buf_put_be64 (result + 0, tmp[0]); buf_put_be64 (result + 8, tmp[1]); return (sizeof(V) + sizeof(T) + sizeof(tmp) + sizeof(int)*2 + sizeof(void*)*5); } #else static void bshift (u32 * M, int i) { u32 t[4], mask; t[0] = M[i * 4 + 0]; t[1] = M[i * 4 + 1]; t[2] = M[i * 4 + 2]; t[3] = M[i * 4 + 3]; mask = t[3] & 1 ? 0xe1 : 0; M[i * 4 + 3] = (t[3] >> 1) ^ (t[2] << 31); M[i * 4 + 2] = (t[2] >> 1) ^ (t[1] << 31); M[i * 4 + 1] = (t[1] >> 1) ^ (t[0] << 31); M[i * 4 + 0] = (t[0] >> 1) ^ (mask << 24); } static void do_fillM (unsigned char *h, u32 *M) { int i, j; M[0 * 4 + 0] = 0; M[0 * 4 + 1] = 0; M[0 * 4 + 2] = 0; M[0 * 4 + 3] = 0; M[8 * 4 + 0] = buf_get_be32 (h + 0); M[8 * 4 + 1] = buf_get_be32 (h + 4); M[8 * 4 + 2] = buf_get_be32 (h + 8); M[8 * 4 + 3] = buf_get_be32 (h + 12); for (i = 4; i > 0; i /= 2) { M[i * 4 + 0] = M[2 * i * 4 + 0]; M[i * 4 + 1] = M[2 * i * 4 + 1]; M[i * 4 + 2] = M[2 * i * 4 + 2]; M[i * 4 + 3] = M[2 * i * 4 + 3]; bshift (M, i); } for (i = 2; i < 16; i *= 2) for (j = 1; j < i; j++) { M[(i + j) * 4 + 0] = M[i * 4 + 0] ^ M[j * 4 + 0]; M[(i + j) * 4 + 1] = M[i * 4 + 1] ^ M[j * 4 + 1]; M[(i + j) * 4 + 2] = M[i * 4 + 2] ^ M[j * 4 + 2]; M[(i + j) * 4 + 3] = M[i * 4 + 3] ^ M[j * 4 + 3]; } } static inline unsigned int do_ghash (unsigned char *result, const unsigned char *buf, const u32 *gcmM) { byte V[16]; u32 tmp[4]; u32 v; const u32 *M, *m; u32 T[3]; int i; buf_xor (V, result, buf, 16); /* V is big-endian */ /* First round can be manually tweaked based on fact that 'tmp' is zero. */ i = 15; v = V[i]; M = &gcmM[(v & 0xf) * 4]; v = (v & 0xf0) >> 4; m = &gcmM[v * 4]; v = V[--i]; tmp[0] = (M[0] >> 4) ^ ((u64) gcmR[(M[3] << 4) & 0xf0] << 16) ^ m[0]; tmp[1] = (M[1] >> 4) ^ (M[0] << 28) ^ m[1]; tmp[2] = (M[2] >> 4) ^ (M[1] << 28) ^ m[2]; tmp[3] = (M[3] >> 4) ^ (M[2] << 28) ^ m[3]; while (1) { M = &gcmM[(v & 0xf) * 4]; v = (v & 0xf0) >> 4; m = &gcmM[v * 4]; T[0] = tmp[0]; T[1] = tmp[1]; T[2] = tmp[2]; tmp[0] = (T[0] >> 8) ^ ((u32) gcmR[tmp[3] & 0xff] << 16) ^ m[0]; tmp[1] = (T[0] << 24) ^ (tmp[1] >> 8) ^ m[1]; tmp[2] = (T[1] << 24) ^ (tmp[2] >> 8) ^ m[2]; tmp[3] = (T[2] << 24) ^ (tmp[3] >> 8) ^ m[3]; tmp[0] ^= (M[0] >> 4) ^ ((u64) gcmR[(M[3] << 4) & 0xf0] << 16); tmp[1] ^= (M[1] >> 4) ^ (M[0] << 28); tmp[2] ^= (M[2] >> 4) ^ (M[1] << 28); tmp[3] ^= (M[3] >> 4) ^ (M[2] << 28); if (i == 0) break; v = V[--i]; } buf_put_be32 (result + 0, tmp[0]); buf_put_be32 (result + 4, tmp[1]); buf_put_be32 (result + 8, tmp[2]); buf_put_be32 (result + 12, tmp[3]); return (sizeof(V) + sizeof(T) + sizeof(tmp) + sizeof(int)*2 + sizeof(void*)*6); } #endif /* !HAVE_U64_TYPEDEF || SIZEOF_UNSIGNED_LONG != 8 */ #define fillM(c, h) do_fillM (h, c->u_mode.gcm.gcm_table) #define GHASH(c, result, buf) do_ghash (result, buf, c->u_mode.gcm.gcm_table) #else static unsigned long bshift (unsigned long *b) { unsigned long c; int i; c = b[3] & 1; for (i = 3; i > 0; i--) { b[i] = (b[i] >> 1) | (b[i - 1] << 31); } b[i] >>= 1; return c; } static unsigned int do_ghash (unsigned char *hsub, unsigned char *result, const unsigned char *buf) { unsigned long V[4]; int i, j; byte *p; #ifdef WORDS_BIGENDIAN p = result; #else unsigned long T[4]; buf_xor (V, result, buf, 16); for (i = 0; i < 4; i++) { V[i] = (V[i] & 0x00ff00ff) << 8 | (V[i] & 0xff00ff00) >> 8; V[i] = (V[i] & 0x0000ffff) << 16 | (V[i] & 0xffff0000) >> 16; } p = (byte *) T; #endif memset (p, 0, 16); for (i = 0; i < 16; i++) { for (j = 0x80; j; j >>= 1) { if (hsub[i] & j) buf_xor (p, p, V, 16); if (bshift (V)) V[0] ^= 0xe1000000; } } #ifndef WORDS_BIGENDIAN for (i = 0, p = (byte *) T; i < 16; i += 4, p += 4) { result[i + 0] = p[3]; result[i + 1] = p[2]; result[i + 2] = p[1]; result[i + 3] = p[0]; } #endif return (sizeof(V) + sizeof(T) + sizeof(int)*2 + sizeof(void*)*5); } #define fillM(c, h) do { } while (0) #define GHASH(c, result, buf) do_ghash (c->u_mode.gcm.u_ghash_key.key, result, buf) #endif /* !GCM_USE_TABLES */ #ifdef GCM_USE_INTEL_PCLMUL /* Intel PCLMUL ghash based on white paper: "Intel® Carry-Less Multiplication Instruction and its Usage for Computing the GCM Mode - Rev 2.01"; Shay Gueron, Michael E. Kounavis. */ static inline void gfmul_pclmul(void) { /* Input: XMM0 and XMM1, Output: XMM1. Input XMM0 stays unmodified. Input must be converted to little-endian. */ asm volatile (/* gfmul, xmm0 has operator a and xmm1 has operator b. */ "pshufd $78, %%xmm0, %%xmm2\n\t" "pshufd $78, %%xmm1, %%xmm4\n\t" "pxor %%xmm0, %%xmm2\n\t" /* xmm2 holds a0+a1 */ "pxor %%xmm1, %%xmm4\n\t" /* xmm4 holds b0+b1 */ "movdqa %%xmm0, %%xmm3\n\t" "pclmulqdq $0, %%xmm1, %%xmm3\n\t" /* xmm3 holds a0*b0 */ "movdqa %%xmm0, %%xmm6\n\t" "pclmulqdq $17, %%xmm1, %%xmm6\n\t" /* xmm6 holds a1*b1 */ "movdqa %%xmm3, %%xmm5\n\t" "pclmulqdq $0, %%xmm2, %%xmm4\n\t" /* xmm4 holds (a0+a1)*(b0+b1) */ "pxor %%xmm6, %%xmm5\n\t" /* xmm5 holds a0*b0+a1*b1 */ "pxor %%xmm5, %%xmm4\n\t" /* xmm4 holds a0*b0+a1*b1+(a0+a1)*(b0+b1) */ "movdqa %%xmm4, %%xmm5\n\t" "psrldq $8, %%xmm4\n\t" "pslldq $8, %%xmm5\n\t" "pxor %%xmm5, %%xmm3\n\t" "pxor %%xmm4, %%xmm6\n\t" /* holds the result of the carry-less multiplication of xmm0 by xmm1 */ /* shift the result by one bit position to the left cope for the fact that bits are reversed */ "movdqa %%xmm3, %%xmm4\n\t" "movdqa %%xmm6, %%xmm5\n\t" "pslld $1, %%xmm3\n\t" "pslld $1, %%xmm6\n\t" "psrld $31, %%xmm4\n\t" "psrld $31, %%xmm5\n\t" "movdqa %%xmm4, %%xmm1\n\t" "pslldq $4, %%xmm5\n\t" "pslldq $4, %%xmm4\n\t" "psrldq $12, %%xmm1\n\t" "por %%xmm4, %%xmm3\n\t" "por %%xmm5, %%xmm6\n\t" "por %%xmm6, %%xmm1\n\t" /* first phase of the reduction */ "movdqa %%xmm3, %%xmm6\n\t" "movdqa %%xmm3, %%xmm7\n\t" "pslld $31, %%xmm6\n\t" /* packed right shifting << 31 */ "movdqa %%xmm3, %%xmm5\n\t" "pslld $30, %%xmm7\n\t" /* packed right shifting shift << 30 */ "pslld $25, %%xmm5\n\t" /* packed right shifting shift << 25 */ "pxor %%xmm7, %%xmm6\n\t" /* xor the shifted versions */ "pxor %%xmm5, %%xmm6\n\t" "movdqa %%xmm6, %%xmm7\n\t" "pslldq $12, %%xmm6\n\t" "psrldq $4, %%xmm7\n\t" "pxor %%xmm6, %%xmm3\n\t" /* first phase of the reduction complete */ /* second phase of the reduction */ "movdqa %%xmm3, %%xmm2\n\t" "movdqa %%xmm3, %%xmm4\n\t" "psrld $1, %%xmm2\n\t" /* packed left shifting >> 1 */ "movdqa %%xmm3, %%xmm5\n\t" "psrld $2, %%xmm4\n\t" /* packed left shifting >> 2 */ "psrld $7, %%xmm5\n\t" /* packed left shifting >> 7 */ "pxor %%xmm4, %%xmm2\n\t" /* xor the shifted versions */ "pxor %%xmm5, %%xmm2\n\t" "pxor %%xmm7, %%xmm2\n\t" "pxor %%xmm2, %%xmm3\n\t" "pxor %%xmm3, %%xmm1\n\t" /* the result is in xmm1 */ ::: "cc" ); } #ifdef __x86_64__ static inline void gfmul_pclmul_aggr4(void) { /* Input: H¹: XMM0 X_i : XMM6 H²: XMM8 X_(i-1) : XMM3 H³: XMM9 X_(i-2) : XMM2 H⁴: XMM10 X_(i-3)⊕Y_(i-4): XMM1 Output: Y_i: XMM1 Inputs XMM0 stays unmodified. Input must be converted to little-endian. */ asm volatile (/* perform clmul and merge results... */ "pshufd $78, %%xmm10, %%xmm11\n\t" "pshufd $78, %%xmm1, %%xmm12\n\t" "pxor %%xmm10, %%xmm11\n\t" /* xmm11 holds 4:a0+a1 */ "pxor %%xmm1, %%xmm12\n\t" /* xmm12 holds 4:b0+b1 */ "pshufd $78, %%xmm9, %%xmm13\n\t" "pshufd $78, %%xmm2, %%xmm14\n\t" "pxor %%xmm9, %%xmm13\n\t" /* xmm13 holds 3:a0+a1 */ "pxor %%xmm2, %%xmm14\n\t" /* xmm14 holds 3:b0+b1 */ "pshufd $78, %%xmm8, %%xmm5\n\t" "pshufd $78, %%xmm3, %%xmm15\n\t" "pxor %%xmm8, %%xmm5\n\t" /* xmm1 holds 2:a0+a1 */ "pxor %%xmm3, %%xmm15\n\t" /* xmm2 holds 2:b0+b1 */ "movdqa %%xmm10, %%xmm4\n\t" "movdqa %%xmm9, %%xmm7\n\t" "pclmulqdq $0, %%xmm1, %%xmm4\n\t" /* xmm4 holds 4:a0*b0 */ "pclmulqdq $0, %%xmm2, %%xmm7\n\t" /* xmm7 holds 3:a0*b0 */ "pclmulqdq $17, %%xmm10, %%xmm1\n\t" /* xmm1 holds 4:a1*b1 */ "pclmulqdq $17, %%xmm9, %%xmm2\n\t" /* xmm9 holds 3:a1*b1 */ "pclmulqdq $0, %%xmm11, %%xmm12\n\t" /* xmm12 holds 4:(a0+a1)*(b0+b1) */ "pclmulqdq $0, %%xmm13, %%xmm14\n\t" /* xmm14 holds 3:(a0+a1)*(b0+b1) */ "pshufd $78, %%xmm0, %%xmm10\n\t" "pshufd $78, %%xmm6, %%xmm11\n\t" "pxor %%xmm0, %%xmm10\n\t" /* xmm10 holds 1:a0+a1 */ "pxor %%xmm6, %%xmm11\n\t" /* xmm11 holds 1:b0+b1 */ "pxor %%xmm4, %%xmm7\n\t" /* xmm7 holds 3+4:a0*b0 */ "pxor %%xmm2, %%xmm1\n\t" /* xmm1 holds 3+4:a1*b1 */ "pxor %%xmm14, %%xmm12\n\t" /* xmm12 holds 3+4:(a0+a1)*(b0+b1) */ "movdqa %%xmm8, %%xmm13\n\t" "pclmulqdq $0, %%xmm3, %%xmm13\n\t" /* xmm13 holds 2:a0*b0 */ "pclmulqdq $17, %%xmm8, %%xmm3\n\t" /* xmm3 holds 2:a1*b1 */ "pclmulqdq $0, %%xmm5, %%xmm15\n\t" /* xmm15 holds 2:(a0+a1)*(b0+b1) */ "pxor %%xmm13, %%xmm7\n\t" /* xmm7 holds 2+3+4:a0*b0 */ "pxor %%xmm3, %%xmm1\n\t" /* xmm1 holds 2+3+4:a1*b1 */ "pxor %%xmm15, %%xmm12\n\t" /* xmm12 holds 2+3+4:(a0+a1)*(b0+b1) */ "movdqa %%xmm0, %%xmm3\n\t" "pclmulqdq $0, %%xmm6, %%xmm3\n\t" /* xmm3 holds 1:a0*b0 */ "pclmulqdq $17, %%xmm0, %%xmm6\n\t" /* xmm6 holds 1:a1*b1 */ "movdqa %%xmm11, %%xmm4\n\t" "pclmulqdq $0, %%xmm10, %%xmm4\n\t" /* xmm4 holds 1:(a0+a1)*(b0+b1) */ "pxor %%xmm7, %%xmm3\n\t" /* xmm3 holds 1+2+3+4:a0*b0 */ "pxor %%xmm1, %%xmm6\n\t" /* xmm6 holds 1+2+3+4:a1*b1 */ "pxor %%xmm12, %%xmm4\n\t" /* xmm4 holds 1+2+3+4:(a0+a1)*(b0+b1) */ /* aggregated reduction... */ "movdqa %%xmm3, %%xmm5\n\t" "pxor %%xmm6, %%xmm5\n\t" /* xmm5 holds a0*b0+a1*b1 */ "pxor %%xmm5, %%xmm4\n\t" /* xmm4 holds a0*b0+a1*b1+(a0+a1)*(b0+b1) */ "movdqa %%xmm4, %%xmm5\n\t" "psrldq $8, %%xmm4\n\t" "pslldq $8, %%xmm5\n\t" "pxor %%xmm5, %%xmm3\n\t" "pxor %%xmm4, %%xmm6\n\t" /* holds the result of the carry-less multiplication of xmm0 by xmm1 */ /* shift the result by one bit position to the left cope for the fact that bits are reversed */ "movdqa %%xmm3, %%xmm4\n\t" "movdqa %%xmm6, %%xmm5\n\t" "pslld $1, %%xmm3\n\t" "pslld $1, %%xmm6\n\t" "psrld $31, %%xmm4\n\t" "psrld $31, %%xmm5\n\t" "movdqa %%xmm4, %%xmm1\n\t" "pslldq $4, %%xmm5\n\t" "pslldq $4, %%xmm4\n\t" "psrldq $12, %%xmm1\n\t" "por %%xmm4, %%xmm3\n\t" "por %%xmm5, %%xmm6\n\t" "por %%xmm6, %%xmm1\n\t" /* first phase of the reduction */ "movdqa %%xmm3, %%xmm6\n\t" "movdqa %%xmm3, %%xmm7\n\t" "pslld $31, %%xmm6\n\t" /* packed right shifting << 31 */ "movdqa %%xmm3, %%xmm5\n\t" "pslld $30, %%xmm7\n\t" /* packed right shifting shift << 30 */ "pslld $25, %%xmm5\n\t" /* packed right shifting shift << 25 */ "pxor %%xmm7, %%xmm6\n\t" /* xor the shifted versions */ "pxor %%xmm5, %%xmm6\n\t" "movdqa %%xmm6, %%xmm7\n\t" "pslldq $12, %%xmm6\n\t" "psrldq $4, %%xmm7\n\t" "pxor %%xmm6, %%xmm3\n\t" /* first phase of the reduction complete */ /* second phase of the reduction */ "movdqa %%xmm3, %%xmm2\n\t" "movdqa %%xmm3, %%xmm4\n\t" "psrld $1, %%xmm2\n\t" /* packed left shifting >> 1 */ "movdqa %%xmm3, %%xmm5\n\t" "psrld $2, %%xmm4\n\t" /* packed left shifting >> 2 */ "psrld $7, %%xmm5\n\t" /* packed left shifting >> 7 */ "pxor %%xmm4, %%xmm2\n\t" /* xor the shifted versions */ "pxor %%xmm5, %%xmm2\n\t" "pxor %%xmm7, %%xmm2\n\t" "pxor %%xmm2, %%xmm3\n\t" "pxor %%xmm3, %%xmm1\n\t" /* the result is in xmm1 */ :::"cc"); } #endif #endif /*GCM_USE_INTEL_PCLMUL*/ static unsigned int ghash (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks) { const unsigned int blocksize = GCRY_GCM_BLOCK_LEN; unsigned int burn; if (nblocks == 0) return 0; if (0) ; #ifdef GCM_USE_INTEL_PCLMUL else if (c->u_mode.gcm.use_intel_pclmul) { static const unsigned char be_mask[16] __attribute__ ((aligned (16))) = { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; /* Preload hash and H1. */ asm volatile ("movdqu %[hash], %%xmm1\n\t" "movdqa %[hsub], %%xmm0\n\t" "pshufb %[be_mask], %%xmm1\n\t" /* be => le */ : : [hash] "m" (*result), [be_mask] "m" (*be_mask), [hsub] "m" (*c->u_mode.gcm.u_ghash_key.key)); #ifdef __x86_64__ if (nblocks >= 4) { do { asm volatile ("movdqa %[be_mask], %%xmm4\n\t" "movdqu 0*16(%[buf]), %%xmm5\n\t" "movdqu 1*16(%[buf]), %%xmm2\n\t" "movdqu 2*16(%[buf]), %%xmm3\n\t" "movdqu 3*16(%[buf]), %%xmm6\n\t" "pshufb %%xmm4, %%xmm5\n\t" /* be => le */ /* Load H2, H3, H4. */ "movdqu 2*16(%[h_234]), %%xmm10\n\t" "movdqu 1*16(%[h_234]), %%xmm9\n\t" "movdqu 0*16(%[h_234]), %%xmm8\n\t" "pxor %%xmm5, %%xmm1\n\t" "pshufb %%xmm4, %%xmm2\n\t" /* be => le */ "pshufb %%xmm4, %%xmm3\n\t" /* be => le */ "pshufb %%xmm4, %%xmm6\n\t" /* be => le */ : : [buf] "r" (buf), [be_mask] "m" (*be_mask), [h_234] "r" (c->u_mode.gcm.gcm_table)); gfmul_pclmul_aggr4 (); buf += 4 * blocksize; nblocks -= 4; } while (nblocks >= 4); /* Clear used x86-64/XMM registers. */ asm volatile( "pxor %%xmm8, %%xmm8\n\t" "pxor %%xmm9, %%xmm9\n\t" "pxor %%xmm10, %%xmm10\n\t" "pxor %%xmm11, %%xmm11\n\t" "pxor %%xmm12, %%xmm12\n\t" "pxor %%xmm13, %%xmm13\n\t" "pxor %%xmm14, %%xmm14\n\t" "pxor %%xmm15, %%xmm15\n\t" ::: "cc" ); } #endif while (nblocks--) { asm volatile ("movdqu %[buf], %%xmm2\n\t" "pshufb %[be_mask], %%xmm2\n\t" /* be => le */ "pxor %%xmm2, %%xmm1\n\t" : : [buf] "m" (*buf), [be_mask] "m" (*be_mask)); gfmul_pclmul (); buf += blocksize; } /* Store hash. */ asm volatile ("pshufb %[be_mask], %%xmm1\n\t" /* be => le */ "movdqu %%xmm1, %[hash]\n\t" : [hash] "=m" (*result) : [be_mask] "m" (*be_mask)); /* Clear used registers. */ asm volatile( "pxor %%xmm0, %%xmm0\n\t" "pxor %%xmm1, %%xmm1\n\t" "pxor %%xmm2, %%xmm2\n\t" "pxor %%xmm3, %%xmm3\n\t" "pxor %%xmm4, %%xmm4\n\t" "pxor %%xmm5, %%xmm5\n\t" "pxor %%xmm6, %%xmm6\n\t" "pxor %%xmm7, %%xmm7\n\t" ::: "cc" ); burn = 0; } #endif else { while (nblocks) { burn = GHASH (c, result, buf); buf += blocksize; nblocks--; } } return burn + (burn ? 5*sizeof(void*) : 0); } static void setupM (gcry_cipher_hd_t c, byte *h) { if (0) ; #ifdef GCM_USE_INTEL_PCLMUL else if (_gcry_get_hw_features () & HWF_INTEL_PCLMUL) { u64 tmp[2]; c->u_mode.gcm.use_intel_pclmul = 1; /* Swap endianness of hsub. */ tmp[0] = buf_get_be64(c->u_mode.gcm.u_ghash_key.key + 8); tmp[1] = buf_get_be64(c->u_mode.gcm.u_ghash_key.key + 0); buf_cpy (c->u_mode.gcm.u_ghash_key.key, tmp, GCRY_GCM_BLOCK_LEN); #ifdef __x86_64__ asm volatile ("movdqu %[h_1], %%xmm0\n\t" "movdqa %%xmm0, %%xmm1\n\t" : : [h_1] "m" (*tmp)); gfmul_pclmul (); /* H•H => H² */ asm volatile ("movdqu %%xmm1, 0*16(%[h_234])\n\t" "movdqa %%xmm1, %%xmm8\n\t" : : [h_234] "r" (c->u_mode.gcm.gcm_table) : "memory"); gfmul_pclmul (); /* H•H² => H³ */ asm volatile ("movdqa %%xmm8, %%xmm0\n\t" "movdqu %%xmm1, 1*16(%[h_234])\n\t" "movdqa %%xmm8, %%xmm1\n\t" : : [h_234] "r" (c->u_mode.gcm.gcm_table) : "memory"); gfmul_pclmul (); /* H²•H² => H⁴ */ asm volatile ("movdqu %%xmm1, 2*16(%[h_234])\n\t" : : [h_234] "r" (c->u_mode.gcm.gcm_table) : "memory"); /* Clear used registers. */ asm volatile( "pxor %%xmm0, %%xmm0\n\t" "pxor %%xmm1, %%xmm1\n\t" "pxor %%xmm2, %%xmm2\n\t" "pxor %%xmm3, %%xmm3\n\t" "pxor %%xmm4, %%xmm4\n\t" "pxor %%xmm5, %%xmm5\n\t" "pxor %%xmm6, %%xmm6\n\t" "pxor %%xmm7, %%xmm7\n\t" "pxor %%xmm8, %%xmm8\n\t" ::: "cc" ); #endif wipememory (tmp, sizeof(tmp)); } #endif else fillM (c, h); } static inline void gcm_bytecounter_add (u32 ctr[2], size_t add) { if (sizeof(add) > sizeof(u32)) { u32 high_add = ((add >> 31) >> 1) & 0xffffffff; ctr[1] += high_add; } ctr[0] += add; if (ctr[0] >= add) return; ++ctr[1]; } static inline u32 gcm_add32_be128 (byte *ctr, unsigned int add) { /* 'ctr' must be aligned to four bytes. */ const unsigned int blocksize = GCRY_GCM_BLOCK_LEN; u32 *pval = (u32 *)(void *)(ctr + blocksize - sizeof(u32)); u32 val; val = be_bswap32(*pval) + add; *pval = be_bswap32(val); return val; /* return result as host-endian value */ } static inline int gcm_check_datalen (u32 ctr[2]) { /* len(plaintext) <= 2^39-256 bits == 2^36-32 bytes == 2^32-2 blocks */ if (ctr[1] > 0xfU) return 0; if (ctr[1] < 0xfU) return 1; if (ctr[0] <= 0xffffffe0U) return 1; return 0; } static inline int gcm_check_aadlen_or_ivlen (u32 ctr[2]) { /* len(aad/iv) <= 2^64-1 bits ~= 2^61-1 bytes */ if (ctr[1] > 0x1fffffffU) return 0; if (ctr[1] < 0x1fffffffU) return 1; if (ctr[0] <= 0xffffffffU) return 1; return 0; } static void do_ghash_buf(gcry_cipher_hd_t c, byte *hash, const byte *buf, size_t buflen, int do_padding) { unsigned int blocksize = GCRY_GCM_BLOCK_LEN; unsigned int unused = c->u_mode.gcm.mac_unused; size_t nblocks, n; unsigned int burn = 0; if (buflen == 0 && (unused == 0 || !do_padding)) return; do { if (buflen + unused < blocksize || unused > 0) { n = blocksize - unused; n = n < buflen ? n : buflen; buf_cpy (&c->u_mode.gcm.macbuf[unused], buf, n); unused += n; buf += n; buflen -= n; } if (!buflen) { if (!do_padding) break; while (unused < blocksize) c->u_mode.gcm.macbuf[unused++] = 0; } if (unused > 0) { gcry_assert (unused == blocksize); /* Process one block from macbuf. */ burn = ghash (c, hash, c->u_mode.gcm.macbuf, 1); unused = 0; } nblocks = buflen / blocksize; if (nblocks) { burn = ghash (c, hash, buf, nblocks); buf += blocksize * nblocks; buflen -= blocksize * nblocks; } } while (buflen > 0); c->u_mode.gcm.mac_unused = unused; if (burn) _gcry_burn_stack (burn); } gcry_err_code_t _gcry_cipher_gcm_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; gcry_err_code_t err; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_data_finalized) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); if (c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode) return GPG_ERR_INV_STATE; if (!c->u_mode.gcm.ghash_aad_finalized) { /* Start of encryption marks end of AAD stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; } gcm_bytecounter_add(c->u_mode.gcm.datalen, inbuflen); if (!gcm_check_datalen(c->u_mode.gcm.datalen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } err = _gcry_cipher_ctr_encrypt(c, outbuf, outbuflen, inbuf, inbuflen); if (err != 0) return err; do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, outbuf, inbuflen, 0); return 0; } gcry_err_code_t _gcry_cipher_gcm_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_data_finalized) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); if (!c->u_mode.gcm.ghash_aad_finalized) { /* Start of decryption marks end of AAD stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; } gcm_bytecounter_add(c->u_mode.gcm.datalen, inbuflen); if (!gcm_check_datalen(c->u_mode.gcm.datalen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, inbuf, inbuflen, 0); return _gcry_cipher_ctr_encrypt(c, outbuf, outbuflen, inbuf, inbuflen); } gcry_err_code_t _gcry_cipher_gcm_authenticate (gcry_cipher_hd_t c, const byte * aadbuf, size_t aadbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_aad_finalized || c->u_mode.gcm.ghash_data_finalized) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); gcm_bytecounter_add(c->u_mode.gcm.aadlen, aadbuflen); if (!gcm_check_aadlen_or_ivlen(c->u_mode.gcm.aadlen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, aadbuf, aadbuflen, 0); return 0; } void _gcry_cipher_gcm_setkey (gcry_cipher_hd_t c) { memset (c->u_mode.gcm.u_ghash_key.key, 0, GCRY_GCM_BLOCK_LEN); c->spec->encrypt (&c->context.c, c->u_mode.gcm.u_ghash_key.key, c->u_mode.gcm.u_ghash_key.key); setupM (c, c->u_mode.gcm.u_ghash_key.key); } static gcry_err_code_t _gcry_cipher_gcm_initiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { memset (c->u_mode.gcm.aadlen, 0, sizeof(c->u_mode.gcm.aadlen)); memset (c->u_mode.gcm.datalen, 0, sizeof(c->u_mode.gcm.datalen)); memset (c->u_mode.gcm.u_tag.tag, 0, GCRY_GCM_BLOCK_LEN); c->u_mode.gcm.datalen_over_limits = 0; c->u_mode.gcm.ghash_data_finalized = 0; c->u_mode.gcm.ghash_aad_finalized = 0; if (ivlen == 0) return GPG_ERR_INV_LENGTH; if (ivlen != GCRY_GCM_BLOCK_LEN - 4) { u32 iv_bytes[2] = {0, 0}; u32 bitlengths[2][2]; memset(c->u_ctr.ctr, 0, GCRY_GCM_BLOCK_LEN); gcm_bytecounter_add(iv_bytes, ivlen); if (!gcm_check_aadlen_or_ivlen(iv_bytes)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } do_ghash_buf(c, c->u_ctr.ctr, iv, ivlen, 1); /* iv length, 64-bit */ bitlengths[1][1] = be_bswap32(iv_bytes[0] << 3); bitlengths[1][0] = be_bswap32((iv_bytes[0] >> 29) | (iv_bytes[1] << 3)); /* zeros, 64-bit */ bitlengths[0][1] = 0; bitlengths[0][0] = 0; do_ghash_buf(c, c->u_ctr.ctr, (byte*)bitlengths, GCRY_GCM_BLOCK_LEN, 1); wipememory (iv_bytes, sizeof iv_bytes); wipememory (bitlengths, sizeof bitlengths); } else { /* 96-bit IV is handled differently. */ memcpy (c->u_ctr.ctr, iv, ivlen); c->u_ctr.ctr[12] = c->u_ctr.ctr[13] = c->u_ctr.ctr[14] = 0; c->u_ctr.ctr[15] = 1; } c->spec->encrypt (&c->context.c, c->u_mode.gcm.tagiv, c->u_ctr.ctr); gcm_add32_be128 (c->u_ctr.ctr, 1); c->unused = 0; c->marks.iv = 1; c->marks.tag = 0; return 0; } gcry_err_code_t _gcry_cipher_gcm_setiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { c->marks.iv = 0; c->marks.tag = 0; c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 0; if (fips_mode ()) { /* Direct invocation of GCM setiv in FIPS mode disables encryption. */ c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 1; } return _gcry_cipher_gcm_initiv (c, iv, ivlen); } #if 0 && TODO void _gcry_cipher_gcm_geniv (gcry_cipher_hd_t c, byte *ivout, size_t ivoutlen, const byte *nonce, size_t noncelen) { /* nonce: user provided part (might be null) */ /* noncelen: check if proper length (if nonce not null) */ /* ivout: iv used to initialize gcm, output to user */ /* ivoutlen: check correct size */ byte iv[IVLEN]; if (!ivout) return GPG_ERR_INV_ARG; if (ivoutlen != IVLEN) return GPG_ERR_INV_LENGTH; if (nonce != NULL && !is_nonce_ok_len(noncelen)) return GPG_ERR_INV_ARG; gcm_generate_iv(iv, nonce, noncelen); c->marks.iv = 0; c->marks.tag = 0; c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 0; _gcry_cipher_gcm_initiv (c, iv, IVLEN); buf_cpy(ivout, iv, IVLEN); wipememory(iv, sizeof(iv)); } #endif static gcry_err_code_t _gcry_cipher_gcm_tag (gcry_cipher_hd_t c, byte * outbuf, size_t outbuflen, int check) { if (outbuflen < GCRY_GCM_BLOCK_LEN) return GPG_ERR_BUFFER_TOO_SHORT; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (!c->marks.tag) { u32 bitlengths[2][2]; /* aad length */ bitlengths[0][1] = be_bswap32(c->u_mode.gcm.aadlen[0] << 3); bitlengths[0][0] = be_bswap32((c->u_mode.gcm.aadlen[0] >> 29) | (c->u_mode.gcm.aadlen[1] << 3)); /* data length */ bitlengths[1][1] = be_bswap32(c->u_mode.gcm.datalen[0] << 3); bitlengths[1][0] = be_bswap32((c->u_mode.gcm.datalen[0] >> 29) | (c->u_mode.gcm.datalen[1] << 3)); /* Finalize data-stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; c->u_mode.gcm.ghash_data_finalized = 1; /* Add bitlengths to tag. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, (byte*)bitlengths, GCRY_GCM_BLOCK_LEN, 1); buf_xor (c->u_mode.gcm.u_tag.tag, c->u_mode.gcm.tagiv, c->u_mode.gcm.u_tag.tag, GCRY_GCM_BLOCK_LEN); c->marks.tag = 1; wipememory (bitlengths, sizeof (bitlengths)); wipememory (c->u_mode.gcm.macbuf, GCRY_GCM_BLOCK_LEN); wipememory (c->u_mode.gcm.tagiv, GCRY_GCM_BLOCK_LEN); wipememory (c->u_mode.gcm.aadlen, sizeof (c->u_mode.gcm.aadlen)); wipememory (c->u_mode.gcm.datalen, sizeof (c->u_mode.gcm.datalen)); } if (!check) { memcpy (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen); return GPG_ERR_NO_ERROR; } else { return buf_eq_const(outbuf, c->u_mode.gcm.u_tag.tag, outbuflen) ? GPG_ERR_NO_ERROR : GPG_ERR_CHECKSUM; } return 0; } gcry_err_code_t _gcry_cipher_gcm_get_tag (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen) { /* Outputting authentication tag is part of encryption. */ if (c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode) return GPG_ERR_INV_STATE; return _gcry_cipher_gcm_tag (c, outtag, taglen, 0); } gcry_err_code_t _gcry_cipher_gcm_check_tag (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen) { return _gcry_cipher_gcm_tag (c, (unsigned char *) intag, taglen, 1); } diff --git a/cipher/cipher-ofb.c b/cipher/cipher-ofb.c index 3842774f..7db76580 100644 --- a/cipher/cipher-ofb.c +++ b/cipher/cipher-ofb.c @@ -1,96 +1,95 @@ /* cipher-ofb.c - Generic OFB mode implementation * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "bufhelp.h" #include "./cipher-internal.h" gcry_err_code_t _gcry_cipher_ofb_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { unsigned char *ivp; gcry_cipher_encrypt_t enc_fn = c->spec->encrypt; size_t blocksize = c->spec->blocksize; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if ( inbuflen <= c->unused ) { /* Short enough to be encoded by the remaining XOR mask. */ /* XOR the input with the IV */ ivp = c->u_iv.iv + blocksize - c->unused; buf_xor(outbuf, ivp, inbuf, inbuflen); c->unused -= inbuflen; return 0; } burn = 0; if( c->unused ) { inbuflen -= c->unused; ivp = c->u_iv.iv + blocksize - c->unused; buf_xor(outbuf, ivp, inbuf, c->unused); outbuf += c->unused; inbuf += c->unused; c->unused = 0; } /* Now we can process complete blocks. */ while ( inbuflen >= blocksize ) { /* Encrypt the IV (and save the current one). */ nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; buf_xor(outbuf, c->u_iv.iv, inbuf, blocksize); outbuf += blocksize; inbuf += blocksize; inbuflen -= blocksize; } if ( inbuflen ) { /* process the remaining bytes */ nburn = enc_fn ( &c->context.c, c->u_iv.iv, c->u_iv.iv ); burn = nburn > burn ? nburn : burn; c->unused = blocksize; c->unused -= inbuflen; buf_xor(outbuf, c->u_iv.iv, inbuf, inbuflen); outbuf += inbuflen; inbuf += inbuflen; inbuflen = 0; } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } diff --git a/cipher/cipher.c b/cipher/cipher.c index 8c5a0b4e..baa4720a 100644 --- a/cipher/cipher.c +++ b/cipher/cipher.c @@ -1,1393 +1,1392 @@ /* cipher.c - cipher dispatcher * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 Free Software Foundation, Inc. * Copyright (C) 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "./cipher-internal.h" /* This is the list of the default ciphers, which are included in libgcrypt. */ static gcry_cipher_spec_t *cipher_list[] = { #if USE_BLOWFISH &_gcry_cipher_spec_blowfish, #endif #if USE_DES &_gcry_cipher_spec_des, &_gcry_cipher_spec_tripledes, #endif #if USE_ARCFOUR &_gcry_cipher_spec_arcfour, #endif #if USE_CAST5 &_gcry_cipher_spec_cast5, #endif #if USE_AES &_gcry_cipher_spec_aes, &_gcry_cipher_spec_aes192, &_gcry_cipher_spec_aes256, #endif #if USE_TWOFISH &_gcry_cipher_spec_twofish, &_gcry_cipher_spec_twofish128, #endif #if USE_SERPENT &_gcry_cipher_spec_serpent128, &_gcry_cipher_spec_serpent192, &_gcry_cipher_spec_serpent256, #endif #if USE_RFC2268 &_gcry_cipher_spec_rfc2268_40, &_gcry_cipher_spec_rfc2268_128, #endif #if USE_SEED &_gcry_cipher_spec_seed, #endif #if USE_CAMELLIA &_gcry_cipher_spec_camellia128, &_gcry_cipher_spec_camellia192, &_gcry_cipher_spec_camellia256, #endif #ifdef USE_IDEA &_gcry_cipher_spec_idea, #endif #if USE_SALSA20 &_gcry_cipher_spec_salsa20, &_gcry_cipher_spec_salsa20r12, #endif #if USE_GOST28147 &_gcry_cipher_spec_gost28147, #endif NULL }; static int map_algo (int algo) { return algo; } /* Return the spec structure for the cipher algorithm ALGO. For an unknown algorithm NULL is returned. */ static gcry_cipher_spec_t * spec_from_algo (int algo) { int idx; gcry_cipher_spec_t *spec; algo = map_algo (algo); for (idx = 0; (spec = cipher_list[idx]); idx++) if (algo == spec->algo) return spec; return NULL; } /* Lookup a cipher's spec by its name. */ static gcry_cipher_spec_t * spec_from_name (const char *name) { gcry_cipher_spec_t *spec; int idx; const char **aliases; for (idx=0; (spec = cipher_list[idx]); idx++) { if (!stricmp (name, spec->name)) return spec; if (spec->aliases) { for (aliases = spec->aliases; *aliases; aliases++) if (!stricmp (name, *aliases)) return spec; } } return NULL; } /* Lookup a cipher's spec by its OID. */ static gcry_cipher_spec_t * spec_from_oid (const char *oid) { gcry_cipher_spec_t *spec; gcry_cipher_oid_spec_t *oid_specs; int idx, j; for (idx=0; (spec = cipher_list[idx]); idx++) { oid_specs = spec->oids; if (oid_specs) { for (j = 0; oid_specs[j].oid; j++) if (!stricmp (oid, oid_specs[j].oid)) return spec; } } return NULL; } /* Locate the OID in the oid table and return the spec or NULL if not found. An optional "oid." or "OID." prefix in OID is ignored, the OID is expected to be in standard IETF dotted notation. A pointer to the OID specification of the module implementing this algorithm is return in OID_SPEC unless passed as NULL.*/ static gcry_cipher_spec_t * search_oid (const char *oid, gcry_cipher_oid_spec_t *oid_spec) { gcry_cipher_spec_t *spec; int i; if (oid && ((! strncmp (oid, "oid.", 4)) || (! strncmp (oid, "OID.", 4)))) oid += 4; spec = spec_from_oid (oid); if (spec && spec->oids) { for (i = 0; spec->oids[i].oid; i++) if (!stricmp (oid, spec->oids[i].oid)) { if (oid_spec) *oid_spec = spec->oids[i]; return spec; } } return NULL; } /* Map STRING to the cipher algorithm identifier. Returns the algorithm ID of the cipher for the given name or 0 if the name is not known. It is valid to pass NULL for STRING which results in a return value of 0. */ int _gcry_cipher_map_name (const char *string) { gcry_cipher_spec_t *spec; if (!string) return 0; /* If the string starts with a digit (optionally prefixed with either "OID." or "oid."), we first look into our table of ASN.1 object identifiers to figure out the algorithm */ spec = search_oid (string, NULL); if (spec) return spec->algo; spec = spec_from_name (string); if (spec) return spec->algo; return 0; } /* Given a STRING with an OID in dotted decimal notation, this function returns the cipher mode (GCRY_CIPHER_MODE_*) associated with that OID or 0 if no mode is known. Passing NULL for string yields a return value of 0. */ int _gcry_cipher_mode_from_oid (const char *string) { gcry_cipher_spec_t *spec; gcry_cipher_oid_spec_t oid_spec; if (!string) return 0; spec = search_oid (string, &oid_spec); if (spec) return oid_spec.mode; return 0; } /* Map the cipher algorithm identifier ALGORITHM to a string representing this algorithm. This string is the default name as used by Libgcrypt. A "?" is returned for an unknown algorithm. NULL is never returned. */ const char * _gcry_cipher_algo_name (int algorithm) { gcry_cipher_spec_t *spec; spec = spec_from_algo (algorithm); return spec? spec->name : "?"; } /* Flag the cipher algorithm with the identifier ALGORITHM as disabled. There is no error return, the function does nothing for unknown algorithms. Disabled algorithms are virtually not available in Libgcrypt. This is not thread safe and should thus be called early. */ static void disable_cipher_algo (int algo) { gcry_cipher_spec_t *spec = spec_from_algo (algo); if (spec) spec->flags.disabled = 1; } /* Return 0 if the cipher algorithm with identifier ALGORITHM is available. Returns a basic error code value if it is not available. */ static gcry_err_code_t check_cipher_algo (int algorithm) { gcry_cipher_spec_t *spec; spec = spec_from_algo (algorithm); if (spec && !spec->flags.disabled) return 0; return GPG_ERR_CIPHER_ALGO; } /* Return the standard length in bits of the key for the cipher algorithm with the identifier ALGORITHM. */ static unsigned int cipher_get_keylen (int algorithm) { gcry_cipher_spec_t *spec; unsigned len = 0; spec = spec_from_algo (algorithm); if (spec) { len = spec->keylen; if (!len) log_bug ("cipher %d w/o key length\n", algorithm); } return len; } /* Return the block length of the cipher algorithm with the identifier ALGORITHM. This function return 0 for an invalid algorithm. */ static unsigned int cipher_get_blocksize (int algorithm) { gcry_cipher_spec_t *spec; unsigned len = 0; spec = spec_from_algo (algorithm); if (spec) { len = spec->blocksize; if (!len) log_bug ("cipher %d w/o blocksize\n", algorithm); } return len; } /* Open a cipher handle for use with cipher algorithm ALGORITHM, using the cipher mode MODE (one of the GCRY_CIPHER_MODE_*) and return a handle in HANDLE. Put NULL into HANDLE and return an error code if something goes wrong. FLAGS may be used to modify the operation. The defined flags are: GCRY_CIPHER_SECURE: allocate all internal buffers in secure memory. GCRY_CIPHER_ENABLE_SYNC: Enable the sync operation as used in OpenPGP. GCRY_CIPHER_CBC_CTS: Enable CTS mode. GCRY_CIPHER_CBC_MAC: Enable MAC mode. Values for these flags may be combined using OR. */ gcry_err_code_t _gcry_cipher_open (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags) { gcry_err_code_t rc; gcry_cipher_hd_t h = NULL; if (mode >= GCRY_CIPHER_MODE_INTERNAL) rc = GPG_ERR_INV_CIPHER_MODE; else rc = _gcry_cipher_open_internal (&h, algo, mode, flags); *handle = rc ? NULL : h; return rc; } gcry_err_code_t _gcry_cipher_open_internal (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags) { int secure = (flags & GCRY_CIPHER_SECURE); gcry_cipher_spec_t *spec; gcry_cipher_hd_t h = NULL; gcry_err_code_t err; /* If the application missed to call the random poll function, we do it here to ensure that it is used once in a while. */ _gcry_fast_random_poll (); spec = spec_from_algo (algo); if (!spec) err = GPG_ERR_CIPHER_ALGO; else if (spec->flags.disabled) err = GPG_ERR_CIPHER_ALGO; else err = 0; /* check flags */ if ((! err) && ((flags & ~(0 | GCRY_CIPHER_SECURE | GCRY_CIPHER_ENABLE_SYNC | GCRY_CIPHER_CBC_CTS | GCRY_CIPHER_CBC_MAC)) || (flags & GCRY_CIPHER_CBC_CTS & GCRY_CIPHER_CBC_MAC))) err = GPG_ERR_CIPHER_ALGO; /* check that a valid mode has been requested */ if (! err) switch (mode) { case GCRY_CIPHER_MODE_CCM: #ifdef HAVE_U64_TYPEDEF if (spec->blocksize != GCRY_CCM_BLOCK_LEN) err = GPG_ERR_INV_CIPHER_MODE; if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; break; #else err = GPG_ERR_NOT_SUPPORTED; #endif case GCRY_CIPHER_MODE_ECB: case GCRY_CIPHER_MODE_CBC: case GCRY_CIPHER_MODE_CFB: case GCRY_CIPHER_MODE_OFB: case GCRY_CIPHER_MODE_CTR: case GCRY_CIPHER_MODE_AESWRAP: case GCRY_CIPHER_MODE_CMAC: case GCRY_CIPHER_MODE_GCM: if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_STREAM: if (!spec->stencrypt || !spec->stdecrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_NONE: /* This mode may be used for debugging. It copies the main text verbatim to the ciphertext. We do not allow this in fips mode or if no debug flag has been set. */ if (fips_mode () || !_gcry_get_debug_flag (0)) err = GPG_ERR_INV_CIPHER_MODE; break; default: err = GPG_ERR_INV_CIPHER_MODE; } /* Perform selftest here and mark this with a flag in cipher_table? No, we should not do this as it takes too long. Further it does not make sense to exclude algorithms with failing selftests at runtime: If a selftest fails there is something seriously wrong with the system and thus we better die immediately. */ if (! err) { size_t size = (sizeof (*h) + 2 * spec->contextsize - sizeof (cipher_context_alignment_t) #ifdef NEED_16BYTE_ALIGNED_CONTEXT + 15 /* Space for leading alignment gap. */ #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/ ); if (secure) h = xtrycalloc_secure (1, size); else h = xtrycalloc (1, size); if (! h) err = gpg_err_code_from_syserror (); else { size_t off = 0; #ifdef NEED_16BYTE_ALIGNED_CONTEXT if ( ((unsigned long)h & 0x0f) ) { /* The malloced block is not aligned on a 16 byte boundary. Correct for this. */ off = 16 - ((unsigned long)h & 0x0f); h = (void*)((char*)h + off); } #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/ h->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL; h->actual_handle_size = size - off; h->handle_offset = off; h->spec = spec; h->algo = algo; h->mode = mode; h->flags = flags; /* Setup bulk encryption routines. */ switch (algo) { #ifdef USE_AES case GCRY_CIPHER_AES128: case GCRY_CIPHER_AES192: case GCRY_CIPHER_AES256: h->bulk.cfb_enc = _gcry_aes_cfb_enc; h->bulk.cfb_dec = _gcry_aes_cfb_dec; h->bulk.cbc_enc = _gcry_aes_cbc_enc; h->bulk.cbc_dec = _gcry_aes_cbc_dec; h->bulk.ctr_enc = _gcry_aes_ctr_enc; break; #endif /*USE_AES*/ #ifdef USE_BLOWFISH case GCRY_CIPHER_BLOWFISH: h->bulk.cfb_dec = _gcry_blowfish_cfb_dec; h->bulk.cbc_dec = _gcry_blowfish_cbc_dec; h->bulk.ctr_enc = _gcry_blowfish_ctr_enc; break; #endif /*USE_BLOWFISH*/ #ifdef USE_CAST5 case GCRY_CIPHER_CAST5: h->bulk.cfb_dec = _gcry_cast5_cfb_dec; h->bulk.cbc_dec = _gcry_cast5_cbc_dec; h->bulk.ctr_enc = _gcry_cast5_ctr_enc; break; #endif /*USE_CAMELLIA*/ #ifdef USE_CAMELLIA case GCRY_CIPHER_CAMELLIA128: case GCRY_CIPHER_CAMELLIA192: case GCRY_CIPHER_CAMELLIA256: h->bulk.cbc_dec = _gcry_camellia_cbc_dec; h->bulk.cfb_dec = _gcry_camellia_cfb_dec; h->bulk.ctr_enc = _gcry_camellia_ctr_enc; break; #endif /*USE_CAMELLIA*/ #ifdef USE_SERPENT case GCRY_CIPHER_SERPENT128: case GCRY_CIPHER_SERPENT192: case GCRY_CIPHER_SERPENT256: h->bulk.cbc_dec = _gcry_serpent_cbc_dec; h->bulk.cfb_dec = _gcry_serpent_cfb_dec; h->bulk.ctr_enc = _gcry_serpent_ctr_enc; break; #endif /*USE_SERPENT*/ #ifdef USE_TWOFISH case GCRY_CIPHER_TWOFISH: case GCRY_CIPHER_TWOFISH128: h->bulk.cbc_dec = _gcry_twofish_cbc_dec; h->bulk.cfb_dec = _gcry_twofish_cfb_dec; h->bulk.ctr_enc = _gcry_twofish_ctr_enc; break; #endif /*USE_TWOFISH*/ default: break; } } } /* Done. */ *handle = err ? NULL : h; return gcry_error (err); } /* Release all resources associated with the cipher handle H. H may be NULL in which case this is a no-operation. */ void _gcry_cipher_close (gcry_cipher_hd_t h) { size_t off; if (!h) return; if ((h->magic != CTX_MAGIC_SECURE) && (h->magic != CTX_MAGIC_NORMAL)) _gcry_fatal_error(GPG_ERR_INTERNAL, "gcry_cipher_close: already closed/invalid handle"); else h->magic = 0; /* We always want to wipe out the memory even when the context has been allocated in secure memory. The user might have disabled secure memory or is using his own implementation which does not do the wiping. To accomplish this we need to keep track of the actual size of this structure because we have no way to known how large the allocated area was when using a standard malloc. */ off = h->handle_offset; wipememory (h, h->actual_handle_size); xfree ((char*)h - off); } /* Set the key to be used for the encryption context C to KEY with length KEYLEN. The length should match the required length. */ static gcry_err_code_t cipher_setkey (gcry_cipher_hd_t c, byte *key, size_t keylen) { gcry_err_code_t rc; rc = c->spec->setkey (&c->context.c, key, keylen); if (!rc) { /* Duplicate initial context. */ memcpy ((void *) ((char *) &c->context.c + c->spec->contextsize), (void *) &c->context.c, c->spec->contextsize); c->marks.key = 1; switch (c->mode) { case GCRY_CIPHER_MODE_CMAC: _gcry_cipher_cmac_set_subkeys (c); break; case GCRY_CIPHER_MODE_GCM: _gcry_cipher_gcm_setkey (c); break; default: break; }; } else c->marks.key = 0; return rc; } /* Set the IV to be used for the encryption context C to IV with length IVLEN. The length should match the required length. */ static gcry_err_code_t cipher_setiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { /* GCM has its own IV handler */ if (c->mode == GCRY_CIPHER_MODE_GCM) return _gcry_cipher_gcm_setiv (c, iv, ivlen); /* If the cipher has its own IV handler, we use only this one. This is currently used for stream ciphers requiring a nonce. */ if (c->spec->setiv) { c->spec->setiv (&c->context.c, iv, ivlen); return 0; } memset (c->u_iv.iv, 0, c->spec->blocksize); if (iv) { if (ivlen != c->spec->blocksize) { log_info ("WARNING: cipher_setiv: ivlen=%u blklen=%u\n", (unsigned int)ivlen, (unsigned int)c->spec->blocksize); fips_signal_error ("IV length does not match blocklength"); } if (ivlen > c->spec->blocksize) ivlen = c->spec->blocksize; memcpy (c->u_iv.iv, iv, ivlen); c->marks.iv = 1; } else c->marks.iv = 0; c->unused = 0; return 0; } /* Reset the cipher context to the initial context. This is basically the same as an release followed by a new. */ static void cipher_reset (gcry_cipher_hd_t c) { unsigned int marks_key; marks_key = c->marks.key; memcpy (&c->context.c, (char *) &c->context.c + c->spec->contextsize, c->spec->contextsize); memset (&c->marks, 0, sizeof c->marks); memset (c->u_iv.iv, 0, c->spec->blocksize); memset (c->lastiv, 0, c->spec->blocksize); memset (c->u_ctr.ctr, 0, c->spec->blocksize); c->unused = 0; c->marks.key = marks_key; switch (c->mode) { case GCRY_CIPHER_MODE_CMAC: /* Only clear 'tag' for cmac, keep subkeys. */ c->u_mode.cmac.tag = 0; break; case GCRY_CIPHER_MODE_GCM: /* Only clear head of u_mode, keep ghash_key and gcm_table. */ { byte *u_mode_pos = (void *)&c->u_mode; byte *ghash_key_pos = c->u_mode.gcm.u_ghash_key.key; size_t u_mode_head_length = ghash_key_pos - u_mode_pos; memset (&c->u_mode, 0, u_mode_head_length); } break; #ifdef HAVE_U64_TYPEDEF case GCRY_CIPHER_MODE_CCM: memset (&c->u_mode.ccm, 0, sizeof c->u_mode.ccm); break; #endif default: break; /* u_mode unused by other modes. */ } } static gcry_err_code_t do_ecb_crypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen, gcry_cipher_encrypt_t crypt_fn) { unsigned int blocksize = c->spec->blocksize; size_t n, nblocks; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if ((inbuflen % blocksize)) return GPG_ERR_INV_LENGTH; nblocks = inbuflen / blocksize; burn = 0; for (n=0; n < nblocks; n++ ) { nburn = crypt_fn (&c->context.c, outbuf, inbuf); burn = nburn > burn ? nburn : burn; inbuf += blocksize; outbuf += blocksize; } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } static gcry_err_code_t do_ecb_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->encrypt); } static gcry_err_code_t do_ecb_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->decrypt); } /**************** * Encrypt INBUF to OUTBUF with the mode selected at open. * inbuf and outbuf may overlap or be the same. * Depending on the mode some constraints apply to INBUFLEN. */ static gcry_err_code_t cipher_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { gcry_err_code_t rc; switch (c->mode) { case GCRY_CIPHER_MODE_ECB: rc = do_ecb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CBC: rc = _gcry_cipher_cbc_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB: rc = _gcry_cipher_cfb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OFB: rc = _gcry_cipher_ofb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CTR: rc = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_AESWRAP: rc = _gcry_cipher_aeswrap_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_STREAM: c->spec->stencrypt (&c->context.c, outbuf, (byte*)/*arggg*/inbuf, inbuflen); rc = 0; break; case GCRY_CIPHER_MODE_NONE: if (fips_mode () || !_gcry_get_debug_flag (0)) { fips_signal_error ("cipher mode NONE used"); rc = GPG_ERR_INV_CIPHER_MODE; } else { if (inbuf != outbuf) memmove (outbuf, inbuf, inbuflen); rc = 0; } break; default: log_fatal ("cipher_encrypt: invalid mode %d\n", c->mode ); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } /**************** * Encrypt IN and write it to OUT. If IN is NULL, in-place encryption has * been requested. */ gcry_err_code_t _gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen) { gcry_err_code_t rc; if (!in) /* Caller requested in-place encryption. */ { in = out; inlen = outsize; } rc = cipher_encrypt (h, out, outsize, in, inlen); /* Failsafe: Make sure that the plaintext will never make it into OUT if the encryption returned an error. */ if (rc && out) memset (out, 0x42, outsize); return rc; } /**************** * Decrypt INBUF to OUTBUF with the mode selected at open. * inbuf and outbuf may overlap or be the same. * Depending on the mode some some contraints apply to INBUFLEN. */ static gcry_err_code_t cipher_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { gcry_err_code_t rc; switch (c->mode) { case GCRY_CIPHER_MODE_ECB: rc = do_ecb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CBC: rc = _gcry_cipher_cbc_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB: rc = _gcry_cipher_cfb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OFB: rc = _gcry_cipher_ofb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CTR: rc = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_AESWRAP: rc = _gcry_cipher_aeswrap_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_STREAM: c->spec->stdecrypt (&c->context.c, outbuf, (byte*)/*arggg*/inbuf, inbuflen); rc = 0; break; case GCRY_CIPHER_MODE_NONE: if (fips_mode () || !_gcry_get_debug_flag (0)) { fips_signal_error ("cipher mode NONE used"); rc = GPG_ERR_INV_CIPHER_MODE; } else { if (inbuf != outbuf) memmove (outbuf, inbuf, inbuflen); rc = 0; } break; default: log_fatal ("cipher_decrypt: invalid mode %d\n", c->mode ); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen) { if (!in) /* Caller requested in-place encryption. */ { in = out; inlen = outsize; } return cipher_decrypt (h, out, outsize, in, inlen); } /**************** * Used for PGP's somewhat strange CFB mode. Only works if * the corresponding flag is set. */ static void cipher_sync (gcry_cipher_hd_t c) { if ((c->flags & GCRY_CIPHER_ENABLE_SYNC) && c->unused) { memmove (c->u_iv.iv + c->unused, c->u_iv.iv, c->spec->blocksize - c->unused); memcpy (c->u_iv.iv, c->lastiv + c->spec->blocksize - c->unused, c->unused); c->unused = 0; } } gcry_err_code_t _gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen) { return cipher_setkey (hd, (void*)key, keylen); } gcry_err_code_t _gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen) { gcry_err_code_t rc = 0; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_set_nonce (hd, iv, ivlen); break; default: rc = cipher_setiv (hd, iv, ivlen); break; } return rc; } /* 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_err_code_t _gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen) { if (ctr && ctrlen == hd->spec->blocksize) { memcpy (hd->u_ctr.ctr, ctr, hd->spec->blocksize); hd->unused = 0; } else if (!ctr || !ctrlen) { memset (hd->u_ctr.ctr, 0, hd->spec->blocksize); hd->unused = 0; } else return GPG_ERR_INV_ARG; return 0; } gcry_err_code_t _gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf, size_t abuflen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_authenticate (hd, abuf, abuflen); break; default: log_error ("gcry_cipher_authenticate: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_get_tag (hd, outtag, taglen); break; default: log_error ("gcry_cipher_gettag: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_check_tag (hd, intag, taglen); break; default: log_error ("gcry_cipher_checktag: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen) { gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_RESET: cipher_reset (h); break; case GCRYCTL_CFB_SYNC: cipher_sync( h ); break; case GCRYCTL_SET_CBC_CTS: if (buflen) if (h->flags & GCRY_CIPHER_CBC_MAC) rc = GPG_ERR_INV_FLAG; else h->flags |= GCRY_CIPHER_CBC_CTS; else h->flags &= ~GCRY_CIPHER_CBC_CTS; break; case GCRYCTL_SET_CBC_MAC: if (buflen) if (h->flags & GCRY_CIPHER_CBC_CTS) rc = GPG_ERR_INV_FLAG; else h->flags |= GCRY_CIPHER_CBC_MAC; else h->flags &= ~GCRY_CIPHER_CBC_MAC; break; case GCRYCTL_SET_CCM_LENGTHS: #ifdef HAVE_U64_TYPEDEF { u64 params[3]; size_t encryptedlen; size_t aadlen; size_t authtaglen; if (h->mode != GCRY_CIPHER_MODE_CCM) return gcry_error (GPG_ERR_INV_CIPHER_MODE); if (!buffer || buflen != 3 * sizeof(u64)) return gcry_error (GPG_ERR_INV_ARG); /* This command is used to pass additional length parameters needed by CCM mode to initialize CBC-MAC. */ memcpy (params, buffer, sizeof(params)); encryptedlen = params[0]; aadlen = params[1]; authtaglen = params[2]; rc = _gcry_cipher_ccm_set_lengths (h, encryptedlen, aadlen, authtaglen); } #else rc = GPG_ERR_NOT_SUPPORTED; #endif break; case GCRYCTL_DISABLE_ALGO: /* This command expects NULL for H and BUFFER to point to an integer with the algo number. */ if( h || !buffer || buflen != sizeof(int) ) return gcry_error (GPG_ERR_CIPHER_ALGO); disable_cipher_algo( *(int*)buffer ); break; case 61: /* Disable weak key detection (private). */ if (h->spec->set_extra_info) rc = h->spec->set_extra_info (&h->context.c, CIPHER_INFO_NO_WEAK_KEY, NULL, 0); else rc = GPG_ERR_NOT_SUPPORTED; break; case 62: /* Return current input vector (private). */ /* This is the input block as used in CFB and OFB mode which has initially been set as IV. The returned format is: 1 byte Actual length of the block in bytes. n byte The block. If the provided buffer is too short, an error is returned. */ if (buflen < (1 + h->spec->blocksize)) rc = GPG_ERR_TOO_SHORT; else { unsigned char *ivp; unsigned char *dst = buffer; int n = h->unused; if (!n) n = h->spec->blocksize; gcry_assert (n <= h->spec->blocksize); *dst++ = n; ivp = h->u_iv.iv + h->spec->blocksize - n; while (n--) *dst++ = *ivp++; } break; default: rc = GPG_ERR_INV_OP; } return rc; } /* Return information about the cipher handle H. CMD is the kind of information requested. BUFFER and NBYTES are reserved for now. There are no values for CMD yet defined. The function always returns GPG_ERR_INV_OP. */ gcry_err_code_t _gcry_cipher_info (gcry_cipher_hd_t h, int cmd, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; (void)h; (void)buffer; (void)nbytes; switch (cmd) { default: rc = GPG_ERR_INV_OP; } return rc; } /* Return information about the given cipher algorithm ALGO. WHAT select the kind of information returned: GCRYCTL_GET_KEYLEN: Return the length of the key. If the algorithm ALGO supports multiple key lengths, the maximum supported key length is returned. The key length is returned as number of octets. BUFFER and NBYTES must be zero. GCRYCTL_GET_BLKLEN: Return the blocklength of the algorithm ALGO counted in octets. BUFFER and NBYTES must be zero. GCRYCTL_TEST_ALGO: Returns 0 if the specified algorithm ALGO is available for use. BUFFER and NBYTES must be zero. Note: Because this function is in most cases used to return an integer value, we can make it easier for the caller to just look at the return value. The caller will in all cases consult the value and thereby detecting whether a error occurred or not (i.e. while checking the block size) */ gcry_err_code_t _gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; unsigned int ui; switch (what) { case GCRYCTL_GET_KEYLEN: if (buffer || (! nbytes)) rc = GPG_ERR_CIPHER_ALGO; else { ui = cipher_get_keylen (algo); if ((ui > 0) && (ui <= 512)) *nbytes = (size_t) ui / 8; else /* The only reason for an error is an invalid algo. */ rc = GPG_ERR_CIPHER_ALGO; } break; case GCRYCTL_GET_BLKLEN: if (buffer || (! nbytes)) rc = GPG_ERR_CIPHER_ALGO; else { ui = cipher_get_blocksize (algo); if ((ui > 0) && (ui < 10000)) *nbytes = ui; else { /* The only reason is an invalid algo or a strange blocksize. */ rc = GPG_ERR_CIPHER_ALGO; } } break; case GCRYCTL_TEST_ALGO: if (buffer || nbytes) rc = GPG_ERR_INV_ARG; else rc = check_cipher_algo (algo); break; default: rc = GPG_ERR_INV_OP; } return rc; } /* This function returns length of the key for algorithm ALGO. If the algorithm supports multiple key lengths, the maximum supported key length is returned. On error 0 is returned. The key length is returned as number of octets. This is a convenience functions which should be preferred over gcry_cipher_algo_info because it allows for proper type checking. */ size_t _gcry_cipher_get_algo_keylen (int algo) { size_t n; if (_gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &n)) n = 0; return n; } /* This functions returns the blocklength of the algorithm ALGO counted in octets. On error 0 is returned. This is a convenience functions which should be preferred over gcry_cipher_algo_info because it allows for proper type checking. */ size_t _gcry_cipher_get_algo_blklen (int algo) { size_t n; if (_gcry_cipher_algo_info( algo, GCRYCTL_GET_BLKLEN, NULL, &n)) n = 0; return n; } /* Explicitly initialize this module. */ gcry_err_code_t _gcry_cipher_init (void) { return 0; } /* Run the selftests for cipher algorithm ALGO with optional reporting function REPORT. */ gpg_error_t _gcry_cipher_selftest (int algo, int extended, selftest_report_func_t report) { gcry_err_code_t ec = 0; gcry_cipher_spec_t *spec; spec = spec_from_algo (algo); if (spec && !spec->flags.disabled && spec->selftest) ec = spec->selftest (algo, extended, report); else { ec = GPG_ERR_CIPHER_ALGO; if (report) report ("cipher", algo, "module", (spec && !spec->flags.disabled)? "no selftest available" : spec? "algorithm disabled" : "algorithm not found"); } return gpg_error (ec); } diff --git a/cipher/kdf.c b/cipher/kdf.c index af0dc480..ad5c46ef 100644 --- a/cipher/kdf.c +++ b/cipher/kdf.c @@ -1,300 +1,299 @@ /* kdf.c - Key Derivation Functions * Copyright (C) 1998, 2011 Free Software Foundation, Inc. * Copyright (C) 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "kdf-internal.h" /* Transform a passphrase into a suitable key of length KEYSIZE and store this key in the caller provided buffer KEYBUFFER. The caller must provide an HASHALGO, a valid ALGO and depending on that algo a SALT of 8 bytes and the number of ITERATIONS. Code taken from gnupg/agent/protect.c:hash_passphrase. */ static gpg_err_code_t openpgp_s2k (const void *passphrase, size_t passphraselen, int algo, int hashalgo, const void *salt, size_t saltlen, unsigned long iterations, size_t keysize, void *keybuffer) { gpg_err_code_t ec; gcry_md_hd_t md; char *key = keybuffer; int pass, i; int used = 0; int secmode; if ((algo == GCRY_KDF_SALTED_S2K || algo == GCRY_KDF_ITERSALTED_S2K) && (!salt || saltlen != 8)) return GPG_ERR_INV_VALUE; secmode = _gcry_is_secure (passphrase) || _gcry_is_secure (keybuffer); ec = _gcry_md_open (&md, hashalgo, secmode? GCRY_MD_FLAG_SECURE : 0); if (ec) return ec; for (pass=0; used < keysize; pass++) { if (pass) { _gcry_md_reset (md); for (i=0; i < pass; i++) /* Preset the hash context. */ _gcry_md_putc (md, 0); } if (algo == GCRY_KDF_SALTED_S2K || algo == GCRY_KDF_ITERSALTED_S2K) { int len2 = passphraselen + 8; unsigned long count = len2; if (algo == GCRY_KDF_ITERSALTED_S2K) { count = iterations; if (count < len2) count = len2; } while (count > len2) { _gcry_md_write (md, salt, saltlen); _gcry_md_write (md, passphrase, passphraselen); count -= len2; } if (count < saltlen) _gcry_md_write (md, salt, count); else { _gcry_md_write (md, salt, saltlen); count -= saltlen; _gcry_md_write (md, passphrase, count); } } else _gcry_md_write (md, passphrase, passphraselen); _gcry_md_final (md); i = _gcry_md_get_algo_dlen (hashalgo); if (i > keysize - used) i = keysize - used; memcpy (key+used, _gcry_md_read (md, hashalgo), i); used += i; } _gcry_md_close (md); return 0; } /* Transform a passphrase into a suitable key of length KEYSIZE and store this key in the caller provided buffer KEYBUFFER. The caller must provide PRFALGO which indicates the pseudorandom function to use: This shall be the algorithms id of a hash algorithm; it is used in HMAC mode. SALT is a salt of length SALTLEN and ITERATIONS gives the number of iterations. */ gpg_err_code_t _gcry_kdf_pkdf2 (const void *passphrase, size_t passphraselen, int hashalgo, const void *salt, size_t saltlen, unsigned long iterations, size_t keysize, void *keybuffer) { gpg_err_code_t ec; gcry_md_hd_t md; int secmode; unsigned int dklen = keysize; char *dk = keybuffer; unsigned int hlen; /* Output length of the digest function. */ unsigned int l; /* Rounded up number of blocks. */ unsigned int r; /* Number of octets in the last block. */ char *sbuf; /* Malloced buffer to concatenate salt and iter as well as space to hold TBUF and UBUF. */ char *tbuf; /* Buffer for T; ptr into SBUF, size is HLEN. */ char *ubuf; /* Buffer for U; ptr into SBUF, size is HLEN. */ unsigned int lidx; /* Current block number. */ unsigned long iter; /* Current iteration number. */ unsigned int i; /* NWe allow for a saltlen of 0 here to support scrypt. It is not clear whether rfc2898 allows for this this, thus we do a test on saltlen > 0 only in gcry_kdf_derive. */ if (!salt || !iterations || !dklen) return GPG_ERR_INV_VALUE; hlen = _gcry_md_get_algo_dlen (hashalgo); if (!hlen) return GPG_ERR_DIGEST_ALGO; secmode = _gcry_is_secure (passphrase) || _gcry_is_secure (keybuffer); /* We ignore step 1 from pksc5v2.1 which demands a check that dklen is not larger that 0xffffffff * hlen. */ /* Step 2 */ l = ((dklen - 1)/ hlen) + 1; r = dklen - (l - 1) * hlen; /* Setup buffers and prepare a hash context. */ sbuf = (secmode ? xtrymalloc_secure (saltlen + 4 + hlen + hlen) : xtrymalloc (saltlen + 4 + hlen + hlen)); if (!sbuf) return gpg_err_code_from_syserror (); tbuf = sbuf + saltlen + 4; ubuf = tbuf + hlen; ec = _gcry_md_open (&md, hashalgo, (GCRY_MD_FLAG_HMAC | (secmode?GCRY_MD_FLAG_SECURE:0))); if (ec) { xfree (sbuf); return ec; } ec = _gcry_md_setkey (md, passphrase, passphraselen); if (ec) { _gcry_md_close (md); xfree (sbuf); return ec; } /* Step 3 and 4. */ memcpy (sbuf, salt, saltlen); for (lidx = 1; lidx <= l; lidx++) { for (iter = 0; iter < iterations; iter++) { _gcry_md_reset (md); if (!iter) /* Compute U_1: */ { sbuf[saltlen] = (lidx >> 24); sbuf[saltlen + 1] = (lidx >> 16); sbuf[saltlen + 2] = (lidx >> 8); sbuf[saltlen + 3] = lidx; _gcry_md_write (md, sbuf, saltlen + 4); memcpy (ubuf, _gcry_md_read (md, 0), hlen); memcpy (tbuf, ubuf, hlen); } else /* Compute U_(2..c): */ { _gcry_md_write (md, ubuf, hlen); memcpy (ubuf, _gcry_md_read (md, 0), hlen); for (i=0; i < hlen; i++) tbuf[i] ^= ubuf[i]; } } if (lidx == l) /* Last block. */ memcpy (dk, tbuf, r); else { memcpy (dk, tbuf, hlen); dk += hlen; } } _gcry_md_close (md); xfree (sbuf); return 0; } /* Derive a key from a passphrase. KEYSIZE gives the requested size of the keys in octets. KEYBUFFER is a caller provided buffer filled on success with the derived key. The input passphrase is taken from (PASSPHRASE,PASSPHRASELEN) which is an arbitrary memory buffer. ALGO specifies the KDF algorithm to use; these are the constants GCRY_KDF_*. SUBALGO specifies an algorithm used internally by the KDF algorithms; this is usually a hash algorithm but certain KDF algorithm may use it differently. {SALT,SALTLEN} is a salt as needed by most KDF algorithms. ITERATIONS is a positive integer parameter to most KDFs. 0 is returned on success, or an error code on failure. */ gpg_err_code_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) { gpg_err_code_t ec; if (!passphrase) { ec = GPG_ERR_INV_DATA; goto leave; } if (!keybuffer || !keysize) { ec = GPG_ERR_INV_VALUE; goto leave; } switch (algo) { case GCRY_KDF_SIMPLE_S2K: case GCRY_KDF_SALTED_S2K: case GCRY_KDF_ITERSALTED_S2K: if (!passphraselen) ec = GPG_ERR_INV_DATA; else ec = openpgp_s2k (passphrase, passphraselen, algo, subalgo, salt, saltlen, iterations, keysize, keybuffer); break; case GCRY_KDF_PBKDF1: ec = GPG_ERR_UNSUPPORTED_ALGORITHM; break; case GCRY_KDF_PBKDF2: if (!saltlen) ec = GPG_ERR_INV_VALUE; else ec = _gcry_kdf_pkdf2 (passphrase, passphraselen, subalgo, salt, saltlen, iterations, keysize, keybuffer); break; case 41: case GCRY_KDF_SCRYPT: #if USE_SCRYPT ec = _gcry_kdf_scrypt (passphrase, passphraselen, algo, subalgo, salt, saltlen, iterations, keysize, keybuffer); #else ec = GPG_ERR_UNSUPPORTED_ALGORITHM; #endif /*USE_SCRYPT*/ break; default: ec = GPG_ERR_UNKNOWN_ALGORITHM; break; } leave: return ec; } diff --git a/cipher/md.c b/cipher/md.c index 1b597650..f4fb1294 100644 --- a/cipher/md.c +++ b/cipher/md.c @@ -1,1250 +1,1249 @@ /* md.c - message digest dispatcher * Copyright (C) 1998, 1999, 2002, 2003, 2006, * 2008 Free Software Foundation, Inc. * Copyright (C) 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 . */ #include #include #include #include #include #include "g10lib.h" #include "cipher.h" -#include "ath.h" #include "rmd.h" /* This is the list of the digest implementations included in libgcrypt. */ static gcry_md_spec_t *digest_list[] = { #if USE_CRC &_gcry_digest_spec_crc32, &_gcry_digest_spec_crc32_rfc1510, &_gcry_digest_spec_crc24_rfc2440, #endif #if USE_SHA1 &_gcry_digest_spec_sha1, #endif #if USE_SHA256 &_gcry_digest_spec_sha256, &_gcry_digest_spec_sha224, #endif #if USE_SHA512 &_gcry_digest_spec_sha512, &_gcry_digest_spec_sha384, #endif #ifdef USE_GOST_R_3411_94 &_gcry_digest_spec_gost3411_94, #endif #ifdef USE_GOST_R_3411_12 &_gcry_digest_spec_stribog_256, &_gcry_digest_spec_stribog_512, #endif #if USE_WHIRLPOOL &_gcry_digest_spec_whirlpool, #endif #if USE_RMD160 &_gcry_digest_spec_rmd160, #endif #if USE_TIGER &_gcry_digest_spec_tiger, &_gcry_digest_spec_tiger1, &_gcry_digest_spec_tiger2, #endif #if USE_MD5 &_gcry_digest_spec_md5, #endif #if USE_MD4 &_gcry_digest_spec_md4, #endif NULL }; typedef struct gcry_md_list { gcry_md_spec_t *spec; struct gcry_md_list *next; size_t actual_struct_size; /* Allocated size of this structure. */ PROPERLY_ALIGNED_TYPE context; } GcryDigestEntry; /* This structure is put right after the gcry_md_hd_t buffer, so that * only one memory block is needed. */ struct gcry_md_context { int magic; size_t actual_handle_size; /* Allocated size of this handle. */ int secure; FILE *debug; int finalized; GcryDigestEntry *list; byte *macpads; int macpads_Bsize; /* Blocksize as used for the HMAC pads. */ }; #define CTX_MAGIC_NORMAL 0x11071961 #define CTX_MAGIC_SECURE 0x16917011 static gcry_err_code_t md_enable (gcry_md_hd_t hd, int algo); static void md_close (gcry_md_hd_t a); static void md_write (gcry_md_hd_t a, const void *inbuf, size_t inlen); static byte *md_read( gcry_md_hd_t a, int algo ); static int md_get_algo( gcry_md_hd_t a ); static int md_digest_length( int algo ); static void md_start_debug ( gcry_md_hd_t a, const char *suffix ); static void md_stop_debug ( gcry_md_hd_t a ); static int map_algo (int algo) { return algo; } /* Return the spec structure for the hash algorithm ALGO. For an unknown algorithm NULL is returned. */ static gcry_md_spec_t * spec_from_algo (int algo) { int idx; gcry_md_spec_t *spec; algo = map_algo (algo); for (idx = 0; (spec = digest_list[idx]); idx++) if (algo == spec->algo) return spec; return NULL; } /* Lookup a hash's spec by its name. */ static gcry_md_spec_t * spec_from_name (const char *name) { gcry_md_spec_t *spec; int idx; for (idx=0; (spec = digest_list[idx]); idx++) { if (!stricmp (name, spec->name)) return spec; } return NULL; } /* Lookup a hash's spec by its OID. */ static gcry_md_spec_t * spec_from_oid (const char *oid) { gcry_md_spec_t *spec; gcry_md_oid_spec_t *oid_specs; int idx, j; for (idx=0; (spec = digest_list[idx]); idx++) { oid_specs = spec->oids; if (oid_specs) { for (j = 0; oid_specs[j].oidstring; j++) if (!stricmp (oid, oid_specs[j].oidstring)) return spec; } } return NULL; } static gcry_md_spec_t * search_oid (const char *oid, gcry_md_oid_spec_t *oid_spec) { gcry_md_spec_t *spec; int i; if (oid && ((! strncmp (oid, "oid.", 4)) || (! strncmp (oid, "OID.", 4)))) oid += 4; spec = spec_from_oid (oid); if (spec && spec->oids) { for (i = 0; spec->oids[i].oidstring; i++) if (!stricmp (oid, spec->oids[i].oidstring)) { if (oid_spec) *oid_spec = spec->oids[i]; return spec; } } return NULL; } /**************** * Map a string to the digest algo */ int _gcry_md_map_name (const char *string) { gcry_md_spec_t *spec; if (!string) return 0; /* If the string starts with a digit (optionally prefixed with either "OID." or "oid."), we first look into our table of ASN.1 object identifiers to figure out the algorithm */ spec = search_oid (string, NULL); if (spec) return spec->algo; /* Not found, search a matching digest name. */ spec = spec_from_name (string); if (spec) return spec->algo; return 0; } /**************** * This function simply returns the name of the algorithm or some constant * string when there is no algo. It will never return NULL. * Use the macro gcry_md_test_algo() to check whether the algorithm * is valid. */ const char * _gcry_md_algo_name (int algorithm) { gcry_md_spec_t *spec; spec = spec_from_algo (algorithm); return spec ? spec->name : "?"; } static gcry_err_code_t check_digest_algo (int algorithm) { gcry_md_spec_t *spec; spec = spec_from_algo (algorithm); if (spec && !spec->flags.disabled) return 0; return GPG_ERR_DIGEST_ALGO; } /**************** * Open a message digest handle for use with algorithm ALGO. * More algorithms may be added by md_enable(). The initial algorithm * may be 0. */ static gcry_err_code_t md_open (gcry_md_hd_t *h, int algo, int secure, int hmac) { gcry_err_code_t err = GPG_ERR_NO_ERROR; int bufsize = secure ? 512 : 1024; struct gcry_md_context *ctx; gcry_md_hd_t hd; size_t n; /* Allocate a memory area to hold the caller visible buffer with it's * control information and the data required by this module. Set the * context pointer at the beginning to this area. * We have to use this strange scheme because we want to hide the * internal data but have a variable sized buffer. * * +---+------+---........------+-------------+ * !ctx! bctl ! buffer ! private ! * +---+------+---........------+-------------+ * ! ^ * !---------------------------! * * We have to make sure that private is well aligned. */ n = sizeof (struct gcry_md_handle) + bufsize; n = ((n + sizeof (PROPERLY_ALIGNED_TYPE) - 1) / sizeof (PROPERLY_ALIGNED_TYPE)) * sizeof (PROPERLY_ALIGNED_TYPE); /* Allocate and set the Context pointer to the private data */ if (secure) hd = xtrymalloc_secure (n + sizeof (struct gcry_md_context)); else hd = xtrymalloc (n + sizeof (struct gcry_md_context)); if (! hd) err = gpg_err_code_from_errno (errno); if (! err) { hd->ctx = ctx = (struct gcry_md_context *) ((char *) hd + n); /* Setup the globally visible data (bctl in the diagram).*/ hd->bufsize = n - sizeof (struct gcry_md_handle) + 1; hd->bufpos = 0; /* Initialize the private data. */ memset (hd->ctx, 0, sizeof *hd->ctx); ctx->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL; ctx->actual_handle_size = n + sizeof (struct gcry_md_context); ctx->secure = secure; if (hmac) { switch (algo) { case GCRY_MD_SHA384: case GCRY_MD_SHA512: ctx->macpads_Bsize = 128; break; case GCRY_MD_GOSTR3411_94: ctx->macpads_Bsize = 32; break; default: ctx->macpads_Bsize = 64; break; } ctx->macpads = xtrymalloc_secure (2*(ctx->macpads_Bsize)); if (!ctx->macpads) { err = gpg_err_code_from_errno (errno); md_close (hd); } } } if (! err) { /* Hmmm, should we really do that? - yes [-wk] */ _gcry_fast_random_poll (); if (algo) { err = md_enable (hd, algo); if (err) md_close (hd); } } if (! err) *h = hd; return err; } /* 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. H is guaranteed to be a valid handle or NULL on error. */ gcry_err_code_t _gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags) { gcry_err_code_t rc; gcry_md_hd_t hd; if ((flags & ~(GCRY_MD_FLAG_SECURE | GCRY_MD_FLAG_HMAC))) rc = GPG_ERR_INV_ARG; else { rc = md_open (&hd, algo, (flags & GCRY_MD_FLAG_SECURE), (flags & GCRY_MD_FLAG_HMAC)); } *h = rc? NULL : hd; return rc; } static gcry_err_code_t md_enable (gcry_md_hd_t hd, int algorithm) { struct gcry_md_context *h = hd->ctx; gcry_md_spec_t *spec; GcryDigestEntry *entry; gcry_err_code_t err = 0; for (entry = h->list; entry; entry = entry->next) if (entry->spec->algo == algorithm) return 0; /* Already enabled */ spec = spec_from_algo (algorithm); if (!spec) { log_debug ("md_enable: algorithm %d not available\n", algorithm); err = GPG_ERR_DIGEST_ALGO; } if (!err && algorithm == GCRY_MD_MD5 && fips_mode ()) { _gcry_inactivate_fips_mode ("MD5 used"); if (_gcry_enforced_fips_mode () ) { /* We should never get to here because we do not register MD5 in enforced fips mode. But better throw an error. */ err = GPG_ERR_DIGEST_ALGO; } } if (!err) { size_t size = (sizeof (*entry) + spec->contextsize - sizeof (entry->context)); /* And allocate a new list entry. */ if (h->secure) entry = xtrymalloc_secure (size); else entry = xtrymalloc (size); if (! entry) err = gpg_err_code_from_errno (errno); else { entry->spec = spec; entry->next = h->list; entry->actual_struct_size = size; h->list = entry; /* And init this instance. */ entry->spec->init (&entry->context.c); } } return err; } gcry_err_code_t _gcry_md_enable (gcry_md_hd_t hd, int algorithm) { return md_enable (hd, algorithm); } static gcry_err_code_t md_copy (gcry_md_hd_t ahd, gcry_md_hd_t *b_hd) { gcry_err_code_t err = 0; struct gcry_md_context *a = ahd->ctx; struct gcry_md_context *b; GcryDigestEntry *ar, *br; gcry_md_hd_t bhd; size_t n; if (ahd->bufpos) md_write (ahd, NULL, 0); n = (char *) ahd->ctx - (char *) ahd; if (a->secure) bhd = xtrymalloc_secure (n + sizeof (struct gcry_md_context)); else bhd = xtrymalloc (n + sizeof (struct gcry_md_context)); if (! bhd) err = gpg_err_code_from_errno (errno); if (! err) { bhd->ctx = b = (struct gcry_md_context *) ((char *) bhd + n); /* No need to copy the buffer due to the write above. */ gcry_assert (ahd->bufsize == (n - sizeof (struct gcry_md_handle) + 1)); bhd->bufsize = ahd->bufsize; bhd->bufpos = 0; gcry_assert (! ahd->bufpos); memcpy (b, a, sizeof *a); b->list = NULL; b->debug = NULL; if (a->macpads) { b->macpads = xtrymalloc_secure (2*(a->macpads_Bsize)); if (! b->macpads) { err = gpg_err_code_from_errno (errno); md_close (bhd); } else memcpy (b->macpads, a->macpads, (2*(a->macpads_Bsize))); } } /* Copy the complete list of algorithms. The copied list is reversed, but that doesn't matter. */ if (!err) { for (ar = a->list; ar; ar = ar->next) { if (a->secure) br = xtrymalloc_secure (sizeof *br + ar->spec->contextsize - sizeof(ar->context)); else br = xtrymalloc (sizeof *br + ar->spec->contextsize - sizeof (ar->context)); if (!br) { err = gpg_err_code_from_errno (errno); md_close (bhd); break; } memcpy (br, ar, (sizeof (*br) + ar->spec->contextsize - sizeof (ar->context))); br->next = b->list; b->list = br; } } if (a->debug && !err) md_start_debug (bhd, "unknown"); if (!err) *b_hd = bhd; return err; } gcry_err_code_t _gcry_md_copy (gcry_md_hd_t *handle, gcry_md_hd_t hd) { gcry_err_code_t rc; rc = md_copy (hd, handle); if (rc) *handle = NULL; return rc; } /* * Reset all contexts and discard any buffered stuff. This may be used * instead of a md_close(); md_open(). */ void _gcry_md_reset (gcry_md_hd_t a) { GcryDigestEntry *r; /* Note: We allow this even in fips non operational mode. */ a->bufpos = a->ctx->finalized = 0; for (r = a->ctx->list; r; r = r->next) { memset (r->context.c, 0, r->spec->contextsize); (*r->spec->init) (&r->context.c); } if (a->ctx->macpads) md_write (a, a->ctx->macpads, a->ctx->macpads_Bsize); /* inner pad */ } static void md_close (gcry_md_hd_t a) { GcryDigestEntry *r, *r2; if (! a) return; if (a->ctx->debug) md_stop_debug (a); for (r = a->ctx->list; r; r = r2) { r2 = r->next; wipememory (r, r->actual_struct_size); xfree (r); } if (a->ctx->macpads) { wipememory (a->ctx->macpads, 2*(a->ctx->macpads_Bsize)); xfree(a->ctx->macpads); } wipememory (a, a->ctx->actual_handle_size); xfree(a); } void _gcry_md_close (gcry_md_hd_t hd) { /* Note: We allow this even in fips non operational mode. */ md_close (hd); } static void md_write (gcry_md_hd_t a, const void *inbuf, size_t inlen) { GcryDigestEntry *r; if (a->ctx->debug) { if (a->bufpos && fwrite (a->buf, a->bufpos, 1, a->ctx->debug) != 1) BUG(); if (inlen && fwrite (inbuf, inlen, 1, a->ctx->debug) != 1) BUG(); } for (r = a->ctx->list; r; r = r->next) { if (a->bufpos) (*r->spec->write) (&r->context.c, a->buf, a->bufpos); (*r->spec->write) (&r->context.c, inbuf, inlen); } a->bufpos = 0; } void _gcry_md_write (gcry_md_hd_t hd, const void *inbuf, size_t inlen) { md_write (hd, inbuf, inlen); } static void md_final (gcry_md_hd_t a) { GcryDigestEntry *r; if (a->ctx->finalized) return; if (a->bufpos) md_write (a, NULL, 0); for (r = a->ctx->list; r; r = r->next) (*r->spec->final) (&r->context.c); a->ctx->finalized = 1; if (a->ctx->macpads) { /* Finish the hmac. */ int algo = md_get_algo (a); byte *p = md_read (a, algo); size_t dlen = md_digest_length (algo); gcry_md_hd_t om; gcry_err_code_t err = md_open (&om, algo, a->ctx->secure, 0); if (err) _gcry_fatal_error (err, NULL); md_write (om, (a->ctx->macpads)+(a->ctx->macpads_Bsize), a->ctx->macpads_Bsize); md_write (om, p, dlen); md_final (om); /* Replace our digest with the mac (they have the same size). */ memcpy (p, md_read (om, algo), dlen); md_close (om); } } static gcry_err_code_t prepare_macpads (gcry_md_hd_t hd, const unsigned char *key, size_t keylen) { int i; int algo = md_get_algo (hd); unsigned char *helpkey = NULL; unsigned char *ipad, *opad; if (!algo) return GPG_ERR_DIGEST_ALGO; /* Might happen if no algo is enabled. */ if ( keylen > hd->ctx->macpads_Bsize ) { helpkey = xtrymalloc_secure (md_digest_length (algo)); if (!helpkey) return gpg_err_code_from_errno (errno); _gcry_md_hash_buffer (algo, helpkey, key, keylen); key = helpkey; keylen = md_digest_length (algo); gcry_assert ( keylen <= hd->ctx->macpads_Bsize ); } memset ( hd->ctx->macpads, 0, 2*(hd->ctx->macpads_Bsize) ); ipad = hd->ctx->macpads; opad = (hd->ctx->macpads)+(hd->ctx->macpads_Bsize); memcpy ( ipad, key, keylen ); memcpy ( opad, key, keylen ); for (i=0; i < hd->ctx->macpads_Bsize; i++ ) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } xfree (helpkey); return 0; } gcry_err_code_t _gcry_md_ctl (gcry_md_hd_t hd, int cmd, void *buffer, size_t buflen) { gcry_err_code_t rc = 0; (void)buflen; /* Currently not used. */ switch (cmd) { case GCRYCTL_FINALIZE: md_final (hd); break; case GCRYCTL_START_DUMP: md_start_debug (hd, buffer); break; case GCRYCTL_STOP_DUMP: md_stop_debug ( hd ); break; default: rc = GPG_ERR_INV_OP; } return rc; } gcry_err_code_t _gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen) { gcry_err_code_t rc; if (!hd->ctx->macpads) rc = GPG_ERR_CONFLICT; else { rc = prepare_macpads (hd, key, keylen); if (!rc) _gcry_md_reset (hd); } return rc; } /* The new debug interface. If SUFFIX is a string it creates an debug file for the context HD. IF suffix is NULL, the file is closed and debugging is stopped. */ void _gcry_md_debug (gcry_md_hd_t hd, const char *suffix) { if (suffix) md_start_debug (hd, suffix); else md_stop_debug (hd); } /**************** * If ALGO is null get the digest for the used algo (which should be * only one) */ static byte * md_read( gcry_md_hd_t a, int algo ) { GcryDigestEntry *r = a->ctx->list; if (! algo) { /* Return the first algorithm */ if (r) { if (r->next) log_debug ("more than one algorithm in md_read(0)\n"); return r->spec->read (&r->context.c); } } else { for (r = a->ctx->list; r; r = r->next) if (r->spec->algo == algo) return r->spec->read (&r->context.c); } BUG(); return NULL; } /* * Read out the complete digest, this function implictly finalizes * the hash. */ byte * _gcry_md_read (gcry_md_hd_t hd, int algo) { /* This function is expected to always return a digest, thus we can't return an error which we actually should do in non-operational state. */ _gcry_md_ctl (hd, GCRYCTL_FINALIZE, NULL, 0); return md_read (hd, algo); } /* * Read out an intermediate digest. Not yet functional. */ gcry_err_code_t _gcry_md_get (gcry_md_hd_t hd, int algo, byte *buffer, int buflen) { (void)hd; (void)algo; (void)buffer; (void)buflen; /*md_digest ... */ fips_signal_error ("unimplemented function called"); return GPG_ERR_INTERNAL; } /* * Shortcut function to hash a buffer with a given algo. The only * guaranteed supported algorithms are RIPE-MD160 and SHA-1. The * supplied digest buffer must be large enough to store the resulting * hash. No error is returned, the function will abort on an invalid * algo. DISABLED_ALGOS are ignored here. */ void _gcry_md_hash_buffer (int algo, void *digest, const void *buffer, size_t length) { if (algo == GCRY_MD_SHA1) _gcry_sha1_hash_buffer (digest, buffer, length); else if (algo == GCRY_MD_RMD160 && !fips_mode () ) _gcry_rmd160_hash_buffer (digest, buffer, length); else { /* For the others we do not have a fast function, so we use the normal functions. */ gcry_md_hd_t h; gpg_err_code_t err; if (algo == GCRY_MD_MD5 && fips_mode ()) { _gcry_inactivate_fips_mode ("MD5 used"); if (_gcry_enforced_fips_mode () ) { /* We should never get to here because we do not register MD5 in enforced fips mode. */ _gcry_fips_noreturn (); } } err = md_open (&h, algo, 0, 0); if (err) log_bug ("gcry_md_open failed for algo %d: %s", algo, gpg_strerror (gcry_error(err))); md_write (h, (byte *) buffer, length); md_final (h); memcpy (digest, md_read (h, algo), md_digest_length (algo)); md_close (h); } } /* Shortcut function to hash multiple buffers with a given algo. In contrast to gcry_md_hash_buffer, this function returns an error on invalid arguments or on other problems; disabled algorithms are _not_ ignored but flagged as an error. The data to sign is taken from the array IOV which has IOVCNT items. The only supported flag in FLAGS is GCRY_MD_FLAG_HMAC which turns this function into a HMAC function; the first item in IOV is then used as the key. On success 0 is returned and resulting hash or HMAC is stored at DIGEST which must have been provided by the caller with an appropriate length. */ gpg_err_code_t _gcry_md_hash_buffers (int algo, unsigned int flags, void *digest, const gcry_buffer_t *iov, int iovcnt) { int hmac; if (!iov || iovcnt < 0) return GPG_ERR_INV_ARG; if (flags & ~(GCRY_MD_FLAG_HMAC)) return GPG_ERR_INV_ARG; hmac = !!(flags & GCRY_MD_FLAG_HMAC); if (hmac && iovcnt < 1) return GPG_ERR_INV_ARG; if (algo == GCRY_MD_SHA1 && !hmac) _gcry_sha1_hash_buffers (digest, iov, iovcnt); else { /* For the others we do not have a fast function, so we use the normal functions. */ gcry_md_hd_t h; gpg_err_code_t rc; if (algo == GCRY_MD_MD5 && fips_mode ()) { _gcry_inactivate_fips_mode ("MD5 used"); if (_gcry_enforced_fips_mode () ) { /* We should never get to here because we do not register MD5 in enforced fips mode. */ _gcry_fips_noreturn (); } } rc = md_open (&h, algo, 0, hmac); if (rc) return rc; if (hmac) { rc = _gcry_md_setkey (h, (const char*)iov[0].data + iov[0].off, iov[0].len); if (rc) { md_close (h); return rc; } iov++; iovcnt--; } for (;iovcnt; iov++, iovcnt--) md_write (h, (const char*)iov[0].data + iov[0].off, iov[0].len); md_final (h); memcpy (digest, md_read (h, algo), md_digest_length (algo)); md_close (h); } return 0; } static int md_get_algo (gcry_md_hd_t a) { GcryDigestEntry *r = a->ctx->list; if (r && r->next) { fips_signal_error ("possible usage error"); log_error ("WARNING: more than one algorithm in md_get_algo()\n"); } return r ? r->spec->algo : 0; } int _gcry_md_get_algo (gcry_md_hd_t hd) { return md_get_algo (hd); } /**************** * Return the length of the digest */ static int md_digest_length (int algorithm) { gcry_md_spec_t *spec; spec = spec_from_algo (algorithm); return spec? spec->mdlen : 0; } /**************** * Return the length of the digest in bytes. * This function will return 0 in case of errors. */ unsigned int _gcry_md_get_algo_dlen (int algorithm) { return md_digest_length (algorithm); } /* Hmmm: add a mode to enumerate the OIDs * to make g10/sig-check.c more portable */ static const byte * md_asn_oid (int algorithm, size_t *asnlen, size_t *mdlen) { gcry_md_spec_t *spec; const byte *asnoid = NULL; spec = spec_from_algo (algorithm); if (spec) { if (asnlen) *asnlen = spec->asnlen; if (mdlen) *mdlen = spec->mdlen; asnoid = spec->asnoid; } else log_bug ("no ASN.1 OID for md algo %d\n", algorithm); return asnoid; } /**************** * Return information about the given cipher algorithm * WHAT select the kind of information returned: * GCRYCTL_TEST_ALGO: * Returns 0 when the specified algorithm is available for use. * buffer and nbytes must be zero. * GCRYCTL_GET_ASNOID: * Return the ASNOID of the algorithm in buffer. if buffer is NULL, only * the required length is returned. * GCRYCTL_SELFTEST * Helper for the regression tests - shall not be used by applications. * * Note: Because this function is in most cases used to return an * integer value, we can make it easier for the caller to just look at * the return value. The caller will in all cases consult the value * and thereby detecting whether a error occurred or not (i.e. while checking * the block size) */ gcry_err_code_t _gcry_md_algo_info (int algo, int what, void *buffer, size_t *nbytes) { gcry_err_code_t rc; switch (what) { case GCRYCTL_TEST_ALGO: if (buffer || nbytes) rc = GPG_ERR_INV_ARG; else rc = check_digest_algo (algo); break; case GCRYCTL_GET_ASNOID: /* We need to check that the algo is available because md_asn_oid would otherwise raise an assertion. */ rc = check_digest_algo (algo); if (!rc) { const char unsigned *asn; size_t asnlen; asn = md_asn_oid (algo, &asnlen, NULL); if (buffer && (*nbytes >= asnlen)) { memcpy (buffer, asn, asnlen); *nbytes = asnlen; } else if (!buffer && nbytes) *nbytes = asnlen; else { if (buffer) rc = GPG_ERR_TOO_SHORT; else rc = GPG_ERR_INV_ARG; } } break; case GCRYCTL_SELFTEST: /* Helper function for the regression tests. */ rc = gpg_err_code (_gcry_md_selftest (algo, nbytes? (int)*nbytes : 0, NULL)); break; default: rc = GPG_ERR_INV_OP; break; } return rc; } static void md_start_debug ( gcry_md_hd_t md, const char *suffix ) { static int idx=0; char buf[50]; if (fips_mode ()) return; if ( md->ctx->debug ) { log_debug("Oops: md debug already started\n"); return; } idx++; snprintf (buf, DIM(buf)-1, "dbgmd-%05d.%.10s", idx, suffix ); md->ctx->debug = fopen(buf, "w"); if ( !md->ctx->debug ) log_debug("md debug: can't open %s\n", buf ); } static void md_stop_debug( gcry_md_hd_t md ) { if ( md->ctx->debug ) { if ( md->bufpos ) md_write ( md, NULL, 0 ); fclose (md->ctx->debug); md->ctx->debug = NULL; } #ifdef HAVE_U64_TYPEDEF { /* a kludge to pull in the __muldi3 for Solaris */ volatile u32 a = (u32)(ulong)md; volatile u64 b = 42; volatile u64 c; c = a * b; (void)c; } #endif } /* * Return information about the digest handle. * GCRYCTL_IS_SECURE: * Returns 1 when the handle works on secured memory * otherwise 0 is returned. There is no error return. * GCRYCTL_IS_ALGO_ENABLED: * Returns 1 if the algo is enabled for that handle. * The algo must be passed as the address of an int. */ gcry_err_code_t _gcry_md_info (gcry_md_hd_t h, int cmd, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_IS_SECURE: *nbytes = h->ctx->secure; break; case GCRYCTL_IS_ALGO_ENABLED: { GcryDigestEntry *r; int algo; if ( !buffer || (nbytes && (*nbytes != sizeof (int)))) rc = GPG_ERR_INV_ARG; else { algo = *(int*)buffer; *nbytes = 0; for(r=h->ctx->list; r; r = r->next ) { if (r->spec->algo == algo) { *nbytes = 1; break; } } } break; } default: rc = GPG_ERR_INV_OP; } return rc; } /* Explicitly initialize this module. */ gcry_err_code_t _gcry_md_init (void) { return 0; } int _gcry_md_is_secure (gcry_md_hd_t a) { size_t value; if (_gcry_md_info (a, GCRYCTL_IS_SECURE, NULL, &value)) value = 1; /* It seems to be better to assume secure memory on error. */ return value; } int _gcry_md_is_enabled (gcry_md_hd_t a, int algo) { size_t value; value = sizeof algo; if (_gcry_md_info (a, GCRYCTL_IS_ALGO_ENABLED, &algo, &value)) value = 0; return value; } /* Run the selftests for digest algorithm ALGO with optional reporting function REPORT. */ gpg_error_t _gcry_md_selftest (int algo, int extended, selftest_report_func_t report) { gcry_err_code_t ec = 0; gcry_md_spec_t *spec; spec = spec_from_algo (algo); if (spec && !spec->flags.disabled && spec->selftest) ec = spec->selftest (algo, extended, report); else { ec = spec->selftest? GPG_ERR_DIGEST_ALGO : GPG_ERR_NOT_IMPLEMENTED; if (report) report ("digest", algo, "module", (spec && !spec->flags.disabled)? "no selftest available" : spec? "algorithm disabled" : "algorithm not found"); } return gpg_error (ec); } diff --git a/cipher/primegen.c b/cipher/primegen.c index 645b0f82..9f6ec705 100644 --- a/cipher/primegen.c +++ b/cipher/primegen.c @@ -1,1863 +1,1849 @@ /* primegen.c - prime number generator * Copyright (C) 1998, 2000, 2001, 2002, 2003 * 2004, 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" -#include "ath.h" static gcry_mpi_t gen_prime (unsigned int nbits, int secret, int randomlevel, int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg); static int check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds, gcry_prime_check_func_t cb_func, void *cb_arg ); static int is_prime (gcry_mpi_t n, int steps, unsigned int *count); static void m_out_of_n( char *array, int m, int n ); static void (*progress_cb) (void *,const char*,int,int, int ); static void *progress_cb_data; /* Note: 2 is not included because it can be tested more easily by looking at bit 0. The last entry in this list is marked by a zero */ static ushort small_prime_numbers[] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 0 }; static int no_of_small_prime_numbers = DIM (small_prime_numbers) - 1; /* An object and a list to build up a global pool of primes. See save_pool_prime and get_pool_prime. */ struct primepool_s { struct primepool_s *next; gcry_mpi_t prime; /* If this is NULL the entry is not used. */ unsigned int nbits; gcry_random_level_t randomlevel; }; struct primepool_s *primepool; /* Mutex used to protect access to the primepool. */ -static ath_mutex_t primepool_lock; +GPGRT_LOCK_DEFINE (primepool_lock); gcry_err_code_t _gcry_primegen_init (void) { - gcry_err_code_t ec; - - ec = ath_mutex_init (&primepool_lock); - if (ec) - return gpg_err_code_from_errno (ec); - return ec; + /* This function was formerly used to initialize the primepool + Mutex. This has been replace by a static initialization. */ + return 0; } /* Save PRIME which has been generated at RANDOMLEVEL for later use. Needs to be called while primepool_lock is being hold. Note that PRIME should be considered released after calling this function. */ static void save_pool_prime (gcry_mpi_t prime, gcry_random_level_t randomlevel) { struct primepool_s *item, *item2; size_t n; for (n=0, item = primepool; item; item = item->next, n++) if (!item->prime) break; if (!item && n > 100) { /* Remove some of the entries. Our strategy is removing the last third from the list. */ int i; for (i=0, item2 = primepool; item2; item2 = item2->next) { if (i >= n/3*2) { _gcry_mpi_release (item2->prime); item2->prime = NULL; if (!item) item = item2; } } } if (!item) { item = xtrycalloc (1, sizeof *item); if (!item) { /* Out of memory. Silently giving up. */ _gcry_mpi_release (prime); return; } item->next = primepool; primepool = item; } item->prime = prime; item->nbits = mpi_get_nbits (prime); item->randomlevel = randomlevel; } /* Return a prime for the prime pool or NULL if none has been found. The prime needs to match NBITS and randomlevel. This function needs to be called with the primepool_look is being hold. */ static gcry_mpi_t get_pool_prime (unsigned int nbits, gcry_random_level_t randomlevel) { struct primepool_s *item; for (item = primepool; item; item = item->next) if (item->prime && item->nbits == nbits && item->randomlevel == randomlevel) { gcry_mpi_t prime = item->prime; item->prime = NULL; gcry_assert (nbits == mpi_get_nbits (prime)); return prime; } return NULL; } void _gcry_register_primegen_progress ( void (*cb)(void *,const char*,int,int,int), void *cb_data ) { progress_cb = cb; progress_cb_data = cb_data; } static void progress( int c ) { if ( progress_cb ) progress_cb ( progress_cb_data, "primegen", c, 0, 0 ); } /**************** * Generate a prime number (stored in secure memory) */ gcry_mpi_t _gcry_generate_secret_prime (unsigned int nbits, gcry_random_level_t random_level, int (*extra_check)(void*, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime; prime = gen_prime (nbits, 1, random_level, extra_check, extra_check_arg); progress('\n'); return prime; } /* Generate a prime number which may be public, i.e. not allocated in secure memory. */ gcry_mpi_t _gcry_generate_public_prime (unsigned int nbits, gcry_random_level_t random_level, int (*extra_check)(void*, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime; prime = gen_prime (nbits, 0, random_level, extra_check, extra_check_arg); progress('\n'); return prime; } /* Core prime generation function. The algorithm used to generate practically save primes is due to Lim and Lee as described in the CRYPTO '97 proceedings (ISBN3540633847) page 260. NEED_Q_FACTOR: If true make sure that at least one factor is of size qbits. This is for example required for DSA. PRIME_GENERATED: Adresss of a variable where the resulting prime number will be stored. PBITS: Requested size of the prime number. At least 48. QBITS: One factor of the prime needs to be of this size. Maybe 0 if this is not required. See also MODE. G: If not NULL an MPI which will receive a generator for the prime for use with Elgamal. RET_FACTORS: if not NULL, an array with all factors are stored at that address. ALL_FACTORS: If set to true all factors of prime-1 are returned. RANDOMLEVEL: How strong should the random numers be. FLAGS: Prime generation bit flags. Currently supported: GCRY_PRIME_FLAG_SECRET - The prime needs to be kept secret. CB_FUNC, CB_ARG: Callback to be used for extra checks. */ static gcry_err_code_t prime_generate_internal (int need_q_factor, gcry_mpi_t *prime_generated, unsigned int pbits, unsigned int qbits, gcry_mpi_t g, gcry_mpi_t **ret_factors, gcry_random_level_t randomlevel, unsigned int flags, int all_factors, gcry_prime_check_func_t cb_func, void *cb_arg) { gcry_err_code_t err = 0; gcry_mpi_t *factors_new = NULL; /* Factors to return to the caller. */ gcry_mpi_t *factors = NULL; /* Current factors. */ gcry_random_level_t poolrandomlevel; /* Random level used for pool primes. */ gcry_mpi_t *pool = NULL; /* Pool of primes. */ int *pool_in_use = NULL; /* Array with currently used POOL elements. */ unsigned char *perms = NULL; /* Permutations of POOL. */ gcry_mpi_t q_factor = NULL; /* Used if QBITS is non-zero. */ unsigned int fbits = 0; /* Length of prime factors. */ unsigned int n = 0; /* Number of factors. */ unsigned int m = 0; /* Number of primes in pool. */ gcry_mpi_t q = NULL; /* First prime factor. */ gcry_mpi_t prime = NULL; /* Prime candidate. */ unsigned int nprime = 0; /* Bits of PRIME. */ unsigned int req_qbits; /* The original QBITS value. */ gcry_mpi_t val_2; /* For check_prime(). */ int is_locked = 0; /* Flag to help unlocking the primepool. */ unsigned int is_secret = (flags & GCRY_PRIME_FLAG_SECRET); unsigned int count1 = 0, count2 = 0; unsigned int i = 0, j = 0; if (pbits < 48) return GPG_ERR_INV_ARG; /* We won't use a too strong random elvel for the pooled subprimes. */ poolrandomlevel = (randomlevel > GCRY_STRONG_RANDOM? GCRY_STRONG_RANDOM : randomlevel); /* If QBITS is not given, assume a reasonable value. */ if (!qbits) qbits = pbits / 3; req_qbits = qbits; /* Find number of needed prime factors N. */ for (n = 1; (pbits - qbits - 1) / n >= qbits; n++) ; n--; val_2 = mpi_alloc_set_ui (2); if ((! n) || ((need_q_factor) && (n < 2))) { err = GPG_ERR_INV_ARG; goto leave; } if (need_q_factor) { n--; /* Need one factor less because we want a specific Q-FACTOR. */ fbits = (pbits - 2 * req_qbits -1) / n; qbits = pbits - req_qbits - n * fbits; } else { fbits = (pbits - req_qbits -1) / n; qbits = pbits - n * fbits; } if (DBG_CIPHER) log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n", pbits, req_qbits, qbits, fbits, n); /* Allocate an integer to old the new prime. */ prime = mpi_new (pbits); /* Generate first prime factor. */ q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); /* Generate a specific Q-Factor if requested. */ if (need_q_factor) q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL); /* Allocate an array to hold all factors + 2 for later usage. */ factors = xtrycalloc (n + 2, sizeof (*factors)); if (!factors) { err = gpg_err_code_from_errno (errno); goto leave; } /* Allocate an array to track pool usage. */ pool_in_use = xtrymalloc (n * sizeof *pool_in_use); if (!pool_in_use) { err = gpg_err_code_from_errno (errno); goto leave; } for (i=0; i < n; i++) pool_in_use[i] = -1; /* Make a pool of 3n+5 primes (this is an arbitrary value). We require at least 30 primes for are useful selection process. Fixme: We need to research the best formula for sizing the pool. */ m = n * 3 + 5; if (need_q_factor) /* Need some more in this case. */ m += 5; if (m < 30) m = 30; pool = xtrycalloc (m , sizeof (*pool)); if (! pool) { err = gpg_err_code_from_errno (errno); goto leave; } /* Permutate over the pool of primes until we find a prime of the requested length. */ do { next_try: for (i=0; i < n; i++) pool_in_use[i] = -1; if (!perms) { /* Allocate new primes. This is done right at the beginning of the loop and if we have later run out of primes. */ for (i = 0; i < m; i++) { mpi_free (pool[i]); pool[i] = NULL; } /* Init m_out_of_n(). */ perms = xtrycalloc (1, m); if (!perms) { err = gpg_err_code_from_errno (errno); goto leave; } - if (ath_mutex_lock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + err = gpgrt_lock_lock (&primepool_lock); + if (err) + goto leave; is_locked = 1; + for (i = 0; i < n; i++) { perms[i] = 1; /* At a maximum we use strong random for the factors. This saves us a lot of entropy. Given that Q and possible Q-factor are also used in the final prime this should be acceptable. We also don't allocate in secure memory to save on that scare resource too. If Q has been allocated in secure memory, the final prime will be saved there anyway. This is because our MPI routines take care of that. GnuPG has worked this way ever since. */ pool[i] = NULL; if (is_locked) { pool[i] = get_pool_prime (fbits, poolrandomlevel); if (!pool[i]) { - if (ath_mutex_unlock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + err = gpgrt_lock_unlock (&primepool_lock); + if (err) + goto leave; is_locked = 0; } } if (!pool[i]) pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL); pool_in_use[i] = i; factors[i] = pool[i]; } - if (is_locked && ath_mutex_unlock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + + if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock))) + goto leave; is_locked = 0; } else { /* Get next permutation. */ m_out_of_n ( (char*)perms, n, m); - if (ath_mutex_lock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + + if ((err = gpgrt_lock_lock (&primepool_lock))) + goto leave; is_locked = 1; + for (i = j = 0; (i < m) && (j < n); i++) if (perms[i]) { /* If the subprime has not yet beed generated do it now. */ if (!pool[i] && is_locked) { pool[i] = get_pool_prime (fbits, poolrandomlevel); if (!pool[i]) { - if (ath_mutex_unlock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + if ((err = gpgrt_lock_unlock (&primepool_lock))) + goto leave; is_locked = 0; } } if (!pool[i]) pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL); pool_in_use[j] = i; factors[j++] = pool[i]; } - if (is_locked && ath_mutex_unlock (&primepool_lock)) - { - err = GPG_ERR_INTERNAL; - goto leave; - } + + if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock))) + goto leave; is_locked = 0; + if (i == n) { /* Ran out of permutations: Allocate new primes. */ xfree (perms); perms = NULL; progress ('!'); goto next_try; } } /* Generate next prime candidate: p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1. */ mpi_set (prime, q); mpi_mul_ui (prime, prime, 2); if (need_q_factor) mpi_mul (prime, prime, q_factor); for(i = 0; i < n; i++) mpi_mul (prime, prime, factors[i]); mpi_add_ui (prime, prime, 1); nprime = mpi_get_nbits (prime); if (nprime < pbits) { if (++count1 > 20) { count1 = 0; qbits++; progress('>'); mpi_free (q); q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); goto next_try; } } else count1 = 0; if (nprime > pbits) { if (++count2 > 20) { count2 = 0; qbits--; progress('<'); mpi_free (q); q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); goto next_try; } } else count2 = 0; } while (! ((nprime == pbits) && check_prime (prime, val_2, 5, cb_func, cb_arg))); if (DBG_CIPHER) { progress ('\n'); log_mpidump ("prime ", prime); log_mpidump ("factor q", q); if (need_q_factor) log_mpidump ("factor q0", q_factor); for (i = 0; i < n; i++) log_mpidump ("factor pi", factors[i]); log_debug ("bit sizes: prime=%u, q=%u", mpi_get_nbits (prime), mpi_get_nbits (q)); if (need_q_factor) log_printf (", q0=%u", mpi_get_nbits (q_factor)); for (i = 0; i < n; i++) log_printf (", p%d=%u", i, mpi_get_nbits (factors[i])); log_printf ("\n"); } if (ret_factors) { /* Caller wants the factors. */ factors_new = xtrycalloc (n + 4, sizeof (*factors_new)); if (! factors_new) { err = gpg_err_code_from_errno (errno); goto leave; } if (all_factors) { i = 0; factors_new[i++] = mpi_set_ui (NULL, 2); factors_new[i++] = mpi_copy (q); if (need_q_factor) factors_new[i++] = mpi_copy (q_factor); for(j=0; j < n; j++) factors_new[i++] = mpi_copy (factors[j]); } else { i = 0; if (need_q_factor) { factors_new[i++] = mpi_copy (q_factor); for (; i <= n; i++) factors_new[i] = mpi_copy (factors[i]); } else for (; i < n; i++ ) factors_new[i] = mpi_copy (factors[i]); } } if (g) { /* Create a generator (start with 3). */ gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t b = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t pmin1 = mpi_alloc (mpi_get_nlimbs (prime)); if (need_q_factor) err = GPG_ERR_NOT_IMPLEMENTED; else { factors[n] = q; factors[n + 1] = mpi_alloc_set_ui (2); mpi_sub_ui (pmin1, prime, 1); mpi_set_ui (g, 2); do { mpi_add_ui (g, g, 1); if (DBG_CIPHER) log_printmpi ("checking g", g); else progress('^'); for (i = 0; i < n + 2; i++) { mpi_fdiv_q (tmp, pmin1, factors[i]); /* No mpi_pow(), but it is okay to use this with mod prime. */ mpi_powm (b, g, tmp, prime); if (! mpi_cmp_ui (b, 1)) break; } if (DBG_CIPHER) progress('\n'); } while (i < n + 2); mpi_free (factors[n+1]); mpi_free (tmp); mpi_free (b); mpi_free (pmin1); } } if (! DBG_CIPHER) progress ('\n'); leave: if (pool) { - is_locked = !ath_mutex_lock (&primepool_lock); + is_locked = !gpgrt_lock_lock (&primepool_lock); for(i = 0; i < m; i++) { if (pool[i]) { for (j=0; j < n; j++) if (pool_in_use[j] == i) break; if (j == n && is_locked) { /* This pooled subprime has not been used. */ save_pool_prime (pool[i], poolrandomlevel); } else mpi_free (pool[i]); } } - if (is_locked && ath_mutex_unlock (&primepool_lock)) - err = GPG_ERR_INTERNAL; + if (is_locked) + err = gpgrt_lock_unlock (&primepool_lock); is_locked = 0; xfree (pool); } xfree (pool_in_use); if (factors) xfree (factors); /* Factors are shallow copies. */ if (perms) xfree (perms); mpi_free (val_2); mpi_free (q); mpi_free (q_factor); if (! err) { *prime_generated = prime; if (ret_factors) *ret_factors = factors_new; } else { if (factors_new) { for (i = 0; factors_new[i]; i++) mpi_free (factors_new[i]); xfree (factors_new); } mpi_free (prime); } return err; } /* Generate a prime used for discrete logarithm algorithms; i.e. this prime will be public and no strong random is required. */ gcry_mpi_t _gcry_generate_elg_prime (int mode, unsigned pbits, unsigned qbits, gcry_mpi_t g, gcry_mpi_t **ret_factors) { gcry_mpi_t prime = NULL; if (prime_generate_internal ((mode == 1), &prime, pbits, qbits, g, ret_factors, GCRY_WEAK_RANDOM, 0, 0, NULL, NULL)) prime = NULL; /* (Should be NULL in the error case anyway.) */ return prime; } static gcry_mpi_t gen_prime (unsigned int nbits, int secret, int randomlevel, int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime, ptest, pminus1, val_2, val_3, result; int i; unsigned int x, step; unsigned int count1, count2; int *mods; /* if ( DBG_CIPHER ) */ /* log_debug ("generate a prime of %u bits ", nbits ); */ if (nbits < 16) log_fatal ("can't generate a prime with less than %d bits\n", 16); mods = xmalloc (no_of_small_prime_numbers * sizeof *mods); /* Make nbits fit into gcry_mpi_t implementation. */ val_2 = mpi_alloc_set_ui( 2 ); val_3 = mpi_alloc_set_ui( 3); prime = secret? mpi_snew (nbits): mpi_new (nbits); result = mpi_alloc_like( prime ); pminus1= mpi_alloc_like( prime ); ptest = mpi_alloc_like( prime ); count1 = count2 = 0; for (;;) { /* try forvever */ int dotcount=0; /* generate a random number */ _gcry_mpi_randomize( prime, nbits, randomlevel ); /* Set high order bit to 1, set low order bit to 1. If we are generating a secret prime we are most probably doing that for RSA, to make sure that the modulus does have the requested key size we set the 2 high order bits. */ mpi_set_highbit (prime, nbits-1); if (secret) mpi_set_bit (prime, nbits-2); mpi_set_bit(prime, 0); /* Calculate all remainders. */ for (i=0; (x = small_prime_numbers[i]); i++ ) mods[i] = mpi_fdiv_r_ui(NULL, prime, x); /* Now try some primes starting with prime. */ for(step=0; step < 20000; step += 2 ) { /* Check against all the small primes we have in mods. */ count1++; for (i=0; (x = small_prime_numbers[i]); i++ ) { while ( mods[i] + step >= x ) mods[i] -= x; if ( !(mods[i] + step) ) break; } if ( x ) continue; /* Found a multiple of an already known prime. */ mpi_add_ui( ptest, prime, step ); /* Do a fast Fermat test now. */ count2++; mpi_sub_ui( pminus1, ptest, 1); mpi_powm( result, val_2, pminus1, ptest ); if ( !mpi_cmp_ui( result, 1 ) ) { /* Not composite, perform stronger tests */ if (is_prime(ptest, 5, &count2 )) { if (!mpi_test_bit( ptest, nbits-1-secret )) { progress('\n'); log_debug ("overflow in prime generation\n"); break; /* Stop loop, continue with a new prime. */ } if (extra_check && extra_check (extra_check_arg, ptest)) { /* The extra check told us that this prime is not of the caller's taste. */ progress ('/'); } else { /* Got it. */ mpi_free(val_2); mpi_free(val_3); mpi_free(result); mpi_free(pminus1); mpi_free(prime); xfree(mods); return ptest; } } } if (++dotcount == 10 ) { progress('.'); dotcount = 0; } } progress(':'); /* restart with a new random value */ } } /**************** * Returns: true if this may be a prime * RM_ROUNDS gives the number of Rabin-Miller tests to run. */ static int check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds, gcry_prime_check_func_t cb_func, void *cb_arg) { int i; unsigned int x; unsigned int count=0; /* Check against small primes. */ for (i=0; (x = small_prime_numbers[i]); i++ ) { if ( mpi_divisible_ui( prime, x ) ) return 0; } /* A quick Fermat test. */ { gcry_mpi_t result = mpi_alloc_like( prime ); gcry_mpi_t pminus1 = mpi_alloc_like( prime ); mpi_sub_ui( pminus1, prime, 1); mpi_powm( result, val_2, pminus1, prime ); mpi_free( pminus1 ); if ( mpi_cmp_ui( result, 1 ) ) { /* Is composite. */ mpi_free( result ); progress('.'); return 0; } mpi_free( result ); } if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_MAYBE_PRIME, prime)) { /* Perform stronger tests. */ if ( is_prime( prime, rm_rounds, &count ) ) { if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_GOT_PRIME, prime)) return 1; /* Probably a prime. */ } } progress('.'); return 0; } /* * Return true if n is probably a prime */ static int is_prime (gcry_mpi_t n, int steps, unsigned int *count) { gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t y = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t z = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t nminus1 = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t a2 = mpi_alloc_set_ui( 2 ); gcry_mpi_t q; unsigned i, j, k; int rc = 0; unsigned nbits = mpi_get_nbits( n ); if (steps < 5) /* Make sure that we do at least 5 rounds. */ steps = 5; mpi_sub_ui( nminus1, n, 1 ); /* Find q and k, so that n = 1 + 2^k * q . */ q = mpi_copy ( nminus1 ); k = mpi_trailing_zeros ( q ); mpi_tdiv_q_2exp (q, q, k); for (i=0 ; i < steps; i++ ) { ++*count; if( !i ) { mpi_set_ui( x, 2 ); } else { _gcry_mpi_randomize( x, nbits, GCRY_WEAK_RANDOM ); /* Make sure that the number is smaller than the prime and keep the randomness of the high bit. */ if ( mpi_test_bit ( x, nbits-2) ) { mpi_set_highbit ( x, nbits-2); /* Clear all higher bits. */ } else { mpi_set_highbit( x, nbits-2 ); mpi_clear_bit( x, nbits-2 ); } gcry_assert (mpi_cmp (x, nminus1) < 0 && mpi_cmp_ui (x, 1) > 0); } mpi_powm ( y, x, q, n); if ( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) ) { for ( j=1; j < k && mpi_cmp( y, nminus1 ); j++ ) { mpi_powm(y, y, a2, n); if( !mpi_cmp_ui( y, 1 ) ) goto leave; /* Not a prime. */ } if (mpi_cmp( y, nminus1 ) ) goto leave; /* Not a prime. */ } progress('+'); } rc = 1; /* May be a prime. */ leave: mpi_free( x ); mpi_free( y ); mpi_free( z ); mpi_free( nminus1 ); mpi_free( q ); mpi_free( a2 ); return rc; } /* Given ARRAY of size N with M elements set to true produce a modified array with the next permutation of M elements. Note, that ARRAY is used in a one-bit-per-byte approach. To detected the last permutation it is useful to initialize the array with the first M element set to true and use this test: m_out_of_n (array, m, n); for (i = j = 0; i < n && j < m; i++) if (array[i]) j++; if (j == m) goto ready; This code is based on the algorithm 452 from the "Collected Algorithms From ACM, Volume II" by C. N. Liu and D. T. Tang. */ static void m_out_of_n ( char *array, int m, int n ) { int i=0, i1=0, j=0, jp=0, j1=0, k1=0, k2=0; if( !m || m >= n ) return; /* Need to handle this simple case separately. */ if( m == 1 ) { for (i=0; i < n; i++ ) { if ( array[i] ) { array[i++] = 0; if( i >= n ) i = 0; array[i] = 1; return; } } BUG(); } for (j=1; j < n; j++ ) { if ( array[n-1] == array[n-j-1]) continue; j1 = j; break; } if ( (m & 1) ) { /* M is odd. */ if( array[n-1] ) { if( j1 & 1 ) { k1 = n - j1; k2 = k1+2; if( k2 > n ) k2 = n; goto leave; } goto scan; } k2 = n - j1 - 1; if( k2 == 0 ) { k1 = i; k2 = n - j1; } else if( array[k2] && array[k2-1] ) k1 = n; else k1 = k2 + 1; } else { /* M is even. */ if( !array[n-1] ) { k1 = n - j1; k2 = k1 + 1; goto leave; } if( !(j1 & 1) ) { k1 = n - j1; k2 = k1+2; if( k2 > n ) k2 = n; goto leave; } scan: jp = n - j1 - 1; for (i=1; i <= jp; i++ ) { i1 = jp + 2 - i; if( array[i1-1] ) { if( array[i1-2] ) { k1 = i1 - 1; k2 = n - j1; } else { k1 = i1 - 1; k2 = n + 1 - j1; } goto leave; } } k1 = 1; k2 = n + 1 - m; } leave: /* Now complement the two selected bits. */ array[k1-1] = !array[k1-1]; array[k2-1] = !array[k2-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_err_code_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) { gcry_err_code_t rc = 0; gcry_mpi_t *factors_generated = NULL; gcry_mpi_t prime_generated = NULL; unsigned int mode = 0; if (!prime) return GPG_ERR_INV_ARG; *prime = NULL; if (flags & GCRY_PRIME_FLAG_SPECIAL_FACTOR) mode = 1; /* Generate. */ rc = prime_generate_internal ((mode==1), &prime_generated, prime_bits, factor_bits, NULL, factors? &factors_generated : NULL, random_level, flags, 1, cb_func, cb_arg); if (!rc && cb_func) { /* Additional check. */ if ( !cb_func (cb_arg, GCRY_PRIME_CHECK_AT_FINISH, prime_generated)) { /* Failed, deallocate resources. */ unsigned int i; mpi_free (prime_generated); if (factors) { for (i = 0; factors_generated[i]; i++) mpi_free (factors_generated[i]); xfree (factors_generated); } rc = GPG_ERR_GENERAL; } } if (!rc) { if (factors) *factors = factors_generated; *prime = prime_generated; } return rc; } /* Check whether the number X is prime. */ gcry_err_code_t _gcry_prime_check (gcry_mpi_t x, unsigned int flags) { gcry_err_code_t rc = 0; gcry_mpi_t val_2 = mpi_alloc_set_ui (2); /* Used by the Fermat test. */ (void)flags; /* We use 64 rounds because the prime we are going to test is not guaranteed to be a random one. */ if (! check_prime (x, val_2, 64, NULL, NULL)) rc = GPG_ERR_NO_PRIME; mpi_free (val_2); return rc; } /* 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 s atart for the search. Returns 0 on success.*/ gcry_err_code_t _gcry_prime_group_generator (gcry_mpi_t *r_g, gcry_mpi_t prime, gcry_mpi_t *factors, gcry_mpi_t start_g) { gcry_mpi_t tmp = mpi_new (0); gcry_mpi_t b = mpi_new (0); gcry_mpi_t pmin1 = mpi_new (0); gcry_mpi_t g = start_g? mpi_copy (start_g) : mpi_set_ui (NULL, 3); int first = 1; int i, n; if (!factors || !r_g || !prime) return GPG_ERR_INV_ARG; *r_g = NULL; for (n=0; factors[n]; n++) ; if (n < 2) return GPG_ERR_INV_ARG; /* Extra sanity check - usually disabled. */ /* mpi_set (tmp, factors[0]); */ /* for(i = 1; i < n; i++) */ /* mpi_mul (tmp, tmp, factors[i]); */ /* mpi_add_ui (tmp, tmp, 1); */ /* if (mpi_cmp (prime, tmp)) */ /* return gpg_error (GPG_ERR_INV_ARG); */ mpi_sub_ui (pmin1, prime, 1); do { if (first) first = 0; else mpi_add_ui (g, g, 1); if (DBG_CIPHER) log_printmpi ("checking g", g); else progress('^'); for (i = 0; i < n; i++) { mpi_fdiv_q (tmp, pmin1, factors[i]); mpi_powm (b, g, tmp, prime); if (! mpi_cmp_ui (b, 1)) break; } if (DBG_CIPHER) progress('\n'); } while (i < n); _gcry_mpi_release (tmp); _gcry_mpi_release (b); _gcry_mpi_release (pmin1); *r_g = g; return 0; } /* Convenience function to release the factors array. */ void _gcry_prime_release_factors (gcry_mpi_t *factors) { if (factors) { int i; for (i=0; factors[i]; i++) mpi_free (factors[i]); xfree (factors); } } /* Helper for _gcry_derive_x931_prime. */ static gcry_mpi_t find_x931_prime (const gcry_mpi_t pfirst) { gcry_mpi_t val_2 = mpi_alloc_set_ui (2); gcry_mpi_t prime; prime = mpi_copy (pfirst); /* If P is even add 1. */ mpi_set_bit (prime, 0); /* We use 64 Rabin-Miller rounds which is better and thus sufficient. We do not have a Lucas test implementaion thus we can't do it in the X9.31 preferred way of running a few Rabin-Miller followed by one Lucas test. */ while ( !check_prime (prime, val_2, 64, NULL, NULL) ) mpi_add_ui (prime, prime, 2); mpi_free (val_2); return prime; } /* Generate a prime using the algorithm from X9.31 appendix B.4. This function requires that the provided public exponent E is odd. XP, XP1 and XP2 are the seed values. All values are mandatory. On success the prime is returned. If R_P1 or R_P2 are given the internal values P1 and P2 are saved at these addresses. On error NULL is returned. */ gcry_mpi_t _gcry_derive_x931_prime (const gcry_mpi_t xp, const gcry_mpi_t xp1, const gcry_mpi_t xp2, const gcry_mpi_t e, gcry_mpi_t *r_p1, gcry_mpi_t *r_p2) { gcry_mpi_t p1, p2, p1p2, yp0; if (!xp || !xp1 || !xp2) return NULL; if (!e || !mpi_test_bit (e, 0)) return NULL; /* We support only odd values for E. */ p1 = find_x931_prime (xp1); p2 = find_x931_prime (xp2); p1p2 = mpi_alloc_like (xp); mpi_mul (p1p2, p1, p2); { gcry_mpi_t r1, tmp; /* r1 = (p2^{-1} mod p1)p2 - (p1^{-1} mod p2) */ tmp = mpi_alloc_like (p1); mpi_invm (tmp, p2, p1); mpi_mul (tmp, tmp, p2); r1 = tmp; tmp = mpi_alloc_like (p2); mpi_invm (tmp, p1, p2); mpi_mul (tmp, tmp, p1); mpi_sub (r1, r1, tmp); /* Fixup a negative value. */ if (mpi_has_sign (r1)) mpi_add (r1, r1, p1p2); /* yp0 = xp + (r1 - xp mod p1*p2) */ yp0 = tmp; tmp = NULL; mpi_subm (yp0, r1, xp, p1p2); mpi_add (yp0, yp0, xp); mpi_free (r1); /* Fixup a negative value. */ if (mpi_cmp (yp0, xp) < 0 ) mpi_add (yp0, yp0, p1p2); } /* yp0 is now the first integer greater than xp with p1 being a large prime factor of yp0-1 and p2 a large prime factor of yp0+1. */ /* Note that the first example from X9.31 (D.1.1) which uses (Xq1 #1A5CF72EE770DE50CB09ACCEA9#) (Xq2 #134E4CAA16D2350A21D775C404#) (Xq #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC325 6D29C2627479C086A699A49C4C9CEE7EF7BD1B34 321DE34A#)))) returns an yp0 of #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC4E3 BF20CB896EE37E098A906313271422162CB6C642 75C1201F# and not #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC2E6 C88FE299D52D78BE405A97E01FD71DD7819ECB91 FA85A076# as stated in the standard. This seems to be a bug in X9.31. */ { gcry_mpi_t val_2 = mpi_alloc_set_ui (2); gcry_mpi_t gcdtmp = mpi_alloc_like (yp0); int gcdres; mpi_sub_ui (p1p2, p1p2, 1); /* Adjust for loop body. */ mpi_sub_ui (yp0, yp0, 1); /* Ditto. */ for (;;) { gcdres = mpi_gcd (gcdtmp, e, yp0); mpi_add_ui (yp0, yp0, 1); if (!gcdres) progress ('/'); /* gcd (e, yp0-1) != 1 */ else if (check_prime (yp0, val_2, 64, NULL, NULL)) break; /* Found. */ /* We add p1p2-1 because yp0 is incremented after the gcd test. */ mpi_add (yp0, yp0, p1p2); } mpi_free (gcdtmp); mpi_free (val_2); } mpi_free (p1p2); progress('\n'); if (r_p1) *r_p1 = p1; else mpi_free (p1); if (r_p2) *r_p2 = p2; else mpi_free (p2); return yp0; } /* Generate the two prime used for DSA using the algorithm specified in FIPS 186-2. PBITS is the desired length of the prime P and a QBITS the length of the prime Q. If SEED is not supplied and SEEDLEN is 0 the function generates an appropriate SEED. On success the generated primes are stored at R_Q and R_P, the counter value is stored at R_COUNTER and the seed actually used for generation is stored at R_SEED and R_SEEDVALUE. */ gpg_err_code_t _gcry_generate_fips186_2_prime (unsigned int pbits, unsigned int qbits, const void *seed, size_t seedlen, gcry_mpi_t *r_q, gcry_mpi_t *r_p, int *r_counter, void **r_seed, size_t *r_seedlen) { gpg_err_code_t ec; unsigned char seed_help_buffer[160/8]; /* Used to hold a generated SEED. */ unsigned char *seed_plus; /* Malloced buffer to hold SEED+x. */ unsigned char digest[160/8]; /* Helper buffer for SHA-1 digest. */ gcry_mpi_t val_2 = NULL; /* Helper for the prime test. */ gcry_mpi_t tmpval = NULL; /* Helper variable. */ int i; unsigned char value_u[160/8]; int value_n, value_b, value_k; int counter; gcry_mpi_t value_w = NULL; gcry_mpi_t value_x = NULL; gcry_mpi_t prime_q = NULL; gcry_mpi_t prime_p = NULL; /* FIPS 186-2 allows only for 1024/160 bit. */ if (pbits != 1024 || qbits != 160) return GPG_ERR_INV_KEYLEN; if (!seed && !seedlen) ; /* No seed value given: We are asked to generate it. */ else if (!seed || seedlen < qbits/8) return GPG_ERR_INV_ARG; /* Allocate a buffer to later compute SEED+some_increment. */ seed_plus = xtrymalloc (seedlen < 20? 20:seedlen); if (!seed_plus) { ec = gpg_err_code_from_syserror (); goto leave; } val_2 = mpi_alloc_set_ui (2); value_n = (pbits - 1) / qbits; value_b = (pbits - 1) - value_n * qbits; value_w = mpi_new (pbits); value_x = mpi_new (pbits); restart: /* Generate Q. */ for (;;) { /* Step 1: Generate a (new) seed unless one has been supplied. */ if (!seed) { seedlen = sizeof seed_help_buffer; _gcry_create_nonce (seed_help_buffer, seedlen); seed = seed_help_buffer; } /* Step 2: U = sha1(seed) ^ sha1((seed+1) mod 2^{qbits}) */ memcpy (seed_plus, seed, seedlen); for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (GCRY_MD_SHA1, value_u, seed, seedlen); _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen); for (i=0; i < sizeof value_u; i++) value_u[i] ^= digest[i]; /* Step 3: Form q from U */ _gcry_mpi_release (prime_q); prime_q = NULL; ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG, value_u, sizeof value_u, NULL); if (ec) goto leave; mpi_set_highbit (prime_q, qbits-1 ); mpi_set_bit (prime_q, 0); /* Step 4: Test whether Q is prime using 64 round of Rabin-Miller. */ if (check_prime (prime_q, val_2, 64, NULL, NULL)) break; /* Yes, Q is prime. */ /* Step 5. */ seed = NULL; /* Force a new seed at Step 1. */ } /* Step 6. Note that we do no use an explicit offset but increment SEED_PLUS accordingly. SEED_PLUS is currently SEED+1. */ counter = 0; /* Generate P. */ prime_p = mpi_new (pbits); for (;;) { /* Step 7: For k = 0,...n let V_k = sha1(seed+offset+k) mod 2^{qbits} Step 8: W = V_0 + V_1*2^160 + ... + V_{n-1}*2^{(n-1)*160} + (V_{n} mod 2^b)*2^{n*160} */ mpi_set_ui (value_w, 0); for (value_k=0; value_k <= value_n; value_k++) { /* There is no need to have an explicit offset variable: In the first round we shall have an offset of 2, this is achieved by using SEED_PLUS which is already at SEED+1, thus we just need to increment it once again. The requirement for the next round is to update offset by N, which we implictly did at the end of this loop, and then to add one; this one is the same as in the first round. */ for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen); _gcry_mpi_release (tmpval); tmpval = NULL; ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG, digest, sizeof digest, NULL); if (ec) goto leave; if (value_k == value_n) mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */ mpi_lshift (tmpval, tmpval, value_k*qbits); mpi_add (value_w, value_w, tmpval); } /* Step 8 continued: X = W + 2^{L-1} */ mpi_set_ui (value_x, 0); mpi_set_highbit (value_x, pbits-1); mpi_add (value_x, value_x, value_w); /* Step 9: c = X mod 2q, p = X - (c - 1) */ mpi_mul_2exp (tmpval, prime_q, 1); mpi_mod (tmpval, value_x, tmpval); mpi_sub_ui (tmpval, tmpval, 1); mpi_sub (prime_p, value_x, tmpval); /* Step 10: If p < 2^{L-1} skip the primality test. */ /* Step 11 and 12: Primality test. */ if (mpi_get_nbits (prime_p) >= pbits-1 && check_prime (prime_p, val_2, 64, NULL, NULL) ) break; /* Yes, P is prime, continue with Step 15. */ /* Step 13: counter = counter + 1, offset = offset + n + 1. */ counter++; /* Step 14: If counter >= 2^12 goto Step 1. */ if (counter >= 4096) goto restart; } /* Step 15: Save p, q, counter and seed. */ /* log_debug ("fips186-2 pbits p=%u q=%u counter=%d\n", */ /* mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); */ /* log_printhex("fips186-2 seed:", seed, seedlen); */ /* log_mpidump ("fips186-2 prime p", prime_p); */ /* log_mpidump ("fips186-2 prime q", prime_q); */ if (r_q) { *r_q = prime_q; prime_q = NULL; } if (r_p) { *r_p = prime_p; prime_p = NULL; } if (r_counter) *r_counter = counter; if (r_seed && r_seedlen) { memcpy (seed_plus, seed, seedlen); *r_seed = seed_plus; seed_plus = NULL; *r_seedlen = seedlen; } leave: _gcry_mpi_release (tmpval); _gcry_mpi_release (value_x); _gcry_mpi_release (value_w); _gcry_mpi_release (prime_p); _gcry_mpi_release (prime_q); xfree (seed_plus); _gcry_mpi_release (val_2); return ec; } /* WARNING: The code below has not yet been tested! However, it is not yet used. We need to wait for FIPS 186-3 final and for test vectors. Generate the two prime used for DSA using the algorithm specified in FIPS 186-3, A.1.1.2. PBITS is the desired length of the prime P and a QBITS the length of the prime Q. If SEED is not supplied and SEEDLEN is 0 the function generates an appropriate SEED. On success the generated primes are stored at R_Q and R_P, the counter value is stored at R_COUNTER and the seed actually used for generation is stored at R_SEED and R_SEEDVALUE. The hash algorithm used is stored at R_HASHALGO. Note that this function is very similar to the fips186_2 code. Due to the minor differences, other buffer sizes and for documentarion, we use a separate function. */ gpg_err_code_t _gcry_generate_fips186_3_prime (unsigned int pbits, unsigned int qbits, const void *seed, size_t seedlen, gcry_mpi_t *r_q, gcry_mpi_t *r_p, int *r_counter, void **r_seed, size_t *r_seedlen, int *r_hashalgo) { gpg_err_code_t ec; unsigned char seed_help_buffer[256/8]; /* Used to hold a generated SEED. */ unsigned char *seed_plus; /* Malloced buffer to hold SEED+x. */ unsigned char digest[256/8]; /* Helper buffer for SHA-1 digest. */ gcry_mpi_t val_2 = NULL; /* Helper for the prime test. */ gcry_mpi_t tmpval = NULL; /* Helper variable. */ int hashalgo; /* The id of the Approved Hash Function. */ int i; unsigned char value_u[256/8]; int value_n, value_b, value_j; int counter; gcry_mpi_t value_w = NULL; gcry_mpi_t value_x = NULL; gcry_mpi_t prime_q = NULL; gcry_mpi_t prime_p = NULL; gcry_assert (sizeof seed_help_buffer == sizeof digest && sizeof seed_help_buffer == sizeof value_u); /* Step 1: Check the requested prime lengths. */ /* Note that due to the size of our buffers QBITS is limited to 256. */ if (pbits == 1024 && qbits == 160) hashalgo = GCRY_MD_SHA1; else if (pbits == 2048 && qbits == 224) hashalgo = GCRY_MD_SHA224; else if (pbits == 2048 && qbits == 256) hashalgo = GCRY_MD_SHA256; else if (pbits == 3072 && qbits == 256) hashalgo = GCRY_MD_SHA256; else return GPG_ERR_INV_KEYLEN; /* Also check that the hash algorithm is available. */ ec = _gcry_md_test_algo (hashalgo); if (ec) return ec; gcry_assert (qbits/8 <= sizeof digest); gcry_assert (_gcry_md_get_algo_dlen (hashalgo) == qbits/8); /* Step 2: Check seedlen. */ if (!seed && !seedlen) ; /* No seed value given: We are asked to generate it. */ else if (!seed || seedlen < qbits/8) return GPG_ERR_INV_ARG; /* Allocate a buffer to later compute SEED+some_increment and a few helper variables. */ seed_plus = xtrymalloc (seedlen < sizeof seed_help_buffer? sizeof seed_help_buffer : seedlen); if (!seed_plus) { ec = gpg_err_code_from_syserror (); goto leave; } val_2 = mpi_alloc_set_ui (2); value_w = mpi_new (pbits); value_x = mpi_new (pbits); /* Step 3: n = \lceil L / outlen \rceil - 1 */ value_n = (pbits + qbits - 1) / qbits - 1; /* Step 4: b = L - 1 - (n * outlen) */ value_b = pbits - 1 - (value_n * qbits); restart: /* Generate Q. */ for (;;) { /* Step 5: Generate a (new) seed unless one has been supplied. */ if (!seed) { seedlen = qbits/8; gcry_assert (seedlen <= sizeof seed_help_buffer); _gcry_create_nonce (seed_help_buffer, seedlen); seed = seed_help_buffer; } /* Step 6: U = hash(seed) */ _gcry_md_hash_buffer (hashalgo, value_u, seed, seedlen); /* Step 7: q = 2^{N-1} + U + 1 - (U mod 2) */ if ( !(value_u[qbits/8-1] & 0x01) ) { for (i=qbits/8-1; i >= 0; i--) { value_u[i]++; if (value_u[i]) break; } } _gcry_mpi_release (prime_q); prime_q = NULL; ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG, value_u, sizeof value_u, NULL); if (ec) goto leave; mpi_set_highbit (prime_q, qbits-1 ); /* Step 8: Test whether Q is prime using 64 round of Rabin-Miller. According to table C.1 this is sufficient for all supported prime sizes (i.e. up 3072/256). */ if (check_prime (prime_q, val_2, 64, NULL, NULL)) break; /* Yes, Q is prime. */ /* Step 8. */ seed = NULL; /* Force a new seed at Step 5. */ } /* Step 11. Note that we do no use an explicit offset but increment SEED_PLUS accordingly. */ memcpy (seed_plus, seed, seedlen); counter = 0; /* Generate P. */ prime_p = mpi_new (pbits); for (;;) { /* Step 11.1: For j = 0,...n let V_j = hash(seed+offset+j) Step 11.2: W = V_0 + V_1*2^outlen + ... + V_{n-1}*2^{(n-1)*outlen} + (V_{n} mod 2^b)*2^{n*outlen} */ mpi_set_ui (value_w, 0); for (value_j=0; value_j <= value_n; value_j++) { /* There is no need to have an explicit offset variable: In the first round we shall have an offset of 1 and a j of 0. This is achieved by incrementing SEED_PLUS here. For the next round offset is implicitly updated by using SEED_PLUS again. */ for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen); _gcry_mpi_release (tmpval); tmpval = NULL; ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG, digest, sizeof digest, NULL); if (ec) goto leave; if (value_j == value_n) mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */ mpi_lshift (tmpval, tmpval, value_j*qbits); mpi_add (value_w, value_w, tmpval); } /* Step 11.3: X = W + 2^{L-1} */ mpi_set_ui (value_x, 0); mpi_set_highbit (value_x, pbits-1); mpi_add (value_x, value_x, value_w); /* Step 11.4: c = X mod 2q */ mpi_mul_2exp (tmpval, prime_q, 1); mpi_mod (tmpval, value_x, tmpval); /* Step 11.5: p = X - (c - 1) */ mpi_sub_ui (tmpval, tmpval, 1); mpi_sub (prime_p, value_x, tmpval); /* Step 11.6: If p < 2^{L-1} skip the primality test. */ /* Step 11.7 and 11.8: Primality test. */ if (mpi_get_nbits (prime_p) >= pbits-1 && check_prime (prime_p, val_2, 64, NULL, NULL) ) break; /* Yes, P is prime, continue with Step 15. */ /* Step 11.9: counter = counter + 1, offset = offset + n + 1. If counter >= 4L goto Step 5. */ counter++; if (counter >= 4*pbits) goto restart; } /* Step 12: Save p, q, counter and seed. */ log_debug ("fips186-3 pbits p=%u q=%u counter=%d\n", mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); log_printhex ("fips186-3 seed", seed, seedlen); log_printmpi ("fips186-3 p", prime_p); log_printmpi ("fips186-3 q", prime_q); if (r_q) { *r_q = prime_q; prime_q = NULL; } if (r_p) { *r_p = prime_p; prime_p = NULL; } if (r_counter) *r_counter = counter; if (r_seed && r_seedlen) { memcpy (seed_plus, seed, seedlen); *r_seed = seed_plus; seed_plus = NULL; *r_seedlen = seedlen; } if (r_hashalgo) *r_hashalgo = hashalgo; leave: _gcry_mpi_release (tmpval); _gcry_mpi_release (value_x); _gcry_mpi_release (value_w); _gcry_mpi_release (prime_p); _gcry_mpi_release (prime_q); xfree (seed_plus); _gcry_mpi_release (val_2); return ec; } diff --git a/cipher/pubkey.c b/cipher/pubkey.c index d1303881..9aeacedb 100644 --- a/cipher/pubkey.c +++ b/cipher/pubkey.c @@ -1,962 +1,961 @@ /* pubkey.c - pubkey dispatcher * Copyright (C) 1998, 1999, 2000, 2002, 2003, 2005, * 2007, 2008, 2011 Free Software Foundation, Inc. * Copyright (C) 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 . */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" -#include "ath.h" #include "context.h" #include "pubkey-internal.h" /* This is the list of the public-key algorithms included in Libgcrypt. */ static gcry_pk_spec_t *pubkey_list[] = { #if USE_ECC &_gcry_pubkey_spec_ecc, #endif #if USE_RSA &_gcry_pubkey_spec_rsa, #endif #if USE_DSA &_gcry_pubkey_spec_dsa, #endif #if USE_ELGAMAL &_gcry_pubkey_spec_elg, #endif NULL }; static int map_algo (int algo) { switch (algo) { case GCRY_PK_ECDSA: case GCRY_PK_ECDH: return GCRY_PK_ECC; case GCRY_PK_ELG_E: return GCRY_PK_ELG; default: return algo; } } /* Return the spec structure for the public key algorithm ALGO. For an unknown algorithm NULL is returned. */ static gcry_pk_spec_t * spec_from_algo (int algo) { int idx; gcry_pk_spec_t *spec; algo = map_algo (algo); for (idx = 0; (spec = pubkey_list[idx]); idx++) if (algo == spec->algo) return spec; return NULL; } /* Return the spec structure for the public key algorithm with NAME. For an unknown name NULL is returned. */ static gcry_pk_spec_t * spec_from_name (const char *name) { gcry_pk_spec_t *spec; int idx; const char **aliases; for (idx=0; (spec = pubkey_list[idx]); idx++) { if (!stricmp (name, spec->name)) return spec; for (aliases = spec->aliases; *aliases; aliases++) if (!stricmp (name, *aliases)) return spec; } return NULL; } /* Given the s-expression SEXP with the first element be either * "private-key" or "public-key" return the spec structure for it. We * look through the list to find a list beginning with "private-key" * or "public-key" - the first one found is used. If WANT_PRIVATE is * set the function will only succeed if a private key has been given. * On success the spec is stored at R_SPEC. On error NULL is stored * at R_SPEC and an error code returned. If R_PARMS is not NULL and * the fucntion returns success, the parameter list below * "private-key" or "public-key" is stored there and the caller must * call gcry_sexp_release on it. */ static gcry_err_code_t spec_from_sexp (gcry_sexp_t sexp, int want_private, gcry_pk_spec_t **r_spec, gcry_sexp_t *r_parms) { gcry_sexp_t list, l2; char *name; gcry_pk_spec_t *spec; *r_spec = NULL; if (r_parms) *r_parms = NULL; /* Check that the first element is valid. If we are looking for a public key but a private key was supplied, we allow the use of the private key anyway. The rationale for this is that the private key is a superset of the public key. */ list = sexp_find_token (sexp, want_private? "private-key":"public-key", 0); if (!list && !want_private) list = sexp_find_token (sexp, "private-key", 0); if (!list) return GPG_ERR_INV_OBJ; /* Does not contain a key object. */ l2 = sexp_cadr (list); sexp_release (list); list = l2; name = sexp_nth_string (list, 0); if (!name) { sexp_release ( list ); return GPG_ERR_INV_OBJ; /* Invalid structure of object. */ } spec = spec_from_name (name); xfree (name); if (!spec) { sexp_release (list); return GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */ } *r_spec = spec; if (r_parms) *r_parms = list; else sexp_release (list); return 0; } /* Disable the use of the algorithm ALGO. This is not thread safe and should thus be called early. */ static void disable_pubkey_algo (int algo) { gcry_pk_spec_t *spec = spec_from_algo (algo); if (spec) spec->flags.disabled = 1; } /* * Map a string to the pubkey algo */ int _gcry_pk_map_name (const char *string) { gcry_pk_spec_t *spec; if (!string) return 0; spec = spec_from_name (string); if (!spec) return 0; if (spec->flags.disabled) return 0; return spec->algo; } /* 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 algo) { gcry_pk_spec_t *spec; spec = spec_from_algo (algo); if (spec) return spec->name; return "?"; } /**************** * A USE of 0 means: don't care. */ static gcry_err_code_t check_pubkey_algo (int algo, unsigned use) { gcry_err_code_t err = 0; gcry_pk_spec_t *spec; spec = spec_from_algo (algo); if (spec) { if (((use & GCRY_PK_USAGE_SIGN) && (! (spec->use & GCRY_PK_USAGE_SIGN))) || ((use & GCRY_PK_USAGE_ENCR) && (! (spec->use & GCRY_PK_USAGE_ENCR)))) err = GPG_ERR_WRONG_PUBKEY_ALGO; } else err = GPG_ERR_PUBKEY_ALGO; return err; } /**************** * Return the number of public key material numbers */ static int pubkey_get_npkey (int algo) { gcry_pk_spec_t *spec = spec_from_algo (algo); return spec? strlen (spec->elements_pkey) : 0; } /**************** * Return the number of secret key material numbers */ static int pubkey_get_nskey (int algo) { gcry_pk_spec_t *spec = spec_from_algo (algo); return spec? strlen (spec->elements_skey) : 0; } /**************** * Return the number of signature material numbers */ static int pubkey_get_nsig (int algo) { gcry_pk_spec_t *spec = spec_from_algo (algo); return spec? strlen (spec->elements_sig) : 0; } /**************** * Return the number of encryption material numbers */ static int pubkey_get_nenc (int algo) { gcry_pk_spec_t *spec = spec_from_algo (algo); return spec? strlen (spec->elements_enc) : 0; } /* Do a PK encrypt operation Caller has to provide a public key as the SEXP pkey and data as a SEXP with just one MPI in it. Alternatively S_DATA might be a complex S-Expression, similar to the one used for signature verification. This provides a flag which allows to handle PKCS#1 block type 2 padding. The function returns a sexp which may be passed to to pk_decrypt. Returns: 0 or an errorcode. s_data = See comment for _gcry_pk_util_data_to_mpi s_pkey = r_ciph = (enc-val ( ( ) ... ( ) )) */ gcry_err_code_t _gcry_pk_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t s_pkey) { gcry_err_code_t rc; gcry_pk_spec_t *spec; gcry_sexp_t keyparms; *r_ciph = NULL; rc = spec_from_sexp (s_pkey, 0, &spec, &keyparms); if (rc) goto leave; if (spec->encrypt) rc = spec->encrypt (r_ciph, s_data, keyparms); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (keyparms); return rc; } /* Do a PK decrypt operation Caller has to provide a secret key as the SEXP skey and data in a format as created by gcry_pk_encrypt. For historic reasons the function returns simply an MPI as an S-expression part; this is deprecated and the new method should be used which returns a real S-expressionl this is selected by adding at least an empty flags list to S_DATA. Returns: 0 or an errorcode. s_data = (enc-val [(flags [raw, pkcs1, oaep])] ( ( ) ... ( ) )) s_skey = r_plain= Either an incomplete S-expression without the parentheses or if the flags list is used (even if empty) a real S-expression: (value PLAIN). In raw mode (or no flags given) the returned value is to be interpreted as a signed MPI, thus it may have an extra leading zero octet even if not included in the original data. With pkcs1 or oaep decoding enabled the returned value is a verbatim octet string. */ gcry_err_code_t _gcry_pk_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t s_skey) { gcry_err_code_t rc; gcry_pk_spec_t *spec; gcry_sexp_t keyparms; *r_plain = NULL; rc = spec_from_sexp (s_skey, 1, &spec, &keyparms); if (rc) goto leave; if (spec->decrypt) rc = spec->decrypt (r_plain, s_data, keyparms); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (keyparms); return rc; } /* Create a signature. Caller has to provide a secret key as the SEXP skey and data expressed as a SEXP list hash with only one element which should instantly be available as a MPI. Alternatively the structure given below may be used for S_HASH, it provides the abiliy to pass flags to the operation; the flags defined by now are "pkcs1" which does PKCS#1 block type 1 style padding and "pss" for PSS encoding. Returns: 0 or an errorcode. In case of 0 the function returns a new SEXP with the signature value; the structure of this signature depends on the other arguments but is always suitable to be passed to gcry_pk_verify s_hash = See comment for _gcry-pk_util_data_to_mpi s_skey = r_sig = (sig-val ( ( ) ... ( )) [(hash algo)]) Note that (hash algo) in R_SIG is not used. */ gcry_err_code_t _gcry_pk_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_hash, gcry_sexp_t s_skey) { gcry_err_code_t rc; gcry_pk_spec_t *spec; gcry_sexp_t keyparms; *r_sig = NULL; rc = spec_from_sexp (s_skey, 1, &spec, &keyparms); if (rc) goto leave; if (spec->sign) rc = spec->sign (r_sig, s_hash, keyparms); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (keyparms); return rc; } /* Verify a signature. Caller has to supply the public key pkey, the signature sig and his hashvalue data. Public key has to be a standard public key given as an S-Exp, sig is a S-Exp as returned from gcry_pk_sign and data must be an S-Exp like the one in sign too. */ gcry_err_code_t _gcry_pk_verify (gcry_sexp_t s_sig, gcry_sexp_t s_hash, gcry_sexp_t s_pkey) { gcry_err_code_t rc; gcry_pk_spec_t *spec; gcry_sexp_t keyparms; rc = spec_from_sexp (s_pkey, 0, &spec, &keyparms); if (rc) goto leave; if (spec->verify) rc = spec->verify (s_sig, s_hash, keyparms); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (keyparms); return rc; } /* Test a key. This may be used either for a public or a secret key to see whether the internal structure is okay. Returns: 0 or an errorcode. NOTE: We currently support only secret key checking. */ gcry_err_code_t _gcry_pk_testkey (gcry_sexp_t s_key) { gcry_err_code_t rc; gcry_pk_spec_t *spec; gcry_sexp_t keyparms; rc = spec_from_sexp (s_key, 1, &spec, &keyparms); if (rc) goto leave; if (spec->check_secret_key) rc = spec->check_secret_key (keyparms); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (keyparms); return rc; } /* Create a public key pair and return it in r_key. How the key is created depends on s_parms: (genkey (algo (parameter_name_1 ....) .... (parameter_name_n ....) )) The key is returned in a format depending on the algorithm. Both, private and secret keys are returned and optionally some additional informatin. For elgamal we return this structure: (key-data (public-key (elg (p ) (g ) (y ) ) ) (private-key (elg (p ) (g ) (y ) (x ) ) ) (misc-key-info (pm1-factors n1 n2 ... nn) )) */ gcry_err_code_t _gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms) { gcry_pk_spec_t *spec = NULL; gcry_sexp_t list = NULL; gcry_sexp_t l2 = NULL; char *name = NULL; gcry_err_code_t rc; *r_key = NULL; list = sexp_find_token (s_parms, "genkey", 0); if (!list) { rc = GPG_ERR_INV_OBJ; /* Does not contain genkey data. */ goto leave; } l2 = sexp_cadr (list); sexp_release (list); list = l2; l2 = NULL; if (! list) { rc = GPG_ERR_NO_OBJ; /* No cdr for the genkey. */ goto leave; } name = _gcry_sexp_nth_string (list, 0); if (!name) { rc = GPG_ERR_INV_OBJ; /* Algo string missing. */ goto leave; } spec = spec_from_name (name); xfree (name); name = NULL; if (!spec) { rc = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */ goto leave; } if (spec->generate) rc = spec->generate (list, r_key); else rc = GPG_ERR_NOT_IMPLEMENTED; leave: sexp_release (list); xfree (name); sexp_release (l2); return rc; } /* Get the number of nbits from the public key. Hmmm: Should we have really this function or is it better to have a more general function to retrieve different properties of the key? */ unsigned int _gcry_pk_get_nbits (gcry_sexp_t key) { gcry_pk_spec_t *spec; gcry_sexp_t parms; unsigned int nbits; /* Parsing KEY might be considered too much overhead. For example for RSA we would only need to look at P and stop parsing right away. However, with ECC things are more complicate in that only a curve name might be specified. Thus we need to tear the sexp apart. */ if (spec_from_sexp (key, 0, &spec, &parms)) return 0; /* Error - 0 is a suitable indication for that. */ nbits = spec->get_nbits (parms); sexp_release (parms); return nbits; } /* Return the so called KEYGRIP which is the SHA-1 hash of the public key parameters expressed in a way depending on the algorithm. ARRAY must either be 20 bytes long or NULL; in the latter case a newly allocated array of that size is returned, otherwise ARRAY or NULL is returned to indicate an error which is most likely an unknown algorithm. The function accepts public or secret keys. */ unsigned char * _gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array) { gcry_sexp_t list = NULL; gcry_sexp_t l2 = NULL; gcry_pk_spec_t *spec = NULL; const char *s; char *name = NULL; int idx; const char *elems; gcry_md_hd_t md = NULL; int okay = 0; /* Check that the first element is valid. */ list = sexp_find_token (key, "public-key", 0); if (! list) list = sexp_find_token (key, "private-key", 0); if (! list) list = sexp_find_token (key, "protected-private-key", 0); if (! list) list = sexp_find_token (key, "shadowed-private-key", 0); if (! list) return NULL; /* No public- or private-key object. */ l2 = sexp_cadr (list); sexp_release (list); list = l2; l2 = NULL; name = _gcry_sexp_nth_string (list, 0); if (!name) goto fail; /* Invalid structure of object. */ spec = spec_from_name (name); if (!spec) goto fail; /* Unknown algorithm. */ elems = spec->elements_grip; if (!elems) goto fail; /* No grip parameter. */ if (_gcry_md_open (&md, GCRY_MD_SHA1, 0)) goto fail; if (spec->comp_keygrip) { /* Module specific method to compute a keygrip. */ if (spec->comp_keygrip (md, list)) goto fail; } else { /* Generic method to compute a keygrip. */ for (idx = 0, s = elems; *s; s++, idx++) { const char *data; size_t datalen; char buf[30]; l2 = sexp_find_token (list, s, 1); if (! l2) goto fail; data = sexp_nth_data (l2, 1, &datalen); if (! data) goto fail; snprintf (buf, sizeof buf, "(1:%c%u:", *s, (unsigned int)datalen); _gcry_md_write (md, buf, strlen (buf)); _gcry_md_write (md, data, datalen); sexp_release (l2); l2 = NULL; _gcry_md_write (md, ")", 1); } } if (!array) { array = xtrymalloc (20); if (! array) goto fail; } memcpy (array, _gcry_md_read (md, GCRY_MD_SHA1), 20); okay = 1; fail: xfree (name); sexp_release (l2); _gcry_md_close (md); sexp_release (list); return okay? array : NULL; } const char * _gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits) { const char *result = NULL; gcry_pk_spec_t *spec; gcry_sexp_t keyparms = NULL; if (r_nbits) *r_nbits = 0; if (key) { iterator = 0; if (spec_from_sexp (key, 0, &spec, &keyparms)) return NULL; } else { spec = spec_from_name ("ecc"); if (!spec) return NULL; } if (spec->get_curve) result = spec->get_curve (keyparms, iterator, r_nbits); sexp_release (keyparms); return result; } gcry_sexp_t _gcry_pk_get_param (int algo, const char *name) { gcry_sexp_t result = NULL; gcry_pk_spec_t *spec = NULL; algo = map_algo (algo); if (algo != GCRY_PK_ECC) return NULL; spec = spec_from_name ("ecc"); if (spec) { if (spec && spec->get_curve_param) result = spec->get_curve_param (name); } return result; } gcry_err_code_t _gcry_pk_ctl (int cmd, void *buffer, size_t buflen) { gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_DISABLE_ALGO: /* This one expects a buffer pointing to an integer with the algo number. */ if ((! buffer) || (buflen != sizeof (int))) rc = GPG_ERR_INV_ARG; else disable_pubkey_algo (*((int *) buffer)); break; default: rc = GPG_ERR_INV_OP; } return rc; } /* Return information about the given algorithm WHAT selects the kind of information returned: GCRYCTL_TEST_ALGO: Returns 0 when the specified algorithm is available for use. Buffer must be NULL, nbytes may have the address of a variable with the required usage of the algorithm. It may be 0 for don't care or a combination of the GCRY_PK_USAGE_xxx flags; GCRYCTL_GET_ALGO_USAGE: Return the usage flags for the given algo. An invalid algo returns 0. Disabled algos are ignored here because we only want to know whether the algo is at all capable of the usage. Note: Because this function is in most cases used to return an integer value, we can make it easier for the caller to just look at the return value. The caller will in all cases consult the value and thereby detecting whether a error occurred or not (i.e. while checking the block size) */ gcry_err_code_t _gcry_pk_algo_info (int algorithm, int what, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; switch (what) { case GCRYCTL_TEST_ALGO: { int use = nbytes ? *nbytes : 0; if (buffer) rc = GPG_ERR_INV_ARG; else if (check_pubkey_algo (algorithm, use)) rc = GPG_ERR_PUBKEY_ALGO; break; } case GCRYCTL_GET_ALGO_USAGE: { gcry_pk_spec_t *spec; spec = spec_from_algo (algorithm); *nbytes = spec? spec->use : 0; break; } case GCRYCTL_GET_ALGO_NPKEY: { /* FIXME? */ int npkey = pubkey_get_npkey (algorithm); *nbytes = npkey; break; } case GCRYCTL_GET_ALGO_NSKEY: { /* FIXME? */ int nskey = pubkey_get_nskey (algorithm); *nbytes = nskey; break; } case GCRYCTL_GET_ALGO_NSIGN: { /* FIXME? */ int nsign = pubkey_get_nsig (algorithm); *nbytes = nsign; break; } case GCRYCTL_GET_ALGO_NENCR: { /* FIXME? */ int nencr = pubkey_get_nenc (algorithm); *nbytes = nencr; break; } default: rc = GPG_ERR_INV_OP; } return rc; } /* Return an S-expression representing the context CTX. Depending on the state of that context, the S-expression may either be a public key, a private key or any other object used with public key operations. On success a new S-expression is stored at R_SEXP and 0 is returned, on error NULL is store there and an error code is returned. MODE is either 0 or one of the GCRY_PK_GET_xxx values. As of now it only support certain ECC operations because a context object is right now only defined for ECC. Over time this function will be extended to cover more algorithms. Note also that the name of the function is gcry_pubkey_xxx and not gcry_pk_xxx. The idea is that we will eventually provide variants of the existing gcry_pk_xxx functions which will take a context parameter. */ gcry_err_code_t _gcry_pubkey_get_sexp (gcry_sexp_t *r_sexp, int mode, gcry_ctx_t ctx) { mpi_ec_t ec; if (!r_sexp) return GPG_ERR_INV_VALUE; *r_sexp = NULL; switch (mode) { case 0: case GCRY_PK_GET_PUBKEY: case GCRY_PK_GET_SECKEY: break; default: return GPG_ERR_INV_VALUE; } if (!ctx) return GPG_ERR_NO_CRYPT_CTX; ec = _gcry_ctx_find_pointer (ctx, CONTEXT_TYPE_EC); if (ec) return _gcry_pk_ecc_get_sexp (r_sexp, mode, ec); return GPG_ERR_WRONG_CRYPT_CTX; } /* Explicitly initialize this module. */ gcry_err_code_t _gcry_pk_init (void) { return 0; } /* Run the selftests for pubkey algorithm ALGO with optional reporting function REPORT. */ gpg_error_t _gcry_pk_selftest (int algo, int extended, selftest_report_func_t report) { gcry_err_code_t ec; gcry_pk_spec_t *spec; algo = map_algo (algo); spec = spec_from_algo (algo); if (spec && !spec->flags.disabled && spec->selftest) ec = spec->selftest (algo, extended, report); else { ec = GPG_ERR_PUBKEY_ALGO; /* Fixme: We need to change the report fucntion to allow passing of an encryption mode (e.g. pkcs1, ecdsa, or ecdh). */ if (report) report ("pubkey", algo, "module", spec && !spec->flags.disabled? "no selftest available" : spec? "algorithm disabled" : "algorithm not found"); } return gpg_error (ec); } diff --git a/compat/compat.c b/compat/compat.c index 5678067a..39d64988 100644 --- a/compat/compat.c +++ b/compat/compat.c @@ -1,40 +1,40 @@ /* compat.c - Dummy file to avoid an empty library. * Copyright (C) 2010 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 . */ #include #include "../src/g10lib.h" const char * _gcry_compat_identification (void) { /* For complete list of copyright holders see the file AUTHORS in the source distribution. */ static const char blurb[] = "\n\n" "This is Libgcrypt " PACKAGE_VERSION " - The GNU Crypto Library\n" "Copyright (C) 2000-2012 Free Software Foundation, Inc.\n" - "Copyright (C) 2012-2013 g10 Code GmbH\n" - "Copyright (C) 2013 Jussi Kivilinna\n" + "Copyright (C) 2012-2014 g10 Code GmbH\n" + "Copyright (C) 2013-2014 Jussi Kivilinna\n" "\n" "(" BUILD_REVISION " " BUILD_TIMESTAMP ")\n" "\n\n"; return blurb; } diff --git a/configure.ac b/configure.ac index 7d37f94e..6272871f 100644 --- a/configure.ac +++ b/configure.ac @@ -1,2042 +1,2037 @@ # Configure.ac script for Libgcrypt # Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006, # 2007, 2008, 2009, 2011 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 . # (Process this file with autoconf to produce a configure script.) AC_REVISION($Revision$) AC_PREREQ(2.60) min_automake_version="1.10" # To build a release you need to create a tag with the version number # (git tag -s libgcrypt-n.m.k) and run "./autogen.sh --force". Please # bump the version number immediately after the release and do another # commit and push so that the git magic is able to work. See below # for the LT versions. m4_define(mym4_version_major, [1]) m4_define(mym4_version_minor, [7]) m4_define(mym4_version_micro, [0]) # Below is m4 magic to extract and compute the revision number, the # decimalized short revision number, a beta version string, and a flag # indicating a development version (mym4_isgit). Note that the m4 # processing is done by autoconf and not during the configure run. m4_define(mym4_version, [mym4_version_major.mym4_version_minor.mym4_version_micro]) m4_define([mym4_revision], m4_esyscmd([git rev-parse --short HEAD | tr -d '\n\r'])) m4_define([mym4_revision_dec], m4_esyscmd_s([echo $((0x$(echo ]mym4_revision[|head -c 4)))])) m4_define([mym4_betastring], m4_esyscmd_s([git describe --match 'libgcrypt-[0-9].*[0-9]' --long|\ awk -F- '$3!=0{print"-beta"$3}'])) m4_define([mym4_isgit],m4_if(mym4_betastring,[],[no],[yes])) m4_define([mym4_full_version],[mym4_version[]mym4_betastring]) AC_INIT([libgcrypt],[mym4_full_version],[http://bugs.gnupg.org]) # LT Version numbers, remember to change them just *before* a release. # (Interfaces removed: CURRENT++, AGE=0, REVISION=0) # (Interfaces added: CURRENT++, AGE++, REVISION=0) # (No interfaces changed: REVISION++) LIBGCRYPT_LT_CURRENT=20 LIBGCRYPT_LT_AGE=0 LIBGCRYPT_LT_REVISION=0 # If the API is changed in an incompatible way: increment the next counter. # # 1.6: ABI and API change but the change is to most users irrelevant # and thus the API version number has not been incremented. LIBGCRYPT_CONFIG_API_VERSION=1 # If you change the required gpg-error version, please remove # unnecessary error code defines in src/gcrypt-int.h. -NEED_GPG_ERROR_VERSION=1.11 +NEED_GPG_ERROR_VERSION=1.13 PACKAGE=$PACKAGE_NAME VERSION=$PACKAGE_VERSION AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_SRCDIR([src/libgcrypt.vers]) AM_INIT_AUTOMAKE AC_CONFIG_HEADER(config.h) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_LIBOBJ_DIR([compat]) AC_CANONICAL_HOST AM_MAINTAINER_MODE AM_SILENT_RULES AH_TOP([ #ifndef _GCRYPT_CONFIG_H_INCLUDED #define _GCRYPT_CONFIG_H_INCLUDED /* Enable gpg-error's strerror macro for W32CE. */ #define GPG_ERR_ENABLE_ERRNO_MACROS 1 ]) AH_BOTTOM([ #define _GCRYPT_IN_LIBGCRYPT 1 /* If the configure check for endianness has been disabled, get it from OS macros. This is intended for making fat binary builds on OS X. */ #ifdef DISABLED_ENDIAN_CHECK # if defined(__BIG_ENDIAN__) # define WORDS_BIGENDIAN 1 # elif defined(__LITTLE_ENDIAN__) # undef WORDS_BIGENDIAN # else # error "No endianness found" # endif #endif /*DISABLED_ENDIAN_CHECK*/ /* We basically use the original Camellia source. Make sure the symbols properly prefixed. */ #define CAMELLIA_EXT_SYM_PREFIX _gcry_ #endif /*_GCRYPT_CONFIG_H_INCLUDED*/ ]) AH_VERBATIM([_REENTRANT], [/* To allow the use of Libgcrypt in multithreaded programs we have to use special features from the library. */ #ifndef _REENTRANT # define _REENTRANT 1 #endif ]) AC_SUBST(LIBGCRYPT_LT_CURRENT) AC_SUBST(LIBGCRYPT_LT_AGE) AC_SUBST(LIBGCRYPT_LT_REVISION) AC_SUBST(PACKAGE) AC_SUBST(VERSION) AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package]) VERSION_NUMBER=m4_esyscmd(printf "0x%02x%02x%02x" mym4_version_major \ mym4_version_minor mym4_version_micro) AC_SUBST(VERSION_NUMBER) ###################### ## Basic checks. ### (we need some results later on (e.g. $GCC) ###################### AC_PROG_MAKE_SET missing_dir=`cd $ac_aux_dir && pwd` AM_MISSING_PROG(ACLOCAL, aclocal, $missing_dir) AM_MISSING_PROG(AUTOCONF, autoconf, $missing_dir) AM_MISSING_PROG(AUTOMAKE, automake, $missing_dir) AM_MISSING_PROG(AUTOHEADER, autoheader, $missing_dir) # AM_MISSING_PROG(MAKEINFO, makeinfo, $missing_dir) AC_PROG_CC AC_PROG_CPP AM_PROG_CC_C_O AM_PROG_AS AC_ISC_POSIX AC_PROG_INSTALL AC_PROG_AWK AC_GNU_SOURCE # We need to compile and run a program on the build machine. A # comment in libgpg-error says that the AC_PROG_CC_FOR_BUILD macro in # the AC archive is broken for autoconf 2.57. Given that there is no # newer version of that macro, we assume that it is also broken for # autoconf 2.61 and thus we use a simple but usually sufficient # approach. AC_MSG_CHECKING(for cc for build) if test "$cross_compiling" = "yes"; then CC_FOR_BUILD="${CC_FOR_BUILD-cc}" else CC_FOR_BUILD="${CC_FOR_BUILD-$CC}" fi AC_MSG_RESULT($CC_FOR_BUILD) AC_ARG_VAR(CC_FOR_BUILD,[build system C compiler]) LT_PREREQ([2.2.6]) LT_INIT([win32-dll disable-static]) LT_LANG([Windows Resource]) ########################## ## General definitions. ## ########################## # Used by libgcrypt-config LIBGCRYPT_CONFIG_LIBS="-lgcrypt" LIBGCRYPT_CONFIG_CFLAGS="" LIBGCRYPT_CONFIG_HOST="$host" # Definitions for symmetric ciphers. available_ciphers="arcfour blowfish cast5 des aes twofish serpent rfc2268 seed" available_ciphers="$available_ciphers camellia idea salsa20 gost28147" enabled_ciphers="" # Definitions for public-key ciphers. available_pubkey_ciphers="dsa elgamal rsa ecc" enabled_pubkey_ciphers="" # Definitions for message digests. available_digests="crc gostr3411-94 md4 md5 rmd160 sha1 sha256" available_digests_64="sha512 tiger whirlpool stribog" enabled_digests="" # Definitions for kdfs (optional ones) available_kdfs="s2k pkdf2" available_kdfs_64="scrypt" enabled_kdfs="" # Definitions for random modules. available_random_modules="linux egd unix" auto_random_modules="$available_random_modules" # Supported thread backends. LIBGCRYPT_THREAD_MODULES="" # Other definitions. print_egd_notice=no have_w32_system=no have_w32ce_system=no have_pthread=no # Setup some stuff depending on host. case "${host}" in *-*-mingw32*) ac_cv_have_dev_random=no have_w32_system=yes case "${host}" in *-mingw32ce*) have_w32ce_system=yes available_random_modules="w32ce" ;; *) available_random_modules="w32" ;; esac AC_DEFINE(USE_ONLY_8DOT3,1, [set this to limit filenames to the 8.3 format]) AC_DEFINE(HAVE_DRIVE_LETTERS,1, [defined if we must run on a stupid file system]) AC_DEFINE(HAVE_DOSISH_SYSTEM,1, [defined if we run on some of the PCDOS like systems (DOS, Windoze. OS/2) with special properties like no file modes]) ;; i?86-emx-os2 | i?86-*-os2*emx) # OS/2 with the EMX environment ac_cv_have_dev_random=no AC_DEFINE(HAVE_DRIVE_LETTERS) AC_DEFINE(HAVE_DOSISH_SYSTEM) ;; i?86-*-msdosdjgpp*) # DOS with the DJGPP environment ac_cv_have_dev_random=no AC_DEFINE(HAVE_DRIVE_LETTERS) AC_DEFINE(HAVE_DOSISH_SYSTEM) ;; *-*-hpux*) if test -z "$GCC" ; then CFLAGS="$CFLAGS -Ae -D_HPUX_SOURCE" fi ;; *-dec-osf4*) if test -z "$GCC" ; then # Suppress all warnings # to get rid of the unsigned/signed char mismatch warnings. CFLAGS="$CFLAGS -w" fi ;; m68k-atari-mint) ;; *) ;; esac if test "$have_w32_system" = yes; then AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system]) if test "$have_w32ce_system" = yes; then AC_DEFINE(HAVE_W32CE_SYSTEM,1,[Defined if we run on WindowsCE]) fi fi AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes) AM_CONDITIONAL(HAVE_W32CE_SYSTEM, test "$have_w32ce_system" = yes) # A printable OS Name is sometimes useful. case "${host}" in *-*-mingw32ce*) PRINTABLE_OS_NAME="W32CE" ;; *-*-mingw32*) PRINTABLE_OS_NAME="W32" ;; i?86-emx-os2 | i?86-*-os2*emx ) PRINTABLE_OS_NAME="OS/2" ;; i?86-*-msdosdjgpp*) PRINTABLE_OS_NAME="MSDOS/DJGPP" ;; *-linux*) PRINTABLE_OS_NAME="GNU/Linux" ;; *) PRINTABLE_OS_NAME=`uname -s || echo "Unknown"` ;; esac # # Figure out the name of the random device # case "${host}" in *-openbsd*) NAME_OF_DEV_RANDOM="/dev/srandom" NAME_OF_DEV_URANDOM="/dev/urandom" ;; *) NAME_OF_DEV_RANDOM="/dev/random" NAME_OF_DEV_URANDOM="/dev/urandom" ;; esac AC_ARG_ENABLE(endian-check, AC_HELP_STRING([--disable-endian-check], [disable the endian check and trust the OS provided macros]), endiancheck=$enableval,endiancheck=yes) if test x"$endiancheck" = xyes ; then AC_C_BIGENDIAN else AC_DEFINE(DISABLED_ENDIAN_CHECK,1,[configure did not test for endianess]) fi AC_CHECK_SIZEOF(unsigned short, 2) AC_CHECK_SIZEOF(unsigned int, 4) AC_CHECK_SIZEOF(unsigned long, 4) AC_CHECK_SIZEOF(unsigned long long, 0) AC_TYPE_UINTPTR_T if test "$ac_cv_sizeof_unsigned_short" = "0" \ || test "$ac_cv_sizeof_unsigned_int" = "0" \ || test "$ac_cv_sizeof_unsigned_long" = "0"; then AC_MSG_WARN([Hmmm, something is wrong with the sizes - using defaults]); fi # Do we have any 64-bit data types? if test "$ac_cv_sizeof_unsigned_int" != "8" \ && test "$ac_cv_sizeof_unsigned_long" != "8" \ && test "$ac_cv_sizeof_unsigned_long_long" != "8" \ && test "$ac_cv_sizeof_uint64_t" != "8"; then AC_MSG_WARN([No 64-bit types. Disabling TIGER/192, SCRYPT, SHA-384, \ SHA-512 and GOST R 34.11-12]) else available_digests="$available_digests $available_digests_64" available_kdfs="$available_kdfs $available_kdfs_64" fi # If not specified otherwise, all available algorithms will be # included. default_ciphers="$available_ciphers" default_pubkey_ciphers="$available_pubkey_ciphers" default_digests="$available_digests" default_kdfs="$available_kdfs" # Substitutions to set generated files in a Emacs buffer to read-only. AC_SUBST(emacs_local_vars_begin, ['Local Variables:']) AC_SUBST(emacs_local_vars_read_only, ['buffer-read-only: t']) AC_SUBST(emacs_local_vars_end, ['End:']) ############################ ## Command line switches. ## ############################ # Implementation of the --enable-ciphers switch. AC_ARG_ENABLE(ciphers, AC_HELP_STRING([--enable-ciphers=ciphers], [select the symmetric ciphers to include]), [enabled_ciphers=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`], [enabled_ciphers=""]) if test "x$enabled_ciphers" = "x" \ -o "$enabled_ciphers" = "yes" \ -o "$enabled_ciphers" = "no"; then enabled_ciphers=$default_ciphers fi AC_MSG_CHECKING([which symmetric ciphers to include]) for cipher in $enabled_ciphers; do LIST_MEMBER($cipher, $available_ciphers) if test "$found" = "0"; then AC_MSG_ERROR([unsupported cipher "$cipher" specified]) fi done AC_MSG_RESULT([$enabled_ciphers]) # Implementation of the --enable-pubkey-ciphers switch. AC_ARG_ENABLE(pubkey-ciphers, AC_HELP_STRING([--enable-pubkey-ciphers=ciphers], [select the public-key ciphers to include]), [enabled_pubkey_ciphers=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`], [enabled_pubkey_ciphers=""]) if test "x$enabled_pubkey_ciphers" = "x" \ -o "$enabled_pubkey_ciphers" = "yes" \ -o "$enabled_pubkey_ciphers" = "no"; then enabled_pubkey_ciphers=$default_pubkey_ciphers fi AC_MSG_CHECKING([which public-key ciphers to include]) for cipher in $enabled_pubkey_ciphers; do LIST_MEMBER($cipher, $available_pubkey_ciphers) if test "$found" = "0"; then AC_MSG_ERROR([unsupported public-key cipher specified]) fi done AC_MSG_RESULT([$enabled_pubkey_ciphers]) # Implementation of the --enable-digests switch. AC_ARG_ENABLE(digests, AC_HELP_STRING([--enable-digests=digests], [select the message digests to include]), [enabled_digests=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`], [enabled_digests=""]) if test "x$enabled_digests" = "x" \ -o "$enabled_digests" = "yes" \ -o "$enabled_digests" = "no"; then enabled_digests=$default_digests fi AC_MSG_CHECKING([which message digests to include]) for digest in $enabled_digests; do LIST_MEMBER($digest, $available_digests) if test "$found" = "0"; then AC_MSG_ERROR([unsupported message digest specified]) fi done AC_MSG_RESULT([$enabled_digests]) # Implementation of the --enable-kdfs switch. AC_ARG_ENABLE(kdfs, AC_HELP_STRING([--enable-kfds=kdfs], [select the KDFs to include]), [enabled_kdfs=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`], [enabled_kdfs=""]) if test "x$enabled_kdfs" = "x" \ -o "$enabled_kdfs" = "yes" \ -o "$enabled_kdfs" = "no"; then enabled_kdfs=$default_kdfs fi AC_MSG_CHECKING([which key derivation functions to include]) for kdf in $enabled_kdfs; do LIST_MEMBER($kdf, $available_kdfs) if test "$found" = "0"; then AC_MSG_ERROR([unsupported key derivation function specified]) fi done AC_MSG_RESULT([$enabled_kdfs]) # Implementation of the --enable-random switch. AC_ARG_ENABLE(random, AC_HELP_STRING([--enable-random=name], [select which random number generator to use]), [random=`echo $enableval | tr '[A-Z]' '[a-z]'`], []) if test "x$random" = "x" -o "$random" = "yes" -o "$random" = "no"; then random=default fi AC_MSG_CHECKING([which random module to use]) if test "$random" != "default" -a "$random" != "auto"; then LIST_MEMBER($random, $available_random_modules) if test "$found" = "0"; then AC_MSG_ERROR([unsupported random module specified]) fi fi AC_MSG_RESULT($random) # Implementation of the --disable-dev-random switch. AC_MSG_CHECKING([whether use of /dev/random is requested]) AC_ARG_ENABLE(dev-random, [ --disable-dev-random disable the use of dev random], try_dev_random=$enableval, try_dev_random=yes) AC_MSG_RESULT($try_dev_random) # Implementation of the --with-egd-socket switch. AC_ARG_WITH(egd-socket, [ --with-egd-socket=NAME Use NAME for the EGD socket)], egd_socket_name="$withval", egd_socket_name="" ) AC_DEFINE_UNQUOTED(EGD_SOCKET_NAME, "$egd_socket_name", [Define if you don't want the default EGD socket name. For details see cipher/rndegd.c]) # Implementation of the --enable-random-daemon AC_MSG_CHECKING([whether the experimental random daemon is requested]) AC_ARG_ENABLE([random-daemon], AC_HELP_STRING([--enable-random-daemon], [Build and support the experimental gcryptrnd]), [use_random_daemon=$enableval], [use_random_daemon=no]) AC_MSG_RESULT($use_random_daemon) if test x$use_random_daemon = xyes ; then AC_DEFINE(USE_RANDOM_DAEMON,1, [Define to support the experimental random daemon]) fi AM_CONDITIONAL(USE_RANDOM_DAEMON, test x$use_random_daemon = xyes) # Implementation of --disable-asm. AC_MSG_CHECKING([whether MPI assembler modules are requested]) AC_ARG_ENABLE([asm], AC_HELP_STRING([--disable-asm], [Disable MPI assembler modules]), [try_asm_modules=$enableval], [try_asm_modules=yes]) AC_MSG_RESULT($try_asm_modules) # Implementation of the --enable-m-guard switch. AC_MSG_CHECKING([whether memory guard is requested]) AC_ARG_ENABLE(m-guard, AC_HELP_STRING([--enable-m-guard], [Enable memory guard facility]), [use_m_guard=$enableval], [use_m_guard=no]) AC_MSG_RESULT($use_m_guard) if test "$use_m_guard" = yes ; then AC_DEFINE(M_GUARD,1,[Define to use the (obsolete) malloc guarding feature]) fi # Implementation of the --enable-large-data-tests switch. AC_MSG_CHECKING([whether to run large data tests]) AC_ARG_ENABLE(large-data-tests, AC_HELP_STRING([--enable-large-data-tests], [Enable the real long ruinning large data tests]), large_data_tests=$enableval,large_data_tests=no) AC_MSG_RESULT($large_data_tests) AC_SUBST(RUN_LARGE_DATA_TESTS, $large_data_tests) # Implementation of the --with-capabilities switch. # Check whether we want to use Linux capabilities AC_MSG_CHECKING([whether use of capabilities is requested]) AC_ARG_WITH(capabilities, AC_HELP_STRING([--with-capabilities], [Use linux capabilities [default=no]]), [use_capabilities="$withval"],[use_capabilities=no]) AC_MSG_RESULT($use_capabilities) # Implementation of the --enable-hmac-binary-check. AC_MSG_CHECKING([whether a HMAC binary check is requested]) AC_ARG_ENABLE(hmac-binary-check, AC_HELP_STRING([--enable-hmac-binary-check], [Enable library integrity check]), [use_hmac_binary_check=$enableval], [use_hmac_binary_check=no]) AC_MSG_RESULT($use_hmac_binary_check) if test "$use_hmac_binary_check" = yes ; then AC_DEFINE(ENABLE_HMAC_BINARY_CHECK,1, [Define to support an HMAC based integrity check]) fi # Implementation of the --disable-padlock-support switch. AC_MSG_CHECKING([whether padlock support is requested]) AC_ARG_ENABLE(padlock-support, AC_HELP_STRING([--disable-padlock-support], [Disable support for the PadLock Engine of VIA processors]), padlocksupport=$enableval,padlocksupport=yes) AC_MSG_RESULT($padlocksupport) if test x"$padlocksupport" = xyes ; then AC_DEFINE(ENABLE_PADLOCK_SUPPORT, 1, [Enable support for the PadLock engine.]) fi # Implementation of the --disable-aesni-support switch. AC_MSG_CHECKING([whether AESNI support is requested]) AC_ARG_ENABLE(aesni-support, AC_HELP_STRING([--disable-aesni-support], [Disable support for the Intel AES-NI instructions]), aesnisupport=$enableval,aesnisupport=yes) AC_MSG_RESULT($aesnisupport) # Implementation of the --disable-pclmul-support switch. AC_MSG_CHECKING([whether PCLMUL support is requested]) AC_ARG_ENABLE(pclmul-support, AC_HELP_STRING([--disable-pclmul-support], [Disable support for the Intel PCLMUL instructions]), pclmulsupport=$enableval,pclmulsupport=yes) AC_MSG_RESULT($pclmulsupport) # Implementation of the --disable-drng-support switch. AC_MSG_CHECKING([whether DRNG support is requested]) AC_ARG_ENABLE(drng-support, AC_HELP_STRING([--disable-drng-support], [Disable support for the Intel DRNG (RDRAND instruction)]), drngsupport=$enableval,drngsupport=yes) AC_MSG_RESULT($drngsupport) if test x"$drngsupport" = xyes ; then AC_DEFINE(ENABLE_DRNG_SUPPORT, 1, [Enable support for Intel DRNG (RDRAND instruction).]) fi # Implementation of the --disable-avx-support switch. AC_MSG_CHECKING([whether AVX support is requested]) AC_ARG_ENABLE(avx-support, AC_HELP_STRING([--disable-avx-support], [Disable support for the Intel AVX instructions]), avxsupport=$enableval,avxsupport=yes) AC_MSG_RESULT($avxsupport) # Implementation of the --disable-avx2-support switch. AC_MSG_CHECKING([whether AVX2 support is requested]) AC_ARG_ENABLE(avx2-support, AC_HELP_STRING([--disable-avx2-support], [Disable support for the Intel AVX2 instructions]), avx2support=$enableval,avx2support=yes) AC_MSG_RESULT($avx2support) # Implementation of the --disable-neon-support switch. AC_MSG_CHECKING([whether NEON support is requested]) AC_ARG_ENABLE(neon-support, AC_HELP_STRING([--disable-neon-support], [Disable support for the ARM NEON instructions]), neonsupport=$enableval,neonsupport=yes) AC_MSG_RESULT($neonsupport) # Implementation of the --disable-O-flag-munging switch. AC_MSG_CHECKING([whether a -O flag munging is requested]) AC_ARG_ENABLE([O-flag-munging], AC_HELP_STRING([--disable-O-flag-munging], [Disable modification of the cc -O flag]), [enable_o_flag_munging=$enableval], [enable_o_flag_munging=yes]) AC_MSG_RESULT($enable_o_flag_munging) AM_CONDITIONAL(ENABLE_O_FLAG_MUNGING, test "$enable_o_flag_munging" = "yes") # Implementation of the --disable-amd64-as-feature-detection switch. AC_MSG_CHECKING([whether to enable AMD64 as(1) feature detection]) AC_ARG_ENABLE(amd64-as-feature-detection, AC_HELP_STRING([--disable-amd64-as-feature-detection], [Disable the auto-detection of AMD64 as(1) features]), amd64_as_feature_detection=$enableval, amd64_as_feature_detection=yes) AC_MSG_RESULT($amd64_as_feature_detection) AC_DEFINE_UNQUOTED(PRINTABLE_OS_NAME, "$PRINTABLE_OS_NAME", [A human readable text with the name of the OS]) # For some systems we know that we have ld_version scripts. # Use it then as default. have_ld_version_script=no case "${host}" in *-*-linux*) have_ld_version_script=yes ;; *-*-gnu*) have_ld_version_script=yes ;; esac AC_ARG_ENABLE([ld-version-script], AC_HELP_STRING([--enable-ld-version-script], [enable/disable use of linker version script. (default is system dependent)]), [have_ld_version_script=$enableval], [ : ] ) AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes") AC_DEFINE_UNQUOTED(NAME_OF_DEV_RANDOM, "$NAME_OF_DEV_RANDOM", [defined to the name of the strong random device]) AC_DEFINE_UNQUOTED(NAME_OF_DEV_URANDOM, "$NAME_OF_DEV_URANDOM", [defined to the name of the weaker random device]) ############################### #### Checks for libraries. #### ############################### # # gpg-error is required. # AM_PATH_GPG_ERROR("$NEED_GPG_ERROR_VERSION") if test "x$GPG_ERROR_LIBS" = "x"; then AC_MSG_ERROR([libgpg-error is needed. See ftp://ftp.gnupg.org/gcrypt/libgpg-error/ .]) fi AC_DEFINE(GPG_ERR_SOURCE_DEFAULT, GPG_ERR_SOURCE_GCRYPT, [The default error source for libgcrypt.]) # # Check whether the GNU Pth library is available. We require this # to build the optional gcryptrnd program. # AC_ARG_WITH(pth-prefix, AC_HELP_STRING([--with-pth-prefix=PFX], [prefix where GNU Pth is installed (optional)]), pth_config_prefix="$withval", pth_config_prefix="") if test x$pth_config_prefix != x ; then PTH_CONFIG="$pth_config_prefix/bin/pth-config" fi if test "$use_random_daemon" = "yes"; then AC_PATH_PROG(PTH_CONFIG, pth-config, no) if test "$PTH_CONFIG" = "no"; then AC_MSG_WARN([[ *** *** To build the Libgcrypt's random number daemon *** we need the support of the GNU Portable Threads Library. *** Download it from ftp://ftp.gnu.org/gnu/pth/ *** On a Debian GNU/Linux system you might want to try *** apt-get install libpth-dev ***]]) else GNUPG_PTH_VERSION_CHECK([1.3.7]) if test $have_pth = yes; then PTH_CFLAGS=`$PTH_CONFIG --cflags` PTH_LIBS=`$PTH_CONFIG --ldflags` PTH_LIBS="$PTH_LIBS `$PTH_CONFIG --libs --all`" AC_DEFINE(USE_GNU_PTH, 1, [Defined if the GNU Portable Thread Library should be used]) AC_DEFINE(HAVE_PTH, 1, [Defined if the GNU Pth is available]) fi fi fi AC_SUBST(PTH_CFLAGS) AC_SUBST(PTH_LIBS) # # Check whether pthreads is available # AC_CHECK_LIB(pthread,pthread_create,have_pthread=yes) if test "$have_pthread" = yes; then AC_DEFINE(HAVE_PTHREAD, ,[Define if we have pthread.]) fi -# -# See which thread system we have -# FIXME: Thus duplicates the above check. -# -gl_LOCK # Solaris needs -lsocket and -lnsl. Unisys system includes # gethostbyname in libsocket but needs libnsl for socket. AC_SEARCH_LIBS(setsockopt, [socket], , [AC_SEARCH_LIBS(setsockopt, [socket], , , [-lnsl])]) AC_SEARCH_LIBS(setsockopt, [nsl]) ################################## #### Checks for header files. #### ################################## AC_HEADER_STDC AC_CHECK_HEADERS(unistd.h sys/select.h sys/msg.h) INSERT_SYS_SELECT_H= if test x"$ac_cv_header_sys_select_h" = xyes; then INSERT_SYS_SELECT_H=" include " fi AC_SUBST(INSERT_SYS_SELECT_H) ########################################## #### Checks for typedefs, structures, #### #### and compiler characteristics. #### ########################################## AC_C_CONST AC_C_INLINE AC_TYPE_SIZE_T AC_TYPE_SIGNAL AC_DECL_SYS_SIGLIST AC_TYPE_PID_T GNUPG_CHECK_TYPEDEF(byte, HAVE_BYTE_TYPEDEF) GNUPG_CHECK_TYPEDEF(ushort, HAVE_USHORT_TYPEDEF) GNUPG_CHECK_TYPEDEF(ulong, HAVE_ULONG_TYPEDEF) GNUPG_CHECK_TYPEDEF(u16, HAVE_U16_TYPEDEF) GNUPG_CHECK_TYPEDEF(u32, HAVE_U32_TYPEDEF) gl_TYPE_SOCKLEN_T case "${host}" in *-*-mingw32*) # socklen_t may or may not be defined depending on what headers # are included. To be safe we use int as this is the actual type. FALLBACK_SOCKLEN_T="typedef int gcry_socklen_t;" ;; *) if test ".$gl_cv_socklen_t_equiv" = "."; then FALLBACK_SOCKLEN_T="typedef socklen_t gcry_socklen_t;" else FALLBACK_SOCKLEN_T="typedef ${gl_cv_socklen_t_equiv} gcry_socklen_t;" fi esac AC_SUBST(FALLBACK_SOCKLEN_T) # # Check for __builtin_bswap32 intrinsic. # AC_CACHE_CHECK(for __builtin_bswap32, [gcry_cv_have_builtin_bswap32], [gcry_cv_have_builtin_bswap32=no AC_LINK_IFELSE([AC_LANG_PROGRAM([], [int x = 0; int y = __builtin_bswap32(x); return y;])], [gcry_cv_have_builtin_bswap32=yes])]) if test "$gcry_cv_have_builtin_bswap32" = "yes" ; then AC_DEFINE(HAVE_BUILTIN_BSWAP32,1, [Defined if compiler has '__builtin_bswap32' intrinsic]) fi # # Check for __builtin_bswap64 intrinsic. # AC_CACHE_CHECK(for __builtin_bswap64, [gcry_cv_have_builtin_bswap64], [gcry_cv_have_builtin_bswap64=no AC_LINK_IFELSE([AC_LANG_PROGRAM([], [long long x = 0; long long y = __builtin_bswap64(x); return y;])], [gcry_cv_have_builtin_bswap64=yes])]) if test "$gcry_cv_have_builtin_bswap64" = "yes" ; then AC_DEFINE(HAVE_BUILTIN_BSWAP64,1, [Defined if compiler has '__builtin_bswap64' intrinsic]) fi # # Check for VLA support (variable length arrays). # AC_CACHE_CHECK(whether the variable length arrays are supported, [gcry_cv_have_vla], [gcry_cv_have_vla=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void f1(char *, int); char foo(int i) { char b[(i < 0 ? 0 : i) + 1]; f1(b, sizeof b); return b[0];}]])], [gcry_cv_have_vla=yes])]) if test "$gcry_cv_have_vla" = "yes" ; then AC_DEFINE(HAVE_VLA,1, [Defined if variable length arrays are supported]) fi # # Check for ELF visibility support. # AC_CACHE_CHECK(whether the visibility attribute is supported, gcry_cv_visibility_attribute, [gcry_cv_visibility_attribute=no AC_LANG_CONFTEST([AC_LANG_SOURCE( [[int foo __attribute__ ((visibility ("hidden"))) = 1; int bar __attribute__ ((visibility ("protected"))) = 1; ]])]) if ${CC-cc} -Werror -S conftest.c -o conftest.s \ 1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then if grep '\.hidden.*foo' conftest.s >/dev/null 2>&1 ; then if grep '\.protected.*bar' conftest.s >/dev/null 2>&1; then gcry_cv_visibility_attribute=yes fi fi fi ]) if test "$gcry_cv_visibility_attribute" = "yes"; then AC_CACHE_CHECK(for broken visibility attribute, gcry_cv_broken_visibility_attribute, [gcry_cv_broken_visibility_attribute=yes AC_LANG_CONFTEST([AC_LANG_SOURCE( [[int foo (int x); int bar (int x) __asm__ ("foo") __attribute__ ((visibility ("hidden"))); int bar (int x) { return x; } ]])]) if ${CC-cc} -Werror -S conftest.c -o conftest.s \ 1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then if grep '\.hidden@<:@ _@:>@foo' conftest.s >/dev/null 2>&1; then gcry_cv_broken_visibility_attribute=no fi fi ]) fi if test "$gcry_cv_visibility_attribute" = "yes"; then AC_CACHE_CHECK(for broken alias attribute, gcry_cv_broken_alias_attribute, [gcry_cv_broken_alias_attribute=yes AC_LANG_CONFTEST([AC_LANG_SOURCE( [[extern int foo (int x) __asm ("xyzzy"); int bar (int x) { return x; } extern __typeof (bar) foo __attribute ((weak, alias ("bar"))); extern int dfoo; extern __typeof (dfoo) dfoo __asm ("abccb"); int dfoo = 1; ]])]) if ${CC-cc} -Werror -S conftest.c -o conftest.s \ 1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then if grep 'xyzzy' conftest.s >/dev/null 2>&1 && \ grep 'abccb' conftest.s >/dev/null 2>&1; then gcry_cv_broken_alias_attribute=no fi fi ]) fi if test "$gcry_cv_visibility_attribute" = "yes"; then AC_CACHE_CHECK(if gcc supports -fvisibility=hidden, gcry_cv_gcc_has_f_visibility, [gcry_cv_gcc_has_f_visibility=no _gcc_cflags_save=$CFLAGS CFLAGS="-fvisibility=hidden" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], gcry_cv_gcc_has_f_visibility=yes) CFLAGS=$_gcc_cflags_save; ]) fi if test "$gcry_cv_visibility_attribute" = "yes" \ && test "$gcry_cv_broken_visibility_attribute" != "yes" \ && test "$gcry_cv_broken_alias_attribute" != "yes" \ && test "$gcry_cv_gcc_has_f_visibility" = "yes" then AC_DEFINE(GCRY_USE_VISIBILITY, 1, [Define to use the GNU C visibility attribute.]) CFLAGS="$CFLAGS -fvisibility=hidden" fi # # Check whether the compiler supports the GCC style aligned attribute # AC_CACHE_CHECK([whether the GCC style aligned attribute is supported], [gcry_cv_gcc_attribute_aligned], [gcry_cv_gcc_attribute_aligned=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[struct { int a; } foo __attribute__ ((aligned (16)));]])], [gcry_cv_gcc_attribute_aligned=yes])]) if test "$gcry_cv_gcc_attribute_aligned" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_ALIGNED,1, [Defined if a GCC style "__attribute__ ((aligned (n))" is supported]) fi # # Check whether the compiler supports 'asm' or '__asm__' keyword for # assembler blocks. # AC_CACHE_CHECK([whether 'asm' assembler keyword is supported], [gcry_cv_have_asm], [gcry_cv_have_asm=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { asm("":::"memory"); }]])], [gcry_cv_have_asm=yes])]) AC_CACHE_CHECK([whether '__asm__' assembler keyword is supported], [gcry_cv_have___asm__], [gcry_cv_have___asm__=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("":::"memory"); }]])], [gcry_cv_have___asm__=yes])]) if test "$gcry_cv_have_asm" = "no" ; then if test "$gcry_cv_have___asm__" = "yes" ; then AC_DEFINE(asm,__asm__, [Define to supported assembler block keyword, if plain 'asm' was not supported]) fi fi # # Check whether the compiler supports inline assembly memory barrier. # if test "$gcry_cv_have_asm" = "no" ; then if test "$gcry_cv_have___asm__" = "yes" ; then AC_CACHE_CHECK([whether inline assembly memory barrier is supported], [gcry_cv_have_asm_volatile_memory], [gcry_cv_have_asm_volatile_memory=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__ volatile("":::"memory"); }]])], [gcry_cv_have_asm_volatile_memory=yes])]) fi else AC_CACHE_CHECK([whether inline assembly memory barrier is supported], [gcry_cv_have_asm_volatile_memory], [gcry_cv_have_asm_volatile_memory=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { asm volatile("":::"memory"); }]])], [gcry_cv_have_asm_volatile_memory=yes])]) fi if test "$gcry_cv_have_asm_volatile_memory" = "yes" ; then AC_DEFINE(HAVE_GCC_ASM_VOLATILE_MEMORY,1, [Define if inline asm memory barrier is supported]) fi # # Check whether GCC inline assembler supports SSSE3 instructions # This is required for the AES-NI instructions. # AC_CACHE_CHECK([whether GCC inline assembler supports SSSE3 instructions], [gcry_cv_gcc_inline_asm_ssse3], [gcry_cv_gcc_inline_asm_ssse3=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[static unsigned char be_mask[16] __attribute__ ((aligned (16))) = { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; void a(void) { __asm__("pshufb %[mask], %%xmm2\n\t"::[mask]"m"(*be_mask):); }]])], [gcry_cv_gcc_inline_asm_ssse3=yes])]) if test "$gcry_cv_gcc_inline_asm_ssse3" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_SSSE3,1, [Defined if inline assembler supports SSSE3 instructions]) fi # # Check whether GCC inline assembler supports PCLMUL instructions. # AC_CACHE_CHECK([whether GCC inline assembler supports PCLMUL instructions], [gcry_cv_gcc_inline_asm_pclmul], [gcry_cv_gcc_inline_asm_pclmul=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("pclmulqdq \$0, %%xmm1, %%xmm3\n\t":::"cc"); }]])], [gcry_cv_gcc_inline_asm_pclmul=yes])]) if test "$gcry_cv_gcc_inline_asm_pclmul" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_PCLMUL,1, [Defined if inline assembler supports PCLMUL instructions]) fi # # Check whether GCC inline assembler supports AVX instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AVX instructions], [gcry_cv_gcc_inline_asm_avx], [gcry_cv_gcc_inline_asm_avx=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("xgetbv; vaesdeclast (%[mem]),%%xmm0,%%xmm7\n\t"::[mem]"r"(0):); }]])], [gcry_cv_gcc_inline_asm_avx=yes])]) if test "$gcry_cv_gcc_inline_asm_avx" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AVX,1, [Defined if inline assembler supports AVX instructions]) fi # # Check whether GCC inline assembler supports AVX2 instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AVX2 instructions], [gcry_cv_gcc_inline_asm_avx2], [gcry_cv_gcc_inline_asm_avx2=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("xgetbv; vpbroadcastb %%xmm7,%%ymm1\n\t":::"cc"); }]])], [gcry_cv_gcc_inline_asm_avx2=yes])]) if test "$gcry_cv_gcc_inline_asm_avx2" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AVX2,1, [Defined if inline assembler supports AVX2 instructions]) fi # # Check whether GCC inline assembler supports BMI2 instructions # AC_CACHE_CHECK([whether GCC inline assembler supports BMI2 instructions], [gcry_cv_gcc_inline_asm_bmi2], [gcry_cv_gcc_inline_asm_bmi2=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("rorxl \$23, %%eax, %%edx\\n\\t":::"memory"); }]])], [gcry_cv_gcc_inline_asm_bmi2=yes])]) if test "$gcry_cv_gcc_inline_asm_bmi2" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_BMI2,1, [Defined if inline assembler supports BMI2 instructions]) fi # # Check whether GCC assembler needs "-Wa,--divide" to correctly handle # constant division # if test $amd64_as_feature_detection = yes; then AC_CACHE_CHECK([whether GCC assembler handles division correctly], [gcry_cv_gcc_as_const_division_ok], [gcry_cv_gcc_as_const_division_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__("xorl \$(123456789/12345678), %ebp;\n\t");]])], [gcry_cv_gcc_as_const_division_ok=yes])]) if test "$gcry_cv_gcc_as_const_division_ok" = "no" ; then # # Add '-Wa,--divide' to CPPFLAGS and try check again. # _gcc_cppflags_save="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -Wa,--divide" AC_CACHE_CHECK([whether GCC assembler handles division correctly with "-Wa,--divide"], [gcry_cv_gcc_as_const_division_with_wadivide_ok], [gcry_cv_gcc_as_const_division_with_wadivide_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__("xorl \$(123456789/12345678), %ebp;\n\t");]])], [gcry_cv_gcc_as_const_division_with_wadivide_ok=yes])]) if test "$gcry_cv_gcc_as_const_division_with_wadivide_ok" = "no" ; then # '-Wa,--divide' did not work, restore old flags. CPPFLAGS="$_gcc_cppflags_save" fi fi fi # # Check whether GCC assembler supports features needed for our amd64 # implementations # if test $amd64_as_feature_detection = yes; then AC_CACHE_CHECK([whether GCC assembler is compatible for amd64 assembly implementations], [gcry_cv_gcc_amd64_platform_as_ok], [gcry_cv_gcc_amd64_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( /* Test if '.type' and '.size' are supported. */ /* These work only on ELF targets. */ /* TODO: add COFF (mingw64, cygwin64) support to assembly * implementations. Mingw64/cygwin64 also require additional * work because they use different calling convention. */ "asmfunc:\n\t" ".size asmfunc,.-asmfunc;\n\t" ".type asmfunc,@function;\n\t" /* Test if assembler allows use of '/' for constant division * (Solaris/x86 issue). If previous constant division check * and "-Wa,--divide" workaround failed, this causes assembly * to be disable on this machine. */ "xorl \$(123456789/12345678), %ebp;\n\t" );]])], [gcry_cv_gcc_amd64_platform_as_ok=yes])]) if test "$gcry_cv_gcc_amd64_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_AMD64_PLATFORM_AS,1, [Defined if underlying assembler is compatible with amd64 assembly implementations]) fi fi # # Check whether GCC assembler supports features needed for assembly # implementations that use Intel syntax # AC_CACHE_CHECK([whether GCC assembler is compatible for Intel syntax assembly implementations], [gcry_cv_gcc_platform_as_ok_for_intel_syntax], [gcry_cv_gcc_platform_as_ok_for_intel_syntax=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".intel_syntax noprefix\n\t" "pxor xmm1, xmm7;\n\t" /* Intel syntax implementation also use GAS macros, so check * for them here. */ "VAL_A = xmm4\n\t" "VAL_B = xmm2\n\t" ".macro SET_VAL_A p1\n\t" " VAL_A = \\\\p1 \n\t" ".endm\n\t" ".macro SET_VAL_B p1\n\t" " VAL_B = \\\\p1 \n\t" ".endm\n\t" "vmovdqa VAL_A, VAL_B;\n\t" "SET_VAL_A eax\n\t" "SET_VAL_B ebp\n\t" "add VAL_A, VAL_B;\n\t" "add VAL_B, 0b10101;\n\t" );]])], [gcry_cv_gcc_platform_as_ok_for_intel_syntax=yes])]) if test "$gcry_cv_gcc_platform_as_ok_for_intel_syntax" = "yes" ; then AC_DEFINE(HAVE_INTEL_SYNTAX_PLATFORM_AS,1, [Defined if underlying assembler is compatible with Intel syntax assembly implementations]) fi # # Check whether compiler is configured for ARMv6 or newer architecture # AC_CACHE_CHECK([whether compiler is configured for ARMv6 or newer architecture], [gcry_cv_cc_arm_arch_is_v6], [AC_EGREP_CPP(yes, [#if defined(__arm__) && \ ((defined(__ARM_ARCH) && __ARM_ARCH >= 6) \ || defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) \ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) \ || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ || defined(__ARM_ARCH_7EM__)) yes #endif ], gcry_cv_cc_arm_arch_is_v6=yes, gcry_cv_cc_arm_arch_is_v6=no)]) if test "$gcry_cv_cc_arm_arch_is_v6" = "yes" ; then AC_DEFINE(HAVE_ARM_ARCH_V6,1, [Defined if ARM architecture is v6 or newer]) fi # # Check whether GCC inline assembler supports NEON instructions # AC_CACHE_CHECK([whether GCC inline assembler supports NEON instructions], [gcry_cv_gcc_inline_asm_neon], [gcry_cv_gcc_inline_asm_neon=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".syntax unified\n\t" ".thumb\n\t" ".fpu neon\n\t" "vld1.64 {%q0-%q1}, [%r0]!;\n\t" "vrev64.8 %q0, %q3;\n\t" "vadd.u64 %q0, %q1;\n\t" "vadd.s64 %d3, %d2, %d3;\n\t" ); ]])], [gcry_cv_gcc_inline_asm_neon=yes])]) if test "$gcry_cv_gcc_inline_asm_neon" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_NEON,1, [Defined if inline assembler supports NEON instructions]) fi # # Check whether GCC assembler supports features needed for our ARM # implementations # AC_CACHE_CHECK([whether GCC assembler is compatible for ARM assembly implementations], [gcry_cv_gcc_arm_platform_as_ok], [gcry_cv_gcc_arm_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( /* Test if assembler supports UAL syntax. */ ".syntax unified\n\t" ".arm\n\t" /* our assembly code is in ARM mode */ /* Following causes error if assembler ignored '.syntax unified'. */ "asmfunc:\n\t" "add %r0, %r0, %r4, ror #12;\n\t" /* Test if '.type' and '.size' are supported. */ ".size asmfunc,.-asmfunc;\n\t" ".type asmfunc,%function;\n\t" );]])], [gcry_cv_gcc_arm_platform_as_ok=yes])]) if test "$gcry_cv_gcc_arm_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_ARM_PLATFORM_AS,1, [Defined if underlying assembler is compatible with ARM assembly implementations]) fi ####################################### #### Checks for library functions. #### ####################################### AC_FUNC_VPRINTF # We have replacements for these in src/missing-string.c AC_CHECK_FUNCS(stpcpy strcasecmp) # We have replacements for these in src/g10lib.h AC_CHECK_FUNCS(strtoul memmove stricmp atexit raise) # Other checks AC_CHECK_FUNCS(strerror rand mmap getpagesize sysconf waitpid wait4) AC_CHECK_FUNCS(gettimeofday getrusage gethrtime clock_gettime syslog) AC_CHECK_FUNCS(fcntl ftruncate) GNUPG_CHECK_MLOCK # # Replacement functions. # AC_REPLACE_FUNCS([getpid clock]) # # Check wether it is necessary to link against libdl. # DL_LIBS="" if test "$use_hmac_binary_check" = yes ; then _gcry_save_libs="$LIBS" LIBS="" AC_SEARCH_LIBS(dlopen, c dl,,,) DL_LIBS=$LIBS LIBS="$_gcry_save_libs" LIBGCRYPT_CONFIG_LIBS="${LIBGCRYPT_CONFIG_LIBS} ${DL_LIBS}" fi AC_SUBST(DL_LIBS) # # Check whether we can use Linux capabilities as requested. # if test "$use_capabilities" = "yes" ; then use_capabilities=no AC_CHECK_HEADERS(sys/capability.h) if test "$ac_cv_header_sys_capability_h" = "yes" ; then AC_CHECK_LIB(cap, cap_init, ac_need_libcap=1) if test "$ac_cv_lib_cap_cap_init" = "yes"; then AC_DEFINE(USE_CAPABILITIES,1, [define if capabilities should be used]) LIBS="$LIBS -lcap" use_capabilities=yes fi fi if test "$use_capabilities" = "no" ; then AC_MSG_WARN([[ *** *** The use of capabilities on this system is not possible. *** You need a recent Linux kernel and some patches: *** fcaps-2.2.9-990610.patch (kernel patch for 2.2.9) *** fcap-module-990613.tar.gz (kernel module) *** libcap-1.92.tar.gz (user mode library and utilities) *** And you have to configure the kernel with CONFIG_VFS_CAP_PLUGIN *** set (filesystems menu). Be warned: This code is *really* ALPHA. ***]]) fi fi # Check whether a random device is available. if test "$try_dev_random" = yes ; then AC_CACHE_CHECK(for random device, ac_cv_have_dev_random, [if test -r "$NAME_OF_DEV_RANDOM" && test -r "$NAME_OF_DEV_URANDOM" ; then ac_cv_have_dev_random=yes; else ac_cv_have_dev_random=no; fi]) if test "$ac_cv_have_dev_random" = yes; then AC_DEFINE(HAVE_DEV_RANDOM,1, [defined if the system supports a random device] ) fi else AC_MSG_CHECKING(for random device) ac_cv_have_dev_random=no AC_MSG_RESULT(has been disabled) fi # Figure out the random modules for this configuration. if test "$random" = "default"; then # Select default value. if test "$ac_cv_have_dev_random" = yes; then # Try Linuxish random device. random_modules="linux" else case "${host}" in *-*-mingw32ce*) # WindowsCE random device. random_modules="w32ce" ;; *-*-mingw32*|*-*-cygwin*) # Windows random device. random_modules="w32" ;; *) # Build everything, allow to select at runtime. random_modules="$auto_random_modules" ;; esac fi else if test "$random" = "auto"; then # Build everything, allow to select at runtime. random_modules="$auto_random_modules" else random_modules="$random" fi fi # # Setup assembler stuff. # # Note that config.links also defines mpi_cpu_arch, which is required # later on. # GNUPG_SYS_SYMBOL_UNDERSCORE() AC_ARG_ENABLE(mpi-path, AC_HELP_STRING([--enable-mpi-path=EXTRA_PATH], [prepend EXTRA_PATH to list of CPU specific optimizations]), mpi_extra_path="$enableval",mpi_extra_path="") AC_MSG_CHECKING(for mpi assembler functions) if test -f $srcdir/mpi/config.links ; then . $srcdir/mpi/config.links AC_CONFIG_LINKS("$mpi_ln_list") ac_cv_mpi_sflags="$mpi_sflags" AC_MSG_RESULT(done) else AC_MSG_RESULT(failed) AC_MSG_ERROR([mpi/config.links missing!]) fi MPI_SFLAGS="$ac_cv_mpi_sflags" AC_SUBST(MPI_SFLAGS) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_ADD1, test "$mpi_mod_asm_mpih_add1" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_SUB1, test "$mpi_mod_asm_mpih_sub1" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL1, test "$mpi_mod_asm_mpih_mul1" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL2, test "$mpi_mod_asm_mpih_mul2" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL3, test "$mpi_mod_asm_mpih_mul3" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_LSHIFT, test "$mpi_mod_asm_mpih_lshift" = yes) AM_CONDITIONAL(MPI_MOD_ASM_MPIH_RSHIFT, test "$mpi_mod_asm_mpih_rshift" = yes) AM_CONDITIONAL(MPI_MOD_ASM_UDIV, test "$mpi_mod_asm_udiv" = yes) AM_CONDITIONAL(MPI_MOD_ASM_UDIV_QRNND, test "$mpi_mod_asm_udiv_qrnnd" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_ADD1, test "$mpi_mod_c_mpih_add1" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_SUB1, test "$mpi_mod_c_mpih_sub1" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL1, test "$mpi_mod_c_mpih_mul1" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL2, test "$mpi_mod_c_mpih_mul2" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL3, test "$mpi_mod_c_mpih_mul3" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_LSHIFT, test "$mpi_mod_c_mpih_lshift" = yes) AM_CONDITIONAL(MPI_MOD_C_MPIH_RSHIFT, test "$mpi_mod_c_mpih_rshift" = yes) AM_CONDITIONAL(MPI_MOD_C_UDIV, test "$mpi_mod_c_udiv" = yes) AM_CONDITIONAL(MPI_MOD_C_UDIV_QRNND, test "$mpi_mod_c_udiv_qrnnd" = yes) if test mym4_isgit = "yes"; then AC_DEFINE(IS_DEVELOPMENT_VERSION,1, [Defined if this is not a regular release]) fi AM_CONDITIONAL(CROSS_COMPILING, test x$cross_compiling = xyes) # This is handy for debugging so the compiler doesn't rearrange # things and eliminate variables. AC_ARG_ENABLE(optimization, AC_HELP_STRING([--disable-optimization], [disable compiler optimization]), [if test $enableval = no ; then CFLAGS=`echo $CFLAGS | sed 's/-O[[0-9]]//'` fi]) # CFLAGS mangling when using gcc. if test "$GCC" = yes; then CFLAGS="$CFLAGS -Wall" if test "$USE_MAINTAINER_MODE" = "yes"; then CFLAGS="$CFLAGS -Wcast-align -Wshadow -Wstrict-prototypes" CFLAGS="$CFLAGS -Wformat -Wno-format-y2k -Wformat-security" # If -Wno-missing-field-initializers is supported we can enable a # a bunch of really useful warnings. AC_MSG_CHECKING([if gcc supports -Wno-missing-field-initializers]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wno-missing-field-initializers" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],_gcc_wopt=yes,_gcc_wopt=no) AC_MSG_RESULT($_gcc_wopt) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_wopt" = xyes ; then CFLAGS="$CFLAGS -W -Wextra -Wbad-function-cast" CFLAGS="$CFLAGS -Wwrite-strings" CFLAGS="$CFLAGS -Wdeclaration-after-statement" CFLAGS="$CFLAGS -Wno-missing-field-initializers" CFLAGS="$CFLAGS -Wno-sign-compare" fi AC_MSG_CHECKING([if gcc supports -Wpointer-arith]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wpointer-arith" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],_gcc_wopt=yes,_gcc_wopt=no) AC_MSG_RESULT($_gcc_wopt) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_wopt" = xyes ; then CFLAGS="$CFLAGS -Wpointer-arith" fi fi fi # Check whether as(1) supports a noeexecstack feature. This test # includes an override option. CL_AS_NOEXECSTACK AC_SUBST(LIBGCRYPT_CONFIG_API_VERSION) AC_SUBST(LIBGCRYPT_CONFIG_LIBS) AC_SUBST(LIBGCRYPT_CONFIG_CFLAGS) AC_SUBST(LIBGCRYPT_CONFIG_HOST) AC_SUBST(LIBGCRYPT_THREAD_MODULES) AC_CONFIG_COMMANDS([gcrypt-conf],[[ chmod +x src/libgcrypt-config ]],[[ prefix=$prefix exec_prefix=$exec_prefix libdir=$libdir datadir=$datadir DATADIRNAME=$DATADIRNAME ]]) ##################### #### Conclusion. #### ##################### # Check that requested feature can actually be used and define # ENABLE_foo_SUPPORT macros. if test x"$aesnisupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_ssse3" != "yes" ; then aesnisupport="no (unsupported by compiler)" fi fi if test x"$pclmulsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_pclmul" != "yes" ; then pclmulsupport="no (unsupported by compiler)" fi fi if test x"$avxsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_avx" != "yes" ; then avxsupport="no (unsupported by compiler)" fi fi if test x"$avx2support" = xyes ; then if test "$gcry_cv_gcc_inline_asm_avx2" != "yes" ; then avx2support="no (unsupported by compiler)" fi fi if test x"$neonsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_neon" != "yes" ; then neonsupport="no (unsupported by compiler)" fi fi if test x"$aesnisupport" = xyes ; then AC_DEFINE(ENABLE_AESNI_SUPPORT, 1, [Enable support for Intel AES-NI instructions.]) fi if test x"$pclmulsupport" = xyes ; then AC_DEFINE(ENABLE_PCLMUL_SUPPORT, 1, [Enable support for Intel PCLMUL instructions.]) fi if test x"$avxsupport" = xyes ; then AC_DEFINE(ENABLE_AVX_SUPPORT,1, [Enable support for Intel AVX instructions.]) fi if test x"$avx2support" = xyes ; then AC_DEFINE(ENABLE_AVX2_SUPPORT,1, [Enable support for Intel AVX2 instructions.]) fi if test x"$neonsupport" = xyes ; then AC_DEFINE(ENABLE_NEON_SUPPORT,1, [Enable support for ARM NEON instructions.]) fi # Define conditional sources and config.h symbols depending on the # selected ciphers, pubkey-ciphers, digests, kdfs, and random modules. LIST_MEMBER(arcfour, $enabled_ciphers) if test "$found" = "1"; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS arcfour.lo" AC_DEFINE(USE_ARCFOUR, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS arcfour-amd64.lo" ;; esac fi LIST_MEMBER(blowfish, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish.lo" AC_DEFINE(USE_BLOWFISH, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish-arm.lo" ;; esac fi LIST_MEMBER(cast5, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5.lo" AC_DEFINE(USE_CAST5, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5-arm.lo" ;; esac fi LIST_MEMBER(des, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS des.lo" AC_DEFINE(USE_DES, 1, [Defined if this module should be included]) fi LIST_MEMBER(aes, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael.lo" AC_DEFINE(USE_AES, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-arm.lo" ;; esac fi LIST_MEMBER(twofish, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish.lo" AC_DEFINE(USE_TWOFISH, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-arm.lo" ;; esac fi LIST_MEMBER(serpent, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent.lo" AC_DEFINE(USE_SERPENT, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the SSE2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-sse2-amd64.lo" ;; esac if test x"$avx2support" = xyes ; then # Build with the AVX2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-avx2-amd64.lo" fi if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-armv7-neon.lo" fi fi LIST_MEMBER(rfc2268, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS rfc2268.lo" AC_DEFINE(USE_RFC2268, 1, [Defined if this module should be included]) fi LIST_MEMBER(seed, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS seed.lo" AC_DEFINE(USE_SEED, 1, [Defined if this module should be included]) fi LIST_MEMBER(camellia, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia.lo camellia-glue.lo" AC_DEFINE(USE_CAMELLIA, 1, [Defined if this module should be included]) case "${host}" in arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-arm.lo" ;; esac if test x"$avxsupport" = xyes ; then if test x"$aesnisupport" = xyes ; then # Build with the AES-NI/AVX implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-aesni-avx-amd64.lo" fi fi if test x"$avx2support" = xyes ; then if test x"$aesnisupport" = xyes ; then # Build with the AES-NI/AVX2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-aesni-avx2-amd64.lo" fi fi fi LIST_MEMBER(idea, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS idea.lo" AC_DEFINE(USE_IDEA, 1, [Defined if this module should be included]) fi LIST_MEMBER(salsa20, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20.lo" AC_DEFINE(USE_SALSA20, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20-amd64.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20-armv7-neon.lo" fi fi LIST_MEMBER(gost28147, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS gost28147.lo" AC_DEFINE(USE_GOST28147, 1, [Defined if this module should be included]) fi LIST_MEMBER(dsa, $enabled_pubkey_ciphers) if test "$found" = "1" ; then GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS dsa.lo" AC_DEFINE(USE_DSA, 1, [Defined if this module should be included]) fi LIST_MEMBER(rsa, $enabled_pubkey_ciphers) if test "$found" = "1" ; then GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS rsa.lo" AC_DEFINE(USE_RSA, 1, [Defined if this module should be included]) fi LIST_MEMBER(elgamal, $enabled_pubkey_ciphers) if test "$found" = "1" ; then GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS elgamal.lo" AC_DEFINE(USE_ELGAMAL, 1, [Defined if this module should be included]) fi LIST_MEMBER(ecc, $enabled_pubkey_ciphers) if test "$found" = "1" ; then GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS \ ecc.lo ecc-curves.lo ecc-misc.lo \ ecc-ecdsa.lo ecc-eddsa.lo ecc-gost.lo" AC_DEFINE(USE_ECC, 1, [Defined if this module should be included]) fi LIST_MEMBER(crc, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS crc.lo" AC_DEFINE(USE_CRC, 1, [Defined if this module should be included]) fi LIST_MEMBER(gostr3411-94, $enabled_digests) if test "$found" = "1" ; then # GOST R 34.11-94 internally uses GOST 28147-89 LIST_MEMBER(gost28147, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS gostr3411-94.lo" AC_DEFINE(USE_GOST_R_3411_94, 1, [Defined if this module should be included]) fi fi LIST_MEMBER(stribog, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS stribog.lo" AC_DEFINE(USE_GOST_R_3411_12, 1, [Defined if this module should be included]) fi LIST_MEMBER(md4, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS md4.lo" AC_DEFINE(USE_MD4, 1, [Defined if this module should be included]) fi LIST_MEMBER(md5, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS md5.lo" AC_DEFINE(USE_MD5, 1, [Defined if this module should be included]) fi LIST_MEMBER(sha256, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256.lo" AC_DEFINE(USE_SHA256, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-avx2-bmi2-amd64.lo" ;; esac fi LIST_MEMBER(sha512, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512.lo" AC_DEFINE(USE_SHA512, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-avx2-bmi2-amd64.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-armv7-neon.lo" fi fi LIST_MEMBER(tiger, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS tiger.lo" AC_DEFINE(USE_TIGER, 1, [Defined if this module should be included]) fi LIST_MEMBER(whirlpool, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS whirlpool.lo" AC_DEFINE(USE_WHIRLPOOL, 1, [Defined if this module should be included]) fi # rmd160 and sha1 should be included always. GCRYPT_DIGESTS="$GCRYPT_DIGESTS rmd160.lo sha1.lo" AC_DEFINE(USE_RMD160, 1, [Defined if this module should be included]) AC_DEFINE(USE_SHA1, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-avx-bmi2-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-armv7-neon.lo" ;; esac LIST_MEMBER(scrypt, $enabled_kdfs) if test "$found" = "1" ; then GCRYPT_KDFS="$GCRYPT_KDFS scrypt.lo" AC_DEFINE(USE_SCRYPT, 1, [Defined if this module should be included]) fi LIST_MEMBER(linux, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndlinux.lo" AC_DEFINE(USE_RNDLINUX, 1, [Defined if the /dev/random RNG should be used.]) fi LIST_MEMBER(unix, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndunix.lo" AC_DEFINE(USE_RNDUNIX, 1, [Defined if the default Unix RNG should be used.]) print_egd_notice=yes fi LIST_MEMBER(egd, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndegd.lo" AC_DEFINE(USE_RNDEGD, 1, [Defined if the EGD based RNG should be used.]) fi LIST_MEMBER(w32, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndw32.lo" AC_DEFINE(USE_RNDW32, 1, [Defined if the Windows specific RNG should be used.]) fi LIST_MEMBER(w32ce, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndw32ce.lo" AC_DEFINE(USE_RNDW32CE, 1, [Defined if the WindowsCE specific RNG should be used.]) fi AC_SUBST([GCRYPT_CIPHERS]) AC_SUBST([GCRYPT_PUBKEY_CIPHERS]) AC_SUBST([GCRYPT_DIGESTS]) AC_SUBST([GCRYPT_KDFS]) AC_SUBST([GCRYPT_RANDOM]) AC_SUBST(LIBGCRYPT_CIPHERS, $enabled_ciphers) AC_SUBST(LIBGCRYPT_PUBKEY_CIPHERS, $enabled_pubkey_ciphers) AC_SUBST(LIBGCRYPT_DIGESTS, $enabled_digests) # For printing the configuration we need a colon separated list of # algorithm names. tmp=`echo "$enabled_ciphers" | tr ' ' : ` AC_DEFINE_UNQUOTED(LIBGCRYPT_CIPHERS, "$tmp", [List of available cipher algorithms]) tmp=`echo "$enabled_pubkey_ciphers" | tr ' ' : ` AC_DEFINE_UNQUOTED(LIBGCRYPT_PUBKEY_CIPHERS, "$tmp", [List of available public key cipher algorithms]) tmp=`echo "$enabled_digests" | tr ' ' : ` AC_DEFINE_UNQUOTED(LIBGCRYPT_DIGESTS, "$tmp", [List of available digest algorithms]) tmp=`echo "$enabled_kdfs" | tr ' ' : ` AC_DEFINE_UNQUOTED(LIBGCRYPT_KDFS, "$tmp", [List of available KDF algorithms]) # # Define conditional sources depending on the used hardware platform. # Note that all possible modules must also be listed in # src/Makefile.am (EXTRA_libgcrypt_la_SOURCES). # GCRYPT_HWF_MODULES= case "$mpi_cpu_arch" in x86) AC_DEFINE(HAVE_CPU_ARCH_X86, 1, [Defined for the x86 platforms]) GCRYPT_HWF_MODULES="hwf-x86.lo" ;; alpha) AC_DEFINE(HAVE_CPU_ARCH_ALPHA, 1, [Defined for Alpha platforms]) ;; sparc) AC_DEFINE(HAVE_CPU_ARCH_SPARC, 1, [Defined for SPARC platforms]) ;; mips) AC_DEFINE(HAVE_CPU_ARCH_MIPS, 1, [Defined for MIPS platforms]) ;; m68k) AC_DEFINE(HAVE_CPU_ARCH_M68K, 1, [Defined for M68k platforms]) ;; ppc) AC_DEFINE(HAVE_CPU_ARCH_PPC, 1, [Defined for PPC platforms]) ;; arm) AC_DEFINE(HAVE_CPU_ARCH_ARM, 1, [Defined for ARM platforms]) GCRYPT_HWF_MODULES="hwf-arm.lo" ;; esac AC_SUBST([GCRYPT_HWF_MODULES]) # # Provide information about the build. # BUILD_REVISION="mym4_revision" AC_SUBST(BUILD_REVISION) AC_DEFINE_UNQUOTED(BUILD_REVISION, "$BUILD_REVISION", [GIT commit id revision used to build this package]) changequote(,)dnl BUILD_FILEVERSION=`echo "$VERSION" | sed 's/\([0-9.]*\).*/\1./;s/\./,/g'` changequote([,])dnl BUILD_FILEVERSION="${BUILD_FILEVERSION}mym4_revision_dec" AC_SUBST(BUILD_FILEVERSION) BUILD_TIMESTAMP=`date -u +%Y-%m-%dT%H:%M+0000 2>/dev/null || date` AC_SUBST(BUILD_TIMESTAMP) AC_DEFINE_UNQUOTED(BUILD_TIMESTAMP, "$BUILD_TIMESTAMP", [The time this package was configured for a build]) # And create the files. AC_CONFIG_FILES([ Makefile m4/Makefile compat/Makefile mpi/Makefile cipher/Makefile random/Makefile doc/Makefile src/Makefile src/gcrypt.h src/libgcrypt-config src/versioninfo.rc tests/Makefile ]) AC_CONFIG_FILES([tests/hashtest-256g], [chmod +x tests/hashtest-256g]) AC_OUTPUT detection_module="${GCRYPT_HWF_MODULES%.lo}" test -n "$detection_module" || detection_module="none" # Give some feedback GCRY_MSG_SHOW([],[]) GCRY_MSG_SHOW([Libgcrypt],[v${VERSION} has been configured as follows:]) GCRY_MSG_SHOW([],[]) GCRY_MSG_SHOW([Platform: ],[$PRINTABLE_OS_NAME ($host)]) GCRY_MSG_SHOW([Hardware detection module:],[$detection_module]) GCRY_MSG_WRAP([Enabled cipher algorithms:],[$enabled_ciphers]) GCRY_MSG_WRAP([Enabled digest algorithms:],[$enabled_digests]) GCRY_MSG_WRAP([Enabled kdf algorithms: ],[$enabled_kdfs]) GCRY_MSG_WRAP([Enabled pubkey algorithms:],[$enabled_pubkey_ciphers]) GCRY_MSG_SHOW([Random number generator: ],[$random]) GCRY_MSG_SHOW([Using linux capabilities: ],[$use_capabilities]) GCRY_MSG_SHOW([Try using Padlock crypto: ],[$padlocksupport]) GCRY_MSG_SHOW([Try using AES-NI crypto: ],[$aesnisupport]) GCRY_MSG_SHOW([Try using Intel PCLMUL: ],[$pclmulsupport]) GCRY_MSG_SHOW([Try using DRNG (RDRAND): ],[$drngsupport]) GCRY_MSG_SHOW([Try using Intel AVX: ],[$avxsupport]) GCRY_MSG_SHOW([Try using Intel AVX2: ],[$avx2support]) GCRY_MSG_SHOW([Try using ARM NEON: ],[$neonsupport]) GCRY_MSG_SHOW([],[]) if test "$print_egd_notice" = "yes"; then cat < @end example The name space of Libgcrypt is @code{gcry_*} for function and type names and @code{GCRY*} for other symbols. In addition the same name prefixes with one prepended underscore are reserved for internal use and should never be used by an application. Note that Libgcrypt uses libgpg-error, which uses @code{gpg_*} as name space for function and type names and @code{GPG_*} for other symbols, including all the error codes. @noindent Certain parts of gcrypt.h may be excluded by defining these macros: @table @code @item GCRYPT_NO_MPI_MACROS Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}. @item GCRYPT_NO_DEPRECATED Do not include definitions for deprecated features. This is useful to make sure that no deprecated features are used. @end table @node Building sources @section Building sources If you want to compile a source file including the `gcrypt.h' header file, you must make sure that the compiler can find it in the directory hierarchy. This is accomplished by adding the path to the directory in which the header file is located to the compilers include file search path (via the @option{-I} option). However, the path to the include file is determined at the time the source is configured. To solve this problem, Libgcrypt ships with a small helper program @command{libgcrypt-config} that knows the path to the include file and other configuration options. The options that need to be added to the compiler invocation at compile time are output by the @option{--cflags} option to @command{libgcrypt-config}. The following example shows how it can be used at the command line: @example gcc -c foo.c `libgcrypt-config --cflags` @end example Adding the output of @samp{libgcrypt-config --cflags} to the compilers command line will ensure that the compiler can find the Libgcrypt header file. A similar problem occurs when linking the program with the library. Again, the compiler has to find the library files. For this to work, the path to the library files has to be added to the library search path (via the @option{-L} option). For this, the option @option{--libs} to @command{libgcrypt-config} can be used. For convenience, this option also outputs all other options that are required to link the program with the Libgcrypt libraries (in particular, the @samp{-lgcrypt} option). The example shows how to link @file{foo.o} with the Libgcrypt library to a program @command{foo}. @example gcc -o foo foo.o `libgcrypt-config --libs` @end example Of course you can also combine both examples to a single command by specifying both options to @command{libgcrypt-config}: @example gcc -o foo foo.c `libgcrypt-config --cflags --libs` @end example @node Building sources using Automake @section Building sources using Automake It is much easier if you use GNU Automake instead of writing your own Makefiles. If you do that, you do not have to worry about finding and invoking the @command{libgcrypt-config} script at all. Libgcrypt provides an extension to Automake that does all the work for you. @c A simple macro for optional variables. @macro ovar{varname} @r{[}@var{\varname\}@r{]} @end macro @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found}) Check whether Libgcrypt (at least version @var{minimum-version}, if given) exists on the host system. If it is found, execute @var{action-if-found}, otherwise do @var{action-if-not-found}, if given. Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the flags needed for compilation of the program to find the @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker flags needed to link the program to the Libgcrypt library. @end defmac You can use the defined Autoconf variables like this in your @file{Makefile.am}: @example AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS) LDADD = $(LIBGCRYPT_LIBS) @end example @node Initializing the library @section Initializing the library Before the library can be used, it must initialize itself. This is achieved by invoking the function @code{gcry_check_version} described below. Also, it is often desirable to check that the version of Libgcrypt used is indeed one which fits all requirements. Even with binary compatibility, new features may have been introduced, but due to problem with the dynamic linker an old version may actually be used. So you may want to check that the version is okay right after program startup. @deftypefun {const char *} gcry_check_version (const char *@var{req_version}) The function @code{gcry_check_version} initializes some subsystems used by Libgcrypt and must be invoked before any other function in the -library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS} command -(called via the @code{gcry_control} function). +library. @xref{Multi-Threading}. Furthermore, this function returns the version number of the library. It can also verify that the version number is higher than a certain required version number @var{req_version}, if this value is not a null pointer. @end deftypefun Libgcrypt uses a concept known as secure memory, which is a region of memory set aside for storing sensitive data. Because such memory is a scarce resource, it needs to be setup in advanced to a fixed size. Further, most operating systems have special requirements on how that secure memory can be used. For example, it might be required to install an application as ``setuid(root)'' to allow allocating such memory. Libgcrypt requires a sequence of initialization steps to make sure that this works correctly. The following examples show the necessary steps. If you don't have a need for secure memory, for example if your application does not use secret keys or other confidential data or it runs in a controlled environment where key material floating around in memory is not a problem, you should initialize Libgcrypt this way: @example /* Version check should be the very first call because it makes sure that important subsystems are intialized. */ if (!gcry_check_version (GCRYPT_VERSION)) @{ fputs ("libgcrypt version mismatch\n", stderr); exit (2); @} /* Disable secure memory. */ gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* ... If required, other initialization goes here. */ /* Tell Libgcrypt that initialization has completed. */ gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); @end example If you have to protect your keys or other information in memory against being swapped out to disk and to enable an automatic overwrite of used and freed memory, you need to initialize Libgcrypt this way: @example /* Version check should be the very first call because it makes sure that important subsystems are initialized. */ if (!gcry_check_version (GCRYPT_VERSION)) @{ fputs ("libgcrypt version mismatch\n", stderr); exit (2); @} @anchor{sample-use-suspend-secmem} /* We don't want to see any warnings, e.g. because we have not yet parsed program options which might be used to suppress such warnings. */ gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); /* ... If required, other initialization goes here. Note that the process might still be running with increased privileges and that the secure memory has not been initialized. */ /* Allocate a pool of 16k secure memory. This make the secure memory available and also drops privileges where needed. */ gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); @anchor{sample-use-resume-secmem} /* It is now okay to let Libgcrypt complain when there was/is a problem with the secure memory. */ gcry_control (GCRYCTL_RESUME_SECMEM_WARN); /* ... If required, other initialization goes here. */ /* Tell Libgcrypt that initialization has completed. */ gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); @end example It is important that these initialization steps are not done by a library but by the actual application. A library using Libgcrypt might want to check for finished initialization using: @example if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P)) @{ fputs ("libgcrypt has not been initialized\n", stderr); abort (); @} @end example Instead of terminating the process, the library may instead print a warning and try to initialize Libgcrypt itself. See also the section on multi-threading below for more pitfalls. @node Multi-Threading @section Multi-Threading As mentioned earlier, the Libgcrypt library is thread-safe if you adhere to the following requirements: @itemize @bullet @item -If your application is multi-threaded, you must set the thread support -callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command -@strong{before} any other function in the library. - -This is easy enough if you are indeed writing an application using -Libgcrypt. It is rather problematic if you are writing a library -instead. Here are some tips what to do if you are writing a library: - -If your library requires a certain thread package, just initialize -Libgcrypt to use this thread package. If your library supports multiple -thread packages, but needs to be configured, you will have to -implement a way to determine which thread package the application -wants to use with your library anyway. Then configure Libgcrypt to use -this thread package. - -If your library is fully reentrant without any special support by a -thread package, then you are lucky indeed. Unfortunately, this does -not relieve you from doing either of the two above, or use a third -option. The third option is to let the application initialize Libgcrypt -for you. Then you are not using Libgcrypt transparently, though. - -As if this was not difficult enough, a conflict may arise if two -libraries try to initialize Libgcrypt independently of each others, and -both such libraries are then linked into the same application. To -make it a bit simpler for you, this will probably work, but only if -both libraries have the same requirement for the thread package. This -is currently only supported for the non-threaded case, GNU Pth and -pthread. - If you use pthread and your applications forks and does not directly call exec (even calling stdio functions), all kind of problems may occur. Future versions of Libgcrypt will try to cleanup using pthread_atfork but even that may lead to problems. This is a common problem with almost all applications using pthread and fork. -Note that future versions of Libgcrypt will drop this flexible thread -support and instead only support the platforms standard thread -implementation. - @item The function @code{gcry_check_version} must be called before any other -function in the library, except the @code{GCRYCTL_SET_THREAD_CBS} -command (called via the @code{gcry_control} function), because it -initializes the thread support subsystem in Libgcrypt. To +function in the library. To achieve this in multi-threaded programs, you must synchronize the memory with respect to other threads that also want to use Libgcrypt. For this, it is sufficient to call @code{gcry_check_version} before creating the other threads using Libgcrypt@footnote{At least this is true for POSIX threads, as @code{pthread_create} is a function that synchronizes memory with respects to other threads. There are many functions which have this property, a complete list can be found in POSIX, IEEE Std 1003.1-2003, Base Definitions, Issue 6, in the definition of the term ``Memory Synchronization''. For other thread packages, more relaxed or more strict rules may apply.}. @item Just like the function @code{gpg_strerror}, the function @code{gcry_strerror} is not thread safe. You have to use @code{gpg_strerror_r} instead. @end itemize -Libgcrypt contains convenient macros, which define the -necessary thread callbacks for PThread and for GNU Pth: - -@table @code -@item GCRY_THREAD_OPTION_PTH_IMPL - -This macro defines the following (static) symbols: -@code{gcry_pth_init}, @code{gcry_pth_mutex_init}, -@code{gcry_pth_mutex_destroy}, @code{gcry_pth_mutex_lock}, -@code{gcry_pth_mutex_unlock}, @code{gcry_pth_read}, -@code{gcry_pth_write}, @code{gcry_pth_select}, -@code{gcry_pth_waitpid}, @code{gcry_pth_accept}, -@code{gcry_pth_connect}, @code{gcry_threads_pth}. - -After including this macro, @code{gcry_control()} shall be used with a -command of @code{GCRYCTL_SET_THREAD_CBS} in order to register the -thread callback structure named ``gcry_threads_pth''. Example: - -@smallexample - ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth); -@end smallexample - - -@item GCRY_THREAD_OPTION_PTHREAD_IMPL - -This macro defines the following (static) symbols: -@code{gcry_pthread_mutex_init}, @code{gcry_pthread_mutex_destroy}, -@code{gcry_pthread_mutex_lock}, @code{gcry_pthread_mutex_unlock}, -@code{gcry_threads_pthread}. - -After including this macro, @code{gcry_control()} shall be used with a -command of @code{GCRYCTL_SET_THREAD_CBS} in order to register the -thread callback structure named ``gcry_threads_pthread''. Example: - -@smallexample - ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); -@end smallexample - - -@end table - -Note that these macros need to be terminated with a semicolon. Keep -in mind that these are convenient macros for C programmers; C++ -programmers might have to wrap these macros in an ``extern C'' body. - - @node Enabling FIPS mode @section How to enable the FIPS mode @cindex FIPS mode @cindex FIPS 140 Libgcrypt may be used in a FIPS 140-2 mode. Note, that this does not necessary mean that Libcgrypt is an appoved FIPS 140-2 module. Check the NIST database at @url{http://csrc.nist.gov/groups/STM/cmvp/} to see what versions of Libgcrypt are approved. Because FIPS 140 has certain restrictions on the use of cryptography which are not always wanted, Libgcrypt needs to be put into FIPS mode explicitly. Three alternative mechanisms are provided to switch Libgcrypt into this mode: @itemize @item If the file @file{/proc/sys/crypto/fips_enabled} exists and contains a numeric value other than @code{0}, Libgcrypt is put into FIPS mode at initialization time. Obviously this works only on systems with a @code{proc} file system (i.e. GNU/Linux). @item If the file @file{/etc/gcrypt/fips_enabled} exists, Libgcrypt is put into FIPS mode at initialization time. Note that this filename is hardwired and does not depend on any configuration options. @item If the application requests FIPS mode using the control command @code{GCRYCTL_FORCE_FIPS_MODE}. This must be done prior to any initialization (i.e. before @code{gcry_check_version}). @end itemize @cindex Enforced FIPS mode In addition to the standard FIPS mode, Libgcrypt may also be put into an Enforced FIPS mode by writing a non-zero value into the file @file{/etc/gcrypt/fips_enabled} or by using the control command @code{GCRYCTL_SET_ENFORCED_FIPS_FLAG} before any other calls to libgcrypt. The Enforced FIPS mode helps to detect applications which don't fulfill all requirements for using Libgcrypt in FIPS mode (@pxref{FIPS Mode}). Once Libgcrypt has been put into FIPS mode, it is not possible to switch back to standard mode without terminating the process first. If the logging verbosity level of Libgcrypt has been set to at least 2, the state transitions and the self-tests are logged. @node Hardware features @section How to disable hardware features @cindex hardware features Libgcrypt makes use of certain hardware features. If the use of a feature is not desired it may be either be disabled by a program or globally using a configuration file. The currently supported features are @table @code @item padlock-rng @item padlock-aes @item padlock-sha @item padlock-mmul @item intel-cpu @item intel-bmi2 @item intel-ssse3 @item intel-pclmul @item intel-aesni @item intel-rdrand @item intel-avx @item intel-avx2 @item arm-neon @end table To disable a feature for all processes using Libgcrypt 1.6 or newer, create the file @file{/etc/gcrypt/hwf.deny} and put each feature not to be used on a single line. Empty lines, white space, and lines prefixed with a hash mark are ignored. The file should be world readable. To disable a feature specifically for a program that program must tell it Libgcrypt before before calling @code{gcry_check_version}. Example:@footnote{NB. Libgcrypt uses the RDRAND feature only as one source of entropy. A CPU with a broken RDRAND will thus not compromise of the random number generator} @example gcry_control (GCRYCTL_DISABLE_HWF, "intel-rdrand", NULL); @end example @noindent To print the list of active features you may use this command: @example mpicalc --print-config | grep ^hwflist: | tr : '\n' | tail -n +2 @end example @c ********************************************************** @c ******************* General **************************** @c ********************************************************** @node Generalities @chapter Generalities @menu * Controlling the library:: Controlling Libgcrypt's behavior. * Error Handling:: Error codes and such. @end menu @node Controlling the library @section Controlling the library @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...) This function can be used to influence the general behavior of Libgcrypt in several ways. Depending on @var{cmd}, more arguments can or have to be provided. @table @code @item GCRYCTL_ENABLE_M_GUARD; Arguments: none This command enables the built-in memory guard. It must not be used to activate the memory guard after the memory management has already been used; therefore it can ONLY be used before @code{gcry_check_version}. Note that the memory guard is NOT used when the user of the library has set his own memory management callbacks. @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none This command inhibits the use the very secure random quality level (@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to @code{GCRY_STRONG_RANDOM}. In general this is not recommended. However, for some applications the extra quality random Libgcrypt tries to create is not justified and this option may help to get better performance. Please check with a crypto expert whether this option can be used for your application. This option can only be used at initialization time. @item GCRYCTL_DUMP_RANDOM_STATS; Arguments: none This command dumps random number generator related statistics to the library's logging stream. @item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none This command dumps memory management related statistics to the library's logging stream. @item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none This command dumps secure memory management related statistics to the library's logging stream. @item GCRYCTL_DROP_PRIVS; Arguments: none This command disables the use of secure memory and drops the privileges of the current process. This command has not much use; the suggested way to disable secure memory is to use @code{GCRYCTL_DISABLE_SECMEM} right after initialization. @item GCRYCTL_DISABLE_SECMEM; Arguments: none This command disables the use of secure memory. If this command is used in FIPS mode, FIPS mode will be disabled and the function @code{gcry_fips_mode_active} returns false. However, in Enforced FIPS mode this command has no effect at all. Many applications do not require secure memory, so they should disable it right away. This command should be executed right after @code{gcry_check_version}. @item GCRYCTL_DISABLE_LOCKED_SECMEM; Arguments: none This command disables the use of the mlock call for secure memory. Disabling the use of mlock may for example be done if an encrypted swap space is in use. This command should be executed right after @code{gcry_check_version}. @item GCRYCTL_DISABLE_PRIV_DROP; Arguments: none This command sets a global flag to tell the secure memory subsystem that it shall not drop privileges after secure memory has been allocated. This command is commonly used right after @code{gcry_check_version} but may also be used right away at program startup. It won't have an effect after the secure memory pool has been initialized. WARNING: A process running setuid(root) is a severe security risk. Processes making use of Libgcrypt or other complex code should drop these extra privileges as soon as possible. If this command has been used the caller is responsible for dropping the privileges. @item GCRYCTL_INIT_SECMEM; Arguments: int nbytes This command is used to allocate a pool of secure memory and thus enabling the use of secure memory. It also drops all extra privileges the process has (i.e. if it is run as setuid (root)). If the argument @var{nbytes} is 0, secure memory will be disabled. The minimum amount of secure memory allocated is currently 16384 bytes; you may thus use a value of 1 to request that default size. @item GCRYCTL_TERM_SECMEM; Arguments: none This command zeroises the secure memory and destroys the handler. The secure memory pool may not be used anymore after running this command. If the secure memory pool as already been destroyed, this command has no effect. Applications might want to run this command from their exit handler to make sure that the secure memory gets properly destroyed. This command is not necessarily thread-safe but that should not be needed in cleanup code. It may be called from a signal handler. @item GCRYCTL_DISABLE_SECMEM_WARN; Arguments: none Disable warning messages about problems with the secure memory subsystem. This command should be run right after @code{gcry_check_version}. @item GCRYCTL_SUSPEND_SECMEM_WARN; Arguments: none Postpone warning messages from the secure memory subsystem. @xref{sample-use-suspend-secmem,,the initialization example}, on how to use it. @item GCRYCTL_RESUME_SECMEM_WARN; Arguments: none Resume warning messages from the secure memory subsystem. @xref{sample-use-resume-secmem,,the initialization example}, on how to use it. @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none This command tells the PRNG to store random numbers in secure memory. This command should be run right after @code{gcry_check_version} and not later than the command GCRYCTL_INIT_SECMEM. Note that in FIPS mode the secure memory is always used. @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename This command specifies the file, which is to be used as seed file for the PRNG. If the seed file is registered prior to initialization of the PRNG, the seed file's content (if it exists and seems to be valid) is fed into the PRNG pool. After the seed file has been registered, the PRNG can be signalled to write out the PRNG pool's content into the seed file with the following command. @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none Write out the PRNG pool's content into the registered seed file. Multiple instances of the applications sharing the same random seed file can be started in parallel, in which case they will read out the same pool and then race for updating it (the last update overwrites earlier updates). They will differentiate only by the weak entropy that is added in read_seed_file based on the PID and clock, and up to 16 bytes of weak random non-blockingly. The consequence is that the output of these different instances is correlated to some extent. In a perfect attack scenario, the attacker can control (or at least guess) the PID and clock of the application, and drain the system's entropy pool to reduce the "up to 16 bytes" above to 0. Then the dependencies of the initial states of the pools are completely known. Note that this is not an issue if random of @code{GCRY_VERY_STRONG_RANDOM} quality is requested as in this case enough extra entropy gets mixed. It is also not an issue when using Linux (rndlinux driver), because this one guarantees to read full 16 bytes from /dev/urandom and thus there is no way for an attacker without kernel access to control these 16 bytes. @item GCRYCTL_CLOSE_RANDOM_DEVICE; Arguments: none Try to close the random device. If on Unix system you call fork(), the child process does no call exec(), and you do not intend to use Libgcrypt in the child, it might be useful to use this control code to close the inherited file descriptors of the random device. If Libgcrypt is later used again by the child, the device will be re-opened. On non-Unix systems this control code is ignored. @item GCRYCTL_SET_VERBOSITY; Arguments: int level This command sets the verbosity of the logging. A level of 0 disables all extra logging whereas positive numbers enable more verbose logging. The level may be changed at any time but be aware that no memory synchronization is done so the effect of this command might not immediately show up in other threads. This command may even be used prior to @code{gcry_check_version}. @item GCRYCTL_SET_DEBUG_FLAGS; Arguments: unsigned int flags Set the debug flag bits as given by the argument. Be aware that that no memory synchronization is done so the effect of this command might not immediately show up in other threads. The debug flags are not considered part of the API and thus may change without notice. As of now bit 0 enables debugging of cipher functions and bit 1 debugging of multi-precision-integers. This command may even be used prior to @code{gcry_check_version}. @item GCRYCTL_CLEAR_DEBUG_FLAGS; Arguments: unsigned int flags Set the debug flag bits as given by the argument. Be aware that that no memory synchronization is done so the effect of this command might not immediately show up in other threads. This command may even be used prior to @code{gcry_check_version}. @item GCRYCTL_DISABLE_INTERNAL_LOCKING; Arguments: none This command does nothing. It exists only for backward compatibility. @item GCRYCTL_ANY_INITIALIZATION_P; Arguments: none This command returns true if the library has been basically initialized. Such a basic initialization happens implicitly with many commands to get certain internal subsystems running. The common and suggested way to do this basic initialization is by calling gcry_check_version. @item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none This command tells the library that the application has finished the initialization. @item GCRYCTL_INITIALIZATION_FINISHED_P; Arguments: none This command returns true if the command@* GCRYCTL_INITIALIZATION_FINISHED has already been run. @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops -This command registers a thread-callback structure. -@xref{Multi-Threading}. +This command is obsolete since version 1.6. @item GCRYCTL_FAST_POLL; Arguments: none Run a fast random poll. @item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename This command may be used to override the default name of the EGD socket to connect to. It may be used only during initialization as it is not thread safe. Changing the socket name again is not supported. The function may return an error if the given filename is too long for a local socket name. EGD is an alternative random gatherer, used only on systems lacking a proper random device. @item GCRYCTL_PRINT_CONFIG; Arguments: FILE *stream This command dumps information pertaining to the configuration of the library to the given stream. If NULL is given for @var{stream}, the log system is used. This command may be used before the initialization has been finished but not before a @code{gcry_check_version}. @item GCRYCTL_OPERATIONAL_P; Arguments: none This command returns true if the library is in an operational state. This information makes only sense in FIPS mode. In contrast to other functions, this is a pure test function and won't put the library into FIPS mode or change the internal state. This command may be used before the initialization has been finished but not before a @code{gcry_check_version}. @item GCRYCTL_FIPS_MODE_P; Arguments: none This command returns true if the library is in FIPS mode. Note, that this is no indication about the current state of the library. This command may be used before the initialization has been finished but not before a @code{gcry_check_version}. An application may use this command or the convenience macro below to check whether FIPS mode is actually active. @deftypefun int gcry_fips_mode_active (void) Returns true if the FIPS mode is active. Note that this is implemented as a macro. @end deftypefun @item GCRYCTL_FORCE_FIPS_MODE; Arguments: none Running this command puts the library into FIPS mode. If the library is already in FIPS mode, a self-test is triggered and thus the library will be put into operational state. This command may be used before a call to @code{gcry_check_version} and that is actually the recommended way to let an application switch the library into FIPS mode. Note that Libgcrypt will reject an attempt to switch to fips mode during or after the initialization. @item GCRYCTL_SET_ENFORCED_FIPS_FLAG; Arguments: none Running this command sets the internal flag that puts the library into the enforced FIPS mode during the FIPS mode initialization. This command does not affect the library if the library is not put into the FIPS mode and it must be used before any other libgcrypt library calls that initialize the library such as @code{gcry_check_version}. Note that Libgcrypt will reject an attempt to switch to the enforced fips mode during or after the initialization. @item GCRYCTL_SET_PREFERRED_RNG_TYPE; Arguments: int These are advisory commands to select a certain random number generator. They are only advisory because libraries may not know what an application actually wants or vice versa. Thus Libgcrypt employs a priority check to select the actually used RNG. If an applications selects a lower priority RNG but a library requests a higher priority RNG Libgcrypt will switch to the higher priority RNG. Applications and libraries should use these control codes before @code{gcry_check_version}. The available generators are: @table @code @item GCRY_RNG_TYPE_STANDARD A conservative standard generator based on the ``Continuously Seeded Pseudo Random Number Generator'' designed by Peter Gutmann. @item GCRY_RNG_TYPE_FIPS A deterministic random number generator conforming to he document ``NIST-Recommended Random Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms'' (2005-01-31). This implementation uses the AES variant. @item GCRY_RNG_TYPE_SYSTEM A wrapper around the system's native RNG. On Unix system these are usually the /dev/random and /dev/urandom devices. @end table The default is @code{GCRY_RNG_TYPE_STANDARD} unless FIPS mode as been enabled; in which case @code{GCRY_RNG_TYPE_FIPS} is used and locked against further changes. @item GCRYCTL_GET_CURRENT_RNG_TYPE; Arguments: int * This command stores the type of the currently used RNG as an integer value at the provided address. @item GCRYCTL_SELFTEST; Arguments: none This may be used at anytime to have the library run all implemented self-tests. It works in standard and in FIPS mode. Returns 0 on success or an error code on failure. @item GCRYCTL_DISABLE_HWF; Arguments: const char *name Libgcrypt detects certain features of the CPU at startup time. For performance tests it is sometimes required not to use such a feature. This option may be used to disable a certain feature; i.e. Libgcrypt behaves as if this feature has not been detected. Note that the detection code might be run if the feature has been disabled. This command must be used at initialization time; i.e. before calling @code{gcry_check_version}. @end table @end deftypefun @c ********************************************************** @c ******************* Errors **************************** @c ********************************************************** @node Error Handling @section Error Handling Many functions in Libgcrypt can return an error if they fail. For this reason, the application should always catch the error condition and take appropriate measures, for example by releasing the resources and passing the error up to the caller, or by displaying a descriptive message to the user and cancelling the operation. Some error values do not indicate a system error or an error in the operation, but the result of an operation that failed properly. For example, if you try to decrypt a tempered message, the decryption will fail. Another error value actually means that the end of a data buffer or list has been reached. The following descriptions explain for many error codes what they mean usually. Some error values have specific meanings if returned by a certain functions. Such cases are described in the documentation of those functions. Libgcrypt uses the @code{libgpg-error} library. This allows to share the error codes with other components of the GnuPG system, and to pass error values transparently from the crypto engine, or some helper application of the crypto engine, to the user. This way no information is lost. As a consequence, Libgcrypt does not use its own identifiers for error codes, but uses those provided by @code{libgpg-error}. They usually start with @code{GPG_ERR_}. However, Libgcrypt does provide aliases for the functions defined in libgpg-error, which might be preferred for name space consistency. Most functions in Libgcrypt return an error code in the case of failure. For this reason, the application should always catch the error condition and take appropriate measures, for example by releasing the resources and passing the error up to the caller, or by displaying a descriptive message to the user and canceling the operation. Some error values do not indicate a system error or an error in the operation, but the result of an operation that failed properly. GnuPG components, including Libgcrypt, use an extra library named libgpg-error to provide a common error handling scheme. For more information on libgpg-error, see the according manual. @menu * Error Values:: The error value and what it means. * Error Sources:: A list of important error sources. * Error Codes:: A list of important error codes. * Error Strings:: How to get a descriptive string from a value. @end menu @node Error Values @subsection Error Values @cindex error values @cindex error codes @cindex error sources @deftp {Data type} {gcry_err_code_t} The @code{gcry_err_code_t} type is an alias for the @code{libgpg-error} type @code{gpg_err_code_t}. The error code indicates the type of an error, or the reason why an operation failed. A list of important error codes can be found in the next section. @end deftp @deftp {Data type} {gcry_err_source_t} The @code{gcry_err_source_t} type is an alias for the @code{libgpg-error} type @code{gpg_err_source_t}. The error source has not a precisely defined meaning. Sometimes it is the place where the error happened, sometimes it is the place where an error was encoded into an error value. Usually the error source will give an indication to where to look for the problem. This is not always true, but it is attempted to achieve this goal. A list of important error sources can be found in the next section. @end deftp @deftp {Data type} {gcry_error_t} The @code{gcry_error_t} type is an alias for the @code{libgpg-error} type @code{gpg_error_t}. An error value like this has always two components, an error code and an error source. Both together form the error value. Thus, the error value can not be directly compared against an error code, but the accessor functions described below must be used. However, it is guaranteed that only 0 is used to indicate success (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of the error value are set to 0, too. Note that in Libgcrypt, the error source is used purely for diagnostic purposes. Only the error code should be checked to test for a certain outcome of a function. The manual only documents the error code part of an error value. The error source is left unspecified and might be anything. @end deftp @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}}) The static inline function @code{gcry_err_code} returns the @code{gcry_err_code_t} component of the error value @var{err}. This function must be used to extract the error code from an error value in order to compare it with the @code{GPG_ERR_*} error code macros. @end deftypefun @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}}) The static inline function @code{gcry_err_source} returns the @code{gcry_err_source_t} component of the error value @var{err}. This function must be used to extract the error source from an error value in order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros. @end deftypefun @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}}) The static inline function @code{gcry_err_make} returns the error value consisting of the error source @var{source} and the error code @var{code}. This function can be used in callback functions to construct an error value to return it to the library. @end deftypefun @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}}) The static inline function @code{gcry_error} returns the error value consisting of the default error source and the error code @var{code}. For @acronym{GCRY} applications, the default error source is @code{GPG_ERR_SOURCE_USER_1}. You can define @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to change this default. This function can be used in callback functions to construct an error value to return it to the library. @end deftypefun The @code{libgpg-error} library provides error codes for all system error numbers it knows about. If @var{err} is an unknown error number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The following functions can be used to construct error values from system errno numbers. @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}}) The function @code{gcry_err_make_from_errno} is like @code{gcry_err_make}, but it takes a system error like @code{errno} instead of a @code{gcry_err_code_t} error code. @end deftypefun @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}}) The function @code{gcry_error_from_errno} is like @code{gcry_error}, but it takes a system error like @code{errno} instead of a @code{gcry_err_code_t} error code. @end deftypefun Sometimes you might want to map system error numbers to error codes directly, or map an error code representing a system error back to the system error number. The following functions can be used to do that. @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}}) The function @code{gcry_err_code_from_errno} returns the error code for the system error @var{err}. If @var{err} is not a known system error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}. @end deftypefun @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}}) The function @code{gcry_err_code_to_errno} returns the system error for the error code @var{err}. If @var{err} is not an error code representing a system error, or if this system error is not defined on this system, the function returns @code{0}. @end deftypefun @node Error Sources @subsection Error Sources @cindex error codes, list of The library @code{libgpg-error} defines an error source for every component of the GnuPG system. The error source part of an error value is not well defined. As such it is mainly useful to improve the diagnostic error message for the user. If the error code part of an error value is @code{0}, the whole error value will be @code{0}. In this case the error source part is of course @code{GPG_ERR_SOURCE_UNKNOWN}. The list of error sources that might occur in applications using @acronym{Libgcrypt} is: @table @code @item GPG_ERR_SOURCE_UNKNOWN The error source is not known. The value of this error source is @code{0}. @item GPG_ERR_SOURCE_GPGME The error source is @acronym{GPGME} itself. @item GPG_ERR_SOURCE_GPG The error source is GnuPG, which is the crypto engine used for the OpenPGP protocol. @item GPG_ERR_SOURCE_GPGSM The error source is GPGSM, which is the crypto engine used for the OpenPGP protocol. @item GPG_ERR_SOURCE_GCRYPT The error source is @code{libgcrypt}, which is used by crypto engines to perform cryptographic operations. @item GPG_ERR_SOURCE_GPGAGENT The error source is @command{gpg-agent}, which is used by crypto engines to perform operations with the secret key. @item GPG_ERR_SOURCE_PINENTRY The error source is @command{pinentry}, which is used by @command{gpg-agent} to query the passphrase to unlock a secret key. @item GPG_ERR_SOURCE_SCD The error source is the SmartCard Daemon, which is used by @command{gpg-agent} to delegate operations with the secret key to a SmartCard. @item GPG_ERR_SOURCE_KEYBOX The error source is @code{libkbx}, a library used by the crypto engines to manage local keyrings. @item GPG_ERR_SOURCE_USER_1 @item GPG_ERR_SOURCE_USER_2 @item GPG_ERR_SOURCE_USER_3 @item GPG_ERR_SOURCE_USER_4 These error sources are not used by any GnuPG component and can be used by other software. For example, applications using Libgcrypt can use them to mark error values coming from callback handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors created with @code{gcry_error} and @code{gcry_error_from_errno}, unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h}. @end table @node Error Codes @subsection Error Codes @cindex error codes, list of The library @code{libgpg-error} defines many error values. The following list includes the most important error codes. @table @code @item GPG_ERR_EOF This value indicates the end of a list, buffer or file. @item GPG_ERR_NO_ERROR This value indicates success. The value of this error code is @code{0}. Also, it is guaranteed that an error value made from the error code @code{0} will be @code{0} itself (as a whole). This means that the error source information is lost for this error code, however, as this error code indicates that no error occurred, this is generally not a problem. @item GPG_ERR_GENERAL This value means that something went wrong, but either there is not enough information about the problem to return a more useful error value, or there is no separate error value for this type of problem. @item GPG_ERR_ENOMEM This value means that an out-of-memory condition occurred. @item GPG_ERR_E... System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for the system error. @item GPG_ERR_INV_VALUE This value means that some user provided data was out of range. @item GPG_ERR_UNUSABLE_PUBKEY This value means that some recipients for a message were invalid. @item GPG_ERR_UNUSABLE_SECKEY This value means that some signers were invalid. @item GPG_ERR_NO_DATA This value means that data was expected where no data was found. @item GPG_ERR_CONFLICT This value means that a conflict of some sort occurred. @item GPG_ERR_NOT_IMPLEMENTED This value indicates that the specific function (or operation) is not implemented. This error should never happen. It can only occur if you use certain values or configuration options which do not work, but for which we think that they should work at some later time. @item GPG_ERR_DECRYPT_FAILED This value indicates that a decryption operation was unsuccessful. @item GPG_ERR_WRONG_KEY_USAGE This value indicates that a key is not used appropriately. @item GPG_ERR_NO_SECKEY This value indicates that no secret key for the user ID is available. @item GPG_ERR_UNSUPPORTED_ALGORITHM This value means a verification failed because the cryptographic algorithm is not supported by the crypto backend. @item GPG_ERR_BAD_SIGNATURE This value means a verification failed because the signature is bad. @item GPG_ERR_NO_PUBKEY This value means a verification failed because the public key is not available. @item GPG_ERR_NOT_OPERATIONAL This value means that the library is not yet in state which allows to use this function. This error code is in particular returned if Libgcrypt is operated in FIPS mode and the internal state of the library does not yet or not anymore allow the use of a service. This error code is only available with newer libgpg-error versions, thus you might see ``invalid error code'' when passing this to @code{gpg_strerror}. The numeric value of this error code is 176. @item GPG_ERR_USER_1 @item GPG_ERR_USER_2 @item ... @item GPG_ERR_USER_16 These error codes are not used by any GnuPG component and can be freely used by other software. Applications using Libgcrypt might use them to mark specific errors returned by callback handlers if no suitable error codes (including the system errors) for these errors exist already. @end table @node Error Strings @subsection Error Strings @cindex error values, printing of @cindex error codes, printing of @cindex error sources, printing of @cindex error strings @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}}) The function @code{gcry_strerror} returns a pointer to a statically allocated string containing a description of the error code contained in the error value @var{err}. This string can be used to output a diagnostic message to the user. @end deftypefun @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}}) The function @code{gcry_strsource} returns a pointer to a statically allocated string containing a description of the error source contained in the error value @var{err}. This string can be used to output a diagnostic message to the user. @end deftypefun The following example illustrates the use of the functions described above: @example @{ gcry_cipher_hd_t handle; gcry_error_t err = 0; err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0); if (err) @{ fprintf (stderr, "Failure: %s/%s\n", gcry_strsource (err), gcry_strerror (err)); @} @} @end example @c ********************************************************** @c ******************* General **************************** @c ********************************************************** @node Handler Functions @chapter Handler Functions Libgcrypt makes it possible to install so called `handler functions', which get called by Libgcrypt in case of certain events. @menu * Progress handler:: Using a progress handler function. * Allocation handler:: Using special memory allocation functions. * Error handler:: Using error handler functions. * Logging handler:: Using a special logging function. @end menu @node Progress handler @section Progress handler It is often useful to retrieve some feedback while long running operations are performed. @deftp {Data type} gcry_handler_progress_t Progress handler functions have to be of the type @code{gcry_handler_progress_t}, which is defined as: @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)} @end deftp The following function may be used to register a handler function for this purpose. @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data}) This function installs @var{cb} as the `Progress handler' function. It may be used only during initialization. @var{cb} must be defined as follows: @example void my_progress_handler (void *@var{cb_data}, const char *@var{what}, int @var{printchar}, int @var{current}, int @var{total}) @{ /* Do something. */ @} @end example A description of the arguments of the progress handler function follows. @table @var @item cb_data The argument provided in the call to @code{gcry_set_progress_handler}. @item what A string identifying the type of the progress output. The following values for @var{what} are defined: @table @code @item need_entropy Not enough entropy is available. @var{total} holds the number of required bytes. @item wait_dev_random Waiting to re-open a random device. @var{total} gives the number of seconds until the next try. @item primegen Values for @var{printchar}: @table @code @item \n Prime generated. @item ! Need to refresh the pool of prime numbers. @item <, > Number of bits adjusted. @item ^ Searching for a generator. @item . Fermat test on 10 candidates failed. @item : Restart with a new random value. @item + Rabin Miller test passed. @end table @end table @end table @end deftypefun @node Allocation handler @section Allocation handler It is possible to make Libgcrypt use special memory allocation functions instead of the built-in ones. Memory allocation functions are of the following types: @deftp {Data type} gcry_handler_alloc_t This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}. @end deftp @deftp {Data type} gcry_handler_secure_check_t This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}. @end deftp @deftp {Data type} gcry_handler_realloc_t This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}. @end deftp @deftp {Data type} gcry_handler_free_t This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}. @end deftp Special memory allocation functions can be installed with the following function: @deftypefun void gcry_set_allocation_handler (gcry_handler_alloc_t @var{func_alloc}, gcry_handler_alloc_t @var{func_alloc_secure}, gcry_handler_secure_check_t @var{func_secure_check}, gcry_handler_realloc_t @var{func_realloc}, gcry_handler_free_t @var{func_free}) Install the provided functions and use them instead of the built-in functions for doing memory allocation. Using this function is in general not recommended because the standard Libgcrypt allocation functions are guaranteed to zeroize memory if needed. This function may be used only during initialization and may not be used in fips mode. @end deftypefun @node Error handler @section Error handler The following functions may be used to register handler functions that are called by Libgcrypt in case certain error conditions occur. They may and should be registered prior to calling @code{gcry_check_version}. @deftp {Data type} gcry_handler_no_mem_t This type is defined as: @code{int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)} @end deftp @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data}) This function registers @var{func_no_mem} as `out-of-core handler', which means that it will be called in the case of not having enough memory available. The handler is called with 3 arguments: The first one is the pointer @var{cb_data} as set with this function, the second is the requested memory size and the last being a flag. If bit 0 of the flag is set, secure memory has been requested. The handler should either return true to indicate that Libgcrypt should try again allocating memory or return false to let Libgcrypt use its default fatal error handler. @end deftypefun @deftp {Data type} gcry_handler_error_t This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)} @end deftp @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data}) This function registers @var{func_error} as `error handler', which means that it will be called in error conditions. @end deftypefun @node Logging handler @section Logging handler @deftp {Data type} gcry_handler_log_t This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)} @end deftp @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data}) This function registers @var{func_log} as `logging handler', which means that it will be called in case Libgcrypt wants to log a message. This function may and should be used prior to calling @code{gcry_check_version}. @end deftypefun @c ********************************************************** @c ******************* Ciphers **************************** @c ********************************************************** @c @include cipher-ref.texi @node Symmetric cryptography @chapter Symmetric cryptography The cipher functions are used for symmetrical cryptography, i.e. cryptography using a shared key. The programming model follows an open/process/close paradigm and is in that similar to other building blocks provided by Libgcrypt. @menu * Available ciphers:: List of ciphers supported by the library. * Available cipher modes:: List of cipher modes supported by the library. * Working with cipher handles:: How to perform operations related to cipher handles. * General cipher functions:: General cipher functions independent of cipher handles. @end menu @node Available ciphers @section Available ciphers @table @code @item GCRY_CIPHER_NONE This is not a real algorithm but used by some functions as error return. The value always evaluates to false. @item GCRY_CIPHER_IDEA @cindex IDEA This is the IDEA algorithm. @item GCRY_CIPHER_3DES @cindex 3DES @cindex Triple-DES @cindex DES-EDE @cindex Digital Encryption Standard Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but you have to pass 192 bits because the most significant bits of each byte are ignored. @item GCRY_CIPHER_CAST5 @cindex CAST5 CAST128-5 block cipher algorithm. The key size is 128 bits. @item GCRY_CIPHER_BLOWFISH @cindex Blowfish The blowfish algorithm. The current implementation allows only for a key size of 128 bits. @item GCRY_CIPHER_SAFER_SK128 Reserved and not currently implemented. @item GCRY_CIPHER_DES_SK Reserved and not currently implemented. @item GCRY_CIPHER_AES @itemx GCRY_CIPHER_AES128 @itemx GCRY_CIPHER_RIJNDAEL @itemx GCRY_CIPHER_RIJNDAEL128 @cindex Rijndael @cindex AES @cindex Advanced Encryption Standard AES (Rijndael) with a 128 bit key. @item GCRY_CIPHER_AES192 @itemx GCRY_CIPHER_RIJNDAEL192 AES (Rijndael) with a 192 bit key. @item GCRY_CIPHER_AES256 @itemx GCRY_CIPHER_RIJNDAEL256 AES (Rijndael) with a 256 bit key. @item GCRY_CIPHER_TWOFISH @cindex Twofish The Twofish algorithm with a 256 bit key. @item GCRY_CIPHER_TWOFISH128 The Twofish algorithm with a 128 bit key. @item GCRY_CIPHER_ARCFOUR @cindex Arcfour @cindex RC4 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm. Note that this is a stream cipher and must be used very carefully to avoid a couple of weaknesses. @item GCRY_CIPHER_DES @cindex DES Standard DES with a 56 bit key. You need to pass 64 bit but the high bits of each byte are ignored. Note, that this is a weak algorithm which can be broken in reasonable time using a brute force approach. @item GCRY_CIPHER_SERPENT128 @itemx GCRY_CIPHER_SERPENT192 @itemx GCRY_CIPHER_SERPENT256 @cindex Serpent The Serpent cipher from the AES contest. @item GCRY_CIPHER_RFC2268_40 @itemx GCRY_CIPHER_RFC2268_128 @cindex rfc-2268 @cindex RC2 Ron's Cipher 2 in the 40 and 128 bit variants. @item GCRY_CIPHER_SEED @cindex Seed (cipher) A 128 bit cipher as described by RFC4269. @item GCRY_CIPHER_CAMELLIA128 @itemx GCRY_CIPHER_CAMELLIA192 @itemx GCRY_CIPHER_CAMELLIA256 @cindex Camellia The Camellia cipher by NTT. See @uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}. @item GCRY_CIPHER_SALSA20 @cindex Salsa20 This is the Salsa20 stream cipher. @item GCRY_CIPHER_SALSA20R12 @cindex Salsa20/12 This is the Salsa20/12 - reduced round version of Salsa20 stream cipher. @item GCRY_CIPHER_GOST28147 @cindex GOST 28147-89 The GOST 28147-89 cipher, defined in the respective GOST standard. Translation of this GOST into English is provided in the RFC-5830. @end table @node Available cipher modes @section Available cipher modes @table @code @item GCRY_CIPHER_MODE_NONE No mode specified. This should not be used. The only exception is that if Libgcrypt is not used in FIPS mode and if any debug flag has been set, this mode may be used to bypass the actual encryption. @item GCRY_CIPHER_MODE_ECB @cindex ECB, Electronic Codebook mode Electronic Codebook mode. @item GCRY_CIPHER_MODE_CFB @cindex CFB, Cipher Feedback mode Cipher Feedback mode. The shift size equals the block size of the cipher (e.g. for AES it is CFB-128). @item GCRY_CIPHER_MODE_CBC @cindex CBC, Cipher Block Chaining mode Cipher Block Chaining mode. @item GCRY_CIPHER_MODE_STREAM Stream mode, only to be used with stream cipher algorithms. @item GCRY_CIPHER_MODE_OFB @cindex OFB, Output Feedback mode Output Feedback mode. @item GCRY_CIPHER_MODE_CTR @cindex CTR, Counter mode Counter mode. @item GCRY_CIPHER_MODE_AESWRAP @cindex AES-Wrap mode This mode is used to implement the AES-Wrap algorithm according to RFC-3394. It may be used with any 128 bit block length algorithm, however the specs require one of the 3 AES algorithms. These special conditions apply: If @code{gcry_cipher_setiv} has not been used the standard IV is used; if it has been used the lower 64 bit of the IV are used as the Alternative Initial Value. On encryption the provided output buffer must be 64 bit (8 byte) larger than the input buffer; in-place encryption is still allowed. On decryption the output buffer may be specified 64 bit (8 byte) shorter than then input buffer. As per specs the input length must be at least 128 bits and the length must be a multiple of 64 bits. @item GCRY_CIPHER_MODE_CCM @cindex CCM, Counter with CBC-MAC mode Counter with CBC-MAC mode is an Authenticated Encryption with Associated Data (AEAD) block cipher mode, which is specified in 'NIST Special Publication 800-38C' and RFC 3610. @item GCRY_CIPHER_MODE_GCM @cindex GCM, Galois/Counter Mode Galois/Counter Mode (GCM) is an Authenticated Encryption with Associated Data (AEAD) block cipher mode, which is specified in 'NIST Special Publication 800-38D'. @end table @node Working with cipher handles @section Working with cipher handles To use a cipher algorithm, you must first allocate an according handle. This is to be done using the open function: @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags}) This function creates the context handle required for most of the other cipher functions and returns a handle to it in `hd'. In case of an error, an according error code is returned. The ID of algorithm to use must be specified via @var{algo}. See @xref{Available ciphers}, for a list of supported ciphers and the according constants. Besides using the constants directly, the function @code{gcry_cipher_map_name} may be used to convert the textual name of an algorithm into the according numeric ID. The cipher mode to use must be specified via @var{mode}. See @xref{Available cipher modes}, for a list of supported cipher modes and the according constants. Note that some modes are incompatible with some algorithms - in particular, stream mode (@code{GCRY_CIPHER_MODE_STREAM}) only works with stream ciphers. The block cipher modes (@code{GCRY_CIPHER_MODE_ECB}, @code{GCRY_CIPHER_MODE_CBC}, @code{GCRY_CIPHER_MODE_CFB}, @code{GCRY_CIPHER_MODE_OFB} and @code{GCRY_CIPHER_MODE_CTR}) will work with any block cipher algorithm. @code{GCRY_CIPHER_MODE_CCM} and @code{GCRY_CIPHER_MODE_GCM} modes will only work with block cipher algorithms which have the block size of 16 bytes. The third argument @var{flags} can either be passed as @code{0} or as the bit-wise OR of the following constants. @table @code @item GCRY_CIPHER_SECURE Make sure that all operations are allocated in secure memory. This is useful when the key material is highly confidential. @item GCRY_CIPHER_ENABLE_SYNC @cindex sync mode (OpenPGP) This flag enables the CFB sync mode, which is a special feature of Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant. See @code{gcry_cipher_sync}. @item GCRY_CIPHER_CBC_CTS @cindex cipher text stealing Enable cipher text stealing (CTS) for the CBC mode. Cannot be used simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to transform data of almost arbitrary size (only limitation is that it must be greater than the algorithm's block size). @item GCRY_CIPHER_CBC_MAC @cindex CBC-MAC Compute CBC-MAC keyed checksums. This is the same as CBC mode, but only output the last block. Cannot be used simultaneous as GCRY_CIPHER_CBC_CTS. @end table @end deftypefun Use the following function to release an existing handle: @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h}) This function releases the context created by @code{gcry_cipher_open}. It also zeroises all sensitive information associated with this cipher handle. @end deftypefun In order to use a handle for performing cryptographic operations, a `key' has to be set first: @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l}) Set the key @var{k} used for encryption or decryption in the context denoted by the handle @var{h}. The length @var{l} (in bytes) of the key @var{k} must match the required length of the algorithm set for this context or be in the allowed range for algorithms with variable key size. The function checks this and returns an error if there is a problem. A caller should always check for an error. @end deftypefun Most crypto modes requires an initialization vector (IV), which usually is a non-secret random string acting as a kind of salt value. The CTR mode requires a counter, which is also similar to a salt value. To set the IV or CTR, use these functions: @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l}) Set the initialization vector used for encryption or decryption. The vector is passed as the buffer @var{K} of length @var{l} bytes and copied to internal data structures. The function checks that the IV matches the requirement of the selected algorithm and mode. This function is also used with the Salsa20 stream cipher to set or update the required nonce. In this case it needs to be called after setting the key. This function is also used with the AEAD cipher modes to set or update the required nonce. @end deftypefun @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, const void *@var{c}, size_t @var{l}) Set the counter vector used for encryption or decryption. The counter is passed as the buffer @var{c} of length @var{l} bytes and copied to internal data structures. The function checks that the counter matches the requirement of the selected algorithm (i.e., it must be the same size as the block size). @end deftypefun @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h}) Set the given handle's context back to the state it had after the last call to gcry_cipher_setkey and clear the initialization vector. Note that gcry_cipher_reset is implemented as a macro. @end deftypefun Authenticated Encryption with Associated Data (AEAD) block cipher modes require the handling of the authentication tag and the additional authenticated data, which can be done by using the following functions: @deftypefun gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t @var{h}, const void *@var{abuf}, size_t @var{abuflen}) Process the buffer @var{abuf} of length @var{abuflen} as the additional authenticated data (AAD) for AEAD cipher modes. @end deftypefun @deftypefun gcry_error_t gcry_cipher_gettag (gcry_cipher_hd_t @var{h}, void *@var{tag}, size_t @var{taglen}) This function is used to read the authentication tag after encryption. The function finalizes and outputs the authentication tag to the buffer @var{tag} of length @var{taglen} bytes. @end deftypefun @deftypefun gcry_error_t gcry_cipher_checktag (gcry_cipher_hd_t @var{h}, const void *@var{tag}, size_t @var{taglen}) Check the authentication tag after decryption. The authentication tag is passed as the buffer @var{tag} of length @var{taglen} bytes and compared to internal authentication tag computed during decryption. Error code @code{GPG_ERR_CHECKSUM} is returned if the authentication tag in the buffer @var{tag} does not match the authentication tag calculated during decryption. @end deftypefun The actual encryption and decryption is done by using one of the following functions. They may be used as often as required to process all the data. @deftypefun gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen}) @code{gcry_cipher_encrypt} is used to encrypt the data. This function can either work in place or with two buffers. It uses the cipher context already setup and described by the handle @var{h}. There are 2 ways to use the function: If @var{in} is passed as @code{NULL} and @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or length @var{outsize} takes place. With @var{in} being not @code{NULL}, @var{inlen} bytes are encrypted to the buffer @var{out} which must have at least a size of @var{inlen}. @var{outsize} must be set to the allocated size of @var{out}, so that the function can check that there is sufficient space. Note that overlapping buffers are not allowed. Depending on the selected algorithms and encryption mode, the length of the buffers must be a multiple of the block size. The function returns @code{0} on success or an error code. @end deftypefun @deftypefun gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen}) @code{gcry_cipher_decrypt} is used to decrypt the data. This function can either work in place or with two buffers. It uses the cipher context already setup and described by the handle @var{h}. There are 2 ways to use the function: If @var{in} is passed as @code{NULL} and @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or length @var{outsize} takes place. With @var{in} being not @code{NULL}, @var{inlen} bytes are decrypted to the buffer @var{out} which must have at least a size of @var{inlen}. @var{outsize} must be set to the allocated size of @var{out}, so that the function can check that there is sufficient space. Note that overlapping buffers are not allowed. Depending on the selected algorithms and encryption mode, the length of the buffers must be a multiple of the block size. The function returns @code{0} on success or an error code. @end deftypefun OpenPGP (as defined in RFC-2440) requires a special sync operation in some places. The following function is used for this: @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h}) Perform the OpenPGP sync operation on context @var{h}. Note that this is a no-op unless the context was created with the flag @code{GCRY_CIPHER_ENABLE_SYNC} @end deftypefun Some of the described functions are implemented as macros utilizing a catch-all control function. This control function is rarely used directly but there is nothing which would inhibit it: @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen}) @code{gcry_cipher_ctl} controls various aspects of the cipher module and specific cipher contexts. Usually some more specialized functions or macros are used for this purpose. The semantics of the function and its parameters depends on the the command @var{cmd} and the passed context handle @var{h}. Please see the comments in the source code (@code{src/global.c}) for details. @end deftypefun @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes}) @code{gcry_cipher_info} is used to retrieve various information about a cipher context or the cipher module in general. Currently no information is available. @end deftypefun @node General cipher functions @section General cipher functions To work with the algorithms, several functions are available to map algorithm names to the internal identifiers, as well as ways to retrieve information about an algorithm or the current cipher context. @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes}) This function is used to retrieve information on a specific algorithm. You pass the cipher algorithm ID as @var{algo} and the type of information requested as @var{what}. The result is either returned as the return code of the function or copied to the provided @var{buffer} whose allocated length must be available in an integer variable with the address passed in @var{nbytes}. This variable will also receive the actual used length of the buffer. Here is a list of supported codes for @var{what}: @c begin constants for gcry_cipher_algo_info @table @code @item GCRYCTL_GET_KEYLEN: Return the length of the key. If the algorithm supports multiple key lengths, the maximum supported value is returned. The length is returned as number of octets (bytes) and not as number of bits in @var{nbytes}; @var{buffer} must be zero. Note that it is usually better to use the convenience function @code{gcry_cipher_get_algo_keylen}. @item GCRYCTL_GET_BLKLEN: Return the block length of the algorithm. The length is returned as a number of octets in @var{nbytes}; @var{buffer} must be zero. Note that it is usually better to use the convenience function @code{gcry_cipher_get_algo_blklen}. @item GCRYCTL_TEST_ALGO: Returns @code{0} when the specified algorithm is available for use. @var{buffer} and @var{nbytes} must be zero. @end table @c end constants for gcry_cipher_algo_info @end deftypefun @c end gcry_cipher_algo_info @deftypefun size_t gcry_cipher_get_algo_keylen (@var{algo}) This function returns length of the key for algorithm @var{algo}. If the algorithm supports multiple key lengths, the maximum supported key length is returned. On error @code{0} is returned. The key length is returned as number of octets. This is a convenience functions which should be preferred over @code{gcry_cipher_algo_info} because it allows for proper type checking. @end deftypefun @c end gcry_cipher_get_algo_keylen @deftypefun size_t gcry_cipher_get_algo_blklen (int @var{algo}) This functions returns the block-length of the algorithm @var{algo} counted in octets. On error @code{0} is returned. This is a convenience functions which should be preferred over @code{gcry_cipher_algo_info} because it allows for proper type checking. @end deftypefun @c end gcry_cipher_get_algo_blklen @deftypefun {const char *} gcry_cipher_algo_name (int @var{algo}) @code{gcry_cipher_algo_name} returns a string with the name of the cipher algorithm @var{algo}. If the algorithm is not known or another error occurred, the string @code{"?"} is returned. This function should not be used to test for the availability of an algorithm. @end deftypefun @deftypefun int gcry_cipher_map_name (const char *@var{name}) @code{gcry_cipher_map_name} returns the algorithm identifier for the cipher algorithm described by the string @var{name}. If this algorithm is not available @code{0} is returned. @end deftypefun @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string}) Return the cipher mode associated with an @acronym{ASN.1} object identifier. The object identifier is expected to be in the @acronym{IETF}-style dotted decimal notation. The function returns @code{0} for an unknown object identifier or when no mode is associated with it. @end deftypefun @c ********************************************************** @c ******************* Public Key ************************* @c ********************************************************** @node Public Key cryptography @chapter Public Key cryptography Public key cryptography, also known as asymmetric cryptography, is an easy way for key management and to provide digital signatures. Libgcrypt provides two completely different interfaces to public key cryptography, this chapter explains the one based on S-expressions. @menu * Available algorithms:: Algorithms supported by the library. * Used S-expressions:: Introduction into the used S-expression. * Cryptographic Functions:: Functions for performing the cryptographic actions. * General public-key related Functions:: General functions, not implementing any cryptography. @end menu @node Available algorithms @section Available algorithms Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well as DSA (Digital Signature Algorithm) and Elgamal. The versatile interface allows to add more algorithms in the future. @node Used S-expressions @section Used S-expressions Libgcrypt's API for asymmetric cryptography is based on data structures called S-expressions (see @uref{http://people.csail.mit.edu/@/rivest/@/sexp.html}) and does not work with contexts as most of the other building blocks of Libgcrypt do. @noindent The following information are stored in S-expressions: @itemize @item keys @item plain text data @item encrypted data @item signatures @end itemize @noindent To describe how Libgcrypt expect keys, we use examples. Note that words in @ifnottex uppercase @end ifnottex @iftex italics @end iftex indicate parameters whereas lowercase words are literals. Note that all MPI (multi-precision-integers) values are expected to be in @code{GCRYMPI_FMT_USG} format. An easy way to create S-expressions is by using @code{gcry_sexp_build} which allows to pass a string with printf-like escapes to insert MPI values. @menu * RSA key parameters:: Parameters used with an RSA key. * DSA key parameters:: Parameters used with a DSA key. * ECC key parameters:: Parameters used with ECC keys. @end menu @node RSA key parameters @subsection RSA key parameters @noindent An RSA private key is described by this S-expression: @example (private-key (rsa (n @var{n-mpi}) (e @var{e-mpi}) (d @var{d-mpi}) (p @var{p-mpi}) (q @var{q-mpi}) (u @var{u-mpi}))) @end example @noindent An RSA public key is described by this S-expression: @example (public-key (rsa (n @var{n-mpi}) (e @var{e-mpi}))) @end example @table @var @item n-mpi RSA public modulus @math{n}. @item e-mpi RSA public exponent @math{e}. @item d-mpi RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}. @item p-mpi RSA secret prime @math{p}. @item q-mpi RSA secret prime @math{q} with @math{p < q}. @item u-mpi Multiplicative inverse @math{u = p^{-1} \bmod q}. @end table For signing and decryption the parameters @math{(p, q, u)} are optional but greatly improve the performance. Either all of these optional parameters must be given or none of them. They are mandatory for gcry_pk_testkey. Note that OpenSSL uses slighly different parameters: @math{q < p} and @math{u = q^{-1} \bmod p}. To use these parameters you will need to swap the values and recompute @math{u}. Here is example code to do this: @example if (gcry_mpi_cmp (p, q) > 0) @{ gcry_mpi_swap (p, q); gcry_mpi_invm (u, p, q); @} @end example @node DSA key parameters @subsection DSA key parameters @noindent A DSA private key is described by this S-expression: @example (private-key (dsa (p @var{p-mpi}) (q @var{q-mpi}) (g @var{g-mpi}) (y @var{y-mpi}) (x @var{x-mpi}))) @end example @table @var @item p-mpi DSA prime @math{p}. @item q-mpi DSA group order @math{q} (which is a prime divisor of @math{p-1}). @item g-mpi DSA group generator @math{g}. @item y-mpi DSA public key value @math{y = g^x \bmod p}. @item x-mpi DSA secret exponent x. @end table The public key is similar with "private-key" replaced by "public-key" and no @var{x-mpi}. @node ECC key parameters @subsection ECC key parameters @anchor{ecc_keyparam} @noindent An ECC private key is described by this S-expression: @example (private-key (ecc (p @var{p-mpi}) (a @var{a-mpi}) (b @var{b-mpi}) (g @var{g-point}) (n @var{n-mpi}) (q @var{q-point}) (d @var{d-mpi}))) @end example @table @var @item p-mpi Prime specifying the field @math{GF(p)}. @item a-mpi @itemx b-mpi The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b} @item g-point Base point @math{g}. @item n-mpi Order of @math{g} @item q-point The point representing the public key @math{Q = dG}. @item d-mpi The private key @math{d} @end table All point values are encoded in standard format; Libgcrypt does in general only support uncompressed points, thus the first byte needs to be @code{0x04}. However ``EdDSA'' describes its own compression scheme which is used by default. The public key is similar with "private-key" replaced by "public-key" and no @var{d-mpi}. If the domain parameters are well-known, the name of this curve may be used. For example @example (private-key (ecc (curve "NIST P-192") (q @var{q-point}) (d @var{d-mpi}))) @end example Note that @var{q-point} is optional for a private key. The @code{curve} parameter may be given in any case and is used to replace missing parameters. @noindent Currently implemented curves are: @table @code @item NIST P-192 @itemx 1.2.840.10045.3.1.1 @itemx prime192v1 @itemx secp192r1 The NIST 192 bit curve, its OID, X9.62 and SECP aliases. @item NIST P-224 @itemx secp224r1 The NIST 224 bit curve and its SECP alias. @item NIST P-256 @itemx 1.2.840.10045.3.1.7 @itemx prime256v1 @itemx secp256r1 The NIST 256 bit curve, its OID, X9.62 and SECP aliases. @item NIST P-384 @itemx secp384r1 The NIST 384 bit curve and its SECP alias. @item NIST P-521 @itemx secp521r1 The NIST 521 bit curve and its SECP alias. @end table As usual the OIDs may optionally be prefixed with the string @code{OID.} or @code{oid.}. @node Cryptographic Functions @section Cryptographic Functions @noindent Some functions operating on S-expressions support `flags' to influence the operation. These flags have to be listed in a sub-S-expression named `flags'. Flag names are case-sensitive. The following flags are known: @table @code @item comp @itemx nocomp @cindex comp @cindex nocomp If supported by the algorithm and curve the @code{comp} flag requests that points are returned in compact (compressed) representation. The @code{nocomp} flag requests that points are returned with full coordinates. The default depends on the the algorithm and curve. The compact representation requires a small overhead before a point can be used but halves the size of a to be conveyed public key. @item pkcs1 @cindex PKCS1 Use PKCS#1 block type 2 padding for encryption, block type 1 padding for signing. @item oaep @cindex OAEP Use RSA-OAEP padding for encryption. @item pss @cindex PSS Use RSA-PSS padding for signing. @item eddsa @cindex EdDSA Use the EdDSA scheme signing instead of the default ECDSA algorithm. Note that the EdDSA uses a special form of the public key. @item rfc6979 @cindex RFC6979 For DSA and ECDSA use a deterministic scheme for the k parameter. @item no-blinding @cindex no-blinding Do not use a technique called `blinding', which is used by default in order to prevent leaking of secret information. Blinding is only implemented by RSA, but it might be implemented by other algorithms in the future as well, when necessary. @item param @cindex param For ECC key generation also return the domain parameters. For ECC signing and verification override default parameters by provided domain parameters of the public or private key. @item transient-key @cindex transient-key This flag is only meaningful for RSA, DSA, and ECC key generation. If given the key is created using a faster and a somewhat less secure random number generator. This flag may be used for keys which are only used for a short time or per-message and do not require full cryptographic strength. @item use-x931 @cindex X9.31 Force the use of the ANSI X9.31 key generation algorithm instead of the default algorithm. This flag is only meaningful for RSA key generation and usually not required. Note that this algorithm is implicitly used if either @code{derive-parms} is given or Libgcrypt is in FIPS mode. @item use-fips186 @cindex FIPS 186 Force the use of the FIPS 186 key generation algorithm instead of the default algorithm. This flag is only meaningful for DSA and usually not required. Note that this algorithm is implicitly used if either @code{derive-parms} is given or Libgcrypt is in FIPS mode. As of now FIPS 186-2 is implemented; after the approval of FIPS 186-3 the code will be changed to implement 186-3. @item use-fips186-2 @cindex FIPS 186-2 Force the use of the FIPS 186-2 key generation algorithm instead of the default algorithm. This algorithm is slightly different from FIPS 186-3 and allows only 1024 bit keys. This flag is only meaningful for DSA and only required for FIPS testing backward compatibility. @end table @noindent Now that we know the key basics, we can carry on and explain how to encrypt and decrypt data. In almost all cases the data is a random session key which is in turn used for the actual encryption of the real data. There are 2 functions to do this: @deftypefun gcry_error_t gcry_pk_encrypt (@w{gcry_sexp_t *@var{r_ciph},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{pkey}}) Obviously a public key must be provided for encryption. It is expected as an appropriate S-expression (see above) in @var{pkey}. The data to be encrypted can either be in the simple old format, which is a very simple S-expression consisting only of one MPI, or it may be a more complex S-expression which also allows to specify flags for operation, like e.g. padding rules. @noindent If you don't want to let Libgcrypt handle the padding, you must pass an appropriate MPI using this expression for @var{data}: @example (data (flags raw) (value @var{mpi})) @end example @noindent This has the same semantics as the old style MPI only way. @var{MPI} is the actual data, already padded appropriate for your protocol. Most RSA based systems however use PKCS#1 padding and so you can use this S-expression for @var{data}: @example (data (flags pkcs1) (value @var{block})) @end example @noindent Here, the "flags" list has the "pkcs1" flag which let the function know that it should provide PKCS#1 block type 2 padding. The actual data to be encrypted is passed as a string of octets in @var{block}. The function checks that this data actually can be used with the given key, does the padding and encrypts it. If the function could successfully perform the encryption, the return value will be 0 and a new S-expression with the encrypted result is allocated and assigned to the variable at the address of @var{r_ciph}. The caller is responsible to release this value using @code{gcry_sexp_release}. In case of an error, an error code is returned and @var{r_ciph} will be set to @code{NULL}. @noindent The returned S-expression has this format when used with RSA: @example (enc-val (rsa (a @var{a-mpi}))) @end example @noindent Where @var{a-mpi} is an MPI with the result of the RSA operation. When using the Elgamal algorithm, the return value will have this format: @example (enc-val (elg (a @var{a-mpi}) (b @var{b-mpi}))) @end example @noindent Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the Elgamal encryption operation. @end deftypefun @c end gcry_pk_encrypt @deftypefun gcry_error_t gcry_pk_decrypt (@w{gcry_sexp_t *@var{r_plain},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{skey}}) Obviously a private key must be provided for decryption. It is expected as an appropriate S-expression (see above) in @var{skey}. The data to be decrypted must match the format of the result as returned by @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags} element: @example (enc-val (flags) (elg (a @var{a-mpi}) (b @var{b-mpi}))) @end example @noindent This function does not remove padding from the data by default. To let Libgcrypt remove padding, give a hint in `flags' telling which padding method was used when encrypting: @example (flags @var{padding-method}) @end example @noindent Currently @var{padding-method} is either @code{pkcs1} for PKCS#1 block type 2 padding, or @code{oaep} for RSA-OAEP padding. @noindent The function returns 0 on success or an error code. The variable at the address of @var{r_plain} will be set to NULL on error or receive the decrypted value on success. The format of @var{r_plain} is a simple S-expression part (i.e. not a valid one) with just one MPI if there was no @code{flags} element in @var{data}; if at least an empty @code{flags} is passed in @var{data}, the format is: @example (value @var{plaintext}) @end example @end deftypefun @c end gcry_pk_decrypt Another operation commonly performed using public key cryptography is signing data. In some sense this is even more important than encryption because digital signatures are an important instrument for key management. Libgcrypt supports digital signatures using 2 functions, similar to the encryption functions: @deftypefun gcry_error_t gcry_pk_sign (@w{gcry_sexp_t *@var{r_sig},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{skey}}) This function creates a digital signature for @var{data} using the private key @var{skey} and place it into the variable at the address of @var{r_sig}. @var{data} may either be the simple old style S-expression with just one MPI or a modern and more versatile S-expression which allows to let Libgcrypt handle padding: @example (data (flags pkcs1) (hash @var{hash-algo} @var{block})) @end example @noindent This example requests to sign the data in @var{block} after applying PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the hash algorithm to be encoded into the signature, this may be any hash algorithm name as supported by Libgcrypt. Most likely, this will be "sha256" or "sha1". It is obvious that the length of @var{block} must match the size of that message digests; the function checks that this and other constraints are valid. @noindent If PKCS#1 padding is not required (because the caller does already provide a padded value), either the old format or better the following format should be used: @example (data (flags raw) (value @var{mpi})) @end example @noindent Here, the data to be signed is directly given as an @var{MPI}. @noindent For DSA the input data is expected in this format: @example (data (flags raw) (value @var{mpi})) @end example @noindent Here, the data to be signed is directly given as an @var{MPI}. It is expect that this MPI is the the hash value. For the standard DSA using a MPI is not a problem in regard to leading zeroes because the hash value is directly used as an MPI. For better standard conformance it would be better to explicit use a memory string (like with pkcs1) but that is currently not supported. However, for deterministic DSA as specified in RFC6979 this can't be used. Instead the following input is expected. @example (data (flags rfc6979) (hash @var{hash-algo} @var{block})) @end example Note that the provided hash-algo is used for the internal HMAC; it should match the hash-algo used to create @var{block}. @noindent The signature is returned as a newly allocated S-expression in @var{r_sig} using this format for RSA: @example (sig-val (rsa (s @var{s-mpi}))) @end example Where @var{s-mpi} is the result of the RSA sign operation. For DSA the S-expression returned is: @example (sig-val (dsa (r @var{r-mpi}) (s @var{s-mpi}))) @end example Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign operation. For Elgamal signing (which is slow, yields large numbers and probably is not as secure as the other algorithms), the same format is used with "elg" replacing "dsa"; for ECDSA signing, the same format is used with "ecdsa" replacing "dsa". For the EdDSA algorithm (cf. Ed25515) the required input parameters are: @example (data (flags eddsa) (hash-algo sha512) (value @var{message})) @end example Note that the @var{message} may be of any length; hashing is part of the algorithm. Using a large data block for @var{message} is not suggested; in that case the used protocol should better require that a hash of the message is used as input to the EdDSA algorithm. @end deftypefun @c end gcry_pk_sign @noindent The operation most commonly used is definitely the verification of a signature. Libgcrypt provides this function: @deftypefun gcry_error_t gcry_pk_verify (@w{gcry_sexp_t @var{sig}}, @w{gcry_sexp_t @var{data}}, @w{gcry_sexp_t @var{pkey}}) This is used to check whether the signature @var{sig} matches the @var{data}. The public key @var{pkey} must be provided to perform this verification. This function is similar in its parameters to @code{gcry_pk_sign} with the exceptions that the public key is used instead of the private key and that no signature is created but a signature, in a format as created by @code{gcry_pk_sign}, is passed to the function in @var{sig}. @noindent The result is 0 for success (i.e. the data matches the signature), or an error code where the most relevant code is @code{GCRY_ERR_BAD_SIGNATURE} to indicate that the signature does not match the provided data. @end deftypefun @c end gcry_pk_verify @node General public-key related Functions @section General public-key related Functions @noindent A couple of utility functions are available to retrieve the length of the key, map algorithm identifiers and perform sanity checks: @deftypefun {const char *} gcry_pk_algo_name (int @var{algo}) Map the public key algorithm id @var{algo} to a string representation of the algorithm name. For unknown algorithms this functions returns the string @code{"?"}. This function should not be used to test for the availability of an algorithm. @end deftypefun @deftypefun int gcry_pk_map_name (const char *@var{name}) Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if the algorithm name is not known. @end deftypefun @deftypefun int gcry_pk_test_algo (int @var{algo}) Return 0 if the public key algorithm @var{algo} is available for use. Note that this is implemented as a macro. @end deftypefun @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key}) Return what is commonly referred as the key length for the given public or private in @var{key}. @end deftypefun @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}}) Return the so called "keygrip" which is the SHA-1 hash of the public key parameters expressed in a way depended on the algorithm. @var{array} must either provide space for 20 bytes or be @code{NULL}. In the latter case a newly allocated array of that size is returned. On success a pointer to the newly allocated space or to @var{array} is returned. @code{NULL} is returned to indicate an error which is most likely an unknown algorithm or one where a "keygrip" has not yet been defined. The function accepts public or secret keys in @var{key}. @end deftypefun @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key}) Return zero if the private key @var{key} is `sane', an error code otherwise. Note that it is not possible to check the `saneness' of a public key. @end deftypefun @deftypefun gcry_error_t gcry_pk_algo_info (@w{int @var{algo}}, @w{int @var{what}}, @w{void *@var{buffer}}, @w{size_t *@var{nbytes}}) Depending on the value of @var{what} return various information about the public key algorithm with the id @var{algo}. Note that the function returns @code{-1} on error and the actual error code must be retrieved using the function @code{gcry_errno}. The currently defined values for @var{what} are: @table @code @item GCRYCTL_TEST_ALGO: Return 0 if the specified algorithm is available for use. @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as @code{NULL} or point to a variable with the required usage of the algorithm. This may be 0 for "don't care" or the bit-wise OR of these flags: @table @code @item GCRY_PK_USAGE_SIGN Algorithm is usable for signing. @item GCRY_PK_USAGE_ENCR Algorithm is usable for encryption. @end table Unless you need to test for the allowed usage, it is in general better to use the macro gcry_pk_test_algo instead. @item GCRYCTL_GET_ALGO_USAGE: Return the usage flags for the given algorithm. An invalid algorithm return 0. Disabled algorithms are ignored here because we want to know whether the algorithm is at all capable of a certain usage. @item GCRYCTL_GET_ALGO_NPKEY Return the number of elements the public key for algorithm @var{algo} consist of. Return 0 for an unknown algorithm. @item GCRYCTL_GET_ALGO_NSKEY Return the number of elements the private key for algorithm @var{algo} consist of. Note that this value is always larger than that of the public key. Return 0 for an unknown algorithm. @item GCRYCTL_GET_ALGO_NSIGN Return the number of elements a signature created with the algorithm @var{algo} consists of. Return 0 for an unknown algorithm or for an algorithm not capable of creating signatures. @item GCRYCTL_GET_ALGO_NENC Return the number of elements a encrypted message created with the algorithm @var{algo} consists of. Return 0 for an unknown algorithm or for an algorithm not capable of encryption. @end table @noindent Please note that parameters not required should be passed as @code{NULL}. @end deftypefun @c end gcry_pk_algo_info @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}}) This is a general purpose function to perform certain control operations. @var{cmd} controls what is to be done. The return value is 0 for success or an error code. Currently supported values for @var{cmd} are: @table @code @item GCRYCTL_DISABLE_ALGO Disable the algorithm given as an algorithm id in @var{buffer}. @var{buffer} must point to an @code{int} variable with the algorithm id and @var{buflen} must have the value @code{sizeof (int)}. This -fucntion is not thread safe and should thus be used before any other +function is not thread safe and should thus be used before any other threads are started. @end table @end deftypefun @c end gcry_pk_ctl @noindent Libgcrypt also provides a function to generate public key pairs: @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}}) This function create a new public key pair using information given in the S-expression @var{parms} and stores the private and the public key in one new S-expression at the address given by @var{r_key}. In case of an error, @var{r_key} is set to @code{NULL}. The return code is 0 for success or an error code otherwise. @noindent Here is an example for @var{parms} to create an 2048 bit RSA key: @example (genkey (rsa (nbits 4:2048))) @end example @noindent To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA key use "dsa". Valid ranges for the key length depend on the algorithms; all commonly used key lengths are supported. Currently supported parameters are: @table @code @item nbits This is always required to specify the length of the key. The argument is a string with a number in C-notation. The value should be a multiple of 8. Note that the S-expression syntax requires that a number is prefixed with its string length; thus the @code{4:} in the above example. @item curve @var{name} For ECC a named curve may be used instead of giving the number of requested bits. This allows to request a specific curve to override a default selection Libgcrypt would have taken if @code{nbits} has been given. The available names are listed with the description of the ECC public key parameters. @item rsa-use-e @var{value} This is only used with RSA to give a hint for the public exponent. The @var{value} will be used as a base to test for a usable exponent. Some values are special: @table @samp @item 0 Use a secure and fast value. This is currently the number 41. @item 1 Use a value as required by some crypto policies. This is currently the number 65537. @item 2 Reserved @item > 2 Use the given value. @end table @noindent If this parameter is not used, Libgcrypt uses for historic reasons 65537. @item qbits @var{n} This is only meanigful for DSA keys. If it is given the DSA key is generated with a Q parameyer of size @var{n} bits. If it is not given or zero Q is deduced from NBITS in this way: @table @samp @item 512 <= N <= 1024 Q = 160 @item N = 2048 Q = 224 @item N = 3072 Q = 256 @item N = 7680 Q = 384 @item N = 15360 Q = 512 @end table Note that in this case only the values for N, as given in the table, are allowed. When specifying Q all values of N in the range 512 to 15680 are valid as long as they are multiples of 8. @item domain @var{list} This is only meaningful for DLP algorithms. If specified keys are generated with domain parameters taken from this list. The exact format of this parameter depends on the actual algorithm. It is currently only implemented for DSA using this format: @example (genkey (dsa (domain (p @var{p-mpi}) (q @var{q-mpi}) (g @var{q-mpi})))) @end example @code{nbits} and @code{qbits} may not be specified because they are derived from the domain parameters. @item derive-parms @var{list} This is currently only implemented for RSA and DSA keys. It is not allowed to use this together with a @code{domain} specification. If given, it is used to derive the keys using the given parameters. If given for an RSA key the X9.31 key generation algorithm is used even if libgcrypt is not in FIPS mode. If given for a DSA key, the FIPS 186 algorithm is used even if libgcrypt is not in FIPS mode. @example (genkey (rsa (nbits 4:1024) (rsa-use-e 1:3) (derive-parms (Xp1 #1A1916DDB29B4EB7EB6732E128#) (Xp2 #192E8AAC41C576C822D93EA433#) (Xp #D8CD81F035EC57EFE822955149D3BFF70C53520D 769D6D76646C7A792E16EBD89FE6FC5B605A6493 39DFC925A86A4C6D150B71B9EEA02D68885F5009 B98BD984#) (Xq1 #1A5CF72EE770DE50CB09ACCEA9#) (Xq2 #134E4CAA16D2350A21D775C404#) (Xq #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC325 6D29C2627479C086A699A49C4C9CEE7EF7BD1B34 321DE34A#)))) @end example @example (genkey (dsa (nbits 4:1024) (derive-parms (seed @var{seed-mpi})))) @end example @item flags @var{flaglist} This is preferred way to define flags. @var{flaglist} may contain any number of flags. See above for a specification of these flags. Here is an example on how to create a key using curve Ed25519 with the ECDSA signature algorithm. Note that the use of ECDSA with that curve is in general not recommended. @example (genkey (ecc (flags transient-key))) @end example @item transient-key @itemx use-x931 @itemx use-fips186 @itemx use-fips186-2 These are deprecated ways to set a flag with that name; see above for a description of each flag. @end table @c end table of parameters @noindent The key pair is returned in a format depending on the algorithm. Both private and public keys are returned in one container and may be accompanied by some miscellaneous information. @noindent Here are two examples; the first for Elgamal and the second for elliptic curve key generation: @example (key-data (public-key (elg (p @var{p-mpi}) (g @var{g-mpi}) (y @var{y-mpi}))) (private-key (elg (p @var{p-mpi}) (g @var{g-mpi}) (y @var{y-mpi}) (x @var{x-mpi}))) (misc-key-info (pm1-factors @var{n1 n2 ... nn})) @end example @example (key-data (public-key (ecc (curve Ed25519) (flags eddsa) (q @var{q-value}))) (private-key (ecc (curve Ed25519) (flags eddsa) (q @var{q-value}) (d @var{d-value})))) @end example @noindent As you can see, some of the information is duplicated, but this provides an easy way to extract either the public or the private key. Note that the order of the elements is not defined, e.g. the private key may be stored before the public key. @var{n1 n2 ... nn} is a list of prime numbers used to composite @var{p-mpi}; this is in general not a very useful information and only available if the key generation algorithm provides them. @end deftypefun @c end gcry_pk_genkey @noindent Future versions of Libgcrypt will have extended versions of the public key interfaced which will take an additional context to allow for pre-computations, special operations, and other optimization. As a first step a new function is introduced to help using the ECC algorithms in new ways: @deftypefun gcry_error_t gcry_pubkey_get_sexp (@w{gcry_sexp_t *@var{r_sexp}}, @ @w{int @var{mode}}, @w{gcry_ctx_t @var{ctx}}) Return an S-expression representing the context @var{ctx}. Depending on the state of that context, the S-expression may either be a public key, a private key or any other object used with public key operations. On success 0 is returned and a new S-expression is stored at @var{r_sexp}; on error an error code is returned and NULL is stored at @var{r_sexp}. @var{mode} must be one of: @table @code @item 0 Decide what to return depending on the context. For example if the private key parameter is available a private key is returned, if not a public key is returned. @item GCRY_PK_GET_PUBKEY Return the public key even if the context has the private key parameter. @item GCRY_PK_GET_SECKEY Return the private key or the error @code{GPG_ERR_NO_SECKEY} if it is not possible. @end table As of now this function supports only certain ECC operations because a context object is right now only defined for ECC. Over time this function will be extended to cover more algorithms. @end deftypefun @c end gcry_pubkey_get_sexp @c ********************************************************** @c ******************* Hash Functions ********************* @c ********************************************************** @node Hashing @chapter Hashing Libgcrypt provides an easy and consistent to use interface for hashing. Hashing is buffered and several hash algorithms can be updated at once. It is possible to compute a HMAC using the same routines. The programming model follows an open/process/close paradigm and is in that similar to other building blocks provided by Libgcrypt. For convenience reasons, a few cyclic redundancy check value operations are also supported. @menu * Available hash algorithms:: List of hash algorithms supported by the library. * Working with hash algorithms:: List of functions related to hashing. @end menu @node Available hash algorithms @section Available hash algorithms @c begin table of hash algorithms @cindex SHA-1 @cindex SHA-224, SHA-256, SHA-384, SHA-512 @cindex RIPE-MD-160 @cindex MD2, MD4, MD5 @cindex TIGER, TIGER1, TIGER2 @cindex HAVAL @cindex Whirlpool @cindex CRC32 @table @code @item GCRY_MD_NONE This is not a real algorithm but used by some functions as an error return value. This constant is guaranteed to have the value @code{0}. @item GCRY_MD_SHA1 This is the SHA-1 algorithm which yields a message digest of 20 bytes. Note that SHA-1 begins to show some weaknesses and it is suggested to fade out its use if strong cryptographic properties are required. @item GCRY_MD_RMD160 This is the 160 bit version of the RIPE message digest (RIPE-MD-160). Like SHA-1 it also yields a digest of 20 bytes. This algorithm share a lot of design properties with SHA-1 and thus it is advisable not to use it for new protocols. @item GCRY_MD_MD5 This is the well known MD5 algorithm, which yields a message digest of 16 bytes. Note that the MD5 algorithm has severe weaknesses, for example it is easy to compute two messages yielding the same hash (collision attack). The use of this algorithm is only justified for non-cryptographic application. @item GCRY_MD_MD4 This is the MD4 algorithm, which yields a message digest of 16 bytes. This algorithm has severe weaknesses and should not be used. @item GCRY_MD_MD2 This is an reserved identifier for MD-2; there is no implementation yet. This algorithm has severe weaknesses and should not be used. @item GCRY_MD_TIGER This is the TIGER/192 algorithm which yields a message digest of 24 bytes. Actually this is a variant of TIGER with a different output print order as used by GnuPG up to version 1.3.2. @item GCRY_MD_TIGER1 This is the TIGER variant as used by the NESSIE project. It uses the most commonly used output print order. @item GCRY_MD_TIGER2 This is another variant of TIGER with a different padding scheme. @item GCRY_MD_HAVAL This is an reserved value for the HAVAL algorithm with 5 passes and 160 bit. It yields a message digest of 20 bytes. Note that there is no implementation yet available. @item GCRY_MD_SHA224 This is the SHA-224 algorithm which yields a message digest of 28 bytes. See Change Notice 1 for FIPS 180-2 for the specification. @item GCRY_MD_SHA256 This is the SHA-256 algorithm which yields a message digest of 32 bytes. See FIPS 180-2 for the specification. @item GCRY_MD_SHA384 This is the SHA-384 algorithm which yields a message digest of 48 bytes. See FIPS 180-2 for the specification. @item GCRY_MD_SHA512 This is the SHA-384 algorithm which yields a message digest of 64 bytes. See FIPS 180-2 for the specification. @item GCRY_MD_CRC32 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It yields an output of 4 bytes. Note that this is not a hash algorithm in the cryptographic sense. @item GCRY_MD_CRC32_RFC1510 This is the above cyclic redundancy check function, as modified by RFC 1510. It yields an output of 4 bytes. Note that this is not a hash algorithm in the cryptographic sense. @item GCRY_MD_CRC24_RFC2440 This is the OpenPGP cyclic redundancy check function. It yields an output of 3 bytes. Note that this is not a hash algorithm in the cryptographic sense. @item GCRY_MD_WHIRLPOOL This is the Whirlpool algorithm which yields a message digest of 64 bytes. @item GCRY_MD_GOSTR3411_94 This is the hash algorithm described in GOST R 34.11-94 which yields a message digest of 32 bytes. @item GCRY_MD_STRIBOG256 This is the 256-bit version of hash algorithm described in GOST R 34.11-2012 which yields a message digest of 32 bytes. @item GCRY_MD_STRIBOG512 This is the 512-bit version of hash algorithm described in GOST R 34.11-2012 which yields a message digest of 64 bytes. @end table @c end table of hash algorithms @node Working with hash algorithms @section Working with hash algorithms To use most of these function it is necessary to create a context; this is done using: @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags}) Create a message digest object for algorithm @var{algo}. @var{flags} may be given as an bitwise OR of constants described below. @var{algo} may be given as @code{0} if the algorithms to use are later set using @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid handle or NULL. For a list of supported algorithms, see @xref{Available hash algorithms}. The flags allowed for @var{mode} are: @c begin table of hash flags @table @code @item GCRY_MD_FLAG_SECURE Allocate all buffers and the resulting digest in "secure memory". Use this is the hashed data is highly confidential. @item GCRY_MD_FLAG_HMAC @cindex HMAC Turn the algorithm into a HMAC message authentication algorithm. This only works if just one algorithm is enabled for the handle. Note that the function @code{gcry_md_setkey} must be used to set the MAC key. The size of the MAC is equal to the message digest of the underlying hash algorithm. If you want CBC message authentication codes based on a cipher, see @xref{Working with cipher handles}. @end table @c begin table of hash flags You may use the function @code{gcry_md_is_enabled} to later check whether an algorithm has been enabled. @end deftypefun @c end function gcry_md_open If you want to calculate several hash algorithms at the same time, you have to use the following function right after the @code{gcry_md_open}: @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo}) Add the message digest algorithm @var{algo} to the digest object described by handle @var{h}. Duplicated enabling of algorithms is detected and ignored. @end deftypefun If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must be set using the function: @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen}) For use with the HMAC feature, set the MAC key to the value of @var{key} of length @var{keylen} bytes. There is no restriction on the length of the key. @end deftypefun After you are done with the hash calculation, you should release the resources by using: @deftypefun void gcry_md_close (gcry_md_hd_t @var{h}) Release all resources of hash context @var{h}. @var{h} should not be used after a call to this function. A @code{NULL} passed as @var{h} is ignored. The function also zeroises all sensitive information associated with this handle. @end deftypefun Often you have to do several hash operations using the same algorithm. To avoid the overhead of creating and releasing context, a reset function is provided: @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h}) Reset the current context to its initial state. This is effectively identical to a close followed by an open and enabling all currently active algorithms. @end deftypefun Often it is necessary to start hashing some data and then continue to hash different data. To avoid hashing the same data several times (which might not even be possible if the data is received from a pipe), a snapshot of the current hash context can be taken and turned into a new context: @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src}) Create a new digest object as an exact copy of the object described by handle @var{handle_src} and store it in @var{handle_dst}. The context is not reset and you can continue to hash data using this context and independently using the original context. @end deftypefun Now that we have prepared everything to calculate hashes, it is time to see how it is actually done. There are two ways for this, one to update the hash with a block of memory and one macro to update the hash by just one character. Both methods can be used on the same hash context. @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length}) Pass @var{length} bytes of the data in @var{buffer} to the digest object with handle @var{h} to update the digest values. This function should be used for large blocks of data. @end deftypefun @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c}) Pass the byte in @var{c} to the digest object with handle @var{h} to update the digest value. This is an efficient function, implemented as a macro to buffer the data before an actual update. @end deftypefun The semantics of the hash functions do not provide for reading out intermediate message digests because the calculation must be finalized first. This finalization may for example include the number of bytes hashed in the message digest or some padding. @deftypefun void gcry_md_final (gcry_md_hd_t @var{h}) Finalize the message digest calculation. This is not really needed because @code{gcry_md_read} does this implicitly. After this has been done no further updates (by means of @code{gcry_md_write} or @code{gcry_md_putc} are allowed. Only the first call to this function has an effect. It is implemented as a macro. @end deftypefun The way to read out the calculated message digest is by using the function: @deftypefun {unsigned char *} gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo}) @code{gcry_md_read} returns the message digest after finalizing the calculation. This function may be used as often as required but it will always return the same value for one handle. The returned message digest is allocated within the message context and therefore valid until the handle is released or reseted (using @code{gcry_md_close} or @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only enabled message digest or it may specify one of the enabled algorithms. The function does return @code{NULL} if the requested algorithm has not been enabled. @end deftypefun Because it is often necessary to get the message digest of blocks of memory, two fast convenience function are available for this task: @deftypefun gpg_err_code_t gcry_md_hash_buffers ( @ @w{int @var{algo}}, @w{unsigned int @var{flags}}, @ @w{void *@var{digest}}, @ @w{const gcry_buffer_t *@var{iov}}, @w{int @var{iovcnt}} ) @code{gcry_md_hash_buffers} is a shortcut function to calculate a message digest from several buffers. This function does not require a context and immediately returns the message digest of the data described by @var{iov} and @var{iovcnt}. @var{digest} must be allocated by the caller, large enough to hold the message digest yielded by the the specified algorithm @var{algo}. This required size may be obtained by using the function @code{gcry_md_get_algo_dlen}. @var{iov} is an array of buffer descriptions with @var{iovcnt} items. The caller should zero out the structures in this array and for each array item set the fields @code{.data} to the address of the data to be hashed, @code{.len} to number of bytes to be hashed. If @var{.off} is also set, the data is taken starting at @var{.off} bytes from the begin of the buffer. The field @code{.size} is not used. The only supported flag value for @var{flags} is @var{GCRY_MD_FLAG_HMAC} which turns this function into a HMAC function; the first item in @var{iov} is then used as the key. On success the function returns 0 and stores the resulting hash or MAC at @var{digest}. @end deftypefun @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length}); @code{gcry_md_hash_buffer} is a shortcut function to calculate a message digest of a buffer. This function does not require a context and immediately returns the message digest of the @var{length} bytes at @var{buffer}. @var{digest} must be allocated by the caller, large enough to hold the message digest yielded by the the specified algorithm @var{algo}. This required size may be obtained by using the function @code{gcry_md_get_algo_dlen}. Note that in contrast to @code{gcry_md_hash_buffers} this function will abort the process if an unavailable algorithm is used. @end deftypefun @c *********************************** @c ***** MD info functions *********** @c *********************************** Hash algorithms are identified by internal algorithm numbers (see @code{gcry_md_open} for a list). However, in most applications they are used by names, so two functions are available to map between string representations and hash algorithm identifiers. @deftypefun {const char *} gcry_md_algo_name (int @var{algo}) Map the digest algorithm id @var{algo} to a string representation of the algorithm name. For unknown algorithms this function returns the string @code{"?"}. This function should not be used to test for the availability of an algorithm. @end deftypefun @deftypefun int gcry_md_map_name (const char *@var{name}) Map the algorithm with @var{name} to a digest algorithm identifier. Returns 0 if the algorithm name is not known. Names representing @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF} dotted format is used and the OID is prefixed with either "@code{oid.}" or "@code{OID.}". For a list of supported OIDs, see the source code at @file{cipher/md.c}. This function should not be used to test for the availability of an algorithm. @end deftypefun @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length}) Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the user allocated @var{buffer}. @var{length} must point to variable with the available size of @var{buffer} and receives after return the actual size of the returned OID. The returned error code may be @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive the OID; it is possible to call the function with @code{NULL} for @var{buffer} to have it only return the required size. The function returns 0 on success. @end deftypefun To test whether an algorithm is actually available for use, the following macro should be used: @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo}) The macro returns 0 if the algorithm @var{algo} is available for use. @end deftypefun If the length of a message digest is not known, it can be retrieved using the following function: @deftypefun {unsigned int} gcry_md_get_algo_dlen (int @var{algo}) Retrieve the length in bytes of the digest yielded by algorithm @var{algo}. This is often used prior to @code{gcry_md_read} to allocate sufficient memory for the digest. @end deftypefun In some situations it might be hard to remember the algorithm used for the ongoing hashing. The following function might be used to get that information: @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h}) Retrieve the algorithm used with the handle @var{h}. Note that this does not work reliable if more than one algorithm is enabled in @var{h}. @end deftypefun The following macro might also be useful: @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h}) This function returns true when the digest object @var{h} is allocated in "secure memory"; i.e. @var{h} was created with the @code{GCRY_MD_FLAG_SECURE}. @end deftypefun @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo}) This function returns true when the algorithm @var{algo} has been enabled for the digest object @var{h}. @end deftypefun Tracking bugs related to hashing is often a cumbersome task which requires to add a lot of printf statements into the code. Libgcrypt provides an easy way to avoid this. The actual data hashed can be written to files on request. @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix}) Enable debugging for the digest object with handle @var{h}. This creates create files named @file{dbgmd-.} while doing the actual hashing. @var{suffix} is the string part in the filename. The number is a counter incremented for each new hashing. The data in the file is the raw data as passed to @code{gcry_md_write} or @code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the debugging is stopped and the file closed. This is only rarely required because @code{gcry_md_close} implicitly stops debugging. @end deftypefun @c ********************************************************** @c ******************* MAC Functions ********************** @c ********************************************************** @node Message Authentication Codes @chapter Message Authentication Codes Libgcrypt provides an easy and consistent to use interface for generating Message Authentication Codes (MAC). MAC generation is buffered and interface similar to the one used with hash algorithms. The programming model follows an open/process/close paradigm and is in that similar to other building blocks provided by Libgcrypt. @menu * Available MAC algorithms:: List of MAC algorithms supported by the library. * Working with MAC algorithms:: List of functions related to MAC algorithms. @end menu @node Available MAC algorithms @section Available MAC algorithms @c begin table of MAC algorithms @cindex HMAC-SHA-1 @cindex HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, HMAC-SHA-512 @cindex HMAC-RIPE-MD-160 @cindex HMAC-MD2, HMAC-MD4, HMAC-MD5 @cindex HMAC-TIGER1 @cindex HMAC-Whirlpool @cindex HMAC-Stribog-256, HMAC-Stribog-512 @cindex HMAC-GOSTR-3411-94 @table @code @item GCRY_MAC_NONE This is not a real algorithm but used by some functions as an error return value. This constant is guaranteed to have the value @code{0}. @item GCRY_MAC_HMAC_SHA256 This is keyed-hash message authentication code (HMAC) message authentication algorithm based on the SHA-256 hash algorithm. @item GCRY_MAC_HMAC_SHA224 This is HMAC message authentication algorithm based on the SHA-224 hash algorithm. @item GCRY_MAC_HMAC_SHA512 This is HMAC message authentication algorithm based on the SHA-512 hash algorithm. @item GCRY_MAC_HMAC_SHA384 This is HMAC message authentication algorithm based on the SHA-384 hash algorithm. @item GCRY_MAC_HMAC_SHA1 This is HMAC message authentication algorithm based on the SHA-1 hash algorithm. @item GCRY_MAC_HMAC_MD5 This is HMAC message authentication algorithm based on the MD5 hash algorithm. @item GCRY_MAC_HMAC_MD4 This is HMAC message authentication algorithm based on the MD4 hash algorithm. @item GCRY_MAC_HMAC_RMD160 This is HMAC message authentication algorithm based on the RIPE-MD-160 hash algorithm. @item GCRY_MAC_HMAC_WHIRLPOOL This is HMAC message authentication algorithm based on the WHIRLPOOL hash algorithm. @item GCRY_MAC_HMAC_GOSTR3411_94 This is HMAC message authentication algorithm based on the GOST R 34.11-94 hash algorithm. @item GCRY_MAC_HMAC_STRIBOG256 This is HMAC message authentication algorithm based on the 256-bit hash algorithm described in GOST R 34.11-2012. @item GCRY_MAC_HMAC_STRIBOG512 This is HMAC message authentication algorithm based on the 512-bit hash algorithm described in GOST R 34.11-2012. @item GCRY_MAC_CMAC_AES This is CMAC (Cipher-based MAC) message authentication algorithm based on the AES block cipher algorithm. @item GCRY_MAC_CMAC_3DES This is CMAC message authentication algorithm based on the three-key EDE Triple-DES block cipher algorithm. @item GCRY_MAC_CMAC_CAMELLIA This is CMAC message authentication algorithm based on the Camellia block cipher algorithm. @item GCRY_MAC_CMAC_CAST5 This is CMAC message authentication algorithm based on the CAST128-5 block cipher algorithm. @item GCRY_MAC_CMAC_BLOWFISH This is CMAC message authentication algorithm based on the Blowfish block cipher algorithm. @item GCRY_MAC_CMAC_TWOFISH This is CMAC message authentication algorithm based on the Twofish block cipher algorithm. @item GCRY_MAC_CMAC_SERPENT This is CMAC message authentication algorithm based on the Serpent block cipher algorithm. @item GCRY_MAC_CMAC_SEED This is CMAC message authentication algorithm based on the SEED block cipher algorithm. @item GCRY_MAC_CMAC_RFC2268 This is CMAC message authentication algorithm based on the Ron's Cipher 2 block cipher algorithm. @item GCRY_MAC_CMAC_IDEA This is CMAC message authentication algorithm based on the IDEA block cipher algorithm. @item GCRY_MAC_CMAC_GOST28147 This is CMAC message authentication algorithm based on the GOST 28147-89 block cipher algorithm. @item GCRY_MAC_GMAC_AES This is GMAC (GCM mode based MAC) message authentication algorithm based on the AES block cipher algorithm. @item GCRY_MAC_GMAC_CAMELLIA This is GMAC message authentication algorithm based on the Camellia block cipher algorithm. @item GCRY_MAC_GMAC_TWOFISH This is GMAC message authentication algorithm based on the Twofish block cipher algorithm. @item GCRY_MAC_GMAC_SERPENT This is GMAC message authentication algorithm based on the Serpent block cipher algorithm. @item GCRY_MAC_GMAC_SEED This is GMAC message authentication algorithm based on the SEED block cipher algorithm. @end table @c end table of MAC algorithms @node Working with MAC algorithms @section Working with MAC algorithms To use most of these function it is necessary to create a context; this is done using: @deftypefun gcry_error_t gcry_mac_open (gcry_mac_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags}, gcry_ctx_t @var{ctx}) Create a MAC object for algorithm @var{algo}. @var{flags} may be given as an bitwise OR of constants described below. @var{hd} is guaranteed to either receive a valid handle or NULL. @var{ctx} is context object to associate MAC object with. @var{ctx} maybe set to NULL. For a list of supported algorithms, see @xref{Available MAC algorithms}. The flags allowed for @var{mode} are: @c begin table of MAC flags @table @code @item GCRY_MAC_FLAG_SECURE Allocate all buffers and the resulting MAC in "secure memory". Use this if the MAC data is highly confidential. @end table @c begin table of MAC flags @end deftypefun @c end function gcry_mac_open In order to use a handle for performing MAC algorithm operations, a `key' has to be set first: @deftypefun gcry_error_t gcry_mac_setkey (gcry_mac_hd_t @var{h}, const void *@var{key}, size_t @var{keylen}) Set the MAC key to the value of @var{key} of length @var{keylen} bytes. With HMAC algorithms, there is no restriction on the length of the key. With CMAC algorithms, the length of the key is restricted to those supported by the underlying block cipher. @end deftypefun GMAC algorithms need initialization vector to be set, which can be performed with function: @deftypefun gcry_error_t gcry_mac_setiv (gcry_mac_hd_t @var{h}, const void *@var{iv}, size_t @var{ivlen}) Set the IV to the value of @var{iv} of length @var{ivlen} bytes. @end deftypefun After you are done with the MAC calculation, you should release the resources by using: @deftypefun void gcry_mac_close (gcry_mac_hd_t @var{h}) Release all resources of MAC context @var{h}. @var{h} should not be used after a call to this function. A @code{NULL} passed as @var{h} is ignored. The function also clears all sensitive information associated with this handle. @end deftypefun Often you have to do several MAC operations using the same algorithm. To avoid the overhead of creating and releasing context, a reset function is provided: @deftypefun gcry_error_t gcry_mac_reset (gcry_mac_hd_t @var{h}) Reset the current context to its initial state. This is effectively identical to a close followed by an open and setting same key. Note that gcry_mac_reset is implemented as a macro. @end deftypefun Now that we have prepared everything to calculate MAC, it is time to see how it is actually done. @deftypefun gcry_error_t gcry_mac_write (gcry_mac_hd_t @var{h}, const void *@var{buffer}, size_t @var{length}) Pass @var{length} bytes of the data in @var{buffer} to the MAC object with handle @var{h} to update the MAC values. @end deftypefun The way to read out the calculated MAC is by using the function: @deftypefun gcry_error_t gcry_mac_read (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t *@var{length}) @code{gcry_mac_read} returns the MAC after finalizing the calculation. Function copies the resulting MAC value to @var{buffer} of the length @var{length}. If @var{length} is larger than length of resulting MAC value, then length of MAC is returned through @var{length}. @end deftypefun To compare existing MAC value with recalculated MAC, one is to use the function: @deftypefun gcry_error_t gcry_mac_verify (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t @var{length}) @code{gcry_mac_verify} finalizes MAC calculation and compares result with @var{length} bytes of data in @var{buffer}. Error code @code{GPG_ERR_CHECKSUM} is returned if the MAC value in the buffer @var{buffer} does not match the MAC calculated in object @var{h}. @end deftypefun In some situations it might be hard to remember the algorithm used for the MAC calculation. The following function might be used to get that information: @deftypefun {int} gcry_mac_get_algo (gcry_mac_hd_t @var{h}) Retrieve the algorithm used with the handle @var{h}. @end deftypefun @c *********************************** @c ***** MAC info functions ********** @c *********************************** MAC algorithms are identified by internal algorithm numbers (see @code{gcry_mac_open} for a list). However, in most applications they are used by names, so two functions are available to map between string representations and MAC algorithm identifiers. @deftypefun {const char *} gcry_mac_algo_name (int @var{algo}) Map the MAC algorithm id @var{algo} to a string representation of the algorithm name. For unknown algorithms this function returns the string @code{"?"}. This function should not be used to test for the availability of an algorithm. @end deftypefun @deftypefun int gcry_mac_map_name (const char *@var{name}) Map the algorithm with @var{name} to a MAC algorithm identifier. Returns 0 if the algorithm name is not known. This function should not be used to test for the availability of an algorithm. @end deftypefun To test whether an algorithm is actually available for use, the following macro should be used: @deftypefun gcry_error_t gcry_mac_test_algo (int @var{algo}) The macro returns 0 if the MAC algorithm @var{algo} is available for use. @end deftypefun If the length of a message digest is not known, it can be retrieved using the following function: @deftypefun {unsigned int} gcry_mac_get_algo_maclen (int @var{algo}) Retrieve the length in bytes of the MAC yielded by algorithm @var{algo}. This is often used prior to @code{gcry_mac_read} to allocate sufficient memory for the MAC value. On error @code{0} is returned. @end deftypefun @deftypefun {unsigned int} gcry_mac_get_algo_keylen (@var{algo}) This function returns length of the key for MAC algorithm @var{algo}. If the algorithm supports multiple key lengths, the default supported key length is returned. On error @code{0} is returned. The key length is returned as number of octets. @end deftypefun @c ******************************************************* @c ******************* KDF ***************************** @c ******************************************************* @node Key Derivation @chapter Key Derivation @acronym{Libgcypt} provides a general purpose function to derive keys from strings. @deftypefun gpg_error_t gcry_kdf_derive ( @ @w{const void *@var{passphrase}}, @w{size_t @var{passphraselen}}, @ @w{int @var{algo}}, @w{int @var{subalgo}}, @ @w{const void *@var{salt}}, @w{size_t @var{saltlen}}, @ @w{unsigned long @var{iterations}}, @ @w{size_t @var{keysize}}, @w{void *@var{keybuffer}} ) Derive a key from a passphrase. @var{keysize} gives the requested size of the keys in octets. @var{keybuffer} is a caller provided buffer filled on success with the derived key. The input passphrase is taken from @var{passphrase} which is an arbitrary memory buffer of @var{passphraselen} octets. @var{algo} specifies the KDF algorithm to use; see below. @var{subalgo} specifies an algorithm used internally by the KDF algorithms; this is usually a hash algorithm but certain KDF algorithms may use it differently. @var{salt} is a salt of length @var{saltlen} octets, as needed by most KDF algorithms. @var{iterations} is a positive integer parameter to most KDFs. @noindent On success 0 is returned; on failure an error code. @noindent Currently supported KDFs (parameter @var{algo}): @table @code @item GCRY_KDF_SIMPLE_S2K The OpenPGP simple S2K algorithm (cf. RFC4880). Its use is strongly deprecated. @var{salt} and @var{iterations} are not needed and may be passed as @code{NULL}/@code{0}. @item GCRY_KDF_SALTED_S2K The OpenPGP salted S2K algorithm (cf. RFC4880). Usually not used. @var{iterations} is not needed and may be passed as @code{0}. @var{saltlen} must be given as 8. @item GCRY_KDF_ITERSALTED_S2K The OpenPGP iterated+salted S2K algorithm (cf. RFC4880). This is the default for most OpenPGP applications. @var{saltlen} must be given as 8. Note that OpenPGP defines a special encoding of the @var{iterations}; however this function takes the plain decoded iteration count. @item GCRY_KDF_PBKDF2 The PKCS#5 Passphrase Based Key Derivation Function number 2. @item GCRY_KDF_SCRYPT The SCRYPT Key Derivation Function. The subalgorithm is used to specify the CPU/memory cost parameter N, and the number of iterations is used for the parallelization parameter p. The block size is fixed at 8 in the current implementation. @end table @end deftypefun @c ********************************************************** @c ******************* Random ***************************** @c ********************************************************** @node Random Numbers @chapter Random Numbers @menu * Quality of random numbers:: Libgcrypt uses different quality levels. * Retrieving random numbers:: How to retrieve random numbers. @end menu @node Quality of random numbers @section Quality of random numbers @acronym{Libgcypt} offers random numbers of different quality levels: @deftp {Data type} gcry_random_level_t The constants for the random quality levels are of this enum type. @end deftp @table @code @item GCRY_WEAK_RANDOM For all functions, except for @code{gcry_mpi_randomize}, this level maps to GCRY_STRONG_RANDOM. If you do not want this, consider using @code{gcry_create_nonce}. @item GCRY_STRONG_RANDOM Use this level for session keys and similar purposes. @item GCRY_VERY_STRONG_RANDOM Use this level for long term key material. @end table @node Retrieving random numbers @section Retrieving random numbers @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level}) Fill @var{buffer} with @var{length} random bytes using a random quality as defined by @var{level}. @end deftypefun @deftypefun {void *} gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level}) Convenience function to allocate a memory block consisting of @var{nbytes} fresh random bytes using a random quality as defined by @var{level}. @end deftypefun @deftypefun {void *} gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level}) Convenience function to allocate a memory block consisting of @var{nbytes} fresh random bytes using a random quality as defined by @var{level}. This function differs from @code{gcry_random_bytes} in that the returned buffer is allocated in a ``secure'' area of the memory. @end deftypefun @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length}) Fill @var{buffer} with @var{length} unpredictable bytes. This is commonly called a nonce and may also be used for initialization vectors and padding. This is an extra function nearly independent of the other random function for 3 reasons: It better protects the regular random generator's internal state, provides better performance and does not drain the precious entropy pool. @end deftypefun @c ********************************************************** @c ******************* S-Expressions *********************** @c ********************************************************** @node S-expressions @chapter S-expressions S-expressions are used by the public key functions to pass complex data structures around. These LISP like objects are used by some cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions to parse and construct them. For detailed information, see @cite{Ron Rivest, code and description of S-expressions, @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}. @menu * Data types for S-expressions:: Data types related with S-expressions. * Working with S-expressions:: How to work with S-expressions. @end menu @node Data types for S-expressions @section Data types for S-expressions @deftp {Data type} gcry_sexp_t The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal representation of an S-expression. @end deftp @node Working with S-expressions @section Working with S-expressions @noindent There are several functions to create an Libgcrypt S-expression object from its external representation or from a string template. There is also a function to convert the internal representation back into one of the external formats: @deftypefun gcry_error_t gcry_sexp_new (@w{gcry_sexp_t *@var{r_sexp}}, @w{const void *@var{buffer}}, @w{size_t @var{length}}, @w{int @var{autodetect}}) This is the generic function to create an new S-expression object from its external representation in @var{buffer} of @var{length} bytes. On success the result is stored at the address given by @var{r_sexp}. With @var{autodetect} set to 0, the data in @var{buffer} is expected to be in canonized format, with @var{autodetect} set to 1 the parses any of the defined external formats. If @var{buffer} does not hold a valid S-expression an error code is returned and @var{r_sexp} set to @code{NULL}. Note that the caller is responsible for releasing the newly allocated S-expression using @code{gcry_sexp_release}. @end deftypefun @deftypefun gcry_error_t gcry_sexp_create (@w{gcry_sexp_t *@var{r_sexp}}, @w{void *@var{buffer}}, @w{size_t @var{length}}, @w{int @var{autodetect}}, @w{void (*@var{freefnc})(void*)}) This function is identical to @code{gcry_sexp_new} but has an extra argument @var{freefnc}, which, when not set to @code{NULL}, is expected to be a function to release the @var{buffer}; most likely the standard @code{free} function is used for this argument. This has the effect of transferring the ownership of @var{buffer} to the created object in @var{r_sexp}. The advantage of using this function is that Libgcrypt might decide to directly use the provided buffer and thus avoid extra copying. @end deftypefun @deftypefun gcry_error_t gcry_sexp_sscan (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{buffer}}, @w{size_t @var{length}}) This is another variant of the above functions. It behaves nearly identical but provides an @var{erroff} argument which will receive the offset into the buffer where the parsing stopped on error. @end deftypefun @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...}) This function creates an internal S-expression from the string template @var{format} and stores it at the address of @var{r_sexp}. If there is a parsing error, the function returns an appropriate error code and stores the offset into @var{format} where the parsing stopped in @var{erroff}. The function supports a couple of printf-like formatting characters and expects arguments for some of these escape sequences right after @var{format}. The following format characters are defined: @table @samp @item %m The next argument is expected to be of type @code{gcry_mpi_t} and a copy of its value is inserted into the resulting S-expression. The MPI is stored as a signed integer. @item %M The next argument is expected to be of type @code{gcry_mpi_t} and a copy of its value is inserted into the resulting S-expression. The MPI is stored as an unsigned integer. @item %s The next argument is expected to be of type @code{char *} and that string is inserted into the resulting S-expression. @item %d The next argument is expected to be of type @code{int} and its value is inserted into the resulting S-expression. @item %u The next argument is expected to be of type @code{unsigned int} and its value is inserted into the resulting S-expression. @item %b The next argument is expected to be of type @code{int} directly followed by an argument of type @code{char *}. This represents a buffer of given length to be inserted into the resulting S-expression. @item %S The next argument is expected to be of type @code{gcry_sexp_t} and a copy of that S-expression is embedded in the resulting S-expression. The argument needs to be a regular S-expression, starting with a parenthesis. @end table @noindent No other format characters are defined and would return an error. Note that the format character @samp{%%} does not exists, because a percent sign is not a valid character in an S-expression. @end deftypefun @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}}) Release the S-expression object @var{sexp}. If the S-expression is stored in secure memory it explicitly zeroises that memory; note that this is done in addition to the zeroisation always done when freeing secure memory. @end deftypefun @noindent The next 2 functions are used to convert the internal representation back into a regular external S-expression format and to show the structure for debugging. @deftypefun size_t gcry_sexp_sprint (@w{gcry_sexp_t @var{sexp}}, @w{int @var{mode}}, @w{char *@var{buffer}}, @w{size_t @var{maxlength}}) Copies the S-expression object @var{sexp} into @var{buffer} using the format specified in @var{mode}. @var{maxlength} must be set to the allocated length of @var{buffer}. The function returns the actual length of valid bytes put into @var{buffer} or 0 if the provided buffer is too short. Passing @code{NULL} for @var{buffer} returns the required length for @var{buffer}. For convenience reasons an extra byte with value 0 is appended to the buffer. @noindent The following formats are supported: @table @code @item GCRYSEXP_FMT_DEFAULT Returns a convenient external S-expression representation. @item GCRYSEXP_FMT_CANON Return the S-expression in canonical format. @item GCRYSEXP_FMT_BASE64 Not currently supported. @item GCRYSEXP_FMT_ADVANCED Returns the S-expression in advanced format. @end table @end deftypefun @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}}) Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's logging stream. @end deftypefun @noindent Often canonical encoding is used in the external representation. The following function can be used to check for valid encoding and to learn the length of the S-expression" @deftypefun size_t gcry_sexp_canon_len (@w{const unsigned char *@var{buffer}}, @w{size_t @var{length}}, @w{size_t *@var{erroff}}, @w{int *@var{errcode}}) Scan the canonical encoded @var{buffer} with implicit length values and return the actual length this S-expression uses. For a valid S-expression it should never return 0. If @var{length} is not 0, the maximum length to scan is given; this can be used for syntax checks of data passed from outside. @var{errcode} and @var{erroff} may both be passed as @code{NULL}. @end deftypefun @noindent There are functions to parse S-expressions and retrieve elements: @deftypefun gcry_sexp_t gcry_sexp_find_token (@w{const gcry_sexp_t @var{list}}, @w{const char *@var{token}}, @w{size_t @var{toklen}}) Scan the S-expression for a sublist with a type (the car of the list) matching the string @var{token}. If @var{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 @code{NULL} when not found. @end deftypefun @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}}) Return the length of the @var{list}. For a valid S-expression this should be at least 1. @end deftypefun @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}) Create and return a new S-expression from the element with index @var{number} in @var{list}. Note that the first element has the index 0. If there is no such element, @code{NULL} is returned. @end deftypefun @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}}) Create and return a new S-expression from the first element in @var{list}; this called the "type" and should always exist and be a string. @code{NULL} is returned in case of a problem. @end deftypefun @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{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 @code{NULL} on error. @end deftypefun @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}}) This function is used to get data from a @var{list}. A pointer to the actual data with index @var{number} is returned and the length of this data will be stored to @var{datalen}. If there is no data at the given index or the index represents another list, @code{NULL} is returned. @strong{Caution:} The returned pointer is valid as long as @var{list} is not modified or released. @noindent Here is an example on how to extract and print the surname (Meier) from the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}: @example size_t len; const char *name; name = gcry_sexp_nth_data (list, 2, &len); printf ("my name is %.*s\n", (int)len, name); @end example @end deftypefun @deftypefun {void *} gcry_sexp_nth_buffer (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{rlength}}) This function is used to get data from a @var{list}. A malloced buffer with the actual data at list index @var{number} is returned and the length of this buffer will be stored to @var{rlength}. If there is no data at the given index or the index represents another list, @code{NULL} is returned. The caller must release the result using @code{gcry_free}. @noindent Here is an example on how to extract and print the CRC value from the S-expression @samp{(hash crc32 #23ed00d7)}: @example size_t len; char *value; value = gcry_sexp_nth_buffer (list, 2, &len); if (value) fwrite (value, len, 1, stdout); gcry_free (value); @end example @end deftypefun @deftypefun {char *} gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}) This function is used to get and convert data from a @var{list}. The data is assumed to be a Nul terminated string. The caller must release this returned value using @code{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, @code{NULL} is returned. @end deftypefun @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}}) This function is used to get and convert data from a @var{list}. This data is assumed to be an MPI stored in the format described by @var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must release this returned value using @code{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, @code{NULL} is returned. If you use this function to parse results of a public key function, you most likely want to use @code{GCRYMPI_FMT_USG}. @end deftypefun @deftypefun gpg_error_t gcry_sexp_extract_param ( @ @w{gcry_sexp_t @var{sexp}}, @ @w{const char *@var{path}}, @ @w{const char *@var{list}}, ...) Extract parameters from an S-expression using a list of parameter names. The names of these parameters are specified in LIST. White space between the parameter names are ignored. Some special characters may be given to control the conversion: @table @samp @item + Switch to unsigned integer format (GCRYMPI_FMT_USG). This is the default mode. @item - Switch to standard signed format (GCRYMPI_FMT_STD). @item / Switch to opaque MPI format. The resulting MPIs may not be used for computations; see @code{gcry_mpi_get_opaque} for details. @item & Switch to buffer descriptor mode. See below for details. @item ? If immediately following a parameter letter (no white space allowed), that parameter is considered optional. @end table In general parameter names are single letters. To use a string for a parameter name, enclose the name in single quotes. Unless in buffer descriptor mode for each parameter name a pointer to an @code{gcry_mpi_t} variable is expected finally followed by a @code{NULL}. For example @example _gcry_sexp_extract_param (key, NULL, "n/x+e d-'foo'", &mpi_n, &mpi_x, &mpi_e, &mpi_foo, NULL) @end example stores the parameter 'n' from @var{key} as an unsigned MPI into @var{mpi_n}, the parameter 'x' as an opaque MPI into @var{mpi_x}, the parameter 'e' again as an unsigned MPI into @var{mpi_e}, and the parameter 'foo' as a signed MPI. @var{path} is an optional string used to locate a token. The exclamation mark separated tokens are used via @code{gcry_sexp_find_token} to find a start point inside the S-expression. In buffer descriptor mode a pointer to a @code{gcry_buffer_t} descriptor is expected instead of a pointer to an MPI. The caller may use two different operation modes here: If the @var{data} field of the provided descriptor is @code{NULL}, the function allocates a new buffer and stores it at @var{data}; the other fields are set accordingly with @var{off} set to 0. If @var{data} is not @code{NULL}, the function assumes that the @var{data}, @var{size}, and @var{off} fields specify a buffer where to but the value of the respective parameter; on return the @var{len} field receives the number of bytes copied to that buffer; in case the buffer is too small, the function immediately returns with an error code (and @var{len} is set to 0). The function returns NULL on success. On error an error code is returned and the passed MPIs are either unchanged or set to NULL. @end deftypefun @c ********************************************************** @c ******************* MPIs ******** *********************** @c ********************************************************** @node MPI library @chapter MPI library @menu * Data types:: MPI related data types. * Basic functions:: First steps with MPI numbers. * MPI formats:: External representation of MPIs. * Calculations:: Performing MPI calculations. * Comparisons:: How to compare MPI values. * Bit manipulations:: How to access single bits of MPI values. * EC functions:: Elliptic curve related functions. * Miscellaneous:: Miscellaneous MPI functions. @end menu Public key cryptography is based on mathematics with large numbers. To implement the public key functions, a library for handling these large numbers is required. Because of the general usefulness of such a library, its interface is exposed by Libgcrypt. In the context of Libgcrypt and in most other applications, these large numbers are called MPIs (multi-precision-integers). @node Data types @section Data types @deftp {Data type} {gcry_mpi_t} This type represents an object to hold an MPI. @end deftp @deftp {Data type} {gcry_mpi_point_t} This type represents an object to hold a point for elliptic curve math. @end deftp @node Basic functions @section Basic functions @noindent To work with MPIs, storage must be allocated and released for the numbers. This can be done with one of these functions: @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}}) Allocate a new MPI object, initialize it to 0 and initially allocate enough memory for a number of at least @var{nbits}. This pre-allocation is only a small performance issue and not actually necessary because Libgcrypt automatically re-allocates the required memory. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}}) This is identical to @code{gcry_mpi_new} but allocates the MPI in the so called "secure memory" which in turn will take care that all derived values will also be stored in this "secure memory". Use this for highly confidential data like private key parameters. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}}) Create a new MPI as the exact copy of @var{a} but with the constant and immutable flags cleared. @end deftypefun @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}}) Release the MPI @var{a} and free all associated resources. Passing @code{NULL} is allowed and ignored. When a MPI stored in the "secure memory" is released, that memory gets wiped out immediately. @end deftypefun @noindent The simplest operations are used to assign a new value to an MPI: @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}}) Assign the value of @var{u} to @var{w} and return @var{w}. If @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the value of @var{u} and returned. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}}) Assign the value of @var{u} to @var{w} and return @var{w}. If @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the value of @var{u} and returned. This function takes an @code{unsigned int} as type for @var{u} and thus it is only possible to set @var{w} to small values (usually up to the word size of the CPU). @end deftypefun @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}}) Swap the values of @var{a} and @var{b}. @end deftypefun @deftypefun void gcry_mpi_snatch (@w{gcry_mpi_t @var{w}}, @ @w{const gcry_mpi_t @var{u}}) Set @var{u} into @var{w} and release @var{u}. If @var{w} is @code{NULL} only @var{u} will be released. @end deftypefun @deftypefun void gcry_mpi_neg (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}) Set the sign of @var{w} to the negative of @var{u}. @end deftypefun @deftypefun void gcry_mpi_abs (@w{gcry_mpi_t @var{w}}) Clear the sign of @var{w}. @end deftypefun @node MPI formats @section MPI formats @noindent The following functions are used to convert between an external representation of an MPI and the internal one of Libgcrypt. @deftypefun gcry_error_t gcry_mpi_scan (@w{gcry_mpi_t *@var{r_mpi}}, @w{enum gcry_mpi_format @var{format}}, @w{const unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nscanned}}) Convert the external representation of an integer stored in @var{buffer} with a length of @var{buflen} into a newly created MPI returned which will be stored at the address of @var{r_mpi}. For certain formats the length argument is not required and should be passed as @code{0}. After a successful operation the variable @var{nscanned} receives the number of bytes actually scanned unless @var{nscanned} was given as @code{NULL}. @var{format} describes the format of the MPI as stored in @var{buffer}: @table @code @item GCRYMPI_FMT_STD 2-complement stored without a length header. Note that @code{gcry_mpi_print} stores a @code{0} as a string of zero length. @item GCRYMPI_FMT_PGP As used by OpenPGP (only defined as unsigned). This is basically @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header. @item GCRYMPI_FMT_SSH As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD} with a 4 byte big endian header. @item GCRYMPI_FMT_HEX Stored as a string with each byte of the MPI encoded as 2 hex digits. Negative numbers are prefix with a minus sign and in addition the high bit is always zero to make clear that an explicit sign ist used. When using this format, @var{buflen} must be zero. @item GCRYMPI_FMT_USG Simple unsigned integer. @end table @noindent Note that all of the above formats store the integer in big-endian format (MSB first). @end deftypefun @deftypefun gcry_error_t gcry_mpi_print (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nwritten}}, @w{const gcry_mpi_t @var{a}}) Convert the MPI @var{a} into an external representation described by @var{format} (see above) and store it in the provided @var{buffer} which has a usable length of at least the @var{buflen} bytes. If @var{nwritten} is not NULL, it will receive the number of bytes actually stored in @var{buffer} after a successful operation. @end deftypefun @deftypefun gcry_error_t gcry_mpi_aprint (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char **@var{buffer}}, @w{size_t *@var{nbytes}}, @w{const gcry_mpi_t @var{a}}) Convert the MPI @var{a} into an external representation described by @var{format} (see above) and store it in a newly allocated buffer which address will be stored in the variable @var{buffer} points to. The number of bytes stored in this buffer will be stored in the variable @var{nbytes} points to, unless @var{nbytes} is @code{NULL}. Even if @var{nbytes} is zero, the function allocates at least one byte and store a zero there. Thus with formats @code{GCRYMPI_FMT_STD} and @code{GCRYMPI_FMT_USG} the caller may safely set a returned length of 0 to 1 to represent a zero as a 1 byte string. @end deftypefun @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}}) Dump the value of @var{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 @code{NULL} for @var{a}. @end deftypefun @node Calculations @section Calculations @noindent Basic arithmetic operations: @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}) @math{@var{w} = @var{u} + @var{v}}. @end deftypefun @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}}) @math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer. @end deftypefun @deftypefun void gcry_mpi_addm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}}) @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}. @end deftypefun @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}) @math{@var{w} = @var{u} - @var{v}}. @end deftypefun @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}}) @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer. @end deftypefun @deftypefun void gcry_mpi_subm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}}) @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}. @end deftypefun @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}) @math{@var{w} = @var{u} * @var{v}}. @end deftypefun @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}}) @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer. @end deftypefun @deftypefun void gcry_mpi_mulm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}}) @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}. @end deftypefun @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}}) @c FIXME: I am in need for a real TeX{info} guru: @c I don't know why TeX can grok @var{e} here. @math{@var{w} = @var{u} * 2^e}. @end deftypefun @deftypefun void gcry_mpi_div (@w{gcry_mpi_t @var{q}}, @w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}}, @w{int @var{round}}) @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} = @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed as @code{NULL}. @var{round} should be negative or 0. @end deftypefun @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}}) @math{@var{r} = @var{dividend} \bmod @var{divisor}}. @end deftypefun @deftypefun void gcry_mpi_powm (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{b}}, @w{const gcry_mpi_t @var{e}}, @w{const gcry_mpi_t @var{m}}) @c I don't know why TeX can grok @var{e} here. @math{@var{w} = @var{b}^e \bmod @var{m}}. @end deftypefun @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}}) Set @var{g} to the greatest common divisor of @var{a} and @var{b}. Return true if the @var{g} is 1. @end deftypefun @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}}) Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}. Return true if the inverse exists. @end deftypefun @node Comparisons @section Comparisons @noindent The next 2 functions are used to compare MPIs: @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}}) Compare the multi-precision-integers number @var{u} and @var{v} returning 0 for equality, a positive value for @var{u} > @var{v} and a negative for @var{u} < @var{v}. If both numbers are opaque values (cf, gcry_mpi_set_opaque) the comparison is done by checking the bit sizes using memcmp. If only one number is an opaque value, the opaque value is less than the other number. @end deftypefun @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}}) Compare the multi-precision-integers number @var{u} with the unsigned integer @var{v} returning 0 for equality, a positive value for @var{u} > @var{v} and a negative for @var{u} < @var{v}. @end deftypefun @deftypefun int gcry_mpi_is_neg (@w{const gcry_mpi_t @var{a}}) Return 1 if @var{a} is less than zero; return 0 if zero or positive. @end deftypefun @node Bit manipulations @section Bit manipulations @noindent There are a couple of functions to get information on arbitrary bits in an MPI and to set or clear them: @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}}) Return the number of bits required to represent @var{a}. @end deftypefun @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Return true if bit number @var{n} (counting from 0) is set in @var{a}. @end deftypefun @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Set bit number @var{n} in @var{a}. @end deftypefun @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Clear bit number @var{n} in @var{a}. @end deftypefun @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}. @end deftypefun @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Clear bit number @var{n} in @var{a} and all bits greater than @var{n}. @end deftypefun @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Shift the value of @var{a} by @var{n} bits to the right and store the result in @var{x}. @end deftypefun @deftypefun void gcry_mpi_lshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}}) Shift the value of @var{a} by @var{n} bits to the left and store the result in @var{x}. @end deftypefun @node EC functions @section EC functions @noindent Libgcrypt provides an API to access low level functions used by its elliptic curve implementation. These functions allow to implement elliptic curve methods for which no explicit support is available. @deftypefun gcry_mpi_point_t gcry_mpi_point_new (@w{unsigned int @var{nbits}}) Allocate a new point object, initialize it to 0, and allocate enough memory for a points of at least @var{nbits}. This pre-allocation yields only a small performance win and is not really necessary because Libgcrypt automatically re-allocates the required memory. Using 0 for @var{nbits} is usually the right thing to do. @end deftypefun @deftypefun void gcry_mpi_point_release (@w{gcry_mpi_point_t @var{point}}) Release @var{point} and free all associated resources. Passing @code{NULL} is allowed and ignored. @end deftypefun @deftypefun void gcry_mpi_point_get (@w{gcry_mpi_t @var{x}}, @ @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @ @w{gcry_mpi_point_t @var{point}}) Store the projective coordinates from @var{point} into the MPIs @var{x}, @var{y}, and @var{z}. If a coordinate is not required, @code{NULL} may be used for @var{x}, @var{y}, or @var{z}. @end deftypefun @deftypefun void gcry_mpi_point_snatch_get (@w{gcry_mpi_t @var{x}}, @ @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @ @w{gcry_mpi_point_t @var{point}}) Store the projective coordinates from @var{point} into the MPIs @var{x}, @var{y}, and @var{z}. If a coordinate is not required, @code{NULL} may be used for @var{x}, @var{y}, or @var{z}. The object @var{point} is then released. Using this function instead of @code{gcry_mpi_point_get} and @code{gcry_mpi_point_release} has the advantage of avoiding some extra memory allocations and copies. @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_point_set ( @ @w{gcry_mpi_point_t @var{point}}, @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}) Store the projective coordinates from @var{x}, @var{y}, and @var{z} into @var{point}. If a coordinate is given as @code{NULL}, the value 0 is used. If @code{NULL} is used for @var{point} a new point object is allocated and returned. Returns @var{point} or the newly allocated point object. @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_point_snatch_set ( @ @w{gcry_mpi_point_t @var{point}}, @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}) Store the projective coordinates from @var{x}, @var{y}, and @var{z} into @var{point}. If a coordinate is given as @code{NULL}, the value 0 is used. If @code{NULL} is used for @var{point} a new point object is allocated and returned. The MPIs @var{x}, @var{y}, and @var{z} are released. Using this function instead of @code{gcry_mpi_point_set} and 3 calls to @code{gcry_mpi_release} has the advantage of avoiding some extra memory allocations and copies. Returns @var{point} or the newly allocated point object. @end deftypefun @anchor{gcry_mpi_ec_new} @deftypefun gpg_error_t gcry_mpi_ec_p_new (@w{gpg_ctx_t *@var{r_ctx}}, @ @w{gcry_sexp_t @var{keyparam}}, @w{const char *@var{curvename}}) Allocate a new context for elliptic curve operations. If @var{keyparam} is given it specifies the parameters of the curve (@pxref{ecc_keyparam}). If @var{curvename} is given in addition to @var{keyparam} and the key parameters do not include a named curve reference, the string @var{curvename} is used to fill in missing parameters. If only @var{curvename} is given, the context is initialized for this named curve. If a parameter specifying a point (e.g. @code{g} or @code{q}) is not found, the parser looks for a non-encoded point by appending @code{.x}, @code{.y}, and @code{.z} to the parameter name and looking them all up to create a point. A parameter with the suffix @code{.z} is optional and defaults to 1. On success the function returns 0 and stores the new context object at @var{r_ctx}; this object eventually needs to be released (@pxref{gcry_ctx_release}). On error the function stores @code{NULL} at @var{r_ctx} and returns an error code. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_ec_get_mpi ( @ @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}}) Return the MPI with @var{name} from the context @var{ctx}. If not found @code{NULL} is returned. If the returned MPI may later be modified, it is suggested to pass @code{1} to @var{copy}, so that the function guarantees that a modifiable copy of the MPI is returned. If @code{0} is used for @var{copy}, this function may return a constant flagged MPI. In any case @code{gcry_mpi_release} needs to be called to release the result. For valid names @ref{ecc_keyparam}. If the public key @code{q} is requested but only the private key @code{d} is available, @code{q} will be recomputed on the fly. If a point parameter is requested it is returned as an uncompressed encoded point unless these special names are used: @table @var @item q@@eddsa Return an EdDSA style compressed point. This is only supported for Twisted Edwards curves. @end table @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_ec_get_point ( @ @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}}) Return the point with @var{name} from the context @var{ctx}. If not found @code{NULL} is returned. If the returned MPI may later be modified, it is suggested to pass @code{1} to @var{copy}, so that the function guarantees that a modifiable copy of the MPI is returned. If @code{0} is used for @var{copy}, this function may return a constant flagged point. In any case @code{gcry_mpi_point_release} needs to be called to release the result. If the public key @code{q} is requested but only the private key @code{d} is available, @code{q} will be recomputed on the fly. @end deftypefun @deftypefun gpg_error_t gcry_mpi_ec_set_mpi ( @ @w{const char *@var{name}}, @w{gcry_mpi_t @var{newvalue}}, @ @w{gcry_ctx_t @var{ctx}}) Store the MPI @var{newvalue} at @var{name} into the context @var{ctx}. On success @code{0} is returned; on error an error code. Valid names are the MPI parameters of an elliptic curve (@pxref{ecc_keyparam}). @end deftypefun @deftypefun gpg_error_t gcry_mpi_ec_set_point ( @ @w{const char *@var{name}}, @w{gcry_mpi_point_t @var{newvalue}}, @ @w{gcry_ctx_t @var{ctx}}) Store the point @var{newvalue} at @var{name} into the context @var{ctx}. On success @code{0} is returned; on error an error code. Valid names are the point parameters of an elliptic curve (@pxref{ecc_keyparam}). @end deftypefun @deftypefun int gcry_mpi_ec_get_affine ( @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @ @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}}) Compute the affine coordinates from the projective coordinates in @var{point} and store them into @var{x} and @var{y}. If one coordinate is not required, @code{NULL} may be passed to @var{x} or @var{y}. @var{ctx} is the context object which has been created using @code{gcry_mpi_ec_new}. Returns 0 on success or not 0 if @var{point} is at infinity. Note that you can use @code{gcry_mpi_ec_set_point} with the value @code{GCRYMPI_CONST_ONE} for @var{z} to convert affine coordinates back into projective coordinates. @end deftypefun @deftypefun void gcry_mpi_ec_dup ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @ @w{gcry_ctx_t @var{ctx}}) Double the point @var{u} of the elliptic curve described by @var{ctx} and store the result into @var{w}. @end deftypefun @deftypefun void gcry_mpi_ec_add ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @ @w{gcry_mpi_point_t @var{v}}, @w{gcry_ctx_t @var{ctx}}) Add the points @var{u} and @var{v} of the elliptic curve described by @var{ctx} and store the result into @var{w}. @end deftypefun @deftypefun void gcry_mpi_ec_mul ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_t @var{n}}, @ @w{gcry_mpi_point_t @var{u}}, @w{gcry_ctx_t @var{ctx}}) Multiply the point @var{u} of the elliptic curve described by @var{ctx} by @var{n} and store the result into @var{w}. @end deftypefun @deftypefun int gcry_mpi_ec_curve_point ( @ @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}}) Return true if @var{point} is on the elliptic curve described by @var{ctx}. @end deftypefun @node Miscellaneous @section Miscellaneous An MPI data type is allowed to be ``misused'' to store an arbitrary value. Two functions implement this kludge: @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}}) Store @var{nbits} of the value @var{p} points to in @var{a} and mark @var{a} as an opaque value (i.e. an value that can't be used for any math calculation and is only used to store an arbitrary bit pattern in @var{a}). Ownership of @var{p} is taken by this function and thus the user may not use dereference the passed value anymore. It is required that them memory referenced by @var{p} has been allocated in a way that @code{gcry_free} is able to release it. WARNING: Never use an opaque MPI for actual math operations. The only valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use gcry_mpi_scan to convert a string of arbitrary bytes into an MPI. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_set_opaque_copy (@w{gcry_mpi_t @var{a}}, @w{const void *@var{p}}, @w{unsigned int @var{nbits}}) Same as @code{gcry_mpi_set_opaque} but ownership of @var{p} is not taken instead a copy of @var{p} is used. @end deftypefun @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}}) Return a pointer to an opaque value stored in @var{a} and return its size in @var{nbits}. Note that the returned pointer is still owned by @var{a} and that the function should never be used for an non-opaque MPI. @end deftypefun Each MPI has an associated set of flags for special purposes. The currently defined flags are: @table @code @item GCRYMPI_FLAG_SECURE Setting this flag converts @var{a} into an MPI stored in "secure memory". Clearing this flag is not allowed. @item GCRYMPI_FLAG_OPAQUE This is an interanl flag, indicating the an opaque valuue and not an integer is stored. This is an read-only flag; it may not be set or cleared. @item GCRYMPI_FLAG_IMMUTABLE If this flag is set, the MPI is marked as immutable. Setting or changing the value of that MPI is ignored and an error message is logged. The flag is sometimes useful for debugging. @item GCRYMPI_FLAG_CONST If this flag is set, the MPI is marked as a constant and as immutable Setting or changing the value of that MPI is ignored and an error message is logged. Such an MPI will never be deallocated and may thus be used without copying. Note that using gcry_mpi_copy will return a copy of that constant with this and the immutable flag cleared. A few commonly used constants are pre-defined and accessible using the macros @code{GCRYMPI_CONST_ONE}, @code{GCRYMPI_CONST_TWO}, @code{GCRYMPI_CONST_THREE}, @code{GCRYMPI_CONST_FOUR}, and @code{GCRYMPI_CONST_EIGHT}. @item GCRYMPI_FLAG_USER1 @itemx GCRYMPI_FLAG_USER2 @itemx GCRYMPI_FLAG_USER3 @itemx GCRYMPI_FLAG_USER4 These flags are reserved for use by the application. @end table @deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @ @w{enum gcry_mpi_flag @var{flag}}) Set the @var{flag} for the MPI @var{a}. The only allowed flags are @code{GCRYMPI_FLAG_SECURE}, @code{GCRYMPI_FLAG_IMMUTABLE}, and @code{GCRYMPI_FLAG_CONST}. @end deftypefun @deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @ @w{enum gcry_mpi_flag @var{flag}}) Clear @var{flag} for the multi-precision-integers @var{a}. The only allowed flag is @code{GCRYMPI_FLAG_IMMUTABLE} but only if @code{GCRYMPI_FLAG_CONST} is not set. If @code{GCRYMPI_FLAG_CONST} is set, clearing @code{GCRYMPI_FLAG_IMMUTABLE} will simply be ignored. @end deftypefun o @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @ @w{enum gcry_mpi_flag @var{flag}}) Return true if @var{flag} is set for @var{a}. @end deftypefun To put a random value into an MPI, the following convenience function may be used: @deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}}) Set the multi-precision-integers @var{w} to a random non-negative number of @var{nbits}, using random data quality of level @var{level}. In case @var{nbits} is not a multiple of a byte, @var{nbits} is rounded up to the next byte boundary. When using a @var{level} of @code{GCRY_WEAK_RANDOM} this function makes use of @code{gcry_create_nonce}. @end deftypefun @c ********************************************************** @c ******************** Prime numbers *********************** @c ********************************************************** @node Prime numbers @chapter Prime numbers @menu * Generation:: Generation of new prime numbers. * Checking:: Checking if a given number is prime. @end menu @node Generation @section Generation @deftypefun gcry_error_t gcry_prime_generate (gcry_mpi_t *@var{prime},unsigned int @var{prime_bits}, unsigned int @var{factor_bits}, gcry_mpi_t **@var{factors}, gcry_prime_check_func_t @var{cb_func}, void *@var{cb_arg}, gcry_random_level_t @var{random_level}, unsigned int @var{flags}) Generate a new prime number of @var{prime_bits} bits and store it in @var{prime}. If @var{factor_bits} is non-zero, one of the prime factors of (@var{prime} - 1) / 2 must be @var{factor_bits} bits long. If @var{factors} is non-zero, allocate a new, @code{NULL}-terminated array holding the prime factors and store it in @var{factors}. @var{flags} might be used to influence the prime number generation process. @end deftypefun @deftypefun gcry_error_t gcry_prime_group_generator (gcry_mpi_t *@var{r_g}, gcry_mpi_t @var{prime}, gcry_mpi_t *@var{factors}, gcry_mpi_t @var{start_g}) Find a generator for @var{prime} where the factorization of (@var{prime}-1) is in the @code{NULL} terminated array @var{factors}. Return the generator as a newly allocated MPI in @var{r_g}. If @var{start_g} is not NULL, use this as the start for the search. @end deftypefun @deftypefun void gcry_prime_release_factors (gcry_mpi_t *@var{factors}) Convenience function to release the @var{factors} array. @end deftypefun @node Checking @section Checking @deftypefun gcry_error_t gcry_prime_check (gcry_mpi_t @var{p}, unsigned int @var{flags}) Check whether the number @var{p} is prime. Returns zero in case @var{p} is indeed a prime, returns @code{GPG_ERR_NO_PRIME} in case @var{p} is not a prime and a different error code in case something went horribly wrong. @end deftypefun @c ********************************************************** @c ******************** Utilities *************************** @c ********************************************************** @node Utilities @chapter Utilities @menu * Memory allocation:: Functions related with memory allocation. * Context management:: Functions related with context management. * Buffer description:: A data type to describe buffers. @end menu @node Memory allocation @section Memory allocation @deftypefun {void *} gcry_malloc (size_t @var{n}) This function tries to allocate @var{n} bytes of memory. On success it returns a pointer to the memory area, in an out-of-core condition, it returns NULL. @end deftypefun @deftypefun {void *} gcry_malloc_secure (size_t @var{n}) Like @code{gcry_malloc}, but uses secure memory. @end deftypefun @deftypefun {void *} gcry_calloc (size_t @var{n}, size_t @var{m}) This function allocates a cleared block of memory (i.e. initialized with zero bytes) long enough to contain a vector of @var{n} elements, each of size @var{m} bytes. On success it returns a pointer to the memory block; in an out-of-core condition, it returns NULL. @end deftypefun @deftypefun {void *} gcry_calloc_secure (size_t @var{n}, size_t @var{m}) Like @code{gcry_calloc}, but uses secure memory. @end deftypefun @deftypefun {void *} gcry_realloc (void *@var{p}, size_t @var{n}) This function tries to resize the memory area pointed to by @var{p} to @var{n} bytes. On success it returns a pointer to the new memory area, in an out-of-core condition, it returns NULL. Depending on whether the memory pointed to by @var{p} is secure memory or not, gcry_realloc tries to use secure memory as well. @end deftypefun @deftypefun void gcry_free (void *@var{p}) Release the memory area pointed to by @var{p}. @end deftypefun @node Context management @section Context management Some function make use of a context object. As of now there are only a few math functions. However, future versions of Libgcrypt may make more use of this context object. @deftp {Data type} {gcry_ctx_t} This type is used to refer to the general purpose context object. @end deftp @anchor{gcry_ctx_release} @deftypefun void gcry_ctx_release (gcry_ctx_t @var{ctx}) Release the context object @var{ctx} and all associated resources. A @code{NULL} passed as @var{ctx} is ignored. @end deftypefun @node Buffer description @section Buffer description To help hashing non-contiguous areas of memory a general purpose data type is defined: @deftp {Data type} {gcry_buffer_t} This type is a structure to describe a buffer. The user should make sure that this structure is initialized to zero. The available fields of this structure are: @table @code @item .size This is either 0 for no information available or indicates the allocated length of the buffer. @item .off This is the offset into the buffer. @item .len This is the valid length of the buffer starting at @code{.off}. @item .data This is the address of the buffer. @end table @end deftp @c ********************************************************** @c ********************* Tools **************************** @c ********************************************************** @node Tools @chapter Tools @menu * hmac256:: A standalone HMAC-SHA-256 implementation @end menu @manpage hmac256.1 @node hmac256 @section A HMAC-SHA-256 tool @ifset manverb .B hmac256 \- Compute an HMAC-SHA-256 MAC @end ifset @mansect synopsis @ifset manverb .B hmac256 .RB [ \-\-binary ] .I key .I [FILENAME] @end ifset @mansect description This is a standalone HMAC-SHA-256 implementation used to compute an HMAC-SHA-256 message authentication code. The tool has originally been developed as a second implementation for Libgcrypt to allow comparing against the primary implementation and to be used for internal consistency checks. It should not be used for sensitive data because no mechanisms to clear the stack etc are used. The code has been written in a highly portable manner and requires only a few standard definitions to be provided in a config.h file. @noindent @command{hmac256} is commonly invoked as @example hmac256 "This is my key" foo.txt @end example @noindent This compute the MAC on the file @file{foo.txt} using the key given on the command line. @mansect options @noindent @command{hmac256} understands these options: @table @gnupgtabopt @item --binary Print the MAC as a binary string. The default is to print the MAC encoded has lower case hex digits. @item --version Print version of the program and exit. @end table @mansect see also @ifset isman @command{sha256sum}(1) @end ifset @manpause @c ********************************************************** @c ***************** Architecure Overview ***************** @c ********************************************************** @node Architecture @chapter Architecture This chapter describes the internal architecture of Libgcrypt. Libgcrypt is a function library written in ISO C-90. Any compliant compiler should be able to build Libgcrypt as long as the target is either a POSIX platform or compatible to the API used by Windows NT. Provisions have been take so that the library can be directly used from C++ applications; however building with a C++ compiler is not supported. Building Libgcrypt is done by using the common @code{./configure && make} approach. The configure command is included in the source distribution and as a portable shell script it works on any Unix-alike system. The result of running the configure script are a C header file (@file{config.h}), customized Makefiles, the setup of symbolic links and a few other things. After that the make tool builds and optionally installs the library and the documentation. See the files @file{INSTALL} and @file{README} in the source distribution on how to do this. Libgcrypt is developed using a Subversion@footnote{A version control system available for many platforms} repository. Although all released versions are tagged in this repository, they should not be used to build production versions of Libgcrypt. Instead released tarballs should be used. These tarballs are available from several places with the master copy at @indicateurl{ftp://ftp.gnupg.org/gcrypt/libgcrypt/}. Announcements of new releases are posted to the @indicateurl{gnupg-announce@@gnupg.org} mailing list@footnote{See @url{http://www.gnupg.org/documentation/mailing-lists.en.html} for details.}. @float Figure,fig:subsystems @caption{Libgcrypt subsystems} @center @image{libgcrypt-modules, 150mm,,Libgcrypt subsystems} @end float Libgcrypt consists of several subsystems (@pxref{fig:subsystems}) and all these subsystems provide a public API; this includes the helper subsystems like the one for S-expressions. The API style depends on the subsystem; in general an open-use-close approach is implemented. The open returns a handle to a context used for all further operations on this handle, several functions may then be used on this handle and a final close function releases all resources associated with the handle. @menu * Public-Key Subsystem Architecture:: About public keys. * Symmetric Encryption Subsystem Architecture:: About standard ciphers. * Hashing and MACing Subsystem Architecture:: About hashing. * Multi-Precision-Integer Subsystem Architecture:: About big integers. * Prime-Number-Generator Subsystem Architecture:: About prime numbers. * Random-Number Subsystem Architecture:: About random stuff. @c * Helper Subsystems Architecture:: About other stuff. @end menu @node Public-Key Subsystem Architecture @section Public-Key Architecture Because public key cryptography is almost always used to process small amounts of data (hash values or session keys), the interface is not implemented using the open-use-close paradigm, but with single self-contained functions. Due to the wide variety of parameters required by different algorithms S-expressions, as flexible way to convey these parameters, are used. There is a set of helper functions to work with these S-expressions. @c see @xref{S-expression Subsystem Architecture}. Aside of functions to register new algorithms, map algorithms names to algorithms identifiers and to lookup properties of a key, the following main functions are available: @table @code @item gcry_pk_encrypt Encrypt data using a public key. @item gcry_pk_decrypt Decrypt data using a private key. @item gcry_pk_sign Sign data using a private key. @item gcry_pk_verify Verify that a signature matches the data. @item gcry_pk_testkey Perform a consistency over a public or private key. @item gcry_pk_genkey Create a new public/private key pair. @end table All these functions lookup the module implementing the algorithm and pass the actual work to that module. The parsing of the S-expression input and the construction of S-expression for the return values is done by the high level code (@file{cipher/pubkey.c}). Thus the internal interface between the algorithm modules and the high level functions passes data in a custom format. By default Libgcrypt uses a blinding technique for RSA decryption to mitigate real world timing attacks over a network: Instead of using the RSA decryption directly, a blinded value @math{y = x r^{e} \bmod n} is decrypted and the unblinded value @math{x' = y' r^{-1} \bmod n} returned. The blinding value @math{r} is a random value with the size of the modulus @math{n} and generated with @code{GCRY_WEAK_RANDOM} random level. @cindex X9.31 @cindex FIPS 186 The algorithm used for RSA and DSA key generation depends on whether Libgcrypt is operated in standard or in FIPS mode. In standard mode an algorithm based on the Lim-Lee prime number generator is used. In FIPS mode RSA keys are generated as specified in ANSI X9.31 (1998) and DSA keys as specified in FIPS 186-2. @node Symmetric Encryption Subsystem Architecture @section Symmetric Encryption Subsystem Architecture The interface to work with symmetric encryption algorithms is made up of functions from the @code{gcry_cipher_} name space. The implementation follows the open-use-close paradigm and uses registered algorithm modules for the actual work. Unless a module implements optimized cipher mode implementations, the high level code (@file{cipher/cipher.c}) implements the modes and calls the core algorithm functions to process each block. The most important functions are: @table @code @item gcry_cipher_open Create a new instance to encrypt or decrypt using a specified algorithm and mode. @item gcry_cipher_close Release an instance. @item gcry_cipher_setkey Set a key to be used for encryption or decryption. @item gcry_cipher_setiv Set an initialization vector to be used for encryption or decryption. @item gcry_cipher_encrypt @itemx gcry_cipher_decrypt Encrypt or decrypt data. These functions may be called with arbitrary amounts of data and as often as needed to encrypt or decrypt all data. @end table There are also functions to query properties of algorithms or context, like block length, key length, map names or to enable features like padding methods. @node Hashing and MACing Subsystem Architecture @section Hashing and MACing Subsystem Architecture The interface to work with message digests and CRC algorithms is made up of functions from the @code{gcry_md_} name space. The implementation follows the open-use-close paradigm and uses registered algorithm modules for the actual work. Although CRC algorithms are not considered cryptographic hash algorithms, they share enough properties so that it makes sense to handle them in the same way. It is possible to use several algorithms at once with one context and thus compute them all on the same data. The most important functions are: @table @code @item gcry_md_open Create a new message digest instance and optionally enable one algorithm. A flag may be used to turn the message digest algorithm into a HMAC algorithm. @item gcry_md_enable Enable an additional algorithm for the instance. @item gcry_md_setkey Set the key for the MAC. @item gcry_md_write Pass more data for computing the message digest to an instance. @item gcry_md_putc Buffered version of @code{gcry_md_write} implemented as a macro. @item gcry_md_read Finalize the computation of the message digest or HMAC and return the result. @item gcry_md_close Release an instance @item gcry_md_hash_buffer Convenience function to directly compute a message digest over a memory buffer without the need to create an instance first. @end table There are also functions to query properties of algorithms or the instance, like enabled algorithms, digest length, map algorithm names. it is also possible to reset an instance or to copy the current state of an instance at any time. Debug functions to write the hashed data to files are available as well. @node Multi-Precision-Integer Subsystem Architecture @section Multi-Precision-Integer Subsystem Architecture The implementation of Libgcrypt's big integer computation code is based on an old release of GNU Multi-Precision Library (GMP). The decision not to use the GMP library directly was due to stalled development at that time and due to security requirements which could not be provided by the code in GMP. As GMP does, Libgcrypt provides high performance assembler implementations of low level code for several CPUS to gain much better performance than with a generic C implementation. @noindent Major features of Libgcrypt's multi-precision-integer code compared to GMP are: @itemize @item Avoidance of stack based allocations to allow protection against swapping out of sensitive data and for easy zeroing of sensitive intermediate results. @item Optional use of secure memory and tracking of its use so that results are also put into secure memory. @item MPIs are identified by a handle (implemented as a pointer) to give better control over allocations and to augment them with extra properties like opaque data. @item Removal of unnecessary code to reduce complexity. @item Functions specialized for public key cryptography. @end itemize @node Prime-Number-Generator Subsystem Architecture @section Prime-Number-Generator Subsystem Architecture Libgcrypt provides an interface to its prime number generator. These functions make use of the internal prime number generator which is required for the generation for public key key pairs. The plain prime checking function is exported as well. The generation of random prime numbers is based on the Lim and Lee algorithm to create practically save primes.@footnote{Chae Hoon Lim and Pil Joong Lee. A key recovery attack on discrete log-based schemes using a prime order subgroup. In Burton S. Kaliski Jr., editor, Advances in Cryptology: Crypto '97, pages 249­-263, Berlin / Heidelberg / New York, 1997. Springer-Verlag. Described on page 260.} This algorithm creates a pool of smaller primes, select a few of them to create candidate primes of the form @math{2 * p_0 * p_1 * ... * p_n + 1}, tests the candidate for primality and permutates the pool until a prime has been found. It is possible to clamp one of the small primes to a certain size to help DSA style algorithms. Because most of the small primes in the pool are not used for the resulting prime number, they are saved for later use (see @code{save_pool_prime} and @code{get_pool_prime} in @file{cipher/primegen.c}). The prime generator optionally supports the finding of an appropriate generator. @noindent The primality test works in three steps: @enumerate @item The standard sieve algorithm using the primes up to 4999 is used as a quick first check. @item A Fermat test filters out almost all non-primes. @item A 5 round Rabin-Miller test is finally used. The first round uses a witness of 2, whereas the next rounds use a random witness. @end enumerate To support the generation of RSA and DSA keys in FIPS mode according to X9.31 and FIPS 186-2, Libgcrypt implements two additional prime generation functions: @code{_gcry_derive_x931_prime} and @code{_gcry_generate_fips186_2_prime}. These functions are internal and not available through the public API. @node Random-Number Subsystem Architecture @section Random-Number Subsystem Architecture Libgcrypt provides 3 levels or random quality: The level @code{GCRY_VERY_STRONG_RANDOM} usually used for key generation, the level @code{GCRY_STRONG_RANDOM} for all other strong random requirements and the function @code{gcry_create_nonce} which is used for weaker usages like nonces. There is also a level @code{GCRY_WEAK_RANDOM} which in general maps to @code{GCRY_STRONG_RANDOM} except when used with the function @code{gcry_mpi_randomize}, where it randomizes an multi-precision-integer using the @code{gcry_create_nonce} function. @noindent There are two distinct random generators available: @itemize @item The Continuously Seeded Pseudo Random Number Generator (CSPRNG), which is based on the classic GnuPG derived big pool implementation. Implemented in @code{random/random-csprng.c} and used by default. @item A FIPS approved ANSI X9.31 PRNG using AES with a 128 bit key. Implemented in @code{random/random-fips.c} and used if Libgcrypt is in FIPS mode. @end itemize @noindent Both generators make use of so-called entropy gathering modules: @table @asis @item rndlinux Uses the operating system provided @file{/dev/random} and @file{/dev/urandom} devices. @item rndunix Runs several operating system commands to collect entropy from sources like virtual machine and process statistics. It is a kind of poor-man's @code{/dev/random} implementation. It is not available in FIPS mode. @item rndegd Uses the operating system provided Entropy Gathering Daemon (EGD). The EGD basically uses the same algorithms as rndunix does. However as a system daemon it keeps on running and thus can serve several processes requiring entropy input and does not waste collected entropy if the application does not need all the collected entropy. It is not available in FIPS mode. @item rndw32 Targeted for the Microsoft Windows OS. It uses certain properties of that system and is the only gathering module available for that OS. @item rndhw Extra module to collect additional entropy by utilizing a hardware random number generator. As of now the only supported hardware RNG is the Padlock engine of VIA (Centaur) CPUs. It is not available in FIPS mode. @end table @menu * CSPRNG Description:: Description of the CSPRNG. * FIPS PRNG Description:: Description of the FIPS X9.31 PRNG. @end menu @node CSPRNG Description @subsection Description of the CSPRNG This random number generator is loosely modelled after the one described in Peter Gutmann's paper: "Software Generation of Practically Strong Random Numbers".@footnote{Also described in chapter 6 of his book "Cryptographic Security Architecture", New York, 2004, ISBN 0-387-95387-6.} A pool of 600 bytes is used and mixed using the core RIPE-MD160 hash transform function. Several extra features are used to make the robust against a wide variety of attacks and to protect against failures of subsystems. The state of the generator may be saved to a file and initially seed form a file. Depending on how Libgcrypt was build the generator is able to select the best working entropy gathering module. It makes use of the slow and fast collection methods and requires the pool to initially seeded form the slow gatherer or a seed file. An entropy estimation is used to mix in enough data from the gather modules before returning the actual random output. Process fork detection and protection is implemented. @c FIXME: The design and implementaion needs a more verbose description. The implementation of the nonce generator (for @code{gcry_create_nonce}) is a straightforward repeated hash design: A 28 byte buffer is initially seeded with the PID and the time in seconds in the first 20 bytes and with 8 bytes of random taken from the @code{GCRY_STRONG_RANDOM} generator. Random numbers are then created by hashing all the 28 bytes with SHA-1 and saving that again in the first 20 bytes. The hash is also returned as result. @node FIPS PRNG Description @subsection Description of the FIPS X9.31 PRNG The core of this deterministic random number generator is implemented according to the document ``NIST-Recommended Random Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms'', dated 2005-01-31. This implementation uses the AES variant. The generator is based on contexts to utilize the same core functions for all random levels as required by the high-level interface. All random generators return their data in 128 bit blocks. If the caller requests less bits, the extra bits are not used. The key for each generator is only set once at the first time a generator context is used. The seed value is set along with the key and again after 1000 output blocks. On Unix like systems the @code{GCRY_VERY_STRONG_RANDOM} and @code{GCRY_STRONG_RANDOM} generators are keyed and seeded using the rndlinux module with the @file{/dev/random} device. Thus these generators may block until the OS kernel has collected enough entropy. When used with Microsoft Windows the rndw32 module is used instead. The generator used for @code{gcry_create_nonce} is keyed and seeded from the @code{GCRY_STRONG_RANDOM} generator. Thus is may also block if the @code{GCRY_STRONG_RANDOM} generator has not yet been used before and thus gets initialized on the first use by @code{gcry_create_nonce}. This special treatment is justified by the weaker requirements for a nonce generator and to save precious kernel entropy for use by the ``real'' random generators. A self-test facility uses a separate context to check the functionality of the core X9.31 functions using a known answers test. During runtime each output block is compared to the previous one to detect a stuck generator. The DT value for the generator is made up of the current time down to microseconds (if available) and a free running 64 bit counter. When used with the test context the DT value is taken from the context and incremented on each use. @c @node Helper Subsystems Architecture @c @section Helper Subsystems Architecture @c @c There are a few smaller subsystems which are mainly used internally by @c Libgcrypt but also available to applications. @c @c @menu @c * S-expression Subsystem Architecture:: Details about the S-expression architecture. @c * Memory Subsystem Architecture:: Details about the memory allocation architecture. @c * Miscellaneous Subsystems Architecture:: Details about other subsystems. @c @end menu @c @c @node S-expression Subsystem Architecture @c @subsection S-expression Subsystem Architecture @c @c Libgcrypt provides an interface to S-expression to create and parse @c them. To use an S-expression with Libgcrypt it needs first be @c converted into the internal representation used by Libgcrypt (the type @c @code{gcry_sexp_t}). The conversion functions support a large subset @c of the S-expression specification and further feature a printf like @c function to convert a list of big integers or other binary data into @c an S-expression. @c @c Libgcrypt currently implements S-expressions using a tagged linked @c list. However this is not exposed to an application and may be @c changed in future releases to reduce overhead when already working @c with canonically encoded S-expressions. Secure memory is supported by @c this S-expressions implementation. @c @c @node Memory Subsystem Architecture @c @subsection Memory Subsystem Architecture @c @c TBD. @c @c @c @node Miscellaneous Subsystems Architecture @c @subsection Miscellaneous Subsystems Architecture @c @c TBD. @c @c @c ********************************************************** @c ******************* Appendices ************************* @c ********************************************************** @c ******************************************** @node Self-Tests @appendix Description of the Self-Tests In addition to the build time regression test suite, Libgcrypt implements self-tests to be performed at runtime. Which self-tests are actually used depends on the mode Libgcrypt is used in. In standard mode a limited set of self-tests is run at the time an algorithm is first used. Note that not all algorithms feature a self-test in standard mode. The @code{GCRYCTL_SELFTEST} control command may be used to run all implemented self-tests at any time; this will even run more tests than those run in FIPS mode. If any of the self-tests fails, the library immediately returns an error code to the caller. If Libgcrypt is in FIPS mode the self-tests will be performed within the ``Self-Test'' state and any failure puts the library into the ``Error'' state. @c -------------------------------- @section Power-Up Tests Power-up tests are only performed if Libgcrypt is in FIPS mode. @subsection Symmetric Cipher Algorithm Power-Up Tests The following symmetric encryption algorithm tests are run during power-up: @table @asis @item 3DES To test the 3DES 3-key EDE encryption in ECB mode these tests are run: @enumerate @item A known answer test is run on a 64 bit test vector processed by 64 rounds of Single-DES block encryption and decryption using a key changed with each round. @item A known answer test is run on a 64 bit test vector processed by 16 rounds of 2-key and 3-key Triple-DES block encryption and decryptions using a key changed with each round. @item 10 known answer tests using 3-key Triple-DES EDE encryption, comparing the ciphertext to the known value, then running a decryption and comparing it to the initial plaintext. @end enumerate (@code{cipher/des.c:selftest}) @item AES-128 A known answer tests is run using one test vector and one test key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_128}) @item AES-192 A known answer tests is run using one test vector and one test key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_192}) @item AES-256 A known answer tests is run using one test vector and one test key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_256}) @end table @subsection Hash Algorithm Power-Up Tests The following hash algorithm tests are run during power-up: @table @asis @item SHA-1 A known answer test using the string @code{"abc"} is run. (@code{cipher/@/sha1.c:@/selftests_sha1}) @item SHA-224 A known answer test using the string @code{"abc"} is run. (@code{cipher/@/sha256.c:@/selftests_sha224}) @item SHA-256 A known answer test using the string @code{"abc"} is run. (@code{cipher/@/sha256.c:@/selftests_sha256}) @item SHA-384 A known answer test using the string @code{"abc"} is run. (@code{cipher/@/sha512.c:@/selftests_sha384}) @item SHA-512 A known answer test using the string @code{"abc"} is run. (@code{cipher/@/sha512.c:@/selftests_sha512}) @end table @subsection MAC Algorithm Power-Up Tests The following MAC algorithm tests are run during power-up: @table @asis @item HMAC SHA-1 A known answer test using 9 byte of data and a 64 byte key is run. (@code{cipher/hmac-tests.c:selftests_sha1}) @item HMAC SHA-224 A known answer test using 28 byte of data and a 4 byte key is run. (@code{cipher/hmac-tests.c:selftests_sha224}) @item HMAC SHA-256 A known answer test using 28 byte of data and a 4 byte key is run. (@code{cipher/hmac-tests.c:selftests_sha256}) @item HMAC SHA-384 A known answer test using 28 byte of data and a 4 byte key is run. (@code{cipher/hmac-tests.c:selftests_sha384}) @item HMAC SHA-512 A known answer test using 28 byte of data and a 4 byte key is run. (@code{cipher/hmac-tests.c:selftests_sha512}) @end table @subsection Random Number Power-Up Test The DRNG is tested during power-up this way: @enumerate @item Requesting one block of random using the public interface to check general working and the duplicated block detection. @item 3 know answer tests using pre-defined keys, seed and initial DT values. For each test 3 blocks of 16 bytes are requested and compared to the expected result. The DT value is incremented for each block. @end enumerate @subsection Public Key Algorithm Power-Up Tests The public key algorithms are tested during power-up: @table @asis @item RSA A pre-defined 1024 bit RSA key is used and these tests are run in turn: @enumerate @item Conversion of S-expression to internal format. (@code{cipher/@/rsa.c:@/selftests_rsa}) @item Private key consistency check. (@code{cipher/@/rsa.c:@/selftests_rsa}) @item A pre-defined 20 byte value is signed with PKCS#1 padding for SHA-1. The result is verified using the public key against the original data and against modified data. (@code{cipher/@/rsa.c:@/selftest_sign_1024}) @item A 1000 bit random value is encrypted and checked that it does not match the original random value. The encrypted result is then decrypted and checked that it matches the original random value. (@code{cipher/@/rsa.c:@/selftest_encr_1024}) @end enumerate @item DSA A pre-defined 1024 bit DSA key is used and these tests are run in turn: @enumerate @item Conversion of S-expression to internal format. (@code{cipher/@/dsa.c:@/selftests_dsa}) @item Private key consistency check. (@code{cipher/@/dsa.c:@/selftests_dsa}) @item A pre-defined 20 byte value is signed with PKCS#1 padding for SHA-1. The result is verified using the public key against the original data and against modified data. (@code{cipher/@/dsa.c:@/selftest_sign_1024}) @end enumerate @end table @subsection Integrity Power-Up Tests The integrity of the Libgcrypt is tested during power-up but only if checking has been enabled at build time. The check works by computing a HMAC SHA-256 checksum over the file used to load Libgcrypt into memory. That checksum is compared against a checksum stored in a file of the same name but with a single dot as a prefix and a suffix of @file{.hmac}. @subsection Critical Functions Power-Up Tests The 3DES weak key detection is tested during power-up by calling the detection function with keys taken from a table listening all weak keys. The table itself is protected using a SHA-1 hash. (@code{cipher/@/des.c:@/selftest}) @c -------------------------------- @section Conditional Tests The conditional tests are performed if a certain condition is met. This may occur at any time; the library does not necessary enter the ``Self-Test'' state to run these tests but will transit to the ``Error'' state if a test failed. @subsection Key-Pair Generation Tests After an asymmetric key-pair has been generated, Libgcrypt runs a pair-wise consistency tests on the generated key. On failure the generated key is not used, an error code is returned and, if in FIPS mode, the library is put into the ``Error'' state. @table @asis @item RSA The test uses a random number 64 bits less the size of the modulus as plaintext and runs an encryption and decryption operation in turn. The encrypted value is checked to not match the plaintext and the result of the decryption is checked to match the plaintext. A new random number of the same size is generated, signed and verified to test the correctness of the signing operation. As a second signing test, the signature is modified by incrementing its value and then verified with the expected result that the verification fails. (@code{cipher/@/rsa.c:@/test_keys}) @item DSA The test uses a random number of the size of the Q parameter to create a signature and then checks that the signature verifies. As a second signing test, the data is modified by incrementing its value and then verified against the signature with the expected result that the verification fails. (@code{cipher/@/dsa.c:@/test_keys}) @end table @subsection Software Load Tests No code is loaded at runtime. @subsection Manual Key Entry Tests A manual key entry feature is not implemented in Libgcrypt. @subsection Continuous RNG Tests The continuous random number test is only used in FIPS mode. The RNG generates blocks of 128 bit size; the first block generated per context is saved in the context and another block is generated to be returned to the caller. Each block is compared against the saved block and then stored in the context. If a duplicated block is detected an error is signaled and the library is put into the ``Fatal-Error'' state. (@code{random/@/random-fips.c:@/x931_aes_driver}) @c -------------------------------- @section Application Requested Tests The application may requests tests at any time by means of the @code{GCRYCTL_SELFTEST} control command. Note that using these tests is not FIPS conform: Although Libgcrypt rejects all application requests for services while running self-tests, it does not ensure that no other operations of Libgcrypt are still being executed. Thus, in FIPS mode an application requesting self-tests needs to power-cycle Libgcrypt instead. When self-tests are requested, Libgcrypt runs all the tests it does during power-up as well as a few extra checks as described below. @subsection Symmetric Cipher Algorithm Tests The following symmetric encryption algorithm tests are run in addition to the power-up tests: @table @asis @item AES-128 A known answer tests with test vectors taken from NIST SP800-38a and using the high level functions is run for block modes CFB and OFB. @end table @subsection Hash Algorithm Tests The following hash algorithm tests are run in addition to the power-up tests: @table @asis @item SHA-1 @itemx SHA-224 @itemx SHA-256 @enumerate @item A known answer test using a 56 byte string is run. @item A known answer test using a string of one million letters "a" is run. @end enumerate (@code{cipher/@/sha1.c:@/selftests_sha1}, @code{cipher/@/sha256.c:@/selftests_sha224}, @code{cipher/@/sha256.c:@/selftests_sha256}) @item SHA-384 @item SHA-512 @enumerate @item A known answer test using a 112 byte string is run. @item A known answer test using a string of one million letters "a" is run. @end enumerate (@code{cipher/@/sha512.c:@/selftests_sha384}, @code{cipher/@/sha512.c:@/selftests_sha512}) @end table @subsection MAC Algorithm Tests The following MAC algorithm tests are run in addition to the power-up tests: @table @asis @item HMAC SHA-1 @enumerate @item A known answer test using 9 byte of data and a 20 byte key is run. @item A known answer test using 9 byte of data and a 100 byte key is run. @item A known answer test using 9 byte of data and a 49 byte key is run. @end enumerate (@code{cipher/hmac-tests.c:selftests_sha1}) @item HMAC SHA-224 @itemx HMAC SHA-256 @itemx HMAC SHA-384 @itemx HMAC SHA-512 @enumerate @item A known answer test using 9 byte of data and a 20 byte key is run. @item A known answer test using 50 byte of data and a 20 byte key is run. @item A known answer test using 50 byte of data and a 26 byte key is run. @item A known answer test using 54 byte of data and a 131 byte key is run. @item A known answer test using 152 byte of data and a 131 byte key is run. @end enumerate (@code{cipher/@/hmac-tests.c:@/selftests_sha224}, @code{cipher/@/hmac-tests.c:@/selftests_sha256}, @code{cipher/@/hmac-tests.c:@/selftests_sha384}, @code{cipher/@/hmac-tests.c:@/selftests_sha512}) @end table @c ******************************************** @node FIPS Mode @appendix Description of the FIPS Mode This appendix gives detailed information pertaining to the FIPS mode. In particular, the changes to the standard mode and the finite state machine are described. The self-tests required in this mode are described in the appendix on self-tests. @c ------------------------------- @section Restrictions in FIPS Mode @noindent If Libgcrypt is used in FIPS mode these restrictions are effective: @itemize @item The cryptographic algorithms are restricted to this list: @table @asis @item GCRY_CIPHER_3DES 3 key EDE Triple-DES symmetric encryption. @item GCRY_CIPHER_AES128 AES 128 bit symmetric encryption. @item GCRY_CIPHER_AES192 AES 192 bit symmetric encryption. @item GCRY_CIPHER_AES256 AES 256 bit symmetric encryption. @item GCRY_MD_SHA1 SHA-1 message digest. @item GCRY_MD_SHA224 SHA-224 message digest. @item GCRY_MD_SHA256 SHA-256 message digest. @item GCRY_MD_SHA384 SHA-384 message digest. @item GCRY_MD_SHA512 SHA-512 message digest. @item GCRY_MD_SHA1,GCRY_MD_FLAG_HMAC HMAC using a SHA-1 message digest. @item GCRY_MD_SHA224,GCRY_MD_FLAG_HMAC HMAC using a SHA-224 message digest. @item GCRY_MD_SHA256,GCRY_MD_FLAG_HMAC HMAC using a SHA-256 message digest. @item GCRY_MD_SHA384,GCRY_MD_FLAG_HMAC HMAC using a SHA-384 message digest. @item GCRY_MD_SHA512,GCRY_MD_FLAG_HMAC HMAC using a SHA-512 message digest. @item GCRY_PK_RSA RSA encryption and signing. @item GCRY_PK_DSA DSA signing. @end table Note that the CRC algorithms are not considered cryptographic algorithms and thus are in addition available. @item RSA key generation refuses to create a key with a keysize of less than 1024 bits. @item DSA key generation refuses to create a key with a keysize other than 1024 bits. @item The @code{transient-key} flag for RSA and DSA key generation is ignored. @item Support for the VIA Padlock engine is disabled. @item FIPS mode may only be used on systems with a /dev/random device. Switching into FIPS mode on other systems will fail at runtime. @item Saving and loading a random seed file is ignored. @item An X9.31 style random number generator is used in place of the large-pool-CSPRNG generator. @item The command @code{GCRYCTL_ENABLE_QUICK_RANDOM} is ignored. @item Message digest debugging is disabled. @item All debug output related to cryptographic data is suppressed. @item On-the-fly self-tests are not performed, instead self-tests are run before entering operational state. @item The function @code{gcry_set_allocation_handler} may not be used. If it is used Libgcrypt disables FIPS mode unless Enforced FIPS mode is enabled, in which case Libgcrypt will enter the error state. @item The digest algorithm MD5 may not be used. If it is used Libgcrypt disables FIPS mode unless Enforced FIPS mode is enabled, in which case Libgcrypt will enter the error state. @item In Enforced FIPS mode the command @code{GCRYCTL_DISABLE_SECMEM} is ignored. In standard FIPS mode it disables FIPS mode. @item A handler set by @code{gcry_set_outofcore_handler} is ignored. @item A handler set by @code{gcry_set_fatalerror_handler} is ignored. @end itemize Note that when we speak about disabling FIPS mode, it merely means that the function @code{gcry_fips_mode_active} returns false; it does not mean that any non FIPS algorithms are allowed. @c ******************************************** @section FIPS Finite State Machine The FIPS mode of libgcrypt implements a finite state machine (FSM) using 8 states (@pxref{tbl:fips-states}) and checks at runtime that only valid transitions (@pxref{tbl:fips-state-transitions}) may happen. @float Figure,fig:fips-fsm @caption{FIPS mode state diagram} @center @image{fips-fsm,150mm,,FIPS FSM Diagram} @end float @float Table,tbl:fips-states @caption{FIPS mode states} @noindent States used by the FIPS FSM: @table @asis @item Power-Off Libgcrypt is not runtime linked to another application. This usually means that the library is not loaded into main memory. This state is documentation only. @item Power-On Libgcrypt is loaded into memory and API calls may be made. Compiler introduced constructor functions may be run. Note that Libgcrypt does not implement any arbitrary constructor functions to be called by the operating system @item Init The Libgcrypt initialization functions are performed and the library has not yet run any self-test. @item Self-Test Libgcrypt is performing self-tests. @item Operational Libgcrypt is in the operational state and all interfaces may be used. @item Error Libgrypt is in the error state. When calling any FIPS relevant interfaces they either return an error (@code{GPG_ERR_NOT_OPERATIONAL}) or put Libgcrypt into the Fatal-Error state and won't return. @item Fatal-Error Libgcrypt is in a non-recoverable error state and will automatically transit into the Shutdown state. @item Shutdown Libgcrypt is about to be terminated and removed from the memory. The application may at this point still running cleanup handlers. @end table @end float @float Table,tbl:fips-state-transitions @caption{FIPS mode state transitions} @noindent The valid state transitions (@pxref{fig:fips-fsm}) are: @table @code @item 1 Power-Off to Power-On is implicitly done by the OS loading Libgcrypt as a shared library and having it linked to an application. @item 2 Power-On to Init is triggered by the application calling the Libgcrypt initialization function @code{gcry_check_version}. @item 3 Init to Self-Test is either triggered by a dedicated API call or implicit by invoking a libgrypt service controlled by the FSM. @item 4 Self-Test to Operational is triggered after all self-tests passed successfully. @item 5 Operational to Shutdown is an artificial state without any direct action in Libgcrypt. When reaching the Shutdown state the library is deinitialized and can't return to any other state again. @item 6 Shutdown to Power-off is the process of removing Libgcrypt from the computer's memory. For obvious reasons the Power-Off state can't be represented within Libgcrypt and thus this transition is for documentation only. @item 7 Operational to Error is triggered if Libgcrypt detected an application error which can't be returned to the caller but still allows Libgcrypt to properly run. In the Error state all FIPS relevant interfaces return an error code. @item 8 Error to Shutdown is similar to the Operational to Shutdown transition (5). @item 9 Error to Fatal-Error is triggered if Libgrypt detects an fatal error while already being in Error state. @item 10 Fatal-Error to Shutdown is automatically entered by Libgcrypt after having reported the error. @item 11 Power-On to Shutdown is an artificial state to document that Libgcrypt has not ye been initialized but the process is about to terminate. @item 12 Power-On to Fatal-Error will be triggered if certain Libgcrypt functions are used without having reached the Init state. @item 13 Self-Test to Fatal-Error is triggered by severe errors in Libgcrypt while running self-tests. @item 14 Self-Test to Error is triggered by a failed self-test. @item 15 Operational to Fatal-Error is triggered if Libcrypt encountered a non-recoverable error. @item 16 Operational to Self-Test is triggered if the application requested to run the self-tests again. @item 17 Error to Self-Test is triggered if the application has requested to run self-tests to get to get back into operational state after an error. @item 18 Init to Error is triggered by errors in the initialization code. @item 19 Init to Fatal-Error is triggered by non-recoverable errors in the initialization code. @item 20 Error to Error is triggered by errors while already in the Error state. @end table @end float @c ******************************************** @section FIPS Miscellaneous Information Libgcrypt does not do any key management on itself; the application needs to care about it. Keys which are passed to Libgcrypt should be allocated in secure memory as available with the functions @code{gcry_malloc_secure} and @code{gcry_calloc_secure}. By calling @code{gcry_free} on this memory, the memory and thus the keys are overwritten with zero bytes before releasing the memory. For use with the random number generator, Libgcrypt generates 3 internal keys which are stored in the encryption contexts used by the RNG. These keys are stored in secure memory for the lifetime of the process. Application are required to use @code{GCRYCTL_TERM_SECMEM} before process termination. This will zero out the entire secure memory and thus also the encryption contexts with these keys. @c ********************************************************** @c ************* Appendices (license etc.) **************** @c ********************************************************** @include lgpl.texi @include gpl.texi @node Figures and Tables @unnumbered List of Figures and Tables @listoffloats Figure @listoffloats Table @node Concept Index @unnumbered Concept Index @printindex cp @node Function and Data Index @unnumbered Function and Data Index @printindex fn @bye GCRYCTL_SET_RANDOM_DAEMON_SOCKET GCRYCTL_USE_RANDOM_DAEMON The random daemon is still a bit experimental, thus we do not document them. Note that they should be used during initialization and that these functions are not really thread safe. @c LocalWords: int HD diff --git a/random/random-csprng.c b/random/random-csprng.c index 87235d82..429c84f8 100644 --- a/random/random-csprng.c +++ b/random/random-csprng.c @@ -1,1327 +1,1322 @@ /* random-csprng.c - CSPRNG style random number generator (libgcrypt classic) * Copyright (C) 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2008, 2010, 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 random number generator is modelled after the one described in Peter Gutmann's 1998 Usenix Security Symposium paper: "Software Generation of Practically Strong Random Numbers". See also chapter 6 in his book "Cryptographic Security Architecture", New York, 2004, ISBN 0-387-95387-6. Note that the acronym CSPRNG stands for "Continuously Seeded PseudoRandom Number Generator" as used in Peter's implementation of the paper and not only for "Cryptographically Secure PseudoRandom Number Generator". */ #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_GETHRTIME #include #endif #ifdef HAVE_GETTIMEOFDAY #include #endif #ifdef HAVE_GETRUSAGE #include #endif #ifdef __MINGW32__ #include #endif #include "g10lib.h" #include "../cipher/rmd.h" #include "random.h" #include "rand-internal.h" #include "cipher.h" /* Required for the rmd160_hash_buffer() prototype. */ -#include "ath.h" #ifndef RAND_MAX /* For SunOS. */ #define RAND_MAX 32767 #endif /* Check whether we can lock the seed file read write. */ #if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE) && !defined(HAVE_W32_SYSTEM) #define LOCK_SEED_FILE 1 #else #define LOCK_SEED_FILE 0 #endif /* Define the constant we use for transforming the pool at read-out. */ #if SIZEOF_UNSIGNED_LONG == 8 #define ADD_VALUE 0xa5a5a5a5a5a5a5a5 #elif SIZEOF_UNSIGNED_LONG == 4 #define ADD_VALUE 0xa5a5a5a5 #else #error weird size for an unsigned long #endif /* Contstants pertaining to the hash pool. */ #define BLOCKLEN 64 /* Hash this amount of bytes... */ #define DIGESTLEN 20 /* ... into a digest of this length (rmd160). */ /* POOLBLOCKS is the number of digests which make up the pool. */ #define POOLBLOCKS 30 /* POOLSIZE must be a multiple of the digest length to make the AND operations faster, the size should also be a multiple of unsigned long. */ #define POOLSIZE (POOLBLOCKS*DIGESTLEN) #if (POOLSIZE % SIZEOF_UNSIGNED_LONG) #error Please make sure that poolsize is a multiple of unsigned long #endif #define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG) /* RNDPOOL is the pool we use to collect the entropy and to stir it up. Its allocated size is POOLSIZE+BLOCKLEN. Note that this is also an indication on whether the module has been fully initialized. */ static unsigned char *rndpool; /* KEYPOOL is used as a scratch copy to read out random from RNDPOOL. Its allocated size is also POOLSIZE+BLOCKLEN. */ static unsigned char *keypool; /* This is the offset into RNDPOOL where the next random bytes are to be mixed in. */ static size_t pool_writepos; /* When reading data out of KEYPOOL, we start the read at different positions. This variable keeps track on where to read next. */ static size_t pool_readpos; /* This flag is set to true as soon as the pool has been completely filled the first time. This may happen either by rereading a seed file or by adding enough entropy. */ static int pool_filled; /* This counter is used to track whether the initial seeding has been done with enough bytes from a reliable entropy source. */ static size_t pool_filled_counter; /* If random of level GCRY_VERY_STRONG_RANDOM has been requested we have stricter requirements on what kind of entropy is in the pool. In particular POOL_FILLED is not sufficient. Thus we add some extra seeding and set this flag to true if the extra seeding has been done. */ static int did_initial_extra_seeding; /* This variable is used to estimated the amount of fresh entropy available in RNDPOOL. */ static int pool_balance; /* After a mixing operation this variable will be set to true and cleared if new entropy has been added or a remix is required for other reasons. */ static int just_mixed; /* The name of the seed file or NULL if no seed file has been defined. The seed file needs to be regsitered at initialiation time. We keep a malloced copy here. */ static char *seed_file_name; /* If a seed file has been registered and maybe updated on exit this flag set. */ static int allow_seed_file_update; /* Option flag set at initialiation time to force allocation of the pool in secure memory. */ static int secure_alloc; /* This function pointer is set to the actual entropy gathering function during initialization. After initialization it is guaranteed to point to function. (On systems without a random gatherer module a dummy function is used).*/ static int (*slow_gather_fnc)(void (*)(const void*, size_t, enum random_origins), enum random_origins, size_t, int); /* This function is set to the actual fast entropy gathering function during initialization. If it is NULL, no such function is available. */ static void (*fast_gather_fnc)(void (*)(const void*, size_t, enum random_origins), enum random_origins); /* Option flag useful for debugging and the test suite. If set requests for very strong random are degraded to strong random. Not used by regular applications. */ static int quick_test; /* On systems without entropy gathering modules, this flag is set to indicate that the random generator is not working properly. A warning message is issued as well. This is useful only for debugging and during development. */ static int faked_rng; /* This is the lock we use to protect all pool operations. */ -static ath_mutex_t pool_lock; +GPGRT_LOCK_DEFINE (pool_lock); /* This is a helper for assert calls. These calls are used to assert that functions are called in a locked state. It is not meant to be thread-safe but as a method to get aware of missing locks in the test suite. */ static int pool_is_locked; /* We keep some counters in this structure for the sake of the _gcry_random_dump_stats () function. */ static struct { unsigned long mixrnd; unsigned long mixkey; unsigned long slowpolls; unsigned long fastpolls; unsigned long getbytes1; unsigned long ngetbytes1; unsigned long getbytes2; unsigned long ngetbytes2; unsigned long addbytes; unsigned long naddbytes; } rndstats; /* --- Stuff pertaining to the random daemon support. --- */ #ifdef USE_RANDOM_DAEMON /* If ALLOW_DAEMON is true, the module will try to use the random daemon first. If the daemon has failed, this variable is set to back to false and the code continues as normal. Note, we don't test this flag in a locked state because a wrong value does not harm and the trhead will find out itself that the daemon does not work and set it (again) to false. */ static int allow_daemon; /* During initialization, the user may set a non-default socket name for accessing the random daemon. If this value is NULL, the default name will be used. */ static char *daemon_socket_name; #endif /*USE_RANDOM_DAEMON*/ /* --- Prototypes --- */ static void read_pool (byte *buffer, size_t length, int level ); static void add_randomness (const void *buffer, size_t length, enum random_origins origin); static void random_poll (void); static void do_fast_random_poll (void); static int (*getfnc_gather_random (void))(void (*)(const void*, size_t, enum random_origins), enum random_origins, size_t, int); static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t, enum random_origins), enum random_origins); static void read_random_source (enum random_origins origin, size_t length, int level); static int gather_faked (void (*add)(const void*, size_t, enum random_origins), enum random_origins, size_t length, int level ); /* --- Functions --- */ /* Basic initialization which is required to initialize mutexes and such. It does not run a full initialization so that the filling of the random pool can be delayed until it is actually needed. We assume that this function is used before any concurrent access happens. */ static void initialize_basics(void) { static int initialized; - int err; if (!initialized) { initialized = 1; - err = ath_mutex_init (&pool_lock); - if (err) - log_fatal ("failed to create the pool lock: %s\n", strerror (err) ); #ifdef USE_RANDOM_DAEMON _gcry_daemon_initialize_basics (); #endif /*USE_RANDOM_DAEMON*/ /* 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); } } /* Take the pool lock. */ static void lock_pool (void) { int err; - err = ath_mutex_lock (&pool_lock); + err = gpgrt_lock_lock (&pool_lock); if (err) - log_fatal ("failed to acquire the pool lock: %s\n", strerror (err)); + log_fatal ("failed to acquire the pool lock: %s\n", gpg_strerror (err)); pool_is_locked = 1; } /* Release the pool lock. */ static void unlock_pool (void) { int err; pool_is_locked = 0; - err = ath_mutex_unlock (&pool_lock); + err = gpgrt_lock_unlock (&pool_lock); if (err) - log_fatal ("failed to release the pool lock: %s\n", strerror (err)); + log_fatal ("failed to release the pool lock: %s\n", gpg_strerror (err)); } /* Full initialization of this module. */ static void initialize(void) { /* Although the basic initialization should have happened already, we call it here to make sure that all prerequisites are met. */ initialize_basics (); /* Now we can look the pool and complete the initialization if necessary. */ lock_pool (); if (!rndpool) { /* The data buffer is allocated somewhat larger, so that we can use this extra space (which is allocated in secure memory) as a temporary hash buffer */ rndpool = (secure_alloc ? xcalloc_secure (1, POOLSIZE + BLOCKLEN) : xcalloc (1, POOLSIZE + BLOCKLEN)); keypool = (secure_alloc ? xcalloc_secure (1, POOLSIZE + BLOCKLEN) : xcalloc (1, POOLSIZE + BLOCKLEN)); /* Setup the slow entropy gathering function. The code requires that this function exists. */ slow_gather_fnc = getfnc_gather_random (); if (!slow_gather_fnc) { faked_rng = 1; slow_gather_fnc = gather_faked; } /* Setup the fast entropy gathering function. */ fast_gather_fnc = getfnc_fast_random_poll (); } unlock_pool (); } /* Initialize this random subsystem. If FULL is false, this function merely calls the initialize 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_rngcsprng_initialize (int full) { if (!full) initialize_basics (); else initialize (); } /* Try to close the FDs of the random gather module. This is currently only implemented for rndlinux. */ void _gcry_rngcsprng_close_fds (void) { lock_pool (); #if USE_RNDLINUX _gcry_rndlinux_gather_random (NULL, 0, 0, 0); pool_filled = 0; /* Force re-open on next use. */ #endif unlock_pool (); } void _gcry_rngcsprng_dump_stats (void) { /* In theory we would need to lock the stats here. However this function is usually called during cleanup and then we _might_ run into problems. */ log_info ("random usage: poolsize=%d mixed=%lu polls=%lu/%lu added=%lu/%lu\n" " outmix=%lu getlvl1=%lu/%lu getlvl2=%lu/%lu%s\n", POOLSIZE, rndstats.mixrnd, rndstats.slowpolls, rndstats.fastpolls, rndstats.naddbytes, rndstats.addbytes, rndstats.mixkey, rndstats.ngetbytes1, rndstats.getbytes1, rndstats.ngetbytes2, rndstats.getbytes2, _gcry_rndhw_failed_p()? " (hwrng failed)":""); } /* This function should be called during initialization and before initialization of this module to place the random pools into secure memory. */ void _gcry_rngcsprng_secure_alloc (void) { secure_alloc = 1; } /* 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_rngcsprng_enable_quick_gen (void) { quick_test = 1; } void _gcry_rngcsprng_set_daemon_socket (const char *socketname) { #ifdef USE_RANDOM_DAEMON if (daemon_socket_name) BUG (); daemon_socket_name = gcry_xstrdup (socketname); #else /*!USE_RANDOM_DAEMON*/ (void)socketname; #endif /*!USE_RANDOM_DAEMON*/ } /* 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_rngcsprng_use_daemon (int onoff) { #ifdef USE_RANDOM_DAEMON int last; /* This is not really thread safe. However it is expected that this function is being called during initialization and at that point we are for other reasons not really thread safe. We do not want to lock it because we might eventually decide that this function may even be called prior to gcry_check_version. */ last = allow_daemon; if (onoff != -1) allow_daemon = onoff; return last; #else /*!USE_RANDOM_DAEMON*/ (void)onoff; return 0; #endif /*!USE_RANDOM_DAEMON*/ } /* This function returns true if no real RNG is available or the quality of the RNG has been degraded for test purposes. */ int _gcry_rngcsprng_is_faked (void) { /* We need to initialize due to the runtime determination of available entropy gather modules. */ initialize(); return (faked_rng || quick_test); } /* 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_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality) { size_t nbytes; const char *bufptr; if (quality == -1) quality = 35; else if (quality > 100) quality = 100; else if (quality < 0) quality = 0; if (!buf) return gpg_error (GPG_ERR_INV_ARG); if (!buflen || quality < 10) return 0; /* Take a shortcut. */ /* Because we don't increment the entropy estimation with FASTPOLL, we don't need to take lock that estimation while adding from an external source. This limited entropy estimation also means that we can't take QUALITY into account. */ initialize_basics (); bufptr = buf; while (buflen) { nbytes = buflen > POOLSIZE? POOLSIZE : buflen; lock_pool (); if (rndpool) add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL); unlock_pool (); bufptr += nbytes; buflen -= nbytes; } return 0; } /* 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_rngcsprng_randomize (void *buffer, size_t length, enum gcry_random_level level) { unsigned char *p; /* Make sure we are initialized. */ initialize (); /* Handle our hack used for regression tests of Libgcrypt. */ if ( quick_test && level > GCRY_STRONG_RANDOM ) level = GCRY_STRONG_RANDOM; /* Make sure the level is okay. */ level &= 3; #ifdef USE_RANDOM_DAEMON if (allow_daemon && !_gcry_daemon_randomize (daemon_socket_name, buffer, length, level)) return; /* The daemon succeeded. */ allow_daemon = 0; /* Daemon failed - switch off. */ #endif /*USE_RANDOM_DAEMON*/ /* Acquire the pool lock. */ lock_pool (); /* Update the statistics. */ if (level >= GCRY_VERY_STRONG_RANDOM) { rndstats.getbytes2 += length; rndstats.ngetbytes2++; } else { rndstats.getbytes1 += length; rndstats.ngetbytes1++; } /* Read the random into the provided buffer. */ for (p = buffer; length > 0;) { size_t n; n = length > POOLSIZE? POOLSIZE : length; read_pool (p, n, level); length -= n; p += n; } /* Release the pool lock. */ unlock_pool (); } /* Mix the pool: |........blocks*20byte........|20byte|..44byte..| <..44byte..> <20byte> | | | +------+ +---------------------------|----------+ v v |........blocks*20byte........|20byte|..44byte..| <.....64bytes.....> | +----------------------------------+ Hash v |.............................|20byte|..44byte..| <20byte><20byte><..44byte..> | | | +---------------------+ +-----------------------------+ | v v |.............................|20byte|..44byte..| <.....64byte......> | +-------------------------+ Hash v |.............................|20byte|..44byte..| <20byte><20byte><..44byte..> and so on until we did this for all blocks. To better protect against implementation errors in this code, we xor a digest of the entire pool into the pool before mixing. Note: this function must only be called with a locked pool. */ static void mix_pool(unsigned char *pool) { static unsigned char failsafe_digest[DIGESTLEN]; static int failsafe_digest_valid; unsigned char *hashbuf = pool + POOLSIZE; unsigned char *p, *pend; int i, n; RMD160_CONTEXT md; #if DIGESTLEN != 20 #error must have a digest length of 20 for ripe-md-160 #endif gcry_assert (pool_is_locked); _gcry_rmd160_init( &md ); /* Loop over the pool. */ pend = pool + POOLSIZE; memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN ); memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN); _gcry_rmd160_mixblock( &md, hashbuf); memcpy(pool, hashbuf, 20 ); if (failsafe_digest_valid && pool == rndpool) { for (i=0; i < 20; i++) pool[i] ^= failsafe_digest[i]; } p = pool; for (n=1; n < POOLBLOCKS; n++) { memcpy (hashbuf, p, DIGESTLEN); p += DIGESTLEN; if (p+DIGESTLEN+BLOCKLEN < pend) memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN); else { unsigned char *pp = p + DIGESTLEN; for (i=DIGESTLEN; i < BLOCKLEN; i++ ) { if ( pp >= pend ) pp = pool; hashbuf[i] = *pp++; } } _gcry_rmd160_mixblock ( &md, hashbuf); memcpy(p, hashbuf, 20 ); } /* Our hash implementation does only leave small parts (64 bytes) of the pool on the stack, so it is okay not to require secure memory here. Before we use this pool, it will be copied to the help buffer anyway. */ if ( pool == rndpool) { _gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE); failsafe_digest_valid = 1; } _gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */ } void _gcry_rngcsprng_set_seed_file (const char *name) { if (seed_file_name) BUG (); seed_file_name = xstrdup (name); } /* Lock an open file identified by file descriptor FD and wait a reasonable time to succeed. With FOR_WRITE set to true a write lock will be taken. FNAME is used only for diagnostics. Returns 0 on success or -1 on error. */ static int lock_seed_file (int fd, const char *fname, int for_write) { #ifdef __GCC__ #warning Check whether we can lock on Windows. #endif #if LOCK_SEED_FILE struct flock lck; struct timeval tv; int backoff=0; /* We take a lock on the entire file. */ memset (&lck, 0, sizeof lck); lck.l_type = for_write? F_WRLCK : F_RDLCK; lck.l_whence = SEEK_SET; while (fcntl (fd, F_SETLK, &lck) == -1) { if (errno != EAGAIN && errno != EACCES) { log_info (_("can't lock `%s': %s\n"), fname, strerror (errno)); return -1; } if (backoff > 2) /* Show the first message after ~2.25 seconds. */ log_info( _("waiting for lock on `%s'...\n"), fname); tv.tv_sec = backoff; tv.tv_usec = 250000; select (0, NULL, NULL, NULL, &tv); if (backoff < 10) backoff++ ; } #endif /*!LOCK_SEED_FILE*/ return 0; } /* Read in a seed from the random_seed file and return true if this was successful. Note: Multiple instances of applications sharing the same random seed file can be started in parallel, in which case they will read out the same pool and then race for updating it (the last update overwrites earlier updates). They will differentiate only by the weak entropy that is added in read_seed_file based on the PID and clock, and up to 16 bytes of weak random non-blockingly. The consequence is that the output of these different instances is correlated to some extent. In the perfect scenario, the attacker can control (or at least guess) the PID and clock of the application, and drain the system's entropy pool to reduce the "up to 16 bytes" above to 0. Then the dependencies of the initial states of the pools are completely known. */ static int read_seed_file (void) { int fd; struct stat sb; unsigned char buffer[POOLSIZE]; int n; gcry_assert (pool_is_locked); if (!seed_file_name) return 0; #ifdef HAVE_DOSISH_SYSTEM fd = open( seed_file_name, O_RDONLY | O_BINARY ); #else fd = open( seed_file_name, O_RDONLY ); #endif if( fd == -1 && errno == ENOENT) { allow_seed_file_update = 1; return 0; } if (fd == -1 ) { log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) ); return 0; } if (lock_seed_file (fd, seed_file_name, 0)) { close (fd); return 0; } if (fstat( fd, &sb ) ) { log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) ); close(fd); return 0; } if (!S_ISREG(sb.st_mode) ) { log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name ); close(fd); return 0; } if (!sb.st_size ) { log_info(_("note: random_seed file is empty\n") ); close(fd); allow_seed_file_update = 1; return 0; } if (sb.st_size != POOLSIZE ) { log_info(_("warning: invalid size of random_seed file - not used\n") ); close(fd); return 0; } do { n = read( fd, buffer, POOLSIZE ); } while (n == -1 && errno == EINTR ); if (n != POOLSIZE) { log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) ); close(fd);/*NOTREACHED*/ return 0; } close(fd); add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT ); /* add some minor entropy to the pool now (this will also force a mixing) */ { pid_t x = getpid(); add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT ); } { time_t x = time(NULL); add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT ); } { clock_t x = clock(); add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT ); } /* And read a few bytes from our entropy source. By using a level * of 0 this will not block and might not return anything with some * entropy drivers, however the rndlinux driver will use * /dev/urandom and return some stuff - Do not read too much as we * want to be friendly to the scare system entropy resource. */ read_random_source ( RANDOM_ORIGIN_INIT, 16, GCRY_WEAK_RANDOM ); allow_seed_file_update = 1; return 1; } void _gcry_rngcsprng_update_seed_file (void) { unsigned long *sp, *dp; int fd, i; /* We do only a basic initialization so that we can lock the pool. This is required to cope with the case that this function is called by some cleanup code at a point where the RNG has never been initialized. */ initialize_basics (); lock_pool (); if ( !seed_file_name || !rndpool || !pool_filled ) { unlock_pool (); return; } if ( !allow_seed_file_update ) { unlock_pool (); log_info(_("note: random_seed file not updated\n")); return; } /* At this point we know that there is something in the pool and thus we can conclude that the pool has been fully initialized. */ /* Copy the entropy pool to a scratch pool and mix both of them. */ for (i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool; i < POOLWORDS; i++, dp++, sp++ ) { *dp = *sp + ADD_VALUE; } mix_pool(rndpool); rndstats.mixrnd++; mix_pool(keypool); rndstats.mixkey++; #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__) fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, S_IRUSR|S_IWUSR ); #else # if LOCK_SEED_FILE fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR ); # else fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR ); # endif #endif if (fd == -1 ) log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) ); else if (lock_seed_file (fd, seed_file_name, 1)) { close (fd); } #if LOCK_SEED_FILE else if (ftruncate (fd, 0)) { log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno)); close (fd); } #endif /*LOCK_SEED_FILE*/ else { do { i = write (fd, keypool, POOLSIZE ); } while (i == -1 && errno == EINTR); if (i != POOLSIZE) log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno)); if (close(fd)) log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno)); } unlock_pool (); } /* Read random out of the pool. This function is the core of the public random functions. Note that Level GCRY_WEAK_RANDOM is not anymore handled special and in fact is an alias in the API for level GCRY_STRONG_RANDOM. Must be called with the pool already locked. */ static void read_pool (byte *buffer, size_t length, int level) { int i; unsigned long *sp, *dp; /* The volatile is there to make sure the compiler does not optimize the code away in case the getpid function is badly attributed. Note that we keep a pid in a static variable as well as in a stack based one; the latter is to detect ill behaving thread libraries, ignoring the pool mutexes. */ static volatile pid_t my_pid = (pid_t)(-1); volatile pid_t my_pid2; gcry_assert (pool_is_locked); retry: /* Get our own pid, so that we can detect a fork. */ my_pid2 = getpid (); if (my_pid == (pid_t)(-1)) my_pid = my_pid2; if ( my_pid != my_pid2 ) { /* We detected a plain fork; i.e. we are now the child. Update the static pid and add some randomness. */ pid_t x; my_pid = my_pid2; x = my_pid; add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT); just_mixed = 0; /* Make sure it will get mixed. */ } gcry_assert (pool_is_locked); /* Our code does not allow to extract more than POOLSIZE. Better check it here. */ if (length > POOLSIZE) { log_bug("too many random bits requested\n"); } if (!pool_filled) { if (read_seed_file() ) pool_filled = 1; } /* For level 2 quality (key generation) we always make sure that the pool has been seeded enough initially. */ if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding) { size_t needed; pool_balance = 0; needed = length - pool_balance; if (needed < POOLSIZE/2) needed = POOLSIZE/2; else if( needed > POOLSIZE ) BUG (); read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed, GCRY_VERY_STRONG_RANDOM); pool_balance += needed; did_initial_extra_seeding = 1; } /* For level 2 make sure that there is enough random in the pool. */ if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length) { size_t needed; if (pool_balance < 0) pool_balance = 0; needed = length - pool_balance; if (needed > POOLSIZE) BUG (); read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed, GCRY_VERY_STRONG_RANDOM); pool_balance += needed; } /* Make sure the pool is filled. */ while (!pool_filled) random_poll(); /* Always do a fast random poll (we have to use the unlocked version). */ do_fast_random_poll(); /* Mix the pid in so that we for sure won't deliver the same random after a fork. */ { pid_t apid = my_pid; add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT); } /* Mix the pool (if add_randomness() didn't it). */ if (!just_mixed) { mix_pool(rndpool); rndstats.mixrnd++; } /* Create a new pool. */ for(i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool; i < POOLWORDS; i++, dp++, sp++ ) *dp = *sp + ADD_VALUE; /* Mix both pools. */ mix_pool(rndpool); rndstats.mixrnd++; mix_pool(keypool); rndstats.mixkey++; /* Read the requested data. We use a read pointer to read from a different position each time. */ while (length--) { *buffer++ = keypool[pool_readpos++]; if (pool_readpos >= POOLSIZE) pool_readpos = 0; pool_balance--; } if (pool_balance < 0) pool_balance = 0; /* Clear the keypool. */ memset (keypool, 0, POOLSIZE); /* We need to detect whether a fork has happened. A fork might have an identical pool and thus the child and the parent could emit the very same random number. This test here is to detect forks in a multi-threaded process. It does not work with all thread implementations in particular not with pthreads. However it is good enough for GNU Pth. */ if ( getpid () != my_pid2 ) { pid_t x = getpid(); add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT); just_mixed = 0; /* Make sure it will get mixed. */ my_pid = x; /* Also update the static pid. */ goto retry; } } /* Add LENGTH bytes of randomness from buffer to the pool. ORIGIN is used to specify the randomness origin. This is one of the RANDOM_ORIGIN_* values. */ static void add_randomness (const void *buffer, size_t length, enum random_origins origin) { const unsigned char *p = buffer; size_t count = 0; gcry_assert (pool_is_locked); rndstats.addbytes += length; rndstats.naddbytes++; while (length-- ) { rndpool[pool_writepos++] ^= *p++; count++; if (pool_writepos >= POOLSIZE ) { /* It is possible that we are invoked before the pool is filled using an unreliable origin of entropy, for example the fast random poll. To avoid flagging the pool as filled in this case, we track the initial filling state separately. See also the remarks about the seed file. */ if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled) { pool_filled_counter += count; count = 0; if (pool_filled_counter >= POOLSIZE) pool_filled = 1; } pool_writepos = 0; mix_pool(rndpool); rndstats.mixrnd++; just_mixed = !length; } } } static void random_poll() { rndstats.slowpolls++; read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM); } /* Runtime determination of the slow entropy gathering module. */ static int (* getfnc_gather_random (void))(void (*)(const void*, size_t, enum random_origins), enum random_origins, size_t, int) { int (*fnc)(void (*)(const void*, size_t, enum random_origins), enum random_origins, size_t, int); #if USE_RNDLINUX if ( !access (NAME_OF_DEV_RANDOM, R_OK) && !access (NAME_OF_DEV_URANDOM, R_OK)) { fnc = _gcry_rndlinux_gather_random; return fnc; } #endif #if USE_RNDEGD if ( _gcry_rndegd_connect_socket (1) != -1 ) { fnc = _gcry_rndegd_gather_random; return fnc; } #endif #if USE_RNDUNIX fnc = _gcry_rndunix_gather_random; return fnc; #endif #if USE_RNDW32 fnc = _gcry_rndw32_gather_random; return fnc; #endif #if USE_RNDW32CE fnc = _gcry_rndw32ce_gather_random; return fnc; #endif log_fatal (_("no entropy gathering module detected\n")); return NULL; /*NOTREACHED*/ } /* Runtime determination of the fast entropy gathering function. (Currently a compile time method is used.) */ static void (* getfnc_fast_random_poll (void))( void (*)(const void*, size_t, enum random_origins), enum random_origins) { #if USE_RNDW32 return _gcry_rndw32_gather_random_fast; #endif #if USE_RNDW32CE return _gcry_rndw32ce_gather_random_fast; #endif return NULL; } static void do_fast_random_poll (void) { gcry_assert (pool_is_locked); rndstats.fastpolls++; if (fast_gather_fnc) fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL); /* Continue with the generic functions. */ #if HAVE_GETHRTIME { hrtime_t tv; tv = gethrtime(); add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL ); } #elif HAVE_GETTIMEOFDAY { struct timeval tv; if( gettimeofday( &tv, NULL ) ) BUG(); add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL ); add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), RANDOM_ORIGIN_FASTPOLL ); } #elif HAVE_CLOCK_GETTIME { struct timespec tv; if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 ) BUG(); add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL ); add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), RANDOM_ORIGIN_FASTPOLL ); } #else /* use times */ # ifndef HAVE_DOSISH_SYSTEM { struct tms buf; times( &buf ); add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL ); } # endif #endif #ifdef HAVE_GETRUSAGE # ifdef RUSAGE_SELF { struct rusage buf; /* QNX/Neutrino does return ENOSYS - so we just ignore it and add whatever is in buf. In a chroot environment it might not work at all (i.e. because /proc/ is not accessible), so we better ignore all error codes and hope for the best. */ getrusage (RUSAGE_SELF, &buf ); add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL ); memset( &buf, 0, sizeof buf ); } # else /*!RUSAGE_SELF*/ # ifdef __GCC__ # warning There is no RUSAGE_SELF on this system # endif # endif /*!RUSAGE_SELF*/ #endif /*HAVE_GETRUSAGE*/ /* Time and clock are availabe on all systems - so we better do it just in case one of the above functions didn't work. */ { time_t x = time(NULL); add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL ); } { clock_t x = clock(); add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL ); } /* If the system features a fast hardware RNG, read some bytes from there. */ _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL); } /* 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_rngcsprng_fast_poll (void) { initialize_basics (); lock_pool (); if (rndpool) { /* Yes, we are fully initialized. */ do_fast_random_poll (); } unlock_pool (); } static void read_random_source (enum random_origins orgin, size_t length, int level ) { if ( !slow_gather_fnc ) log_fatal ("Slow entropy gathering module not yet initialized\n"); if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0) log_fatal ("No way to gather entropy for the RNG\n"); } static int gather_faked (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin, size_t length, int level ) { static int initialized=0; size_t n; char *buffer, *p; (void)add; (void)level; if ( !initialized ) { log_info(_("WARNING: using insecure random number generator!!\n")); initialized=1; #ifdef HAVE_RAND srand( time(NULL)*getpid()); #else srandom( time(NULL)*getpid()); #endif } p = buffer = xmalloc( length ); n = length; #ifdef HAVE_RAND while ( n-- ) *p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1); #else while ( n-- ) *p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1); #endif add_randomness ( buffer, length, origin ); xfree (buffer); return 0; /* okay */ } diff --git a/random/random-daemon.c b/random/random-daemon.c index 98a01536..8ea4df28 100644 --- a/random/random-daemon.c +++ b/random/random-daemon.c @@ -1,348 +1,336 @@ /* random-daemon.c - Access to the external random daemon * Copyright (C) 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 */ /* The functions here are used by random.c to divert calls to an external random number daemon. The actual daemon we use is gcryptrnd. Such a daemon is useful to keep a persistent pool in memory over invocations of a single application and to allow prioritizing access to the actual entropy sources. The drawback is that we need to use IPC (i.e. unix domain socket) to convey sensitive data. */ -#error This dameon needs to be fixed due to the ath changes - #include #include #include #include #include #include #include #include #include #include "g10lib.h" #include "random.h" -#include "ath.h" /* This is default socket name we use in case the provided socket name is NULL. */ #define RANDOM_DAEMON_SOCKET "/var/run/libgcrypt/S.gcryptrnd" /* The lock serializing access to the daemon. */ -static ath_mutex_t daemon_lock = ATH_MUTEX_INITIALIZER; +GPGRT_LOCK_DEFINE (daemon_lock); /* The socket connected to the daemon. */ static int daemon_socket = -1; /* Creates a socket connected to the daemon. On success, store the socket fd in *SOCK. Returns error code. */ static gcry_error_t connect_to_socket (const char *socketname, int *sock) { struct sockaddr_un *srvr_addr; socklen_t addrlen; gcry_error_t err; int fd; int rc; srvr_addr = NULL; /* Create a socket. */ fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { log_error ("can't create socket: %s\n", strerror (errno)); err = gcry_error_from_errno (errno); goto out; } /* Set up address. */ srvr_addr = gcry_malloc (sizeof *srvr_addr); if (! srvr_addr) { log_error ("malloc failed: %s\n", strerror (errno)); err = gcry_error_from_errno (errno); goto out; } memset (srvr_addr, 0, sizeof *srvr_addr); srvr_addr->sun_family = AF_UNIX; if (strlen (socketname) + 1 >= sizeof (srvr_addr->sun_path)) { log_error ("socket name `%s' too long\n", socketname); err = gcry_error (GPG_ERR_ENAMETOOLONG); goto out; } strcpy (srvr_addr->sun_path, socketname); addrlen = (offsetof (struct sockaddr_un, sun_path) + strlen (srvr_addr->sun_path) + 1); /* Connect socket. */ rc = connect (fd, (struct sockaddr *) srvr_addr, addrlen); if (rc == -1) { log_error ("error connecting socket `%s': %s\n", srvr_addr->sun_path, strerror (errno)); err = gcry_error_from_errno (errno); goto out; } err = 0; out: gcry_free (srvr_addr); if (err) { close (fd); fd = -1; } *sock = fd; return err; } /* Initialize basics of this module. This should be viewed as a constructor to prepare locking. */ void _gcry_daemon_initialize_basics (void) { - static int initialized; - int err; - - if (!initialized) - { - initialized = 1; - err = ath_mutex_init (&daemon_lock); - if (err) - log_fatal ("failed to create the daemon lock: %s\n", strerror (err) ); - } + /* Not anymore required. */ } /* Send LENGTH bytes of BUFFER to file descriptor FD. Returns 0 on success or another value on write error. */ static int writen (int fd, const void *buffer, size_t length) { ssize_t n; while (length) { do n = ath_write (fd, buffer, length); while (n < 0 && errno == EINTR); if (n < 0) { log_error ("write error: %s\n", strerror (errno)); return -1; /* write error */ } length -= n; buffer = (const char*)buffer + n; } return 0; /* Okay */ } static int readn (int fd, void *buf, size_t buflen, size_t *ret_nread) { size_t nleft = buflen; int nread; char *p; p = buf; while (nleft > 0) { nread = ath_read (fd, buf, nleft); if (nread < 0) { if (nread == EINTR) nread = 0; else return -1; } else if (!nread) break; /* EOF */ nleft -= nread; buf = (char*)buf + nread; } if (ret_nread) *ret_nread = buflen - nleft; return 0; } /* This functions requests REQ_NBYTES from the daemon. If NONCE is true, the data should be suited for a nonce. If NONCE is FALSE, data of random level LEVEL will be generated. The retrieved random data will be stored in BUFFER. Returns error code. */ static gcry_error_t call_daemon (const char *socketname, void *buffer, size_t req_nbytes, int nonce, enum gcry_random_level level) { static int initialized; unsigned char buf[255]; gcry_error_t err = 0; size_t nbytes; size_t nread; int rc; if (!req_nbytes) return 0; - ath_mutex_lock (&daemon_lock); + gpgrt_lock_lock (&daemon_lock); /* Open the socket if that has not been done. */ if (!initialized) { initialized = 1; err = connect_to_socket (socketname ? socketname : RANDOM_DAEMON_SOCKET, &daemon_socket); if (err) { daemon_socket = -1; log_info ("not using random daemon\n"); - ath_mutex_unlock (&daemon_lock); + gpgrt_lock_unlock (&daemon_lock); return err; } } /* Check that we have a valid socket descriptor. */ if ( daemon_socket == -1 ) { - ath_mutex_unlock (&daemon_lock); + gpgrt_lock_unlock (&daemon_lock); return gcry_error (GPG_ERR_INTERNAL); } /* Do the real work. */ do { /* Process in chunks. */ nbytes = req_nbytes > sizeof (buf) ? sizeof (buf) : req_nbytes; req_nbytes -= nbytes; /* Construct request. */ buf[0] = 3; if (nonce) buf[1] = 10; else if (level == GCRY_VERY_STRONG_RANDOM) buf[1] = 12; else if (level == GCRY_STRONG_RANDOM) buf[1] = 11; buf[2] = nbytes; /* Send request. */ rc = writen (daemon_socket, buf, 3); if (rc == -1) { err = gcry_error_from_errno (errno); break; } /* Retrieve response. */ rc = readn (daemon_socket, buf, 2, &nread); if (rc == -1) { err = gcry_error_from_errno (errno); log_error ("read error: %s\n", _gcry_strerror (err)); break; } if (nread && buf[0]) { log_error ("random daemon returned error code %d\n", buf[0]); err = gcry_error (GPG_ERR_INTERNAL); /* ? */ break; } if (nread != 2) { log_error ("response too small\n"); err = gcry_error (GPG_ERR_PROTOCOL_VIOLATION); /* ? */ break; } /* if (1)*/ /* Do this in verbose mode? */ /* log_info ("received response with %d bytes of data\n", buf[1]);*/ if (buf[1] < nbytes) { log_error ("error: server returned less bytes than requested\n"); err = gcry_error (GPG_ERR_PROTOCOL_VIOLATION); /* ? */ break; } else if (buf[1] > nbytes) { log_error ("warning: server returned more bytes than requested\n"); err = gcry_error (GPG_ERR_PROTOCOL_VIOLATION); /* ? */ break; } assert (nbytes <= sizeof (buf)); rc = readn (daemon_socket, buf, nbytes, &nread); if (rc == -1) { err = gcry_error_from_errno (errno); log_error ("read error: %s\n", _gcry_strerror (err)); break; } if (nread != nbytes) { log_error ("too little random data read\n"); err = gcry_error (GPG_ERR_INTERNAL); break; } /* Successfuly read another chunk of data. */ memcpy (buffer, buf, nbytes); buffer = ((char *) buffer) + nbytes; } while (req_nbytes); - ath_mutex_unlock (&daemon_lock); + gpgrt_lock_unlock (&daemon_lock); return err; } /* Internal function to fill BUFFER with LENGTH bytes of random. We support GCRY_STRONG_RANDOM and GCRY_VERY_STRONG_RANDOM here. Return 0 on success. */ int _gcry_daemon_randomize (const char *socketname, void *buffer, size_t length, enum gcry_random_level level) { gcry_error_t err; err = call_daemon (socketname, buffer, length, 0, level); return err ? -1 : 0; } /* END */ diff --git a/random/random-fips.c b/random/random-fips.c index d00825e2..0a763628 100644 --- a/random/random-fips.c +++ b/random/random-fips.c @@ -1,1129 +1,1124 @@ /* random-fips.c - FIPS style random number generator * 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 . */ /* The core of this deterministic random number generator is implemented according to the document "NIST-Recommended Random Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms" (2005-01-31). This implementation uses the AES variant. There are 3 random context which map to the different levels of random quality: Generator Seed and Key Kernel entropy (init/reseed) ------------------------------------------------------------ GCRY_VERY_STRONG_RANDOM /dev/random 256/128 bits GCRY_STRONG_RANDOM /dev/random 256/128 bits gcry_create_nonce GCRY_STRONG_RANDOM n/a All random generators return their data in 128 bit blocks. If the caller requested less bits, the extra bits are not used. The key for each generator is only set once at the first time a generator is used. The seed value is set with the key and again after 1000 (SEED_TTL) output blocks; the re-seeding is disabled in test mode. The GCRY_VERY_STRONG_RANDOM and GCRY_STRONG_RANDOM generators are keyed and seeded from the /dev/random device. Thus these generators may block until the kernel has collected enough entropy. The gcry_create_nonce generator is keyed and seeded from the GCRY_STRONG_RANDOM generator. It may also block if the GCRY_STRONG_RANDOM generator has not yet been used before and thus gets initialized on the first use by gcry_create_nonce. This special treatment is justified by the weaker requirements for a nonce generator and to save precious kernel entropy for use by the real random generators. */ #include #include #include #include #include #include #ifdef HAVE_GETTIMEOFDAY #include #endif #include "g10lib.h" #include "random.h" #include "rand-internal.h" -#include "ath.h" /* This is the lock we use to serialize access to this RNG. The extra integer variable is only used to check the locking state; that is, it is not meant to be thread-safe but merely as a failsafe feature to assert proper locking. */ -static ath_mutex_t fips_rng_lock; +GPGRT_LOCK_DEFINE (fips_rng_lock); static int fips_rng_is_locked; /* The required size for the temporary buffer of the x931_aes_driver function and the buffer itself which will be allocated in secure memory. This needs to be global variable for proper initialization and to allow shutting down the RNG without leaking memory. May only be used while holding the FIPS_RNG_LOCK. This variable is also used to avoid duplicate initialization. */ #define TEMPVALUE_FOR_X931_AES_DRIVER_SIZE 48 static unsigned char *tempvalue_for_x931_aes_driver; /* After having retrieved this number of blocks from the RNG, we want to do a reseeding. */ #define SEED_TTL 1000 /* The length of the key we use: 16 bytes (128 bit) for AES128. */ #define X931_AES_KEYLEN 16 /* A global buffer used to communicate between the x931_generate_key and x931_generate_seed functions and the entropy_collect_cb function. It may only be used by these functions. */ static unsigned char *entropy_collect_buffer; /* Buffer. */ static size_t entropy_collect_buffer_len; /* Used length. */ static size_t entropy_collect_buffer_size; /* Allocated length. */ /* This random context type is used to track properties of one random generator. Thee context are usually allocated in secure memory so that the seed value is well protected. There are a couble of guard fields to help detecting applications accidently overwriting parts of the memory. */ struct rng_context { unsigned char guard_0[1]; /* The handle of the cipher used by the RNG. If this one is not NULL a cipher handle along with a random key has been established. */ gcry_cipher_hd_t cipher_hd; /* If this flag is true, the SEED_V buffer below carries a valid seed. */ int is_seeded:1; /* The very first block generated is used to compare the result against the last result. This flag indicates that such a block is available. */ int compare_value_valid:1; /* A counter used to trigger re-seeding. */ unsigned int use_counter; unsigned char guard_1[1]; /* The buffer containing the seed value V. */ unsigned char seed_V[16]; unsigned char guard_2[1]; /* The last result from the x931_aes function. Only valid if compare_value_valid is set. */ unsigned char compare_value[16]; unsigned char guard_3[1]; /* The external test may want to suppress the duplicate bock check. This is done if the this flag is set. */ unsigned char test_no_dup_check; /* To implement a KAT we need to provide a know DT value. To accomplish this the x931_get_dt function checks whether this field is not NULL and then uses the 16 bytes at this address for the DT value. However the last 4 bytes are replaced by the value of field TEST_DT_COUNTER which will be incremented after each invocation of x931_get_dt. We use a pointer and not a buffer because there is no need to put this value into secure memory. */ const unsigned char *test_dt_ptr; u32 test_dt_counter; /* 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 key_init_pid; pid_t seed_init_pid; }; typedef struct rng_context *rng_context_t; /* The random context used for the nonce generator. May only be used while holding the FIPS_RNG_LOCK. */ static rng_context_t nonce_context; /* The random context used for the standard random generator. May only be used while holding the FIPS_RNG_LOCK. */ static rng_context_t std_rng_context; /* The random context used for the very strong random generator. May only be used while holding the FIPS_RNG_LOCK. */ static rng_context_t strong_rng_context; /* --- Local prototypes --- */ static void x931_reseed (rng_context_t rng_ctx); static void get_random (void *buffer, size_t length, rng_context_t rng_ctx); /* --- Functions --- */ /* Basic initialization is required to initialize mutexes and do a few checks on the implementation. */ static void basic_initialization (void) { static int initialized; - int my_errno; if (initialized) return; initialized = 1; - my_errno = ath_mutex_init (&fips_rng_lock); - if (my_errno) - log_fatal ("failed to create the RNG lock: %s\n", strerror (my_errno)); fips_rng_is_locked = 0; /* 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); } /* Acquire the fips_rng_lock. */ static void lock_rng (void) { - int my_errno; + gpg_err_code_t rc; - my_errno = ath_mutex_lock (&fips_rng_lock); - if (my_errno) - log_fatal ("failed to acquire the RNG lock: %s\n", strerror (my_errno)); + rc = gpgrt_lock_lock (&fips_rng_lock); + if (rc) + log_fatal ("failed to acquire the RNG lock: %s\n", gpg_strerror (rc)); fips_rng_is_locked = 1; } /* Release the fips_rng_lock. */ static void unlock_rng (void) { - int my_errno; + gpg_err_code_t rc; fips_rng_is_locked = 0; - my_errno = ath_mutex_unlock (&fips_rng_lock); - if (my_errno) - log_fatal ("failed to release the RNG lock: %s\n", strerror (my_errno)); + rc = gpgrt_lock_unlock (&fips_rng_lock); + if (rc) + log_fatal ("failed to release the RNG lock: %s\n", gpg_strerror (rc)); } static void setup_guards (rng_context_t rng_ctx) { /* Set the guards to some arbitrary values. */ rng_ctx->guard_0[0] = 17; rng_ctx->guard_1[0] = 42; rng_ctx->guard_2[0] = 137; rng_ctx->guard_3[0] = 252; } static void check_guards (rng_context_t rng_ctx) { if ( rng_ctx->guard_0[0] != 17 || rng_ctx->guard_1[0] != 42 || rng_ctx->guard_2[0] != 137 || rng_ctx->guard_3[0] != 252 ) log_fatal ("memory corruption detected in RNG context %p\n", rng_ctx); } /* Get the DT vector for use with the core PRNG function. Buffer needs to be provided by the caller with a size of at least LENGTH bytes. RNG_CTX needs to be passed to allow for a KAT. The 16 byte timestamp we construct is made up the real time and three counters: Buffer: 00112233445566778899AABBCCDDEEFF !--+---!!-+-!!+!!--+---!!--+---! seconds ---------/ | | | | microseconds -----------/ | | | counter2 -------------------/ | | counter1 ------------------------/ | counter0 --------------------------------/ Counter 2 is just 12 bits wide and used to track fractions of milliseconds whereas counters 1 and 0 are combined to a free running 64 bit counter. */ static void x931_get_dt (unsigned char *buffer, size_t length, rng_context_t rng_ctx) { gcry_assert (length == 16); /* This length is required for use with AES. */ gcry_assert (fips_rng_is_locked); /* If the random context indicates that a test DT should be used, take the DT value from the context. For safety reasons we do this only if the context is not one of the regular contexts. */ if (rng_ctx->test_dt_ptr && rng_ctx != nonce_context && rng_ctx != std_rng_context && rng_ctx != strong_rng_context) { memcpy (buffer, rng_ctx->test_dt_ptr, 16); buffer[12] = (rng_ctx->test_dt_counter >> 24); buffer[13] = (rng_ctx->test_dt_counter >> 16); buffer[14] = (rng_ctx->test_dt_counter >> 8); buffer[15] = rng_ctx->test_dt_counter; rng_ctx->test_dt_counter++; return; } #if HAVE_GETTIMEOFDAY { static u32 last_sec, last_usec; static u32 counter1, counter0; static u16 counter2; unsigned int usec; struct timeval tv; if (!last_sec) { /* This is the very first time we are called: Set the counters to an not so easy predictable value to avoid always starting at 0. Not really needed but it doesn't harm. */ counter1 = (u32)getpid (); #ifndef HAVE_W32_SYSTEM counter0 = (u32)getppid (); #endif } if (gettimeofday (&tv, NULL)) log_fatal ("gettimeofday() failed: %s\n", strerror (errno)); /* The microseconds part is always less than 1 millon (0x0f4240). Thus we don't care about the MSB and in addition shift it to the left by 4 bits. */ usec = tv.tv_usec; usec <<= 4; /* If we got the same time as by the last invocation, bump up counter2 and save the time for the next invocation. */ if (tv.tv_sec == last_sec && usec == last_usec) { counter2++; counter2 &= 0x0fff; } else { counter2 = 0; last_sec = tv.tv_sec; last_usec = usec; } /* Fill the buffer with the timestamp. */ buffer[0] = ((tv.tv_sec >> 24) & 0xff); buffer[1] = ((tv.tv_sec >> 16) & 0xff); buffer[2] = ((tv.tv_sec >> 8) & 0xff); buffer[3] = (tv.tv_sec & 0xff); buffer[4] = ((usec >> 16) & 0xff); buffer[5] = ((usec >> 8) & 0xff); buffer[6] = ((usec & 0xf0) | ((counter2 >> 8) & 0x0f)); buffer[7] = (counter2 & 0xff); /* Add the free running counter. */ buffer[8] = ((counter1 >> 24) & 0xff); buffer[9] = ((counter1 >> 16) & 0xff); buffer[10] = ((counter1 >> 8) & 0xff); buffer[11] = ((counter1) & 0xff); buffer[12] = ((counter0 >> 24) & 0xff); buffer[13] = ((counter0 >> 16) & 0xff); buffer[14] = ((counter0 >> 8) & 0xff); buffer[15] = ((counter0) & 0xff); /* Bump up that counter. */ if (!++counter0) ++counter1; } #else log_fatal ("gettimeofday() not available on this system\n"); #endif /* log_printhex ("x931_get_dt: ", buffer, 16); */ } /* XOR the buffers A and B which are each of LENGTH bytes and store the result at R. R needs to be provided by the caller with a size of at least LENGTH bytes. */ static void xor_buffer (unsigned char *r, const unsigned char *a, const unsigned char *b, size_t length) { for ( ; length; length--, a++, b++, r++) *r = (*a ^ *b); } /* Encrypt LENGTH bytes of INPUT to OUTPUT using KEY. LENGTH needs to be 16. */ static void encrypt_aes (gcry_cipher_hd_t key, unsigned char *output, const unsigned char *input, size_t length) { gpg_error_t err; gcry_assert (length == 16); err = _gcry_cipher_encrypt (key, output, length, input, length); if (err) log_fatal ("AES encryption in RNG failed: %s\n", _gcry_strerror (err)); } /* The core ANSI X9.31, Appendix A.2.4 function using AES. The caller needs to pass a 16 byte buffer for the result, the 16 byte datetime_DT value and the 16 byte seed value V. The caller also needs to pass an appropriate KEY and make sure to pass a valid seed_V. The caller also needs to provide two 16 bytes buffer for intermediate results, they may be reused by the caller later. On return the result is stored at RESULT_R and the SEED_V is updated. May only be used while holding the lock. */ static void x931_aes (unsigned char result_R[16], unsigned char datetime_DT[16], unsigned char seed_V[16], gcry_cipher_hd_t key, unsigned char intermediate_I[16], unsigned char temp_xor[16]) { /* Let ede*X(Y) represent the AES encryption of Y under the key *X. Let V be a 128-bit seed value which is also kept secret, and XOR be the exclusive-or operator. Let DT be a date/time vector which is updated on each iteration. I is a intermediate value. I = ede*K(DT) */ encrypt_aes (key, intermediate_I, datetime_DT, 16); /* R = ede*K(I XOR V) */ xor_buffer (temp_xor, intermediate_I, seed_V, 16); encrypt_aes (key, result_R, temp_xor, 16); /* V = ede*K(R XOR I). */ xor_buffer (temp_xor, result_R, intermediate_I, 16); encrypt_aes (key, seed_V, temp_xor, 16); /* Zero out temporary values. */ wipememory (intermediate_I, 16); wipememory (temp_xor, 16); } /* The high level driver to x931_aes. This one does the required tests and calls the core function until the entire buffer has been filled. OUTPUT is a caller provided buffer of LENGTH bytes to receive the random, RNG_CTX is the context of the RNG. The context must be properly initialized. Returns 0 on success. */ static int x931_aes_driver (unsigned char *output, size_t length, rng_context_t rng_ctx) { unsigned char datetime_DT[16]; unsigned char *intermediate_I, *temp_buffer, *result_buffer; size_t nbytes; gcry_assert (fips_rng_is_locked); gcry_assert (rng_ctx->cipher_hd); gcry_assert (rng_ctx->is_seeded); gcry_assert (tempvalue_for_x931_aes_driver); gcry_assert (TEMPVALUE_FOR_X931_AES_DRIVER_SIZE == 48); intermediate_I = tempvalue_for_x931_aes_driver; temp_buffer = tempvalue_for_x931_aes_driver + 16; result_buffer = tempvalue_for_x931_aes_driver + 32; while (length) { /* Unless we are running with a test context, we require a new seed after some time. */ if (!rng_ctx->test_dt_ptr && rng_ctx->use_counter > SEED_TTL) { x931_reseed (rng_ctx); rng_ctx->use_counter = 0; } /* Due to the design of the RNG, we always receive 16 bytes (128 bit) of random even if we require less. The extra bytes returned are not used. Intheory we could save them for the next invocation, but that would make the control flow harder to read. */ nbytes = length < 16? length : 16; x931_get_dt (datetime_DT, 16, rng_ctx); x931_aes (result_buffer, datetime_DT, rng_ctx->seed_V, rng_ctx->cipher_hd, intermediate_I, temp_buffer); rng_ctx->use_counter++; if (rng_ctx->test_no_dup_check && rng_ctx->test_dt_ptr && rng_ctx != nonce_context && rng_ctx != std_rng_context && rng_ctx != strong_rng_context) { /* This is a test context which does not want the duplicate block check. */ } else { /* Do a basic check on the output to avoid a stuck generator. */ if (!rng_ctx->compare_value_valid) { /* First time used, only save the result. */ memcpy (rng_ctx->compare_value, result_buffer, 16); rng_ctx->compare_value_valid = 1; continue; } if (!memcmp (rng_ctx->compare_value, result_buffer, 16)) { /* Ooops, we received the same 128 bit block - that should in theory never happen. The FIPS requirement says that we need to put ourself into the error state in such case. */ fips_signal_error ("duplicate 128 bit block returned by RNG"); return -1; } memcpy (rng_ctx->compare_value, result_buffer, 16); } /* Append to outbut. */ memcpy (output, result_buffer, nbytes); wipememory (result_buffer, 16); output += nbytes; length -= nbytes; } return 0; } /* Callback for x931_generate_key. Note that this callback uses the global ENTROPY_COLLECT_BUFFER which has been setup by get_entropy. ORIGIN is not used but required due to the design of entropy gathering module. */ static void entropy_collect_cb (const void *buffer, size_t length, enum random_origins origin) { const unsigned char *p = buffer; (void)origin; gcry_assert (fips_rng_is_locked); gcry_assert (entropy_collect_buffer); /* Note that we need to protect against gatherers returning more than the requested bytes (e.g. rndw32). */ while (length-- && entropy_collect_buffer_len < entropy_collect_buffer_size) { entropy_collect_buffer[entropy_collect_buffer_len++] ^= *p++; } } /* Get NBYTES of entropy from the kernel device. The callers needs to free the returned buffer. The function either succeeds or terminates the process in case of a fatal error. */ static void * get_entropy (size_t nbytes) { void *result; int rc; gcry_assert (!entropy_collect_buffer); entropy_collect_buffer = xmalloc_secure (nbytes); entropy_collect_buffer_size = nbytes; entropy_collect_buffer_len = 0; #if USE_RNDLINUX rc = _gcry_rndlinux_gather_random (entropy_collect_cb, 0, X931_AES_KEYLEN, GCRY_VERY_STRONG_RANDOM); #elif USE_RNDW32 do { rc = _gcry_rndw32_gather_random (entropy_collect_cb, 0, X931_AES_KEYLEN, GCRY_VERY_STRONG_RANDOM); } while (rc >= 0 && entropy_collect_buffer_len < entropy_collect_buffer_size); #else rc = -1; #endif if (rc < 0 || entropy_collect_buffer_len != entropy_collect_buffer_size) { xfree (entropy_collect_buffer); entropy_collect_buffer = NULL; log_fatal ("error getting entropy data\n"); } result = entropy_collect_buffer; entropy_collect_buffer = NULL; return result; } /* Generate a key for use with x931_aes. The function returns a handle to the cipher context readily prepared for ECB encryption. If FOR_NONCE is true, the key is retrieved by readong random from the standard generator. On error NULL is returned. */ static gcry_cipher_hd_t x931_generate_key (int for_nonce) { gcry_cipher_hd_t hd; gpg_err_code_t rc; void *buffer; gcry_assert (fips_rng_is_locked); /* Allocate a cipher context. */ rc = _gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_SECURE); if (rc) { log_error ("error creating cipher context for RNG: %s\n", _gcry_strerror (rc)); return NULL; } /* Get a key from the standard RNG or from the entropy source. */ if (for_nonce) { buffer = xmalloc (X931_AES_KEYLEN); get_random (buffer, X931_AES_KEYLEN, std_rng_context); } else { buffer = get_entropy (X931_AES_KEYLEN); } /* Set the key and delete the buffer because the key is now part of the cipher context. */ rc = _gcry_cipher_setkey (hd, buffer, X931_AES_KEYLEN); wipememory (buffer, X931_AES_KEYLEN); xfree (buffer); if (rc) { log_error ("error creating key for RNG: %s\n", _gcry_strerror (rc)); _gcry_cipher_close (hd); return NULL; } return hd; } /* Generate a key for use with x931_aes. The function copies a seed of LENGTH bytes into SEED_BUFFER. LENGTH needs to by given as 16. */ static void x931_generate_seed (unsigned char *seed_buffer, size_t length) { void *buffer; gcry_assert (fips_rng_is_locked); gcry_assert (length == 16); buffer = get_entropy (X931_AES_KEYLEN); memcpy (seed_buffer, buffer, X931_AES_KEYLEN); wipememory (buffer, X931_AES_KEYLEN); xfree (buffer); } /* Reseed a generator. This is also used for the initial seeding. */ static void x931_reseed (rng_context_t rng_ctx) { gcry_assert (fips_rng_is_locked); if (rng_ctx == nonce_context) { /* The nonce context is special. It will be seeded using the standard random generator. */ get_random (rng_ctx->seed_V, 16, std_rng_context); rng_ctx->is_seeded = 1; rng_ctx->seed_init_pid = getpid (); } else { /* The other two generators are seeded from /dev/random. */ x931_generate_seed (rng_ctx->seed_V, 16); rng_ctx->is_seeded = 1; rng_ctx->seed_init_pid = getpid (); } } /* Core random function. This is used for both nonce and random generator. The actual RNG to be used depends on the random context RNG_CTX passed. Note that this function is called with the RNG not yet locked. */ static void get_random (void *buffer, size_t length, rng_context_t rng_ctx) { gcry_assert (buffer); gcry_assert (rng_ctx); check_guards (rng_ctx); /* Initialize the cipher handle and thus setup the key if needed. */ if (!rng_ctx->cipher_hd) { if (rng_ctx == nonce_context) rng_ctx->cipher_hd = x931_generate_key (1); else rng_ctx->cipher_hd = x931_generate_key (0); if (!rng_ctx->cipher_hd) goto bailout; rng_ctx->key_init_pid = getpid (); } /* Initialize the seed value if needed. */ if (!rng_ctx->is_seeded) x931_reseed (rng_ctx); if (rng_ctx->key_init_pid != getpid () || rng_ctx->seed_init_pid != getpid ()) { /* We are in a child of us. Because we have no way yet to do proper re-initialization (including self-checks etc), the only chance we have is to bail out. Obviusly a fork/exec won't harm because the exec overwrites the old image. */ fips_signal_error ("fork without proper re-initialization " "detected in RNG"); goto bailout; } if (x931_aes_driver (buffer, length, rng_ctx)) goto bailout; check_guards (rng_ctx); return; bailout: log_fatal ("severe error getting random\n"); /*NOTREACHED*/ } /* --- Public Functions --- */ /* 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_rngfips_initialize (int full) { basic_initialization (); if (!full) return; /* Allocate temporary buffers. If that buffer already exists we know that we are already initialized. */ lock_rng (); if (!tempvalue_for_x931_aes_driver) { tempvalue_for_x931_aes_driver = xmalloc_secure (TEMPVALUE_FOR_X931_AES_DRIVER_SIZE); /* Allocate the random contexts. Note that we do not need to use secure memory for the nonce context. */ nonce_context = xcalloc (1, sizeof *nonce_context); setup_guards (nonce_context); std_rng_context = xcalloc_secure (1, sizeof *std_rng_context); setup_guards (std_rng_context); strong_rng_context = xcalloc_secure (1, sizeof *strong_rng_context); setup_guards (strong_rng_context); } else { /* Already initialized. Do some sanity checks. */ gcry_assert (!nonce_context->test_dt_ptr); gcry_assert (!std_rng_context->test_dt_ptr); gcry_assert (!strong_rng_context->test_dt_ptr); check_guards (nonce_context); check_guards (std_rng_context); check_guards (strong_rng_context); } unlock_rng (); } /* Try to close the FDs of the random gather module. This is currently only implemented for rndlinux. */ void _gcry_rngfips_close_fds (void) { lock_rng (); #if USE_RNDLINUX _gcry_rndlinux_gather_random (NULL, 0, 0, 0); #endif unlock_rng (); } /* Print some statistics about the RNG. */ void _gcry_rngfips_dump_stats (void) { /* Not yet implemented. */ } /* This function returns true if no real RNG is available or the quality of the RNG has been degraded for test purposes. */ int _gcry_rngfips_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_rngfips_add_bytes (const void *buf, size_t buflen, int quality) { (void)buf; (void)buflen; (void)quality; return 0; /* Not implemented. */ } /* Public function to fill the buffer with LENGTH bytes of cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is here mapped to GCRY_STRONG_RANDOM, 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_rngfips_randomize (void *buffer, size_t length, enum gcry_random_level level) { _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ lock_rng (); if (level == GCRY_VERY_STRONG_RANDOM) get_random (buffer, length, strong_rng_context); else get_random (buffer, length, std_rng_context); unlock_rng (); } /* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ void _gcry_rngfips_create_nonce (void *buffer, size_t length) { _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ lock_rng (); get_random (buffer, length, nonce_context); unlock_rng (); } /* Run a Know-Answer-Test using a dedicated test context. Note that we can't use the samples from the NISR RNGVS document because they don't take the requirement to throw away the first block and use that for duplicate check in account. Thus we made up our own test vectors. */ static gcry_err_code_t selftest_kat (selftest_report_func_t report) { static struct { const unsigned char key[16]; const unsigned char dt[16]; const unsigned char v[16]; const unsigned char r[3][16]; } tv[] = { { { 0xb9, 0xca, 0x7f, 0xd6, 0xa0, 0xf5, 0xd3, 0x42, 0x19, 0x6d, 0x84, 0x91, 0x76, 0x1c, 0x3b, 0xbe }, { 0x48, 0xb2, 0x82, 0x98, 0x68, 0xc2, 0x80, 0x00, 0x00, 0x00, 0x28, 0x18, 0x00, 0x00, 0x25, 0x00 }, { 0x52, 0x17, 0x8d, 0x29, 0xa2, 0xd5, 0x84, 0x12, 0x9d, 0x89, 0x9a, 0x45, 0x82, 0x02, 0xf7, 0x77 }, { { 0x42, 0x9c, 0x08, 0x3d, 0x82, 0xf4, 0x8a, 0x40, 0x66, 0xb5, 0x49, 0x27, 0xab, 0x42, 0xc7, 0xc3 }, { 0x0e, 0xb7, 0x61, 0x3c, 0xfe, 0xb0, 0xbe, 0x73, 0xf7, 0x6e, 0x6d, 0x6f, 0x1d, 0xa3, 0x14, 0xfa }, { 0xbb, 0x4b, 0xc1, 0x0e, 0xc5, 0xfb, 0xcd, 0x46, 0xbe, 0x28, 0x61, 0xe7, 0x03, 0x2b, 0x37, 0x7d } } }, { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { { 0xf7, 0x95, 0xbd, 0x4a, 0x52, 0xe2, 0x9e, 0xd7, 0x13, 0xd3, 0x13, 0xfa, 0x20, 0xe9, 0x8d, 0xbc }, { 0xc8, 0xd1, 0xe5, 0x11, 0x59, 0x52, 0xf7, 0xfa, 0x37, 0x38, 0xb4, 0xc5, 0xce, 0xb2, 0xb0, 0x9a }, { 0x0d, 0x9c, 0xc5, 0x0d, 0x16, 0xe1, 0xbc, 0xed, 0xcf, 0x60, 0x62, 0x09, 0x9d, 0x20, 0x83, 0x7e } } }, { { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { 0x80, 0x00, 0x81, 0x01, 0x82, 0x02, 0x83, 0x03, 0xa0, 0x20, 0xa1, 0x21, 0xa2, 0x22, 0xa3, 0x23 }, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { { 0x96, 0xed, 0xcc, 0xc3, 0xdd, 0x04, 0x7f, 0x75, 0x63, 0x19, 0x37, 0x6f, 0x15, 0x22, 0x57, 0x56 }, { 0x7a, 0x14, 0x76, 0x77, 0x95, 0x17, 0x7e, 0xc8, 0x92, 0xe8, 0xdd, 0x15, 0xcb, 0x1f, 0xbc, 0xb1 }, { 0x25, 0x3e, 0x2e, 0xa2, 0x41, 0x1b, 0xdd, 0xf5, 0x21, 0x48, 0x41, 0x71, 0xb3, 0x8d, 0x2f, 0x4c } } } }; int tvidx, ridx; rng_context_t test_ctx; gpg_err_code_t rc; const char *errtxt = NULL; unsigned char result[16]; gcry_assert (tempvalue_for_x931_aes_driver); test_ctx = xcalloc (1, sizeof *test_ctx); setup_guards (test_ctx); lock_rng (); for (tvidx=0; tvidx < DIM (tv); tvidx++) { /* Setup the key. */ rc = _gcry_cipher_open (&test_ctx->cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_SECURE); if (rc) { errtxt = "error creating cipher context for RNG"; goto leave; } rc = _gcry_cipher_setkey (test_ctx->cipher_hd, tv[tvidx].key, 16); if (rc) { errtxt = "error setting key for RNG"; goto leave; } test_ctx->key_init_pid = getpid (); /* Setup the seed. */ memcpy (test_ctx->seed_V, tv[tvidx].v, 16); test_ctx->is_seeded = 1; test_ctx->seed_init_pid = getpid (); /* Setup a DT value. */ test_ctx->test_dt_ptr = tv[tvidx].dt; test_ctx->test_dt_counter = ( (tv[tvidx].dt[12] << 24) |(tv[tvidx].dt[13] << 16) |(tv[tvidx].dt[14] << 8) |(tv[tvidx].dt[15]) ); /* Get and compare the first three results. */ for (ridx=0; ridx < 3; ridx++) { /* Compute the next value. */ if (x931_aes_driver (result, 16, test_ctx)) { errtxt = "X9.31 RNG core function failed"; goto leave; } /* Compare it to the known value. */ if (memcmp (result, tv[tvidx].r[ridx], 16)) { /* log_printhex ("x931_aes got: ", result, 16); */ /* log_printhex ("x931_aes exp: ", tv[tvidx].r[ridx], 16); */ errtxt = "RNG output does not match known value"; goto leave; } } /* This test is actual pretty pointless because we use a local test context. */ if (test_ctx->key_init_pid != getpid () || test_ctx->seed_init_pid != getpid ()) { errtxt = "fork detection failed"; goto leave; } _gcry_cipher_close (test_ctx->cipher_hd); test_ctx->cipher_hd = NULL; test_ctx->is_seeded = 0; check_guards (test_ctx); } leave: unlock_rng (); _gcry_cipher_close (test_ctx->cipher_hd); check_guards (test_ctx); xfree (test_ctx); if (report && errtxt) report ("random", 0, "KAT", errtxt); return errtxt? GPG_ERR_SELFTEST_FAILED : 0; } /* Run the self-tests. */ gcry_error_t _gcry_rngfips_selftest (selftest_report_func_t report) { gcry_err_code_t ec; #if defined(USE_RNDLINUX) || defined(USE_RNDW32) { char buffer[8]; /* Do a simple test using the public interface. This will also enforce full initialization of the RNG. We need to be fully initialized due to the global requirement of the tempvalue_for_x931_aes_driver stuff. */ _gcry_randomize (buffer, sizeof buffer, GCRY_STRONG_RANDOM); } ec = selftest_kat (report); #else /*!(USE_RNDLINUX||USE_RNDW32)*/ report ("random", 0, "setup", "no entropy gathering module"); ec = GPG_ERR_SELFTEST_FAILED; #endif return gpg_error (ec); } /* 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_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) { gpg_err_code_t rc; rng_context_t test_ctx; _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ if (!r_context || !key || keylen != 16 || !seed || seedlen != 16 || !dt || dtlen != 16 ) return GPG_ERR_INV_ARG; test_ctx = xtrycalloc (1, sizeof *test_ctx + dtlen); if (!test_ctx) return gpg_err_code_from_syserror (); setup_guards (test_ctx); /* Setup the key. */ rc = _gcry_cipher_open (&test_ctx->cipher_hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_SECURE); if (rc) goto leave; rc = _gcry_cipher_setkey (test_ctx->cipher_hd, key, keylen); if (rc) goto leave; test_ctx->key_init_pid = getpid (); /* Setup the seed. */ memcpy (test_ctx->seed_V, seed, seedlen); test_ctx->is_seeded = 1; test_ctx->seed_init_pid = getpid (); /* Setup a DT value. Because our context structure only stores a pointer we copy the DT value to the extra space we allocated in the test_ctx and set the pointer to that address. */ memcpy ((unsigned char*)test_ctx + sizeof *test_ctx, dt, dtlen); test_ctx->test_dt_ptr = (unsigned char*)test_ctx + sizeof *test_ctx; test_ctx->test_dt_counter = ( (test_ctx->test_dt_ptr[12] << 24) |(test_ctx->test_dt_ptr[13] << 16) |(test_ctx->test_dt_ptr[14] << 8) |(test_ctx->test_dt_ptr[15]) ); if ( (flags & 1) ) test_ctx->test_no_dup_check = 1; check_guards (test_ctx); /* All fine. */ rc = 0; leave: if (rc) { _gcry_cipher_close (test_ctx->cipher_hd); xfree (test_ctx); *r_context = NULL; } else *r_context = test_ctx; return rc; } /* 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_rngfips_run_external_test (void *context, char *buffer, size_t buflen) { rng_context_t test_ctx = context; if (!test_ctx || !buffer || buflen != 16) return GPG_ERR_INV_ARG; lock_rng (); get_random (buffer, buflen, test_ctx); unlock_rng (); return 0; } /* Release the test CONTEXT. */ void _gcry_rngfips_deinit_external_test (void *context) { rng_context_t test_ctx = context; if (test_ctx) { _gcry_cipher_close (test_ctx->cipher_hd); xfree (test_ctx); } } diff --git a/random/random-system.c b/random/random-system.c index 3962ab88..8b79511c 100644 --- a/random/random-system.c +++ b/random/random-system.c @@ -1,256 +1,250 @@ /* random-system.c - wrapper around the system's RNG * Copyright (C) 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 RNG is merely wrapper around the system's native RNG. For example on Unix systems it directly uses /dev/{u,}random. */ #include #include #include #include #include #include #ifdef HAVE_GETTIMEOFDAY #include #endif #include "g10lib.h" #include "random.h" #include "rand-internal.h" -#include "ath.h" /* This is the lock we use to serialize access to this RNG. The extra integer variable is only used to check the locking state; that is, it is not meant to be thread-safe but merely as a failsafe feature to assert proper locking. */ -static ath_mutex_t system_rng_lock; +GPGRT_LOCK_DEFINE (system_rng_lock); static int system_rng_is_locked; /* --- Local prototypes --- */ /* --- Functions --- */ /* Basic initialization is required to initialize mutexes and do a few checks on the implementation. */ static void basic_initialization (void) { static int initialized; - int my_errno; if (initialized) return; initialized = 1; - my_errno = ath_mutex_init (&system_rng_lock); - if (my_errno) - log_fatal ("failed to create the System RNG lock: %s\n", - strerror (my_errno)); system_rng_is_locked = 0; /* Make sure that we are still using the values we traditionally used for the random levels. */ gcry_assert (GCRY_WEAK_RANDOM == 0 && GCRY_STRONG_RANDOM == 1 && GCRY_VERY_STRONG_RANDOM == 2); } /* Acquire the system_rng_lock. */ static void lock_rng (void) { - int my_errno; + gpg_err_code_t rc; - my_errno = ath_mutex_lock (&system_rng_lock); - if (my_errno) + rc = gpgrt_lock_lock (&system_rng_lock); + if (rc) log_fatal ("failed to acquire the System RNG lock: %s\n", - strerror (my_errno)); + gpg_strerror (rc)); system_rng_is_locked = 1; } /* Release the system_rng_lock. */ static void unlock_rng (void) { - int my_errno; + gpg_err_code_t rc; system_rng_is_locked = 0; - my_errno = ath_mutex_unlock (&system_rng_lock); - if (my_errno) + rc = gpgrt_lock_unlock (&system_rng_lock); + if (rc) log_fatal ("failed to release the System RNG lock: %s\n", - strerror (my_errno)); + gpg_strerror (rc)); } /* 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 _gcry_rnd*_gather_random. */ static void read_cb (const void *buffer, size_t length, enum random_origins origin) { const unsigned char *p = buffer; (void)origin; gcry_assert (system_rng_is_locked); 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++; } } /* Fill BUFFER with LENGTH bytes of random at quality LEVEL. The function either succeeds or terminates the process in case of a fatal error. */ static void get_random (void *buffer, size_t length, int level) { int rc; gcry_assert (buffer); read_cb_buffer = buffer; read_cb_size = length; read_cb_len = 0; #if USE_RNDLINUX rc = _gcry_rndlinux_gather_random (read_cb, 0, length, level); #elif USE_RNDUNIX rc = _gcry_rndunix_gather_random (read_cb, 0, length, level); #elif USE_RNDW32 do { rc = _gcry_rndw32_gather_random (read_cb, 0, length, level); } while (rc >= 0 && read_cb_len < read_cb_size); #else rc = -1; #endif if (rc < 0 || read_cb_len != read_cb_size) { log_fatal ("error reading random from system RNG (rc=%d)\n", rc); } } /* --- Public Functions --- */ /* 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_rngsystem_initialize (int full) { basic_initialization (); if (!full) return; /* Nothing more to initialize. */ return; } /* Try to close the FDs of the random gather module. This is currently only implemented for rndlinux. */ void _gcry_rngsystem_close_fds (void) { lock_rng (); #if USE_RNDLINUX _gcry_rndlinux_gather_random (NULL, 0, 0, 0); #endif unlock_rng (); } /* Print some statistics about the RNG. */ void _gcry_rngsystem_dump_stats (void) { /* Not yet implemented. */ } /* This function returns true if no real RNG is available or the quality of the RNG has been degraded for test purposes. */ int _gcry_rngsystem_is_faked (void) { return 0; /* Faked random is not supported. */ } /* 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_rngsystem_add_bytes (const void *buf, size_t buflen, int quality) { (void)buf; (void)buflen; (void)quality; return 0; /* Not implemented. */ } /* Public function to fill the buffer with LENGTH bytes of cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is here mapped to GCRY_STRONG_RANDOM, 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_rngsystem_randomize (void *buffer, size_t length, enum gcry_random_level level) { _gcry_rngsystem_initialize (1); /* Auto-initialize if needed. */ if (level != GCRY_VERY_STRONG_RANDOM) level = GCRY_STRONG_RANDOM; lock_rng (); get_random (buffer, length, level); unlock_rng (); } diff --git a/random/random.c b/random/random.c index ff9d6d25..41d4cb36 100644 --- a/random/random.c +++ b/random/random.c @@ -1,559 +1,546 @@ /* 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(). */ -#include "ath.h" /* 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. */ -static ath_mutex_t nonce_buffer_lock; +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) { - static int nonce_initialized; - int err; - - if (!nonce_initialized) - { - nonce_initialized = 1; - err = ath_mutex_init (&nonce_buffer_lock); - if (err) - log_fatal ("failed to create the nonce buffer lock: %s\n", - strerror (err) ); - } - if (fips_mode ()) _gcry_rngfips_initialize (full); else if (rng_types.standard) _gcry_rngcsprng_initialize (full); else if (rng_types.fips) _gcry_rngfips_initialize (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 (); else if (rng_types.standard) _gcry_rngcsprng_close_fds (); else if (rng_types.fips) _gcry_rngfips_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 (); 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 (); 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); else if (rng_types.standard) _gcry_rngcsprng_randomize (buffer, length, level); else if (rng_types.fips) _gcry_rngfips_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); 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 = ath_mutex_lock (&nonce_buffer_lock); + err = gpgrt_lock_lock (&nonce_buffer_lock); if (err) log_fatal ("failed to acquire the nonce buffer lock: %s\n", - strerror (err)); + 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 = ath_mutex_unlock (&nonce_buffer_lock); + err = gpgrt_lock_unlock (&nonce_buffer_lock); if (err) log_fatal ("failed to release the nonce buffer lock: %s\n", - strerror (err)); + 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); 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/src/Makefile.am b/src/Makefile.am index c0202395..b764852b 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,158 +1,157 @@ # Makefile.am - for gcrypt/src # Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, # 2006, 2007 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 General Public License # along with this program; if not, see . ## Process this file with automake to produce Makefile.in EXTRA_DIST = Manifest libgcrypt-config.in libgcrypt.m4 libgcrypt.vers \ gcrypt.h.in libgcrypt.def bin_SCRIPTS = libgcrypt-config m4datadir = $(datadir)/aclocal m4data_DATA = libgcrypt.m4 include_HEADERS = gcrypt.h lib_LTLIBRARIES = libgcrypt.la bin_PROGRAMS = dumpsexp hmac256 mpicalc if USE_RANDOM_DAEMON sbin_PROGRAMS = gcryptrnd bin_PROGRAMS += getrandom endif USE_RANDOM_DAEMON # Depending on the architecture some targets require libgpg-error. if HAVE_W32CE_SYSTEM arch_gpg_error_cflags = $(GPG_ERROR_CFLAGS) arch_gpg_error_libs = $(GPG_ERROR_LIBS) else arch_gpg_error_cflags = arch_gpg_error_libs = endif AM_CFLAGS = $(GPG_ERROR_CFLAGS) AM_CCASFLAGS = $(NOEXECSTACK_FLAGS) if HAVE_LD_VERSION_SCRIPT libgcrypt_version_script_cmd = -Wl,--version-script=$(srcdir)/libgcrypt.vers else libgcrypt_version_script_cmd = endif libgcrypt_la_CFLAGS = $(GPG_ERROR_CFLAGS) libgcrypt_la_SOURCES = \ gcrypt-int.h g10lib.h visibility.c visibility.h types.h \ cipher.h cipher-proto.h \ misc.c global.c sexp.c hwfeatures.c hwf-common.h \ stdmem.c stdmem.h secmem.c secmem.h \ mpi.h missing-string.c fips.c \ hmac256.c hmac256.h context.c context.h \ - ec-context.h \ - ath.h ath.c + ec-context.h EXTRA_libgcrypt_la_SOURCES = hwf-x86.c hwf-arm.c gcrypt_hwf_modules = @GCRYPT_HWF_MODULES@ if HAVE_W32_SYSTEM RCCOMPILE = $(RC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(libgcrypt_la_CPPFLAGS) $(AM_CPPFLAGS) $(CPPFLAGS) LTRCCOMPILE = $(LIBTOOL) --mode=compile --tag=RC $(RCCOMPILE) SUFFIXES = .rc .lo .rc.lo: $(LTRCCOMPILE) -i "$<" -o "$@" gcrypt_res = versioninfo.lo no_undefined = -no-undefined export_symbols = -export-symbols $(srcdir)/libgcrypt.def install-def-file: -$(INSTALL) -d $(DESTDIR)$(libdir) $(INSTALL) $(srcdir)/libgcrypt.def $(DESTDIR)$(libdir)/libgcrypt.def uninstall-def-file: -rm $(DESTDIR)$(libdir)/libgcrypt.def gcrypt_deps = $(gcrypt_res) libgcrypt.def else !HAVE_W32_SYSTEM gcrypt_res = gcrypt_res_ldflag = no_undefined = export_symbols = install-def-file: uninstall-def-file: gcrypt_deps = endif !HAVE_W32_SYSTEM libgcrypt_la_LDFLAGS = $(no_undefined) $(export_symbols) \ $(libgcrypt_version_script_cmd) -version-info \ @LIBGCRYPT_LT_CURRENT@:@LIBGCRYPT_LT_REVISION@:@LIBGCRYPT_LT_AGE@ libgcrypt_la_DEPENDENCIES = \ $(gcrypt_hwf_modules) \ ../cipher/libcipher.la \ ../random/librandom.la \ ../mpi/libmpi.la \ ../compat/libcompat.la \ $(srcdir)/libgcrypt.vers $(gcrypt_deps) libgcrypt_la_LIBADD = $(gcrypt_res) \ $(gcrypt_hwf_modules) \ ../cipher/libcipher.la \ ../random/librandom.la \ ../mpi/libmpi.la \ ../compat/libcompat.la $(GPG_ERROR_LIBS) dumpsexp_SOURCES = dumpsexp.c dumpsexp_CFLAGS = $(arch_gpg_error_cflags) dumpsexp_LDADD = $(arch_gpg_error_libs) mpicalc_SOURCES = mpicalc.c mpicalc_CFLAGS = $(GPG_ERROR_CFLAGS) mpicalc_LDADD = libgcrypt.la $(GPG_ERROR_LIBS) hmac256_SOURCES = hmac256.c hmac256_CFLAGS = -DSTANDALONE $(arch_gpg_error_cflags) hmac256_LDADD = $(arch_gpg_error_libs) if USE_RANDOM_DAEMON gcryptrnd_SOURCES = gcryptrnd.c gcryptrnd_CFLAGS = $(GPG_ERROR_CFLAGS) $(PTH_CFLAGS) gcryptrnd_LDADD = libgcrypt.la $(GPG_ERROR_LIBS) $(PTH_LIBS) getrandom_SOURCES = getrandom.c endif USE_RANDOM_DAEMON install-data-local: install-def-file uninstall-local: uninstall-def-file # FIXME: We need to figure out how to get the actual name (parsing # libgcrypt.la?) and how to create the hmac file already at link time # so that it can be used without installing libgcrypt first. #install-exec-hook: # ./hmac256 "What am I, a doctor or a moonshuttle conductor?" \ # < $(DESTDIR)$(libdir)/libgcrypt.so.11.5.0 \ # > $(DESTDIR)$(libdir)/.libgcrypt.so.11.5.0.hmac diff --git a/src/ath.c b/src/ath.c deleted file mode 100644 index 7a7035d4..00000000 --- a/src/ath.c +++ /dev/null @@ -1,333 +0,0 @@ -/* ath.c - A Thread-safeness library. - * Copyright (C) 2002, 2003, 2004, 2011 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 . - */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#include -#include -#if USE_POSIX_THREADS_WEAK -# include -#endif - -#include "ath.h" - - - -/* On an ELF system it is easy to use pthreads using weak references. - Take care not to test the address of a weak referenced function we - actually use; some GCC versions have a bug were &foo != NULL is - always evaluated to true in PIC mode. USING_PTHREAD_AS_DEFAULT is - used by ath_install to detect the default usage of pthread. */ -#if USE_POSIX_THREADS_WEAK -# pragma weak pthread_cancel -# pragma weak pthread_mutex_init -# pragma weak pthread_mutex_lock -# pragma weak pthread_mutex_unlock -# pragma weak pthread_mutex_destroy -#endif - -/* For the dummy interface. The MUTEX_NOTINIT value is used to check - that a mutex has been initialized. */ -#define MUTEX_NOTINIT ((ath_mutex_t) 0) -#define MUTEX_UNLOCKED ((ath_mutex_t) 1) -#define MUTEX_LOCKED ((ath_mutex_t) 2) -#define MUTEX_DESTROYED ((ath_mutex_t) 3) - - -/* Return the thread type from the option field. */ -#define GET_OPTION(a) ((a) & 0xff) - - - -enum ath_thread_model { - ath_model_undefined = 0, - ath_model_none, /* No thread support. */ - ath_model_pthreads_weak, /* POSIX threads using weak symbols. */ - ath_model_pthreads, /* POSIX threads directly linked. */ - ath_model_w32 /* Microsoft Windows threads. */ -}; - - -/* The thread model in use. */ -static enum ath_thread_model thread_model; - - -/* Initialize the ath subsystem. This is called as part of the - Libgcrypt initialization. It's purpose is to initialize the - locking system. It returns 0 on sucess or an ERRNO value on error. - In the latter case it is not defined whether ERRNO was changed. - - Note: This should be called as early as possible because it is not - always possible to detect the thread model to use while already - running multi threaded. */ -int -ath_init (void) -{ - int err = 0; - - if (thread_model) - return 0; /* Already initialized - no error. */ - - if (0) - ; -#if USE_POSIX_THREADS_WEAK - else if (pthread_cancel) - { - thread_model = ath_model_pthreads_weak; - } -#endif - else - { - /* Assume a single threaded application. */ - thread_model = ath_model_none; - } - - return err; -} - - -/* Return the used thread model as string for display purposes an if - R_MODEL is not null store its internal number at R_MODEL. */ -const char * -ath_get_model (int *r_model) -{ - if (r_model) - *r_model = thread_model; - switch (thread_model) - { - case ath_model_undefined: return "undefined"; - case ath_model_none: return "none"; - case ath_model_pthreads_weak: return "pthread(weak)"; - case ath_model_pthreads: return "pthread"; - case ath_model_w32: return "w32"; - default: return "?"; - } -} - - -/* This function was used in old Libgcrypt versions (via - GCRYCTL_SET_THREAD_CBS) to register the thread callback functions. - It is not anymore required. However to allow existing code to - continue to work, we keep this function and check that no user - defined callbacks are used and that the requested thread system - matches the one Libgcrypt is using. */ -gpg_err_code_t -ath_install (struct ath_ops *ath_ops) -{ - gpg_err_code_t rc; - unsigned int thread_option; - - /* Fist call ath_init so that we know our thread model. */ - rc = ath_init (); - if (rc) - return rc; - - /* Check if the requested thread option is compatible to the - thread option we are already committed to. */ - thread_option = ath_ops? GET_OPTION (ath_ops->option) : 0; - - /* Return an error if the requested thread model does not match the - configured one. */ - if (0) - ; -#if USE_POSIX_THREADS_WEAK - else if (thread_model == ath_model_pthreads_weak) - { - if (thread_option == ATH_THREAD_OPTION_PTHREAD) - return 0; /* Okay - compatible. */ - if (thread_option == ATH_THREAD_OPTION_PTH) - return 0; /* Okay - compatible. */ - } -#endif /*USE_POSIX_THREADS_WEAK*/ - else if (thread_option == ATH_THREAD_OPTION_PTH) - { - if (thread_model == ath_model_none) - return 0; /* Okay - compatible. */ - } - else if (thread_option == ATH_THREAD_OPTION_DEFAULT) - return 0; /* No thread support requested. */ - - return GPG_ERR_NOT_SUPPORTED; -} - - -/* Initialize a new mutex. This function returns 0 on success or an - system error code (i.e. an ERRNO value). ERRNO may or may not be - changed on error. */ -int -ath_mutex_init (ath_mutex_t *lock) -{ - int err; - - switch (thread_model) - { - case ath_model_none: - *lock = MUTEX_UNLOCKED; - err = 0; - break; - -#if USE_POSIX_THREADS_WEAK - case ath_model_pthreads_weak: - { - pthread_mutex_t *plck; - - plck = malloc (sizeof *plck); - if (!plck) - err = errno? errno : ENOMEM; - else - { - err = pthread_mutex_init (plck, NULL); - if (err) - free (plck); - else - *lock = (void*)plck; - } - } - break; -#endif /*USE_POSIX_THREADS_WEAK*/ - - default: - err = EINVAL; - break; - } - - return err; -} - - -/* Destroy a mutex. This function is a NOP if LOCK is NULL. If the - mutex is still locked it can't be destroyed and the function - returns EBUSY. ERRNO may or may not be changed on error. */ -int -ath_mutex_destroy (ath_mutex_t *lock) -{ - int err; - - if (!*lock) - return 0; - - switch (thread_model) - { - case ath_model_none: - if (*lock != MUTEX_UNLOCKED) - err = EBUSY; - else - { - *lock = MUTEX_DESTROYED; - err = 0; - } - break; - -#if USE_POSIX_THREADS_WEAK - case ath_model_pthreads_weak: - { - pthread_mutex_t *plck = (pthread_mutex_t*) (*lock); - - err = pthread_mutex_destroy (plck); - if (!err) - { - free (plck); - lock = NULL; - } - } - break; -#endif /*USE_POSIX_THREADS_WEAK*/ - - default: - err = EINVAL; - break; - } - - return err; -} - - -/* Lock the mutex LOCK. On success the function returns 0; on error - an error code. ERRNO may or may not be changed on error. */ -int -ath_mutex_lock (ath_mutex_t *lock) -{ - int err; - - switch (thread_model) - { - case ath_model_none: - if (*lock == MUTEX_NOTINIT) - err = EINVAL; - else if (*lock == MUTEX_UNLOCKED) - { - *lock = MUTEX_LOCKED; - err = 0; - } - else - err = EDEADLK; - break; - -#if USE_POSIX_THREADS_WEAK - case ath_model_pthreads_weak: - err = pthread_mutex_lock ((pthread_mutex_t*)(*lock)); - break; -#endif /*USE_POSIX_THREADS_WEAK*/ - - default: - err = EINVAL; - break; - } - - return err; -} - -/* Unlock the mutex LOCK. On success the function returns 0; on error - an error code. ERRNO may or may not be changed on error. */ -int -ath_mutex_unlock (ath_mutex_t *lock) -{ - int err; - - switch (thread_model) - { - case ath_model_none: - if (*lock == MUTEX_NOTINIT) - err = EINVAL; - else if (*lock == MUTEX_LOCKED) - { - *lock = MUTEX_UNLOCKED; - err = 0; - } - else - err = EPERM; - break; - -#if USE_POSIX_THREADS_WEAK - case ath_model_pthreads_weak: - err = pthread_mutex_unlock ((pthread_mutex_t*)(*lock)); - break; -#endif /*USE_POSIX_THREADS_WEAK*/ - - default: - err = EINVAL; - break; - } - - return err; -} diff --git a/src/ath.h b/src/ath.h deleted file mode 100644 index a132e0b7..00000000 --- a/src/ath.h +++ /dev/null @@ -1,93 +0,0 @@ -/* ath.h - Thread-safeness library. - * Copyright (C) 2002, 2003, 2004, 2011 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 ATH_H -#define ATH_H - -#include - -#ifdef _WIN32 -# include -# include -#else /* !_WIN32 */ -# ifdef HAVE_SYS_SELECT_H -# include -# else -# include -# endif -# include -# ifdef HAVE_SYS_MSG_H -# include /* (e.g. for zOS) */ -# endif -# include -#endif /* !_WIN32 */ -#include - - - -/* Define _ATH_EXT_SYM_PREFIX if you want to give all external symbols - a prefix. */ -#define _ATH_EXT_SYM_PREFIX _gcry_ - -#ifdef _ATH_EXT_SYM_PREFIX -#define _ATH_PREFIX1(x,y) x ## y -#define _ATH_PREFIX2(x,y) _ATH_PREFIX1(x,y) -#define _ATH_PREFIX(x) _ATH_PREFIX2(_ATH_EXT_SYM_PREFIX,x) -#define ath_install _ATH_PREFIX(ath_install) -#define ath_init _ATH_PREFIX(ath_init) -#define ath_get_model _ATH_PREFIX(ath_get_model) -#define ath_mutex_init _ATH_PREFIX(ath_mutex_init) -#define ath_mutex_destroy _ATH_PREFIX(ath_mutex_destroy) -#define ath_mutex_lock _ATH_PREFIX(ath_mutex_lock) -#define ath_mutex_unlock _ATH_PREFIX(ath_mutex_unlock) -#endif - - -enum ath_thread_option - { - ATH_THREAD_OPTION_DEFAULT = 0, - ATH_THREAD_OPTION_USER = 1, - ATH_THREAD_OPTION_PTH = 2, - ATH_THREAD_OPTION_PTHREAD = 3 - }; - -struct ath_ops -{ - /* 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; - -}; - -gpg_err_code_t ath_install (struct ath_ops *ath_ops); -int ath_init (void); -const char *ath_get_model (int *r_model); - -/* Functions for mutual exclusion. */ -typedef void *ath_mutex_t; - -int ath_mutex_init (ath_mutex_t *mutex); -int ath_mutex_destroy (ath_mutex_t *mutex); -int ath_mutex_lock (ath_mutex_t *mutex); -int ath_mutex_unlock (ath_mutex_t *mutex); - -#endif /* ATH_H */ diff --git a/src/fips.c b/src/fips.c index 3ab33f93..c90e4b69 100644 --- a/src/fips.c +++ b/src/fips.c @@ -1,860 +1,859 @@ /* fips.c - FIPS mode management * 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 . */ #include #include #include #include #include #include #ifdef ENABLE_HMAC_BINARY_CHECK # include #endif #ifdef HAVE_SYSLOG # include #endif /*HAVE_SYSLOG*/ #include "g10lib.h" -#include "ath.h" #include "cipher-proto.h" #include "hmac256.h" /* The name of the file used to force libgcrypt into fips mode. */ #define FIPS_FORCE_FILE "/etc/gcrypt/fips_enabled" /* The states of the finite state machine used in fips mode. */ enum module_states { /* POWEROFF cannot be represented. */ STATE_POWERON = 0, STATE_INIT, STATE_SELFTEST, STATE_OPERATIONAL, STATE_ERROR, STATE_FATALERROR, STATE_SHUTDOWN }; /* Flag telling whether we are in fips mode. It uses inverse logic so that fips mode is the default unless changed by the initialization code. To check whether fips mode is enabled, use the function fips_mode()! */ static int no_fips_mode_required; /* Flag to indicate that we are in the enforced FIPS mode. */ static int enforced_fips_mode; /* If this flag is set, the application may no longer assume that the process is running in FIPS mode. This flag is protected by the FSM_LOCK. */ static int inactive_fips_mode; /* This is the lock we use to protect the FSM. */ -static ath_mutex_t fsm_lock; +GPGRT_LOCK_DEFINE (fsm_lock); /* The current state of the FSM. The whole state machinery is only used while in fips mode. Change this only while holding fsm_lock. */ static enum module_states current_state; static void fips_new_state (enum module_states new_state); /* Convert lowercase hex digits; assumes valid hex digits. */ #define loxtoi_1(p) (*(p) <= '9'? (*(p)- '0'): (*(p)-'a'+10)) #define loxtoi_2(p) ((loxtoi_1(p) * 16) + loxtoi_1((p)+1)) /* Returns true if P points to a lowercase hex digit. */ #define loxdigit_p(p) !!strchr ("01234567890abcdef", *(p)) /* Check whether the OS is in FIPS mode and record that in a module local variable. If FORCE is passed as true, fips mode will be enabled anyway. Note: This function is not thread-safe and should be called before any threads are created. This function may only be called once. */ void _gcry_initialize_fips_mode (int force) { static int done; gpg_error_t err; /* Make sure we are not accidently called twice. */ if (done) { if ( fips_mode () ) { fips_new_state (STATE_FATALERROR); fips_noreturn (); } /* If not in fips mode an assert is sufficient. */ gcry_assert (!done); } done = 1; /* If the calling application explicitly requested fipsmode, do so. */ if (force) { gcry_assert (!no_fips_mode_required); goto leave; } /* For testing the system it is useful to override the system provided detection of the FIPS mode and force FIPS mode using a file. The filename is hardwired so that there won't be any confusion on whether /etc/gcrypt/ or /usr/local/etc/gcrypt/ is actually used. The file itself may be empty. */ if ( !access (FIPS_FORCE_FILE, F_OK) ) { gcry_assert (!no_fips_mode_required); goto leave; } /* Checking based on /proc file properties. */ { static const char procfname[] = "/proc/sys/crypto/fips_enabled"; FILE *fp; int saved_errno; fp = fopen (procfname, "r"); if (fp) { char line[256]; if (fgets (line, sizeof line, fp) && atoi (line)) { /* System is in fips mode. */ fclose (fp); gcry_assert (!no_fips_mode_required); goto leave; } fclose (fp); } else if ((saved_errno = errno) != ENOENT && saved_errno != EACCES && !access ("/proc/version", F_OK) ) { /* Problem reading the fips file despite that we have the proc file system. We better stop right away. */ log_info ("FATAL: error reading `%s' in libgcrypt: %s\n", procfname, strerror (saved_errno)); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "reading `%s' failed: %s - abort", procfname, strerror (saved_errno)); #endif /*HAVE_SYSLOG*/ abort (); } } /* Fips not not requested, set flag. */ no_fips_mode_required = 1; leave: if (!no_fips_mode_required) { /* Yes, we are in FIPS mode. */ FILE *fp; /* Intitialize the lock to protect the FSM. */ - err = ath_mutex_init (&fsm_lock); + err = gpgrt_lock_init (&fsm_lock); if (err) { /* If that fails we can't do anything but abort the process. We need to use log_info so that the FSM won't get involved. */ log_info ("FATAL: failed to create the FSM lock in libgcrypt: %s\n", - strerror (err)); + gpg_strerror (err)); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "creating FSM lock failed: %s - abort", - strerror (err)); + gpg_strerror (err)); #endif /*HAVE_SYSLOG*/ abort (); } /* If the FIPS force files exists, is readable and has a number != 0 on its first line, we enable the enforced fips mode. */ fp = fopen (FIPS_FORCE_FILE, "r"); if (fp) { char line[256]; if (fgets (line, sizeof line, fp) && atoi (line)) enforced_fips_mode = 1; fclose (fp); } /* Now get us into the INIT state. */ fips_new_state (STATE_INIT); } return; } static void lock_fsm (void) { gpg_error_t err; - err = ath_mutex_lock (&fsm_lock); + err = gpgrt_lock_lock (&fsm_lock); if (err) { log_info ("FATAL: failed to acquire the FSM lock in libgrypt: %s\n", - strerror (err)); + gpg_strerror (err)); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "acquiring FSM lock failed: %s - abort", - strerror (err)); + gpg_strerror (err)); #endif /*HAVE_SYSLOG*/ abort (); } } static void unlock_fsm (void) { gpg_error_t err; - err = ath_mutex_unlock (&fsm_lock); + err = gpgrt_lock_unlock (&fsm_lock); if (err) { log_info ("FATAL: failed to release the FSM lock in libgrypt: %s\n", - strerror (err)); + gpg_strerror (err)); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "releasing FSM lock failed: %s - abort", - strerror (err)); + gpg_strerror (err)); #endif /*HAVE_SYSLOG*/ abort (); } } /* This function returns true if fips mode is enabled. This is independent of the fips required finite state machine and only used to enable fips specific code. Please use the fips_mode macro instead of calling this function directly. */ int _gcry_fips_mode (void) { /* No locking is required because we have the requirement that this variable is only initialized once with no other threads existing. */ return !no_fips_mode_required; } /* Return a flag telling whether we are in the enforced fips mode. */ int _gcry_enforced_fips_mode (void) { if (!_gcry_fips_mode ()) return 0; return enforced_fips_mode; } /* Set a flag telling whether we are in the enforced fips mode. */ void _gcry_set_enforced_fips_mode (void) { enforced_fips_mode = 1; } /* If we do not want to enforce the fips mode, we can set a flag so that the application may check whether it is still in fips mode. TEXT will be printed as part of a syslog message. This function may only be be called if in fips mode. */ void _gcry_inactivate_fips_mode (const char *text) { gcry_assert (_gcry_fips_mode ()); if (_gcry_enforced_fips_mode () ) { /* Get us into the error state. */ fips_signal_error (text); return; } lock_fsm (); if (!inactive_fips_mode) { inactive_fips_mode = 1; unlock_fsm (); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_WARNING, "Libgcrypt warning: " "%s - FIPS mode inactivated", text); #endif /*HAVE_SYSLOG*/ } else unlock_fsm (); } /* Return the FIPS mode inactive flag. If it is true the FIPS mode is not anymore active. */ int _gcry_is_fips_mode_inactive (void) { int flag; if (!_gcry_fips_mode ()) return 0; lock_fsm (); flag = inactive_fips_mode; unlock_fsm (); return flag; } static const char * state2str (enum module_states state) { const char *s; switch (state) { case STATE_POWERON: s = "Power-On"; break; case STATE_INIT: s = "Init"; break; case STATE_SELFTEST: s = "Self-Test"; break; case STATE_OPERATIONAL: s = "Operational"; break; case STATE_ERROR: s = "Error"; break; case STATE_FATALERROR: s = "Fatal-Error"; break; case STATE_SHUTDOWN: s = "Shutdown"; break; default: s = "?"; break; } return s; } /* Return true if the library is in the operational state. */ int _gcry_fips_is_operational (void) { int result; if (!fips_mode ()) result = 1; else { lock_fsm (); if (current_state == STATE_INIT) { /* If we are still in the INIT state, we need to run the selftests so that the FSM can eventually get into operational state. Given that we would need a 2-phase initialization of libgcrypt, but that has traditionally not been enforced, we use this on demand self-test checking. Note that Proper applications would do the application specific libgcrypt initialization between a gcry_check_version() and gcry_control (GCRYCTL_INITIALIZATION_FINISHED) where the latter will run the selftests. The drawback of these on-demand self-tests are a small chance that self-tests are performed by severeal threads; that is no problem because our FSM make sure that we won't oversee any error. */ unlock_fsm (); _gcry_fips_run_selftests (0); lock_fsm (); } result = (current_state == STATE_OPERATIONAL); unlock_fsm (); } return result; } /* This is test on whether the library is in the operational state. In contrast to _gcry_fips_is_operational this function won't do a state transition on the fly. */ int _gcry_fips_test_operational (void) { int result; if (!fips_mode ()) result = 1; else { lock_fsm (); result = (current_state == STATE_OPERATIONAL); unlock_fsm (); } return result; } /* This is a test on whether the library is in the error or operational state. */ int _gcry_fips_test_error_or_operational (void) { int result; if (!fips_mode ()) result = 1; else { lock_fsm (); result = (current_state == STATE_OPERATIONAL || current_state == STATE_ERROR); unlock_fsm (); } return result; } static void reporter (const char *domain, int algo, const char *what, const char *errtxt) { if (!errtxt && !_gcry_log_verbosity (2)) return; log_info ("libgcrypt selftest: %s %s%s (%d): %s%s%s%s\n", !strcmp (domain, "hmac")? "digest":domain, !strcmp (domain, "hmac")? "HMAC-":"", !strcmp (domain, "cipher")? _gcry_cipher_algo_name (algo) : !strcmp (domain, "digest")? _gcry_md_algo_name (algo) : !strcmp (domain, "hmac")? _gcry_md_algo_name (algo) : !strcmp (domain, "pubkey")? _gcry_pk_algo_name (algo) : "", algo, errtxt? errtxt:"Okay", what?" (":"", what? what:"", what?")":""); } /* Run self-tests for all required cipher algorithms. Return 0 on success. */ static int run_cipher_selftests (int extended) { static int algos[] = { GCRY_CIPHER_3DES, GCRY_CIPHER_AES128, GCRY_CIPHER_AES192, GCRY_CIPHER_AES256, 0 }; int idx; gpg_error_t err; int anyerr = 0; for (idx=0; algos[idx]; idx++) { err = _gcry_cipher_selftest (algos[idx], extended, reporter); reporter ("cipher", algos[idx], NULL, err? gpg_strerror (err):NULL); if (err) anyerr = 1; } return anyerr; } /* Run self-tests for all required hash algorithms. Return 0 on success. */ static int run_digest_selftests (int extended) { static int algos[] = { GCRY_MD_SHA1, GCRY_MD_SHA224, GCRY_MD_SHA256, GCRY_MD_SHA384, GCRY_MD_SHA512, 0 }; int idx; gpg_error_t err; int anyerr = 0; for (idx=0; algos[idx]; idx++) { err = _gcry_md_selftest (algos[idx], extended, reporter); reporter ("digest", algos[idx], NULL, err? gpg_strerror (err):NULL); if (err) anyerr = 1; } return anyerr; } /* Run self-tests for all HMAC algorithms. Return 0 on success. */ static int run_hmac_selftests (int extended) { static int algos[] = { GCRY_MD_SHA1, GCRY_MD_SHA224, GCRY_MD_SHA256, GCRY_MD_SHA384, GCRY_MD_SHA512, 0 }; int idx; gpg_error_t err; int anyerr = 0; for (idx=0; algos[idx]; idx++) { err = _gcry_hmac_selftest (algos[idx], extended, reporter); reporter ("hmac", algos[idx], NULL, err? gpg_strerror (err):NULL); if (err) anyerr = 1; } return anyerr; } /* Run self-tests for all required public key algorithms. Return 0 on success. */ static int run_pubkey_selftests (int extended) { static int algos[] = { GCRY_PK_RSA, GCRY_PK_DSA, /* GCRY_PK_ECC is not enabled in fips mode. */ 0 }; int idx; gpg_error_t err; int anyerr = 0; for (idx=0; algos[idx]; idx++) { err = _gcry_pk_selftest (algos[idx], extended, reporter); reporter ("pubkey", algos[idx], NULL, err? gpg_strerror (err):NULL); if (err) anyerr = 1; } return anyerr; } /* Run self-tests for the random number generator. Returns 0 on success. */ static int run_random_selftests (void) { gpg_error_t err; err = _gcry_random_selftest (reporter); reporter ("random", 0, NULL, err? gpg_strerror (err):NULL); return !!err; } /* Run an integrity check on the binary. Returns 0 on success. */ static int check_binary_integrity (void) { #ifdef ENABLE_HMAC_BINARY_CHECK gpg_error_t err; Dl_info info; unsigned char digest[32]; int dlen; char *fname = NULL; const char key[] = "What am I, a doctor or a moonshuttle conductor?"; if (!dladdr ("gcry_check_version", &info)) err = gpg_error_from_syserror (); else { dlen = _gcry_hmac256_file (digest, sizeof digest, info.dli_fname, key, strlen (key)); if (dlen < 0) err = gpg_error_from_syserror (); else if (dlen != 32) err = gpg_error (GPG_ERR_INTERNAL); else { fname = xtrymalloc (strlen (info.dli_fname) + 1 + 5 + 1 ); if (!fname) err = gpg_error_from_syserror (); else { FILE *fp; char *p; /* Prefix the basename with a dot. */ strcpy (fname, info.dli_fname); p = strrchr (fname, '/'); if (p) p++; else p = fname; memmove (p+1, p, strlen (p)+1); *p = '.'; strcat (fname, ".hmac"); /* Open the file. */ fp = fopen (fname, "r"); if (!fp) err = gpg_error_from_syserror (); else { /* A buffer of 64 bytes plus one for a LF and one to detect garbage. */ unsigned char buffer[64+1+1]; const unsigned char *s; int n; /* The HMAC files consists of lowercase hex digits only with an optional trailing linefeed. Fail if there is any garbage. */ err = gpg_error (GPG_ERR_SELFTEST_FAILED); n = fread (buffer, 1, sizeof buffer, fp); if (n == 64 || (n == 65 && buffer[64] == '\n')) { buffer[64] = 0; for (n=0, s= buffer; n < 32 && loxdigit_p (s) && loxdigit_p (s+1); n++, s += 2) buffer[n] = loxtoi_2 (s); if ( n == 32 && !memcmp (digest, buffer, 32) ) err = 0; } fclose (fp); } } } } reporter ("binary", 0, fname, err? gpg_strerror (err):NULL); #ifdef HAVE_SYSLOG if (err) syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "integrity check using `%s' failed: %s", fname? fname:"[?]", gpg_strerror (err)); #endif /*HAVE_SYSLOG*/ xfree (fname); return !!err; #else return 0; #endif } /* Run the self-tests. If EXTENDED is true, extended versions of the selftest are run, that is more tests than required by FIPS. */ gpg_err_code_t _gcry_fips_run_selftests (int extended) { enum module_states result = STATE_ERROR; gcry_err_code_t ec = GPG_ERR_SELFTEST_FAILED; if (fips_mode ()) fips_new_state (STATE_SELFTEST); if (run_cipher_selftests (extended)) goto leave; if (run_digest_selftests (extended)) goto leave; if (run_hmac_selftests (extended)) goto leave; /* Run random tests before the pubkey tests because the latter require random. */ if (run_random_selftests ()) goto leave; if (run_pubkey_selftests (extended)) goto leave; /* Now check the integrity of the binary. We do this this after having checked the HMAC code. */ if (check_binary_integrity ()) goto leave; /* All selftests passed. */ result = STATE_OPERATIONAL; ec = 0; leave: if (fips_mode ()) fips_new_state (result); return ec; } /* This function is used to tell the FSM about errors in the library. The FSM will be put into an error state. This function should not be called directly but by one of the macros fips_signal_error (description) fips_signal_fatal_error (description) where DESCRIPTION is a string describing the error. */ void _gcry_fips_signal_error (const char *srcfile, int srcline, const char *srcfunc, int is_fatal, const char *description) { if (!fips_mode ()) return; /* Not required. */ /* Set new state before printing an error. */ fips_new_state (is_fatal? STATE_FATALERROR : STATE_ERROR); /* Print error. */ log_info ("%serror in libgcrypt, file %s, line %d%s%s: %s\n", is_fatal? "fatal ":"", srcfile, srcline, srcfunc? ", function ":"", srcfunc? srcfunc:"", description? description : "no description available"); #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: " "%serror in file %s, line %d%s%s: %s", is_fatal? "fatal ":"", srcfile, srcline, srcfunc? ", function ":"", srcfunc? srcfunc:"", description? description : "no description available"); #endif /*HAVE_SYSLOG*/ } /* Perform a state transition to NEW_STATE. If this is an invalid transition, the module will go into a fatal error state. */ static void fips_new_state (enum module_states new_state) { int ok = 0; enum module_states last_state; lock_fsm (); last_state = current_state; switch (current_state) { case STATE_POWERON: if (new_state == STATE_INIT || new_state == STATE_ERROR || new_state == STATE_FATALERROR) ok = 1; break; case STATE_INIT: if (new_state == STATE_SELFTEST || new_state == STATE_ERROR || new_state == STATE_FATALERROR) ok = 1; break; case STATE_SELFTEST: if (new_state == STATE_OPERATIONAL || new_state == STATE_ERROR || new_state == STATE_FATALERROR) ok = 1; break; case STATE_OPERATIONAL: if (new_state == STATE_SHUTDOWN || new_state == STATE_SELFTEST || new_state == STATE_ERROR || new_state == STATE_FATALERROR) ok = 1; break; case STATE_ERROR: if (new_state == STATE_SHUTDOWN || new_state == STATE_ERROR || new_state == STATE_FATALERROR || new_state == STATE_SELFTEST) ok = 1; break; case STATE_FATALERROR: if (new_state == STATE_SHUTDOWN ) ok = 1; break; case STATE_SHUTDOWN: /* We won't see any transition *from* Shutdown because the only allowed new state is Power-Off and that one can't be represented. */ break; } if (ok) { current_state = new_state; } unlock_fsm (); if (!ok || _gcry_log_verbosity (2)) log_info ("libgcrypt state transition %s => %s %s\n", state2str (last_state), state2str (new_state), ok? "granted":"denied"); if (!ok) { /* Invalid state transition. Halting library. */ #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt error: invalid state transition %s => %s", state2str (last_state), state2str (new_state)); #endif /*HAVE_SYSLOG*/ fips_noreturn (); } else if (new_state == STATE_ERROR || new_state == STATE_FATALERROR) { #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_WARNING, "Libgcrypt notice: state transition %s => %s", state2str (last_state), state2str (new_state)); #endif /*HAVE_SYSLOG*/ } } /* This function should be called to ensure that the execution shall not continue. */ void _gcry_fips_noreturn (void) { #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_ERR, "Libgcrypt terminated the application"); #endif /*HAVE_SYSLOG*/ fflush (NULL); abort (); /*NOTREACHED*/ } diff --git a/src/global.c b/src/global.c index 9af499e2..b2b1de6e 100644 --- a/src/global.c +++ b/src/global.c @@ -1,1119 +1,1110 @@ /* 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 g10 Code GmbH + * 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 */ -#include "ath.h" + /**************** * 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; /* 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); - /* Initialize our portable thread/mutex wrapper. */ - err = ath_init (); - if (err) - { - err = gpg_error_from_errno (err); - goto fail; - } - /* 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 ()); - fnc (fp, "threads:%s:\n", ath_get_model (NULL)); 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 accidently 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); - rc = ath_install (va_arg (arg_ptr, void *)); - if (!rc) - global_init (); + 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_error (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); } break; case 59: /* Run external random 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 (); else rc = _gcry_random_run_external_test (ctx, buffer, buflen); } break; case 60: /* Deinit external random test. */ { void *ctx = va_arg (arg_ptr, void *); _gcry_random_deinit_external_test (ctx); } break; case 61: /* RFU */ 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; 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 accidently 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); } diff --git a/src/secmem.c b/src/secmem.c index 2bf7d8c6..cfea9213 100644 --- a/src/secmem.c +++ b/src/secmem.c @@ -1,736 +1,730 @@ /* secmem.c - memory allocation from a secure heap * Copyright (C) 1998, 1999, 2000, 2001, 2002, * 2003, 2007 Free Software Foundation, Inc. * Copyright (C) 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 . */ #include #include #include #include #include #include #include #include #if defined(HAVE_MLOCK) || defined(HAVE_MMAP) #include #include #include #ifdef USE_CAPABILITIES #include #endif #endif -#include "ath.h" #include "g10lib.h" #include "secmem.h" #if defined (MAP_ANON) && ! defined (MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif #define MINIMUM_POOL_SIZE 16384 #define STANDARD_POOL_SIZE 32768 #define DEFAULT_PAGE_SIZE 4096 typedef struct memblock { unsigned size; /* Size of the memory available to the user. */ int flags; /* See below. */ PROPERLY_ALIGNED_TYPE aligned; } memblock_t; /* This flag specifies that the memory block is in use. */ #define MB_FLAG_ACTIVE (1 << 0) /* The pool of secure memory. */ static void *pool; /* Size of POOL in bytes. */ static size_t pool_size; /* True, if the memory pool is ready for use. May be checked in an atexit function. */ static volatile int pool_okay; /* True, if the memory pool is mmapped. */ static volatile int pool_is_mmapped; /* FIXME? */ static int disable_secmem; static int show_warning; static int not_locked; static int no_warning; static int suspend_warning; static int no_mlock; static int no_priv_drop; /* Stats. */ static unsigned int cur_alloced, cur_blocks; /* Lock protecting accesses to the memory pool. */ -static ath_mutex_t secmem_lock; +GPGRT_LOCK_DEFINE (secmem_lock); /* Convenient macros. */ -#define SECMEM_LOCK ath_mutex_lock (&secmem_lock) -#define SECMEM_UNLOCK ath_mutex_unlock (&secmem_lock) +#define SECMEM_LOCK gpgrt_lock_lock (&secmem_lock) +#define SECMEM_UNLOCK gpgrt_lock_unlock (&secmem_lock) /* The size of the memblock structure; this does not include the memory that is available to the user. */ #define BLOCK_HEAD_SIZE \ offsetof (memblock_t, aligned) /* Convert an address into the according memory block structure. */ #define ADDR_TO_BLOCK(addr) \ (memblock_t *) ((char *) addr - BLOCK_HEAD_SIZE) /* Check whether P points into the pool. */ static int ptr_into_pool_p (const void *p) { /* We need to convert pointers to addresses. This is required by C-99 6.5.8 to avoid undefined behaviour. Using size_t is at least only implementation defined. See also http://lists.gnupg.org/pipermail/gcrypt-devel/2007-February/001102.html */ size_t p_addr = (size_t)p; size_t pool_addr = (size_t)pool; return p_addr >= pool_addr && p_addr < pool_addr+pool_size; } /* Update the stats. */ static void stats_update (size_t add, size_t sub) { if (add) { cur_alloced += add; cur_blocks++; } if (sub) { cur_alloced -= sub; cur_blocks--; } } /* Return the block following MB or NULL, if MB is the last block. */ static memblock_t * mb_get_next (memblock_t *mb) { memblock_t *mb_next; mb_next = (memblock_t *) ((char *) mb + BLOCK_HEAD_SIZE + mb->size); if (! ptr_into_pool_p (mb_next)) mb_next = NULL; return mb_next; } /* Return the block preceding MB or NULL, if MB is the first block. */ static memblock_t * mb_get_prev (memblock_t *mb) { memblock_t *mb_prev, *mb_next; if (mb == pool) mb_prev = NULL; else { mb_prev = (memblock_t *) pool; while (1) { mb_next = mb_get_next (mb_prev); if (mb_next == mb) break; else mb_prev = mb_next; } } return mb_prev; } /* If the preceding block of MB and/or the following block of MB exist and are not active, merge them to form a bigger block. */ static void mb_merge (memblock_t *mb) { memblock_t *mb_prev, *mb_next; mb_prev = mb_get_prev (mb); mb_next = mb_get_next (mb); if (mb_prev && (! (mb_prev->flags & MB_FLAG_ACTIVE))) { mb_prev->size += BLOCK_HEAD_SIZE + mb->size; mb = mb_prev; } if (mb_next && (! (mb_next->flags & MB_FLAG_ACTIVE))) mb->size += BLOCK_HEAD_SIZE + mb_next->size; } /* Return a new block, which can hold SIZE bytes. */ static memblock_t * mb_get_new (memblock_t *block, size_t size) { memblock_t *mb, *mb_split; for (mb = block; ptr_into_pool_p (mb); mb = mb_get_next (mb)) if (! (mb->flags & MB_FLAG_ACTIVE) && mb->size >= size) { /* Found a free block. */ mb->flags |= MB_FLAG_ACTIVE; if (mb->size - size > BLOCK_HEAD_SIZE) { /* Split block. */ mb_split = (memblock_t *) (((char *) mb) + BLOCK_HEAD_SIZE + size); mb_split->size = mb->size - size - BLOCK_HEAD_SIZE; mb_split->flags = 0; mb->size = size; mb_merge (mb_split); } break; } if (! ptr_into_pool_p (mb)) { gpg_err_set_errno (ENOMEM); mb = NULL; } return mb; } /* Print a warning message. */ static void print_warn (void) { if (!no_warning) log_info (_("Warning: using insecure memory!\n")); } /* Lock the memory pages into core and drop privileges. */ static void lock_pool (void *p, size_t n) { #if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK) int err; { cap_t cap; cap = cap_from_text ("cap_ipc_lock+ep"); cap_set_proc (cap); cap_free (cap); err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; cap = cap_from_text ("cap_ipc_lock+p"); cap_set_proc (cap); cap_free(cap); } if (err) { if (errno != EPERM #ifdef EAGAIN /* OpenBSD returns this */ && errno != EAGAIN #endif #ifdef ENOSYS /* Some SCOs return this (function not implemented) */ && errno != ENOSYS #endif #ifdef ENOMEM /* Linux might return this. */ && errno != ENOMEM #endif ) log_error ("can't lock memory: %s\n", strerror (err)); show_warning = 1; not_locked = 1; } #elif defined(HAVE_MLOCK) uid_t uid; int err; uid = getuid (); #ifdef HAVE_BROKEN_MLOCK /* Under HP/UX mlock segfaults if called by non-root. Note, we have noch checked whether mlock does really work under AIX where we also detected a broken nlock. Note further, that using plock () is not a good idea under AIX. */ if (uid) { errno = EPERM; err = errno; } else { err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; } #else /* !HAVE_BROKEN_MLOCK */ err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; #endif /* !HAVE_BROKEN_MLOCK */ /* Test whether we are running setuid(0). */ if (uid && ! geteuid ()) { /* Yes, we are. */ if (!no_priv_drop) { /* Check that we really dropped the privs. * Note: setuid(0) should always fail */ if (setuid (uid) || getuid () != geteuid () || !setuid (0)) log_fatal ("failed to reset uid: %s\n", strerror (errno)); } } if (err) { if (errno != EPERM #ifdef EAGAIN /* OpenBSD returns this. */ && errno != EAGAIN #endif #ifdef ENOSYS /* Some SCOs return this (function not implemented). */ && errno != ENOSYS #endif #ifdef ENOMEM /* Linux might return this. */ && errno != ENOMEM #endif ) log_error ("can't lock memory: %s\n", strerror (err)); show_warning = 1; not_locked = 1; } #elif defined ( __QNX__ ) /* QNX does not page at all, so the whole secure memory stuff does * not make much sense. However it is still of use because it * wipes out the memory on a free(). * Therefore it is sufficient to suppress the warning. */ (void)p; (void)n; #elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__) /* It does not make sense to print such a warning, given the fact that * this whole Windows !@#$% and their user base are inherently insecure. */ (void)p; (void)n; #elif defined (__riscos__) /* No virtual memory on RISC OS, so no pages are swapped to disc, * besides we don't have mmap, so we don't use it! ;-) * But don't complain, as explained above. */ (void)p; (void)n; #else (void)p; (void)n; if (!no_mlock) log_info ("Please note that you don't have secure memory on this system\n"); #endif } /* Initialize POOL. */ static void init_pool (size_t n) { size_t pgsize; long int pgsize_val; memblock_t *mb; pool_size = n; if (disable_secmem) log_bug ("secure memory is disabled"); #if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE) pgsize_val = sysconf (_SC_PAGESIZE); #elif defined(HAVE_GETPAGESIZE) pgsize_val = getpagesize (); #else pgsize_val = -1; #endif pgsize = (pgsize_val != -1 && pgsize_val > 0)? pgsize_val:DEFAULT_PAGE_SIZE; #if HAVE_MMAP pool_size = (pool_size + pgsize - 1) & ~(pgsize - 1); #ifdef MAP_ANONYMOUS pool = mmap (0, pool_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #else /* map /dev/zero instead */ { int fd; fd = open ("/dev/zero", O_RDWR); if (fd == -1) { log_error ("can't open /dev/zero: %s\n", strerror (errno)); pool = (void *) -1; } else { pool = mmap (0, pool_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); close (fd); } } #endif if (pool == (void *) -1) log_info ("can't mmap pool of %u bytes: %s - using malloc\n", (unsigned) pool_size, strerror (errno)); else { pool_is_mmapped = 1; pool_okay = 1; } #endif if (!pool_okay) { pool = malloc (pool_size); if (!pool) log_fatal ("can't allocate memory pool of %u bytes\n", (unsigned) pool_size); else pool_okay = 1; } /* Initialize first memory block. */ mb = (memblock_t *) pool; mb->size = pool_size; mb->flags = 0; } void _gcry_secmem_set_flags (unsigned flags) { int was_susp; SECMEM_LOCK; was_susp = suspend_warning; no_warning = flags & GCRY_SECMEM_FLAG_NO_WARNING; suspend_warning = flags & GCRY_SECMEM_FLAG_SUSPEND_WARNING; no_mlock = flags & GCRY_SECMEM_FLAG_NO_MLOCK; no_priv_drop = flags & GCRY_SECMEM_FLAG_NO_PRIV_DROP; /* and now issue the warning if it is not longer suspended */ if (was_susp && !suspend_warning && show_warning) { show_warning = 0; print_warn (); } SECMEM_UNLOCK; } unsigned int _gcry_secmem_get_flags (void) { unsigned flags; SECMEM_LOCK; flags = no_warning ? GCRY_SECMEM_FLAG_NO_WARNING : 0; flags |= suspend_warning ? GCRY_SECMEM_FLAG_SUSPEND_WARNING : 0; flags |= not_locked ? GCRY_SECMEM_FLAG_NOT_LOCKED : 0; flags |= no_mlock ? GCRY_SECMEM_FLAG_NO_MLOCK : 0; flags |= no_priv_drop ? GCRY_SECMEM_FLAG_NO_PRIV_DROP : 0; SECMEM_UNLOCK; return flags; } /* See _gcry_secmem_init. This function is expected to be called with the secmem lock held. */ static void secmem_init (size_t n) { if (!n) { #ifdef USE_CAPABILITIES /* drop all capabilities */ { cap_t cap; cap = cap_from_text ("all-eip"); cap_set_proc (cap); cap_free (cap); } #elif !defined(HAVE_DOSISH_SYSTEM) uid_t uid; disable_secmem = 1; uid = getuid (); if (uid != geteuid ()) { if (setuid (uid) || getuid () != geteuid () || !setuid (0)) log_fatal ("failed to drop setuid\n"); } #endif } else { if (n < MINIMUM_POOL_SIZE) n = MINIMUM_POOL_SIZE; if (! pool_okay) { init_pool (n); lock_pool (pool, n); } else log_error ("Oops, secure memory pool already initialized\n"); } } /* Initialize the secure memory system. If running with the necessary privileges, the secure memory pool will be locked into the core in order to prevent page-outs of the data. Furthermore allocated secure memory will be wiped out when released. */ void _gcry_secmem_init (size_t n) { SECMEM_LOCK; secmem_init (n); SECMEM_UNLOCK; } gcry_err_code_t _gcry_secmem_module_init () { - int err; - - err = ath_mutex_init (&secmem_lock); - if (err) - log_fatal ("could not allocate secmem lock\n"); - + /* No anymore needed. */ return 0; } static void * _gcry_secmem_malloc_internal (size_t size) { memblock_t *mb; if (!pool_okay) { /* Try to initialize the pool if the user forgot about it. */ secmem_init (STANDARD_POOL_SIZE); if (!pool_okay) { log_info (_("operation is not possible without " "initialized secure memory\n")); gpg_err_set_errno (ENOMEM); return NULL; } } if (not_locked && fips_mode ()) { log_info (_("secure memory pool is not locked while in FIPS mode\n")); gpg_err_set_errno (ENOMEM); return NULL; } if (show_warning && !suspend_warning) { show_warning = 0; print_warn (); } /* Blocks are always a multiple of 32. */ size = ((size + 31) / 32) * 32; mb = mb_get_new ((memblock_t *) pool, size); if (mb) stats_update (size, 0); return mb ? &mb->aligned.c : NULL; } void * _gcry_secmem_malloc (size_t size) { void *p; SECMEM_LOCK; p = _gcry_secmem_malloc_internal (size); SECMEM_UNLOCK; return p; } static void _gcry_secmem_free_internal (void *a) { memblock_t *mb; int size; if (!a) return; mb = ADDR_TO_BLOCK (a); size = mb->size; /* This does not make much sense: probably this memory is held in the * cache. We do it anyway: */ #define MB_WIPE_OUT(byte) \ wipememory2 ((memblock_t *) ((char *) mb + BLOCK_HEAD_SIZE), (byte), size); MB_WIPE_OUT (0xff); MB_WIPE_OUT (0xaa); MB_WIPE_OUT (0x55); MB_WIPE_OUT (0x00); stats_update (0, size); mb->flags &= ~MB_FLAG_ACTIVE; /* Update stats. */ mb_merge (mb); } /* Wipe out and release memory. */ void _gcry_secmem_free (void *a) { SECMEM_LOCK; _gcry_secmem_free_internal (a); SECMEM_UNLOCK; } /* Realloc memory. */ void * _gcry_secmem_realloc (void *p, size_t newsize) { memblock_t *mb; size_t size; void *a; SECMEM_LOCK; mb = (memblock_t *) ((char *) p - ((size_t) &((memblock_t *) 0)->aligned.c)); size = mb->size; if (newsize < size) { /* It is easier to not shrink the memory. */ a = p; } else { a = _gcry_secmem_malloc_internal (newsize); if (a) { memcpy (a, p, size); memset ((char *) a + size, 0, newsize - size); _gcry_secmem_free_internal (p); } } SECMEM_UNLOCK; return a; } /* Return true if P points into the secure memory area. */ int _gcry_private_is_secure (const void *p) { return pool_okay && ptr_into_pool_p (p); } /**************** * Warning: This code might be called by an interrupt handler * and frankly, there should really be such a handler, * to make sure that the memory is wiped out. * We hope that the OS wipes out mlocked memory after * receiving a SIGKILL - it really should do so, otherwise * there is no chance to get the secure memory cleaned. */ void _gcry_secmem_term () { if (!pool_okay) return; wipememory2 (pool, 0xff, pool_size); wipememory2 (pool, 0xaa, pool_size); wipememory2 (pool, 0x55, pool_size); wipememory2 (pool, 0x00, pool_size); #if HAVE_MMAP if (pool_is_mmapped) munmap (pool, pool_size); #endif pool = NULL; pool_okay = 0; pool_size = 0; not_locked = 0; } void _gcry_secmem_dump_stats () { #if 1 SECMEM_LOCK; if (pool_okay) log_info ("secmem usage: %u/%lu bytes in %u blocks\n", cur_alloced, (unsigned long)pool_size, cur_blocks); SECMEM_UNLOCK; #else memblock_t *mb; int i; SECMEM_LOCK; for (i = 0, mb = (memblock_t *) pool; ptr_into_pool_p (mb); mb = mb_get_next (mb), i++) log_info ("SECMEM: [%s] block: %i; size: %i\n", (mb->flags & MB_FLAG_ACTIVE) ? "used" : "free", i, mb->size); SECMEM_UNLOCK; #endif }