1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3 * 2009, 2013, 2014, 2015 Free Software Foundation, Inc.
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/>.
23 CHV means Card Holder Verification and is nothing else than a PIN
24 or password. That term seems to have been used originally with GSM
25 cards. Version v2 of the specs changes the term to the clearer
26 term PW for password. We use the terms here interchangeable
27 because we do not want to change existing strings i18n wise.
29 Version 2 of the specs also drops the separate PW2 which was
30 required in v1 due to ISO requirements. It is now possible to have
31 one physical PW but two reference to it so that they can be
32 individually be verified (e.g. to implement a forced verification
33 for one key). Thus you will noticed the use of PW2 with the verify
34 command but not with change_reference_data because the latter
35 operates directly on the physical PW.
37 The Reset Code (RC) as implemented by v2 cards uses the same error
38 counter as the PW2 of v1 cards. By default no RC is set and thus
39 that error counter is set to 0. After setting the RC the error
40 counter will be initialized to 3.
53 #if GNUPG_MAJOR_VERSION == 1
54 /* This is used with GnuPG version < 1.9. The code has been source
55 copied from the current GnuPG >= 1.9 and is maintained over
61 #else /* GNUPG_MAJOR_VERSION != 1 */
63 #endif /* GNUPG_MAJOR_VERSION != 1 */
68 #include "app-common.h"
71 #include "openpgpdefs.h"
74 /* A table describing the DOs of the card. */
78 int get_from; /* Constructed DO with this DO or 0 for direct access. */
82 int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
83 this data object if it is used in 1.1
84 and later versions of the card. This
85 does not work with composite DO and
86 is currently only useful for the CHV
88 int try_extlen:1; /* Large object; try to use an extended
92 { 0x005E, 0, 0, 1, 0, 0, 0, 0, "Login Data" },
93 { 0x5F50, 0, 0, 0, 0, 0, 0, 0, "URL" },
94 { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
95 { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
96 { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
97 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
98 { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
99 { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
100 { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
101 { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
102 { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
103 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
104 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
105 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
106 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
107 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
108 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
109 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
110 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
111 { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
112 { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
113 { 0x0101, 0, 0, 0, 0, 0, 0, 0, "Private DO 1"},
114 { 0x0102, 0, 0, 0, 0, 0, 0, 0, "Private DO 2"},
115 { 0x0103, 0, 0, 0, 0, 0, 0, 0, "Private DO 3"},
116 { 0x0104, 0, 0, 0, 0, 0, 0, 0, "Private DO 4"},
117 { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
119 { 0x7F74, 0, 0, 1, 0, 0, 0, 0, "General Feature Management"},
120 { 0x00D5, 0, 0, 1, 0, 0, 0, 0, "AES key data"},
134 /* The format of RSA private keys. */
146 /* One cache item for DOs. */
148 struct cache_s *next;
151 unsigned char data[1];
155 /* Object with application (i.e. OpenPGP card) specific data. */
157 /* A linked list with cached DOs. */
158 struct cache_s *cache;
160 /* Keep track of the public keys. */
163 int read_done; /* True if we have at least tried to read them. */
164 unsigned char *key; /* This is a malloced buffer with a canonical
165 encoded S-expression encoding a public
166 key. Might be NULL if key is not
168 size_t keylen; /* The length of the above S-expression. This
169 is usually only required for cross checks
170 because the length of an S-expression is
171 implicitly available. */
174 unsigned char status_indicator; /* The card status indicator. */
176 unsigned int manufacturer:16; /* Manufacturer ID from the s/n. */
178 /* Keep track of the ISO card capabilities. */
181 unsigned int cmd_chaining:1; /* Command chaining is supported. */
182 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
185 /* Keep track of extended card capabilities. */
188 unsigned int is_v2:1; /* This is a v2.0 compatible card. */
189 unsigned int sm_supported:1; /* Secure Messaging is supported. */
190 unsigned int get_challenge:1;
191 unsigned int key_import:1;
192 unsigned int change_force_chv:1;
193 unsigned int private_dos:1;
194 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
195 unsigned int has_decrypt:1; /* Support symmetric decryption. */
196 unsigned int has_button:1;
197 unsigned int sm_algo:2; /* Symmetric crypto algo for SM. */
198 unsigned int max_certlen_3:16;
199 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
200 unsigned int max_cmd_data:16; /* Maximum data size for a command. */
201 unsigned int max_rsp_data:16; /* Maximum size of a response. */
204 /* Flags used to control the application. */
207 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
208 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
211 /* Pinpad request specified on card. */
214 unsigned int specified:1;
224 unsigned int n_bits; /* Size of the modulus in bits. The rest
225 of this strucuire is only valid if
227 unsigned int e_bits; /* Size of the public exponent in bits. */
228 rsa_key_format_t format;
238 #define ECC_FLAG_DJB_TWEAK (1 << 0)
241 /***** Local prototypes *****/
242 static unsigned long convert_sig_counter_value (const unsigned char *value,
244 static unsigned long get_sig_counter (app_t app);
245 static gpg_error_t do_auth (app_t app, const char *keyidstr,
246 gpg_error_t (*pincb)(void*, const char *, char **),
248 const void *indata, size_t indatalen,
249 unsigned char **outdata, size_t *outdatalen);
250 static void parse_algorithm_attribute (app_t app, int keyno);
251 static gpg_error_t change_keyattr_from_string
253 gpg_error_t (*pincb)(void*, const char *, char **),
255 const void *value, size_t valuelen);
263 do_deinit (app_t app)
265 if (app && app->app_local)
267 struct cache_s *c, *c2;
270 for (c = app->app_local->cache; c; c = c2)
276 for (i=0; i < DIM (app->app_local->pk); i++)
278 xfree (app->app_local->pk[i].key);
279 app->app_local->pk[i].read_done = 0;
281 xfree (app->app_local);
282 app->app_local = NULL;
287 /* Wrapper around iso7816_get_data which first tries to get the data
288 from the cache. With GET_IMMEDIATE passed as true, the cache is
289 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
290 supported by the card. */
292 get_cached_data (app_t app, int tag,
293 unsigned char **result, size_t *resultlen,
294 int get_immediate, int try_extlen)
308 for (c=app->app_local->cache; c; c = c->next)
313 p = xtrymalloc (c->length);
315 return gpg_error (gpg_err_code_from_errno (errno));
316 memcpy (p, c->data, c->length);
320 *resultlen = c->length;
326 if (try_extlen && app->app_local->cardcap.ext_lc_le)
327 exmode = app->app_local->extcap.max_rsp_data;
331 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
337 /* Check whether we should cache this object. */
341 for (i=0; data_objects[i].tag; i++)
342 if (data_objects[i].tag == tag)
344 if (data_objects[i].dont_cache)
349 /* Okay, cache it. */
350 for (c=app->app_local->cache; c; c = c->next)
351 assert (c->tag != tag);
353 c = xtrymalloc (sizeof *c + len);
356 memcpy (c->data, p, len);
359 c->next = app->app_local->cache;
360 app->app_local->cache = c;
366 /* Remove DO at TAG from the cache. */
368 flush_cache_item (app_t app, int tag)
370 struct cache_s *c, *cprev;
376 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
380 cprev->next = c->next;
382 app->app_local->cache = c->next;
385 for (c=app->app_local->cache; c ; c = c->next)
387 assert (c->tag != tag); /* Oops: duplicated entry. */
392 /* Try again if we have an outer tag. */
393 for (i=0; data_objects[i].tag; i++)
394 if (data_objects[i].tag == tag && data_objects[i].get_from
395 && data_objects[i].get_from != tag)
396 flush_cache_item (app, data_objects[i].get_from);
399 /* Flush all entries from the cache which might be out of sync after
402 flush_cache_after_error (app_t app)
406 for (i=0; data_objects[i].tag; i++)
407 if (data_objects[i].flush_on_error)
408 flush_cache_item (app, data_objects[i].tag);
412 /* Flush the entire cache. */
414 flush_cache (app_t app)
416 if (app && app->app_local)
418 struct cache_s *c, *c2;
420 for (c = app->app_local->cache; c; c = c2)
425 app->app_local->cache = NULL;
430 /* Get the DO identified by TAG from the card in SLOT and return a
431 buffer with its content in RESULT and NBYTES. The return value is
432 NULL if not found or a pointer which must be used to release the
433 buffer holding value. */
435 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
439 unsigned char *buffer;
441 unsigned char *value;
452 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
455 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
457 if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
458 exmode = app->app_local->extcap.max_rsp_data;
461 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
474 if (data_objects[i].tag && data_objects[i].get_from)
476 rc = get_cached_data (app, data_objects[i].get_from,
478 (data_objects[i].dont_cache
479 || data_objects[i].get_immediate_in_v11),
480 data_objects[i].try_extlen);
483 const unsigned char *s;
485 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
487 value = NULL; /* not found */
488 else if (valuelen > buflen - (s - buffer))
490 log_error ("warning: constructed DO too short\n");
492 xfree (buffer); buffer = NULL;
495 value = buffer + (s - buffer);
499 if (!value) /* Not in a constructed DO, try simple. */
501 rc = get_cached_data (app, tag, &buffer, &buflen,
502 (data_objects[i].dont_cache
503 || data_objects[i].get_immediate_in_v11),
504 data_objects[i].try_extlen);
524 dump_all_do (int slot)
527 unsigned char *buffer;
530 for (i=0; data_objects[i].tag; i++)
532 if (data_objects[i].get_from)
535 /* We don't try extended length APDU because such large DO would
536 be pretty useless in a log file. */
537 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
538 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
541 log_info ("DO '%s' not available: %s\n",
542 data_objects[i].desc, gpg_strerror (rc));
545 if (data_objects[i].binary)
547 log_info ("DO '%s': ", data_objects[i].desc);
548 log_printhex ("", buffer, buflen);
551 log_info ("DO '%s': '%.*s'\n",
552 data_objects[i].desc,
553 (int)buflen, buffer); /* FIXME: sanitize */
555 if (data_objects[i].constructed)
557 for (j=0; data_objects[j].tag; j++)
559 const unsigned char *value;
562 if (j==i || data_objects[i].tag != data_objects[j].get_from)
564 value = find_tlv_unchecked (buffer, buflen,
565 data_objects[j].tag, &valuelen);
568 else if (valuelen > buflen - (value - buffer))
569 log_error ("warning: constructed DO too short\n");
572 if (data_objects[j].binary)
574 log_info ("DO '%s': ", data_objects[j].desc);
576 log_info ("[%u]\n", (unsigned int)valuelen);
578 log_printhex ("", value, valuelen);
581 log_info ("DO '%s': '%.*s'\n",
582 data_objects[j].desc,
583 (int)valuelen, value); /* FIXME: sanitize */
588 xfree (buffer); buffer = NULL;
593 /* Count the number of bits, assuming the A represents an unsigned big
594 integer of length LEN bytes. */
596 count_bits (const unsigned char *a, size_t len)
598 unsigned int n = len * 8;
601 for (; len && !*a; len--, a++, n -=8)
605 for (i=7; i && !(*a & (1<<i)); i--)
611 /* GnuPG makes special use of the login-data DO, this function parses
612 the login data to store the flags for later use. It may be called
613 at any time and should be called after changing the login-data DO.
615 Everything up to a LF is considered a mailbox or account name. If
616 the first LF is followed by DC4 (0x14) control sequence are
617 expected up to the next LF. Control sequences are separated by FS
618 (0x18) and consist of key=value pairs. There are two keys defined:
622 Where FLAGS is a plain hexadecimal number representing flag values.
623 The lsb is here the rightmost bit. Defined flags bits are:
625 Bit 0 = CHV1 and CHV2 are not syncronized
626 Bit 1 = CHV2 has been been set to the default PIN of "123456"
627 (this implies that bit 0 is also set).
631 Where PINPAD_REQUEST is in the format of: <n> or <n>,<m>.
632 N for user PIN, M for admin PIN. If M is missing it means M=N.
633 0 means to force not to use pinpad.
637 parse_login_data (app_t app)
639 unsigned char *buffer, *p;
644 app->app_local->flags.no_sync = 0;
645 app->app_local->flags.def_chv2 = 0;
646 app->app_local->pinpad.specified = 0;
647 app->app_local->pinpad.fixedlen_user = -1;
648 app->app_local->pinpad.fixedlen_admin = -1;
651 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
654 for (; buflen; buflen--, buffer++)
657 if (buflen < 2 || buffer[1] != '\x14')
660 return; /* No control sequences. */
669 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
671 /* Flags control sequence found. */
674 /* For now we are only interested in the last digit, so skip
675 any leading digits but bail out on invalid characters. */
676 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
677 lastdig = xtoi_1 (p);
680 if (len && !(*p == '\n' || *p == '\x18'))
681 goto next; /* Invalid characters in field. */
682 app->app_local->flags.no_sync = !!(lastdig & 1);
683 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
685 else if (buflen > 1 && *buffer == 'P' && buffer[1] == '=')
687 /* Pinpad request control sequence found. */
698 n = strtol (buffer, &q, 10);
699 if (q >= (char *)buffer + buflen
700 || *q == '\x18' || *q == '\n')
704 if (*q++ != ',' || !digitp (q))
706 m = strtol (q, &q, 10);
709 if (buflen < ((unsigned char *)q - buffer))
712 buflen -= ((unsigned char *)q - buffer);
715 if (buflen && !(*buffer == '\n' || *buffer == '\x18'))
717 app->app_local->pinpad.specified = 1;
718 app->app_local->pinpad.fixedlen_user = n;
719 app->app_local->pinpad.fixedlen_admin = m;
724 /* Skip to FS (0x18) or LF (\n). */
725 for (; buflen && *buffer != '\x18' && *buffer != '\n'; buflen--)
728 while (buflen && *buffer != '\n');
734 #define MAX_ARGS_STORE_FPR 3
736 /* Note, that FPR must be at least 20 bytes. */
738 store_fpr (app_t app, int keynumber, u32 timestamp, unsigned char *fpr,
741 unsigned int n, nbits;
742 unsigned char *buffer, *p;
745 const unsigned char *m[MAX_ARGS_STORE_FPR];
746 size_t mlen[MAX_ARGS_STORE_FPR];
751 n = 6; /* key packet version, 4-byte timestamps, and algorithm */
752 if (algo == PUBKEY_ALGO_ECDH)
758 for (i = 0; i < argc; i++)
760 m[i] = va_arg (ap, const unsigned char *);
761 mlen[i] = va_arg (ap, size_t);
762 if (algo == PUBKEY_ALGO_RSA || i == 1)
768 p = buffer = xtrymalloc (3 + n);
770 return gpg_error_from_syserror ();
772 *p++ = 0x99; /* ctb */
773 *p++ = n >> 8; /* 2 byte length header */
775 *p++ = 4; /* key packet version */
776 *p++ = timestamp >> 24;
777 *p++ = timestamp >> 16;
778 *p++ = timestamp >> 8;
782 for (i = 0; i < argc; i++)
784 if (algo == PUBKEY_ALGO_RSA || i == 1)
786 nbits = count_bits (m[i], mlen[i]);
790 memcpy (p, m[i], mlen[i]);
794 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
798 tag = (app->card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
799 flush_cache_item (app, 0xC5);
800 tag2 = 0xCE + keynumber;
801 flush_cache_item (app, 0xCD);
803 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
805 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
807 if (!rc && app->card_version > 0x0100)
809 unsigned char buf[4];
811 buf[0] = timestamp >> 24;
812 buf[1] = timestamp >> 16;
813 buf[2] = timestamp >> 8;
816 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
818 log_error (_("failed to store the creation date: %s\n"),
827 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
828 int number, const unsigned char *fpr)
834 for (i=0; i < 20 && !fpr[i]; i++)
837 return; /* All zero. */
838 bin2hex (fpr, 20, buf);
840 *numbuf = 0; /* Don't print the key number */
842 sprintf (numbuf, "%d", number);
843 send_status_info (ctrl, keyword,
844 numbuf, (size_t)strlen(numbuf),
845 buf, (size_t)strlen (buf), NULL, 0);
849 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
850 int number, const unsigned char *stamp)
852 char numbuf1[50], numbuf2[50];
855 value = buf32_to_ulong (stamp);
858 sprintf (numbuf1, "%d", number);
859 sprintf (numbuf2, "%lu", value);
860 send_status_info (ctrl, keyword,
861 numbuf1, (size_t)strlen(numbuf1),
862 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
866 send_key_data (ctrl_t ctrl, const char *name,
867 const unsigned char *a, size_t alen)
872 buffer = buf = bin2hex (a, alen, NULL);
875 log_error ("memory allocation error in send_key_data\n");
878 buflen = strlen (buffer);
880 /* 768 is the hexified size for the modulus of an 3072 bit key. We
881 use extra chunks to transmit larger data (i.e for 4096 bit). */
882 for ( ;buflen > 768; buflen -= 768, buf += 768)
883 send_status_info (ctrl, "KEY-DATA",
887 send_status_info (ctrl, "KEY-DATA",
888 name, (size_t)strlen(name),
896 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int keyno)
900 assert (keyno >=0 && keyno < DIM(app->app_local->keyattr));
902 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
903 snprintf (buffer, sizeof buffer, "%d 1 rsa%u %u %d",
905 app->app_local->keyattr[keyno].rsa.n_bits,
906 app->app_local->keyattr[keyno].rsa.e_bits,
907 app->app_local->keyattr[keyno].rsa.format);
908 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
910 snprintf (buffer, sizeof buffer, "%d %d %s",
912 keyno==1? PUBKEY_ALGO_ECDH :
913 app->app_local->keyattr[keyno].ecc.flags?
914 PUBKEY_ALGO_EDDSA : PUBKEY_ALGO_ECDSA,
915 openpgp_oid_to_curve (app->app_local->keyattr[keyno].ecc.oid, 0));
918 snprintf (buffer, sizeof buffer, "%d 0 0 UNKNOWN", keyno+1);
920 send_status_direct (ctrl, keyword, buffer);
924 /* Implement the GETATTR command. This is similar to the LEARN
925 command but returns just one value via the status interface. */
927 do_getattr (app_t app, ctrl_t ctrl, const char *name)
934 { "DISP-NAME", 0x005B },
935 { "LOGIN-DATA", 0x005E },
936 { "DISP-LANG", 0x5F2D },
937 { "DISP-SEX", 0x5F35 },
938 { "PUBKEY-URL", 0x5F50 },
939 { "KEY-FPR", 0x00C5, 3 },
940 { "KEY-TIME", 0x00CD, 4 },
941 { "KEY-ATTR", 0x0000, -5 },
942 { "CA-FPR", 0x00C6, 3 },
943 { "CHV-STATUS", 0x00C4, 1 },
944 { "SIG-COUNTER", 0x0093, 2 },
945 { "SERIALNO", 0x004F, -1 },
947 { "EXTCAP", 0x0000, -2 },
948 { "PRIVATE-DO-1", 0x0101 },
949 { "PRIVATE-DO-2", 0x0102 },
950 { "PRIVATE-DO-3", 0x0103 },
951 { "PRIVATE-DO-4", 0x0104 },
952 { "$AUTHKEYID", 0x0000, -3 },
953 { "$DISPSERIALNO",0x0000, -4 },
958 unsigned char *value;
961 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
963 if (!table[idx].name)
964 return gpg_error (GPG_ERR_INV_NAME);
966 if (table[idx].special == -1)
968 /* The serial number is very special. We could have used the
969 AID DO to retrieve it, but we have it already in the app
970 context and the stamp argument is required anyway which we
971 can't by other means. The AID DO is available anyway but not
977 if (!app_get_serial_and_stamp (app, &serial, &stamp))
979 sprintf (tmp, "%lu", (unsigned long)stamp);
980 send_status_info (ctrl, "SERIALNO",
981 serial, strlen (serial),
988 if (table[idx].special == -2)
992 snprintf (tmp, sizeof tmp,
993 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d "
994 "sm=%d si=%u dec=%d bt=%d",
995 app->app_local->extcap.get_challenge,
996 app->app_local->extcap.key_import,
997 app->app_local->extcap.change_force_chv,
998 app->app_local->extcap.private_dos,
999 app->app_local->extcap.max_certlen_3,
1000 app->app_local->extcap.algo_attr_change,
1001 (app->app_local->extcap.sm_supported
1002 ? (app->app_local->extcap.sm_algo == 0? CIPHER_ALGO_3DES :
1003 (app->app_local->extcap.sm_algo == 1?
1004 CIPHER_ALGO_AES : CIPHER_ALGO_AES256))
1006 app->app_local->status_indicator,
1007 app->app_local->extcap.has_decrypt,
1008 app->app_local->extcap.has_button);
1009 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1012 if (table[idx].special == -3)
1014 char const tmp[] = "OPENPGP.3";
1015 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1018 if (table[idx].special == -4)
1023 if (!app_get_serial_and_stamp (app, &serial, &stamp))
1025 if (strlen (serial) > 16+12)
1027 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
1033 return gpg_error (GPG_ERR_INV_NAME);
1035 if (table[idx].special == -5)
1037 for (i=0; i < 3; i++)
1038 send_key_attr (ctrl, app, table[idx].name, i);
1042 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
1045 if (table[idx].special == 1)
1049 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
1050 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
1051 send_status_info (ctrl, table[idx].name,
1052 numbuf, strlen (numbuf), NULL, 0);
1054 else if (table[idx].special == 2)
1058 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
1059 send_status_info (ctrl, table[idx].name,
1060 numbuf, strlen (numbuf), NULL, 0);
1062 else if (table[idx].special == 3)
1065 for (i=0; i < 3; i++)
1066 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
1068 else if (table[idx].special == 4)
1071 for (i=0; i < 3; i++)
1072 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
1075 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
1082 /* Retrieve the fingerprint from the card inserted in SLOT and write
1083 the according hex representation to FPR. Caller must have provide
1084 a buffer at FPR of least 41 bytes. Returns 0 on success or an
1086 #if GNUPG_MAJOR_VERSION > 1
1088 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
1090 gpg_error_t err = 0;
1092 unsigned char *value;
1095 assert (keyno >=0 && keyno <= 2);
1097 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
1098 if (relptr && valuelen >= 60)
1099 bin2hex (value+keyno*20, 20, fpr);
1101 err = gpg_error (GPG_ERR_NOT_FOUND);
1105 #endif /*GNUPG_MAJOR_VERSION > 1*/
1108 /* Retrieve the public key material for the RSA key, whose fingerprint
1109 is FPR, from gpg output, which can be read through the stream FP.
1110 The RSA modulus will be stored at the address of M and MLEN, the
1111 public exponent at E and ELEN. Returns zero on success, an error
1112 code on failure. Caller must release the allocated buffers at M
1113 and E if the function returns success. */
1114 #if GNUPG_MAJOR_VERSION > 1
1116 retrieve_key_material (FILE *fp, const char *hexkeyid,
1117 const unsigned char **m, size_t *mlen,
1118 const unsigned char **e, size_t *elen)
1120 gcry_error_t err = 0;
1121 char *line = NULL; /* read_line() buffer. */
1122 size_t line_size = 0; /* Helper for for read_line. */
1123 int found_key = 0; /* Helper to find a matching key. */
1124 unsigned char *m_new = NULL;
1125 unsigned char *e_new = NULL;
1129 /* Loop over all records until we have found the subkey
1130 corresponding to the fingerprint. Inm general the first record
1131 should be the pub record, but we don't rely on that. Given that
1132 we only need to look at one key, it is sufficient to compare the
1133 keyid so that we don't need to look at "fpr" records. */
1137 char *fields[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
1144 i = read_line (fp, &line, &line_size, &max_length);
1149 err = gpg_error_from_syserror ();
1150 goto leave; /* Error. */
1154 err = gpg_error (GPG_ERR_TRUNCATED);
1155 goto leave; /* Line truncated - we better stop processing. */
1158 /* Parse the line into fields. */
1159 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1161 fields[nfields] = p;
1162 p = strchr (p, ':');
1167 continue; /* No fields at all - skip line. */
1171 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1172 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1177 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1178 break; /* Next key - stop. */
1180 if ( strcmp (fields[0], "pkd") )
1181 continue; /* Not a key data record. */
1182 i = 0; /* Avoid erroneous compiler warning. */
1183 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1184 || (!i && m_new) || (i && e_new))
1186 err = gpg_error (GPG_ERR_GENERAL);
1187 goto leave; /* Error: Invalid key data record or not an RSA key. */
1190 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1194 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1196 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1197 gcry_mpi_release (mpi);
1212 err = gpg_error (GPG_ERR_GENERAL);
1220 #endif /*GNUPG_MAJOR_VERSION > 1*/
1223 /* Get the public key for KEYNO and store it as an S-expresion with
1224 the APP handle. On error that field gets cleared. If we already
1225 know about the public key we will just return. Note that this does
1226 not mean a key is available; this is soley indicated by the
1227 presence of the app->app_local->pk[KEYNO-1].key field.
1229 Note that GnuPG 1.x does not need this and it would be too time
1230 consuming to send it just for the fun of it. However, given that we
1231 use the same code in gpg 1.4, we can't use the gcry S-expresion
1232 here but need to open encode it. */
1233 #if GNUPG_MAJOR_VERSION > 1
1235 get_public_key (app_t app, int keyno)
1237 gpg_error_t err = 0;
1238 unsigned char *buffer;
1239 const unsigned char *keydata, *m, *e;
1240 size_t buflen, keydatalen;
1243 unsigned char *mbuf = NULL;
1244 unsigned char *ebuf = NULL;
1245 char *keybuf = NULL;
1249 if (keyno < 1 || keyno > 3)
1250 return gpg_error (GPG_ERR_INV_ID);
1253 /* Already cached? */
1254 if (app->app_local->pk[keyno].read_done)
1257 xfree (app->app_local->pk[keyno].key);
1258 app->app_local->pk[keyno].key = NULL;
1259 app->app_local->pk[keyno].keylen = 0;
1261 m = e = NULL; /* (avoid cc warning) */
1263 if (app->card_version > 0x0100)
1265 int exmode, le_value;
1267 /* We may simply read the public key out of these cards. */
1268 if (app->app_local->cardcap.ext_lc_le)
1270 exmode = 1; /* Use extended length. */
1271 le_value = app->app_local->extcap.max_rsp_data;
1276 le_value = 256; /* Use legacy value. */
1279 err = iso7816_read_public_key
1281 (const unsigned char*)(keyno == 0? "\xB6" :
1282 keyno == 1? "\xB8" : "\xA4"), 2,
1287 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1291 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1294 err = gpg_error (GPG_ERR_CARD);
1295 log_error (_("response does not contain the public key data\n"));
1299 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1301 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1304 err = gpg_error (GPG_ERR_CARD);
1305 log_error (_("response does not contain the RSA modulus\n"));
1309 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1312 err = gpg_error (GPG_ERR_CARD);
1313 log_error (_("response does not contain the RSA public exponent\n"));
1319 m = find_tlv (keydata, keydatalen, 0x0086, &mlen);
1322 err = gpg_error (GPG_ERR_CARD);
1323 log_error (_("response does not contain the EC public point\n"));
1330 /* Due to a design problem in v1.0 cards we can't get the public
1331 key out of these cards without doing a verify on CHV3.
1332 Clearly that is not an option and thus we try to locate the
1333 key using an external helper.
1335 The helper we use here is gpg itself, which should know about
1336 the key in any case. */
1340 char *command = NULL;
1344 buffer = NULL; /* We don't need buffer. */
1346 err = retrieve_fpr_from_card (app, keyno, fpr);
1349 log_error ("error while retrieving fpr from card: %s\n",
1350 gpg_strerror (err));
1353 hexkeyid = fpr + 24;
1355 ret = gpgrt_asprintf
1356 (&command, "gpg --list-keys --with-colons --with-key-data '%s'", fpr);
1359 err = gpg_error_from_syserror ();
1363 fp = popen (command, "r");
1367 err = gpg_error_from_syserror ();
1368 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1372 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1376 log_error ("error while retrieving key material through pipe: %s\n",
1377 gpg_strerror (err));
1382 mbuf = xtrymalloc (mlen + 1);
1385 err = gpg_error_from_syserror ();
1389 if ((app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA
1390 || (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC
1391 && !app->app_local->keyattr[keyno].ecc.flags))
1392 && mlen && (*m & 0x80))
1393 { /* Prepend numbers with a 0 if needed for MPI. */
1395 memcpy (mbuf+1, m, mlen);
1398 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC
1399 && app->app_local->keyattr[keyno].ecc.flags)
1400 { /* Prepend 0x40 prefix. */
1402 memcpy (mbuf+1, m, mlen);
1406 memcpy (mbuf, m, mlen);
1408 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1410 ebuf = xtrymalloc (elen + 1);
1413 err = gpg_error_from_syserror ();
1416 /* Prepend numbers with a 0 if needed. */
1417 if (elen && (*e & 0x80))
1420 memcpy (ebuf+1, e, elen);
1424 memcpy (ebuf, e, elen);
1426 err = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%b)(e%b)))",
1427 (int)mlen, mbuf, (int)elen, ebuf);
1429 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
1433 if (!app->app_local->keyattr[keyno].ecc.flags)
1434 format = "(public-key(ecc(curve%s)(q%b)))";
1435 else if (keyno == 1)
1436 format = "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))";
1438 format = "(public-key(ecc(curve%s)(flags eddsa)(q%b)))";
1440 err = gcry_sexp_build (&s_pkey, NULL, format,
1441 openpgp_oid_to_curve (app->app_local->keyattr[keyno].ecc.oid, 1),
1445 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1450 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1452 keybuf = xtrymalloc (len);
1455 gcry_sexp_release (s_pkey);
1456 err = gpg_error_from_syserror ();
1459 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1460 gcry_sexp_release (s_pkey);
1462 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1463 app->app_local->pk[keyno].keylen = len - 1; /* Decrement for trailing '\0' */
1466 /* Set a flag to indicate that we tried to read the key. */
1467 app->app_local->pk[keyno].read_done = 1;
1474 #endif /* GNUPG_MAJOR_VERSION > 1 */
1478 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1479 This is used by the LEARN command. */
1481 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1483 gpg_error_t err = 0;
1484 /* Note that GnuPG 1.x does not need this and it would be too time
1485 consuming to send it just for the fun of it. */
1486 #if GNUPG_MAJOR_VERSION > 1
1487 unsigned char grip[20];
1491 err = get_public_key (app, keyno);
1495 assert (keyno >= 1 && keyno <= 3);
1496 if (!app->app_local->pk[keyno-1].key)
1497 goto leave; /* No such key - ignore. */
1499 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1500 app->app_local->pk[keyno-1].keylen,
1505 bin2hex (grip, 20, gripstr);
1507 sprintf (idbuf, "OPENPGP.%d", keyno);
1508 send_status_info (ctrl, "KEYPAIRINFO",
1510 idbuf, strlen (idbuf),
1514 #endif /* GNUPG_MAJOR_VERSION > 1 */
1520 /* Handle the LEARN command for OpenPGP. */
1522 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1526 do_getattr (app, ctrl, "EXTCAP");
1527 do_getattr (app, ctrl, "DISP-NAME");
1528 do_getattr (app, ctrl, "DISP-LANG");
1529 do_getattr (app, ctrl, "DISP-SEX");
1530 do_getattr (app, ctrl, "PUBKEY-URL");
1531 do_getattr (app, ctrl, "LOGIN-DATA");
1532 do_getattr (app, ctrl, "KEY-FPR");
1533 if (app->card_version > 0x0100)
1534 do_getattr (app, ctrl, "KEY-TIME");
1535 do_getattr (app, ctrl, "CA-FPR");
1536 do_getattr (app, ctrl, "CHV-STATUS");
1537 do_getattr (app, ctrl, "SIG-COUNTER");
1538 if (app->app_local->extcap.private_dos)
1540 do_getattr (app, ctrl, "PRIVATE-DO-1");
1541 do_getattr (app, ctrl, "PRIVATE-DO-2");
1543 do_getattr (app, ctrl, "PRIVATE-DO-3");
1545 do_getattr (app, ctrl, "PRIVATE-DO-4");
1547 send_keypair_info (app, ctrl, 1);
1548 send_keypair_info (app, ctrl, 2);
1549 send_keypair_info (app, ctrl, 3);
1550 /* Note: We do not send the Cardholder Certificate, because that is
1551 relativly long and for OpenPGP applications not really needed. */
1556 /* Handle the READKEY command for OpenPGP. On success a canonical
1557 encoded S-expression with the public key will get stored at PK and
1558 its length (for assertions) at PKLEN; the caller must release that
1559 buffer. On error PK and PKLEN are not changed and an error code is
1562 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1564 #if GNUPG_MAJOR_VERSION > 1
1569 if (!strcmp (keyid, "OPENPGP.1"))
1571 else if (!strcmp (keyid, "OPENPGP.2"))
1573 else if (!strcmp (keyid, "OPENPGP.3"))
1576 return gpg_error (GPG_ERR_INV_ID);
1578 err = get_public_key (app, keyno);
1582 buf = app->app_local->pk[keyno-1].key;
1584 return gpg_error (GPG_ERR_NO_PUBKEY);
1585 *pklen = app->app_local->pk[keyno-1].keylen;;
1586 *pk = xtrymalloc (*pklen);
1589 err = gpg_error_from_syserror ();
1593 memcpy (*pk, buf, *pklen);
1596 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1600 /* Read the standard certificate of an OpenPGP v2 card. It is
1601 returned in a freshly allocated buffer with that address stored at
1602 CERT and the length of the certificate stored at CERTLEN. CERTID
1603 needs to be set to "OPENPGP.3". */
1605 do_readcert (app_t app, const char *certid,
1606 unsigned char **cert, size_t *certlen)
1608 #if GNUPG_MAJOR_VERSION > 1
1610 unsigned char *buffer;
1616 if (strcmp (certid, "OPENPGP.3"))
1617 return gpg_error (GPG_ERR_INV_ID);
1618 if (!app->app_local->extcap.is_v2)
1619 return gpg_error (GPG_ERR_NOT_FOUND);
1621 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1623 return gpg_error (GPG_ERR_NOT_FOUND);
1626 err = gpg_error (GPG_ERR_NOT_FOUND);
1627 else if (!(*cert = xtrymalloc (buflen)))
1628 err = gpg_error_from_syserror ();
1631 memcpy (*cert, buffer, buflen);
1638 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1643 /* Decide if we use the pinpad of the reader for PIN input according
1644 to the user preference on the card, and the capability of the
1645 reader. This routine is only called when the reader has pinpad.
1646 Returns 0 if we use pinpad, 1 otherwise. */
1648 check_pinpad_request (app_t app, pininfo_t *pininfo, int admin_pin)
1650 if (app->app_local->pinpad.specified == 0) /* No preference on card. */
1652 if (pininfo->fixedlen == 0) /* Reader has varlen capability. */
1653 return 0; /* Then, use pinpad. */
1656 * Reader has limited capability, and it may not match PIN of
1663 pininfo->fixedlen = app->app_local->pinpad.fixedlen_admin;
1665 pininfo->fixedlen = app->app_local->pinpad.fixedlen_user;
1667 if (pininfo->fixedlen == 0 /* User requests disable pinpad. */
1668 || pininfo->fixedlen < pininfo->minlen
1669 || pininfo->fixedlen > pininfo->maxlen
1670 /* Reader doesn't have the capability to input a PIN which
1671 * length is FIXEDLEN. */)
1678 /* Verify a CHV either using using the pinentry or if possibile by
1679 using a pinpad. PINCB and PINCB_ARG describe the usual callback
1680 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1681 used with CHV1. PINVALUE is the address of a pointer which will
1682 receive a newly allocated block with the actual PIN (this is useful
1683 in case that PIN shall be used for another verify operation). The
1684 caller needs to free this value. If the function returns with
1685 success and NULL is stored at PINVALUE, the caller should take this
1686 as an indication that the pinpad has been used.
1689 verify_a_chv (app_t app,
1690 gpg_error_t (*pincb)(void*, const char *, char **),
1692 int chvno, unsigned long sigcount, char **pinvalue)
1695 char *prompt_buffer = NULL;
1700 assert (chvno == 1 || chvno == 2);
1704 if (chvno == 2 && app->app_local->flags.def_chv2)
1706 /* Special case for def_chv2 mechanism. */
1708 log_info (_("using default PIN as %s\n"), "CHV2");
1709 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1712 /* Verification of CHV2 with the default PIN failed,
1713 although the card pretends to have the default PIN set as
1714 CHV2. We better disable the def_chv2 flag now. */
1715 log_info (_("failed to use default PIN as %s: %s"
1716 " - disabling further default use\n"),
1717 "CHV2", gpg_strerror (rc));
1718 app->app_local->flags.def_chv2 = 0;
1723 memset (&pininfo, 0, sizeof pininfo);
1724 pininfo.fixedlen = -1;
1725 pininfo.minlen = minlen;
1730 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1731 size_t promptsize = strlen (PROMPTSTRING) + 50;
1733 prompt_buffer = xtrymalloc (promptsize);
1735 return gpg_error_from_syserror ();
1736 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1737 prompt = prompt_buffer;
1741 prompt = _("||Please enter the PIN");
1744 if (!opt.disable_pinpad
1745 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
1746 && !check_pinpad_request (app, &pininfo, 0))
1748 /* The reader supports the verify command through the pinpad.
1749 Note that the pincb appends a text to the prompt telling the
1750 user to use the pinpad. */
1751 rc = pincb (pincb_arg, prompt, NULL);
1753 xfree (prompt_buffer);
1754 prompt_buffer = NULL;
1757 log_info (_("PIN callback returned error: %s\n"),
1761 rc = iso7816_verify_kp (app->slot, 0x80+chvno, &pininfo);
1762 /* Dismiss the prompt. */
1763 pincb (pincb_arg, NULL, NULL);
1765 assert (!*pinvalue);
1769 /* The reader has no pinpad or we don't want to use it. */
1770 rc = pincb (pincb_arg, prompt, pinvalue);
1772 xfree (prompt_buffer);
1773 prompt_buffer = NULL;
1776 log_info (_("PIN callback returned error: %s\n"),
1781 if (strlen (*pinvalue) < minlen)
1783 log_error (_("PIN for CHV%d is too short;"
1784 " minimum length is %d\n"), chvno, minlen);
1787 return gpg_error (GPG_ERR_BAD_PIN);
1790 rc = iso7816_verify (app->slot, 0x80+chvno,
1791 *pinvalue, strlen (*pinvalue));
1796 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1799 flush_cache_after_error (app);
1806 /* Verify CHV2 if required. Depending on the configuration of the
1807 card CHV1 will also be verified. */
1809 verify_chv2 (app_t app,
1810 gpg_error_t (*pincb)(void*, const char *, char **),
1817 return 0; /* We already verified CHV2. */
1819 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1824 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1826 /* For convenience we verify CHV1 here too. We do this only if
1827 the card is not configured to require a verification before
1828 each CHV1 controlled operation (force_chv1) and if we are not
1829 using the pinpad (PINVALUE == NULL). */
1830 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1831 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1832 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1835 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1836 flush_cache_after_error (app);
1848 /* Build the prompt to enter the Admin PIN. The prompt depends on the
1849 current sdtate of the card. */
1851 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1854 unsigned char *value;
1861 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1862 if (!relptr || valuelen < 7)
1864 log_error (_("error retrieving CHV status from card\n"));
1866 return gpg_error (GPG_ERR_CARD);
1870 log_info (_("card is permanently locked!\n"));
1872 return gpg_error (GPG_ERR_BAD_PIN);
1874 remaining = value[6];
1877 log_info(_("%d Admin PIN attempts remaining before card"
1878 " is permanently locked\n"), remaining);
1882 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1883 the start of the string. Use %%0A to force a linefeed. */
1884 prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1885 "[remaining attempts: %d]"), remaining);
1888 prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1891 return gpg_error_from_syserror ();
1898 /* Verify CHV3 if required. */
1900 verify_chv3 (app_t app,
1901 gpg_error_t (*pincb)(void*, const char *, char **),
1906 #if GNUPG_MAJOR_VERSION != 1
1907 if (!opt.allow_admin)
1909 log_info (_("access to admin commands is not configured\n"));
1910 return gpg_error (GPG_ERR_EACCES);
1920 memset (&pininfo, 0, sizeof pininfo);
1921 pininfo.fixedlen = -1;
1922 pininfo.minlen = minlen;
1924 rc = build_enter_admin_pin_prompt (app, &prompt);
1928 if (!opt.disable_pinpad
1929 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
1930 && !check_pinpad_request (app, &pininfo, 1))
1932 /* The reader supports the verify command through the pinpad. */
1933 rc = pincb (pincb_arg, prompt, NULL);
1938 log_info (_("PIN callback returned error: %s\n"),
1942 rc = iso7816_verify_kp (app->slot, 0x83, &pininfo);
1943 /* Dismiss the prompt. */
1944 pincb (pincb_arg, NULL, NULL);
1950 rc = pincb (pincb_arg, prompt, &pinvalue);
1955 log_info (_("PIN callback returned error: %s\n"),
1960 if (strlen (pinvalue) < minlen)
1962 log_error (_("PIN for CHV%d is too short;"
1963 " minimum length is %d\n"), 3, minlen);
1965 return gpg_error (GPG_ERR_BAD_PIN);
1968 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1974 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1975 flush_cache_after_error (app);
1984 /* Handle the SETATTR operation. All arguments are already basically
1987 do_setattr (app_t app, const char *name,
1988 gpg_error_t (*pincb)(void*, const char *, char **),
1990 const unsigned char *value, size_t valuelen)
1999 unsigned int need_v2:1;
2001 { "DISP-NAME", 0x005B, 3 },
2002 { "LOGIN-DATA", 0x005E, 3, 2 },
2003 { "DISP-LANG", 0x5F2D, 3 },
2004 { "DISP-SEX", 0x5F35, 3 },
2005 { "PUBKEY-URL", 0x5F50, 3 },
2006 { "CHV-STATUS-1", 0x00C4, 3, 1 },
2007 { "CA-FPR-1", 0x00CA, 3 },
2008 { "CA-FPR-2", 0x00CB, 3 },
2009 { "CA-FPR-3", 0x00CC, 3 },
2010 { "PRIVATE-DO-1", 0x0101, 2 },
2011 { "PRIVATE-DO-2", 0x0102, 3 },
2012 { "PRIVATE-DO-3", 0x0103, 2 },
2013 { "PRIVATE-DO-4", 0x0104, 3 },
2014 { "CERT-3", 0x7F21, 3, 0, 1 },
2015 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
2016 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
2017 { "KEY-ATTR", 0, 0, 3, 1 },
2018 { "AESKEY", 0x00D5, 3, 0, 1 },
2023 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
2025 if (!table[idx].name)
2026 return gpg_error (GPG_ERR_INV_NAME);
2027 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
2028 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
2030 if (table[idx].special == 3)
2031 return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
2033 switch (table[idx].need_chv)
2036 rc = verify_chv2 (app, pincb, pincb_arg);
2039 rc = verify_chv3 (app, pincb, pincb_arg);
2047 /* Flush the cache before writing it, so that the next get operation
2048 will reread the data from the card and thus get synced in case of
2049 errors (e.g. data truncated by the card). */
2050 flush_cache_item (app, table[idx].tag);
2052 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
2053 exmode = 1; /* Use extended length w/o a limit. */
2054 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
2055 exmode = -254; /* Command chaining with max. 254 bytes. */
2058 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
2060 log_error ("failed to set '%s': %s\n", table[idx].name, gpg_strerror (rc));
2062 if (table[idx].special == 1)
2063 app->force_chv1 = (valuelen && *value == 0);
2064 else if (table[idx].special == 2)
2065 parse_login_data (app);
2071 /* Handle the WRITECERT command for OpenPGP. This rites the standard
2072 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
2073 PINCB and PINCB_ARG are the usual arguments for the pinentry
2076 do_writecert (app_t app, ctrl_t ctrl,
2077 const char *certidstr,
2078 gpg_error_t (*pincb)(void*, const char *, char **),
2080 const unsigned char *certdata, size_t certdatalen)
2083 #if GNUPG_MAJOR_VERSION > 1
2084 if (strcmp (certidstr, "OPENPGP.3"))
2085 return gpg_error (GPG_ERR_INV_ID);
2086 if (!certdata || !certdatalen)
2087 return gpg_error (GPG_ERR_INV_ARG);
2088 if (!app->app_local->extcap.is_v2)
2089 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2090 if (certdatalen > app->app_local->extcap.max_certlen_3)
2091 return gpg_error (GPG_ERR_TOO_LARGE);
2092 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
2094 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2100 /* Handle the PASSWD command. The following combinations are
2103 Flags CHVNO Vers. Description
2104 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
2105 RESET 1 2 Verify PW3 and set a new PW1.
2106 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
2107 RESET 2 2 Verify PW3 and set a new Reset Code.
2108 RESET 3 any Returns GPG_ERR_INV_ID.
2109 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
2110 - 1 2 Verify PW1 and set a new PW1.
2111 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
2112 - 2 2 Verify Reset Code and set a new PW1.
2113 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
2116 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
2118 gpg_error_t (*pincb)(void*, const char *, char **),
2122 int chvno = atoi (chvnostr);
2123 char *resetcode = NULL;
2124 char *oldpinvalue = NULL;
2125 char *pinvalue = NULL;
2126 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
2127 int set_resetcode = 0;
2133 memset (&pininfo, 0, sizeof pininfo);
2134 pininfo.fixedlen = -1;
2135 pininfo.minlen = minlen;
2137 if (reset_mode && chvno == 3)
2139 rc = gpg_error (GPG_ERR_INV_ID);
2143 if (!app->app_local->extcap.is_v2)
2145 /* Version 1 cards. */
2147 if (reset_mode || chvno == 3)
2149 /* We always require that the PIN is entered. */
2151 rc = verify_chv3 (app, pincb, pincb_arg);
2155 else if (chvno == 1 || chvno == 2)
2157 /* On a v1.x card CHV1 and CVH2 should always have the same
2158 value, thus we enforce it here. */
2159 int save_force = app->force_chv1;
2161 app->force_chv1 = 0;
2164 rc = verify_chv2 (app, pincb, pincb_arg);
2165 app->force_chv1 = save_force;
2171 rc = gpg_error (GPG_ERR_INV_ID);
2177 /* Version 2 cards. */
2179 if (!opt.disable_pinpad
2180 && !iso7816_check_pinpad (app->slot,
2181 ISO7816_CHANGE_REFERENCE_DATA, &pininfo)
2182 && !check_pinpad_request (app, &pininfo, chvno == 3))
2187 /* To reset a PIN the Admin PIN is required. */
2190 rc = verify_chv3 (app, pincb, pincb_arg);
2197 else if (chvno == 1 || chvno == 3)
2201 char *promptbuf = NULL;
2207 rc = build_enter_admin_pin_prompt (app, &promptbuf);
2213 prompt = _("||Please enter the PIN");
2214 rc = pincb (pincb_arg, prompt, &oldpinvalue);
2219 log_info (_("PIN callback returned error: %s\n"),
2224 if (strlen (oldpinvalue) < minlen)
2226 log_info (_("PIN for CHV%d is too short;"
2227 " minimum length is %d\n"), chvno, minlen);
2228 rc = gpg_error (GPG_ERR_BAD_PIN);
2233 else if (chvno == 2)
2235 /* There is no PW2 for v2 cards. We use this condition to
2236 allow a PW reset using the Reset Code. */
2238 unsigned char *value;
2244 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2245 if (!relptr || valuelen < 7)
2247 log_error (_("error retrieving CHV status from card\n"));
2249 rc = gpg_error (GPG_ERR_CARD);
2252 remaining = value[5];
2256 log_error (_("Reset Code not or not anymore available\n"));
2257 rc = gpg_error (GPG_ERR_BAD_PIN);
2261 rc = pincb (pincb_arg,
2262 _("||Please enter the Reset Code for the card"),
2266 log_info (_("PIN callback returned error: %s\n"),
2270 if (strlen (resetcode) < minlen)
2272 log_info (_("Reset Code is too short; minimum length is %d\n"),
2274 rc = gpg_error (GPG_ERR_BAD_PIN);
2280 rc = gpg_error (GPG_ERR_INV_ID);
2288 app->did_chv1 = app->did_chv2 = 0;
2292 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2293 keep it at the start of the string. We need this elsewhere
2294 to get some infos on the string. */
2295 rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
2296 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2300 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2310 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2312 rc = gpg_error_from_syserror ();
2315 strcpy (stpcpy (buffer, resetcode), pinvalue);
2316 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2317 buffer, strlen (buffer));
2318 wipememory (buffer, strlen (buffer));
2322 else if (set_resetcode)
2324 if (strlen (pinvalue) < 8)
2326 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2327 rc = gpg_error (GPG_ERR_BAD_PIN);
2330 rc = iso7816_put_data (app->slot, 0, 0xD3,
2331 pinvalue, strlen (pinvalue));
2333 else if (reset_mode)
2335 rc = iso7816_reset_retry_counter (app->slot, 0x81,
2336 pinvalue, strlen (pinvalue));
2337 if (!rc && !app->app_local->extcap.is_v2)
2338 rc = iso7816_reset_retry_counter (app->slot, 0x82,
2339 pinvalue, strlen (pinvalue));
2341 else if (!app->app_local->extcap.is_v2)
2343 /* Version 1 cards. */
2344 if (chvno == 1 || chvno == 2)
2346 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2347 pinvalue, strlen (pinvalue));
2349 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2350 pinvalue, strlen (pinvalue));
2352 else /* CHVNO == 3 */
2354 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2355 pinvalue, strlen (pinvalue));
2360 /* Version 2 cards. */
2361 assert (chvno == 1 || chvno == 3);
2365 rc = pincb (pincb_arg,
2367 _("||Please enter the Admin PIN and New Admin PIN") :
2368 _("||Please enter the PIN and New PIN"), NULL);
2371 log_info (_("PIN callback returned error: %s\n"),
2375 rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0,
2377 pincb (pincb_arg, NULL, NULL); /* Dismiss the prompt. */
2380 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2381 oldpinvalue, strlen (oldpinvalue),
2382 pinvalue, strlen (pinvalue));
2387 wipememory (pinvalue, strlen (pinvalue));
2391 flush_cache_after_error (app);
2396 wipememory (resetcode, strlen (resetcode));
2401 wipememory (oldpinvalue, strlen (oldpinvalue));
2402 xfree (oldpinvalue);
2408 /* Check whether a key already exists. KEYIDX is the index of the key
2409 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2410 error returned if the key already exists. The flag GENERATING is
2411 only used to print correct messages. */
2413 does_key_exist (app_t app, int keyidx, int generating, int force)
2415 const unsigned char *fpr;
2416 unsigned char *buffer;
2420 assert (keyidx >=0 && keyidx <= 2);
2422 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2424 log_error (_("error reading application data\n"));
2425 return gpg_error (GPG_ERR_GENERAL);
2427 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2430 log_error (_("error reading fingerprint DO\n"));
2432 return gpg_error (GPG_ERR_GENERAL);
2435 for (i=0; i < 20 && !fpr[i]; i++)
2438 if (i!=20 && !force)
2440 log_error (_("key already exists\n"));
2441 return gpg_error (GPG_ERR_EEXIST);
2444 log_info (_("existing key will be replaced\n"));
2445 else if (generating)
2446 log_info (_("generating new key\n"));
2448 log_info (_("writing new key\n"));
2453 /* Create a TLV tag and value and store it at BUFFER. Return the length
2454 of tag and length. A LENGTH greater than 65535 is truncated. */
2456 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2458 unsigned char *p = buffer;
2460 assert (tag <= 0xffff);
2466 else if (length < 256)
2473 if (length > 0xffff)
2485 build_privkey_template (app_t app, int keyno,
2486 const unsigned char *rsa_n, size_t rsa_n_len,
2487 const unsigned char *rsa_e, size_t rsa_e_len,
2488 const unsigned char *rsa_p, size_t rsa_p_len,
2489 const unsigned char *rsa_q, size_t rsa_q_len,
2490 const unsigned char *rsa_u, size_t rsa_u_len,
2491 const unsigned char *rsa_dp, size_t rsa_dp_len,
2492 const unsigned char *rsa_dq, size_t rsa_dq_len,
2493 unsigned char **result, size_t *resultlen)
2495 size_t rsa_e_reqlen;
2496 unsigned char privkey[7*(1+3+3)];
2498 unsigned char exthdr[2+2+3];
2500 unsigned char suffix[2+3];
2504 unsigned char *template;
2505 size_t template_size;
2510 switch (app->app_local->keyattr[keyno].rsa.format)
2519 return gpg_error (GPG_ERR_INV_VALUE);
2522 /* Get the required length for E. Rounded up to the nearest byte */
2523 rsa_e_reqlen = (app->app_local->keyattr[keyno].rsa.e_bits + 7) / 8;
2524 assert (rsa_e_len <= rsa_e_reqlen);
2526 /* Build the 7f48 cardholder private key template. */
2530 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2531 datalen += rsa_e_reqlen;
2533 tp += add_tlv (tp, 0x92, rsa_p_len);
2534 datalen += rsa_p_len;
2536 tp += add_tlv (tp, 0x93, rsa_q_len);
2537 datalen += rsa_q_len;
2539 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
2540 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2542 tp += add_tlv (tp, 0x94, rsa_u_len);
2543 datalen += rsa_u_len;
2544 tp += add_tlv (tp, 0x95, rsa_dp_len);
2545 datalen += rsa_dp_len;
2546 tp += add_tlv (tp, 0x96, rsa_dq_len);
2547 datalen += rsa_dq_len;
2550 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
2551 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2553 tp += add_tlv (tp, 0x97, rsa_n_len);
2554 datalen += rsa_n_len;
2556 privkey_len = tp - privkey;
2558 /* Build the extended header list without the private key template. */
2560 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2562 tp += add_tlv (tp, 0x7f48, privkey_len);
2563 exthdr_len = tp - exthdr;
2565 /* Build the 5f48 suffix of the data. */
2567 tp += add_tlv (tp, 0x5f48, datalen);
2568 suffix_len = tp - suffix;
2570 /* Now concatenate everything. */
2571 template_size = (1 + 3 /* 0x4d and len. */
2576 tp = template = xtrymalloc_secure (template_size);
2578 return gpg_error_from_syserror ();
2580 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2581 memcpy (tp, exthdr, exthdr_len);
2583 memcpy (tp, privkey, privkey_len);
2585 memcpy (tp, suffix, suffix_len);
2588 memcpy (tp, rsa_e, rsa_e_len);
2589 if (rsa_e_len < rsa_e_reqlen)
2591 /* Right justify E. */
2592 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2593 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2597 memcpy (tp, rsa_p, rsa_p_len);
2600 memcpy (tp, rsa_q, rsa_q_len);
2603 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
2604 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2606 memcpy (tp, rsa_u, rsa_u_len);
2608 memcpy (tp, rsa_dp, rsa_dp_len);
2610 memcpy (tp, rsa_dq, rsa_dq_len);
2614 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
2615 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2617 memcpy (tp, rsa_n, rsa_n_len);
2621 /* Sanity check. We don't know the exact length because we
2622 allocated 3 bytes for the first length header. */
2623 assert (tp - template <= template_size);
2626 *resultlen = tp - template;
2631 build_ecc_privkey_template (app_t app, int keyno,
2632 const unsigned char *ecc_d, size_t ecc_d_len,
2633 unsigned char **result, size_t *resultlen)
2635 unsigned char privkey[2];
2637 unsigned char exthdr[2+2+1];
2639 unsigned char suffix[2+1];
2643 unsigned char *template;
2644 size_t template_size;
2651 /* Build the 7f48 cardholder private key template. */
2655 tp += add_tlv (tp, 0x92, ecc_d_len);
2656 datalen += ecc_d_len;
2658 privkey_len = tp - privkey;
2660 /* Build the extended header list without the private key template. */
2662 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2664 tp += add_tlv (tp, 0x7f48, privkey_len);
2665 exthdr_len = tp - exthdr;
2667 /* Build the 5f48 suffix of the data. */
2669 tp += add_tlv (tp, 0x5f48, datalen);
2670 suffix_len = tp - suffix;
2672 /* Now concatenate everything. */
2673 template_size = (1 + 1 /* 0x4d and len. */
2678 tp = template = xtrymalloc_secure (template_size);
2680 return gpg_error_from_syserror ();
2682 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2683 memcpy (tp, exthdr, exthdr_len);
2685 memcpy (tp, privkey, privkey_len);
2687 memcpy (tp, suffix, suffix_len);
2690 memcpy (tp, ecc_d, ecc_d_len);
2693 assert (tp - template == template_size);
2696 *resultlen = tp - template;
2701 /* Helper for do_writekley to change the size of a key. Not ethat
2702 this deletes the entire key without asking. */
2704 change_keyattr (app_t app, int keyno, const unsigned char *buf, size_t buflen,
2705 gpg_error_t (*pincb)(void*, const char *, char **),
2710 assert (keyno >=0 && keyno <= 2);
2712 /* Prepare for storing the key. */
2713 err = verify_chv3 (app, pincb, pincb_arg);
2717 /* Change the attribute. */
2718 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buf, buflen);
2720 log_error ("error changing key attribute (key=%d)\n", keyno+1);
2722 log_info ("key attribute changed (key=%d)\n", keyno+1);
2724 parse_algorithm_attribute (app, keyno);
2732 /* Helper to process an setattr command for name KEY-ATTR.
2733 In (VALUE,VALUELEN), it expects following string:
2734 RSA: "--force <keyno> <algo> rsa<nbits>"
2735 ECC: "--force <keyno> <algo> <curvename>"
2738 change_keyattr_from_string (app_t app,
2739 gpg_error_t (*pincb)(void*, const char *, char **),
2741 const void *value, size_t valuelen)
2743 gpg_error_t err = 0;
2748 /* VALUE is expected to be a string but not guaranteed to be
2749 terminated. Thus copy it to an allocated buffer first. */
2750 string = xtrymalloc (valuelen+1);
2752 return gpg_error_from_syserror ();
2753 memcpy (string, value, valuelen);
2754 string[valuelen] = 0;
2756 /* Because this function deletes the key we require the string
2757 "--force" in the data to make clear that something serious might
2759 sscanf (string, " --force %d %d %n", &keyno, &algo, &n);
2762 err = gpg_error (GPG_ERR_INV_DATA);
2766 if (keyno < 1 || keyno > 3)
2767 err = gpg_error (GPG_ERR_INV_ID);
2768 else if (algo == PUBKEY_ALGO_RSA)
2773 nbits = strtoul (string+n+3, NULL, 10);
2775 err = gpg_error (GPG_ERR_INV_DATA);
2776 else if (nbits < 1024)
2777 err = gpg_error (GPG_ERR_TOO_SHORT);
2778 else if (nbits > 4096)
2779 err = gpg_error (GPG_ERR_TOO_LARGE);
2786 /* Read the current attributes into a buffer. */
2787 relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL);
2790 err = gpg_error (GPG_ERR_CARD);
2793 if (buflen < 6 || buf[0] != PUBKEY_ALGO_RSA)
2795 /* Attriutes too short or not an RSA key. */
2797 err = gpg_error (GPG_ERR_CARD);
2801 /* We only change n_bits and don't touch anything else. Before we
2802 do so, we round up NBITS to a sensible way in the same way as
2803 gpg's key generation does it. This may help to sort out problems
2804 with a few bits too short keys. */
2805 nbits = ((nbits + 31) / 32) * 32;
2806 buf[1] = (nbits >> 8);
2808 err = change_keyattr (app, keyno-1, buf, buflen, pincb, pincb_arg);
2812 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
2813 || algo == PUBKEY_ALGO_EDDSA)
2817 oidstr = openpgp_curve_to_oid (string+n, NULL);
2819 err = gpg_error (GPG_ERR_INV_DATA);
2824 err = openpgp_oid_from_str (oidstr, &m);
2828 const unsigned char *buf = gcry_mpi_get_opaque (m, &len);
2830 /* We have enough room at STRING. */
2833 memcpy (string+1, buf+1, len++);
2834 err = change_keyattr (app, keyno-1, string, len,
2836 gcry_mpi_release (m);
2841 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
2850 rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
2851 void *pincb_arg, int keyno,
2852 const unsigned char *buf, size_t buflen, int depth)
2855 const unsigned char *tok;
2857 int last_depth1, last_depth2;
2858 const unsigned char *rsa_n = NULL;
2859 const unsigned char *rsa_e = NULL;
2860 const unsigned char *rsa_p = NULL;
2861 const unsigned char *rsa_q = NULL;
2862 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2864 unsigned int maxbits;
2865 unsigned char *template = NULL;
2867 size_t template_len;
2868 unsigned char fprbuf[20];
2871 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA)
2873 log_error (_("unsupported algorithm: %s"), "RSA");
2874 err = gpg_error (GPG_ERR_INV_VALUE);
2878 last_depth1 = depth;
2879 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2880 && depth && depth >= last_depth1)
2884 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2887 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2889 if (tok && toklen == 1)
2891 const unsigned char **mpi;
2896 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2897 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2898 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2899 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2900 default: mpi = NULL; mpi_len = NULL; break;
2904 err = gpg_error (GPG_ERR_DUP_VALUE);
2907 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2911 /* Strip off leading zero bytes and save. */
2912 for (;toklen && !*tok; toklen--, tok++)
2918 /* Skip until end of list. */
2919 last_depth2 = depth;
2920 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2921 && depth && depth >= last_depth2)
2926 /* Parse other attributes. */
2927 last_depth1 = depth;
2928 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2929 && depth && depth >= last_depth1)
2933 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2936 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2938 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2940 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2944 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2946 created_at = created_at*10 + (*tok - '0');
2949 /* Skip until end of list. */
2950 last_depth2 = depth;
2951 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2952 && depth && depth >= last_depth2)
2959 /* Check that we have all parameters and that they match the card
2963 log_error (_("creation timestamp missing\n"));
2964 err = gpg_error (GPG_ERR_INV_VALUE);
2968 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
2969 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2971 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2972 nbits, (unsigned int)rsa_n_len);
2973 if (nbits != maxbits)
2975 log_error (_("RSA modulus missing or not of size %d bits\n"),
2977 err = gpg_error (GPG_ERR_BAD_SECKEY);
2981 maxbits = app->app_local->keyattr[keyno].rsa.e_bits;
2982 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2983 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2984 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2985 if (nbits < 2 || nbits > maxbits)
2987 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2989 err = gpg_error (GPG_ERR_BAD_SECKEY);
2993 maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2;
2994 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2995 if (nbits != maxbits)
2997 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2999 err = gpg_error (GPG_ERR_BAD_SECKEY);
3002 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
3003 if (nbits != maxbits)
3005 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3007 err = gpg_error (GPG_ERR_BAD_SECKEY);
3011 /* We need to remove the cached public key. */
3012 xfree (app->app_local->pk[keyno].key);
3013 app->app_local->pk[keyno].key = NULL;
3014 app->app_local->pk[keyno].keylen = 0;
3015 app->app_local->pk[keyno].read_done = 0;
3018 if (app->app_local->extcap.is_v2)
3020 unsigned char *rsa_u, *rsa_dp, *rsa_dq;
3021 size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
3022 gcry_mpi_t mpi_e, mpi_p, mpi_q;
3023 gcry_mpi_t mpi_u = gcry_mpi_snew (0);
3024 gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
3025 gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
3026 gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
3029 /* Calculate the u, dp and dq components needed by RSA_CRT cards */
3030 gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
3031 gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
3032 gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
3034 gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
3035 gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
3036 gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
3037 gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
3038 gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
3040 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
3041 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
3042 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
3044 gcry_mpi_release (mpi_e);
3045 gcry_mpi_release (mpi_p);
3046 gcry_mpi_release (mpi_q);
3047 gcry_mpi_release (mpi_u);
3048 gcry_mpi_release (mpi_dp);
3049 gcry_mpi_release (mpi_dq);
3050 gcry_mpi_release (mpi_tmp);
3052 /* Build the private key template as described in section 4.3.3.7 of
3053 the OpenPGP card specs version 2.0. */
3054 err = build_privkey_template (app, keyno,
3062 &template, &template_len);
3070 /* Prepare for storing the key. */
3071 err = verify_chv3 (app, pincb, pincb_arg);
3075 /* Store the key. */
3076 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3077 exmode = 1; /* Use extended length w/o a limit. */
3078 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3082 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3083 template, template_len);
3087 /* Build the private key template as described in section 4.3.3.6 of
3088 the OpenPGP card specs version 1.1:
3089 0xC0 <length> public exponent
3090 0xC1 <length> prime p
3091 0xC2 <length> prime q
3093 assert (rsa_e_len <= 4);
3094 template_len = (1 + 1 + 4
3096 + 1 + 1 + rsa_q_len);
3097 template = tp = xtrymalloc_secure (template_len);
3100 err = gpg_error_from_syserror ();
3105 memcpy (tp, rsa_e, rsa_e_len);
3108 /* Right justify E. */
3109 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
3110 memset (tp, 0, 4-rsa_e_len);
3116 memcpy (tp, rsa_p, rsa_p_len);
3121 memcpy (tp, rsa_q, rsa_q_len);
3124 assert (tp - template == template_len);
3126 /* Prepare for storing the key. */
3127 err = verify_chv3 (app, pincb, pincb_arg);
3131 /* Store the key. */
3132 err = iso7816_put_data (app->slot, 0,
3133 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
3134 template, template_len);
3138 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3142 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
3143 rsa_n, rsa_n_len, rsa_e, rsa_e_len);
3155 ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3156 void *pincb_arg, int keyno,
3157 const unsigned char *buf, size_t buflen, int depth)
3160 const unsigned char *tok;
3162 int last_depth1, last_depth2;
3163 const unsigned char *ecc_q = NULL;
3164 const unsigned char *ecc_d = NULL;
3165 size_t ecc_q_len, ecc_d_len;
3167 const char *oidstr = NULL;
3168 int flag_djb_tweak = 0;
3171 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3172 curve = "NIST P-256" */
3173 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3174 curve = "secp256k1" */
3175 /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)):
3176 curve = "Ed25519" */
3177 last_depth1 = depth;
3178 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3179 && depth && depth >= last_depth1)
3183 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3186 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3189 if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
3191 unsigned char *curve;
3193 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3196 curve = xtrymalloc (toklen+1);
3199 err = gpg_error_from_syserror ();
3203 memcpy (curve, tok, toklen);
3205 oidstr = openpgp_curve_to_oid (curve, NULL);
3208 else if (tok && toklen == 5 && !memcmp (tok, "flags", 5))
3210 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3215 if ((toklen == 5 && !memcmp (tok, "eddsa", 5))
3216 || (toklen == 9 && !memcmp (tok, "djb-tweak", 9)))
3220 else if (tok && toklen == 1)
3222 const unsigned char **buf2;
3227 case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break;
3228 case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; break;
3229 default: buf2 = NULL; buf2len = NULL; break;
3233 err = gpg_error (GPG_ERR_DUP_VALUE);
3236 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3238 if (tok && buf2 && !flag_djb_tweak)
3239 /* It's MPI. Strip off leading zero bytes and save. */
3240 for (;toklen && !*tok; toklen--, tok++)
3246 /* Skip until end of list. */
3247 last_depth2 = depth;
3248 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3249 && depth && depth >= last_depth2)
3254 /* Parse other attributes. */
3255 last_depth1 = depth;
3256 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3257 && depth && depth >= last_depth1)
3261 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3264 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3266 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3268 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3272 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3274 created_at = created_at*10 + (*tok - '0');
3277 /* Skip until end of list. */
3278 last_depth2 = depth;
3279 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3280 && depth && depth >= last_depth2)
3287 /* Check that we have all parameters and that they match the card
3291 log_error (_("unsupported curve\n"));
3292 err = gpg_error (GPG_ERR_INV_VALUE);
3297 log_error (_("creation timestamp missing\n"));
3298 err = gpg_error (GPG_ERR_INV_VALUE);
3301 if (flag_djb_tweak && keyno != 1)
3302 algo = PUBKEY_ALGO_EDDSA;
3303 else if (keyno == 1)
3304 algo = PUBKEY_ALGO_ECDH;
3306 algo = PUBKEY_ALGO_ECDSA;
3308 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC
3309 || app->app_local->keyattr[keyno].ecc.oid != oidstr
3310 || app->app_local->keyattr[keyno].ecc.flags != flag_djb_tweak)
3312 log_error ("key attribute on card doesn't match\n");
3313 err = gpg_error (GPG_ERR_INV_VALUE);
3318 log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
3320 /* We need to remove the cached public key. */
3321 xfree (app->app_local->pk[keyno].key);
3322 app->app_local->pk[keyno].key = NULL;
3323 app->app_local->pk[keyno].keylen = 0;
3324 app->app_local->pk[keyno].read_done = 0;
3326 if (app->app_local->extcap.is_v2)
3328 /* Build the private key template as described in section 4.3.3.7 of
3329 the OpenPGP card specs version 2.0. */
3330 unsigned char *template;
3331 size_t template_len;
3334 err = build_ecc_privkey_template (app, keyno,
3336 &template, &template_len);
3340 /* Prepare for storing the key. */
3341 err = verify_chv3 (app, pincb, pincb_arg);
3348 /* Store the key. */
3349 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3350 exmode = 1; /* Use extended length w/o a limit. */
3351 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3355 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3356 template, template_len);
3360 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3364 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3370 const unsigned char *oidbuf;
3373 unsigned char fprbuf[20];
3375 err = openpgp_oid_from_str (oidstr, &oid);
3379 oidbuf = gcry_mpi_get_opaque (oid, &n);
3383 err = gpg_error_from_syserror ();
3384 gcry_mpi_release (oid);
3387 err = store_fpr (app, keyno, created_at, fprbuf, algo,
3388 oidbuf, oid_len, ecc_q, ecc_q_len,
3389 "\x03\x01\x08\x07", (size_t)4);
3390 gcry_mpi_release (oid);
3397 /* Handle the WRITEKEY command for OpenPGP. This function expects a
3398 canonical encoded S-expression with the secret key in KEYDATA and
3399 its length (for assertions) in KEYDATALEN. KEYID needs to be the
3400 usual keyid which for OpenPGP is the string "OPENPGP.n" with
3401 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
3402 get overwritten. PINCB and PINCB_ARG are the usual arguments for
3403 the pinentry callback. */
3405 do_writekey (app_t app, ctrl_t ctrl,
3406 const char *keyid, unsigned int flags,
3407 gpg_error_t (*pincb)(void*, const char *, char **),
3409 const unsigned char *keydata, size_t keydatalen)
3412 int force = (flags & 1);
3414 const unsigned char *buf, *tok;
3415 size_t buflen, toklen;
3420 if (!strcmp (keyid, "OPENPGP.1"))
3422 else if (!strcmp (keyid, "OPENPGP.2"))
3424 else if (!strcmp (keyid, "OPENPGP.3"))
3427 return gpg_error (GPG_ERR_INV_ID);
3429 err = does_key_exist (app, keyno, 0, force);
3435 Parse the S-expression
3438 buflen = keydatalen;
3440 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3442 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3444 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
3448 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
3449 log_info ("protected-private-key passed to writekey\n");
3450 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
3451 log_info ("shadowed-private-key passed to writekey\n");
3452 err = gpg_error (GPG_ERR_BAD_SECKEY);
3455 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3457 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3459 if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
3460 err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3461 else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
3462 err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3465 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
3475 /* Handle the GENKEY command. */
3477 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
3479 gpg_error_t (*pincb)(void*, const char *, char **),
3484 unsigned char fprbuf[20];
3485 const unsigned char *keydata, *m, *e;
3486 unsigned char *buffer = NULL;
3487 size_t buflen, keydatalen, mlen, elen;
3489 int keyno = atoi (keynostr);
3490 int force = (flags & 1);
3494 unsigned int keybits;
3496 if (keyno < 1 || keyno > 3)
3497 return gpg_error (GPG_ERR_INV_ID);
3500 /* We flush the cache to increase the traffic before a key
3501 generation. This _might_ help a card to gather more entropy. */
3504 /* Obviously we need to remove the cached public key. */
3505 xfree (app->app_local->pk[keyno].key);
3506 app->app_local->pk[keyno].key = NULL;
3507 app->app_local->pk[keyno].keylen = 0;
3508 app->app_local->pk[keyno].read_done = 0;
3510 /* Check whether a key already exists. */
3511 rc = does_key_exist (app, keyno, 1, force);
3515 /* Because we send the key parameter back via status lines we need
3516 to put a limit on the max. allowed keysize. 2048 bit will
3517 already lead to a 527 byte long status line and thus a 4096 bit
3518 key would exceed the Assuan line length limit. */
3519 keybits = app->app_local->keyattr[keyno].rsa.n_bits;
3521 return gpg_error (GPG_ERR_TOO_LARGE);
3523 /* Prepare for key generation by verifying the Admin PIN. */
3524 rc = verify_chv3 (app, pincb, pincb_arg);
3528 /* Test whether we will need extended length mode. (1900 is an
3529 arbitrary length which for sure fits into a short apdu.) */
3530 if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
3532 exmode = 1; /* Use extended length w/o a limit. */
3533 le_value = app->app_local->extcap.max_rsp_data;
3534 /* No need to check le_value because it comes from a 16 bit
3535 value and thus can't create an overflow on a 32 bit
3541 le_value = 256; /* Use legacy value. */
3544 log_info (_("please wait while key is being generated ...\n"));
3545 start_at = time (NULL);
3546 rc = iso7816_generate_keypair
3547 /* # warning key generation temporary replaced by reading an existing key. */
3548 /* rc = iso7816_read_public_key */
3550 (const unsigned char*)(keyno == 0? "\xB6" :
3551 keyno == 1? "\xB8" : "\xA4"), 2,
3556 rc = gpg_error (GPG_ERR_CARD);
3557 log_error (_("generating key failed\n"));