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
5 * This file is part of GnuPG.
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.
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.
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/>.
30 #ifdef HAVE_W32_SYSTEM
31 # ifdef HAVE_WINSOCK2_H
32 # include <winsock2.h>
36 # include <sys/times.h>
41 #include "cvt-openpgp.h"
42 #include "sexp-parse.h"
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
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)
56 /* Decode an rfc4880 encoded S2K count. */
57 #define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6))
60 /* A table containing the information needed to create a protected
65 int prot_from, prot_to;
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 },
78 /* A helper object for time measurement. */
79 struct calibrate_time_s
81 #ifdef HAVE_W32_SYSTEM
82 FILETIME creation_time, exit_time, kernel_time, user_time;
90 hash_passphrase (const char *passphrase, int hashalgo,
92 const unsigned char *s2ksalt, unsigned long s2kcount,
93 unsigned char *key, size_t keylen);
98 /* Get the process time and store it in DATA. */
100 calibrate_get_time (struct calibrate_time_s *data)
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);
108 GetProcessTimes (GetCurrentProcess (),
109 &data->creation_time, &data->exit_time,
110 &data->kernel_time, &data->user_time);
116 data->ticks = tmp.tms_utime;
122 calibrate_elapsed_time (struct calibrate_time_s *starttime)
124 struct calibrate_time_s stoptime;
126 calibrate_get_time (&stoptime);
127 #ifdef HAVE_W32_SYSTEM
129 unsigned long long t1, t2;
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);
142 return (unsigned long)((((double) (stoptime.ticks - starttime->ticks))
143 /CLOCKS_PER_SEC)*10000000);
148 /* Run a test hashing for COUNT and return the time required in
151 calibrate_s2k_count_one (unsigned long count)
154 char keybuf[PROT_CIPHER_KEYLEN];
155 struct calibrate_time_s starttime;
157 calibrate_get_time (&starttime);
158 rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1,
159 3, "saltsalt", count, keybuf, sizeof keybuf);
162 return calibrate_elapsed_time (&starttime);
166 /* Measure the time we need to do the hash operations and deduce an
167 S2K count which requires about 100ms of time. */
169 calibrate_s2k_count (void)
174 for (count = 65536; count; count *= 2)
176 ms = calibrate_s2k_count_one (count);
178 log_info ("S2K calibration: %lu -> %lums\n", count, ms);
183 count = (unsigned long)(((double)count / ms) * 100);
191 ms = calibrate_s2k_count_one (count);
192 log_info ("S2K calibration: %lu -> %lums\n", count, ms);
200 /* Return the standard S2K count. */
202 get_standard_s2k_count (void)
204 static unsigned long count;
207 count = calibrate_s2k_count ();
209 /* Enforce a lower limit. */
210 return count < 65536 ? 65536 : count;
214 /* Same as get_standard_s2k_count but return the count in the encoding
215 as described by rfc4880. */
217 get_standard_s2k_count_rfc4880 (void)
219 unsigned long iterations;
221 unsigned char result;
224 iterations = get_standard_s2k_count ();
225 if (iterations >= 65011712)
228 /* Need count to be in the range 16-31 */
229 for (count=iterations>>6; count>=32; count>>=1)
232 result = (c<<4)|(count-16);
234 if (S2K_DECODE_COUNT(result) < iterations)
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. */
247 calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash)
249 const unsigned char *hash_begin, *hash_end;
250 const unsigned char *s;
252 int is_shared_secret;
256 return gpg_error (GPG_ERR_INV_SEXP);
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;
266 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
268 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
270 if (!is_shared_secret)
275 return gpg_error (GPG_ERR_INV_SEXP);
276 s += n; /* Skip the algorithm name. */
284 return gpg_error (GPG_ERR_INV_SEXP);
288 return gpg_error (GPG_ERR_INV_SEXP);
291 return gpg_error (GPG_ERR_INV_SEXP);
295 return gpg_error (GPG_ERR_INV_SEXP);
299 gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash,
300 hash_begin, hash_end - hash_begin);
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.
312 The parameter block is expected to be an incomplete canonical
313 encoded S-Expression of the form (example in advanced format):
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#)
320 the returned block is the S-Expression:
322 (protected mode (parms) encrypted_octet_string)
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)
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. */
343 int saltpos, ivpos, encpos;
345 s2ksalt = iv; /* Silence compiler warning. */
350 modestr = (use_ocb? "openpgp-s2k3-ocb-aes"
351 /* */: "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc");
353 rc = gcry_cipher_open (&hd, PROT_CIPHER,
354 use_ocb? GCRY_CIPHER_MODE_OCB :
355 GCRY_CIPHER_MODE_CBC,
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:
365 * ((<parameter_list>)(4:hash4:sha120:<hashvalue>)) + padding
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:
371 * ((<parameter_list>))
373 blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
377 outlen = 2 + protlen + 2 ;
378 enclen = outlen + 16 /* taglen */;
379 outbuf = gcry_malloc_secure (enclen);
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);
391 /* Allocate a buffer for the nonce and the salt. */
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);
400 rc = gpg_error_from_syserror ();
403 gcry_create_nonce (iv, ivsize);
404 s2ksalt = iv + ivsize - 8;
408 /* Hash the passphrase and set the key. */
412 size_t keylen = PROT_CIPHER_KEYLEN;
414 key = gcry_malloc_secure (keylen);
419 rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
421 s2k_count? s2k_count:get_standard_s2k_count(),
424 rc = gcry_cipher_setkey (hd, key, keylen);
429 /* Set the IV/nonce. */
432 rc = gcry_cipher_setiv (hd, iv, use_ocb? 12 : blklen);
437 /* In OCB Mode we use only the public key parameters as AAD. */
438 rc = gcry_cipher_authenticate (hd, hashbegin, protbegin - hashbegin);
440 rc = gcry_cipher_authenticate (hd, timestamp_exp, timestamp_exp_len);
442 rc = gcry_cipher_authenticate
443 (hd, protbegin+protlen, hashlen - (protbegin+protlen - hashbegin));
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. */
453 rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 );
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);
473 memcpy (p, protbegin, protlen);
482 memcpy (p, ")(4:hash4:sha120:", 17);
484 memcpy (p, hashvalue, 20);
488 memcpy (p, iv+blklen, blklen); /* Add padding. */
491 assert ( p - outbuf == outlen);
494 gcry_cipher_final (hd);
495 rc = gcry_cipher_encrypt (hd, outbuf, outlen, NULL, 0);
498 log_assert (outlen + 16 == enclen);
499 rc = gcry_cipher_gettag (hd, outbuf + outlen, 16);
504 rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0);
508 /* Release cipher handle and check for errors. */
509 gcry_cipher_close (hd);
517 /* Now allocate the buffer we want to return. This is
519 (protected openpgp-s2k3-sha1-aes-cbc
520 ((sha1 salt no_of_iterations) 16byte_iv)
521 encrypted_octet_string)
523 in canoncical format of course. We use asprintf and %n modifier
524 and dummy values as placeholders. */
528 snprintf (countbuf, sizeof countbuf, "%lu",
529 s2k_count ? s2k_count : get_standard_s2k_count ());
531 ("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)",
532 (int)strlen (modestr), modestr,
534 (unsigned int)strlen (countbuf), countbuf,
535 use_ocb? 12 : blklen, &ivpos, use_ocb? 12 : blklen, "",
536 enclen, &encpos, enclen, "");
539 gpg_error_t tmperr = out_of_core ();
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);
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. */
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)
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;
575 char timestamp_exp[35];
576 unsigned char *protected;
583 use_ocb = PROT_DEFAULT_TO_OCB;
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] = ')';
590 /* Parse original key. */
593 return gpg_error (GPG_ERR_INV_SEXP);
598 return gpg_error (GPG_ERR_INV_SEXP);
599 if (!smatch (&s, n, "private-key"))
600 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
602 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
608 return gpg_error (GPG_ERR_INV_SEXP);
610 for (infidx=0; protect_info[infidx].algo
611 && !smatch (&s, n, protect_info[infidx].algo); infidx++)
613 if (!protect_info[infidx].algo)
614 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
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++)
627 if (i == prot_from_idx)
630 return gpg_error (GPG_ERR_INV_SEXP);
635 return gpg_error (GPG_ERR_INV_SEXP);
636 if (n != 1 || c != *s)
638 if (n == 5 && !memcmp (s, "curve", 5)
639 && !i && protect_info[infidx].ecc_hack)
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. */
649 else if (n == 5 && !memcmp (s, "flags", 5)
650 && i == 1 && have_curve)
652 /* "curve" followed by "flags": Change again. */
658 return gpg_error (GPG_ERR_INV_SEXP);
663 return gpg_error (GPG_ERR_INV_SEXP);
664 s +=n; /* skip value */
666 return gpg_error (GPG_ERR_INV_SEXP);
668 if (i == prot_to_idx)
672 if (*s != ')' || !prot_begin || !prot_end )
673 return gpg_error (GPG_ERR_INV_SEXP);
677 /* Skip to the end of the S-expression. */
679 rc = sskip (&s, &depth);
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);
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>). */
697 + (prot_begin-plainkey)
700 + (real_end-prot_end));
701 *result = p = xtrymalloc (*resultlen);
704 gpg_error_t tmperr = out_of_core ();
708 memcpy (p, "(21:protected-", 14);
710 memcpy (p, plainkey+4, prot_begin - plainkey - 4);
711 p += prot_begin - plainkey - 4;
712 memcpy (p, protected, protectedlen);
715 memcpy (p, timestamp_exp, 35);
718 memcpy (p, prot_end+1, real_end - prot_end);
719 p += real_end - prot_end;
720 assert ( p - *result == *resultlen);
728 /* Do the actual decryption and check the return list for consistency. */
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)
742 unsigned char *outbuf;
745 blklen = gcry_cipher_get_algo_blklen (prot_cipher);
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);
756 if (protectedlen < 4 || (protectedlen%blklen))
757 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
760 rc = gcry_cipher_open (&hd, prot_cipher,
761 is_ocb? GCRY_CIPHER_MODE_OCB :
762 GCRY_CIPHER_MODE_CBC,
767 outbuf = gcry_malloc_secure (protectedlen);
771 /* Hash the passphrase and set the key. */
776 key = gcry_malloc_secure (prot_cipher_keylen);
781 rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
782 3, s2ksalt, s2kcount, key, prot_cipher_keylen);
784 rc = gcry_cipher_setkey (hd, key, prot_cipher_keylen);
789 /* Set the IV/nonce. */
792 rc = gcry_cipher_setiv (hd, iv, ivlen);
800 rc = gcry_cipher_authenticate (hd, aad_begin,
801 aadhole_begin - aad_begin);
803 rc = gcry_cipher_authenticate
804 (hd, aadhole_begin + aadhole_len,
805 aad_len - (aadhole_begin+aadhole_len - aad_begin));
809 gcry_cipher_final (hd);
810 rc = gcry_cipher_decrypt (hd, outbuf, protectedlen - 16,
811 protected, protectedlen - 16);
814 rc = gcry_cipher_checktag (hd, protected + protectedlen - 16, 16);
818 rc = gcry_cipher_decrypt (hd, outbuf, protectedlen,
819 protected, protectedlen);
823 /* Release cipher handle and check for errors. */
824 gcry_cipher_close (hd);
831 /* Do a quick check on the data structure. */
832 if (*outbuf != '(' && outbuf[1] != '(')
834 /* Note that in OCB mode this is actually invalid _encrypted_
835 * data and not a bad passphrase. */
837 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
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) )
845 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
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
860 merge_lists (const unsigned char *protectedkey,
862 const unsigned char *cleartext,
863 unsigned char *sha1hash,
864 unsigned char **result, size_t *resultlen,
865 size_t *cutoff, size_t *cutlen)
867 size_t n, newlistlen;
868 unsigned char *newlist, *p;
869 const unsigned char *s;
870 const unsigned char *startpos, *endpos;
879 return gpg_error (GPG_ERR_BUG);
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);
886 return gpg_error (GPG_ERR_BUG);
887 n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL);
889 return gpg_error (GPG_ERR_BUG);
891 newlist = gcry_malloc_secure (newlistlen);
893 return out_of_core ();
895 /* Copy the initial segment */
896 strcpy ((char*)newlist, "(11:private-key");
898 memcpy (p, protectedkey+15+10, replacepos-15-10);
899 p += replacepos-15-10;
901 /* Copy the cleartext. */
903 if (*s != '(' && s[1] != '(')
904 return gpg_error (GPG_ERR_BUG); /*we already checked this */
927 /* Intermezzo: Get the MIC if requested. */
934 if (!smatch (&s, n, "hash"))
937 if (!smatch (&s, n, "sha1"))
942 memcpy (sha1hash, s, 20);
948 /* Append the parameter list. */
949 memcpy (p, startpos, endpos - startpos);
950 p += endpos - startpos;
952 /* Skip over the protected list element in the original list. */
953 s = protectedkey + replacepos;
960 /* Record the position of the optional protected-at expression. */
963 const unsigned char *save_s = s;
966 if (smatch (&s, n, "protected-at"))
972 *cutlen = s - save_s;
977 i = 2; /* we are inside this level */
981 assert (s[-1] == ')');
982 endpos = s; /* one behind the end of the list */
984 /* Append the rest. */
986 *cutoff = p - newlist;
987 memcpy (p, startpos, endpos - startpos);
988 p += endpos - startpos;
993 *resultlen = newlistlen;
997 wipememory (newlist, newlistlen);
1002 wipememory (newlist, newlistlen);
1004 return gpg_error (GPG_ERR_INV_SEXP);
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. */
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)
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;
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 }
1030 const unsigned char *s;
1031 const unsigned char *protect_list;
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;
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;
1045 size_t cutoff, cutlen;
1052 return gpg_error (GPG_ERR_INV_SEXP);
1056 return gpg_error (GPG_ERR_INV_SEXP);
1057 if (!smatch (&s, n, "protected-private-key"))
1058 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1060 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1062 aad_begin = aad_end = s;
1065 rc = sskip (&aad_end, &i);
1073 return gpg_error (GPG_ERR_INV_SEXP);
1075 for (infidx=0; protect_info[infidx].algo
1076 && !smatch (&s, n, protect_info[infidx].algo); infidx++)
1078 if (!protect_info[infidx].algo)
1079 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
1081 /* See wether we have a protected-at timestamp. */
1082 protect_list = s; /* Save for later. */
1091 return gpg_error (GPG_ERR_INV_SEXP);
1092 if (smatch (&s, n, "protected-at"))
1096 return gpg_error (GPG_ERR_INV_SEXP);
1098 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1099 memcpy (protected_at, s, 15);
1100 protected_at[15] = 0;
1105 rc = sskip (&s, &i);
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>)
1121 return gpg_error (GPG_ERR_INV_SEXP);
1126 return gpg_error (GPG_ERR_INV_SEXP);
1127 if (smatch (&s, n, "protected"))
1131 rc = sskip (&s, &i);
1137 aadhole_begin = aadhole_end = prot_begin;
1140 rc = sskip (&aadhole_end, &i);
1146 return gpg_error (GPG_ERR_INV_SEXP);
1148 /* Lookup the protection algo. */
1149 prot_cipher = 0; /* (avoid gcc warning) */
1150 prot_cipher_keylen = 0; /* (avoid gcc warning) */
1152 for (i=0; i < DIM (algotable); i++)
1153 if (smatch (&s, n, algotable[i].name))
1155 prot_cipher = algotable[i].algo;
1156 prot_cipher_keylen = algotable[i].keylen;
1157 is_ocb = algotable[i].is_ocb;
1160 if (i == DIM (algotable))
1161 return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
1163 if (!prot_cipher) /* This is "openpgp-native". */
1165 gcry_sexp_t s_prot_begin;
1167 rc = gcry_sexp_sscan (&s_prot_begin, NULL,
1169 gcry_sexp_canon_len (prot_begin, 0,NULL,NULL));
1173 rc = convert_from_openpgp_native (ctrl, s_prot_begin, passphrase, &final);
1174 gcry_sexp_release (s_prot_begin);
1178 *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
1183 if (*s != '(' || s[1] != '(')
1184 return gpg_error (GPG_ERR_INV_SEXP);
1188 return gpg_error (GPG_ERR_INV_SEXP);
1189 if (!smatch (&s, n, "sha1"))
1190 return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
1193 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
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 */
1203 return gpg_error (GPG_ERR_INV_SEXP);
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);
1215 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1217 s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6);
1218 if (s2kcount < 65536)
1219 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1222 s++; /* skip list end */
1227 if (n != 12) /* Wrong size of the nonce. */
1228 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1232 if (n != 16) /* Wrong blocksize for IV (we support only 128 bit). */
1233 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1238 return gpg_error (GPG_ERR_INV_SEXP);
1242 return gpg_error (GPG_ERR_INV_SEXP);
1244 cleartext = NULL; /* Avoid cc warning. */
1245 rc = do_decryption (aad_begin, aad_end - aad_begin,
1246 aadhole_begin, aadhole_end - aadhole_begin,
1248 passphrase, s2ksalt, s2kcount,
1250 prot_cipher, prot_cipher_keylen, is_ocb,
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);
1268 rc = calculate_mic (final, sha1hash2);
1269 if (!rc && memcmp (sha1hash, sha1hash2, 20))
1270 rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1273 wipememory (final, finallen);
1279 /* Now remove the part which is included in the MIC but should not
1280 go into the final thing. */
1283 memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen);
1288 *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
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
1301 agent_private_key_type (const unsigned char *privatekey)
1303 const unsigned char *s;
1309 return PRIVATE_KEY_UNKNOWN;
1313 return PRIVATE_KEY_UNKNOWN;
1314 if (smatch (&s, n, "protected-private-key"))
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. */
1321 return PRIVATE_KEY_PROTECTED; /* Unknown sexp - assume protected. */
1325 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1326 s += n; /* Skip over the algo */
1328 /* Find the (protected ...) list. */
1332 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1336 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1337 if (smatch (&s, n, "protected"))
1342 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1344 /* Found - Is this openpgp-native? */
1347 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1348 if (smatch (&s, n, "openpgp-native")) /* Yes. */
1351 return PRIVATE_KEY_UNKNOWN; /* Unknown sexp. */
1355 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1356 s += n; /* Skip over "openpgp-private-key". */
1357 /* Find the (protection ...) list. */
1361 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1365 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1366 if (smatch (&s, n, "protection"))
1371 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1373 /* Found - Is the mode "none"? */
1376 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1377 if (smatch (&s, n, "none"))
1378 return PRIVATE_KEY_OPENPGP_NONE; /* Yes. */
1381 return PRIVATE_KEY_PROTECTED;
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;
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.
1397 Returns an error code on failure. */
1399 hash_passphrase (const char *passphrase, int hashalgo,
1401 const unsigned char *s2ksalt,
1402 unsigned long s2kcount,
1403 unsigned char *key, size_t keylen)
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,
1420 s2k_hash_passphrase (const char *passphrase, int hashalgo,
1422 const unsigned char *s2ksalt,
1423 unsigned int s2kcount,
1424 unsigned char *key, size_t keylen)
1426 return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt,
1427 S2K_DECODE_COUNT (s2kcount),
1434 /* Create an canonical encoded S-expression with the shadow info from
1435 a card's SERIALNO and the IDSTRING. */
1437 make_shadow_info (const char *serialno, const char *idstring)
1444 for (s=serialno, n=0; *s && s[1]; s += 2)
1447 info = p = xtrymalloc (1 + sizeof numbuf + n
1448 + sizeof numbuf + strlen (idstring) + 1 + 1);
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);
1459 return (unsigned char *)info;
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
1470 agent_shadow_key (const unsigned char *pubkey,
1471 const unsigned char *shadow_info,
1472 unsigned char **result)
1474 const unsigned char *s;
1475 const unsigned char *point;
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);
1482 if (!pubkey_len || !shadow_info_len)
1483 return gpg_error (GPG_ERR_INV_VALUE);
1486 return gpg_error (GPG_ERR_INV_SEXP);
1491 return gpg_error (GPG_ERR_INV_SEXP);
1492 if (!smatch (&s, n, "public-key"))
1493 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1495 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1500 return gpg_error (GPG_ERR_INV_SEXP);
1501 s += n; /* skip over the algorithm name */
1506 return gpg_error (GPG_ERR_INV_SEXP);
1511 return gpg_error (GPG_ERR_INV_SEXP);
1515 return gpg_error (GPG_ERR_INV_SEXP);
1516 s +=n; /* skip value */
1518 return gpg_error (GPG_ERR_INV_SEXP);
1522 point = s; /* insert right before the point */
1525 assert (depth == 1);
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);
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;
1542 memcpy (p, point, pubkey_len - (point - pubkey));
1543 p += pubkey_len - (point - pubkey);
1548 /* Parse a canonical encoded shadowed key and return a pointer to the
1549 inner list with the shadow_info */
1551 agent_get_shadow_info (const unsigned char *shadowkey,
1552 unsigned char const **shadow_info)
1554 const unsigned char *s;
1560 return gpg_error (GPG_ERR_INV_SEXP);
1565 return gpg_error (GPG_ERR_INV_SEXP);
1566 if (!smatch (&s, n, "shadowed-private-key"))
1567 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1569 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1574 return gpg_error (GPG_ERR_INV_SEXP);
1575 s += n; /* skip over the algorithm name */
1580 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1582 return gpg_error (GPG_ERR_INV_SEXP);
1587 return gpg_error (GPG_ERR_INV_SEXP);
1588 if (smatch (&s, n, "shadowed"))
1593 return gpg_error (GPG_ERR_INV_SEXP);
1594 s +=n; /* skip value */
1596 return gpg_error (GPG_ERR_INV_SEXP);
1600 /* Found the shadowed list, S points to the protocol */
1603 return gpg_error (GPG_ERR_INV_SEXP);
1604 if (smatch (&s, n, "t1-v1"))
1607 return gpg_error (GPG_ERR_INV_SEXP);
1611 return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
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. */
1623 parse_shadow_info (const unsigned char *shadow_info,
1624 char **r_hexsn, char **r_idstr, int *r_pinlen)
1626 const unsigned char *s;
1638 return gpg_error (GPG_ERR_INV_SEXP);
1642 return gpg_error (GPG_ERR_INV_SEXP);
1646 *r_hexsn = bin2hex (s, n, NULL);
1648 return gpg_error_from_syserror ();
1660 return gpg_error (GPG_ERR_INV_SEXP);
1665 *r_idstr = xtrymalloc (n+1);
1673 return gpg_error_from_syserror ();
1675 memcpy (*r_idstr, s, n);
1679 /* Parse the optional PINLEN. */
1686 char *tmpstr = xtrymalloc (n+1);
1699 return gpg_error_from_syserror ();
1701 memcpy (tmpstr, s, n);
1704 *r_pinlen = (int)strtol (tmpstr, NULL, 10);