LCOV - code coverage report
Current view: top level - src - global.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 235 439 53.5 %
Date: 2015-11-05 17:08:00 Functions: 26 29 89.7 %

          Line data    Source code
       1             : /* global.c  -  global control functions
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
       3             :  *               2004, 2005, 2006, 2008, 2011,
       4             :  *               2012  Free Software Foundation, Inc.
       5             :  * Copyright (C) 2013, 2014 g10 Code GmbH
       6             :  *
       7             :  * This file is part of Libgcrypt.
       8             :  *
       9             :  * Libgcrypt is free software; you can redistribute it and/or modify
      10             :  * it under the terms of the GNU Lesser general Public License as
      11             :  * published by the Free Software Foundation; either version 2.1 of
      12             :  * the License, or (at your option) any later version.
      13             :  *
      14             :  * Libgcrypt is distributed in the hope that it will be useful,
      15             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      16             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17             :  * GNU Lesser General Public License for more details.
      18             :  *
      19             :  * You should have received a copy of the GNU Lesser General Public
      20             :  * License along with this program; if not, see <http://www.gnu.org/licenses/>.
      21             :  */
      22             : 
      23             : #include <config.h>
      24             : 
      25             : #include <stdio.h>
      26             : #include <stdlib.h>
      27             : #include <string.h>
      28             : #include <stdarg.h>
      29             : #include <ctype.h>
      30             : #include <limits.h>
      31             : #include <errno.h>
      32             : #include <unistd.h>
      33             : #ifdef HAVE_SYSLOG
      34             : # include <syslog.h>
      35             : #endif /*HAVE_SYSLOG*/
      36             : 
      37             : #include "g10lib.h"
      38             : #include "cipher.h"
      39             : #include "stdmem.h" /* our own memory allocator */
      40             : #include "secmem.h" /* our own secmem allocator */
      41             : 
      42             : 
      43             : 
      44             : 
      45             : /****************
      46             :  * flag bits: 0 : general cipher debug
      47             :  *            1 : general MPI debug
      48             :  */
      49             : static unsigned int debug_flags;
      50             : 
      51             : /* gcry_control (GCRYCTL_SET_FIPS_MODE), sets this flag so that the
      52             :    initialization code switched fips mode on.  */
      53             : static int force_fips_mode;
      54             : 
      55             : /* Controlled by global_init().  */
      56             : static int any_init_done;
      57             : 
      58             : /* Memory management. */
      59             : 
      60             : static gcry_handler_alloc_t alloc_func;
      61             : static gcry_handler_alloc_t alloc_secure_func;
      62             : static gcry_handler_secure_check_t is_secure_func;
      63             : static gcry_handler_realloc_t realloc_func;
      64             : static gcry_handler_free_t free_func;
      65             : static gcry_handler_no_mem_t outofcore_handler;
      66             : static void *outofcore_handler_value;
      67             : static int no_secure_memory;
      68             : 
      69             : /* Prototypes.  */
      70             : static gpg_err_code_t external_lock_test (int cmd);
      71             : 
      72             : 
      73             : 
      74             : 
      75             : /* This is our handmade constructor.  It gets called by any function
      76             :    likely to be called at startup.  The suggested way for an
      77             :    application to make sure that this has been called is by using
      78             :    gcry_check_version. */
      79             : static void
      80          94 : global_init (void)
      81             : {
      82          94 :   gcry_error_t err = 0;
      83             : 
      84          94 :   if (any_init_done)
      85          63 :     return;
      86          31 :   any_init_done = 1;
      87             : 
      88             :   /* Tell the random module that we have seen an init call.  */
      89          31 :   _gcry_set_preferred_rng_type (0);
      90             : 
      91             :   /* See whether the system is in FIPS mode.  This needs to come as
      92             :      early as possible but after ATH has been initialized.  */
      93          31 :   _gcry_initialize_fips_mode (force_fips_mode);
      94             : 
      95             :   /* Before we do any other initialization we need to test available
      96             :      hardware features.  */
      97          31 :   _gcry_detect_hw_features ();
      98             : 
      99             :   /* Initialize the modules - this is mainly allocating some memory and
     100             :      creating mutexes.  */
     101          31 :   err = _gcry_cipher_init ();
     102          31 :   if (err)
     103           0 :     goto fail;
     104          31 :   err = _gcry_md_init ();
     105          31 :   if (err)
     106           0 :     goto fail;
     107          31 :   err = _gcry_pk_init ();
     108          31 :   if (err)
     109           0 :     goto fail;
     110          31 :   err = _gcry_primegen_init ();
     111          31 :   if (err)
     112           0 :     goto fail;
     113          31 :   err = _gcry_secmem_module_init ();
     114          31 :   if (err)
     115           0 :     goto fail;
     116          31 :   err = _gcry_mpi_init ();
     117          31 :   if (err)
     118           0 :     goto fail;
     119             : 
     120          31 :   return;
     121             : 
     122             :  fail:
     123           0 :   BUG ();
     124             : }
     125             : 
     126             : 
     127             : /* This function is called by the macro fips_is_operational and makes
     128             :    sure that the minimal initialization has been done.  This is far
     129             :    from a perfect solution and hides problems with an improper
     130             :    initialization but at least in single-threaded mode it should work
     131             :    reliable.
     132             : 
     133             :    The reason we need this is that a lot of applications don't use
     134             :    Libgcrypt properly by not running any initialization code at all.
     135             :    They just call a Libgcrypt function and that is all what they want.
     136             :    Now with the FIPS mode, that has the side effect of entering FIPS
     137             :    mode (for security reasons, FIPS mode is the default if no
     138             :    initialization has been done) and bailing out immediately because
     139             :    the FSM is in the wrong state.  If we always run the init code,
     140             :    Libgcrypt can test for FIPS mode and at least if not in FIPS mode,
     141             :    it will behave as before.  Note that this on-the-fly initialization
     142             :    is only done for the cryptographic functions subject to FIPS mode
     143             :    and thus not all API calls will do such an initialization.  */
     144             : int
     145    31439993 : _gcry_global_is_operational (void)
     146             : {
     147    31439993 :   if (!any_init_done)
     148             :     {
     149             : #ifdef HAVE_SYSLOG
     150           0 :       syslog (LOG_USER|LOG_WARNING, "Libgcrypt warning: "
     151             :               "missing initialization - please fix the application");
     152             : #endif /*HAVE_SYSLOG*/
     153           0 :       global_init ();
     154             :     }
     155    31439993 :   return _gcry_fips_is_operational ();
     156             : }
     157             : 
     158             : 
     159             : 
     160             : 
     161             : /* Version number parsing.  */
     162             : 
     163             : /* This function parses the first portion of the version number S and
     164             :    stores it in *NUMBER.  On success, this function returns a pointer
     165             :    into S starting with the first character, which is not part of the
     166             :    initial number portion; on failure, NULL is returned.  */
     167             : static const char*
     168         168 : parse_version_number( const char *s, int *number )
     169             : {
     170         168 :     int val = 0;
     171             : 
     172         168 :     if( *s == '0' && isdigit(s[1]) )
     173           0 :         return NULL; /* leading zeros are not allowed */
     174         336 :     for ( ; isdigit(*s); s++ ) {
     175         168 :         val *= 10;
     176         168 :         val += *s - '0';
     177             :     }
     178         168 :     *number = val;
     179         168 :     return val < 0? NULL : s;
     180             : }
     181             : 
     182             : /* This function breaks up the complete string-representation of the
     183             :    version number S, which is of the following struture: <major
     184             :    number>.<minor number>.<micro number><patch level>.  The major,
     185             :    minor and micro number components will be stored in *MAJOR, *MINOR
     186             :    and *MICRO.
     187             : 
     188             :    On success, the last component, the patch level, will be returned;
     189             :    in failure, NULL will be returned.  */
     190             : 
     191             : static const char *
     192          56 : parse_version_string( const char *s, int *major, int *minor, int *micro )
     193             : {
     194          56 :     s = parse_version_number( s, major );
     195          56 :     if( !s || *s != '.' )
     196           0 :         return NULL;
     197          56 :     s++;
     198          56 :     s = parse_version_number( s, minor );
     199          56 :     if( !s || *s != '.' )
     200           0 :         return NULL;
     201          56 :     s++;
     202          56 :     s = parse_version_number( s, micro );
     203          56 :     if( !s )
     204           0 :         return NULL;
     205          56 :     return s; /* patchlevel */
     206             : }
     207             : 
     208             : /* If REQ_VERSION is non-NULL, check that the version of the library
     209             :    is at minimum the requested one.  Returns the string representation
     210             :    of the library version if the condition is satisfied; return NULL
     211             :    if the requested version is newer than that of the library.
     212             : 
     213             :    If a NULL is passed to this function, no check is done, but the
     214             :    string representation of the library is simply returned.  */
     215             : const char *
     216          33 : _gcry_check_version (const char *req_version)
     217             : {
     218          33 :     const char *ver = VERSION;
     219             :     int my_major, my_minor, my_micro;
     220             :     int rq_major, rq_minor, rq_micro;
     221             :     const char *my_plvl;
     222             : 
     223          33 :     if (req_version && req_version[0] == 1 && req_version[1] == 1)
     224           0 :         return _gcry_compat_identification ();
     225             : 
     226             :     /* Initialize library.  */
     227          33 :     global_init ();
     228             : 
     229          33 :     if ( !req_version )
     230             :         /* Caller wants our version number.  */
     231           5 :         return ver;
     232             : 
     233             :     /* Parse own version number.  */
     234          28 :     my_plvl = parse_version_string( ver, &my_major, &my_minor, &my_micro );
     235          28 :     if ( !my_plvl )
     236             :         /* very strange our own version is bogus.  Shouldn't we use
     237             :            assert() here and bail out in case this happens?  -mo.  */
     238           0 :         return NULL;
     239             : 
     240             :     /* Parse requested version number.  */
     241          28 :     if (!parse_version_string (req_version, &rq_major, &rq_minor, &rq_micro))
     242           0 :       return NULL;  /* req version string is invalid, this can happen.  */
     243             : 
     244             :     /* Compare version numbers.  */
     245          28 :     if ( my_major > rq_major
     246          28 :         || (my_major == rq_major && my_minor > rq_minor)
     247          26 :         || (my_major == rq_major && my_minor == rq_minor                                                         && my_micro > rq_micro)
     248          26 :         || (my_major == rq_major && my_minor == rq_minor
     249          26 :                                  && my_micro == rq_micro))
     250             :       {
     251          28 :         return ver;
     252             :       }
     253             : 
     254           0 :     return NULL;
     255             : }
     256             : 
     257             : 
     258             : static void
     259           1 : print_config ( int (*fnc)(FILE *fp, const char *format, ...), FILE *fp)
     260             : {
     261             :   unsigned int hwfeatures, afeature;
     262             :   int i;
     263             :   const char *s;
     264             : 
     265           1 :   fnc (fp, "version:%s:\n", VERSION);
     266           1 :   fnc (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS);
     267           1 :   fnc (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS);
     268           1 :   fnc (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS);
     269           1 :   fnc (fp, "rnd-mod:"
     270             : #if USE_RNDEGD
     271             :                 "egd:"
     272             : #endif
     273             : #if USE_RNDLINUX
     274             :                 "linux:"
     275             : #endif
     276             : #if USE_RNDUNIX
     277             :                 "unix:"
     278             : #endif
     279             : #if USE_RNDW32
     280             :                 "w32:"
     281             : #endif
     282             :        "\n");
     283           1 :   fnc (fp, "cpu-arch:"
     284             : #if defined(HAVE_CPU_ARCH_X86)
     285             :        "x86"
     286             : #elif defined(HAVE_CPU_ARCH_ALPHA)
     287             :        "alpha"
     288             : #elif defined(HAVE_CPU_ARCH_SPARC)
     289             :        "sparc"
     290             : #elif defined(HAVE_CPU_ARCH_MIPS)
     291             :        "mips"
     292             : #elif defined(HAVE_CPU_ARCH_M68K)
     293             :        "m68k"
     294             : #elif defined(HAVE_CPU_ARCH_PPC)
     295             :        "ppc"
     296             : #elif defined(HAVE_CPU_ARCH_ARM)
     297             :        "arm"
     298             : #endif
     299             :        ":\n");
     300           1 :   fnc (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ());
     301           1 :   hwfeatures = _gcry_get_hw_features ();
     302           1 :   fnc (fp, "hwflist:");
     303          15 :   for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++)
     304          14 :     if ((hwfeatures & afeature))
     305           6 :       fnc (fp, "%s:", s);
     306           1 :   fnc (fp, "\n");
     307             :   /* We use y/n instead of 1/0 for the simple reason that Emacsen's
     308             :      compile error parser would accidently flag that line when printed
     309             :      during "make check" as an error.  */
     310           2 :   fnc (fp, "fips-mode:%c:%c:\n",
     311           1 :        fips_mode ()? 'y':'n',
     312           1 :        _gcry_enforced_fips_mode ()? 'y':'n' );
     313             :   /* The currently used RNG type.  */
     314             :   {
     315           1 :     i = _gcry_get_rng_type (0);
     316           1 :     switch (i)
     317             :       {
     318           1 :       case GCRY_RNG_TYPE_STANDARD: s = "standard"; break;
     319           0 :       case GCRY_RNG_TYPE_FIPS:     s = "fips"; break;
     320           0 :       case GCRY_RNG_TYPE_SYSTEM:   s = "system"; break;
     321           0 :       default: BUG ();
     322             :       }
     323           1 :     fnc (fp, "rng-type:%s:%d:\n", s, i);
     324             :   }
     325             : 
     326           1 : }
     327             : 
     328             : 
     329             : 
     330             : 
     331             : /* Command dispatcher function, acting as general control
     332             :    function.  */
     333             : gcry_err_code_t
     334       24435 : _gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr)
     335             : {
     336             :   static int init_finished = 0;
     337       24435 :   gcry_err_code_t rc = 0;
     338             : 
     339       24435 :   switch (cmd)
     340             :     {
     341             :     case GCRYCTL_ENABLE_M_GUARD:
     342           0 :       _gcry_private_enable_m_guard ();
     343          12 :       break;
     344             : 
     345             :     case GCRYCTL_ENABLE_QUICK_RANDOM:
     346          15 :       _gcry_set_preferred_rng_type (0);
     347          15 :       _gcry_enable_quick_random_gen ();
     348          15 :       break;
     349             : 
     350             :     case GCRYCTL_FAKED_RANDOM_P:
     351             :       /* Return an error if the RNG is faked one (e.g. enabled by
     352             :          ENABLE_QUICK_RANDOM. */
     353           0 :       if (_gcry_random_is_faked ())
     354           0 :         rc = GPG_ERR_GENERAL;  /* Use as TRUE value.  */
     355           0 :       break;
     356             : 
     357             :     case GCRYCTL_DUMP_RANDOM_STATS:
     358           0 :       _gcry_random_dump_stats ();
     359           0 :       break;
     360             : 
     361             :     case GCRYCTL_DUMP_MEMORY_STATS:
     362             :       /*m_print_stats("[fixme: prefix]");*/
     363           0 :       break;
     364             : 
     365             :     case GCRYCTL_DUMP_SECMEM_STATS:
     366           0 :       _gcry_secmem_dump_stats ();
     367           0 :       break;
     368             : 
     369             :     case GCRYCTL_DROP_PRIVS:
     370           0 :       global_init ();
     371           0 :       _gcry_secmem_init (0);
     372           0 :       break;
     373             : 
     374             :     case GCRYCTL_DISABLE_SECMEM:
     375          30 :       global_init ();
     376          30 :       no_secure_memory = 1;
     377          30 :       break;
     378             : 
     379             :     case GCRYCTL_INIT_SECMEM:
     380           1 :       global_init ();
     381           1 :       _gcry_secmem_init (va_arg (arg_ptr, unsigned int));
     382           1 :       if ((_gcry_secmem_get_flags () & GCRY_SECMEM_FLAG_NOT_LOCKED))
     383           0 :         rc = GPG_ERR_GENERAL;
     384           1 :       break;
     385             : 
     386             :     case GCRYCTL_TERM_SECMEM:
     387           0 :       global_init ();
     388           0 :       _gcry_secmem_term ();
     389           0 :       break;
     390             : 
     391             :     case GCRYCTL_DISABLE_SECMEM_WARN:
     392           1 :       _gcry_set_preferred_rng_type (0);
     393           1 :       _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
     394             :                                | GCRY_SECMEM_FLAG_NO_WARNING));
     395           1 :       break;
     396             : 
     397             :     case GCRYCTL_SUSPEND_SECMEM_WARN:
     398           0 :       _gcry_set_preferred_rng_type (0);
     399           0 :       _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
     400             :                                | GCRY_SECMEM_FLAG_SUSPEND_WARNING));
     401           0 :       break;
     402             : 
     403             :     case GCRYCTL_RESUME_SECMEM_WARN:
     404           0 :       _gcry_set_preferred_rng_type (0);
     405           0 :       _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
     406             :                                & ~GCRY_SECMEM_FLAG_SUSPEND_WARNING));
     407           0 :       break;
     408             : 
     409             :     case GCRYCTL_USE_SECURE_RNDPOOL:
     410           0 :       global_init ();
     411           0 :       _gcry_secure_random_alloc (); /* Put random number into secure memory. */
     412           0 :       break;
     413             : 
     414             :     case GCRYCTL_SET_RANDOM_SEED_FILE:
     415           0 :       _gcry_set_preferred_rng_type (0);
     416           0 :       _gcry_set_random_seed_file (va_arg (arg_ptr, const char *));
     417           0 :       break;
     418             : 
     419             :     case GCRYCTL_UPDATE_RANDOM_SEED_FILE:
     420           0 :       _gcry_set_preferred_rng_type (0);
     421           0 :       if ( fips_is_operational () )
     422           0 :         _gcry_update_random_seed_file ();
     423           0 :       break;
     424             : 
     425             :     case GCRYCTL_SET_VERBOSITY:
     426           4 :       _gcry_set_preferred_rng_type (0);
     427           4 :       _gcry_set_log_verbosity (va_arg (arg_ptr, int));
     428           4 :       break;
     429             : 
     430             :     case GCRYCTL_SET_DEBUG_FLAGS:
     431           0 :       debug_flags |= va_arg (arg_ptr, unsigned int);
     432           0 :       break;
     433             : 
     434             :     case GCRYCTL_CLEAR_DEBUG_FLAGS:
     435           0 :       debug_flags &= ~va_arg (arg_ptr, unsigned int);
     436           0 :       break;
     437             : 
     438             :     case GCRYCTL_DISABLE_INTERNAL_LOCKING:
     439             :       /* Not used anymore.  */
     440           0 :       global_init ();
     441           0 :       break;
     442             : 
     443             :     case GCRYCTL_ANY_INITIALIZATION_P:
     444           0 :       if (any_init_done)
     445           0 :         rc = GPG_ERR_GENERAL;
     446           0 :       break;
     447             : 
     448             :     case GCRYCTL_INITIALIZATION_FINISHED_P:
     449           0 :       if (init_finished)
     450           0 :         rc = GPG_ERR_GENERAL; /* Yes.  */
     451           0 :       break;
     452             : 
     453             :     case GCRYCTL_INITIALIZATION_FINISHED:
     454             :       /* This is a hook which should be used by an application after
     455             :          all initialization has been done and right before any threads
     456             :          are started.  It is not really needed but the only way to be
     457             :          really sure that all initialization for thread-safety has
     458             :          been done. */
     459          29 :       if (! init_finished)
     460             :         {
     461          29 :           global_init ();
     462             :           /* Do only a basic random initialization, i.e. init the
     463             :              mutexes. */
     464          29 :           _gcry_random_initialize (0);
     465          29 :           init_finished = 1;
     466             :           /* Force us into operational state if in FIPS mode.  */
     467          29 :           (void)fips_is_operational ();
     468             :         }
     469          29 :       break;
     470             : 
     471             :     case GCRYCTL_SET_THREAD_CBS:
     472             :       /* This is now a dummy call.  We used to install our own thread
     473             :          library here. */
     474           0 :       _gcry_set_preferred_rng_type (0);
     475           0 :       global_init ();
     476           0 :       break;
     477             : 
     478             :     case GCRYCTL_FAST_POLL:
     479           0 :       _gcry_set_preferred_rng_type (0);
     480             :       /* We need to do make sure that the random pool is really
     481             :          initialized so that the poll function is not a NOP. */
     482           0 :       _gcry_random_initialize (1);
     483             : 
     484           0 :       if ( fips_is_operational () )
     485           0 :         _gcry_fast_random_poll ();
     486           0 :       break;
     487             : 
     488             :     case GCRYCTL_SET_RNDEGD_SOCKET:
     489             : #if USE_RNDEGD
     490             :       _gcry_set_preferred_rng_type (0);
     491             :       rc = _gcry_rndegd_set_socket_name (va_arg (arg_ptr, const char *));
     492             : #else
     493           0 :       rc = GPG_ERR_NOT_SUPPORTED;
     494             : #endif
     495           0 :       break;
     496             : 
     497             :     case GCRYCTL_SET_RANDOM_DAEMON_SOCKET:
     498           0 :       _gcry_set_preferred_rng_type (0);
     499           0 :       _gcry_set_random_daemon_socket (va_arg (arg_ptr, const char *));
     500           0 :       break;
     501             : 
     502             :     case GCRYCTL_USE_RANDOM_DAEMON:
     503             :       /* We need to do make sure that the random pool is really
     504             :          initialized so that the poll function is not a NOP. */
     505           0 :       _gcry_set_preferred_rng_type (0);
     506           0 :       _gcry_random_initialize (1);
     507           0 :       _gcry_use_random_daemon (!! va_arg (arg_ptr, int));
     508           0 :       break;
     509             : 
     510             :     case GCRYCTL_CLOSE_RANDOM_DEVICE:
     511           0 :       _gcry_random_close_fds ();
     512           0 :       break;
     513             : 
     514             :       /* This command dumps information pertaining to the
     515             :          configuration of libgcrypt to the given stream.  It may be
     516             :          used before the initialization has been finished but not
     517             :          before a gcry_version_check. */
     518             :     case GCRYCTL_PRINT_CONFIG:
     519             :       {
     520           1 :         FILE *fp = va_arg (arg_ptr, FILE *);
     521           1 :         _gcry_set_preferred_rng_type (0);
     522           1 :         print_config (fp?fprintf:_gcry_log_info_with_dummy_fp, fp);
     523             :       }
     524           1 :       break;
     525             : 
     526             :     case GCRYCTL_OPERATIONAL_P:
     527             :       /* Returns true if the library is in an operational state.  This
     528             :          is always true for non-fips mode.  */
     529           0 :       _gcry_set_preferred_rng_type (0);
     530           0 :       if (_gcry_fips_test_operational ())
     531           0 :         rc = GPG_ERR_GENERAL; /* Used as TRUE value */
     532           0 :       break;
     533             : 
     534             :     case GCRYCTL_FIPS_MODE_P:
     535           8 :       if (fips_mode ()
     536           0 :           && !_gcry_is_fips_mode_inactive ()
     537           0 :           && !no_secure_memory)
     538           0 :         rc = GPG_ERR_GENERAL; /* Used as TRUE value */
     539           8 :       break;
     540             : 
     541             :     case GCRYCTL_FORCE_FIPS_MODE:
     542             :       /* Performing this command puts the library into fips mode.  If
     543             :          the library has already been initialized into fips mode, a
     544             :          selftest is triggered.  It is not possible to put the libraty
     545             :          into fips mode after having passed the initialization. */
     546           0 :       _gcry_set_preferred_rng_type (0);
     547           0 :       if (!any_init_done)
     548             :         {
     549             :           /* Not yet intialized at all.  Set a flag so that we are put
     550             :              into fips mode during initialization.  */
     551           0 :           force_fips_mode = 1;
     552             :         }
     553             :       else
     554             :         {
     555             :           /* Already initialized.  If we are already operational we
     556             :              run a selftest.  If not we use the is_operational call to
     557             :              force us into operational state if possible.  */
     558           0 :           if (_gcry_fips_test_error_or_operational ())
     559           0 :             _gcry_fips_run_selftests (1);
     560           0 :           if (_gcry_fips_is_operational ())
     561           0 :             rc = GPG_ERR_GENERAL; /* Used as TRUE value */
     562             :       }
     563           0 :       break;
     564             : 
     565             :     case GCRYCTL_SELFTEST:
     566             :       /* Run a selftest.  This works in fips mode as well as in
     567             :          standard mode.  In contrast to the power-up tests, we use an
     568             :          extended version of the selftests. Returns 0 on success or an
     569             :          error code. */
     570           1 :       global_init ();
     571           1 :       rc = _gcry_fips_run_selftests (1);
     572           1 :       break;
     573             : 
     574             : #if _GCRY_GCC_VERSION >= 40600
     575             : # pragma GCC diagnostic push
     576             : # pragma GCC diagnostic ignored "-Wswitch"
     577             : #endif
     578             :     case 58:  /* Init external random test.  */
     579             :       {
     580           0 :         void **rctx        = va_arg (arg_ptr, void **);
     581           0 :         unsigned int flags = va_arg (arg_ptr, unsigned int);
     582           0 :         const void *key    = va_arg (arg_ptr, const void *);
     583           0 :         size_t keylen      = va_arg (arg_ptr, size_t);
     584           0 :         const void *seed   = va_arg (arg_ptr, const void *);
     585           0 :         size_t seedlen     = va_arg (arg_ptr, size_t);
     586           0 :         const void *dt     = va_arg (arg_ptr, const void *);
     587           0 :         size_t dtlen       = va_arg (arg_ptr, size_t);
     588           0 :         if (!fips_is_operational ())
     589           0 :           rc = fips_not_operational ();
     590             :         else
     591           0 :           rc = _gcry_random_init_external_test (rctx, flags, key, keylen,
     592             :                                                 seed, seedlen, dt, dtlen);
     593             :       }
     594           0 :       break;
     595             :     case 59:  /* Run external random test.  */
     596             :       {
     597           0 :         void *ctx     = va_arg (arg_ptr, void *);
     598           0 :         void *buffer  = va_arg (arg_ptr, void *);
     599           0 :         size_t buflen = va_arg (arg_ptr, size_t);
     600           0 :         if (!fips_is_operational ())
     601           0 :           rc = fips_not_operational ();
     602             :         else
     603           0 :           rc = _gcry_random_run_external_test (ctx, buffer, buflen);
     604             :       }
     605           0 :       break;
     606             :     case 60:  /* Deinit external random test.  */
     607             :       {
     608           0 :         void *ctx = va_arg (arg_ptr, void *);
     609           0 :         _gcry_random_deinit_external_test (ctx);
     610             :       }
     611           0 :       break;
     612             :     case 61:  /* Run external lock test */
     613       24223 :       rc = external_lock_test (va_arg (arg_ptr, int));
     614       24112 :       break;
     615             :     case 62:  /* RFU */
     616           0 :       break;
     617             : #if _GCRY_GCC_VERSION >= 40600
     618             : # pragma GCC diagnostic pop
     619             : #endif
     620             : 
     621             :     case GCRYCTL_DISABLE_HWF:
     622             :       {
     623           0 :         const char *name = va_arg (arg_ptr, const char *);
     624           0 :         rc = _gcry_disable_hw_feature (name);
     625             :       }
     626           0 :       break;
     627             : 
     628             :     case GCRYCTL_SET_ENFORCED_FIPS_FLAG:
     629           0 :       if (!any_init_done)
     630             :         {
     631             :           /* Not yet initialized at all.  Set the enforced fips mode flag */
     632           0 :           _gcry_set_preferred_rng_type (0);
     633           0 :           _gcry_set_enforced_fips_mode ();
     634             :         }
     635             :       else
     636           0 :         rc = GPG_ERR_GENERAL;
     637           0 :       break;
     638             : 
     639             :     case GCRYCTL_SET_PREFERRED_RNG_TYPE:
     640             :       /* This may be called before gcry_check_version.  */
     641             :       {
     642          42 :         int i = va_arg (arg_ptr, int);
     643             :         /* Note that we may not pass 0 to _gcry_set_preferred_rng_type.  */
     644          42 :         if (i > 0)
     645          42 :           _gcry_set_preferred_rng_type (i);
     646             :       }
     647          42 :       break;
     648             : 
     649             :     case GCRYCTL_GET_CURRENT_RNG_TYPE:
     650             :       {
     651          80 :         int *ip = va_arg (arg_ptr, int*);
     652          80 :         if (ip)
     653          80 :           *ip = _gcry_get_rng_type (!any_init_done);
     654             :       }
     655          80 :       break;
     656             : 
     657             :     case GCRYCTL_DISABLE_LOCKED_SECMEM:
     658           0 :       _gcry_set_preferred_rng_type (0);
     659           0 :       _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
     660             :                                | GCRY_SECMEM_FLAG_NO_MLOCK));
     661           0 :       break;
     662             : 
     663             :     case GCRYCTL_DISABLE_PRIV_DROP:
     664           0 :       _gcry_set_preferred_rng_type (0);
     665           0 :       _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
     666             :                                | GCRY_SECMEM_FLAG_NO_PRIV_DROP));
     667           0 :       break;
     668             : 
     669             :     case GCRYCTL_INACTIVATE_FIPS_FLAG:
     670             :     case GCRYCTL_REACTIVATE_FIPS_FLAG:
     671           0 :       rc = GPG_ERR_NOT_IMPLEMENTED;
     672           0 :       break;
     673             : 
     674             :     default:
     675           0 :       _gcry_set_preferred_rng_type (0);
     676           0 :       rc = GPG_ERR_INV_OP;
     677             :     }
     678             : 
     679       24336 :   return rc;
     680             : }
     681             : 
     682             : 
     683             : 
     684             : /* Set custom allocation handlers.  This is in general not useful
     685             :  * because the libgcrypt allocation functions are guaranteed to
     686             :  * provide proper allocation handlers which zeroize memory if needed.
     687             :  * NOTE: All 5 functions should be set.  */
     688             : void
     689           0 : _gcry_set_allocation_handler (gcry_handler_alloc_t new_alloc_func,
     690             :                               gcry_handler_alloc_t new_alloc_secure_func,
     691             :                               gcry_handler_secure_check_t new_is_secure_func,
     692             :                               gcry_handler_realloc_t new_realloc_func,
     693             :                               gcry_handler_free_t new_free_func)
     694             : {
     695           0 :   global_init ();
     696             : 
     697           0 :   if (fips_mode ())
     698             :     {
     699             :       /* We do not want to enforce the fips mode, but merely set a
     700             :          flag so that the application may check whether it is still in
     701             :          fips mode.  */
     702           0 :       _gcry_inactivate_fips_mode ("custom allocation handler");
     703             :     }
     704             : 
     705           0 :   alloc_func = new_alloc_func;
     706           0 :   alloc_secure_func = new_alloc_secure_func;
     707           0 :   is_secure_func = new_is_secure_func;
     708           0 :   realloc_func = new_realloc_func;
     709           0 :   free_func = new_free_func;
     710           0 : }
     711             : 
     712             : 
     713             : 
     714             : /****************
     715             :  * Set an optional handler which is called in case the xmalloc functions
     716             :  * ran out of memory.  This handler may do one of these things:
     717             :  *   o free some memory and return true, so that the xmalloc function
     718             :  *     tries again.
     719             :  *   o Do whatever it like and return false, so that the xmalloc functions
     720             :  *     use the default fatal error handler.
     721             :  *   o Terminate the program and don't return.
     722             :  *
     723             :  * The handler function is called with 3 arguments:  The opaque value set with
     724             :  * this function, the requested memory size, and a flag with these bits
     725             :  * currently defined:
     726             :  *      bit 0 set = secure memory has been requested.
     727             :  */
     728             : void
     729           0 : _gcry_set_outofcore_handler (int (*f)(void*, size_t, unsigned int), void *value)
     730             : {
     731           0 :   global_init ();
     732             : 
     733           0 :   if (fips_mode () )
     734             :     {
     735           0 :       log_info ("out of core handler ignored in FIPS mode\n");
     736           0 :       return;
     737             :     }
     738             : 
     739           0 :   outofcore_handler = f;
     740           0 :   outofcore_handler_value = value;
     741             : }
     742             : 
     743             : /* Return the no_secure_memory flag.  */
     744             : static int
     745      650107 : get_no_secure_memory (void)
     746             : {
     747      650107 :   if (!no_secure_memory)
     748         390 :     return 0;
     749      649717 :   if (_gcry_enforced_fips_mode ())
     750             :     {
     751           0 :       no_secure_memory = 0;
     752           0 :       return 0;
     753             :     }
     754      649717 :   return no_secure_memory;
     755             : }
     756             : 
     757             : 
     758             : static gcry_err_code_t
     759    75128912 : do_malloc (size_t n, unsigned int flags, void **mem)
     760             : {
     761    75128912 :   gcry_err_code_t err = 0;
     762             :   void *m;
     763             : 
     764    75128912 :   if ((flags & GCRY_ALLOC_FLAG_SECURE) && !get_no_secure_memory ())
     765             :     {
     766           6 :       if (alloc_secure_func)
     767           0 :         m = (*alloc_secure_func) (n);
     768             :       else
     769           3 :         m = _gcry_private_malloc_secure (n);
     770             :     }
     771             :   else
     772             :     {
     773    75128909 :       if (alloc_func)
     774           0 :         m = (*alloc_func) (n);
     775             :       else
     776    75128909 :         m = _gcry_private_malloc (n);
     777             :     }
     778             : 
     779    75128912 :   if (!m)
     780             :     {
     781             :       /* Make sure that ERRNO has been set in case a user supplied
     782             :          memory handler didn't it correctly. */
     783           0 :       if (!errno)
     784           0 :         gpg_err_set_errno (ENOMEM);
     785           0 :       err = gpg_err_code_from_errno (errno);
     786             :     }
     787             :   else
     788    75128912 :     *mem = m;
     789             : 
     790    75128912 :   return err;
     791             : }
     792             : 
     793             : void *
     794    74799657 : _gcry_malloc (size_t n)
     795             : {
     796    74799657 :   void *mem = NULL;
     797             : 
     798    74799657 :   do_malloc (n, 0, &mem);
     799             : 
     800    74799657 :   return mem;
     801             : }
     802             : 
     803             : void *
     804      329255 : _gcry_malloc_secure (size_t n)
     805             : {
     806      329255 :   void *mem = NULL;
     807             : 
     808      329255 :   do_malloc (n, GCRY_ALLOC_FLAG_SECURE, &mem);
     809             : 
     810      329255 :   return mem;
     811             : }
     812             : 
     813             : int
     814      320852 : _gcry_is_secure (const void *a)
     815             : {
     816      320852 :   if (get_no_secure_memory ())
     817      320465 :     return 0;
     818         387 :   if (is_secure_func)
     819           0 :     return is_secure_func (a) ;
     820         387 :   return _gcry_private_is_secure (a);
     821             : }
     822             : 
     823             : void
     824           0 : _gcry_check_heap( const void *a )
     825             : {
     826             :   (void)a;
     827             : 
     828             :     /* FIXME: implement this*/
     829             : #if 0
     830             :     if( some_handler )
     831             :         some_handler(a)
     832             :     else
     833             :         _gcry_private_check_heap(a)
     834             : #endif
     835           0 : }
     836             : 
     837             : void *
     838      195169 : _gcry_realloc (void *a, size_t n)
     839             : {
     840             :   void *p;
     841             : 
     842             :   /* To avoid problems with non-standard realloc implementations and
     843             :      our own secmem_realloc, we divert to malloc and free here.  */
     844      195169 :   if (!a)
     845           0 :     return _gcry_malloc (n);
     846      195169 :   if (!n)
     847             :     {
     848           0 :       xfree (a);
     849           0 :       return NULL;
     850             :     }
     851             : 
     852      195169 :   if (realloc_func)
     853           0 :     p = realloc_func (a, n);
     854             :   else
     855      195169 :     p =  _gcry_private_realloc (a, n);
     856      195169 :   if (!p && !errno)
     857           0 :     gpg_err_set_errno (ENOMEM);
     858      195169 :   return p;
     859             : }
     860             : 
     861             : void
     862    75146241 : _gcry_free (void *p)
     863             : {
     864             :   int save_errno;
     865             : 
     866    75146241 :   if (!p)
     867    75164566 :     return;
     868             : 
     869             :   /* In case ERRNO is set we better save it so that the free machinery
     870             :      may not accidently change ERRNO.  We restore it only if it was
     871             :      already set to comply with the usual C semantic for ERRNO.  */
     872    75127916 :   save_errno = errno;
     873    75127916 :   if (free_func)
     874           0 :     free_func (p);
     875             :   else
     876    75127916 :     _gcry_private_free (p);
     877             : 
     878    75127916 :   if (save_errno)
     879    75127908 :     gpg_err_set_errno (save_errno);
     880             : }
     881             : 
     882             : void *
     883        5047 : _gcry_calloc (size_t n, size_t m)
     884             : {
     885             :   size_t bytes;
     886             :   void *p;
     887             : 
     888        5047 :   bytes = n * m; /* size_t is unsigned so the behavior on overflow is
     889             :                     defined. */
     890        5047 :   if (m && bytes / m != n)
     891             :     {
     892           0 :       gpg_err_set_errno (ENOMEM);
     893           0 :       return NULL;
     894             :     }
     895             : 
     896        5047 :   p = _gcry_malloc (bytes);
     897        5047 :   if (p)
     898        5047 :     memset (p, 0, bytes);
     899        5047 :   return p;
     900             : }
     901             : 
     902             : void *
     903        1158 : _gcry_calloc_secure (size_t n, size_t m)
     904             : {
     905             :   size_t bytes;
     906             :   void *p;
     907             : 
     908        1158 :   bytes = n * m; /* size_t is unsigned so the behavior on overflow is
     909             :                     defined. */
     910        1158 :   if (m && bytes / m != n)
     911             :     {
     912           0 :       gpg_err_set_errno (ENOMEM);
     913           0 :       return NULL;
     914             :     }
     915             : 
     916        1158 :   p = _gcry_malloc_secure (bytes);
     917        1158 :   if (p)
     918        1158 :     memset (p, 0, bytes);
     919        1158 :   return p;
     920             : }
     921             : 
     922             : 
     923             : /* Create and return a copy of the null-terminated string STRING.  If
     924             :    it is contained in secure memory, the copy will be contained in
     925             :    secure memory as well.  In an out-of-memory condition, NULL is
     926             :    returned.  */
     927             : char *
     928        9242 : _gcry_strdup (const char *string)
     929             : {
     930        9242 :   char *string_cp = NULL;
     931        9242 :   size_t string_n = 0;
     932             : 
     933        9242 :   string_n = strlen (string);
     934             : 
     935        9242 :   if (_gcry_is_secure (string))
     936           0 :     string_cp = _gcry_malloc_secure (string_n + 1);
     937             :   else
     938        9242 :     string_cp = _gcry_malloc (string_n + 1);
     939             : 
     940        9242 :   if (string_cp)
     941        9242 :     strcpy (string_cp, string);
     942             : 
     943        9242 :   return string_cp;
     944             : }
     945             : 
     946             : 
     947             : void *
     948    74385393 : _gcry_xmalloc( size_t n )
     949             : {
     950             :   void *p;
     951             : 
     952   148770786 :   while ( !(p = _gcry_malloc( n )) )
     953             :     {
     954           0 :       if ( fips_mode ()
     955           0 :            || !outofcore_handler
     956           0 :            || !outofcore_handler (outofcore_handler_value, n, 0) )
     957             :         {
     958           0 :           _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL);
     959             :         }
     960             :     }
     961    74385393 :     return p;
     962             : }
     963             : 
     964             : void *
     965      178206 : _gcry_xrealloc( void *a, size_t n )
     966             : {
     967             :   void *p;
     968             : 
     969      356412 :   while ( !(p = _gcry_realloc( a, n )) )
     970             :     {
     971           0 :       if ( fips_mode ()
     972           0 :            || !outofcore_handler
     973           0 :            || !outofcore_handler (outofcore_handler_value, n,
     974           0 :                                   _gcry_is_secure(a)? 3:2))
     975             :         {
     976           0 :           _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL );
     977             :         }
     978             :     }
     979      178206 :     return p;
     980             : }
     981             : 
     982             : void *
     983      325275 : _gcry_xmalloc_secure( size_t n )
     984             : {
     985             :   void *p;
     986             : 
     987      650550 :   while ( !(p = _gcry_malloc_secure( n )) )
     988             :     {
     989           0 :       if ( fips_mode ()
     990           0 :            || !outofcore_handler
     991           0 :            || !outofcore_handler (outofcore_handler_value, n, 1) )
     992             :         {
     993           0 :           _gcry_fatal_error (gpg_err_code_from_errno (errno),
     994             :                              _("out of core in secure memory"));
     995             :         }
     996             :     }
     997      325275 :   return p;
     998             : }
     999             : 
    1000             : 
    1001             : void *
    1002       68232 : _gcry_xcalloc( size_t n, size_t m )
    1003             : {
    1004             :   size_t nbytes;
    1005             :   void *p;
    1006             : 
    1007       68232 :   nbytes = n * m;
    1008       68232 :   if (m && nbytes / m != n)
    1009             :     {
    1010           0 :       gpg_err_set_errno (ENOMEM);
    1011           0 :       _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL );
    1012             :     }
    1013             : 
    1014       68232 :   p = _gcry_xmalloc ( nbytes );
    1015       68232 :   memset ( p, 0, nbytes );
    1016       68232 :   return p;
    1017             : }
    1018             : 
    1019             : void *
    1020        1216 : _gcry_xcalloc_secure( size_t n, size_t m )
    1021             : {
    1022             :   size_t nbytes;
    1023             :   void *p;
    1024             : 
    1025        1216 :   nbytes = n * m;
    1026        1216 :   if (m && nbytes / m != n)
    1027             :     {
    1028           0 :       gpg_err_set_errno (ENOMEM);
    1029           0 :       _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL );
    1030             :     }
    1031             : 
    1032        1216 :   p = _gcry_xmalloc_secure ( nbytes );
    1033        1216 :   memset ( p, 0, nbytes );
    1034        1216 :   return p;
    1035             : }
    1036             : 
    1037             : char *
    1038        9242 : _gcry_xstrdup (const char *string)
    1039             : {
    1040             :   char *p;
    1041             : 
    1042       18484 :   while ( !(p = _gcry_strdup (string)) )
    1043             :     {
    1044           0 :       size_t n = strlen (string);
    1045           0 :       int is_sec = !!_gcry_is_secure (string);
    1046             : 
    1047           0 :       if (fips_mode ()
    1048           0 :           || !outofcore_handler
    1049           0 :           || !outofcore_handler (outofcore_handler_value, n, is_sec) )
    1050             :         {
    1051           0 :           _gcry_fatal_error (gpg_err_code_from_errno (errno),
    1052             :                              is_sec? _("out of core in secure memory"):NULL);
    1053             :         }
    1054             :     }
    1055             : 
    1056        9242 :   return p;
    1057             : }
    1058             : 
    1059             : 
    1060             : int
    1061       33455 : _gcry_get_debug_flag (unsigned int mask)
    1062             : {
    1063       33455 :   if ( fips_mode () )
    1064           0 :     return 0;
    1065       33455 :   return (debug_flags & mask);
    1066             : }
    1067             : 
    1068             : 
    1069             : 
    1070             : /* It is often useful to get some feedback of long running operations.
    1071             :    This function may be used to register a handler for this.
    1072             :    The callback function CB is used as:
    1073             : 
    1074             :    void cb (void *opaque, const char *what, int printchar,
    1075             :            int current, int total);
    1076             : 
    1077             :    Where WHAT is a string identifying the the type of the progress
    1078             :    output, PRINTCHAR the character usually printed, CURRENT the amount
    1079             :    of progress currently done and TOTAL the expected amount of
    1080             :    progress.  A value of 0 for TOTAL indicates that there is no
    1081             :    estimation available.
    1082             : 
    1083             :    Defined values for WHAT:
    1084             : 
    1085             :    "need_entropy"  X    0  number-of-bytes-required
    1086             :             When running low on entropy
    1087             :    "primegen"      '\n'  0 0
    1088             :            Prime generated
    1089             :                    '!'
    1090             :            Need to refresh the prime pool
    1091             :                    '<','>'
    1092             :            Number of bits adjusted
    1093             :                    '^'
    1094             :            Looking for a generator
    1095             :                    '.'
    1096             :            Fermat tests on 10 candidates failed
    1097             :                   ':'
    1098             :            Restart with a new random value
    1099             :                   '+'
    1100             :            Rabin Miller test passed
    1101             :    "pk_elg"        '+','-','.','\n'   0  0
    1102             :             Only used in debugging mode.
    1103             :    "pk_dsa"
    1104             :             Only used in debugging mode.
    1105             : */
    1106             : void
    1107           1 : _gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int),
    1108             :                             void *cb_data)
    1109             : {
    1110             : #if USE_DSA
    1111           1 :   _gcry_register_pk_dsa_progress (cb, cb_data);
    1112             : #endif
    1113             : #if USE_ELGAMAL
    1114           1 :   _gcry_register_pk_elg_progress (cb, cb_data);
    1115             : #endif
    1116           1 :   _gcry_register_primegen_progress (cb, cb_data);
    1117           1 :   _gcry_register_random_progress (cb, cb_data);
    1118           1 : }
    1119             : 
    1120             : 
    1121             : 
    1122             : /* This is a helper for the regression test suite to test Libgcrypt's locks.
    1123             :    It works using a one test lock with CMD controlling what to do:
    1124             : 
    1125             :      30111 - Allocate and init lock
    1126             :      30112 - Take lock
    1127             :      30113 - Release lock
    1128             :      30114 - Destroy lock.
    1129             : 
    1130             :    This function is used by tests/t-lock.c - it is not part of the
    1131             :    public API!
    1132             :  */
    1133             : static gpg_err_code_t
    1134       24785 : external_lock_test (int cmd)
    1135             : {
    1136             :   GPGRT_LOCK_DEFINE (testlock);
    1137       24785 :   gpg_err_code_t rc = 0;
    1138             : 
    1139       24785 :   switch (cmd)
    1140             :     {
    1141             :     case 30111:  /* Init Lock.  */
    1142           2 :       rc = gpgrt_lock_init (&testlock);
    1143           0 :       break;
    1144             : 
    1145             :     case 30112:  /* Take Lock.  */
    1146       12341 :       rc = gpgrt_lock_lock (&testlock);
    1147       12440 :       break;
    1148             : 
    1149             :     case 30113:  /* Release Lock.  */
    1150       12440 :       rc = gpgrt_lock_unlock (&testlock);
    1151       12357 :       break;
    1152             : 
    1153             :     case 30114:  /* Destroy Lock.  */
    1154           2 :       rc = gpgrt_lock_destroy (&testlock);
    1155           2 :       break;
    1156             : 
    1157             :     default:
    1158           0 :       rc = GPG_ERR_INV_OP;
    1159           0 :       break;
    1160             :     }
    1161             : 
    1162       24168 :   return rc;
    1163             : }

Generated by: LCOV version 1.11