1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3 * 2009, 2013 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
23 CHV means Card Holder Verification and is nothing else than a PIN
24 or password. That term seems to have been used originally with GSM
25 cards. Version v2 of the specs changes the term to the clearer
26 term PW for password. We use the terms here interchangeable
27 because we do not want to change existing strings i18n wise.
29 Version 2 of the specs also drops the separate PW2 which was
30 required in v1 due to ISO requirements. It is now possible to have
31 one physical PW but two reference to it so that they can be
32 individually be verified (e.g. to implement a forced verification
33 for one key). Thus you will noticed the use of PW2 with the verify
34 command but not with change_reference_data because the latter
35 operates directly on the physical PW.
37 The Reset Code (RC) as implemented by v2 cards uses the same error
38 counter as the PW2 of v1 cards. By default no RC is set and thus
39 that error counter is set to 0. After setting the RC the error
40 counter will be initialized to 3.
52 #if GNUPG_MAJOR_VERSION == 1
53 /* This is used with GnuPG version < 1.9. The code has been source
54 copied from the current GnuPG >= 1.9 and is maintained over
61 #else /* GNUPG_MAJOR_VERSION != 1 */
63 #endif /* GNUPG_MAJOR_VERSION != 1 */
67 #include "app-common.h"
73 /* A table describing the DOs of the card. */
77 int get_from; /* Constructed DO with this DO or 0 for direct access. */
81 int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
82 this data object if it is used in 1.1
83 and later versions of the card. This
84 does not work with composite DO and
85 is currently only useful for the CHV
87 int try_extlen:1; /* Large object; try to use an extended
91 { 0x005E, 0, 0, 1, 0, 0, 0, 0, "Login Data" },
92 { 0x5F50, 0, 0, 0, 0, 0, 0, 0, "URL" },
93 { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
94 { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
95 { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
96 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
97 { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
98 { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
99 { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
100 { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
101 { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
102 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
103 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
104 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
105 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
106 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
107 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
108 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
109 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
110 { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
111 { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
112 { 0x0101, 0, 0, 0, 0, 0, 0, 0, "Private DO 1"},
113 { 0x0102, 0, 0, 0, 0, 0, 0, 0, "Private DO 2"},
114 { 0x0103, 0, 0, 0, 0, 0, 0, 0, "Private DO 3"},
115 { 0x0104, 0, 0, 0, 0, 0, 0, 0, "Private DO 4"},
116 { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
121 /* The format of RSA private keys. */
133 /* One cache item for DOs. */
135 struct cache_s *next;
138 unsigned char data[1];
142 /* Object with application (i.e. OpenPGP card) specific data. */
144 /* A linked list with cached DOs. */
145 struct cache_s *cache;
147 /* Keep track of the public keys. */
150 int read_done; /* True if we have at least tried to read them. */
151 unsigned char *key; /* This is a malloced buffer with a canonical
152 encoded S-expression encoding a public
153 key. Might be NULL if key is not
155 size_t keylen; /* The length of the above S-expression. This
156 is usually only required for cross checks
157 because the length of an S-expression is
158 implicitly available. */
161 unsigned char status_indicator; /* The card status indicator. */
163 unsigned int manufacturer:16; /* Manufacturer ID from the s/n. */
165 /* Keep track of the ISO card capabilities. */
168 unsigned int cmd_chaining:1; /* Command chaining is supported. */
169 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
172 /* Keep track of extended card capabilities. */
175 unsigned int is_v2:1; /* This is a v2.0 compatible card. */
176 unsigned int get_challenge:1;
177 unsigned int key_import:1;
178 unsigned int change_force_chv:1;
179 unsigned int private_dos:1;
180 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
181 unsigned int sm_supported:1; /* Secure Messaging is supported. */
182 unsigned int sm_aes128:1; /* Use AES-128 for SM. */
183 unsigned int max_certlen_3:16;
184 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
187 /* Flags used to control the application. */
190 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
191 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
194 /* Pinpad request specified on card. */
197 unsigned int specified:1;
204 unsigned int n_bits; /* Size of the modulus in bits. The rest
205 of this strucuire is only valid if
207 unsigned int e_bits; /* Size of the public exponent in bits. */
208 rsa_key_format_t format;
215 /***** Local prototypes *****/
216 static unsigned long convert_sig_counter_value (const unsigned char *value,
218 static unsigned long get_sig_counter (app_t app);
219 static gpg_error_t do_auth (app_t app, const char *keyidstr,
220 gpg_error_t (*pincb)(void*, const char *, char **),
222 const void *indata, size_t indatalen,
223 unsigned char **outdata, size_t *outdatalen);
224 static void parse_algorithm_attribute (app_t app, int keyno);
225 static gpg_error_t change_keyattr_from_string
227 gpg_error_t (*pincb)(void*, const char *, char **),
229 const void *value, size_t valuelen);
237 do_deinit (app_t app)
239 if (app && app->app_local)
241 struct cache_s *c, *c2;
244 for (c = app->app_local->cache; c; c = c2)
250 for (i=0; i < DIM (app->app_local->pk); i++)
252 xfree (app->app_local->pk[i].key);
253 app->app_local->pk[i].read_done = 0;
255 xfree (app->app_local);
256 app->app_local = NULL;
261 /* Wrapper around iso7816_get_data which first tries to get the data
262 from the cache. With GET_IMMEDIATE passed as true, the cache is
263 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
264 supported by the card. */
266 get_cached_data (app_t app, int tag,
267 unsigned char **result, size_t *resultlen,
268 int get_immediate, int try_extlen)
282 for (c=app->app_local->cache; c; c = c->next)
287 p = xtrymalloc (c->length);
289 return gpg_error (gpg_err_code_from_errno (errno));
290 memcpy (p, c->data, c->length);
294 *resultlen = c->length;
300 if (try_extlen && app->app_local->cardcap.ext_lc_le)
301 exmode = app->app_local->extcap.max_certlen_3;
305 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
311 /* Check whether we should cache this object. */
315 for (i=0; data_objects[i].tag; i++)
316 if (data_objects[i].tag == tag)
318 if (data_objects[i].dont_cache)
323 /* Okay, cache it. */
324 for (c=app->app_local->cache; c; c = c->next)
325 assert (c->tag != tag);
327 c = xtrymalloc (sizeof *c + len);
330 memcpy (c->data, p, len);
333 c->next = app->app_local->cache;
334 app->app_local->cache = c;
340 /* Remove DO at TAG from the cache. */
342 flush_cache_item (app_t app, int tag)
344 struct cache_s *c, *cprev;
350 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
354 cprev->next = c->next;
356 app->app_local->cache = c->next;
359 for (c=app->app_local->cache; c ; c = c->next)
361 assert (c->tag != tag); /* Oops: duplicated entry. */
366 /* Try again if we have an outer tag. */
367 for (i=0; data_objects[i].tag; i++)
368 if (data_objects[i].tag == tag && data_objects[i].get_from
369 && data_objects[i].get_from != tag)
370 flush_cache_item (app, data_objects[i].get_from);
373 /* Flush all entries from the cache which might be out of sync after
376 flush_cache_after_error (app_t app)
380 for (i=0; data_objects[i].tag; i++)
381 if (data_objects[i].flush_on_error)
382 flush_cache_item (app, data_objects[i].tag);
386 /* Flush the entire cache. */
388 flush_cache (app_t app)
390 if (app && app->app_local)
392 struct cache_s *c, *c2;
394 for (c = app->app_local->cache; c; c = c2)
399 app->app_local->cache = NULL;
404 /* Get the DO identified by TAG from the card in SLOT and return a
405 buffer with its content in RESULT and NBYTES. The return value is
406 NULL if not found or a pointer which must be used to release the
407 buffer holding value. */
409 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
413 unsigned char *buffer;
415 unsigned char *value;
426 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
429 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
432 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
445 if (data_objects[i].tag && data_objects[i].get_from)
447 rc = get_cached_data (app, data_objects[i].get_from,
449 (data_objects[i].dont_cache
450 || data_objects[i].get_immediate_in_v11),
451 data_objects[i].try_extlen);
454 const unsigned char *s;
456 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
458 value = NULL; /* not found */
459 else if (valuelen > buflen - (s - buffer))
461 log_error ("warning: constructed DO too short\n");
463 xfree (buffer); buffer = NULL;
466 value = buffer + (s - buffer);
470 if (!value) /* Not in a constructed DO, try simple. */
472 rc = get_cached_data (app, tag, &buffer, &buflen,
473 (data_objects[i].dont_cache
474 || data_objects[i].get_immediate_in_v11),
475 data_objects[i].try_extlen);
495 dump_all_do (int slot)
498 unsigned char *buffer;
501 for (i=0; data_objects[i].tag; i++)
503 if (data_objects[i].get_from)
506 /* We don't try extended length APDU because such large DO would
507 be pretty useless in a log file. */
508 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
509 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
512 log_info ("DO `%s' not available: %s\n",
513 data_objects[i].desc, gpg_strerror (rc));
516 if (data_objects[i].binary)
518 log_info ("DO `%s': ", data_objects[i].desc);
519 log_printhex ("", buffer, buflen);
522 log_info ("DO `%s': `%.*s'\n",
523 data_objects[i].desc,
524 (int)buflen, buffer); /* FIXME: sanitize */
526 if (data_objects[i].constructed)
528 for (j=0; data_objects[j].tag; j++)
530 const unsigned char *value;
533 if (j==i || data_objects[i].tag != data_objects[j].get_from)
535 value = find_tlv_unchecked (buffer, buflen,
536 data_objects[j].tag, &valuelen);
539 else if (valuelen > buflen - (value - buffer))
540 log_error ("warning: constructed DO too short\n");
543 if (data_objects[j].binary)
545 log_info ("DO `%s': ", data_objects[j].desc);
547 log_info ("[%u]\n", (unsigned int)valuelen);
549 log_printhex ("", value, valuelen);
552 log_info ("DO `%s': `%.*s'\n",
553 data_objects[j].desc,
554 (int)valuelen, value); /* FIXME: sanitize */
559 xfree (buffer); buffer = NULL;
564 /* Count the number of bits, assuming the A represents an unsigned big
565 integer of length LEN bytes. */
567 count_bits (const unsigned char *a, size_t len)
569 unsigned int n = len * 8;
572 for (; len && !*a; len--, a++, n -=8)
576 for (i=7; i && !(*a & (1<<i)); i--)
582 /* GnuPG makes special use of the login-data DO, this function parses
583 the login data to store the flags for later use. It may be called
584 at any time and should be called after changing the login-data DO.
586 Everything up to a LF is considered a mailbox or account name. If
587 the first LF is followed by DC4 (0x14) control sequence are
588 expected up to the next LF. Control sequences are separated by FS
589 (0x18) and consist of key=value pairs. There are two keys defined:
593 Where FLAGS is a plain hexadecimal number representing flag values.
594 The lsb is here the rightmost bit. Defined flags bits are:
596 Bit 0 = CHV1 and CHV2 are not syncronized
597 Bit 1 = CHV2 has been been set to the default PIN of "123456"
598 (this implies that bit 0 is also set).
602 Where PINPAD_REQUEST is in the format of: <n> or <n>,<m>.
603 N for user PIN, M for admin PIN. If M is missing it means M=N.
604 0 means to force not to use pinpad.
608 parse_login_data (app_t app)
610 unsigned char *buffer, *p;
615 app->app_local->flags.no_sync = 0;
616 app->app_local->flags.def_chv2 = 0;
617 app->app_local->pinpad.specified = 0;
618 app->app_local->pinpad.fixedlen_user = -1;
619 app->app_local->pinpad.fixedlen_admin = -1;
622 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
625 for (; buflen; buflen--, buffer++)
628 if (buflen < 2 || buffer[1] != '\x14')
631 return; /* No control sequences. */
640 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
642 /* Flags control sequence found. */
645 /* For now we are only interested in the last digit, so skip
646 any leading digits but bail out on invalid characters. */
647 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
648 lastdig = xtoi_1 (p);
651 if (len && !(*p == '\n' || *p == '\x18'))
652 goto next; /* Invalid characters in field. */
653 app->app_local->flags.no_sync = !!(lastdig & 1);
654 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
656 else if (buflen > 1 && *buffer == 'P' && buffer[1] == '=')
658 /* Pinpad request control sequence found. */
669 n = strtol (buffer, &q, 10);
670 if (q >= (char *)buffer + buflen
671 || *q == '\x18' || *q == '\n')
675 if (*q++ != ',' || !digitp (q))
677 m = strtol (q, &q, 10);
680 if (buflen < ((unsigned char *)q - buffer))
683 buflen -= ((unsigned char *)q - buffer);
686 if (buflen && !(*buffer == '\n' || *buffer == '\x18'))
688 app->app_local->pinpad.specified = 1;
689 app->app_local->pinpad.fixedlen_user = n;
690 app->app_local->pinpad.fixedlen_admin = m;
695 /* Skip to FS (0x18) or LF (\n). */
696 for (; buflen && *buffer != '\x18' && *buffer != '\n'; buflen--)
699 while (buflen && *buffer != '\n');
704 /* Note, that FPR must be at least 20 bytes. */
706 store_fpr (app_t app, int keynumber, u32 timestamp,
707 const unsigned char *m, size_t mlen,
708 const unsigned char *e, size_t elen,
709 unsigned char *fpr, unsigned int card_version)
711 unsigned int n, nbits;
712 unsigned char *buffer, *p;
716 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
718 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
721 n = 6 + 2 + mlen + 2 + elen;
722 p = buffer = xtrymalloc (3 + n);
724 return gpg_error_from_syserror ();
726 *p++ = 0x99; /* ctb */
727 *p++ = n >> 8; /* 2 byte length header */
729 *p++ = 4; /* key packet version */
730 *p++ = timestamp >> 24;
731 *p++ = timestamp >> 16;
732 *p++ = timestamp >> 8;
735 nbits = count_bits (m, mlen);
738 memcpy (p, m, mlen); p += mlen;
739 nbits = count_bits (e, elen);
742 memcpy (p, e, elen); p += elen;
744 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
748 tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
749 flush_cache_item (app, 0xC5);
750 tag2 = 0xCE + keynumber;
751 flush_cache_item (app, 0xCD);
753 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
755 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
757 if (!rc && card_version > 0x0100)
759 unsigned char buf[4];
761 buf[0] = timestamp >> 24;
762 buf[1] = timestamp >> 16;
763 buf[2] = timestamp >> 8;
766 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
768 log_error (_("failed to store the creation date: %s\n"),
777 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
778 int number, const unsigned char *fpr)
784 for (i=0; i < 20 && !fpr[i]; i++)
787 return; /* All zero. */
788 bin2hex (fpr, 20, buf);
790 *numbuf = 0; /* Don't print the key number */
792 sprintf (numbuf, "%d", number);
793 send_status_info (ctrl, keyword,
794 numbuf, (size_t)strlen(numbuf),
795 buf, (size_t)strlen (buf), NULL, 0);
799 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
800 int number, const unsigned char *stamp)
802 char numbuf1[50], numbuf2[50];
805 value = buf32_to_ulong (stamp);
808 sprintf (numbuf1, "%d", number);
809 sprintf (numbuf2, "%lu", value);
810 send_status_info (ctrl, keyword,
811 numbuf1, (size_t)strlen(numbuf1),
812 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
816 send_key_data (ctrl_t ctrl, const char *name,
817 const unsigned char *a, size_t alen)
822 buffer = buf = bin2hex (a, alen, NULL);
825 log_error ("memory allocation error in send_key_data\n");
828 buflen = strlen (buffer);
830 /* 768 is the hexified size for the modulus of an 3072 bit key. We
831 use extra chunks to transmit larger data (i.e for 4096 bit). */
832 for ( ;buflen > 768; buflen -= 768, buf += 768)
833 send_status_info (ctrl, "KEY-DATA",
837 send_status_info (ctrl, "KEY-DATA",
838 name, (size_t)strlen(name),
846 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
850 assert (number >=0 && number < DIM(app->app_local->keyattr));
852 /* We only support RSA thus the algo identifier is fixed to 1. */
853 /* Note that PUBKEY_ALGO_RSA == 1 */
854 snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
856 app->app_local->keyattr[number].n_bits,
857 app->app_local->keyattr[number].e_bits,
858 app->app_local->keyattr[number].format);
859 send_status_direct (ctrl, keyword, buffer);
863 #define RSA_SMALL_SIZE_KEY 1952
864 #define RSA_SMALL_SIZE_OP 2048
867 determine_rsa_response (app_t app, int keyno)
871 size = 2 + 3 /* header */
872 + 4 /* tag+len */ + app->app_local->keyattr[keyno].n_bits/8
873 + 2 /* tag+len */ + app->app_local->keyattr[keyno].e_bits/8;
879 /* Implement the GETATTR command. This is similar to the LEARN
880 command but returns just one value via the status interface. */
882 do_getattr (app_t app, ctrl_t ctrl, const char *name)
889 { "DISP-NAME", 0x005B },
890 { "LOGIN-DATA", 0x005E },
891 { "DISP-LANG", 0x5F2D },
892 { "DISP-SEX", 0x5F35 },
893 { "PUBKEY-URL", 0x5F50 },
894 { "KEY-FPR", 0x00C5, 3 },
895 { "KEY-TIME", 0x00CD, 4 },
896 { "KEY-ATTR", 0x0000, -5 },
897 { "CA-FPR", 0x00C6, 3 },
898 { "CHV-STATUS", 0x00C4, 1 },
899 { "SIG-COUNTER", 0x0093, 2 },
900 { "SERIALNO", 0x004F, -1 },
902 { "EXTCAP", 0x0000, -2 },
903 { "PRIVATE-DO-1", 0x0101 },
904 { "PRIVATE-DO-2", 0x0102 },
905 { "PRIVATE-DO-3", 0x0103 },
906 { "PRIVATE-DO-4", 0x0104 },
907 { "$AUTHKEYID", 0x0000, -3 },
908 { "$DISPSERIALNO",0x0000, -4 },
913 unsigned char *value;
916 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
918 if (!table[idx].name)
919 return gpg_error (GPG_ERR_INV_NAME);
921 if (table[idx].special == -1)
923 /* The serial number is very special. We could have used the
924 AID DO to retrieve it, but we have it already in the app
925 context and the stamp argument is required anyway which we
926 can't by other means. The AID DO is available anyway but not
932 if (!app_get_serial_and_stamp (app, &serial, &stamp))
934 sprintf (tmp, "%lu", (unsigned long)stamp);
935 send_status_info (ctrl, "SERIALNO",
936 serial, strlen (serial),
943 if (table[idx].special == -2)
947 snprintf (tmp, sizeof tmp,
948 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
949 app->app_local->extcap.get_challenge,
950 app->app_local->extcap.key_import,
951 app->app_local->extcap.change_force_chv,
952 app->app_local->extcap.private_dos,
953 app->app_local->extcap.max_certlen_3,
954 app->app_local->extcap.algo_attr_change,
955 (app->app_local->extcap.sm_supported
956 ? (app->app_local->extcap.sm_aes128? CIPHER_ALGO_AES : CIPHER_ALGO_3DES)
958 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
961 if (table[idx].special == -3)
963 char const tmp[] = "OPENPGP.3";
964 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
967 if (table[idx].special == -4)
972 if (!app_get_serial_and_stamp (app, &serial, &stamp))
974 if (strlen (serial) > 16+12)
976 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
982 return gpg_error (GPG_ERR_INV_NAME);
984 if (table[idx].special == -5)
986 for (i=0; i < 3; i++)
987 send_key_attr (ctrl, app, table[idx].name, i);
991 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
994 if (table[idx].special == 1)
998 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
999 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
1000 send_status_info (ctrl, table[idx].name,
1001 numbuf, strlen (numbuf), NULL, 0);
1003 else if (table[idx].special == 2)
1007 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
1008 send_status_info (ctrl, table[idx].name,
1009 numbuf, strlen (numbuf), NULL, 0);
1011 else if (table[idx].special == 3)
1014 for (i=0; i < 3; i++)
1015 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
1017 else if (table[idx].special == 4)
1020 for (i=0; i < 3; i++)
1021 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
1024 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
1031 /* Retrieve the fingerprint from the card inserted in SLOT and write
1032 the according hex representation to FPR. Caller must have provide
1033 a buffer at FPR of least 41 bytes. Returns 0 on success or an
1035 #if GNUPG_MAJOR_VERSION > 1
1037 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
1039 gpg_error_t err = 0;
1041 unsigned char *value;
1044 assert (keyno >=0 && keyno <= 2);
1046 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
1047 if (relptr && valuelen >= 60)
1048 bin2hex (value+keyno*20, 20, fpr);
1050 err = gpg_error (GPG_ERR_NOT_FOUND);
1054 #endif /*GNUPG_MAJOR_VERSION > 1*/
1057 /* Retrieve the public key material for the RSA key, whose fingerprint
1058 is FPR, from gpg output, which can be read through the stream FP.
1059 The RSA modulus will be stored at the address of M and MLEN, the
1060 public exponent at E and ELEN. Returns zero on success, an error
1061 code on failure. Caller must release the allocated buffers at M
1062 and E if the function returns success. */
1063 #if GNUPG_MAJOR_VERSION > 1
1065 retrieve_key_material (FILE *fp, const char *hexkeyid,
1066 const unsigned char **m, size_t *mlen,
1067 const unsigned char **e, size_t *elen)
1069 gcry_error_t err = 0;
1070 char *line = NULL; /* read_line() buffer. */
1071 size_t line_size = 0; /* Helper for for read_line. */
1072 int found_key = 0; /* Helper to find a matching key. */
1073 unsigned char *m_new = NULL;
1074 unsigned char *e_new = NULL;
1078 /* Loop over all records until we have found the subkey
1079 corresponding to the fingerprint. Inm general the first record
1080 should be the pub record, but we don't rely on that. Given that
1081 we only need to look at one key, it is sufficient to compare the
1082 keyid so that we don't need to look at "fpr" records. */
1093 i = read_line (fp, &line, &line_size, &max_length);
1098 err = gpg_error_from_syserror ();
1099 goto leave; /* Error. */
1103 err = gpg_error (GPG_ERR_TRUNCATED);
1104 goto leave; /* Line truncated - we better stop processing. */
1107 /* Parse the line into fields. */
1108 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1110 fields[nfields] = p;
1111 p = strchr (p, ':');
1116 continue; /* No fields at all - skip line. */
1120 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1121 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1126 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1127 break; /* Next key - stop. */
1129 if ( strcmp (fields[0], "pkd") )
1130 continue; /* Not a key data record. */
1131 i = 0; /* Avoid erroneous compiler warning. */
1132 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1133 || (!i && m_new) || (i && e_new))
1135 err = gpg_error (GPG_ERR_GENERAL);
1136 goto leave; /* Error: Invalid key data record or not an RSA key. */
1139 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1143 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1145 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1146 gcry_mpi_release (mpi);
1161 err = gpg_error (GPG_ERR_GENERAL);
1169 #endif /*GNUPG_MAJOR_VERSION > 1*/
1172 /* Get the public key for KEYNO and store it as an S-expresion with
1173 the APP handle. On error that field gets cleared. If we already
1174 know about the public key we will just return. Note that this does
1175 not mean a key is available; this is soley indicated by the
1176 presence of the app->app_local->pk[KEYNO].key field.
1178 Note that GnuPG 1.x does not need this and it would be too time
1179 consuming to send it just for the fun of it. However, given that we
1180 use the same code in gpg 1.4, we can't use the gcry S-expresion
1181 here but need to open encode it. */
1182 #if GNUPG_MAJOR_VERSION > 1
1184 get_public_key (app_t app, int keyno)
1186 gpg_error_t err = 0;
1187 unsigned char *buffer;
1188 const unsigned char *keydata, *m, *e;
1189 size_t buflen, keydatalen, mlen, elen;
1190 unsigned char *mbuf = NULL;
1191 unsigned char *ebuf = NULL;
1192 char *keybuf = NULL;
1195 if (keyno < 0 || keyno > 2)
1196 return gpg_error (GPG_ERR_INV_ID);
1198 /* Already cached? */
1199 if (app->app_local->pk[keyno].read_done)
1202 xfree (app->app_local->pk[keyno].key);
1203 app->app_local->pk[keyno].key = NULL;
1204 app->app_local->pk[keyno].keylen = 0;
1206 m = e = NULL; /* (avoid cc warning) */
1208 if (app->card_version > 0x0100)
1210 int exmode, le_value;
1212 /* We may simply read the public key out of these cards. */
1213 if (app->app_local->cardcap.ext_lc_le
1214 && app->app_local->keyattr[keyno].n_bits > RSA_SMALL_SIZE_KEY)
1216 exmode = 1; /* Use extended length. */
1217 le_value = determine_rsa_response (app, keyno);
1222 le_value = 256; /* Use legacy value. */
1225 err = iso7816_read_public_key (app->slot, exmode,
1226 (keyno == 0? "\xB6" :
1227 keyno == 1? "\xB8" : "\xA4"),
1228 2, le_value, &buffer, &buflen);
1231 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1235 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1238 err = gpg_error (GPG_ERR_CARD);
1239 log_error (_("response does not contain the public key data\n"));
1243 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1246 err = gpg_error (GPG_ERR_CARD);
1247 log_error (_("response does not contain the RSA modulus\n"));
1252 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1255 err = gpg_error (GPG_ERR_CARD);
1256 log_error (_("response does not contain the RSA public exponent\n"));
1260 /* Prepend numbers with a 0 if needed. */
1261 if (mlen && (*m & 0x80))
1263 mbuf = xtrymalloc ( mlen + 1);
1266 err = gpg_error_from_syserror ();
1270 memcpy (mbuf+1, m, mlen);
1274 if (elen && (*e & 0x80))
1276 ebuf = xtrymalloc ( elen + 1);
1279 err = gpg_error_from_syserror ();
1283 memcpy (ebuf+1, e, elen);
1291 /* Due to a design problem in v1.0 cards we can't get the public
1292 key out of these cards without doing a verify on CHV3.
1293 Clearly that is not an option and thus we try to locate the
1294 key using an external helper.
1296 The helper we use here is gpg itself, which should know about
1297 the key in any case. */
1301 char *command = NULL;
1305 buffer = NULL; /* We don't need buffer. */
1307 err = retrieve_fpr_from_card (app, keyno, fpr);
1310 log_error ("error while retrieving fpr from card: %s\n",
1311 gpg_strerror (err));
1314 hexkeyid = fpr + 24;
1316 ret = estream_asprintf (&command,
1317 "gpg --list-keys --with-colons --with-key-data '%s'",
1321 err = gpg_error_from_syserror ();
1325 fp = popen (command, "r");
1329 err = gpg_error_from_syserror ();
1330 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1334 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1338 log_error ("error while retrieving key material through pipe: %s\n",
1339 gpg_strerror (err));
1344 /* Allocate a buffer to construct the S-expression. */
1345 /* FIXME: We should provide a generalized S-expression creation
1347 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1350 err = gpg_error_from_syserror ();
1354 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1355 keybuf_p = keybuf + strlen (keybuf);
1356 memcpy (keybuf_p, m, mlen);
1358 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1359 keybuf_p += strlen (keybuf_p);
1360 memcpy (keybuf_p, e, elen);
1362 strcpy (keybuf_p, ")))");
1363 keybuf_p += strlen (keybuf_p);
1365 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1366 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1369 /* Set a flag to indicate that we tried to read the key. */
1370 app->app_local->pk[keyno].read_done = 1;
1377 #endif /* GNUPG_MAJOR_VERSION > 1 */
1381 /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3].
1382 This is used by the LEARN command. */
1384 send_keypair_info (app_t app, ctrl_t ctrl, int key)
1386 int keyno = key - 1;
1387 gpg_error_t err = 0;
1388 /* Note that GnuPG 1.x does not need this and it would be too time
1389 consuming to send it just for the fun of it. */
1390 #if GNUPG_MAJOR_VERSION > 1
1391 unsigned char grip[20];
1395 err = get_public_key (app, keyno);
1399 assert (keyno >= 0 && keyno <= 2);
1400 if (!app->app_local->pk[keyno].key)
1401 goto leave; /* No such key - ignore. */
1403 err = keygrip_from_canon_sexp (app->app_local->pk[keyno].key,
1404 app->app_local->pk[keyno].keylen,
1409 bin2hex (grip, 20, gripstr);
1411 sprintf (idbuf, "OPENPGP.%d", keyno+1);
1412 send_status_info (ctrl, "KEYPAIRINFO",
1414 idbuf, strlen (idbuf),
1418 #endif /* GNUPG_MAJOR_VERSION > 1 */
1424 /* Handle the LEARN command for OpenPGP. */
1426 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1430 do_getattr (app, ctrl, "EXTCAP");
1431 do_getattr (app, ctrl, "DISP-NAME");
1432 do_getattr (app, ctrl, "DISP-LANG");
1433 do_getattr (app, ctrl, "DISP-SEX");
1434 do_getattr (app, ctrl, "PUBKEY-URL");
1435 do_getattr (app, ctrl, "LOGIN-DATA");
1436 do_getattr (app, ctrl, "KEY-FPR");
1437 if (app->card_version > 0x0100)
1438 do_getattr (app, ctrl, "KEY-TIME");
1439 do_getattr (app, ctrl, "CA-FPR");
1440 do_getattr (app, ctrl, "CHV-STATUS");
1441 do_getattr (app, ctrl, "SIG-COUNTER");
1442 if (app->app_local->extcap.private_dos)
1444 do_getattr (app, ctrl, "PRIVATE-DO-1");
1445 do_getattr (app, ctrl, "PRIVATE-DO-2");
1447 do_getattr (app, ctrl, "PRIVATE-DO-3");
1449 do_getattr (app, ctrl, "PRIVATE-DO-4");
1451 send_keypair_info (app, ctrl, 1);
1452 send_keypair_info (app, ctrl, 2);
1453 send_keypair_info (app, ctrl, 3);
1454 /* Note: We do not send the Cardholder Certificate, because that is
1455 relativly long and for OpenPGP applications not really needed. */
1460 /* Handle the READKEY command for OpenPGP. On success a canonical
1461 encoded S-expression with the public key will get stored at PK and
1462 its length (for assertions) at PKLEN; the caller must release that
1463 buffer. On error PK and PKLEN are not changed and an error code is
1466 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1468 #if GNUPG_MAJOR_VERSION > 1
1473 if (!strcmp (keyid, "OPENPGP.1"))
1475 else if (!strcmp (keyid, "OPENPGP.2"))
1477 else if (!strcmp (keyid, "OPENPGP.3"))
1480 return gpg_error (GPG_ERR_INV_ID);
1482 err = get_public_key (app, keyno);
1486 buf = app->app_local->pk[keyno].key;
1488 return gpg_error (GPG_ERR_NO_PUBKEY);
1489 *pklen = app->app_local->pk[keyno].keylen;;
1490 *pk = xtrymalloc (*pklen);
1493 err = gpg_error_from_syserror ();
1497 memcpy (*pk, buf, *pklen);
1500 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1504 /* Read the standard certificate of an OpenPGP v2 card. It is
1505 returned in a freshly allocated buffer with that address stored at
1506 CERT and the length of the certificate stored at CERTLEN. CERTID
1507 needs to be set to "OPENPGP.3". */
1509 do_readcert (app_t app, const char *certid,
1510 unsigned char **cert, size_t *certlen)
1512 #if GNUPG_MAJOR_VERSION > 1
1514 unsigned char *buffer;
1520 if (strcmp (certid, "OPENPGP.3"))
1521 return gpg_error (GPG_ERR_INV_ID);
1522 if (!app->app_local->extcap.is_v2)
1523 return gpg_error (GPG_ERR_NOT_FOUND);
1525 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1527 return gpg_error (GPG_ERR_NOT_FOUND);
1530 err = gpg_error (GPG_ERR_NOT_FOUND);
1531 else if (!(*cert = xtrymalloc (buflen)))
1532 err = gpg_error_from_syserror ();
1535 memcpy (*cert, buffer, buflen);
1542 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1547 /* Decide if we use the pinpad of the reader for PIN input according
1548 to the user preference on the card, and the capability of the
1549 reader. This routine is only called when the reader has pinpad.
1550 Returns 0 if we use pinpad, 1 otherwise. */
1552 check_pinpad_request (app_t app, pininfo_t *pininfo, int admin_pin)
1554 if (app->app_local->pinpad.specified == 0) /* No preference on card. */
1556 if (pininfo->fixedlen == 0) /* Reader has varlen capability. */
1557 return 0; /* Then, use pinpad. */
1560 * Reader has limited capability, and it may not match PIN of
1567 pininfo->fixedlen = app->app_local->pinpad.fixedlen_admin;
1569 pininfo->fixedlen = app->app_local->pinpad.fixedlen_user;
1571 if (pininfo->fixedlen == 0 /* User requests disable pinpad. */
1572 || pininfo->fixedlen < pininfo->minlen
1573 || pininfo->fixedlen > pininfo->maxlen
1574 /* Reader doesn't have the capability to input a PIN which
1575 * length is FIXEDLEN. */)
1582 /* Verify a CHV either using using the pinentry or if possibile by
1583 using a pinpad. PINCB and PINCB_ARG describe the usual callback
1584 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1585 used with CHV1. PINVALUE is the address of a pointer which will
1586 receive a newly allocated block with the actual PIN (this is useful
1587 in case that PIN shall be used for another verify operation). The
1588 caller needs to free this value. If the function returns with
1589 success and NULL is stored at PINVALUE, the caller should take this
1590 as an indication that the pinpad has been used.
1593 verify_a_chv (app_t app,
1594 gpg_error_t (*pincb)(void*, const char *, char **),
1596 int chvno, unsigned long sigcount, char **pinvalue)
1599 char *prompt_buffer = NULL;
1604 assert (chvno == 1 || chvno == 2);
1608 if (chvno == 2 && app->app_local->flags.def_chv2)
1610 /* Special case for def_chv2 mechanism. */
1612 log_info (_("using default PIN as %s\n"), "CHV2");
1613 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1616 /* Verification of CHV2 with the default PIN failed,
1617 although the card pretends to have the default PIN set as
1618 CHV2. We better disable the def_chv2 flag now. */
1619 log_info (_("failed to use default PIN as %s: %s"
1620 " - disabling further default use\n"),
1621 "CHV2", gpg_strerror (rc));
1622 app->app_local->flags.def_chv2 = 0;
1627 memset (&pininfo, 0, sizeof pininfo);
1628 pininfo.fixedlen = -1;
1629 pininfo.minlen = minlen;
1634 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1635 size_t promptsize = strlen (PROMPTSTRING) + 50;
1637 prompt_buffer = xtrymalloc (promptsize);
1639 return gpg_error_from_syserror ();
1640 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1641 prompt = prompt_buffer;
1645 prompt = _("||Please enter the PIN");
1648 if (!opt.disable_pinpad
1649 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
1650 && !check_pinpad_request (app, &pininfo, 0))
1652 /* The reader supports the verify command through the pinpad.
1653 Note that the pincb appends a text to the prompt telling the
1654 user to use the pinpad. */
1655 rc = pincb (pincb_arg, prompt, NULL);
1657 xfree (prompt_buffer);
1658 prompt_buffer = NULL;
1661 log_info (_("PIN callback returned error: %s\n"),
1665 rc = iso7816_verify_kp (app->slot, 0x80+chvno, &pininfo);
1666 /* Dismiss the prompt. */
1667 pincb (pincb_arg, NULL, NULL);
1669 assert (!*pinvalue);
1673 /* The reader has no pinpad or we don't want to use it. */
1674 rc = pincb (pincb_arg, prompt, pinvalue);
1676 xfree (prompt_buffer);
1677 prompt_buffer = NULL;
1680 log_info (_("PIN callback returned error: %s\n"),
1685 if (strlen (*pinvalue) < minlen)
1687 log_error (_("PIN for CHV%d is too short;"
1688 " minimum length is %d\n"), chvno, minlen);
1691 return gpg_error (GPG_ERR_BAD_PIN);
1694 rc = iso7816_verify (app->slot, 0x80+chvno,
1695 *pinvalue, strlen (*pinvalue));
1700 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1703 flush_cache_after_error (app);
1710 /* Verify CHV2 if required. Depending on the configuration of the
1711 card CHV1 will also be verified. */
1713 verify_chv2 (app_t app,
1714 gpg_error_t (*pincb)(void*, const char *, char **),
1721 return 0; /* We already verified CHV2. */
1723 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1728 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1730 /* For convenience we verify CHV1 here too. We do this only if
1731 the card is not configured to require a verification before
1732 each CHV1 controlled operation (force_chv1) and if we are not
1733 using the pinpad (PINVALUE == NULL). */
1734 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1735 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1736 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1739 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1740 flush_cache_after_error (app);
1752 /* Build the prompt to enter the Admin PIN. The prompt depends on the
1753 current sdtate of the card. */
1755 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1758 unsigned char *value;
1765 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1766 if (!relptr || valuelen < 7)
1768 log_error (_("error retrieving CHV status from card\n"));
1770 return gpg_error (GPG_ERR_CARD);
1774 log_info (_("card is permanently locked!\n"));
1776 return gpg_error (GPG_ERR_BAD_PIN);
1778 remaining = value[6];
1781 log_info(_("%d Admin PIN attempts remaining before card"
1782 " is permanently locked\n"), remaining);
1786 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1787 the start of the string. Use %%0A to force a linefeed. */
1788 prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1789 "[remaining attempts: %d]"), remaining);
1792 prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1795 return gpg_error_from_syserror ();
1802 /* Verify CHV3 if required. */
1804 verify_chv3 (app_t app,
1805 gpg_error_t (*pincb)(void*, const char *, char **),
1810 #if GNUPG_MAJOR_VERSION != 1
1811 if (!opt.allow_admin)
1813 log_info (_("access to admin commands is not configured\n"));
1814 return gpg_error (GPG_ERR_EACCES);
1824 memset (&pininfo, 0, sizeof pininfo);
1825 pininfo.fixedlen = -1;
1826 pininfo.minlen = minlen;
1828 rc = build_enter_admin_pin_prompt (app, &prompt);
1832 if (!opt.disable_pinpad
1833 && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
1834 && !check_pinpad_request (app, &pininfo, 1))
1836 /* The reader supports the verify command through the pinpad. */
1837 rc = pincb (pincb_arg, prompt, NULL);
1842 log_info (_("PIN callback returned error: %s\n"),
1846 rc = iso7816_verify_kp (app->slot, 0x83, &pininfo);
1847 /* Dismiss the prompt. */
1848 pincb (pincb_arg, NULL, NULL);
1854 rc = pincb (pincb_arg, prompt, &pinvalue);
1859 log_info (_("PIN callback returned error: %s\n"),
1864 if (strlen (pinvalue) < minlen)
1866 log_error (_("PIN for CHV%d is too short;"
1867 " minimum length is %d\n"), 3, minlen);
1869 return gpg_error (GPG_ERR_BAD_PIN);
1872 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1878 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1879 flush_cache_after_error (app);
1888 /* Handle the SETATTR operation. All arguments are already basically
1891 do_setattr (app_t app, const char *name,
1892 gpg_error_t (*pincb)(void*, const char *, char **),
1894 const unsigned char *value, size_t valuelen)
1903 unsigned int need_v2:1;
1905 { "DISP-NAME", 0x005B, 3 },
1906 { "LOGIN-DATA", 0x005E, 3, 2 },
1907 { "DISP-LANG", 0x5F2D, 3 },
1908 { "DISP-SEX", 0x5F35, 3 },
1909 { "PUBKEY-URL", 0x5F50, 3 },
1910 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1911 { "CA-FPR-1", 0x00CA, 3 },
1912 { "CA-FPR-2", 0x00CB, 3 },
1913 { "CA-FPR-3", 0x00CC, 3 },
1914 { "PRIVATE-DO-1", 0x0101, 2 },
1915 { "PRIVATE-DO-2", 0x0102, 3 },
1916 { "PRIVATE-DO-3", 0x0103, 2 },
1917 { "PRIVATE-DO-4", 0x0104, 3 },
1918 { "CERT-3", 0x7F21, 3, 0, 1 },
1919 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1920 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1921 { "KEY-ATTR", 0, 0, 3, 1 },
1926 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1928 if (!table[idx].name)
1929 return gpg_error (GPG_ERR_INV_NAME);
1930 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1931 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1933 if (table[idx].special == 3)
1934 return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
1936 switch (table[idx].need_chv)
1939 rc = verify_chv2 (app, pincb, pincb_arg);
1942 rc = verify_chv3 (app, pincb, pincb_arg);
1950 /* Flush the cache before writing it, so that the next get operation
1951 will reread the data from the card and thus get synced in case of
1952 errors (e.g. data truncated by the card). */
1953 flush_cache_item (app, table[idx].tag);
1955 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1956 exmode = 1; /* Use extended length w/o a limit. */
1957 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1958 exmode = -254; /* Command chaining with max. 254 bytes. */
1961 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1963 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1965 if (table[idx].special == 1)
1966 app->force_chv1 = (valuelen && *value == 0);
1967 else if (table[idx].special == 2)
1968 parse_login_data (app);
1974 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1975 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1976 PINCB and PINCB_ARG are the usual arguments for the pinentry
1979 do_writecert (app_t app, ctrl_t ctrl,
1980 const char *certidstr,
1981 gpg_error_t (*pincb)(void*, const char *, char **),
1983 const unsigned char *certdata, size_t certdatalen)
1986 #if GNUPG_MAJOR_VERSION > 1
1987 if (strcmp (certidstr, "OPENPGP.3"))
1988 return gpg_error (GPG_ERR_INV_ID);
1989 if (!certdata || !certdatalen)
1990 return gpg_error (GPG_ERR_INV_ARG);
1991 if (!app->app_local->extcap.is_v2)
1992 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1993 if (certdatalen > app->app_local->extcap.max_certlen_3)
1994 return gpg_error (GPG_ERR_TOO_LARGE);
1995 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1997 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
2003 /* Handle the PASSWD command. The following combinations are
2006 Flags CHVNO Vers. Description
2007 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
2008 RESET 1 2 Verify PW3 and set a new PW1.
2009 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
2010 RESET 2 2 Verify PW3 and set a new Reset Code.
2011 RESET 3 any Returns GPG_ERR_INV_ID.
2012 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
2013 - 1 2 Verify PW1 and set a new PW1.
2014 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
2015 - 2 2 Verify Reset Code and set a new PW1.
2016 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
2019 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
2021 gpg_error_t (*pincb)(void*, const char *, char **),
2025 int chvno = atoi (chvnostr);
2026 char *resetcode = NULL;
2027 char *oldpinvalue = NULL;
2028 char *pinvalue = NULL;
2029 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
2030 int set_resetcode = 0;
2036 memset (&pininfo, 0, sizeof pininfo);
2037 pininfo.fixedlen = -1;
2038 pininfo.minlen = minlen;
2040 if (reset_mode && chvno == 3)
2042 rc = gpg_error (GPG_ERR_INV_ID);
2046 if (!app->app_local->extcap.is_v2)
2048 /* Version 1 cards. */
2050 if (reset_mode || chvno == 3)
2052 /* We always require that the PIN is entered. */
2054 rc = verify_chv3 (app, pincb, pincb_arg);
2058 else if (chvno == 1 || chvno == 2)
2060 /* On a v1.x card CHV1 and CVH2 should always have the same
2061 value, thus we enforce it here. */
2062 int save_force = app->force_chv1;
2064 app->force_chv1 = 0;
2067 rc = verify_chv2 (app, pincb, pincb_arg);
2068 app->force_chv1 = save_force;
2074 rc = gpg_error (GPG_ERR_INV_ID);
2080 /* Version 2 cards. */
2082 if (!opt.disable_pinpad
2083 && !iso7816_check_pinpad (app->slot,
2084 ISO7816_CHANGE_REFERENCE_DATA, &pininfo)
2085 && !check_pinpad_request (app, &pininfo, chvno == 3))
2090 /* To reset a PIN the Admin PIN is required. */
2093 rc = verify_chv3 (app, pincb, pincb_arg);
2100 else if (chvno == 1 || chvno == 3)
2104 char *promptbuf = NULL;
2110 rc = build_enter_admin_pin_prompt (app, &promptbuf);
2116 prompt = _("||Please enter the PIN");
2117 rc = pincb (pincb_arg, prompt, &oldpinvalue);
2122 log_info (_("PIN callback returned error: %s\n"),
2127 if (strlen (oldpinvalue) < minlen)
2129 log_info (_("PIN for CHV%d is too short;"
2130 " minimum length is %d\n"), chvno, minlen);
2131 rc = gpg_error (GPG_ERR_BAD_PIN);
2136 else if (chvno == 2)
2138 /* There is no PW2 for v2 cards. We use this condition to
2139 allow a PW reset using the Reset Code. */
2141 unsigned char *value;
2147 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2148 if (!relptr || valuelen < 7)
2150 log_error (_("error retrieving CHV status from card\n"));
2152 rc = gpg_error (GPG_ERR_CARD);
2155 remaining = value[5];
2159 log_error (_("Reset Code not or not anymore available\n"));
2160 rc = gpg_error (GPG_ERR_BAD_PIN);
2164 rc = pincb (pincb_arg,
2165 _("||Please enter the Reset Code for the card"),
2169 log_info (_("PIN callback returned error: %s\n"),
2173 if (strlen (resetcode) < minlen)
2175 log_info (_("Reset Code is too short; minimum length is %d\n"),
2177 rc = gpg_error (GPG_ERR_BAD_PIN);
2183 rc = gpg_error (GPG_ERR_INV_ID);
2191 app->did_chv1 = app->did_chv2 = 0;
2195 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2196 keep it at the start of the string. We need this elsewhere
2197 to get some infos on the string. */
2198 rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
2199 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2203 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2213 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2215 rc = gpg_error_from_syserror ();
2218 strcpy (stpcpy (buffer, resetcode), pinvalue);
2219 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2220 buffer, strlen (buffer));
2221 wipememory (buffer, strlen (buffer));
2225 else if (set_resetcode)
2227 if (strlen (pinvalue) < 8)
2229 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2230 rc = gpg_error (GPG_ERR_BAD_PIN);
2233 rc = iso7816_put_data (app->slot, 0, 0xD3,
2234 pinvalue, strlen (pinvalue));
2236 else if (reset_mode)
2238 rc = iso7816_reset_retry_counter (app->slot, 0x81,
2239 pinvalue, strlen (pinvalue));
2240 if (!rc && !app->app_local->extcap.is_v2)
2241 rc = iso7816_reset_retry_counter (app->slot, 0x82,
2242 pinvalue, strlen (pinvalue));
2244 else if (!app->app_local->extcap.is_v2)
2246 /* Version 1 cards. */
2247 if (chvno == 1 || chvno == 2)
2249 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2250 pinvalue, strlen (pinvalue));
2252 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2253 pinvalue, strlen (pinvalue));
2255 else /* CHVNO == 3 */
2257 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2258 pinvalue, strlen (pinvalue));
2263 /* Version 2 cards. */
2264 assert (chvno == 1 || chvno == 3);
2268 rc = pincb (pincb_arg,
2270 _("||Please enter the Admin PIN and New Admin PIN") :
2271 _("||Please enter the PIN and New PIN"), NULL);
2274 log_info (_("PIN callback returned error: %s\n"),
2278 rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0,
2280 /* Dismiss the prompt. */
2281 pincb (pincb_arg, NULL, NULL);
2284 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2285 oldpinvalue, strlen (oldpinvalue),
2286 pinvalue, strlen (pinvalue));
2291 wipememory (pinvalue, strlen (pinvalue));
2295 flush_cache_after_error (app);
2300 wipememory (resetcode, strlen (resetcode));
2305 wipememory (oldpinvalue, strlen (oldpinvalue));
2306 xfree (oldpinvalue);
2312 /* Check whether a key already exists. KEYIDX is the index of the key
2313 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2314 error returned if the key already exists. The flag GENERATING is
2315 only used to print correct messages. */
2317 does_key_exist (app_t app, int keyidx, int generating, int force)
2319 const unsigned char *fpr;
2320 unsigned char *buffer;
2324 assert (keyidx >=0 && keyidx <= 2);
2326 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2328 log_error (_("error reading application data\n"));
2329 return gpg_error (GPG_ERR_GENERAL);
2331 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2334 log_error (_("error reading fingerprint DO\n"));
2336 return gpg_error (GPG_ERR_GENERAL);
2339 for (i=0; i < 20 && !fpr[i]; i++)
2342 if (i!=20 && !force)
2344 log_error (_("key already exists\n"));
2345 return gpg_error (GPG_ERR_EEXIST);
2348 log_info (_("existing key will be replaced\n"));
2349 else if (generating)
2350 log_info (_("generating new key\n"));
2352 log_info (_("writing new key\n"));
2357 /* Create a TLV tag and value and store it at BUFFER. Return the length
2358 of tag and length. A LENGTH greater than 65535 is truncated. */
2360 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2362 unsigned char *p = buffer;
2364 assert (tag <= 0xffff);
2370 else if (length < 256)
2377 if (length > 0xffff)
2388 /* Build the private key template as specified in the OpenPGP specs
2389 v2.0 section 4.3.3.7. */
2391 build_privkey_template (app_t app, int keyno,
2392 const unsigned char *rsa_n, size_t rsa_n_len,
2393 const unsigned char *rsa_e, size_t rsa_e_len,
2394 const unsigned char *rsa_p, size_t rsa_p_len,
2395 const unsigned char *rsa_q, size_t rsa_q_len,
2396 const unsigned char *rsa_u, size_t rsa_u_len,
2397 const unsigned char *rsa_dp, size_t rsa_dp_len,
2398 const unsigned char *rsa_dq, size_t rsa_dq_len,
2399 unsigned char **result, size_t *resultlen)
2401 size_t rsa_e_reqlen;
2402 unsigned char privkey[7*(1+3+3)];
2404 unsigned char exthdr[2+2+3];
2406 unsigned char suffix[2+3];
2410 unsigned char *template;
2411 size_t template_size;
2416 switch (app->app_local->keyattr[keyno].format)
2425 return gpg_error (GPG_ERR_INV_VALUE);
2428 /* Get the required length for E. Rounded up to the nearest byte */
2429 rsa_e_reqlen = (app->app_local->keyattr[keyno].e_bits + 7) / 8;
2430 assert (rsa_e_len <= rsa_e_reqlen);
2432 /* Build the 7f48 cardholder private key template. */
2436 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2437 datalen += rsa_e_reqlen;
2439 tp += add_tlv (tp, 0x92, rsa_p_len);
2440 datalen += rsa_p_len;
2442 tp += add_tlv (tp, 0x93, rsa_q_len);
2443 datalen += rsa_q_len;
2445 if (app->app_local->keyattr[keyno].format == RSA_CRT
2446 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2448 tp += add_tlv (tp, 0x94, rsa_u_len);
2449 datalen += rsa_u_len;
2450 tp += add_tlv (tp, 0x95, rsa_dp_len);
2451 datalen += rsa_dp_len;
2452 tp += add_tlv (tp, 0x96, rsa_dq_len);
2453 datalen += rsa_dq_len;
2456 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2457 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2459 tp += add_tlv (tp, 0x97, rsa_n_len);
2460 datalen += rsa_n_len;
2462 privkey_len = tp - privkey;
2464 /* Build the extended header list without the private key template. */
2466 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2468 tp += add_tlv (tp, 0x7f48, privkey_len);
2469 exthdr_len = tp - exthdr;
2471 /* Build the 5f48 suffix of the data. */
2473 tp += add_tlv (tp, 0x5f48, datalen);
2474 suffix_len = tp - suffix;
2476 /* Now concatenate everything. */
2477 template_size = (1 + 3 /* 0x4d and len. */
2482 tp = template = xtrymalloc_secure (template_size);
2484 return gpg_error_from_syserror ();
2486 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2487 memcpy (tp, exthdr, exthdr_len);
2489 memcpy (tp, privkey, privkey_len);
2491 memcpy (tp, suffix, suffix_len);
2494 memcpy (tp, rsa_e, rsa_e_len);
2495 if (rsa_e_len < rsa_e_reqlen)
2497 /* Right justify E. */
2498 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2499 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2503 memcpy (tp, rsa_p, rsa_p_len);
2506 memcpy (tp, rsa_q, rsa_q_len);
2509 if (app->app_local->keyattr[keyno].format == RSA_CRT
2510 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2512 memcpy (tp, rsa_u, rsa_u_len);
2514 memcpy (tp, rsa_dp, rsa_dp_len);
2516 memcpy (tp, rsa_dq, rsa_dq_len);
2520 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2521 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2523 memcpy (tp, rsa_n, rsa_n_len);
2527 /* Sanity check. We don't know the exact length because we
2528 allocated 3 bytes for the first length header. */
2529 assert (tp - template <= template_size);
2532 *resultlen = tp - template;
2537 /* Helper for do_writekley to change the size of a key. Not ethat
2538 this deletes the entire key without asking. */
2540 change_keyattr (app_t app, int keyno, unsigned int nbits,
2541 gpg_error_t (*pincb)(void*, const char *, char **),
2545 unsigned char *buffer;
2549 assert (keyno >=0 && keyno <= 2);
2552 return gpg_error (GPG_ERR_TOO_LARGE);
2554 /* Read the current attributes into a buffer. */
2555 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
2557 return gpg_error (GPG_ERR_CARD);
2558 if (buflen < 6 || buffer[0] != PUBKEY_ALGO_RSA)
2560 /* Attriutes too short or not an RSA key. */
2562 return gpg_error (GPG_ERR_CARD);
2565 /* We only change n_bits and don't touch anything else. Before we
2566 do so, we round up NBITS to a sensible way in the same way as
2567 gpg's key generation does it. This may help to sort out problems
2568 with a few bits too short keys. */
2569 nbits = ((nbits + 31) / 32) * 32;
2570 buffer[1] = (nbits >> 8);
2573 /* Prepare for storing the key. */
2574 err = verify_chv3 (app, pincb, pincb_arg);
2581 /* Change the attribute. */
2582 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
2585 log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
2587 log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
2589 parse_algorithm_attribute (app, keyno);
2597 /* Helper to process an setattr command for name KEY-ATTR. It expects
2598 a string "--force <keyno> <algo> <nbits>" in (VALUE,VALUELEN). */
2600 change_keyattr_from_string (app_t app,
2601 gpg_error_t (*pincb)(void*, const char *, char **),
2603 const void *value, size_t valuelen)
2610 /* VALUE is expected to be a string but not guaranteed to be
2611 terminated. Thus copy it to an allocated buffer first. */
2612 string = xtrymalloc (valuelen+1);
2614 return gpg_error_from_syserror ();
2615 memcpy (string, value, valuelen);
2616 string[valuelen] = 0;
2618 /* Because this function deletes the key we require the string
2619 "--force" in the data to make clear that something serious might
2621 if (sscanf (string, " --force %d %d %u", &keyno, &algo, &nbits) != 3)
2622 err = gpg_error (GPG_ERR_INV_DATA);
2626 if (keyno < 0 || keyno > 2)
2627 err = gpg_error (GPG_ERR_INV_ID);
2628 else if (algo != PUBKEY_ALGO_RSA)
2629 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
2630 else if (nbits < 1024)
2631 err = gpg_error (GPG_ERR_TOO_SHORT);
2633 err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2641 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2642 canonical encoded S-expression with the secret key in KEYDATA and
2643 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2644 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2645 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2646 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2647 the pinentry callback. */
2649 do_writekey (app_t app, ctrl_t ctrl,
2650 const char *keyid, unsigned int flags,
2651 gpg_error_t (*pincb)(void*, const char *, char **),
2653 const unsigned char *keydata, size_t keydatalen)
2656 int force = (flags & 1);
2658 const unsigned char *buf, *tok;
2659 size_t buflen, toklen;
2660 int depth, last_depth1, last_depth2;
2661 const unsigned char *rsa_n = NULL;
2662 const unsigned char *rsa_e = NULL;
2663 const unsigned char *rsa_p = NULL;
2664 const unsigned char *rsa_q = NULL;
2665 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2667 unsigned int maxbits;
2668 unsigned char *template = NULL;
2670 size_t template_len;
2671 unsigned char fprbuf[20];
2676 if (!strcmp (keyid, "OPENPGP.1"))
2678 else if (!strcmp (keyid, "OPENPGP.2"))
2680 else if (!strcmp (keyid, "OPENPGP.3"))
2683 return gpg_error (GPG_ERR_INV_ID);
2685 err = does_key_exist (app, keyno, 0, force);
2691 Parse the S-expression
2694 buflen = keydatalen;
2696 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2698 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2700 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2704 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2705 log_info ("protected-private-key passed to writekey\n");
2706 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2707 log_info ("shadowed-private-key passed to writekey\n");
2708 err = gpg_error (GPG_ERR_BAD_SECKEY);
2711 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2713 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2715 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2717 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2720 last_depth1 = depth;
2721 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2722 && depth && depth >= last_depth1)
2726 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2729 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2731 if (tok && toklen == 1)
2733 const unsigned char **mpi;
2738 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2739 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2740 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2741 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2742 default: mpi = NULL; mpi_len = NULL; break;
2746 err = gpg_error (GPG_ERR_DUP_VALUE);
2749 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2753 /* Strip off leading zero bytes and save. */
2754 for (;toklen && !*tok; toklen--, tok++)
2760 /* Skip until end of list. */
2761 last_depth2 = depth;
2762 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2763 && depth && depth >= last_depth2)
2768 /* Parse other attributes. */
2769 last_depth1 = depth;
2770 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2771 && depth && depth >= last_depth1)
2775 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2778 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2780 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2782 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2786 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2788 created_at = created_at*10 + (*tok - '0');
2791 /* Skip until end of list. */
2792 last_depth2 = depth;
2793 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2794 && depth && depth >= last_depth2)
2801 /* Check that we have all parameters and that they match the card
2805 log_error (_("creation timestamp missing\n"));
2806 err = gpg_error (GPG_ERR_INV_VALUE);
2810 maxbits = app->app_local->keyattr[keyno].n_bits;
2811 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2813 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2814 nbits, (unsigned int)rsa_n_len);
2815 if (nbits && nbits != maxbits
2816 && app->app_local->extcap.algo_attr_change)
2818 /* Try to switch the key to a new length. */
2819 err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2821 maxbits = app->app_local->keyattr[keyno].n_bits;
2823 if (nbits != maxbits)
2825 log_error (_("RSA modulus missing or not of size %d bits\n"),
2827 err = gpg_error (GPG_ERR_BAD_SECKEY);
2831 maxbits = app->app_local->keyattr[keyno].e_bits;
2832 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2833 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2834 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2835 if (nbits < 2 || nbits > maxbits)
2837 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2839 err = gpg_error (GPG_ERR_BAD_SECKEY);
2843 maxbits = app->app_local->keyattr[keyno].n_bits/2;
2844 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2845 if (nbits != maxbits)
2847 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2849 err = gpg_error (GPG_ERR_BAD_SECKEY);
2852 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2853 if (nbits != maxbits)
2855 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2857 err = gpg_error (GPG_ERR_BAD_SECKEY);
2861 /* We need to remove the cached public key. */
2862 xfree (app->app_local->pk[keyno].key);
2863 app->app_local->pk[keyno].key = NULL;
2864 app->app_local->pk[keyno].keylen = 0;
2865 app->app_local->pk[keyno].read_done = 0;
2868 if (app->app_local->extcap.is_v2)
2870 unsigned char *rsa_u, *rsa_dp, *rsa_dq;
2871 size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
2872 gcry_mpi_t mpi_e, mpi_p, mpi_q;
2873 gcry_mpi_t mpi_u = gcry_mpi_snew (0);
2874 gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
2875 gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
2876 gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
2879 /* Calculate the u, dp and dq components needed by RSA_CRT cards */
2880 gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
2881 gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
2882 gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
2884 gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
2885 gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
2886 gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
2887 gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
2888 gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
2890 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
2891 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
2892 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
2894 gcry_mpi_release (mpi_e);
2895 gcry_mpi_release (mpi_p);
2896 gcry_mpi_release (mpi_q);
2897 gcry_mpi_release (mpi_u);
2898 gcry_mpi_release (mpi_dp);
2899 gcry_mpi_release (mpi_dq);
2900 gcry_mpi_release (mpi_tmp);
2902 /* Build the private key template as described in section 4.3.3.7 of
2903 the OpenPGP card specs version 2.0. */
2904 err = build_privkey_template (app, keyno,
2912 &template, &template_len);
2920 /* Prepare for storing the key. */
2921 err = verify_chv3 (app, pincb, pincb_arg);
2925 /* Store the key. */
2926 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2927 exmode = 1; /* Use extended length w/o a limit. */
2928 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2932 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2933 template, template_len);
2937 /* Build the private key template as described in section 4.3.3.6 of
2938 the OpenPGP card specs version 1.1:
2939 0xC0 <length> public exponent
2940 0xC1 <length> prime p
2941 0xC2 <length> prime q
2943 assert (rsa_e_len <= 4);
2944 template_len = (1 + 1 + 4
2946 + 1 + 1 + rsa_q_len);
2947 template = tp = xtrymalloc_secure (template_len);
2950 err = gpg_error_from_syserror ();
2955 memcpy (tp, rsa_e, rsa_e_len);
2958 /* Right justify E. */
2959 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2960 memset (tp, 0, 4-rsa_e_len);
2966 memcpy (tp, rsa_p, rsa_p_len);
2971 memcpy (tp, rsa_q, rsa_q_len);
2974 assert (tp - template == template_len);
2976 /* Prepare for storing the key. */
2977 err = verify_chv3 (app, pincb, pincb_arg);
2981 /* Store the key. */
2982 err = iso7816_put_data (app->slot, 0,
2983 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2984 template, template_len);
2988 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2992 err = store_fpr (app, keyno, created_at,
2993 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2994 fprbuf, app->card_version);
3005 /* Handle the GENKEY command. */
3007 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
3009 gpg_error_t (*pincb)(void*, const char *, char **),
3014 unsigned char fprbuf[20];
3015 const unsigned char *keydata, *m, *e;
3016 unsigned char *buffer = NULL;
3017 size_t buflen, keydatalen, mlen, elen;
3019 int keyno = atoi (keynostr) - 1;
3020 int force = (flags & 1);
3024 unsigned int keybits;
3026 if (keyno < 0 || keyno > 2)
3027 return gpg_error (GPG_ERR_INV_ID);
3029 /* We flush the cache to increase the traffic before a key
3030 generation. This _might_ help a card to gather more entropy. */
3033 /* Obviously we need to remove the cached public key. */
3034 xfree (app->app_local->pk[keyno].key);
3035 app->app_local->pk[keyno].key = NULL;
3036 app->app_local->pk[keyno].keylen = 0;
3037 app->app_local->pk[keyno].read_done = 0;
3039 /* Check whether a key already exists. */
3040 err = does_key_exist (app, keyno, 1, force);
3044 /* Because we send the key parameter back via status lines we need
3045 to put a limit on the max. allowed keysize. 2048 bit will
3046 already lead to a 527 byte long status line and thus a 4096 bit
3047 key would exceed the Assuan line length limit. */
3048 keybits = app->app_local->keyattr[keyno].n_bits;
3050 return gpg_error (GPG_ERR_TOO_LARGE);
3052 /* Prepare for key generation by verifying the Admin PIN. */
3053 err = verify_chv3 (app, pincb, pincb_arg);
3057 /* Test whether we will need extended length mode. */
3058 if (app->app_local->cardcap.ext_lc_le && keybits > RSA_SMALL_SIZE_KEY)
3060 exmode = 1; /* Use extended length w/o a limit. */
3061 le_value = determine_rsa_response (app, keyno);
3062 /* No need to check le_value because it comes from a 16 bit
3063 value and thus can't create an overflow on a 32 bit
3069 le_value = 256; /* Use legacy value. */
3072 log_info (_("please wait while key is being generated ...\n"));
3073 start_at = time (NULL);
3074 err = iso7816_generate_keypair (app->slot, exmode,
3075 (keyno == 0? "\xB6" :
3076 keyno == 1? "\xB8" : "\xA4"),
3077 2, le_value, &buffer, &buflen);
3080 err = gpg_error (GPG_ERR_CARD);
3081 log_error (_("generating key failed\n"));
3084 log_info (_("key generation completed (%d seconds)\n"),
3085 (int)(time (NULL) - start_at));
3087 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
3090 err = gpg_error (GPG_ERR_CARD);
3091 log_error (_("response does not contain the public key data\n"));
3095 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
3098 err = gpg_error (GPG_ERR_CARD);
3099 log_error (_("response does not contain the RSA modulus\n"));
3102 /* log_printhex ("RSA n:", m, mlen); */
3103 send_key_data (ctrl, "n", m, mlen);
3105 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
3108 err = gpg_error (GPG_ERR_CARD);
3109 log_error (_("response does not contain the RSA public exponent\n"));
3112 /* log_printhex ("RSA e:", e, elen); */
3113 send_key_data (ctrl, "e", e, elen);
3115 created_at = (u32)(createtime? createtime : gnupg_get_time ());
3116 sprintf (numbuf, "%u", created_at);
3117 send_status_info (ctrl, "KEY-CREATED-AT",
3118 numbuf, (size_t)strlen(numbuf), NULL, 0);
3120 err = store_fpr (app, keyno, (u32)created_at,
3121 m, mlen, e, elen, fprbuf, app->card_version);
3124 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
3133 static unsigned long
3134 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
3139 ul = (value[0] << 16) | (value[1] << 8) | value[2];
3142 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
3148 static unsigned long
3149 get_sig_counter (app_t app)
3152 unsigned char *value;
3156 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
3159 ul = convert_sig_counter_value (value, valuelen);
3165 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
3167 const unsigned char *fpr;
3168 unsigned char *buffer;
3172 assert (keyno >= 0 && keyno <= 2);
3174 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
3177 log_error (_("error reading application data\n"));
3178 return gpg_error (GPG_ERR_GENERAL);
3180 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
3181 if (!fpr || n != 60)
3184 log_error (_("error reading fingerprint DO\n"));
3185 return gpg_error (GPG_ERR_GENERAL);
3188 for (i=0; i < 20; i++)
3189 if (sha1fpr[i] != fpr[i])
3192 log_info (_("fingerprint on card does not match requested one\n"));
3193 return gpg_error (GPG_ERR_WRONG_SECKEY);
3200 /* If a fingerprint has been specified check it against the one on the
3201 card. This allows for a meaningful error message in case the key
3202 on the card has been replaced but the shadow information known to
3203 gpg has not been updated. If there is no fingerprint we assume
3204 that this is okay. */
3206 check_against_given_fingerprint (app_t app, const char *fpr, int key)
3208 unsigned char tmp[20];
3212 for (s=fpr, n=0; hexdigitp (s); s++, n++)
3215 return gpg_error (GPG_ERR_INV_ID);
3219 return gpg_error (GPG_ERR_INV_ID);
3221 for (s=fpr, n=0; n < 20; s += 2, n++)
3222 tmp[n] = xtoi_2 (s);
3223 return compare_fingerprint (app, key-1, tmp);
3228 /* Compute a digital signature on INDATA which is expected to be the
3229 raw message digest. For this application the KEYIDSTR consists of
3230 the serialnumber and the fingerprint delimited by a slash.
3232 Note that this function may return the error code
3233 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3234 not match the one required for the requested action (e.g. the
3235 serial number does not match).
3237 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3238 operation to the auth command.
3241 do_sign (app_t app, const char *keyidstr, int hashalgo,
3242 gpg_error_t (*pincb)(void*, const char *, char **),
3244 const void *indata, size_t indatalen,
3245 unsigned char **outdata, size_t *outdatalen )
3247 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3248 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3249 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3250 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
3251 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3252 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3253 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3254 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3255 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3257 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3258 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3259 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3261 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3262 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3263 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3265 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3266 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3267 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3270 unsigned char data[19+64];
3272 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3275 const char *fpr = NULL;
3276 unsigned long sigcount;
3278 int exmode, le_value;
3280 if (!keyidstr || !*keyidstr)
3281 return gpg_error (GPG_ERR_INV_VALUE);
3283 /* Strip off known prefixes. */
3284 #define X(a,b,c,d) \
3285 if (hashalgo == GCRY_MD_ ## a \
3287 && indatalen == sizeof b ## _prefix + (c) \
3288 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3290 indata = (const char*)indata + sizeof b ## _prefix; \
3291 indatalen -= sizeof b ## _prefix; \
3294 if (indatalen == 20)
3295 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3296 else X(SHA1, sha1, 20, 1)
3297 else X(RMD160, rmd160, 20, 1)
3298 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3299 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3300 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3301 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3302 else if ((indatalen == 28 || indatalen == 32
3303 || indatalen == 48 || indatalen ==64)
3304 && app->app_local->extcap.is_v2)
3305 ; /* Assume a plain SHA-3 digest has been given. */
3308 log_error (_("card does not support digest algorithm %s\n"),
3309 gcry_md_algo_name (hashalgo));
3310 /* Or the supplied digest length does not match an algorithm. */
3311 return gpg_error (GPG_ERR_INV_VALUE);
3315 /* Check whether an OpenPGP card of any version has been requested. */
3316 if (!strcmp (keyidstr, "OPENPGP.1"))
3318 else if (!strcmp (keyidstr, "OPENPGP.3"))
3320 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3321 return gpg_error (GPG_ERR_INV_ID);
3324 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3327 return gpg_error (GPG_ERR_INV_ID);
3329 ; /* no fingerprint given: we allow this for now. */
3333 return gpg_error (GPG_ERR_INV_ID);
3335 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3336 tmp_sn[n] = xtoi_2 (s);
3338 if (app->serialnolen != 16)
3339 return gpg_error (GPG_ERR_INV_CARD);
3340 if (memcmp (app->serialno, tmp_sn, 16))
3341 return gpg_error (GPG_ERR_WRONG_CARD);
3344 /* If a fingerprint has been specified check it against the one on
3345 the card. This is allows for a meaningful error message in case
3346 the key on the card has been replaced but the shadow information
3347 known to gpg was not updated. If there is no fingerprint, gpg
3348 will detect a bogus signature anyway due to the
3349 verify-after-signing feature. */
3350 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3354 /* Concatenate prefix and digest. */
3356 if (hashalgo == GCRY_MD_ ## a && (d) ) \
3358 datalen = sizeof b ## _prefix + indatalen; \
3359 assert (datalen <= sizeof data); \
3360 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3361 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3365 else X(RMD160, rmd160, 1)
3366 else X(SHA224, sha224, app->app_local->extcap.is_v2)
3367 else X(SHA256, sha256, app->app_local->extcap.is_v2)
3368 else X(SHA384, sha384, app->app_local->extcap.is_v2)
3369 else X(SHA512, sha512, app->app_local->extcap.is_v2)
3371 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3374 /* Redirect to the AUTH command if asked to. */
3377 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3379 outdata, outdatalen);
3382 /* Show the number of signature done using this key. */
3383 sigcount = get_sig_counter (app);
3384 log_info (_("signatures created so far: %lu\n"), sigcount);
3386 /* Check CHV if needed. */
3387 if (!app->did_chv1 || app->force_chv1 )
3391 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3397 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3398 sync, thus we verify CHV2 here using the given PIN. Cards
3399 with version2 to not have the need for a separate CHV2 and
3400 internally use just one. Obviously we can't do that if the
3401 pinpad has been used. */
3402 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3404 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3405 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3406 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3409 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3411 flush_cache_after_error (app);
3420 if (app->app_local->cardcap.ext_lc_le
3421 && app->app_local->keyattr[0].n_bits > RSA_SMALL_SIZE_OP)
3423 exmode = 1; /* Use extended length. */
3424 le_value = app->app_local->keyattr[0].n_bits / 8;
3431 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3432 outdata, outdatalen);
3436 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3437 on INDATA which is expected to be the raw message digest. For this
3438 application the KEYIDSTR consists of the serialnumber and the
3439 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3442 Note that this function may return the error code
3443 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3444 not match the one required for the requested action (e.g. the
3445 serial number does not match). */
3447 do_auth (app_t app, const char *keyidstr,
3448 gpg_error_t (*pincb)(void*, const char *, char **),
3450 const void *indata, size_t indatalen,
3451 unsigned char **outdata, size_t *outdatalen )
3454 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3457 const char *fpr = NULL;
3459 if (!keyidstr || !*keyidstr)
3460 return gpg_error (GPG_ERR_INV_VALUE);
3461 if (indatalen > 101) /* For a 2048 bit key. */
3462 return gpg_error (GPG_ERR_INV_VALUE);
3464 /* Check whether an OpenPGP card of any version has been requested. */
3465 if (!strcmp (keyidstr, "OPENPGP.3"))
3467 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3468 return gpg_error (GPG_ERR_INV_ID);
3471 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3474 return gpg_error (GPG_ERR_INV_ID);
3476 ; /* no fingerprint given: we allow this for now. */
3480 return gpg_error (GPG_ERR_INV_ID);
3482 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3483 tmp_sn[n] = xtoi_2 (s);
3485 if (app->serialnolen != 16)
3486 return gpg_error (GPG_ERR_INV_CARD);
3487 if (memcmp (app->serialno, tmp_sn, 16))
3488 return gpg_error (GPG_ERR_WRONG_CARD);
3491 /* If a fingerprint has been specified check it against the one on
3492 the card. This is allows for a meaningful error message in case
3493 the key on the card has been replaced but the shadow information
3494 known to gpg was not updated. If there is no fingerprint, gpg
3495 will detect a bogus signature anyway due to the
3496 verify-after-signing feature. */
3497 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3501 rc = verify_chv2 (app, pincb, pincb_arg);
3504 int exmode, le_value;
3506 if (app->app_local->cardcap.ext_lc_le
3507 && app->app_local->keyattr[2].n_bits > RSA_SMALL_SIZE_OP)
3509 exmode = 1; /* Use extended length. */
3510 le_value = app->app_local->keyattr[2].n_bits / 8;
3517 rc = iso7816_internal_authenticate (app->slot, exmode,
3518 indata, indatalen, le_value,
3519 outdata, outdatalen);
3526 do_decipher (app_t app, const char *keyidstr,
3527 gpg_error_t (*pincb)(void*, const char *, char **),
3529 const void *indata, size_t indatalen,
3530 unsigned char **outdata, size_t *outdatalen )
3533 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3536 const char *fpr = NULL;
3537 int exmode, le_value;
3539 if (!keyidstr || !*keyidstr || !indatalen)
3540 return gpg_error (GPG_ERR_INV_VALUE);
3542 /* Check whether an OpenPGP card of any version has been requested. */
3543 if (!strcmp (keyidstr, "OPENPGP.2"))
3545 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3546 return gpg_error (GPG_ERR_INV_ID);
3549 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3552 return gpg_error (GPG_ERR_INV_ID);
3554 ; /* no fingerprint given: we allow this for now. */