Fixed EOF detection for encrypted packets.
[gnupg.git] / scd / app-openpgp.c
blobd4685916e0bd5bc51f595841bfe077a33530dfd8
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/>.
21 /* Some notes:
23 CHV means Card Holder Verification and is nothing else than a PIN
24 or password. That term seems to have been used originally with GSM
25 cards. Version v2 of the specs changes the term to the clearer
26 term PW for password. We use the terms here interchangeable
27 because we do not want to change existing strings i18n wise.
29 Version 2 of the specs also drops the separate PW2 which was
30 required in v1 due to ISO requirements. It is now possible to have
31 one physical PW but two reference to it so that they can be
32 individually be verified (e.g. to implement a forced verification
33 for one key). Thus you will noticed the use of PW2 with the verify
34 command but not with change_reference_data because the latter
35 operates directly on the physical PW.
37 The Reset Code (RC) as implemented by v2 cards uses the same error
38 counter as the PW2 of v1 cards. By default no RC is set and thus
39 that error counter is set to 0. After setting the RC the error
40 counter will be initialized to 3.
44 #include <config.h>
45 #include <errno.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <assert.h>
50 #include <time.h>
52 #if GNUPG_MAJOR_VERSION == 1
53 /* This is used with GnuPG version < 1.9. The code has been source
54 copied from the current GnuPG >= 1.9 and is maintained over
55 there. */
56 #include "options.h"
57 #include "errors.h"
58 #include "memory.h"
59 #include "util.h"
60 #include "cardglue.h"
61 #else /* GNUPG_MAJOR_VERSION != 1 */
62 #include "scdaemon.h"
63 #endif /* GNUPG_MAJOR_VERSION != 1 */
65 #include "i18n.h"
66 #include "iso7816.h"
67 #include "app-common.h"
68 #include "tlv.h"
71 /* A table describing the DOs of the card. */
72 static struct {
73 int tag;
74 int constructed;
75 int get_from; /* Constructed DO with this DO or 0 for direct access. */
76 int binary:1;
77 int dont_cache:1;
78 int flush_on_error:1;
79 int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
80 this data object if it is used in 1.1
81 and later versions of the card. This
82 does not work with composite DO and
83 is currently only useful for the CHV
84 status bytes. */
85 int try_extlen:1; /* Large object; try to use an extended
86 length APDU. */
87 char *desc;
88 } data_objects[] = {
89 { 0x005E, 0, 0, 1, 0, 0, 0, 0, "Login Data" },
90 { 0x5F50, 0, 0, 0, 0, 0, 0, 0, "URL" },
91 { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
92 { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
93 { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
94 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
95 { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
96 { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
97 { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
98 { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
99 { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
100 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
101 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
102 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
103 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
104 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
105 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
106 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
107 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
108 { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
109 { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
110 { 0x0101, 0, 0, 0, 0, 0, 0, 0, "Private DO 1"},
111 { 0x0102, 0, 0, 0, 0, 0, 0, 0, "Private DO 2"},
112 { 0x0103, 0, 0, 0, 0, 0, 0, 0, "Private DO 3"},
113 { 0x0104, 0, 0, 0, 0, 0, 0, 0, "Private DO 4"},
114 { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
115 { 0 }
119 /* The format of RSA private keys. */
120 typedef enum
122 RSA_UNKNOWN_FMT,
123 RSA_STD,
124 RSA_STD_N,
125 RSA_CRT,
126 RSA_CRT_N
128 rsa_key_format_t;
131 /* One cache item for DOs. */
132 struct cache_s {
133 struct cache_s *next;
134 int tag;
135 size_t length;
136 unsigned char data[1];
140 /* Object with application (i.e. OpenPGP card) specific data. */
141 struct app_local_s {
142 /* A linked list with cached DOs. */
143 struct cache_s *cache;
145 /* Keep track of the public keys. */
146 struct
148 int read_done; /* True if we have at least tried to read them. */
149 unsigned char *key; /* This is a malloced buffer with a canonical
150 encoded S-expression encoding a public
151 key. Might be NULL if key is not
152 available. */
153 size_t keylen; /* The length of the above S-expression. This
154 is usually only required for cross checks
155 because the length of an S-expression is
156 implicitly available. */
157 } pk[3];
159 unsigned char status_indicator; /* The card status indicator. */
161 /* Keep track of the ISO card capabilities. */
162 struct
164 unsigned int cmd_chaining:1; /* Command chaining is supported. */
165 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
166 } cardcap;
168 /* Keep track of extended card capabilities. */
169 struct
171 unsigned int is_v2:1; /* This is a v2.0 compatible card. */
172 unsigned int get_challenge:1;
173 unsigned int key_import:1;
174 unsigned int change_force_chv:1;
175 unsigned int private_dos:1;
176 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
177 unsigned int sm_supported:1; /* Secure Messaging is supported. */
178 unsigned int sm_aes128:1; /* Use AES-128 for SM. */
179 unsigned int max_certlen_3:16;
180 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
181 unsigned int max_cmd_data:16; /* Maximum data size for a command. */
182 unsigned int max_rsp_data:16; /* Maximum size of a response. */
183 } extcap;
185 /* Flags used to control the application. */
186 struct
188 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
189 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
190 } flags;
192 struct
194 unsigned int n_bits; /* Size of the modulus in bits. The rest
195 of this strucuire is only valid if
196 this is not 0. */
197 unsigned int e_bits; /* Size of the public exponent in bits. */
198 rsa_key_format_t format;
199 } keyattr[3];
205 /***** Local prototypes *****/
206 static unsigned long convert_sig_counter_value (const unsigned char *value,
207 size_t valuelen);
208 static unsigned long get_sig_counter (app_t app);
209 static gpg_error_t do_auth (app_t app, const char *keyidstr,
210 gpg_error_t (*pincb)(void*, const char *, char **),
211 void *pincb_arg,
212 const void *indata, size_t indatalen,
213 unsigned char **outdata, size_t *outdatalen);
214 static void parse_algorithm_attribute (app_t app, int keyno);
215 static gpg_error_t change_keyattr_from_string
216 (app_t app,
217 gpg_error_t (*pincb)(void*, const char *, char **),
218 void *pincb_arg,
219 const void *value, size_t valuelen);
225 /* Deconstructor. */
226 static void
227 do_deinit (app_t app)
229 if (app && app->app_local)
231 struct cache_s *c, *c2;
232 int i;
234 for (c = app->app_local->cache; c; c = c2)
236 c2 = c->next;
237 xfree (c);
240 for (i=0; i < DIM (app->app_local->pk); i++)
242 xfree (app->app_local->pk[i].key);
243 app->app_local->pk[i].read_done = 0;
245 xfree (app->app_local);
246 app->app_local = NULL;
251 /* Wrapper around iso7816_get_data which first tries to get the data
252 from the cache. With GET_IMMEDIATE passed as true, the cache is
253 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
254 supported by the card. */
255 static gpg_error_t
256 get_cached_data (app_t app, int tag,
257 unsigned char **result, size_t *resultlen,
258 int get_immediate, int try_extlen)
260 gpg_error_t err;
261 int i;
262 unsigned char *p;
263 size_t len;
264 struct cache_s *c;
265 int exmode;
267 *result = NULL;
268 *resultlen = 0;
270 if (!get_immediate)
272 for (c=app->app_local->cache; c; c = c->next)
273 if (c->tag == tag)
275 if(c->length)
277 p = xtrymalloc (c->length);
278 if (!p)
279 return gpg_error (gpg_err_code_from_errno (errno));
280 memcpy (p, c->data, c->length);
281 *result = p;
284 *resultlen = c->length;
286 return 0;
290 if (try_extlen && app->app_local->cardcap.ext_lc_le)
291 exmode = app->app_local->extcap.max_rsp_data;
292 else
293 exmode = 0;
295 err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
296 if (err)
297 return err;
298 *result = p;
299 *resultlen = len;
301 /* Check whether we should cache this object. */
302 if (get_immediate)
303 return 0;
305 for (i=0; data_objects[i].tag; i++)
306 if (data_objects[i].tag == tag)
308 if (data_objects[i].dont_cache)
309 return 0;
310 break;
313 /* Okay, cache it. */
314 for (c=app->app_local->cache; c; c = c->next)
315 assert (c->tag != tag);
317 c = xtrymalloc (sizeof *c + len);
318 if (c)
320 memcpy (c->data, p, len);
321 c->length = len;
322 c->tag = tag;
323 c->next = app->app_local->cache;
324 app->app_local->cache = c;
327 return 0;
330 /* Remove DO at TAG from the cache. */
331 static void
332 flush_cache_item (app_t app, int tag)
334 struct cache_s *c, *cprev;
335 int i;
337 if (!app->app_local)
338 return;
340 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
341 if (c->tag == tag)
343 if (cprev)
344 cprev->next = c->next;
345 else
346 app->app_local->cache = c->next;
347 xfree (c);
349 for (c=app->app_local->cache; c ; c = c->next)
351 assert (c->tag != tag); /* Oops: duplicated entry. */
353 return;
356 /* Try again if we have an outer tag. */
357 for (i=0; data_objects[i].tag; i++)
358 if (data_objects[i].tag == tag && data_objects[i].get_from
359 && data_objects[i].get_from != tag)
360 flush_cache_item (app, data_objects[i].get_from);
363 /* Flush all entries from the cache which might be out of sync after
364 an error. */
365 static void
366 flush_cache_after_error (app_t app)
368 int i;
370 for (i=0; data_objects[i].tag; i++)
371 if (data_objects[i].flush_on_error)
372 flush_cache_item (app, data_objects[i].tag);
376 /* Flush the entire cache. */
377 static void
378 flush_cache (app_t app)
380 if (app && app->app_local)
382 struct cache_s *c, *c2;
384 for (c = app->app_local->cache; c; c = c2)
386 c2 = c->next;
387 xfree (c);
389 app->app_local->cache = NULL;
394 /* Get the DO identified by TAG from the card in SLOT and return a
395 buffer with its content in RESULT and NBYTES. The return value is
396 NULL if not found or a pointer which must be used to release the
397 buffer holding value. */
398 static void *
399 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
400 int *r_rc)
402 int rc, i;
403 unsigned char *buffer;
404 size_t buflen;
405 unsigned char *value;
406 size_t valuelen;
407 int dummyrc;
408 int exmode;
410 if (!r_rc)
411 r_rc = &dummyrc;
413 *result = NULL;
414 *nbytes = 0;
415 *r_rc = 0;
416 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
419 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
421 if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
422 exmode = app->app_local->extcap.max_rsp_data;
423 else
424 exmode = 0;
425 rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
426 if (rc)
428 *r_rc = rc;
429 return NULL;
431 *result = buffer;
432 *nbytes = buflen;
433 return buffer;
436 value = NULL;
437 rc = -1;
438 if (data_objects[i].tag && data_objects[i].get_from)
440 rc = get_cached_data (app, data_objects[i].get_from,
441 &buffer, &buflen,
442 (data_objects[i].dont_cache
443 || data_objects[i].get_immediate_in_v11),
444 data_objects[i].try_extlen);
445 if (!rc)
447 const unsigned char *s;
449 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
450 if (!s)
451 value = NULL; /* not found */
452 else if (valuelen > buflen - (s - buffer))
454 log_error ("warning: constructed DO too short\n");
455 value = NULL;
456 xfree (buffer); buffer = NULL;
458 else
459 value = buffer + (s - buffer);
463 if (!value) /* Not in a constructed DO, try simple. */
465 rc = get_cached_data (app, tag, &buffer, &buflen,
466 (data_objects[i].dont_cache
467 || data_objects[i].get_immediate_in_v11),
468 data_objects[i].try_extlen);
469 if (!rc)
471 value = buffer;
472 valuelen = buflen;
476 if (!rc)
478 *nbytes = valuelen;
479 *result = value;
480 return buffer;
482 *r_rc = rc;
483 return NULL;
487 static void
488 dump_all_do (int slot)
490 int rc, i, j;
491 unsigned char *buffer;
492 size_t buflen;
494 for (i=0; data_objects[i].tag; i++)
496 if (data_objects[i].get_from)
497 continue;
499 /* We don't try extended length APDU because such large DO would
500 be pretty useless in a log file. */
501 rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
502 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
504 else if (rc)
505 log_info ("DO `%s' not available: %s\n",
506 data_objects[i].desc, gpg_strerror (rc));
507 else
509 if (data_objects[i].binary)
511 log_info ("DO `%s': ", data_objects[i].desc);
512 log_printhex ("", buffer, buflen);
514 else
515 log_info ("DO `%s': `%.*s'\n",
516 data_objects[i].desc,
517 (int)buflen, buffer); /* FIXME: sanitize */
519 if (data_objects[i].constructed)
521 for (j=0; data_objects[j].tag; j++)
523 const unsigned char *value;
524 size_t valuelen;
526 if (j==i || data_objects[i].tag != data_objects[j].get_from)
527 continue;
528 value = find_tlv_unchecked (buffer, buflen,
529 data_objects[j].tag, &valuelen);
530 if (!value)
531 ; /* not found */
532 else if (valuelen > buflen - (value - buffer))
533 log_error ("warning: constructed DO too short\n");
534 else
536 if (data_objects[j].binary)
538 log_info ("DO `%s': ", data_objects[j].desc);
539 if (valuelen > 200)
540 log_info ("[%u]\n", (unsigned int)valuelen);
541 else
542 log_printhex ("", value, valuelen);
544 else
545 log_info ("DO `%s': `%.*s'\n",
546 data_objects[j].desc,
547 (int)valuelen, value); /* FIXME: sanitize */
552 xfree (buffer); buffer = NULL;
557 /* Count the number of bits, assuming the A represents an unsigned big
558 integer of length LEN bytes. */
559 static unsigned int
560 count_bits (const unsigned char *a, size_t len)
562 unsigned int n = len * 8;
563 int i;
565 for (; len && !*a; len--, a++, n -=8)
567 if (len)
569 for (i=7; i && !(*a & (1<<i)); i--)
570 n--;
572 return n;
575 /* GnuPG makes special use of the login-data DO, this function parses
576 the login data to store the flags for later use. It may be called
577 at any time and should be called after changing the login-data DO.
579 Everything up to a LF is considered a mailbox or account name. If
580 the first LF is followed by DC4 (0x14) control sequence are
581 expected up to the next LF. Control sequences are separated by FS
582 (0x18) and consist of key=value pairs. There is one key defined:
584 F=<flags>
586 Were FLAGS is a plain hexadecimal number representing flag values.
587 The lsb is here the rightmost bit. Defined flags bits are:
589 Bit 0 = CHV1 and CHV2 are not syncronized
590 Bit 1 = CHV2 has been been set to the default PIN of "123456"
591 (this implies that bit 0 is also set).
594 static void
595 parse_login_data (app_t app)
597 unsigned char *buffer, *p;
598 size_t buflen, len;
599 void *relptr;
601 /* Set defaults. */
602 app->app_local->flags.no_sync = 0;
603 app->app_local->flags.def_chv2 = 0;
605 /* Read the DO. */
606 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
607 if (!relptr)
608 return; /* Ooops. */
609 for (; buflen; buflen--, buffer++)
610 if (*buffer == '\n')
611 break;
612 if (buflen < 2 || buffer[1] != '\x14')
613 return; /* No control sequences. */
614 buflen--;
615 buffer++;
618 buflen--;
619 buffer++;
620 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
622 /* Flags control sequence found. */
623 int lastdig = 0;
625 /* For now we are only interested in the last digit, so skip
626 any leading digits but bail out on invalid characters. */
627 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
628 lastdig = xtoi_1 (p);
629 if (len && !(*p == '\n' || *p == '\x18'))
630 goto next; /* Invalid characters in field. */
631 app->app_local->flags.no_sync = !!(lastdig & 1);
632 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
634 next:
635 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
636 if (*buffer == '\n')
637 buflen = 1;
639 while (buflen);
641 xfree (relptr);
644 /* Note, that FPR must be at least 20 bytes. */
645 static gpg_error_t
646 store_fpr (app_t app, int keynumber, u32 timestamp,
647 const unsigned char *m, size_t mlen,
648 const unsigned char *e, size_t elen,
649 unsigned char *fpr, unsigned int card_version)
651 unsigned int n, nbits;
652 unsigned char *buffer, *p;
653 int tag, tag2;
654 int rc;
656 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
658 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
661 n = 6 + 2 + mlen + 2 + elen;
662 p = buffer = xtrymalloc (3 + n);
663 if (!buffer)
664 return gpg_error_from_syserror ();
666 *p++ = 0x99; /* ctb */
667 *p++ = n >> 8; /* 2 byte length header */
668 *p++ = n;
669 *p++ = 4; /* key packet version */
670 *p++ = timestamp >> 24;
671 *p++ = timestamp >> 16;
672 *p++ = timestamp >> 8;
673 *p++ = timestamp;
674 *p++ = 1; /* RSA */
675 nbits = count_bits (m, mlen);
676 *p++ = nbits >> 8;
677 *p++ = nbits;
678 memcpy (p, m, mlen); p += mlen;
679 nbits = count_bits (e, elen);
680 *p++ = nbits >> 8;
681 *p++ = nbits;
682 memcpy (p, e, elen); p += elen;
684 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
686 xfree (buffer);
688 tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
689 flush_cache_item (app, tag);
690 tag2 = 0xCE + keynumber;
691 flush_cache_item (app, tag2);
693 rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
694 if (rc)
695 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
697 if (!rc && card_version > 0x0100)
699 unsigned char buf[4];
701 buf[0] = timestamp >> 24;
702 buf[1] = timestamp >> 16;
703 buf[2] = timestamp >> 8;
704 buf[3] = timestamp;
706 rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
707 if (rc)
708 log_error (_("failed to store the creation date: %s\n"),
709 gpg_strerror (rc));
712 return rc;
716 static void
717 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
718 int number, const unsigned char *fpr)
720 int i;
721 char buf[41];
722 char numbuf[25];
724 for (i=0; i < 20 && !fpr[i]; i++)
726 if (i==20)
727 return; /* All zero. */
728 bin2hex (fpr, 20, buf);
729 if (number == -1)
730 *numbuf = 0; /* Don't print the key number */
731 else
732 sprintf (numbuf, "%d", number);
733 send_status_info (ctrl, keyword,
734 numbuf, (size_t)strlen(numbuf),
735 buf, (size_t)strlen (buf), NULL, 0);
738 static void
739 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
740 int number, const unsigned char *stamp)
742 char numbuf1[50], numbuf2[50];
743 unsigned long value;
745 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
746 if (!value)
747 return;
748 sprintf (numbuf1, "%d", number);
749 sprintf (numbuf2, "%lu", value);
750 send_status_info (ctrl, keyword,
751 numbuf1, (size_t)strlen(numbuf1),
752 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
755 static void
756 send_key_data (ctrl_t ctrl, const char *name,
757 const unsigned char *a, size_t alen)
759 char *buf;
761 buf = bin2hex (a, alen, NULL);
762 if (!buf)
764 log_error ("memory allocation error in send_key_data\n");
765 return;
768 send_status_info (ctrl, "KEY-DATA",
769 name, (size_t)strlen(name),
770 buf, (size_t)strlen (buf),
771 NULL, 0);
772 xfree (buf);
776 static void
777 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
779 char buffer[200];
781 assert (number >=0 && number < DIM(app->app_local->keyattr));
783 /* We only support RSA thus the algo identifier is fixed to 1. */
784 snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
785 number+1,
786 app->app_local->keyattr[number].n_bits,
787 app->app_local->keyattr[number].e_bits,
788 app->app_local->keyattr[number].format);
789 send_status_direct (ctrl, keyword, buffer);
793 /* Implement the GETATTR command. This is similar to the LEARN
794 command but returns just one value via the status interface. */
795 static gpg_error_t
796 do_getattr (app_t app, ctrl_t ctrl, const char *name)
798 static struct {
799 const char *name;
800 int tag;
801 int special;
802 } table[] = {
803 { "DISP-NAME", 0x005B },
804 { "LOGIN-DATA", 0x005E },
805 { "DISP-LANG", 0x5F2D },
806 { "DISP-SEX", 0x5F35 },
807 { "PUBKEY-URL", 0x5F50 },
808 { "KEY-FPR", 0x00C5, 3 },
809 { "KEY-TIME", 0x00CD, 4 },
810 { "KEY-ATTR", 0x0000, -5 },
811 { "CA-FPR", 0x00C6, 3 },
812 { "CHV-STATUS", 0x00C4, 1 },
813 { "SIG-COUNTER", 0x0093, 2 },
814 { "SERIALNO", 0x004F, -1 },
815 { "AID", 0x004F },
816 { "EXTCAP", 0x0000, -2 },
817 { "PRIVATE-DO-1", 0x0101 },
818 { "PRIVATE-DO-2", 0x0102 },
819 { "PRIVATE-DO-3", 0x0103 },
820 { "PRIVATE-DO-4", 0x0104 },
821 { "$AUTHKEYID", 0x0000, -3 },
822 { "$DISPSERIALNO",0x0000, -4 },
823 { NULL, 0 }
825 int idx, i, rc;
826 void *relptr;
827 unsigned char *value;
828 size_t valuelen;
830 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
832 if (!table[idx].name)
833 return gpg_error (GPG_ERR_INV_NAME);
835 if (table[idx].special == -1)
837 /* The serial number is very special. We could have used the
838 AID DO to retrieve it, but we have it already in the app
839 context and the stamp argument is required anyway which we
840 can't by other means. The AID DO is available anyway but not
841 hex formatted. */
842 char *serial;
843 time_t stamp;
844 char tmp[50];
846 if (!app_get_serial_and_stamp (app, &serial, &stamp))
848 sprintf (tmp, "%lu", (unsigned long)stamp);
849 send_status_info (ctrl, "SERIALNO",
850 serial, strlen (serial),
851 tmp, strlen (tmp),
852 NULL, 0);
853 xfree (serial);
855 return 0;
857 if (table[idx].special == -2)
859 char tmp[100];
861 snprintf (tmp, sizeof tmp,
862 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
863 app->app_local->extcap.get_challenge,
864 app->app_local->extcap.key_import,
865 app->app_local->extcap.change_force_chv,
866 app->app_local->extcap.private_dos,
867 app->app_local->extcap.max_certlen_3,
868 app->app_local->extcap.algo_attr_change,
869 (app->app_local->extcap.sm_supported
870 ? (app->app_local->extcap.sm_aes128? 7 : 2)
871 : 0));
872 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
873 return 0;
875 if (table[idx].special == -3)
877 char const tmp[] = "OPENPGP.3";
878 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
879 return 0;
881 if (table[idx].special == -4)
883 char *serial;
884 time_t stamp;
886 if (!app_get_serial_and_stamp (app, &serial, &stamp))
888 if (strlen (serial) > 16+12)
890 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
891 xfree (serial);
892 return 0;
894 xfree (serial);
896 return gpg_error (GPG_ERR_INV_NAME);
898 if (table[idx].special == -5)
900 for (i=0; i < 3; i++)
901 send_key_attr (ctrl, app, table[idx].name, i);
902 return 0;
905 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
906 if (relptr)
908 if (table[idx].special == 1)
910 char numbuf[7*23];
912 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
913 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
914 send_status_info (ctrl, table[idx].name,
915 numbuf, strlen (numbuf), NULL, 0);
917 else if (table[idx].special == 2)
919 char numbuf[50];
921 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
922 send_status_info (ctrl, table[idx].name,
923 numbuf, strlen (numbuf), NULL, 0);
925 else if (table[idx].special == 3)
927 if (valuelen >= 60)
928 for (i=0; i < 3; i++)
929 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
931 else if (table[idx].special == 4)
933 if (valuelen >= 12)
934 for (i=0; i < 3; i++)
935 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
937 else
938 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
940 xfree (relptr);
942 return rc;
945 /* Retrieve the fingerprint from the card inserted in SLOT and write
946 the according hex representation to FPR. Caller must have provide
947 a buffer at FPR of least 41 bytes. Returns 0 on success or an
948 error code. */
949 #if GNUPG_MAJOR_VERSION > 1
950 static gpg_error_t
951 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
953 gpg_error_t err = 0;
954 void *relptr;
955 unsigned char *value;
956 size_t valuelen;
958 assert (keyno >=0 && keyno <= 2);
960 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
961 if (relptr && valuelen >= 60)
962 bin2hex (value+keyno*20, 20, fpr);
963 else
964 err = gpg_error (GPG_ERR_NOT_FOUND);
965 xfree (relptr);
966 return err;
968 #endif /*GNUPG_MAJOR_VERSION > 1*/
971 /* Retrieve the public key material for the RSA key, whose fingerprint
972 is FPR, from gpg output, which can be read through the stream FP.
973 The RSA modulus will be stored at the address of M and MLEN, the
974 public exponent at E and ELEN. Returns zero on success, an error
975 code on failure. Caller must release the allocated buffers at M
976 and E if the function returns success. */
977 #if GNUPG_MAJOR_VERSION > 1
978 static gpg_error_t
979 retrieve_key_material (FILE *fp, const char *hexkeyid,
980 const unsigned char **m, size_t *mlen,
981 const unsigned char **e, size_t *elen)
983 gcry_error_t err = 0;
984 char *line = NULL; /* read_line() buffer. */
985 size_t line_size = 0; /* Helper for for read_line. */
986 int found_key = 0; /* Helper to find a matching key. */
987 unsigned char *m_new = NULL;
988 unsigned char *e_new = NULL;
989 size_t m_new_n = 0;
990 size_t e_new_n = 0;
992 /* Loop over all records until we have found the subkey
993 corresponding to the fingerprint. Inm general the first record
994 should be the pub record, but we don't rely on that. Given that
995 we only need to look at one key, it is sufficient to compare the
996 keyid so that we don't need to look at "fpr" records. */
997 for (;;)
999 char *p;
1000 char *fields[6];
1001 int nfields;
1002 size_t max_length;
1003 gcry_mpi_t mpi;
1004 int i;
1006 max_length = 4096;
1007 i = read_line (fp, &line, &line_size, &max_length);
1008 if (!i)
1009 break; /* EOF. */
1010 if (i < 0)
1012 err = gpg_error_from_syserror ();
1013 goto leave; /* Error. */
1015 if (!max_length)
1017 err = gpg_error (GPG_ERR_TRUNCATED);
1018 goto leave; /* Line truncated - we better stop processing. */
1021 /* Parse the line into fields. */
1022 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1024 fields[nfields] = p;
1025 p = strchr (p, ':');
1026 if (p)
1027 *(p++) = 0;
1029 if (!nfields)
1030 continue; /* No fields at all - skip line. */
1032 if (!found_key)
1034 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1035 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1036 found_key = 1;
1037 continue;
1040 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1041 break; /* Next key - stop. */
1043 if ( strcmp (fields[0], "pkd") )
1044 continue; /* Not a key data record. */
1045 i = 0; /* Avoid erroneous compiler warning. */
1046 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1047 || (!i && m_new) || (i && e_new))
1049 err = gpg_error (GPG_ERR_GENERAL);
1050 goto leave; /* Error: Invalid key data record or not an RSA key. */
1053 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1054 if (err)
1055 mpi = NULL;
1056 else if (!i)
1057 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1058 else
1059 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1060 gcry_mpi_release (mpi);
1061 if (err)
1062 goto leave;
1065 if (m_new && e_new)
1067 *m = m_new;
1068 *mlen = m_new_n;
1069 m_new = NULL;
1070 *e = e_new;
1071 *elen = e_new_n;
1072 e_new = NULL;
1074 else
1075 err = gpg_error (GPG_ERR_GENERAL);
1077 leave:
1078 xfree (m_new);
1079 xfree (e_new);
1080 xfree (line);
1081 return err;
1083 #endif /*GNUPG_MAJOR_VERSION > 1*/
1086 /* Get the public key for KEYNO and store it as an S-expresion with
1087 the APP handle. On error that field gets cleared. If we already
1088 know about the public key we will just return. Note that this does
1089 not mean a key is available; this is soley indicated by the
1090 presence of the app->app_local->pk[KEYNO-1].key field.
1092 Note that GnuPG 1.x does not need this and it would be too time
1093 consuming to send it just for the fun of it. However, given that we
1094 use the same code in gpg 1.4, we can't use the gcry S-expresion
1095 here but need to open encode it. */
1096 #if GNUPG_MAJOR_VERSION > 1
1097 static gpg_error_t
1098 get_public_key (app_t app, int keyno)
1100 gpg_error_t err = 0;
1101 unsigned char *buffer;
1102 const unsigned char *keydata, *m, *e;
1103 size_t buflen, keydatalen, mlen, elen;
1104 unsigned char *mbuf = NULL;
1105 unsigned char *ebuf = NULL;
1106 char *keybuf = NULL;
1107 char *keybuf_p;
1109 if (keyno < 1 || keyno > 3)
1110 return gpg_error (GPG_ERR_INV_ID);
1111 keyno--;
1113 /* Already cached? */
1114 if (app->app_local->pk[keyno].read_done)
1115 return 0;
1117 xfree (app->app_local->pk[keyno].key);
1118 app->app_local->pk[keyno].key = NULL;
1119 app->app_local->pk[keyno].keylen = 0;
1121 m = e = NULL; /* (avoid cc warning) */
1123 if (app->card_version > 0x0100)
1125 int exmode, le_value;
1127 /* We may simply read the public key out of these cards. */
1128 if (app->app_local->cardcap.ext_lc_le)
1130 exmode = 1; /* Use extended length. */
1131 le_value = app->app_local->extcap.max_rsp_data;
1133 else
1135 exmode = 0;
1136 le_value = 256; /* Use legacy value. */
1139 err = iso7816_read_public_key
1140 (app->slot, exmode,
1141 (const unsigned char*)(keyno == 0? "\xB6" :
1142 keyno == 1? "\xB8" : "\xA4"), 2,
1143 le_value,
1144 &buffer, &buflen);
1145 if (err)
1147 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1148 goto leave;
1151 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1152 if (!keydata)
1154 err = gpg_error (GPG_ERR_CARD);
1155 log_error (_("response does not contain the public key data\n"));
1156 goto leave;
1159 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1160 if (!m)
1162 err = gpg_error (GPG_ERR_CARD);
1163 log_error (_("response does not contain the RSA modulus\n"));
1164 goto leave;
1168 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1169 if (!e)
1171 err = gpg_error (GPG_ERR_CARD);
1172 log_error (_("response does not contain the RSA public exponent\n"));
1173 goto leave;
1176 /* Prepend numbers with a 0 if needed. */
1177 if (mlen && (*m & 0x80))
1179 mbuf = xtrymalloc ( mlen + 1);
1180 if (!mbuf)
1182 err = gpg_error_from_syserror ();
1183 goto leave;
1185 *mbuf = 0;
1186 memcpy (mbuf+1, m, mlen);
1187 mlen++;
1188 m = mbuf;
1190 if (elen && (*e & 0x80))
1192 ebuf = xtrymalloc ( elen + 1);
1193 if (!ebuf)
1195 err = gpg_error_from_syserror ();
1196 goto leave;
1198 *ebuf = 0;
1199 memcpy (ebuf+1, e, elen);
1200 elen++;
1201 e = ebuf;
1205 else
1207 /* Due to a design problem in v1.0 cards we can't get the public
1208 key out of these cards without doing a verify on CHV3.
1209 Clearly that is not an option and thus we try to locate the
1210 key using an external helper.
1212 The helper we use here is gpg itself, which should know about
1213 the key in any case. */
1215 char fpr[41];
1216 char *hexkeyid;
1217 char *command = NULL;
1218 FILE *fp;
1219 int ret;
1221 buffer = NULL; /* We don't need buffer. */
1223 err = retrieve_fpr_from_card (app, keyno, fpr);
1224 if (err)
1226 log_error ("error while retrieving fpr from card: %s\n",
1227 gpg_strerror (err));
1228 goto leave;
1230 hexkeyid = fpr + 24;
1232 ret = estream_asprintf (&command,
1233 "gpg --list-keys --with-colons --with-key-data '%s'",
1234 fpr);
1235 if (ret < 0)
1237 err = gpg_error_from_syserror ();
1238 goto leave;
1241 fp = popen (command, "r");
1242 xfree (command);
1243 if (!fp)
1245 err = gpg_error_from_syserror ();
1246 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1247 goto leave;
1250 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1251 fclose (fp);
1252 if (err)
1254 log_error ("error while retrieving key material through pipe: %s\n",
1255 gpg_strerror (err));
1256 goto leave;
1260 /* Allocate a buffer to construct the S-expression. */
1261 /* FIXME: We should provide a generalized S-expression creation
1262 mechanism. */
1263 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1264 if (!keybuf)
1266 err = gpg_error_from_syserror ();
1267 goto leave;
1270 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1271 keybuf_p = keybuf + strlen (keybuf);
1272 memcpy (keybuf_p, m, mlen);
1273 keybuf_p += mlen;
1274 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1275 keybuf_p += strlen (keybuf_p);
1276 memcpy (keybuf_p, e, elen);
1277 keybuf_p += elen;
1278 strcpy (keybuf_p, ")))");
1279 keybuf_p += strlen (keybuf_p);
1281 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1282 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1284 leave:
1285 /* Set a flag to indicate that we tried to read the key. */
1286 app->app_local->pk[keyno].read_done = 1;
1288 xfree (buffer);
1289 xfree (mbuf);
1290 xfree (ebuf);
1291 return 0;
1293 #endif /* GNUPG_MAJOR_VERSION > 1 */
1297 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1298 This is used by the LEARN command. */
1299 static gpg_error_t
1300 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1302 gpg_error_t err = 0;
1303 /* Note that GnuPG 1.x does not need this and it would be too time
1304 consuming to send it just for the fun of it. */
1305 #if GNUPG_MAJOR_VERSION > 1
1306 unsigned char grip[20];
1307 char gripstr[41];
1308 char idbuf[50];
1310 err = get_public_key (app, keyno);
1311 if (err)
1312 goto leave;
1314 assert (keyno >= 1 && keyno <= 3);
1315 if (!app->app_local->pk[keyno-1].key)
1316 goto leave; /* No such key - ignore. */
1318 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1319 app->app_local->pk[keyno-1].keylen,
1320 grip);
1321 if (err)
1322 goto leave;
1324 bin2hex (grip, 20, gripstr);
1326 sprintf (idbuf, "OPENPGP.%d", keyno);
1327 send_status_info (ctrl, "KEYPAIRINFO",
1328 gripstr, 40,
1329 idbuf, strlen (idbuf),
1330 NULL, (size_t)0);
1332 leave:
1333 #endif /* GNUPG_MAJOR_VERSION > 1 */
1335 return err;
1339 /* Handle the LEARN command for OpenPGP. */
1340 static gpg_error_t
1341 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1343 (void)flags;
1345 do_getattr (app, ctrl, "EXTCAP");
1346 do_getattr (app, ctrl, "DISP-NAME");
1347 do_getattr (app, ctrl, "DISP-LANG");
1348 do_getattr (app, ctrl, "DISP-SEX");
1349 do_getattr (app, ctrl, "PUBKEY-URL");
1350 do_getattr (app, ctrl, "LOGIN-DATA");
1351 do_getattr (app, ctrl, "KEY-FPR");
1352 if (app->card_version > 0x0100)
1353 do_getattr (app, ctrl, "KEY-TIME");
1354 do_getattr (app, ctrl, "CA-FPR");
1355 do_getattr (app, ctrl, "CHV-STATUS");
1356 do_getattr (app, ctrl, "SIG-COUNTER");
1357 if (app->app_local->extcap.private_dos)
1359 do_getattr (app, ctrl, "PRIVATE-DO-1");
1360 do_getattr (app, ctrl, "PRIVATE-DO-2");
1361 if (app->did_chv2)
1362 do_getattr (app, ctrl, "PRIVATE-DO-3");
1363 if (app->did_chv3)
1364 do_getattr (app, ctrl, "PRIVATE-DO-4");
1366 send_keypair_info (app, ctrl, 1);
1367 send_keypair_info (app, ctrl, 2);
1368 send_keypair_info (app, ctrl, 3);
1369 /* Note: We do not send the Cardholder Certificate, because that is
1370 relativly long and for OpenPGP applications not really needed. */
1371 return 0;
1375 /* Handle the READKEY command for OpenPGP. On success a canonical
1376 encoded S-expression with the public key will get stored at PK and
1377 its length (for assertions) at PKLEN; the caller must release that
1378 buffer. On error PK and PKLEN are not changed and an error code is
1379 returned. */
1380 static gpg_error_t
1381 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1383 #if GNUPG_MAJOR_VERSION > 1
1384 gpg_error_t err;
1385 int keyno;
1386 unsigned char *buf;
1388 if (!strcmp (keyid, "OPENPGP.1"))
1389 keyno = 1;
1390 else if (!strcmp (keyid, "OPENPGP.2"))
1391 keyno = 2;
1392 else if (!strcmp (keyid, "OPENPGP.3"))
1393 keyno = 3;
1394 else
1395 return gpg_error (GPG_ERR_INV_ID);
1397 err = get_public_key (app, keyno);
1398 if (err)
1399 return err;
1401 buf = app->app_local->pk[keyno-1].key;
1402 if (!buf)
1403 return gpg_error (GPG_ERR_NO_PUBKEY);
1404 *pklen = app->app_local->pk[keyno-1].keylen;;
1405 *pk = xtrymalloc (*pklen);
1406 if (!*pk)
1408 err = gpg_error_from_syserror ();
1409 *pklen = 0;
1410 return err;
1412 memcpy (*pk, buf, *pklen);
1413 return 0;
1414 #else
1415 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1416 #endif
1419 /* Read the standard certificate of an OpenPGP v2 card. It is
1420 returned in a freshly allocated buffer with that address stored at
1421 CERT and the length of the certificate stored at CERTLEN. CERTID
1422 needs to be set to "OPENPGP.3". */
1423 static gpg_error_t
1424 do_readcert (app_t app, const char *certid,
1425 unsigned char **cert, size_t *certlen)
1427 #if GNUPG_MAJOR_VERSION > 1
1428 gpg_error_t err;
1429 unsigned char *buffer;
1430 size_t buflen;
1431 void *relptr;
1433 *cert = NULL;
1434 *certlen = 0;
1435 if (strcmp (certid, "OPENPGP.3"))
1436 return gpg_error (GPG_ERR_INV_ID);
1437 if (!app->app_local->extcap.is_v2)
1438 return gpg_error (GPG_ERR_NOT_FOUND);
1440 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1441 if (!relptr)
1442 return gpg_error (GPG_ERR_NOT_FOUND);
1444 if (!buflen)
1445 err = gpg_error (GPG_ERR_NOT_FOUND);
1446 else if (!(*cert = xtrymalloc (buflen)))
1447 err = gpg_error_from_syserror ();
1448 else
1450 memcpy (*cert, buffer, buflen);
1451 *certlen = buflen;
1452 err = 0;
1454 xfree (relptr);
1455 return err;
1456 #else
1457 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1458 #endif
1462 /* Verify a CHV either using using the pinentry or if possibile by
1463 using a keypad. PINCB and PINCB_ARG describe the usual callback
1464 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1465 used with CHV1. PINVALUE is the address of a pointer which will
1466 receive a newly allocated block with the actual PIN (this is useful
1467 in case that PIN shall be used for another verify operation). The
1468 caller needs to free this value. If the function returns with
1469 success and NULL is stored at PINVALUE, the caller should take this
1470 as an indication that the keypad has been used.
1472 static gpg_error_t
1473 verify_a_chv (app_t app,
1474 gpg_error_t (*pincb)(void*, const char *, char **),
1475 void *pincb_arg,
1476 int chvno, unsigned long sigcount, char **pinvalue)
1478 int rc = 0;
1479 char *prompt_buffer = NULL;
1480 const char *prompt;
1481 iso7816_pininfo_t pininfo;
1482 int minlen = 6;
1484 assert (chvno == 1 || chvno == 2);
1486 *pinvalue = NULL;
1488 if (chvno == 2 && app->app_local->flags.def_chv2)
1490 /* Special case for def_chv2 mechanism. */
1491 if (opt.verbose)
1492 log_info (_("using default PIN as %s\n"), "CHV2");
1493 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1494 if (rc)
1496 /* Verification of CHV2 with the default PIN failed,
1497 although the card pretends to have the default PIN set as
1498 CHV2. We better disable the def_chv2 flag now. */
1499 log_info (_("failed to use default PIN as %s: %s"
1500 " - disabling further default use\n"),
1501 "CHV2", gpg_strerror (rc));
1502 app->app_local->flags.def_chv2 = 0;
1504 return rc;
1507 memset (&pininfo, 0, sizeof pininfo);
1508 pininfo.mode = 1;
1509 pininfo.minlen = minlen;
1512 if (chvno == 1)
1514 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1515 size_t promptsize = strlen (PROMPTSTRING) + 50;
1517 prompt_buffer = xtrymalloc (promptsize);
1518 if (!prompt_buffer)
1519 return gpg_error_from_syserror ();
1520 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1521 prompt = prompt_buffer;
1522 #undef PROMPTSTRING
1524 else
1525 prompt = _("||Please enter the PIN");
1528 if (!opt.disable_keypad
1529 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1531 /* The reader supports the verify command through the keypad.
1532 Note that the pincb appends a text to the prompt telling the
1533 user to use the keypad. */
1534 rc = pincb (pincb_arg, prompt, NULL);
1535 prompt = NULL;
1536 xfree (prompt_buffer);
1537 prompt_buffer = NULL;
1538 if (rc)
1540 log_info (_("PIN callback returned error: %s\n"),
1541 gpg_strerror (rc));
1542 return rc;
1544 rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1545 /* Dismiss the prompt. */
1546 pincb (pincb_arg, NULL, NULL);
1548 assert (!*pinvalue);
1550 else
1552 /* The reader has no keypad or we don't want to use it. */
1553 rc = pincb (pincb_arg, prompt, pinvalue);
1554 prompt = NULL;
1555 xfree (prompt_buffer);
1556 prompt_buffer = NULL;
1557 if (rc)
1559 log_info (_("PIN callback returned error: %s\n"),
1560 gpg_strerror (rc));
1561 return rc;
1564 if (strlen (*pinvalue) < minlen)
1566 log_error (_("PIN for CHV%d is too short;"
1567 " minimum length is %d\n"), chvno, minlen);
1568 xfree (*pinvalue);
1569 *pinvalue = NULL;
1570 return gpg_error (GPG_ERR_BAD_PIN);
1573 rc = iso7816_verify (app->slot, 0x80+chvno,
1574 *pinvalue, strlen (*pinvalue));
1577 if (rc)
1579 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1580 xfree (*pinvalue);
1581 *pinvalue = NULL;
1582 flush_cache_after_error (app);
1585 return rc;
1589 /* Verify CHV2 if required. Depending on the configuration of the
1590 card CHV1 will also be verified. */
1591 static gpg_error_t
1592 verify_chv2 (app_t app,
1593 gpg_error_t (*pincb)(void*, const char *, char **),
1594 void *pincb_arg)
1596 int rc;
1597 char *pinvalue;
1599 if (app->did_chv2)
1600 return 0; /* We already verified CHV2. */
1602 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1603 if (rc)
1604 return rc;
1605 app->did_chv2 = 1;
1607 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1609 /* For convenience we verify CHV1 here too. We do this only if
1610 the card is not configured to require a verification before
1611 each CHV1 controlled operation (force_chv1) and if we are not
1612 using the keypad (PINVALUE == NULL). */
1613 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1614 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1615 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1616 if (rc)
1618 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1619 flush_cache_after_error (app);
1621 else
1622 app->did_chv1 = 1;
1625 xfree (pinvalue);
1627 return rc;
1631 /* Build the prompt to enter the Admin PIN. The prompt depends on the
1632 current sdtate of the card. */
1633 static gpg_error_t
1634 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1636 void *relptr;
1637 unsigned char *value;
1638 size_t valuelen;
1639 int remaining;
1640 char *prompt;
1642 *r_prompt = NULL;
1644 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1645 if (!relptr || valuelen < 7)
1647 log_error (_("error retrieving CHV status from card\n"));
1648 xfree (relptr);
1649 return gpg_error (GPG_ERR_CARD);
1651 if (value[6] == 0)
1653 log_info (_("card is permanently locked!\n"));
1654 xfree (relptr);
1655 return gpg_error (GPG_ERR_BAD_PIN);
1657 remaining = value[6];
1658 xfree (relptr);
1660 log_info(_("%d Admin PIN attempts remaining before card"
1661 " is permanently locked\n"), remaining);
1663 if (remaining < 3)
1665 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1666 the start of the string. Use %%0A to force a linefeed. */
1667 prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1668 "[remaining attempts: %d]"), remaining);
1670 else
1671 prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1673 if (!prompt)
1674 return gpg_error_from_syserror ();
1676 *r_prompt = prompt;
1677 return 0;
1681 /* Verify CHV3 if required. */
1682 static gpg_error_t
1683 verify_chv3 (app_t app,
1684 gpg_error_t (*pincb)(void*, const char *, char **),
1685 void *pincb_arg)
1687 int rc = 0;
1689 #if GNUPG_MAJOR_VERSION != 1
1690 if (!opt.allow_admin)
1692 log_info (_("access to admin commands is not configured\n"));
1693 return gpg_error (GPG_ERR_EACCES);
1695 #endif
1697 if (!app->did_chv3)
1699 iso7816_pininfo_t pininfo;
1700 int minlen = 8;
1701 char *prompt;
1703 memset (&pininfo, 0, sizeof pininfo);
1704 pininfo.mode = 1;
1705 pininfo.minlen = minlen;
1707 rc = build_enter_admin_pin_prompt (app, &prompt);
1708 if (rc)
1709 return rc;
1711 if (!opt.disable_keypad
1712 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1714 /* The reader supports the verify command through the keypad. */
1715 rc = pincb (pincb_arg, prompt, NULL);
1716 xfree (prompt);
1717 prompt = NULL;
1718 if (rc)
1720 log_info (_("PIN callback returned error: %s\n"),
1721 gpg_strerror (rc));
1722 return rc;
1724 rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1725 /* Dismiss the prompt. */
1726 pincb (pincb_arg, NULL, NULL);
1728 else
1730 char *pinvalue;
1732 rc = pincb (pincb_arg, prompt, &pinvalue);
1733 xfree (prompt);
1734 prompt = NULL;
1735 if (rc)
1737 log_info (_("PIN callback returned error: %s\n"),
1738 gpg_strerror (rc));
1739 return rc;
1742 if (strlen (pinvalue) < minlen)
1744 log_error (_("PIN for CHV%d is too short;"
1745 " minimum length is %d\n"), 3, minlen);
1746 xfree (pinvalue);
1747 return gpg_error (GPG_ERR_BAD_PIN);
1750 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1751 xfree (pinvalue);
1754 if (rc)
1756 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1757 flush_cache_after_error (app);
1758 return rc;
1760 app->did_chv3 = 1;
1762 return rc;
1766 /* Handle the SETATTR operation. All arguments are already basically
1767 checked. */
1768 static gpg_error_t
1769 do_setattr (app_t app, const char *name,
1770 gpg_error_t (*pincb)(void*, const char *, char **),
1771 void *pincb_arg,
1772 const unsigned char *value, size_t valuelen)
1774 gpg_error_t rc;
1775 int idx;
1776 static struct {
1777 const char *name;
1778 int tag;
1779 int need_chv;
1780 int special;
1781 unsigned int need_v2:1;
1782 } table[] = {
1783 { "DISP-NAME", 0x005B, 3 },
1784 { "LOGIN-DATA", 0x005E, 3, 2 },
1785 { "DISP-LANG", 0x5F2D, 3 },
1786 { "DISP-SEX", 0x5F35, 3 },
1787 { "PUBKEY-URL", 0x5F50, 3 },
1788 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1789 { "CA-FPR-1", 0x00CA, 3 },
1790 { "CA-FPR-2", 0x00CB, 3 },
1791 { "CA-FPR-3", 0x00CC, 3 },
1792 { "PRIVATE-DO-1", 0x0101, 2 },
1793 { "PRIVATE-DO-2", 0x0102, 3 },
1794 { "PRIVATE-DO-3", 0x0103, 2 },
1795 { "PRIVATE-DO-4", 0x0104, 3 },
1796 { "CERT-3", 0x7F21, 3, 0, 1 },
1797 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1798 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1799 { "KEY-ATTR", 0, 0, 3, 1 },
1800 { NULL, 0 }
1802 int exmode;
1804 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1806 if (!table[idx].name)
1807 return gpg_error (GPG_ERR_INV_NAME);
1808 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1809 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1811 if (table[idx].special == 3)
1812 return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
1814 switch (table[idx].need_chv)
1816 case 2:
1817 rc = verify_chv2 (app, pincb, pincb_arg);
1818 break;
1819 case 3:
1820 rc = verify_chv3 (app, pincb, pincb_arg);
1821 break;
1822 default:
1823 rc = 0;
1825 if (rc)
1826 return rc;
1828 /* Flush the cache before writing it, so that the next get operation
1829 will reread the data from the card and thus get synced in case of
1830 errors (e.g. data truncated by the card). */
1831 flush_cache_item (app, table[idx].tag);
1833 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1834 exmode = 1; /* Use extended length w/o a limit. */
1835 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1836 exmode = -254; /* Command chaining with max. 254 bytes. */
1837 else
1838 exmode = 0;
1839 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1840 if (rc)
1841 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1843 if (table[idx].special == 1)
1844 app->force_chv1 = (valuelen && *value == 0);
1845 else if (table[idx].special == 2)
1846 parse_login_data (app);
1848 return rc;
1852 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1853 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1854 PINCB and PINCB_ARG are the usual arguments for the pinentry
1855 callback. */
1856 static gpg_error_t
1857 do_writecert (app_t app, ctrl_t ctrl,
1858 const char *certidstr,
1859 gpg_error_t (*pincb)(void*, const char *, char **),
1860 void *pincb_arg,
1861 const unsigned char *certdata, size_t certdatalen)
1863 (void)ctrl;
1864 #if GNUPG_MAJOR_VERSION > 1
1865 if (strcmp (certidstr, "OPENPGP.3"))
1866 return gpg_error (GPG_ERR_INV_ID);
1867 if (!certdata || !certdatalen)
1868 return gpg_error (GPG_ERR_INV_ARG);
1869 if (!app->app_local->extcap.is_v2)
1870 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1871 if (certdatalen > app->app_local->extcap.max_certlen_3)
1872 return gpg_error (GPG_ERR_TOO_LARGE);
1873 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1874 #else
1875 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1876 #endif
1881 /* Handle the PASSWD command. The following combinations are
1882 possible:
1884 Flags CHVNO Vers. Description
1885 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
1886 RESET 1 2 Verify PW3 and set a new PW1.
1887 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
1888 RESET 2 2 Verify PW3 and set a new Reset Code.
1889 RESET 3 any Returns GPG_ERR_INV_ID.
1890 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
1891 - 1 2 Verify PW1 and set a new PW1.
1892 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
1893 - 2 2 Verify Reset Code and set a new PW1.
1894 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
1896 static gpg_error_t
1897 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
1898 unsigned int flags,
1899 gpg_error_t (*pincb)(void*, const char *, char **),
1900 void *pincb_arg)
1902 int rc = 0;
1903 int chvno = atoi (chvnostr);
1904 char *resetcode = NULL;
1905 char *oldpinvalue = NULL;
1906 char *pinvalue;
1907 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1908 int set_resetcode = 0;
1910 (void)ctrl;
1912 if (reset_mode && chvno == 3)
1914 rc = gpg_error (GPG_ERR_INV_ID);
1915 goto leave;
1918 if (!app->app_local->extcap.is_v2)
1920 /* Version 1 cards. */
1922 if (reset_mode || chvno == 3)
1924 /* We always require that the PIN is entered. */
1925 app->did_chv3 = 0;
1926 rc = verify_chv3 (app, pincb, pincb_arg);
1927 if (rc)
1928 goto leave;
1930 else if (chvno == 1 || chvno == 2)
1932 /* On a v1.x card CHV1 and CVH2 should always have the same
1933 value, thus we enforce it here. */
1934 int save_force = app->force_chv1;
1936 app->force_chv1 = 0;
1937 app->did_chv1 = 0;
1938 app->did_chv2 = 0;
1939 rc = verify_chv2 (app, pincb, pincb_arg);
1940 app->force_chv1 = save_force;
1941 if (rc)
1942 goto leave;
1944 else
1946 rc = gpg_error (GPG_ERR_INV_ID);
1947 goto leave;
1950 else
1952 /* Version 2 cards. */
1954 if (reset_mode)
1956 /* To reset a PIN the Admin PIN is required. */
1957 app->did_chv3 = 0;
1958 rc = verify_chv3 (app, pincb, pincb_arg);
1959 if (rc)
1960 goto leave;
1962 if (chvno == 2)
1963 set_resetcode = 1;
1965 else if (chvno == 1 || chvno == 3)
1967 int minlen = (chvno ==3)? 8 : 6;
1968 char *promptbuf = NULL;
1969 const char *prompt;
1971 if (chvno == 3)
1973 rc = build_enter_admin_pin_prompt (app, &promptbuf);
1974 if (rc)
1975 goto leave;
1976 prompt = promptbuf;
1978 else
1979 prompt = _("||Please enter the PIN");
1980 rc = pincb (pincb_arg, prompt, &oldpinvalue);
1981 xfree (promptbuf);
1982 promptbuf = NULL;
1983 if (rc)
1985 log_info (_("PIN callback returned error: %s\n"),
1986 gpg_strerror (rc));
1987 goto leave;
1990 if (strlen (oldpinvalue) < minlen)
1992 log_info (_("PIN for CHV%d is too short;"
1993 " minimum length is %d\n"), chvno, minlen);
1994 rc = gpg_error (GPG_ERR_BAD_PIN);
1995 goto leave;
1998 else if (chvno == 2)
2000 /* There is no PW2 for v2 cards. We use this condition to
2001 allow a PW reset using the Reset Code. */
2002 void *relptr;
2003 unsigned char *value;
2004 size_t valuelen;
2005 int remaining;
2006 int minlen = 8;
2008 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2009 if (!relptr || valuelen < 7)
2011 log_error (_("error retrieving CHV status from card\n"));
2012 xfree (relptr);
2013 rc = gpg_error (GPG_ERR_CARD);
2014 goto leave;
2016 remaining = value[5];
2017 xfree (relptr);
2018 if (!remaining)
2020 log_error (_("Reset Code not or not anymore available\n"));
2021 rc = gpg_error (GPG_ERR_BAD_PIN);
2022 goto leave;
2025 rc = pincb (pincb_arg,
2026 _("||Please enter the Reset Code for the card"),
2027 &resetcode);
2028 if (rc)
2030 log_info (_("PIN callback returned error: %s\n"),
2031 gpg_strerror (rc));
2032 goto leave;
2034 if (strlen (resetcode) < minlen)
2036 log_info (_("Reset Code is too short; minimum length is %d\n"),
2037 minlen);
2038 rc = gpg_error (GPG_ERR_BAD_PIN);
2039 goto leave;
2042 else
2044 rc = gpg_error (GPG_ERR_INV_ID);
2045 goto leave;
2049 if (chvno == 3)
2050 app->did_chv3 = 0;
2051 else
2052 app->did_chv1 = app->did_chv2 = 0;
2054 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2055 keep it at the start of the string. We need this elsewhere
2056 to get some infos on the string. */
2057 rc = pincb (pincb_arg,
2058 set_resetcode? _("|RN|New Reset Code") :
2059 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2060 &pinvalue);
2061 if (rc)
2063 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2064 goto leave;
2068 if (resetcode)
2070 char *buffer;
2072 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2073 if (!buffer)
2074 rc = gpg_error_from_syserror ();
2075 else
2077 strcpy (stpcpy (buffer, resetcode), pinvalue);
2078 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2079 buffer, strlen (buffer));
2080 wipememory (buffer, strlen (buffer));
2081 xfree (buffer);
2084 else if (set_resetcode)
2086 if (strlen (pinvalue) < 8)
2088 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2089 rc = gpg_error (GPG_ERR_BAD_PIN);
2091 else
2092 rc = iso7816_put_data (app->slot, 0, 0xD3,
2093 pinvalue, strlen (pinvalue));
2095 else if (reset_mode)
2097 rc = iso7816_reset_retry_counter (app->slot, 0x81,
2098 pinvalue, strlen (pinvalue));
2099 if (!rc && !app->app_local->extcap.is_v2)
2100 rc = iso7816_reset_retry_counter (app->slot, 0x82,
2101 pinvalue, strlen (pinvalue));
2103 else if (!app->app_local->extcap.is_v2)
2105 /* Version 1 cards. */
2106 if (chvno == 1 || chvno == 2)
2108 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2109 pinvalue, strlen (pinvalue));
2110 if (!rc)
2111 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2112 pinvalue, strlen (pinvalue));
2114 else /* CHVNO == 3 */
2116 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2117 pinvalue, strlen (pinvalue));
2120 else
2122 /* Version 2 cards. */
2123 assert (chvno == 1 || chvno == 3);
2125 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2126 oldpinvalue, strlen (oldpinvalue),
2127 pinvalue, strlen (pinvalue));
2130 if (pinvalue)
2132 wipememory (pinvalue, strlen (pinvalue));
2133 xfree (pinvalue);
2135 if (rc)
2136 flush_cache_after_error (app);
2138 leave:
2139 if (resetcode)
2141 wipememory (resetcode, strlen (resetcode));
2142 xfree (resetcode);
2144 if (oldpinvalue)
2146 wipememory (oldpinvalue, strlen (oldpinvalue));
2147 xfree (oldpinvalue);
2149 return rc;
2153 /* Check whether a key already exists. KEYIDX is the index of the key
2154 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2155 error returned if the key already exists. The flag GENERATING is
2156 only used to print correct messages. */
2157 static gpg_error_t
2158 does_key_exist (app_t app, int keyidx, int generating, int force)
2160 const unsigned char *fpr;
2161 unsigned char *buffer;
2162 size_t buflen, n;
2163 int i;
2165 assert (keyidx >=0 && keyidx <= 2);
2167 if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2169 log_error (_("error reading application data\n"));
2170 return gpg_error (GPG_ERR_GENERAL);
2172 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2173 if (!fpr || n < 60)
2175 log_error (_("error reading fingerprint DO\n"));
2176 xfree (buffer);
2177 return gpg_error (GPG_ERR_GENERAL);
2179 fpr += 20*keyidx;
2180 for (i=0; i < 20 && !fpr[i]; i++)
2182 xfree (buffer);
2183 if (i!=20 && !force)
2185 log_error (_("key already exists\n"));
2186 return gpg_error (GPG_ERR_EEXIST);
2188 else if (i!=20)
2189 log_info (_("existing key will be replaced\n"));
2190 else if (generating)
2191 log_info (_("generating new key\n"));
2192 else
2193 log_info (_("writing new key\n"));
2194 return 0;
2198 /* Create a TLV tag and value and store it at BUFFER. Return the length
2199 of tag and length. A LENGTH greater than 65535 is truncated. */
2200 static size_t
2201 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2203 unsigned char *p = buffer;
2205 assert (tag <= 0xffff);
2206 if ( tag > 0xff )
2207 *p++ = tag >> 8;
2208 *p++ = tag;
2209 if (length < 128)
2210 *p++ = length;
2211 else if (length < 256)
2213 *p++ = 0x81;
2214 *p++ = length;
2216 else
2218 if (length > 0xffff)
2219 length = 0xffff;
2220 *p++ = 0x82;
2221 *p++ = length >> 8;
2222 *p++ = length;
2225 return p - buffer;
2229 /* Build the private key template as specified in the OpenPGP specs
2230 v2.0 section 4.3.3.7. */
2231 static gpg_error_t
2232 build_privkey_template (app_t app, int keyno,
2233 const unsigned char *rsa_n, size_t rsa_n_len,
2234 const unsigned char *rsa_e, size_t rsa_e_len,
2235 const unsigned char *rsa_p, size_t rsa_p_len,
2236 const unsigned char *rsa_q, size_t rsa_q_len,
2237 unsigned char **result, size_t *resultlen)
2239 size_t rsa_e_reqlen;
2240 unsigned char privkey[7*(1+3)];
2241 size_t privkey_len;
2242 unsigned char exthdr[2+2+3];
2243 size_t exthdr_len;
2244 unsigned char suffix[2+3];
2245 size_t suffix_len;
2246 unsigned char *tp;
2247 size_t datalen;
2248 unsigned char *template;
2249 size_t template_size;
2251 *result = NULL;
2252 *resultlen = 0;
2254 switch (app->app_local->keyattr[keyno].format)
2256 case RSA_STD:
2257 case RSA_STD_N:
2258 break;
2259 case RSA_CRT:
2260 case RSA_CRT_N:
2261 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2263 default:
2264 return gpg_error (GPG_ERR_INV_VALUE);
2267 /* Get the required length for E. */
2268 rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2269 assert (rsa_e_len <= rsa_e_reqlen);
2271 /* Build the 7f48 cardholder private key template. */
2272 datalen = 0;
2273 tp = privkey;
2275 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2276 datalen += rsa_e_reqlen;
2278 tp += add_tlv (tp, 0x92, rsa_p_len);
2279 datalen += rsa_p_len;
2281 tp += add_tlv (tp, 0x93, rsa_q_len);
2282 datalen += rsa_q_len;
2284 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2285 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2287 tp += add_tlv (tp, 0x97, rsa_n_len);
2288 datalen += rsa_n_len;
2290 privkey_len = tp - privkey;
2292 /* Build the extended header list without the private key template. */
2293 tp = exthdr;
2294 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2295 *tp++ = 0;
2296 tp += add_tlv (tp, 0x7f48, privkey_len);
2297 exthdr_len = tp - exthdr;
2299 /* Build the 5f48 suffix of the data. */
2300 tp = suffix;
2301 tp += add_tlv (tp, 0x5f48, datalen);
2302 suffix_len = tp - suffix;
2304 /* Now concatenate everything. */
2305 template_size = (1 + 3 /* 0x4d and len. */
2306 + exthdr_len
2307 + privkey_len
2308 + suffix_len
2309 + datalen);
2310 tp = template = xtrymalloc_secure (template_size);
2311 if (!template)
2312 return gpg_error_from_syserror ();
2314 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2315 memcpy (tp, exthdr, exthdr_len);
2316 tp += exthdr_len;
2317 memcpy (tp, privkey, privkey_len);
2318 tp += privkey_len;
2319 memcpy (tp, suffix, suffix_len);
2320 tp += suffix_len;
2322 memcpy (tp, rsa_e, rsa_e_len);
2323 if (rsa_e_len < rsa_e_reqlen)
2325 /* Right justify E. */
2326 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2327 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2329 tp += rsa_e_reqlen;
2331 memcpy (tp, rsa_p, rsa_p_len);
2332 tp += rsa_p_len;
2334 memcpy (tp, rsa_q, rsa_q_len);
2335 tp += rsa_q_len;
2337 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2338 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2340 memcpy (tp, rsa_n, rsa_n_len);
2341 tp += rsa_n_len;
2344 /* Sanity check. We don't know the exact length because we
2345 allocated 3 bytes for the first length header. */
2346 assert (tp - template <= template_size);
2348 *result = template;
2349 *resultlen = tp - template;
2350 return 0;
2354 /* Helper for do_writekley to change the size of a key. Not ethat
2355 this deletes the entire key without asking. */
2356 static gpg_error_t
2357 change_keyattr (app_t app, int keyno, unsigned int nbits,
2358 gpg_error_t (*pincb)(void*, const char *, char **),
2359 void *pincb_arg)
2361 gpg_error_t err;
2362 unsigned char *buffer;
2363 size_t buflen;
2364 void *relptr;
2366 assert (keyno >=0 && keyno <= 2);
2368 if (nbits > 3072)
2369 return gpg_error (GPG_ERR_TOO_LARGE);
2371 /* Read the current attributes into a buffer. */
2372 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
2373 if (!relptr)
2374 return gpg_error (GPG_ERR_CARD);
2375 if (buflen < 6 || buffer[0] != 1)
2377 /* Attriutes too short or not an RSA key. */
2378 xfree (relptr);
2379 return gpg_error (GPG_ERR_CARD);
2382 /* We only change n_bits and don't touch anything else. Before we
2383 do so, we round up NBITS to a sensible way in the same way as
2384 gpg's key generation does it. This may help to sort out problems
2385 with a few bits too short keys. */
2386 nbits = ((nbits + 31) / 32) * 32;
2387 buffer[1] = (nbits >> 8);
2388 buffer[2] = nbits;
2390 /* Prepare for storing the key. */
2391 err = verify_chv3 (app, pincb, pincb_arg);
2392 if (err)
2394 xfree (relptr);
2395 return err;
2398 /* Change the attribute. */
2399 err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
2400 xfree (relptr);
2401 if (err)
2402 log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
2403 else
2404 log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
2405 flush_cache (app);
2406 parse_algorithm_attribute (app, keyno);
2407 app->did_chv1 = 0;
2408 app->did_chv2 = 0;
2409 app->did_chv3 = 0;
2410 return err;
2414 /* Helper to process an setattr command for name KEY-ATTR. It expects
2415 a string "--force <keyno> <algo> <nbits>" in (VALUE,VALUELEN). */
2416 static gpg_error_t
2417 change_keyattr_from_string (app_t app,
2418 gpg_error_t (*pincb)(void*, const char *, char **),
2419 void *pincb_arg,
2420 const void *value, size_t valuelen)
2422 gpg_error_t err;
2423 char *string;
2424 int keyno, algo;
2425 unsigned int nbits;
2427 /* VALUE is expected to be a string but not guaranteed to be
2428 terminated. Thus copy it to an allocated buffer first. */
2429 string = xtrymalloc (valuelen+1);
2430 if (!string)
2431 return gpg_error_from_syserror ();
2432 memcpy (string, value, valuelen);
2433 string[valuelen] = 0;
2435 /* Because this function deletes the key we require the string
2436 "--force" in the data to make clear that something serious might
2437 happen. */
2438 if (sscanf (string, " --force %d %d %u", &keyno, &algo, &nbits) != 3)
2439 err = gpg_error (GPG_ERR_INV_DATA);
2440 else if (keyno < 1 || keyno > 3)
2441 err = gpg_error (GPG_ERR_INV_ID);
2442 else if (algo != 1)
2443 err = gpg_error (GPG_ERR_PUBKEY_ALGO); /* Not RSA. */
2444 else if (nbits < 1024)
2445 err = gpg_error (GPG_ERR_TOO_SHORT);
2446 else
2447 err = change_keyattr (app, keyno-1, nbits, pincb, pincb_arg);
2449 xfree (string);
2450 return err;
2454 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2455 canonical encoded S-expression with the secret key in KEYDATA and
2456 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2457 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2458 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2459 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2460 the pinentry callback. */
2461 static gpg_error_t
2462 do_writekey (app_t app, ctrl_t ctrl,
2463 const char *keyid, unsigned int flags,
2464 gpg_error_t (*pincb)(void*, const char *, char **),
2465 void *pincb_arg,
2466 const unsigned char *keydata, size_t keydatalen)
2468 gpg_error_t err;
2469 int force = (flags & 1);
2470 int keyno;
2471 const unsigned char *buf, *tok;
2472 size_t buflen, toklen;
2473 int depth, last_depth1, last_depth2;
2474 const unsigned char *rsa_n = NULL;
2475 const unsigned char *rsa_e = NULL;
2476 const unsigned char *rsa_p = NULL;
2477 const unsigned char *rsa_q = NULL;
2478 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2479 unsigned int nbits;
2480 unsigned int maxbits;
2481 unsigned char *template = NULL;
2482 unsigned char *tp;
2483 size_t template_len;
2484 unsigned char fprbuf[20];
2485 u32 created_at = 0;
2487 (void)ctrl;
2489 if (!strcmp (keyid, "OPENPGP.1"))
2490 keyno = 0;
2491 else if (!strcmp (keyid, "OPENPGP.2"))
2492 keyno = 1;
2493 else if (!strcmp (keyid, "OPENPGP.3"))
2494 keyno = 2;
2495 else
2496 return gpg_error (GPG_ERR_INV_ID);
2498 err = does_key_exist (app, keyno, 0, force);
2499 if (err)
2500 return err;
2504 Parse the S-expression
2506 buf = keydata;
2507 buflen = keydatalen;
2508 depth = 0;
2509 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2510 goto leave;
2511 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2512 goto leave;
2513 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2515 if (!tok)
2517 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2518 log_info ("protected-private-key passed to writekey\n");
2519 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2520 log_info ("shadowed-private-key passed to writekey\n");
2521 err = gpg_error (GPG_ERR_BAD_SECKEY);
2522 goto leave;
2524 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2525 goto leave;
2526 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2527 goto leave;
2528 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2530 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2531 goto leave;
2533 last_depth1 = depth;
2534 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2535 && depth && depth >= last_depth1)
2537 if (tok)
2539 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2540 goto leave;
2542 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2543 goto leave;
2544 if (tok && toklen == 1)
2546 const unsigned char **mpi;
2547 size_t *mpi_len;
2549 switch (*tok)
2551 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2552 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2553 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2554 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2555 default: mpi = NULL; mpi_len = NULL; break;
2557 if (mpi && *mpi)
2559 err = gpg_error (GPG_ERR_DUP_VALUE);
2560 goto leave;
2562 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2563 goto leave;
2564 if (tok && mpi)
2566 /* Strip off leading zero bytes and save. */
2567 for (;toklen && !*tok; toklen--, tok++)
2569 *mpi = tok;
2570 *mpi_len = toklen;
2573 /* Skip until end of list. */
2574 last_depth2 = depth;
2575 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2576 && depth && depth >= last_depth2)
2578 if (err)
2579 goto leave;
2581 /* Parse other attributes. */
2582 last_depth1 = depth;
2583 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2584 && depth && depth >= last_depth1)
2586 if (tok)
2588 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2589 goto leave;
2591 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2592 goto leave;
2593 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2595 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2596 goto leave;
2597 if (tok)
2599 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2600 tok++, toklen--)
2601 created_at = created_at*10 + (*tok - '0');
2604 /* Skip until end of list. */
2605 last_depth2 = depth;
2606 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2607 && depth && depth >= last_depth2)
2609 if (err)
2610 goto leave;
2614 /* Check that we have all parameters and that they match the card
2615 description. */
2616 if (!created_at)
2618 log_error (_("creation timestamp missing\n"));
2619 err = gpg_error (GPG_ERR_INV_VALUE);
2620 goto leave;
2623 maxbits = app->app_local->keyattr[keyno].n_bits;
2624 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2625 if (opt.verbose)
2626 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2627 nbits, (unsigned int)rsa_n_len);
2628 if (nbits && nbits != maxbits
2629 && app->app_local->extcap.algo_attr_change)
2631 /* Try to switch the key to a new length. */
2632 err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2633 if (!err)
2634 maxbits = app->app_local->keyattr[keyno].n_bits;
2636 if (nbits != maxbits)
2638 log_error (_("RSA modulus missing or not of size %d bits\n"),
2639 (int)maxbits);
2640 err = gpg_error (GPG_ERR_BAD_SECKEY);
2641 goto leave;
2644 maxbits = app->app_local->keyattr[keyno].e_bits;
2645 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2646 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2647 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2648 if (nbits < 2 || nbits > maxbits)
2650 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2651 (int)maxbits);
2652 err = gpg_error (GPG_ERR_BAD_SECKEY);
2653 goto leave;
2656 maxbits = app->app_local->keyattr[keyno].n_bits/2;
2657 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2658 if (nbits != maxbits)
2660 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2661 "P", (int)maxbits);
2662 err = gpg_error (GPG_ERR_BAD_SECKEY);
2663 goto leave;
2665 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2666 if (nbits != maxbits)
2668 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2669 "Q", (int)maxbits);
2670 err = gpg_error (GPG_ERR_BAD_SECKEY);
2671 goto leave;
2674 /* We need to remove the cached public key. */
2675 xfree (app->app_local->pk[keyno].key);
2676 app->app_local->pk[keyno].key = NULL;
2677 app->app_local->pk[keyno].keylen = 0;
2678 app->app_local->pk[keyno].read_done = 0;
2681 if (app->app_local->extcap.is_v2)
2683 /* Build the private key template as described in section 4.3.3.7 of
2684 the OpenPGP card specs version 2.0. */
2685 int exmode;
2687 err = build_privkey_template (app, keyno,
2688 rsa_n, rsa_n_len,
2689 rsa_e, rsa_e_len,
2690 rsa_p, rsa_p_len,
2691 rsa_q, rsa_q_len,
2692 &template, &template_len);
2693 if (err)
2694 goto leave;
2696 /* Prepare for storing the key. */
2697 err = verify_chv3 (app, pincb, pincb_arg);
2698 if (err)
2699 goto leave;
2701 /* Store the key. */
2702 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2703 exmode = 1; /* Use extended length w/o a limit. */
2704 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2705 exmode = -254;
2706 else
2707 exmode = 0;
2708 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2709 template, template_len);
2711 else
2713 /* Build the private key template as described in section 4.3.3.6 of
2714 the OpenPGP card specs version 1.1:
2715 0xC0 <length> public exponent
2716 0xC1 <length> prime p
2717 0xC2 <length> prime q
2719 assert (rsa_e_len <= 4);
2720 template_len = (1 + 1 + 4
2721 + 1 + 1 + rsa_p_len
2722 + 1 + 1 + rsa_q_len);
2723 template = tp = xtrymalloc_secure (template_len);
2724 if (!template)
2726 err = gpg_error_from_syserror ();
2727 goto leave;
2729 *tp++ = 0xC0;
2730 *tp++ = 4;
2731 memcpy (tp, rsa_e, rsa_e_len);
2732 if (rsa_e_len < 4)
2734 /* Right justify E. */
2735 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2736 memset (tp, 0, 4-rsa_e_len);
2738 tp += 4;
2740 *tp++ = 0xC1;
2741 *tp++ = rsa_p_len;
2742 memcpy (tp, rsa_p, rsa_p_len);
2743 tp += rsa_p_len;
2745 *tp++ = 0xC2;
2746 *tp++ = rsa_q_len;
2747 memcpy (tp, rsa_q, rsa_q_len);
2748 tp += rsa_q_len;
2750 assert (tp - template == template_len);
2752 /* Prepare for storing the key. */
2753 err = verify_chv3 (app, pincb, pincb_arg);
2754 if (err)
2755 goto leave;
2757 /* Store the key. */
2758 err = iso7816_put_data (app->slot, 0,
2759 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2760 template, template_len);
2762 if (err)
2764 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2765 goto leave;
2768 err = store_fpr (app, keyno, created_at,
2769 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2770 fprbuf, app->card_version);
2771 if (err)
2772 goto leave;
2775 leave:
2776 xfree (template);
2777 return err;
2781 /* Handle the GENKEY command. */
2782 static gpg_error_t
2783 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
2784 time_t createtime,
2785 gpg_error_t (*pincb)(void*, const char *, char **),
2786 void *pincb_arg)
2788 int rc;
2789 char numbuf[30];
2790 unsigned char fprbuf[20];
2791 const unsigned char *keydata, *m, *e;
2792 unsigned char *buffer = NULL;
2793 size_t buflen, keydatalen, mlen, elen;
2794 time_t created_at;
2795 int keyno = atoi (keynostr);
2796 int force = (flags & 1);
2797 time_t start_at;
2798 int exmode;
2799 int le_value;
2800 unsigned int keybits;
2802 if (keyno < 1 || keyno > 3)
2803 return gpg_error (GPG_ERR_INV_ID);
2804 keyno--;
2806 /* We flush the cache to increase the traffic before a key
2807 generation. This _might_ help a card to gather more entropy. */
2808 flush_cache (app);
2810 /* Obviously we need to remove the cached public key. */
2811 xfree (app->app_local->pk[keyno].key);
2812 app->app_local->pk[keyno].key = NULL;
2813 app->app_local->pk[keyno].keylen = 0;
2814 app->app_local->pk[keyno].read_done = 0;
2816 /* Check whether a key already exists. */
2817 rc = does_key_exist (app, keyno, 1, force);
2818 if (rc)
2819 return rc;
2821 /* Because we send the key parameter back via status lines we need
2822 to put a limit on the max. allowed keysize. 2048 bit will
2823 already lead to a 527 byte long status line and thus a 4096 bit
2824 key would exceed the Assuan line length limit. */
2825 keybits = app->app_local->keyattr[keyno].n_bits;
2826 if (keybits > 3072)
2827 return gpg_error (GPG_ERR_TOO_LARGE);
2829 /* Prepare for key generation by verifying the Admin PIN. */
2830 rc = verify_chv3 (app, pincb, pincb_arg);
2831 if (rc)
2832 goto leave;
2834 /* Test whether we will need extended length mode. (1900 is an
2835 arbitrary length which for sure fits into a short apdu.) */
2836 if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
2838 exmode = 1; /* Use extended length w/o a limit. */
2839 le_value = app->app_local->extcap.max_rsp_data;
2840 /* No need to check le_value because it comes from a 16 bit
2841 value and thus can't create an overflow on a 32 bit
2842 system. */
2844 else
2846 exmode = 0;
2847 le_value = 256; /* Use legacy value. */
2850 log_info (_("please wait while key is being generated ...\n"));
2851 start_at = time (NULL);
2852 rc = iso7816_generate_keypair
2853 /* # warning key generation temporary replaced by reading an existing key. */
2854 /* rc = iso7816_read_public_key */
2855 (app->slot, exmode,
2856 (const unsigned char*)(keyno == 0? "\xB6" :
2857 keyno == 1? "\xB8" : "\xA4"), 2,
2858 le_value,
2859 &buffer, &buflen);
2860 if (rc)
2862 rc = gpg_error (GPG_ERR_CARD);
2863 log_error (_("generating key failed\n"));
2864 goto leave;
2866 log_info (_("key generation completed (%d seconds)\n"),
2867 (int)(time (NULL) - start_at));
2869 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2870 if (!keydata)
2872 rc = gpg_error (GPG_ERR_CARD);
2873 log_error (_("response does not contain the public key data\n"));
2874 goto leave;
2877 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2878 if (!m)
2880 rc = gpg_error (GPG_ERR_CARD);
2881 log_error (_("response does not contain the RSA modulus\n"));
2882 goto leave;
2884 /* log_printhex ("RSA n:", m, mlen); */
2885 send_key_data (ctrl, "n", m, mlen);
2887 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2888 if (!e)
2890 rc = gpg_error (GPG_ERR_CARD);
2891 log_error (_("response does not contain the RSA public exponent\n"));
2892 goto leave;
2894 /* log_printhex ("RSA e:", e, elen); */
2895 send_key_data (ctrl, "e", e, elen);
2897 created_at = createtime? createtime : gnupg_get_time ();
2898 sprintf (numbuf, "%lu", (unsigned long)created_at);
2899 send_status_info (ctrl, "KEY-CREATED-AT",
2900 numbuf, (size_t)strlen(numbuf), NULL, 0);
2902 rc = store_fpr (app, keyno, (u32)created_at,
2903 m, mlen, e, elen, fprbuf, app->card_version);
2904 if (rc)
2905 goto leave;
2906 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2909 leave:
2910 xfree (buffer);
2911 return rc;
2915 static unsigned long
2916 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2918 unsigned long ul;
2920 if (valuelen == 3 )
2921 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2922 else
2924 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2925 ul = 0;
2927 return ul;
2930 static unsigned long
2931 get_sig_counter (app_t app)
2933 void *relptr;
2934 unsigned char *value;
2935 size_t valuelen;
2936 unsigned long ul;
2938 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2939 if (!relptr)
2940 return 0;
2941 ul = convert_sig_counter_value (value, valuelen);
2942 xfree (relptr);
2943 return ul;
2946 static gpg_error_t
2947 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2949 const unsigned char *fpr;
2950 unsigned char *buffer;
2951 size_t buflen, n;
2952 int rc, i;
2954 assert (keyno >= 1 && keyno <= 3);
2956 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
2957 if (rc)
2959 log_error (_("error reading application data\n"));
2960 return gpg_error (GPG_ERR_GENERAL);
2962 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2963 if (!fpr || n != 60)
2965 xfree (buffer);
2966 log_error (_("error reading fingerprint DO\n"));
2967 return gpg_error (GPG_ERR_GENERAL);
2969 fpr += (keyno-1)*20;
2970 for (i=0; i < 20; i++)
2971 if (sha1fpr[i] != fpr[i])
2973 xfree (buffer);
2974 log_info (_("fingerprint on card does not match requested one\n"));
2975 return gpg_error (GPG_ERR_WRONG_SECKEY);
2977 xfree (buffer);
2978 return 0;
2982 /* If a fingerprint has been specified check it against the one on the
2983 card. This allows for a meaningful error message in case the key
2984 on the card has been replaced but the shadow information known to
2985 gpg has not been updated. If there is no fingerprint we assume
2986 that this is okay. */
2987 static gpg_error_t
2988 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2990 unsigned char tmp[20];
2991 const char *s;
2992 int n;
2994 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2996 if (n != 40)
2997 return gpg_error (GPG_ERR_INV_ID);
2998 else if (!*s)
2999 ; /* okay */
3000 else
3001 return gpg_error (GPG_ERR_INV_ID);
3003 for (s=fpr, n=0; n < 20; s += 2, n++)
3004 tmp[n] = xtoi_2 (s);
3005 return compare_fingerprint (app, keyno, tmp);
3010 /* Compute a digital signature on INDATA which is expected to be the
3011 raw message digest. For this application the KEYIDSTR consists of
3012 the serialnumber and the fingerprint delimited by a slash.
3014 Note that this function may return the error code
3015 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3016 not match the one required for the requested action (e.g. the
3017 serial number does not match).
3019 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3020 operation to the auth command.
3022 static gpg_error_t
3023 do_sign (app_t app, const char *keyidstr, int hashalgo,
3024 gpg_error_t (*pincb)(void*, const char *, char **),
3025 void *pincb_arg,
3026 const void *indata, size_t indatalen,
3027 unsigned char **outdata, size_t *outdatalen )
3029 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3030 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3031 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3032 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
3033 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3034 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3035 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3036 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3037 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3038 0x1C };
3039 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3040 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3041 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3042 0x00, 0x04, 0x20 };
3043 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3044 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3045 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3046 0x00, 0x04, 0x30 };
3047 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3048 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3049 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3050 0x00, 0x04, 0x40 };
3051 int rc;
3052 unsigned char data[19+64];
3053 size_t datalen;
3054 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3055 const char *s;
3056 int n;
3057 const char *fpr = NULL;
3058 unsigned long sigcount;
3059 int use_auth = 0;
3060 int exmode, le_value;
3062 if (!keyidstr || !*keyidstr)
3063 return gpg_error (GPG_ERR_INV_VALUE);
3065 /* Strip off known prefixes. */
3066 #define X(a,b,c,d) \
3067 if (hashalgo == GCRY_MD_ ## a \
3068 && (d) \
3069 && indatalen == sizeof b ## _prefix + (c) \
3070 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3072 indata = (const char*)indata + sizeof b ## _prefix; \
3073 indatalen -= sizeof b ## _prefix; \
3076 if (indatalen == 20)
3077 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3078 else X(SHA1, sha1, 20, 1)
3079 else X(RMD160, rmd160, 20, 1)
3080 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3081 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3082 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3083 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3084 else if ((indatalen == 28 || indatalen == 32
3085 || indatalen == 48 || indatalen ==64)
3086 && app->app_local->extcap.is_v2)
3087 ; /* Assume a plain SHA-3 digest has been given. */
3088 else
3090 log_error (_("card does not support digest algorithm %s\n"),
3091 gcry_md_algo_name (hashalgo));
3092 /* Or the supplied digest length does not match an algorithm. */
3093 return gpg_error (GPG_ERR_INV_VALUE);
3095 #undef X
3097 /* Check whether an OpenPGP card of any version has been requested. */
3098 if (!strcmp (keyidstr, "OPENPGP.1"))
3100 else if (!strcmp (keyidstr, "OPENPGP.3"))
3101 use_auth = 1;
3102 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3103 return gpg_error (GPG_ERR_INV_ID);
3104 else
3106 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3108 if (n != 32)
3109 return gpg_error (GPG_ERR_INV_ID);
3110 else if (!*s)
3111 ; /* no fingerprint given: we allow this for now. */
3112 else if (*s == '/')
3113 fpr = s + 1;
3114 else
3115 return gpg_error (GPG_ERR_INV_ID);
3117 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3118 tmp_sn[n] = xtoi_2 (s);
3120 if (app->serialnolen != 16)
3121 return gpg_error (GPG_ERR_INV_CARD);
3122 if (memcmp (app->serialno, tmp_sn, 16))
3123 return gpg_error (GPG_ERR_WRONG_CARD);
3126 /* If a fingerprint has been specified check it against the one on
3127 the card. This is allows for a meaningful error message in case
3128 the key on the card has been replaced but the shadow information
3129 known to gpg was not updated. If there is no fingerprint, gpg
3130 will detect a bogus signature anyway due to the
3131 verify-after-signing feature. */
3132 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3133 if (rc)
3134 return rc;
3136 /* Concatenate prefix and digest. */
3137 #define X(a,b,d) \
3138 if (hashalgo == GCRY_MD_ ## a && (d) ) \
3140 datalen = sizeof b ## _prefix + indatalen; \
3141 assert (datalen <= sizeof data); \
3142 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3143 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3146 X(SHA1, sha1, 1)
3147 else X(RMD160, rmd160, 1)
3148 else X(SHA224, sha224, app->app_local->extcap.is_v2)
3149 else X(SHA256, sha256, app->app_local->extcap.is_v2)
3150 else X(SHA384, sha384, app->app_local->extcap.is_v2)
3151 else X(SHA512, sha512, app->app_local->extcap.is_v2)
3152 else
3153 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3154 #undef X
3156 /* Redirect to the AUTH command if asked to. */
3157 if (use_auth)
3159 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3160 data, datalen,
3161 outdata, outdatalen);
3164 /* Show the number of signature done using this key. */
3165 sigcount = get_sig_counter (app);
3166 log_info (_("signatures created so far: %lu\n"), sigcount);
3168 /* Check CHV if needed. */
3169 if (!app->did_chv1 || app->force_chv1 )
3171 char *pinvalue;
3173 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3174 if (rc)
3175 return rc;
3177 app->did_chv1 = 1;
3179 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3180 sync, thus we verify CHV2 here using the given PIN. Cards
3181 with version2 to not have the need for a separate CHV2 and
3182 internally use just one. Obviously we can't do that if the
3183 keypad has been used. */
3184 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3186 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3187 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3188 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3189 if (rc)
3191 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3192 xfree (pinvalue);
3193 flush_cache_after_error (app);
3194 return rc;
3196 app->did_chv2 = 1;
3198 xfree (pinvalue);
3202 if (app->app_local->cardcap.ext_lc_le)
3204 exmode = 1; /* Use extended length. */
3205 le_value = app->app_local->extcap.max_rsp_data;
3207 else
3209 exmode = 0;
3210 le_value = 0;
3212 rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3213 outdata, outdatalen);
3214 return rc;
3217 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3218 on INDATA which is expected to be the raw message digest. For this
3219 application the KEYIDSTR consists of the serialnumber and the
3220 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3221 be given.
3223 Note that this function may return the error code
3224 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3225 not match the one required for the requested action (e.g. the
3226 serial number does not match). */
3227 static gpg_error_t
3228 do_auth (app_t app, const char *keyidstr,
3229 gpg_error_t (*pincb)(void*, const char *, char **),
3230 void *pincb_arg,
3231 const void *indata, size_t indatalen,
3232 unsigned char **outdata, size_t *outdatalen )
3234 int rc;
3235 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3236 const char *s;
3237 int n;
3238 const char *fpr = NULL;
3240 if (!keyidstr || !*keyidstr)
3241 return gpg_error (GPG_ERR_INV_VALUE);
3242 if (indatalen > 101) /* For a 2048 bit key. */
3243 return gpg_error (GPG_ERR_INV_VALUE);
3245 /* Check whether an OpenPGP card of any version has been requested. */
3246 if (!strcmp (keyidstr, "OPENPGP.3"))
3248 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3249 return gpg_error (GPG_ERR_INV_ID);
3250 else
3252 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3254 if (n != 32)
3255 return gpg_error (GPG_ERR_INV_ID);
3256 else if (!*s)
3257 ; /* no fingerprint given: we allow this for now. */
3258 else if (*s == '/')
3259 fpr = s + 1;
3260 else
3261 return gpg_error (GPG_ERR_INV_ID);
3263 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3264 tmp_sn[n] = xtoi_2 (s);
3266 if (app->serialnolen != 16)
3267 return gpg_error (GPG_ERR_INV_CARD);
3268 if (memcmp (app->serialno, tmp_sn, 16))
3269 return gpg_error (GPG_ERR_WRONG_CARD);
3272 /* If a fingerprint has been specified check it against the one on
3273 the card. This is allows for a meaningful error message in case
3274 the key on the card has been replaced but the shadow information
3275 known to gpg was not updated. If there is no fingerprint, gpg
3276 will detect a bogus signature anyway due to the
3277 verify-after-signing feature. */
3278 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3279 if (rc)
3280 return rc;
3282 rc = verify_chv2 (app, pincb, pincb_arg);
3283 if (!rc)
3285 int exmode, le_value;
3287 if (app->app_local->cardcap.ext_lc_le)
3289 exmode = 1; /* Use extended length. */
3290 le_value = app->app_local->extcap.max_rsp_data;
3292 else
3294 exmode = 0;
3295 le_value = 0;
3297 rc = iso7816_internal_authenticate (app->slot, exmode,
3298 indata, indatalen, le_value,
3299 outdata, outdatalen);
3301 return rc;
3305 static gpg_error_t
3306 do_decipher (app_t app, const char *keyidstr,
3307 gpg_error_t (*pincb)(void*, const char *, char **),
3308 void *pincb_arg,
3309 const void *indata, size_t indatalen,
3310 unsigned char **outdata, size_t *outdatalen )
3312 int rc;
3313 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3314 const char *s;
3315 int n;
3316 const char *fpr = NULL;
3317 int exmode, le_value;
3319 if (!keyidstr || !*keyidstr || !indatalen)
3320 return gpg_error (GPG_ERR_INV_VALUE);
3322 /* Check whether an OpenPGP card of any version has been requested. */
3323 if (!strcmp (keyidstr, "OPENPGP.2"))
3325 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3326 return gpg_error (GPG_ERR_INV_ID);
3327 else
3329 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3331 if (n != 32)
3332 return gpg_error (GPG_ERR_INV_ID);
3333 else if (!*s)
3334 ; /* no fingerprint given: we allow this for now. */
3335 else if (*s == '/')
3336 fpr = s + 1;
3337 else
3338 return gpg_error (GPG_ERR_INV_ID);
3340 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3341 tmp_sn[n] = xtoi_2 (s);
3343 if (app->serialnolen != 16)
3344 return gpg_error (GPG_ERR_INV_CARD);
3345 if (memcmp (app->serialno, tmp_sn, 16))
3346 return gpg_error (GPG_ERR_WRONG_CARD);
3349 /* If a fingerprint has been specified check it against the one on
3350 the card. This is allows for a meaningful error message in case
3351 the key on the card has been replaced but the shadow information
3352 known to gpg was not updated. If there is no fingerprint, the
3353 decryption won't produce the right plaintext anyway. */
3354 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3355 if (rc)
3356 return rc;
3358 rc = verify_chv2 (app, pincb, pincb_arg);
3359 if (!rc)
3361 size_t fixuplen;
3362 unsigned char *fixbuf = NULL;
3363 int padind = 0;
3365 /* We might encounter a couple of leading zeroes in the
3366 cryptogram. Due to internal use of MPIs thease leading
3367 zeroes are stripped. However the OpenPGP card expects
3368 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3369 need to fix it up. We do this for up to 16 leading zero
3370 bytes; a cryptogram with more than this is with a very high
3371 probability anyway broken. */
3372 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
3373 fixuplen = 128 - indatalen;
3374 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
3375 fixuplen = 192 - indatalen;
3376 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
3377 fixuplen = 256 - indatalen;
3378 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
3379 fixuplen = 384 - indatalen;
3380 else
3381 fixuplen = 0;
3383 if (fixuplen)
3385 /* While we have to prepend stuff anyway, we can also
3386 include the padding byte here so that iso1816_decipher
3387 does not need to do another data mangling. */
3388 fixuplen++;
3390 fixbuf = xtrymalloc (fixuplen + indatalen);
3391 if (!fixbuf)
3392 return gpg_error_from_syserror ();
3394 memset (fixbuf, 0, fixuplen);
3395 memcpy (fixbuf+fixuplen, indata, indatalen);
3396 indata = fixbuf;
3397 indatalen = fixuplen + indatalen;
3398 padind = -1; /* Already padded. */
3401 if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
3403 exmode = 1; /* Extended length w/o a limit. */
3404 le_value = app->app_local->extcap.max_rsp_data;
3406 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
3408 exmode = -254; /* Command chaining with max. 254 bytes. */
3409 le_value = 0;
3411 else
3412 exmode = le_value = 0;
3414 rc = iso7816_decipher (app->slot, exmode,
3415 indata, indatalen, le_value, padind,
3416 outdata, outdatalen);
3417 xfree (fixbuf);
3420 return rc;
3424 /* Perform a simple verify operation for CHV1 and CHV2, so that
3425 further operations won't ask for CHV2 and it is possible to do a
3426 cheap check on the PIN: If there is something wrong with the PIN
3427 entry system, only the regular CHV will get blocked and not the
3428 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3429 optional fingerprint part will be ignored.
3431 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3432 the "[CHV3]" being a literal string: The Admin Pin is checked if
3433 and only if the retry counter is still at 3. */
3434 static gpg_error_t
3435 do_check_pin (app_t app, const char *keyidstr,
3436 gpg_error_t (*pincb)(void*, const char *, char **),
3437 void *pincb_arg)
3439 unsigned char tmp_sn[20];
3440 const char *s;
3441 int n;
3442 int admin_pin = 0;
3444 if (!keyidstr || !*keyidstr)
3445 return gpg_error (GPG_ERR_INV_VALUE);
3447 /* Check whether an OpenPGP card of any version has been requested. */
3448 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3449 return gpg_error (GPG_ERR_INV_ID);
3451 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3453 if (n != 32)
3454 return gpg_error (GPG_ERR_INV_ID);
3455 else if (!*s)
3456 ; /* No fingerprint given: we allow this for now. */
3457 else if (*s == '/')
3458 ; /* We ignore a fingerprint. */
3459 else if (!strcmp (s, "[CHV3]") )
3460 admin_pin = 1;
3461 else
3462 return gpg_error (GPG_ERR_INV_ID);
3464 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3465 tmp_sn[n] = xtoi_2 (s);
3467 if (app->serialnolen != 16)
3468 return gpg_error (GPG_ERR_INV_CARD);
3469 if (memcmp (app->serialno, tmp_sn, 16))
3470 return gpg_error (GPG_ERR_WRONG_CARD);
3472 /* Yes, there is a race conditions: The user might pull the card
3473 right here and we won't notice that. However this is not a
3474 problem and the check above is merely for a graceful failure
3475 between operations. */
3477 if (admin_pin)
3479 void *relptr;
3480 unsigned char *value;
3481 size_t valuelen;
3482 int count;
3484 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3485 if (!relptr || valuelen < 7)
3487 log_error (_("error retrieving CHV status from card\n"));
3488 xfree (relptr);
3489 return gpg_error (GPG_ERR_CARD);
3491 count = value[6];
3492 xfree (relptr);
3494 if (!count)
3496 log_info (_("card is permanently locked!\n"));
3497 return gpg_error (GPG_ERR_BAD_PIN);
3499 else if (value[6] < 3)
3501 log_info (_("verification of Admin PIN is currently prohibited "
3502 "through this command\n"));
3503 return gpg_error (GPG_ERR_GENERAL);
3506 app->did_chv3 = 0; /* Force verification. */
3507 return verify_chv3 (app, pincb, pincb_arg);
3509 else
3510 return verify_chv2 (app, pincb, pincb_arg);
3514 /* Show information about card capabilities. */
3515 static void
3516 show_caps (struct app_local_s *s)
3518 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3519 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3520 if (s->extcap.get_challenge)
3521 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3522 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3523 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3524 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3525 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3526 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3527 if (s->extcap.sm_supported)
3528 log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3529 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3530 log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3531 log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3532 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3533 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3534 log_info ("Status Indicator: %02X\n", s->status_indicator);
3536 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
3537 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
3541 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3542 APPLOC. */
3543 static void
3544 parse_historical (struct app_local_s *apploc,
3545 const unsigned char * buffer, size_t buflen)
3547 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3548 if (buflen < 4)
3550 log_error ("warning: historical bytes are too short\n");
3551 return; /* Too short. */
3553 if (*buffer)
3555 log_error ("warning: bad category indicator in historical bytes\n");
3556 return;
3559 /* Skip category indicator. */
3560 buffer++;
3561 buflen--;
3563 /* Get the status indicator. */
3564 apploc->status_indicator = buffer[buflen-3];
3565 buflen -= 3;
3567 /* Parse the compact TLV. */
3568 while (buflen)
3570 unsigned int tag = (*buffer & 0xf0) >> 4;
3571 unsigned int len = (*buffer & 0x0f);
3572 if (len+1 > buflen)
3574 log_error ("warning: bad Compact-TLV in historical bytes\n");
3575 return; /* Error. */
3577 buffer++;
3578 buflen--;
3579 if (tag == 7 && len == 3)
3581 /* Card capabilities. */
3582 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3583 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
3585 buffer += len;
3586 buflen -= len;
3591 /* Parse and optionally show the algorithm attributes for KEYNO.
3592 KEYNO must be in the range 0..2. */
3593 static void
3594 parse_algorithm_attribute (app_t app, int keyno)
3596 unsigned char *buffer;
3597 size_t buflen;
3598 void *relptr;
3599 const char const desc[3][5] = {"sign", "encr", "auth"};
3601 assert (keyno >=0 && keyno <= 2);
3603 app->app_local->keyattr[keyno].n_bits = 0;
3605 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3606 if (!relptr)
3608 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3609 return;
3611 if (buflen < 1)
3613 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3614 xfree (relptr);
3615 return;
3618 if (opt.verbose)
3619 log_info ("Key-Attr-%s ..: ", desc[keyno]);
3620 if (*buffer == 1 && (buflen == 5 || buflen == 6))
3622 app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3623 app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3624 app->app_local->keyattr[keyno].format = 0;
3625 if (buflen < 6)
3626 app->app_local->keyattr[keyno].format = RSA_STD;
3627 else
3628 app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD :
3629 buffer[5] == 1? RSA_STD_N :
3630 buffer[5] == 2? RSA_CRT :
3631 buffer[5] == 3? RSA_CRT_N :
3632 RSA_UNKNOWN_FMT);
3634 if (opt.verbose)
3635 log_printf
3636 ("RSA, n=%u, e=%u, fmt=%s\n",
3637 app->app_local->keyattr[keyno].n_bits,
3638 app->app_local->keyattr[keyno].e_bits,
3639 app->app_local->keyattr[keyno].format == RSA_STD? "std" :
3640 app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3641 app->app_local->keyattr[keyno].format == RSA_CRT? "crt" :
3642 app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3644 else if (opt.verbose)
3645 log_printhex ("", buffer, buflen);
3647 xfree (relptr);
3650 /* Select the OpenPGP application on the card in SLOT. This function
3651 must be used before any other OpenPGP application functions. */
3652 gpg_error_t
3653 app_select_openpgp (app_t app)
3655 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3656 int slot = app->slot;
3657 int rc;
3658 unsigned char *buffer;
3659 size_t buflen;
3660 void *relptr;
3662 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3663 special flag value. */
3664 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3665 if (!rc)
3667 unsigned int manufacturer;
3669 app->apptype = "OPENPGP";
3671 app->did_chv1 = 0;
3672 app->did_chv2 = 0;
3673 app->did_chv3 = 0;
3674 app->app_local = NULL;
3676 /* The OpenPGP card returns the serial number as part of the
3677 AID; because we prefer to use OpenPGP serial numbers, we
3678 replace a possibly already set one from a EF.GDO with this
3679 one. Note, that for current OpenPGP cards, no EF.GDO exists
3680 and thus it won't matter at all. */
3681 rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
3682 if (rc)
3683 goto leave;
3684 if (opt.verbose)
3686 log_info ("AID: ");
3687 log_printhex ("", buffer, buflen);
3690 app->card_version = buffer[6] << 8;
3691 app->card_version |= buffer[7];
3692 manufacturer = (buffer[8]<<8 | buffer[9]);
3694 xfree (app->serialno);
3695 app->serialno = buffer;
3696 app->serialnolen = buflen;
3697 buffer = NULL;
3698 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3699 if (!app->app_local)
3701 rc = gpg_error (gpg_err_code_from_errno (errno));
3702 goto leave;
3705 if (app->card_version >= 0x0200)
3706 app->app_local->extcap.is_v2 = 1;
3709 /* Read the historical bytes. */
3710 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3711 if (relptr)
3713 if (opt.verbose)
3715 log_info ("Historical Bytes: ");
3716 log_printhex ("", buffer, buflen);
3718 parse_historical (app->app_local, buffer, buflen);
3719 xfree (relptr);
3722 /* Read the force-chv1 flag. */
3723 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3724 if (!relptr)
3726 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3727 "CHV Status Bytes");
3728 goto leave;
3730 app->force_chv1 = (buflen && *buffer == 0);
3731 xfree (relptr);
3733 /* Read the extended capabilities. */
3734 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3735 if (!relptr)
3737 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3738 "Extended Capability Flags" );
3739 goto leave;
3741 if (buflen)
3743 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
3744 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
3745 app->app_local->extcap.key_import = !!(*buffer & 0x20);
3746 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3747 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
3748 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3750 if (buflen >= 10)
3752 /* Available with v2 cards. */
3753 app->app_local->extcap.sm_aes128 = (buffer[1] == 1);
3754 app->app_local->extcap.max_get_challenge
3755 = (buffer[2] << 8 | buffer[3]);
3756 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3757 app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
3758 app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
3760 xfree (relptr);
3762 /* Some of the first cards accidently don't set the
3763 CHANGE_FORCE_CHV bit but allow it anyway. */
3764 if (app->card_version <= 0x0100 && manufacturer == 1)
3765 app->app_local->extcap.change_force_chv = 1;
3767 parse_login_data (app);
3769 if (opt.verbose)
3770 show_caps (app->app_local);
3772 parse_algorithm_attribute (app, 0);
3773 parse_algorithm_attribute (app, 1);
3774 parse_algorithm_attribute (app, 2);
3776 if (opt.verbose > 1)
3777 dump_all_do (slot);
3779 app->fnc.deinit = do_deinit;
3780 app->fnc.learn_status = do_learn_status;
3781 app->fnc.readcert = do_readcert;
3782 app->fnc.readkey = do_readkey;
3783 app->fnc.getattr = do_getattr;
3784 app->fnc.setattr = do_setattr;
3785 app->fnc.writecert = do_writecert;
3786 app->fnc.writekey = do_writekey;
3787 app->fnc.genkey = do_genkey;
3788 app->fnc.sign = do_sign;
3789 app->fnc.auth = do_auth;
3790 app->fnc.decipher = do_decipher;
3791 app->fnc.change_pin = do_change_pin;
3792 app->fnc.check_pin = do_check_pin;
3795 leave:
3796 if (rc)
3797 do_deinit (app);
3798 return rc;