diff --git a/mpi/mpiutil.c b/mpi/mpiutil.c index 74fbac37..d5a1b8a8 100644 --- a/mpi/mpiutil.c +++ b/mpi/mpiutil.c @@ -1,802 +1,795 @@ /* mpiutil.ac - Utility functions for MPI * Copyright (C) 1998, 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 "g10lib.h" #include "mpi-internal.h" #include "mod-source-info.h" #if SIZEOF_UNSIGNED_INT == 2 # define MY_UINT_MAX 0xffff /* (visual check: 0123 ) */ #elif SIZEOF_UNSIGNED_INT == 4 # define MY_UINT_MAX 0xffffffff /* (visual check: 01234567 ) */ #elif SIZEOF_UNSIGNED_INT == 8 # define MY_UINT_MAX 0xffffffffffffffff /* (visual check: 0123456789abcdef ) */ #else # error Need MY_UINT_MAX for this limb size #endif /* Constants allocated right away at startup. */ static gcry_mpi_t constants[MPI_NUMBER_OF_CONSTANTS]; /* These variables are used to generate masks from conditional operation * flag parameters. Use of volatile prevents compiler optimizations from * converting AND-masking to conditional branches. */ static volatile mpi_limb_t vzero = 0; static volatile mpi_limb_t vone = 1; const char * _gcry_mpi_get_hw_config (void) { return mod_source_info + 1; } /* Initialize the MPI subsystem. This is called early and allows to do some initialization without taking care of threading issues. */ gcry_err_code_t _gcry_mpi_init (void) { int idx; unsigned long value; for (idx=0; idx < MPI_NUMBER_OF_CONSTANTS; idx++) { switch (idx) { case MPI_C_ZERO: value = 0; break; case MPI_C_ONE: value = 1; break; case MPI_C_TWO: value = 2; break; case MPI_C_THREE: value = 3; break; case MPI_C_FOUR: value = 4; break; case MPI_C_EIGHT: value = 8; break; default: log_bug ("invalid mpi_const selector %d\n", idx); } constants[idx] = mpi_alloc_set_ui (value); constants[idx]->flags = (16|32); } return 0; } /**************** * Note: It was a bad idea to use the number of limbs to allocate * because on a alpha the limbs are large but we normally need * integers of n bits - So we should change this to bits (or bytes). * * But mpi_alloc is used in a lot of places :-(. New code * should use mpi_new. */ gcry_mpi_t _gcry_mpi_alloc( unsigned nlimbs ) { gcry_mpi_t a; a = xmalloc( sizeof *a ); a->d = nlimbs? mpi_alloc_limb_space( nlimbs, 0 ) : NULL; a->alloced = nlimbs; a->nlimbs = 0; a->sign = 0; a->flags = 0; return a; } -void -_gcry_mpi_m_check( gcry_mpi_t a ) -{ - _gcry_check_heap(a); - _gcry_check_heap(a->d); -} - gcry_mpi_t _gcry_mpi_alloc_secure( unsigned nlimbs ) { gcry_mpi_t a; a = xmalloc( sizeof *a ); a->d = nlimbs? mpi_alloc_limb_space( nlimbs, 1 ) : NULL; a->alloced = nlimbs; a->flags = 1; a->nlimbs = 0; a->sign = 0; return a; } mpi_ptr_t _gcry_mpi_alloc_limb_space( unsigned int nlimbs, int secure ) { mpi_ptr_t p; size_t len; len = (nlimbs ? nlimbs : 1) * sizeof (mpi_limb_t); p = secure ? xmalloc_secure (len) : xmalloc (len); if (! nlimbs) *p = 0; return p; } void _gcry_mpi_free_limb_space( mpi_ptr_t a, unsigned int nlimbs) { if (a) { size_t len = nlimbs * sizeof(mpi_limb_t); /* If we have information on the number of allocated limbs, we better wipe that space out. This is a failsafe feature if secure memory has been disabled or was not properly implemented in user provided allocation functions. */ if (len) wipememory (a, len); xfree(a); } } void _gcry_mpi_assign_limb_space( gcry_mpi_t a, mpi_ptr_t ap, unsigned int nlimbs ) { _gcry_mpi_free_limb_space (a->d, a->alloced); a->d = ap; a->alloced = nlimbs; } /**************** * Resize the array of A to NLIMBS. The additional space is cleared * (set to 0). */ void _gcry_mpi_resize (gcry_mpi_t a, unsigned nlimbs) { size_t i; if (nlimbs <= a->alloced) { /* We only need to clear the new space (this is a nop if the limb space is already of the correct size. */ for (i=a->nlimbs; i < a->alloced; i++) a->d[i] = 0; return; } /* Actually resize the limb space. */ if (a->d) { a->d = xrealloc (a->d, nlimbs * sizeof (mpi_limb_t)); for (i=a->nlimbs; i < nlimbs; i++) a->d[i] = 0; } else { if (a->flags & 1) /* Secure memory is wanted. */ a->d = xcalloc_secure (nlimbs , sizeof (mpi_limb_t)); else /* Standard memory. */ a->d = xcalloc (nlimbs , sizeof (mpi_limb_t)); } a->alloced = nlimbs; } void _gcry_mpi_clear( gcry_mpi_t a ) { if (mpi_is_immutable (a)) { mpi_immutable_failed (); return; } a->nlimbs = 0; a->flags = 0; } void _gcry_mpi_free( gcry_mpi_t a ) { if (!a ) return; if ((a->flags & 32)) { #if GPGRT_VERSION_NUMBER >= 0x011600 /* 1.22 */ gpgrt_annotate_leaked_object(a); #endif return; /* Never release a constant. */ } if ((a->flags & 4)) xfree( a->d ); else { _gcry_mpi_free_limb_space(a->d, a->alloced); } /* Check that the flags makes sense. We better allow for bit 1 (value 2) for backward ABI compatibility. */ if ((a->flags & ~(1|2|4|16 |GCRYMPI_FLAG_USER1 |GCRYMPI_FLAG_USER2 |GCRYMPI_FLAG_USER3 |GCRYMPI_FLAG_USER4))) log_bug("invalid flag value in mpi_free\n"); xfree (a); } void _gcry_mpi_immutable_failed (void) { log_info ("Warning: trying to change an immutable MPI\n"); } static void mpi_set_secure( gcry_mpi_t a ) { mpi_ptr_t ap, bp; if ( (a->flags & 1) ) return; a->flags |= 1; ap = a->d; if (!a->nlimbs) { gcry_assert (!ap); return; } bp = mpi_alloc_limb_space (a->alloced, 1); MPN_COPY( bp, ap, a->nlimbs ); a->d = bp; _gcry_mpi_free_limb_space (ap, a->alloced); } gcry_mpi_t _gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits) { if (!a) a = mpi_alloc(0); if (mpi_is_immutable (a)) { mpi_immutable_failed (); return a; } if( a->flags & 4 ) xfree (a->d); else _gcry_mpi_free_limb_space (a->d, a->alloced); a->d = p; a->alloced = 0; a->nlimbs = 0; a->sign = nbits; a->flags = 4 | (a->flags & (GCRYMPI_FLAG_USER1|GCRYMPI_FLAG_USER2 |GCRYMPI_FLAG_USER3|GCRYMPI_FLAG_USER4)); if (_gcry_is_secure (a->d)) a->flags |= 1; return a; } gcry_mpi_t _gcry_mpi_set_opaque_copy (gcry_mpi_t a, const void *p, unsigned int nbits) { void *d; unsigned int n; n = (nbits+7)/8; d = _gcry_is_secure (p)? xtrymalloc_secure (n) : xtrymalloc (n); if (!d) return NULL; memcpy (d, p, n); return mpi_set_opaque (a, d, nbits); } void * _gcry_mpi_get_opaque (gcry_mpi_t a, unsigned int *nbits) { if( !(a->flags & 4) ) log_bug("mpi_get_opaque on normal mpi\n"); if( nbits ) *nbits = a->sign; return a->d; } void * _gcry_mpi_get_opaque_copy (gcry_mpi_t a, unsigned int *nbits) { const void *s; void *d; unsigned int n; s = mpi_get_opaque (a, nbits); if (!s && nbits) return NULL; n = (*nbits+7)/8; d = _gcry_is_secure (s)? xtrymalloc_secure (n) : xtrymalloc (n); if (d) memcpy (d, s, n); return d; } /**************** * Note: This copy function should not interpret the MPI * but copy it transparently. */ gcry_mpi_t _gcry_mpi_copy (gcry_mpi_t a) { int i; gcry_mpi_t b; if( a && (a->flags & 4) ) { void *p = NULL; if (a->sign) { p = _gcry_is_secure(a->d)? xmalloc_secure ((a->sign+7)/8) : xmalloc ((a->sign+7)/8); if (a->d) memcpy( p, a->d, (a->sign+7)/8 ); } b = mpi_set_opaque( NULL, p, a->sign ); b->flags = a->flags; b->flags &= ~(16|32); /* Reset the immutable and constant flags. */ } else if( a ) { b = mpi_is_secure(a)? mpi_alloc_secure( a->nlimbs ) : mpi_alloc( a->nlimbs ); b->nlimbs = a->nlimbs; b->sign = a->sign; b->flags = a->flags; b->flags &= ~(16|32); /* Reset the immutable and constant flags. */ for(i=0; i < b->nlimbs; i++ ) b->d[i] = a->d[i]; } else b = NULL; return b; } /* Return true if A is negative. */ int _gcry_mpi_is_neg (gcry_mpi_t a) { if (a->sign && _gcry_mpi_cmp_ui (a, 0)) return 1; else return 0; } /* W = - U */ void _gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u) { if (w != u) mpi_set (w, u); else if (mpi_is_immutable (w)) { mpi_immutable_failed (); return; } w->sign = !u->sign; } /* W = [W] */ void _gcry_mpi_abs (gcry_mpi_t w) { if (mpi_is_immutable (w)) { mpi_immutable_failed (); return; } w->sign = 0; } /**************** * This function allocates an MPI which is optimized to hold * a value as large as the one given in the argument and allocates it * with the same flags as A. */ gcry_mpi_t _gcry_mpi_alloc_like( gcry_mpi_t a ) { gcry_mpi_t b; if( a && (a->flags & 4) ) { int n = (a->sign+7)/8; void *p = _gcry_is_secure(a->d)? xtrymalloc_secure (n) : xtrymalloc (n); memcpy( p, a->d, n ); b = mpi_set_opaque( NULL, p, a->sign ); } else if( a ) { b = mpi_is_secure(a)? mpi_alloc_secure( a->nlimbs ) : mpi_alloc( a->nlimbs ); b->nlimbs = 0; b->sign = 0; b->flags = a->flags; } else b = NULL; return b; } /* Set U into W and release U. If W is NULL only U will be released. */ void _gcry_mpi_snatch (gcry_mpi_t w, gcry_mpi_t u) { if (w) { if (mpi_is_immutable (w)) { mpi_immutable_failed (); return; } _gcry_mpi_assign_limb_space (w, u->d, u->alloced); w->nlimbs = u->nlimbs; w->sign = u->sign; w->flags = u->flags; u->alloced = 0; u->nlimbs = 0; u->d = NULL; } _gcry_mpi_free (u); } gcry_mpi_t _gcry_mpi_set (gcry_mpi_t w, gcry_mpi_t u) { mpi_ptr_t wp, up; mpi_size_t usize = u->nlimbs; int usign = u->sign; if (!w) w = _gcry_mpi_alloc( mpi_get_nlimbs(u) ); if (mpi_is_immutable (w)) { mpi_immutable_failed (); return w; } RESIZE_IF_NEEDED(w, usize); wp = w->d; up = u->d; MPN_COPY( wp, up, usize ); w->nlimbs = usize; w->flags = u->flags; w->flags &= ~(16|32); /* Reset the immutable and constant flags. */ w->sign = usign; return w; } /**************** * Set the value of W by the one of U, when SET is 1. * Leave the value when SET is 0. * This implementation should be constant-time regardless of SET. */ gcry_mpi_t _gcry_mpi_set_cond (gcry_mpi_t w, const gcry_mpi_t u, unsigned long set) { mpi_size_t i; mpi_size_t nlimbs = u->alloced; mpi_limb_t mask1 = vzero - set; mpi_limb_t mask2 = set - vone; mpi_limb_t xu; mpi_limb_t xw; mpi_limb_t *uu = u->d; mpi_limb_t *uw = w->d; if (w->alloced != u->alloced) log_bug ("mpi_set_cond: different sizes\n"); for (i = 0; i < nlimbs; i++) { xu = uu[i]; xw = uw[i]; uw[i] = (xw & mask2) | (xu & mask1); } xu = u->nlimbs; xw = w->nlimbs; w->nlimbs = (xw & mask2) | (xu & mask1); xu = u->sign; xw = w->sign; w->sign = (xw & mask2) | (xu & mask1); return w; } gcry_mpi_t _gcry_mpi_set_ui (gcry_mpi_t w, unsigned long u) { if (!w) w = _gcry_mpi_alloc (1); /* FIXME: If U is 0 we have no need to resize and thus possible allocating the the limbs. */ if (mpi_is_immutable (w)) { mpi_immutable_failed (); return w; } RESIZE_IF_NEEDED(w, 1); w->d[0] = u; w->nlimbs = u? 1:0; w->sign = 0; w->flags = 0; return w; } /* If U is non-negative and small enough store it as an unsigned int * at W. If the value does not fit into an unsigned int or is * negative return GPG_ERR_ERANGE. Note that we return an unsigned * int so that the value can be used with the bit test functions; in * contrast the other _ui functions take an unsigned long so that on * some platforms they may accept a larger value. On error the value * at W is not changed. */ gcry_err_code_t _gcry_mpi_get_ui (unsigned int *w, gcry_mpi_t u) { mpi_limb_t x; if (u->nlimbs > 1 || u->sign) return GPG_ERR_ERANGE; x = (u->nlimbs == 1) ? u->d[0] : 0; if (sizeof (x) > sizeof (unsigned int) && x > MY_UINT_MAX) return GPG_ERR_ERANGE; *w = x; return 0; } gcry_mpi_t _gcry_mpi_alloc_set_ui( unsigned long u) { gcry_mpi_t w = mpi_alloc(1); w->d[0] = u; w->nlimbs = u? 1:0; w->sign = 0; return w; } void _gcry_mpi_swap (gcry_mpi_t a, gcry_mpi_t b) { struct gcry_mpi tmp; tmp = *a; *a = *b; *b = tmp; } /**************** * Swap the value of A and B, when SWAP is 1. * Leave the value when SWAP is 0. * This implementation should be constant-time regardless of SWAP. */ void _gcry_mpi_swap_cond (gcry_mpi_t a, gcry_mpi_t b, unsigned long swap) { mpi_size_t i; mpi_size_t nlimbs; mpi_limb_t mask1 = vzero - swap; mpi_limb_t mask2 = swap - vone; mpi_limb_t *ua = a->d; mpi_limb_t *ub = b->d; mpi_limb_t xa; mpi_limb_t xb; if (a->alloced > b->alloced) nlimbs = b->alloced; else nlimbs = a->alloced; if (a->nlimbs > nlimbs || b->nlimbs > nlimbs) log_bug ("mpi_swap_cond: different sizes\n"); for (i = 0; i < nlimbs; i++) { xa = ua[i]; xb = ub[i]; ua[i] = (xa & mask2) | (xb & mask1); ub[i] = (xa & mask1) | (xb & mask2); } xa = a->nlimbs; xb = b->nlimbs; a->nlimbs = (xa & mask2) | (xb & mask1); b->nlimbs = (xa & mask1) | (xb & mask2); xa = a->sign; xb = b->sign; a->sign = (xa & mask2) | (xb & mask1); b->sign = (xa & mask1) | (xb & mask2); } /**************** * Set bit N of A, when SET is 1. * This implementation should be constant-time regardless of SET. */ void _gcry_mpi_set_bit_cond (gcry_mpi_t a, unsigned int n, unsigned long set) { unsigned int limbno, bitno; mpi_limb_t set_the_bit = !!set; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; a->d[limbno] |= (set_the_bit<flags |= (16|32); break; case GCRYMPI_FLAG_IMMUTABLE: a->flags |= 16; break; case GCRYMPI_FLAG_USER1: case GCRYMPI_FLAG_USER2: case GCRYMPI_FLAG_USER3: case GCRYMPI_FLAG_USER4: a->flags |= flag; break; case GCRYMPI_FLAG_OPAQUE: default: log_bug("invalid flag value\n"); } } void _gcry_mpi_clear_flag (gcry_mpi_t a, enum gcry_mpi_flag flag) { (void)a; /* Not yet used. */ switch (flag) { case GCRYMPI_FLAG_IMMUTABLE: if (!(a->flags & 32)) a->flags &= ~16; break; case GCRYMPI_FLAG_USER1: case GCRYMPI_FLAG_USER2: case GCRYMPI_FLAG_USER3: case GCRYMPI_FLAG_USER4: a->flags &= ~flag; break; case GCRYMPI_FLAG_CONST: case GCRYMPI_FLAG_SECURE: case GCRYMPI_FLAG_OPAQUE: default: log_bug("invalid flag value\n"); } } int _gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag) { switch (flag) { case GCRYMPI_FLAG_SECURE: return !!(a->flags & 1); case GCRYMPI_FLAG_OPAQUE: return !!(a->flags & 4); case GCRYMPI_FLAG_IMMUTABLE: return !!(a->flags & 16); case GCRYMPI_FLAG_CONST: return !!(a->flags & 32); case GCRYMPI_FLAG_USER1: case GCRYMPI_FLAG_USER2: case GCRYMPI_FLAG_USER3: case GCRYMPI_FLAG_USER4: return !!(a->flags & flag); default: log_bug("invalid flag value\n"); } /*NOTREACHED*/ return 0; } /* Return a constant MPI descripbed by NO which is one of the MPI_C_xxx macros. There is no need to copy this returned value; it may be used directly. */ gcry_mpi_t _gcry_mpi_const (enum gcry_mpi_constants no) { if ((int)no < 0 || no > MPI_NUMBER_OF_CONSTANTS) log_bug("invalid mpi_const selector %d\n", no); if (!constants[no]) log_bug("MPI subsystem not initialized\n"); return constants[no]; } diff --git a/src/g10lib.h b/src/g10lib.h index bfaf509f..22c0f0c2 100644 --- a/src/g10lib.h +++ b/src/g10lib.h @@ -1,481 +1,480 @@ /* g10lib.h - Internal definitions for libgcrypt * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005 * 2007, 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 . */ /* This header is to be used inside of libgcrypt in place of gcrypt.h. This way we can better distinguish between internal and external usage of gcrypt.h. */ #ifndef G10LIB_H #define G10LIB_H 1 #ifdef _GCRYPT_H #error gcrypt.h already included #endif #ifndef _GCRYPT_IN_LIBGCRYPT #error something is wrong with config.h #endif #include #include #include "visibility.h" #include "types.h" /* Attribute handling macros. */ #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) #define JNLIB_GCC_M_FUNCTION 1 #define JNLIB_GCC_A_NR __attribute__ ((noreturn)) #define JNLIB_GCC_A_PRINTF( f, a ) __attribute__ ((format (printf,f,a))) #define JNLIB_GCC_A_NR_PRINTF( f, a ) \ __attribute__ ((noreturn, format (printf,f,a))) #define GCC_ATTR_NORETURN __attribute__ ((__noreturn__)) #else #define JNLIB_GCC_A_NR #define JNLIB_GCC_A_PRINTF( f, a ) #define JNLIB_GCC_A_NR_PRINTF( f, a ) #define GCC_ATTR_NORETURN #endif #if __GNUC__ >= 3 /* According to glibc this attribute is available since 2.8 however we better play safe and use it only with gcc 3 or newer. */ #define GCC_ATTR_FORMAT_ARG(a) __attribute__ ((format_arg (a))) #else #define GCC_ATTR_FORMAT_ARG(a) #endif /* I am not sure since when the unused attribute is really supported. In any case it it only needed for gcc versions which print a warning. Thus let us require gcc >= 3.5. */ #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 5 ) #define GCC_ATTR_UNUSED __attribute__ ((unused)) #else #define GCC_ATTR_UNUSED #endif #if __GNUC__ > 3 #define NOINLINE_FUNC __attribute__((noinline)) #else #define NOINLINE_FUNC #endif #if __GNUC__ >= 3 #define LIKELY(expr) __builtin_expect( !!(expr), 1 ) #define UNLIKELY(expr) __builtin_expect( !!(expr), 0 ) #define CONSTANT_P(expr) __builtin_constant_p( expr ) #else #define LIKELY(expr) (!!(expr)) #define UNLIKELY(expr) (!!(expr)) #define CONSTANT_P(expr) (0) #endif /* Gettext macros. */ #define _(a) _gcry_gettext(a) #define N_(a) (a) /* Some handy macros */ #ifndef STR #define STR(v) #v #endif #define STR2(v) STR(v) #define DIM(v) (sizeof(v)/sizeof((v)[0])) #define DIMof(type,member) DIM(((type *)0)->member) #define my_isascii(c) (!((c) & 0x80)) /*-- src/global.c -*/ extern int _gcry_global_any_init_done; int _gcry_global_is_operational (void); gcry_err_code_t _gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr); -void _gcry_check_heap (const void *a); void _gcry_pre_syscall (void); void _gcry_post_syscall (void); int _gcry_get_debug_flag (unsigned int mask); char *_gcry_get_config (int mode, const char *what); /* Malloc functions and common wrapper macros. */ void *_gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *_gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *_gcry_malloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *_gcry_calloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *_gcry_realloc (void *a, size_t n); char *_gcry_strdup (const char *string) _GCRY_GCC_ATTR_MALLOC; void *_gcry_xmalloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *_gcry_xcalloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *_gcry_xmalloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *_gcry_xcalloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *_gcry_xrealloc (void *a, size_t n); char *_gcry_xstrdup (const char * a) _GCRY_GCC_ATTR_MALLOC; void _gcry_free (void *a); int _gcry_is_secure (const void *a) _GCRY_GCC_ATTR_PURE; #define xtrymalloc(a) _gcry_malloc ((a)) #define xtrycalloc(a,b) _gcry_calloc ((a),(b)) #define xtrymalloc_secure(a) _gcry_malloc_secure ((a)) #define xtrycalloc_secure(a,b) _gcry_calloc_secure ((a),(b)) #define xtryrealloc(a,b) _gcry_realloc ((a),(b)) #define xtrystrdup(a) _gcry_strdup ((a)) #define xmalloc(a) _gcry_xmalloc ((a)) #define xcalloc(a,b) _gcry_xcalloc ((a),(b)) #define xmalloc_secure(a) _gcry_xmalloc_secure ((a)) #define xcalloc_secure(a,b) _gcry_xcalloc_secure ((a),(b)) #define xrealloc(a,b) _gcry_xrealloc ((a),(b)) #define xstrdup(a) _gcry_xstrdup ((a)) #define xfree(a) _gcry_free ((a)) /*-- src/misc.c --*/ #if defined(JNLIB_GCC_M_FUNCTION) || __STDC_VERSION__ >= 199901L void _gcry_bug (const char *file, int line, const char *func) GCC_ATTR_NORETURN; void _gcry_assert_failed (const char *expr, const char *file, int line, const char *func) GCC_ATTR_NORETURN; #else void _gcry_bug (const char *file, int line); void _gcry_assert_failed (const char *expr, const char *file, int line); #endif void _gcry_divide_by_zero (void) JNLIB_GCC_A_NR; const char *_gcry_gettext (const char *key) GCC_ATTR_FORMAT_ARG(1); void _gcry_fatal_error(int rc, const char *text ) JNLIB_GCC_A_NR; void _gcry_logv (int level, const char *fmt, va_list arg_ptr) JNLIB_GCC_A_PRINTF(2,0); void _gcry_log( int level, const char *fmt, ... ) JNLIB_GCC_A_PRINTF(2,3); void _gcry_log_bug( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); void _gcry_log_fatal( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); void _gcry_log_error( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void _gcry_log_info( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void _gcry_log_debug( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void _gcry_log_printf ( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void _gcry_log_printhex (const char *text, const void *buffer, size_t length); void _gcry_log_printmpi (const char *text, gcry_mpi_t mpi); void _gcry_log_printsxp (const char *text, gcry_sexp_t sexp); void _gcry_set_log_verbosity( int level ); int _gcry_log_verbosity( int level ); #ifdef JNLIB_GCC_M_FUNCTION #define BUG() _gcry_bug( __FILE__ , __LINE__, __FUNCTION__ ) #define gcry_assert(expr) (LIKELY(expr)? (void)0 \ : _gcry_assert_failed (STR(expr), __FILE__, __LINE__, __FUNCTION__)) #elif __STDC_VERSION__ >= 199901L #define BUG() _gcry_bug( __FILE__ , __LINE__, __func__ ) #define gcry_assert(expr) (LIKELY(expr)? (void)0 \ : _gcry_assert_failed (STR(expr), __FILE__, __LINE__, __func__)) #else #define BUG() _gcry_bug( __FILE__ , __LINE__ ) #define gcry_assert(expr) (LIKELY(expr)? (void)0 \ : _gcry_assert_failed (STR(expr), __FILE__, __LINE__)) #endif #define log_bug _gcry_log_bug #define log_fatal _gcry_log_fatal #define log_error _gcry_log_error #define log_info _gcry_log_info #define log_debug _gcry_log_debug #define log_printf _gcry_log_printf #define log_printhex _gcry_log_printhex #define log_printmpi _gcry_log_printmpi #define log_printsxp _gcry_log_printsxp /* Compatibility macro. */ #define log_mpidump _gcry_log_printmpi /* Tokeninze STRING and return a malloced array. */ char **_gcry_strtokenize (const char *string, const char *delim); /*-- src/hwfeatures.c --*/ #if defined(HAVE_CPU_ARCH_X86) #define HWF_PADLOCK_RNG (1 << 0) #define HWF_PADLOCK_AES (1 << 1) #define HWF_PADLOCK_SHA (1 << 2) #define HWF_PADLOCK_MMUL (1 << 3) #define HWF_INTEL_CPU (1 << 4) #define HWF_INTEL_FAST_SHLD (1 << 5) #define HWF_INTEL_BMI2 (1 << 6) #define HWF_INTEL_SSSE3 (1 << 7) #define HWF_INTEL_SSE4_1 (1 << 8) #define HWF_INTEL_PCLMUL (1 << 9) #define HWF_INTEL_AESNI (1 << 10) #define HWF_INTEL_RDRAND (1 << 11) #define HWF_INTEL_AVX (1 << 12) #define HWF_INTEL_AVX2 (1 << 13) #define HWF_INTEL_FAST_VPGATHER (1 << 14) #define HWF_INTEL_RDTSC (1 << 15) #define HWF_INTEL_SHAEXT (1 << 16) #define HWF_INTEL_VAES_VPCLMUL (1 << 17) #elif defined(HAVE_CPU_ARCH_ARM) #define HWF_ARM_NEON (1 << 0) #define HWF_ARM_AES (1 << 1) #define HWF_ARM_SHA1 (1 << 2) #define HWF_ARM_SHA2 (1 << 3) #define HWF_ARM_PMULL (1 << 4) #elif defined(HAVE_CPU_ARCH_PPC) #define HWF_PPC_VCRYPTO (1 << 0) #define HWF_PPC_ARCH_3_00 (1 << 1) #define HWF_PPC_ARCH_2_07 (1 << 2) #define HWF_PPC_ARCH_3_10 (1 << 3) #elif defined(HAVE_CPU_ARCH_S390X) #define HWF_S390X_MSA (1 << 0) #define HWF_S390X_MSA_4 (1 << 1) #define HWF_S390X_MSA_8 (1 << 2) #define HWF_S390X_MSA_9 (1 << 3) #define HWF_S390X_VX (1 << 4) #endif gpg_err_code_t _gcry_disable_hw_feature (const char *name); void _gcry_detect_hw_features (void); unsigned int _gcry_get_hw_features (void); const char *_gcry_enum_hw_features (int idx, unsigned int *r_feature); /*-- mpi/mpiutil.c --*/ const char *_gcry_mpi_get_hw_config (void); /*-- cipher/pubkey.c --*/ /* FIXME: shouldn't this go into mpi.h? */ #ifndef mpi_powm #define mpi_powm(w,b,e,m) gcry_mpi_powm( (w), (b), (e), (m) ) #endif /*-- primegen.c --*/ gcry_err_code_t _gcry_primegen_init (void); 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 _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_err_code_t _gcry_generate_elg_prime (int mode, unsigned int pbits, unsigned int qbits, gcry_mpi_t g, gcry_mpi_t *r_prime, gcry_mpi_t **factors); 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); 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 _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 _gcry_fips186_4_prime_check (const gcry_mpi_t x, unsigned int bits); /* Replacements of missing functions (missing-string.c). */ #ifndef HAVE_STPCPY char *stpcpy (char *a, const char *b); #endif #ifndef HAVE_STRCASECMP int strcasecmp (const char *a, const char *b) _GCRY_GCC_ATTR_PURE; #endif #include "../compat/libcompat.h" /* Macros used to rename missing functions. */ #ifndef HAVE_STRTOUL #define strtoul(a,b,c) ((unsigned long)strtol((a),(b),(c))) #endif #ifndef HAVE_MEMMOVE #define memmove(d, s, n) bcopy((s), (d), (n)) #endif #ifndef HAVE_STRICMP #define stricmp(a,b) strcasecmp( (a), (b) ) #endif #ifndef HAVE_ATEXIT #define atexit(a) (on_exit((a),0)) #endif #ifndef HAVE_RAISE #define raise(a) kill(getpid(), (a)) #endif /* Stack burning. */ #ifdef HAVE_GCC_ASM_VOLATILE_MEMORY #define __gcry_burn_stack_dummy() asm volatile ("":::"memory") #else void __gcry_burn_stack_dummy (void); #endif void __gcry_burn_stack (unsigned int bytes); #define _gcry_burn_stack(bytes) \ do { __gcry_burn_stack (bytes); \ __gcry_burn_stack_dummy (); } while(0) /* To avoid that a compiler optimizes certain memset calls away, this macro may be used instead. For constant length buffers, memory wiping is inlined. Dead store elimination of inlined memset is avoided here by using assembly block after memset. For non-constant length buffers, memory is wiped through _gcry_fast_wipememory. */ #ifdef HAVE_GCC_ASM_VOLATILE_MEMORY #define fast_wipememory2_inline(_ptr,_set,_len) do { \ memset((_ptr), (_set), (_len)); \ asm volatile ("\n" :: "r" (_ptr) : "memory"); \ } while(0) #else #define fast_wipememory2_inline(_ptr,_set,_len) \ _gcry_fast_wipememory2((void *)_ptr, _set, _len) #endif #define wipememory2(_ptr,_set,_len) do { \ if (!CONSTANT_P(_len) || !CONSTANT_P(_set)) { \ if (CONSTANT_P(_set) && (_set) == 0) \ _gcry_fast_wipememory((void *)(_ptr), (_len)); \ else \ _gcry_fast_wipememory2((void *)(_ptr), (_set), (_len)); \ } else { \ fast_wipememory2_inline((void *)(_ptr), (_set), (_len)); \ } \ } while(0) #define wipememory(_ptr,_len) wipememory2((_ptr),0,(_len)) void _gcry_fast_wipememory(void *ptr, size_t len); void _gcry_fast_wipememory2(void *ptr, int set, size_t len); /* Digit predicates. */ #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define octdigitp(p) (*(p) >= '0' && *(p) <= '7') #define alphap(a) ( (*(a) >= 'A' && *(a) <= 'Z') \ || (*(a) >= 'a' && *(a) <= 'z')) #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* Init functions. */ gcry_err_code_t _gcry_cipher_init (void); gcry_err_code_t _gcry_md_init (void); gcry_err_code_t _gcry_mac_init (void); gcry_err_code_t _gcry_pk_init (void); gcry_err_code_t _gcry_secmem_module_init (void); gcry_err_code_t _gcry_mpi_init (void); /* Memory management. */ #define GCRY_ALLOC_FLAG_SECURE (1 << 0) #define GCRY_ALLOC_FLAG_XHINT (1 << 1) /* Called from xmalloc. */ /*-- sexp.c --*/ gcry_err_code_t _gcry_sexp_vbuild (gcry_sexp_t *retsexp, size_t *erroff, const char *format, va_list arg_ptr); char *_gcry_sexp_nth_string (const gcry_sexp_t list, int number); gpg_err_code_t _gcry_sexp_vextract_param (gcry_sexp_t sexp, const char *path, const char *list, va_list arg_ptr); /*-- fips.c --*/ extern int _gcry_no_fips_mode_required; void _gcry_initialize_fips_mode (int force); int _gcry_fips_to_activate (void); /* This macro 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. No locking is required because we have the requirement that this variable is only initialized once with no other threads existing. */ #define fips_mode() (!_gcry_no_fips_mode_required) void _gcry_fips_signal_error (const char *srcfile, int srcline, const char *srcfunc, int is_fatal, const char *description); #ifdef JNLIB_GCC_M_FUNCTION # define fips_signal_error(a) \ _gcry_fips_signal_error (__FILE__, __LINE__, __FUNCTION__, 0, (a)) # define fips_signal_fatal_error(a) \ _gcry_fips_signal_error (__FILE__, __LINE__, __FUNCTION__, 1, (a)) #else # define fips_signal_error(a) \ _gcry_fips_signal_error (__FILE__, __LINE__, NULL, 0, (a)) # define fips_signal_fatal_error(a) \ _gcry_fips_signal_error (__FILE__, __LINE__, NULL, 1, (a)) #endif int _gcry_fips_indicator_cipher (va_list arg_ptr); int _gcry_fips_indicator_kdf (va_list arg_ptr); int _gcry_fips_is_operational (void); /* Return true if the library is in the operational state. */ #define fips_is_operational() \ (!_gcry_global_any_init_done ? \ _gcry_global_is_operational() : \ (!fips_mode () || _gcry_global_is_operational ())) #define fips_not_operational() (GPG_ERR_NOT_OPERATIONAL) int _gcry_fips_test_operational (void); int _gcry_fips_test_error_or_operational (void); gpg_err_code_t _gcry_fips_run_selftests (int extended); void _gcry_fips_noreturn (void); #define fips_noreturn() (_gcry_fips_noreturn ()) #endif /* G10LIB_H */ diff --git a/src/global.c b/src/global.c index 956043c4..258ea4d1 100644 --- a/src/global.c +++ b/src/global.c @@ -1,1406 +1,1394 @@ /* global.c - global control functions * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2004, 2005, 2006, 2008, 2011, * 2012 Free Software Foundation, Inc. * Copyright (C) 2013, 2014, 2017 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 "gcrypt-testapi.h" #include "cipher.h" #include "stdmem.h" /* our own memory allocator */ #include "secmem.h" /* our own secmem allocator */ /**************** * flag bits: 0 : general cipher debug * 1 : general MPI debug */ static unsigned int debug_flags; /* gcry_control (GCRYCTL_SET_FIPS_MODE), sets this flag so that the initialization code switched fips mode on. */ static int force_fips_mode; /* Controlled by global_init(). */ int _gcry_global_any_init_done; /* * Functions called before and after blocking syscalls. * Initialized by global_init and used via * _gcry_pre_syscall and _gcry_post_syscall. */ static void (*pre_syscall_func)(void); static void (*post_syscall_func)(void); /* Memory management. */ static gcry_handler_alloc_t alloc_func; static gcry_handler_alloc_t alloc_secure_func; static gcry_handler_secure_check_t is_secure_func; static gcry_handler_realloc_t realloc_func; static gcry_handler_free_t free_func; static gcry_handler_no_mem_t outofcore_handler; static void *outofcore_handler_value; static int no_secure_memory; /* Prototypes. */ static gpg_err_code_t external_lock_test (int cmd); /* This is our handmade constructor. It gets called by any function likely to be called at startup. The suggested way for an application to make sure that this has been called is by using gcry_check_version. */ static void global_init (void) { gcry_error_t err = 0; if (_gcry_global_any_init_done) return; _gcry_global_any_init_done = 1; /* Tell the random module that we have seen an init call. */ _gcry_set_preferred_rng_type (0); /* Get the system call clamp functions. */ if (!pre_syscall_func) gpgrt_get_syscall_clamp (&pre_syscall_func, &post_syscall_func); /* 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_mac_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 (); } #ifdef ENABLE_HMAC_BINARY_CHECK # if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7 ) # define GCC_ATTR_CONSTRUCTOR __attribute__ ((__constructor__)) static void GCC_ATTR_CONSTRUCTOR _gcry_global_constructor (void) { force_fips_mode = _gcry_fips_to_activate (); if (force_fips_mode) { no_secure_memory = 1; global_init (); _gcry_fips_run_selftests (0); _gcry_random_close_fds (); no_secure_memory = 0; } } # endif #endif /* ENABLE_HMAC_BINARY_CHECK */ /* 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 (!_gcry_global_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 (const char *what, gpgrt_stream_t fp) { int i; const char *s; if (!what || !strcmp (what, "version")) { gpgrt_fprintf (fp, "version:%s:%x:%s:%x:\n", VERSION, GCRYPT_VERSION_NUMBER, GPGRT_VERSION, GPGRT_VERSION_NUMBER); } if (!what || !strcmp (what, "cc")) { gpgrt_fprintf (fp, "cc:%d:%s:\n", #if GPGRT_VERSION_NUMBER >= 0x011b00 /* 1.27 */ GPGRT_GCC_VERSION #else _GPG_ERR_GCC_VERSION /* Due to a bug in gpg-error.h. */ #endif , #ifdef __clang__ "clang:" __VERSION__ #elif __GNUC__ "gcc:" __VERSION__ #else ":" #endif ); } if (!what || !strcmp (what, "ciphers")) gpgrt_fprintf (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS); if (!what || !strcmp (what, "pubkeys")) gpgrt_fprintf (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS); if (!what || !strcmp (what, "digests")) gpgrt_fprintf (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS); if (!what || !strcmp (what, "rnd-mod")) { gpgrt_fprintf (fp, "rnd-mod:" #if USE_RNDEGD "egd:" #endif #if USE_RNDGETENTROPY "getentropy:" #endif #if USE_RNDOLDLINUX "oldlinux:" #endif #if USE_RNDUNIX "unix:" #endif #if USE_RNDW32 "w32:" #endif "\n"); } if (!what || !strcmp (what, "cpu-arch")) { gpgrt_fprintf (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"); } if (!what || !strcmp (what, "mpi-asm")) gpgrt_fprintf (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ()); if (!what || !strcmp (what, "hwflist")) { unsigned int hwfeatures, afeature; hwfeatures = _gcry_get_hw_features (); gpgrt_fprintf (fp, "hwflist:"); for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++) if ((hwfeatures & afeature)) gpgrt_fprintf (fp, "%s:", s); gpgrt_fprintf (fp, "\n"); } if (!what || !strcmp (what, "fips-mode")) { /* We use y/n instead of 1/0 for the stupid reason that * Emacsen's compile error parser would accidentally flag that * line when printed during "make check" as an error. The * second field is obsolete and thus empty (used to be used for * a so-called enforced-fips-mode). The third field has an * option static string describing the module versions; this is * an optional configure option. */ gpgrt_fprintf (fp, "fips-mode:%c::%s:\n", fips_mode ()? 'y':'n', #ifdef FIPS_MODULE_VERSION fips_mode () ? FIPS_MODULE_VERSION : "" #else "" #endif /* FIPS_MODULE_VERSION */ ); } if (!what || !strcmp (what, "rng-type")) { /* The currently used RNG type. */ unsigned int jver; int active; 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 (); } jver = _gcry_rndjent_get_version (&active); gpgrt_fprintf (fp, "rng-type:%s:%d:%u:%d:\n", s, i, jver, active); } if (!what || !strcmp (what, "compliance")) { /* Right now we have no certification for 1.9 so we return an * empty string. As soon as this version has been approved for * VS-Nfd we will put the string "de-vs" into the second * field. If further specifications are required they are added * as parameters to that field. Other certifications will go * into field 3 and so on. * field 1: keyword "compliance" * field 2: German VS-Nfd is marked with "de-vs" * field 3: reserved for FIPS. */ gpgrt_fprintf (fp, "compliance:%s::\n", ""); } } /* With a MODE of 0 return a malloced string with configured features. * In that case a WHAT of NULL returns everything in the same way * GCRYCTL_PRINT_CONFIG would do. With a specific WHAT string only * the requested feature is returned (w/o the trailing LF. On error * NULL is returned. */ char * _gcry_get_config (int mode, const char *what) { gpgrt_stream_t fp; int save_errno; void *data; char *p; if (mode) { gpg_err_set_errno (EINVAL); return NULL; } fp = gpgrt_fopenmem (0, "w+b,samethread"); if (!fp) return NULL; print_config (what, fp); if (!what) { /* Null-terminate bulk output. */ gpgrt_fwrite ("\0", 1, 1, fp); } if (gpgrt_ferror (fp)) { save_errno = errno; gpgrt_fclose (fp); gpg_err_set_errno (save_errno); return NULL; } gpgrt_rewind (fp); if (gpgrt_fclose_snatch (fp, &data, NULL)) { save_errno = errno; gpgrt_fclose (fp); gpg_err_set_errno (save_errno); return NULL; } if (!data) { /* Nothing was printed (unknown value for WHAT). This is okay, * so clear ERRNO to indicate this. */ gpg_err_set_errno (0); return NULL; } /* Strip trailing LF. */ if (what && (p = strchr (data, '\n'))) *p = 0; return data; } #if _GCRY_GCC_VERSION >= 40200 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wswitch" #endif /* 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: rc = GPG_ERR_NOT_SUPPORTED; 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 (0); break; case GCRYCTL_DROP_PRIVS: global_init (); _gcry_secmem_init (0); break; case GCRYCTL_DISABLE_SECMEM: global_init (); /* When FIPS enabled, no effect at all. */ if (!fips_mode ()) 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_AUTO_EXPAND_SECMEM: _gcry_secmem_set_auto_expand (va_arg (arg_ptr, unsigned int)); 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 (_gcry_global_any_init_done) rc = GPG_ERR_GENERAL; break; case GCRYCTL_INITIALIZATION_FINISHED_P: if (init_finished) rc = GPG_ERR_GENERAL; /* Yes. */ break; case GCRYCTL_INITIALIZATION_FINISHED: /* This is a hook which should be used by an application after all initialization has been done and right before any threads are started. It is not really needed but the only way to be really sure that all initialization for thread-safety has been done. */ if (! init_finished) { global_init (); /* Do only a basic random initialization, i.e. init the mutexes. */ _gcry_random_initialize (0); init_finished = 1; /* Force us into operational state if in FIPS mode. */ (void)fips_is_operational (); } break; case GCRYCTL_SET_THREAD_CBS: /* This is now a dummy call. We used to install our own thread library here. */ _gcry_set_preferred_rng_type (0); global_init (); break; case GCRYCTL_FAST_POLL: _gcry_set_preferred_rng_type (0); /* We need to do make sure that the random pool is really initialized so that the poll function is not a NOP. */ _gcry_random_initialize (1); if ( fips_is_operational () ) _gcry_fast_random_poll (); break; case GCRYCTL_SET_RNDEGD_SOCKET: #if USE_RNDEGD _gcry_set_preferred_rng_type (0); rc = _gcry_rndegd_set_socket_name (va_arg (arg_ptr, const char *)); #else rc = GPG_ERR_NOT_SUPPORTED; #endif break; case GCRYCTL_SET_RANDOM_DAEMON_SOCKET: rc = GPG_ERR_NOT_SUPPORTED; break; case GCRYCTL_USE_RANDOM_DAEMON: rc = GPG_ERR_NOT_SUPPORTED; 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. See also gcry_get_config. */ case GCRYCTL_PRINT_CONFIG: { FILE *fp = va_arg (arg_ptr, FILE *); char *tmpstr; _gcry_set_preferred_rng_type (0); tmpstr = _gcry_get_config (0, NULL); if (tmpstr) { if (fp) fputs (tmpstr, fp); else log_info ("%s", tmpstr); xfree (tmpstr); } } 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 ()) 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 (!_gcry_global_any_init_done) { /* Not yet initialized 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_NO_FIPS_MODE: /* Performing this command puts the library into non-fips mode, even if system has fips setting. It is not possible to put the libraty into non-fips mode after having passed the initialization. */ _gcry_set_preferred_rng_type (0); if (!_gcry_global_any_init_done) { /* Not yet initialized at all. Set a flag so that we are put into non-fips mode during initialization. */ force_fips_mode = 0; } else if (!init_finished) { /* Already initialized. */ _gcry_no_fips_mode_required = 1; } else rc = GPG_ERR_GENERAL; 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; case GCRYCTL_FIPS_SERVICE_INDICATOR_CIPHER: /* Get FIPS Service Indicator for a given symmetric algorithm and * optional mode. Returns GPG_ERR_NO_ERROR if algorithm is allowed or * GPG_ERR_NOT_SUPPORTED otherwise */ rc = _gcry_fips_indicator_cipher (arg_ptr); break; case GCRYCTL_FIPS_SERVICE_INDICATOR_KDF: /* Get FIPS Service Indicator for a given KDF. Returns GPG_ERR_NO_ERROR * if algorithm is allowed or GPG_ERR_NOT_SUPPORTED otherwise */ rc = _gcry_fips_indicator_kdf (arg_ptr); break; case PRIV_CTL_INIT_EXTRNG_TEST: /* Init external random test. */ rc = GPG_ERR_NOT_SUPPORTED; break; case PRIV_CTL_RUN_EXTRNG_TEST: /* Run external DRBG test. */ { struct gcry_drbg_test_vector *test = va_arg (arg_ptr, struct gcry_drbg_test_vector *); unsigned char *buf = va_arg (arg_ptr, unsigned char *); if (buf) rc = _gcry_rngdrbg_cavs_test (test, buf); else rc = _gcry_rngdrbg_healthcheck_one (test); } break; case PRIV_CTL_DEINIT_EXTRNG_TEST: /* Deinit external random test. */ rc = GPG_ERR_NOT_SUPPORTED; break; case PRIV_CTL_EXTERNAL_LOCK_TEST: /* Run external lock test */ rc = external_lock_test (va_arg (arg_ptr, int)); break; case PRIV_CTL_DUMP_SECMEM_STATS: _gcry_secmem_dump_stats (1); break; 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: /* Obsolete - ignore */ 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 (!_gcry_global_any_init_done); } break; case GCRYCTL_DISABLE_LOCKED_SECMEM: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_MLOCK)); break; case GCRYCTL_DISABLE_PRIV_DROP: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_PRIV_DROP)); break; case GCRYCTL_INACTIVATE_FIPS_FLAG: case GCRYCTL_REACTIVATE_FIPS_FLAG: rc = GPG_ERR_NOT_IMPLEMENTED; break; case GCRYCTL_DRBG_REINIT: { const char *flagstr = va_arg (arg_ptr, const char *); gcry_buffer_t *pers = va_arg (arg_ptr, gcry_buffer_t *); int npers = va_arg (arg_ptr, int); if (va_arg (arg_ptr, void *) || npers < 0) rc = GPG_ERR_INV_ARG; else if (_gcry_get_rng_type (!_gcry_global_any_init_done) != GCRY_RNG_TYPE_FIPS) rc = GPG_ERR_NOT_SUPPORTED; else rc = _gcry_rngdrbg_reinit (flagstr, pers, npers); } break; case GCRYCTL_REINIT_SYSCALL_CLAMP: if (!pre_syscall_func) gpgrt_get_syscall_clamp (&pre_syscall_func, &post_syscall_func); break; default: _gcry_set_preferred_rng_type (0); rc = GPG_ERR_INV_OP; } return rc; } #if _GCRY_GCC_VERSION >= 40200 # pragma GCC diagnostic pop #endif /* 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 ()) { /* In FIPS mode, we can not use custom allocation handlers because * fips requires explicit zeroization and we can not guarantee that * with custom free functions (and we can not do it transparently as * in free we do not know the zize). */ return; } 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; } 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) && !no_secure_memory) { if (alloc_secure_func) m = (*alloc_secure_func) (n); else m = _gcry_private_malloc_secure (n, !!(flags & GCRY_ALLOC_FLAG_XHINT)); } 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; } static void * _gcry_malloc_secure_core (size_t n, int xhint) { void *mem = NULL; do_malloc (n, (GCRY_ALLOC_FLAG_SECURE | (xhint? GCRY_ALLOC_FLAG_XHINT:0)), &mem); return mem; } void * _gcry_malloc_secure (size_t n) { return _gcry_malloc_secure_core (n, 0); } int _gcry_is_secure (const void *a) { if (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) -#endif -} - static void * _gcry_realloc_core (void *a, size_t n, int xhint) { 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, xhint); if (!p && !errno) gpg_err_set_errno (ENOMEM); return p; } void * _gcry_realloc (void *a, size_t n) { return _gcry_realloc_core (a, n, 0); } void _gcry_free (void *p) { int save_errno; if (!p) return; /* In case ERRNO is set we better save it so that the free machinery may not accidentally change ERRNO. We restore it only if it was already set to comply with the usual C semantic for ERRNO. */ save_errno = errno; if (free_func) free_func (p); else _gcry_private_free (p); if (save_errno && save_errno != 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; } static char * _gcry_strdup_core (const char *string, int xhint) { char *string_cp = NULL; size_t string_n = 0; string_n = strlen (string); if (_gcry_is_secure (string)) string_cp = _gcry_malloc_secure_core (string_n + 1, xhint); else string_cp = _gcry_malloc (string_n + 1); if (string_cp) strcpy (string_cp, string); return string_cp; } /* 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) { return _gcry_strdup_core (string, 0); } 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_core (a, n, 1))) { 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_core (n, 1))) { 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_core (string, 1)) ) { 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; } /* Used before blocking system calls. */ void _gcry_pre_syscall (void) { if (pre_syscall_func) pre_syscall_func (); } /* Used after blocking system calls. */ void _gcry_post_syscall (void) { if (post_syscall_func) post_syscall_func (); } int _gcry_get_debug_flag (unsigned int mask) { if ( fips_mode () ) return 0; return (debug_flags & mask); } /* It is often useful to get some feedback of long running operations. This function may be used to register a handler for this. The callback function CB is used as: void cb (void *opaque, const char *what, int printchar, int current, int total); Where WHAT is a string identifying the the type of the progress output, PRINTCHAR the character usually printed, CURRENT the amount of progress currently done and TOTAL the expected amount of progress. A value of 0 for TOTAL indicates that there is no estimation available. Defined values for WHAT: "need_entropy" X 0 number-of-bytes-required When running low on entropy "primegen" '\n' 0 0 Prime generated '!' Need to refresh the prime pool '<','>' Number of bits adjusted '^' Looking for a generator '.' Fermat tests on 10 candidates failed ':' Restart with a new random value '+' Rabin Miller test passed "pk_elg" '+','-','.','\n' 0 0 Only used in debugging mode. "pk_dsa" Only used in debugging mode. */ void _gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int), void *cb_data) { #if USE_DSA _gcry_register_pk_dsa_progress (cb, cb_data); #endif #if USE_ELGAMAL _gcry_register_pk_elg_progress (cb, cb_data); #endif _gcry_register_primegen_progress (cb, cb_data); _gcry_register_random_progress (cb, cb_data); } /* This is a helper for the regression test suite to test Libgcrypt's locks. It works using a one test lock with CMD controlling what to do: 30111 - Allocate and init lock 30112 - Take lock 30113 - Release lock 30114 - Destroy lock. This function is used by tests/t-lock.c - it is not part of the public API! */ static gpg_err_code_t external_lock_test (int cmd) { GPGRT_LOCK_DEFINE (testlock); gpg_err_code_t rc = 0; switch (cmd) { case 30111: /* Init Lock. */ rc = gpgrt_lock_init (&testlock); break; case 30112: /* Take Lock. */ rc = gpgrt_lock_lock (&testlock); break; case 30113: /* Release Lock. */ rc = gpgrt_lock_unlock (&testlock); break; case 30114: /* Destroy Lock. */ rc = gpgrt_lock_destroy (&testlock); break; default: rc = GPG_ERR_INV_OP; break; } return rc; } diff --git a/src/mpi.h b/src/mpi.h index 9e234eff..c2ebd0da 100644 --- a/src/mpi.h +++ b/src/mpi.h @@ -1,327 +1,325 @@ /* mpi.h - Multi Precision Integers * Copyright (C) 1994, 1996, 1998, * 2001, 2002, 2003, 2005 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 * * Note: This code is heavily based on the GNU MP Library. * Actually it's the same code with only minor changes in the * way the data is stored; this is to support the abstraction * of an optional secure memory allocation which may be used * to avoid revealing of sensitive data due to paging etc. */ #ifndef G10_MPI_H #define G10_MPI_H #include #include #include #include "types.h" #include "../mpi/mpi-asm-defs.h" #include "g10lib.h" #ifndef _GCRYPT_IN_LIBGCRYPT #error this file should only be used inside libgcrypt #endif #ifndef BITS_PER_MPI_LIMB #if BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_INT typedef unsigned int mpi_limb_t; typedef signed int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG typedef unsigned long int mpi_limb_t; typedef signed long int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG_LONG typedef unsigned long long int mpi_limb_t; typedef signed long long int mpi_limb_signed_t; #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_SHORT typedef unsigned short int mpi_limb_t; typedef signed short int mpi_limb_signed_t; #else #error BYTES_PER_MPI_LIMB does not match any C type #endif #define BITS_PER_MPI_LIMB (8*BYTES_PER_MPI_LIMB) #endif /*BITS_PER_MPI_LIMB*/ #define DBG_MPI _gcry_get_debug_flag( 2 ); struct gcry_mpi { int alloced; /* Array size (# of allocated limbs). */ int nlimbs; /* Number of valid limbs. */ int sign; /* Indicates a negative number and is also used for opaque MPIs to store the length. */ unsigned int flags; /* Bit 0: Array to be allocated in secure memory space.*/ /* Bit 2: The limb is a pointer to some m_alloced data.*/ /* Bit 4: Immutable MPI - the MPI may not be modified. */ /* Bit 5: Constant MPI - the MPI will not be freed. */ mpi_limb_t *d; /* Array with the limbs */ }; #define MPI_NULL NULL #define mpi_get_nlimbs(a) ((a)->nlimbs) #define mpi_has_sign(a) ((a)->sign) /*-- mpiutil.c --*/ #ifdef M_DEBUG # define mpi_alloc(n) _gcry_mpi_debug_alloc((n), M_DBGINFO( __LINE__ ) ) # define mpi_alloc_secure(n) _gcry_mpi_debug_alloc_secure((n), M_DBGINFO( __LINE__ ) ) # define mpi_free(a) _gcry_mpi_debug_free((a), M_DBGINFO(__LINE__) ) # define mpi_resize(a,b) _gcry_mpi_debug_resize((a),(b), M_DBGINFO(__LINE__) ) # define mpi_copy(a) _gcry_mpi_debug_copy((a), M_DBGINFO(__LINE__) ) gcry_mpi_t _gcry_mpi_debug_alloc( unsigned nlimbs, const char *info ); gcry_mpi_t _gcry_mpi_debug_alloc_secure( unsigned nlimbs, const char *info ); void _gcry_mpi_debug_free( gcry_mpi_t a, const char *info ); void _gcry_mpi_debug_resize( gcry_mpi_t a, unsigned nlimbs, const char *info ); gcry_mpi_t _gcry_mpi_debug_copy( gcry_mpi_t a, const char *info ); #else # define mpi_alloc(n) _gcry_mpi_alloc((n) ) # define mpi_alloc_secure(n) _gcry_mpi_alloc_secure((n) ) # define mpi_free(a) _gcry_mpi_free((a) ) # define mpi_resize(a,b) _gcry_mpi_resize((a),(b)) # define mpi_copy(a) _gcry_mpi_copy((a)) gcry_mpi_t _gcry_mpi_alloc( unsigned nlimbs ); gcry_mpi_t _gcry_mpi_alloc_secure( unsigned nlimbs ); void _gcry_mpi_free( gcry_mpi_t a ); void _gcry_mpi_resize( gcry_mpi_t a, unsigned nlimbs ); gcry_mpi_t _gcry_mpi_copy( gcry_mpi_t a ); #endif void _gcry_mpi_immutable_failed (void); #define mpi_immutable_failed() _gcry_mpi_immutable_failed () #define mpi_is_const(a) ((a)->flags&32) #define mpi_is_immutable(a) ((a)->flags&16) #define mpi_is_opaque(a) ((a) && ((a)->flags&4)) #define mpi_is_secure(a) ((a) && ((a)->flags&1)) #define mpi_clear(a) _gcry_mpi_clear ((a)) #define mpi_alloc_like(a) _gcry_mpi_alloc_like((a)) #define mpi_alloc_set_ui(a) _gcry_mpi_alloc_set_ui ((a)) -#define mpi_m_check(a) _gcry_mpi_m_check ((a)) #define mpi_const(n) _gcry_mpi_const ((n)) #define mpi_swap_cond(a,b,sw) _gcry_mpi_swap_cond ((a),(b),(sw)) #define mpi_set_cond(w,u,set) _gcry_mpi_set_cond ((w),(u),(set)) #define mpi_set_bit_cond(a,n,set) _gcry_mpi_set_bit_cond ((a),(n),(set)) void _gcry_mpi_clear( gcry_mpi_t a ); gcry_mpi_t _gcry_mpi_set_cond (gcry_mpi_t w, const gcry_mpi_t u, unsigned long swap); gcry_mpi_t _gcry_mpi_alloc_like( gcry_mpi_t a ); gcry_mpi_t _gcry_mpi_alloc_set_ui( unsigned long u); -void _gcry_mpi_m_check( gcry_mpi_t a ); void _gcry_mpi_swap( gcry_mpi_t a, gcry_mpi_t b); void _gcry_mpi_swap_cond (gcry_mpi_t a, gcry_mpi_t b, unsigned long swap); void _gcry_mpi_set_bit_cond (gcry_mpi_t a, unsigned int n, unsigned long set); gcry_mpi_t _gcry_mpi_new (unsigned int nbits); gcry_mpi_t _gcry_mpi_snew (unsigned int nbits); gcry_mpi_t _gcry_mpi_set_opaque_copy (gcry_mpi_t a, const void *p, unsigned int nbits); void *_gcry_mpi_get_opaque_copy (gcry_mpi_t a, unsigned int *nbits); int _gcry_mpi_is_neg (gcry_mpi_t a); void _gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u); void _gcry_mpi_abs (gcry_mpi_t w); /* Constants used to return constant MPIs. See _gcry_mpi_init if you want to add more constants. */ #define MPI_NUMBER_OF_CONSTANTS 6 enum gcry_mpi_constants { MPI_C_ZERO, MPI_C_ONE, MPI_C_TWO, MPI_C_THREE, MPI_C_FOUR, MPI_C_EIGHT }; gcry_mpi_t _gcry_mpi_const (enum gcry_mpi_constants no); /*-- mpicoder.c --*/ void _gcry_log_mpidump( const char *text, gcry_mpi_t a ); u32 _gcry_mpi_get_keyid( gcry_mpi_t a, u32 *keyid ); byte *_gcry_mpi_get_buffer (gcry_mpi_t a, unsigned int fill_le, unsigned int *r_nbytes, int *sign); byte *_gcry_mpi_get_buffer_extra (gcry_mpi_t a, unsigned int fill_le, int extraalloc, unsigned int *r_nbytes, int *sign); byte *_gcry_mpi_get_secure_buffer (gcry_mpi_t a, unsigned int fill_le, unsigned *r_nbytes, int *sign); void _gcry_mpi_set_buffer ( gcry_mpi_t a, const void *buffer, unsigned int nbytes, int sign ); gpg_err_code_t _gcry_mpi_to_octet_string (unsigned char **r_frame, void *space, gcry_mpi_t value, size_t nbytes); /*-- mpi-div.c --*/ #define mpi_fdiv_r_ui(a,b,c) _gcry_mpi_fdiv_r_ui((a),(b),(c)) #define mpi_fdiv_r(a,b,c) _gcry_mpi_fdiv_r((a),(b),(c)) #define mpi_fdiv_q(a,b,c) _gcry_mpi_fdiv_q((a),(b),(c)) #define mpi_fdiv_qr(a,b,c,d) _gcry_mpi_fdiv_qr((a),(b),(c),(d)) #define mpi_tdiv_r(a,b,c) _gcry_mpi_tdiv_r((a),(b),(c)) #define mpi_tdiv_qr(a,b,c,d) _gcry_mpi_tdiv_qr((a),(b),(c),(d)) #define mpi_tdiv_q_2exp(a,b,c) _gcry_mpi_tdiv_q_2exp((a),(b),(c)) #define mpi_divisible_ui(a,b) _gcry_mpi_divisible_ui((a),(b)) unsigned long _gcry_mpi_fdiv_r_ui( gcry_mpi_t rem, gcry_mpi_t dividend, unsigned long divisor ); void _gcry_mpi_fdiv_r( gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_fdiv_q( gcry_mpi_t quot, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_fdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); void _gcry_mpi_tdiv_r( gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); void _gcry_mpi_tdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); void _gcry_mpi_tdiv_q_2exp( gcry_mpi_t w, gcry_mpi_t u, unsigned count ); int _gcry_mpi_divisible_ui(gcry_mpi_t dividend, unsigned long divisor ); /*-- mpi-mod.c --*/ #define mpi_barrett_init(m,f) _gcry_mpi_barrett_init ((m),(f)) #define mpi_barrett_free(c) _gcry_mpi_barrett_free ((c)) #define mpi_mod_barrett(r,a,c) _gcry_mpi_mod_barrett ((r), (a), (c)) #define mpi_mul_barrett(r,u,v,c) _gcry_mpi_mul_barrett ((r), (u), (v), (c)) /* Context used with Barrett reduction. */ struct barrett_ctx_s; typedef struct barrett_ctx_s *mpi_barrett_t; mpi_barrett_t _gcry_mpi_barrett_init (gcry_mpi_t m, int copy); void _gcry_mpi_barrett_free (mpi_barrett_t ctx); void _gcry_mpi_mod_barrett (gcry_mpi_t r, gcry_mpi_t x, mpi_barrett_t ctx); void _gcry_mpi_mul_barrett (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_barrett_t ctx); /*-- mpi-mpow.c --*/ #define mpi_mulpowm(a,b,c,d) _gcry_mpi_mulpowm ((a),(b),(c),(d)) void _gcry_mpi_mulpowm( gcry_mpi_t res, gcry_mpi_t *basearray, gcry_mpi_t *exparray, gcry_mpi_t mod); /*-- mpi-scan.c --*/ #define mpi_trailing_zeros(a) _gcry_mpi_trailing_zeros ((a)) int _gcry_mpi_getbyte( gcry_mpi_t a, unsigned idx ); void _gcry_mpi_putbyte( gcry_mpi_t a, unsigned idx, int value ); unsigned _gcry_mpi_trailing_zeros( gcry_mpi_t a ); /*-- mpi-bit.c --*/ #define mpi_normalize(a) _gcry_mpi_normalize ((a)) void _gcry_mpi_normalize( gcry_mpi_t a ); /*-- ec.c --*/ /* Object to represent a point in projective coordinates. */ struct gcry_mpi_point { gcry_mpi_t x; gcry_mpi_t y; gcry_mpi_t z; }; typedef struct gcry_mpi_point mpi_point_struct; typedef struct gcry_mpi_point *mpi_point_t; void _gcry_mpi_point_init (mpi_point_t p); void _gcry_mpi_point_free_parts (mpi_point_t p); void _gcry_mpi_get_point (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point); void _gcry_mpi_snatch_point (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point); /* Models describing an elliptic curve. */ enum gcry_mpi_ec_models { /* The Short Weierstrass equation is y^2 = x^3 + ax + b */ MPI_EC_WEIERSTRASS = 0, /* The Montgomery equation is by^2 = x^3 + ax^2 + x */ MPI_EC_MONTGOMERY, /* The Twisted Edwards equation is ax^2 + y^2 = 1 + bx^2y^2 Note that we use 'b' instead of the commonly used 'd'. */ MPI_EC_EDWARDS }; /* Dialects used with elliptic curves. It is easier to keep the definition here than in ecc-common.h. */ enum ecc_dialects { ECC_DIALECT_STANDARD = 0, ECC_DIALECT_ED25519, ECC_DIALECT_SAFECURVE }; void _gcry_mpi_point_log (const char *name, mpi_point_t point, mpi_ec_t ctx); #define log_printpnt(a,p,c) _gcry_mpi_point_log ((a), (p), (c)) mpi_ec_t _gcry_mpi_ec_p_internal_new (enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b); gpg_err_code_t _gcry_mpi_ec_p_new (gcry_ctx_t *r_ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b); void _gcry_mpi_ec_free (mpi_ec_t ctx); void _gcry_mpi_ec_dup_point (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx); void _gcry_mpi_ec_add_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx); void _gcry_mpi_ec_sub_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx); void _gcry_mpi_ec_mul_point (mpi_point_t result, gcry_mpi_t scalar, mpi_point_t point, mpi_ec_t ctx); int _gcry_mpi_ec_curve_point (gcry_mpi_point_t point, mpi_ec_t ctx); int _gcry_mpi_ec_bad_point (gcry_mpi_point_t point, mpi_ec_t ctx); gcry_mpi_t _gcry_mpi_ec_ec2os (gcry_mpi_point_t point, mpi_ec_t ectx); gcry_mpi_t _gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy); gcry_mpi_point_t _gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy); gpg_err_code_t _gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx); gpg_err_code_t _gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx); gpg_err_code_t _gcry_mpi_ec_decode_point (mpi_point_t result, gcry_mpi_t value, mpi_ec_t ec); /*-- ecc-curves.c --*/ gpg_err_code_t _gcry_mpi_ec_new (gcry_ctx_t *r_ctx, gcry_sexp_t keyparam, const char *curvename); gpg_err_code_t _gcry_mpi_ec_internal_new (mpi_ec_t *r_ec, int *r_flags, const char *name_op, gcry_sexp_t keyparam, const char *curvename); #endif /*G10_MPI_H*/