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