LCOV - code coverage report
Current view: top level - g10 - passphrase.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 108 210 51.4 %
Date: 2016-11-29 15:00:56 Functions: 7 12 58.3 %

          Line data    Source code
       1             : /* passphrase.c -  Get a passphrase
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
       3             :  *               2005, 2006, 2007, 2009, 2011 Free Software Foundation, Inc.
       4             :  *
       5             :  * This file is part of GnuPG.
       6             :  *
       7             :  * GnuPG is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU General Public License as published by
       9             :  * the Free Software Foundation; either version 3 of the License, or
      10             :  * (at your option) any later version.
      11             :  *
      12             :  * GnuPG is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU General Public License
      18             :  * along with this program; if not, see <https://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : #include <stddef.h>
      23             : #include <stdio.h>
      24             : #include <stdlib.h>
      25             : #include <string.h>
      26             : #include <unistd.h>
      27             : #include <errno.h>
      28             : #ifdef HAVE_LOCALE_H
      29             : #include <locale.h>
      30             : #endif
      31             : #ifdef HAVE_LANGINFO_CODESET
      32             : #include <langinfo.h>
      33             : #endif
      34             : 
      35             : #include "gpg.h"
      36             : #include "util.h"
      37             : #include "options.h"
      38             : #include "ttyio.h"
      39             : #include "keydb.h"
      40             : #include "main.h"
      41             : #include "i18n.h"
      42             : #include "status.h"
      43             : #include "call-agent.h"
      44             : #include "../common/shareddefs.h"
      45             : 
      46             : static char *fd_passwd = NULL;
      47             : static char *next_pw = NULL;
      48             : static char *last_pw = NULL;
      49             : 
      50             : 
      51             : 
      52             : /* Pack an s2k iteration count into the form specified in 2440.  If
      53             :    we're in between valid values, round up.  With value 0 return the
      54             :    old default.  */
      55             : unsigned char
      56         112 : encode_s2k_iterations (int iterations)
      57             : {
      58             :   gpg_error_t err;
      59         112 :   unsigned char c=0;
      60             :   unsigned char result;
      61             :   unsigned int count;
      62             : 
      63         112 :   if (!iterations)
      64             :     {
      65             :       unsigned long mycnt;
      66             : 
      67             :       /* Ask the gpg-agent for a useful iteration count.  */
      68           3 :       err = agent_get_s2k_count (&mycnt);
      69           3 :       if (err || mycnt < 65536)
      70             :         {
      71             :           /* Don't print an error if an older agent is used.  */
      72           0 :           if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER)
      73           0 :             log_error (_("problem with the agent: %s\n"), gpg_strerror (err));
      74             :           /* Default to 65536 which we used up to 2.0.13.  */
      75           0 :           return 96;
      76             :         }
      77           3 :       else if (mycnt >= 65011712)
      78           0 :         return 255; /* Largest possible value.  */
      79             :       else
      80           3 :         return encode_s2k_iterations ((int)mycnt);
      81             :     }
      82             : 
      83         109 :   if (iterations <= 1024)
      84           0 :     return 0;  /* Command line arg compatibility.  */
      85             : 
      86         109 :   if (iterations >= 65011712)
      87           0 :     return 255;
      88             : 
      89             :   /* Need count to be in the range 16-31 */
      90         787 :   for (count=iterations>>6; count>=32; count>>=1)
      91         678 :     c++;
      92             : 
      93         109 :   result = (c<<4)|(count-16);
      94             : 
      95         109 :   if (S2K_DECODE_COUNT(result) < iterations)
      96           3 :     result++;
      97             : 
      98         109 :   return result;
      99             : }
     100             : 
     101             : 
     102             : int
     103         114 : have_static_passphrase()
     104             : {
     105         228 :   return (!!fd_passwd
     106         114 :           && (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
     107             : }
     108             : 
     109             : /* Return a static passphrase.  The returned value is only valid as
     110             :    long as no other passphrase related function is called.  NULL may
     111             :    be returned if no passphrase has been set; better use
     112             :    have_static_passphrase first.  */
     113             : const char *
     114           0 : get_static_passphrase (void)
     115             : {
     116           0 :   return fd_passwd;
     117             : }
     118             : 
     119             : 
     120             : /****************
     121             :  * Set the passphrase to be used for the next query and only for the next
     122             :  * one.
     123             :  */
     124             : void
     125           4 : set_next_passphrase( const char *s )
     126             : {
     127           4 :   xfree(next_pw);
     128           4 :   next_pw = NULL;
     129           4 :   if ( s )
     130             :     {
     131           0 :       next_pw = xmalloc_secure( strlen(s)+1 );
     132           0 :       strcpy (next_pw, s );
     133             :     }
     134           4 : }
     135             : 
     136             : /****************
     137             :  * Get the last passphrase used in passphrase_to_dek.
     138             :  * Note: This removes the passphrase from this modules and
     139             :  * the caller must free the result.  May return NULL:
     140             :  */
     141             : char *
     142           3 : get_last_passphrase()
     143             : {
     144           3 :   char *p = last_pw;
     145           3 :   last_pw = NULL;
     146           3 :   return p;
     147             : }
     148             : 
     149             : /* Here's an interesting question: since this passphrase was passed in
     150             :    on the command line, is there really any point in using secure
     151             :    memory for it?  I'm going with 'yes', since it doesn't hurt, and
     152             :    might help in some small way (swapping). */
     153             : 
     154             : void
     155           0 : set_passphrase_from_string(const char *pass)
     156             : {
     157           0 :   xfree (fd_passwd);
     158           0 :   fd_passwd = xmalloc_secure(strlen(pass)+1);
     159           0 :   strcpy (fd_passwd, pass);
     160           0 : }
     161             : 
     162             : 
     163             : void
     164         188 : read_passphrase_from_fd( int fd )
     165             : {
     166             :   int i, len;
     167             :   char *pw;
     168             : 
     169         188 :   if ( !opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
     170             :     { /* Not used but we have to do a dummy read, so that it won't end
     171             :          up at the begin of the message if the quite usual trick to
     172             :          prepend the passphtrase to the message is used. */
     173             :       char buf[1];
     174             : 
     175           0 :       while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
     176             :         ;
     177           0 :       *buf = 0;
     178         188 :       return;
     179             :     }
     180             : 
     181        2337 :   for (pw = NULL, i = len = 100; ; i++ )
     182             :     {
     183        2337 :       if (i >= len-1 )
     184             :         {
     185         188 :           char *pw2 = pw;
     186         188 :           len += 100;
     187         188 :           pw = xmalloc_secure( len );
     188         188 :           if( pw2 )
     189             :             {
     190           0 :               memcpy(pw, pw2, i );
     191           0 :               xfree (pw2);
     192             :             }
     193             :           else
     194         188 :             i=0;
     195             :         }
     196        2337 :       if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
     197             :         break;
     198        2149 :     }
     199         188 :   pw[i] = 0;
     200         188 :   if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
     201           0 :     tty_printf("\b\b\b   \n" );
     202             : 
     203         188 :   xfree ( fd_passwd );
     204         188 :   fd_passwd = pw;
     205             : }
     206             : 
     207             : 
     208             : /*
     209             :  * Ask the GPG Agent for the passphrase.
     210             :  * If NOCACHE is set the symmetric passpharse caching will not be used.
     211             :  *
     212             :  * Note that TRYAGAIN_TEXT must not be translated.  If CANCELED is not
     213             :  * NULL, the function does set it to 1 if the user canceled the
     214             :  * operation.  If CACHEID is not NULL, it will be used as the cacheID
     215             :  * for the gpg-agent; if is NULL and a key fingerprint can be
     216             :  * computed, this will be used as the cacheid.
     217             :  */
     218             : static char *
     219           0 : passphrase_get (int nocache, const char *cacheid, int repeat,
     220             :                 const char *tryagain_text, int *canceled)
     221             : {
     222             :   int rc;
     223           0 :   char *pw = NULL;
     224             :   char *orig_codeset;
     225             :   const char *my_cacheid;
     226             : 
     227           0 :   if (canceled)
     228           0 :     *canceled = 0;
     229             : 
     230           0 :   orig_codeset = i18n_switchto_utf8 ();
     231             : 
     232           0 :   if (!nocache && cacheid)
     233           0 :     my_cacheid = cacheid;
     234             :   else
     235           0 :     my_cacheid = NULL;
     236             : 
     237           0 :   if (tryagain_text)
     238           0 :     tryagain_text = _(tryagain_text);
     239             : 
     240           0 :   rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
     241           0 :                              _("Enter passphrase\n"),
     242             :                              repeat, nocache, &pw);
     243             : 
     244           0 :   i18n_switchback (orig_codeset);
     245             : 
     246             : 
     247           0 :   if (!rc)
     248             :     ;
     249           0 :   else if (gpg_err_code (rc) == GPG_ERR_CANCELED
     250           0 :             || gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
     251             :     {
     252           0 :       log_info (_("cancelled by user\n") );
     253           0 :       if (canceled)
     254           0 :         *canceled = 1;
     255             :     }
     256             :   else
     257             :     {
     258           0 :       log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
     259             :       /* Due to limitations in the API of the upper layers they
     260             :          consider an error as no passphrase entered.  This works in
     261             :          most cases but not during key creation where this should
     262             :          definitely not happen and let it continue without requiring a
     263             :          passphrase.  Given that now all the upper layers handle a
     264             :          cancel correctly, we simply set the cancel flag now for all
     265             :          errors from the agent.  */
     266           0 :       if (canceled)
     267           0 :         *canceled = 1;
     268             : 
     269           0 :       write_status_errcode ("get_passphrase", rc);
     270             :     }
     271             : 
     272           0 :   if (rc)
     273             :     {
     274           0 :       xfree (pw);
     275           0 :       pw = NULL;
     276             :     }
     277           0 :   return pw;
     278             : }
     279             : 
     280             : 
     281             : /*
     282             :  * Clear the cached passphrase with CACHEID.
     283             :  */
     284             : void
     285           0 : passphrase_clear_cache (const char *cacheid)
     286             : {
     287             :   int rc;
     288             : 
     289           0 :   rc = agent_clear_passphrase (cacheid);
     290           0 :   if (rc)
     291           0 :     log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
     292           0 : }
     293             : 
     294             : 
     295             : /* Return a new DEK object using the string-to-key specifier S2K.
     296             :  * Returns NULL if the user canceled the passphrase entry and if
     297             :  * CANCELED is not NULL, sets it to true.
     298             :  *
     299             :  * If CREATE is true a new passphrase sll be created.  If NOCACHE is
     300             :  * true the symmetric key caching will not be used.  */
     301             : DEK *
     302         113 : passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
     303             :                    int create, int nocache,
     304             :                    const char *tryagain_text, int *canceled)
     305             : {
     306         113 :   char *pw = NULL;
     307             :   DEK *dek;
     308             :   STRING2KEY help_s2k;
     309             :   int dummy_canceled;
     310             :   char s2k_cacheidbuf[1+16+1];
     311         113 :   char *s2k_cacheid = NULL;
     312             : 
     313         113 :   if (!canceled)
     314          57 :     canceled = &dummy_canceled;
     315         113 :   *canceled = 0;
     316             : 
     317         113 :   if ( !s2k )
     318             :     {
     319           0 :       log_assert (create && !nocache);
     320             :       /* This is used for the old rfc1991 mode
     321             :        * Note: This must match the code in encode.c with opt.rfc1991 set */
     322           0 :       s2k = &help_s2k;
     323           0 :       s2k->mode = 0;
     324           0 :       s2k->hash_algo = S2K_DIGEST_ALGO;
     325             :     }
     326             : 
     327             :   /* Create a new salt or what else to be filled into the s2k for a
     328             :      new key.  */
     329         113 :   if (create && (s2k->mode == 1 || s2k->mode == 3))
     330             :     {
     331          56 :       gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
     332          56 :       if ( s2k->mode == 3 )
     333             :         {
     334             :           /* We delay the encoding until it is really needed.  This is
     335             :              if we are going to dynamically calibrate it, we need to
     336             :              call out to gpg-agent and that should not be done during
     337             :              option processing in main().  */
     338          56 :           if (!opt.s2k_count)
     339           3 :             opt.s2k_count = encode_s2k_iterations (0);
     340          56 :           s2k->count = opt.s2k_count;
     341             :         }
     342             :     }
     343             : 
     344             :   /* If we do not have a passphrase available in NEXT_PW and status
     345             :      information are request, we print them now. */
     346         113 :   if ( !next_pw && is_status_enabled() )
     347             :     {
     348             :       char buf[50];
     349             : 
     350           0 :       snprintf (buf, sizeof buf, "%d %d %d",
     351           0 :                 cipher_algo, s2k->mode, s2k->hash_algo );
     352           0 :       write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
     353             :     }
     354             : 
     355         113 :   if ( next_pw )
     356             :     {
     357             :       /* Simply return the passphrase we already have in NEXT_PW. */
     358           0 :       pw = next_pw;
     359           0 :       next_pw = NULL;
     360             :     }
     361         113 :   else if ( have_static_passphrase () )
     362             :     {
     363             :       /* Return the passphrase we have stored in FD_PASSWD. */
     364         113 :       pw = xmalloc_secure ( strlen(fd_passwd)+1 );
     365         113 :       strcpy ( pw, fd_passwd );
     366             :     }
     367             :   else
     368             :     {
     369           0 :       if (!nocache && (s2k->mode == 1 || s2k->mode == 3))
     370             :         {
     371           0 :           memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
     372           0 :           *s2k_cacheidbuf = 'S';
     373           0 :           bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
     374           0 :           s2k_cacheid = s2k_cacheidbuf;
     375             :         }
     376             : 
     377           0 :       if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
     378             :         {
     379             :           char buf[32];
     380             : 
     381           0 :           snprintf (buf, sizeof (buf), "%u", 100);
     382           0 :           write_status_text (STATUS_INQUIRE_MAXLEN, buf);
     383             :         }
     384             : 
     385             :       /* Divert to the gpg-agent. */
     386           0 :       pw = passphrase_get (create && nocache, s2k_cacheid,
     387             :                            create? opt.passphrase_repeat : 0,
     388             :                            tryagain_text, canceled);
     389           0 :       if (*canceled)
     390             :         {
     391           0 :           xfree (pw);
     392           0 :           write_status( STATUS_MISSING_PASSPHRASE );
     393           0 :           return NULL;
     394             :         }
     395             :     }
     396             : 
     397         113 :   if ( !pw || !*pw )
     398           0 :     write_status( STATUS_MISSING_PASSPHRASE );
     399             : 
     400             :   /* Hash the passphrase and store it in a newly allocated DEK object.
     401             :      Keep a copy of the passphrase in LAST_PW for use by
     402             :      get_last_passphrase(). */
     403         113 :   dek = xmalloc_secure_clear ( sizeof *dek );
     404         113 :   dek->algo = cipher_algo;
     405         113 :   if ( (!pw || !*pw) && create)
     406           0 :     dek->keylen = 0;
     407             :   else
     408             :     {
     409             :       gpg_error_t err;
     410             : 
     411         113 :       dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
     412         113 :       if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
     413           0 :         BUG ();
     414         452 :       err = gcry_kdf_derive (pw, strlen (pw),
     415         113 :                              s2k->mode == 3? GCRY_KDF_ITERSALTED_S2K :
     416           0 :                              s2k->mode == 1? GCRY_KDF_SALTED_S2K :
     417             :                              /* */           GCRY_KDF_SIMPLE_S2K,
     418         113 :                              s2k->hash_algo, s2k->salt, 8,
     419         113 :                              S2K_DECODE_COUNT(s2k->count),
     420         113 :                              dek->keylen, dek->key);
     421         113 :       if (err)
     422             :         {
     423           0 :           log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
     424           0 :           xfree (pw);
     425           0 :           xfree (dek);
     426           0 :           write_status( STATUS_MISSING_PASSPHRASE );
     427           0 :           return NULL;
     428             :         }
     429             :     }
     430         113 :   if (s2k_cacheid)
     431           0 :     memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
     432         113 :   xfree(last_pw);
     433         113 :   last_pw = pw;
     434         113 :   return dek;
     435             : }
     436             : 
     437             : 
     438             : /* Emit the USERID_HINT and the NEED_PASSPHRASE status messages.
     439             :    MAINKEYID may be NULL. */
     440             : void
     441           0 : emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo)
     442             : {
     443             :   char buf[50];
     444             :   char *us;
     445             : 
     446           0 :   us = get_long_user_id_string (keyid);
     447           0 :   write_status_text (STATUS_USERID_HINT, us);
     448           0 :   xfree (us);
     449             : 
     450           0 :   snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
     451           0 :             (ulong)keyid[0],
     452           0 :             (ulong)keyid[1],
     453           0 :             (ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
     454           0 :             (ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
     455             :             pubkey_algo);
     456             : 
     457           0 :   write_status_text (STATUS_NEED_PASSPHRASE, buf);
     458           0 : }
     459             : 
     460             : 
     461             : /* Return an allocated utf-8 string describing the key PK.  If ESCAPED
     462             :    is true spaces and control characters are percent or plus escaped.
     463             :    MODE describes the use of the key description; use one of the
     464             :    FORMAT_KEYDESC_ macros. */
     465             : char *
     466         441 : gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped)
     467             : {
     468             :   char *uid;
     469             :   size_t uidlen;
     470             :   const char *algo_name;
     471             :   const char *timestr;
     472             :   char *orig_codeset;
     473             :   char *maink;
     474             :   char *desc;
     475             :   const char *prompt;
     476         441 :   const char *trailer = "";
     477             :   int is_subkey;
     478             : 
     479        1323 :   is_subkey = (pk->main_keyid[0] && pk->main_keyid[1]
     480         441 :                && pk->keyid[0] != pk->main_keyid[0]
     481         732 :                && pk->keyid[1] != pk->main_keyid[1]);
     482         441 :   algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
     483         441 :   timestr = strtimestamp (pk->timestamp);
     484         441 :   uid = get_user_id (is_subkey? pk->main_keyid:pk->keyid, &uidlen);
     485             : 
     486         441 :   orig_codeset = i18n_switchto_utf8 ();
     487             : 
     488         441 :   if (is_subkey)
     489         291 :     maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
     490             :   else
     491         150 :     maink = NULL;
     492             : 
     493         441 :   switch (mode)
     494             :     {
     495             :     case FORMAT_KEYDESC_NORMAL:
     496         403 :       prompt = _("Please enter the passphrase to unlock the"
     497             :                  " OpenPGP secret key:");
     498         403 :       break;
     499             :     case FORMAT_KEYDESC_IMPORT:
     500          33 :       prompt = _("Please enter the passphrase to import the"
     501             :                  " OpenPGP secret key:");
     502          33 :       break;
     503             :     case FORMAT_KEYDESC_EXPORT:
     504           5 :       if (is_subkey)
     505           2 :         prompt = _("Please enter the passphrase to export the"
     506             :                    " OpenPGP secret subkey:");
     507             :       else
     508           3 :         prompt = _("Please enter the passphrase to export the"
     509             :                    " OpenPGP secret key:");
     510           5 :       break;
     511             :     case FORMAT_KEYDESC_DELKEY:
     512           0 :       if (is_subkey)
     513           0 :         prompt = _("Do you really want to permanently delete the"
     514             :                    " OpenPGP secret subkey key:");
     515             :       else
     516           0 :         prompt = _("Do you really want to permanently delete the"
     517             :                    " OpenPGP secret key:");
     518           0 :       trailer = "?";
     519           0 :       break;
     520             :     default:
     521           0 :       prompt = "?";
     522           0 :       break;
     523             :     }
     524             : 
     525         882 :   desc = xtryasprintf (_("%s\n"
     526             :                          "\"%.*s\"\n"
     527             :                          "%u-bit %s key, ID %s,\n"
     528             :                          "created %s%s.\n%s"),
     529             :                        prompt,
     530             :                        (int)uidlen, uid,
     531             :                        nbits_from_pk (pk), algo_name,
     532         441 :                        keystr (pk->keyid), timestr,
     533             :                        maink?maink:"", trailer);
     534         441 :   xfree (maink);
     535         441 :   xfree (uid);
     536             : 
     537         441 :   i18n_switchback (orig_codeset);
     538             : 
     539         441 :   if (escaped)
     540             :     {
     541         441 :       char *tmp = percent_plus_escape (desc);
     542         441 :       xfree (desc);
     543         441 :       desc = tmp;
     544             :     }
     545             : 
     546         441 :   return desc;
     547             : }

Generated by: LCOV version 1.11