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 <http://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"
44 /* The protection mode for encryption. The supported modes for
45 decryption are listed in agent_unprotect(). */
46 #define PROT_CIPHER GCRY_CIPHER_AES128
47 #define PROT_CIPHER_STRING "aes"
48 #define PROT_CIPHER_KEYLEN (128/8)
50 /* Decode an rfc4880 encoded S2K count. */
51 #define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6))
54 /* A table containing the information needed to create a protected
59 int prot_from, prot_to;
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 },
72 /* A helper object for time measurement. */
73 struct calibrate_time_s
75 #ifdef HAVE_W32_SYSTEM
76 FILETIME creation_time, exit_time, kernel_time, user_time;
84 hash_passphrase (const char *passphrase, int hashalgo,
86 const unsigned char *s2ksalt, unsigned long s2kcount,
87 unsigned char *key, size_t keylen);
91 /* Get the process time and store it in DATA. */
93 calibrate_get_time (struct calibrate_time_s *data)
95 #ifdef HAVE_W32_SYSTEM
96 # ifdef HAVE_W32CE_SYSTEM
97 GetThreadTimes (GetCurrentThread (),
99 GetProcessTimes (GetCurrentProcess (),
101 &data->creation_time, &data->exit_time,
102 &data->kernel_time, &data->user_time);
107 data->ticks = tmp.tms_utime;
113 calibrate_elapsed_time (struct calibrate_time_s *starttime)
115 struct calibrate_time_s stoptime;
117 calibrate_get_time (&stoptime);
118 #ifdef HAVE_W32_SYSTEM
120 unsigned long long t1, t2;
122 t1 = (((unsigned long long)starttime->kernel_time.dwHighDateTime << 32)
123 + starttime->kernel_time.dwLowDateTime);
124 t1 += (((unsigned long long)starttime->user_time.dwHighDateTime << 32)
125 + starttime->user_time.dwLowDateTime);
126 t2 = (((unsigned long long)stoptime.kernel_time.dwHighDateTime << 32)
127 + stoptime.kernel_time.dwLowDateTime);
128 t2 += (((unsigned long long)stoptime.user_time.dwHighDateTime << 32)
129 + stoptime.user_time.dwLowDateTime);
130 return (unsigned long)((t2 - t1)/10000);
133 return (unsigned long)((((double) (stoptime.ticks - starttime->ticks))
134 /CLOCKS_PER_SEC)*10000000);
139 /* Run a test hashing for COUNT and return the time required in
142 calibrate_s2k_count_one (unsigned long count)
145 char keybuf[PROT_CIPHER_KEYLEN];
146 struct calibrate_time_s starttime;
148 calibrate_get_time (&starttime);
149 rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1,
150 3, "saltsalt", count, keybuf, sizeof keybuf);
153 return calibrate_elapsed_time (&starttime);
157 /* Measure the time we need to do the hash operations and deduce an
158 S2K count which requires about 100ms of time. */
160 calibrate_s2k_count (void)
165 for (count = 65536; count; count *= 2)
167 ms = calibrate_s2k_count_one (count);
169 log_info ("S2K calibration: %lu -> %lums\n", count, ms);
174 count = (unsigned long)(((double)count / ms) * 100);
182 ms = calibrate_s2k_count_one (count);
183 log_info ("S2K calibration: %lu -> %lums\n", count, ms);
191 /* Return the standard S2K count. */
193 get_standard_s2k_count (void)
195 static unsigned long count;
198 count = calibrate_s2k_count ();
200 /* Enforce a lower limit. */
201 return count < 65536 ? 65536 : count;
205 /* Same as get_standard_s2k_count but return the count in the encoding
206 as described by rfc4880. */
208 get_standard_s2k_count_rfc4880 (void)
210 unsigned long iterations;
212 unsigned char result;
215 iterations = get_standard_s2k_count ();
216 if (iterations >= 65011712)
219 /* Need count to be in the range 16-31 */
220 for (count=iterations>>6; count>=32; count>>=1)
223 result = (c<<4)|(count-16);
225 if (S2K_DECODE_COUNT(result) < iterations)
234 /* Calculate the MIC for a private key or shared secret S-expression.
235 SHA1HASH should point to a 20 byte buffer. This function is
236 suitable for all algorithms. */
238 calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash)
240 const unsigned char *hash_begin, *hash_end;
241 const unsigned char *s;
243 int is_shared_secret;
247 return gpg_error (GPG_ERR_INV_SEXP);
251 return gpg_error (GPG_ERR_INV_SEXP);
252 if (smatch (&s, n, "private-key"))
253 is_shared_secret = 0;
254 else if (smatch (&s, n, "shared-secret"))
255 is_shared_secret = 1;
257 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
259 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
261 if (!is_shared_secret)
266 return gpg_error (GPG_ERR_INV_SEXP);
267 s += n; /* Skip the algorithm name. */
275 return gpg_error (GPG_ERR_INV_SEXP);
279 return gpg_error (GPG_ERR_INV_SEXP);
282 return gpg_error (GPG_ERR_INV_SEXP);
286 return gpg_error (GPG_ERR_INV_SEXP);
290 gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash,
291 hash_begin, hash_end - hash_begin);
298 /* Encrypt the parameter block starting at PROTBEGIN with length
299 PROTLEN using the utf8 encoded key PASSPHRASE and return the entire
300 encrypted block in RESULT or return with an error code. SHA1HASH
301 is the 20 byte SHA-1 hash required for the integrity code.
303 The parameter block is expected to be an incomplete S-Expression of
304 the form (example in advanced format):
306 (d #046129F..[some bytes not shown]..81#)
307 (p #00e861b..[some bytes not shown]..f1#)
308 (q #00f7a7c..[some bytes not shown]..61#)
309 (u #304559a..[some bytes not shown]..9b#)
311 the returned block is the S-Expression:
313 (protected mode (parms) encrypted_octet_string)
317 do_encryption (const unsigned char *protbegin, size_t protlen,
318 const char *passphrase, const unsigned char *sha1hash,
319 unsigned char **result, size_t *resultlen,
320 unsigned long s2k_count)
323 const char *modestr = "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc";
324 int blklen, enclen, outlen;
325 unsigned char *iv = NULL;
329 int saltpos, ivpos, encpos;
334 rc = gcry_cipher_open (&hd, PROT_CIPHER, GCRY_CIPHER_MODE_CBC,
340 /* We need to work on a copy of the data because this makes it
341 easier to add the trailer and the padding and more important we
342 have to prefix the text with 2 parenthesis, so we have to
343 allocate enough space for:
345 ((<parameter_list>)(4:hash4:sha120:<hashvalue>)) + padding
347 We always append a full block of random bytes as padding but
348 encrypt only what is needed for a full blocksize. */
349 blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
350 outlen = 2 + protlen + 2 + 6 + 6 + 23 + 2 + blklen;
351 enclen = outlen/blklen * blklen;
352 outbuf = gcry_malloc_secure (outlen);
357 /* Allocate random bytes to be used as IV, padding and s2k salt. */
358 iv = xtrymalloc (blklen*2+8);
360 rc = gpg_error (GPG_ERR_ENOMEM);
363 gcry_create_nonce (iv, blklen*2+8);
364 rc = gcry_cipher_setiv (hd, iv, blklen);
370 size_t keylen = PROT_CIPHER_KEYLEN;
372 key = gcry_malloc_secure (keylen);
377 rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
379 s2k_count ? s2k_count : get_standard_s2k_count(),
382 rc = gcry_cipher_setkey (hd, key, keylen);
391 memcpy (p, protbegin, protlen);
393 memcpy (p, ")(4:hash4:sha120:", 17);
395 memcpy (p, sha1hash, 20);
399 memcpy (p, iv+blklen, blklen);
401 assert ( p - outbuf == outlen);
402 rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0);
404 gcry_cipher_close (hd);
412 /* Now allocate the buffer we want to return. This is
414 (protected openpgp-s2k3-sha1-aes-cbc
415 ((sha1 salt no_of_iterations) 16byte_iv)
416 encrypted_octet_string)
418 in canoncical format of course. We use asprintf and %n modifier
419 and dummy values as placeholders. */
423 snprintf (countbuf, sizeof countbuf, "%lu",
424 s2k_count ? s2k_count : get_standard_s2k_count ());
426 ("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)",
427 (int)strlen (modestr), modestr,
429 (unsigned int)strlen (countbuf), countbuf,
430 blklen, &ivpos, blklen, "",
431 enclen, &encpos, enclen, "");
434 gpg_error_t tmperr = out_of_core ();
440 *resultlen = strlen (p);
441 *result = (unsigned char*)p;
442 memcpy (p+saltpos, iv+2*blklen, 8);
443 memcpy (p+ivpos, iv, blklen);
444 memcpy (p+encpos, outbuf, enclen);
452 /* Protect the key encoded in canonical format in PLAINKEY. We assume
453 a valid S-Exp here. */
455 agent_protect (const unsigned char *plainkey, const char *passphrase,
456 unsigned char **result, size_t *resultlen,
457 unsigned long s2k_count)
460 const char *parmlist;
461 int prot_from_idx, prot_to_idx;
462 const unsigned char *s;
463 const unsigned char *hash_begin, *hash_end;
464 const unsigned char *prot_begin, *prot_end, *real_end;
467 unsigned char hashvalue[20];
468 char timestamp_exp[35];
469 unsigned char *protected;
476 /* Create an S-expression with the protected-at timestamp. */
477 memcpy (timestamp_exp, "(12:protected-at15:", 19);
478 gnupg_get_isotime (timestamp_exp+19);
479 timestamp_exp[19+15] = ')';
481 /* Parse original key. */
484 return gpg_error (GPG_ERR_INV_SEXP);
489 return gpg_error (GPG_ERR_INV_SEXP);
490 if (!smatch (&s, n, "private-key"))
491 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
493 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
499 return gpg_error (GPG_ERR_INV_SEXP);
501 for (infidx=0; protect_info[infidx].algo
502 && !smatch (&s, n, protect_info[infidx].algo); infidx++)
504 if (!protect_info[infidx].algo)
505 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
507 /* The parser below is a complete mess: To make it robust for ECC
508 use we should reorder the s-expression to include only what we
509 really need and thus guarantee the right order for saving stuff.
510 This should be done before calling this function and maybe with
511 the help of the new gcry_sexp_extract_param. */
512 parmlist = protect_info[infidx].parmlist;
513 prot_from_idx = protect_info[infidx].prot_from;
514 prot_to_idx = protect_info[infidx].prot_to;
515 prot_begin = prot_end = NULL;
516 for (i=0; (c=parmlist[i]); i++)
518 if (i == prot_from_idx)
521 return gpg_error (GPG_ERR_INV_SEXP);
526 return gpg_error (GPG_ERR_INV_SEXP);
527 if (n != 1 || c != *s)
529 if (n == 5 && !memcmp (s, "curve", 5)
530 && !i && protect_info[infidx].ecc_hack)
532 /* This is a private ECC key but the first parameter is
533 the name of the curve. We change the parameter list
534 here to the one we expect in this case. */
540 else if (n == 5 && !memcmp (s, "flags", 5)
541 && i == 1 && have_curve)
543 /* "curve" followed by "flags": Change again. */
549 return gpg_error (GPG_ERR_INV_SEXP);
554 return gpg_error (GPG_ERR_INV_SEXP);
555 s +=n; /* skip value */
557 return gpg_error (GPG_ERR_INV_SEXP);
559 if (i == prot_to_idx)
563 if (*s != ')' || !prot_begin || !prot_end )
564 return gpg_error (GPG_ERR_INV_SEXP);
568 /* Skip to the end of the S-expression. */
570 rc = sskip (&s, &depth);
576 /* Hash the stuff. Because the timestamp_exp won't get protected,
577 we can't simply hash a continuous buffer but need to use several
579 rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 );
582 gcry_md_write (md, hash_begin, hash_end - hash_begin);
583 gcry_md_write (md, timestamp_exp, 35);
584 gcry_md_write (md, ")", 1);
585 memcpy (hashvalue, gcry_md_read (md, GCRY_MD_SHA1), 20);
588 rc = do_encryption (prot_begin, prot_end - prot_begin + 1,
589 passphrase, hashvalue,
590 &protected, &protectedlen, s2k_count);
594 /* Now create the protected version of the key. Note that the 10
595 extra bytes are for for the inserted "protected-" string (the
596 beginning of the plaintext reads: "((11:private-key(" ). The 35
597 term is the space for (12:protected-at15:<timestamp>). */
599 + (prot_begin-plainkey)
602 + (real_end-prot_end));
603 *result = p = xtrymalloc (*resultlen);
606 gpg_error_t tmperr = out_of_core ();
610 memcpy (p, "(21:protected-", 14);
612 memcpy (p, plainkey+4, prot_begin - plainkey - 4);
613 p += prot_begin - plainkey - 4;
614 memcpy (p, protected, protectedlen);
617 memcpy (p, timestamp_exp, 35);
620 memcpy (p, prot_end+1, real_end - prot_end);
621 p += real_end - prot_end;
622 assert ( p - *result == *resultlen);
630 /* Do the actual decryption and check the return list for consistency. */
632 do_decryption (const unsigned char *protected, size_t protectedlen,
633 const char *passphrase,
634 const unsigned char *s2ksalt, unsigned long s2kcount,
635 const unsigned char *iv, size_t ivlen,
636 int prot_cipher, int prot_cipher_keylen,
637 unsigned char **result)
642 unsigned char *outbuf;
645 blklen = gcry_cipher_get_algo_blklen (prot_cipher);
646 if (protectedlen < 4 || (protectedlen%blklen))
647 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
649 rc = gcry_cipher_open (&hd, prot_cipher, GCRY_CIPHER_MODE_CBC,
654 outbuf = gcry_malloc_secure (protectedlen);
658 rc = gcry_cipher_setiv (hd, iv, ivlen);
663 key = gcry_malloc_secure (prot_cipher_keylen);
668 rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
669 3, s2ksalt, s2kcount, key, prot_cipher_keylen);
671 rc = gcry_cipher_setkey (hd, key, prot_cipher_keylen);
676 rc = gcry_cipher_decrypt (hd, outbuf, protectedlen,
677 protected, protectedlen);
678 gcry_cipher_close (hd);
684 /* Do a quick check first. */
685 if (*outbuf != '(' && outbuf[1] != '(')
688 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
690 /* Check that we have a consistent S-Exp. */
691 reallen = gcry_sexp_canon_len (outbuf, protectedlen, NULL, NULL);
692 if (!reallen || (reallen + blklen < protectedlen) )
695 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
702 /* Merge the parameter list contained in CLEARTEXT with the original
703 protect lists PROTECTEDKEY by replacing the list at REPLACEPOS.
704 Return the new list in RESULT and the MIC value in the 20 byte
705 buffer SHA1HASH. CUTOFF and CUTLEN will receive the offset and the
706 length of the resulting list which should go into the MIC
707 calculation but then be removed. */
709 merge_lists (const unsigned char *protectedkey,
711 const unsigned char *cleartext,
712 unsigned char *sha1hash,
713 unsigned char **result, size_t *resultlen,
714 size_t *cutoff, size_t *cutlen)
716 size_t n, newlistlen;
717 unsigned char *newlist, *p;
718 const unsigned char *s;
719 const unsigned char *startpos, *endpos;
728 return gpg_error (GPG_ERR_BUG);
730 /* Estimate the required size of the resulting list. We have a large
731 safety margin of >20 bytes (MIC hash from CLEARTEXT and the
732 removed "protected-" */
733 newlistlen = gcry_sexp_canon_len (protectedkey, 0, NULL, NULL);
735 return gpg_error (GPG_ERR_BUG);
736 n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL);
738 return gpg_error (GPG_ERR_BUG);
740 newlist = gcry_malloc_secure (newlistlen);
742 return out_of_core ();
744 /* Copy the initial segment */
745 strcpy ((char*)newlist, "(11:private-key");
747 memcpy (p, protectedkey+15+10, replacepos-15-10);
748 p += replacepos-15-10;
750 /* copy the cleartext */
752 if (*s != '(' && s[1] != '(')
753 return gpg_error (GPG_ERR_BUG); /*we already checked this */
775 /* Intermezzo: Get the MIC */
780 if (!smatch (&s, n, "hash"))
783 if (!smatch (&s, n, "sha1"))
788 memcpy (sha1hash, s, 20);
794 /* append the parameter list */
795 memcpy (p, startpos, endpos - startpos);
796 p += endpos - startpos;
798 /* Skip over the protected list element in the original list. */
799 s = protectedkey + replacepos;
806 /* Record the position of the optional protected-at expression. */
809 const unsigned char *save_s = s;
812 if (smatch (&s, n, "protected-at"))
818 *cutlen = s - save_s;
823 i = 2; /* we are inside this level */
827 assert (s[-1] == ')');
828 endpos = s; /* one behind the end of the list */
830 /* Append the rest. */
832 *cutoff = p - newlist;
833 memcpy (p, startpos, endpos - startpos);
834 p += endpos - startpos;
839 *resultlen = newlistlen;
843 wipememory (newlist, newlistlen);
848 wipememory (newlist, newlistlen);
850 return gpg_error (GPG_ERR_INV_SEXP);
855 /* Unprotect the key encoded in canonical format. We assume a valid
856 S-Exp here. If a protected-at item is available, its value will
857 be stored at protected_at unless this is NULL. */
859 agent_unprotect (ctrl_t ctrl,
860 const unsigned char *protectedkey, const char *passphrase,
861 gnupg_isotime_t protected_at,
862 unsigned char **result, size_t *resultlen)
865 const char *name; /* Name of the protection method. */
866 int algo; /* (A zero indicates the "openpgp-native" hack.) */
867 int keylen; /* Used key length in bytes. */
869 { "openpgp-s2k3-sha1-aes-cbc", GCRY_CIPHER_AES128, (128/8)},
870 { "openpgp-s2k3-sha1-aes256-cbc", GCRY_CIPHER_AES256, (256/8)},
871 { "openpgp-native", 0, 0 }
874 const unsigned char *s;
875 const unsigned char *protect_list;
878 unsigned char sha1hash[20], sha1hash2[20];
879 const unsigned char *s2ksalt;
880 unsigned long s2kcount;
881 const unsigned char *iv;
882 int prot_cipher, prot_cipher_keylen;
883 const unsigned char *prot_begin;
884 unsigned char *cleartext;
885 unsigned char *final;
887 size_t cutoff, cutlen;
894 return gpg_error (GPG_ERR_INV_SEXP);
898 return gpg_error (GPG_ERR_INV_SEXP);
899 if (!smatch (&s, n, "protected-private-key"))
900 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
902 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
906 return gpg_error (GPG_ERR_INV_SEXP);
908 for (infidx=0; protect_info[infidx].algo
909 && !smatch (&s, n, protect_info[infidx].algo); infidx++)
911 if (!protect_info[infidx].algo)
912 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
915 /* See wether we have a protected-at timestamp. */
916 protect_list = s; /* Save for later. */
925 return gpg_error (GPG_ERR_INV_SEXP);
926 if (smatch (&s, n, "protected-at"))
930 return gpg_error (GPG_ERR_INV_SEXP);
932 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
933 memcpy (protected_at, s, 15);
934 protected_at[15] = 0;
945 /* Now find the list with the protected information. Here is an
946 example for such a list:
947 (protected openpgp-s2k3-sha1-aes-cbc
948 ((sha1 <salt> <count>) <Initialization_Vector>)
955 return gpg_error (GPG_ERR_INV_SEXP);
960 return gpg_error (GPG_ERR_INV_SEXP);
961 if (smatch (&s, n, "protected"))
972 return gpg_error (GPG_ERR_INV_SEXP);
974 /* Lookup the protection algo. */
975 prot_cipher = 0; /* (avoid gcc warning) */
976 prot_cipher_keylen = 0; /* (avoid gcc warning) */
977 for (i= 0; i < DIM (algotable); i++)
978 if (smatch (&s, n, algotable[i].name))
980 prot_cipher = algotable[i].algo;
981 prot_cipher_keylen = algotable[i].keylen;
984 if (i == DIM (algotable))
985 return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
987 if (!prot_cipher) /* This is "openpgp-native". */
989 gcry_sexp_t s_prot_begin;
991 rc = gcry_sexp_sscan (&s_prot_begin, NULL,
993 gcry_sexp_canon_len (prot_begin, 0,NULL,NULL));
997 rc = convert_from_openpgp_native (ctrl, s_prot_begin, passphrase, &final);
998 gcry_sexp_release (s_prot_begin);
1002 *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
1007 if (*s != '(' || s[1] != '(')
1008 return gpg_error (GPG_ERR_INV_SEXP);
1012 return gpg_error (GPG_ERR_INV_SEXP);
1013 if (!smatch (&s, n, "sha1"))
1014 return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
1017 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1022 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1023 /* We expect a list close as next, so we can simply use strtoul()
1024 here. We might want to check that we only have digits - but this
1025 is nothing we should worry about */
1027 return gpg_error (GPG_ERR_INV_SEXP);
1029 /* Old versions of gpg-agent used the funny floating point number in
1030 a byte encoding as specified by OpenPGP. However this is not
1031 needed and thus we now store it as a plain unsigned integer. We
1032 can easily distinguish the old format by looking at its value:
1033 Less than 256 is an old-style encoded number; other values are
1034 plain integers. In any case we check that they are at least
1035 65536 because we never used a lower value in the past and we
1036 should have a lower limit. */
1037 s2kcount = strtoul ((const char*)s, NULL, 10);
1039 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1041 s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6);
1042 if (s2kcount < 65536)
1043 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1046 s++; /* skip list end */
1049 if (n != 16) /* Wrong blocksize for IV (we support only 128 bit). */
1050 return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1054 return gpg_error (GPG_ERR_INV_SEXP);
1058 return gpg_error (GPG_ERR_INV_SEXP);
1060 cleartext = NULL; /* Avoid cc warning. */
1061 rc = do_decryption (s, n,
1062 passphrase, s2ksalt, s2kcount,
1063 iv, 16, prot_cipher, prot_cipher_keylen,
1068 rc = merge_lists (protectedkey, prot_begin-protectedkey, cleartext,
1069 sha1hash, &final, &finallen, &cutoff, &cutlen);
1070 /* Albeit cleartext has been allocated in secure memory and thus
1071 xfree will wipe it out, we do an extra wipe just in case
1072 somethings goes badly wrong. */
1073 wipememory (cleartext, n);
1078 rc = calculate_mic (final, sha1hash2);
1079 if (!rc && memcmp (sha1hash, sha1hash2, 20))
1080 rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
1083 wipememory (final, finallen);
1087 /* Now remove the part which is included in the MIC but should not
1088 go into the final thing. */
1091 memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen);
1096 *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
1100 /* Check the type of the private key, this is one of the constants:
1101 PRIVATE_KEY_UNKNOWN if we can't figure out the type (this is the
1102 value 0), PRIVATE_KEY_CLEAR for an unprotected private key.
1103 PRIVATE_KEY_PROTECTED for an protected private key or
1104 PRIVATE_KEY_SHADOWED for a sub key where the secret parts are
1105 stored elsewhere. Finally PRIVATE_KEY_OPENPGP_NONE may be returned
1106 is the key is still in the openpgp-native format but without
1109 agent_private_key_type (const unsigned char *privatekey)
1111 const unsigned char *s;
1117 return PRIVATE_KEY_UNKNOWN;
1121 return PRIVATE_KEY_UNKNOWN;
1122 if (smatch (&s, n, "protected-private-key"))
1124 /* We need to check whether this is openpgp-native protected
1125 with the protection method "none". In that case we return a
1126 different key type so that the caller knows that there is no
1127 need to ask for a passphrase. */
1129 return PRIVATE_KEY_PROTECTED; /* Unknown sexp - assume protected. */
1133 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1134 s += n; /* Skip over the algo */
1136 /* Find the (protected ...) list. */
1140 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1144 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1145 if (smatch (&s, n, "protected"))
1150 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1152 /* Found - Is this openpgp-native? */
1155 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1156 if (smatch (&s, n, "openpgp-native")) /* Yes. */
1159 return PRIVATE_KEY_UNKNOWN; /* Unknown sexp. */
1163 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1164 s += n; /* Skip over "openpgp-private-key". */
1165 /* Find the (protection ...) list. */
1169 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1173 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1174 if (smatch (&s, n, "protection"))
1179 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1181 /* Found - Is the mode "none"? */
1184 return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
1185 log_debug ("openpgp-native protection '%.*s'\n", (int)n, s);
1186 if (smatch (&s, n, "none"))
1187 return PRIVATE_KEY_OPENPGP_NONE; /* Yes. */
1190 return PRIVATE_KEY_PROTECTED;
1192 if (smatch (&s, n, "shadowed-private-key"))
1193 return PRIVATE_KEY_SHADOWED;
1194 if (smatch (&s, n, "private-key"))
1195 return PRIVATE_KEY_CLEAR;
1196 return PRIVATE_KEY_UNKNOWN;
1201 /* Transform a passphrase into a suitable key of length KEYLEN and
1202 store this key in the caller provided buffer KEY. The caller must
1203 provide an HASHALGO, a valid S2KMODE (see rfc-2440) and depending on
1204 that mode an S2KSALT of 8 random bytes and an S2KCOUNT.
1206 Returns an error code on failure. */
1208 hash_passphrase (const char *passphrase, int hashalgo,
1210 const unsigned char *s2ksalt,
1211 unsigned long s2kcount,
1212 unsigned char *key, size_t keylen)
1214 /* The key derive function does not support a zero length string for
1215 the passphrase in the S2K modes. Return a better suited error
1216 code than GPG_ERR_INV_DATA. */
1217 if (!passphrase || !*passphrase)
1218 return gpg_error (GPG_ERR_NO_PASSPHRASE);
1219 return gcry_kdf_derive (passphrase, strlen (passphrase),
1220 s2kmode == 3? GCRY_KDF_ITERSALTED_S2K :
1221 s2kmode == 1? GCRY_KDF_SALTED_S2K :
1222 s2kmode == 0? GCRY_KDF_SIMPLE_S2K : GCRY_KDF_NONE,
1223 hashalgo, s2ksalt, 8, s2kcount,
1229 s2k_hash_passphrase (const char *passphrase, int hashalgo,
1231 const unsigned char *s2ksalt,
1232 unsigned int s2kcount,
1233 unsigned char *key, size_t keylen)
1235 return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt,
1236 S2K_DECODE_COUNT (s2kcount),
1243 /* Create an canonical encoded S-expression with the shadow info from
1244 a card's SERIALNO and the IDSTRING. */
1246 make_shadow_info (const char *serialno, const char *idstring)
1253 for (s=serialno, n=0; *s && s[1]; s += 2)
1256 info = p = xtrymalloc (1 + sizeof numbuf + n
1257 + sizeof numbuf + strlen (idstring) + 1 + 1);
1261 p = stpcpy (p, smklen (numbuf, sizeof numbuf, n, NULL));
1262 for (s=serialno; *s && s[1]; s += 2)
1263 *(unsigned char *)p++ = xtoi_2 (s);
1264 p = stpcpy (p, smklen (numbuf, sizeof numbuf, strlen (idstring), NULL));
1265 p = stpcpy (p, idstring);
1268 return (unsigned char *)info;
1273 /* Create a shadow key from a public key. We use the shadow protocol
1274 "ti-v1" and insert the S-expressionn SHADOW_INFO. The resulting
1275 S-expression is returned in an allocated buffer RESULT will point
1276 to. The input parameters are expected to be valid canonicalized
1279 agent_shadow_key (const unsigned char *pubkey,
1280 const unsigned char *shadow_info,
1281 unsigned char **result)
1283 const unsigned char *s;
1284 const unsigned char *point;
1288 size_t pubkey_len = gcry_sexp_canon_len (pubkey, 0, NULL,NULL);
1289 size_t shadow_info_len = gcry_sexp_canon_len (shadow_info, 0, NULL,NULL);
1291 if (!pubkey_len || !shadow_info_len)
1292 return gpg_error (GPG_ERR_INV_VALUE);
1295 return gpg_error (GPG_ERR_INV_SEXP);
1300 return gpg_error (GPG_ERR_INV_SEXP);
1301 if (!smatch (&s, n, "public-key"))
1302 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1304 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1309 return gpg_error (GPG_ERR_INV_SEXP);
1310 s += n; /* skip over the algorithm name */
1315 return gpg_error (GPG_ERR_INV_SEXP);
1320 return gpg_error (GPG_ERR_INV_SEXP);
1324 return gpg_error (GPG_ERR_INV_SEXP);
1325 s +=n; /* skip value */
1327 return gpg_error (GPG_ERR_INV_SEXP);
1331 point = s; /* insert right before the point */
1334 assert (depth == 1);
1336 /* Calculate required length by taking in account: the "shadowed-"
1337 prefix, the "shadowed", "t1-v1" as well as some parenthesis */
1338 n = 12 + pubkey_len + 1 + 3+8 + 2+5 + shadow_info_len + 1;
1339 *result = xtrymalloc (n);
1342 return out_of_core ();
1343 p = stpcpy (p, "(20:shadowed-private-key");
1344 /* (10:public-key ...)*/
1345 memcpy (p, pubkey+14, point - (pubkey+14));
1346 p += point - (pubkey+14);
1347 p = stpcpy (p, "(8:shadowed5:t1-v1");
1348 memcpy (p, shadow_info, shadow_info_len);
1349 p += shadow_info_len;
1351 memcpy (p, point, pubkey_len - (point - pubkey));
1352 p += pubkey_len - (point - pubkey);
1357 /* Parse a canonical encoded shadowed key and return a pointer to the
1358 inner list with the shadow_info */
1360 agent_get_shadow_info (const unsigned char *shadowkey,
1361 unsigned char const **shadow_info)
1363 const unsigned char *s;
1369 return gpg_error (GPG_ERR_INV_SEXP);
1374 return gpg_error (GPG_ERR_INV_SEXP);
1375 if (!smatch (&s, n, "shadowed-private-key"))
1376 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1378 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1383 return gpg_error (GPG_ERR_INV_SEXP);
1384 s += n; /* skip over the algorithm name */
1389 return gpg_error (GPG_ERR_UNKNOWN_SEXP);
1391 return gpg_error (GPG_ERR_INV_SEXP);
1396 return gpg_error (GPG_ERR_INV_SEXP);
1397 if (smatch (&s, n, "shadowed"))
1402 return gpg_error (GPG_ERR_INV_SEXP);
1403 s +=n; /* skip value */
1405 return gpg_error (GPG_ERR_INV_SEXP);
1409 /* Found the shadowed list, S points to the protocol */
1412 return gpg_error (GPG_ERR_INV_SEXP);
1413 if (smatch (&s, n, "t1-v1"))
1416 return gpg_error (GPG_ERR_INV_SEXP);
1420 return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
1425 /* Parse the canonical encoded SHADOW_INFO S-expression. On success
1426 the hex encoded serial number is returned as a malloced strings at
1427 R_HEXSN and the Id string as a malloced string at R_IDSTR. On
1428 error an error code is returned and NULL is stored at the result
1429 parameters addresses. If the serial number or the ID string is not
1430 required, NULL may be passed for them. */
1432 parse_shadow_info (const unsigned char *shadow_info,
1433 char **r_hexsn, char **r_idstr, int *r_pinlen)
1435 const unsigned char *s;
1447 return gpg_error (GPG_ERR_INV_SEXP);
1451 return gpg_error (GPG_ERR_INV_SEXP);
1455 *r_hexsn = bin2hex (s, n, NULL);
1457 return gpg_error_from_syserror ();
1469 return gpg_error (GPG_ERR_INV_SEXP);
1474 *r_idstr = xtrymalloc (n+1);
1482 return gpg_error_from_syserror ();
1484 memcpy (*r_idstr, s, n);
1488 /* Parse the optional PINLEN. */
1495 char *tmpstr = xtrymalloc (n+1);
1508 return gpg_error_from_syserror ();
1510 memcpy (tmpstr, s, n);
1513 *r_pinlen = (int)strtol (tmpstr, NULL, 10);