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].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 < 0 || keyno > 2)
1250 return gpg_error (GPG_ERR_INV_ID);
1252 /* Already cached? */
1253 if (app->app_local->pk[keyno].read_done)
1256 xfree (app->app_local->pk[keyno].key);
1257 app->app_local->pk[keyno].key = NULL;
1258 app->app_local->pk[keyno].keylen = 0;
1260 m = e = NULL; /* (avoid cc warning) */
1262 if (app->card_version > 0x0100)
1264 int exmode, le_value;
1266 /* We may simply read the public key out of these cards. */
1267 if (app->app_local->cardcap.ext_lc_le)
1269 exmode = 1; /* Use extended length. */
1270 le_value = app->app_local->extcap.max_rsp_data;
1275 le_value = 256; /* Use legacy value. */
1278 err = iso7816_read_public_key
1280 (const unsigned char*)(keyno == 0? "\xB6" :
1281 keyno == 1? "\xB8" : "\xA4"), 2,
1286 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1290 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1293 err = gpg_error (GPG_ERR_CARD);
1294 log_error (_("response does not contain the public key data\n"));
1298 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1300 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1303 err = gpg_error (GPG_ERR_CARD);
1304 log_error (_("response does not contain the RSA modulus\n"));
1308 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1311 err = gpg_error (GPG_ERR_CARD);
1312 log_error (_("response does not contain the RSA public exponent\n"));
1318 m = find_tlv (keydata, keydatalen, 0x0086, &mlen);
1321 err = gpg_error (GPG_ERR_CARD);
1322 log_error (_("response does not contain the EC public point\n"));
1329 /* Due to a design problem in v1.0 cards we can't get the public
1330 key out of these cards without doing a verify on CHV3.
1331 Clearly that is not an option and thus we try to locate the
1332 key using an external helper.
1334 The helper we use here is gpg itself, which should know about
1335 the key in any case. */
1339 char *command = NULL;
1343 buffer = NULL; /* We don't need buffer. */
1345 err = retrieve_fpr_from_card (app, keyno, fpr);
1348 log_error ("error while retrieving fpr from card: %s\n",
1349 gpg_strerror (err));
1352 hexkeyid = fpr + 24;
1354 ret = gpgrt_asprintf
1355 (&command, "gpg --list-keys --with-colons --with-key-data '%s'", fpr);
1358 err = gpg_error_from_syserror ();
1362 fp = popen (command, "r");
1366 err = gpg_error_from_syserror ();
1367 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1371 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1375 log_error ("error while retrieving key material through pipe: %s\n",
1376 gpg_strerror (err));
1381 mbuf = xtrymalloc (mlen + 1);
1384 err = gpg_error_from_syserror ();
1388 if ((app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA
1389 || (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC
1390 && !app->app_local->keyattr[keyno].ecc.flags))
1391 && mlen && (*m & 0x80))
1392 { /* Prepend numbers with a 0 if needed for MPI. */
1394 memcpy (mbuf+1, m, mlen);
1397 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC
1398 && app->app_local->keyattr[keyno].ecc.flags)
1399 { /* Prepend 0x40 prefix. */
1401 memcpy (mbuf+1, m, mlen);
1405 memcpy (mbuf, m, mlen);
1407 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1409 ebuf = xtrymalloc (elen + 1);
1412 err = gpg_error_from_syserror ();
1415 /* Prepend numbers with a 0 if needed. */
1416 if (elen && (*e & 0x80))
1419 memcpy (ebuf+1, e, elen);
1423 memcpy (ebuf, e, elen);
1425 err = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%b)(e%b)))",
1426 (int)mlen, mbuf, (int)elen, ebuf);
1428 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
1432 if (!app->app_local->keyattr[keyno].ecc.flags)
1433 format = "(public-key(ecc(curve%s)(q%b)))";
1434 else if (keyno == 1)
1435 format = "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))";
1437 format = "(public-key(ecc(curve%s)(flags eddsa)(q%b)))";
1439 err = gcry_sexp_build (&s_pkey, NULL, format,
1440 openpgp_oid_to_curve (app->app_local->keyattr[keyno].ecc.oid, 1),
1444 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1449 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1451 keybuf = xtrymalloc (len);
1454 gcry_sexp_release (s_pkey);
1455 err = gpg_error_from_syserror ();
1458 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1459 gcry_sexp_release (s_pkey);
1461 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1462 app->app_local->pk[keyno].keylen = len - 1; /* Decrement for trailing '\0' */
1465 /* Set a flag to indicate that we tried to read the key. */
1466 app->app_local->pk[keyno].read_done = 1;
1473 #endif /* GNUPG_MAJOR_VERSION > 1 */
1477 /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3].
1478 This is used by the LEARN command. */
1480 send_keypair_info (app_t app, ctrl_t ctrl, int key)
1482 int keyno = key - 1;
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 >= 0 && keyno <= 2);
1496 if (!app->app_local->pk[keyno].key)
1497 goto leave; /* No such key - ignore. */
1499 err = keygrip_from_canon_sexp (app->app_local->pk[keyno].key,
1500 app->app_local->pk[keyno].keylen,
1505 bin2hex (grip, 20, gripstr);
1507 sprintf (idbuf, "OPENPGP.%d", keyno+1);
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].key;
1584 return gpg_error (GPG_ERR_NO_PUBKEY);
1585 *pklen = app->app_local->pk[keyno].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);
2733 change_rsa_keyattr (app_t app, int keyno, unsigned int nbits,
2734 gpg_error_t (*pincb)(void*, const char *, char **),
2737 gpg_error_t err = 0;
2742 /* Read the current attributes into a buffer. */
2743 relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL);
2745 err = gpg_error (GPG_ERR_CARD);
2746 else if (buflen < 6 || buf[0] != PUBKEY_ALGO_RSA)
2748 /* Attriutes too short or not an RSA key. */
2750 err = gpg_error (GPG_ERR_CARD);
2754 /* We only change n_bits and don't touch anything else. Before we
2755 do so, we round up NBITS to a sensible way in the same way as
2756 gpg's key generation does it. This may help to sort out problems
2757 with a few bits too short keys. */
2758 nbits = ((nbits + 31) / 32) * 32;
2759 buf[1] = (nbits >> 8);
2761 err = change_keyattr (app, keyno, buf, buflen, pincb, pincb_arg);
2769 /* Helper to process an setattr command for name KEY-ATTR.
2770 In (VALUE,VALUELEN), it expects following string:
2771 RSA: "--force <key> <algo> rsa<nbits>"
2772 ECC: "--force <key> <algo> <curvename>"
2775 change_keyattr_from_string (app_t app,
2776 gpg_error_t (*pincb)(void*, const char *, char **),
2778 const void *value, size_t valuelen)
2780 gpg_error_t err = 0;
2782 int key, keyno, algo;
2785 /* VALUE is expected to be a string but not guaranteed to be
2786 terminated. Thus copy it to an allocated buffer first. */
2787 string = xtrymalloc (valuelen+1);
2789 return gpg_error_from_syserror ();
2790 memcpy (string, value, valuelen);
2791 string[valuelen] = 0;
2793 /* Because this function deletes the key we require the string
2794 "--force" in the data to make clear that something serious might
2796 sscanf (string, " --force %d %d %n", &key, &algo, &n);
2799 err = gpg_error (GPG_ERR_INV_DATA);
2804 if (keyno < 0 || keyno > 2)
2805 err = gpg_error (GPG_ERR_INV_ID);
2806 else if (algo == PUBKEY_ALGO_RSA)
2811 nbits = strtoul (string+n+3, NULL, 10);
2813 err = gpg_error (GPG_ERR_INV_DATA);
2814 else if (nbits < 1024)
2815 err = gpg_error (GPG_ERR_TOO_SHORT);
2816 else if (nbits > 4096)
2817 err = gpg_error (GPG_ERR_TOO_LARGE);
2819 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
2821 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
2822 || algo == PUBKEY_ALGO_EDDSA)
2826 const unsigned char *oidbuf;
2829 oidstr = openpgp_curve_to_oid (string+n, NULL);
2832 err = gpg_error (GPG_ERR_INV_DATA);
2836 err = openpgp_oid_from_str (oidstr, &oid);
2840 oidbuf = gcry_mpi_get_opaque (oid, &n);
2843 /* We have enough room at STRING. */
2845 memcpy (string+1, oidbuf+1, oid_len-1);
2846 err = change_keyattr (app, keyno, string, oid_len, pincb, pincb_arg);
2847 gcry_mpi_release (oid);
2850 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
2859 rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
2860 void *pincb_arg, int keyno,
2861 const unsigned char *buf, size_t buflen, int depth)
2864 const unsigned char *tok;
2866 int last_depth1, last_depth2;
2867 const unsigned char *rsa_n = NULL;
2868 const unsigned char *rsa_e = NULL;
2869 const unsigned char *rsa_p = NULL;
2870 const unsigned char *rsa_q = NULL;
2871 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2873 unsigned int maxbits;
2874 unsigned char *template = NULL;
2876 size_t template_len;
2877 unsigned char fprbuf[20];
2880 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA)
2882 log_error (_("unsupported algorithm: %s"), "RSA");
2883 err = gpg_error (GPG_ERR_INV_VALUE);
2887 last_depth1 = depth;
2888 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2889 && depth && depth >= last_depth1)
2893 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2896 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2898 if (tok && toklen == 1)
2900 const unsigned char **mpi;
2905 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2906 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2907 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2908 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2909 default: mpi = NULL; mpi_len = NULL; break;
2913 err = gpg_error (GPG_ERR_DUP_VALUE);
2916 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2920 /* Strip off leading zero bytes and save. */
2921 for (;toklen && !*tok; toklen--, tok++)
2927 /* Skip until end of list. */
2928 last_depth2 = depth;
2929 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2930 && depth && depth >= last_depth2)
2935 /* Parse other attributes. */
2936 last_depth1 = depth;
2937 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2938 && depth && depth >= last_depth1)
2942 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2945 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2947 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2949 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2953 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2955 created_at = created_at*10 + (*tok - '0');
2958 /* Skip until end of list. */
2959 last_depth2 = depth;
2960 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2961 && depth && depth >= last_depth2)
2968 /* Check that we have all parameters and that they match the card
2972 log_error (_("creation timestamp missing\n"));
2973 err = gpg_error (GPG_ERR_INV_VALUE);
2977 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
2978 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2980 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2981 nbits, (unsigned int)rsa_n_len);
2982 if (nbits && nbits != maxbits
2983 && app->app_local->extcap.algo_attr_change)
2985 /* Try to switch the key to a new length. */
2986 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
2988 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
2990 if (nbits != maxbits)
2992 log_error (_("RSA modulus missing or not of size %d bits\n"),
2994 err = gpg_error (GPG_ERR_BAD_SECKEY);
2998 maxbits = app->app_local->keyattr[keyno].rsa.e_bits;
2999 if (maxbits > 32 && !app->app_local->extcap.is_v2)
3000 maxbits = 32; /* Our code for v1 does only support 32 bits. */
3001 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
3002 if (nbits < 2 || nbits > maxbits)
3004 log_error (_("RSA public exponent missing or larger than %d bits\n"),
3006 err = gpg_error (GPG_ERR_BAD_SECKEY);
3010 maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2;
3011 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
3012 if (nbits != maxbits)
3014 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3016 err = gpg_error (GPG_ERR_BAD_SECKEY);
3019 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
3020 if (nbits != maxbits)
3022 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3024 err = gpg_error (GPG_ERR_BAD_SECKEY);
3028 /* We need to remove the cached public key. */
3029 xfree (app->app_local->pk[keyno].key);
3030 app->app_local->pk[keyno].key = NULL;
3031 app->app_local->pk[keyno].keylen = 0;
3032 app->app_local->pk[keyno].read_done = 0;
3035 if (app->app_local->extcap.is_v2)
3037 unsigned char *rsa_u, *rsa_dp, *rsa_dq;
3038 size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
3039 gcry_mpi_t mpi_e, mpi_p, mpi_q;
3040 gcry_mpi_t mpi_u = gcry_mpi_snew (0);
3041 gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
3042 gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
3043 gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
3046 /* Calculate the u, dp and dq components needed by RSA_CRT cards */
3047 gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
3048 gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
3049 gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
3051 gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
3052 gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
3053 gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
3054 gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
3055 gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
3057 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
3058 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
3059 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
3061 gcry_mpi_release (mpi_e);
3062 gcry_mpi_release (mpi_p);
3063 gcry_mpi_release (mpi_q);
3064 gcry_mpi_release (mpi_u);
3065 gcry_mpi_release (mpi_dp);
3066 gcry_mpi_release (mpi_dq);
3067 gcry_mpi_release (mpi_tmp);
3069 /* Build the private key template as described in section 4.3.3.7 of
3070 the OpenPGP card specs version 2.0. */
3071 err = build_privkey_template (app, keyno,
3079 &template, &template_len);
3087 /* Prepare for storing the key. */
3088 err = verify_chv3 (app, pincb, pincb_arg);
3092 /* Store the key. */
3093 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3094 exmode = 1; /* Use extended length w/o a limit. */
3095 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3099 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3100 template, template_len);
3104 /* Build the private key template as described in section 4.3.3.6 of
3105 the OpenPGP card specs version 1.1:
3106 0xC0 <length> public exponent
3107 0xC1 <length> prime p
3108 0xC2 <length> prime q
3110 assert (rsa_e_len <= 4);
3111 template_len = (1 + 1 + 4
3113 + 1 + 1 + rsa_q_len);
3114 template = tp = xtrymalloc_secure (template_len);
3117 err = gpg_error_from_syserror ();
3122 memcpy (tp, rsa_e, rsa_e_len);
3125 /* Right justify E. */
3126 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
3127 memset (tp, 0, 4-rsa_e_len);
3133 memcpy (tp, rsa_p, rsa_p_len);
3138 memcpy (tp, rsa_q, rsa_q_len);
3141 assert (tp - template == template_len);
3143 /* Prepare for storing the key. */
3144 err = verify_chv3 (app, pincb, pincb_arg);
3148 /* Store the key. */
3149 err = iso7816_put_data (app->slot, 0,
3150 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
3151 template, template_len);
3155 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3159 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
3160 rsa_n, rsa_n_len, rsa_e, rsa_e_len);
3172 ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3173 void *pincb_arg, int keyno,
3174 const unsigned char *buf, size_t buflen, int depth)
3177 const unsigned char *tok;
3179 int last_depth1, last_depth2;
3180 const unsigned char *ecc_q = NULL;
3181 const unsigned char *ecc_d = NULL;
3182 size_t ecc_q_len, ecc_d_len;
3184 const char *oidstr = NULL;
3185 int flag_djb_tweak = 0;
3188 const unsigned char *oidbuf = NULL;
3191 unsigned char fprbuf[20];
3193 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3194 curve = "NIST P-256" */
3195 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3196 curve = "secp256k1" */
3197 /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)):
3198 curve = "Ed25519" */
3199 last_depth1 = depth;
3200 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3201 && depth && depth >= last_depth1)
3205 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3208 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3211 if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
3213 unsigned char *curve;
3215 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3218 curve = xtrymalloc (toklen+1);
3221 err = gpg_error_from_syserror ();
3225 memcpy (curve, tok, toklen);
3227 oidstr = openpgp_curve_to_oid (curve, NULL);
3230 else if (tok && toklen == 5 && !memcmp (tok, "flags", 5))
3232 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3237 if ((toklen == 5 && !memcmp (tok, "eddsa", 5))
3238 || (toklen == 9 && !memcmp (tok, "djb-tweak", 9)))
3242 else if (tok && toklen == 1)
3244 const unsigned char **buf2;
3249 case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break;
3250 case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; break;
3251 default: buf2 = NULL; buf2len = NULL; break;
3255 err = gpg_error (GPG_ERR_DUP_VALUE);
3258 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3260 if (tok && buf2 && !flag_djb_tweak)
3261 /* It's MPI. Strip off leading zero bytes and save. */
3262 for (;toklen && !*tok; toklen--, tok++)
3268 /* Skip until end of list. */
3269 last_depth2 = depth;
3270 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3271 && depth && depth >= last_depth2)
3276 /* Parse other attributes. */
3277 last_depth1 = depth;
3278 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3279 && depth && depth >= last_depth1)
3283 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3286 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3288 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3290 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3294 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3296 created_at = created_at*10 + (*tok - '0');
3299 /* Skip until end of list. */
3300 last_depth2 = depth;
3301 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3302 && depth && depth >= last_depth2)
3309 /* Check that we have all parameters and that they match the card
3313 log_error (_("unsupported curve\n"));
3314 err = gpg_error (GPG_ERR_INV_VALUE);
3319 log_error (_("creation timestamp missing\n"));
3320 err = gpg_error (GPG_ERR_INV_VALUE);
3323 if (flag_djb_tweak && keyno != 1)
3324 algo = PUBKEY_ALGO_EDDSA;
3325 else if (keyno == 1)
3326 algo = PUBKEY_ALGO_ECDH;
3328 algo = PUBKEY_ALGO_ECDSA;
3330 err = openpgp_oid_from_str (oidstr, &oid);
3333 oidbuf = gcry_mpi_get_opaque (oid, &n);
3337 err = gpg_error_from_syserror ();
3338 gcry_mpi_release (oid);
3342 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC
3343 || app->app_local->keyattr[keyno].ecc.oid != oidstr
3344 || app->app_local->keyattr[keyno].ecc.flags != flag_djb_tweak)
3346 if (app->app_local->extcap.algo_attr_change)
3348 unsigned char keyattr[oid_len];
3351 memcpy (keyattr+1, oidbuf+1, oid_len-1);
3352 err = change_keyattr (app, keyno, keyattr, oid_len, pincb, pincb_arg);
3358 log_error ("key attribute on card doesn't match\n");
3359 err = gpg_error (GPG_ERR_INV_VALUE);
3365 log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
3367 /* We need to remove the cached public key. */
3368 xfree (app->app_local->pk[keyno].key);
3369 app->app_local->pk[keyno].key = NULL;
3370 app->app_local->pk[keyno].keylen = 0;
3371 app->app_local->pk[keyno].read_done = 0;
3373 if (app->app_local->extcap.is_v2)
3375 /* Build the private key template as described in section 4.3.3.7 of
3376 the OpenPGP card specs version 2.0. */
3377 unsigned char *template;
3378 size_t template_len;
3381 err = build_ecc_privkey_template (app, keyno,
3383 &template, &template_len);
3387 /* Prepare for storing the key. */
3388 err = verify_chv3 (app, pincb, pincb_arg);
3395 /* Store the key. */
3396 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3397 exmode = 1; /* Use extended length w/o a limit. */
3398 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3402 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3403 template, template_len);
3407 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3411 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3415 err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
3416 ecc_q, ecc_q_len, "\x03\x01\x08\x07", (size_t)4);
3420 gcry_mpi_release (oid);
3424 /* Handle the WRITEKEY command for OpenPGP. This function expects a
3425 canonical encoded S-expression with the secret key in KEYDATA and
3426 its length (for assertions) in KEYDATALEN. KEYID needs to be the
3427 usual keyid which for OpenPGP is the string "OPENPGP.n" with
3428 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
3429 get overwritten. PINCB and PINCB_ARG are the usual arguments for
3430 the pinentry callback. */
3432 do_writekey (app_t app, ctrl_t ctrl,
3433 const char *keyid, unsigned int flags,
3434 gpg_error_t (*pincb)(void*, const char *, char **),
3436 const unsigned char *keydata, size_t keydatalen)
3439 int force = (flags & 1);
3441 const unsigned char *buf, *tok;
3442 size_t buflen, toklen;
3447 if (!strcmp (keyid, "OPENPGP.1"))
3449 else if (!strcmp (keyid, "OPENPGP.2"))
3451 else if (!strcmp (keyid, "OPENPGP.3"))
3454 return gpg_error (GPG_ERR_INV_ID);
3456 err = does_key_exist (app, keyno, 0, force);
3462 Parse the S-expression
3465 buflen = keydatalen;
3467 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3469 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3471 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
3475 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
3476 log_info ("protected-private-key passed to writekey\n");
3477 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
3478 log_info ("shadowed-private-key passed to writekey\n");
3479 err = gpg_error (GPG_ERR_BAD_SECKEY);
3482 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3484 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3486 if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
3487 err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3488 else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
3489 err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3492 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
3502 /* Handle the GENKEY command. */
3504 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
3506 gpg_error_t (*pincb)(void*, const char *, char **),
3511 unsigned char fprbuf[20];
3512 const unsigned char *keydata, *m, *e;
3513 unsigned char *buffer = NULL;
3514 size_t buflen, keydatalen, mlen, elen;
3516 int keyno = atoi (keynostr) - 1;
3517 int force = (flags & 1);
3521 unsigned int keybits;
3523 if (keyno < 0 || keyno > 2)
3524 return gpg_error (GPG_ERR_INV_ID);
3526 /* We flush the cache to increase the traffic before a key
3527 generation. This _might_ help a card to gather more entropy. */
3530 /* Obviously we need to remove the cached public key. */
3531 xfree (app->app_local->pk[keyno].key);
3532 app->app_local->pk[keyno].key = NULL;
3533 app->app_local->pk[keyno].keylen = 0;
3534 app->app_local->pk[keyno].read_done = 0;
3536 /* Check whether a key already exists. */
3537 rc = does_key_exist (app, keyno, 1, force);
3541 /* Because we send the key parameter back via status lines we need
3542 to put a limit on the max. allowed keysize. 2048 bit will
3543 already lead to a 527 byte long status line and thus a 4096 bit
3544 key would exceed the Assuan line length limit. */
3545 keybits = app->app_local->keyattr[keyno].rsa.n_bits;
3547 return gpg_error (GPG_ERR_TOO_LARGE);
3549 /* Prepare for key generation by verifying the Admin PIN. */
3550 rc = verify_chv3 (app, pincb, pincb_arg);
3554 /* Test whether we will need extended length mode. (1900 is an
3555 arbitrary length which for sure fits into a short apdu.) */
3556 if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
3558 exmode = 1; /* Use extended length w/o a limit. */
3559 le_value = app->app_local->extcap.max_rsp_data;
3560 /* No need to check le_value because it comes from a 16 bit
3561 value and thus can't create an overflow on a 32 bit
3567 le_value = 256; /* Use legacy value. */
3570 log_info (_("please wait while key is being generated ...\n"));
3571 start_at = time (NULL);
3572 rc = iso7816_generate_keypair
3573 /* # warning key generation temporary replaced by reading an existing key. */
3574 /* rc = iso7816_read_public_key */
3576 (const unsigned char*)(keyno == 0? "\xB6" :
3577 keyno == 1? "\xB8" : "\xA4"), 2,
3582 rc = gpg_error (GPG_ERR_CARD);
3583 log_error (_("generating key failed\n"));
3586 log_info (_("key generation completed (%d seconds)\n"),
3587 (int)(time (NULL) - start_at));
3589 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
3592 rc = gpg_error (GPG_ERR_CARD);
3593 log_error (_("response does not contain the public key data\n"));
3597 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
3600 rc = gpg_error (GPG_ERR_CARD);
3601 log_error (_("response does not contain the RSA modulus\n"));
3604 /* log_printhex ("RSA n:", m, mlen); */
3605 send_key_data (ctrl, "n", m, mlen);
3607 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
3610 rc = gpg_error (GPG_ERR_CARD);
3611 log_error (_("response does not contain the RSA public exponent\n"));
3614 /* log_printhex ("RSA e:", e, elen); */
3615 send_key_data (ctrl, "e", e, elen);
3617 created_at = createtime? createtime : gnupg_get_time ();
3618 sprintf (numbuf, "%lu", (unsigned long)created_at);
3619 send_status_info (ctrl, "KEY-CREATED-AT",
3620 numbuf, (size_t)strlen(numbuf), NULL, 0);
3622 rc = store_fpr (app, keyno, (u32)created_at, fprbuf, PUBKEY_ALGO_RSA,
3626 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
3635 static unsigned long
3636 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
3641 ul = (value[0] << 16) | (value[1] << 8) | value[2];
3644 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
3650 static unsigned long
3651 get_sig_counter (app_t app)
3654 unsigned char *value;
3658 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
3661 ul = convert_sig_counter_value (value, valuelen);
3667 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
3669 const unsigned char *fpr;
3670 unsigned char *buffer;
3674 assert (keyno >= 0 && keyno <= 2);
3676 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
3679 log_error (_("error reading application data\n"));
3680 return gpg_error (GPG_ERR_GENERAL);
3682 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
3683 if (!fpr || n != 60)
3686 log_error (_("error reading fingerprint DO\n"));
3687 return gpg_error (GPG_ERR_GENERAL);
3690 for (i=0; i < 20; i++)
3691 if (sha1fpr[i] != fpr[i])
3694 log_info (_("fingerprint on card does not match requested one\n"));
3695 return gpg_error (GPG_ERR_WRONG_SECKEY);
3702 /* If a fingerprint has been specified check it against the one on the
3703 card. This allows for a meaningful error message in case the key
3704 on the card has been replaced but the shadow information known to
3705 gpg has not been updated. If there is no fingerprint we assume
3706 that this is okay. */
3708 check_against_given_fingerprint (app_t app, const char *fpr, int key)
3710 unsigned char tmp[20];
3714 for (s=fpr, n=0; hexdigitp (s); s++, n++)
3717 return gpg_error (GPG_ERR_INV_ID);
3721 return gpg_error (GPG_ERR_INV_ID);
3723 for (s=fpr, n=0; n < 20; s += 2, n++)
3724 tmp[n] = xtoi_2 (s);
3725 return compare_fingerprint (app, key-1, tmp);
3730 /* Compute a digital signature on INDATA which is expected to be the
3731 raw message digest. For this application the KEYIDSTR consists of
3732 the serialnumber and the fingerprint delimited by a slash.
3734 Note that this function may return the error code
3735 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3736 not match the one required for the requested action (e.g. the
3737 serial number does not match).
3739 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3740 operation to the auth command.
3743 do_sign (app_t app, const char *keyidstr, int hashalgo,
3744 gpg_error_t (*pincb)(void*, const char *, char **),
3746 const void *indata, size_t indatalen,
3747 unsigned char **outdata, size_t *outdatalen )
3749 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3750 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3751 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3752 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
3753 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3754 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3755 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3756 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3757 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3759 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3760 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3761 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3763 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3764 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3765 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3767 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3768 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3769 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3772 unsigned char data[19+64];
3774 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3777 const char *fpr = NULL;
3778 unsigned long sigcount;
3780 int exmode, le_value;
3782 if (!keyidstr || !*keyidstr)
3783 return gpg_error (GPG_ERR_INV_VALUE);
3785 /* Strip off known prefixes. */
3786 #define X(a,b,c,d) \
3787 if (hashalgo == GCRY_MD_ ## a \
3789 && indatalen == sizeof b ## _prefix + (c) \
3790 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3792 indata = (const char*)indata + sizeof b ## _prefix; \
3793 indatalen -= sizeof b ## _prefix; \
3796 if (indatalen == 20)
3797 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3798 else X(SHA1, sha1, 20, 1)
3799 else X(RMD160, rmd160, 20, 1)
3800 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3801 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3802 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3803 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3804 else if ((indatalen == 28 || indatalen == 32
3805 || indatalen == 48 || indatalen ==64)
3806 && app->app_local->extcap.is_v2)
3807 ; /* Assume a plain SHA-3 digest has been given. */
3810 log_error (_("card does not support digest algorithm %s\n"),
3811 gcry_md_algo_name (hashalgo));
3812 /* Or the supplied digest length does not match an algorithm. */
3813 return gpg_error (GPG_ERR_INV_VALUE);
3817 /* Check whether an OpenPGP card of any version has been requested. */
3818 if (!strcmp (keyidstr, "OPENPGP.1"))
3820 else if (!strcmp (keyidstr, "OPENPGP.3"))
3822 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3823 return gpg_error (GPG_ERR_INV_ID);
3826 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3829 return gpg_error (GPG_ERR_INV_ID);
3831 ; /* no fingerprint given: we allow this for now. */
3835 return gpg_error (GPG_ERR_INV_ID);
3837 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3838 tmp_sn[n] = xtoi_2 (s);
3840 if (app->serialnolen != 16)
3841 return gpg_error (GPG_ERR_INV_CARD);
3842 if (memcmp (app->serialno, tmp_sn, 16))
3843 return gpg_error (GPG_ERR_WRONG_CARD);
3846 /* If a fingerprint has been specified check it against the one on
3847 the card. This is allows for a meaningful error message in case
3848 the key on the card has been replaced but the shadow information
3849 known to gpg was not updated. If there is no fingerprint, gpg
3850 will detect a bogus signature anyway due to the
3851 verify-after-signing feature. */
3852 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3856 /* Concatenate prefix and digest. */
3858 if (hashalgo == GCRY_MD_ ## a && (d) ) \
3860 datalen = sizeof b ## _prefix + indatalen; \
3861 assert (datalen <= sizeof data); \
3862 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3863 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3867 || app->app_local->keyattr[use_auth? 2: 0].key_type == KEY_TYPE_RSA)
3870 else X(RMD160, rmd160, 1)
3871 else X(SHA224, sha224, app->app_local->extcap.is_v2)
3872 else X(SHA256, sha256, app->app_local->extcap.is_v2)
3873 else X(SHA384, sha384, app->app_local->extcap.is_v2)
3874 else X(SHA512, sha512, app->app_local->extcap.is_v2)
3876 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3880 datalen = indatalen;
3881 memcpy (data, indata, indatalen);
3885 /* Redirect to the AUTH command if asked to. */
3888 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3890 outdata, outdatalen);
3893 /* Show the number of signature done using this key. */
3894 sigcount = get_sig_counter (app);
3895 log_info (_("signatures created so far: %lu\n"), sigcount);
3897 /* Check CHV if needed. */
3898 if (!app->did_chv1 || app->force_chv1 )
3902 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3908 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3909 sync, thus we verify CHV2 here using the given PIN. Cards
3910 with version2 to not have the need for a separate CHV2 and
3911 internally use just one. Obviously we can't do that if the
3912 pinpad has been used. */
3913 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3915 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3916 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3917 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3920 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3922 flush_cache_after_error (app);
3931 if (app->app_local->cardcap.ext_lc_le)
3933 exmode = 1; /* Use extended length. */
3934 le_value = app->app_local->extcap.max_rsp_data;
3941 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3942 outdata, outdatalen);
3946 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3947 on INDATA which is expected to be the raw message digest. For this
3948 application the KEYIDSTR consists of the serialnumber and the
3949 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3952 Note that this function may return the error code
3953 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3954 not match the one required for the requested action (e.g. the
3955 serial number does not match). */
3957 do_auth (app_t app, const char *keyidstr,
3958 gpg_error_t (*pincb)(void*, const char *, char **),
3960 const void *indata, size_t indatalen,
3961 unsigned char **outdata, size_t *outdatalen )
3964 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3967 const char *fpr = NULL;
3969 if (!keyidstr || !*keyidstr)
3970 return gpg_error (GPG_ERR_INV_VALUE);
3971 if (app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
3972 && indatalen > 101) /* For a 2048 bit key. */
3973 return gpg_error (GPG_ERR_INV_VALUE);
3975 if (app->app_local->keyattr[2].key_type == KEY_TYPE_ECC)
3977 if (!app->app_local->keyattr[2].ecc.flags
3978 && (indatalen == 51 || indatalen == 67 || indatalen == 83))
3980 const char *p = (const char *)indata + 19;
3986 const char *p = (const char *)indata + 15;
3992 /* Check whether an OpenPGP card of any version has been requested. */
3993 if (!strcmp (keyidstr, "OPENPGP.3"))
3995 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3996 return gpg_error (GPG_ERR_INV_ID);
3999 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4002 return gpg_error (GPG_ERR_INV_ID);
4004 ; /* no fingerprint given: we allow this for now. */
4008 return gpg_error (GPG_ERR_INV_ID);
4010 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4011 tmp_sn[n] = xtoi_2 (s);
4013 if (app->serialnolen != 16)
4014 return gpg_error (GPG_ERR_INV_CARD);
4015 if (memcmp (app->serialno, tmp_sn, 16))
4016 return gpg_error (GPG_ERR_WRONG_CARD);
4019 /* If a fingerprint has been specified check it against the one on
4020 the card. This is allows for a meaningful error message in case
4021 the key on the card has been replaced but the shadow information
4022 known to gpg was not updated. If there is no fingerprint, gpg
4023 will detect a bogus signature anyway due to the
4024 verify-after-signing feature. */
4025 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
4029 rc = verify_chv2 (app, pincb, pincb_arg);
4032 int exmode, le_value;
4034 if (app->app_local->cardcap.ext_lc_le)
4036 exmode = 1; /* Use extended length. */
4037 le_value = app->app_local->extcap.max_rsp_data;
4044 rc = iso7816_internal_authenticate (app->slot, exmode,
4045 indata, indatalen, le_value,
4046 outdata, outdatalen);
4053 do_decipher (app_t app, const char *keyidstr,
4054 gpg_error_t (*pincb)(void*, const char *, char **),
4056 const void *indata, size_t indatalen,
4057 unsigned char **outdata, size_t *outdatalen,
4058 unsigned int *r_info)
4061 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
4064 const char *fpr = NULL;
4065 int exmode, le_value;
4066 unsigned char *fixbuf = NULL;
4070 if (!keyidstr || !*keyidstr || !indatalen)
4071 return gpg_error (GPG_ERR_INV_VALUE);
4073 /* Check whether an OpenPGP card of any version has been requested. */
4074 if (!strcmp (keyidstr, "OPENPGP.2"))
4076 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4077 return gpg_error (GPG_ERR_INV_ID);
4080 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4083 return gpg_error (GPG_ERR_INV_ID);
4085 ; /* no fingerprint given: we allow this for now. */
4089 return gpg_error (GPG_ERR_INV_ID);
4091 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4092 tmp_sn[n] = xtoi_2 (s);
4094 if (app->serialnolen != 16)
4095 return gpg_error (GPG_ERR_INV_CARD);
4096 if (memcmp (app->serialno, tmp_sn, 16))
4097 return gpg_error (GPG_ERR_WRONG_CARD);
4100 /* If a fingerprint has been specified check it against the one on
4101 the card. This is allows for a meaningful error message in case
4102 the key on the card has been replaced but the shadow information
4103 known to gpg was not updated. If there is no fingerprint, the
4104 decryption won't produce the right plaintext anyway. */
4105 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
4109 rc = verify_chv2 (app, pincb, pincb_arg);
4113 if (indatalen == 16 + 1 || indatalen == 32 + 1)
4114 /* PSO:DECIPHER with symmetric key. */
4116 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA)
4118 /* We might encounter a couple of leading zeroes in the
4119 cryptogram. Due to internal use of MPIs these leading zeroes
4120 are stripped. However the OpenPGP card expects exactly 128
4121 bytes for the cryptogram (for a 1k key). Thus we need to fix
4122 it up. We do this for up to 16 leading zero bytes; a
4123 cryptogram with more than this is with a very high
4124 probability anyway broken. If a signed conversion was used
4125 we may also encounter one leading zero followed by the correct
4126 length. We fix that as well. */
4127 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
4128 fixuplen = 128 - indatalen;
4129 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
4130 fixuplen = 192 - indatalen;
4131 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
4132 fixuplen = 256 - indatalen;
4133 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
4134 fixuplen = 384 - indatalen;
4135 else if (indatalen >= (512-16) && indatalen < 512) /* 4096 bit key. */
4136 fixuplen = 512 - indatalen;
4137 else if (!*(const char *)indata && (indatalen == 129
4141 || indatalen == 513))
4148 /* While we have to prepend stuff anyway, we can also
4149 include the padding byte here so that iso1816_decipher
4150 does not need to do another data mangling. */
4153 fixbuf = xtrymalloc (fixuplen + indatalen);
4155 return gpg_error_from_syserror ();
4157 memset (fixbuf, 0, fixuplen);
4158 memcpy (fixbuf+fixuplen, indata, indatalen);
4160 indatalen = fixuplen + indatalen;
4161 padind = -1; /* Already padded. */
4163 else if (fixuplen < 0)
4165 /* We use the extra leading zero as the padding byte. */
4169 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
4172 fixbuf = xtrymalloc (fixuplen + indatalen);
4174 return gpg_error_from_syserror ();
4176 /* Build 'Cipher DO' */
4178 fixbuf[1] = (char)(indatalen+5);
4181 fixbuf[4] = (char)(indatalen+2);
4183 fixbuf[6] = (char)indatalen;
4184 memcpy (fixbuf+fixuplen, indata, indatalen);
4186 indatalen = fixuplen + indatalen;
4191 return gpg_error (GPG_ERR_INV_VALUE);
4193 if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
4195 exmode = 1; /* Extended length w/o a limit. */
4196 le_value = app->app_local->extcap.max_rsp_data;
4198 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
4200 exmode = -254; /* Command chaining with max. 254 bytes. */
4204 exmode = le_value = 0;
4206 rc = iso7816_decipher (app->slot, exmode,
4207 indata, indatalen, le_value, padind,
4208 outdata, outdatalen);
4211 if (gpg_err_code (rc) == GPG_ERR_CARD /* actual SW is 0x640a */
4212 && app->app_local->manufacturer == 5
4213 && app->card_version == 0x0200)
4214 log_info ("NOTE: Cards with manufacturer id 5 and s/n <= 346 (0x15a)"
4215 " do not work with encryption keys > 2048 bits\n");
4217 *r_info |= APP_DECIPHER_INFO_NOPAD;
4223 /* Perform a simple verify operation for CHV1 and CHV2, so that
4224 further operations won't ask for CHV2 and it is possible to do a
4225 cheap check on the PIN: If there is something wrong with the PIN
4226 entry system, only the regular CHV will get blocked and not the
4227 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
4228 optional fingerprint part will be ignored.
4230 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
4231 the "[CHV3]" being a literal string: The Admin Pin is checked if
4232 and only if the retry counter is still at 3. */
4234 do_check_pin (app_t app, const char *keyidstr,
4235 gpg_error_t (*pincb)(void*, const char *, char **),
4238 unsigned char tmp_sn[20];
4243 if (!keyidstr || !*keyidstr)
4244 return gpg_error (GPG_ERR_INV_VALUE);
4246 /* Check whether an OpenPGP card of any version has been requested. */
4247 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4248 return gpg_error (GPG_ERR_INV_ID);
4250 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4253 return gpg_error (GPG_ERR_INV_ID);
4255 ; /* No fingerprint given: we allow this for now. */
4257 ; /* We ignore a fingerprint. */
4258 else if (!strcmp (s, "[CHV3]") )
4261 return gpg_error (GPG_ERR_INV_ID);
4263 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4264 tmp_sn[n] = xtoi_2 (s);
4266 if (app->serialnolen != 16)
4267 return gpg_error (GPG_ERR_INV_CARD);
4268 if (memcmp (app->serialno, tmp_sn, 16))
4269 return gpg_error (GPG_ERR_WRONG_CARD);
4271 /* Yes, there is a race conditions: The user might pull the card
4272 right here and we won't notice that. However this is not a
4273 problem and the check above is merely for a graceful failure
4274 between operations. */
4279 unsigned char *value;
4283 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
4284 if (!relptr || valuelen < 7)
4286 log_error (_("error retrieving CHV status from card\n"));
4288 return gpg_error (GPG_ERR_CARD);
4295 log_info (_("card is permanently locked!\n"));
4296 return gpg_error (GPG_ERR_BAD_PIN);
4300 log_info (_("verification of Admin PIN is currently prohibited "
4301 "through this command\n"));
4302 return gpg_error (GPG_ERR_GENERAL);
4305 app->did_chv3 = 0; /* Force verification. */
4306 return verify_chv3 (app, pincb, pincb_arg);
4309 return verify_chv2 (app, pincb, pincb_arg);
4313 /* Show information about card capabilities. */
4315 show_caps (struct app_local_s *s)
4317 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
4318 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
4319 if (s->extcap.get_challenge)
4320 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
4321 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
4322 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
4323 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
4324 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
4325 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
4326 if (s->extcap.sm_supported)
4327 log_printf (" (%s)", s->extcap.sm_algo==2? "3DES":
4328 (s->extcap.sm_algo==2? "AES-128" : "AES-256"));
4329 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
4330 log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
4331 log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
4332 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
4333 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
4334 log_info ("Status Indicator: %02X\n", s->status_indicator);
4335 log_info ("Symmetric crypto: %s\n", s->extcap.has_decrypt? "yes":"no");
4336 log_info ("Button..........: %s\n", s->extcap.has_button? "yes":"no");
4338 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
4339 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
4343 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
4346 parse_historical (struct app_local_s *apploc,
4347 const unsigned char * buffer, size_t buflen)
4349 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
4352 log_error ("warning: historical bytes are too short\n");
4353 return; /* Too short. */
4357 log_error ("warning: bad category indicator in historical bytes\n");
4361 /* Skip category indicator. */
4365 /* Get the status indicator. */
4366 apploc->status_indicator = buffer[buflen-3];
4369 /* Parse the compact TLV. */
4372 unsigned int tag = (*buffer & 0xf0) >> 4;
4373 unsigned int len = (*buffer & 0x0f);
4376 log_error ("warning: bad Compact-TLV in historical bytes\n");
4377 return; /* Error. */
4381 if (tag == 7 && len == 3)
4383 /* Card capabilities. */
4384 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
4385 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
4394 * Check if the OID in an DER encoding is available by GnuPG/libgcrypt,
4395 * and return the constant string in dotted decimal form.
4396 * Return NULL if not available.
4397 * The constant string is not allocated dynamically, never free it.
4400 ecc_oid (unsigned char *buf, size_t buflen)
4405 unsigned char *oidbuf;
4407 oidbuf = xtrymalloc (buflen + 1);
4411 memcpy (oidbuf+1, buf, buflen);
4413 oid = gcry_mpi_set_opaque (NULL, oidbuf, (buflen+1) * 8);
4420 oidstr = openpgp_oid_to_str (oid);
4421 gcry_mpi_release (oid);
4425 result = openpgp_curve_to_oid (oidstr, NULL);
4431 /* Parse and optionally show the algorithm attributes for KEYNO.
4432 KEYNO must be in the range 0..2. */
4434 parse_algorithm_attribute (app_t app, int keyno)
4436 unsigned char *buffer;
4439 const char desc[3][5] = {"sign", "encr", "auth"};
4441 assert (keyno >=0 && keyno <= 2);
4443 app->app_local->keyattr[keyno].key_type = KEY_TYPE_RSA;
4444 app->app_local->keyattr[keyno].rsa.n_bits = 0;
4446 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
4449 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
4454 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
4460 log_info ("Key-Attr-%s ..: ", desc[keyno]);
4461 if (*buffer == PUBKEY_ALGO_RSA && (buflen == 5 || buflen == 6))
4463 app->app_local->keyattr[keyno].rsa.n_bits = (buffer[1]<<8 | buffer[2]);
4464 app->app_local->keyattr[keyno].rsa.e_bits = (buffer[3]<<8 | buffer[4]);
4465 app->app_local->keyattr[keyno].rsa.format = 0;
4467 app->app_local->keyattr[keyno].rsa.format = RSA_STD;
4469 app->app_local->keyattr[keyno].rsa.format = (buffer[5] == 0? RSA_STD :
4470 buffer[5] == 1? RSA_STD_N :
4471 buffer[5] == 2? RSA_CRT :
4472 buffer[5] == 3? RSA_CRT_N :
4477 ("RSA, n=%u, e=%u, fmt=%s\n",
4478 app->app_local->keyattr[keyno].rsa.n_bits,
4479 app->app_local->keyattr[keyno].rsa.e_bits,
4480 app->app_local->keyattr[keyno].rsa.format == RSA_STD? "std" :
4481 app->app_local->keyattr[keyno].rsa.format == RSA_STD_N?"std+n":
4482 app->app_local->keyattr[keyno].rsa.format == RSA_CRT? "crt" :
4483 app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N?"crt+n":"?");
4485 else if (*buffer == PUBKEY_ALGO_ECDH || *buffer == PUBKEY_ALGO_ECDSA
4486 || *buffer == PUBKEY_ALGO_EDDSA)
4488 const char *oid = ecc_oid (buffer + 1, buflen - 1);
4491 log_printhex ("Curve with OID not supported: ", buffer+1, buflen-1);
4494 app->app_local->keyattr[keyno].key_type = KEY_TYPE_ECC;
4495 app->app_local->keyattr[keyno].ecc.oid = oid;
4496 if (*buffer == PUBKEY_ALGO_EDDSA
4497 || (*buffer == PUBKEY_ALGO_ECDH
4498 && !strcmp (app->app_local->keyattr[keyno].ecc.oid,
4499 "1.3.6.1.4.1.3029.1.5.1")))
4500 app->app_local->keyattr[keyno].ecc.flags = ECC_FLAG_DJB_TWEAK;
4502 app->app_local->keyattr[keyno].ecc.flags = 0;
4505 ("ECC, curve=%s%s\n", app->app_local->keyattr[keyno].ecc.oid,
4506 !app->app_local->keyattr[keyno].ecc.flags ? "":
4507 keyno==1? " (djb-tweak)": " (eddsa)");
4510 else if (opt.verbose)
4511 log_printhex ("", buffer, buflen);
4516 /* Select the OpenPGP application on the card in SLOT. This function
4517 must be used before any other OpenPGP application functions. */
4519 app_select_openpgp (app_t app)
4521 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
4522 int slot = app->slot;
4524 unsigned char *buffer;
4528 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
4529 special flag value. */
4530 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
4533 unsigned int manufacturer;
4535 app->apptype = "OPENPGP";
4540 app->app_local = NULL;
4542 /* The OpenPGP card returns the serial number as part of the
4543 AID; because we prefer to use OpenPGP serial numbers, we
4544 replace a possibly already set one from a EF.GDO with this
4545 one. Note, that for current OpenPGP cards, no EF.GDO exists
4546 and thus it won't matter at all. */
4547 rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
4553 log_printhex ("", buffer, buflen);
4556 app->card_version = buffer[6] << 8;
4557 app->card_version |= buffer[7];
4558 manufacturer = (buffer[8]<<8 | buffer[9]);
4560 xfree (app->serialno);
4561 app->serialno = buffer;
4562 app->serialnolen = buflen;
4564 app->app_local = xtrycalloc (1, sizeof *app->app_local);
4565 if (!app->app_local)
4567 rc = gpg_error (gpg_err_code_from_errno (errno));
4571 app->app_local->manufacturer = manufacturer;
4573 if (app->card_version >= 0x0200)
4574 app->app_local->extcap.is_v2 = 1;
4577 /* Read the historical bytes. */
4578 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
4583 log_info ("Historical Bytes: ");
4584 log_printhex ("", buffer, buflen);
4586 parse_historical (app->app_local, buffer, buflen);
4590 /* Read the force-chv1 flag. */
4591 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
4594 log_error (_("can't access %s - invalid OpenPGP card?\n"),
4595 "CHV Status Bytes");
4598 app->force_chv1 = (buflen && *buffer == 0);
4601 /* Read the extended capabilities. */
4602 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
4605 log_error (_("can't access %s - invalid OpenPGP card?\n"),
4606 "Extended Capability Flags" );
4611 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
4612 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
4613 app->app_local->extcap.key_import = !!(*buffer & 0x20);
4614 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
4615 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
4616 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
4617 app->app_local->extcap.has_decrypt = !!(*buffer & 0x02);
4621 /* Available with v2 cards. */
4622 app->app_local->extcap.sm_algo = buffer[1];
4623 app->app_local->extcap.max_get_challenge
4624 = (buffer[2] << 8 | buffer[3]);
4625 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
4626 app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
4627 app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
4631 /* Some of the first cards accidently don't set the
4632 CHANGE_FORCE_CHV bit but allow it anyway. */
4633 if (app->card_version <= 0x0100 && manufacturer == 1)
4634 app->app_local->extcap.change_force_chv = 1;
4636 /* Check optional DO of "General Feature Management" for button. */
4637 relptr = get_one_do (app, 0x7f74, &buffer, &buflen, NULL);
4639 /* It must be: 03 81 01 20 */
4640 app->app_local->extcap.has_button = 1;
4642 parse_login_data (app);
4645 show_caps (app->app_local);
4647 parse_algorithm_attribute (app, 0);
4648 parse_algorithm_attribute (app, 1);
4649 parse_algorithm_attribute (app, 2);
4651 if (opt.verbose > 1)
4654 app->fnc.deinit = do_deinit;
4655 app->fnc.learn_status = do_learn_status;
4656 app->fnc.readcert = do_readcert;
4657 app->fnc.readkey = do_readkey;
4658 app->fnc.getattr = do_getattr;
4659 app->fnc.setattr = do_setattr;
4660 app->fnc.writecert = do_writecert;
4661 app->fnc.writekey = do_writekey;
4662 app->fnc.genkey = do_genkey;
4663 app->fnc.sign = do_sign;
4664 app->fnc.auth = do_auth;
4665 app->fnc.decipher = do_decipher;
4666 app->fnc.change_pin = do_change_pin;
4667 app->fnc.check_pin = do_check_pin;