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 */
65 #include "../common/util.h"
66 #include "../common/i18n.h"
68 #include "app-common.h"
69 #include "../common/tlv.h"
70 #include "../common/host2net.h"
71 #include "../common/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. */
79 unsigned int binary:1;
80 unsigned int dont_cache:1;
81 unsigned int flush_on_error:1;
82 unsigned 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 unsigned int try_extlen:2; /* Large object; try to use an extended
89 length APDU when !=0. The size is
90 determined by extcap.max_certlen_3
91 when == 1, and by extcap.max_special_do
95 { 0x005E, 0, 0, 1, 0, 0, 0, 2, "Login Data" },
96 { 0x5F50, 0, 0, 0, 0, 0, 0, 2, "URL" },
97 { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
98 { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
99 { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
100 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
101 { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
102 { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
103 { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
104 { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
105 { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
106 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
107 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
108 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
109 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
110 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
111 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
112 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
113 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
114 { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
115 { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
116 { 0x0101, 0, 0, 0, 0, 0, 0, 2, "Private DO 1"},
117 { 0x0102, 0, 0, 0, 0, 0, 0, 2, "Private DO 2"},
118 { 0x0103, 0, 0, 0, 0, 0, 0, 2, "Private DO 3"},
119 { 0x0104, 0, 0, 0, 0, 0, 0, 2, "Private DO 4"},
120 { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
122 { 0x7F74, 0, 0, 1, 0, 0, 0, 0, "General Feature Management"},
123 { 0x00D5, 0, 0, 1, 0, 0, 0, 0, "AES key data"},
124 { 0x00F9, 0, 0, 1, 0, 0, 0, 0, "KDF data object"},
138 /* The format of RSA private keys. */
150 /* One cache item for DOs. */
152 struct cache_s *next;
155 unsigned char data[1];
159 /* Object with application (i.e. OpenPGP card) specific data. */
161 /* A linked list with cached DOs. */
162 struct cache_s *cache;
164 /* Keep track of the public keys. */
167 int read_done; /* True if we have at least tried to read them. */
168 unsigned char *key; /* This is a malloced buffer with a canonical
169 encoded S-expression encoding a public
170 key. Might be NULL if key is not
172 size_t keylen; /* The length of the above S-expression. This
173 is usually only required for cross checks
174 because the length of an S-expression is
175 implicitly available. */
178 unsigned char status_indicator; /* The card status indicator. */
180 unsigned int manufacturer:16; /* Manufacturer ID from the s/n. */
182 /* Keep track of the ISO card capabilities. */
185 unsigned int cmd_chaining:1; /* Command chaining is supported. */
186 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
189 /* Keep track of extended card capabilities. */
192 unsigned int is_v2:1; /* Compatible to v2 or later. */
193 unsigned int extcap_v3:1; /* Extcap is in v3 format. */
194 unsigned int has_button:1; /* Has confirmation button or not. */
196 unsigned int sm_supported:1; /* Secure Messaging is supported. */
197 unsigned int get_challenge:1;
198 unsigned int key_import:1;
199 unsigned int change_force_chv:1;
200 unsigned int private_dos:1;
201 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
202 unsigned int has_decrypt:1; /* Support symmetric decryption. */
203 unsigned int kdf_do:1; /* Support KDF DO. */
205 unsigned int sm_algo:2; /* Symmetric crypto algo for SM. */
206 unsigned int pin_blk2:1; /* PIN block 2 format supported. */
207 unsigned int mse:1; /* MSE command supported. */
208 unsigned int max_certlen_3:16;
209 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
210 unsigned int max_special_do:16; /* Maximum size for special DOs. */
213 /* Flags used to control the application. */
216 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
217 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
220 /* Pinpad request specified on card. */
223 unsigned int specified:1;
233 unsigned int n_bits; /* Size of the modulus in bits. The rest
234 of this strucuire is only valid if
236 unsigned int e_bits; /* Size of the public exponent in bits. */
237 rsa_key_format_t format;
247 #define ECC_FLAG_DJB_TWEAK (1 << 0)
248 #define ECC_FLAG_PUBKEY (1 << 1)
251 /***** Local prototypes *****/
252 static unsigned long convert_sig_counter_value (const unsigned char *value,
254 static unsigned long get_sig_counter (app_t app);
255 static gpg_error_t do_auth (app_t app, const char *keyidstr,
256 gpg_error_t (*pincb)(void*, const char *, char **),
258 const void *indata, size_t indatalen,
259 unsigned char **outdata, size_t *outdatalen);
260 static void parse_algorithm_attribute (app_t app, int keyno);
261 static gpg_error_t change_keyattr_from_string
263 gpg_error_t (*pincb)(void*, const char *, char **),
265 const void *value, size_t valuelen);
273 do_deinit (app_t app)
275 if (app && app->app_local)
277 struct cache_s *c, *c2;
280 for (c = app->app_local->cache; c; c = c2)
286 for (i=0; i < DIM (app->app_local->pk); i++)
288 xfree (app->app_local->pk[i].key);
289 app->app_local->pk[i].read_done = 0;
291 xfree (app->app_local);
292 app->app_local = NULL;
297 /* Wrapper around iso7816_get_data which first tries to get the data
298 from the cache. With GET_IMMEDIATE passed as true, the cache is
299 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
300 supported by the card. */
302 get_cached_data (app_t app, int tag,
303 unsigned char **result, size_t *resultlen,
304 int get_immediate, int try_extlen)
318 for (c=app->app_local->cache; c; c = c->next)
323 p = xtrymalloc (c->length);
325 return gpg_error (gpg_err_code_from_errno (errno));
326 memcpy (p, c->data, c->length);
330 *resultlen = c->length;
336 if (try_extlen && app->app_local->cardcap.ext_lc_le)
339 exmode = app->app_local->extcap.max_certlen_3;
340 else if (try_extlen == 2 && app->app_local->extcap.extcap_v3)
341 exmode = app->app_local->extcap.max_special_do;
348 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
355 /* Check whether we should cache this object. */
359 for (i=0; data_objects[i].tag; i++)
360 if (data_objects[i].tag == tag)
362 if (data_objects[i].dont_cache)
367 /* Okay, cache it. */
368 for (c=app->app_local->cache; c; c = c->next)
369 assert (c->tag != tag);
371 c = xtrymalloc (sizeof *c + len);
375 memcpy (c->data, p, len);
380 c->next = app->app_local->cache;
381 app->app_local->cache = c;
387 /* Remove DO at TAG from the cache. */
389 flush_cache_item (app_t app, int tag)
391 struct cache_s *c, *cprev;
397 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
401 cprev->next = c->next;
403 app->app_local->cache = c->next;
406 for (c=app->app_local->cache; c ; c = c->next)
408 assert (c->tag != tag); /* Oops: duplicated entry. */
413 /* Try again if we have an outer tag. */
414 for (i=0; data_objects[i].tag; i++)
415 if (data_objects[i].tag == tag && data_objects[i].get_from
416 && data_objects[i].get_from != tag)
417 flush_cache_item (app, data_objects[i].get_from);
420 /* Flush all entries from the cache which might be out of sync after
423 flush_cache_after_error (app_t app)
427 for (i=0; data_objects[i].tag; i++)
428 if (data_objects[i].flush_on_error)
429 flush_cache_item (app, data_objects[i].tag);
433 /* Flush the entire cache. */
435 flush_cache (app_t app)
437 if (app && app->app_local)
439 struct cache_s *c, *c2;
441 for (c = app->app_local->cache; c; c = c2)
446 app->app_local->cache = NULL;
451 /* Get the DO identified by TAG from the card in SLOT and return a
452 buffer with its content in RESULT and NBYTES. The return value is
453 NULL if not found or a pointer which must be used to release the
454 buffer holding value. */
456 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
460 unsigned char *buffer;
462 unsigned char *value;
473 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
476 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
479 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
492 if (data_objects[i].tag && data_objects[i].get_from)
494 rc = get_cached_data (app, data_objects[i].get_from,
496 (data_objects[i].dont_cache
497 || data_objects[i].get_immediate_in_v11),
498 data_objects[i].try_extlen);
501 const unsigned char *s;
503 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
505 value = NULL; /* not found */
506 else if (valuelen > buflen - (s - buffer))
508 log_error ("warning: constructed DO too short\n");
510 xfree (buffer); buffer = NULL;
513 value = buffer + (s - buffer);
517 if (!value) /* Not in a constructed DO, try simple. */
519 rc = get_cached_data (app, tag, &buffer, &buflen,
520 (data_objects[i].dont_cache
521 || data_objects[i].get_immediate_in_v11),
522 data_objects[i].try_extlen);
542 dump_all_do (int slot)
545 unsigned char *buffer;
548 for (i=0; data_objects[i].tag; i++)
550 if (data_objects[i].get_from)
553 /* We don't try extended length APDU because such large DO would
554 be pretty useless in a log file. */
555 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
556 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
559 log_info ("DO '%s' not available: %s\n",
560 data_objects[i].desc, gpg_strerror (rc));
563 if (data_objects[i].binary)
565 log_info ("DO '%s': ", data_objects[i].desc);
566 log_printhex ("", buffer, buflen);
569 log_info ("DO '%s': '%.*s'\n",
570 data_objects[i].desc,
571 (int)buflen, buffer); /* FIXME: sanitize */
573 if (data_objects[i].constructed)
575 for (j=0; data_objects[j].tag; j++)
577 const unsigned char *value;
580 if (j==i || data_objects[i].tag != data_objects[j].get_from)
582 value = find_tlv_unchecked (buffer, buflen,
583 data_objects[j].tag, &valuelen);
586 else if (valuelen > buflen - (value - buffer))
587 log_error ("warning: constructed DO too short\n");
590 if (data_objects[j].binary)
592 log_info ("DO '%s': ", data_objects[j].desc);
594 log_info ("[%u]\n", (unsigned int)valuelen);
596 log_printhex ("", value, valuelen);
599 log_info ("DO '%s': '%.*s'\n",
600 data_objects[j].desc,
601 (int)valuelen, value); /* FIXME: sanitize */
606 xfree (buffer); buffer = NULL;
611 /* Count the number of bits, assuming the A represents an unsigned big
612 integer of length LEN bytes. */
614 count_bits (const unsigned char *a, size_t len)
616 unsigned int n = len * 8;
619 for (; len && !*a; len--, a++, n -=8)
623 for (i=7; i && !(*a & (1<<i)); i--)
629 /* GnuPG makes special use of the login-data DO, this function parses
630 the login data to store the flags for later use. It may be called
631 at any time and should be called after changing the login-data DO.
633 Everything up to a LF is considered a mailbox or account name. If
634 the first LF is followed by DC4 (0x14) control sequence are
635 expected up to the next LF. Control sequences are separated by FS
636 (0x18) and consist of key=value pairs. There are two keys defined:
640 Where FLAGS is a plain hexadecimal number representing flag values.
641 The lsb is here the rightmost bit. Defined flags bits are:
643 Bit 0 = CHV1 and CHV2 are not syncronized
644 Bit 1 = CHV2 has been set to the default PIN of "123456"
645 (this implies that bit 0 is also set).
649 Where PINPAD_REQUEST is in the format of: <n> or <n>,<m>.
650 N for user PIN, M for admin PIN. If M is missing it means M=N.
651 0 means to force not to use pinpad.
655 parse_login_data (app_t app)
657 unsigned char *buffer, *p;
662 app->app_local->flags.no_sync = 0;
663 app->app_local->flags.def_chv2 = 0;
664 app->app_local->pinpad.specified = 0;
665 app->app_local->pinpad.fixedlen_user = -1;
666 app->app_local->pinpad.fixedlen_admin = -1;
669 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
672 for (; buflen; buflen--, buffer++)
675 if (buflen < 2 || buffer[1] != '\x14')
678 return; /* No control sequences. */
687 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
689 /* Flags control sequence found. */
692 /* For now we are only interested in the last digit, so skip
693 any leading digits but bail out on invalid characters. */
694 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
695 lastdig = xtoi_1 (p);
698 if (len && !(*p == '\n' || *p == '\x18'))
699 goto next; /* Invalid characters in field. */
700 app->app_local->flags.no_sync = !!(lastdig & 1);
701 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
703 else if (buflen > 1 && *buffer == 'P' && buffer[1] == '=')
705 /* Pinpad request control sequence found. */
716 n = strtol (buffer, &q, 10);
717 if (q >= (char *)buffer + buflen
718 || *q == '\x18' || *q == '\n')
722 if (*q++ != ',' || !digitp (q))
724 m = strtol (q, &q, 10);
727 if (buflen < ((unsigned char *)q - buffer))
730 buflen -= ((unsigned char *)q - buffer);
733 if (buflen && !(*buffer == '\n' || *buffer == '\x18'))
735 app->app_local->pinpad.specified = 1;
736 app->app_local->pinpad.fixedlen_user = n;
737 app->app_local->pinpad.fixedlen_admin = m;
742 /* Skip to FS (0x18) or LF (\n). */
743 for (; buflen && *buffer != '\x18' && *buffer != '\n'; buflen--)
746 while (buflen && *buffer != '\n');
752 #define MAX_ARGS_STORE_FPR 3
754 /* Note, that FPR must be at least 20 bytes. */
756 store_fpr (app_t app, int keynumber, u32 timestamp, unsigned char *fpr,
759 unsigned int n, nbits;
760 unsigned char *buffer, *p;
763 const unsigned char *m[MAX_ARGS_STORE_FPR];
764 size_t mlen[MAX_ARGS_STORE_FPR];
769 n = 6; /* key packet version, 4-byte timestamps, and algorithm */
770 if (algo == PUBKEY_ALGO_ECDH)
776 for (i = 0; i < argc; i++)
778 m[i] = va_arg (ap, const unsigned char *);
779 mlen[i] = va_arg (ap, size_t);
780 if (algo == PUBKEY_ALGO_RSA || i == 1)
786 p = buffer = xtrymalloc (3 + n);
788 return gpg_error_from_syserror ();
790 *p++ = 0x99; /* ctb */
791 *p++ = n >> 8; /* 2 byte length header */
793 *p++ = 4; /* key packet version */
794 *p++ = timestamp >> 24;
795 *p++ = timestamp >> 16;
796 *p++ = timestamp >> 8;
800 for (i = 0; i < argc; i++)
802 if (algo == PUBKEY_ALGO_RSA || i == 1)
804 nbits = count_bits (m[i], mlen[i]);
808 memcpy (p, m[i], mlen[i]);
812 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
816 tag = (app->card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
817 flush_cache_item (app, 0xC5);
818 tag2 = 0xCE + keynumber;
819 flush_cache_item (app, 0xCD);
821 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
823 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
825 if (!rc && app->card_version > 0x0100)
827 unsigned char buf[4];
829 buf[0] = timestamp >> 24;
830 buf[1] = timestamp >> 16;
831 buf[2] = timestamp >> 8;
834 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
836 log_error (_("failed to store the creation date: %s\n"),
845 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
846 int number, const unsigned char *fpr)
852 for (i=0; i < 20 && !fpr[i]; i++)
855 return; /* All zero. */
856 bin2hex (fpr, 20, buf);
858 *numbuf = 0; /* Don't print the key number */
860 sprintf (numbuf, "%d", number);
861 send_status_info (ctrl, keyword,
862 numbuf, (size_t)strlen(numbuf),
863 buf, (size_t)strlen (buf), NULL, 0);
867 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
868 int number, const unsigned char *stamp)
870 char numbuf1[50], numbuf2[50];
873 value = buf32_to_ulong (stamp);
876 sprintf (numbuf1, "%d", number);
877 sprintf (numbuf2, "%lu", value);
878 send_status_info (ctrl, keyword,
879 numbuf1, (size_t)strlen(numbuf1),
880 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
884 send_key_data (ctrl_t ctrl, const char *name,
885 const unsigned char *a, size_t alen)
890 buffer = buf = bin2hex (a, alen, NULL);
893 log_error ("memory allocation error in send_key_data\n");
896 buflen = strlen (buffer);
898 /* 768 is the hexified size for the modulus of an 3072 bit key. We
899 use extra chunks to transmit larger data (i.e for 4096 bit). */
900 for ( ;buflen > 768; buflen -= 768, buf += 768)
901 send_status_info (ctrl, "KEY-DATA",
905 send_status_info (ctrl, "KEY-DATA",
906 name, (size_t)strlen(name),
914 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int keyno)
918 assert (keyno >=0 && keyno < DIM(app->app_local->keyattr));
920 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
921 snprintf (buffer, sizeof buffer, "%d 1 rsa%u %u %d",
923 app->app_local->keyattr[keyno].rsa.n_bits,
924 app->app_local->keyattr[keyno].rsa.e_bits,
925 app->app_local->keyattr[keyno].rsa.format);
926 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
928 snprintf (buffer, sizeof buffer, "%d %d %s",
930 keyno==1? PUBKEY_ALGO_ECDH :
931 (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)?
932 PUBKEY_ALGO_EDDSA : PUBKEY_ALGO_ECDSA,
933 app->app_local->keyattr[keyno].ecc.curve);
936 snprintf (buffer, sizeof buffer, "%d 0 0 UNKNOWN", keyno+1);
938 send_status_direct (ctrl, keyword, buffer);
942 #define RSA_SMALL_SIZE_KEY 1952
943 #define RSA_SMALL_SIZE_OP 2048
946 determine_rsa_response (app_t app, int keyno)
950 size = 2 + 3 /* header */
951 + 4 /* tag+len */ + (app->app_local->keyattr[keyno].rsa.n_bits+7)/8
952 + 2 /* tag+len */ + (app->app_local->keyattr[keyno].rsa.e_bits+7)/8;
958 /* Implement the GETATTR command. This is similar to the LEARN
959 command but returns just one value via the status interface. */
961 do_getattr (app_t app, ctrl_t ctrl, const char *name)
968 { "DISP-NAME", 0x005B },
969 { "LOGIN-DATA", 0x005E },
970 { "DISP-LANG", 0x5F2D },
971 { "DISP-SEX", 0x5F35 },
972 { "PUBKEY-URL", 0x5F50 },
973 { "KEY-FPR", 0x00C5, 3 },
974 { "KEY-TIME", 0x00CD, 4 },
975 { "KEY-ATTR", 0x0000, -5 },
976 { "CA-FPR", 0x00C6, 3 },
977 { "CHV-STATUS", 0x00C4, 1 },
978 { "SIG-COUNTER", 0x0093, 2 },
979 { "SERIALNO", 0x004F, -1 },
981 { "EXTCAP", 0x0000, -2 },
982 { "PRIVATE-DO-1", 0x0101 },
983 { "PRIVATE-DO-2", 0x0102 },
984 { "PRIVATE-DO-3", 0x0103 },
985 { "PRIVATE-DO-4", 0x0104 },
986 { "$AUTHKEYID", 0x0000, -3 },
987 { "$DISPSERIALNO",0x0000, -4 },
993 unsigned char *value;
996 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
998 if (!table[idx].name)
999 return gpg_error (GPG_ERR_INV_NAME);
1001 if (table[idx].special == -1)
1003 /* The serial number is very special. We could have used the
1004 AID DO to retrieve it. The AID DO is available anyway but
1005 not hex formatted. */
1006 char *serial = app_get_serialno (app);
1010 send_status_direct (ctrl, "SERIALNO", serial);
1015 if (table[idx].special == -2)
1019 snprintf (tmp, sizeof tmp,
1020 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d "
1021 "sm=%d si=%u dec=%d bt=%d",
1022 app->app_local->extcap.get_challenge,
1023 app->app_local->extcap.key_import,
1024 app->app_local->extcap.change_force_chv,
1025 app->app_local->extcap.private_dos,
1026 app->app_local->extcap.max_certlen_3,
1027 app->app_local->extcap.algo_attr_change,
1028 (app->app_local->extcap.sm_supported
1029 ? (app->app_local->extcap.sm_algo == 0? CIPHER_ALGO_3DES :
1030 (app->app_local->extcap.sm_algo == 1?
1031 CIPHER_ALGO_AES : CIPHER_ALGO_AES256))
1033 app->app_local->status_indicator,
1034 app->app_local->extcap.has_decrypt,
1035 app->app_local->extcap.has_button);
1036 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1039 if (table[idx].special == -3)
1041 char const tmp[] = "OPENPGP.3";
1042 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
1045 if (table[idx].special == -4)
1047 char *serial = app_get_serialno (app);
1051 if (strlen (serial) > 16+12)
1053 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
1059 return gpg_error (GPG_ERR_INV_NAME);
1061 if (table[idx].special == -5)
1063 for (i=0; i < 3; i++)
1064 send_key_attr (ctrl, app, table[idx].name, i);
1068 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
1071 if (table[idx].special == 1)
1075 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
1076 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
1077 send_status_info (ctrl, table[idx].name,
1078 numbuf, strlen (numbuf), NULL, 0);
1080 else if (table[idx].special == 2)
1084 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
1085 send_status_info (ctrl, table[idx].name,
1086 numbuf, strlen (numbuf), NULL, 0);
1088 else if (table[idx].special == 3)
1091 for (i=0; i < 3; i++)
1092 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
1094 else if (table[idx].special == 4)
1097 for (i=0; i < 3; i++)
1098 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
1101 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
1109 /* Return the DISP-NAME without any padding characters. Caller must
1110 * free the result. If not found or empty NULL is returned. */
1112 get_disp_name (app_t app)
1116 unsigned char *value;
1122 relptr = get_one_do (app, 0x005B, &value, &valuelen, &rc);
1126 string = xtrymalloc (valuelen + 1);
1132 memcpy (string, value, valuelen);
1133 string[valuelen] = 0;
1136 /* Swap surname and given name. */
1137 given = strstr (string, "<<");
1138 for (p = string; *p; p++)
1142 if (given && given[2])
1146 result = strconcat (given, " ", string, NULL);
1159 /* Return the pretty formatted serialnumber. On error NULL is
1162 get_disp_serialno (app_t app)
1164 char *serial = app_get_serialno (app);
1166 /* For our OpenPGP cards we do not want to show the entire serial
1167 * number but a nicely reformatted actual serial number. */
1168 if (serial && strlen (serial) > 16+12)
1170 memmove (serial, serial+16, 4);
1172 /* memmove (serial+5, serial+20, 4); */
1173 /* serial[9] = ' '; */
1174 /* memmove (serial+10, serial+24, 4); */
1175 /* serial[14] = 0; */
1176 memmove (serial+5, serial+20, 8);
1183 /* Return the number of remaining tries for the standard or the admin
1184 * pw. Returns -1 on card error. */
1186 get_remaining_tries (app_t app, int adminpw)
1189 unsigned char *value;
1193 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1194 if (!relptr || valuelen < 7)
1196 log_error (_("error retrieving CHV status from card\n"));
1200 remaining = value[adminpw? 6 : 4];
1206 /* Retrieve the fingerprint from the card inserted in SLOT and write
1207 the according hex representation to FPR. Caller must have provide
1208 a buffer at FPR of least 41 bytes. Returns 0 on success or an
1210 #if GNUPG_MAJOR_VERSION > 1
1212 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
1214 gpg_error_t err = 0;
1216 unsigned char *value;
1219 assert (keyno >=0 && keyno <= 2);
1221 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
1222 if (relptr && valuelen >= 60)
1223 bin2hex (value+keyno*20, 20, fpr);
1225 err = gpg_error (GPG_ERR_NOT_FOUND);
1229 #endif /*GNUPG_MAJOR_VERSION > 1*/
1232 /* Retrieve the public key material for the RSA key, whose fingerprint
1233 is FPR, from gpg output, which can be read through the stream FP.
1234 The RSA modulus will be stored at the address of M and MLEN, the
1235 public exponent at E and ELEN. Returns zero on success, an error
1236 code on failure. Caller must release the allocated buffers at M
1237 and E if the function returns success. */
1238 #if GNUPG_MAJOR_VERSION > 1
1240 retrieve_key_material (FILE *fp, const char *hexkeyid,
1241 const unsigned char **m, size_t *mlen,
1242 const unsigned char **e, size_t *elen)
1244 gcry_error_t err = 0;
1245 char *line = NULL; /* read_line() buffer. */
1246 size_t line_size = 0; /* Helper for for read_line. */
1247 int found_key = 0; /* Helper to find a matching key. */
1248 unsigned char *m_new = NULL;
1249 unsigned char *e_new = NULL;
1253 /* Loop over all records until we have found the subkey
1254 corresponding to the fingerprint. Inm general the first record
1255 should be the pub record, but we don't rely on that. Given that
1256 we only need to look at one key, it is sufficient to compare the
1257 keyid so that we don't need to look at "fpr" records. */
1261 char *fields[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
1268 i = read_line (fp, &line, &line_size, &max_length);
1273 err = gpg_error_from_syserror ();
1274 goto leave; /* Error. */
1278 err = gpg_error (GPG_ERR_TRUNCATED);
1279 goto leave; /* Line truncated - we better stop processing. */
1282 /* Parse the line into fields. */
1283 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1285 fields[nfields] = p;
1286 p = strchr (p, ':');
1291 continue; /* No fields at all - skip line. */
1295 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1296 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1301 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1302 break; /* Next key - stop. */
1304 if ( strcmp (fields[0], "pkd") )
1305 continue; /* Not a key data record. */
1306 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1307 || (!i && m_new) || (i && e_new))
1309 err = gpg_error (GPG_ERR_GENERAL);
1310 goto leave; /* Error: Invalid key data record or not an RSA key. */
1313 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1317 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1319 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1320 gcry_mpi_release (mpi);
1335 err = gpg_error (GPG_ERR_GENERAL);
1343 #endif /*GNUPG_MAJOR_VERSION > 1*/
1347 rsa_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1348 const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp)
1351 const unsigned char *m, *e;
1353 unsigned char *mbuf = NULL, *ebuf = NULL;
1355 m = find_tlv (data, datalen, 0x0081, &mlen);
1358 log_error (_("response does not contain the RSA modulus\n"));
1359 return gpg_error (GPG_ERR_CARD);
1362 e = find_tlv (data, datalen, 0x0082, &elen);
1365 log_error (_("response does not contain the RSA public exponent\n"));
1366 return gpg_error (GPG_ERR_CARD);
1371 send_key_data (ctrl, "n", m, mlen);
1372 send_key_data (ctrl, "e", e, elen);
1375 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
1377 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
1382 unsigned char fprbuf[20];
1384 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
1389 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1392 mbuf = xtrymalloc (mlen + 1);
1395 err = gpg_error_from_syserror ();
1398 /* Prepend numbers with a 0 if needed. */
1399 if (mlen && (*m & 0x80))
1402 memcpy (mbuf+1, m, mlen);
1406 memcpy (mbuf, m, mlen);
1408 ebuf = xtrymalloc (elen + 1);
1411 err = gpg_error_from_syserror ();
1414 /* Prepend numbers with a 0 if needed. */
1415 if (elen && (*e & 0x80))
1418 memcpy (ebuf+1, e, elen);
1422 memcpy (ebuf, e, elen);
1424 err = gcry_sexp_build (r_sexp, NULL, "(public-key(rsa(n%b)(e%b)))",
1425 (int)mlen, mbuf, (int)elen, ebuf);
1433 /* Determine KDF hash algorithm and KEK encryption algorithm by CURVE. */
1434 static const unsigned char*
1435 ecdh_params (const char *curve)
1439 openpgp_curve_to_oid (curve, &nbits);
1441 /* See RFC-6637 for those constants.
1442 0x03: Number of bytes
1443 0x01: Version for this parameter format
1448 return (const unsigned char*)"\x03\x01\x08\x07";
1449 else if (nbits <= 384)
1450 return (const unsigned char*)"\x03\x01\x09\x08";
1452 return (const unsigned char*)"\x03\x01\x0a\x09";
1456 ecc_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1457 const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp)
1460 unsigned char *qbuf = NULL;
1461 const unsigned char *ecc_q;
1463 gcry_mpi_t oid = NULL;
1467 const unsigned char *oidbuf;
1472 ecc_q = find_tlv (data, datalen, 0x0086, &ecc_q_len);
1475 log_error (_("response does not contain the EC public key\n"));
1476 return gpg_error (GPG_ERR_CARD);
1479 curve = app->app_local->keyattr[keyno].ecc.curve;
1480 oidstr = openpgp_curve_to_oid (curve, NULL);
1481 err = openpgp_oid_from_str (oidstr, &oid);
1484 oidbuf = gcry_mpi_get_opaque (oid, &n);
1487 err = gpg_error_from_syserror ();
1492 qbuf = xtrymalloc (ecc_q_len + 1);
1495 err = gpg_error_from_syserror ();
1499 if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1500 { /* Prepend 0x40 prefix. */
1502 memcpy (qbuf+1, ecc_q, ecc_q_len);
1506 memcpy (qbuf, ecc_q, ecc_q_len);
1510 send_key_data (ctrl, "q", qbuf, ecc_q_len);
1511 send_key_data (ctrl, "curve", oidbuf, oid_len);
1517 send_key_data (ctrl, "kdf/kek", ecdh_params (curve), (size_t)4);
1518 algo = PUBKEY_ALGO_ECDH;
1522 if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1523 algo = PUBKEY_ALGO_EDDSA;
1525 algo = PUBKEY_ALGO_ECDSA;
1530 unsigned char fprbuf[20];
1532 err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
1533 qbuf, ecc_q_len, ecdh_params (curve), (size_t)4);
1537 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1540 if (!(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))
1541 format = "(public-key(ecc(curve%s)(q%b)))";
1542 else if (keyno == 1)
1543 format = "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))";
1545 format = "(public-key(ecc(curve%s)(flags eddsa)(q%b)))";
1547 err = gcry_sexp_build (r_sexp, NULL, format,
1548 app->app_local->keyattr[keyno].ecc.curve,
1549 (int)ecc_q_len, qbuf);
1551 gcry_mpi_release (oid);
1557 /* Parse tag-length-value data for public key in BUFFER of BUFLEN
1558 length. Key of KEYNO in APP is updated with an S-expression of
1559 public key. When CTRL is not NULL, fingerprint is computed with
1560 CREATED_AT, and fingerprint is written to the card, and key data
1561 and fingerprint are send back to the client side.
1564 read_public_key (app_t app, ctrl_t ctrl, u32 created_at, int keyno,
1565 const unsigned char *buffer, size_t buflen)
1568 const unsigned char *data;
1570 gcry_sexp_t s_pkey = NULL;
1572 data = find_tlv (buffer, buflen, 0x7F49, &datalen);
1575 log_error (_("response does not contain the public key data\n"));
1576 return gpg_error (GPG_ERR_CARD);
1579 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
1580 err = rsa_read_pubkey (app, ctrl, created_at, keyno,
1581 data, datalen, &s_pkey);
1582 else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC)
1583 err = ecc_read_pubkey (app, ctrl, created_at, keyno,
1584 data, datalen, &s_pkey);
1586 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1590 unsigned char *keybuf;
1593 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1594 keybuf = xtrymalloc (len);
1597 err = gpg_error_from_syserror ();
1598 gcry_sexp_release (s_pkey);
1602 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1603 gcry_sexp_release (s_pkey);
1605 app->app_local->pk[keyno].key = keybuf;
1606 /* Decrement for trailing '\0' */
1607 app->app_local->pk[keyno].keylen = len - 1;
1614 /* Get the public key for KEYNO and store it as an S-expression with
1615 the APP handle. On error that field gets cleared. If we already
1616 know about the public key we will just return. Note that this does
1617 not mean a key is available; this is solely indicated by the
1618 presence of the app->app_local->pk[KEYNO].key field.
1620 Note that GnuPG 1.x does not need this and it would be too time
1621 consuming to send it just for the fun of it. However, given that we
1622 use the same code in gpg 1.4, we can't use the gcry S-expression
1623 here but need to open encode it. */
1624 #if GNUPG_MAJOR_VERSION > 1
1626 get_public_key (app_t app, int keyno)
1628 gpg_error_t err = 0;
1629 unsigned char *buffer;
1630 const unsigned char *m, *e;
1634 char *keybuf = NULL;
1638 if (keyno < 0 || keyno > 2)
1639 return gpg_error (GPG_ERR_INV_ID);
1641 /* Already cached? */
1642 if (app->app_local->pk[keyno].read_done)
1645 xfree (app->app_local->pk[keyno].key);
1646 app->app_local->pk[keyno].key = NULL;
1647 app->app_local->pk[keyno].keylen = 0;
1649 m = e = NULL; /* (avoid cc warning) */
1651 if (app->card_version > 0x0100)
1653 int exmode, le_value;
1655 /* We may simply read the public key out of these cards. */
1656 if (app->app_local->cardcap.ext_lc_le
1657 && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA
1658 && app->app_local->keyattr[keyno].rsa.n_bits > RSA_SMALL_SIZE_KEY)
1660 exmode = 1; /* Use extended length. */
1661 le_value = determine_rsa_response (app, keyno);
1666 le_value = 256; /* Use legacy value. */
1669 err = iso7816_read_public_key (app->slot, exmode,
1670 (keyno == 0? "\xB6" :
1671 keyno == 1? "\xB8" : "\xA4"),
1672 2, le_value, &buffer, &buflen);
1675 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1679 err = read_public_key (app, NULL, 0U, keyno, buffer, buflen);
1683 /* Due to a design problem in v1.0 cards we can't get the public
1684 key out of these cards without doing a verify on CHV3.
1685 Clearly that is not an option and thus we try to locate the
1686 key using an external helper.
1688 The helper we use here is gpg itself, which should know about
1689 the key in any case. */
1693 char *command = NULL;
1697 buffer = NULL; /* We don't need buffer. */
1699 err = retrieve_fpr_from_card (app, keyno, fpr);
1702 log_error ("error while retrieving fpr from card: %s\n",
1703 gpg_strerror (err));
1706 hexkeyid = fpr + 24;
1708 ret = gpgrt_asprintf
1709 (&command, "gpg --list-keys --with-colons --with-key-data '%s'", fpr);
1712 err = gpg_error_from_syserror ();
1716 fp = popen (command, "r");
1720 err = gpg_error_from_syserror ();
1721 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1725 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1729 log_error ("error while retrieving key material through pipe: %s\n",
1730 gpg_strerror (err));
1734 err = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%b)(e%b)))",
1735 (int)mlen, m, (int)elen, e);
1739 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1741 keybuf = xtrymalloc (len);
1744 err = gpg_error_from_syserror ();
1745 gcry_sexp_release (s_pkey);
1749 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len);
1750 gcry_sexp_release (s_pkey);
1752 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1753 /* Decrement for trailing '\0' */
1754 app->app_local->pk[keyno].keylen = len - 1;
1758 /* Set a flag to indicate that we tried to read the key. */
1759 app->app_local->pk[keyno].read_done = 1;
1764 #endif /* GNUPG_MAJOR_VERSION > 1 */
1768 /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3].
1769 This is used by the LEARN command. */
1771 send_keypair_info (app_t app, ctrl_t ctrl, int key)
1773 int keyno = key - 1;
1774 gpg_error_t err = 0;
1775 /* Note that GnuPG 1.x does not need this and it would be too time
1776 consuming to send it just for the fun of it. */
1777 #if GNUPG_MAJOR_VERSION > 1
1778 unsigned char grip[20];
1782 err = get_public_key (app, keyno);
1786 assert (keyno >= 0 && keyno <= 2);
1787 if (!app->app_local->pk[keyno].key)
1788 goto leave; /* No such key - ignore. */
1790 err = keygrip_from_canon_sexp (app->app_local->pk[keyno].key,
1791 app->app_local->pk[keyno].keylen,
1796 bin2hex (grip, 20, gripstr);
1798 sprintf (idbuf, "OPENPGP.%d", keyno+1);
1799 send_status_info (ctrl, "KEYPAIRINFO",
1801 idbuf, strlen (idbuf),
1805 #endif /* GNUPG_MAJOR_VERSION > 1 */
1811 /* Handle the LEARN command for OpenPGP. */
1813 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1817 do_getattr (app, ctrl, "EXTCAP");
1818 do_getattr (app, ctrl, "DISP-NAME");
1819 do_getattr (app, ctrl, "DISP-LANG");
1820 do_getattr (app, ctrl, "DISP-SEX");
1821 do_getattr (app, ctrl, "PUBKEY-URL");
1822 do_getattr (app, ctrl, "LOGIN-DATA");
1823 do_getattr (app, ctrl, "KEY-FPR");
1824 if (app->card_version > 0x0100)
1825 do_getattr (app, ctrl, "KEY-TIME");
1826 do_getattr (app, ctrl, "CA-FPR");
1827 do_getattr (app, ctrl, "CHV-STATUS");
1828 do_getattr (app, ctrl, "SIG-COUNTER");
1829 if (app->app_local->extcap.private_dos)
1831 do_getattr (app, ctrl, "PRIVATE-DO-1");
1832 do_getattr (app, ctrl, "PRIVATE-DO-2");
1834 do_getattr (app, ctrl, "PRIVATE-DO-3");
1836 do_getattr (app, ctrl, "PRIVATE-DO-4");
1838 send_keypair_info (app, ctrl, 1);
1839 send_keypair_info (app, ctrl, 2);
1840 send_keypair_info (app, ctrl, 3);
1841 /* Note: We do not send the Cardholder Certificate, because that is
1842 relatively long and for OpenPGP applications not really needed. */
1847 /* Handle the READKEY command for OpenPGP. On success a canonical
1848 encoded S-expression with the public key will get stored at PK and
1849 its length (for assertions) at PKLEN; the caller must release that
1850 buffer. On error PK and PKLEN are not changed and an error code is
1853 do_readkey (app_t app, int advanced, const char *keyid,
1854 unsigned char **pk, size_t *pklen)
1856 #if GNUPG_MAJOR_VERSION > 1
1861 if (!strcmp (keyid, "OPENPGP.1"))
1863 else if (!strcmp (keyid, "OPENPGP.2"))
1865 else if (!strcmp (keyid, "OPENPGP.3"))
1868 return gpg_error (GPG_ERR_INV_ID);
1870 err = get_public_key (app, keyno);
1874 buf = app->app_local->pk[keyno].key;
1876 return gpg_error (GPG_ERR_NO_PUBKEY);
1882 err = gcry_sexp_new (&s_key, buf, app->app_local->pk[keyno].keylen, 0);
1886 *pklen = gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, NULL, 0);
1887 *pk = xtrymalloc (*pklen);
1890 err = gpg_error_from_syserror ();
1895 gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, *pk, *pklen);
1896 gcry_sexp_release (s_key);
1897 /* Decrement for trailing '\0' */
1898 *pklen = *pklen - 1;
1902 *pklen = app->app_local->pk[keyno].keylen;
1903 *pk = xtrymalloc (*pklen);
1906 err = gpg_error_from_syserror ();
1910 memcpy (*pk, buf, *pklen);
1915 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1919 /* Read the standard certificate of an OpenPGP v2 card. It is
1920 returned in a freshly allocated buffer with that address stored at
1921 CERT and the length of the certificate stored at CERTLEN. CERTID
1922 needs to be set to "OPENPGP.3". */
1924 do_readcert (app_t app, const char *certid,
1925 unsigned char **cert, size_t *certlen)
1927 #if GNUPG_MAJOR_VERSION > 1
1929 unsigned char *buffer;
1935 if (strcmp (certid, "OPENPGP.3"))
1936 return gpg_error (GPG_ERR_INV_ID);
1937 if (!app->app_local->extcap.is_v2)
1938 return gpg_error (GPG_ERR_NOT_FOUND);
1940 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1942 return gpg_error (GPG_ERR_NOT_FOUND);
1945 err = gpg_error (GPG_ERR_NOT_FOUND);
1946 else if (!(*cert = xtrymalloc (buflen)))
1947 err = gpg_error_from_syserror ();
1950 memcpy (*cert, buffer, buflen);
1957 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1962 /* Decide if we use the pinpad of the reader for PIN input according
1963 to the user preference on the card, and the capability of the
1964 reader. This routine is only called when the reader has pinpad.
1965 Returns 0 if we use pinpad, 1 otherwise. */
1967 check_pinpad_request (app_t app, pininfo_t *pininfo, int admin_pin)
1969 if (app->app_local->pinpad.specified == 0) /* No preference on card. */
1971 if (pininfo->fixedlen == 0) /* Reader has varlen capability. */
1972 return 0; /* Then, use pinpad. */
1975 * Reader has limited capability, and it may not match PIN of
1982 pininfo->fixedlen = app->app_local->pinpad.fixedlen_admin;
1984 pininfo->fixedlen = app->app_local->pinpad.fixedlen_user;
1986 if (pininfo->fixedlen == 0 /* User requests disable pinpad. */
1987 || pininfo->fixedlen < pininfo->minlen
1988 || pininfo->fixedlen > pininfo->maxlen
1989 /* Reader doesn't have the capability to input a PIN which
1990 * length is FIXEDLEN. */)
1997 /* Return a string with information about the card for use in a
1998 * prompt. Returns NULL on memory failure. */
2000 get_prompt_info (app_t app, int chvno, unsigned long sigcount, int remaining)
2002 char *serial, *disp_name, *rembuf, *tmpbuf, *result;
2004 serial = get_disp_serialno (app);
2008 disp_name = get_disp_name (app);
2011 /* TRANSLATORS: Put a \x1f right before a colon. This can be
2012 * used by pinentry to nicely align the names and values. Keep
2013 * the %s at the start and end of the string. */
2014 result = xtryasprintf (_("%s"
2015 "Number\x1f: %s%%0A"
2016 "Holder\x1f: %s%%0A"
2021 disp_name? disp_name:"",
2027 result = xtryasprintf (_("%s"
2028 "Number\x1f: %s%%0A"
2033 disp_name? disp_name:"",
2039 if (remaining != -1)
2041 /* TRANSLATORS: This is the number of remaining attempts to
2042 * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */
2043 rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
2049 tmpbuf = strconcat (result, "%0A%0A", rembuf, NULL);
2063 /* Compute hash if KDF-DO is available. CHVNO must be 0 for reset
2064 code, 1 or 2 for user pin and 3 for admin pin.
2067 pin2hash_if_kdf (app_t app, int chvno, char *pinvalue, int *r_pinlen)
2069 gpg_error_t err = 0;
2071 unsigned char *buffer;
2074 if (app->app_local->extcap.kdf_do
2075 && (relptr = get_one_do (app, 0x00F9, &buffer, &buflen, NULL))
2076 && buflen == 110 && (buffer[2] == 0x03))
2079 unsigned long s2k_count;
2082 salt = &buffer[(chvno==3 ? 34 : (chvno==0 ? 24 : 14))];
2083 s2k_count = (((unsigned int)buffer[8] << 24)
2084 | (buffer[9] << 16) | (buffer[10] << 8) | buffer[11]);
2085 err = gcry_kdf_derive (pinvalue, strlen (pinvalue),
2086 GCRY_KDF_ITERSALTED_S2K,
2087 DIGEST_ALGO_SHA256, salt, 8,
2088 s2k_count, sizeof (dek), dek);
2091 /* pinvalue has a buffer of MAXLEN_PIN+1, 32 is OK. */
2093 memcpy (pinvalue, dek, *r_pinlen);
2094 wipememory (dek, *r_pinlen);
2100 *r_pinlen = strlen (pinvalue);
2106 /* Verify a CHV either using the pinentry or if possible by
2107 using a pinpad. PINCB and PINCB_ARG describe the usual callback
2108 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
2109 used with CHV1. PINVALUE is the address of a pointer which will
2110 receive a newly allocated block with the actual PIN (this is useful
2111 in case that PIN shall be used for another verify operation). The
2112 caller needs to free this value. If the function returns with
2113 success and NULL is stored at PINVALUE, the caller should take this
2114 as an indication that the pinpad has been used.
2117 verify_a_chv (app_t app,
2118 gpg_error_t (*pincb)(void*, const char *, char **),
2119 void *pincb_arg, int chvno, unsigned long sigcount,
2120 char **pinvalue, int *pinlen)
2123 char *prompt_buffer = NULL;
2129 log_assert (chvno == 1 || chvno == 2);
2134 remaining = get_remaining_tries (app, 0);
2135 if (remaining == -1)
2136 return gpg_error (GPG_ERR_CARD);
2138 if (chvno == 2 && app->app_local->flags.def_chv2)
2140 /* Special case for def_chv2 mechanism. */
2142 log_info (_("using default PIN as %s\n"), "CHV2");
2143 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
2146 /* Verification of CHV2 with the default PIN failed,
2147 although the card pretends to have the default PIN set as
2148 CHV2. We better disable the def_chv2 flag now. */
2149 log_info (_("failed to use default PIN as %s: %s"
2150 " - disabling further default use\n"),
2151 "CHV2", gpg_strerror (rc));
2152 app->app_local->flags.def_chv2 = 0;
2157 memset (&pininfo, 0, sizeof pininfo);
2158 pininfo.fixedlen = -1;
2159 pininfo.minlen = minlen;
2162 const char *firstline = _("||Please unlock the card");
2163 char *infoblock = get_prompt_info (app, chvno, sigcount,
2164 remaining < 3? remaining : -1);
2166 prompt_buffer = strconcat (firstline, "%0A%0A", infoblock, NULL);
2168 prompt = prompt_buffer;
2170 prompt = firstline; /* ENOMEM fallback. */
2175 if (!opt.disable_pinpad
2176 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
2177 && !check_pinpad_request (app, &pininfo, 0))
2179 /* The reader supports the verify command through the pinpad.
2180 Note that the pincb appends a text to the prompt telling the
2181 user to use the pinpad. */
2182 rc = pincb (pincb_arg, prompt, NULL);
2184 xfree (prompt_buffer);
2185 prompt_buffer = NULL;
2188 log_info (_("PIN callback returned error: %s\n"),
2192 rc = iso7816_verify_kp (app->slot, 0x80+chvno, &pininfo);
2193 /* Dismiss the prompt. */
2194 pincb (pincb_arg, NULL, NULL);
2196 log_assert (!*pinvalue);
2200 /* The reader has no pinpad or we don't want to use it. */
2201 rc = pincb (pincb_arg, prompt, pinvalue);
2203 xfree (prompt_buffer);
2204 prompt_buffer = NULL;
2207 log_info (_("PIN callback returned error: %s\n"),
2212 if (strlen (*pinvalue) < minlen)
2214 log_error (_("PIN for CHV%d is too short;"
2215 " minimum length is %d\n"), chvno, minlen);
2218 return gpg_error (GPG_ERR_BAD_PIN);
2221 rc = pin2hash_if_kdf (app, chvno, *pinvalue, pinlen);
2223 rc = iso7816_verify (app->slot, 0x80+chvno, *pinvalue, *pinlen);
2228 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
2231 flush_cache_after_error (app);
2238 /* Verify CHV2 if required. Depending on the configuration of the
2239 card CHV1 will also be verified. */
2241 verify_chv2 (app_t app,
2242 gpg_error_t (*pincb)(void*, const char *, char **),
2250 return 0; /* We already verified CHV2. */
2252 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue, &pinlen);
2257 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
2259 /* For convenience we verify CHV1 here too. We do this only if
2260 the card is not configured to require a verification before
2261 each CHV1 controlled operation (force_chv1) and if we are not
2262 using the pinpad (PINVALUE == NULL). */
2263 rc = iso7816_verify (app->slot, 0x81, pinvalue, pinlen);
2264 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2265 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2268 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
2269 flush_cache_after_error (app);
2281 /* Build the prompt to enter the Admin PIN. The prompt depends on the
2282 current sdtate of the card. */
2284 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
2292 remaining = get_remaining_tries (app, 1);
2293 if (remaining == -1)
2294 return gpg_error (GPG_ERR_CARD);
2297 log_info (_("card is permanently locked!\n"));
2298 return gpg_error (GPG_ERR_BAD_PIN);
2301 log_info (ngettext("%d Admin PIN attempt remaining before card"
2302 " is permanently locked\n",
2303 "%d Admin PIN attempts remaining before card"
2304 " is permanently locked\n",
2305 remaining), remaining);
2307 infoblock = get_prompt_info (app, 3, 0, remaining < 3? remaining : -1);
2309 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
2310 the start of the string. Use %0A (single percent) for a linefeed. */
2311 prompt = strconcat (_("|A|Please enter the Admin PIN"),
2312 "%0A%0A", infoblock, NULL);
2315 return gpg_error_from_syserror ();
2322 /* Verify CHV3 if required. */
2324 verify_chv3 (app_t app,
2325 gpg_error_t (*pincb)(void*, const char *, char **),
2330 #if GNUPG_MAJOR_VERSION != 1
2331 if (!opt.allow_admin)
2333 log_info (_("access to admin commands is not configured\n"));
2334 return gpg_error (GPG_ERR_EACCES);
2344 memset (&pininfo, 0, sizeof pininfo);
2345 pininfo.fixedlen = -1;
2346 pininfo.minlen = minlen;
2348 rc = build_enter_admin_pin_prompt (app, &prompt);
2352 if (!opt.disable_pinpad
2353 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
2354 && !check_pinpad_request (app, &pininfo, 1))
2356 /* The reader supports the verify command through the pinpad. */
2357 rc = pincb (pincb_arg, prompt, NULL);
2362 log_info (_("PIN callback returned error: %s\n"),
2366 rc = iso7816_verify_kp (app->slot, 0x83, &pininfo);
2367 /* Dismiss the prompt. */
2368 pincb (pincb_arg, NULL, NULL);
2375 rc = pincb (pincb_arg, prompt, &pinvalue);
2380 log_info (_("PIN callback returned error: %s\n"),
2385 if (strlen (pinvalue) < minlen)
2387 log_error (_("PIN for CHV%d is too short;"
2388 " minimum length is %d\n"), 3, minlen);
2390 return gpg_error (GPG_ERR_BAD_PIN);
2393 rc = pin2hash_if_kdf (app, 3, pinvalue, &pinlen);
2395 rc = iso7816_verify (app->slot, 0x83, pinvalue, pinlen);
2401 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
2402 flush_cache_after_error (app);
2411 /* Handle the SETATTR operation. All arguments are already basically
2414 do_setattr (app_t app, const char *name,
2415 gpg_error_t (*pincb)(void*, const char *, char **),
2417 const unsigned char *value, size_t valuelen)
2426 unsigned int need_v2:1;
2428 { "DISP-NAME", 0x005B, 3 },
2429 { "LOGIN-DATA", 0x005E, 3, 2 },
2430 { "DISP-LANG", 0x5F2D, 3 },
2431 { "DISP-SEX", 0x5F35, 3 },
2432 { "PUBKEY-URL", 0x5F50, 3 },
2433 { "CHV-STATUS-1", 0x00C4, 3, 1 },
2434 { "CA-FPR-1", 0x00CA, 3 },
2435 { "CA-FPR-2", 0x00CB, 3 },
2436 { "CA-FPR-3", 0x00CC, 3 },
2437 { "PRIVATE-DO-1", 0x0101, 2 },
2438 { "PRIVATE-DO-2", 0x0102, 3 },
2439 { "PRIVATE-DO-3", 0x0103, 2 },
2440 { "PRIVATE-DO-4", 0x0104, 3 },
2441 { "CERT-3", 0x7F21, 3, 0, 1 },
2442 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
2443 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
2444 { "KEY-ATTR", 0, 0, 3, 1 },
2445 { "AESKEY", 0x00D5, 3, 0, 1 },
2446 { "KDF", 0x00F9, 3, 0, 1 },
2451 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
2453 if (!table[idx].name)
2454 return gpg_error (GPG_ERR_INV_NAME);
2455 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
2456 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
2458 if (table[idx].special == 3)
2459 return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
2461 switch (table[idx].need_chv)
2464 rc = verify_chv2 (app, pincb, pincb_arg);
2467 rc = verify_chv3 (app, pincb, pincb_arg);
2475 /* Flush the cache before writing it, so that the next get operation
2476 will reread the data from the card and thus get synced in case of
2477 errors (e.g. data truncated by the card). */
2478 flush_cache_item (app, table[idx].tag);
2480 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
2481 exmode = 1; /* Use extended length w/o a limit. */
2482 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
2483 exmode = -254; /* Command chaining with max. 254 bytes. */
2486 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
2488 log_error ("failed to set '%s': %s\n", table[idx].name, gpg_strerror (rc));
2490 if (table[idx].special == 1)
2491 app->force_chv1 = (valuelen && *value == 0);
2492 else if (table[idx].special == 2)
2493 parse_login_data (app);
2499 /* Handle the WRITECERT command for OpenPGP. This rites the standard
2500 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
2501 PINCB and PINCB_ARG are the usual arguments for the pinentry
2504 do_writecert (app_t app, ctrl_t ctrl,
2505 const char *certidstr,
2506 gpg_error_t (*pincb)(void*, const char *, char **),
2508 const unsigned char *certdata, size_t certdatalen)
2511 #if GNUPG_MAJOR_VERSION > 1
2512 if (strcmp (certidstr, "OPENPGP.3"))
2513 return gpg_error (GPG_ERR_INV_ID);
2514 if (!certdata || !certdatalen)
2515 return gpg_error (GPG_ERR_INV_ARG);
2516 if (!app->app_local->extcap.is_v2)
2517 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2518 if (certdatalen > app->app_local->extcap.max_certlen_3)
2519 return gpg_error (GPG_ERR_TOO_LARGE);
2520 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
2522 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2528 /* Handle the PASSWD command. The following combinations are
2531 Flags CHVNO Vers. Description
2532 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
2533 RESET 1 2 Verify PW3 and set a new PW1.
2534 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
2535 RESET 2 2 Verify PW3 and set a new Reset Code.
2536 RESET 3 any Returns GPG_ERR_INV_ID.
2537 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
2538 - 1 2 Verify PW1 and set a new PW1.
2539 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
2540 - 2 2 Verify Reset Code and set a new PW1.
2541 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
2544 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
2546 gpg_error_t (*pincb)(void*, const char *, char **),
2550 int chvno = atoi (chvnostr);
2551 char *resetcode = NULL;
2552 char *oldpinvalue = NULL;
2553 char *pinvalue = NULL;
2554 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
2555 int set_resetcode = 0;
2563 memset (&pininfo, 0, sizeof pininfo);
2564 pininfo.fixedlen = -1;
2565 pininfo.minlen = minlen;
2567 if (reset_mode && chvno == 3)
2569 rc = gpg_error (GPG_ERR_INV_ID);
2573 if (!app->app_local->extcap.is_v2)
2575 /* Version 1 cards. */
2577 if (reset_mode || chvno == 3)
2579 /* We always require that the PIN is entered. */
2581 rc = verify_chv3 (app, pincb, pincb_arg);
2585 else if (chvno == 1 || chvno == 2)
2587 /* On a v1.x card CHV1 and CVH2 should always have the same
2588 value, thus we enforce it here. */
2589 int save_force = app->force_chv1;
2591 app->force_chv1 = 0;
2594 rc = verify_chv2 (app, pincb, pincb_arg);
2595 app->force_chv1 = save_force;
2601 rc = gpg_error (GPG_ERR_INV_ID);
2607 /* Version 2 cards. */
2609 if (!opt.disable_pinpad
2610 && !iso7816_check_pinpad (app->slot,
2611 ISO7816_CHANGE_REFERENCE_DATA, &pininfo)
2612 && !check_pinpad_request (app, &pininfo, chvno == 3))
2617 /* To reset a PIN the Admin PIN is required. */
2620 rc = verify_chv3 (app, pincb, pincb_arg);
2627 else if (chvno == 1 || chvno == 3)
2631 char *promptbuf = NULL;
2637 rc = build_enter_admin_pin_prompt (app, &promptbuf);
2643 prompt = _("||Please enter the PIN");
2644 rc = pincb (pincb_arg, prompt, &oldpinvalue);
2649 log_info (_("PIN callback returned error: %s\n"),
2654 if (strlen (oldpinvalue) < minlen)
2656 log_info (_("PIN for CHV%d is too short;"
2657 " minimum length is %d\n"), chvno, minlen);
2658 rc = gpg_error (GPG_ERR_BAD_PIN);
2663 else if (chvno == 2)
2665 /* There is no PW2 for v2 cards. We use this condition to
2666 allow a PW reset using the Reset Code. */
2668 unsigned char *value;
2674 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2675 if (!relptr || valuelen < 7)
2677 log_error (_("error retrieving CHV status from card\n"));
2679 rc = gpg_error (GPG_ERR_CARD);
2682 remaining = value[5];
2686 log_error (_("Reset Code not or not anymore available\n"));
2687 rc = gpg_error (GPG_ERR_BAD_PIN);
2691 rc = pincb (pincb_arg,
2692 _("||Please enter the Reset Code for the card"),
2696 log_info (_("PIN callback returned error: %s\n"),
2700 if (strlen (resetcode) < minlen)
2702 log_info (_("Reset Code is too short; minimum length is %d\n"),
2704 rc = gpg_error (GPG_ERR_BAD_PIN);
2710 rc = gpg_error (GPG_ERR_INV_ID);
2718 app->did_chv1 = app->did_chv2 = 0;
2722 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2723 keep it at the start of the string. We need this elsewhere
2724 to get some infos on the string. */
2725 rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
2726 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2728 if (rc || pinvalue == NULL)
2730 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2740 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2742 rc = gpg_error_from_syserror ();
2745 strcpy (buffer, resetcode);
2746 rc = pin2hash_if_kdf (app, 0, buffer, &pinlen0);
2749 strcpy (buffer+pinlen0, pinvalue);
2750 rc = pin2hash_if_kdf (app, 0, buffer+pinlen0, &pinlen);
2753 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2754 buffer, pinlen0+pinlen);
2755 wipememory (buffer, pinlen0 + pinlen);
2759 else if (set_resetcode)
2761 if (strlen (pinvalue) < 8)
2763 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2764 rc = gpg_error (GPG_ERR_BAD_PIN);
2768 rc = pin2hash_if_kdf (app, 0, pinvalue, &pinlen);
2770 rc = iso7816_put_data (app->slot, 0, 0xD3, pinvalue, pinlen);
2773 else if (reset_mode)
2775 rc = pin2hash_if_kdf (app, 1, pinvalue, &pinlen);
2777 rc = iso7816_reset_retry_counter (app->slot, 0x81, pinvalue, pinlen);
2778 if (!rc && !app->app_local->extcap.is_v2)
2779 rc = iso7816_reset_retry_counter (app->slot, 0x82, pinvalue, pinlen);
2781 else if (!app->app_local->extcap.is_v2)
2783 /* Version 1 cards. */
2784 if (chvno == 1 || chvno == 2)
2786 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2787 pinvalue, strlen (pinvalue));
2789 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2790 pinvalue, strlen (pinvalue));
2792 else /* CHVNO == 3 */
2794 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2795 pinvalue, strlen (pinvalue));
2800 /* Version 2 cards. */
2801 assert (chvno == 1 || chvno == 3);
2805 rc = pincb (pincb_arg,
2807 _("||Please enter the Admin PIN and New Admin PIN") :
2808 _("||Please enter the PIN and New PIN"), NULL);
2811 log_info (_("PIN callback returned error: %s\n"),
2815 rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0,
2817 pincb (pincb_arg, NULL, NULL); /* Dismiss the prompt. */
2821 rc = pin2hash_if_kdf (app, chvno, oldpinvalue, &pinlen0);
2823 rc = pin2hash_if_kdf (app, chvno, pinvalue, &pinlen);
2825 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2826 oldpinvalue, pinlen0,
2833 wipememory (pinvalue, pinlen);
2837 flush_cache_after_error (app);
2842 wipememory (resetcode, strlen (resetcode));
2847 wipememory (oldpinvalue, pinlen0);
2848 xfree (oldpinvalue);
2854 /* Check whether a key already exists. KEYIDX is the index of the key
2855 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2856 error returned if the key already exists. The flag GENERATING is
2857 only used to print correct messages. */
2859 does_key_exist (app_t app, int keyidx, int generating, int force)
2861 const unsigned char *fpr;
2862 unsigned char *buffer;
2866 assert (keyidx >=0 && keyidx <= 2);
2868 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2870 log_error (_("error reading application data\n"));
2871 return gpg_error (GPG_ERR_GENERAL);
2873 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2876 log_error (_("error reading fingerprint DO\n"));
2878 return gpg_error (GPG_ERR_GENERAL);
2881 for (i=0; i < 20 && !fpr[i]; i++)
2884 if (i!=20 && !force)
2886 log_error (_("key already exists\n"));
2887 return gpg_error (GPG_ERR_EEXIST);
2890 log_info (_("existing key will be replaced\n"));
2891 else if (generating)
2892 log_info (_("generating new key\n"));
2894 log_info (_("writing new key\n"));
2899 /* Create a TLV tag and value and store it at BUFFER. Return the length
2900 of tag and length. A LENGTH greater than 65535 is truncated. */
2902 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2904 unsigned char *p = buffer;
2906 assert (tag <= 0xffff);
2912 else if (length < 256)
2919 if (length > 0xffff)
2931 build_privkey_template (app_t app, int keyno,
2932 const unsigned char *rsa_n, size_t rsa_n_len,
2933 const unsigned char *rsa_e, size_t rsa_e_len,
2934 const unsigned char *rsa_p, size_t rsa_p_len,
2935 const unsigned char *rsa_q, size_t rsa_q_len,
2936 const unsigned char *rsa_u, size_t rsa_u_len,
2937 const unsigned char *rsa_dp, size_t rsa_dp_len,
2938 const unsigned char *rsa_dq, size_t rsa_dq_len,
2939 unsigned char **result, size_t *resultlen)
2941 size_t rsa_e_reqlen;
2942 unsigned char privkey[7*(1+3+3)];
2944 unsigned char exthdr[2+2+3];
2946 unsigned char suffix[2+3];
2950 unsigned char *template;
2951 size_t template_size;
2956 switch (app->app_local->keyattr[keyno].rsa.format)
2965 return gpg_error (GPG_ERR_INV_VALUE);
2968 /* Get the required length for E. Rounded up to the nearest byte */
2969 rsa_e_reqlen = (app->app_local->keyattr[keyno].rsa.e_bits + 7) / 8;
2970 assert (rsa_e_len <= rsa_e_reqlen);
2972 /* Build the 7f48 cardholder private key template. */
2976 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2977 datalen += rsa_e_reqlen;
2979 tp += add_tlv (tp, 0x92, rsa_p_len);
2980 datalen += rsa_p_len;
2982 tp += add_tlv (tp, 0x93, rsa_q_len);
2983 datalen += rsa_q_len;
2985 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
2986 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2988 tp += add_tlv (tp, 0x94, rsa_u_len);
2989 datalen += rsa_u_len;
2990 tp += add_tlv (tp, 0x95, rsa_dp_len);
2991 datalen += rsa_dp_len;
2992 tp += add_tlv (tp, 0x96, rsa_dq_len);
2993 datalen += rsa_dq_len;
2996 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
2997 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
2999 tp += add_tlv (tp, 0x97, rsa_n_len);
3000 datalen += rsa_n_len;
3002 privkey_len = tp - privkey;
3004 /* Build the extended header list without the private key template. */
3006 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
3008 tp += add_tlv (tp, 0x7f48, privkey_len);
3009 exthdr_len = tp - exthdr;
3011 /* Build the 5f48 suffix of the data. */
3013 tp += add_tlv (tp, 0x5f48, datalen);
3014 suffix_len = tp - suffix;
3016 /* Now concatenate everything. */
3017 template_size = (1 + 3 /* 0x4d and len. */
3022 tp = template = xtrymalloc_secure (template_size);
3024 return gpg_error_from_syserror ();
3026 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
3027 memcpy (tp, exthdr, exthdr_len);
3029 memcpy (tp, privkey, privkey_len);
3031 memcpy (tp, suffix, suffix_len);
3034 memcpy (tp, rsa_e, rsa_e_len);
3035 if (rsa_e_len < rsa_e_reqlen)
3037 /* Right justify E. */
3038 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
3039 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
3043 memcpy (tp, rsa_p, rsa_p_len);
3046 memcpy (tp, rsa_q, rsa_q_len);
3049 if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
3050 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
3052 memcpy (tp, rsa_u, rsa_u_len);
3054 memcpy (tp, rsa_dp, rsa_dp_len);
3056 memcpy (tp, rsa_dq, rsa_dq_len);
3060 if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
3061 || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
3063 memcpy (tp, rsa_n, rsa_n_len);
3067 /* Sanity check. We don't know the exact length because we
3068 allocated 3 bytes for the first length header. */
3069 assert (tp - template <= template_size);
3072 *resultlen = tp - template;
3077 build_ecc_privkey_template (app_t app, int keyno,
3078 const unsigned char *ecc_d, size_t ecc_d_len,
3079 const unsigned char *ecc_q, size_t ecc_q_len,
3080 unsigned char **result, size_t *resultlen)
3082 unsigned char privkey[2+2];
3084 unsigned char exthdr[2+2+1];
3086 unsigned char suffix[2+1];
3090 unsigned char *template;
3091 size_t template_size;
3092 int pubkey_required;
3094 pubkey_required = !!(app->app_local->keyattr[keyno].ecc.flags
3100 /* Build the 7f48 cardholder private key template. */
3104 tp += add_tlv (tp, 0x92, ecc_d_len);
3105 datalen += ecc_d_len;
3107 if (pubkey_required)
3109 tp += add_tlv (tp, 0x99, ecc_q_len);
3110 datalen += ecc_q_len;
3113 privkey_len = tp - privkey;
3116 /* Build the extended header list without the private key template. */
3118 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
3120 tp += add_tlv (tp, 0x7f48, privkey_len);
3121 exthdr_len = tp - exthdr;
3123 /* Build the 5f48 suffix of the data. */
3125 tp += add_tlv (tp, 0x5f48, datalen);
3126 suffix_len = tp - suffix;
3128 /* Now concatenate everything. */
3129 template_size = (1 + 1 /* 0x4d and len. */
3134 if (exthdr_len + privkey_len + suffix_len + datalen >= 128)
3136 tp = template = xtrymalloc_secure (template_size);
3138 return gpg_error_from_syserror ();
3140 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
3141 memcpy (tp, exthdr, exthdr_len);
3143 memcpy (tp, privkey, privkey_len);
3145 memcpy (tp, suffix, suffix_len);
3148 memcpy (tp, ecc_d, ecc_d_len);
3151 if (pubkey_required)
3153 memcpy (tp, ecc_q, ecc_q_len);
3157 assert (tp - template == template_size);
3160 *resultlen = tp - template;
3165 /* Helper for do_writekley to change the size of a key. Not ethat
3166 this deletes the entire key without asking. */
3168 change_keyattr (app_t app, int keyno, const unsigned char *buf, size_t buflen,
3169 gpg_error_t (*pincb)(void*, const char *, char **),
3174 assert (keyno >=0 && keyno <= 2);
3176 /* Prepare for storing the key. */
3177 err = verify_chv3 (app, pincb, pincb_arg);
3181 /* Change the attribute. */
3182 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buf, buflen);
3184 log_error ("error changing key attribute (key=%d)\n", keyno+1);
3186 log_info ("key attribute changed (key=%d)\n", keyno+1);
3188 parse_algorithm_attribute (app, keyno);
3197 change_rsa_keyattr (app_t app, int keyno, unsigned int nbits,
3198 gpg_error_t (*pincb)(void*, const char *, char **),
3201 gpg_error_t err = 0;
3206 /* Read the current attributes into a buffer. */
3207 relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL);
3209 err = gpg_error (GPG_ERR_CARD);
3210 else if (buflen < 6 || buf[0] != PUBKEY_ALGO_RSA)
3212 /* Attriutes too short or not an RSA key. */
3214 err = gpg_error (GPG_ERR_CARD);
3218 /* We only change n_bits and don't touch anything else. Before we
3219 do so, we round up NBITS to a sensible way in the same way as
3220 gpg's key generation does it. This may help to sort out problems
3221 with a few bits too short keys. */
3222 nbits = ((nbits + 31) / 32) * 32;
3223 buf[1] = (nbits >> 8);
3225 err = change_keyattr (app, keyno, buf, buflen, pincb, pincb_arg);
3233 /* Helper to process an setattr command for name KEY-ATTR.
3234 In (VALUE,VALUELEN), it expects following string:
3235 RSA: "--force <key> <algo> rsa<nbits>"
3236 ECC: "--force <key> <algo> <curvename>"
3239 change_keyattr_from_string (app_t app,
3240 gpg_error_t (*pincb)(void*, const char *, char **),
3242 const void *value, size_t valuelen)
3244 gpg_error_t err = 0;
3246 int key, keyno, algo;
3249 /* VALUE is expected to be a string but not guaranteed to be
3250 terminated. Thus copy it to an allocated buffer first. */
3251 string = xtrymalloc (valuelen+1);
3253 return gpg_error_from_syserror ();
3254 memcpy (string, value, valuelen);
3255 string[valuelen] = 0;
3257 /* Because this function deletes the key we require the string
3258 "--force" in the data to make clear that something serious might
3260 sscanf (string, "--force %d %d %n", &key, &algo, &n);
3263 err = gpg_error (GPG_ERR_INV_DATA);
3268 if (keyno < 0 || keyno > 2)
3269 err = gpg_error (GPG_ERR_INV_ID);
3270 else if (algo == PUBKEY_ALGO_RSA)
3275 nbits = strtoul (string+n+3, NULL, 10);
3277 err = gpg_error (GPG_ERR_INV_DATA);
3278 else if (nbits < 1024)
3279 err = gpg_error (GPG_ERR_TOO_SHORT);
3280 else if (nbits > 4096)
3281 err = gpg_error (GPG_ERR_TOO_LARGE);
3283 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
3285 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
3286 || algo == PUBKEY_ALGO_EDDSA)
3290 const unsigned char *oidbuf;
3293 oidstr = openpgp_curve_to_oid (string+n, NULL);
3296 err = gpg_error (GPG_ERR_INV_DATA);
3300 err = openpgp_oid_from_str (oidstr, &oid);
3304 oidbuf = gcry_mpi_get_opaque (oid, &n);
3307 /* We have enough room at STRING. */
3309 memcpy (string+1, oidbuf+1, oid_len-1);
3310 err = change_keyattr (app, keyno, string, oid_len, pincb, pincb_arg);
3311 gcry_mpi_release (oid);
3314 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3323 rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3324 void *pincb_arg, int keyno,
3325 const unsigned char *buf, size_t buflen, int depth)
3328 const unsigned char *tok;
3330 int last_depth1, last_depth2;
3331 const unsigned char *rsa_n = NULL;
3332 const unsigned char *rsa_e = NULL;
3333 const unsigned char *rsa_p = NULL;
3334 const unsigned char *rsa_q = NULL;
3335 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
3337 unsigned int maxbits;
3338 unsigned char *template = NULL;
3340 size_t template_len;
3341 unsigned char fprbuf[20];
3344 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA)
3346 log_error (_("unsupported algorithm: %s"), "RSA");
3347 err = gpg_error (GPG_ERR_INV_VALUE);
3351 last_depth1 = depth;
3352 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3353 && depth && depth >= last_depth1)
3357 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3360 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3362 if (tok && toklen == 1)
3364 const unsigned char **mpi;
3369 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
3370 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
3371 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
3372 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
3373 default: mpi = NULL; mpi_len = NULL; break;
3377 err = gpg_error (GPG_ERR_DUP_VALUE);
3380 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3384 /* Strip off leading zero bytes and save. */
3385 for (;toklen && !*tok; toklen--, tok++)
3391 /* Skip until end of list. */
3392 last_depth2 = depth;
3393 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3394 && depth && depth >= last_depth2)
3399 /* Parse other attributes. */
3400 last_depth1 = depth;
3401 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3402 && depth && depth >= last_depth1)
3406 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3409 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3411 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3413 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3417 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3419 created_at = created_at*10 + (*tok - '0');
3422 /* Skip until end of list. */
3423 last_depth2 = depth;
3424 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3425 && depth && depth >= last_depth2)
3432 /* Check that we have all parameters and that they match the card
3436 log_error (_("creation timestamp missing\n"));
3437 err = gpg_error (GPG_ERR_INV_VALUE);
3441 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
3442 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
3444 log_info ("RSA modulus size is %u bits\n", nbits);
3445 if (nbits && nbits != maxbits
3446 && app->app_local->extcap.algo_attr_change)
3448 /* Try to switch the key to a new length. */
3449 err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
3451 maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
3453 if (nbits != maxbits)
3455 log_error (_("RSA modulus missing or not of size %d bits\n"),
3457 err = gpg_error (GPG_ERR_BAD_SECKEY);
3461 maxbits = app->app_local->keyattr[keyno].rsa.e_bits;
3462 if (maxbits > 32 && !app->app_local->extcap.is_v2)
3463 maxbits = 32; /* Our code for v1 does only support 32 bits. */
3464 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
3465 if (nbits < 2 || nbits > maxbits)
3467 log_error (_("RSA public exponent missing or larger than %d bits\n"),
3469 err = gpg_error (GPG_ERR_BAD_SECKEY);
3473 maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2;
3474 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
3475 if (nbits != maxbits)
3477 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3479 err = gpg_error (GPG_ERR_BAD_SECKEY);
3482 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
3483 if (nbits != maxbits)
3485 log_error (_("RSA prime %s missing or not of size %d bits\n"),
3487 err = gpg_error (GPG_ERR_BAD_SECKEY);
3491 /* We need to remove the cached public key. */
3492 xfree (app->app_local->pk[keyno].key);
3493 app->app_local->pk[keyno].key = NULL;
3494 app->app_local->pk[keyno].keylen = 0;
3495 app->app_local->pk[keyno].read_done = 0;
3498 if (app->app_local->extcap.is_v2)
3500 unsigned char *rsa_u, *rsa_dp, *rsa_dq;
3501 size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
3502 gcry_mpi_t mpi_e, mpi_p, mpi_q;
3503 gcry_mpi_t mpi_u = gcry_mpi_snew (0);
3504 gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
3505 gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
3506 gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
3509 /* Calculate the u, dp and dq components needed by RSA_CRT cards */
3510 gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
3511 gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
3512 gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
3514 gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
3515 gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
3516 gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
3517 gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
3518 gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
3520 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
3521 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
3522 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
3524 gcry_mpi_release (mpi_e);
3525 gcry_mpi_release (mpi_p);
3526 gcry_mpi_release (mpi_q);
3527 gcry_mpi_release (mpi_u);
3528 gcry_mpi_release (mpi_dp);
3529 gcry_mpi_release (mpi_dq);
3530 gcry_mpi_release (mpi_tmp);
3532 /* Build the private key template as described in section 4.3.3.7 of
3533 the OpenPGP card specs version 2.0. */
3534 err = build_privkey_template (app, keyno,
3542 &template, &template_len);
3550 /* Prepare for storing the key. */
3551 err = verify_chv3 (app, pincb, pincb_arg);
3555 /* Store the key. */
3556 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3557 exmode = 1; /* Use extended length w/o a limit. */
3558 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3562 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3563 template, template_len);
3567 /* Build the private key template as described in section 4.3.3.6 of
3568 the OpenPGP card specs version 1.1:
3569 0xC0 <length> public exponent
3570 0xC1 <length> prime p
3571 0xC2 <length> prime q
3573 assert (rsa_e_len <= 4);
3574 template_len = (1 + 1 + 4
3576 + 1 + 1 + rsa_q_len);
3577 template = tp = xtrymalloc_secure (template_len);
3580 err = gpg_error_from_syserror ();
3585 memcpy (tp, rsa_e, rsa_e_len);
3588 /* Right justify E. */
3589 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
3590 memset (tp, 0, 4-rsa_e_len);
3596 memcpy (tp, rsa_p, rsa_p_len);
3601 memcpy (tp, rsa_q, rsa_q_len);
3604 assert (tp - template == template_len);
3606 /* Prepare for storing the key. */
3607 err = verify_chv3 (app, pincb, pincb_arg);
3611 /* Store the key. */
3612 err = iso7816_put_data (app->slot, 0,
3613 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
3614 template, template_len);
3618 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3622 err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
3623 rsa_n, rsa_n_len, rsa_e, rsa_e_len);
3635 ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
3636 void *pincb_arg, int keyno,
3637 const unsigned char *buf, size_t buflen, int depth)
3640 const unsigned char *tok;
3642 int last_depth1, last_depth2;
3643 const unsigned char *ecc_q = NULL;
3644 const unsigned char *ecc_d = NULL;
3645 size_t ecc_q_len, ecc_d_len;
3646 const char *curve = NULL;
3649 int flag_djb_tweak = 0;
3651 gcry_mpi_t oid = NULL;
3652 const unsigned char *oidbuf;
3655 unsigned char fprbuf[20];
3657 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3658 curve = "NIST P-256" */
3659 /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
3660 curve = "secp256k1" */
3661 /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)):
3662 curve = "Ed25519" */
3663 last_depth1 = depth;
3664 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3665 && depth && depth >= last_depth1)
3669 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3672 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3675 if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
3679 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3682 curve_name = xtrymalloc (toklen+1);
3685 err = gpg_error_from_syserror ();
3689 memcpy (curve_name, tok, toklen);
3690 curve_name[toklen] = 0;
3691 curve = openpgp_is_curve_supported (curve_name, NULL, NULL);
3694 else if (tok && toklen == 5 && !memcmp (tok, "flags", 5))
3696 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3701 if ((toklen == 5 && !memcmp (tok, "eddsa", 5))
3702 || (toklen == 9 && !memcmp (tok, "djb-tweak", 9)))
3706 else if (tok && toklen == 1)
3708 const unsigned char **buf2;
3710 int native = flag_djb_tweak;
3714 case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break;
3715 case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; native = 0; break;
3716 default: buf2 = NULL; buf2len = NULL; break;
3720 err = gpg_error (GPG_ERR_DUP_VALUE);
3723 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3728 /* Strip off leading zero bytes and save. */
3729 for (;toklen && !*tok; toklen--, tok++)
3736 /* Skip until end of list. */
3737 last_depth2 = depth;
3738 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3739 && depth && depth >= last_depth2)
3744 /* Parse other attributes. */
3745 last_depth1 = depth;
3746 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3747 && depth && depth >= last_depth1)
3751 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
3754 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3756 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
3758 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
3762 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
3764 created_at = created_at*10 + (*tok - '0');
3767 /* Skip until end of list. */
3768 last_depth2 = depth;
3769 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
3770 && depth && depth >= last_depth2)
3777 /* Check that we have all parameters and that they match the card
3781 log_error (_("unsupported curve\n"));
3782 err = gpg_error (GPG_ERR_INV_VALUE);
3787 log_error (_("creation timestamp missing\n"));
3788 err = gpg_error (GPG_ERR_INV_VALUE);
3791 if (flag_djb_tweak && keyno != 1)
3792 algo = PUBKEY_ALGO_EDDSA;
3793 else if (keyno == 1)
3794 algo = PUBKEY_ALGO_ECDH;
3796 algo = PUBKEY_ALGO_ECDSA;
3798 oidstr = openpgp_curve_to_oid (curve, NULL);
3799 err = openpgp_oid_from_str (oidstr, &oid);
3802 oidbuf = gcry_mpi_get_opaque (oid, &n);
3805 err = gpg_error_from_syserror ();
3810 if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC
3811 || app->app_local->keyattr[keyno].ecc.curve != curve
3812 || (flag_djb_tweak !=
3813 (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)))
3815 if (app->app_local->extcap.algo_attr_change)
3817 unsigned char *keyattr;
3821 err = gpg_error (GPG_ERR_INTERNAL);
3824 keyattr = xtrymalloc (oid_len);
3827 err = gpg_error_from_syserror ();
3831 memcpy (keyattr+1, oidbuf+1, oid_len-1);
3832 err = change_keyattr (app, keyno, keyattr, oid_len, pincb, pincb_arg);
3839 log_error ("key attribute on card doesn't match\n");
3840 err = gpg_error (GPG_ERR_INV_VALUE);
3846 log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
3848 /* We need to remove the cached public key. */
3849 xfree (app->app_local->pk[keyno].key);
3850 app->app_local->pk[keyno].key = NULL;
3851 app->app_local->pk[keyno].keylen = 0;
3852 app->app_local->pk[keyno].read_done = 0;
3854 if (app->app_local->extcap.is_v2)
3856 /* Build the private key template as described in section 4.3.3.7 of
3857 the OpenPGP card specs version 2.0. */
3858 unsigned char *template;
3859 size_t template_len;
3862 err = build_ecc_privkey_template (app, keyno,
3865 &template, &template_len);
3869 /* Prepare for storing the key. */
3870 err = verify_chv3 (app, pincb, pincb_arg);
3877 /* Store the key. */
3878 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
3879 exmode = 1; /* Use extended length w/o a limit. */
3880 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
3884 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
3885 template, template_len);
3889 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3893 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3897 err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
3898 ecc_q, ecc_q_len, ecdh_params (curve), (size_t)4);
3901 gcry_mpi_release (oid);
3905 /* Handle the WRITEKEY command for OpenPGP. This function expects a
3906 canonical encoded S-expression with the secret key in KEYDATA and
3907 its length (for assertions) in KEYDATALEN. KEYID needs to be the
3908 usual keyid which for OpenPGP is the string "OPENPGP.n" with
3909 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
3910 get overwritten. PINCB and PINCB_ARG are the usual arguments for
3911 the pinentry callback. */
3913 do_writekey (app_t app, ctrl_t ctrl,
3914 const char *keyid, unsigned int flags,
3915 gpg_error_t (*pincb)(void*, const char *, char **),
3917 const unsigned char *keydata, size_t keydatalen)
3920 int force = (flags & 1);
3922 const unsigned char *buf, *tok;
3923 size_t buflen, toklen;
3928 if (!strcmp (keyid, "OPENPGP.1"))
3930 else if (!strcmp (keyid, "OPENPGP.2"))
3932 else if (!strcmp (keyid, "OPENPGP.3"))
3935 return gpg_error (GPG_ERR_INV_ID);
3937 err = does_key_exist (app, keyno, 0, force);
3943 Parse the S-expression
3946 buflen = keydatalen;
3948 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3950 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3952 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
3956 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
3957 log_info ("protected-private-key passed to writekey\n");
3958 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
3959 log_info ("shadowed-private-key passed to writekey\n");
3960 err = gpg_error (GPG_ERR_BAD_SECKEY);
3963 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3965 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3967 if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
3968 err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3969 else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
3970 err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
3973 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
3983 /* Handle the GENKEY command. */
3985 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
3987 gpg_error_t (*pincb)(void*, const char *, char **),
3992 unsigned char *buffer = NULL;
3993 const unsigned char *keydata;
3994 size_t buflen, keydatalen;
3996 int keyno = atoi (keynostr) - 1;
3997 int force = (flags & 1);
4000 int le_value = 256; /* Use legacy value. */
4002 if (keyno < 0 || keyno > 2)
4003 return gpg_error (GPG_ERR_INV_ID);
4005 /* We flush the cache to increase the traffic before a key
4006 generation. This _might_ help a card to gather more entropy. */
4009 /* Obviously we need to remove the cached public key. */
4010 xfree (app->app_local->pk[keyno].key);
4011 app->app_local->pk[keyno].key = NULL;
4012 app->app_local->pk[keyno].keylen = 0;
4013 app->app_local->pk[keyno].read_done = 0;
4015 /* Check whether a key already exists. */
4016 err = does_key_exist (app, keyno, 1, force);
4020 if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
4022 unsigned int keybits = app->app_local->keyattr[keyno].rsa.n_bits;
4024 /* Because we send the key parameter back via status lines we need
4025 to put a limit on the max. allowed keysize. 2048 bit will
4026 already lead to a 527 byte long status line and thus a 4096 bit
4027 key would exceed the Assuan line length limit. */
4029 return gpg_error (GPG_ERR_TOO_LARGE);
4031 if (app->app_local->cardcap.ext_lc_le && keybits > RSA_SMALL_SIZE_KEY
4032 && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA)
4034 exmode = 1; /* Use extended length w/o a limit. */
4035 le_value = determine_rsa_response (app, keyno);
4036 /* No need to check le_value because it comes from a 16 bit
4037 value and thus can't create an overflow on a 32 bit
4042 /* Prepare for key generation by verifying the Admin PIN. */
4043 err = verify_chv3 (app, pincb, pincb_arg);
4048 log_info (_("please wait while key is being generated ...\n"));
4049 start_at = time (NULL);
4050 err = iso7816_generate_keypair (app->slot, exmode,
4051 (keyno == 0? "\xB6" :
4052 keyno == 1? "\xB8" : "\xA4"),
4053 2, le_value, &buffer, &buflen);
4056 log_error (_("generating key failed\n"));
4057 return gpg_error (GPG_ERR_CARD);
4061 int nsecs = (int)(time (NULL) - start_at);
4062 log_info (ngettext("key generation completed (%d second)\n",
4063 "key generation completed (%d seconds)\n",
4067 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
4070 err = gpg_error (GPG_ERR_CARD);
4071 log_error (_("response does not contain the public key data\n"));
4075 created_at = (u32)(createtime? createtime : gnupg_get_time ());
4076 sprintf (numbuf, "%u", created_at);
4077 send_status_info (ctrl, "KEY-CREATED-AT",
4078 numbuf, (size_t)strlen(numbuf), NULL, 0);
4080 err = read_public_key (app, ctrl, created_at, keyno, buffer, buflen);
4087 static unsigned long
4088 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
4093 ul = (value[0] << 16) | (value[1] << 8) | value[2];
4096 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
4102 static unsigned long
4103 get_sig_counter (app_t app)
4106 unsigned char *value;
4110 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
4113 ul = convert_sig_counter_value (value, valuelen);
4119 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
4121 const unsigned char *fpr;
4122 unsigned char *buffer;
4126 assert (keyno >= 0 && keyno <= 2);
4128 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
4131 log_error (_("error reading application data\n"));
4132 return gpg_error (GPG_ERR_GENERAL);
4134 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
4135 if (!fpr || n != 60)
4138 log_error (_("error reading fingerprint DO\n"));
4139 return gpg_error (GPG_ERR_GENERAL);
4142 for (i=0; i < 20; i++)
4143 if (sha1fpr[i] != fpr[i])
4146 log_info (_("fingerprint on card does not match requested one\n"));
4147 return gpg_error (GPG_ERR_WRONG_SECKEY);
4154 /* If a fingerprint has been specified check it against the one on the
4155 card. This allows for a meaningful error message in case the key
4156 on the card has been replaced but the shadow information known to
4157 gpg has not been updated. If there is no fingerprint we assume
4158 that this is okay. */
4160 check_against_given_fingerprint (app_t app, const char *fpr, int key)
4162 unsigned char tmp[20];
4166 for (s=fpr, n=0; hexdigitp (s); s++, n++)
4169 return gpg_error (GPG_ERR_INV_ID);
4173 return gpg_error (GPG_ERR_INV_ID);
4175 for (s=fpr, n=0; n < 20; s += 2, n++)
4176 tmp[n] = xtoi_2 (s);
4177 return compare_fingerprint (app, key-1, tmp);
4182 /* Compute a digital signature on INDATA which is expected to be the
4183 raw message digest. For this application the KEYIDSTR consists of
4184 the serialnumber and the fingerprint delimited by a slash.
4186 Note that this function may return the error code
4187 GPG_ERR_WRONG_CARD to indicate that the card currently present does
4188 not match the one required for the requested action (e.g. the
4189 serial number does not match).
4191 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
4192 operation to the auth command.
4195 do_sign (app_t app, const char *keyidstr, int hashalgo,
4196 gpg_error_t (*pincb)(void*, const char *, char **),
4198 const void *indata, size_t indatalen,
4199 unsigned char **outdata, size_t *outdatalen )
4201 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
4202 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
4203 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
4204 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
4205 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
4206 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
4207 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
4208 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
4209 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
4211 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
4212 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
4213 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
4215 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
4216 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
4217 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
4219 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
4220 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
4221 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
4224 unsigned char data[19+64];
4226 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
4229 const char *fpr = NULL;
4230 unsigned long sigcount;
4232 int exmode, le_value;
4234 if (!keyidstr || !*keyidstr)
4235 return gpg_error (GPG_ERR_INV_VALUE);
4237 /* Strip off known prefixes. */
4238 #define X(a,b,c,d) \
4239 if (hashalgo == GCRY_MD_ ## a \
4241 && indatalen == sizeof b ## _prefix + (c) \
4242 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
4244 indata = (const char*)indata + sizeof b ## _prefix; \
4245 indatalen -= sizeof b ## _prefix; \
4248 if (indatalen == 20)
4249 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
4250 else X(SHA1, sha1, 20, 1)
4251 else X(RMD160, rmd160, 20, 1)
4252 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
4253 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
4254 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
4255 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
4256 else if ((indatalen == 28 || indatalen == 32
4257 || indatalen == 48 || indatalen ==64)
4258 && app->app_local->extcap.is_v2)
4259 ; /* Assume a plain SHA-3 digest has been given. */
4262 log_error (_("card does not support digest algorithm %s\n"),
4263 gcry_md_algo_name (hashalgo));
4264 /* Or the supplied digest length does not match an algorithm. */
4265 return gpg_error (GPG_ERR_INV_VALUE);
4269 /* Check whether an OpenPGP card of any version has been requested. */
4270 if (!strcmp (keyidstr, "OPENPGP.1"))
4272 else if (!strcmp (keyidstr, "OPENPGP.3"))
4274 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4275 return gpg_error (GPG_ERR_INV_ID);
4278 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4281 return gpg_error (GPG_ERR_INV_ID);
4283 ; /* no fingerprint given: we allow this for now. */
4287 return gpg_error (GPG_ERR_INV_ID);
4289 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4290 tmp_sn[n] = xtoi_2 (s);
4292 if (app->serialnolen != 16)
4293 return gpg_error (GPG_ERR_INV_CARD);
4294 if (memcmp (app->serialno, tmp_sn, 16))
4295 return gpg_error (GPG_ERR_WRONG_CARD);
4298 /* If a fingerprint has been specified check it against the one on
4299 the card. This is allows for a meaningful error message in case
4300 the key on the card has been replaced but the shadow information
4301 known to gpg was not updated. If there is no fingerprint, gpg
4302 will detect a bogus signature anyway due to the
4303 verify-after-signing feature. */
4304 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
4308 /* Concatenate prefix and digest. */
4310 if (hashalgo == GCRY_MD_ ## a && (d) ) \
4312 datalen = sizeof b ## _prefix + indatalen; \
4313 assert (datalen <= sizeof data); \
4314 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
4315 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
4319 || app->app_local->keyattr[use_auth? 2: 0].key_type == KEY_TYPE_RSA)
4322 else X(RMD160, rmd160, 1)
4323 else X(SHA224, sha224, app->app_local->extcap.is_v2)
4324 else X(SHA256, sha256, app->app_local->extcap.is_v2)
4325 else X(SHA384, sha384, app->app_local->extcap.is_v2)
4326 else X(SHA512, sha512, app->app_local->extcap.is_v2)
4328 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
4332 datalen = indatalen;
4333 memcpy (data, indata, indatalen);
4337 /* Redirect to the AUTH command if asked to. */
4340 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
4342 outdata, outdatalen);
4345 /* Show the number of signature done using this key. */
4346 sigcount = get_sig_counter (app);
4347 log_info (_("signatures created so far: %lu\n"), sigcount);
4349 /* Check CHV if needed. */
4350 if (!app->did_chv1 || app->force_chv1 )
4355 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue, &pinlen);
4361 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
4362 sync, thus we verify CHV2 here using the given PIN. Cards
4363 with version2 to not have the need for a separate CHV2 and
4364 internally use just one. Obviously we can't do that if the
4365 pinpad has been used. */
4366 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
4368 rc = iso7816_verify (app->slot, 0x82, pinvalue, pinlen);
4369 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
4370 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
4373 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
4375 flush_cache_after_error (app);
4384 if (app->app_local->cardcap.ext_lc_le
4385 && app->app_local->keyattr[0].key_type == KEY_TYPE_RSA
4386 && app->app_local->keyattr[0].rsa.n_bits > RSA_SMALL_SIZE_OP)
4388 exmode = 1; /* Use extended length. */
4389 le_value = app->app_local->keyattr[0].rsa.n_bits / 8;
4396 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
4397 outdata, outdatalen);
4401 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
4402 on INDATA which is expected to be the raw message digest. For this
4403 application the KEYIDSTR consists of the serialnumber and the
4404 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
4407 Note that this function may return the error code
4408 GPG_ERR_WRONG_CARD to indicate that the card currently present does
4409 not match the one required for the requested action (e.g. the
4410 serial number does not match). */
4412 do_auth (app_t app, const char *keyidstr,
4413 gpg_error_t (*pincb)(void*, const char *, char **),
4415 const void *indata, size_t indatalen,
4416 unsigned char **outdata, size_t *outdatalen )
4419 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
4422 const char *fpr = NULL;
4424 if (!keyidstr || !*keyidstr)
4425 return gpg_error (GPG_ERR_INV_VALUE);
4426 if (app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
4427 && indatalen > 101) /* For a 2048 bit key. */
4428 return gpg_error (GPG_ERR_INV_VALUE);
4430 if (app->app_local->keyattr[2].key_type == KEY_TYPE_ECC)
4432 if (!(app->app_local->keyattr[2].ecc.flags & ECC_FLAG_DJB_TWEAK)
4433 && (indatalen == 51 || indatalen == 67 || indatalen == 83))
4435 const char *p = (const char *)indata + 19;
4441 const char *p = (const char *)indata + 15;
4447 /* Check whether an OpenPGP card of any version has been requested. */
4448 if (!strcmp (keyidstr, "OPENPGP.3"))
4450 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4451 return gpg_error (GPG_ERR_INV_ID);
4454 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4457 return gpg_error (GPG_ERR_INV_ID);
4459 ; /* no fingerprint given: we allow this for now. */
4463 return gpg_error (GPG_ERR_INV_ID);
4465 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4466 tmp_sn[n] = xtoi_2 (s);
4468 if (app->serialnolen != 16)
4469 return gpg_error (GPG_ERR_INV_CARD);
4470 if (memcmp (app->serialno, tmp_sn, 16))
4471 return gpg_error (GPG_ERR_WRONG_CARD);
4474 /* If a fingerprint has been specified check it against the one on
4475 the card. This is allows for a meaningful error message in case
4476 the key on the card has been replaced but the shadow information
4477 known to gpg was not updated. If there is no fingerprint, gpg
4478 will detect a bogus signature anyway due to the
4479 verify-after-signing feature. */
4480 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
4484 rc = verify_chv2 (app, pincb, pincb_arg);
4487 int exmode, le_value;
4489 if (app->app_local->cardcap.ext_lc_le
4490 && app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
4491 && app->app_local->keyattr[2].rsa.n_bits > RSA_SMALL_SIZE_OP)
4493 exmode = 1; /* Use extended length. */
4494 le_value = app->app_local->keyattr[2].rsa.n_bits / 8;
4501 rc = iso7816_internal_authenticate (app->slot, exmode,
4502 indata, indatalen, le_value,
4503 outdata, outdatalen);
4510 do_decipher (app_t app, const char *keyidstr,
4511 gpg_error_t (*pincb)(void*, const char *, char **),
4513 const void *indata, size_t indatalen,
4514 unsigned char **outdata, size_t *outdatalen,
4515 unsigned int *r_info)
4518 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
4521 const char *fpr = NULL;
4522 int exmode, le_value;
4523 unsigned char *fixbuf = NULL;
4527 if (!keyidstr || !*keyidstr || !indatalen)
4528 return gpg_error (GPG_ERR_INV_VALUE);
4530 /* Check whether an OpenPGP card of any version has been requested. */
4531 if (!strcmp (keyidstr, "OPENPGP.2"))
4533 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4534 return gpg_error (GPG_ERR_INV_ID);
4537 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4540 return gpg_error (GPG_ERR_INV_ID);
4542 ; /* no fingerprint given: we allow this for now. */
4546 return gpg_error (GPG_ERR_INV_ID);
4548 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4549 tmp_sn[n] = xtoi_2 (s);
4551 if (app->serialnolen != 16)
4552 return gpg_error (GPG_ERR_INV_CARD);
4553 if (memcmp (app->serialno, tmp_sn, 16))
4554 return gpg_error (GPG_ERR_WRONG_CARD);
4557 /* If a fingerprint has been specified check it against the one on
4558 the card. This is allows for a meaningful error message in case
4559 the key on the card has been replaced but the shadow information
4560 known to gpg was not updated. If there is no fingerprint, the
4561 decryption won't produce the right plaintext anyway. */
4562 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
4566 rc = verify_chv2 (app, pincb, pincb_arg);
4570 if ((indatalen == 16 + 1 || indatalen == 32 + 1)
4571 && ((char *)indata)[0] == 0x02)
4573 /* PSO:DECIPHER with symmetric key. */
4576 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA)
4578 /* We might encounter a couple of leading zeroes in the
4579 cryptogram. Due to internal use of MPIs these leading zeroes
4580 are stripped. However the OpenPGP card expects exactly 128
4581 bytes for the cryptogram (for a 1k key). Thus we need to fix
4582 it up. We do this for up to 16 leading zero bytes; a
4583 cryptogram with more than this is with a very high
4584 probability anyway broken. If a signed conversion was used
4585 we may also encounter one leading zero followed by the correct
4586 length. We fix that as well. */
4587 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
4588 fixuplen = 128 - indatalen;
4589 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
4590 fixuplen = 192 - indatalen;
4591 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
4592 fixuplen = 256 - indatalen;
4593 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
4594 fixuplen = 384 - indatalen;
4595 else if (indatalen >= (512-16) && indatalen < 512) /* 4096 bit key. */
4596 fixuplen = 512 - indatalen;
4597 else if (!*(const char *)indata && (indatalen == 129
4601 || indatalen == 513))
4608 /* While we have to prepend stuff anyway, we can also
4609 include the padding byte here so that iso1816_decipher
4610 does not need to do another data mangling. */
4613 fixbuf = xtrymalloc (fixuplen + indatalen);
4615 return gpg_error_from_syserror ();
4617 memset (fixbuf, 0, fixuplen);
4618 memcpy (fixbuf+fixuplen, indata, indatalen);
4620 indatalen = fixuplen + indatalen;
4621 padind = -1; /* Already padded. */
4623 else if (fixuplen < 0)
4625 /* We use the extra leading zero as the padding byte. */
4629 else if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
4631 int old_format_len = 0;
4633 if ((app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK))
4635 if (indatalen > 32 && (indatalen % 2))
4637 * Skip the prefix. It may be 0x40 (in new format), or MPI
4638 * head of 0x00 (in old format).
4640 indata = (const char *)indata + 1;
4643 else if (indatalen < 32)
4645 * Old format trancated by MPI handling.
4647 old_format_len = indatalen;
4653 if (indatalen < 128)
4658 fixbuf = xtrymalloc (fixuplen + indatalen);
4660 return gpg_error_from_syserror ();
4662 /* Build 'Cipher DO' */
4663 fixbuf[n++] = '\xa6';
4664 if (indatalen < 128)
4665 fixbuf[n++] = (char)(indatalen+5);
4669 fixbuf[n++] = (char)(indatalen+7);
4671 fixbuf[n++] = '\x7f';
4672 fixbuf[n++] = '\x49';
4673 if (indatalen < 128)
4674 fixbuf[n++] = (char)(indatalen+2);
4678 fixbuf[n++] = (char)(indatalen+3);
4680 fixbuf[n++] = '\x86';
4681 if (indatalen < 128)
4682 fixbuf[n++] = (char)indatalen;
4686 fixbuf[n++] = (char)indatalen;
4691 memset (fixbuf+fixuplen, 0, 32 - old_format_len);
4692 memcpy (fixbuf+fixuplen + 32 - old_format_len,
4693 indata, old_format_len);
4697 memcpy (fixbuf+fixuplen, indata, indatalen);
4700 indatalen = fixuplen + indatalen;
4705 return gpg_error (GPG_ERR_INV_VALUE);
4707 if (app->app_local->cardcap.ext_lc_le
4709 || (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA
4710 && app->app_local->keyattr[1].rsa.n_bits > RSA_SMALL_SIZE_OP)))
4712 exmode = 1; /* Extended length w/o a limit. */
4713 le_value = app->app_local->keyattr[1].rsa.n_bits / 8;
4715 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
4717 exmode = -254; /* Command chaining with max. 254 bytes. */
4721 exmode = le_value = 0;
4723 rc = iso7816_decipher (app->slot, exmode,
4724 indata, indatalen, le_value, padind,
4725 outdata, outdatalen);
4727 if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
4729 unsigned char prefix = 0;
4731 if (app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK)
4733 else if ((*outdatalen % 2) == 0) /* No 0x04 -> x-coordinate only */
4737 { /* Add the prefix */
4738 fixbuf = xtrymalloc (*outdatalen + 1);
4742 return gpg_error_from_syserror ();
4745 memcpy (fixbuf+1, *outdata, *outdatalen);
4748 *outdatalen = *outdatalen + 1;
4752 if (gpg_err_code (rc) == GPG_ERR_CARD /* actual SW is 0x640a */
4753 && app->app_local->manufacturer == 5
4754 && app->card_version == 0x0200)
4755 log_info ("NOTE: Cards with manufacturer id 5 and s/n <= 346 (0x15a)"
4756 " do not work with encryption keys > 2048 bits\n");
4758 *r_info |= APP_DECIPHER_INFO_NOPAD;
4764 /* Perform a simple verify operation for CHV1 and CHV2, so that
4765 further operations won't ask for CHV2 and it is possible to do a
4766 cheap check on the PIN: If there is something wrong with the PIN
4767 entry system, only the regular CHV will get blocked and not the
4768 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
4769 optional fingerprint part will be ignored.
4771 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
4772 the "[CHV3]" being a literal string: The Admin Pin is checked if
4773 and only if the retry counter is still at 3. */
4775 do_check_pin (app_t app, const char *keyidstr,
4776 gpg_error_t (*pincb)(void*, const char *, char **),
4779 unsigned char tmp_sn[20];
4784 if (!keyidstr || !*keyidstr)
4785 return gpg_error (GPG_ERR_INV_VALUE);
4787 /* Check whether an OpenPGP card of any version has been requested. */
4788 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
4789 return gpg_error (GPG_ERR_INV_ID);
4791 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
4794 return gpg_error (GPG_ERR_INV_ID);
4796 ; /* No fingerprint given: we allow this for now. */
4798 ; /* We ignore a fingerprint. */
4799 else if (!strcmp (s, "[CHV3]") )
4802 return gpg_error (GPG_ERR_INV_ID);
4804 for (s=keyidstr, n=0; n < 16; s += 2, n++)
4805 tmp_sn[n] = xtoi_2 (s);
4807 if (app->serialnolen != 16)
4808 return gpg_error (GPG_ERR_INV_CARD);
4809 if (memcmp (app->serialno, tmp_sn, 16))
4810 return gpg_error (GPG_ERR_WRONG_CARD);
4812 /* Yes, there is a race conditions: The user might pull the card
4813 right here and we won't notice that. However this is not a
4814 problem and the check above is merely for a graceful failure
4815 between operations. */
4820 unsigned char *value;
4824 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
4825 if (!relptr || valuelen < 7)
4827 log_error (_("error retrieving CHV status from card\n"));
4829 return gpg_error (GPG_ERR_CARD);
4836 log_info (_("card is permanently locked!\n"));
4837 return gpg_error (GPG_ERR_BAD_PIN);
4841 log_info (_("verification of Admin PIN is currently prohibited "
4842 "through this command\n"));
4843 return gpg_error (GPG_ERR_GENERAL);
4846 app->did_chv3 = 0; /* Force verification. */
4847 return verify_chv3 (app, pincb, pincb_arg);
4850 return verify_chv2 (app, pincb, pincb_arg);
4854 /* Show information about card capabilities. */
4856 show_caps (struct app_local_s *s)
4858 log_info ("Version-2+ .....: %s\n", s->extcap.is_v2? "yes":"no");
4859 log_info ("Extcap-v3 ......: %s\n", s->extcap.extcap_v3? "yes":"no");
4860 log_info ("Button .........: %s\n", s->extcap.has_button? "yes":"no");
4862 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
4863 if (s->extcap.sm_supported)
4864 log_printf (" (%s)", s->extcap.sm_algo==2? "3DES":
4865 (s->extcap.sm_algo==2? "AES-128" : "AES-256"));
4866 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
4867 if (s->extcap.get_challenge)
4868 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
4869 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
4870 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
4871 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
4872 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
4873 log_info ("Symmetric Crypto: %s\n", s->extcap.has_decrypt? "yes":"no");
4874 log_info ("KDF-Support ....: %s\n", s->extcap.kdf_do? "yes":"no");
4875 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
4876 if (s->extcap.extcap_v3)
4878 log_info ("PIN-Block-2 ....: %s\n", s->extcap.pin_blk2? "yes":"no");
4879 log_info ("MSE-Support ....: %s\n", s->extcap.mse? "yes":"no");
4880 log_info ("Max-Special-DOs : %u\n", s->extcap.max_special_do);
4882 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
4883 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
4884 log_info ("Status-Indicator: %02X\n", s->status_indicator);
4886 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
4887 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
4891 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
4894 parse_historical (struct app_local_s *apploc,
4895 const unsigned char * buffer, size_t buflen)
4897 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
4900 log_error ("warning: historical bytes are too short\n");
4901 return; /* Too short. */
4905 log_error ("warning: bad category indicator in historical bytes\n");
4909 /* Skip category indicator. */
4913 /* Get the status indicator. */
4914 apploc->status_indicator = buffer[buflen-3];
4917 /* Parse the compact TLV. */
4920 unsigned int tag = (*buffer & 0xf0) >> 4;
4921 unsigned int len = (*buffer & 0x0f);
4924 log_error ("warning: bad Compact-TLV in historical bytes\n");
4925 return; /* Error. */
4929 if (tag == 7 && len == 3)
4931 /* Card capabilities. */
4932 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
4933 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
4942 * Check if the OID in an DER encoding is available by GnuPG/libgcrypt,
4943 * and return the curve name. Return NULL if not available.
4944 * The constant string is not allocated dynamically, never free it.
4947 ecc_curve (unsigned char *buf, size_t buflen)
4952 unsigned char *oidbuf;
4954 oidbuf = xtrymalloc (buflen + 1);
4958 memcpy (oidbuf+1, buf, buflen);
4960 oid = gcry_mpi_set_opaque (NULL, oidbuf, (buflen+1) * 8);
4967 oidstr = openpgp_oid_to_str (oid);
4968 gcry_mpi_release (oid);
4972 result = openpgp_oid_to_curve (oidstr, 1);
4978 /* Parse and optionally show the algorithm attributes for KEYNO.
4979 KEYNO must be in the range 0..2. */
4981 parse_algorithm_attribute (app_t app, int keyno)
4983 unsigned char *buffer;
4986 const char desc[3][5] = {"sign", "encr", "auth"};
4988 assert (keyno >=0 && keyno <= 2);
4990 app->app_local->keyattr[keyno].key_type = KEY_TYPE_RSA;
4991 app->app_local->keyattr[keyno].rsa.n_bits = 0;
4993 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
4996 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
5001 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
5007 log_info ("Key-Attr-%s ..: ", desc[keyno]);
5008 if (*buffer == PUBKEY_ALGO_RSA && (buflen == 5 || buflen == 6))
5010 app->app_local->keyattr[keyno].rsa.n_bits = (buffer[1]<<8 | buffer[2]);
5011 app->app_local->keyattr[keyno].rsa.e_bits = (buffer[3]<<8 | buffer[4]);
5012 app->app_local->keyattr[keyno].rsa.format = 0;
5014 app->app_local->keyattr[keyno].rsa.format = RSA_STD;
5016 app->app_local->keyattr[keyno].rsa.format = (buffer[5] == 0? RSA_STD :
5017 buffer[5] == 1? RSA_STD_N :
5018 buffer[5] == 2? RSA_CRT :
5019 buffer[5] == 3? RSA_CRT_N :
5024 ("RSA, n=%u, e=%u, fmt=%s\n",
5025 app->app_local->keyattr[keyno].rsa.n_bits,
5026 app->app_local->keyattr[keyno].rsa.e_bits,
5027 app->app_local->keyattr[keyno].rsa.format == RSA_STD? "std" :
5028 app->app_local->keyattr[keyno].rsa.format == RSA_STD_N?"std+n":
5029 app->app_local->keyattr[keyno].rsa.format == RSA_CRT? "crt" :
5030 app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N?"crt+n":"?");
5032 else if (*buffer == PUBKEY_ALGO_ECDH || *buffer == PUBKEY_ALGO_ECDSA
5033 || *buffer == PUBKEY_ALGO_EDDSA)
5036 int oidlen = buflen - 1;
5038 app->app_local->keyattr[keyno].ecc.flags = 0;
5040 if (buffer[buflen-1] == 0x00 || buffer[buflen-1] == 0xff)
5041 { /* Found "pubkey required"-byte for private key template. */
5043 if (buffer[buflen-1] == 0xff)
5044 app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_PUBKEY;
5047 curve = ecc_curve (buffer + 1, oidlen);
5050 log_printhex ("Curve with OID not supported: ", buffer+1, buflen-1);
5053 app->app_local->keyattr[keyno].key_type = KEY_TYPE_ECC;
5054 app->app_local->keyattr[keyno].ecc.curve = curve;
5055 if (*buffer == PUBKEY_ALGO_EDDSA
5056 || (*buffer == PUBKEY_ALGO_ECDH
5057 && !strcmp (app->app_local->keyattr[keyno].ecc.curve,
5059 app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_DJB_TWEAK;
5062 ("ECC, curve=%s%s\n", app->app_local->keyattr[keyno].ecc.curve,
5063 !(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)?
5064 "": keyno==1? " (djb-tweak)": " (eddsa)");
5067 else if (opt.verbose)
5068 log_printhex ("", buffer, buflen);
5073 /* Select the OpenPGP application on the card in SLOT. This function
5074 must be used before any other OpenPGP application functions. */
5076 app_select_openpgp (app_t app)
5078 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
5079 int slot = app->slot;
5081 unsigned char *buffer;
5085 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
5086 special flag value. */
5087 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
5090 unsigned int manufacturer;
5092 app->apptype = "OPENPGP";
5097 app->app_local = NULL;
5099 /* The OpenPGP card returns the serial number as part of the
5100 AID; because we prefer to use OpenPGP serial numbers, we
5101 replace a possibly already set one from a EF.GDO with this
5102 one. Note, that for current OpenPGP cards, no EF.GDO exists
5103 and thus it won't matter at all. */
5104 rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
5110 log_printhex ("", buffer, buflen);
5113 app->card_version = buffer[6] << 8;
5114 app->card_version |= buffer[7];
5115 manufacturer = (buffer[8]<<8 | buffer[9]);
5117 xfree (app->serialno);
5118 app->serialno = buffer;
5119 app->serialnolen = buflen;
5121 app->app_local = xtrycalloc (1, sizeof *app->app_local);
5122 if (!app->app_local)
5124 rc = gpg_error (gpg_err_code_from_errno (errno));
5128 app->app_local->manufacturer = manufacturer;
5130 if (app->card_version >= 0x0200)
5131 app->app_local->extcap.is_v2 = 1;
5133 if (app->card_version >= 0x0300)
5134 app->app_local->extcap.extcap_v3 = 1;
5136 /* Read the historical bytes. */
5137 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
5142 log_info ("Historical Bytes: ");
5143 log_printhex ("", buffer, buflen);
5145 parse_historical (app->app_local, buffer, buflen);
5149 /* Read the force-chv1 flag. */
5150 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
5153 log_error (_("can't access %s - invalid OpenPGP card?\n"),
5154 "CHV Status Bytes");
5157 app->force_chv1 = (buflen && *buffer == 0);
5160 /* Read the extended capabilities. */
5161 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
5164 log_error (_("can't access %s - invalid OpenPGP card?\n"),
5165 "Extended Capability Flags" );
5170 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
5171 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
5172 app->app_local->extcap.key_import = !!(*buffer & 0x20);
5173 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
5174 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
5175 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
5176 app->app_local->extcap.has_decrypt = !!(*buffer & 0x02);
5177 app->app_local->extcap.kdf_do = !!(*buffer & 0x01);
5181 /* Available with cards of v2 or later. */
5182 app->app_local->extcap.sm_algo = buffer[1];
5183 app->app_local->extcap.max_get_challenge
5184 = (buffer[2] << 8 | buffer[3]);
5185 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
5187 /* Interpretation is different between v2 and v3, unfortunately. */
5188 if (app->app_local->extcap.extcap_v3)
5190 app->app_local->extcap.max_special_do
5191 = (buffer[6] << 8 | buffer[7]);
5192 app->app_local->extcap.pin_blk2 = !!(buffer[8] & 0x01);
5193 app->app_local->extcap.mse= !!(buffer[9] & 0x01);
5198 /* Some of the first cards accidentally don't set the
5199 CHANGE_FORCE_CHV bit but allow it anyway. */
5200 if (app->card_version <= 0x0100 && manufacturer == 1)
5201 app->app_local->extcap.change_force_chv = 1;
5203 /* Check optional DO of "General Feature Management" for button. */
5204 relptr = get_one_do (app, 0x7f74, &buffer, &buflen, NULL);
5206 /* It must be: 03 81 01 20 */
5207 app->app_local->extcap.has_button = 1;
5209 parse_login_data (app);
5212 show_caps (app->app_local);
5214 parse_algorithm_attribute (app, 0);
5215 parse_algorithm_attribute (app, 1);
5216 parse_algorithm_attribute (app, 2);
5218 if (opt.verbose > 1)
5221 app->fnc.deinit = do_deinit;
5222 app->fnc.learn_status = do_learn_status;
5223 app->fnc.readcert = do_readcert;
5224 app->fnc.readkey = do_readkey;
5225 app->fnc.getattr = do_getattr;
5226 app->fnc.setattr = do_setattr;
5227 app->fnc.writecert = do_writecert;
5228 app->fnc.writekey = do_writekey;
5229 app->fnc.genkey = do_genkey;
5230 app->fnc.sign = do_sign;
5231 app->fnc.auth = do_auth;
5232 app->fnc.decipher = do_decipher;
5233 app->fnc.change_pin = do_change_pin;
5234 app->fnc.check_pin = do_check_pin;