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 <https://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. */
202 /* Flags used to control the application. */
205 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
206 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
209 /* Pinpad request specified on card. */
212 unsigned int specified:1;
222 unsigned int n_bits; /* Size of the modulus in bits. The rest
223 of this strucuire is only valid if
225 unsigned int e_bits; /* Size of the public exponent in bits. */
226 rsa_key_format_t format;
236 #define ECC_FLAG_DJB_TWEAK (1 << 0)
237 #define ECC_FLAG_PUBKEY (1 << 1)
240 /***** Local prototypes *****/
241 static unsigned long convert_sig_counter_value (const unsigned char *value,
243 static unsigned long get_sig_counter (app_t app);
244 static gpg_error_t do_auth (app_t app, const char *keyidstr,
245 gpg_error_t (*pincb)(void*, const char *, char **),
247 const void *indata, size_t indatalen,
248 unsigned char **outdata, size_t *outdatalen);
249 static void parse_algorithm_attribute (app_t app, int keyno);
250 static gpg_error_t change_keyattr_from_string
252 gpg_error_t (*pincb)(void*, const char *, char **),
254 const void *value, size_t valuelen);
262 do_deinit (app_t app)
264 if (app && app->app_local)
266 struct cache_s *c, *c2;
269 for (c = app->app_local->cache; c; c = c2)
275 for (i=0; i < DIM (app->app_local->pk); i++)
277 xfree (app->app_local->pk[i].key);
278 app->app_local->pk[i].read_done = 0;
280 xfree (app->app_local);
281 app->app_local = NULL;
286 /* Wrapper around iso7816_get_data which first tries to get the data
287 from the cache. With GET_IMMEDIATE passed as true, the cache is
288 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
289 supported by the card. */
291 get_cached_data (app_t app, int tag,
292 unsigned char **result, size_t *resultlen,
293 int get_immediate, int try_extlen)
307 for (c=app->app_local->cache; c; c = c->next)
312 p = xtrymalloc (c->length);
314 return gpg_error (gpg_err_code_from_errno (errno));
315 memcpy (p, c->data, c->length);
319 *resultlen = c->length;
325 if (try_extlen && app->app_local->cardcap.ext_lc_le)
326 exmode = app->app_local->extcap.max_certlen_3;
330 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
336 /* Check whether we should cache this object. */
340 for (i=0; data_objects[i].tag; i++)
341 if (data_objects[i].tag == tag)
343 if (data_objects[i].dont_cache)
348 /* Okay, cache it. */
349 for (c=app->app_local->cache; c; c = c->next)
350 assert (c->tag != tag);
352 c = xtrymalloc (sizeof *c + len);
355 memcpy (c->data, p, len);
358 c->next = app->app_local->cache;
359 app->app_local->cache = c;
365 /* Remove DO at TAG from the cache. */
367 flush_cache_item (app_t app, int tag)
369 struct cache_s *c, *cprev;
375 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
379 cprev->next = c->next;
381 app->app_local->cache = c->next;
384 for (c=app->app_local->cache; c ; c = c->next)
386 assert (c->tag != tag); /* Oops: duplicated entry. */
391 /* Try again if we have an outer tag. */
392 for (i=0; data_objects[i].tag; i++)
393 if (data_objects[i].tag == tag && data_objects[i].get_from
394 && data_objects[i].get_from != tag)
395 flush_cache_item (app, data_objects[i].get_from);
398 /* Flush all entries from the cache which might be out of sync after
401 flush_cache_after_error (app_t app)
405 for (i=0; data_objects[i].tag; i++)
406 if (data_objects[i].flush_on_error)
407 flush_cache_item (app, data_objects[i].tag);
411 /* Flush the entire cache. */
413 flush_cache (app_t app)
415 if (app && app->app_local)
417 struct cache_s *c, *c2;
419 for (c = app->app_local->cache; c; c = c2)
424 app->app_local->cache = NULL;
429 /* Get the DO identified by TAG from the card in SLOT and return a
430 buffer with its content in RESULT and NBYTES. The return value is
431 NULL if not found or a pointer which must be used to release the
432 buffer holding value. */
434 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
438 unsigned char *buffer;
440 unsigned char *value;
451 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
454 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
457 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
470 if (data_objects[i].tag && data_objects[i].get_from)
472 rc = get_cached_data (app, data_objects[i].get_from,
474 (data_objects[i].dont_cache
475 || data_objects[i].get_immediate_in_v11),
476 data_objects[i].try_extlen);
479 const unsigned char *s;
481 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
483 value = NULL; /* not found */
484 else if (valuelen > buflen - (s - buffer))
486 log_error ("warning: constructed DO too short\n");
488 xfree (buffer); buffer = NULL;
491 value = buffer + (s - buffer);
495 if (!value) /* Not in a constructed DO, try simple. */
497 rc = get_cached_data (app, tag, &buffer, &buflen,
498 (data_objects[i].dont_cache
499 || data_objects[i].get_immediate_in_v11),
500 data_objects[i].try_extlen);
520 dump_all_do (int slot)
523 unsigned char *buffer;
526 for (i=0; data_objects[i].tag; i++)
528 if (data_objects[i].get_from)
531 /* We don't try extended length APDU because such large DO would
532 be pretty useless in a log file. */
533 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
534 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
537 log_info ("DO '%s' not available: %s\n",
538 data_objects[i].desc, gpg_strerror (rc));
541 if (data_objects[i].binary)
543 log_info ("DO '%s': ", data_objects[i].desc);
544 log_printhex ("", buffer, buflen);
547 log_info ("DO '%s': '%.*s'\n",
548 data_objects[i].desc,
549 (int)buflen, buffer); /* FIXME: sanitize */
551 if (data_objects[i].constructed)
553 for (j=0; data_objects[j].tag; j++)
555 const unsigned char *value;
558 if (j==i || data_objects[i].tag != data_objects[j].get_from)
560 value = find_tlv_unchecked (buffer, buflen,
561 data_objects[j].tag, &valuelen);
564 else if (valuelen > buflen - (value - buffer))
565 log_error ("warning: constructed DO too short\n");
568 if (data_objects[j].binary)
570 log_info ("DO '%s': ", data_objects[j].desc);
572 log_info ("[%u]\n", (unsigned int)valuelen);
574 log_printhex ("", value, valuelen);
577 log_info ("DO '%s': '%.*s'\n",
578 data_objects[j].desc,
579 (int)valuelen, value); /* FIXME: sanitize */
584 xfree (buffer); buffer = NULL;
589 /* Count the number of bits, assuming the A represents an unsigned big
590 integer of length LEN bytes. */
592 count_bits (const unsigned char *a, size_t len)
594 unsigned int n = len * 8;
597 for (; len && !*a; len--, a++, n -=8)
601 for (i=7; i && !(*a & (1<<i)); i--)
607 /* GnuPG makes special use of the login-data DO, this function parses
608 the login data to store the flags for later use. It may be called
609 at any time and should be called after changing the login-data DO.
611 Everything up to a LF is considered a mailbox or account name. If
612 the first LF is followed by DC4 (0x14) control sequence are
613 expected up to the next LF. Control sequences are separated by FS
614 (0x18) and consist of key=value pairs. There are two keys defined:
618 Where FLAGS is a plain hexadecimal number representing flag values.
619 The lsb is here the rightmost bit. Defined flags bits are:
621 Bit 0 = CHV1 and CHV2 are not syncronized
622 Bit 1 = CHV2 has been been set to the default PIN of "123456"
623 (this implies that bit 0 is also set).
627 Where PINPAD_REQUEST is in the format of: <n> or <n>,<m>.
628 N for user PIN, M for admin PIN. If M is missing it means M=N.
629 0 means to force not to use pinpad.
633 parse_login_data (app_t app)
635 unsigned char *buffer, *p;
640 app->app_local->flags.no_sync = 0;
641 app->app_local->flags.def_chv2 = 0;
642 app->app_local->pinpad.specified = 0;
643 app->app_local->pinpad.fixedlen_user = -1;
644 app->app_local->pinpad.fixedlen_admin = -1;
647 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
650 for (; buflen; buflen--, buffer++)
653 if (buflen < 2 || buffer[1] != '\x14')
656 return; /* No control sequences. */
665 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
667 /* Flags control sequence found. */
670 /* For now we are only interested in the last digit, so skip
671 any leading digits but bail out on invalid characters. */
672 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
673 lastdig = xtoi_1 (p);
676 if (len && !(*p == '\n' || *p == '\x18'))
677 goto next; /* Invalid characters in field. */
678 app->app_local->flags.no_sync = !!(lastdig & 1);
679 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
681 else if (buflen > 1 && *buffer == 'P' && buffer[1] == '=')
683 /* Pinpad request control sequence found. */
694 n = strtol (buffer, &q, 10);
695 if (q >= (char *)buffer + buflen
696 || *q == '\x18' || *q == '\n')
700 if (*q++ != ',' || !digitp (q))
702 m = strtol (q, &q, 10);
705 if (buflen < ((unsigned char *)q - buffer))
708 buflen -= ((unsigned char *)q - buffer);
711 if (buflen && !(*buffer == '\n' || *buffer == '\x18'))
713 app->app_local->pinpad.specified = 1;
714 app->app_local->pinpad.fixedlen_user = n;
715 app->app_local->pinpad.fixedlen_admin = m;
720 /* Skip to FS (0x18) or LF (\n). */
721 for (; buflen && *buffer != '\x18' && *buffer != '\n'; buflen--)
724 while (buflen && *buffer != '\n');
730 #define MAX_ARGS_STORE_FPR 3
732 /* Note, that FPR must be at least 20 bytes. */
734 store_fpr (app_t app, int keynumber, u32 timestamp, unsigned char *fpr,
737 unsigned int n, nbits;
738 unsigned char *buffer, *p;
741 const unsigned char *m[MAX_ARGS_STORE_FPR];
742 size_t mlen[MAX_ARGS_STORE_FPR];
747 n = 6; /* key packet version, 4-byte timestamps, and algorithm */
748 if (algo == PUBKEY_ALGO_ECDH)
754 for (i = 0; i < argc; i++)
756 m[i] = va_arg (ap, const unsigned char *);
757 mlen[i] = va_arg (ap, size_t);
758 if (algo == PUBKEY_ALGO_RSA || i == 1)
764 p = buffer = xtrymalloc (3 + n);
766 return gpg_error_from_syserror ();
768 *p++ = 0x99; /* ctb */
769 *p++ = n >> 8; /* 2 byte length header */
771 *p++ = 4; /* key packet version */
772 *p++ = timestamp >> 24;
773 *p++ = timestamp >> 16;
774 *p++ = timestamp >> 8;
778 for (i = 0; i < argc; i++)
780 if (algo == PUBKEY_ALGO_RSA || i == 1)
782 nbits = count_bits (m[i], mlen[i]);
786 memcpy (p, m[i], mlen[i]);
790 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
794 tag = (app->card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
795 flush_cache_item (app, 0xC5);
796 tag2 = 0xCE + keynumber;
797 flush_cache_item (app, 0xCD);
799 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
801 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
803 if (!rc && app->card_version > 0x0100)
805 unsigned char buf[4];
807 buf[0] = timestamp >> 24;
808 buf[1] = timestamp >> 16;
809 buf[2] = timestamp >> 8;
812 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
814 log_error (_("failed to store the creation date: %s\n"),
823 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
824 int number, const unsigned char *fpr)
830 for (i=0; i < 20 && !fpr[i]; i++)
833 return; /* All zero. */
834 bin2hex (fpr, 20, buf);
836 *numbuf = 0; /* Don't print the key number */
838 sprintf (numbuf, "%d", number);
839 send_status_info (ctrl, keyword,
840 numbuf, (size_t)strlen(numbuf),
841 buf, (size_t)strlen (buf), NULL, 0);
845 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
846 int number, const unsigned char *stamp)
848 char numbuf1[50], numbuf2[50];
851 value = buf32_to_ulong (stamp);
854 sprintf (numbuf1, "%d", number);
855 sprintf (numbuf2, "%lu", value);
856 send_status_info (ctrl, keyword,
857 numbuf1, (size_t)strlen(numbuf1),
858 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
862 send_key_data (ctrl_t ctrl, const char *name,
863 const unsigned char *a, size_t alen)
868 buffer = buf = bin2hex (a, alen, NULL);
871 log_error ("memory allocation error in send_key_data\n");
874 buflen = strlen (buffer);
876 /* 768 is the hexified size for the modulus of an 3072 bit key. We
877 use extra chunks to transmit larger data (i.e for 4096 bit). */
878 for ( ;buflen > 768; buflen -= 768, buf += 768)
879 send_status_info (ctrl, "KEY-DATA",
883 send_status_info (ctrl, "KEY-DATA",
884 name, (size_t)strlen(name),
892 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int keyno)
896 assert (keyno >=0 && keyno < DIM(app->app_local->keyattr));
898 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
899 snprintf (buffer, sizeof buffer, "%d 1 rsa%u %u %d",
901 app->app_local->keyattr[keyno].rsa.n_bits,
902 app->app_local->keyattr[keyno].rsa.e_bits,
903 app->app_local->keyattr[keyno].rsa.format);
904 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
906 snprintf (buffer, sizeof buffer, "%d %d %s",
908 keyno==1? PUBKEY_ALGO_ECDH :
909 (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)?
910 PUBKEY_ALGO_EDDSA : PUBKEY_ALGO_ECDSA,
911 app->app_local->keyattr[keyno].ecc.curve);
914 snprintf (buffer, sizeof buffer, "%d 0 0 UNKNOWN", keyno+1);
916 send_status_direct (ctrl, keyword, buffer);
920 #define RSA_SMALL_SIZE_KEY 1952
921 #define RSA_SMALL_SIZE_OP 2048
924 determine_rsa_response (app_t app, int keyno)
928 size = 2 + 3 /* header */
929 + 4 /* tag+len */ + app->app_local->keyattr[keyno].rsa.n_bits/8
930 + 2 /* tag+len */ + app->app_local->keyattr[keyno].rsa.e_bits/8;
936 /* Implement the GETATTR command. This is similar to the LEARN
937 command but returns just one value via the status interface. */
939 do_getattr (app_t app, ctrl_t ctrl, const char *name)
946 { "DISP-NAME", 0x005B },
947 { "LOGIN-DATA", 0x005E },
948 { "DISP-LANG", 0x5F2D },
949 { "DISP-SEX", 0x5F35 },
950 { "PUBKEY-URL", 0x5F50 },
951 { "KEY-FPR", 0x00C5, 3 },
952 { "KEY-TIME", 0x00CD, 4 },
953 { "KEY-ATTR", 0x0000, -5 },
954 { "CA-FPR", 0x00C6, 3 },
955 { "CHV-STATUS", 0x00C4, 1 },
956 { "SIG-COUNTER", 0x0093, 2 },
957 { "SERIALNO", 0x004F, -1 },
959 { "EXTCAP", 0x0000, -2 },
960 { "PRIVATE-DO-1", 0x0101 },
961 { "PRIVATE-DO-2", 0x0102 },
962 { "PRIVATE-DO-3", 0x0103 },
963 { "PRIVATE-DO-4", 0x0104 },
964 { "$AUTHKEYID", 0x0000, -3 },
965 { "$DISPSERIALNO",0x0000, -4 },
970 unsigned char *value;
973 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
975 if (!table[idx].name)
976 return gpg_error (GPG_ERR_INV_NAME);
978 if (table[idx].special == -1)
980 /* The serial number is very special. We could have used the
981 AID DO to retrieve it, but we have it already in the app
982 context and the stamp argument is required anyway which we
983 can't by other means. The AID DO is available anyway but not
989 if (!app_get_serial_and_stamp (app, &serial, &stamp))
991 sprintf (tmp, "%lu", (unsigned long)stamp);
992 send_status_info (ctrl, "SERIALNO",
993 serial, strlen (serial),
1000 if (table[idx].special == -2)
1004 snprintf (tmp, sizeof tmp,
1005 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d "
1006 "sm=%d si=%u dec=%d bt=%d",
1007 app->app_local->extcap.get_challenge,
1008 app->app_local->extcap.key_import,
1009 app->app_local->extcap.change_force_chv,
1010 app->app_local->extcap.private_dos,
1011 app->app_local->extcap.max_certlen_3,
1012 app->app_local->extcap.algo_attr_change,
1013 (app->app_local->extcap.sm_supported
1014 ? (app->app_local->extcap.sm_algo == 0? CIPHER_ALGO_3DES :
1015 (app->app_local->extcap.sm_algo == 1?
1016 CIPHER_ALGO_AES : CIPHER_ALGO_AES256))
1018 app->app_local->status_indicator,
1019 app->app_local->extcap.has_decrypt,
1020 app->app_local->extcap.has_button);
1021 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1024 if (table[idx].special == -3)
1026 char const tmp[] = "OPENPGP.3";
1027 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1030 if (table[idx].special == -4)
1035 if (!app_get_serial_and_stamp (app, &serial, &stamp))
1037 if (strlen (serial) > 16+12)
1039 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
1045 return gpg_error (GPG_ERR_INV_NAME);
1047 if (table[idx].special == -5)
1049 for (i=0; i < 3; i++)
1050 send_key_attr (ctrl, app, table[idx].name, i);
1054 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
1057 if (table[idx].special == 1)
1061 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
1062 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
1063 send_status_info (ctrl, table[idx].name,
1064 numbuf, strlen (numbuf), NULL, 0);
1066 else if (table[idx].special == 2)
1070 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
1071 send_status_info (ctrl, table[idx].name,
1072 numbuf, strlen (numbuf), NULL, 0);
1074 else if (table[idx].special == 3)
1077 for (i=0; i < 3; i++)
1078 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
1080 else if (table[idx].special == 4)
1083 for (i=0; i < 3; i++)
1084 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
1087 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
1094 /* Retrieve the fingerprint from the card inserted in SLOT and write
1095 the according hex representation to FPR. Caller must have provide
1096 a buffer at FPR of least 41 bytes. Returns 0 on success or an
1098 #if GNUPG_MAJOR_VERSION > 1
1100 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
1102 gpg_error_t err = 0;
1104 unsigned char *value;
1107 assert (keyno >=0 && keyno <= 2);
1109 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
1110 if (relptr && valuelen >= 60)
1111 bin2hex (value+keyno*20, 20, fpr);
1113 err = gpg_error (GPG_ERR_NOT_FOUND);
1117 #endif /*GNUPG_MAJOR_VERSION > 1*/
1120 /* Retrieve the public key material for the RSA key, whose fingerprint
1121 is FPR, from gpg output, which can be read through the stream FP.
1122 The RSA modulus will be stored at the address of M and MLEN, the
1123 public exponent at E and ELEN. Returns zero on success, an error
1124 code on failure. Caller must release the allocated buffers at M
1125 and E if the function returns success. */
1126 #if GNUPG_MAJOR_VERSION > 1
1128 retrieve_key_material (FILE *fp, const char *hexkeyid,
1129 const unsigned char **m, size_t *mlen,
1130 const unsigned char **e, size_t *elen)
1132 gcry_error_t err = 0;
1133 char *line = NULL; /* read_line() buffer. */
1134 size_t line_size = 0; /* Helper for for read_line. */
1135 int found_key = 0; /* Helper to find a matching key. */
1136 unsigned char *m_new = NULL;
1137 unsigned char *e_new = NULL;
1141 /* Loop over all records until we have found the subkey
1142 corresponding to the fingerprint. Inm general the first record
1143 should be the pub record, but we don't rely on that. Given that
1144 we only need to look at one key, it is sufficient to compare the
1145 keyid so that we don't need to look at "fpr" records. */
1149 char *fields[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
1156 i = read_line (fp, &line, &line_size, &max_length);
1161 err = gpg_error_from_syserror ();
1162 goto leave; /* Error. */
1166 err = gpg_error (GPG_ERR_TRUNCATED);
1167 goto leave; /* Line truncated - we better stop processing. */
1170 /* Parse the line into fields. */
1171 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1173 fields[nfields] = p;
1174 p = strchr (p, ':');
1179 continue; /* No fields at all - skip line. */
1183 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1184 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1189 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1190 break; /* Next key - stop. */
1192 if ( strcmp (fields[0], "pkd") )
1193 continue; /* Not a key data record. */
1194 i = 0; /* Avoid erroneous compiler warning. */
1195 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1196 || (!i && m_new) || (i && e_new))
1198 err = gpg_error (GPG_ERR_GENERAL);
1199 goto leave; /* Error: Invalid key data record or not an RSA key. */
1202 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1206 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1208 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1209 gcry_mpi_release (mpi);
1224 err = gpg_error (GPG_ERR_GENERAL);
1232 #endif /*GNUPG_MAJOR_VERSION > 1*/
1236 rsa_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1237 const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp)
1240 const unsigned char *m, *e;
1242 unsigned char *mbuf = NULL, *ebuf = NULL;
1244 m = find_tlv (data, datalen, 0x0081, &mlen);
1247 log_error (_("response does not contain the RSA modulus\n"));
1248 return gpg_error (GPG_ERR_CARD);
1251 e = find_tlv (data, datalen, 0x0082, &elen);
1254 log_error (_("response does not contain the RSA public exponent\n"));
1255 return gpg_error (GPG_ERR_CARD);
1260 send_key_data (ctrl, "n", m, mlen);
1261 send_key_data (ctrl, "e", e, elen);
1264 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
1266 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
1271 unsigned char fprbuf[20];
1273 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
1278 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1281 mbuf = xtrymalloc (mlen + 1);
1284 err = gpg_error_from_syserror ();
1287 /* Prepend numbers with a 0 if needed. */
1288 if (mlen && (*m & 0x80))
1291 memcpy (mbuf+1, m, mlen);
1295 memcpy (mbuf, m, mlen);
1297 ebuf = xtrymalloc (elen + 1);
1300 err = gpg_error_from_syserror ();
1303 /* Prepend numbers with a 0 if needed. */
1304 if (elen && (*e & 0x80))
1307 memcpy (ebuf+1, e, elen);
1311 memcpy (ebuf, e, elen);
1313 err = gcry_sexp_build (r_sexp, NULL, "(public-key(rsa(n%b)(e%b)))",
1314 (int)mlen, mbuf, (int)elen, ebuf);
1322 /* Determine KDF hash algorithm and KEK encryption algorithm by CURVE. */
1323 static const unsigned char*
1324 ecdh_params (const char *curve)
1328 openpgp_curve_to_oid (curve, &nbits);
1330 /* See RFC-6637 for those constants.
1331 0x03: Number of bytes
1332 0x01: Version for this parameter format
1337 return (const unsigned char*)"\x03\x01\x08\x07";
1338 else if (nbits <= 384)
1339 return (const unsigned char*)"\x03\x01\x09\x08";
1341 return (const unsigned char*)"\x03\x01\x0a\x09";
1345 ecc_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1346 const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp)
1349 unsigned char *qbuf = NULL;
1350 const unsigned char *ecc_q;
1352 gcry_mpi_t oid = NULL;
1356 const unsigned char *oidbuf;
1361 ecc_q = find_tlv (data, datalen, 0x0086, &ecc_q_len);
1364 log_error (_("response does not contain the EC public key\n"));
1365 return gpg_error (GPG_ERR_CARD);
1368 curve = app->app_local->keyattr[keyno].ecc.curve;
1369 oidstr = openpgp_curve_to_oid (curve, NULL);
1370 err = openpgp_oid_from_str (oidstr, &oid);
1373 oidbuf = gcry_mpi_get_opaque (oid, &n);
1376 err = gpg_error_from_syserror ();
1381 qbuf = xtrymalloc (ecc_q_len + 1);
1384 err = gpg_error_from_syserror ();
1388 if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1389 { /* Prepend 0x40 prefix. */
1391 memcpy (qbuf+1, ecc_q, ecc_q_len);
1395 memcpy (qbuf, ecc_q, ecc_q_len);
1399 send_key_data (ctrl, "q", qbuf, ecc_q_len);
1400 send_key_data (ctrl, "curve", oidbuf, oid_len);
1406 send_key_data (ctrl, "kdf/kek", ecdh_params (curve), (size_t)4);
1407 algo = PUBKEY_ALGO_ECDH;
1411 if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1412 algo = PUBKEY_ALGO_EDDSA;
1414 algo = PUBKEY_ALGO_ECDSA;
1419 unsigned char fprbuf[20];
1421 err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
1422 qbuf, ecc_q_len, ecdh_params (curve), (size_t)4);
1426 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1429 if (!(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1430 format = "(public-key(ecc(curve%s)(q%b)))";
1431 else if (keyno == 1)
1432 format = "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))";
1434 format = "(public-key(ecc(curve%s)(flags eddsa)(q%b)))";
1436 err = gcry_sexp_build (r_sexp, NULL, format,
1437 app->app_local->keyattr[keyno].ecc.curve,
1438 (int)ecc_q_len, qbuf);
1440 gcry_mpi_release (oid);
1446 /* Parse tag-length-value data for public key in BUFFER of BUFLEN
1447 length. Key of KEYNO in APP is updated with an S-expression of
1448 public key. When CTRL is not NULL, fingerprint is computed with
1449 CREATED_AT, and fingerprint is written to the card, and key data
1450 and fingerprint are send back to the client side.
1453 read_public_key (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1454 const unsigned char *buffer, size_t buflen)
1457 const unsigned char *data;
1459 gcry_sexp_t s_pkey = NULL;
1461 data = find_tlv (buffer, buflen, 0x7F49, &datalen);
1464 log_error (_("response does not contain the public key data\n"));
1465 return gpg_error (GPG_ERR_CARD);
1468 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1469 err = rsa_read_pubkey (app, ctrl, created_at, keyno,
1470 data, datalen, &s_pkey);
1471 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
1472 err = ecc_read_pubkey (app, ctrl, created_at, keyno,
1473 data, datalen, &s_pkey);
1475 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1479 unsigned char *keybuf;
1482 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1483 keybuf = xtrymalloc (len);
1486 err = gpg_error_from_syserror ();
1487 gcry_sexp_release (s_pkey);
1491 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1492 gcry_sexp_release (s_pkey);
1494 app->app_local->pk[keyno].key = keybuf;
1495 /* Decrement for trailing '\0' */
1496 app->app_local->pk[keyno].keylen = len - 1;
1503 /* Get the public key for KEYNO and store it as an S-expresion with
1504 the APP handle. On error that field gets cleared. If we already
1505 know about the public key we will just return. Note that this does
1506 not mean a key is available; this is solely indicated by the
1507 presence of the app->app_local->pk[KEYNO].key field.
1509 Note that GnuPG 1.x does not need this and it would be too time
1510 consuming to send it just for the fun of it. However, given that we
1511 use the same code in gpg 1.4, we can't use the gcry S-expresion
1512 here but need to open encode it. */
1513 #if GNUPG_MAJOR_VERSION > 1
1515 get_public_key (app_t app, int keyno)
1517 gpg_error_t err = 0;
1518 unsigned char *buffer;
1519 const unsigned char *m, *e;
1523 char *keybuf = NULL;
1527 if (keyno < 0 || keyno > 2)
1528 return gpg_error (GPG_ERR_INV_ID);
1530 /* Already cached? */
1531 if (app->app_local->pk[keyno].read_done)
1534 xfree (app->app_local->pk[keyno].key);
1535 app->app_local->pk[keyno].key = NULL;
1536 app->app_local->pk[keyno].keylen = 0;
1538 m = e = NULL; /* (avoid cc warning) */
1540 if (app->card_version > 0x0100)
1542 int exmode, le_value;
1544 /* We may simply read the public key out of these cards. */
1545 if (app->app_local->cardcap.ext_lc_le
1546 && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA
1547 && app->app_local->keyattr[keyno].rsa.n_bits > RSA_SMALL_SIZE_KEY)
1549 exmode = 1; /* Use extended length. */
1550 le_value = determine_rsa_response (app, keyno);
1555 le_value = 256; /* Use legacy value. */
1558 err = iso7816_read_public_key (app->slot, exmode,
1559 (keyno == 0? "\xB6" :
1560 keyno == 1? "\xB8" : "\xA4"),
1561 2, le_value, &buffer, &buflen);
1564 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1568 err = read_public_key (app, NULL, 0U, keyno, buffer, buflen);
1572 /* Due to a design problem in v1.0 cards we can't get the public
1573 key out of these cards without doing a verify on CHV3.
1574 Clearly that is not an option and thus we try to locate the
1575 key using an external helper.
1577 The helper we use here is gpg itself, which should know about
1578 the key in any case. */
1582 char *command = NULL;
1586 buffer = NULL; /* We don't need buffer. */
1588 err = retrieve_fpr_from_card (app, keyno, fpr);
1591 log_error ("error while retrieving fpr from card: %s\n",
1592 gpg_strerror (err));
1595 hexkeyid = fpr + 24;
1597 ret = gpgrt_asprintf
1598 (&command, "gpg --list-keys --with-colons --with-key-data '%s'", fpr);
1601 err = gpg_error_from_syserror ();
1605 fp = popen (command, "r");
1609 err = gpg_error_from_syserror ();
1610 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1614 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1618 log_error ("error while retrieving key material through pipe: %s\n",
1619 gpg_strerror (err));
1623 err = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%b)(e%b)))",
1624 (int)mlen, m, (int)elen, e);
1628 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1630 keybuf = xtrymalloc (len);
1633 err = gpg_error_from_syserror ();
1634 gcry_sexp_release (s_pkey);
1638 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1639 gcry_sexp_release (s_pkey);
1641 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1642 /* Decrement for trailing '\0' */
1643 app->app_local->pk[keyno].keylen = len - 1;
1647 /* Set a flag to indicate that we tried to read the key. */
1648 app->app_local->pk[keyno].read_done = 1;
1653 #endif /* GNUPG_MAJOR_VERSION > 1 */
1657 /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3].
1658 This is used by the LEARN command. */
1660 send_keypair_info (app_t app, ctrl_t ctrl, int key)
1662 int keyno = key - 1;
1663 gpg_error_t err = 0;
1664 /* Note that GnuPG 1.x does not need this and it would be too time
1665 consuming to send it just for the fun of it. */
1666 #if GNUPG_MAJOR_VERSION > 1
1667 unsigned char grip[20];
1671 err = get_public_key (app, keyno);
1675 assert (keyno >= 0 && keyno <= 2);
1676 if (!app->app_local->pk[keyno].key)
1677 goto leave; /* No such key - ignore. */
1679 err = keygrip_from_canon_sexp (app->app_local->pk[keyno].key,
1680 app->app_local->pk[keyno].keylen,
1685 bin2hex (grip, 20, gripstr);
1687 sprintf (idbuf, "OPENPGP.%d", keyno+1);
1688 send_status_info (ctrl, "KEYPAIRINFO",
1690 idbuf, strlen (idbuf),
1694 #endif /* GNUPG_MAJOR_VERSION > 1 */
1700 /* Handle the LEARN command for OpenPGP. */
1702 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1706 do_getattr (app, ctrl, "EXTCAP");
1707 do_getattr (app, ctrl, "DISP-NAME");
1708 do_getattr (app, ctrl, "DISP-LANG");
1709 do_getattr (app, ctrl, "DISP-SEX");
1710 do_getattr (app, ctrl, "PUBKEY-URL");
1711 do_getattr (app, ctrl, "LOGIN-DATA");
1712 do_getattr (app, ctrl, "KEY-FPR");
1713 if (app->card_version > 0x0100)
1714 do_getattr (app, ctrl, "KEY-TIME");
1715 do_getattr (app, ctrl, "CA-FPR");
1716 do_getattr (app, ctrl, "CHV-STATUS");
1717 do_getattr (app, ctrl, "SIG-COUNTER");
1718 if (app->app_local->extcap.private_dos)
1720 do_getattr (app, ctrl, "PRIVATE-DO-1");
1721 do_getattr (app, ctrl, "PRIVATE-DO-2");
1723 do_getattr (app, ctrl, "PRIVATE-DO-3");
1725 do_getattr (app, ctrl, "PRIVATE-DO-4");
1727 send_keypair_info (app, ctrl, 1);
1728 send_keypair_info (app, ctrl, 2);
1729 send_keypair_info (app, ctrl, 3);
1730 /* Note: We do not send the Cardholder Certificate, because that is
1731 relatively long and for OpenPGP applications not really needed. */
1736 /* Handle the READKEY command for OpenPGP. On success a canonical
1737 encoded S-expression with the public key will get stored at PK and
1738 its length (for assertions) at PKLEN; the caller must release that
1739 buffer. On error PK and PKLEN are not changed and an error code is
1742 do_readkey (app_t app, int advanced, const char *keyid,
1743 unsigned char **pk, size_t *pklen)
1745 #if GNUPG_MAJOR_VERSION > 1
1750 if (!strcmp (keyid, "OPENPGP.1"))
1752 else if (!strcmp (keyid, "OPENPGP.2"))
1754 else if (!strcmp (keyid, "OPENPGP.3"))
1757 return gpg_error (GPG_ERR_INV_ID);
1759 err = get_public_key (app, keyno);
1763 buf = app->app_local->pk[keyno].key;
1765 return gpg_error (GPG_ERR_NO_PUBKEY);
1771 err = gcry_sexp_new (&s_key, buf, app->app_local->pk[keyno].keylen, 0);
1775 *pklen = gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, NULL, 0);
1776 *pk = xtrymalloc (*pklen);
1779 err = gpg_error_from_syserror ();
1784 gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, *pk, *pklen);
1785 gcry_sexp_release (s_key);
1786 /* Decrement for trailing '\0' */
1787 *pklen = *pklen - 1;
1791 *pklen = app->app_local->pk[keyno].keylen;
1792 *pk = xtrymalloc (*pklen);
1795 err = gpg_error_from_syserror ();
1799 memcpy (*pk, buf, *pklen);
1804 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1808 /* Read the standard certificate of an OpenPGP v2 card. It is
1809 returned in a freshly allocated buffer with that address stored at
1810 CERT and the length of the certificate stored at CERTLEN. CERTID
1811 needs to be set to "OPENPGP.3". */
1813 do_readcert (app_t app, const char *certid,
1814 unsigned char **cert, size_t *certlen)
1816 #if GNUPG_MAJOR_VERSION > 1
1818 unsigned char *buffer;
1824 if (strcmp (certid, "OPENPGP.3"))
1825 return gpg_error (GPG_ERR_INV_ID);
1826 if (!app->app_local->extcap.is_v2)
1827 return gpg_error (GPG_ERR_NOT_FOUND);
1829 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1831 return gpg_error (GPG_ERR_NOT_FOUND);
1834 err = gpg_error (GPG_ERR_NOT_FOUND);
1835 else if (!(*cert = xtrymalloc (buflen)))
1836 err = gpg_error_from_syserror ();
1839 memcpy (*cert, buffer, buflen);
1846 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1851 /* Decide if we use the pinpad of the reader for PIN input according
1852 to the user preference on the card, and the capability of the
1853 reader. This routine is only called when the reader has pinpad.
1854 Returns 0 if we use pinpad, 1 otherwise. */
1856 check_pinpad_request (app_t app, pininfo_t *pininfo, int admin_pin)
1858 if (app->app_local->pinpad.specified == 0) /* No preference on card. */
1860 if (pininfo->fixedlen == 0) /* Reader has varlen capability. */
1861 return 0; /* Then, use pinpad. */
1864 * Reader has limited capability, and it may not match PIN of
1871 pininfo->fixedlen = app->app_local->pinpad.fixedlen_admin;
1873 pininfo->fixedlen = app->app_local->pinpad.fixedlen_user;
1875 if (pininfo->fixedlen == 0 /* User requests disable pinpad. */
1876 || pininfo->fixedlen < pininfo->minlen
1877 || pininfo->fixedlen > pininfo->maxlen
1878 /* Reader doesn't have the capability to input a PIN which
1879 * length is FIXEDLEN. */)
1886 /* Verify a CHV either using using the pinentry or if possible by
1887 using a pinpad. PINCB and PINCB_ARG describe the usual callback
1888 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1889 used with CHV1. PINVALUE is the address of a pointer which will
1890 receive a newly allocated block with the actual PIN (this is useful
1891 in case that PIN shall be used for another verify operation). The
1892 caller needs to free this value. If the function returns with
1893 success and NULL is stored at PINVALUE, the caller should take this
1894 as an indication that the pinpad has been used.
1897 verify_a_chv (app_t app,
1898 gpg_error_t (*pincb)(void*, const char *, char **),
1900 int chvno, unsigned long sigcount, char **pinvalue)
1903 char *prompt_buffer = NULL;
1908 assert (chvno == 1 || chvno == 2);
1912 if (chvno == 2 && app->app_local->flags.def_chv2)
1914 /* Special case for def_chv2 mechanism. */
1916 log_info (_("using default PIN as %s\n"), "CHV2");
1917 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1920 /* Verification of CHV2 with the default PIN failed,
1921 although the card pretends to have the default PIN set as
1922 CHV2. We better disable the def_chv2 flag now. */
1923 log_info (_("failed to use default PIN as %s: %s"
1924 " - disabling further default use\n"),
1925 "CHV2", gpg_strerror (rc));
1926 app->app_local->flags.def_chv2 = 0;
1931 memset (&pininfo, 0, sizeof pininfo);
1932 pininfo.fixedlen = -1;
1933 pininfo.minlen = minlen;
1938 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1939 size_t promptsize = strlen (PROMPTSTRING) + 50;
1941 prompt_buffer = xtrymalloc (promptsize);
1943 return gpg_error_from_syserror ();
1944 snprintf (prompt_buffer, promptsize, PROMPTSTRING, sigcount);
1945 prompt = prompt_buffer;
1949 prompt = _("||Please enter the PIN");
1952 if (!opt.disable_pinpad
1953 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
1954 && !check_pinpad_request (app, &pininfo, 0))
1956 /* The reader supports the verify command through the pinpad.
1957 Note that the pincb appends a text to the prompt telling the
1958 user to use the pinpad. */
1959 rc = pincb (pincb_arg, prompt, NULL);
1961 xfree (prompt_buffer);
1962 prompt_buffer = NULL;
1965 log_info (_("PIN callback returned error: %s\n"),
1969 rc = iso7816_verify_kp (app->slot, 0x80+chvno, &pininfo);
1970 /* Dismiss the prompt. */
1971 pincb (pincb_arg, NULL, NULL);
1973 assert (!*pinvalue);
1977 /* The reader has no pinpad or we don't want to use it. */
1978 rc = pincb (pincb_arg, prompt, pinvalue);
1980 xfree (prompt_buffer);
1981 prompt_buffer = NULL;
1984 log_info (_("PIN callback returned error: %s\n"),
1989 if (strlen (*pinvalue) < minlen)
1991 log_error (_("PIN for CHV%d is too short;"
1992 " minimum length is %d\n"), chvno, minlen);
1995 return gpg_error (GPG_ERR_BAD_PIN);
1998 rc = iso7816_verify (app->slot, 0x80+chvno,
1999 *pinvalue, strlen (*pinvalue));
2004 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
2007 flush_cache_after_error (app);
2014 /* Verify CHV2 if required. Depending on the configuration of the
2015 card CHV1 will also be verified. */
2017 verify_chv2 (app_t app,
2018 gpg_error_t (*pincb)(void*, const char *, char **),
2025 return 0; /* We already verified CHV2. */
2027 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
2032 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
2034 /* For convenience we verify CHV1 here too. We do this only if
2035 the card is not configured to require a verification before
2036 each CHV1 controlled operation (force_chv1) and if we are not
2037 using the pinpad (PINVALUE == NULL). */
2038 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
2039 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2040 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2043 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
2044 flush_cache_after_error (app);
2056 /* Build the prompt to enter the Admin PIN. The prompt depends on the
2057 current sdtate of the card. */
2059 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
2062 unsigned char *value;
2069 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2070 if (!relptr || valuelen < 7)
2072 log_error (_("error retrieving CHV status from card\n"));
2074 return gpg_error (GPG_ERR_CARD);
2078 log_info (_("card is permanently locked!\n"));
2080 return gpg_error (GPG_ERR_BAD_PIN);
2082 remaining = value[6];
2085 log_info (ngettext("%d Admin PIN attempt remaining before card"
2086 " is permanently locked\n",
2087 "%d Admin PIN attempts remaining before card"
2088 " is permanently locked\n",
2089 remaining), remaining);
2093 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
2094 the start of the string. Use %%0A to force a linefeed. */
2095 prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
2096 "[remaining attempts: %d]"), remaining);
2099 prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
2102 return gpg_error_from_syserror ();
2109 /* Verify CHV3 if required. */
2111 verify_chv3 (app_t app,
2112 gpg_error_t (*pincb)(void*, const char *, char **),
2117 #if GNUPG_MAJOR_VERSION != 1
2118 if (!opt.allow_admin)
2120 log_info (_("access to admin commands is not configured\n"));
2121 return gpg_error (GPG_ERR_EACCES);
2131 memset (&pininfo, 0, sizeof pininfo);
2132 pininfo.fixedlen = -1;
2133 pininfo.minlen = minlen;
2135 rc = build_enter_admin_pin_prompt (app, &prompt);
2139 if (!opt.disable_pinpad
2140 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
2141 && !check_pinpad_request (app, &pininfo, 1))
2143 /* The reader supports the verify command through the pinpad. */
2144 rc = pincb (pincb_arg, prompt, NULL);
2149 log_info (_("PIN callback returned error: %s\n"),
2153 rc = iso7816_verify_kp (app->slot, 0x83, &pininfo);
2154 /* Dismiss the prompt. */
2155 pincb (pincb_arg, NULL, NULL);
2161 rc = pincb (pincb_arg, prompt, &pinvalue);
2166 log_info (_("PIN callback returned error: %s\n"),
2171 if (strlen (pinvalue) < minlen)
2173 log_error (_("PIN for CHV%d is too short;"
2174 " minimum length is %d\n"), 3, minlen);
2176 return gpg_error (GPG_ERR_BAD_PIN);
2179 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
2185 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
2186 flush_cache_after_error (app);
2195 /* Handle the SETATTR operation. All arguments are already basically
2198 do_setattr (app_t app, const char *name,
2199 gpg_error_t (*pincb)(void*, const char *, char **),
2201 const unsigned char *value, size_t valuelen)
2210 unsigned int need_v2:1;
2212 { "DISP-NAME", 0x005B, 3 },
2213 { "LOGIN-DATA", 0x005E, 3, 2 },
2214 { "DISP-LANG", 0x5F2D, 3 },
2215 { "DISP-SEX", 0x5F35, 3 },
2216 { "PUBKEY-URL", 0x5F50, 3 },
2217 { "CHV-STATUS-1", 0x00C4, 3, 1 },
2218 { "CA-FPR-1", 0x00CA, 3 },
2219 { "CA-FPR-2", 0x00CB, 3 },
2220 { "CA-FPR-3", 0x00CC, 3 },
2221 { "PRIVATE-DO-1", 0x0101, 2 },
2222 { "PRIVATE-DO-2", 0x0102, 3 },
2223 { "PRIVATE-DO-3", 0x0103, 2 },
2224 { "PRIVATE-DO-4", 0x0104, 3 },
2225 { "CERT-3", 0x7F21, 3, 0, 1 },
2226 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
2227 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
2228 { "KEY-ATTR", 0, 0, 3, 1 },
2229 { "AESKEY", 0x00D5, 3, 0, 1 },
2234 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
2236 if (!table[idx].name)
2237 return gpg_error (GPG_ERR_INV_NAME);
2238 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
2239 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
2241 if (table[idx].special == 3)
2242 return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
2244 switch (table[idx].need_chv)
2247 rc = verify_chv2 (app, pincb, pincb_arg);
2250 rc = verify_chv3 (app, pincb, pincb_arg);
2258 /* Flush the cache before writing it, so that the next get operation
2259 will reread the data from the card and thus get synced in case of
2260 errors (e.g. data truncated by the card). */
2261 flush_cache_item (app, table[idx].tag);
2263 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
2264 exmode = 1; /* Use extended length w/o a limit. */
2265 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
2266 exmode = -254; /* Command chaining with max. 254 bytes. */
2269 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
2271 log_error ("failed to set '%s': %s\n", table[idx].name, gpg_strerror (rc));
2273 if (table[idx].special == 1)
2274 app->force_chv1 = (valuelen && *value == 0);
2275 else if (table[idx].special == 2)
2276 parse_login_data (app);
2282 /* Handle the WRITECERT command for OpenPGP. This rites the standard
2283 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
2284 PINCB and PINCB_ARG are the usual arguments for the pinentry
2287 do_writecert (app_t app, ctrl_t ctrl,
2288 const char *certidstr,
2289 gpg_error_t (*pincb)(void*, const char *, char **),
2291 const unsigned char *certdata, size_t certdatalen)
2294 #if GNUPG_MAJOR_VERSION > 1
2295 if (strcmp (certidstr, "OPENPGP.3"))
2296 return gpg_error (GPG_ERR_INV_ID);
2297 if (!certdata || !certdatalen)
2298 return gpg_error (GPG_ERR_INV_ARG);
2299 if (!app->app_local->extcap.is_v2)
2300 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2301 if (certdatalen > app->app_local->extcap.max_certlen_3)
2302 return gpg_error (GPG_ERR_TOO_LARGE);
2303 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
2305 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2311 /* Handle the PASSWD command. The following combinations are
2314 Flags CHVNO Vers. Description
2315 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
2316 RESET 1 2 Verify PW3 and set a new PW1.
2317 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
2318 RESET 2 2 Verify PW3 and set a new Reset Code.
2319 RESET 3 any Returns GPG_ERR_INV_ID.
2320 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
2321 - 1 2 Verify PW1 and set a new PW1.
2322 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
2323 - 2 2 Verify Reset Code and set a new PW1.
2324 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
2327 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
2329 gpg_error_t (*pincb)(void*, const char *, char **),
2333 int chvno = atoi (chvnostr);
2334 char *resetcode = NULL;
2335 char *oldpinvalue = NULL;
2336 char *pinvalue = NULL;
2337 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
2338 int set_resetcode = 0;
2344 memset (&pininfo, 0, sizeof pininfo);
2345 pininfo.fixedlen = -1;
2346 pininfo.minlen = minlen;
2348 if (reset_mode && chvno == 3)
2350 rc = gpg_error (GPG_ERR_INV_ID);
2354 if (!app->app_local->extcap.is_v2)
2356 /* Version 1 cards. */
2358 if (reset_mode || chvno == 3)
2360 /* We always require that the PIN is entered. */
2362 rc = verify_chv3 (app, pincb, pincb_arg);
2366 else if (chvno == 1 || chvno == 2)
2368 /* On a v1.x card CHV1 and CVH2 should always have the same
2369 value, thus we enforce it here. */
2370 int save_force = app->force_chv1;
2372 app->force_chv1 = 0;
2375 rc = verify_chv2 (app, pincb, pincb_arg);
2376 app->force_chv1 = save_force;
2382 rc = gpg_error (GPG_ERR_INV_ID);
2388 /* Version 2 cards. */
2390 if (!opt.disable_pinpad
2391 && !iso7816_check_pinpad (app->slot,
2392 ISO7816_CHANGE_REFERENCE_DATA, &pininfo)
2393 && !check_pinpad_request (app, &pininfo, chvno == 3))
2398 /* To reset a PIN the Admin PIN is required. */
2401 rc = verify_chv3 (app, pincb, pincb_arg);
2408 else if (chvno == 1 || chvno == 3)
2412 char *promptbuf = NULL;
2418 rc = build_enter_admin_pin_prompt (app, &promptbuf);
2424 prompt = _("||Please enter the PIN");
2425 rc = pincb (pincb_arg, prompt, &oldpinvalue);
2430 log_info (_("PIN callback returned error: %s\n"),
2435 if (strlen (oldpinvalue) < minlen)
2437 log_info (_("PIN for CHV%d is too short;"
2438 " minimum length is %d\n"), chvno, minlen);
2439 rc = gpg_error (GPG_ERR_BAD_PIN);
2444 else if (chvno == 2)
2446 /* There is no PW2 for v2 cards. We use this condition to
2447 allow a PW reset using the Reset Code. */
2449 unsigned char *value;
2455 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2456 if (!relptr || valuelen < 7)
2458 log_error (_("error retrieving CHV status from card\n"));
2460 rc = gpg_error (GPG_ERR_CARD);
2463 remaining = value[5];
2467 log_error (_("Reset Code not or not anymore available\n"));
2468 rc = gpg_error (GPG_ERR_BAD_PIN);
2472 rc = pincb (pincb_arg,
2473 _("||Please enter the Reset Code for the card"),
2477 log_info (_("PIN callback returned error: %s\n"),
2481 if (strlen (resetcode) < minlen)
2483 log_info (_("Reset Code is too short; minimum length is %d\n"),
2485 rc = gpg_error (GPG_ERR_BAD_PIN);
2491 rc = gpg_error (GPG_ERR_INV_ID);
2499 app->did_chv1 = app->did_chv2 = 0;
2503 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2504 keep it at the start of the string. We need this elsewhere
2505 to get some infos on the string. */
2506 rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
2507 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2511 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2521 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2523 rc = gpg_error_from_syserror ();
2526 strcpy (stpcpy (buffer, resetcode), pinvalue);
2527 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2528 buffer, strlen (buffer));
2529 wipememory (buffer, strlen (buffer));
2533 else if (set_resetcode)
2535 if (strlen (pinvalue) < 8)
2537 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2538 rc = gpg_error (GPG_ERR_BAD_PIN);
2541 rc = iso7816_put_data (app->slot, 0, 0xD3,
2542 pinvalue, strlen (pinvalue));
2544 else if (reset_mode)
2546 rc = iso7816_reset_retry_counter (app->slot, 0x81,
2547 pinvalue, strlen (pinvalue));
2548 if (!rc && !app->app_local->extcap.is_v2)
2549 rc = iso7816_reset_retry_counter (app->slot, 0x82,
2550 pinvalue, strlen (pinvalue));
2552 else if (!app->app_local->extcap.is_v2)
2554 /* Version 1 cards. */
2555 if (chvno == 1 || chvno == 2)
2557 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2558 pinvalue, strlen (pinvalue));
2560 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2561 pinvalue, strlen (pinvalue));
2563 else /* CHVNO == 3 */
2565 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2566 pinvalue, strlen (pinvalue));
2571 /* Version 2 cards. */
2572 assert (chvno == 1 || chvno == 3);
2576 rc = pincb (pincb_arg,
2578 _("||Please enter the Admin PIN and New Admin PIN") :
2579 _("||Please enter the PIN and New PIN"), NULL);
2582 log_info (_("PIN callback returned error: %s\n"),
2586 rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0,
2588 pincb (pincb_arg, NULL, NULL); /* Dismiss the prompt. */
2591 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2592 oldpinvalue, strlen (oldpinvalue),
2593 pinvalue, strlen (pinvalue));
2598 wipememory (pinvalue, strlen (pinvalue));
2602 flush_cache_after_error (app);
2607 wipememory (resetcode, strlen (resetcode));
2612 wipememory (oldpinvalue, strlen (oldpinvalue));
2613 xfree (oldpinvalue);
2619 /* Check whether a key already exists. KEYIDX is the index of the key
2620 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2621 error returned if the key already exists. The flag GENERATING is
2622 only used to print correct messages. */
2624 does_key_exist (app_t app, int keyidx, int generating, int force)
2626 const unsigned char *fpr;
2627 unsigned char *buffer;
2631 assert (keyidx >=0 && keyidx <= 2);
2633 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2635 log_error (_("error reading application data\n"));
2636 return gpg_error (GPG_ERR_GENERAL);
2638 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2641 log_error (_("error reading fingerprint DO\n"));
2643 return gpg_error (GPG_ERR_GENERAL);
2646 for (i=0; i < 20 && !fpr[i]; i++)
2649 if (i!=20 && !force)
2651 log_error (_("key already exists\n"));
2652 return gpg_error (GPG_ERR_EEXIST);
2655 log_info (_("existing key will be replaced\n"));
2656 else if (generating)
2657 log_info (_("generating new key\n"));
2659 log_info (_("writing new key\n"));
2664 /* Create a TLV tag and value and store it at BUFFER. Return the length
2665 of tag and length. A LENGTH greater than 65535 is truncated. */
2667 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2669 unsigned char *p = buffer;
2671 assert (tag <= 0xffff);
2677 else if (length < 256)
2684 if (length > 0xffff)
2696 build_privkey_template (app_t app, int keyno,
2697 const unsigned char *rsa_n, size_t rsa_n_len,
2698 const unsigned char *rsa_e, size_t rsa_e_len,
2699 const unsigned char *rsa_p, size_t rsa_p_len,
2700 const unsigned char *rsa_q, size_t rsa_q_len,
2701 const unsigned char *rsa_u, size_t rsa_u_len,
2702 const unsigned char *rsa_dp, size_t rsa_dp_len,
2703 const unsigned char *rsa_dq, size_t rsa_dq_len,
2704 unsigned char **result, size_t *resultlen)
2706 size_t rsa_e_reqlen;
2707 unsigned char privkey[7*(1+3+3)];
2709 unsigned char exthdr[2+2+3];
2711 unsigned char suffix[2+3];
2715 unsigned char *template;
2716 size_t template_size;
2721 switch (app->app_local->keyattr[keyno].rsa.format)
2730 return gpg_error (GPG_ERR_INV_VALUE);
2733 /* Get the required length for E. Rounded up to the nearest byte */
2734 rsa_e_reqlen = (app->app_local->keyattr[keyno].rsa.e_bits + 7) / 8;
2735 assert (rsa_e_len <= rsa_e_reqlen);
2737 /* Build the 7f48 cardholder private key template. */
2741 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2742 datalen += rsa_e_reqlen;
2744 tp += add_tlv (tp, 0x92, rsa_p_len);
2745 datalen += rsa_p_len;
2747 tp += add_tlv (tp, 0x93, rsa_q_len);
2748 datalen += rsa_q_len;
2750 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
2751 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2753 tp += add_tlv (tp, 0x94, rsa_u_len);
2754 datalen += rsa_u_len;
2755 tp += add_tlv (tp, 0x95, rsa_dp_len);
2756 datalen += rsa_dp_len;
2757 tp += add_tlv (tp, 0x96, rsa_dq_len);
2758 datalen += rsa_dq_len;
2761 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
2762 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2764 tp += add_tlv (tp, 0x97, rsa_n_len);
2765 datalen += rsa_n_len;
2767 privkey_len = tp - privkey;
2769 /* Build the extended header list without the private key template. */
2771 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2773 tp += add_tlv (tp, 0x7f48, privkey_len);
2774 exthdr_len = tp - exthdr;
2776 /* Build the 5f48 suffix of the data. */
2778 tp += add_tlv (tp, 0x5f48, datalen);
2779 suffix_len = tp - suffix;
2781 /* Now concatenate everything. */
2782 template_size = (1 + 3 /* 0x4d and len. */
2787 tp = template = xtrymalloc_secure (template_size);
2789 return gpg_error_from_syserror ();
2791 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2792 memcpy (tp, exthdr, exthdr_len);
2794 memcpy (tp, privkey, privkey_len);
2796 memcpy (tp, suffix, suffix_len);
2799 memcpy (tp, rsa_e, rsa_e_len);
2800 if (rsa_e_len < rsa_e_reqlen)
2802 /* Right justify E. */
2803 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2804 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2808 memcpy (tp, rsa_p, rsa_p_len);
2811 memcpy (tp, rsa_q, rsa_q_len);
2814 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
2815 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2817 memcpy (tp, rsa_u, rsa_u_len);
2819 memcpy (tp, rsa_dp, rsa_dp_len);
2821 memcpy (tp, rsa_dq, rsa_dq_len);
2825 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
2826 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2828 memcpy (tp, rsa_n, rsa_n_len);
2832 /* Sanity check. We don't know the exact length because we
2833 allocated 3 bytes for the first length header. */
2834 assert (tp - template <= template_size);
2837 *resultlen = tp - template;
2842 build_ecc_privkey_template (app_t app, int keyno,
2843 const unsigned char *ecc_d, size_t ecc_d_len,
2844 const unsigned char *ecc_q, size_t ecc_q_len,
2845 unsigned char **result, size_t *resultlen)
2847 unsigned char privkey[2+2];
2849 unsigned char exthdr[2+2+1];
2851 unsigned char suffix[2+1];
2855 unsigned char *template;
2856 size_t template_size;
2857 int pubkey_required;
2859 pubkey_required = !!(app->app_local->keyattr[keyno].ecc.flags
2865 /* Build the 7f48 cardholder private key template. */
2869 tp += add_tlv (tp, 0x92, ecc_d_len);
2870 datalen += ecc_d_len;
2872 if (pubkey_required)
2874 tp += add_tlv (tp, 0x99, ecc_q_len);
2875 datalen += ecc_q_len;
2878 privkey_len = tp - privkey;
2881 /* Build the extended header list without the private key template. */
2883 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2885 tp += add_tlv (tp, 0x7f48, privkey_len);
2886 exthdr_len = tp - exthdr;
2888 /* Build the 5f48 suffix of the data. */
2890 tp += add_tlv (tp, 0x5f48, datalen);
2891 suffix_len = tp - suffix;
2893 /* Now concatenate everything. */
2894 template_size = (1 + 1 /* 0x4d and len. */
2899 if (exthdr_len + privkey_len + suffix_len + datalen >= 128)
2901 tp = template = xtrymalloc_secure (template_size);
2903 return gpg_error_from_syserror ();
2905 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2906 memcpy (tp, exthdr, exthdr_len);
2908 memcpy (tp, privkey, privkey_len);
2910 memcpy (tp, suffix, suffix_len);
2913 memcpy (tp, ecc_d, ecc_d_len);
2916 if (pubkey_required)
2918 memcpy (tp, ecc_q, ecc_q_len);
2922 assert (tp - template == template_size);
2925 *resultlen = tp - template;
2930 /* Helper for do_writekley to change the size of a key. Not ethat
2931 this deletes the entire key without asking. */
2933 change_keyattr (app_t app, int keyno, const unsigned char *buf, size_t buflen,
2934 gpg_error_t (*pincb)(void*, const char *, char **),
2939 assert (keyno >=0 && keyno <= 2);
2941 /* Prepare for storing the key. */
2942 err = verify_chv3 (app, pincb, pincb_arg);
2946 /* Change the attribute. */
2947 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buf, buflen);
2949 log_error ("error changing key attribute (key=%d)\n", keyno+1);
2951 log_info ("key attribute changed (key=%d)\n", keyno+1);
2953 parse_algorithm_attribute (app, keyno);
2962 change_rsa_keyattr (app_t app, int keyno, unsigned int nbits,
2963 gpg_error_t (*pincb)(void*, const char *, char **),
2966 gpg_error_t err = 0;
2971 /* Read the current attributes into a buffer. */
2972 relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL);
2974 err = gpg_error (GPG_ERR_CARD);
2975 else if (buflen < 6 || buf[0] != PUBKEY_ALGO_RSA)
2977 /* Attriutes too short or not an RSA key. */
2979 err = gpg_error (GPG_ERR_CARD);
2983 /* We only change n_bits and don't touch anything else. Before we
2984 do so, we round up NBITS to a sensible way in the same way as
2985 gpg's key generation does it. This may help to sort out problems
2986 with a few bits too short keys. */
2987 nbits = ((nbits + 31) / 32) * 32;
2988 buf[1] = (nbits >> 8);
2990 err = change_keyattr (app, keyno, buf, buflen, pincb, pincb_arg);
2998 /* Helper to process an setattr command for name KEY-ATTR.
2999 In (VALUE,VALUELEN), it expects following string:
3000 RSA: "--force <key> <algo> rsa<nbits>"
3001 ECC: "--force <key> <algo> <curvename>"
3004 change_keyattr_from_string (app_t app,
3005 gpg_error_t (*pincb)(void*, const char *, char **),
3007 const void *value, size_t valuelen)
3009 gpg_error_t err = 0;
3011 int key, keyno, algo;
3014 /* VALUE is expected to be a string but not guaranteed to be
3015 terminated. Thus copy it to an allocated buffer first. */
3016 string = xtrymalloc (valuelen+1);
3018 return gpg_error_from_syserror ();
3019 memcpy (string, value, valuelen);
3020 string[valuelen] = 0;
3022 /* Because this function deletes the key we require the string
3023 "--force" in the data to make clear that something serious might
3025 sscanf (string, "--force %d %d %n", &key, &algo, &n);
3028 err = gpg_error (GPG_ERR_INV_DATA);
3033 if (keyno < 0 || keyno > 2)
3034 err = gpg_error (GPG_ERR_INV_ID);
3035 else if (algo == PUBKEY_ALGO_RSA)
3040 nbits = strtoul (string+n+3, NULL, 10);
3042 err = gpg_error (GPG_ERR_INV_DATA);
3043 else if (nbits < 1024)
3044 err = gpg_error (GPG_ERR_TOO_SHORT);
3045 else if (nbits > 4096)
3046 err = gpg_error (GPG_ERR_TOO_LARGE);
3048 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
3050 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
3051 || algo == PUBKEY_ALGO_EDDSA)
3055 const unsigned char *oidbuf;
3058 oidstr = openpgp_curve_to_oid (string+n, NULL);
3061 err = gpg_error (GPG_ERR_INV_DATA);
3065 err = openpgp_oid_from_str (oidstr, &oid);
3069 oidbuf = gcry_mpi_get_opaque (oid, &n);
3072 /* We have enough room at STRING. */
3074 memcpy (string+1, oidbuf+1, oid_len-1);
3075 err = change_keyattr (app, keyno, string, oid_len, pincb, pincb_arg);
3076 gcry_mpi_release (oid);
3079 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3088 rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3089 void *pincb_arg, int keyno,
3090 const unsigned char *buf, size_t buflen, int depth)
3093 const unsigned char *tok;
3095 int last_depth1, last_depth2;
3096 const unsigned char *rsa_n = NULL;
3097 const unsigned char *rsa_e = NULL;
3098 const unsigned char *rsa_p = NULL;
3099 const unsigned char *rsa_q = NULL;
3100 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
3102 unsigned int maxbits;
3103 unsigned char *template = NULL;
3105 size_t template_len;
3106 unsigned char fprbuf[20];
3109 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA)
3111 log_error (_("unsupported algorithm: %s"), "RSA");
3112 err = gpg_error (GPG_ERR_INV_VALUE);
3116 last_depth1 = depth;
3117 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3118 && depth && depth >= last_depth1)
3122 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3125 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3127 if (tok && toklen == 1)
3129 const unsigned char **mpi;
3134 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
3135 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
3136 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
3137 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
3138 default: mpi = NULL; mpi_len = NULL; break;
3142 err = gpg_error (GPG_ERR_DUP_VALUE);
3145 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3149 /* Strip off leading zero bytes and save. */
3150 for (;toklen && !*tok; toklen--, tok++)
3156 /* Skip until end of list. */
3157 last_depth2 = depth;
3158 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3159 && depth && depth >= last_depth2)
3164 /* Parse other attributes. */
3165 last_depth1 = depth;
3166 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3167 && depth && depth >= last_depth1)
3171 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3174 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3176 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3178 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3182 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3184 created_at = created_at*10 + (*tok - '0');
3187 /* Skip until end of list. */
3188 last_depth2 = depth;
3189 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3190 && depth && depth >= last_depth2)
3197 /* Check that we have all parameters and that they match the card
3201 log_error (_("creation timestamp missing\n"));
3202 err = gpg_error (GPG_ERR_INV_VALUE);
3206 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
3207 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
3209 log_info ("RSA modulus size is %u bits (%u bytes)\n",
3210 nbits, (unsigned int)rsa_n_len);
3211 if (nbits && nbits != maxbits
3212 && app->app_local->extcap.algo_attr_change)
3214 /* Try to switch the key to a new length. */
3215 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
3217 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
3219 if (nbits != maxbits)
3221 log_error (_("RSA modulus missing or not of size %d bits\n"),
3223 err = gpg_error (GPG_ERR_BAD_SECKEY);
3227 maxbits = app->app_local->keyattr[keyno].rsa.e_bits;
3228 if (maxbits > 32 && !app->app_local->extcap.is_v2)
3229 maxbits = 32; /* Our code for v1 does only support 32 bits. */
3230 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
3231 if (nbits < 2 || nbits > maxbits)
3233 log_error (_("RSA public exponent missing or larger than %d bits\n"),
3235 err = gpg_error (GPG_ERR_BAD_SECKEY);
3239 maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2;
3240 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
3241 if (nbits != maxbits)
3243 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3245 err = gpg_error (GPG_ERR_BAD_SECKEY);
3248 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
3249 if (nbits != maxbits)
3251 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3253 err = gpg_error (GPG_ERR_BAD_SECKEY);
3257 /* We need to remove the cached public key. */
3258 xfree (app->app_local->pk[keyno].key);
3259 app->app_local->pk[keyno].key = NULL;
3260 app->app_local->pk[keyno].keylen = 0;
3261 app->app_local->pk[keyno].read_done = 0;
3264 if (app->app_local->extcap.is_v2)
3266 unsigned char *rsa_u, *rsa_dp, *rsa_dq;
3267 size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
3268 gcry_mpi_t mpi_e, mpi_p, mpi_q;
3269 gcry_mpi_t mpi_u = gcry_mpi_snew (0);
3270 gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
3271 gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
3272 gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
3275 /* Calculate the u, dp and dq components needed by RSA_CRT cards */
3276 gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
3277 gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
3278 gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
3280 gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
3281 gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
3282 gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
3283 gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
3284 gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
3286 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
3287 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
3288 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
3290 gcry_mpi_release (mpi_e);
3291 gcry_mpi_release (mpi_p);
3292 gcry_mpi_release (mpi_q);
3293 gcry_mpi_release (mpi_u);
3294 gcry_mpi_release (mpi_dp);
3295 gcry_mpi_release (mpi_dq);
3296 gcry_mpi_release (mpi_tmp);
3298 /* Build the private key template as described in section 4.3.3.7 of
3299 the OpenPGP card specs version 2.0. */
3300 err = build_privkey_template (app, keyno,
3308 &template, &template_len);
3316 /* Prepare for storing the key. */
3317 err = verify_chv3 (app, pincb, pincb_arg);
3321 /* Store the key. */
3322 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3323 exmode = 1; /* Use extended length w/o a limit. */
3324 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3328 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3329 template, template_len);
3333 /* Build the private key template as described in section 4.3.3.6 of
3334 the OpenPGP card specs version 1.1:
3335 0xC0 <length> public exponent
3336 0xC1 <length> prime p
3337 0xC2 <length> prime q
3339 assert (rsa_e_len <= 4);
3340 template_len = (1 + 1 + 4
3342 + 1 + 1 + rsa_q_len);
3343 template = tp = xtrymalloc_secure (template_len);
3346 err = gpg_error_from_syserror ();
3351 memcpy (tp, rsa_e, rsa_e_len);
3354 /* Right justify E. */
3355 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
3356 memset (tp, 0, 4-rsa_e_len);
3362 memcpy (tp, rsa_p, rsa_p_len);
3367 memcpy (tp, rsa_q, rsa_q_len);
3370 assert (tp - template == template_len);
3372 /* Prepare for storing the key. */
3373 err = verify_chv3 (app, pincb, pincb_arg);
3377 /* Store the key. */
3378 err = iso7816_put_data (app->slot, 0,
3379 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
3380 template, template_len);
3384 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3388 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
3389 rsa_n, rsa_n_len, rsa_e, rsa_e_len);
3401 ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3402 void *pincb_arg, int keyno,
3403 const unsigned char *buf, size_t buflen, int depth)
3406 const unsigned char *tok;
3408 int last_depth1, last_depth2;
3409 const unsigned char *ecc_q = NULL;
3410 const unsigned char *ecc_d = NULL;
3411 size_t ecc_q_len, ecc_d_len;
3412 const char *curve = NULL;
3415 int flag_djb_tweak = 0;
3417 gcry_mpi_t oid = NULL;
3418 const unsigned char *oidbuf;
3421 unsigned char fprbuf[20];
3423 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3424 curve = "NIST P-256" */
3425 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3426 curve = "secp256k1" */
3427 /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)):
3428 curve = "Ed25519" */
3429 last_depth1 = depth;
3430 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3431 && depth && depth >= last_depth1)
3435 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3438 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3441 if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
3445 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3448 curve_name = xtrymalloc (toklen+1);
3451 err = gpg_error_from_syserror ();
3455 memcpy (curve_name, tok, toklen);
3456 curve_name[toklen] = 0;
3457 curve = openpgp_is_curve_supported (curve_name, NULL, NULL);
3460 else if (tok && toklen == 5 && !memcmp (tok, "flags", 5))
3462 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3467 if ((toklen == 5 && !memcmp (tok, "eddsa", 5))
3468 || (toklen == 9 && !memcmp (tok, "djb-tweak", 9)))
3472 else if (tok && toklen == 1)
3474 const unsigned char **buf2;
3476 int native = flag_djb_tweak;
3480 case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break;
3481 case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; native = 0; break;
3482 default: buf2 = NULL; buf2len = NULL; break;
3486 err = gpg_error (GPG_ERR_DUP_VALUE);
3489 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3494 /* Strip off leading zero bytes and save. */
3495 for (;toklen && !*tok; toklen--, tok++)
3502 /* Skip until end of list. */
3503 last_depth2 = depth;
3504 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3505 && depth && depth >= last_depth2)
3510 /* Parse other attributes. */
3511 last_depth1 = depth;
3512 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3513 && depth && depth >= last_depth1)
3517 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3520 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3522 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3524 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3528 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3530 created_at = created_at*10 + (*tok - '0');
3533 /* Skip until end of list. */
3534 last_depth2 = depth;
3535 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3536 && depth && depth >= last_depth2)
3543 /* Check that we have all parameters and that they match the card
3547 log_error (_("unsupported curve\n"));
3548 err = gpg_error (GPG_ERR_INV_VALUE);
3553 log_error (_("creation timestamp missing\n"));
3554 err = gpg_error (GPG_ERR_INV_VALUE);
3557 if (flag_djb_tweak && keyno != 1)
3558 algo = PUBKEY_ALGO_EDDSA;
3559 else if (keyno == 1)
3560 algo = PUBKEY_ALGO_ECDH;
3562 algo = PUBKEY_ALGO_ECDSA;
3564 oidstr = openpgp_curve_to_oid (curve, NULL);
3565 err = openpgp_oid_from_str (oidstr, &oid);
3568 oidbuf = gcry_mpi_get_opaque (oid, &n);
3571 err = gpg_error_from_syserror ();
3576 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC
3577 || app->app_local->keyattr[keyno].ecc.curve != curve
3578 || (flag_djb_tweak !=
3579 (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)))
3581 if (app->app_local->extcap.algo_attr_change)
3583 unsigned char *keyattr;
3587 err = gpg_error (GPG_ERR_INTERNAL);
3590 keyattr = xtrymalloc (oid_len);
3593 err = gpg_error_from_syserror ();
3597 memcpy (keyattr+1, oidbuf+1, oid_len-1);
3598 err = change_keyattr (app, keyno, keyattr, oid_len, pincb, pincb_arg);
3605 log_error ("key attribute on card doesn't match\n");
3606 err = gpg_error (GPG_ERR_INV_VALUE);
3612 log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
3614 /* We need to remove the cached public key. */
3615 xfree (app->app_local->pk[keyno].key);
3616 app->app_local->pk[keyno].key = NULL;
3617 app->app_local->pk[keyno].keylen = 0;
3618 app->app_local->pk[keyno].read_done = 0;
3620 if (app->app_local->extcap.is_v2)
3622 /* Build the private key template as described in section 4.3.3.7 of
3623 the OpenPGP card specs version 2.0. */
3624 unsigned char *template;
3625 size_t template_len;
3628 err = build_ecc_privkey_template (app, keyno,
3631 &template, &template_len);
3635 /* Prepare for storing the key. */
3636 err = verify_chv3 (app, pincb, pincb_arg);
3643 /* Store the key. */
3644 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3645 exmode = 1; /* Use extended length w/o a limit. */
3646 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3650 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3651 template, template_len);
3655 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3659 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3663 err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
3664 ecc_q, ecc_q_len, ecdh_params (curve), (size_t)4);
3667 gcry_mpi_release (oid);
3671 /* Handle the WRITEKEY command for OpenPGP. This function expects a
3672 canonical encoded S-expression with the secret key in KEYDATA and
3673 its length (for assertions) in KEYDATALEN. KEYID needs to be the
3674 usual keyid which for OpenPGP is the string "OPENPGP.n" with
3675 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
3676 get overwritten. PINCB and PINCB_ARG are the usual arguments for
3677 the pinentry callback. */
3679 do_writekey (app_t app, ctrl_t ctrl,
3680 const char *keyid, unsigned int flags,
3681 gpg_error_t (*pincb)(void*, const char *, char **),
3683 const unsigned char *keydata, size_t keydatalen)
3686 int force = (flags & 1);
3688 const unsigned char *buf, *tok;
3689 size_t buflen, toklen;
3694 if (!strcmp (keyid, "OPENPGP.1"))
3696 else if (!strcmp (keyid, "OPENPGP.2"))
3698 else if (!strcmp (keyid, "OPENPGP.3"))
3701 return gpg_error (GPG_ERR_INV_ID);
3703 err = does_key_exist (app, keyno, 0, force);
3709 Parse the S-expression
3712 buflen = keydatalen;
3714 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3716 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3718 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
3722 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
3723 log_info ("protected-private-key passed to writekey\n");
3724 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
3725 log_info ("shadowed-private-key passed to writekey\n");
3726 err = gpg_error (GPG_ERR_BAD_SECKEY);
3729 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3731 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3733 if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
3734 err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3735 else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
3736 err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3739 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
3749 /* Handle the GENKEY command. */
3751 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
3753 gpg_error_t (*pincb)(void*, const char *, char **),
3758 unsigned char *buffer = NULL;
3759 const unsigned char *keydata;
3760 size_t buflen, keydatalen;
3762 int keyno = atoi (keynostr) - 1;
3763 int force = (flags & 1);
3766 int le_value = 256; /* Use legacy value. */
3768 if (keyno < 0 || keyno > 2)
3769 return gpg_error (GPG_ERR_INV_ID);
3771 /* We flush the cache to increase the traffic before a key
3772 generation. This _might_ help a card to gather more entropy. */
3775 /* Obviously we need to remove the cached public key. */
3776 xfree (app->app_local->pk[keyno].key);
3777 app->app_local->pk[keyno].key = NULL;
3778 app->app_local->pk[keyno].keylen = 0;
3779 app->app_local->pk[keyno].read_done = 0;
3781 /* Check whether a key already exists. */
3782 err = does_key_exist (app, keyno, 1, force);
3786 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
3788 unsigned int keybits = app->app_local->keyattr[keyno].rsa.n_bits;
3790 /* Because we send the key parameter back via status lines we need
3791 to put a limit on the max. allowed keysize. 2048 bit will
3792 already lead to a 527 byte long status line and thus a 4096 bit
3793 key would exceed the Assuan line length limit. */
3795 return gpg_error (GPG_ERR_TOO_LARGE);
3797 if (app->app_local->cardcap.ext_lc_le && keybits > RSA_SMALL_SIZE_KEY
3798 && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
3800 exmode = 1; /* Use extended length w/o a limit. */
3801 le_value = determine_rsa_response (app, keyno);
3802 /* No need to check le_value because it comes from a 16 bit
3803 value and thus can't create an overflow on a 32 bit
3808 /* Prepare for key generation by verifying the Admin PIN. */
3809 err = verify_chv3 (app, pincb, pincb_arg);
3814 log_info (_("please wait while key is being generated ...\n"));
3815 start_at = time (NULL);
3816 err = iso7816_generate_keypair (app->slot, exmode,
3817 (keyno == 0? "\xB6" :
3818 keyno == 1? "\xB8" : "\xA4"),
3819 2, le_value, &buffer, &buflen);
3822 log_error (_("generating key failed\n"));
3823 return gpg_error (GPG_ERR_CARD);
3827 int nsecs = (int)(time (NULL) - start_at);
3828 log_info (ngettext("key generation completed (%d second)\n",
3829 "key generation completed (%d seconds)\n",
3833 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
3836 err = gpg_error (GPG_ERR_CARD);
3837 log_error (_("response does not contain the public key data\n"));
3841 created_at = (u32)(createtime? createtime : gnupg_get_time ());
3842 sprintf (numbuf, "%u", created_at);
3843 send_status_info (ctrl, "KEY-CREATED-AT",
3844 numbuf, (size_t)strlen(numbuf), NULL, 0);
3846 err = read_public_key (app, ctrl, created_at, keyno, buffer, buflen);
3853 static unsigned long
3854 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
3859 ul = (value[0] << 16) | (value[1] << 8) | value[2];
3862 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
3868 static unsigned long
3869 get_sig_counter (app_t app)
3872 unsigned char *value;
3876 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
3879 ul = convert_sig_counter_value (value, valuelen);
3885 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
3887 const unsigned char *fpr;
3888 unsigned char *buffer;
3892 assert (keyno >= 0 && keyno <= 2);
3894 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
3897 log_error (_("error reading application data\n"));
3898 return gpg_error (GPG_ERR_GENERAL);
3900 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
3901 if (!fpr || n != 60)
3904 log_error (_("error reading fingerprint DO\n"));
3905 return gpg_error (GPG_ERR_GENERAL);
3908 for (i=0; i < 20; i++)
3909 if (sha1fpr[i] != fpr[i])
3912 log_info (_("fingerprint on card does not match requested one\n"));
3913 return gpg_error (GPG_ERR_WRONG_SECKEY);
3920 /* If a fingerprint has been specified check it against the one on the
3921 card. This allows for a meaningful error message in case the key
3922 on the card has been replaced but the shadow information known to
3923 gpg has not been updated. If there is no fingerprint we assume
3924 that this is okay. */
3926 check_against_given_fingerprint (app_t app, const char *fpr, int key)
3928 unsigned char tmp[20];
3932 for (s=fpr, n=0; hexdigitp (s); s++, n++)
3935 return gpg_error (GPG_ERR_INV_ID);
3939 return gpg_error (GPG_ERR_INV_ID);
3941 for (s=fpr, n=0; n < 20; s += 2, n++)
3942 tmp[n] = xtoi_2 (s);
3943 return compare_fingerprint (app, key-1, tmp);
3948 /* Compute a digital signature on INDATA which is expected to be the
3949 raw message digest. For this application the KEYIDSTR consists of
3950 the serialnumber and the fingerprint delimited by a slash.
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 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3958 operation to the auth command.
3961 do_sign (app_t app, const char *keyidstr, int hashalgo,
3962 gpg_error_t (*pincb)(void*, const char *, char **),
3964 const void *indata, size_t indatalen,
3965 unsigned char **outdata, size_t *outdatalen )
3967 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3968 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3969 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3970 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
3971 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3972 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3973 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3974 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3975 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3977 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3978 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3979 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3981 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3982 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3983 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3985 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3986 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3987 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3990 unsigned char data[19+64];
3992 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3995 const char *fpr = NULL;
3996 unsigned long sigcount;
3998 int exmode, le_value;
4000 if (!keyidstr || !*keyidstr)
4001 return gpg_error (GPG_ERR_INV_VALUE);
4003 /* Strip off known prefixes. */
4004 #define X(a,b,c,d) \
4005 if (hashalgo == GCRY_MD_ ## a \
4007 && indatalen == sizeof b ## _prefix + (c) \
4008 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
4010 indata = (const char*)indata + sizeof b ## _prefix; \
4011 indatalen -= sizeof b ## _prefix; \
4014 if (indatalen == 20)
4015 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
4016 else X(SHA1, sha1, 20, 1)
4017 else X(RMD160, rmd160, 20, 1)
4018 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
4019 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
4020 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
4021 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
4022 else if ((indatalen == 28 || indatalen == 32
4023 || indatalen == 48 || indatalen ==64)
4024 && app->app_local->extcap.is_v2)
4025 ; /* Assume a plain SHA-3 digest has been given. */
4028 log_error (_("card does not support digest algorithm %s\n"),
4029 gcry_md_algo_name (hashalgo));
4030 /* Or the supplied digest length does not match an algorithm. */
4031 return gpg_error (GPG_ERR_INV_VALUE);
4035 /* Check whether an OpenPGP card of any version has been requested. */
4036 if (!strcmp (keyidstr, "OPENPGP.1"))
4038 else if (!strcmp (keyidstr, "OPENPGP.3"))
4040 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4041 return gpg_error (GPG_ERR_INV_ID);
4044 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4047 return gpg_error (GPG_ERR_INV_ID);
4049 ; /* no fingerprint given: we allow this for now. */
4053 return gpg_error (GPG_ERR_INV_ID);
4055 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4056 tmp_sn[n] = xtoi_2 (s);
4058 if (app->serialnolen != 16)
4059 return gpg_error (GPG_ERR_INV_CARD);
4060 if (memcmp (app->serialno, tmp_sn, 16))
4061 return gpg_error (GPG_ERR_WRONG_CARD);
4064 /* If a fingerprint has been specified check it against the one on
4065 the card. This is allows for a meaningful error message in case
4066 the key on the card has been replaced but the shadow information
4067 known to gpg was not updated. If there is no fingerprint, gpg
4068 will detect a bogus signature anyway due to the
4069 verify-after-signing feature. */
4070 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
4074 /* Concatenate prefix and digest. */
4076 if (hashalgo == GCRY_MD_ ## a && (d) ) \
4078 datalen = sizeof b ## _prefix + indatalen; \
4079 assert (datalen <= sizeof data); \
4080 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
4081 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
4085 || app->app_local->keyattr[use_auth? 2: 0].key_type == KEY_TYPE_RSA)
4088 else X(RMD160, rmd160, 1)
4089 else X(SHA224, sha224, app->app_local->extcap.is_v2)
4090 else X(SHA256, sha256, app->app_local->extcap.is_v2)
4091 else X(SHA384, sha384, app->app_local->extcap.is_v2)
4092 else X(SHA512, sha512, app->app_local->extcap.is_v2)
4094 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
4098 datalen = indatalen;
4099 memcpy (data, indata, indatalen);
4103 /* Redirect to the AUTH command if asked to. */
4106 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
4108 outdata, outdatalen);
4111 /* Show the number of signature done using this key. */
4112 sigcount = get_sig_counter (app);
4113 log_info (_("signatures created so far: %lu\n"), sigcount);
4115 /* Check CHV if needed. */
4116 if (!app->did_chv1 || app->force_chv1 )
4120 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
4126 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
4127 sync, thus we verify CHV2 here using the given PIN. Cards
4128 with version2 to not have the need for a separate CHV2 and
4129 internally use just one. Obviously we can't do that if the
4130 pinpad has been used. */
4131 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
4133 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
4134 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
4135 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
4138 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
4140 flush_cache_after_error (app);
4149 if (app->app_local->cardcap.ext_lc_le
4150 && app->app_local->keyattr[0].key_type == KEY_TYPE_RSA
4151 && app->app_local->keyattr[0].rsa.n_bits > RSA_SMALL_SIZE_OP)
4153 exmode = 1; /* Use extended length. */
4154 le_value = app->app_local->keyattr[0].rsa.n_bits / 8;
4161 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
4162 outdata, outdatalen);
4166 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
4167 on INDATA which is expected to be the raw message digest. For this
4168 application the KEYIDSTR consists of the serialnumber and the
4169 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
4172 Note that this function may return the error code
4173 GPG_ERR_WRONG_CARD to indicate that the card currently present does
4174 not match the one required for the requested action (e.g. the
4175 serial number does not match). */
4177 do_auth (app_t app, const char *keyidstr,
4178 gpg_error_t (*pincb)(void*, const char *, char **),
4180 const void *indata, size_t indatalen,
4181 unsigned char **outdata, size_t *outdatalen )
4184 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
4187 const char *fpr = NULL;
4189 if (!keyidstr || !*keyidstr)
4190 return gpg_error (GPG_ERR_INV_VALUE);
4191 if (app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
4192 && indatalen > 101) /* For a 2048 bit key. */
4193 return gpg_error (GPG_ERR_INV_VALUE);
4195 if (app->app_local->keyattr[2].key_type == KEY_TYPE_ECC)
4197 if (!(app->app_local->keyattr[2].ecc.flags & ECC_FLAG_DJB_TWEAK)
4198 && (indatalen == 51 || indatalen == 67 || indatalen == 83))
4200 const char *p = (const char *)indata + 19;
4206 const char *p = (const char *)indata + 15;
4212 /* Check whether an OpenPGP card of any version has been requested. */
4213 if (!strcmp (keyidstr, "OPENPGP.3"))
4215 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4216 return gpg_error (GPG_ERR_INV_ID);
4219 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4222 return gpg_error (GPG_ERR_INV_ID);
4224 ; /* no fingerprint given: we allow this for now. */
4228 return gpg_error (GPG_ERR_INV_ID);
4230 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4231 tmp_sn[n] = xtoi_2 (s);
4233 if (app->serialnolen != 16)
4234 return gpg_error (GPG_ERR_INV_CARD);
4235 if (memcmp (app->serialno, tmp_sn, 16))
4236 return gpg_error (GPG_ERR_WRONG_CARD);
4239 /* If a fingerprint has been specified check it against the one on
4240 the card. This is allows for a meaningful error message in case
4241 the key on the card has been replaced but the shadow information
4242 known to gpg was not updated. If there is no fingerprint, gpg
4243 will detect a bogus signature anyway due to the
4244 verify-after-signing feature. */
4245 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
4249 rc = verify_chv2 (app, pincb, pincb_arg);
4252 int exmode, le_value;
4254 if (app->app_local->cardcap.ext_lc_le
4255 && app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
4256 && app->app_local->keyattr[2].rsa.n_bits > RSA_SMALL_SIZE_OP)
4258 exmode = 1; /* Use extended length. */
4259 le_value = app->app_local->keyattr[2].rsa.n_bits / 8;
4266 rc = iso7816_internal_authenticate (app->slot, exmode,
4267 indata, indatalen, le_value,
4268 outdata, outdatalen);
4275 do_decipher (app_t app, const char *keyidstr,
4276 gpg_error_t (*pincb)(void*, const char *, char **),
4278 const void *indata, size_t indatalen,
4279 unsigned char **outdata, size_t *outdatalen,
4280 unsigned int *r_info)
4283 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
4286 const char *fpr = NULL;
4287 int exmode, le_value;
4288 unsigned char *fixbuf = NULL;
4292 if (!keyidstr || !*keyidstr || !indatalen)
4293 return gpg_error (GPG_ERR_INV_VALUE);
4295 /* Check whether an OpenPGP card of any version has been requested. */
4296 if (!strcmp (keyidstr, "OPENPGP.2"))
4298 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4299 return gpg_error (GPG_ERR_INV_ID);
4302 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4305 return gpg_error (GPG_ERR_INV_ID);
4307 ; /* no fingerprint given: we allow this for now. */
4311 return gpg_error (GPG_ERR_INV_ID);
4313 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4314 tmp_sn[n] = xtoi_2 (s);
4316 if (app->serialnolen != 16)
4317 return gpg_error (GPG_ERR_INV_CARD);
4318 if (memcmp (app->serialno, tmp_sn, 16))
4319 return gpg_error (GPG_ERR_WRONG_CARD);
4322 /* If a fingerprint has been specified check it against the one on
4323 the card. This is allows for a meaningful error message in case
4324 the key on the card has been replaced but the shadow information
4325 known to gpg was not updated. If there is no fingerprint, the
4326 decryption won't produce the right plaintext anyway. */
4327 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
4331 rc = verify_chv2 (app, pincb, pincb_arg);
4335 if ((indatalen == 16 + 1 || indatalen == 32 + 1)
4336 && ((char *)indata)[0] == 0x02)
4338 /* PSO:DECIPHER with symmetric key. */
4341 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA)
4343 /* We might encounter a couple of leading zeroes in the
4344 cryptogram. Due to internal use of MPIs these leading zeroes
4345 are stripped. However the OpenPGP card expects exactly 128
4346 bytes for the cryptogram (for a 1k key). Thus we need to fix
4347 it up. We do this for up to 16 leading zero bytes; a
4348 cryptogram with more than this is with a very high
4349 probability anyway broken. If a signed conversion was used
4350 we may also encounter one leading zero followed by the correct
4351 length. We fix that as well. */
4352 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
4353 fixuplen = 128 - indatalen;
4354 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
4355 fixuplen = 192 - indatalen;
4356 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
4357 fixuplen = 256 - indatalen;
4358 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
4359 fixuplen = 384 - indatalen;
4360 else if (indatalen >= (512-16) && indatalen < 512) /* 4096 bit key. */
4361 fixuplen = 512 - indatalen;
4362 else if (!*(const char *)indata && (indatalen == 129
4366 || indatalen == 513))
4373 /* While we have to prepend stuff anyway, we can also
4374 include the padding byte here so that iso1816_decipher
4375 does not need to do another data mangling. */
4378 fixbuf = xtrymalloc (fixuplen + indatalen);
4380 return gpg_error_from_syserror ();
4382 memset (fixbuf, 0, fixuplen);
4383 memcpy (fixbuf+fixuplen, indata, indatalen);
4385 indatalen = fixuplen + indatalen;
4386 padind = -1; /* Already padded. */
4388 else if (fixuplen < 0)
4390 /* We use the extra leading zero as the padding byte. */
4394 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
4396 int old_format_len = 0;
4398 if ((app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK))
4400 if (indatalen > 32 && (indatalen % 2))
4402 * Skip the prefix. It may be 0x40 (in new format), or MPI
4403 * head of 0x00 (in old format).
4405 indata = (const char *)indata + 1;
4408 else if (indatalen < 32)
4410 * Old format trancated by MPI handling.
4412 old_format_len = indatalen;
4418 fixbuf = xtrymalloc (fixuplen + indatalen);
4420 return gpg_error_from_syserror ();
4422 /* Build 'Cipher DO' */
4424 fixbuf[1] = (char)(indatalen+5);
4427 fixbuf[4] = (char)(indatalen+2);
4429 fixbuf[6] = (char)indatalen;
4432 memset (fixbuf+fixuplen, 0, 32 - old_format_len);
4433 memcpy (fixbuf+fixuplen + 32 - old_format_len,
4434 indata, old_format_len);
4438 memcpy (fixbuf+fixuplen, indata, indatalen);
4441 indatalen = fixuplen + indatalen;
4446 return gpg_error (GPG_ERR_INV_VALUE);
4448 if (app->app_local->cardcap.ext_lc_le
4450 || (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA
4451 && app->app_local->keyattr[1].rsa.n_bits > RSA_SMALL_SIZE_OP)))
4453 exmode = 1; /* Extended length w/o a limit. */
4454 le_value = app->app_local->keyattr[1].rsa.n_bits / 8;
4456 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
4458 exmode = -254; /* Command chaining with max. 254 bytes. */
4462 exmode = le_value = 0;
4464 rc = iso7816_decipher (app->slot, exmode,
4465 indata, indatalen, le_value, padind,
4466 outdata, outdatalen);
4468 if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
4470 unsigned char prefix = 0;
4472 if (app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK)
4474 else if ((*outdatalen % 2) == 0) /* No 0x04 -> x-coordinate only */
4478 { /* Add the prefix */
4479 fixbuf = xtrymalloc (*outdatalen + 1);
4483 return gpg_error_from_syserror ();
4486 memcpy (fixbuf+1, *outdata, *outdatalen);
4489 *outdatalen = *outdatalen + 1;
4493 if (gpg_err_code (rc) == GPG_ERR_CARD /* actual SW is 0x640a */
4494 && app->app_local->manufacturer == 5
4495 && app->card_version == 0x0200)
4496 log_info ("NOTE: Cards with manufacturer id 5 and s/n <= 346 (0x15a)"
4497 " do not work with encryption keys > 2048 bits\n");
4499 *r_info |= APP_DECIPHER_INFO_NOPAD;
4505 /* Perform a simple verify operation for CHV1 and CHV2, so that
4506 further operations won't ask for CHV2 and it is possible to do a
4507 cheap check on the PIN: If there is something wrong with the PIN
4508 entry system, only the regular CHV will get blocked and not the
4509 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
4510 optional fingerprint part will be ignored.
4512 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
4513 the "[CHV3]" being a literal string: The Admin Pin is checked if
4514 and only if the retry counter is still at 3. */
4516 do_check_pin (app_t app, const char *keyidstr,
4517 gpg_error_t (*pincb)(void*, const char *, char **),
4520 unsigned char tmp_sn[20];
4525 if (!keyidstr || !*keyidstr)
4526 return gpg_error (GPG_ERR_INV_VALUE);
4528 /* Check whether an OpenPGP card of any version has been requested. */
4529 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4530 return gpg_error (GPG_ERR_INV_ID);
4532 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4535 return gpg_error (GPG_ERR_INV_ID);
4537 ; /* No fingerprint given: we allow this for now. */
4539 ; /* We ignore a fingerprint. */
4540 else if (!strcmp (s, "[CHV3]") )
4543 return gpg_error (GPG_ERR_INV_ID);
4545 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4546 tmp_sn[n] = xtoi_2 (s);
4548 if (app->serialnolen != 16)
4549 return gpg_error (GPG_ERR_INV_CARD);
4550 if (memcmp (app->serialno, tmp_sn, 16))
4551 return gpg_error (GPG_ERR_WRONG_CARD);
4553 /* Yes, there is a race conditions: The user might pull the card
4554 right here and we won't notice that. However this is not a
4555 problem and the check above is merely for a graceful failure
4556 between operations. */
4561 unsigned char *value;
4565 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
4566 if (!relptr || valuelen < 7)
4568 log_error (_("error retrieving CHV status from card\n"));
4570 return gpg_error (GPG_ERR_CARD);
4577 log_info (_("card is permanently locked!\n"));
4578 return gpg_error (GPG_ERR_BAD_PIN);
4582 log_info (_("verification of Admin PIN is currently prohibited "
4583 "through this command\n"));
4584 return gpg_error (GPG_ERR_GENERAL);
4587 app->did_chv3 = 0; /* Force verification. */
4588 return verify_chv3 (app, pincb, pincb_arg);
4591 return verify_chv2 (app, pincb, pincb_arg);
4595 /* Show information about card capabilities. */
4597 show_caps (struct app_local_s *s)
4599 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
4600 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
4601 if (s->extcap.get_challenge)
4602 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
4603 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
4604 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
4605 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
4606 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
4607 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
4608 if (s->extcap.sm_supported)
4609 log_printf (" (%s)", s->extcap.sm_algo==2? "3DES":
4610 (s->extcap.sm_algo==2? "AES-128" : "AES-256"));
4611 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
4612 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
4613 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
4614 log_info ("Status Indicator: %02X\n", s->status_indicator);
4615 log_info ("Symmetric crypto: %s\n", s->extcap.has_decrypt? "yes":"no");
4616 log_info ("Button..........: %s\n", s->extcap.has_button? "yes":"no");
4618 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
4619 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
4623 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
4626 parse_historical (struct app_local_s *apploc,
4627 const unsigned char * buffer, size_t buflen)
4629 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
4632 log_error ("warning: historical bytes are too short\n");
4633 return; /* Too short. */
4637 log_error ("warning: bad category indicator in historical bytes\n");
4641 /* Skip category indicator. */
4645 /* Get the status indicator. */
4646 apploc->status_indicator = buffer[buflen-3];
4649 /* Parse the compact TLV. */
4652 unsigned int tag = (*buffer & 0xf0) >> 4;
4653 unsigned int len = (*buffer & 0x0f);
4656 log_error ("warning: bad Compact-TLV in historical bytes\n");
4657 return; /* Error. */
4661 if (tag == 7 && len == 3)
4663 /* Card capabilities. */
4664 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
4665 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
4674 * Check if the OID in an DER encoding is available by GnuPG/libgcrypt,
4675 * and return the curve name. Return NULL if not available.
4676 * The constant string is not allocated dynamically, never free it.
4679 ecc_curve (unsigned char *buf, size_t buflen)
4684 unsigned char *oidbuf;
4686 oidbuf = xtrymalloc (buflen + 1);
4690 memcpy (oidbuf+1, buf, buflen);
4692 oid = gcry_mpi_set_opaque (NULL, oidbuf, (buflen+1) * 8);
4699 oidstr = openpgp_oid_to_str (oid);
4700 gcry_mpi_release (oid);
4704 result = openpgp_oid_to_curve (oidstr, 1);
4710 /* Parse and optionally show the algorithm attributes for KEYNO.
4711 KEYNO must be in the range 0..2. */
4713 parse_algorithm_attribute (app_t app, int keyno)
4715 unsigned char *buffer;
4718 const char desc[3][5] = {"sign", "encr", "auth"};
4720 assert (keyno >=0 && keyno <= 2);
4722 app->app_local->keyattr[keyno].key_type = KEY_TYPE_RSA;
4723 app->app_local->keyattr[keyno].rsa.n_bits = 0;
4725 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
4728 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
4733 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
4739 log_info ("Key-Attr-%s ..: ", desc[keyno]);
4740 if (*buffer == PUBKEY_ALGO_RSA && (buflen == 5 || buflen == 6))
4742 app->app_local->keyattr[keyno].rsa.n_bits = (buffer[1]<<8 | buffer[2]);
4743 app->app_local->keyattr[keyno].rsa.e_bits = (buffer[3]<<8 | buffer[4]);
4744 app->app_local->keyattr[keyno].rsa.format = 0;
4746 app->app_local->keyattr[keyno].rsa.format = RSA_STD;
4748 app->app_local->keyattr[keyno].rsa.format = (buffer[5] == 0? RSA_STD :
4749 buffer[5] == 1? RSA_STD_N :
4750 buffer[5] == 2? RSA_CRT :
4751 buffer[5] == 3? RSA_CRT_N :
4756 ("RSA, n=%u, e=%u, fmt=%s\n",
4757 app->app_local->keyattr[keyno].rsa.n_bits,
4758 app->app_local->keyattr[keyno].rsa.e_bits,
4759 app->app_local->keyattr[keyno].rsa.format == RSA_STD? "std" :
4760 app->app_local->keyattr[keyno].rsa.format == RSA_STD_N?"std+n":
4761 app->app_local->keyattr[keyno].rsa.format == RSA_CRT? "crt" :
4762 app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N?"crt+n":"?");
4764 else if (*buffer == PUBKEY_ALGO_ECDH || *buffer == PUBKEY_ALGO_ECDSA
4765 || *buffer == PUBKEY_ALGO_EDDSA)
4768 int oidlen = buflen - 1;
4770 app->app_local->keyattr[keyno].ecc.flags = 0;
4772 if (buffer[buflen-1] == 0x00 || buffer[buflen-1] == 0xff)
4773 { /* Found "pubkey required"-byte for private key template. */
4775 if (buffer[buflen-1] == 0xff)
4776 app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_PUBKEY;
4779 curve = ecc_curve (buffer + 1, oidlen);
4782 log_printhex ("Curve with OID not supported: ", buffer+1, buflen-1);
4785 app->app_local->keyattr[keyno].key_type = KEY_TYPE_ECC;
4786 app->app_local->keyattr[keyno].ecc.curve = curve;
4787 if (*buffer == PUBKEY_ALGO_EDDSA
4788 || (*buffer == PUBKEY_ALGO_ECDH
4789 && !strcmp (app->app_local->keyattr[keyno].ecc.curve,
4791 app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_DJB_TWEAK;
4794 ("ECC, curve=%s%s\n", app->app_local->keyattr[keyno].ecc.curve,
4795 !(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)?
4796 "": keyno==1? " (djb-tweak)": " (eddsa)");
4799 else if (opt.verbose)
4800 log_printhex ("", buffer, buflen);
4805 /* Select the OpenPGP application on the card in SLOT. This function
4806 must be used before any other OpenPGP application functions. */
4808 app_select_openpgp (app_t app)
4810 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
4811 int slot = app->slot;
4813 unsigned char *buffer;
4817 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
4818 special flag value. */
4819 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
4822 unsigned int manufacturer;
4824 app->apptype = "OPENPGP";
4829 app->app_local = NULL;
4831 /* The OpenPGP card returns the serial number as part of the
4832 AID; because we prefer to use OpenPGP serial numbers, we
4833 replace a possibly already set one from a EF.GDO with this
4834 one. Note, that for current OpenPGP cards, no EF.GDO exists
4835 and thus it won't matter at all. */
4836 rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
4842 log_printhex ("", buffer, buflen);
4845 app->card_version = buffer[6] << 8;
4846 app->card_version |= buffer[7];
4847 manufacturer = (buffer[8]<<8 | buffer[9]);
4849 xfree (app->serialno);
4850 app->serialno = buffer;
4851 app->serialnolen = buflen;
4853 app->app_local = xtrycalloc (1, sizeof *app->app_local);
4854 if (!app->app_local)
4856 rc = gpg_error (gpg_err_code_from_errno (errno));
4860 app->app_local->manufacturer = manufacturer;
4862 if (app->card_version >= 0x0200)
4863 app->app_local->extcap.is_v2 = 1;
4866 /* Read the historical bytes. */
4867 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
4872 log_info ("Historical Bytes: ");
4873 log_printhex ("", buffer, buflen);
4875 parse_historical (app->app_local, buffer, buflen);
4879 /* Read the force-chv1 flag. */
4880 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
4883 log_error (_("can't access %s - invalid OpenPGP card?\n"),
4884 "CHV Status Bytes");
4887 app->force_chv1 = (buflen && *buffer == 0);
4890 /* Read the extended capabilities. */
4891 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
4894 log_error (_("can't access %s - invalid OpenPGP card?\n"),
4895 "Extended Capability Flags" );
4900 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
4901 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
4902 app->app_local->extcap.key_import = !!(*buffer & 0x20);
4903 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
4904 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
4905 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
4906 app->app_local->extcap.has_decrypt = !!(*buffer & 0x02);
4910 /* Available with v2 cards. */
4911 app->app_local->extcap.sm_algo = buffer[1];
4912 app->app_local->extcap.max_get_challenge
4913 = (buffer[2] << 8 | buffer[3]);
4914 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
4918 /* Some of the first cards accidentally don't set the
4919 CHANGE_FORCE_CHV bit but allow it anyway. */
4920 if (app->card_version <= 0x0100 && manufacturer == 1)
4921 app->app_local->extcap.change_force_chv = 1;
4923 /* Check optional DO of "General Feature Management" for button. */
4924 relptr = get_one_do (app, 0x7f74, &buffer, &buflen, NULL);
4926 /* It must be: 03 81 01 20 */
4927 app->app_local->extcap.has_button = 1;
4929 parse_login_data (app);
4932 show_caps (app->app_local);
4934 parse_algorithm_attribute (app, 0);
4935 parse_algorithm_attribute (app, 1);
4936 parse_algorithm_attribute (app, 2);
4938 if (opt.verbose > 1)
4941 app->fnc.deinit = do_deinit;
4942 app->fnc.learn_status = do_learn_status;
4943 app->fnc.readcert = do_readcert;
4944 app->fnc.readkey = do_readkey;
4945 app->fnc.getattr = do_getattr;
4946 app->fnc.setattr = do_setattr;
4947 app->fnc.writecert = do_writecert;
4948 app->fnc.writekey = do_writekey;
4949 app->fnc.genkey = do_genkey;
4950 app->fnc.sign = do_sign;
4951 app->fnc.auth = do_auth;
4952 app->fnc.decipher = do_decipher;
4953 app->fnc.change_pin = do_change_pin;
4954 app->fnc.check_pin = do_check_pin;