summaryrefslogtreecommitdiffstats
path: root/agent/findkey.c
blob: 896cb880e203d3ea498372a608ff8b6e510263aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* findkey.c - locate the secret key
 * Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GnuPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <assert.h>

#include "agent.h"

/* Helper to pass data to the check callback of the unprotect function. */
struct try_unprotect_arg_s {
  const unsigned char *protected_key;
  unsigned char *unprotected_key;
};



int
agent_write_private_key (const unsigned char *grip,
                         const void *buffer, size_t length, int force)
{
  int i;
  char *fname;
  FILE *fp;
  char hexgrip[40+4+1];
  
  for (i=0; i < 20; i++)
    sprintf (hexgrip+2*i, "%02X", grip[i]);
  strcpy (hexgrip+40, ".key");

  fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
  if (force)
    fp = fopen (fname, "wb");
  else
    {
      int fd;

      if (!access (fname, F_OK))
      {
        log_error ("secret key file `%s' already exists\n", fname);
        xfree (fname);
        return gpg_error (GPG_ERR_GENERAL);
      }

      /* We would like to create FNAME but only if it does not already
	 exist.  We cannot make this guarantee just using POSIX (GNU
	 provides the "x" opentype for fopen, however, this is not
	 portable).  Thus, we use the more flexible open function and
	 then use fdopen to obtain a stream.

	 The mode parameter to open is what fopen uses.  It will be
	 combined with the process' umask automatically.  */
      fd = open (fname, O_CREAT | O_EXCL | O_RDWR,
		 S_IRUSR | S_IWUSR 
#ifndef HAVE_W32_SYSTEM
                 | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
#endif
                 );
      if (fd < 0)
	fp = 0;
      else
	{
	  fp = fdopen (fd, "wb");
	  if (!fp)
            { 
              int save_e = errno;
              close (fd);
              errno = save_e;
            }
	}
    }

  if (!fp) 
    { 
      gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
      log_error ("can't create `%s': %s\n", fname, strerror (errno));
      xfree (fname);
      return tmperr;
    }

  if (fwrite (buffer, length, 1, fp) != 1)
    {
      gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
      log_error ("error writing `%s': %s\n", fname, strerror (errno));
      fclose (fp);
      remove (fname);
      xfree (fname);
      return tmperr;
    }
  if ( fclose (fp) )
    {
      gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
      log_error ("error closing `%s': %s\n", fname, strerror (errno));
      remove (fname);
      xfree (fname);
      return tmperr;
    }

  xfree (fname);
  return 0;
}


/* Callback function to try the unprotection from the passpharse query
   code. */
static int
try_unprotect_cb (struct pin_entry_info_s *pi)
{
  struct try_unprotect_arg_s *arg = pi->check_cb_arg;
  size_t dummy;

  assert (!arg->unprotected_key);
  return agent_unprotect (arg->protected_key, pi->pin,
                          &arg->unprotected_key, &dummy);
}


/* Modify a Key description, replacing certain special format
   characters.  List of currently supported replacements:

   %% - Replaced by a single %
   %c - Replaced by the content of COMMENT.

   The functions returns 0 on success or an error code.  On success a
   newly allocated string is stored at the address of RESULT.
 */
static gpg_error_t
modify_description (const char *in, const char *comment, char **result)
{
  size_t comment_length;
  size_t in_len;
  size_t out_len;
  char *out;
  size_t i;
  int special, pass;

  comment_length = strlen (comment);
  in_len  = strlen (in);

  /* First pass calculates the length, second pass does the actual
     copying.  */
  out = NULL;
  out_len = 0;
  for (pass=0; pass < 2; pass++)
    {
      special = 0;
      for (i = 0; i < in_len; i++)
        {
          if (in[i] == '%')
            special = 1;
          else if (special)
            {
              special = 0;
              switch (in[i])
                {
                case '%':
                  out_len++;
                  if (out)
                    *out++ = '%';
                  break;

                case 'c': /* Comment.  */
                  out_len += comment_length;
                  if (out && comment_length)
                    {
                      memcpy (out, comment, comment_length);
                      out += comment_length;
                    }
                  break;

                default: /* Invalid special sequences are ignored.  */
                  break;
                }
            }
          else
            {
              out_len++;
              if (out)
                *out++ = in[i];
            }
        }
      
      if (!pass)
        {
          *result = out = xtrymalloc (out_len + 1);
          if (!out)
            return gpg_error_from_errno (errno);
        }
    }

  *out = 0;
  assert (*result + out_len == out);
  return 0;
}

  

/* Unprotect the canconical encoded S-expression key in KEYBUF.  GRIP
   should be the hex encoded keygrip of that key to be used with the
   caching mechanism. DESC_TEXT may be set to override the default
   description used for the pinentry. */
static int
unprotect (CTRL ctrl, const char *desc_text,
           unsigned char **keybuf, const unsigned char *grip, int ignore_cache)
{
  struct pin_entry_info_s *pi;
  struct try_unprotect_arg_s arg;
  int rc, i;
  unsigned char *result;
  size_t resultlen;
  char hexgrip[40+1];
  
  for (i=0; i < 20; i++)
    sprintf (hexgrip+2*i, "%02X", grip[i]);
  hexgrip[40] = 0;

  /* First try to get it from the cache - if there is none or we can't
     unprotect it, we fall back to ask the user */
  if (!ignore_cache)
    {
      void *cache_marker;
      const char *pw = agent_get_cache (hexgrip, &cache_marker);
      if (pw)
        {
          rc = agent_unprotect (*keybuf, pw, &result, &resultlen);
          agent_unlock_cache_entry (&cache_marker);
          if (!rc)
            {
              xfree (*keybuf);
              *keybuf = result;
              return 0;
            }
          rc  = 0;
        }
    }
  
  pi = gcry_calloc_secure (1, sizeof (*pi) + 100);
  pi->max_length = 100;
  pi->min_digits = 0;  /* we want a real passphrase */
  pi->max_digits = 8;
  pi->max_tries = 3;
  pi->check_cb = try_unprotect_cb;
  arg.protected_key = *keybuf;
  arg.unprotected_key = NULL;
  pi->check_cb_arg = &arg;

  rc = agent_askpin (ctrl, desc_text, NULL, pi);
  if (!rc)
    {
      assert (arg.unprotected_key);
      agent_put_cache (hexgrip, pi->pin, 0);
      xfree (*keybuf);
      *keybuf = arg.unprotected_key;
    }
  xfree (pi);
  return rc;
}



/* Return the secret key as an S-Exp in RESULT after locating it using
   the grip.  Returns NULL in RESULT if the operation should be
   diverted to a token; SHADOW_INFO will point then to an allocated
   S-Expression with the shadow_info part from the file.  With
   IGNORE_CACHE passed as true the passphrase is not taken from the
   cache.  DESC_TEXT may be set to present a custom description for the
   pinentry. */
gpg_error_t
agent_key_from_file (CTRL ctrl, const char *desc_text,
                     const unsigned char *grip, unsigned char **shadow_info,
                     int ignore_cache, gcry_sexp_t *result)
{
  int i, rc;
  char *fname;
  FILE *fp;
  struct stat st;
  unsigned char *buf;
  size_t len, buflen, erroff;
  gcry_sexp_t s_skey;
  char hexgrip[40+4+1];
  int got_shadow_info = 0;
  
  *result = NULL;
  if (shadow_info)
      *shadow_info = NULL;

  for (i=0; i < 20; i++)
    sprintf (hexgrip+2*i, "%02X", grip[i]);
  strcpy (hexgrip+40, ".key");

  fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
  fp = fopen (fname, "rb");
  if (!fp)
    {
      rc = gpg_error_from_errno (errno);
      log_error ("can't open `%s': %s\n", fname, strerror (errno));
      xfree (fname);
      return rc;
    }
  
  if (fstat (fileno(fp), &st))
    {
      rc = gpg_error_from_errno (errno);
      log_error ("can't stat `%s': %s\n", fname, strerror (errno));
      xfree (fname);
      fclose (fp);
      return rc;
    }

  buflen = st.st_size;
  buf = xmalloc (buflen+1);
  if (fread (buf, buflen, 1, fp) != 1)
    {
      rc = gpg_error_from_errno (errno);
      log_error ("error reading `%s': %s\n", fname, strerror (errno));
      xfree (fname);
      fclose (fp);
      xfree (buf);
      return rc;
    }

  rc = gcry_sexp_sscan (&s_skey, &erroff, buf, buflen);
  xfree (fname);
  fclose (fp);
  xfree (buf);
  if (rc)
    {
      log_error ("failed to build S-Exp (off=%u): %s\n",
                 (unsigned int)erroff, gpg_strerror (rc));
      return rc;
    }
  len = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0);
  assert (len);
  buf = xtrymalloc (len);
  if (!buf)
    {
      rc = out_of_core ();
      gcry_sexp_release (s_skey);
      return rc;
    }
  len = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, buf, len);
  assert (len);
  gcry_sexp_release (s_skey);

  switch (agent_private_key_type (buf))
    {
    case PRIVATE_KEY_CLEAR:
      break; /* no unprotection needed */
    case PRIVATE_KEY_PROTECTED:
      {
	gcry_sexp_t comment_sexp;
	size_t comment_length;
	char *desc_text_final;
	const char *comment = NULL;

        /* Note, that we will take the comment as a C styring for
           display purposes; i.e. all stuff beyond a Nul character is
           ignored.  */
	comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
	if (comment_sexp)
	  comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
	if (!comment)
	  {
	    comment = "";
	    comment_length = 0;
	  }

        desc_text_final = NULL;
	if (desc_text)
	  {
            if (comment[comment_length])
              {
                /* Not a C-string; create one.  We might here allocate
                   more than actually displayed but well, that
                   shouldn't be a problem.  */
                char *tmp = xtrymalloc (comment_length+1);
                if (!tmp)
                  rc = gpg_error_from_errno (errno);
                else
                  {
                    memcpy (tmp, comment, comment_length);
                    tmp[comment_length] = 0;
                    rc = modify_description (desc_text, tmp, &desc_text_final);
                    xfree (tmp);
                  }
              }
            else
              rc = modify_description (desc_text, comment, &desc_text_final);
	  }

	if (!rc)
	  {
	    rc = unprotect (ctrl, desc_text_final, &buf, grip, ignore_cache);
	    if (rc)
	      log_error ("failed to unprotect the secret key: %s\n",
			 gpg_strerror (rc));
	  }
        
	gcry_sexp_release (comment_sexp);
	xfree (desc_text_final);
      }
      break;
    case PRIVATE_KEY_SHADOWED:
      if (shadow_info)
        {
          const unsigned char *s;
          size_t n;

          rc = agent_get_shadow_info (buf, &s);
          if (!rc)
            {
              n = gcry_sexp_canon_len (s, 0, NULL,NULL);
              assert (n);
              *shadow_info = xtrymalloc (n);
              if (!*shadow_info)
                rc = out_of_core ();
              else
                {
                  memcpy (*shadow_info, s, n);
                  rc = 0;
                  got_shadow_info = 1;
                }
            }
          if (rc)
            log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
        }
      else
        rc = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
      break;
    default:
      log_error ("invalid private key format\n");
      rc = gpg_error (GPG_ERR_BAD_SECKEY);
      break;
    }
  if (rc || got_shadow_info)
    {
      xfree (buf);
      return rc;
    }

  buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
  rc = gcry_sexp_sscan (&s_skey, &erroff, buf, buflen);
  wipememory (buf, buflen);
  xfree (buf);
  if (rc)
    {
      log_error ("failed to build S-Exp (off=%u): %s\n",
                 (unsigned int)erroff, gpg_strerror (rc));
      return rc;
    }

  *result = s_skey;
  return 0;
}

/* Return the secret key as an S-Exp after locating it using the grip.
   Returns NULL if key is not available. 0 = key is available */
int
agent_key_available (const unsigned char *grip)
{
  int i;
  char *fname;
  char hexgrip[40+4+1];
  
  for (i=0; i < 20; i++)
    sprintf (hexgrip+2*i, "%02X", grip[i]);
  strcpy (hexgrip+40, ".key");

  fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
  i = !access (fname, R_OK)? 0 : -1;
  xfree (fname);
  return i;
}