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

Generated by: LCOV version 1.11