chiark / gitweb /
dirmngr: Drop useless housekeeping.
[gnupg2.git] / agent / protect.c
1 /* protect.c - Un/Protect a secret key
2  * Copyright (C) 1998-2003, 2007, 2009, 2011 Free Software Foundation, Inc.
3  * Copyright (C) 1998-2003, 2007, 2009, 2011, 2013-2015 Werner Koch
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 <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <assert.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #ifdef HAVE_W32_SYSTEM
31 # ifdef HAVE_WINSOCK2_H
32 #  include <winsock2.h>
33 # endif
34 # include <windows.h>
35 #else
36 # include <sys/times.h>
37 #endif
38
39 #include "agent.h"
40
41 #include "cvt-openpgp.h"
42 #include "sexp-parse.h"
43
44
45 /* To use the openpgp-s2k3-ocb-aes scheme by default set the value of
46  * this macro to 1.  Note that the caller of agent_protect may
47  * override this default.  */
48 #define PROT_DEFAULT_TO_OCB 0
49
50 /* The protection mode for encryption.  The supported modes for
51    decryption are listed in agent_unprotect().  */
52 #define PROT_CIPHER        GCRY_CIPHER_AES128
53 #define PROT_CIPHER_STRING "aes"
54 #define PROT_CIPHER_KEYLEN (128/8)
55
56 /* Decode an rfc4880 encoded S2K count.  */
57 #define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6))
58
59
60 /* A table containing the information needed to create a protected
61    private key.  */
62 static struct {
63   const char *algo;
64   const char *parmlist;
65   int prot_from, prot_to;
66   int ecc_hack;
67 } protect_info[] = {
68   { "rsa",  "nedpqu", 2, 5 },
69   { "dsa",  "pqgyx", 4, 4 },
70   { "elg",  "pgyx", 3, 3 },
71   { "ecdsa","pabgnqd", 6, 6, 1 },
72   { "ecdh", "pabgnqd", 6, 6, 1 },
73   { "ecc",  "pabgnqd", 6, 6, 1 },
74   { NULL }
75 };
76
77
78 /* A helper object for time measurement.  */
79 struct calibrate_time_s
80 {
81 #ifdef HAVE_W32_SYSTEM
82   FILETIME creation_time, exit_time, kernel_time, user_time;
83 #else
84   clock_t ticks;
85 #endif
86 };
87
88
89 static int
90 hash_passphrase (const char *passphrase, int hashalgo,
91                  int s2kmode,
92                  const unsigned char *s2ksalt, unsigned long s2kcount,
93                  unsigned char *key, size_t keylen);
94
95
96
97 \f
98 /* Get the process time and store it in DATA.  */
99 static void
100 calibrate_get_time (struct calibrate_time_s *data)
101 {
102 #ifdef HAVE_W32_SYSTEM
103 # ifdef HAVE_W32CE_SYSTEM
104   GetThreadTimes (GetCurrentThread (),
105                   &data->creation_time, &data->exit_time,
106                   &data->kernel_time, &data->user_time);
107 # else
108   GetProcessTimes (GetCurrentProcess (),
109                    &data->creation_time, &data->exit_time,
110                    &data->kernel_time, &data->user_time);
111 # endif
112 #else
113   struct tms tmp;
114
115   times (&tmp);
116   data->ticks = tmp.tms_utime;
117 #endif
118 }
119
120
121 static unsigned long
122 calibrate_elapsed_time (struct calibrate_time_s *starttime)
123 {
124   struct calibrate_time_s stoptime;
125
126   calibrate_get_time (&stoptime);
127 #ifdef HAVE_W32_SYSTEM
128   {
129     unsigned long long t1, t2;
130
131     t1 = (((unsigned long long)starttime->kernel_time.dwHighDateTime << 32)
132           + starttime->kernel_time.dwLowDateTime);
133     t1 += (((unsigned long long)starttime->user_time.dwHighDateTime << 32)
134            + starttime->user_time.dwLowDateTime);
135     t2 = (((unsigned long long)stoptime.kernel_time.dwHighDateTime << 32)
136           + stoptime.kernel_time.dwLowDateTime);
137     t2 += (((unsigned long long)stoptime.user_time.dwHighDateTime << 32)
138            + stoptime.user_time.dwLowDateTime);
139     return (unsigned long)((t2 - t1)/10000);
140   }
141 #else
142   return (unsigned long)((((double) (stoptime.ticks - starttime->ticks))
143                           /CLOCKS_PER_SEC)*10000000);
144 #endif
145 }
146
147
148 /* Run a test hashing for COUNT and return the time required in
149    milliseconds.  */
150 static unsigned long
151 calibrate_s2k_count_one (unsigned long count)
152 {
153   int rc;
154   char keybuf[PROT_CIPHER_KEYLEN];
155   struct calibrate_time_s starttime;
156
157   calibrate_get_time (&starttime);
158   rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1,
159                         3, "saltsalt", count, keybuf, sizeof keybuf);
160   if (rc)
161     BUG ();
162   return calibrate_elapsed_time (&starttime);
163 }
164
165
166 /* Measure the time we need to do the hash operations and deduce an
167    S2K count which requires about 100ms of time.  */
168 static unsigned long
169 calibrate_s2k_count (void)
170 {
171   unsigned long count;
172   unsigned long ms;
173
174   for (count = 65536; count; count *= 2)
175     {
176       ms = calibrate_s2k_count_one (count);
177       if (opt.verbose > 1)
178         log_info ("S2K calibration: %lu -> %lums\n", count, ms);
179       if (ms > 100)
180         break;
181     }
182
183   count = (unsigned long)(((double)count / ms) * 100);
184   count /= 1024;
185   count *= 1024;
186   if (count < 65536)
187     count = 65536;
188
189   if (opt.verbose)
190     {
191       ms = calibrate_s2k_count_one (count);
192       log_info ("S2K calibration: %lu -> %lums\n", count, ms);
193     }
194
195   return count;
196 }
197
198
199
200 /* Return the standard S2K count.  */
201 unsigned long
202 get_standard_s2k_count (void)
203 {
204   static unsigned long count;
205
206   if (!count)
207     count = calibrate_s2k_count ();
208
209   /* Enforce a lower limit.  */
210   return count < 65536 ? 65536 : count;
211 }
212
213
214 /* Same as get_standard_s2k_count but return the count in the encoding
215    as described by rfc4880.  */
216 unsigned char
217 get_standard_s2k_count_rfc4880 (void)
218 {
219   unsigned long iterations;
220   unsigned int count;
221   unsigned char result;
222   unsigned char c=0;
223
224   iterations = get_standard_s2k_count ();
225   if (iterations >= 65011712)
226     return 255;
227
228   /* Need count to be in the range 16-31 */
229   for (count=iterations>>6; count>=32; count>>=1)
230     c++;
231
232   result = (c<<4)|(count-16);
233
234   if (S2K_DECODE_COUNT(result) < iterations)
235     result++;
236
237   return result;
238
239 }
240
241
242 \f
243 /* Calculate the MIC for a private key or shared secret S-expression.
244    SHA1HASH should point to a 20 byte buffer.  This function is
245    suitable for all algorithms. */
246 static int
247 calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash)
248 {
249   const unsigned char *hash_begin, *hash_end;
250   const unsigned char *s;
251   size_t n;
252   int is_shared_secret;
253
254   s = plainkey;
255   if (*s != '(')
256     return gpg_error (GPG_ERR_INV_SEXP);
257   s++;
258   n = snext (&s);
259   if (!n)
260     return gpg_error (GPG_ERR_INV_SEXP);
261   if (smatch (&s, n, "private-key"))
262     is_shared_secret = 0;
263   else if (smatch (&s, n, "shared-secret"))
264     is_shared_secret = 1;
265   else
266     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
267   if (*s != '(')
268     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
269   hash_begin = s;
270   if (!is_shared_secret)
271     {
272       s++;
273       n = snext (&s);
274       if (!n)
275         return gpg_error (GPG_ERR_INV_SEXP);
276       s += n; /* Skip the algorithm name.  */
277     }
278
279   while (*s == '(')
280     {
281       s++;
282       n = snext (&s);
283       if (!n)
284         return gpg_error (GPG_ERR_INV_SEXP);
285       s += n;
286       n = snext (&s);
287       if (!n)
288         return gpg_error (GPG_ERR_INV_SEXP);
289       s += n;
290       if ( *s != ')' )
291         return gpg_error (GPG_ERR_INV_SEXP);
292       s++;
293     }
294   if (*s != ')')
295     return gpg_error (GPG_ERR_INV_SEXP);
296   s++;
297   hash_end = s;
298
299   gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash,
300                        hash_begin, hash_end - hash_begin);
301
302   return 0;
303 }
304
305
306 \f
307 /* Encrypt the parameter block starting at PROTBEGIN with length
308    PROTLEN using the utf8 encoded key PASSPHRASE and return the entire
309    encrypted block in RESULT or return with an error code.  SHA1HASH
310    is the 20 byte SHA-1 hash required for the integrity code.
311
312    The parameter block is expected to be an incomplete canonical
313    encoded S-Expression of the form (example in advanced format):
314
315      (d #046129F..[some bytes not shown]..81#)
316      (p #00e861b..[some bytes not shown]..f1#)
317      (q #00f7a7c..[some bytes not shown]..61#)
318      (u #304559a..[some bytes not shown]..9b#)
319
320      the returned block is the S-Expression:
321
322      (protected mode (parms) encrypted_octet_string)
323
324 */
325 static int
326 do_encryption (const unsigned char *hashbegin, size_t hashlen,
327                const unsigned char *protbegin, size_t protlen,
328                const char *passphrase,
329                const char *timestamp_exp, size_t timestamp_exp_len,
330                unsigned char **result, size_t *resultlen,
331                unsigned long s2k_count, int use_ocb)
332 {
333   gcry_cipher_hd_t hd;
334   const char *modestr;
335   unsigned char hashvalue[20];
336   int blklen, enclen, outlen;
337   unsigned char *iv = NULL;
338   unsigned int ivsize;  /* Size of the buffer allocated for IV.  */
339   const unsigned char *s2ksalt; /* Points into IV.  */
340   int rc;
341   char *outbuf = NULL;
342   char *p;
343   int saltpos, ivpos, encpos;
344
345   s2ksalt = iv;  /* Silence compiler warning.  */
346
347   *resultlen = 0;
348   *result = NULL;
349
350   modestr = (use_ocb? "openpgp-s2k3-ocb-aes"
351              /*   */: "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc");
352
353   rc = gcry_cipher_open (&hd, PROT_CIPHER,
354                          use_ocb? GCRY_CIPHER_MODE_OCB :
355                          GCRY_CIPHER_MODE_CBC,
356                          GCRY_CIPHER_SECURE);
357   if (rc)
358     return rc;
359
360   /* We need to work on a copy of the data because this makes it
361    * easier to add the trailer and the padding and more important we
362    * have to prefix the text with 2 parenthesis.  In CBC mode we
363    * have to allocate enough space for:
364    *
365    *   ((<parameter_list>)(4:hash4:sha120:<hashvalue>)) + padding
366    *
367    * we always append a full block of random bytes as padding but
368    * encrypt only what is needed for a full blocksize.  In OCB mode we
369    * have to allocate enough space for just:
370    *
371    *   ((<parameter_list>))
372    */
373   blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
374   if (use_ocb)
375     {
376       /*       ((            )) */
377       outlen = 2 + protlen + 2 ;
378       enclen = outlen + 16 /* taglen */;
379       outbuf = gcry_malloc_secure (enclen);
380     }
381   else
382     {
383       /*       ((            )( 4:hash 4:sha1 20:<hash> ))  <padding>  */
384       outlen = 2 + protlen + 2 + 6   + 6    + 23      + 2 + blklen;
385       enclen = outlen/blklen * blklen;
386       outbuf = gcry_malloc_secure (outlen);
387     }
388   if (!outbuf)
389     rc = out_of_core ();
390
391   /* Allocate a buffer for the nonce and the salt.  */
392   if (!rc)
393     {
394       /* Allocate random bytes to be used as IV, padding and s2k salt
395        * or in OCB mode for a nonce and the s2k salt.  The IV/nonce is
396        * set later because for OCB we need to set the key first.  */
397       ivsize = (use_ocb? 12 : (blklen*2)) + 8;
398       iv = xtrymalloc (ivsize);
399       if (!iv)
400         rc = gpg_error_from_syserror ();
401       else
402         {
403           gcry_create_nonce (iv, ivsize);
404           s2ksalt = iv + ivsize - 8;
405         }
406     }
407
408   /* Hash the passphrase and set the key.  */
409   if (!rc)
410     {
411       unsigned char *key;
412       size_t keylen = PROT_CIPHER_KEYLEN;
413
414       key = gcry_malloc_secure (keylen);
415       if (!key)
416         rc = out_of_core ();
417       else
418         {
419           rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
420                                 3, s2ksalt,
421                                 s2k_count? s2k_count:get_standard_s2k_count(),
422                                 key, keylen);
423           if (!rc)
424             rc = gcry_cipher_setkey (hd, key, keylen);
425           xfree (key);
426         }
427     }
428
429   /* Set the IV/nonce.  */
430   if (!rc)
431     {
432       rc = gcry_cipher_setiv (hd, iv, use_ocb? 12 : blklen);
433     }
434
435   if (use_ocb)
436     {
437       /* In OCB Mode we use only the public key parameters as AAD.  */
438       rc = gcry_cipher_authenticate (hd, hashbegin, protbegin - hashbegin);
439       if (!rc)
440         rc = gcry_cipher_authenticate (hd, timestamp_exp, timestamp_exp_len);
441       if (!rc)
442         rc = gcry_cipher_authenticate
443           (hd, protbegin+protlen, hashlen - (protbegin+protlen - hashbegin));
444
445     }
446   else
447     {
448       /* Hash the entire expression for CBC mode.  Because
449        * TIMESTAMP_EXP won't get protected, we can't simply hash a
450        * continuous buffer but need to call md_write several times.  */
451       gcry_md_hd_t md;
452
453       rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 );
454       if (!rc)
455         {
456           gcry_md_write (md, hashbegin, protbegin - hashbegin);
457           gcry_md_write (md, protbegin, protlen);
458           gcry_md_write (md, timestamp_exp, timestamp_exp_len);
459           gcry_md_write (md, protbegin+protlen,
460                          hashlen - (protbegin+protlen - hashbegin));
461           memcpy (hashvalue, gcry_md_read (md, GCRY_MD_SHA1), 20);
462           gcry_md_close (md);
463         }
464     }
465
466
467   /* Encrypt.  */
468   if (!rc)
469     {
470       p = outbuf;
471       *p++ = '(';
472       *p++ = '(';
473       memcpy (p, protbegin, protlen);
474       p += protlen;
475       if (use_ocb)
476         {
477           *p++ = ')';
478           *p++ = ')';
479         }
480       else
481         {
482           memcpy (p, ")(4:hash4:sha120:", 17);
483           p += 17;
484           memcpy (p, hashvalue, 20);
485           p += 20;
486           *p++ = ')';
487           *p++ = ')';
488           memcpy (p, iv+blklen, blklen); /* Add padding.  */
489           p += blklen;
490         }
491       assert ( p - outbuf == outlen);
492       if (use_ocb)
493         {
494           gcry_cipher_final (hd);
495           rc = gcry_cipher_encrypt (hd, outbuf, outlen, NULL, 0);
496           if (!rc)
497             {
498               log_assert (outlen + 16 == enclen);
499               rc = gcry_cipher_gettag (hd, outbuf + outlen, 16);
500             }
501         }
502       else
503         {
504           rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0);
505         }
506     }
507
508   /* Release cipher handle and check for errors.  */
509   gcry_cipher_close (hd);
510   if (rc)
511     {
512       xfree (iv);
513       xfree (outbuf);
514       return rc;
515     }
516
517   /* Now allocate the buffer we want to return.  This is
518
519      (protected openpgp-s2k3-sha1-aes-cbc
520        ((sha1 salt no_of_iterations) 16byte_iv)
521        encrypted_octet_string)
522
523      in canoncical format of course.  We use asprintf and %n modifier
524      and dummy values as placeholders.  */
525   {
526     char countbuf[35];
527
528     snprintf (countbuf, sizeof countbuf, "%lu",
529             s2k_count ? s2k_count : get_standard_s2k_count ());
530     p = xtryasprintf
531       ("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)",
532        (int)strlen (modestr), modestr,
533        &saltpos,
534        (unsigned int)strlen (countbuf), countbuf,
535        use_ocb? 12 : blklen, &ivpos, use_ocb? 12 : blklen, "",
536        enclen, &encpos, enclen, "");
537     if (!p)
538       {
539         gpg_error_t tmperr = out_of_core ();
540         xfree (iv);
541         xfree (outbuf);
542         return tmperr;
543       }
544
545   }
546   *resultlen = strlen (p);
547   *result = (unsigned char*)p;
548   memcpy (p+saltpos, s2ksalt, 8);
549   memcpy (p+ivpos, iv, use_ocb? 12 : blklen);
550   memcpy (p+encpos, outbuf, enclen);
551   xfree (iv);
552   xfree (outbuf);
553   return 0;
554 }
555
556
557
558 /* Protect the key encoded in canonical format in PLAINKEY.  We assume
559    a valid S-Exp here.  With USE_UCB set to -1 the default scheme is
560    used (ie. either CBC or OCB), set to 0 the old CBC mode is used,
561    and set to 1 OCB is used. */
562 int
563 agent_protect (const unsigned char *plainkey, const char *passphrase,
564                unsigned char **result, size_t *resultlen,
565                unsigned long s2k_count, int use_ocb)
566 {
567   int rc;
568   const char *parmlist;
569   int prot_from_idx, prot_to_idx;
570   const unsigned char *s;
571   const unsigned char *hash_begin, *hash_end;
572   const unsigned char *prot_begin, *prot_end, *real_end;
573   size_t n;
574   int c, infidx, i;
575   char timestamp_exp[35];
576   unsigned char *protected;
577   size_t protectedlen;
578   int depth = 0;
579   unsigned char *p;
580   int have_curve = 0;
581
582   if (use_ocb == -1)
583     use_ocb = PROT_DEFAULT_TO_OCB;
584
585   /* Create an S-expression with the protected-at timestamp.  */
586   memcpy (timestamp_exp, "(12:protected-at15:", 19);
587   gnupg_get_isotime (timestamp_exp+19);
588   timestamp_exp[19+15] = ')';
589
590   /* Parse original key.  */
591   s = plainkey;
592   if (*s != '(')
593     return gpg_error (GPG_ERR_INV_SEXP);
594   depth++;
595   s++;
596   n = snext (&s);
597   if (!n)
598     return gpg_error (GPG_ERR_INV_SEXP);
599   if (!smatch (&s, n, "private-key"))
600     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
601   if (*s != '(')
602     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
603   depth++;
604   hash_begin = s;
605   s++;
606   n = snext (&s);
607   if (!n)
608     return gpg_error (GPG_ERR_INV_SEXP);
609
610   for (infidx=0; protect_info[infidx].algo
611               && !smatch (&s, n, protect_info[infidx].algo); infidx++)
612     ;
613   if (!protect_info[infidx].algo)
614     return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
615
616   /* The parser below is a complete mess: To make it robust for ECC
617      use we should reorder the s-expression to include only what we
618      really need and thus guarantee the right order for saving stuff.
619      This should be done before calling this function and maybe with
620      the help of the new gcry_sexp_extract_param.  */
621   parmlist      = protect_info[infidx].parmlist;
622   prot_from_idx = protect_info[infidx].prot_from;
623   prot_to_idx   = protect_info[infidx].prot_to;
624   prot_begin = prot_end = NULL;
625   for (i=0; (c=parmlist[i]); i++)
626     {
627       if (i == prot_from_idx)
628         prot_begin = s;
629       if (*s != '(')
630         return gpg_error (GPG_ERR_INV_SEXP);
631       depth++;
632       s++;
633       n = snext (&s);
634       if (!n)
635         return gpg_error (GPG_ERR_INV_SEXP);
636       if (n != 1 || c != *s)
637         {
638           if (n == 5 && !memcmp (s, "curve", 5)
639               && !i && protect_info[infidx].ecc_hack)
640             {
641               /* This is a private ECC key but the first parameter is
642                  the name of the curve.  We change the parameter list
643                  here to the one we expect in this case.  */
644               have_curve = 1;
645               parmlist = "?qd";
646               prot_from_idx = 2;
647               prot_to_idx = 2;
648             }
649           else if (n == 5 && !memcmp (s, "flags", 5)
650                    && i == 1 && have_curve)
651             {
652               /* "curve" followed by "flags": Change again.  */
653               parmlist = "??qd";
654               prot_from_idx = 3;
655               prot_to_idx = 3;
656             }
657           else
658             return gpg_error (GPG_ERR_INV_SEXP);
659         }
660       s += n;
661       n = snext (&s);
662       if (!n)
663         return gpg_error (GPG_ERR_INV_SEXP);
664       s +=n; /* skip value */
665       if (*s != ')')
666         return gpg_error (GPG_ERR_INV_SEXP);
667       depth--;
668       if (i == prot_to_idx)
669         prot_end = s;
670       s++;
671     }
672   if (*s != ')' || !prot_begin || !prot_end )
673     return gpg_error (GPG_ERR_INV_SEXP);
674   depth--;
675   hash_end = s;
676   s++;
677   /* Skip to the end of the S-expression.  */
678   assert (depth == 1);
679   rc = sskip (&s, &depth);
680   if (rc)
681     return rc;
682   assert (!depth);
683   real_end = s-1;
684
685   rc = do_encryption (hash_begin, hash_end - hash_begin + 1,
686                       prot_begin, prot_end - prot_begin + 1,
687                       passphrase, timestamp_exp, sizeof (timestamp_exp),
688                       &protected, &protectedlen, s2k_count, use_ocb);
689   if (rc)
690     return rc;
691
692   /* Now create the protected version of the key.  Note that the 10
693      extra bytes are for for the inserted "protected-" string (the
694      beginning of the plaintext reads: "((11:private-key(" ).  The 35
695      term is the space for (12:protected-at15:<timestamp>).  */
696   *resultlen = (10
697                 + (prot_begin-plainkey)
698                 + protectedlen
699                 + 35
700                 + (real_end-prot_end));
701   *result = p = xtrymalloc (*resultlen);
702   if (!p)
703     {
704       gpg_error_t tmperr = out_of_core ();
705       xfree (protected);
706       return tmperr;
707     }
708   memcpy (p, "(21:protected-", 14);
709   p += 14;
710   memcpy (p, plainkey+4, prot_begin - plainkey - 4);
711   p += prot_begin - plainkey - 4;
712   memcpy (p, protected, protectedlen);
713   p += protectedlen;
714
715   memcpy (p, timestamp_exp, 35);
716   p += 35;
717
718   memcpy (p, prot_end+1, real_end - prot_end);
719   p += real_end - prot_end;
720   assert ( p - *result == *resultlen);
721   xfree (protected);
722
723   return 0;
724 }
725
726
727 \f
728 /* Do the actual decryption and check the return list for consistency.  */
729 static int
730 do_decryption (const unsigned char *aad_begin, size_t aad_len,
731                const unsigned char *aadhole_begin, size_t aadhole_len,
732                const unsigned char *protected, size_t protectedlen,
733                const char *passphrase,
734                const unsigned char *s2ksalt, unsigned long s2kcount,
735                const unsigned char *iv, size_t ivlen,
736                int prot_cipher, int prot_cipher_keylen, int is_ocb,
737                unsigned char **result)
738 {
739   int rc = 0;
740   int blklen;
741   gcry_cipher_hd_t hd;
742   unsigned char *outbuf;
743   size_t reallen;
744
745   blklen = gcry_cipher_get_algo_blklen (prot_cipher);
746   if (is_ocb)
747     {
748       /* OCB does not require a multiple of the block length but we
749        * check that it is long enough for the 128 bit tag and that we
750        * have the 96 bit nonce.  */
751       if (protectedlen < (4 + 16) || ivlen != 12)
752         return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
753     }
754   else
755     {
756       if (protectedlen < 4 || (protectedlen%blklen))
757         return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
758     }
759
760   rc = gcry_cipher_open (&hd, prot_cipher,
761                          is_ocb? GCRY_CIPHER_MODE_OCB :
762                          GCRY_CIPHER_MODE_CBC,
763                          GCRY_CIPHER_SECURE);
764   if (rc)
765     return rc;
766
767   outbuf = gcry_malloc_secure (protectedlen);
768   if (!outbuf)
769     rc = out_of_core ();
770
771   /* Hash the passphrase and set the key.  */
772   if (!rc)
773     {
774       unsigned char *key;
775
776       key = gcry_malloc_secure (prot_cipher_keylen);
777       if (!key)
778         rc = out_of_core ();
779       else
780         {
781           rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
782                                 3, s2ksalt, s2kcount, key, prot_cipher_keylen);
783           if (!rc)
784             rc = gcry_cipher_setkey (hd, key, prot_cipher_keylen);
785           xfree (key);
786         }
787     }
788
789   /* Set the IV/nonce.  */
790   if (!rc)
791     {
792       rc = gcry_cipher_setiv (hd, iv, ivlen);
793     }
794
795   /* Decrypt.  */
796   if (!rc)
797     {
798       if (is_ocb)
799         {
800           rc = gcry_cipher_authenticate (hd, aad_begin,
801                                          aadhole_begin - aad_begin);
802           if (!rc)
803             rc = gcry_cipher_authenticate
804               (hd, aadhole_begin + aadhole_len,
805                aad_len - (aadhole_begin+aadhole_len - aad_begin));
806
807           if (!rc)
808             {
809               gcry_cipher_final (hd);
810               rc = gcry_cipher_decrypt (hd, outbuf, protectedlen - 16,
811                                         protected, protectedlen - 16);
812             }
813           if (!rc)
814             rc = gcry_cipher_checktag (hd, protected + protectedlen - 16, 16);
815         }
816       else
817         {
818           rc = gcry_cipher_decrypt (hd, outbuf, protectedlen,
819                                     protected, protectedlen);
820         }
821     }
822
823   /* Release cipher handle and check for errors.  */
824   gcry_cipher_close (hd);
825   if (rc)
826     {
827       xfree (outbuf);
828       return rc;
829     }
830
831   /* Do a quick check on the data structure. */
832   if (*outbuf != '(' && outbuf[1] != '(')
833     {
834       /* Note that in OCB mode this is actually invalid _encrypted_
835        * data and not a bad passphrase.  */
836       xfree (outbuf);
837       return gpg_error (GPG_ERR_BAD_PASSPHRASE);
838     }
839
840   /* Check that we have a consistent S-Exp. */
841   reallen = gcry_sexp_canon_len (outbuf, protectedlen, NULL, NULL);
842   if (!reallen || (reallen + blklen < protectedlen) )
843     {
844       xfree (outbuf);
845       return gpg_error (GPG_ERR_BAD_PASSPHRASE);
846     }
847   *result = outbuf;
848   return 0;
849 }
850
851
852 /* Merge the parameter list contained in CLEARTEXT with the original
853  * protect lists PROTECTEDKEY by replacing the list at REPLACEPOS.
854  * Return the new list in RESULT and the MIC value in the 20 byte
855  * buffer SHA1HASH; if SHA1HASH is NULL no MIC will be computed.
856  * CUTOFF and CUTLEN will receive the offset and the length of the
857  * resulting list which should go into the MIC calculation but then be
858  * removed.  */
859 static int
860 merge_lists (const unsigned char *protectedkey,
861              size_t replacepos,
862              const unsigned char *cleartext,
863              unsigned char *sha1hash,
864              unsigned char **result, size_t *resultlen,
865              size_t *cutoff, size_t *cutlen)
866 {
867   size_t n, newlistlen;
868   unsigned char *newlist, *p;
869   const unsigned char *s;
870   const unsigned char *startpos, *endpos;
871   int i, rc;
872
873   *result = NULL;
874   *resultlen = 0;
875   *cutoff = 0;
876   *cutlen = 0;
877
878   if (replacepos < 26)
879     return gpg_error (GPG_ERR_BUG);
880
881   /* Estimate the required size of the resulting list.  We have a large
882      safety margin of >20 bytes (FIXME: MIC hash from CLEARTEXT and the
883      removed "protected-" */
884   newlistlen = gcry_sexp_canon_len (protectedkey, 0, NULL, NULL);
885   if (!newlistlen)
886     return gpg_error (GPG_ERR_BUG);
887   n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL);
888   if (!n)
889     return gpg_error (GPG_ERR_BUG);
890   newlistlen += n;
891   newlist = gcry_malloc_secure (newlistlen);
892   if (!newlist)
893     return out_of_core ();
894
895   /* Copy the initial segment */
896   strcpy ((char*)newlist, "(11:private-key");
897   p = newlist + 15;
898   memcpy (p, protectedkey+15+10, replacepos-15-10);
899   p += replacepos-15-10;
900
901   /* Copy the cleartext.  */
902   s = cleartext;
903   if (*s != '(' && s[1] != '(')
904     return gpg_error (GPG_ERR_BUG);  /*we already checked this */
905   s += 2;
906   startpos = s;
907   while ( *s == '(' )
908     {
909       s++;
910       n = snext (&s);
911       if (!n)
912         goto invalid_sexp;
913       s += n;
914       n = snext (&s);
915       if (!n)
916         goto invalid_sexp;
917       s += n;
918       if ( *s != ')' )
919         goto invalid_sexp;
920       s++;
921     }
922   if ( *s != ')' )
923     goto invalid_sexp;
924   endpos = s;
925   s++;
926
927   /* Intermezzo: Get the MIC if requested.  */
928   if (sha1hash)
929     {
930       if (*s != '(')
931         goto invalid_sexp;
932       s++;
933       n = snext (&s);
934       if (!smatch (&s, n, "hash"))
935         goto invalid_sexp;
936       n = snext (&s);
937       if (!smatch (&s, n, "sha1"))
938         goto invalid_sexp;
939       n = snext (&s);
940       if (n != 20)
941         goto invalid_sexp;
942       memcpy (sha1hash, s, 20);
943       s += n;
944       if (*s != ')')
945         goto invalid_sexp;
946     }
947
948   /* Append the parameter list.  */
949   memcpy (p, startpos, endpos - startpos);
950   p += endpos - startpos;
951
952   /* Skip over the protected list element in the original list.  */
953   s = protectedkey + replacepos;
954   assert (*s == '(');
955   s++;
956   i = 1;
957   rc = sskip (&s, &i);
958   if (rc)
959     goto failure;
960   /* Record the position of the optional protected-at expression.  */
961   if (*s == '(')
962     {
963       const unsigned char *save_s = s;
964       s++;
965       n = snext (&s);
966       if (smatch (&s, n, "protected-at"))
967         {
968           i = 1;
969           rc = sskip (&s, &i);
970           if (rc)
971             goto failure;
972           *cutlen = s - save_s;
973         }
974       s = save_s;
975     }
976   startpos = s;
977   i = 2; /* we are inside this level */
978   rc = sskip (&s, &i);
979   if (rc)
980     goto failure;
981   assert (s[-1] == ')');
982   endpos = s; /* one behind the end of the list */
983
984   /* Append the rest. */
985   if (*cutlen)
986     *cutoff = p - newlist;
987   memcpy (p, startpos, endpos - startpos);
988   p += endpos - startpos;
989
990
991   /* ready */
992   *result = newlist;
993   *resultlen = newlistlen;
994   return 0;
995
996  failure:
997   wipememory (newlist, newlistlen);
998   xfree (newlist);
999   return rc;
1000
1001  invalid_sexp:
1002   wipememory (newlist, newlistlen);
1003   xfree (newlist);
1004   return gpg_error (GPG_ERR_INV_SEXP);
1005 }
1006
1007
1008
1009 /* Unprotect the key encoded in canonical format.  We assume a valid
1010    S-Exp here.  If a protected-at item is available, its value will
1011    be stored at protected_at unless this is NULL.  */
1012 int
1013 agent_unprotect (ctrl_t ctrl,
1014                  const unsigned char *protectedkey, const char *passphrase,
1015                  gnupg_isotime_t protected_at,
1016                  unsigned char **result, size_t *resultlen)
1017 {
1018   static struct {
1019     const char *name; /* Name of the protection method. */
1020     int algo;         /* (A zero indicates the "openpgp-native" hack.)  */
1021     int keylen;       /* Used key length in bytes.  */
1022     unsigned int is_ocb:1;
1023   } algotable[] = {
1024     { "openpgp-s2k3-sha1-aes-cbc",    GCRY_CIPHER_AES128, (128/8)},
1025     { "openpgp-s2k3-sha1-aes256-cbc", GCRY_CIPHER_AES256, (256/8)},
1026     { "openpgp-s2k3-ocb-aes",         GCRY_CIPHER_AES128, (128/8), 1},
1027     { "openpgp-native", 0, 0 }
1028   };
1029   int rc;
1030   const unsigned char *s;
1031   const unsigned char *protect_list;
1032   size_t n;
1033   int infidx, i;
1034   unsigned char sha1hash[20], sha1hash2[20];
1035   const unsigned char *s2ksalt;
1036   unsigned long s2kcount;
1037   const unsigned char *iv;
1038   int prot_cipher, prot_cipher_keylen;
1039   int is_ocb;
1040   const unsigned char *aad_begin, *aad_end, *aadhole_begin, *aadhole_end;
1041   const unsigned char *prot_begin;
1042   unsigned char *cleartext;
1043   unsigned char *final;
1044   size_t finallen;
1045   size_t cutoff, cutlen;
1046
1047   if (protected_at)
1048     *protected_at = 0;
1049
1050   s = protectedkey;
1051   if (*s != '(')
1052     return gpg_error (GPG_ERR_INV_SEXP);
1053   s++;
1054   n = snext (&s);
1055   if (!n)
1056     return gpg_error (GPG_ERR_INV_SEXP);
1057   if (!smatch (&s, n, "protected-private-key"))
1058     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1059   if (*s != '(')
1060     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1061   {
1062     aad_begin = aad_end = s;
1063     aad_end++;
1064     i = 1;
1065     rc = sskip (&aad_end, &i);
1066     if (rc)
1067       return rc;
1068   }
1069
1070   s++;
1071   n = snext (&s);
1072   if (!n)
1073     return gpg_error (GPG_ERR_INV_SEXP);
1074
1075   for (infidx=0; protect_info[infidx].algo
1076               && !smatch (&s, n, protect_info[infidx].algo); infidx++)
1077     ;
1078   if (!protect_info[infidx].algo)
1079     return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
1080
1081   /* See wether we have a protected-at timestamp.  */
1082   protect_list = s;  /* Save for later.  */
1083   if (protected_at)
1084     {
1085       while (*s == '(')
1086         {
1087           prot_begin = s;
1088           s++;
1089           n = snext (&s);
1090           if (!n)
1091             return gpg_error (GPG_ERR_INV_SEXP);
1092           if (smatch (&s, n, "protected-at"))
1093             {
1094               n = snext (&s);
1095               if (!n)
1096                 return gpg_error (GPG_ERR_INV_SEXP);
1097               if (n != 15)
1098                 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1099               memcpy (protected_at, s, 15);
1100               protected_at[15] = 0;
1101               break;
1102             }
1103           s += n;
1104           i = 1;
1105           rc = sskip (&s, &i);
1106           if (rc)
1107             return rc;
1108         }
1109     }
1110
1111   /* Now find the list with the protected information.  Here is an
1112      example for such a list:
1113      (protected openpgp-s2k3-sha1-aes-cbc
1114         ((sha1 <salt> <count>) <Initialization_Vector>)
1115         <encrypted_data>)
1116    */
1117   s = protect_list;
1118   for (;;)
1119     {
1120       if (*s != '(')
1121         return gpg_error (GPG_ERR_INV_SEXP);
1122       prot_begin = s;
1123       s++;
1124       n = snext (&s);
1125       if (!n)
1126         return gpg_error (GPG_ERR_INV_SEXP);
1127       if (smatch (&s, n, "protected"))
1128         break;
1129       s += n;
1130       i = 1;
1131       rc = sskip (&s, &i);
1132       if (rc)
1133         return rc;
1134     }
1135   /* found */
1136   {
1137     aadhole_begin = aadhole_end = prot_begin;
1138     aadhole_end++;
1139     i = 1;
1140     rc = sskip (&aadhole_end, &i);
1141     if (rc)
1142       return rc;
1143   }
1144   n = snext (&s);
1145   if (!n)
1146     return gpg_error (GPG_ERR_INV_SEXP);
1147
1148   /* Lookup the protection algo.  */
1149   prot_cipher = 0;        /* (avoid gcc warning) */
1150   prot_cipher_keylen = 0; /* (avoid gcc warning) */
1151   is_ocb = 0;
1152   for (i=0; i < DIM (algotable); i++)
1153     if (smatch (&s, n, algotable[i].name))
1154       {
1155         prot_cipher = algotable[i].algo;
1156         prot_cipher_keylen = algotable[i].keylen;
1157         is_ocb = algotable[i].is_ocb;
1158         break;
1159       }
1160   if (i == DIM (algotable))
1161     return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
1162
1163   if (!prot_cipher)  /* This is "openpgp-native".  */
1164     {
1165       gcry_sexp_t s_prot_begin;
1166
1167       rc = gcry_sexp_sscan (&s_prot_begin, NULL,
1168                             prot_begin,
1169                             gcry_sexp_canon_len (prot_begin, 0,NULL,NULL));
1170       if (rc)
1171         return rc;
1172
1173       rc = convert_from_openpgp_native (ctrl, s_prot_begin, passphrase, &final);
1174       gcry_sexp_release (s_prot_begin);
1175       if (!rc)
1176         {
1177           *result = final;
1178           *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
1179         }
1180       return rc;
1181     }
1182
1183   if (*s != '(' || s[1] != '(')
1184     return gpg_error (GPG_ERR_INV_SEXP);
1185   s += 2;
1186   n = snext (&s);
1187   if (!n)
1188     return gpg_error (GPG_ERR_INV_SEXP);
1189   if (!smatch (&s, n, "sha1"))
1190     return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
1191   n = snext (&s);
1192   if (n != 8)
1193     return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1194   s2ksalt = s;
1195   s += n;
1196   n = snext (&s);
1197   if (!n)
1198     return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1199   /* We expect a list close as next, so we can simply use strtoul()
1200      here.  We might want to check that we only have digits - but this
1201      is nothing we should worry about */
1202   if (s[n] != ')' )
1203     return gpg_error (GPG_ERR_INV_SEXP);
1204
1205   /* Old versions of gpg-agent used the funny floating point number in
1206      a byte encoding as specified by OpenPGP.  However this is not
1207      needed and thus we now store it as a plain unsigned integer.  We
1208      can easily distinguish the old format by looking at its value:
1209      Less than 256 is an old-style encoded number; other values are
1210      plain integers.  In any case we check that they are at least
1211      65536 because we never used a lower value in the past and we
1212      should have a lower limit.  */
1213   s2kcount = strtoul ((const char*)s, NULL, 10);
1214   if (!s2kcount)
1215     return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1216   if (s2kcount < 256)
1217     s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6);
1218   if (s2kcount < 65536)
1219     return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1220
1221   s += n;
1222   s++; /* skip list end */
1223
1224   n = snext (&s);
1225   if (is_ocb)
1226     {
1227       if (n != 12) /* Wrong size of the nonce. */
1228         return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1229     }
1230   else
1231     {
1232       if (n != 16) /* Wrong blocksize for IV (we support only 128 bit). */
1233         return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1234     }
1235   iv = s;
1236   s += n;
1237   if (*s != ')' )
1238     return gpg_error (GPG_ERR_INV_SEXP);
1239   s++;
1240   n = snext (&s);
1241   if (!n)
1242     return gpg_error (GPG_ERR_INV_SEXP);
1243
1244   cleartext = NULL; /* Avoid cc warning. */
1245   rc = do_decryption (aad_begin, aad_end - aad_begin,
1246                       aadhole_begin, aadhole_end - aadhole_begin,
1247                       s, n,
1248                       passphrase, s2ksalt, s2kcount,
1249                       iv, is_ocb? 12:16,
1250                       prot_cipher, prot_cipher_keylen, is_ocb,
1251                       &cleartext);
1252   if (rc)
1253     return rc;
1254
1255   rc = merge_lists (protectedkey, prot_begin-protectedkey, cleartext,
1256                     is_ocb? NULL : sha1hash,
1257                     &final, &finallen, &cutoff, &cutlen);
1258   /* Albeit cleartext has been allocated in secure memory and thus
1259      xfree will wipe it out, we do an extra wipe just in case
1260      somethings goes badly wrong. */
1261   wipememory (cleartext, n);
1262   xfree (cleartext);
1263   if (rc)
1264     return rc;
1265
1266   if (!is_ocb)
1267     {
1268       rc = calculate_mic (final, sha1hash2);
1269       if (!rc && memcmp (sha1hash, sha1hash2, 20))
1270         rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1271       if (rc)
1272         {
1273           wipememory (final, finallen);
1274           xfree (final);
1275           return rc;
1276         }
1277     }
1278
1279   /* Now remove the part which is included in the MIC but should not
1280      go into the final thing.  */
1281   if (cutlen)
1282     {
1283       memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen);
1284       finallen -= cutlen;
1285     }
1286
1287   *result = final;
1288   *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
1289   return 0;
1290 }
1291
1292 /* Check the type of the private key, this is one of the constants:
1293    PRIVATE_KEY_UNKNOWN if we can't figure out the type (this is the
1294    value 0), PRIVATE_KEY_CLEAR for an unprotected private key.
1295    PRIVATE_KEY_PROTECTED for an protected private key or
1296    PRIVATE_KEY_SHADOWED for a sub key where the secret parts are
1297    stored elsewhere.  Finally PRIVATE_KEY_OPENPGP_NONE may be returned
1298    is the key is still in the openpgp-native format but without
1299    protection.  */
1300 int
1301 agent_private_key_type (const unsigned char *privatekey)
1302 {
1303   const unsigned char *s;
1304   size_t n;
1305   int i;
1306
1307   s = privatekey;
1308   if (*s != '(')
1309     return PRIVATE_KEY_UNKNOWN;
1310   s++;
1311   n = snext (&s);
1312   if (!n)
1313     return PRIVATE_KEY_UNKNOWN;
1314   if (smatch (&s, n, "protected-private-key"))
1315     {
1316       /* We need to check whether this is openpgp-native protected
1317          with the protection method "none".  In that case we return a
1318          different key type so that the caller knows that there is no
1319          need to ask for a passphrase. */
1320       if (*s != '(')
1321         return PRIVATE_KEY_PROTECTED; /* Unknown sexp - assume protected. */
1322       s++;
1323       n = snext (&s);
1324       if (!n)
1325         return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1326       s += n; /* Skip over the algo */
1327
1328       /* Find the (protected ...) list.  */
1329       for (;;)
1330         {
1331           if (*s != '(')
1332             return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1333           s++;
1334           n = snext (&s);
1335           if (!n)
1336             return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1337           if (smatch (&s, n, "protected"))
1338             break;
1339           s += n;
1340           i = 1;
1341           if (sskip (&s, &i))
1342             return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1343         }
1344       /* Found - Is this openpgp-native? */
1345       n = snext (&s);
1346       if (!n)
1347         return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1348       if (smatch (&s, n, "openpgp-native")) /* Yes.  */
1349         {
1350           if (*s != '(')
1351             return PRIVATE_KEY_UNKNOWN; /* Unknown sexp. */
1352           s++;
1353           n = snext (&s);
1354           if (!n)
1355             return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1356           s += n; /* Skip over "openpgp-private-key".  */
1357           /* Find the (protection ...) list.  */
1358           for (;;)
1359             {
1360               if (*s != '(')
1361                 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1362               s++;
1363               n = snext (&s);
1364               if (!n)
1365                 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1366               if (smatch (&s, n, "protection"))
1367                 break;
1368               s += n;
1369               i = 1;
1370               if (sskip (&s, &i))
1371                 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1372             }
1373           /* Found - Is the mode "none"? */
1374           n = snext (&s);
1375           if (!n)
1376             return PRIVATE_KEY_UNKNOWN; /* Invalid sexp.  */
1377           if (smatch (&s, n, "none"))
1378             return PRIVATE_KEY_OPENPGP_NONE;  /* Yes.  */
1379         }
1380
1381       return PRIVATE_KEY_PROTECTED;
1382     }
1383   if (smatch (&s, n, "shadowed-private-key"))
1384     return PRIVATE_KEY_SHADOWED;
1385   if (smatch (&s, n, "private-key"))
1386     return PRIVATE_KEY_CLEAR;
1387   return PRIVATE_KEY_UNKNOWN;
1388 }
1389
1390
1391 \f
1392 /* Transform a passphrase into a suitable key of length KEYLEN and
1393    store this key in the caller provided buffer KEY.  The caller must
1394    provide an HASHALGO, a valid S2KMODE (see rfc-2440) and depending on
1395    that mode an S2KSALT of 8 random bytes and an S2KCOUNT.
1396
1397    Returns an error code on failure.  */
1398 static int
1399 hash_passphrase (const char *passphrase, int hashalgo,
1400                  int s2kmode,
1401                  const unsigned char *s2ksalt,
1402                  unsigned long s2kcount,
1403                  unsigned char *key, size_t keylen)
1404 {
1405   /* The key derive function does not support a zero length string for
1406      the passphrase in the S2K modes.  Return a better suited error
1407      code than GPG_ERR_INV_DATA.  */
1408   if (!passphrase || !*passphrase)
1409     return gpg_error (GPG_ERR_NO_PASSPHRASE);
1410   return gcry_kdf_derive (passphrase, strlen (passphrase),
1411                           s2kmode == 3? GCRY_KDF_ITERSALTED_S2K :
1412                           s2kmode == 1? GCRY_KDF_SALTED_S2K :
1413                           s2kmode == 0? GCRY_KDF_SIMPLE_S2K : GCRY_KDF_NONE,
1414                           hashalgo, s2ksalt, 8, s2kcount,
1415                           keylen, key);
1416 }
1417
1418
1419 gpg_error_t
1420 s2k_hash_passphrase (const char *passphrase, int hashalgo,
1421                      int s2kmode,
1422                      const unsigned char *s2ksalt,
1423                      unsigned int s2kcount,
1424                      unsigned char *key, size_t keylen)
1425 {
1426   return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt,
1427                           S2K_DECODE_COUNT (s2kcount),
1428                           key, keylen);
1429 }
1430
1431
1432 \f
1433
1434 /* Create an canonical encoded S-expression with the shadow info from
1435    a card's SERIALNO and the IDSTRING.  */
1436 unsigned char *
1437 make_shadow_info (const char *serialno, const char *idstring)
1438 {
1439   const char *s;
1440   char *info, *p;
1441   char numbuf[20];
1442   size_t n;
1443
1444   for (s=serialno, n=0; *s && s[1]; s += 2)
1445     n++;
1446
1447   info = p = xtrymalloc (1 + sizeof numbuf + n
1448                            + sizeof numbuf + strlen (idstring) + 1 + 1);
1449   if (!info)
1450     return NULL;
1451   *p++ = '(';
1452   p = stpcpy (p, smklen (numbuf, sizeof numbuf, n, NULL));
1453   for (s=serialno; *s && s[1]; s += 2)
1454     *(unsigned char *)p++ = xtoi_2 (s);
1455   p = stpcpy (p, smklen (numbuf, sizeof numbuf, strlen (idstring), NULL));
1456   p = stpcpy (p, idstring);
1457   *p++ = ')';
1458   *p = 0;
1459   return (unsigned char *)info;
1460 }
1461
1462
1463
1464 /* Create a shadow key from a public key.  We use the shadow protocol
1465   "ti-v1" and insert the S-expressionn SHADOW_INFO.  The resulting
1466   S-expression is returned in an allocated buffer RESULT will point
1467   to. The input parameters are expected to be valid canonicalized
1468   S-expressions */
1469 int
1470 agent_shadow_key (const unsigned char *pubkey,
1471                   const unsigned char *shadow_info,
1472                   unsigned char **result)
1473 {
1474   const unsigned char *s;
1475   const unsigned char *point;
1476   size_t n;
1477   int depth = 0;
1478   char *p;
1479   size_t pubkey_len = gcry_sexp_canon_len (pubkey, 0, NULL,NULL);
1480   size_t shadow_info_len = gcry_sexp_canon_len (shadow_info, 0, NULL,NULL);
1481
1482   if (!pubkey_len || !shadow_info_len)
1483     return gpg_error (GPG_ERR_INV_VALUE);
1484   s = pubkey;
1485   if (*s != '(')
1486     return gpg_error (GPG_ERR_INV_SEXP);
1487   depth++;
1488   s++;
1489   n = snext (&s);
1490   if (!n)
1491     return gpg_error (GPG_ERR_INV_SEXP);
1492   if (!smatch (&s, n, "public-key"))
1493     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1494   if (*s != '(')
1495     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1496   depth++;
1497   s++;
1498   n = snext (&s);
1499   if (!n)
1500     return gpg_error (GPG_ERR_INV_SEXP);
1501   s += n; /* skip over the algorithm name */
1502
1503   while (*s != ')')
1504     {
1505       if (*s != '(')
1506         return gpg_error (GPG_ERR_INV_SEXP);
1507       depth++;
1508       s++;
1509       n = snext (&s);
1510       if (!n)
1511         return gpg_error (GPG_ERR_INV_SEXP);
1512       s += n;
1513       n = snext (&s);
1514       if (!n)
1515         return gpg_error (GPG_ERR_INV_SEXP);
1516       s +=n; /* skip value */
1517       if (*s != ')')
1518         return gpg_error (GPG_ERR_INV_SEXP);
1519       depth--;
1520       s++;
1521     }
1522   point = s; /* insert right before the point */
1523   depth--;
1524   s++;
1525   assert (depth == 1);
1526
1527   /* Calculate required length by taking in account: the "shadowed-"
1528      prefix, the "shadowed", "t1-v1" as well as some parenthesis */
1529   n = 12 + pubkey_len + 1 + 3+8 + 2+5 + shadow_info_len + 1;
1530   *result = xtrymalloc (n);
1531   p = (char*)*result;
1532   if (!p)
1533       return out_of_core ();
1534   p = stpcpy (p, "(20:shadowed-private-key");
1535   /* (10:public-key ...)*/
1536   memcpy (p, pubkey+14, point - (pubkey+14));
1537   p += point - (pubkey+14);
1538   p = stpcpy (p, "(8:shadowed5:t1-v1");
1539   memcpy (p, shadow_info, shadow_info_len);
1540   p += shadow_info_len;
1541   *p++ = ')';
1542   memcpy (p, point, pubkey_len - (point - pubkey));
1543   p += pubkey_len - (point - pubkey);
1544
1545   return 0;
1546 }
1547
1548 /* Parse a canonical encoded shadowed key and return a pointer to the
1549    inner list with the shadow_info */
1550 int
1551 agent_get_shadow_info (const unsigned char *shadowkey,
1552                        unsigned char const **shadow_info)
1553 {
1554   const unsigned char *s;
1555   size_t n;
1556   int depth = 0;
1557
1558   s = shadowkey;
1559   if (*s != '(')
1560     return gpg_error (GPG_ERR_INV_SEXP);
1561   depth++;
1562   s++;
1563   n = snext (&s);
1564   if (!n)
1565     return gpg_error (GPG_ERR_INV_SEXP);
1566   if (!smatch (&s, n, "shadowed-private-key"))
1567     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1568   if (*s != '(')
1569     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1570   depth++;
1571   s++;
1572   n = snext (&s);
1573   if (!n)
1574     return gpg_error (GPG_ERR_INV_SEXP);
1575   s += n; /* skip over the algorithm name */
1576
1577   for (;;)
1578     {
1579       if (*s == ')')
1580         return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1581       if (*s != '(')
1582         return gpg_error (GPG_ERR_INV_SEXP);
1583       depth++;
1584       s++;
1585       n = snext (&s);
1586       if (!n)
1587         return gpg_error (GPG_ERR_INV_SEXP);
1588       if (smatch (&s, n, "shadowed"))
1589         break;
1590       s += n;
1591       n = snext (&s);
1592       if (!n)
1593         return gpg_error (GPG_ERR_INV_SEXP);
1594       s +=n; /* skip value */
1595       if (*s != ')')
1596         return gpg_error (GPG_ERR_INV_SEXP);
1597       depth--;
1598       s++;
1599     }
1600   /* Found the shadowed list, S points to the protocol */
1601   n = snext (&s);
1602   if (!n)
1603     return gpg_error (GPG_ERR_INV_SEXP);
1604   if (smatch (&s, n, "t1-v1"))
1605     {
1606       if (*s != '(')
1607         return gpg_error (GPG_ERR_INV_SEXP);
1608       *shadow_info = s;
1609     }
1610   else
1611     return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
1612   return 0;
1613 }
1614
1615
1616 /* Parse the canonical encoded SHADOW_INFO S-expression.  On success
1617    the hex encoded serial number is returned as a malloced strings at
1618    R_HEXSN and the Id string as a malloced string at R_IDSTR.  On
1619    error an error code is returned and NULL is stored at the result
1620    parameters addresses.  If the serial number or the ID string is not
1621    required, NULL may be passed for them.  */
1622 gpg_error_t
1623 parse_shadow_info (const unsigned char *shadow_info,
1624                    char **r_hexsn, char **r_idstr, int *r_pinlen)
1625 {
1626   const unsigned char *s;
1627   size_t n;
1628
1629   if (r_hexsn)
1630     *r_hexsn = NULL;
1631   if (r_idstr)
1632     *r_idstr = NULL;
1633   if (r_pinlen)
1634     *r_pinlen = 0;
1635
1636   s = shadow_info;
1637   if (*s != '(')
1638     return gpg_error (GPG_ERR_INV_SEXP);
1639   s++;
1640   n = snext (&s);
1641   if (!n)
1642     return gpg_error (GPG_ERR_INV_SEXP);
1643
1644   if (r_hexsn)
1645     {
1646       *r_hexsn = bin2hex (s, n, NULL);
1647       if (!*r_hexsn)
1648         return gpg_error_from_syserror ();
1649     }
1650   s += n;
1651
1652   n = snext (&s);
1653   if (!n)
1654     {
1655       if (r_hexsn)
1656         {
1657           xfree (*r_hexsn);
1658           *r_hexsn = NULL;
1659         }
1660       return gpg_error (GPG_ERR_INV_SEXP);
1661     }
1662
1663   if (r_idstr)
1664     {
1665       *r_idstr = xtrymalloc (n+1);
1666       if (!*r_idstr)
1667         {
1668           if (r_hexsn)
1669             {
1670               xfree (*r_hexsn);
1671               *r_hexsn = NULL;
1672             }
1673           return gpg_error_from_syserror ();
1674         }
1675       memcpy (*r_idstr, s, n);
1676       (*r_idstr)[n] = 0;
1677     }
1678
1679   /* Parse the optional PINLEN.  */
1680   n = snext (&s);
1681   if (!n)
1682     return 0;
1683
1684   if (r_pinlen)
1685     {
1686       char *tmpstr = xtrymalloc (n+1);
1687       if (!tmpstr)
1688         {
1689           if (r_hexsn)
1690             {
1691               xfree (*r_hexsn);
1692               *r_hexsn = NULL;
1693             }
1694           if (r_idstr)
1695             {
1696               xfree (*r_idstr);
1697               *r_idstr = NULL;
1698             }
1699           return gpg_error_from_syserror ();
1700         }
1701       memcpy (tmpstr, s, n);
1702       tmpstr[n] = 0;
1703
1704       *r_pinlen = (int)strtol (tmpstr, NULL, 10);
1705       xfree (tmpstr);
1706     }
1707
1708   return 0;
1709 }