~ubuntu-branches/ubuntu/oneiric/gnupg2/oneiric-updates

« back to all changes in this revision

Viewing changes to g10/passphrase.c

  • Committer: Bazaar Package Importer
  • Author(s): Thomas Viehmann
  • Date: 2008-10-04 10:25:53 UTC
  • mfrom: (5.1.15 intrepid)
  • Revision ID: james.westby@ubuntu.com-20081004102553-fv62pp8dsitxli47
Tags: 2.0.9-3.1
* Non-maintainer upload.
* agent/gpg-agent.c: Deinit the threading library before exec'ing
  the command to run in --daemon mode. And because that still doesn't
  restore the sigprocmask, do that manually. Closes: #499569

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* passphrase.c -  Get a passphrase
2
 
 * Copyright (C) 1998,1999,2000,2001,2002,2003 Free Software Foundation, Inc.
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
 
3
 *               2005, 2006, 2007 Free Software Foundation, Inc.
3
4
 *
4
5
 * This file is part of GnuPG.
5
6
 *
6
7
 * GnuPG is free software; you can redistribute it and/or modify
7
8
 * it under the terms of the GNU General Public License as published by
8
 
 * the Free Software Foundation; either version 2 of the License, or
 
9
 * the Free Software Foundation; either version 3 of the License, or
9
10
 * (at your option) any later version.
10
11
 *
11
12
 * GnuPG is distributed in the hope that it will be useful,
14
15
 * GNU General Public License for more details.
15
16
 *
16
17
 * You should have received a copy of the GNU General Public License
17
 
 * along with this program; if not, write to the Free Software
18
 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
18
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19
19
 */
20
20
 
21
21
#include <config.h>
25
25
#include <string.h>
26
26
#include <unistd.h>
27
27
#include <assert.h>
28
 
#if !defined(HAVE_DOSISH_SYSTEM) && !defined(__riscos__)
29
 
#include <sys/socket.h>
30
 
#include <sys/un.h>
31
 
#endif
32
 
#if defined (_WIN32) || defined (__CYGWIN32__)
33
 
# include <windows.h>
34
 
#endif
35
28
#include <errno.h>
36
29
#ifdef HAVE_LOCALE_H
37
30
#include <locale.h>
42
35
 
43
36
#include "gpg.h"
44
37
#include "util.h"
45
 
#include "memory.h"
46
38
#include "options.h"
47
39
#include "ttyio.h"
48
40
#include "cipher.h"
50
42
#include "main.h"
51
43
#include "i18n.h"
52
44
#include "status.h"
53
 
 
54
 
 
55
 
enum gpga_protocol_codes {
56
 
    /* Request codes */
57
 
    GPGA_PROT_GET_VERSION     = 1,
58
 
    GPGA_PROT_GET_PASSPHRASE  = 2,
59
 
    GPGA_PROT_CLEAR_PASSPHRASE= 3,
60
 
    GPGA_PROT_SHUTDOWN        = 4,
61
 
    GPGA_PROT_FLUSH           = 5,
62
 
 
63
 
    /* Reply codes */
64
 
    GPGA_PROT_REPLY_BASE     = 0x10000,
65
 
    GPGA_PROT_OKAY           = 0x10001,
66
 
    GPGA_PROT_GOT_PASSPHRASE = 0x10002,
67
 
 
68
 
    /* Error codes */
69
 
    GPGA_PROT_ERROR_BASE     = 0x20000,
70
 
    GPGA_PROT_PROTOCOL_ERROR = 0x20001,
71
 
    GPGA_PROT_INVALID_REQUEST= 0x20002,
72
 
    GPGA_PROT_CANCELED       = 0x20003,    
73
 
    GPGA_PROT_NO_PASSPHRASE  = 0x20004,    
74
 
    GPGA_PROT_BAD_PASSPHRASE = 0x20005,
75
 
    GPGA_PROT_INVALID_DATA   = 0x20006,
76
 
    GPGA_PROT_NOT_IMPLEMENTED= 0x20007,
77
 
    GPGA_PROT_UI_PROBLEM     = 0x20008
78
 
};
79
 
 
80
 
 
81
 
#define buftou32( p )  ((*(byte*)(p) << 24) | (*((byte*)(p)+1)<< 16) | \
82
 
                       (*((byte*)(p)+2) << 8) | (*((byte*)(p)+3)))
83
 
#define u32tobuf( p, a ) do {                                   \
84
 
                            ((byte*)p)[0] = (byte)((a) >> 24);  \
85
 
                            ((byte*)p)[1] = (byte)((a) >> 16);  \
86
 
                            ((byte*)p)[2] = (byte)((a) >>  8);  \
87
 
                            ((byte*)p)[3] = (byte)((a)      );  \
88
 
                        } while(0)
89
 
 
90
 
#define digitp(p)   (*(p) >= '0' && *(p) <= '9')
91
 
#define hexdigitp(a) (digitp (a)                     \
92
 
                      || (*(a) >= 'A' && *(a) <= 'F')  \
93
 
                      || (*(a) >= 'a' && *(a) <= 'f'))
94
 
#define xtoi_1(p)   (*(p) <= '9'? (*(p)- '0'): \
95
 
                     *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
96
 
#define xtoi_2(p)   ((xtoi_1(p) * 16) + xtoi_1((p)+1))
97
 
 
 
45
#include "call-agent.h"
98
46
 
99
47
 
100
48
static char *fd_passwd = NULL;
101
49
static char *next_pw = NULL;
102
50
static char *last_pw = NULL;
103
51
 
104
 
#if defined (_WIN32)
105
 
static int read_fd = 0;
106
 
static int write_fd = 0;
107
 
#endif
108
 
 
109
 
static void hash_passphrase( DEK *dek, char *pw, STRING2KEY *s2k, int create );
 
52
 
 
53
/* Hash a passphrase using the supplied s2k. If create is true, create
 
54
   a new salt or what else must be filled into the s2k for a new key.
 
55
   always needs: dek->algo, s2k->mode, s2k->hash_algo.  */
 
56
static void
 
57
hash_passphrase ( DEK *dek, char *pw, STRING2KEY *s2k, int create )
 
58
{
 
59
  gcry_md_hd_t md;
 
60
  int pass, i;
 
61
  int used = 0;
 
62
  int pwlen = strlen(pw);
 
63
 
 
64
  assert ( s2k->hash_algo );
 
65
  dek->keylen = gcry_cipher_get_algo_keylen (dek->algo);
 
66
  if ( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
 
67
    BUG();
 
68
 
 
69
  if (gcry_md_open (&md, s2k->hash_algo, 1))
 
70
    BUG ();
 
71
  for (pass=0; used < dek->keylen ; pass++ ) 
 
72
    {
 
73
      if ( pass ) 
 
74
        {
 
75
          gcry_md_reset (md);
 
76
          for (i=0; i < pass; i++ ) /* Preset the hash context.  */
 
77
            gcry_md_putc (md, 0 );
 
78
        }
 
79
 
 
80
      if ( s2k->mode == 1 || s2k->mode == 3 ) 
 
81
        {
 
82
          int len2 = pwlen + 8;
 
83
          ulong count = len2;
 
84
          
 
85
          if ( create && !pass )
 
86
            {
 
87
              gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
 
88
              if ( s2k->mode == 3 )
 
89
                s2k->count = opt.s2k_count;
 
90
            }
 
91
 
 
92
          if ( s2k->mode == 3 )
 
93
            {
 
94
              count = S2K_DECODE_COUNT(s2k->count);
 
95
              if ( count < len2 )
 
96
                count = len2;
 
97
            }
 
98
 
 
99
          /* A little bit complicated because we need a ulong for count. */
 
100
          while ( count > len2 )  /* maybe iterated+salted */
 
101
            { 
 
102
              gcry_md_write ( md, s2k->salt, 8 );
 
103
              gcry_md_write ( md, pw, pwlen );
 
104
              count -= len2;
 
105
            }
 
106
          if ( count < 8 )
 
107
            gcry_md_write ( md, s2k->salt, count );
 
108
          else
 
109
            {
 
110
              gcry_md_write ( md, s2k->salt, 8 );
 
111
              count -= 8;
 
112
              gcry_md_write ( md, pw, count );
 
113
            }
 
114
        }
 
115
      else
 
116
        gcry_md_write ( md, pw, pwlen );
 
117
      gcry_md_final( md );
 
118
 
 
119
      i = gcry_md_get_algo_dlen ( s2k->hash_algo );
 
120
      if ( i > dek->keylen - used )
 
121
        i = dek->keylen - used;
 
122
 
 
123
      memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
 
124
      used += i;
 
125
    }
 
126
  gcry_md_close(md);
 
127
}
 
128
 
 
129
 
110
130
 
111
131
int
112
132
have_static_passphrase()
113
133
{
114
 
    if ( opt.use_agent )
115
 
        return 0;
116
 
    return !!fd_passwd;
 
134
  return !!fd_passwd && opt.batch;
117
135
}
118
136
 
119
137
/****************
123
141
void
124
142
set_next_passphrase( const char *s )
125
143
{
126
 
    xfree (next_pw);
127
 
    next_pw = NULL;
128
 
    if( s ) {
129
 
        next_pw = gcry_xmalloc_secure ( strlen(s)+1 );
130
 
        strcpy(next_pw, s );
 
144
  xfree(next_pw);
 
145
  next_pw = NULL;
 
146
  if ( s )
 
147
    {
 
148
      next_pw = xmalloc_secure( strlen(s)+1 );
 
149
      strcpy (next_pw, s );
131
150
    }
132
151
}
133
152
 
139
158
char *
140
159
get_last_passphrase()
141
160
{
142
 
    char *p = last_pw;
143
 
    last_pw = NULL;
144
 
    return p;
 
161
  char *p = last_pw;
 
162
  last_pw = NULL;
 
163
  return p;
 
164
}
 
165
 
 
166
/* As if we had used the passphrase - make it the last_pw. */
 
167
void
 
168
next_to_last_passphrase(void)
 
169
{
 
170
  if (next_pw)
 
171
    {
 
172
      last_pw=next_pw;
 
173
      next_pw=NULL;
 
174
    }
 
175
}
 
176
 
 
177
/* Here's an interesting question: since this passphrase was passed in
 
178
   on the command line, is there really any point in using secure
 
179
   memory for it?  I'm going with 'yes', since it doesn't hurt, and
 
180
   might help in some small way (swapping). */
 
181
 
 
182
void
 
183
set_passphrase_from_string(const char *pass)
 
184
{
 
185
  xfree (fd_passwd);
 
186
  fd_passwd = xmalloc_secure(strlen(pass)+1);
 
187
  strcpy (fd_passwd, pass);
145
188
}
146
189
 
147
190
 
150
193
{
151
194
  int i, len;
152
195
  char *pw;
153
 
  
154
 
  if ( opt.use_agent ) 
 
196
 
 
197
  if ( !opt.batch ) 
155
198
    { /* Not used but we have to do a dummy read, so that it won't end
156
199
         up at the begin of the message if the quite usual trick to
157
200
         prepend the passphtrase to the message is used. */
163
206
      return; 
164
207
    }
165
208
 
166
 
  if (!opt.batch )
167
 
        tty_printf("Reading passphrase from file descriptor %d ...", fd );
168
209
  for (pw = NULL, i = len = 100; ; i++ ) 
169
210
    {
170
211
      if (i >= len-1 ) 
171
212
        {
172
213
          char *pw2 = pw;
173
214
          len += 100;
174
 
          pw = gcry_xmalloc_secure ( len );
 
215
          pw = xmalloc_secure( len );
175
216
          if( pw2 )
176
 
            memcpy(pw, pw2, i );
 
217
            {
 
218
              memcpy(pw, pw2, i );
 
219
              xfree (pw2);
 
220
            }
177
221
          else
178
222
            i=0;
179
223
        }
188
232
  fd_passwd = pw;
189
233
}
190
234
 
191
 
static int
192
 
writen ( int fd, const void *buf, size_t nbytes )
193
 
{
194
 
#if defined (_WIN32)
195
 
    DWORD nwritten, nleft = nbytes;
196
 
    
197
 
    while (nleft > 0) {
198
 
        if ( !WriteFile( (HANDLE)write_fd, buf, nleft, &nwritten, NULL) ) {
199
 
                log_error("write failed: ec=%d\n", (int)GetLastError());
200
 
                return -1;
201
 
        }
202
 
        /*log_info("** WriteFile fd=%d nytes=%d nwritten=%d\n",
203
 
                 write_fd, nbytes, (int)nwritten);*/
204
 
        Sleep(100);
205
 
        
206
 
        nleft -= nwritten;
207
 
        buf = (const BYTE *)buf + nwritten;
208
 
    }
209
 
#elif defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
210
 
    /* not implemented */
211
 
#else
212
 
    size_t nleft = nbytes;
213
 
    int nwritten;
214
 
 
215
 
    while( nleft > 0 ) {
216
 
        nwritten = write( fd, buf, nleft );
217
 
        if( nwritten < 0 ) {
218
 
            if ( errno == EINTR )
219
 
                nwritten = 0;
220
 
            else {
221
 
                log_error ( "write() failed: %s\n", strerror (errno) );
222
 
                return -1;
223
 
            }
224
 
        }
225
 
        nleft -= nwritten;
226
 
        buf = (const char*)buf + nwritten;
227
 
    }
228
 
#endif
229
 
    
230
 
    return 0;
231
 
}
232
 
 
233
 
 
234
 
static int
235
 
readn ( int fd, void *buf, size_t buflen, size_t *ret_nread )
236
 
{
237
 
#if defined (_WIN32)
238
 
    DWORD nread, nleft = buflen;
239
 
    
240
 
    while (nleft > 0) {
241
 
        if ( !ReadFile( (HANDLE)read_fd, buf, nleft, &nread, NULL) ) {
242
 
            log_error("read() error: ec=%d\n", (int)GetLastError());
243
 
            return -1;
244
 
        }
245
 
        if (!nread || GetLastError() == ERROR_BROKEN_PIPE)
246
 
            break;
247
 
        /*log_info("** ReadFile fd=%d buflen=%d nread=%d\n",
248
 
          read_fd, buflen, (int)nread);*/
249
 
        Sleep(100);
250
 
        
251
 
        nleft -= nread;
252
 
        buf = (BYTE *)buf + nread;
253
 
    }           
254
 
    if (ret_nread)
255
 
        *ret_nread = buflen - nleft;
256
 
 
257
 
#elif defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
258
 
    /* not implemented */
259
 
#else
260
 
    size_t nleft = buflen;
261
 
    int nread;
262
 
    char *p;
263
 
 
264
 
    p = buf;
265
 
    while( nleft > 0 ) {
266
 
        nread = read ( fd, buf, nleft );
267
 
        if( nread < 0 ) {
268
 
            if (nread == EINTR)
269
 
                nread = 0;
270
 
            else {
271
 
                log_error ( "read() error: %s\n", strerror (errno) );
272
 
                return -1;
273
 
            }
274
 
        }
275
 
        else if( !nread )
276
 
            break; /* EOF */
277
 
        nleft -= nread;
278
 
        buf = (char*)buf + nread;
279
 
    }
280
 
    if( ret_nread )
281
 
        *ret_nread = buflen - nleft;
282
 
#endif
283
 
    
284
 
    return 0;
285
 
}
286
 
 
287
 
/* read an entire line */
288
 
static int
289
 
readline (int fd, char *buf, size_t buflen)
290
 
{
291
 
  size_t nleft = buflen;
292
 
  char *p;
293
 
  int nread = 0;
294
 
 
295
 
  while (nleft > 0)
296
 
    {
297
 
      int n = read (fd, buf, nleft);
298
 
      if (n < 0)
299
 
        {
300
 
          if (errno == EINTR)
301
 
            continue;
302
 
          return -1; /* read error */
303
 
        }
304
 
      else if (!n)
305
 
        {
306
 
          return -1; /* incomplete line */
307
 
        }
308
 
      p = buf;
309
 
      nleft -= n;
310
 
      buf += n;
311
 
      nread += n;
312
 
      
313
 
      for (; n && *p != '\n'; n--, p++)
314
 
        ;
315
 
      if (n)
316
 
        {
317
 
          break; /* at least one full line available - that's enough.
318
 
                    This function is just a temporary hack until we use
319
 
                    the assuna lib in gpg.  So it is okay to forget
320
 
                    about pending bytes */
321
 
        }
322
 
    }
323
 
 
324
 
  return nread; 
325
 
}
326
 
 
327
 
 
328
 
 
329
 
#if !defined (__riscos__)
330
 
 
331
 
#if !defined (_WIN32)
332
 
/* For the new Assuan protocol we may have to send options */
333
 
static int
334
 
agent_send_option (int fd, const char *name, const char *value)
335
 
{
336
 
  char buf[200];
337
 
  int nread;
338
 
  char *line;
339
 
  int i; 
340
 
  
341
 
  line = xmalloc (7 + strlen (name) + 1 + strlen (value) + 2);
342
 
  strcpy (stpcpy (stpcpy (stpcpy (
343
 
                     stpcpy (line, "OPTION "), name), "="), value), "\n");
344
 
  i = writen (fd, line, strlen (line));
345
 
  xfree (line);
346
 
  if (i)
347
 
    return -1;
348
 
  
349
 
  /* get response */
350
 
  nread = readline (fd, buf, DIM(buf)-1);
351
 
  if (nread < 3)
352
 
    return -1;
353
 
  
354
 
  if (buf[0] == 'O' && buf[1] == 'K' && (buf[2] == ' ' || buf[2] == '\n')) 
355
 
    return 0; /* okay */
356
 
 
357
 
  return -1;
358
 
}
359
 
 
360
 
static int 
361
 
agent_send_all_options (int fd)
362
 
{
363
 
  char *dft_display = NULL;
364
 
  const char *dft_ttyname = NULL;
365
 
  char *dft_ttytype = NULL;
366
 
  char *old_lc = NULL;
367
 
  char *dft_lc = NULL;
368
 
  int rc = 0;
369
 
 
370
 
  dft_display = getenv ("DISPLAY");
371
 
  if (opt.display || dft_display)
372
 
    {
373
 
      if (agent_send_option (fd, "display",
374
 
                             opt.display ? opt.display : dft_display))
375
 
        return -1;
376
 
    }
377
 
 
378
 
  if (!opt.ttyname)
379
 
    {
380
 
      dft_ttyname = getenv ("GPG_TTY");
381
 
      if ((!dft_ttyname || !*dft_ttyname) && tty_get_ttyname ())
382
 
        dft_ttyname = tty_get_ttyname ();
383
 
    }
384
 
  if (opt.ttyname || dft_ttyname)
385
 
    {
386
 
      if (agent_send_option (fd, "ttyname",
387
 
                             opt.ttyname ? opt.ttyname : dft_ttyname))
388
 
        return -1;
389
 
    }
390
 
 
391
 
  dft_ttytype = getenv ("TERM");
392
 
  if (opt.ttytype || (dft_ttyname && dft_ttytype))
393
 
    {
394
 
      if (agent_send_option (fd, "ttytype",
395
 
                             opt.ttyname ? opt.ttytype : dft_ttytype))
396
 
        return -1;
397
 
    }
398
 
 
399
 
#if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
400
 
  old_lc = setlocale (LC_CTYPE, NULL);
401
 
  if (old_lc)
402
 
    old_lc = xstrdup (old_lc);
403
 
  dft_lc = setlocale (LC_CTYPE, "");
404
 
#endif
405
 
  if (opt.lc_ctype || (dft_ttyname && dft_lc))
406
 
    {
407
 
      rc = agent_send_option (fd, "lc-ctype",
408
 
                              opt.lc_ctype ? opt.lc_ctype : dft_lc);
409
 
    }
410
 
#if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
411
 
  if (old_lc)
412
 
    {
413
 
      setlocale (LC_CTYPE, old_lc);
414
 
      xfree (old_lc);
415
 
    }
416
 
#endif
417
 
  if (rc)
418
 
    return rc;
419
 
 
420
 
#if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
421
 
  old_lc = setlocale (LC_MESSAGES, NULL);
422
 
  if (old_lc)
423
 
    old_lc = xstrdup (old_lc);
424
 
  dft_lc = setlocale (LC_MESSAGES, "");
425
 
#endif
426
 
  if (opt.lc_messages || (dft_ttyname && dft_lc))
427
 
    {
428
 
      rc = agent_send_option (fd, "lc-messages",
429
 
                              opt.lc_messages ? opt.lc_messages : dft_lc);
430
 
    }
431
 
#if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
432
 
  if (old_lc)
433
 
    {
434
 
      setlocale (LC_MESSAGES, old_lc);
435
 
      xfree (old_lc);
436
 
    }
437
 
#endif
438
 
  return rc;
439
 
}
440
 
#endif /*!_WIN32*/
441
 
 
442
 
 
443
 
/*
444
 
 * Open a connection to the agent and send the magic string
445
 
 * Returns: -1 on error or an filedescriptor for urther processing
446
 
 */
447
 
 
448
 
static int
449
 
agent_open (int *ret_prot)
450
 
{
451
 
#if defined (_WIN32)
452
 
    int fd;
453
 
    char *infostr, *p;
454
 
    HANDLE h;
455
 
    char pidstr[128];
456
 
 
457
 
    *ret_prot = 0;
458
 
    if ( !(infostr = read_w32_registry_string(NULL, "Software\\GNU\\GnuPG",
459
 
                                              "agentPID")) 
460
 
         || *infostr == '0') {
461
 
        log_error( _("gpg-agent is not available in this session\n"));
462
 
        return -1;
463
 
    }
464
 
    free(infostr);
465
 
    
466
 
    sprintf(pidstr, "%u", (unsigned int)GetCurrentProcessId());
467
 
    if (write_w32_registry_string(NULL, "Software\\GNU\\GnuPG",
468
 
                                  "agentCID", pidstr)) {
469
 
        log_error( _("can't set client pid for the agent\n") );
470
 
        return -1;
471
 
    }
472
 
    h = OpenEvent(EVENT_ALL_ACCESS, FALSE, "gpg_agent");
473
 
    SetEvent(h);
474
 
    Sleep(50); /* some time for the server */ 
475
 
    if ( !(p = read_w32_registry_string(NULL, "Software\\GNU\\GnuPG",
476
 
                                        "agentReadFD")) ) {
477
 
        log_error( _("can't get server read FD for the agent\n") );
478
 
        return -1;
479
 
    }
480
 
    read_fd = atol(p);
481
 
    free(p);    
482
 
    if ( !(p = read_w32_registry_string(NULL, "Software\\GNU\\GnuPG",
483
 
                                        "agentWriteFD")) ) {
484
 
        log_error ( _("can't get server write FD for the agent\n") );
485
 
        return -1;
486
 
    }
487
 
    write_fd = atol(p);
488
 
    free(p);
489
 
    fd = 0;
490
 
 
491
 
    if ( writen ( fd, "GPGA\0\0\0\x01", 8 ) ) {
492
 
        fd = -1;
493
 
    }
494
 
#else /* Posix */
495
 
 
496
 
    int fd;
497
 
    char *infostr, *p;
498
 
    struct sockaddr_un client_addr;
499
 
    size_t len;
500
 
    int prot;
501
 
 
502
 
    if (opt.gpg_agent_info)
503
 
      infostr = xstrdup (opt.gpg_agent_info);
504
 
    else
505
 
      {
506
 
        infostr = getenv ( "GPG_AGENT_INFO" );
507
 
        if ( !infostr || !*infostr ) {
508
 
          log_error (_("gpg-agent is not available in this session\n"));
509
 
          opt.use_agent = 0;
510
 
          return -1;
511
 
        }
512
 
        infostr = xstrdup ( infostr );
513
 
      }
514
 
 
515
 
    if ( !(p = strchr ( infostr, ':')) || p == infostr
516
 
         || (p-infostr)+1 >= sizeof client_addr.sun_path ) {
517
 
        log_error( _("malformed GPG_AGENT_INFO environment variable\n"));
518
 
        xfree (infostr );
519
 
        opt.use_agent = 0;
520
 
        return -1;
521
 
    }
522
 
    *p++ = 0;
523
 
    /* See whether this is the new gpg-agent using the Assuna protocl.
524
 
       This agent identifies itself by have an info string with a
525
 
       version number in the 3rd field. */
526
 
    while (*p && *p != ':')
527
 
      p++;
528
 
    prot = *p? atoi (p+1) : 0;
529
 
    if ( prot < 0 || prot > 1) {
530
 
        log_error (_("gpg-agent protocol version %d is not supported\n"),prot);
531
 
        xfree (infostr );
532
 
        opt.use_agent = 0;
533
 
        return -1;
534
 
    }
535
 
    *ret_prot = prot;
536
 
       
537
 
    if( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1 ) {
538
 
        log_error ("can't create socket: %s\n", strerror(errno) );
539
 
        xfree (infostr );
540
 
        opt.use_agent = 0;
541
 
        return -1;
542
 
    }
543
 
    
544
 
    memset( &client_addr, 0, sizeof client_addr );
545
 
    client_addr.sun_family = AF_UNIX;
546
 
    strcpy( client_addr.sun_path, infostr );
547
 
    len = offsetof (struct sockaddr_un, sun_path)
548
 
        + strlen(client_addr.sun_path) + 1;
549
 
    
550
 
    if( connect( fd, (struct sockaddr*)&client_addr, len ) == -1 ) {
551
 
        log_error ( _("can't connect to `%s': %s\n"), 
552
 
                    infostr, strerror (errno) );
553
 
        xfree (infostr );
554
 
        close (fd );
555
 
        opt.use_agent = 0;
556
 
        return -1;
557
 
    }
558
 
    xfree (infostr);
559
 
 
560
 
    if (!prot) {
561
 
        if ( writen ( fd, "GPGA\0\0\0\x01", 8 ) ) {
562
 
          close (fd);
563
 
          fd = -1;
564
 
        }
565
 
    }
566
 
    else { /* assuan based gpg-agent */
567
 
      char line[200];
568
 
      int nread;
569
 
 
570
 
      nread = readline (fd, line, DIM(line));
571
 
      if (nread < 3 || !(line[0] == 'O' && line[1] == 'K'
572
 
                         && (line[2] == '\n' || line[2] == ' ')) ) {
573
 
        log_error ( _("communication problem with gpg-agent\n"));
574
 
        close (fd );
575
 
        opt.use_agent = 0;
576
 
        return -1;
577
 
      }
578
 
 
579
 
      if (agent_send_all_options (fd)) {
580
 
        log_error (_("problem with the agent - disabling agent use\n"));
581
 
        close (fd);
582
 
        opt.use_agent = 0;
583
 
        return -1;
584
 
      }
585
 
        
586
 
    }
587
 
#endif
588
 
 
589
 
    return fd;
590
 
}
591
 
 
592
 
 
593
 
static void
594
 
agent_close ( int fd )
595
 
{
596
 
#if defined (_WIN32)
597
 
    HANDLE h = OpenEvent(EVENT_ALL_ACCESS, FALSE, "gpg_agent");
598
 
    ResetEvent(h);
599
 
#else
600
 
    close (fd);
601
 
#endif
602
 
}
603
 
#endif /* !__riscos__ */
604
 
 
605
 
 
606
235
 
607
236
/*
608
237
 * Ask the GPG Agent for the passphrase.
610
239
 *      1:  No cached passphrase FIXME: Not really implemented
611
240
 *      2:  Ditto, but change the text to "repeat entry"
612
241
 *
613
 
 * Note that TRYAGAIN_TEXT must not be translated.  If canceled is not
 
242
 * Note that TRYAGAIN_TEXT must not be translated.  If CANCELED is not
614
243
 * NULL, the function does set it to 1 if the user canceled the
615
 
 * operation.
 
244
 * operation.  If CACHEID is not NULL, it will be used as the cacheID
 
245
 * for the gpg-agent; if is NULL and a key fingerprint can be
 
246
 * computed, this will be used as the cacheid.
616
247
 */
617
248
static char *
618
 
agent_get_passphrase ( u32 *keyid, int mode, const char *tryagain_text,
619
 
                       int *canceled)
 
249
passphrase_get ( u32 *keyid, int mode, const char *cacheid,
 
250
                 const char *tryagain_text,
 
251
                 const char *custom_description,
 
252
                 const char *custom_prompt, int *canceled)
620
253
{
621
 
#if defined(__riscos__)
622
 
  return NULL;
623
 
#else
624
 
  size_t n;
 
254
  int rc;
625
255
  char *atext = NULL;
626
 
  char buf[50];
627
 
  int fd = -1;
628
 
  int nread;
629
 
  u32 reply;
630
256
  char *pw = NULL;
631
 
  PKT_public_key *pk = xcalloc (1, sizeof *pk );
 
257
  PKT_public_key *pk = xmalloc_clear( sizeof *pk );
632
258
  byte fpr[MAX_FINGERPRINT_LEN];
633
259
  int have_fpr = 0;
634
 
  int prot;
635
 
  char *orig_codeset = NULL;
 
260
  char *orig_codeset;
 
261
  char *my_prompt;
 
262
  char hexfprbuf[20*2+1];
 
263
  const char *my_cacheid;
636
264
 
637
265
  if (canceled)
638
266
    *canceled = 0;
644
272
  memset (fpr, 0, MAX_FINGERPRINT_LEN );
645
273
  if( keyid && get_pubkey( pk, keyid ) )
646
274
    {
647
 
      free_public_key( pk );      
 
275
      if (pk)
 
276
        free_public_key( pk );      
648
277
      pk = NULL; /* oops: no key for some reason */
649
278
    }
650
279
  
651
 
#ifdef ENABLE_NLS
652
 
  /* The Assuan agent protocol requires us to transmit utf-8 strings */
653
 
  orig_codeset = bind_textdomain_codeset (PACKAGE_GT, NULL);
654
 
#ifdef HAVE_LANGINFO_CODESET
655
 
  if (!orig_codeset)
656
 
    orig_codeset = nl_langinfo (CODESET);
657
 
#endif
658
 
  if (orig_codeset)
659
 
    { /* We only switch when we are able to restore the codeset later. */
660
 
      orig_codeset = xstrdup (orig_codeset);
661
 
      if (!bind_textdomain_codeset (PACKAGE_GT, "utf-8"))
662
 
        orig_codeset = NULL; 
663
 
    }
664
 
#endif
665
 
 
666
 
  if ( (fd = agent_open (&prot)) == -1 ) 
667
 
    goto failure;
668
 
 
669
 
  if ( !mode && pk && keyid )
 
280
  orig_codeset = i18n_switchto_utf8 ();
 
281
 
 
282
  if (custom_description)
 
283
    atext = native_to_utf8 (custom_description);
 
284
  else if ( !mode && pk && keyid )
670
285
    { 
671
286
      char *uid;
672
287
      size_t uidlen;
676
291
      
677
292
      if ( !algo_name )
678
293
        algo_name = "?";
679
 
      
 
294
 
 
295
#define KEYIDSTRING _(" (main key ID %s)")
 
296
 
 
297
      maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
680
298
      if( keyid[2] && keyid[3] && keyid[0] != keyid[2] 
681
299
          && keyid[1] != keyid[3] )
682
 
         maink = xasprintf ( _(" (main key ID %08lX)"), (ulong)keyid[3] );
 
300
        sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
683
301
      else
684
 
         maink = NULL;
 
302
        *maink = 0;
685
303
      
686
304
      uid = get_user_id ( keyid, &uidlen ); 
687
305
      timestr = strtimestamp (pk->timestamp);
688
 
      atext = xasprintf (
689
 
               _("You need a passphrase to unlock the"
690
 
                 " secret key for user:\n"
691
 
                 "\"%.*s\"\n"
692
 
                 "%u-bit %s key, ID %08lX, created %s%s\n" ),
693
 
               uidlen, uid,
694
 
               nbits_from_pk (pk), algo_name, (ulong)keyid[1], timestr,
695
 
               maink?maink:"" );
 
306
 
 
307
#undef KEYIDSTRING
 
308
 
 
309
#define PROMPTSTRING _("Please enter the passphrase to unlock the" \
 
310
                       " secret key for the OpenPGP certificate:\n" \
 
311
                       "\"%.*s\"\n" \
 
312
                       "%u-bit %s key, ID %s,\n" \
 
313
                       "created %s%s.\n" )
 
314
 
 
315
      atext = xmalloc ( 100 + strlen (PROMPTSTRING)  
 
316
                        + uidlen + 15 + strlen(algo_name) + keystrlen()
 
317
                        + strlen (timestr) + strlen (maink) );
 
318
      sprintf (atext, PROMPTSTRING,
 
319
               (int)uidlen, uid,
 
320
               nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
 
321
               maink  );
696
322
      xfree (uid);
697
323
      xfree (maink);
698
 
      
 
324
 
 
325
#undef PROMPTSTRING
 
326
 
699
327
      { 
700
328
        size_t dummy;
701
329
        fingerprint_from_pk( pk, fpr, &dummy );
708
336
  else
709
337
    atext = xstrdup ( _("Enter passphrase\n") );
710
338
                
711
 
  if (!prot)
712
 
    { /* old style protocol */
713
 
      n = 4 + 20 + strlen (atext);
714
 
      u32tobuf (buf, n );
715
 
      u32tobuf (buf+4, GPGA_PROT_GET_PASSPHRASE );
716
 
      memcpy (buf+8, fpr, 20 );
717
 
      if ( writen ( fd, buf, 28 ) || writen ( fd, atext, strlen (atext) ) ) 
718
 
        goto failure;
719
 
      xfree (atext); atext = NULL;
720
 
      
721
 
      /* get response */
722
 
      if ( readn ( fd, buf, 12, &nread ) ) 
723
 
        goto failure;
724
 
      
725
 
      if ( nread < 8 ) 
726
 
        {
727
 
          log_error ( "response from agent too short\n" );
728
 
          goto failure;
729
 
        }
730
 
      n = buftou32 ( buf );
731
 
      reply = buftou32 ( buf + 4 );
732
 
      if ( reply == GPGA_PROT_GOT_PASSPHRASE ) 
733
 
        {
734
 
          size_t pwlen;
735
 
          size_t nn;
736
 
          
737
 
          if ( nread < 12 || n < 8 ) 
738
 
            {
739
 
              log_error ( "response from agent too short\n" );
740
 
              goto failure;
741
 
            }
742
 
          pwlen = buftou32 ( buf + 8 );
743
 
          nread -= 12;
744
 
          n -= 8;
745
 
          if ( pwlen > n || n > 1000 ) 
746
 
            {
747
 
              log_error (_("passphrase too long\n"));
748
 
              /* or protocol error */
749
 
              goto failure;
750
 
            }
751
 
          /* we read the whole block in one chunk to give no hints
752
 
           * on how long the passhrase actually is - this wastes some bytes
753
 
           * but because we already have this padding we should not loosen
754
 
           * this by issuing 2 read calls */
755
 
          pw = xmalloc_secure ( n+1 );
756
 
          if ( readn ( fd, pw, n, &nn ) )
757
 
            goto failure;
758
 
          if ( n != nn ) 
759
 
            {
760
 
              log_error (_("invalid response from agent\n"));
761
 
              goto failure;           
762
 
            }
763
 
          pw[pwlen] = 0; /* make a C String */
764
 
          agent_close (fd);
765
 
          free_public_key( pk );
766
 
#ifdef ENABLE_NLS
767
 
          if (orig_codeset)
768
 
            bind_textdomain_codeset (PACKAGE_GT, orig_codeset);
769
 
#endif
770
 
          xfree (orig_codeset);
771
 
          return pw;
772
 
        }
773
 
      else if ( reply == GPGA_PROT_CANCELED ) 
774
 
        {
775
 
          log_info ( _("cancelled by user\n") );
776
 
          if (canceled)
777
 
            *canceled = 1;
778
 
        }
779
 
      else 
780
 
        log_error ( _("problem with the agent: agent returns 0x%lx\n"),
781
 
                    (ulong)reply );
782
 
    }
 
339
 
 
340
  if (!mode && cacheid)
 
341
    my_cacheid = cacheid;
 
342
  else if (!mode && have_fpr)
 
343
    my_cacheid = bin2hex (fpr, 20, hexfprbuf);
783
344
  else
784
 
    { /* The new Assuan protocol */
785
 
      char *line, *p;
786
 
      const unsigned char *s;
787
 
      int i; 
788
 
 
789
 
      if (!tryagain_text)
790
 
        tryagain_text = "X";
791
 
      else
792
 
        tryagain_text = _(tryagain_text);
793
 
 
794
 
      /* We allocate 2 time the needed space for atext so that there
795
 
         is enough space for escaping */
796
 
      line = xmalloc (15 + 46 
797
 
                      +  3*strlen (tryagain_text) + 3*strlen (atext) + 2);
798
 
      strcpy (line, "GET_PASSPHRASE ");
799
 
      p = line+15;
800
 
      if (!mode && have_fpr)
801
 
        {
802
 
          for (i=0; i < 20; i++, p +=2 )
803
 
            sprintf (p, "%02X", fpr[i]);
804
 
        }
805
 
      else
806
 
        *p++ = 'X'; /* no caching */
807
 
      *p++ = ' ';
808
 
      for (i=0, s=tryagain_text; *s; s++)
809
 
        {
810
 
          if (*s < ' ' || *s == '+')
811
 
            {
812
 
              sprintf (p, "%%%02X", *s);
813
 
              p += 3;
814
 
            }
815
 
          else if (*s == ' ')
816
 
            *p++ = '+';
817
 
          else
818
 
            *p++ = *s;
819
 
        }
820
 
      *p++ = ' ';
821
 
      *p++ = 'X'; /* Use the standard prompt */
822
 
      *p++ = ' ';
823
 
      /* copy description */
824
 
      for (i=0, s= atext; *s; s++)
825
 
        {
826
 
          if (*s < ' ' || *s == '+')
827
 
            {
828
 
              sprintf (p, "%%%02X", *s);
829
 
              p += 3;
830
 
            }
831
 
          else if (*s == ' ')
832
 
            *p++ = '+';
833
 
          else
834
 
            *p++ = *s;
835
 
        }
836
 
      *p++ = '\n';
837
 
      i = writen (fd, line, p - line);
838
 
      xfree (line);
839
 
      if (i)
840
 
        goto failure;
841
 
      xfree (atext); atext = NULL;
842
 
      
843
 
      /* get response */
844
 
      pw = xmalloc_secure (500);
845
 
      nread = readline (fd, pw, 499);
846
 
      if (nread < 3)
847
 
        goto failure;
848
 
      
849
 
      if (pw[0] == 'O' && pw[1] == 'K' && pw[2] == ' ') 
850
 
        { /* we got a passphrase - convert it back from hex */
851
 
          size_t pwlen = 0;
852
 
 
853
 
          for (i=3; i < nread && hexdigitp (pw+i); i+=2)
854
 
            pw[pwlen++] = xtoi_2 (pw+i);
855
 
          pw[pwlen] = 0; /* make a C String */
856
 
          agent_close (fd);
857
 
          free_public_key( pk );
858
 
#ifdef ENABLE_NLS
859
 
          if (orig_codeset)
860
 
            bind_textdomain_codeset (PACKAGE_GT, orig_codeset);
861
 
#endif
862
 
          xfree (orig_codeset);
863
 
          return pw;
864
 
        }
865
 
      else if (nread > 4 && !memcmp (pw, "ERR ", 4)
866
 
               && (0xffff & strtoul (&pw[4], NULL, 0)) == 99)
867
 
        {
868
 
          /* 99 is GPG_ERR_CANCELED.  FIXME: Check tail and overflow,
869
 
             and use gpg-error.  */
870
 
          log_info (_("cancelled by user\n") );
871
 
          if (canceled)
872
 
            *canceled = 1;
873
 
        }
874
 
      else 
875
 
        {
876
 
          log_error (_("problem with the agent - disabling agent use\n"));
877
 
          opt.use_agent = 0;
878
 
        }
879
 
    }
880
 
      
881
 
        
882
 
 failure:
883
 
#ifdef ENABLE_NLS
884
 
  if (orig_codeset)
885
 
    bind_textdomain_codeset (PACKAGE_GT, orig_codeset);
886
 
#endif
887
 
  xfree (atext);
888
 
  if ( fd != -1 )
889
 
    agent_close (fd);
890
 
  xfree (pw );
891
 
  free_public_key( pk );
 
345
    my_cacheid = NULL;
 
346
 
 
347
  if (tryagain_text)
 
348
    tryagain_text = _(tryagain_text);
 
349
 
 
350
  my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
 
351
 
 
352
  rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext, &pw);
892
353
  
893
 
  return NULL;
894
 
#endif /* Posix or W32 */
 
354
  xfree (my_prompt);
 
355
  xfree (atext); atext = NULL;
 
356
 
 
357
  i18n_switchback (orig_codeset);
 
358
 
 
359
 
 
360
  if (!rc)
 
361
    ;
 
362
  else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
 
363
    {
 
364
      log_info (_("cancelled by user\n") );
 
365
      if (canceled)
 
366
        *canceled = 1;
 
367
    }
 
368
  else 
 
369
    {
 
370
      log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
 
371
      /* Due to limitations in the API of the upper layers they
 
372
         consider an error as no passphrase entered.  This works in
 
373
         most cases but not during key creation where this should
 
374
         definitely not happen and let it continue without requiring a
 
375
         passphrase.  Given that now all the upper layers handle a
 
376
         cancel correctly, we simply set the cancel flag now for all
 
377
         errors from the agent.  */ 
 
378
      if (canceled)
 
379
        *canceled = 1;
 
380
    }
 
381
 
 
382
  if (pk)
 
383
    free_public_key( pk );
 
384
  if (rc)
 
385
    {
 
386
      xfree (pw);
 
387
      return NULL;
 
388
    }
 
389
  return pw;
895
390
}
896
391
 
 
392
 
897
393
/*
898
 
 * Clear the cached passphrase
 
394
 * Clear the cached passphrase.  If CACHEID is not NULL, it will be
 
395
 * used instead of a cache ID derived from KEYID.
899
396
 */
900
397
void
901
 
passphrase_clear_cache ( u32 *keyid, int algo )
 
398
passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
902
399
{
903
 
#if defined(__riscos__)
904
 
  return ;
905
 
#else
906
 
  size_t n;
907
 
  char buf[200];
908
 
  int fd = -1;
909
 
  size_t nread;
910
 
  u32 reply;
911
 
  PKT_public_key *pk;
912
 
  byte fpr[MAX_FINGERPRINT_LEN];
913
 
  int prot;
914
 
  
915
 
#if MAX_FINGERPRINT_LEN < 20
916
 
#error agent needs a 20 byte fingerprint
917
 
#endif
918
 
    
919
 
  if (!opt.use_agent)
920
 
    return;
921
 
  
922
 
  pk = xcalloc (1, sizeof *pk );
923
 
  memset (fpr, 0, MAX_FINGERPRINT_LEN );
924
 
  if( !keyid || get_pubkey( pk, keyid ) )
925
 
    {
926
 
      log_debug ("oops, no key in passphrase_clear_cache\n");
927
 
      goto failure; /* oops: no key for some reason */
928
 
    }
929
 
  
930
 
  {
931
 
    size_t dummy;
932
 
    fingerprint_from_pk( pk, fpr, &dummy );
933
 
  }
934
 
    
935
 
  if ( (fd = agent_open (&prot)) == -1 ) 
936
 
    goto failure;
937
 
 
938
 
  if (!prot)
939
 
    {
940
 
      n = 4 + 20;
941
 
      u32tobuf (buf, n );
942
 
      u32tobuf (buf+4, GPGA_PROT_CLEAR_PASSPHRASE );
943
 
      memcpy (buf+8, fpr, 20 );
944
 
      if ( writen ( fd, buf, 28 ) )  
945
 
        goto failure;
946
 
      
947
 
      /* get response */
948
 
      if ( readn ( fd, buf, 8, &nread ) ) 
949
 
        goto failure;
950
 
      
951
 
      if ( nread < 8 ) {
952
 
        log_error ( "response from agent too short\n" );
953
 
        goto failure;
954
 
      }
955
 
      
956
 
      reply = buftou32 ( buf + 4 );
957
 
      if ( reply != GPGA_PROT_OKAY && reply != GPGA_PROT_NO_PASSPHRASE )
958
 
        {
959
 
          log_error ( _("problem with the agent: agent returns 0x%lx\n"),
960
 
                      (ulong)reply );
961
 
        }
962
 
    }
963
 
  else 
964
 
    { /* The assuan protocol */
965
 
      char *line, *p;
966
 
      int i; 
967
 
 
968
 
      line = xmalloc (17 + 40 + 2);
969
 
      strcpy (line, "CLEAR_PASSPHRASE ");
970
 
      p = line+17;
971
 
      for (i=0; i < 20; i++, p +=2 )
972
 
        sprintf (p, "%02X", fpr[i]);
973
 
      *p++ = '\n';
974
 
      i = writen (fd, line, p - line);
975
 
      xfree (line);
976
 
      if (i)
977
 
        goto failure;
978
 
      
979
 
      /* get response */
980
 
      nread = readline (fd, buf, DIM(buf)-1);
981
 
      if (nread < 3)
982
 
        goto failure;
983
 
      
984
 
      if (buf[0] == 'O' && buf[1] == 'K' && (buf[2] == ' ' || buf[2] == '\n')) 
985
 
        ;
986
 
      else 
987
 
        {
988
 
          log_error (_("problem with the agent - disabling agent use\n"));
989
 
          opt.use_agent = 0;
990
 
        }
991
 
    }
992
 
        
993
 
 failure:
994
 
  if (fd != -1)
995
 
    agent_close (fd);
996
 
  free_public_key( pk );
997
 
#endif /* Posix or W32 */
 
400
  int rc;
 
401
    
 
402
  if (!cacheid)
 
403
    {
 
404
      PKT_public_key *pk;
 
405
#     if MAX_FINGERPRINT_LEN < 20
 
406
#       error agent needs a 20 byte fingerprint
 
407
#     endif
 
408
      byte fpr[MAX_FINGERPRINT_LEN];
 
409
      char hexfprbuf[2*20+1];
 
410
      size_t dummy;
 
411
      
 
412
      pk = xcalloc (1, sizeof *pk);
 
413
      if ( !keyid || get_pubkey( pk, keyid ) )
 
414
        {
 
415
          log_error ("key not found in passphrase_clear_cache\n");
 
416
          free_public_key (pk);
 
417
          return;
 
418
        }
 
419
      memset (fpr, 0, MAX_FINGERPRINT_LEN );
 
420
      fingerprint_from_pk ( pk, fpr, &dummy );
 
421
      bin2hex (fpr, 20, hexfprbuf);
 
422
      rc = agent_clear_passphrase (hexfprbuf);
 
423
      free_public_key ( pk );
 
424
    }
 
425
  else
 
426
    rc = agent_clear_passphrase (cacheid);
 
427
 
 
428
  if (rc)
 
429
    log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
998
430
}
999
431
 
1000
432
 
1001
 
 
1002
 
 
1003
433
/****************
1004
 
 * Get a passphrase for the secret key with KEYID, display TEXT
1005
 
 * if the user needs to enter the passphrase.
1006
 
 * mode 0 = standard, 1 = same but don't show key info,
1007
 
 *      2 = create new passphrase
1008
 
 * Returns: a DEK with a session key; caller must free
1009
 
 *          or NULL if the passphrase was not correctly repeated.
1010
 
 *          (only for mode 2)
1011
 
 *          a dek->keylen of 0 means: no passphrase entered.
1012
 
 *          (only for mode 2)
1013
 
 *
1014
 
 * pubkey_algo is only informational.  Note that TRYAGAIN_TEXT must
1015
 
 * not be translated as this is done within this function (required to
1016
 
 * switch to utf-8 when the agent is in use).  If CANCELED is not
1017
 
 * NULL, it is set to 1 if the user choosed to cancel the operation,
1018
 
 * otherwise it will be set to 0.
 
434
 * Ask for a passphrase and return that string.
1019
435
 */
 
436
char *
 
437
ask_passphrase (const char *description,
 
438
                const char *tryagain_text,
 
439
                const char *promptid,
 
440
                const char *prompt,
 
441
                const char *cacheid, int *canceled)
 
442
{
 
443
  char *pw = NULL;
 
444
  
 
445
  if (canceled)
 
446
    *canceled = 0;
 
447
 
 
448
  if (!opt.batch && description)
 
449
    {
 
450
      if (strchr (description, '%'))
 
451
        {
 
452
          char *tmp = unescape_percent_string
 
453
            ((const unsigned char*)description);
 
454
          tty_printf ("\n%s\n", tmp);
 
455
          xfree (tmp);
 
456
        }
 
457
      else
 
458
        tty_printf ("\n%s\n",description);
 
459
    }
 
460
               
 
461
  if (have_static_passphrase ()) 
 
462
    {
 
463
      pw = xmalloc_secure (strlen(fd_passwd)+1);
 
464
      strcpy (pw, fd_passwd);
 
465
    }
 
466
  else
 
467
    pw = passphrase_get (NULL, 0, cacheid,
 
468
                         tryagain_text, description, prompt,
 
469
                         canceled );
 
470
 
 
471
  if (!pw || !*pw)
 
472
    write_status( STATUS_MISSING_PASSPHRASE );
 
473
 
 
474
  return pw;
 
475
}
 
476
 
 
477
 
 
478
/* Return a new DEK object Using the string-to-key sepcifier S2K.  Use
 
479
   KEYID and PUBKEY_ALGO to prompt the user.  Returns NULL is the user
 
480
   selected to cancel the passphrase entry and if CANCELED is not
 
481
   NULL, sets it to true.
 
482
 
 
483
   MODE 0:  Allow cached passphrase
 
484
        1:  Ignore cached passphrase 
 
485
        2:  Ditto, but change the text to "repeat entry"
 
486
*/
1020
487
DEK *
1021
 
passphrase_to_dek( u32 *keyid, int pubkey_algo,
 
488
passphrase_to_dek (u32 *keyid, int pubkey_algo,
1022
489
                   int cipher_algo, STRING2KEY *s2k, int mode,
1023
490
                   const char *tryagain_text, int *canceled)
1024
491
{
1025
 
    char *pw = NULL;
1026
 
    DEK *dek;
1027
 
    STRING2KEY help_s2k;
1028
 
 
1029
 
    if (canceled)
1030
 
      *canceled = 0;
1031
 
 
1032
 
    if( !s2k ) {
1033
 
        /* This is used for the old rfc1991 mode 
1034
 
         * Note: This must match the code in encode.c with opt.rfc1991 set */
1035
 
        s2k = &help_s2k;
1036
 
        s2k->mode = 0;
1037
 
        s2k->hash_algo = opt.s2k_digest_algo;
1038
 
    }
1039
 
 
1040
 
    if( !next_pw && is_status_enabled() ) {
1041
 
        char buf[50];
1042
 
 
1043
 
        if( keyid ) {
1044
 
            u32 used_kid[2];
1045
 
            char *us;
1046
 
 
1047
 
            if( keyid[2] && keyid[3] ) {
1048
 
                used_kid[0] = keyid[2];
1049
 
                used_kid[1] = keyid[3];
1050
 
            }
1051
 
            else {
1052
 
                used_kid[0] = keyid[0];
1053
 
                used_kid[1] = keyid[1];
1054
 
            }
1055
 
 
1056
 
            us = get_long_user_id_string( keyid );
1057
 
            write_status_text( STATUS_USERID_HINT, us );
1058
 
            xfree (us);
1059
 
 
1060
 
            sprintf( buf, "%08lX%08lX %08lX%08lX %d 0",
1061
 
                     (ulong)keyid[0], (ulong)keyid[1],
1062
 
                     (ulong)used_kid[0], (ulong)used_kid[1],
1063
 
                     pubkey_algo );
1064
 
                     
1065
 
            write_status_text( STATUS_NEED_PASSPHRASE, buf );
1066
 
        }
1067
 
        else {
1068
 
            sprintf( buf, "%d %d %d", cipher_algo, s2k->mode, s2k->hash_algo );
1069
 
            write_status_text( STATUS_NEED_PASSPHRASE_SYM, buf );
1070
 
        }
1071
 
    }
1072
 
 
1073
 
    if( keyid && !opt.batch && !next_pw && mode!=1 ) {
1074
 
        PKT_public_key *pk = xcalloc (1, sizeof *pk );
1075
 
        size_t n;
1076
 
        char *p;
1077
 
 
1078
 
        tty_printf(_("\nYou need a passphrase to unlock the secret key for\n"
1079
 
                     "user: \"") );
1080
 
        p = get_user_id( keyid, &n );
1081
 
        tty_print_utf8_string( p, n );
1082
 
        xfree (p);
1083
 
        tty_printf("\"\n");
1084
 
 
1085
 
        if( !get_pubkey( pk, keyid ) ) {
1086
 
            const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
1087
 
            tty_printf( _("%u-bit %s key, ID %08lX, created %s"),
1088
 
                       nbits_from_pk( pk ), s?s:"?", (ulong)keyid[1],
1089
 
                       strtimestamp(pk->timestamp) );
1090
 
            if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
1091
 
                                     && keyid[1] != keyid[3] )
1092
 
                tty_printf( _(" (main key ID %08lX)"), (ulong)keyid[3] );
1093
 
            tty_printf("\n");
1094
 
        }
1095
 
 
1096
 
        tty_printf("\n");
1097
 
        free_public_key( pk );
1098
 
    }
1099
 
 
1100
 
 agent_died:
1101
 
    if( next_pw ) {
1102
 
        pw = next_pw;
1103
 
        next_pw = NULL;
1104
 
    }
1105
 
    else if ( opt.use_agent ) {
1106
 
        pw = agent_get_passphrase ( keyid, mode == 2? 1: 0,
1107
 
                                    tryagain_text, canceled );
1108
 
        if (!pw)
1109
 
          {
1110
 
            if (!opt.use_agent)
1111
 
              goto agent_died;
1112
 
            pw = xstrdup ("");
1113
 
          }
1114
 
        if( *pw && mode == 2 ) {
1115
 
            char *pw2 = agent_get_passphrase ( keyid, 2, NULL, canceled );
1116
 
            if (!pw2)
1117
 
              {
1118
 
                if (!opt.use_agent)
1119
 
                  {
1120
 
                    xfree (pw);
1121
 
                    pw = NULL;
1122
 
                    goto agent_died;
1123
 
                  }
1124
 
                pw2 = xstrdup ("");
1125
 
              }
1126
 
            if( strcmp(pw, pw2) ) {
1127
 
                xfree (pw2);
1128
 
                xfree (pw);
1129
 
                return NULL;
1130
 
            }
1131
 
            xfree (pw2);
1132
 
        }
1133
 
    }
1134
 
    else if( fd_passwd ) {
1135
 
        pw = xmalloc_secure ( strlen(fd_passwd)+1 );
1136
 
        strcpy( pw, fd_passwd );
1137
 
    }
1138
 
    else if( opt.batch ) {
1139
 
        log_error(_("can't query password in batchmode\n"));
1140
 
        pw = xstrdup ( "" ); /* return an empty passphrase */
1141
 
    }
1142
 
    else {
1143
 
        pw = cpr_get_hidden("passphrase.enter", _("Enter passphrase: ") );
1144
 
        tty_kill_prompt();
1145
 
        if( mode == 2 && !cpr_enabled() ) {
1146
 
            char *pw2 = cpr_get_hidden("passphrase.repeat",
1147
 
                                       _("Repeat passphrase: ") );
1148
 
            tty_kill_prompt();
1149
 
            if( strcmp(pw, pw2) ) {
1150
 
                xfree (pw2);
1151
 
                xfree (pw);
1152
 
                return NULL;
1153
 
            }
1154
 
            xfree (pw2);
1155
 
        }
1156
 
    }
1157
 
 
1158
 
    if( !pw || !*pw )
1159
 
        write_status( STATUS_MISSING_PASSPHRASE );
1160
 
 
1161
 
    dek = xcalloc_secure (1, sizeof *dek );
1162
 
    dek->algo = cipher_algo;
1163
 
    if( !*pw && mode == 2 )
1164
 
        dek->keylen = 0;
1165
 
    else
1166
 
        hash_passphrase( dek, pw, s2k, mode==2 );
1167
 
    xfree (last_pw);
1168
 
    last_pw = pw;
1169
 
    return dek;
1170
 
}
1171
 
 
1172
 
 
1173
 
/****************
1174
 
 * Hash a passphrase using the supplied s2k. If create is true, create
1175
 
 * a new salt or what else must be filled into the s2k for a new key.
1176
 
 * always needs: dek->algo, s2k->mode, s2k->hash_algo.
1177
 
 */
1178
 
static void
1179
 
hash_passphrase( DEK *dek, char *pw, STRING2KEY *s2k, int create )
1180
 
{
1181
 
    MD_HANDLE md;
1182
 
    int pass, i;
1183
 
    int used = 0;
1184
 
    int pwlen = strlen(pw);
1185
 
 
1186
 
    assert( s2k->hash_algo );
1187
 
    dek->keylen = gcry_cipher_get_algo_keylen (dek->algo);
1188
 
    if( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
1189
 
        BUG();
1190
 
 
1191
 
    gcry_md_open (&md, s2k->hash_algo, 1);
1192
 
    for(pass=0; used < dek->keylen ; pass++ ) {
1193
 
        if( pass ) {
1194
 
            gcry_md_reset(md);
1195
 
            for(i=0; i < pass; i++ ) /* preset the hash context */
1196
 
                gcry_md_putc (md, 0 );
1197
 
        }
1198
 
 
1199
 
        if( s2k->mode == 1 || s2k->mode == 3 ) {
1200
 
            int len2 = pwlen + 8;
1201
 
            ulong count = len2;
1202
 
 
1203
 
            if( create && !pass ) {
1204
 
                gcry_randomize(s2k->salt, 8, GCRY_STRONG_RANDOM );
1205
 
                if( s2k->mode == 3 )
1206
 
                    s2k->count = 96; /* 65536 iterations */
1207
 
            }
1208
 
 
1209
 
            if( s2k->mode == 3 ) {
1210
 
                count = (16ul + (s2k->count & 15)) << ((s2k->count >> 4) + 6);
1211
 
                if( count < len2 )
1212
 
                    count = len2;
1213
 
            }
1214
 
            /* a little bit complicated because we need a ulong for count */
1215
 
            while( count > len2 ) { /* maybe iterated+salted */
1216
 
                gcry_md_write( md, s2k->salt, 8 );
1217
 
                gcry_md_write( md, pw, pwlen );
1218
 
                count -= len2;
1219
 
            }
1220
 
            if( count < 8 )
1221
 
                gcry_md_write( md, s2k->salt, count );
1222
 
            else {
1223
 
                gcry_md_write( md, s2k->salt, 8 );
1224
 
                count -= 8;
1225
 
                gcry_md_write( md, pw, count );
1226
 
            }
1227
 
        }
1228
 
        else
1229
 
            gcry_md_write( md, pw, pwlen );
1230
 
        gcry_md_final ( md );
1231
 
        i = gcry_md_get_algo_dlen (s2k->hash_algo);
1232
 
        if( i > dek->keylen - used )
1233
 
            i = dek->keylen - used;
1234
 
        memcpy( dek->key+used, gcry_md_read (md, s2k->hash_algo), i );
1235
 
        used += i;
1236
 
    }
1237
 
    gcry_md_close (md);
1238
 
}
1239
 
 
 
492
  char *pw = NULL;
 
493
  DEK *dek;
 
494
  STRING2KEY help_s2k;
 
495
  int dummy_canceled;
 
496
 
 
497
  if (!canceled)
 
498
    canceled = &dummy_canceled;
 
499
  *canceled = 0;
 
500
  
 
501
  if ( !s2k )
 
502
    {
 
503
      /* This is used for the old rfc1991 mode 
 
504
       * Note: This must match the code in encode.c with opt.rfc1991 set */
 
505
      s2k = &help_s2k;
 
506
      s2k->mode = 0;
 
507
      s2k->hash_algo = S2K_DIGEST_ALGO;
 
508
    }
 
509
 
 
510
  /* If we do not have a passphrase available in NEXT_PW and status
 
511
     information are request, we print them now. */
 
512
  if ( !next_pw && is_status_enabled() ) 
 
513
    {
 
514
      char buf[50];
 
515
      
 
516
      if ( keyid )
 
517
        {
 
518
          u32 used_kid[2];
 
519
          char *us;
 
520
          
 
521
          if ( keyid[2] && keyid[3] ) 
 
522
            {
 
523
              used_kid[0] = keyid[2];
 
524
              used_kid[1] = keyid[3];
 
525
            }
 
526
          else
 
527
            {
 
528
              used_kid[0] = keyid[0];
 
529
              used_kid[1] = keyid[1];
 
530
            }
 
531
          
 
532
          us = get_long_user_id_string ( keyid );
 
533
          write_status_text ( STATUS_USERID_HINT, us );
 
534
          xfree(us);
 
535
          
 
536
          snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
 
537
                    (ulong)keyid[0], (ulong)keyid[1],
 
538
                    (ulong)used_kid[0], (ulong)used_kid[1],
 
539
                    pubkey_algo );
 
540
          
 
541
          write_status_text ( STATUS_NEED_PASSPHRASE, buf );
 
542
        }
 
543
      else
 
544
        {
 
545
          snprintf (buf, sizeof buf -1, "%d %d %d",
 
546
                    cipher_algo, s2k->mode, s2k->hash_algo );
 
547
          write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
 
548
        }
 
549
    }
 
550
 
 
551
  /* If we do have a keyID, we do not have a passphrase available in
 
552
     NEXT_PW, we are not running in batch mode and we do not want to
 
553
     ignore the passphrase cache (mode!=1), print a prompt with
 
554
     information on that key. */
 
555
  if ( keyid && !opt.batch && !next_pw && mode!=1 )
 
556
    {
 
557
      PKT_public_key *pk = xmalloc_clear( sizeof *pk );
 
558
      char *p;
 
559
      
 
560
      p = get_user_id_native(keyid);
 
561
      tty_printf ("\n");
 
562
      tty_printf (_("You need a passphrase to unlock the secret key for\n"
 
563
                    "user: \"%s\"\n"),p);
 
564
      xfree(p);
 
565
 
 
566
      if ( !get_pubkey( pk, keyid ) )
 
567
        {
 
568
          const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
 
569
          
 
570
          tty_printf (_("%u-bit %s key, ID %s, created %s"),
 
571
                      nbits_from_pk( pk ), s?s:"?", keystr(keyid),
 
572
                      strtimestamp(pk->timestamp) );
 
573
          if ( keyid[2] && keyid[3]
 
574
               && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
 
575
            {
 
576
              if ( keystrlen () > 10 )
 
577
                {
 
578
                  tty_printf ("\n");
 
579
                  tty_printf (_("         (subkey on main key ID %s)"),
 
580
                              keystr(&keyid[2]) );
 
581
                }
 
582
              else
 
583
                tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
 
584
            }
 
585
          tty_printf("\n");
 
586
        }
 
587
 
 
588
      tty_printf("\n");
 
589
      if (pk)
 
590
        free_public_key( pk );
 
591
    }
 
592
 
 
593
  if ( next_pw ) 
 
594
    {
 
595
      /* Simply return the passphrase we already have in NEXT_PW. */
 
596
      pw = next_pw;
 
597
      next_pw = NULL;
 
598
    }
 
599
  else if ( have_static_passphrase () ) 
 
600
    {
 
601
      /* Return the passphrase we have stored in FD_PASSWD. */
 
602
      pw = xmalloc_secure ( strlen(fd_passwd)+1 );
 
603
      strcpy ( pw, fd_passwd );
 
604
    }
 
605
  else 
 
606
    {
 
607
      /* Divert to the gpg-agent. */
 
608
      pw = passphrase_get ( keyid, mode == 2? 1: 0, NULL,
 
609
                            tryagain_text, NULL, NULL, canceled );
 
610
      if (*canceled)
 
611
        {
 
612
          xfree (pw);
 
613
          write_status( STATUS_MISSING_PASSPHRASE );
 
614
          return NULL;
 
615
        }
 
616
      if (!pw)
 
617
        pw = xstrdup ("");
 
618
      if ( *pw && mode == 2 )
 
619
        {
 
620
          int i;
 
621
          for(i=0;i<opt.passwd_repeat;i++)
 
622
            {
 
623
              char *pw2 = passphrase_get ( keyid, 2, NULL, NULL, NULL,
 
624
                                           NULL, canceled );
 
625
              if (*canceled)
 
626
                {
 
627
                  xfree (pw);
 
628
                  xfree (pw2);
 
629
                  write_status( STATUS_MISSING_PASSPHRASE );
 
630
                  return NULL;
 
631
                }
 
632
              if (!pw2)
 
633
                pw2 = xstrdup ("");
 
634
              if ( strcmp(pw, pw2) )
 
635
                {
 
636
                  xfree(pw2);
 
637
                  xfree(pw);
 
638
                  return NULL;
 
639
                }
 
640
              xfree(pw2);
 
641
            }
 
642
        }
 
643
    }
 
644
    
 
645
  if ( !pw || !*pw )
 
646
    write_status( STATUS_MISSING_PASSPHRASE );
 
647
 
 
648
  /* Hash the passphrase and store it in a newly allocated DEK object.
 
649
     Keep a copy of the passphrase in LAST_PW for use by
 
650
     get_last_passphrase(). */
 
651
  dek = xmalloc_secure_clear ( sizeof *dek );
 
652
  dek->algo = cipher_algo;
 
653
  if ( !*pw && mode == 2 )
 
654
    dek->keylen = 0;
 
655
  else
 
656
    hash_passphrase( dek, pw, s2k, mode==2 );
 
657
  xfree(last_pw);
 
658
  last_pw = pw;
 
659
  return dek;
 
660
}