Better reset the PIN verification stati after changing the key attributes.
[gnupg.git] / scd / app-openpgp.c
blobd2b2bdd3f123084e8882f499f8cd576c11660d45
1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3 * 2009 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/>.
20 * $Id$
23 /* Some notes:
25 CHV means Card Holder Verification and is nothing else than a PIN
26 or password. That term seems to have been used originally with GSM
27 cards. Version v2 of the specs changes the term to the clearer
28 term PW for password. We use the terms here interchangeable
29 because we do not want to change existing strings i18n wise.
31 Version 2 of the specs also drops the separate PW2 which was
32 required in v1 due to ISO requirements. It is now possible to have
33 one physical PW but two reference to it so that they can be
34 individually be verified (e.g. to implement a forced verification
35 for one key). Thus you will noticed the use of PW2 with the verify
36 command but not with change_reference_data because the latter
37 operates directly on the physical PW.
39 The Reset Code (RC) as implemented by v2 cards uses the same error
40 counter as the PW2 of v1 cards. By default no RC is set and thus
41 that error counter is set to 0. After setting the RC the error
42 counter will be initialized to 3.
46 #include <config.h>
47 #include <errno.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <assert.h>
52 #include <time.h>
54 #if GNUPG_MAJOR_VERSION == 1
55 /* This is used with GnuPG version < 1.9. The code has been source
56 copied from the current GnuPG >= 1.9 and is maintained over
57 there. */
58 #include "options.h"
59 #include "errors.h"
60 #include "memory.h"
61 #include "util.h"
62 #include "cardglue.h"
63 #else /* GNUPG_MAJOR_VERSION != 1 */
64 #include "scdaemon.h"
65 #endif /* GNUPG_MAJOR_VERSION != 1 */
67 #include "i18n.h"
68 #include "iso7816.h"
69 #include "app-common.h"
70 #include "tlv.h"
73 /* A table describing the DOs of the card. */
74 static struct {
75 int tag;
76 int constructed;
77 int get_from; /* Constructed DO with this DO or 0 for direct access. */
78 int binary:1;
79 int dont_cache:1;
80 int flush_on_error:1;
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
86 status bytes. */
87 int try_extlen:1; /* Large object; try to use an extended
88 length APDU. */
89 char *desc;
90 } data_objects[] = {
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"},
117 { 0 }
121 /* The format of RSA private keys. */
122 typedef enum
124 RSA_UNKNOWN_FMT,
125 RSA_STD,
126 RSA_STD_N,
127 RSA_CRT,
128 RSA_CRT_N
130 rsa_key_format_t;
133 /* One cache item for DOs. */
134 struct cache_s {
135 struct cache_s *next;
136 int tag;
137 size_t length;
138 unsigned char data[1];
142 /* Object with application (i.e. OpenPGP card) specific data. */
143 struct app_local_s {
144 /* A linked list with cached DOs. */
145 struct cache_s *cache;
147 /* Keep track of the public keys. */
148 struct
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
154 available. */
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. */
159 } pk[3];
161 unsigned char status_indicator; /* The card status indicator. */
163 /* Keep track of the ISO card capabilities. */
164 struct
166 unsigned int cmd_chaining:1; /* Command chaining is supported. */
167 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
168 } cardcap;
170 /* Keep track of extended card capabilities. */
171 struct
173 unsigned int is_v2:1; /* This is a v2.0 compatible card. */
174 unsigned int get_challenge:1;
175 unsigned int key_import:1;
176 unsigned int change_force_chv:1;
177 unsigned int private_dos:1;
178 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
179 unsigned int sm_supported:1; /* Secure Messaging is supported. */
180 unsigned int sm_aes128:1; /* Use AES-128 for SM. */
181 unsigned int max_certlen_3:16;
182 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
183 unsigned int max_cmd_data:16; /* Maximum data size for a command. */
184 unsigned int max_rsp_data:16; /* Maximum size of a response. */
185 } extcap;
187 /* Flags used to control the application. */
188 struct
190 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
191 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
192 } flags;
194 struct
196 unsigned int n_bits; /* Size of the modulus in bits. The rest
197 of this strucuire is only valid if
198 this is not 0. */
199 unsigned int e_bits; /* Size of the public exponent in bits. */
200 rsa_key_format_t format;
201 } keyattr[3];
207 /***** Local prototypes *****/
208 static unsigned long convert_sig_counter_value (const unsigned char *value,
209 size_t valuelen);
210 static unsigned long get_sig_counter (app_t app);
211 static gpg_error_t do_auth (app_t app, const char *keyidstr,
212 gpg_error_t (*pincb)(void*, const char *, char **),
213 void *pincb_arg,
214 const void *indata, size_t indatalen,
215 unsigned char **outdata, size_t *outdatalen);
216 static void parse_algorithm_attribute (app_t app, int keyno);
222 /* Deconstructor. */
223 static void
224 do_deinit (app_t app)
226 if (app && app->app_local)
228 struct cache_s *c, *c2;
229 int i;
231 for (c = app->app_local->cache; c; c = c2)
233 c2 = c->next;
234 xfree (c);
237 for (i=0; i < DIM (app->app_local->pk); i++)
239 xfree (app->app_local->pk[i].key);
240 app->app_local->pk[i].read_done = 0;
242 xfree (app->app_local);
243 app->app_local = NULL;
248 /* Wrapper around iso7816_get_data which first tries to get the data
249 from the cache. With GET_IMMEDIATE passed as true, the cache is
250 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
251 supported by the card. */
252 static gpg_error_t
253 get_cached_data (app_t app, int tag,
254 unsigned char **result, size_t *resultlen,
255 int get_immediate, int try_extlen)
257 gpg_error_t err;
258 int i;
259 unsigned char *p;
260 size_t len;
261 struct cache_s *c;
262 int exmode;
264 *result = NULL;
265 *resultlen = 0;
267 if (!get_immediate)
269 for (c=app->app_local->cache; c; c = c->next)
270 if (c->tag == tag)
272 if(c->length)
274 p = xtrymalloc (c->length);
275 if (!p)
276 return gpg_error (gpg_err_code_from_errno (errno));
277 memcpy (p, c->data, c->length);
278 *result = p;
281 *resultlen = c->length;
283 return 0;
287 if (try_extlen && app->app_local->cardcap.ext_lc_le)
288 exmode = app->app_local->extcap.max_rsp_data;
289 else
290 exmode = 0;
292 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
293 if (err)
294 return err;
295 *result = p;
296 *resultlen = len;
298 /* Check whether we should cache this object. */
299 if (get_immediate)
300 return 0;
302 for (i=0; data_objects[i].tag; i++)
303 if (data_objects[i].tag == tag)
305 if (data_objects[i].dont_cache)
306 return 0;
307 break;
310 /* Okay, cache it. */
311 for (c=app->app_local->cache; c; c = c->next)
312 assert (c->tag != tag);
314 c = xtrymalloc (sizeof *c + len);
315 if (c)
317 memcpy (c->data, p, len);
318 c->length = len;
319 c->tag = tag;
320 c->next = app->app_local->cache;
321 app->app_local->cache = c;
324 return 0;
327 /* Remove DO at TAG from the cache. */
328 static void
329 flush_cache_item (app_t app, int tag)
331 struct cache_s *c, *cprev;
332 int i;
334 if (!app->app_local)
335 return;
337 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
338 if (c->tag == tag)
340 if (cprev)
341 cprev->next = c->next;
342 else
343 app->app_local->cache = c->next;
344 xfree (c);
346 for (c=app->app_local->cache; c ; c = c->next)
348 assert (c->tag != tag); /* Oops: duplicated entry. */
350 return;
353 /* Try again if we have an outer tag. */
354 for (i=0; data_objects[i].tag; i++)
355 if (data_objects[i].tag == tag && data_objects[i].get_from
356 && data_objects[i].get_from != tag)
357 flush_cache_item (app, data_objects[i].get_from);
360 /* Flush all entries from the cache which might be out of sync after
361 an error. */
362 static void
363 flush_cache_after_error (app_t app)
365 int i;
367 for (i=0; data_objects[i].tag; i++)
368 if (data_objects[i].flush_on_error)
369 flush_cache_item (app, data_objects[i].tag);
373 /* Flush the entire cache. */
374 static void
375 flush_cache (app_t app)
377 if (app && app->app_local)
379 struct cache_s *c, *c2;
381 for (c = app->app_local->cache; c; c = c2)
383 c2 = c->next;
384 xfree (c);
386 app->app_local->cache = NULL;
391 /* Get the DO identified by TAG from the card in SLOT and return a
392 buffer with its content in RESULT and NBYTES. The return value is
393 NULL if not found or a pointer which must be used to release the
394 buffer holding value. */
395 static void *
396 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
397 int *r_rc)
399 int rc, i;
400 unsigned char *buffer;
401 size_t buflen;
402 unsigned char *value;
403 size_t valuelen;
404 int dummyrc;
405 int exmode;
407 if (!r_rc)
408 r_rc = &dummyrc;
410 *result = NULL;
411 *nbytes = 0;
412 *r_rc = 0;
413 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
416 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
418 if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
419 exmode = app->app_local->extcap.max_rsp_data;
420 else
421 exmode = 0;
422 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
423 if (rc)
425 *r_rc = rc;
426 return NULL;
428 *result = buffer;
429 *nbytes = buflen;
430 return buffer;
433 value = NULL;
434 rc = -1;
435 if (data_objects[i].tag && data_objects[i].get_from)
437 rc = get_cached_data (app, data_objects[i].get_from,
438 &buffer, &buflen,
439 (data_objects[i].dont_cache
440 || data_objects[i].get_immediate_in_v11),
441 data_objects[i].try_extlen);
442 if (!rc)
444 const unsigned char *s;
446 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
447 if (!s)
448 value = NULL; /* not found */
449 else if (valuelen > buflen - (s - buffer))
451 log_error ("warning: constructed DO too short\n");
452 value = NULL;
453 xfree (buffer); buffer = NULL;
455 else
456 value = buffer + (s - buffer);
460 if (!value) /* Not in a constructed DO, try simple. */
462 rc = get_cached_data (app, tag, &buffer, &buflen,
463 (data_objects[i].dont_cache
464 || data_objects[i].get_immediate_in_v11),
465 data_objects[i].try_extlen);
466 if (!rc)
468 value = buffer;
469 valuelen = buflen;
473 if (!rc)
475 *nbytes = valuelen;
476 *result = value;
477 return buffer;
479 *r_rc = rc;
480 return NULL;
484 static void
485 dump_all_do (int slot)
487 int rc, i, j;
488 unsigned char *buffer;
489 size_t buflen;
491 for (i=0; data_objects[i].tag; i++)
493 if (data_objects[i].get_from)
494 continue;
496 /* We don't try extended length APDU because such large DO would
497 be pretty useless in a log file. */
498 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
499 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
501 else if (rc)
502 log_info ("DO `%s' not available: %s\n",
503 data_objects[i].desc, gpg_strerror (rc));
504 else
506 if (data_objects[i].binary)
508 log_info ("DO `%s': ", data_objects[i].desc);
509 log_printhex ("", buffer, buflen);
511 else
512 log_info ("DO `%s': `%.*s'\n",
513 data_objects[i].desc,
514 (int)buflen, buffer); /* FIXME: sanitize */
516 if (data_objects[i].constructed)
518 for (j=0; data_objects[j].tag; j++)
520 const unsigned char *value;
521 size_t valuelen;
523 if (j==i || data_objects[i].tag != data_objects[j].get_from)
524 continue;
525 value = find_tlv_unchecked (buffer, buflen,
526 data_objects[j].tag, &valuelen);
527 if (!value)
528 ; /* not found */
529 else if (valuelen > buflen - (value - buffer))
530 log_error ("warning: constructed DO too short\n");
531 else
533 if (data_objects[j].binary)
535 log_info ("DO `%s': ", data_objects[j].desc);
536 if (valuelen > 200)
537 log_info ("[%u]\n", (unsigned int)valuelen);
538 else
539 log_printhex ("", value, valuelen);
541 else
542 log_info ("DO `%s': `%.*s'\n",
543 data_objects[j].desc,
544 (int)valuelen, value); /* FIXME: sanitize */
549 xfree (buffer); buffer = NULL;
554 /* Count the number of bits, assuming the A represents an unsigned big
555 integer of length LEN bytes. */
556 static unsigned int
557 count_bits (const unsigned char *a, size_t len)
559 unsigned int n = len * 8;
560 int i;
562 for (; len && !*a; len--, a++, n -=8)
564 if (len)
566 for (i=7; i && !(*a & (1<<i)); i--)
567 n--;
569 return n;
572 /* GnuPG makes special use of the login-data DO, this function parses
573 the login data to store the flags for later use. It may be called
574 at any time and should be called after changing the login-data DO.
576 Everything up to a LF is considered a mailbox or account name. If
577 the first LF is followed by DC4 (0x14) control sequence are
578 expected up to the next LF. Control sequences are separated by FS
579 (0x18) and consist of key=value pairs. There is one key defined:
581 F=<flags>
583 Were FLAGS is a plain hexadecimal number representing flag values.
584 The lsb is here the rightmost bit. Defined flags bits are:
586 Bit 0 = CHV1 and CHV2 are not syncronized
587 Bit 1 = CHV2 has been been set to the default PIN of "123456"
588 (this implies that bit 0 is also set).
591 static void
592 parse_login_data (app_t app)
594 unsigned char *buffer, *p;
595 size_t buflen, len;
596 void *relptr;
598 /* Set defaults. */
599 app->app_local->flags.no_sync = 0;
600 app->app_local->flags.def_chv2 = 0;
602 /* Read the DO. */
603 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
604 if (!relptr)
605 return; /* Ooops. */
606 for (; buflen; buflen--, buffer++)
607 if (*buffer == '\n')
608 break;
609 if (buflen < 2 || buffer[1] != '\x14')
610 return; /* No control sequences. */
611 buflen--;
612 buffer++;
615 buflen--;
616 buffer++;
617 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
619 /* Flags control sequence found. */
620 int lastdig = 0;
622 /* For now we are only interested in the last digit, so skip
623 any leading digits but bail out on invalid characters. */
624 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
625 lastdig = xtoi_1 (p);
626 if (len && !(*p == '\n' || *p == '\x18'))
627 goto next; /* Invalid characters in field. */
628 app->app_local->flags.no_sync = !!(lastdig & 1);
629 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
631 next:
632 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
633 if (*buffer == '\n')
634 buflen = 1;
636 while (buflen);
638 xfree (relptr);
641 /* Note, that FPR must be at least 20 bytes. */
642 static gpg_error_t
643 store_fpr (app_t app, int keynumber, u32 timestamp,
644 const unsigned char *m, size_t mlen,
645 const unsigned char *e, size_t elen,
646 unsigned char *fpr, unsigned int card_version)
648 unsigned int n, nbits;
649 unsigned char *buffer, *p;
650 int tag, tag2;
651 int rc;
653 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
655 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
658 n = 6 + 2 + mlen + 2 + elen;
659 p = buffer = xtrymalloc (3 + n);
660 if (!buffer)
661 return gpg_error_from_syserror ();
663 *p++ = 0x99; /* ctb */
664 *p++ = n >> 8; /* 2 byte length header */
665 *p++ = n;
666 *p++ = 4; /* key packet version */
667 *p++ = timestamp >> 24;
668 *p++ = timestamp >> 16;
669 *p++ = timestamp >> 8;
670 *p++ = timestamp;
671 *p++ = 1; /* RSA */
672 nbits = count_bits (m, mlen);
673 *p++ = nbits >> 8;
674 *p++ = nbits;
675 memcpy (p, m, mlen); p += mlen;
676 nbits = count_bits (e, elen);
677 *p++ = nbits >> 8;
678 *p++ = nbits;
679 memcpy (p, e, elen); p += elen;
681 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
683 xfree (buffer);
685 tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
686 flush_cache_item (app, tag);
687 tag2 = 0xCE + keynumber;
688 flush_cache_item (app, tag2);
690 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
691 if (rc)
692 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
694 if (!rc && card_version > 0x0100)
696 unsigned char buf[4];
698 buf[0] = timestamp >> 24;
699 buf[1] = timestamp >> 16;
700 buf[2] = timestamp >> 8;
701 buf[3] = timestamp;
703 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
704 if (rc)
705 log_error (_("failed to store the creation date: %s\n"),
706 gpg_strerror (rc));
709 return rc;
713 static void
714 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
715 int number, const unsigned char *fpr)
717 int i;
718 char buf[41];
719 char numbuf[25];
721 for (i=0; i < 20 && !fpr[i]; i++)
723 if (i==20)
724 return; /* All zero. */
725 bin2hex (fpr, 20, buf);
726 if (number == -1)
727 *numbuf = 0; /* Don't print the key number */
728 else
729 sprintf (numbuf, "%d", number);
730 send_status_info (ctrl, keyword,
731 numbuf, (size_t)strlen(numbuf),
732 buf, (size_t)strlen (buf), NULL, 0);
735 static void
736 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
737 int number, const unsigned char *stamp)
739 char numbuf1[50], numbuf2[50];
740 unsigned long value;
742 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
743 if (!value)
744 return;
745 sprintf (numbuf1, "%d", number);
746 sprintf (numbuf2, "%lu", value);
747 send_status_info (ctrl, keyword,
748 numbuf1, (size_t)strlen(numbuf1),
749 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
752 static void
753 send_key_data (ctrl_t ctrl, const char *name,
754 const unsigned char *a, size_t alen)
756 char *buf;
758 buf = bin2hex (a, alen, NULL);
759 if (!buf)
761 log_error ("memory allocation error in send_key_data\n");
762 return;
765 send_status_info (ctrl, "KEY-DATA",
766 name, (size_t)strlen(name),
767 buf, (size_t)strlen (buf),
768 NULL, 0);
769 xfree (buf);
773 static void
774 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
776 char buffer[200];
778 assert (number >=0 && number < DIM(app->app_local->keyattr));
780 /* We only support RSA thus the algo identifier is fixed to 1. */
781 snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
782 number+1,
783 app->app_local->keyattr[number].n_bits,
784 app->app_local->keyattr[number].e_bits,
785 app->app_local->keyattr[number].format);
786 send_status_direct (ctrl, keyword, buffer);
790 /* Implement the GETATTR command. This is similar to the LEARN
791 command but returns just one value via the status interface. */
792 static gpg_error_t
793 do_getattr (app_t app, ctrl_t ctrl, const char *name)
795 static struct {
796 const char *name;
797 int tag;
798 int special;
799 } table[] = {
800 { "DISP-NAME", 0x005B },
801 { "LOGIN-DATA", 0x005E },
802 { "DISP-LANG", 0x5F2D },
803 { "DISP-SEX", 0x5F35 },
804 { "PUBKEY-URL", 0x5F50 },
805 { "KEY-FPR", 0x00C5, 3 },
806 { "KEY-TIME", 0x00CD, 4 },
807 { "KEY-ATTR", 0x0000, -5 },
808 { "CA-FPR", 0x00C6, 3 },
809 { "CHV-STATUS", 0x00C4, 1 },
810 { "SIG-COUNTER", 0x0093, 2 },
811 { "SERIALNO", 0x004F, -1 },
812 { "AID", 0x004F },
813 { "EXTCAP", 0x0000, -2 },
814 { "PRIVATE-DO-1", 0x0101 },
815 { "PRIVATE-DO-2", 0x0102 },
816 { "PRIVATE-DO-3", 0x0103 },
817 { "PRIVATE-DO-4", 0x0104 },
818 { "$AUTHKEYID", 0x0000, -3 },
819 { "$DISPSERIALNO",0x0000, -4 },
820 { NULL, 0 }
822 int idx, i, rc;
823 void *relptr;
824 unsigned char *value;
825 size_t valuelen;
827 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
829 if (!table[idx].name)
830 return gpg_error (GPG_ERR_INV_NAME);
832 if (table[idx].special == -1)
834 /* The serial number is very special. We could have used the
835 AID DO to retrieve it, but we have it already in the app
836 context and the stamp argument is required anyway which we
837 can't by other means. The AID DO is available anyway but not
838 hex formatted. */
839 char *serial;
840 time_t stamp;
841 char tmp[50];
843 if (!app_get_serial_and_stamp (app, &serial, &stamp))
845 sprintf (tmp, "%lu", (unsigned long)stamp);
846 send_status_info (ctrl, "SERIALNO",
847 serial, strlen (serial),
848 tmp, strlen (tmp),
849 NULL, 0);
850 xfree (serial);
852 return 0;
854 if (table[idx].special == -2)
856 char tmp[100];
858 snprintf (tmp, sizeof tmp,
859 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
860 app->app_local->extcap.get_challenge,
861 app->app_local->extcap.key_import,
862 app->app_local->extcap.change_force_chv,
863 app->app_local->extcap.private_dos,
864 app->app_local->extcap.max_certlen_3,
865 app->app_local->extcap.algo_attr_change,
866 (app->app_local->extcap.sm_supported
867 ? (app->app_local->extcap.sm_aes128? 7 : 2)
868 : 0));
869 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
870 return 0;
872 if (table[idx].special == -3)
874 char const tmp[] = "OPENPGP.3";
875 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
876 return 0;
878 if (table[idx].special == -4)
880 char *serial;
881 time_t stamp;
883 if (!app_get_serial_and_stamp (app, &serial, &stamp))
885 if (strlen (serial) > 16+12)
887 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
888 xfree (serial);
889 return 0;
891 xfree (serial);
893 return gpg_error (GPG_ERR_INV_NAME);
895 if (table[idx].special == -5)
897 for (i=0; i < 3; i++)
898 send_key_attr (ctrl, app, table[idx].name, i);
899 return 0;
902 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
903 if (relptr)
905 if (table[idx].special == 1)
907 char numbuf[7*23];
909 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
910 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
911 send_status_info (ctrl, table[idx].name,
912 numbuf, strlen (numbuf), NULL, 0);
914 else if (table[idx].special == 2)
916 char numbuf[50];
918 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
919 send_status_info (ctrl, table[idx].name,
920 numbuf, strlen (numbuf), NULL, 0);
922 else if (table[idx].special == 3)
924 if (valuelen >= 60)
925 for (i=0; i < 3; i++)
926 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
928 else if (table[idx].special == 4)
930 if (valuelen >= 12)
931 for (i=0; i < 3; i++)
932 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
934 else
935 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
937 xfree (relptr);
939 return rc;
942 /* Retrieve the fingerprint from the card inserted in SLOT and write
943 the according hex representation to FPR. Caller must have provide
944 a buffer at FPR of least 41 bytes. Returns 0 on success or an
945 error code. */
946 #if GNUPG_MAJOR_VERSION > 1
947 static gpg_error_t
948 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
950 gpg_error_t err = 0;
951 void *relptr;
952 unsigned char *value;
953 size_t valuelen;
955 assert (keyno >=0 && keyno <= 2);
957 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
958 if (relptr && valuelen >= 60)
959 bin2hex (value+keyno*20, 20, fpr);
960 else
961 err = gpg_error (GPG_ERR_NOT_FOUND);
962 xfree (relptr);
963 return err;
965 #endif /*GNUPG_MAJOR_VERSION > 1*/
968 /* Retrieve the public key material for the RSA key, whose fingerprint
969 is FPR, from gpg output, which can be read through the stream FP.
970 The RSA modulus will be stored at the address of M and MLEN, the
971 public exponent at E and ELEN. Returns zero on success, an error
972 code on failure. Caller must release the allocated buffers at M
973 and E if the function returns success. */
974 #if GNUPG_MAJOR_VERSION > 1
975 static gpg_error_t
976 retrieve_key_material (FILE *fp, const char *hexkeyid,
977 const unsigned char **m, size_t *mlen,
978 const unsigned char **e, size_t *elen)
980 gcry_error_t err = 0;
981 char *line = NULL; /* read_line() buffer. */
982 size_t line_size = 0; /* Helper for for read_line. */
983 int found_key = 0; /* Helper to find a matching key. */
984 unsigned char *m_new = NULL;
985 unsigned char *e_new = NULL;
986 size_t m_new_n = 0;
987 size_t e_new_n = 0;
989 /* Loop over all records until we have found the subkey
990 corresponding to the fingerprint. Inm general the first record
991 should be the pub record, but we don't rely on that. Given that
992 we only need to look at one key, it is sufficient to compare the
993 keyid so that we don't need to look at "fpr" records. */
994 for (;;)
996 char *p;
997 char *fields[6];
998 int nfields;
999 size_t max_length;
1000 gcry_mpi_t mpi;
1001 int i;
1003 max_length = 4096;
1004 i = read_line (fp, &line, &line_size, &max_length);
1005 if (!i)
1006 break; /* EOF. */
1007 if (i < 0)
1009 err = gpg_error_from_syserror ();
1010 goto leave; /* Error. */
1012 if (!max_length)
1014 err = gpg_error (GPG_ERR_TRUNCATED);
1015 goto leave; /* Line truncated - we better stop processing. */
1018 /* Parse the line into fields. */
1019 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1021 fields[nfields] = p;
1022 p = strchr (p, ':');
1023 if (p)
1024 *(p++) = 0;
1026 if (!nfields)
1027 continue; /* No fields at all - skip line. */
1029 if (!found_key)
1031 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1032 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1033 found_key = 1;
1034 continue;
1037 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1038 break; /* Next key - stop. */
1040 if ( strcmp (fields[0], "pkd") )
1041 continue; /* Not a key data record. */
1042 i = 0; /* Avoid erroneous compiler warning. */
1043 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1044 || (!i && m_new) || (i && e_new))
1046 err = gpg_error (GPG_ERR_GENERAL);
1047 goto leave; /* Error: Invalid key data record or not an RSA key. */
1050 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1051 if (err)
1052 mpi = NULL;
1053 else if (!i)
1054 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1055 else
1056 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1057 gcry_mpi_release (mpi);
1058 if (err)
1059 goto leave;
1062 if (m_new && e_new)
1064 *m = m_new;
1065 *mlen = m_new_n;
1066 m_new = NULL;
1067 *e = e_new;
1068 *elen = e_new_n;
1069 e_new = NULL;
1071 else
1072 err = gpg_error (GPG_ERR_GENERAL);
1074 leave:
1075 xfree (m_new);
1076 xfree (e_new);
1077 xfree (line);
1078 return err;
1080 #endif /*GNUPG_MAJOR_VERSION > 1*/
1083 /* Get the public key for KEYNO and store it as an S-expresion with
1084 the APP handle. On error that field gets cleared. If we already
1085 know about the public key we will just return. Note that this does
1086 not mean a key is available; this is soley indicated by the
1087 presence of the app->app_local->pk[KEYNO-1].key field.
1089 Note that GnuPG 1.x does not need this and it would be too time
1090 consuming to send it just for the fun of it. However, given that we
1091 use the same code in gpg 1.4, we can't use the gcry S-expresion
1092 here but need to open encode it. */
1093 #if GNUPG_MAJOR_VERSION > 1
1094 static gpg_error_t
1095 get_public_key (app_t app, int keyno)
1097 gpg_error_t err = 0;
1098 unsigned char *buffer;
1099 const unsigned char *keydata, *m, *e;
1100 size_t buflen, keydatalen, mlen, elen;
1101 unsigned char *mbuf = NULL;
1102 unsigned char *ebuf = NULL;
1103 char *keybuf = NULL;
1104 char *keybuf_p;
1106 if (keyno < 1 || keyno > 3)
1107 return gpg_error (GPG_ERR_INV_ID);
1108 keyno--;
1110 /* Already cached? */
1111 if (app->app_local->pk[keyno].read_done)
1112 return 0;
1114 xfree (app->app_local->pk[keyno].key);
1115 app->app_local->pk[keyno].key = NULL;
1116 app->app_local->pk[keyno].keylen = 0;
1118 m = e = NULL; /* (avoid cc warning) */
1120 if (app->card_version > 0x0100)
1122 int exmode, le_value;
1124 /* We may simply read the public key out of these cards. */
1125 if (app->app_local->cardcap.ext_lc_le)
1127 exmode = 1; /* Use extended length. */
1128 le_value = app->app_local->extcap.max_rsp_data;
1130 else
1132 exmode = 0;
1133 le_value = 256; /* Use legacy value. */
1136 err = iso7816_read_public_key
1137 (app->slot, exmode,
1138 (const unsigned char*)(keyno == 0? "\xB6" :
1139 keyno == 1? "\xB8" : "\xA4"), 2,
1140 le_value,
1141 &buffer, &buflen);
1142 if (err)
1144 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1145 goto leave;
1148 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1149 if (!keydata)
1151 err = gpg_error (GPG_ERR_CARD);
1152 log_error (_("response does not contain the public key data\n"));
1153 goto leave;
1156 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1157 if (!m)
1159 err = gpg_error (GPG_ERR_CARD);
1160 log_error (_("response does not contain the RSA modulus\n"));
1161 goto leave;
1165 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1166 if (!e)
1168 err = gpg_error (GPG_ERR_CARD);
1169 log_error (_("response does not contain the RSA public exponent\n"));
1170 goto leave;
1173 /* Prepend numbers with a 0 if needed. */
1174 if (mlen && (*m & 0x80))
1176 mbuf = xtrymalloc ( mlen + 1);
1177 if (!mbuf)
1179 err = gpg_error_from_syserror ();
1180 goto leave;
1182 *mbuf = 0;
1183 memcpy (mbuf+1, m, mlen);
1184 mlen++;
1185 m = mbuf;
1187 if (elen && (*e & 0x80))
1189 ebuf = xtrymalloc ( elen + 1);
1190 if (!ebuf)
1192 err = gpg_error_from_syserror ();
1193 goto leave;
1195 *ebuf = 0;
1196 memcpy (ebuf+1, e, elen);
1197 elen++;
1198 e = ebuf;
1202 else
1204 /* Due to a design problem in v1.0 cards we can't get the public
1205 key out of these cards without doing a verify on CHV3.
1206 Clearly that is not an option and thus we try to locate the
1207 key using an external helper.
1209 The helper we use here is gpg itself, which should know about
1210 the key in any case. */
1212 char fpr[41];
1213 char *hexkeyid;
1214 char *command = NULL;
1215 FILE *fp;
1216 int ret;
1218 buffer = NULL; /* We don't need buffer. */
1220 err = retrieve_fpr_from_card (app, keyno, fpr);
1221 if (err)
1223 log_error ("error while retrieving fpr from card: %s\n",
1224 gpg_strerror (err));
1225 goto leave;
1227 hexkeyid = fpr + 24;
1229 ret = estream_asprintf (&command,
1230 "gpg --list-keys --with-colons --with-key-data '%s'",
1231 fpr);
1232 if (ret < 0)
1234 err = gpg_error_from_syserror ();
1235 goto leave;
1238 fp = popen (command, "r");
1239 xfree (command);
1240 if (!fp)
1242 err = gpg_error_from_syserror ();
1243 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1244 goto leave;
1247 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1248 fclose (fp);
1249 if (err)
1251 log_error ("error while retrieving key material through pipe: %s\n",
1252 gpg_strerror (err));
1253 goto leave;
1257 /* Allocate a buffer to construct the S-expression. */
1258 /* FIXME: We should provide a generalized S-expression creation
1259 mechanism. */
1260 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1261 if (!keybuf)
1263 err = gpg_error_from_syserror ();
1264 goto leave;
1267 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1268 keybuf_p = keybuf + strlen (keybuf);
1269 memcpy (keybuf_p, m, mlen);
1270 keybuf_p += mlen;
1271 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1272 keybuf_p += strlen (keybuf_p);
1273 memcpy (keybuf_p, e, elen);
1274 keybuf_p += elen;
1275 strcpy (keybuf_p, ")))");
1276 keybuf_p += strlen (keybuf_p);
1278 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1279 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1281 leave:
1282 /* Set a flag to indicate that we tried to read the key. */
1283 app->app_local->pk[keyno].read_done = 1;
1285 xfree (buffer);
1286 xfree (mbuf);
1287 xfree (ebuf);
1288 return 0;
1290 #endif /* GNUPG_MAJOR_VERSION > 1 */
1294 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1295 This is used by the LEARN command. */
1296 static gpg_error_t
1297 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1299 gpg_error_t err = 0;
1300 /* Note that GnuPG 1.x does not need this and it would be too time
1301 consuming to send it just for the fun of it. */
1302 #if GNUPG_MAJOR_VERSION > 1
1303 unsigned char grip[20];
1304 char gripstr[41];
1305 char idbuf[50];
1307 err = get_public_key (app, keyno);
1308 if (err)
1309 goto leave;
1311 assert (keyno >= 1 && keyno <= 3);
1312 if (!app->app_local->pk[keyno-1].key)
1313 goto leave; /* No such key - ignore. */
1315 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1316 app->app_local->pk[keyno-1].keylen,
1317 grip);
1318 if (err)
1319 goto leave;
1321 bin2hex (grip, 20, gripstr);
1323 sprintf (idbuf, "OPENPGP.%d", keyno);
1324 send_status_info (ctrl, "KEYPAIRINFO",
1325 gripstr, 40,
1326 idbuf, strlen (idbuf),
1327 NULL, (size_t)0);
1329 leave:
1330 #endif /* GNUPG_MAJOR_VERSION > 1 */
1332 return err;
1336 /* Handle the LEARN command for OpenPGP. */
1337 static gpg_error_t
1338 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1340 (void)flags;
1342 do_getattr (app, ctrl, "EXTCAP");
1343 do_getattr (app, ctrl, "DISP-NAME");
1344 do_getattr (app, ctrl, "DISP-LANG");
1345 do_getattr (app, ctrl, "DISP-SEX");
1346 do_getattr (app, ctrl, "PUBKEY-URL");
1347 do_getattr (app, ctrl, "LOGIN-DATA");
1348 do_getattr (app, ctrl, "KEY-FPR");
1349 if (app->card_version > 0x0100)
1350 do_getattr (app, ctrl, "KEY-TIME");
1351 do_getattr (app, ctrl, "CA-FPR");
1352 do_getattr (app, ctrl, "CHV-STATUS");
1353 do_getattr (app, ctrl, "SIG-COUNTER");
1354 if (app->app_local->extcap.private_dos)
1356 do_getattr (app, ctrl, "PRIVATE-DO-1");
1357 do_getattr (app, ctrl, "PRIVATE-DO-2");
1358 if (app->did_chv2)
1359 do_getattr (app, ctrl, "PRIVATE-DO-3");
1360 if (app->did_chv3)
1361 do_getattr (app, ctrl, "PRIVATE-DO-4");
1363 send_keypair_info (app, ctrl, 1);
1364 send_keypair_info (app, ctrl, 2);
1365 send_keypair_info (app, ctrl, 3);
1366 /* Note: We do not send the Cardholder Certificate, because that is
1367 relativly long and for OpenPGP applications not really needed. */
1368 return 0;
1372 /* Handle the READKEY command for OpenPGP. On success a canonical
1373 encoded S-expression with the public key will get stored at PK and
1374 its length (for assertions) at PKLEN; the caller must release that
1375 buffer. On error PK and PKLEN are not changed and an error code is
1376 returned. */
1377 static gpg_error_t
1378 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1380 #if GNUPG_MAJOR_VERSION > 1
1381 gpg_error_t err;
1382 int keyno;
1383 unsigned char *buf;
1385 if (!strcmp (keyid, "OPENPGP.1"))
1386 keyno = 1;
1387 else if (!strcmp (keyid, "OPENPGP.2"))
1388 keyno = 2;
1389 else if (!strcmp (keyid, "OPENPGP.3"))
1390 keyno = 3;
1391 else
1392 return gpg_error (GPG_ERR_INV_ID);
1394 err = get_public_key (app, keyno);
1395 if (err)
1396 return err;
1398 buf = app->app_local->pk[keyno-1].key;
1399 if (!buf)
1400 return gpg_error (GPG_ERR_NO_PUBKEY);
1401 *pklen = app->app_local->pk[keyno-1].keylen;;
1402 *pk = xtrymalloc (*pklen);
1403 if (!*pk)
1405 err = gpg_error_from_syserror ();
1406 *pklen = 0;
1407 return err;
1409 memcpy (*pk, buf, *pklen);
1410 return 0;
1411 #else
1412 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1413 #endif
1416 /* Read the standard certificate of an OpenPGP v2 card. It is
1417 returned in a freshly allocated buffer with that address stored at
1418 CERT and the length of the certificate stored at CERTLEN. CERTID
1419 needs to be set to "OPENPGP.3". */
1420 static gpg_error_t
1421 do_readcert (app_t app, const char *certid,
1422 unsigned char **cert, size_t *certlen)
1424 #if GNUPG_MAJOR_VERSION > 1
1425 gpg_error_t err;
1426 unsigned char *buffer;
1427 size_t buflen;
1428 void *relptr;
1430 *cert = NULL;
1431 *certlen = 0;
1432 if (strcmp (certid, "OPENPGP.3"))
1433 return gpg_error (GPG_ERR_INV_ID);
1434 if (!app->app_local->extcap.is_v2)
1435 return gpg_error (GPG_ERR_NOT_FOUND);
1437 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1438 if (!relptr)
1439 return gpg_error (GPG_ERR_NOT_FOUND);
1441 if (!buflen)
1442 err = gpg_error (GPG_ERR_NOT_FOUND);
1443 else if (!(*cert = xtrymalloc (buflen)))
1444 err = gpg_error_from_syserror ();
1445 else
1447 memcpy (*cert, buffer, buflen);
1448 *certlen = buflen;
1449 err = 0;
1451 xfree (relptr);
1452 return err;
1453 #else
1454 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1455 #endif
1459 /* Verify a CHV either using using the pinentry or if possibile by
1460 using a keypad. PINCB and PINCB_ARG describe the usual callback
1461 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1462 used with CHV1. PINVALUE is the address of a pointer which will
1463 receive a newly allocated block with the actual PIN (this is useful
1464 in case that PIN shall be used for another verify operation). The
1465 caller needs to free this value. If the function returns with
1466 success and NULL is stored at PINVALUE, the caller should take this
1467 as an indication that the keypad has been used.
1469 static gpg_error_t
1470 verify_a_chv (app_t app,
1471 gpg_error_t (*pincb)(void*, const char *, char **),
1472 void *pincb_arg,
1473 int chvno, unsigned long sigcount, char **pinvalue)
1475 int rc = 0;
1476 char *prompt_buffer = NULL;
1477 const char *prompt;
1478 iso7816_pininfo_t pininfo;
1479 int minlen = 6;
1481 assert (chvno == 1 || chvno == 2);
1483 *pinvalue = NULL;
1485 if (chvno == 2 && app->app_local->flags.def_chv2)
1487 /* Special case for def_chv2 mechanism. */
1488 if (opt.verbose)
1489 log_info (_("using default PIN as %s\n"), "CHV2");
1490 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1491 if (rc)
1493 /* Verification of CHV2 with the default PIN failed,
1494 although the card pretends to have the default PIN set as
1495 CHV2. We better disable the def_chv2 flag now. */
1496 log_info (_("failed to use default PIN as %s: %s"
1497 " - disabling further default use\n"),
1498 "CHV2", gpg_strerror (rc));
1499 app->app_local->flags.def_chv2 = 0;
1501 return rc;
1504 memset (&pininfo, 0, sizeof pininfo);
1505 pininfo.mode = 1;
1506 pininfo.minlen = minlen;
1509 if (chvno == 1)
1511 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1512 size_t promptsize = strlen (PROMPTSTRING) + 50;
1514 prompt_buffer = xtrymalloc (promptsize);
1515 if (!prompt_buffer)
1516 return gpg_error_from_syserror ();
1517 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1518 prompt = prompt_buffer;
1519 #undef PROMPTSTRING
1521 else
1522 prompt = _("||Please enter the PIN");
1525 if (!opt.disable_keypad
1526 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1528 /* The reader supports the verify command through the keypad.
1529 Note that the pincb appends a text to the prompt telling the
1530 user to use the keypad. */
1531 rc = pincb (pincb_arg, prompt, NULL);
1532 prompt = NULL;
1533 xfree (prompt_buffer);
1534 prompt_buffer = NULL;
1535 if (rc)
1537 log_info (_("PIN callback returned error: %s\n"),
1538 gpg_strerror (rc));
1539 return rc;
1541 rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1542 /* Dismiss the prompt. */
1543 pincb (pincb_arg, NULL, NULL);
1545 assert (!*pinvalue);
1547 else
1549 /* The reader has no keypad or we don't want to use it. */
1550 rc = pincb (pincb_arg, prompt, pinvalue);
1551 prompt = NULL;
1552 xfree (prompt_buffer);
1553 prompt_buffer = NULL;
1554 if (rc)
1556 log_info (_("PIN callback returned error: %s\n"),
1557 gpg_strerror (rc));
1558 return rc;
1561 if (strlen (*pinvalue) < minlen)
1563 log_error (_("PIN for CHV%d is too short;"
1564 " minimum length is %d\n"), chvno, minlen);
1565 xfree (*pinvalue);
1566 *pinvalue = NULL;
1567 return gpg_error (GPG_ERR_BAD_PIN);
1570 rc = iso7816_verify (app->slot, 0x80+chvno,
1571 *pinvalue, strlen (*pinvalue));
1574 if (rc)
1576 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1577 xfree (*pinvalue);
1578 *pinvalue = NULL;
1579 flush_cache_after_error (app);
1582 return rc;
1586 /* Verify CHV2 if required. Depending on the configuration of the
1587 card CHV1 will also be verified. */
1588 static gpg_error_t
1589 verify_chv2 (app_t app,
1590 gpg_error_t (*pincb)(void*, const char *, char **),
1591 void *pincb_arg)
1593 int rc;
1594 char *pinvalue;
1596 if (app->did_chv2)
1597 return 0; /* We already verified CHV2. */
1599 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1600 if (rc)
1601 return rc;
1602 app->did_chv2 = 1;
1604 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1606 /* For convenience we verify CHV1 here too. We do this only if
1607 the card is not configured to require a verification before
1608 each CHV1 controlled operation (force_chv1) and if we are not
1609 using the keypad (PINVALUE == NULL). */
1610 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1611 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1612 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1613 if (rc)
1615 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1616 flush_cache_after_error (app);
1618 else
1619 app->did_chv1 = 1;
1622 xfree (pinvalue);
1624 return rc;
1628 /* Build the prompt to enter the Admin PIN. The prompt depends on the
1629 current sdtate of the card. */
1630 static gpg_error_t
1631 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1633 void *relptr;
1634 unsigned char *value;
1635 size_t valuelen;
1636 int remaining;
1637 char *prompt;
1639 *r_prompt = NULL;
1641 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1642 if (!relptr || valuelen < 7)
1644 log_error (_("error retrieving CHV status from card\n"));
1645 xfree (relptr);
1646 return gpg_error (GPG_ERR_CARD);
1648 if (value[6] == 0)
1650 log_info (_("card is permanently locked!\n"));
1651 xfree (relptr);
1652 return gpg_error (GPG_ERR_BAD_PIN);
1654 remaining = value[6];
1655 xfree (relptr);
1657 log_info(_("%d Admin PIN attempts remaining before card"
1658 " is permanently locked\n"), remaining);
1660 if (remaining < 3)
1662 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1663 the start of the string. Use %%0A to force a linefeed. */
1664 prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1665 "[remaining attempts: %d]"), remaining);
1667 else
1668 prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1670 if (!prompt)
1671 return gpg_error_from_syserror ();
1673 *r_prompt = prompt;
1674 return 0;
1678 /* Verify CHV3 if required. */
1679 static gpg_error_t
1680 verify_chv3 (app_t app,
1681 gpg_error_t (*pincb)(void*, const char *, char **),
1682 void *pincb_arg)
1684 int rc = 0;
1686 #if GNUPG_MAJOR_VERSION != 1
1687 if (!opt.allow_admin)
1689 log_info (_("access to admin commands is not configured\n"));
1690 return gpg_error (GPG_ERR_EACCES);
1692 #endif
1694 if (!app->did_chv3)
1696 iso7816_pininfo_t pininfo;
1697 int minlen = 8;
1698 char *prompt;
1700 memset (&pininfo, 0, sizeof pininfo);
1701 pininfo.mode = 1;
1702 pininfo.minlen = minlen;
1704 rc = build_enter_admin_pin_prompt (app, &prompt);
1705 if (rc)
1706 return rc;
1708 if (!opt.disable_keypad
1709 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1711 /* The reader supports the verify command through the keypad. */
1712 rc = pincb (pincb_arg, prompt, NULL);
1713 xfree (prompt);
1714 prompt = NULL;
1715 if (rc)
1717 log_info (_("PIN callback returned error: %s\n"),
1718 gpg_strerror (rc));
1719 return rc;
1721 rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1722 /* Dismiss the prompt. */
1723 pincb (pincb_arg, NULL, NULL);
1725 else
1727 char *pinvalue;
1729 rc = pincb (pincb_arg, prompt, &pinvalue);
1730 xfree (prompt);
1731 prompt = NULL;
1732 if (rc)
1734 log_info (_("PIN callback returned error: %s\n"),
1735 gpg_strerror (rc));
1736 return rc;
1739 if (strlen (pinvalue) < minlen)
1741 log_error (_("PIN for CHV%d is too short;"
1742 " minimum length is %d\n"), 3, minlen);
1743 xfree (pinvalue);
1744 return gpg_error (GPG_ERR_BAD_PIN);
1747 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1748 xfree (pinvalue);
1751 if (rc)
1753 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1754 flush_cache_after_error (app);
1755 return rc;
1757 app->did_chv3 = 1;
1759 return rc;
1763 /* Handle the SETATTR operation. All arguments are already basically
1764 checked. */
1765 static gpg_error_t
1766 do_setattr (app_t app, const char *name,
1767 gpg_error_t (*pincb)(void*, const char *, char **),
1768 void *pincb_arg,
1769 const unsigned char *value, size_t valuelen)
1771 gpg_error_t rc;
1772 int idx;
1773 static struct {
1774 const char *name;
1775 int tag;
1776 int need_chv;
1777 int special;
1778 unsigned int need_v2:1;
1779 } table[] = {
1780 { "DISP-NAME", 0x005B, 3 },
1781 { "LOGIN-DATA", 0x005E, 3, 2 },
1782 { "DISP-LANG", 0x5F2D, 3 },
1783 { "DISP-SEX", 0x5F35, 3 },
1784 { "PUBKEY-URL", 0x5F50, 3 },
1785 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1786 { "CA-FPR-1", 0x00CA, 3 },
1787 { "CA-FPR-2", 0x00CB, 3 },
1788 { "CA-FPR-3", 0x00CC, 3 },
1789 { "PRIVATE-DO-1", 0x0101, 2 },
1790 { "PRIVATE-DO-2", 0x0102, 3 },
1791 { "PRIVATE-DO-3", 0x0103, 2 },
1792 { "PRIVATE-DO-4", 0x0104, 3 },
1793 { "CERT-3", 0x7F21, 3, 0, 1 },
1794 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1795 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1796 { NULL, 0 }
1798 int exmode;
1800 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1802 if (!table[idx].name)
1803 return gpg_error (GPG_ERR_INV_NAME);
1804 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1805 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1807 switch (table[idx].need_chv)
1809 case 2:
1810 rc = verify_chv2 (app, pincb, pincb_arg);
1811 break;
1812 case 3:
1813 rc = verify_chv3 (app, pincb, pincb_arg);
1814 break;
1815 default:
1816 rc = 0;
1818 if (rc)
1819 return rc;
1821 /* Flush the cache before writing it, so that the next get operation
1822 will reread the data from the card and thus get synced in case of
1823 errors (e.g. data truncated by the card). */
1824 flush_cache_item (app, table[idx].tag);
1826 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1827 exmode = 1; /* Use extended length w/o a limit. */
1828 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1829 exmode = -254; /* Command chaining with max. 254 bytes. */
1830 else
1831 exmode = 0;
1832 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1833 if (rc)
1834 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1836 if (table[idx].special == 1)
1837 app->force_chv1 = (valuelen && *value == 0);
1838 else if (table[idx].special == 2)
1839 parse_login_data (app);
1841 return rc;
1845 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1846 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1847 PINCB and PINCB_ARG are the usual arguments for the pinentry
1848 callback. */
1849 static gpg_error_t
1850 do_writecert (app_t app, ctrl_t ctrl,
1851 const char *certidstr,
1852 gpg_error_t (*pincb)(void*, const char *, char **),
1853 void *pincb_arg,
1854 const unsigned char *certdata, size_t certdatalen)
1856 (void)ctrl;
1857 #if GNUPG_MAJOR_VERSION > 1
1858 if (strcmp (certidstr, "OPENPGP.3"))
1859 return gpg_error (GPG_ERR_INV_ID);
1860 if (!certdata || !certdatalen)
1861 return gpg_error (GPG_ERR_INV_ARG);
1862 if (!app->app_local->extcap.is_v2)
1863 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1864 if (certdatalen > app->app_local->extcap.max_certlen_3)
1865 return gpg_error (GPG_ERR_TOO_LARGE);
1866 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1867 #else
1868 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1869 #endif
1874 /* Handle the PASSWD command. The following combinations are
1875 possible:
1877 Flags CHVNO Vers. Description
1878 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
1879 RESET 1 2 Verify PW3 and set a new PW1.
1880 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
1881 RESET 2 2 Verify PW3 and set a new Reset Code.
1882 RESET 3 any Returns GPG_ERR_INV_ID.
1883 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
1884 - 1 2 Verify PW1 and set a new PW1.
1885 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
1886 - 2 2 Verify Reset Code and set a new PW1.
1887 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
1889 static gpg_error_t
1890 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
1891 unsigned int flags,
1892 gpg_error_t (*pincb)(void*, const char *, char **),
1893 void *pincb_arg)
1895 int rc = 0;
1896 int chvno = atoi (chvnostr);
1897 char *resetcode = NULL;
1898 char *oldpinvalue = NULL;
1899 char *pinvalue;
1900 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1901 int set_resetcode = 0;
1903 (void)ctrl;
1905 if (reset_mode && chvno == 3)
1907 rc = gpg_error (GPG_ERR_INV_ID);
1908 goto leave;
1911 if (!app->app_local->extcap.is_v2)
1913 /* Version 1 cards. */
1915 if (reset_mode || chvno == 3)
1917 /* We always require that the PIN is entered. */
1918 app->did_chv3 = 0;
1919 rc = verify_chv3 (app, pincb, pincb_arg);
1920 if (rc)
1921 goto leave;
1923 else if (chvno == 1 || chvno == 2)
1925 /* On a v1.x card CHV1 and CVH2 should always have the same
1926 value, thus we enforce it here. */
1927 int save_force = app->force_chv1;
1929 app->force_chv1 = 0;
1930 app->did_chv1 = 0;
1931 app->did_chv2 = 0;
1932 rc = verify_chv2 (app, pincb, pincb_arg);
1933 app->force_chv1 = save_force;
1934 if (rc)
1935 goto leave;
1937 else
1939 rc = gpg_error (GPG_ERR_INV_ID);
1940 goto leave;
1943 else
1945 /* Version 2 cards. */
1947 if (reset_mode)
1949 /* To reset a PIN the Admin PIN is required. */
1950 app->did_chv3 = 0;
1951 rc = verify_chv3 (app, pincb, pincb_arg);
1952 if (rc)
1953 goto leave;
1955 if (chvno == 2)
1956 set_resetcode = 1;
1958 else if (chvno == 1 || chvno == 3)
1960 int minlen = (chvno ==3)? 8 : 6;
1961 char *promptbuf = NULL;
1962 const char *prompt;
1964 if (chvno == 3)
1966 rc = build_enter_admin_pin_prompt (app, &promptbuf);
1967 if (rc)
1968 goto leave;
1969 prompt = promptbuf;
1971 else
1972 prompt = _("||Please enter the PIN");
1973 rc = pincb (pincb_arg, prompt, &oldpinvalue);
1974 xfree (promptbuf);
1975 promptbuf = NULL;
1976 if (rc)
1978 log_info (_("PIN callback returned error: %s\n"),
1979 gpg_strerror (rc));
1980 goto leave;
1983 if (strlen (oldpinvalue) < minlen)
1985 log_info (_("PIN for CHV%d is too short;"
1986 " minimum length is %d\n"), chvno, minlen);
1987 rc = gpg_error (GPG_ERR_BAD_PIN);
1988 goto leave;
1991 else if (chvno == 2)
1993 /* There is no PW2 for v2 cards. We use this condition to
1994 allow a PW reset using the Reset Code. */
1995 void *relptr;
1996 unsigned char *value;
1997 size_t valuelen;
1998 int remaining;
1999 int minlen = 8;
2001 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2002 if (!relptr || valuelen < 7)
2004 log_error (_("error retrieving CHV status from card\n"));
2005 xfree (relptr);
2006 rc = gpg_error (GPG_ERR_CARD);
2007 goto leave;
2009 remaining = value[5];
2010 xfree (relptr);
2011 if (!remaining)
2013 log_error (_("Reset Code not or not anymore available\n"));
2014 rc = gpg_error (GPG_ERR_BAD_PIN);
2015 goto leave;
2018 rc = pincb (pincb_arg,
2019 _("||Please enter the Reset Code for the card"),
2020 &resetcode);
2021 if (rc)
2023 log_info (_("PIN callback returned error: %s\n"),
2024 gpg_strerror (rc));
2025 goto leave;
2027 if (strlen (resetcode) < minlen)
2029 log_info (_("Reset Code is too short; minimum length is %d\n"),
2030 minlen);
2031 rc = gpg_error (GPG_ERR_BAD_PIN);
2032 goto leave;
2035 else
2037 rc = gpg_error (GPG_ERR_INV_ID);
2038 goto leave;
2042 if (chvno == 3)
2043 app->did_chv3 = 0;
2044 else
2045 app->did_chv1 = app->did_chv2 = 0;
2047 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2048 keep it at the start of the string. We need this elsewhere
2049 to get some infos on the string. */
2050 rc = pincb (pincb_arg,
2051 set_resetcode? _("|RN|New Reset Code") :
2052 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2053 &pinvalue);
2054 if (rc)
2056 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2057 goto leave;
2061 if (resetcode)
2063 char *buffer;
2065 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2066 if (!buffer)
2067 rc = gpg_error_from_syserror ();
2068 else
2070 strcpy (stpcpy (buffer, resetcode), pinvalue);
2071 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2072 buffer, strlen (buffer));
2073 wipememory (buffer, strlen (buffer));
2074 xfree (buffer);
2077 else if (set_resetcode)
2079 if (strlen (pinvalue) < 8)
2081 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2082 rc = gpg_error (GPG_ERR_BAD_PIN);
2084 else
2085 rc = iso7816_put_data (app->slot, 0, 0xD3,
2086 pinvalue, strlen (pinvalue));
2088 else if (reset_mode)
2090 rc = iso7816_reset_retry_counter (app->slot, 0x81,
2091 pinvalue, strlen (pinvalue));
2092 if (!rc && !app->app_local->extcap.is_v2)
2093 rc = iso7816_reset_retry_counter (app->slot, 0x82,
2094 pinvalue, strlen (pinvalue));
2096 else if (!app->app_local->extcap.is_v2)
2098 /* Version 1 cards. */
2099 if (chvno == 1 || chvno == 2)
2101 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2102 pinvalue, strlen (pinvalue));
2103 if (!rc)
2104 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2105 pinvalue, strlen (pinvalue));
2107 else /* CHVNO == 3 */
2109 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2110 pinvalue, strlen (pinvalue));
2113 else
2115 /* Version 2 cards. */
2116 assert (chvno == 1 || chvno == 3);
2118 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2119 oldpinvalue, strlen (oldpinvalue),
2120 pinvalue, strlen (pinvalue));
2123 if (pinvalue)
2125 wipememory (pinvalue, strlen (pinvalue));
2126 xfree (pinvalue);
2128 if (rc)
2129 flush_cache_after_error (app);
2131 leave:
2132 if (resetcode)
2134 wipememory (resetcode, strlen (resetcode));
2135 xfree (resetcode);
2137 if (oldpinvalue)
2139 wipememory (oldpinvalue, strlen (oldpinvalue));
2140 xfree (oldpinvalue);
2142 return rc;
2146 /* Check whether a key already exists. KEYIDX is the index of the key
2147 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2148 error returned if the key already exists. The flag GENERATING is
2149 only used to print correct messages. */
2150 static gpg_error_t
2151 does_key_exist (app_t app, int keyidx, int generating, int force)
2153 const unsigned char *fpr;
2154 unsigned char *buffer;
2155 size_t buflen, n;
2156 int i;
2158 assert (keyidx >=0 && keyidx <= 2);
2160 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2162 log_error (_("error reading application data\n"));
2163 return gpg_error (GPG_ERR_GENERAL);
2165 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2166 if (!fpr || n < 60)
2168 log_error (_("error reading fingerprint DO\n"));
2169 xfree (buffer);
2170 return gpg_error (GPG_ERR_GENERAL);
2172 fpr += 20*keyidx;
2173 for (i=0; i < 20 && !fpr[i]; i++)
2175 xfree (buffer);
2176 if (i!=20 && !force)
2178 log_error (_("key already exists\n"));
2179 return gpg_error (GPG_ERR_EEXIST);
2181 else if (i!=20)
2182 log_info (_("existing key will be replaced\n"));
2183 else if (generating)
2184 log_info (_("generating new key\n"));
2185 else
2186 log_info (_("writing new key\n"));
2187 return 0;
2191 /* Create a TLV tag and value and store it at BUFFER. Return the length
2192 of tag and length. A LENGTH greater than 65535 is truncated. */
2193 static size_t
2194 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2196 unsigned char *p = buffer;
2198 assert (tag <= 0xffff);
2199 if ( tag > 0xff )
2200 *p++ = tag >> 8;
2201 *p++ = tag;
2202 if (length < 128)
2203 *p++ = length;
2204 else if (length < 256)
2206 *p++ = 0x81;
2207 *p++ = length;
2209 else
2211 if (length > 0xffff)
2212 length = 0xffff;
2213 *p++ = 0x82;
2214 *p++ = length >> 8;
2215 *p++ = length;
2218 return p - buffer;
2222 /* Build the private key template as specified in the OpenPGP specs
2223 v2.0 section 4.3.3.7. */
2224 static gpg_error_t
2225 build_privkey_template (app_t app, int keyno,
2226 const unsigned char *rsa_n, size_t rsa_n_len,
2227 const unsigned char *rsa_e, size_t rsa_e_len,
2228 const unsigned char *rsa_p, size_t rsa_p_len,
2229 const unsigned char *rsa_q, size_t rsa_q_len,
2230 unsigned char **result, size_t *resultlen)
2232 size_t rsa_e_reqlen;
2233 unsigned char privkey[7*(1+3)];
2234 size_t privkey_len;
2235 unsigned char exthdr[2+2+3];
2236 size_t exthdr_len;
2237 unsigned char suffix[2+3];
2238 size_t suffix_len;
2239 unsigned char *tp;
2240 size_t datalen;
2241 unsigned char *template;
2242 size_t template_size;
2244 *result = NULL;
2245 *resultlen = 0;
2247 switch (app->app_local->keyattr[keyno].format)
2249 case RSA_STD:
2250 case RSA_STD_N:
2251 break;
2252 case RSA_CRT:
2253 case RSA_CRT_N:
2254 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2256 default:
2257 return gpg_error (GPG_ERR_INV_VALUE);
2260 /* Get the required length for E. */
2261 rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2262 assert (rsa_e_len <= rsa_e_reqlen);
2264 /* Build the 7f48 cardholder private key template. */
2265 datalen = 0;
2266 tp = privkey;
2268 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2269 datalen += rsa_e_reqlen;
2271 tp += add_tlv (tp, 0x92, rsa_p_len);
2272 datalen += rsa_p_len;
2274 tp += add_tlv (tp, 0x93, rsa_q_len);
2275 datalen += rsa_q_len;
2277 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2278 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2280 tp += add_tlv (tp, 0x97, rsa_n_len);
2281 datalen += rsa_n_len;
2283 privkey_len = tp - privkey;
2285 /* Build the extended header list without the private key template. */
2286 tp = exthdr;
2287 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2288 *tp++ = 0;
2289 tp += add_tlv (tp, 0x7f48, privkey_len);
2290 exthdr_len = tp - exthdr;
2292 /* Build the 5f48 suffix of the data. */
2293 tp = suffix;
2294 tp += add_tlv (tp, 0x5f48, datalen);
2295 suffix_len = tp - suffix;
2297 /* Now concatenate everything. */
2298 template_size = (1 + 3 /* 0x4d and len. */
2299 + exthdr_len
2300 + privkey_len
2301 + suffix_len
2302 + datalen);
2303 tp = template = xtrymalloc_secure (template_size);
2304 if (!template)
2305 return gpg_error_from_syserror ();
2307 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2308 memcpy (tp, exthdr, exthdr_len);
2309 tp += exthdr_len;
2310 memcpy (tp, privkey, privkey_len);
2311 tp += privkey_len;
2312 memcpy (tp, suffix, suffix_len);
2313 tp += suffix_len;
2315 memcpy (tp, rsa_e, rsa_e_len);
2316 if (rsa_e_len < rsa_e_reqlen)
2318 /* Right justify E. */
2319 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2320 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2322 tp += rsa_e_reqlen;
2324 memcpy (tp, rsa_p, rsa_p_len);
2325 tp += rsa_p_len;
2327 memcpy (tp, rsa_q, rsa_q_len);
2328 tp += rsa_q_len;
2330 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2331 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2333 memcpy (tp, rsa_n, rsa_n_len);
2334 tp += rsa_n_len;
2337 /* Sanity check. We don't know the exact length because we
2338 allocated 3 bytes for the first length header. */
2339 assert (tp - template <= template_size);
2341 *result = template;
2342 *resultlen = tp - template;
2343 return 0;
2347 /* Helper for do_writekley to change the size of a key. Not ethat
2348 this deletes the entire key without asking. */
2349 static gpg_error_t
2350 change_keyattr (app_t app, int keyno, unsigned int nbits,
2351 gpg_error_t (*pincb)(void*, const char *, char **),
2352 void *pincb_arg)
2354 gpg_error_t err;
2355 unsigned char *buffer;
2356 size_t buflen;
2357 void *relptr;
2359 assert (keyno >=0 && keyno <= 2);
2361 if (nbits > 3072)
2362 return gpg_error (GPG_ERR_TOO_LARGE);
2364 /* Read the current attributes into a buffer. */
2365 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
2366 if (!relptr)
2367 return gpg_error (GPG_ERR_CARD);
2368 if (buflen < 6 || buffer[0] != 1)
2370 /* Attriutes too short or not an RSA key. */
2371 xfree (relptr);
2372 return gpg_error (GPG_ERR_CARD);
2375 /* We only change n_bits and don't touch anything else. Before we
2376 do so, we round up NBITS to a sensible way in the same way as
2377 gpg's key generation does it. This may help to sort out problems
2378 with a few bits too short keys. */
2379 nbits = ((nbits + 31) / 32) * 32;
2380 buffer[1] = (nbits >> 8);
2381 buffer[2] = nbits;
2383 /* Prepare for storing the key. */
2384 err = verify_chv3 (app, pincb, pincb_arg);
2385 if (err)
2387 xfree (relptr);
2388 return err;
2391 /* Change the attribute. */
2392 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
2393 xfree (relptr);
2394 if (err)
2395 log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
2396 else
2397 log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
2398 flush_cache (app);
2399 parse_algorithm_attribute (app, keyno);
2400 app->did_chv1 = 0;
2401 app->did_chv2 = 0;
2402 app->did_chv3 = 0;
2403 return err;
2408 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2409 canonical encoded S-expression with the secret key in KEYDATA and
2410 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2411 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2412 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2413 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2414 the pinentry callback. */
2415 static gpg_error_t
2416 do_writekey (app_t app, ctrl_t ctrl,
2417 const char *keyid, unsigned int flags,
2418 gpg_error_t (*pincb)(void*, const char *, char **),
2419 void *pincb_arg,
2420 const unsigned char *keydata, size_t keydatalen)
2422 gpg_error_t err;
2423 int force = (flags & 1);
2424 int keyno;
2425 const unsigned char *buf, *tok;
2426 size_t buflen, toklen;
2427 int depth, last_depth1, last_depth2;
2428 const unsigned char *rsa_n = NULL;
2429 const unsigned char *rsa_e = NULL;
2430 const unsigned char *rsa_p = NULL;
2431 const unsigned char *rsa_q = NULL;
2432 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2433 unsigned int nbits;
2434 unsigned int maxbits;
2435 unsigned char *template = NULL;
2436 unsigned char *tp;
2437 size_t template_len;
2438 unsigned char fprbuf[20];
2439 u32 created_at = 0;
2441 (void)ctrl;
2443 if (!strcmp (keyid, "OPENPGP.1"))
2444 keyno = 0;
2445 else if (!strcmp (keyid, "OPENPGP.2"))
2446 keyno = 1;
2447 else if (!strcmp (keyid, "OPENPGP.3"))
2448 keyno = 2;
2449 else
2450 return gpg_error (GPG_ERR_INV_ID);
2452 err = does_key_exist (app, keyno, 0, force);
2453 if (err)
2454 return err;
2458 Parse the S-expression
2460 buf = keydata;
2461 buflen = keydatalen;
2462 depth = 0;
2463 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2464 goto leave;
2465 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2466 goto leave;
2467 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2469 if (!tok)
2471 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2472 log_info ("protected-private-key passed to writekey\n");
2473 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2474 log_info ("shadowed-private-key passed to writekey\n");
2475 err = gpg_error (GPG_ERR_BAD_SECKEY);
2476 goto leave;
2478 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2479 goto leave;
2480 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2481 goto leave;
2482 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2484 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2485 goto leave;
2487 last_depth1 = depth;
2488 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2489 && depth && depth >= last_depth1)
2491 if (tok)
2493 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2494 goto leave;
2496 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2497 goto leave;
2498 if (tok && toklen == 1)
2500 const unsigned char **mpi;
2501 size_t *mpi_len;
2503 switch (*tok)
2505 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2506 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2507 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2508 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2509 default: mpi = NULL; mpi_len = NULL; break;
2511 if (mpi && *mpi)
2513 err = gpg_error (GPG_ERR_DUP_VALUE);
2514 goto leave;
2516 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2517 goto leave;
2518 if (tok && mpi)
2520 /* Strip off leading zero bytes and save. */
2521 for (;toklen && !*tok; toklen--, tok++)
2523 *mpi = tok;
2524 *mpi_len = toklen;
2527 /* Skip until end of list. */
2528 last_depth2 = depth;
2529 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2530 && depth && depth >= last_depth2)
2532 if (err)
2533 goto leave;
2535 /* Parse other attributes. */
2536 last_depth1 = depth;
2537 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2538 && depth && depth >= last_depth1)
2540 if (tok)
2542 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2543 goto leave;
2545 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2546 goto leave;
2547 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2549 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2550 goto leave;
2551 if (tok)
2553 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2554 tok++, toklen--)
2555 created_at = created_at*10 + (*tok - '0');
2558 /* Skip until end of list. */
2559 last_depth2 = depth;
2560 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2561 && depth && depth >= last_depth2)
2563 if (err)
2564 goto leave;
2568 /* Check that we have all parameters and that they match the card
2569 description. */
2570 if (!created_at)
2572 log_error (_("creation timestamp missing\n"));
2573 err = gpg_error (GPG_ERR_INV_VALUE);
2574 goto leave;
2577 maxbits = app->app_local->keyattr[keyno].n_bits;
2578 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2579 if (opt.verbose)
2580 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2581 nbits, (unsigned int)rsa_n_len);
2582 if (nbits && nbits != maxbits
2583 && app->app_local->extcap.algo_attr_change)
2585 /* Try to switch the key to a new length. */
2586 err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2587 if (!err)
2588 maxbits = app->app_local->keyattr[keyno].n_bits;
2590 if (nbits != maxbits)
2592 log_error (_("RSA modulus missing or not of size %d bits\n"),
2593 (int)maxbits);
2594 err = gpg_error (GPG_ERR_BAD_SECKEY);
2595 goto leave;
2598 maxbits = app->app_local->keyattr[keyno].e_bits;
2599 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2600 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2601 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2602 if (nbits < 2 || nbits > maxbits)
2604 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2605 (int)maxbits);
2606 err = gpg_error (GPG_ERR_BAD_SECKEY);
2607 goto leave;
2610 maxbits = app->app_local->keyattr[keyno].n_bits/2;
2611 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2612 if (nbits != maxbits)
2614 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2615 "P", (int)maxbits);
2616 err = gpg_error (GPG_ERR_BAD_SECKEY);
2617 goto leave;
2619 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2620 if (nbits != maxbits)
2622 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2623 "Q", (int)maxbits);
2624 err = gpg_error (GPG_ERR_BAD_SECKEY);
2625 goto leave;
2628 /* We need to remove the cached public key. */
2629 xfree (app->app_local->pk[keyno].key);
2630 app->app_local->pk[keyno].key = NULL;
2631 app->app_local->pk[keyno].keylen = 0;
2632 app->app_local->pk[keyno].read_done = 0;
2635 if (app->app_local->extcap.is_v2)
2637 /* Build the private key template as described in section 4.3.3.7 of
2638 the OpenPGP card specs version 2.0. */
2639 int exmode;
2641 err = build_privkey_template (app, keyno,
2642 rsa_n, rsa_n_len,
2643 rsa_e, rsa_e_len,
2644 rsa_p, rsa_p_len,
2645 rsa_q, rsa_q_len,
2646 &template, &template_len);
2647 if (err)
2648 goto leave;
2650 /* Prepare for storing the key. */
2651 err = verify_chv3 (app, pincb, pincb_arg);
2652 if (err)
2653 goto leave;
2655 /* Store the key. */
2656 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2657 exmode = 1; /* Use extended length w/o a limit. */
2658 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2659 exmode = -254;
2660 else
2661 exmode = 0;
2662 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2663 template, template_len);
2665 else
2667 /* Build the private key template as described in section 4.3.3.6 of
2668 the OpenPGP card specs version 1.1:
2669 0xC0 <length> public exponent
2670 0xC1 <length> prime p
2671 0xC2 <length> prime q
2673 assert (rsa_e_len <= 4);
2674 template_len = (1 + 1 + 4
2675 + 1 + 1 + rsa_p_len
2676 + 1 + 1 + rsa_q_len);
2677 template = tp = xtrymalloc_secure (template_len);
2678 if (!template)
2680 err = gpg_error_from_syserror ();
2681 goto leave;
2683 *tp++ = 0xC0;
2684 *tp++ = 4;
2685 memcpy (tp, rsa_e, rsa_e_len);
2686 if (rsa_e_len < 4)
2688 /* Right justify E. */
2689 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2690 memset (tp, 0, 4-rsa_e_len);
2692 tp += 4;
2694 *tp++ = 0xC1;
2695 *tp++ = rsa_p_len;
2696 memcpy (tp, rsa_p, rsa_p_len);
2697 tp += rsa_p_len;
2699 *tp++ = 0xC2;
2700 *tp++ = rsa_q_len;
2701 memcpy (tp, rsa_q, rsa_q_len);
2702 tp += rsa_q_len;
2704 assert (tp - template == template_len);
2706 /* Prepare for storing the key. */
2707 err = verify_chv3 (app, pincb, pincb_arg);
2708 if (err)
2709 goto leave;
2711 /* Store the key. */
2712 err = iso7816_put_data (app->slot, 0,
2713 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2714 template, template_len);
2716 if (err)
2718 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2719 goto leave;
2722 err = store_fpr (app, keyno, created_at,
2723 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2724 fprbuf, app->card_version);
2725 if (err)
2726 goto leave;
2729 leave:
2730 xfree (template);
2731 return err;
2735 /* Handle the GENKEY command. */
2736 static gpg_error_t
2737 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
2738 time_t createtime,
2739 gpg_error_t (*pincb)(void*, const char *, char **),
2740 void *pincb_arg)
2742 int rc;
2743 char numbuf[30];
2744 unsigned char fprbuf[20];
2745 const unsigned char *keydata, *m, *e;
2746 unsigned char *buffer = NULL;
2747 size_t buflen, keydatalen, mlen, elen;
2748 time_t created_at;
2749 int keyno = atoi (keynostr);
2750 int force = (flags & 1);
2751 time_t start_at;
2752 int exmode;
2753 int le_value;
2754 unsigned int keybits;
2756 if (keyno < 1 || keyno > 3)
2757 return gpg_error (GPG_ERR_INV_ID);
2758 keyno--;
2760 /* We flush the cache to increase the traffic before a key
2761 generation. This _might_ help a card to gather more entropy. */
2762 flush_cache (app);
2764 /* Obviously we need to remove the cached public key. */
2765 xfree (app->app_local->pk[keyno].key);
2766 app->app_local->pk[keyno].key = NULL;
2767 app->app_local->pk[keyno].keylen = 0;
2768 app->app_local->pk[keyno].read_done = 0;
2770 /* Check whether a key already exists. */
2771 rc = does_key_exist (app, keyno, 1, force);
2772 if (rc)
2773 return rc;
2775 /* Because we send the key parameter back via status lines we need
2776 to put a limit on the max. allowed keysize. 2048 bit will
2777 already lead to a 527 byte long status line and thus a 4096 bit
2778 key would exceed the Assuan line length limit. */
2779 keybits = app->app_local->keyattr[keyno].n_bits;
2780 if (keybits > 3072)
2781 return gpg_error (GPG_ERR_TOO_LARGE);
2783 /* Prepare for key generation by verifying the Admin PIN. */
2784 rc = verify_chv3 (app, pincb, pincb_arg);
2785 if (rc)
2786 goto leave;
2788 /* Test whether we will need extended length mode. (1900 is an
2789 arbitrary length which for sure fits into a short apdu.) */
2790 if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
2792 exmode = 1; /* Use extended length w/o a limit. */
2793 le_value = app->app_local->extcap.max_rsp_data;
2794 /* No need to check le_value because it comes from a 16 bit
2795 value and thus can't create an overflow on a 32 bit
2796 system. */
2798 else
2800 exmode = 0;
2801 le_value = 256; /* Use legacy value. */
2804 log_info (_("please wait while key is being generated ...\n"));
2805 start_at = time (NULL);
2806 rc = iso7816_generate_keypair
2807 /* # warning key generation temporary replaced by reading an existing key. */
2808 /* rc = iso7816_read_public_key */
2809 (app->slot, exmode,
2810 (const unsigned char*)(keyno == 0? "\xB6" :
2811 keyno == 1? "\xB8" : "\xA4"), 2,
2812 le_value,
2813 &buffer, &buflen);
2814 if (rc)
2816 rc = gpg_error (GPG_ERR_CARD);
2817 log_error (_("generating key failed\n"));
2818 goto leave;
2820 log_info (_("key generation completed (%d seconds)\n"),
2821 (int)(time (NULL) - start_at));
2823 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2824 if (!keydata)
2826 rc = gpg_error (GPG_ERR_CARD);
2827 log_error (_("response does not contain the public key data\n"));
2828 goto leave;
2831 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2832 if (!m)
2834 rc = gpg_error (GPG_ERR_CARD);
2835 log_error (_("response does not contain the RSA modulus\n"));
2836 goto leave;
2838 /* log_printhex ("RSA n:", m, mlen); */
2839 send_key_data (ctrl, "n", m, mlen);
2841 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2842 if (!e)
2844 rc = gpg_error (GPG_ERR_CARD);
2845 log_error (_("response does not contain the RSA public exponent\n"));
2846 goto leave;
2848 /* log_printhex ("RSA e:", e, elen); */
2849 send_key_data (ctrl, "e", e, elen);
2851 created_at = createtime? createtime : gnupg_get_time ();
2852 sprintf (numbuf, "%lu", (unsigned long)created_at);
2853 send_status_info (ctrl, "KEY-CREATED-AT",
2854 numbuf, (size_t)strlen(numbuf), NULL, 0);
2856 rc = store_fpr (app, keyno, (u32)created_at,
2857 m, mlen, e, elen, fprbuf, app->card_version);
2858 if (rc)
2859 goto leave;
2860 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2863 leave:
2864 xfree (buffer);
2865 return rc;
2869 static unsigned long
2870 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2872 unsigned long ul;
2874 if (valuelen == 3 )
2875 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2876 else
2878 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2879 ul = 0;
2881 return ul;
2884 static unsigned long
2885 get_sig_counter (app_t app)
2887 void *relptr;
2888 unsigned char *value;
2889 size_t valuelen;
2890 unsigned long ul;
2892 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2893 if (!relptr)
2894 return 0;
2895 ul = convert_sig_counter_value (value, valuelen);
2896 xfree (relptr);
2897 return ul;
2900 static gpg_error_t
2901 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2903 const unsigned char *fpr;
2904 unsigned char *buffer;
2905 size_t buflen, n;
2906 int rc, i;
2908 assert (keyno >= 1 && keyno <= 3);
2910 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
2911 if (rc)
2913 log_error (_("error reading application data\n"));
2914 return gpg_error (GPG_ERR_GENERAL);
2916 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2917 if (!fpr || n != 60)
2919 xfree (buffer);
2920 log_error (_("error reading fingerprint DO\n"));
2921 return gpg_error (GPG_ERR_GENERAL);
2923 fpr += (keyno-1)*20;
2924 for (i=0; i < 20; i++)
2925 if (sha1fpr[i] != fpr[i])
2927 xfree (buffer);
2928 log_info (_("fingerprint on card does not match requested one\n"));
2929 return gpg_error (GPG_ERR_WRONG_SECKEY);
2931 xfree (buffer);
2932 return 0;
2936 /* If a fingerprint has been specified check it against the one on the
2937 card. This allows for a meaningful error message in case the key
2938 on the card has been replaced but the shadow information known to
2939 gpg has not been updated. If there is no fingerprint we assume
2940 that this is okay. */
2941 static gpg_error_t
2942 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2944 unsigned char tmp[20];
2945 const char *s;
2946 int n;
2948 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2950 if (n != 40)
2951 return gpg_error (GPG_ERR_INV_ID);
2952 else if (!*s)
2953 ; /* okay */
2954 else
2955 return gpg_error (GPG_ERR_INV_ID);
2957 for (s=fpr, n=0; n < 20; s += 2, n++)
2958 tmp[n] = xtoi_2 (s);
2959 return compare_fingerprint (app, keyno, tmp);
2964 /* Compute a digital signature on INDATA which is expected to be the
2965 raw message digest. For this application the KEYIDSTR consists of
2966 the serialnumber and the fingerprint delimited by a slash.
2968 Note that this function may return the error code
2969 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2970 not match the one required for the requested action (e.g. the
2971 serial number does not match).
2973 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2974 operation to the auth command.
2976 static gpg_error_t
2977 do_sign (app_t app, const char *keyidstr, int hashalgo,
2978 gpg_error_t (*pincb)(void*, const char *, char **),
2979 void *pincb_arg,
2980 const void *indata, size_t indatalen,
2981 unsigned char **outdata, size_t *outdatalen )
2983 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2984 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2985 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2986 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
2987 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2988 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2989 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
2990 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2991 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2992 0x1C };
2993 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
2994 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2995 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2996 0x00, 0x04, 0x20 };
2997 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
2998 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2999 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3000 0x00, 0x04, 0x30 };
3001 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3002 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3003 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3004 0x00, 0x04, 0x40 };
3005 int rc;
3006 unsigned char data[19+64];
3007 size_t datalen;
3008 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3009 const char *s;
3010 int n;
3011 const char *fpr = NULL;
3012 unsigned long sigcount;
3013 int use_auth = 0;
3014 int exmode, le_value;
3016 if (!keyidstr || !*keyidstr)
3017 return gpg_error (GPG_ERR_INV_VALUE);
3019 /* Strip off known prefixes. */
3020 #define X(a,b,c,d) \
3021 if (hashalgo == GCRY_MD_ ## a \
3022 && (d) \
3023 && indatalen == sizeof b ## _prefix + (c) \
3024 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3026 indata = (const char*)indata + sizeof b ## _prefix; \
3027 indatalen -= sizeof b ## _prefix; \
3030 if (indatalen == 20)
3031 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3032 else X(SHA1, sha1, 20, 1)
3033 else X(RMD160, rmd160, 20, 1)
3034 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3035 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3036 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3037 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3038 else if ((indatalen == 28 || indatalen == 32
3039 || indatalen == 48 || indatalen ==64)
3040 && app->app_local->extcap.is_v2)
3041 ; /* Assume a plain SHA-3 digest has been given. */
3042 else
3044 log_error (_("card does not support digest algorithm %s\n"),
3045 gcry_md_algo_name (hashalgo));
3046 /* Or the supplied digest length does not match an algorithm. */
3047 return gpg_error (GPG_ERR_INV_VALUE);
3049 #undef X
3051 /* Check whether an OpenPGP card of any version has been requested. */
3052 if (!strcmp (keyidstr, "OPENPGP.1"))
3054 else if (!strcmp (keyidstr, "OPENPGP.3"))
3055 use_auth = 1;
3056 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3057 return gpg_error (GPG_ERR_INV_ID);
3058 else
3060 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3062 if (n != 32)
3063 return gpg_error (GPG_ERR_INV_ID);
3064 else if (!*s)
3065 ; /* no fingerprint given: we allow this for now. */
3066 else if (*s == '/')
3067 fpr = s + 1;
3068 else
3069 return gpg_error (GPG_ERR_INV_ID);
3071 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3072 tmp_sn[n] = xtoi_2 (s);
3074 if (app->serialnolen != 16)
3075 return gpg_error (GPG_ERR_INV_CARD);
3076 if (memcmp (app->serialno, tmp_sn, 16))
3077 return gpg_error (GPG_ERR_WRONG_CARD);
3080 /* If a fingerprint has been specified check it against the one on
3081 the card. This is allows for a meaningful error message in case
3082 the key on the card has been replaced but the shadow information
3083 known to gpg was not updated. If there is no fingerprint, gpg
3084 will detect a bogus signature anyway due to the
3085 verify-after-signing feature. */
3086 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3087 if (rc)
3088 return rc;
3090 /* Concatenate prefix and digest. */
3091 #define X(a,b,d) \
3092 if (hashalgo == GCRY_MD_ ## a && (d) ) \
3094 datalen = sizeof b ## _prefix + indatalen; \
3095 assert (datalen <= sizeof data); \
3096 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3097 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3100 X(SHA1, sha1, 1)
3101 else X(RMD160, rmd160, 1)
3102 else X(SHA224, sha224, app->app_local->extcap.is_v2)
3103 else X(SHA256, sha256, app->app_local->extcap.is_v2)
3104 else X(SHA384, sha384, app->app_local->extcap.is_v2)
3105 else X(SHA512, sha512, app->app_local->extcap.is_v2)
3106 else
3107 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3108 #undef X
3110 /* Redirect to the AUTH command if asked to. */
3111 if (use_auth)
3113 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3114 data, datalen,
3115 outdata, outdatalen);
3118 /* Show the number of signature done using this key. */
3119 sigcount = get_sig_counter (app);
3120 log_info (_("signatures created so far: %lu\n"), sigcount);
3122 /* Check CHV if needed. */
3123 if (!app->did_chv1 || app->force_chv1 )
3125 char *pinvalue;
3127 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3128 if (rc)
3129 return rc;
3131 app->did_chv1 = 1;
3133 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3134 sync, thus we verify CHV2 here using the given PIN. Cards
3135 with version2 to not have the need for a separate CHV2 and
3136 internally use just one. Obviously we can't do that if the
3137 keypad has been used. */
3138 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3140 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3141 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3142 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3143 if (rc)
3145 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3146 xfree (pinvalue);
3147 flush_cache_after_error (app);
3148 return rc;
3150 app->did_chv2 = 1;
3152 xfree (pinvalue);
3156 if (app->app_local->cardcap.ext_lc_le)
3158 exmode = 1; /* Use extended length. */
3159 le_value = app->app_local->extcap.max_rsp_data;
3161 else
3163 exmode = 0;
3164 le_value = 0;
3166 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3167 outdata, outdatalen);
3168 return rc;
3171 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3172 on INDATA which is expected to be the raw message digest. For this
3173 application the KEYIDSTR consists of the serialnumber and the
3174 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3175 be given.
3177 Note that this function may return the error code
3178 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3179 not match the one required for the requested action (e.g. the
3180 serial number does not match). */
3181 static gpg_error_t
3182 do_auth (app_t app, const char *keyidstr,
3183 gpg_error_t (*pincb)(void*, const char *, char **),
3184 void *pincb_arg,
3185 const void *indata, size_t indatalen,
3186 unsigned char **outdata, size_t *outdatalen )
3188 int rc;
3189 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3190 const char *s;
3191 int n;
3192 const char *fpr = NULL;
3194 if (!keyidstr || !*keyidstr)
3195 return gpg_error (GPG_ERR_INV_VALUE);
3196 if (indatalen > 101) /* For a 2048 bit key. */
3197 return gpg_error (GPG_ERR_INV_VALUE);
3199 /* Check whether an OpenPGP card of any version has been requested. */
3200 if (!strcmp (keyidstr, "OPENPGP.3"))
3202 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3203 return gpg_error (GPG_ERR_INV_ID);
3204 else
3206 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3208 if (n != 32)
3209 return gpg_error (GPG_ERR_INV_ID);
3210 else if (!*s)
3211 ; /* no fingerprint given: we allow this for now. */
3212 else if (*s == '/')
3213 fpr = s + 1;
3214 else
3215 return gpg_error (GPG_ERR_INV_ID);
3217 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3218 tmp_sn[n] = xtoi_2 (s);
3220 if (app->serialnolen != 16)
3221 return gpg_error (GPG_ERR_INV_CARD);
3222 if (memcmp (app->serialno, tmp_sn, 16))
3223 return gpg_error (GPG_ERR_WRONG_CARD);
3226 /* If a fingerprint has been specified check it against the one on
3227 the card. This is allows for a meaningful error message in case
3228 the key on the card has been replaced but the shadow information
3229 known to gpg was not updated. If there is no fingerprint, gpg
3230 will detect a bogus signature anyway due to the
3231 verify-after-signing feature. */
3232 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3233 if (rc)
3234 return rc;
3236 rc = verify_chv2 (app, pincb, pincb_arg);
3237 if (!rc)
3239 int exmode, le_value;
3241 if (app->app_local->cardcap.ext_lc_le)
3243 exmode = 1; /* Use extended length. */
3244 le_value = app->app_local->extcap.max_rsp_data;
3246 else
3248 exmode = 0;
3249 le_value = 0;
3251 rc = iso7816_internal_authenticate (app->slot, exmode,
3252 indata, indatalen, le_value,
3253 outdata, outdatalen);
3255 return rc;
3259 static gpg_error_t
3260 do_decipher (app_t app, const char *keyidstr,
3261 gpg_error_t (*pincb)(void*, const char *, char **),
3262 void *pincb_arg,
3263 const void *indata, size_t indatalen,
3264 unsigned char **outdata, size_t *outdatalen )
3266 int rc;
3267 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3268 const char *s;
3269 int n;
3270 const char *fpr = NULL;
3271 int exmode;
3273 if (!keyidstr || !*keyidstr || !indatalen)
3274 return gpg_error (GPG_ERR_INV_VALUE);
3276 /* Check whether an OpenPGP card of any version has been requested. */
3277 if (!strcmp (keyidstr, "OPENPGP.2"))
3279 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3280 return gpg_error (GPG_ERR_INV_ID);
3281 else
3283 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3285 if (n != 32)
3286 return gpg_error (GPG_ERR_INV_ID);
3287 else if (!*s)
3288 ; /* no fingerprint given: we allow this for now. */
3289 else if (*s == '/')
3290 fpr = s + 1;
3291 else
3292 return gpg_error (GPG_ERR_INV_ID);
3294 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3295 tmp_sn[n] = xtoi_2 (s);
3297 if (app->serialnolen != 16)
3298 return gpg_error (GPG_ERR_INV_CARD);
3299 if (memcmp (app->serialno, tmp_sn, 16))
3300 return gpg_error (GPG_ERR_WRONG_CARD);
3303 /* If a fingerprint has been specified check it against the one on
3304 the card. This is allows for a meaningful error message in case
3305 the key on the card has been replaced but the shadow information
3306 known to gpg was not updated. If there is no fingerprint, the
3307 decryption won't produce the right plaintext anyway. */
3308 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3309 if (rc)
3310 return rc;
3312 rc = verify_chv2 (app, pincb, pincb_arg);
3313 if (!rc)
3315 size_t fixuplen;
3316 unsigned char *fixbuf = NULL;
3317 int padind = 0;
3319 /* We might encounter a couple of leading zeroes in the
3320 cryptogram. Due to internal use of MPIs thease leading
3321 zeroes are stripped. However the OpenPGP card expects
3322 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3323 need to fix it up. We do this for up to 16 leading zero
3324 bytes; a cryptogram with more than this is with a very high
3325 probability anyway broken. */
3326 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
3327 fixuplen = 128 - indatalen;
3328 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
3329 fixuplen = 192 - indatalen;
3330 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
3331 fixuplen = 256 - indatalen;
3332 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
3333 fixuplen = 384 - indatalen;
3334 else
3335 fixuplen = 0;
3337 if (fixuplen)
3339 /* While we have to prepend stuff anyway, we can also
3340 include the padding byte here so that iso1816_decipher
3341 does not need to do another data mangling. */
3342 fixuplen++;
3344 fixbuf = xtrymalloc (fixuplen + indatalen);
3345 if (!fixbuf)
3346 return gpg_error_from_syserror ();
3348 memset (fixbuf, 0, fixuplen);
3349 memcpy (fixbuf+fixuplen, indata, indatalen);
3350 indata = fixbuf;
3351 indatalen = fixuplen + indatalen;
3352 padind = -1; /* Already padded. */
3355 if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
3356 exmode = 1; /* Extended length w/o a limit. */
3357 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
3358 exmode = -254; /* Command chaining with max. 254 bytes. */
3359 else
3360 exmode = 0;
3362 rc = iso7816_decipher (app->slot, exmode,
3363 indata, indatalen, padind,
3364 outdata, outdatalen);
3365 xfree (fixbuf);
3368 return rc;
3372 /* Perform a simple verify operation for CHV1 and CHV2, so that
3373 further operations won't ask for CHV2 and it is possible to do a
3374 cheap check on the PIN: If there is something wrong with the PIN
3375 entry system, only the regular CHV will get blocked and not the
3376 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3377 optional fingerprint part will be ignored.
3379 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3380 the "[CHV3]" being a literal string: The Admin Pin is checked if
3381 and only if the retry counter is still at 3. */
3382 static gpg_error_t
3383 do_check_pin (app_t app, const char *keyidstr,
3384 gpg_error_t (*pincb)(void*, const char *, char **),
3385 void *pincb_arg)
3387 unsigned char tmp_sn[20];
3388 const char *s;
3389 int n;
3390 int admin_pin = 0;
3392 if (!keyidstr || !*keyidstr)
3393 return gpg_error (GPG_ERR_INV_VALUE);
3395 /* Check whether an OpenPGP card of any version has been requested. */
3396 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3397 return gpg_error (GPG_ERR_INV_ID);
3399 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3401 if (n != 32)
3402 return gpg_error (GPG_ERR_INV_ID);
3403 else if (!*s)
3404 ; /* No fingerprint given: we allow this for now. */
3405 else if (*s == '/')
3406 ; /* We ignore a fingerprint. */
3407 else if (!strcmp (s, "[CHV3]") )
3408 admin_pin = 1;
3409 else
3410 return gpg_error (GPG_ERR_INV_ID);
3412 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3413 tmp_sn[n] = xtoi_2 (s);
3415 if (app->serialnolen != 16)
3416 return gpg_error (GPG_ERR_INV_CARD);
3417 if (memcmp (app->serialno, tmp_sn, 16))
3418 return gpg_error (GPG_ERR_WRONG_CARD);
3420 /* Yes, there is a race conditions: The user might pull the card
3421 right here and we won't notice that. However this is not a
3422 problem and the check above is merely for a graceful failure
3423 between operations. */
3425 if (admin_pin)
3427 void *relptr;
3428 unsigned char *value;
3429 size_t valuelen;
3430 int count;
3432 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3433 if (!relptr || valuelen < 7)
3435 log_error (_("error retrieving CHV status from card\n"));
3436 xfree (relptr);
3437 return gpg_error (GPG_ERR_CARD);
3439 count = value[6];
3440 xfree (relptr);
3442 if (!count)
3444 log_info (_("card is permanently locked!\n"));
3445 return gpg_error (GPG_ERR_BAD_PIN);
3447 else if (value[6] < 3)
3449 log_info (_("verification of Admin PIN is currently prohibited "
3450 "through this command\n"));
3451 return gpg_error (GPG_ERR_GENERAL);
3454 app->did_chv3 = 0; /* Force verification. */
3455 return verify_chv3 (app, pincb, pincb_arg);
3457 else
3458 return verify_chv2 (app, pincb, pincb_arg);
3462 /* Show information about card capabilities. */
3463 static void
3464 show_caps (struct app_local_s *s)
3466 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3467 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3468 if (s->extcap.get_challenge)
3469 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3470 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3471 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3472 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3473 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3474 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3475 if (s->extcap.sm_supported)
3476 log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3477 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3478 log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3479 log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3480 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3481 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3482 log_info ("Status Indicator: %02X\n", s->status_indicator);
3484 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
3485 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
3489 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3490 APPLOC. */
3491 static void
3492 parse_historical (struct app_local_s *apploc,
3493 const unsigned char * buffer, size_t buflen)
3495 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3496 if (buflen < 4)
3498 log_error ("warning: historical bytes are too short\n");
3499 return; /* Too short. */
3501 if (*buffer)
3503 log_error ("warning: bad category indicator in historical bytes\n");
3504 return;
3507 /* Skip category indicator. */
3508 buffer++;
3509 buflen--;
3511 /* Get the status indicator. */
3512 apploc->status_indicator = buffer[buflen-3];
3513 buflen -= 3;
3515 /* Parse the compact TLV. */
3516 while (buflen)
3518 unsigned int tag = (*buffer & 0xf0) >> 4;
3519 unsigned int len = (*buffer & 0x0f);
3520 if (len+1 > buflen)
3522 log_error ("warning: bad Compact-TLV in historical bytes\n");
3523 return; /* Error. */
3525 buffer++;
3526 buflen--;
3527 if (tag == 7 && len == 3)
3529 /* Card capabilities. */
3530 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3531 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
3533 buffer += len;
3534 buflen -= len;
3539 /* Parse and optionally show the algorithm attributes for KEYNO.
3540 KEYNO must be in the range 0..2. */
3541 static void
3542 parse_algorithm_attribute (app_t app, int keyno)
3544 unsigned char *buffer;
3545 size_t buflen;
3546 void *relptr;
3547 const char const desc[3][5] = {"sign", "encr", "auth"};
3549 assert (keyno >=0 && keyno <= 2);
3551 app->app_local->keyattr[keyno].n_bits = 0;
3553 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3554 if (!relptr)
3556 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3557 return;
3559 if (buflen < 1)
3561 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3562 xfree (relptr);
3563 return;
3566 if (opt.verbose)
3567 log_info ("Key-Attr-%s ..: ", desc[keyno]);
3568 if (*buffer == 1 && (buflen == 5 || buflen == 6))
3570 app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3571 app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3572 app->app_local->keyattr[keyno].format = 0;
3573 if (buflen < 6)
3574 app->app_local->keyattr[keyno].format = RSA_STD;
3575 else
3576 app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD :
3577 buffer[5] == 1? RSA_STD_N :
3578 buffer[5] == 2? RSA_CRT :
3579 buffer[5] == 3? RSA_CRT_N :
3580 RSA_UNKNOWN_FMT);
3582 if (opt.verbose)
3583 log_printf
3584 ("RSA, n=%u, e=%u, fmt=%s\n",
3585 app->app_local->keyattr[keyno].n_bits,
3586 app->app_local->keyattr[keyno].e_bits,
3587 app->app_local->keyattr[keyno].format == RSA_STD? "std" :
3588 app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3589 app->app_local->keyattr[keyno].format == RSA_CRT? "crt" :
3590 app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3592 else if (opt.verbose)
3593 log_printhex ("", buffer, buflen);
3595 xfree (relptr);
3598 /* Select the OpenPGP application on the card in SLOT. This function
3599 must be used before any other OpenPGP application functions. */
3600 gpg_error_t
3601 app_select_openpgp (app_t app)
3603 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3604 int slot = app->slot;
3605 int rc;
3606 unsigned char *buffer;
3607 size_t buflen;
3608 void *relptr;
3610 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3611 special flag value. */
3612 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3613 if (!rc)
3615 unsigned int manufacturer;
3617 app->apptype = "OPENPGP";
3619 app->did_chv1 = 0;
3620 app->did_chv2 = 0;
3621 app->did_chv3 = 0;
3622 app->app_local = NULL;
3624 /* The OpenPGP card returns the serial number as part of the
3625 AID; because we prefer to use OpenPGP serial numbers, we
3626 replace a possibly already set one from a EF.GDO with this
3627 one. Note, that for current OpenPGP cards, no EF.GDO exists
3628 and thus it won't matter at all. */
3629 rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
3630 if (rc)
3631 goto leave;
3632 if (opt.verbose)
3634 log_info ("AID: ");
3635 log_printhex ("", buffer, buflen);
3638 app->card_version = buffer[6] << 8;
3639 app->card_version |= buffer[7];
3640 manufacturer = (buffer[8]<<8 | buffer[9]);
3642 xfree (app->serialno);
3643 app->serialno = buffer;
3644 app->serialnolen = buflen;
3645 buffer = NULL;
3646 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3647 if (!app->app_local)
3649 rc = gpg_error (gpg_err_code_from_errno (errno));
3650 goto leave;
3653 if (app->card_version >= 0x0200)
3654 app->app_local->extcap.is_v2 = 1;
3657 /* Read the historical bytes. */
3658 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3659 if (relptr)
3661 if (opt.verbose)
3663 log_info ("Historical Bytes: ");
3664 log_printhex ("", buffer, buflen);
3666 parse_historical (app->app_local, buffer, buflen);
3667 xfree (relptr);
3670 /* Read the force-chv1 flag. */
3671 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3672 if (!relptr)
3674 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3675 "CHV Status Bytes");
3676 goto leave;
3678 app->force_chv1 = (buflen && *buffer == 0);
3679 xfree (relptr);
3681 /* Read the extended capabilities. */
3682 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3683 if (!relptr)
3685 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3686 "Extended Capability Flags" );
3687 goto leave;
3689 if (buflen)
3691 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
3692 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
3693 app->app_local->extcap.key_import = !!(*buffer & 0x20);
3694 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3695 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
3696 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3698 if (buflen >= 10)
3700 /* Available with v2 cards. */
3701 app->app_local->extcap.sm_aes128 = (buffer[1] == 1);
3702 app->app_local->extcap.max_get_challenge
3703 = (buffer[2] << 8 | buffer[3]);
3704 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3705 app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
3706 app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
3708 xfree (relptr);
3710 /* Some of the first cards accidently don't set the
3711 CHANGE_FORCE_CHV bit but allow it anyway. */
3712 if (app->card_version <= 0x0100 && manufacturer == 1)
3713 app->app_local->extcap.change_force_chv = 1;
3715 parse_login_data (app);
3717 if (opt.verbose)
3718 show_caps (app->app_local);
3720 parse_algorithm_attribute (app, 0);
3721 parse_algorithm_attribute (app, 1);
3722 parse_algorithm_attribute (app, 2);
3724 if (opt.verbose > 1)
3725 dump_all_do (slot);
3727 app->fnc.deinit = do_deinit;
3728 app->fnc.learn_status = do_learn_status;
3729 app->fnc.readcert = do_readcert;
3730 app->fnc.readkey = do_readkey;
3731 app->fnc.getattr = do_getattr;
3732 app->fnc.setattr = do_setattr;
3733 app->fnc.writecert = do_writecert;
3734 app->fnc.writekey = do_writekey;
3735 app->fnc.genkey = do_genkey;
3736 app->fnc.sign = do_sign;
3737 app->fnc.auth = do_auth;
3738 app->fnc.decipher = do_decipher;
3739 app->fnc.change_pin = do_change_pin;
3740 app->fnc.check_pin = do_check_pin;
3743 leave:
3744 if (rc)
3745 do_deinit (app);
3746 return rc;