Improved smartcard robustness.
[gnupg.git] / scd / app-openpgp.c
bloba633feab6c4570e10b1d71eac8be541c5e201481
1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3 * 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 * $Id$
23 /* Some notes:
25 CHV means Card Holder Verification and is nothing else than a PIN
26 or password. That term seems to have been used originally with GSM
27 cards. Version v2 of the specs changes the term to the clearer
28 term PW for password. We use the terms here interchangeable
29 because we do not want to change existing strings i18n wise.
31 Version 2 of the specs also drops the separate PW2 which was
32 required in v1 due to ISO requirements. It is now possible to have
33 one physical PW but two reference to it so that they can be
34 individually be verified (e.g. to implement a forced verification
35 for one key). Thus you will noticed the use of PW2 with the verify
36 command but not with change_reference_data because the latter
37 operates directly on the physical PW.
39 The Reset Code (RC) as implemented by v2 cards uses the same error
40 counter as the PW2 of v1 cards. By default no RC is set and thus
41 that error counter is set to 0. After setting the RC the error
42 counter will be initialized to 3.
46 #include <config.h>
47 #include <errno.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <assert.h>
52 #include <time.h>
54 #if GNUPG_MAJOR_VERSION == 1
55 /* This is used with GnuPG version < 1.9. The code has been source
56 copied from the current GnuPG >= 1.9 and is maintained over
57 there. */
58 #include "options.h"
59 #include "errors.h"
60 #include "memory.h"
61 #include "util.h"
62 #include "cardglue.h"
63 #else /* GNUPG_MAJOR_VERSION != 1 */
64 #include "scdaemon.h"
65 #endif /* GNUPG_MAJOR_VERSION != 1 */
67 #include "i18n.h"
68 #include "iso7816.h"
69 #include "app-common.h"
70 #include "tlv.h"
73 /* A table describing the DOs of the card. */
74 static struct {
75 int tag;
76 int constructed;
77 int get_from; /* Constructed DO with this DO or 0 for direct access. */
78 int binary;
79 int dont_cache;
80 int flush_on_error;
81 int get_immediate_in_v11; /* Enable a hack to bypass the cache of
82 this data object if it is used in 1.1
83 and later versions of the card. This
84 does not work with composite DO and is
85 currently only useful for the CHV
86 status bytes. */
87 char *desc;
88 } data_objects[] = {
89 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
90 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
91 { 0x5F52, 0, 0, 1, 0, 0, 0, "Historical Bytes" },
92 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
93 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
94 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
95 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
96 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
97 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
98 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
99 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
100 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
101 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
102 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
103 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
104 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
105 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
106 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
107 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
108 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
109 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
110 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
111 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
112 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
113 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
114 { 0x7F21, 1, 0, 1, 0, 0, 0, "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);
219 /* Deconstructor. */
220 static void
221 do_deinit (app_t app)
223 if (app && app->app_local)
225 struct cache_s *c, *c2;
226 int i;
228 for (c = app->app_local->cache; c; c = c2)
230 c2 = c->next;
231 xfree (c);
234 for (i=0; i < DIM (app->app_local->pk); i++)
236 xfree (app->app_local->pk[i].key);
237 app->app_local->pk[i].read_done = 0;
239 xfree (app->app_local);
240 app->app_local = NULL;
245 /* Wrapper around iso7816_get_data which first tries to get the data
246 from the cache. With GET_IMMEDIATE passed as true, the cache is
247 bypassed. */
248 static gpg_error_t
249 get_cached_data (app_t app, int tag,
250 unsigned char **result, size_t *resultlen,
251 int get_immediate)
253 gpg_error_t err;
254 int i;
255 unsigned char *p;
256 size_t len;
257 struct cache_s *c;
259 *result = NULL;
260 *resultlen = 0;
262 if (!get_immediate)
264 for (c=app->app_local->cache; c; c = c->next)
265 if (c->tag == tag)
267 if(c->length)
269 p = xtrymalloc (c->length);
270 if (!p)
271 return gpg_error (gpg_err_code_from_errno (errno));
272 memcpy (p, c->data, c->length);
273 *result = p;
276 *resultlen = c->length;
278 return 0;
282 err = iso7816_get_data (app->slot, tag, &p, &len);
283 if (err)
284 return err;
285 *result = p;
286 *resultlen = len;
288 /* Check whether we should cache this object. */
289 if (get_immediate)
290 return 0;
292 for (i=0; data_objects[i].tag; i++)
293 if (data_objects[i].tag == tag)
295 if (data_objects[i].dont_cache)
296 return 0;
297 break;
300 /* Okay, cache it. */
301 for (c=app->app_local->cache; c; c = c->next)
302 assert (c->tag != tag);
304 c = xtrymalloc (sizeof *c + len);
305 if (c)
307 memcpy (c->data, p, len);
308 c->length = len;
309 c->tag = tag;
310 c->next = app->app_local->cache;
311 app->app_local->cache = c;
314 return 0;
317 /* Remove DO at TAG from the cache. */
318 static void
319 flush_cache_item (app_t app, int tag)
321 struct cache_s *c, *cprev;
322 int i;
324 if (!app->app_local)
325 return;
327 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
328 if (c->tag == tag)
330 if (cprev)
331 cprev->next = c->next;
332 else
333 app->app_local->cache = c->next;
334 xfree (c);
336 for (c=app->app_local->cache; c ; c = c->next)
338 assert (c->tag != tag); /* Oops: duplicated entry. */
340 return;
343 /* Try again if we have an outer tag. */
344 for (i=0; data_objects[i].tag; i++)
345 if (data_objects[i].tag == tag && data_objects[i].get_from
346 && data_objects[i].get_from != tag)
347 flush_cache_item (app, data_objects[i].get_from);
350 /* Flush all entries from the cache which might be out of sync after
351 an error. */
352 static void
353 flush_cache_after_error (app_t app)
355 int i;
357 for (i=0; data_objects[i].tag; i++)
358 if (data_objects[i].flush_on_error)
359 flush_cache_item (app, data_objects[i].tag);
363 /* Flush the entire cache. */
364 static void
365 flush_cache (app_t app)
367 if (app && app->app_local)
369 struct cache_s *c, *c2;
371 for (c = app->app_local->cache; c; c = c2)
373 c2 = c->next;
374 xfree (c);
376 app->app_local->cache = NULL;
381 /* Get the DO identified by TAG from the card in SLOT and return a
382 buffer with its content in RESULT and NBYTES. The return value is
383 NULL if not found or a pointer which must be used to release the
384 buffer holding value. */
385 static void *
386 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
387 int *r_rc)
389 int rc, i;
390 unsigned char *buffer;
391 size_t buflen;
392 unsigned char *value;
393 size_t valuelen;
394 int dummyrc;
396 if (!r_rc)
397 r_rc = &dummyrc;
399 *result = NULL;
400 *nbytes = 0;
401 *r_rc = 0;
402 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
405 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
407 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
408 if (rc)
410 *r_rc = rc;
411 return NULL;
413 *result = buffer;
414 *nbytes = buflen;
415 return buffer;
418 value = NULL;
419 rc = -1;
420 if (data_objects[i].tag && data_objects[i].get_from)
422 rc = get_cached_data (app, data_objects[i].get_from,
423 &buffer, &buflen,
424 (data_objects[i].dont_cache
425 || data_objects[i].get_immediate_in_v11));
426 if (!rc)
428 const unsigned char *s;
430 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
431 if (!s)
432 value = NULL; /* not found */
433 else if (valuelen > buflen - (s - buffer))
435 log_error ("warning: constructed DO too short\n");
436 value = NULL;
437 xfree (buffer); buffer = NULL;
439 else
440 value = buffer + (s - buffer);
444 if (!value) /* Not in a constructed DO, try simple. */
446 rc = get_cached_data (app, tag, &buffer, &buflen,
447 (data_objects[i].dont_cache
448 || data_objects[i].get_immediate_in_v11));
449 if (!rc)
451 value = buffer;
452 valuelen = buflen;
456 if (!rc)
458 *nbytes = valuelen;
459 *result = value;
460 return buffer;
462 *r_rc = rc;
463 return NULL;
467 static void
468 dump_all_do (int slot)
470 int rc, i, j;
471 unsigned char *buffer;
472 size_t buflen;
474 for (i=0; data_objects[i].tag; i++)
476 if (data_objects[i].get_from)
477 continue;
479 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
480 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
482 else if (rc)
483 log_info ("DO `%s' not available: %s\n",
484 data_objects[i].desc, gpg_strerror (rc));
485 else
487 if (data_objects[i].binary)
489 log_info ("DO `%s': ", data_objects[i].desc);
490 log_printhex ("", buffer, buflen);
492 else
493 log_info ("DO `%s': `%.*s'\n",
494 data_objects[i].desc,
495 (int)buflen, buffer); /* FIXME: sanitize */
497 if (data_objects[i].constructed)
499 for (j=0; data_objects[j].tag; j++)
501 const unsigned char *value;
502 size_t valuelen;
504 if (j==i || data_objects[i].tag != data_objects[j].get_from)
505 continue;
506 value = find_tlv_unchecked (buffer, buflen,
507 data_objects[j].tag, &valuelen);
508 if (!value)
509 ; /* not found */
510 else if (valuelen > buflen - (value - buffer))
511 log_error ("warning: constructed DO too short\n");
512 else
514 if (data_objects[j].binary)
516 log_info ("DO `%s': ", data_objects[j].desc);
517 if (valuelen > 200)
518 log_info ("[%u]\n", (unsigned int)valuelen);
519 else
520 log_printhex ("", value, valuelen);
522 else
523 log_info ("DO `%s': `%.*s'\n",
524 data_objects[j].desc,
525 (int)valuelen, value); /* FIXME: sanitize */
530 xfree (buffer); buffer = NULL;
535 /* Count the number of bits, assuming the A represents an unsigned big
536 integer of length LEN bytes. */
537 static unsigned int
538 count_bits (const unsigned char *a, size_t len)
540 unsigned int n = len * 8;
541 int i;
543 for (; len && !*a; len--, a++, n -=8)
545 if (len)
547 for (i=7; i && !(*a & (1<<i)); i--)
548 n--;
550 return n;
553 /* GnuPG makes special use of the login-data DO, this function parses
554 the login data to store the flags for later use. It may be called
555 at any time and should be called after changing the login-data DO.
557 Everything up to a LF is considered a mailbox or account name. If
558 the first LF is followed by DC4 (0x14) control sequence are
559 expected up to the next LF. Control sequences are separated by FS
560 (0x18) and consist of key=value pairs. There is one key defined:
562 F=<flags>
564 Were FLAGS is a plain hexadecimal number representing flag values.
565 The lsb is here the rightmost bit. Defined flags bits are:
567 Bit 0 = CHV1 and CHV2 are not syncronized
568 Bit 1 = CHV2 has been been set to the default PIN of "123456"
569 (this implies that bit 0 is also set).
572 static void
573 parse_login_data (app_t app)
575 unsigned char *buffer, *p;
576 size_t buflen, len;
577 void *relptr;
579 /* Set defaults. */
580 app->app_local->flags.no_sync = 0;
581 app->app_local->flags.def_chv2 = 0;
583 /* Read the DO. */
584 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
585 if (!relptr)
586 return; /* Ooops. */
587 for (; buflen; buflen--, buffer++)
588 if (*buffer == '\n')
589 break;
590 if (buflen < 2 || buffer[1] != '\x14')
591 return; /* No control sequences. */
592 buflen--;
593 buffer++;
596 buflen--;
597 buffer++;
598 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
600 /* Flags control sequence found. */
601 int lastdig = 0;
603 /* For now we are only interested in the last digit, so skip
604 any leading digits but bail out on invalid characters. */
605 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
606 lastdig = xtoi_1 (p);
607 if (len && !(*p == '\n' || *p == '\x18'))
608 goto next; /* Invalid characters in field. */
609 app->app_local->flags.no_sync = !!(lastdig & 1);
610 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
612 next:
613 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
614 if (*buffer == '\n')
615 buflen = 1;
617 while (buflen);
619 xfree (relptr);
622 /* Note, that FPR must be at least 20 bytes. */
623 static gpg_error_t
624 store_fpr (int slot, int keynumber, u32 timestamp,
625 const unsigned char *m, size_t mlen,
626 const unsigned char *e, size_t elen,
627 unsigned char *fpr, unsigned int card_version)
629 unsigned int n, nbits;
630 unsigned char *buffer, *p;
631 int rc;
633 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
635 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
638 n = 6 + 2 + mlen + 2 + elen;
639 p = buffer = xtrymalloc (3 + n);
640 if (!buffer)
641 return gpg_error_from_syserror ();
643 *p++ = 0x99; /* ctb */
644 *p++ = n >> 8; /* 2 byte length header */
645 *p++ = n;
646 *p++ = 4; /* key packet version */
647 *p++ = timestamp >> 24;
648 *p++ = timestamp >> 16;
649 *p++ = timestamp >> 8;
650 *p++ = timestamp;
651 *p++ = 1; /* RSA */
652 nbits = count_bits (m, mlen);
653 *p++ = nbits >> 8;
654 *p++ = nbits;
655 memcpy (p, m, mlen); p += mlen;
656 nbits = count_bits (e, elen);
657 *p++ = nbits >> 8;
658 *p++ = nbits;
659 memcpy (p, e, elen); p += elen;
661 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
663 xfree (buffer);
665 rc = iso7816_put_data (slot, 0,
666 (card_version > 0x0007? 0xC7 : 0xC6)
667 + keynumber, fpr, 20);
668 if (rc)
669 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
671 if (!rc && card_version > 0x0100)
673 unsigned char buf[4];
675 buf[0] = timestamp >> 24;
676 buf[1] = timestamp >> 16;
677 buf[2] = timestamp >> 8;
678 buf[3] = timestamp;
680 rc = iso7816_put_data (slot, 0, 0xCE + keynumber, buf, 4);
681 if (rc)
682 log_error (_("failed to store the creation date: %s\n"),
683 gpg_strerror (rc));
686 return rc;
690 static void
691 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
692 int number, const unsigned char *fpr)
694 int i;
695 char buf[41];
696 char numbuf[25];
698 for (i=0; i < 20 && !fpr[i]; i++)
700 if (i==20)
701 return; /* All zero. */
702 bin2hex (fpr, 20, buf);
703 if (number == -1)
704 *numbuf = 0; /* Don't print the key number */
705 else
706 sprintf (numbuf, "%d", number);
707 send_status_info (ctrl, keyword,
708 numbuf, (size_t)strlen(numbuf),
709 buf, (size_t)strlen (buf), NULL, 0);
712 static void
713 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
714 int number, const unsigned char *stamp)
716 char numbuf1[50], numbuf2[50];
717 unsigned long value;
719 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
720 if (!value)
721 return;
722 sprintf (numbuf1, "%d", number);
723 sprintf (numbuf2, "%lu", value);
724 send_status_info (ctrl, keyword,
725 numbuf1, (size_t)strlen(numbuf1),
726 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
729 static void
730 send_key_data (ctrl_t ctrl, const char *name,
731 const unsigned char *a, size_t alen)
733 char *buf;
735 buf = bin2hex (a, alen, NULL);
736 if (!buf)
738 log_error ("memory allocation error in send_key_data\n");
739 return;
742 send_status_info (ctrl, "KEY-DATA",
743 name, (size_t)strlen(name),
744 buf, (size_t)strlen (buf),
745 NULL, 0);
746 xfree (buf);
750 static void
751 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
753 char buffer[200];
755 assert (number >=0 && number < DIM(app->app_local->keyattr));
757 /* We only support RSA thus the algo identifier is fixed to 1. */
758 snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
759 number+1,
760 app->app_local->keyattr[number].n_bits,
761 app->app_local->keyattr[number].e_bits,
762 app->app_local->keyattr[number].format);
763 send_status_direct (ctrl, keyword, buffer);
767 /* Implement the GETATTR command. This is similar to the LEARN
768 command but returns just one value via the status interface. */
769 static gpg_error_t
770 do_getattr (app_t app, ctrl_t ctrl, const char *name)
772 static struct {
773 const char *name;
774 int tag;
775 int special;
776 } table[] = {
777 { "DISP-NAME", 0x005B },
778 { "LOGIN-DATA", 0x005E },
779 { "DISP-LANG", 0x5F2D },
780 { "DISP-SEX", 0x5F35 },
781 { "PUBKEY-URL", 0x5F50 },
782 { "KEY-FPR", 0x00C5, 3 },
783 { "KEY-TIME", 0x00CD, 4 },
784 { "KEY-ATTR", 0x0000, -5 },
785 { "CA-FPR", 0x00C6, 3 },
786 { "CHV-STATUS", 0x00C4, 1 },
787 { "SIG-COUNTER", 0x0093, 2 },
788 { "SERIALNO", 0x004F, -1 },
789 { "AID", 0x004F },
790 { "EXTCAP", 0x0000, -2 },
791 { "PRIVATE-DO-1", 0x0101 },
792 { "PRIVATE-DO-2", 0x0102 },
793 { "PRIVATE-DO-3", 0x0103 },
794 { "PRIVATE-DO-4", 0x0104 },
795 { "$AUTHKEYID", 0x0000, -3 },
796 { "$DISPSERIALNO",0x0000, -4 },
797 { NULL, 0 }
799 int idx, i, rc;
800 void *relptr;
801 unsigned char *value;
802 size_t valuelen;
804 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
806 if (!table[idx].name)
807 return gpg_error (GPG_ERR_INV_NAME);
809 if (table[idx].special == -1)
811 /* The serial number is very special. We could have used the
812 AID DO to retrieve it, but we have it already in the app
813 context and the stamp argument is required anyway which we
814 can't by other means. The AID DO is available anyway but not
815 hex formatted. */
816 char *serial;
817 time_t stamp;
818 char tmp[50];
820 if (!app_get_serial_and_stamp (app, &serial, &stamp))
822 sprintf (tmp, "%lu", (unsigned long)stamp);
823 send_status_info (ctrl, "SERIALNO",
824 serial, strlen (serial),
825 tmp, strlen (tmp),
826 NULL, 0);
827 xfree (serial);
829 return 0;
831 if (table[idx].special == -2)
833 char tmp[100];
835 snprintf (tmp, sizeof tmp,
836 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d",
837 app->app_local->extcap.get_challenge,
838 app->app_local->extcap.key_import,
839 app->app_local->extcap.change_force_chv,
840 app->app_local->extcap.private_dos,
841 app->app_local->extcap.max_certlen_3,
842 app->app_local->extcap.algo_attr_change);
843 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
844 return 0;
846 if (table[idx].special == -3)
848 char const tmp[] = "OPENPGP.3";
849 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
850 return 0;
852 if (table[idx].special == -4)
854 char *serial;
855 time_t stamp;
857 if (!app_get_serial_and_stamp (app, &serial, &stamp))
859 if (strlen (serial) > 16+12)
861 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
862 xfree (serial);
863 return 0;
865 xfree (serial);
867 return gpg_error (GPG_ERR_INV_NAME);
869 if (table[idx].special == -5)
871 for (i=0; i < 3; i++)
872 send_key_attr (ctrl, app, table[idx].name, i);
873 return 0;
876 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
877 if (relptr)
879 if (table[idx].special == 1)
881 char numbuf[7*23];
883 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
884 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
885 send_status_info (ctrl, table[idx].name,
886 numbuf, strlen (numbuf), NULL, 0);
888 else if (table[idx].special == 2)
890 char numbuf[50];
892 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
893 send_status_info (ctrl, table[idx].name,
894 numbuf, strlen (numbuf), NULL, 0);
896 else if (table[idx].special == 3)
898 if (valuelen >= 60)
899 for (i=0; i < 3; i++)
900 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
902 else if (table[idx].special == 4)
904 if (valuelen >= 12)
905 for (i=0; i < 3; i++)
906 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
908 else
909 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
911 xfree (relptr);
913 return rc;
916 /* Retrieve the fingerprint from the card inserted in SLOT and write
917 the according hex representation to FPR. Caller must have provide
918 a buffer at FPR of least 41 bytes. Returns 0 on success or an
919 error code. */
920 #if GNUPG_MAJOR_VERSION > 1
921 static gpg_error_t
922 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
924 gpg_error_t err = 0;
925 void *relptr;
926 unsigned char *value;
927 size_t valuelen;
929 assert (keyno >=0 && keyno <= 2);
931 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
932 if (relptr && valuelen >= 60)
933 bin2hex (value+keyno*20, 20, fpr);
934 else
935 err = gpg_error (GPG_ERR_NOT_FOUND);
936 xfree (relptr);
937 return err;
939 #endif /*GNUPG_MAJOR_VERSION > 1*/
942 /* Retrieve the public key material for the RSA key, whose fingerprint
943 is FPR, from gpg output, which can be read through the stream FP.
944 The RSA modulus will be stored at the address of M and MLEN, the
945 public exponent at E and ELEN. Returns zero on success, an error
946 code on failure. Caller must release the allocated buffers at M
947 and E if the function returns success. */
948 #if GNUPG_MAJOR_VERSION > 1
949 static gpg_error_t
950 retrieve_key_material (FILE *fp, const char *hexkeyid,
951 const unsigned char **m, size_t *mlen,
952 const unsigned char **e, size_t *elen)
954 gcry_error_t err = 0;
955 char *line = NULL; /* read_line() buffer. */
956 size_t line_size = 0; /* Helper for for read_line. */
957 int found_key = 0; /* Helper to find a matching key. */
958 unsigned char *m_new = NULL;
959 unsigned char *e_new = NULL;
960 size_t m_new_n = 0;
961 size_t e_new_n = 0;
963 /* Loop over all records until we have found the subkey
964 corresponding to the fingerprint. Inm general the first record
965 should be the pub record, but we don't rely on that. Given that
966 we only need to look at one key, it is sufficient to compare the
967 keyid so that we don't need to look at "fpr" records. */
968 for (;;)
970 char *p;
971 char *fields[6];
972 int nfields;
973 size_t max_length;
974 gcry_mpi_t mpi;
975 int i;
977 max_length = 4096;
978 i = read_line (fp, &line, &line_size, &max_length);
979 if (!i)
980 break; /* EOF. */
981 if (i < 0)
983 err = gpg_error_from_syserror ();
984 goto leave; /* Error. */
986 if (!max_length)
988 err = gpg_error (GPG_ERR_TRUNCATED);
989 goto leave; /* Line truncated - we better stop processing. */
992 /* Parse the line into fields. */
993 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
995 fields[nfields] = p;
996 p = strchr (p, ':');
997 if (p)
998 *(p++) = 0;
1000 if (!nfields)
1001 continue; /* No fields at all - skip line. */
1003 if (!found_key)
1005 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1006 && nfields > 4 && !strcmp (fields[4], hexkeyid))
1007 found_key = 1;
1008 continue;
1011 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1012 break; /* Next key - stop. */
1014 if ( strcmp (fields[0], "pkd") )
1015 continue; /* Not a key data record. */
1016 i = 0; /* Avoid erroneous compiler warning. */
1017 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1018 || (!i && m_new) || (i && e_new))
1020 err = gpg_error (GPG_ERR_GENERAL);
1021 goto leave; /* Error: Invalid key data record or not an RSA key. */
1024 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1025 if (err)
1026 mpi = NULL;
1027 else if (!i)
1028 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1029 else
1030 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1031 gcry_mpi_release (mpi);
1032 if (err)
1033 goto leave;
1036 if (m_new && e_new)
1038 *m = m_new;
1039 *mlen = m_new_n;
1040 m_new = NULL;
1041 *e = e_new;
1042 *elen = e_new_n;
1043 e_new = NULL;
1045 else
1046 err = gpg_error (GPG_ERR_GENERAL);
1048 leave:
1049 xfree (m_new);
1050 xfree (e_new);
1051 xfree (line);
1052 return err;
1054 #endif /*GNUPG_MAJOR_VERSION > 1*/
1057 /* Get the public key for KEYNO and store it as an S-expresion with
1058 the APP handle. On error that field gets cleared. If we already
1059 know about the public key we will just return. Note that this does
1060 not mean a key is available; this is soley indicated by the
1061 presence of the app->app_local->pk[KEYNO-1].key field.
1063 Note that GnuPG 1.x does not need this and it would be too time
1064 consuming to send it just for the fun of it. However, given that we
1065 use the same code in gpg 1.4, we can't use the gcry S-expresion
1066 here but need to open encode it. */
1067 #if GNUPG_MAJOR_VERSION > 1
1068 static gpg_error_t
1069 get_public_key (app_t app, int keyno)
1071 gpg_error_t err = 0;
1072 unsigned char *buffer;
1073 const unsigned char *keydata, *m, *e;
1074 size_t buflen, keydatalen, mlen, elen;
1075 unsigned char *mbuf = NULL;
1076 unsigned char *ebuf = NULL;
1077 char *keybuf = NULL;
1078 char *keybuf_p;
1080 if (keyno < 1 || keyno > 3)
1081 return gpg_error (GPG_ERR_INV_ID);
1082 keyno--;
1084 /* Already cached? */
1085 if (app->app_local->pk[keyno].read_done)
1086 return 0;
1088 xfree (app->app_local->pk[keyno].key);
1089 app->app_local->pk[keyno].key = NULL;
1090 app->app_local->pk[keyno].keylen = 0;
1092 m = e = NULL; /* (avoid cc warning) */
1094 if (app->card_version > 0x0100)
1096 /* We may simply read the public key out of these cards. */
1097 err = iso7816_read_public_key
1098 (app->slot, 0, (const unsigned char*)(keyno == 0? "\xB6" :
1099 keyno == 1? "\xB8" : "\xA4"), 2,
1101 &buffer, &buflen);
1102 if (err)
1104 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1105 goto leave;
1108 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1109 if (!keydata)
1111 err = gpg_error (GPG_ERR_CARD);
1112 log_error (_("response does not contain the public key data\n"));
1113 goto leave;
1116 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1117 if (!m)
1119 err = gpg_error (GPG_ERR_CARD);
1120 log_error (_("response does not contain the RSA modulus\n"));
1121 goto leave;
1125 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1126 if (!e)
1128 err = gpg_error (GPG_ERR_CARD);
1129 log_error (_("response does not contain the RSA public exponent\n"));
1130 goto leave;
1133 /* Prepend numbers with a 0 if needed. */
1134 if (mlen && (*m & 0x80))
1136 mbuf = xtrymalloc ( mlen + 1);
1137 if (!mbuf)
1139 err = gpg_error_from_syserror ();
1140 goto leave;
1142 *mbuf = 0;
1143 memcpy (mbuf+1, m, mlen);
1144 mlen++;
1145 m = mbuf;
1147 if (elen && (*e & 0x80))
1149 ebuf = xtrymalloc ( elen + 1);
1150 if (!ebuf)
1152 err = gpg_error_from_syserror ();
1153 goto leave;
1155 *ebuf = 0;
1156 memcpy (ebuf+1, e, elen);
1157 elen++;
1158 e = ebuf;
1162 else
1164 /* Due to a design problem in v1.0 cards we can't get the public
1165 key out of these cards without doing a verify on CHV3.
1166 Clearly that is not an option and thus we try to locate the
1167 key using an external helper.
1169 The helper we use here is gpg itself, which should know about
1170 the key in any case. */
1172 char fpr[41];
1173 char *hexkeyid;
1174 char *command = NULL;
1175 FILE *fp;
1176 int ret;
1178 buffer = NULL; /* We don't need buffer. */
1180 err = retrieve_fpr_from_card (app, keyno, fpr);
1181 if (err)
1183 log_error ("error while retrieving fpr from card: %s\n",
1184 gpg_strerror (err));
1185 goto leave;
1187 hexkeyid = fpr + 24;
1189 ret = estream_asprintf (&command,
1190 "gpg --list-keys --with-colons --with-key-data '%s'",
1191 fpr);
1192 if (ret < 0)
1194 err = gpg_error_from_syserror ();
1195 goto leave;
1198 fp = popen (command, "r");
1199 xfree (command);
1200 if (!fp)
1202 err = gpg_error_from_syserror ();
1203 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1204 goto leave;
1207 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1208 fclose (fp);
1209 if (err)
1211 log_error ("error while retrieving key material through pipe: %s\n",
1212 gpg_strerror (err));
1213 goto leave;
1217 /* Allocate a buffer to construct the S-expression. */
1218 /* FIXME: We should provide a generalized S-expression creation
1219 mechanism. */
1220 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1221 if (!keybuf)
1223 err = gpg_error_from_syserror ();
1224 goto leave;
1227 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1228 keybuf_p = keybuf + strlen (keybuf);
1229 memcpy (keybuf_p, m, mlen);
1230 keybuf_p += mlen;
1231 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1232 keybuf_p += strlen (keybuf_p);
1233 memcpy (keybuf_p, e, elen);
1234 keybuf_p += elen;
1235 strcpy (keybuf_p, ")))");
1236 keybuf_p += strlen (keybuf_p);
1238 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1239 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1241 leave:
1242 /* Set a flag to indicate that we tried to read the key. */
1243 app->app_local->pk[keyno].read_done = 1;
1245 xfree (buffer);
1246 xfree (mbuf);
1247 xfree (ebuf);
1248 return 0;
1250 #endif /* GNUPG_MAJOR_VERSION > 1 */
1254 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1255 This is used by the LEARN command. */
1256 static gpg_error_t
1257 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1259 gpg_error_t err = 0;
1260 /* Note that GnuPG 1.x does not need this and it would be too time
1261 consuming to send it just for the fun of it. */
1262 #if GNUPG_MAJOR_VERSION > 1
1263 unsigned char grip[20];
1264 char gripstr[41];
1265 char idbuf[50];
1267 err = get_public_key (app, keyno);
1268 if (err)
1269 goto leave;
1271 assert (keyno >= 1 && keyno <= 3);
1272 if (!app->app_local->pk[keyno-1].key)
1273 goto leave; /* No such key - ignore. */
1275 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1276 app->app_local->pk[keyno-1].keylen,
1277 grip);
1278 if (err)
1279 goto leave;
1281 bin2hex (grip, 20, gripstr);
1283 sprintf (idbuf, "OPENPGP.%d", keyno);
1284 send_status_info (ctrl, "KEYPAIRINFO",
1285 gripstr, 40,
1286 idbuf, strlen (idbuf),
1287 NULL, (size_t)0);
1289 leave:
1290 #endif /* GNUPG_MAJOR_VERSION > 1 */
1292 return err;
1296 /* Handle the LEARN command for OpenPGP. */
1297 static gpg_error_t
1298 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1300 (void)flags;
1302 do_getattr (app, ctrl, "EXTCAP");
1303 do_getattr (app, ctrl, "DISP-NAME");
1304 do_getattr (app, ctrl, "DISP-LANG");
1305 do_getattr (app, ctrl, "DISP-SEX");
1306 do_getattr (app, ctrl, "PUBKEY-URL");
1307 do_getattr (app, ctrl, "LOGIN-DATA");
1308 do_getattr (app, ctrl, "KEY-FPR");
1309 if (app->card_version > 0x0100)
1310 do_getattr (app, ctrl, "KEY-TIME");
1311 do_getattr (app, ctrl, "CA-FPR");
1312 do_getattr (app, ctrl, "CHV-STATUS");
1313 do_getattr (app, ctrl, "SIG-COUNTER");
1314 if (app->app_local->extcap.private_dos)
1316 do_getattr (app, ctrl, "PRIVATE-DO-1");
1317 do_getattr (app, ctrl, "PRIVATE-DO-2");
1318 if (app->did_chv2)
1319 do_getattr (app, ctrl, "PRIVATE-DO-3");
1320 if (app->did_chv3)
1321 do_getattr (app, ctrl, "PRIVATE-DO-4");
1323 send_keypair_info (app, ctrl, 1);
1324 send_keypair_info (app, ctrl, 2);
1325 send_keypair_info (app, ctrl, 3);
1326 /* Note: We do not send the Cardholder Certificate, because that is
1327 relativly long and for OpenPGP applications not really needed. */
1328 return 0;
1332 /* Handle the READKEY command for OpenPGP. On success a canonical
1333 encoded S-expression with the public key will get stored at PK and
1334 its length (for assertions) at PKLEN; the caller must release that
1335 buffer. On error PK and PKLEN are not changed and an error code is
1336 returned. */
1337 static gpg_error_t
1338 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1340 #if GNUPG_MAJOR_VERSION > 1
1341 gpg_error_t err;
1342 int keyno;
1343 unsigned char *buf;
1345 if (!strcmp (keyid, "OPENPGP.1"))
1346 keyno = 1;
1347 else if (!strcmp (keyid, "OPENPGP.2"))
1348 keyno = 2;
1349 else if (!strcmp (keyid, "OPENPGP.3"))
1350 keyno = 3;
1351 else
1352 return gpg_error (GPG_ERR_INV_ID);
1354 err = get_public_key (app, keyno);
1355 if (err)
1356 return err;
1358 buf = app->app_local->pk[keyno-1].key;
1359 if (!buf)
1360 return gpg_error (GPG_ERR_NO_PUBKEY);
1361 *pklen = app->app_local->pk[keyno-1].keylen;;
1362 *pk = xtrymalloc (*pklen);
1363 if (!*pk)
1365 err = gpg_error_from_syserror ();
1366 *pklen = 0;
1367 return err;
1369 memcpy (*pk, buf, *pklen);
1370 return 0;
1371 #else
1372 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1373 #endif
1376 /* Read the standard certificate of an OpenPGP v2 card. It is
1377 returned in a freshly allocated buffer with that address stored at
1378 CERT and the length of the certificate stored at CERTLEN. CERTID
1379 needs to be set to "OPENPGP.3". */
1380 static gpg_error_t
1381 do_readcert (app_t app, const char *certid,
1382 unsigned char **cert, size_t *certlen)
1384 #if GNUPG_MAJOR_VERSION > 1
1385 gpg_error_t err;
1386 unsigned char *buffer;
1387 size_t buflen;
1388 void *relptr;
1390 *cert = NULL;
1391 *certlen = 0;
1392 if (strcmp (certid, "OPENPGP.3"))
1393 return gpg_error (GPG_ERR_INV_ID);
1394 if (!app->app_local->extcap.is_v2)
1395 return gpg_error (GPG_ERR_NOT_FOUND);
1397 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1398 if (!relptr)
1399 return gpg_error (GPG_ERR_NOT_FOUND);
1401 *cert = xtrymalloc (buflen);
1402 if (!*cert)
1403 err = gpg_error_from_syserror ();
1404 else
1406 memcpy (*cert, buffer, buflen);
1407 *certlen = buflen;
1408 err = 0;
1410 xfree (relptr);
1411 return err;
1412 #else
1413 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1414 #endif
1418 /* Verify a CHV either using using the pinentry or if possibile by
1419 using a keypad. PINCB and PINCB_ARG describe the usual callback
1420 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1421 used with CHV1. PINVALUE is the address of a pointer which will
1422 receive a newly allocated block with the actual PIN (this is useful
1423 in case that PIN shall be used for another verifiy operation). The
1424 caller needs to free this value. If the function returns with
1425 success and NULL is stored at PINVALUE, the caller should take this
1426 as an indication that the keypad has been used.
1428 static gpg_error_t
1429 verify_a_chv (app_t app,
1430 gpg_error_t (*pincb)(void*, const char *, char **),
1431 void *pincb_arg,
1432 int chvno, unsigned long sigcount, char **pinvalue)
1434 int rc = 0;
1435 char *prompt_buffer = NULL;
1436 const char *prompt;
1437 iso7816_pininfo_t pininfo;
1438 int minlen = 6;
1440 assert (chvno == 1 || chvno == 2);
1442 *pinvalue = NULL;
1444 if (chvno == 2 && app->app_local->flags.def_chv2)
1446 /* Special case for def_chv2 mechanism. */
1447 if (opt.verbose)
1448 log_info (_("using default PIN as %s\n"), "CHV2");
1449 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1450 if (rc)
1452 /* Verification of CHV2 with the default PIN failed,
1453 although the card pretends to have the default PIN set as
1454 CHV2. We better disable the def_chv2 flag now. */
1455 log_info (_("failed to use default PIN as %s: %s"
1456 " - disabling further default use\n"),
1457 "CHV2", gpg_strerror (rc));
1458 app->app_local->flags.def_chv2 = 0;
1460 return rc;
1463 memset (&pininfo, 0, sizeof pininfo);
1464 pininfo.mode = 1;
1465 pininfo.minlen = minlen;
1468 if (chvno == 1)
1470 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1471 size_t promptsize = strlen (PROMPTSTRING) + 50;
1473 prompt_buffer = xtrymalloc (promptsize);
1474 if (!prompt_buffer)
1475 return gpg_error_from_syserror ();
1476 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1477 prompt = prompt_buffer;
1478 #undef PROMPTSTRING
1480 else
1481 prompt = _("||Please enter the PIN");
1484 if (!opt.disable_keypad
1485 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1487 /* The reader supports the verify command through the keypad.
1488 Note that the pincb appends a text to the prompt telling the
1489 user to use the keypad. */
1490 rc = pincb (pincb_arg, prompt, NULL);
1491 prompt = NULL;
1492 xfree (prompt_buffer);
1493 prompt_buffer = NULL;
1494 if (rc)
1496 log_info (_("PIN callback returned error: %s\n"),
1497 gpg_strerror (rc));
1498 return rc;
1500 rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1501 /* Dismiss the prompt. */
1502 pincb (pincb_arg, NULL, NULL);
1504 assert (!*pinvalue);
1506 else
1508 /* The reader has no keypad or we don't want to use it. */
1509 rc = pincb (pincb_arg, prompt, pinvalue);
1510 prompt = NULL;
1511 xfree (prompt_buffer);
1512 prompt_buffer = NULL;
1513 if (rc)
1515 log_info (_("PIN callback returned error: %s\n"),
1516 gpg_strerror (rc));
1517 return rc;
1520 if (strlen (*pinvalue) < minlen)
1522 log_error (_("PIN for CHV%d is too short;"
1523 " minimum length is %d\n"), chvno, minlen);
1524 xfree (*pinvalue);
1525 *pinvalue = NULL;
1526 return gpg_error (GPG_ERR_BAD_PIN);
1529 rc = iso7816_verify (app->slot, 0x80+chvno,
1530 *pinvalue, strlen (*pinvalue));
1533 if (rc)
1535 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1536 xfree (*pinvalue);
1537 *pinvalue = NULL;
1538 flush_cache_after_error (app);
1541 return rc;
1545 /* Verify CHV2 if required. Depending on the configuration of the
1546 card CHV1 will also be verified. */
1547 static gpg_error_t
1548 verify_chv2 (app_t app,
1549 gpg_error_t (*pincb)(void*, const char *, char **),
1550 void *pincb_arg)
1552 int rc;
1553 char *pinvalue;
1555 if (app->did_chv2)
1556 return 0; /* We already verified CHV2. */
1558 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1559 if (rc)
1560 return rc;
1562 app->did_chv2 = 1;
1564 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1566 /* For convenience we verify CHV1 here too. We do this only if
1567 the card is not configured to require a verification before
1568 each CHV1 controlled operation (force_chv1) and if we are not
1569 using the keypad (PINVALUE == NULL). */
1570 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1571 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1572 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1573 if (rc)
1575 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1576 flush_cache_after_error (app);
1578 else
1579 app->did_chv1 = 1;
1581 xfree (pinvalue);
1583 return rc;
1587 /* Verify CHV3 if required. */
1588 static gpg_error_t
1589 verify_chv3 (app_t app,
1590 gpg_error_t (*pincb)(void*, const char *, char **),
1591 void *pincb_arg)
1593 int rc = 0;
1595 #if GNUPG_MAJOR_VERSION != 1
1596 if (!opt.allow_admin)
1598 log_info (_("access to admin commands is not configured\n"));
1599 return gpg_error (GPG_ERR_EACCES);
1601 #endif
1603 if (!app->did_chv3)
1605 void *relptr;
1606 unsigned char *value;
1607 size_t valuelen;
1608 iso7816_pininfo_t pininfo;
1609 int minlen = 8;
1610 int remaining;
1611 char *prompt_buffer = NULL;
1612 const char *prompt;
1614 memset (&pininfo, 0, sizeof pininfo);
1615 pininfo.mode = 1;
1616 pininfo.minlen = minlen;
1618 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1619 if (!relptr || valuelen < 7)
1621 log_error (_("error retrieving CHV status from card\n"));
1622 xfree (relptr);
1623 return gpg_error (GPG_ERR_CARD);
1625 if (value[6] == 0)
1627 log_info (_("card is permanently locked!\n"));
1628 xfree (relptr);
1629 return gpg_error (GPG_ERR_BAD_PIN);
1631 remaining = value[6];
1632 xfree (relptr);
1634 log_info(_("%d Admin PIN attempts remaining before card"
1635 " is permanently locked\n"), remaining);
1637 if (remaining < 3)
1639 /* TRANSLATORS: Do not translate the "|A|" prefix but keep
1640 it at the start of the string. Use %%0A to force a
1641 lienfeed. */
1642 #define PROMPTSTRING _("|A|Please enter the Admin PIN%%0A" \
1643 "[remaining attempts: %d]")
1644 size_t promptsize = strlen (PROMPTSTRING) + 50;
1646 prompt_buffer = xtrymalloc (promptsize);
1647 if (!prompt_buffer)
1648 return gpg_error_from_syserror ();
1649 snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, remaining);
1650 prompt = prompt_buffer;
1651 #undef PROMPTSTRING
1653 else
1654 prompt = _("|A|Please enter the Admin PIN");
1656 if (!opt.disable_keypad
1657 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1659 /* The reader supports the verify command through the keypad. */
1660 rc = pincb (pincb_arg, prompt, NULL);
1661 prompt = NULL;
1662 xfree (prompt_buffer);
1663 prompt_buffer = NULL;
1664 if (rc)
1666 log_info (_("PIN callback returned error: %s\n"),
1667 gpg_strerror (rc));
1668 return rc;
1670 rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1671 /* Dismiss the prompt. */
1672 pincb (pincb_arg, NULL, NULL);
1674 else
1676 char *pinvalue;
1678 rc = pincb (pincb_arg, prompt, &pinvalue);
1679 prompt = NULL;
1680 xfree (prompt_buffer);
1681 prompt_buffer = NULL;
1682 if (rc)
1684 log_info (_("PIN callback returned error: %s\n"),
1685 gpg_strerror (rc));
1686 return rc;
1689 if (strlen (pinvalue) < minlen)
1691 log_error (_("PIN for CHV%d is too short;"
1692 " minimum length is %d\n"), 3, minlen);
1693 xfree (pinvalue);
1694 return gpg_error (GPG_ERR_BAD_PIN);
1697 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1698 xfree (pinvalue);
1701 if (rc)
1703 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1704 flush_cache_after_error (app);
1705 return rc;
1707 app->did_chv3 = 1;
1709 return rc;
1713 /* Handle the SETATTR operation. All arguments are already basically
1714 checked. */
1715 static gpg_error_t
1716 do_setattr (app_t app, const char *name,
1717 gpg_error_t (*pincb)(void*, const char *, char **),
1718 void *pincb_arg,
1719 const unsigned char *value, size_t valuelen)
1721 gpg_error_t rc;
1722 int idx;
1723 static struct {
1724 const char *name;
1725 int tag;
1726 int need_chv;
1727 int special;
1728 unsigned int need_v2:1;
1729 } table[] = {
1730 { "DISP-NAME", 0x005B, 3 },
1731 { "LOGIN-DATA", 0x005E, 3, 2 },
1732 { "DISP-LANG", 0x5F2D, 3 },
1733 { "DISP-SEX", 0x5F35, 3 },
1734 { "PUBKEY-URL", 0x5F50, 3 },
1735 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1736 { "CA-FPR-1", 0x00CA, 3 },
1737 { "CA-FPR-2", 0x00CB, 3 },
1738 { "CA-FPR-3", 0x00CC, 3 },
1739 { "PRIVATE-DO-1", 0x0101, 2 },
1740 { "PRIVATE-DO-2", 0x0102, 3 },
1741 { "PRIVATE-DO-3", 0x0103, 2 },
1742 { "PRIVATE-DO-4", 0x0104, 3 },
1743 { "CERT-3", 0x7F21, 3, 0, 1 },
1744 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1745 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1746 { NULL, 0 }
1748 int exmode;
1750 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1752 if (!table[idx].name)
1753 return gpg_error (GPG_ERR_INV_NAME);
1754 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1755 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1757 switch (table[idx].need_chv)
1759 case 2:
1760 rc = verify_chv2 (app, pincb, pincb_arg);
1761 break;
1762 case 3:
1763 rc = verify_chv3 (app, pincb, pincb_arg);
1764 break;
1765 default:
1766 rc = 0;
1768 if (rc)
1769 return rc;
1771 /* Flush the cache before writing it, so that the next get operation
1772 will reread the data from the card and thus get synced in case of
1773 errors (e.g. data truncated by the card). */
1774 flush_cache_item (app, table[idx].tag);
1776 if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1777 exmode = 1; /* Use extended length w/o a limit. */
1778 else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1779 exmode = -254; /* Command chaining with max. 254 bytes. */
1780 else
1781 exmode = 0;
1782 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1783 if (rc)
1784 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1786 if (table[idx].special == 1)
1787 app->force_chv1 = (valuelen && *value == 0);
1788 else if (table[idx].special == 2)
1789 parse_login_data (app);
1791 return rc;
1795 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1796 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1797 PINCB and PINCB_ARG are the usual arguments for the pinentry
1798 callback. */
1799 static gpg_error_t
1800 do_writecert (app_t app, ctrl_t ctrl,
1801 const char *certidstr,
1802 gpg_error_t (*pincb)(void*, const char *, char **),
1803 void *pincb_arg,
1804 const unsigned char *certdata, size_t certdatalen)
1806 (void)ctrl;
1807 #if GNUPG_MAJOR_VERSION > 1
1808 if (strcmp (certidstr, "OPENPGP.3"))
1809 return gpg_error (GPG_ERR_INV_ID);
1810 if (!certdata || !certdatalen)
1811 return gpg_error (GPG_ERR_INV_ARG);
1812 if (!app->app_local->extcap.is_v2)
1813 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1814 if (certdatalen > app->app_local->extcap.max_certlen_3)
1815 return gpg_error (GPG_ERR_TOO_LARGE);
1816 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1817 #else
1818 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1819 #endif
1824 /* Handle the PASSWD command. */
1825 static gpg_error_t
1826 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
1827 unsigned int flags,
1828 gpg_error_t (*pincb)(void*, const char *, char **),
1829 void *pincb_arg)
1831 int rc = 0;
1832 int chvno = atoi (chvnostr);
1833 char *resetcode = NULL;
1834 char *pinvalue;
1835 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1836 int set_resetcode = 0;
1838 (void)ctrl;
1840 if (reset_mode && chvno == 3)
1842 rc = gpg_error (GPG_ERR_INV_ID);
1843 goto leave;
1845 else if (reset_mode || chvno == 3)
1847 /* We always require that the PIN is entered. */
1848 app->did_chv3 = 0;
1849 rc = verify_chv3 (app, pincb, pincb_arg);
1850 if (rc)
1851 goto leave;
1853 if (chvno == 2 && app->app_local->extcap.is_v2)
1854 set_resetcode = 1;
1856 else if (chvno == 2 && app->app_local->extcap.is_v2)
1858 /* There is no PW2 for v2 cards. We use this condition to allow
1859 a PW reset using the Reset Code. */
1860 void *relptr;
1861 unsigned char *value;
1862 size_t valuelen;
1863 int remaining;
1865 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1866 if (!relptr || valuelen < 7)
1868 log_error (_("error retrieving CHV status from card\n"));
1869 xfree (relptr);
1870 rc = gpg_error (GPG_ERR_CARD);
1871 goto leave;
1873 remaining = value[5];
1874 xfree (relptr);
1875 if (!remaining)
1877 log_error (_("Reset Code not or not anymore available\n"));
1878 rc = gpg_error (GPG_ERR_BAD_PIN);
1879 goto leave;
1882 rc = pincb (pincb_arg, _("||Please enter the Reset Code for the card"),
1883 &resetcode);
1884 if (rc)
1886 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1887 goto leave;
1889 if (strlen (resetcode) < 8)
1891 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1892 rc = gpg_error (GPG_ERR_BAD_PIN);
1893 goto leave;
1896 else if (chvno == 1 || chvno == 2)
1898 /* CHV1 and CVH2 should always have the same value, thus we
1899 enforce it here. */
1900 int save_force = app->force_chv1;
1902 app->force_chv1 = 0;
1903 app->did_chv1 = 0;
1904 app->did_chv2 = 0;
1905 rc = verify_chv2 (app, pincb, pincb_arg);
1906 app->force_chv1 = save_force;
1907 if (rc)
1908 goto leave;
1910 else
1912 rc = gpg_error (GPG_ERR_INV_ID);
1913 goto leave;
1916 if (chvno == 3)
1917 app->did_chv3 = 0;
1918 else
1919 app->did_chv1 = app->did_chv2 = 0;
1921 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1922 keep it at the start of the string. We need this elsewhere
1923 to get some infos on the string. */
1924 rc = pincb (pincb_arg,
1925 set_resetcode? _("|RN|New Reset Code") :
1926 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1927 &pinvalue);
1928 if (rc)
1930 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1931 goto leave;
1934 if (resetcode)
1936 char *buffer;
1938 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
1939 if (!buffer)
1940 rc = gpg_error_from_syserror ();
1941 else
1943 strcpy (stpcpy (buffer, resetcode), pinvalue);
1944 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
1945 buffer, strlen (buffer));
1946 wipememory (buffer, strlen (buffer));
1947 xfree (buffer);
1950 else if (set_resetcode)
1952 if (strlen (pinvalue) < 8)
1954 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1955 rc = gpg_error (GPG_ERR_BAD_PIN);
1957 else
1958 rc = iso7816_put_data (app->slot, 0, 0xD3,
1959 pinvalue, strlen (pinvalue));
1961 else if (reset_mode)
1963 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1964 pinvalue, strlen (pinvalue));
1965 if (!rc && !app->app_local->extcap.is_v2)
1966 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1967 pinvalue, strlen (pinvalue));
1969 else
1971 if (chvno == 1 || chvno == 2)
1973 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1974 pinvalue, strlen (pinvalue));
1975 if (!rc && !app->app_local->extcap.is_v2)
1976 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1977 pinvalue, strlen (pinvalue));
1979 else
1980 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1981 pinvalue, strlen (pinvalue));
1983 if (pinvalue)
1985 wipememory (pinvalue, strlen (pinvalue));
1986 xfree (pinvalue);
1988 if (rc)
1989 flush_cache_after_error (app);
1991 leave:
1992 if (resetcode)
1994 wipememory (resetcode, strlen (resetcode));
1995 xfree (resetcode);
1997 return rc;
2001 /* Check whether a key already exists. KEYIDX is the index of the key
2002 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2003 error returned if the key already exists. */
2004 static gpg_error_t
2005 does_key_exist (app_t app, int keyidx, int force)
2007 const unsigned char *fpr;
2008 unsigned char *buffer;
2009 size_t buflen, n;
2010 int i;
2012 assert (keyidx >=0 && keyidx <= 2);
2014 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
2016 log_error (_("error reading application data\n"));
2017 return gpg_error (GPG_ERR_GENERAL);
2019 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2020 if (!fpr || n < 60)
2022 log_error (_("error reading fingerprint DO\n"));
2023 xfree (buffer);
2024 return gpg_error (GPG_ERR_GENERAL);
2026 fpr += 20*keyidx;
2027 for (i=0; i < 20 && !fpr[i]; i++)
2029 xfree (buffer);
2030 if (i!=20 && !force)
2032 log_error (_("key already exists\n"));
2033 return gpg_error (GPG_ERR_EEXIST);
2035 else if (i!=20)
2036 log_info (_("existing key will be replaced\n"));
2037 else
2038 log_info (_("generating new key\n"));
2039 return 0;
2043 /* Create a TLV tag and value and store it at BUFFER. Return the length
2044 of tag and length. A LENGTH greater than 65535 is truncated. */
2045 static size_t
2046 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2048 unsigned char *p = buffer;
2050 assert (tag <= 0xffff);
2051 if ( tag > 0xff )
2052 *p++ = tag >> 8;
2053 *p++ = tag;
2054 if (length < 128)
2055 *p++ = length;
2056 else if (length < 256)
2058 *p++ = 0x81;
2059 *p++ = length;
2061 else
2063 if (length > 0xffff)
2064 length = 0xffff;
2065 *p++ = 0x82;
2066 *p++ = length >> 8;
2067 *p++ = length;
2070 return p - buffer;
2074 /* Build the private key template as specified in the OpenPGP specs
2075 v2.0 section 4.3.3.7. */
2076 static gpg_error_t
2077 build_privkey_template (app_t app, int keyno,
2078 const unsigned char *rsa_n, size_t rsa_n_len,
2079 const unsigned char *rsa_e, size_t rsa_e_len,
2080 const unsigned char *rsa_p, size_t rsa_p_len,
2081 const unsigned char *rsa_q, size_t rsa_q_len,
2082 unsigned char **result, size_t *resultlen)
2084 size_t rsa_e_reqlen;
2085 unsigned char privkey[7*(1+3)];
2086 size_t privkey_len;
2087 unsigned char exthdr[2+2+3];
2088 size_t exthdr_len;
2089 unsigned char suffix[2+3];
2090 size_t suffix_len;
2091 unsigned char *tp;
2092 size_t datalen;
2093 unsigned char *template;
2094 size_t template_size;
2096 *result = NULL;
2097 *resultlen = 0;
2099 switch (app->app_local->keyattr[keyno].format)
2101 case RSA_STD:
2102 case RSA_STD_N:
2103 break;
2104 case RSA_CRT:
2105 case RSA_CRT_N:
2106 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2108 default:
2109 return gpg_error (GPG_ERR_INV_VALUE);
2112 /* Get the required length for E. */
2113 rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2114 assert (rsa_e_len <= rsa_e_reqlen);
2116 /* Build the 7f48 cardholder private key template. */
2117 datalen = 0;
2118 tp = privkey;
2120 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2121 datalen += rsa_e_reqlen;
2123 tp += add_tlv (tp, 0x92, rsa_p_len);
2124 datalen += rsa_p_len;
2126 tp += add_tlv (tp, 0x93, rsa_q_len);
2127 datalen += rsa_q_len;
2129 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2130 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2132 tp += add_tlv (tp, 0x97, rsa_n_len);
2133 datalen += rsa_n_len;
2135 privkey_len = tp - privkey;
2137 /* Build the extended header list without the private key template. */
2138 tp = exthdr;
2139 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2140 *tp++ = 0;
2141 tp += add_tlv (tp, 0x7f48, privkey_len);
2142 exthdr_len = tp - exthdr;
2144 /* Build the 5f48 suffix of the data. */
2145 tp = suffix;
2146 tp += add_tlv (tp, 0x5f48, datalen);
2147 suffix_len = tp - suffix;
2149 /* Now concatenate everything. */
2150 template_size = (1 + 3 /* 0x4d and len. */
2151 + exthdr_len
2152 + privkey_len
2153 + suffix_len
2154 + datalen);
2155 tp = template = xtrymalloc_secure (template_size);
2156 if (!template)
2157 return gpg_error_from_syserror ();
2159 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2160 memcpy (tp, exthdr, exthdr_len);
2161 tp += exthdr_len;
2162 memcpy (tp, privkey, privkey_len);
2163 tp += privkey_len;
2164 memcpy (tp, suffix, suffix_len);
2165 tp += suffix_len;
2167 memcpy (tp, rsa_e, rsa_e_len);
2168 if (rsa_e_len < rsa_e_reqlen)
2170 /* Right justify E. */
2171 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2172 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2174 tp += rsa_e_reqlen;
2176 memcpy (tp, rsa_p, rsa_p_len);
2177 tp += rsa_p_len;
2179 memcpy (tp, rsa_q, rsa_q_len);
2180 tp += rsa_q_len;
2182 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2183 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2185 memcpy (tp, rsa_n, rsa_n_len);
2186 tp += rsa_n_len;
2189 /* Sanity check. We don't know the exact length because we
2190 allocated 3 bytes for the first length header. */
2191 assert (tp - template <= template_size);
2193 *result = template;
2194 *resultlen = tp - template;
2195 return 0;
2200 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2201 canonical encoded S-expression with the secret key in KEYDATA and
2202 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2203 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2204 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2205 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2206 the pinentry callback. */
2207 static gpg_error_t
2208 do_writekey (app_t app, ctrl_t ctrl,
2209 const char *keyid, unsigned int flags,
2210 gpg_error_t (*pincb)(void*, const char *, char **),
2211 void *pincb_arg,
2212 const unsigned char *keydata, size_t keydatalen)
2214 gpg_error_t err;
2215 int force = (flags & 1);
2216 int keyno;
2217 const unsigned char *buf, *tok;
2218 size_t buflen, toklen;
2219 int depth, last_depth1, last_depth2;
2220 const unsigned char *rsa_n = NULL;
2221 const unsigned char *rsa_e = NULL;
2222 const unsigned char *rsa_p = NULL;
2223 const unsigned char *rsa_q = NULL;
2224 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2225 unsigned int nbits;
2226 unsigned int maxbits;
2227 unsigned char *template = NULL;
2228 unsigned char *tp;
2229 size_t template_len;
2230 unsigned char fprbuf[20];
2231 u32 created_at = 0;
2233 (void)ctrl;
2235 if (!strcmp (keyid, "OPENPGP.1"))
2236 keyno = 0;
2237 else if (!strcmp (keyid, "OPENPGP.2"))
2238 keyno = 1;
2239 else if (!strcmp (keyid, "OPENPGP.3"))
2240 keyno = 2;
2241 else
2242 return gpg_error (GPG_ERR_INV_ID);
2244 err = does_key_exist (app, keyno, force);
2245 if (err)
2246 return err;
2250 Parse the S-expression
2252 buf = keydata;
2253 buflen = keydatalen;
2254 depth = 0;
2255 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2256 goto leave;
2257 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2258 goto leave;
2259 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2261 if (!tok)
2263 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2264 log_info ("protected-private-key passed to writekey\n");
2265 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2266 log_info ("shadowed-private-key passed to writekey\n");
2267 err = gpg_error (GPG_ERR_BAD_SECKEY);
2268 goto leave;
2270 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2271 goto leave;
2272 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2273 goto leave;
2274 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2276 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2277 goto leave;
2279 last_depth1 = depth;
2280 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2281 && depth && depth >= last_depth1)
2283 if (tok)
2285 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2286 goto leave;
2288 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2289 goto leave;
2290 if (tok && toklen == 1)
2292 const unsigned char **mpi;
2293 size_t *mpi_len;
2295 switch (*tok)
2297 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2298 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2299 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2300 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2301 default: mpi = NULL; mpi_len = NULL; break;
2303 if (mpi && *mpi)
2305 err = gpg_error (GPG_ERR_DUP_VALUE);
2306 goto leave;
2308 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2309 goto leave;
2310 if (tok && mpi)
2312 /* Strip off leading zero bytes and save. */
2313 for (;toklen && !*tok; toklen--, tok++)
2315 *mpi = tok;
2316 *mpi_len = toklen;
2319 /* Skip until end of list. */
2320 last_depth2 = depth;
2321 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2322 && depth && depth >= last_depth2)
2324 if (err)
2325 goto leave;
2327 /* Parse other attributes. */
2328 last_depth1 = depth;
2329 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2330 && depth && depth >= last_depth1)
2332 if (tok)
2334 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2335 goto leave;
2337 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2338 goto leave;
2339 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2341 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2342 goto leave;
2343 if (tok)
2345 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2346 tok++, toklen--)
2347 created_at = created_at*10 + (*tok - '0');
2350 /* Skip until end of list. */
2351 last_depth2 = depth;
2352 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2353 && depth && depth >= last_depth2)
2355 if (err)
2356 goto leave;
2360 /* Check that we have all parameters and that they match the card
2361 description. */
2362 if (!created_at)
2364 log_error (_("creation timestamp missing\n"));
2365 err = gpg_error (GPG_ERR_INV_VALUE);
2366 goto leave;
2369 maxbits = app->app_local->keyattr[keyno].n_bits;
2370 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2371 if (nbits != maxbits)
2373 log_error (_("RSA modulus missing or not of size %d bits\n"),
2374 (int)maxbits);
2375 err = gpg_error (GPG_ERR_BAD_SECKEY);
2376 goto leave;
2379 maxbits = app->app_local->keyattr[keyno].e_bits;
2380 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2381 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2382 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2383 if (nbits < 2 || nbits > maxbits)
2385 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2386 (int)maxbits);
2387 err = gpg_error (GPG_ERR_BAD_SECKEY);
2388 goto leave;
2391 maxbits = app->app_local->keyattr[keyno].n_bits/2;
2392 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2393 if (nbits != maxbits)
2395 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2396 "P", (int)maxbits);
2397 err = gpg_error (GPG_ERR_BAD_SECKEY);
2398 goto leave;
2400 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2401 if (nbits != maxbits)
2403 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2404 "Q", (int)maxbits);
2405 err = gpg_error (GPG_ERR_BAD_SECKEY);
2406 goto leave;
2409 /* We need to remove the cached public key. */
2410 xfree (app->app_local->pk[keyno].key);
2411 app->app_local->pk[keyno].key = NULL;
2412 app->app_local->pk[keyno].keylen = 0;
2413 app->app_local->pk[keyno].read_done = 0;
2416 if (app->app_local->extcap.is_v2)
2418 /* Build the private key template as described in section 4.3.3.7 of
2419 the OpenPGP card specs version 2.0. */
2420 int exmode;
2422 err = build_privkey_template (app, keyno,
2423 rsa_n, rsa_n_len,
2424 rsa_e, rsa_e_len,
2425 rsa_p, rsa_p_len,
2426 rsa_q, rsa_q_len,
2427 &template, &template_len);
2428 if (err)
2429 goto leave;
2431 /* Prepare for storing the key. */
2432 err = verify_chv3 (app, pincb, pincb_arg);
2433 if (err)
2434 goto leave;
2436 /* Store the key. */
2437 if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2438 exmode = 1; /* Use extended length w/o a limit. */
2439 else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2440 exmode = -254;
2441 else
2442 exmode = 0;
2443 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2444 template, template_len);
2446 else
2448 /* Build the private key template as described in section 4.3.3.6 of
2449 the OpenPGP card specs version 1.1:
2450 0xC0 <length> public exponent
2451 0xC1 <length> prime p
2452 0xC2 <length> prime q
2454 assert (rsa_e_len <= 4);
2455 template_len = (1 + 1 + 4
2456 + 1 + 1 + rsa_p_len
2457 + 1 + 1 + rsa_q_len);
2458 template = tp = xtrymalloc_secure (template_len);
2459 if (!template)
2461 err = gpg_error_from_syserror ();
2462 goto leave;
2464 *tp++ = 0xC0;
2465 *tp++ = 4;
2466 memcpy (tp, rsa_e, rsa_e_len);
2467 if (rsa_e_len < 4)
2469 /* Right justify E. */
2470 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2471 memset (tp, 0, 4-rsa_e_len);
2473 tp += 4;
2475 *tp++ = 0xC1;
2476 *tp++ = rsa_p_len;
2477 memcpy (tp, rsa_p, rsa_p_len);
2478 tp += rsa_p_len;
2480 *tp++ = 0xC2;
2481 *tp++ = rsa_q_len;
2482 memcpy (tp, rsa_q, rsa_q_len);
2483 tp += rsa_q_len;
2485 assert (tp - template == template_len);
2487 /* Prepare for storing the key. */
2488 err = verify_chv3 (app, pincb, pincb_arg);
2489 if (err)
2490 goto leave;
2492 /* Store the key. */
2493 err = iso7816_put_data (app->slot, 0,
2494 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2495 template, template_len);
2497 if (err)
2499 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2500 goto leave;
2503 err = store_fpr (app->slot, keyno, created_at,
2504 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2505 fprbuf, app->card_version);
2506 if (err)
2507 goto leave;
2510 leave:
2511 xfree (template);
2512 return err;
2516 /* Handle the GENKEY command. */
2517 static gpg_error_t
2518 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
2519 time_t createtime,
2520 gpg_error_t (*pincb)(void*, const char *, char **),
2521 void *pincb_arg)
2523 int rc;
2524 char numbuf[30];
2525 unsigned char fprbuf[20];
2526 const unsigned char *keydata, *m, *e;
2527 unsigned char *buffer = NULL;
2528 size_t buflen, keydatalen, mlen, elen;
2529 time_t created_at;
2530 int keyno = atoi (keynostr);
2531 int force = (flags & 1);
2532 time_t start_at;
2533 int exmode;
2534 int le_value;
2535 unsigned int keybits;
2537 if (keyno < 1 || keyno > 3)
2538 return gpg_error (GPG_ERR_INV_ID);
2539 keyno--;
2541 /* We flush the cache to increase the traffic before a key
2542 generation. This _might_ help a card to gather more entropy. */
2543 flush_cache (app);
2545 /* Obviously we need to remove the cached public key. */
2546 xfree (app->app_local->pk[keyno].key);
2547 app->app_local->pk[keyno].key = NULL;
2548 app->app_local->pk[keyno].keylen = 0;
2549 app->app_local->pk[keyno].read_done = 0;
2551 /* Check whether a key already exists. */
2552 rc = does_key_exist (app, keyno, force);
2553 if (rc)
2554 return rc;
2556 /* Because we send the key parameter back via status lines we need
2557 to put a limit on the max. allowed keysize. 2048 bit will
2558 already lead to a 527 byte long status line and thus a 4096 bit
2559 key would exceed the Assuan line length limit. */
2560 keybits = app->app_local->keyattr[keyno].n_bits;
2561 if (keybits > 3072)
2562 return gpg_error (GPG_ERR_TOO_LARGE);
2564 /* Prepare for key generation by verifying the Admin PIN. */
2565 rc = verify_chv3 (app, pincb, pincb_arg);
2566 if (rc)
2567 goto leave;
2569 /* Test whether we will need extended length mode. (1900 is an
2570 arbitrary length which for sure fits into a short apdu.) */
2571 if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
2573 exmode = 1; /* Use extended length w/o a limit. */
2574 le_value = app->app_local->extcap.max_rsp_data;
2575 /* No need to check le_value because it comes from a 16 bit
2576 value and thus can't create an overflow on a 32 bit
2577 system. */
2579 else
2581 exmode = 0;
2582 le_value = 256; /* Use legacy value. */
2585 log_info (_("please wait while key is being generated ...\n"));
2586 start_at = time (NULL);
2587 rc = iso7816_generate_keypair
2588 /* # warning key generation temporary replaced by reading an existing key. */
2589 /* rc = iso7816_read_public_key */
2590 (app->slot, exmode,
2591 (const unsigned char*)(keyno == 0? "\xB6" :
2592 keyno == 1? "\xB8" : "\xA4"), 2,
2593 le_value,
2594 &buffer, &buflen);
2595 if (rc)
2597 rc = gpg_error (GPG_ERR_CARD);
2598 log_error (_("generating key failed\n"));
2599 goto leave;
2601 log_info (_("key generation completed (%d seconds)\n"),
2602 (int)(time (NULL) - start_at));
2604 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2605 if (!keydata)
2607 rc = gpg_error (GPG_ERR_CARD);
2608 log_error (_("response does not contain the public key data\n"));
2609 goto leave;
2612 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2613 if (!m)
2615 rc = gpg_error (GPG_ERR_CARD);
2616 log_error (_("response does not contain the RSA modulus\n"));
2617 goto leave;
2619 /* log_printhex ("RSA n:", m, mlen); */
2620 send_key_data (ctrl, "n", m, mlen);
2622 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2623 if (!e)
2625 rc = gpg_error (GPG_ERR_CARD);
2626 log_error (_("response does not contain the RSA public exponent\n"));
2627 goto leave;
2629 /* log_printhex ("RSA e:", e, elen); */
2630 send_key_data (ctrl, "e", e, elen);
2632 created_at = createtime? createtime : gnupg_get_time ();
2633 sprintf (numbuf, "%lu", (unsigned long)created_at);
2634 send_status_info (ctrl, "KEY-CREATED-AT",
2635 numbuf, (size_t)strlen(numbuf), NULL, 0);
2637 rc = store_fpr (app->slot, keyno, (u32)created_at,
2638 m, mlen, e, elen, fprbuf, app->card_version);
2639 if (rc)
2640 goto leave;
2641 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2644 leave:
2645 xfree (buffer);
2646 return rc;
2650 static unsigned long
2651 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2653 unsigned long ul;
2655 if (valuelen == 3 )
2656 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2657 else
2659 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2660 ul = 0;
2662 return ul;
2665 static unsigned long
2666 get_sig_counter (app_t app)
2668 void *relptr;
2669 unsigned char *value;
2670 size_t valuelen;
2671 unsigned long ul;
2673 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2674 if (!relptr)
2675 return 0;
2676 ul = convert_sig_counter_value (value, valuelen);
2677 xfree (relptr);
2678 return ul;
2681 static gpg_error_t
2682 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2684 const unsigned char *fpr;
2685 unsigned char *buffer;
2686 size_t buflen, n;
2687 int rc, i;
2689 assert (keyno >= 1 && keyno <= 3);
2691 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
2692 if (rc)
2694 log_error (_("error reading application data\n"));
2695 return gpg_error (GPG_ERR_GENERAL);
2697 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2698 if (!fpr || n != 60)
2700 xfree (buffer);
2701 log_error (_("error reading fingerprint DO\n"));
2702 return gpg_error (GPG_ERR_GENERAL);
2704 fpr += (keyno-1)*20;
2705 for (i=0; i < 20; i++)
2706 if (sha1fpr[i] != fpr[i])
2708 xfree (buffer);
2709 log_info (_("fingerprint on card does not match requested one\n"));
2710 return gpg_error (GPG_ERR_WRONG_SECKEY);
2712 xfree (buffer);
2713 return 0;
2717 /* If a fingerprint has been specified check it against the one on
2718 the card. This is allows for a meaningful error message in case
2719 the key on the card has been replaced but the shadow information
2720 known to gpg was not updated. If there is no fingerprint we
2721 assume that this is okay. */
2722 static gpg_error_t
2723 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2725 unsigned char tmp[20];
2726 const char *s;
2727 int n;
2729 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2731 if (n != 40)
2732 return gpg_error (GPG_ERR_INV_ID);
2733 else if (!*s)
2734 ; /* okay */
2735 else
2736 return gpg_error (GPG_ERR_INV_ID);
2738 for (s=fpr, n=0; n < 20; s += 2, n++)
2739 tmp[n] = xtoi_2 (s);
2740 return compare_fingerprint (app, keyno, tmp);
2745 /* Compute a digital signature on INDATA which is expected to be the
2746 raw message digest. For this application the KEYIDSTR consists of
2747 the serialnumber and the fingerprint delimited by a slash.
2749 Note that this function may return the error code
2750 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2751 not match the one required for the requested action (e.g. the
2752 serial number does not match).
2754 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2755 operation to the auth command.
2757 static gpg_error_t
2758 do_sign (app_t app, const char *keyidstr, int hashalgo,
2759 gpg_error_t (*pincb)(void*, const char *, char **),
2760 void *pincb_arg,
2761 const void *indata, size_t indatalen,
2762 unsigned char **outdata, size_t *outdatalen )
2764 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2765 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2766 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2767 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
2768 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2769 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2770 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
2771 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2772 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2773 0x1C };
2774 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
2775 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2776 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2777 0x00, 0x04, 0x20 };
2778 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
2779 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2780 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
2781 0x00, 0x04, 0x30 };
2782 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
2783 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2784 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
2785 0x00, 0x04, 0x40 };
2786 int rc;
2787 unsigned char data[19+64];
2788 size_t datalen;
2789 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
2790 const char *s;
2791 int n;
2792 const char *fpr = NULL;
2793 unsigned long sigcount;
2794 int use_auth = 0;
2796 if (!keyidstr || !*keyidstr)
2797 return gpg_error (GPG_ERR_INV_VALUE);
2799 /* Strip off known prefixes. */
2800 #define X(a,b,c,d) \
2801 if (hashalgo == GCRY_MD_ ## a \
2802 && (d) \
2803 && indatalen == sizeof b ## _prefix + (c) \
2804 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
2806 indata = (const char*)indata + sizeof b ## _prefix; \
2807 indatalen -= sizeof b ## _prefix; \
2810 if (indatalen == 20)
2811 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
2812 else X(SHA1, sha1, 20, 1)
2813 else X(RMD160, rmd160, 20, 1)
2814 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
2815 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
2816 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
2817 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
2818 else if ((indatalen == 28 || indatalen == 32
2819 || indatalen == 48 || indatalen ==64)
2820 && app->app_local->extcap.is_v2)
2821 ; /* Assume a plain SHA-3 digest has been given. */
2822 else
2824 log_error (_("card does not support digest algorithm %s\n"),
2825 gcry_md_algo_name (hashalgo));
2826 /* Or the supplied digest length does not match an algorithm. */
2827 return gpg_error (GPG_ERR_INV_VALUE);
2829 #undef X
2831 /* Check whether an OpenPGP card of any version has been requested. */
2832 if (!strcmp (keyidstr, "OPENPGP.1"))
2834 else if (!strcmp (keyidstr, "OPENPGP.3"))
2835 use_auth = 1;
2836 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2837 return gpg_error (GPG_ERR_INV_ID);
2838 else
2840 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2842 if (n != 32)
2843 return gpg_error (GPG_ERR_INV_ID);
2844 else if (!*s)
2845 ; /* no fingerprint given: we allow this for now. */
2846 else if (*s == '/')
2847 fpr = s + 1;
2848 else
2849 return gpg_error (GPG_ERR_INV_ID);
2851 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2852 tmp_sn[n] = xtoi_2 (s);
2854 if (app->serialnolen != 16)
2855 return gpg_error (GPG_ERR_INV_CARD);
2856 if (memcmp (app->serialno, tmp_sn, 16))
2857 return gpg_error (GPG_ERR_WRONG_CARD);
2860 /* If a fingerprint has been specified check it against the one on
2861 the card. This is allows for a meaningful error message in case
2862 the key on the card has been replaced but the shadow information
2863 known to gpg was not updated. If there is no fingerprint, gpg
2864 will detect a bogus signature anyway due to the
2865 verify-after-signing feature. */
2866 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2867 if (rc)
2868 return rc;
2870 /* Concatenate prefix and digest. */
2871 #define X(a,b,d) \
2872 if (hashalgo == GCRY_MD_ ## a && (d) ) \
2874 datalen = sizeof b ## _prefix + indatalen; \
2875 assert (datalen <= sizeof data); \
2876 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
2877 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
2880 X(SHA1, sha1, 1)
2881 else X(RMD160, rmd160, 1)
2882 else X(SHA224, sha224, app->app_local->extcap.is_v2)
2883 else X(SHA256, sha256, app->app_local->extcap.is_v2)
2884 else X(SHA384, sha384, app->app_local->extcap.is_v2)
2885 else X(SHA512, sha512, app->app_local->extcap.is_v2)
2886 else
2887 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2888 #undef X
2890 /* Redirect to the AUTH command if asked to. */
2891 if (use_auth)
2893 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
2894 data, datalen,
2895 outdata, outdatalen);
2898 /* Show the number of signature done using this key. */
2899 sigcount = get_sig_counter (app);
2900 log_info (_("signatures created so far: %lu\n"), sigcount);
2902 /* Check CHV if needed. */
2903 if (!app->did_chv1 || app->force_chv1 )
2905 char *pinvalue;
2907 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
2908 if (rc)
2909 return rc;
2911 app->did_chv1 = 1;
2913 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
2914 sync, thus we verify CHV2 here using the given PIN. Cards
2915 with version2 to not have the need for a separate CHV2 and
2916 internally use just one. Obviously we can't do that if the
2917 keypad has been used. */
2918 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
2920 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2921 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2922 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2923 if (rc)
2925 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2926 xfree (pinvalue);
2927 flush_cache_after_error (app);
2928 return rc;
2930 app->did_chv2 = 1;
2932 xfree (pinvalue);
2935 rc = iso7816_compute_ds (app->slot, data, datalen, outdata, outdatalen);
2936 return rc;
2939 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2940 on INDATA which is expected to be the raw message digest. For this
2941 application the KEYIDSTR consists of the serialnumber and the
2942 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2943 be given.
2945 Note that this function may return the error code
2946 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2947 not match the one required for the requested action (e.g. the
2948 serial number does not match). */
2949 static gpg_error_t
2950 do_auth (app_t app, const char *keyidstr,
2951 gpg_error_t (*pincb)(void*, const char *, char **),
2952 void *pincb_arg,
2953 const void *indata, size_t indatalen,
2954 unsigned char **outdata, size_t *outdatalen )
2956 int rc;
2957 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
2958 const char *s;
2959 int n;
2960 const char *fpr = NULL;
2962 if (!keyidstr || !*keyidstr)
2963 return gpg_error (GPG_ERR_INV_VALUE);
2964 if (indatalen > 101) /* For a 2048 bit key. */
2965 return gpg_error (GPG_ERR_INV_VALUE);
2967 /* Check whether an OpenPGP card of any version has been requested. */
2968 if (!strcmp (keyidstr, "OPENPGP.3"))
2970 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2971 return gpg_error (GPG_ERR_INV_ID);
2972 else
2974 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2976 if (n != 32)
2977 return gpg_error (GPG_ERR_INV_ID);
2978 else if (!*s)
2979 ; /* no fingerprint given: we allow this for now. */
2980 else if (*s == '/')
2981 fpr = s + 1;
2982 else
2983 return gpg_error (GPG_ERR_INV_ID);
2985 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2986 tmp_sn[n] = xtoi_2 (s);
2988 if (app->serialnolen != 16)
2989 return gpg_error (GPG_ERR_INV_CARD);
2990 if (memcmp (app->serialno, tmp_sn, 16))
2991 return gpg_error (GPG_ERR_WRONG_CARD);
2994 /* If a fingerprint has been specified check it against the one on
2995 the card. This is allows for a meaningful error message in case
2996 the key on the card has been replaced but the shadow information
2997 known to gpg was not updated. If there is no fingerprint, gpg
2998 will detect a bogus signature anyway due to the
2999 verify-after-signing feature. */
3000 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3001 if (rc)
3002 return rc;
3004 rc = verify_chv2 (app, pincb, pincb_arg);
3005 if (!rc)
3006 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
3007 outdata, outdatalen);
3008 return rc;
3012 static gpg_error_t
3013 do_decipher (app_t app, const char *keyidstr,
3014 gpg_error_t (*pincb)(void*, const char *, char **),
3015 void *pincb_arg,
3016 const void *indata, size_t indatalen,
3017 unsigned char **outdata, size_t *outdatalen )
3019 int rc;
3020 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3021 const char *s;
3022 int n;
3023 const char *fpr = NULL;
3024 int exmode;
3026 if (!keyidstr || !*keyidstr || !indatalen)
3027 return gpg_error (GPG_ERR_INV_VALUE);
3029 /* Check whether an OpenPGP card of any version has been requested. */
3030 if (!strcmp (keyidstr, "OPENPGP.2"))
3032 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3033 return gpg_error (GPG_ERR_INV_ID);
3034 else
3036 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3038 if (n != 32)
3039 return gpg_error (GPG_ERR_INV_ID);
3040 else if (!*s)
3041 ; /* no fingerprint given: we allow this for now. */
3042 else if (*s == '/')
3043 fpr = s + 1;
3044 else
3045 return gpg_error (GPG_ERR_INV_ID);
3047 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3048 tmp_sn[n] = xtoi_2 (s);
3050 if (app->serialnolen != 16)
3051 return gpg_error (GPG_ERR_INV_CARD);
3052 if (memcmp (app->serialno, tmp_sn, 16))
3053 return gpg_error (GPG_ERR_WRONG_CARD);
3056 /* If a fingerprint has been specified check it against the one on
3057 the card. This is allows for a meaningful error message in case
3058 the key on the card has been replaced but the shadow information
3059 known to gpg was not updated. If there is no fingerprint, the
3060 decryption won't produce the right plaintext anyway. */
3061 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3062 if (rc)
3063 return rc;
3065 rc = verify_chv2 (app, pincb, pincb_arg);
3066 if (!rc)
3068 size_t fixuplen;
3069 unsigned char *fixbuf = NULL;
3070 int padind = 0;
3072 /* We might encounter a couple of leading zeroes in the
3073 cryptogram. Due to internal use of MPIs thease leading
3074 zeroes are stripped. However the OpenPGP card expects
3075 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3076 need to fix it up. We do this for up to 16 leading zero
3077 bytes; a cryptogram with more than this is with a very high
3078 probability anyway broken. */
3079 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
3080 fixuplen = 128 - indatalen;
3081 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
3082 fixuplen = 192 - indatalen;
3083 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
3084 fixuplen = 256 - indatalen;
3085 else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
3086 fixuplen = 384 - indatalen;
3087 else
3088 fixuplen = 0;
3090 if (fixuplen)
3092 /* While we have to prepend stuff anyway, we can also
3093 include the padding byte here so that iso1816_decipher
3094 does not need to do another data mangling. */
3095 fixuplen++;
3097 fixbuf = xtrymalloc (fixuplen + indatalen);
3098 if (!fixbuf)
3099 return gpg_error_from_syserror ();
3101 memset (fixbuf, 0, fixuplen);
3102 memcpy (fixbuf+fixuplen, indata, indatalen);
3103 indata = fixbuf;
3104 indatalen = fixuplen + indatalen;
3105 padind = -1; /* Already padded. */
3108 if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
3109 exmode = 1; /* Extended length w/o a limit. */
3110 else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
3111 exmode = -254; /* Command chaining with max. 254 bytes. */
3112 else
3113 exmode = 0;
3115 rc = iso7816_decipher (app->slot, exmode,
3116 indata, indatalen, padind,
3117 outdata, outdatalen);
3118 xfree (fixbuf);
3121 return rc;
3125 /* Perform a simple verify operation for CHV1 and CHV2, so that
3126 further operations won't ask for CHV2 and it is possible to do a
3127 cheap check on the PIN: If there is something wrong with the PIN
3128 entry system, only the regular CHV will get blocked and not the
3129 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3130 optional fingerprint part will be ignored.
3132 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3133 the "[CHV3]" being a literal string: The Admin Pin is checked if
3134 and only if the retry counter is still at 3. */
3135 static gpg_error_t
3136 do_check_pin (app_t app, const char *keyidstr,
3137 gpg_error_t (*pincb)(void*, const char *, char **),
3138 void *pincb_arg)
3140 unsigned char tmp_sn[20];
3141 const char *s;
3142 int n;
3143 int admin_pin = 0;
3145 if (!keyidstr || !*keyidstr)
3146 return gpg_error (GPG_ERR_INV_VALUE);
3148 /* Check whether an OpenPGP card of any version has been requested. */
3149 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3150 return gpg_error (GPG_ERR_INV_ID);
3152 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3154 if (n != 32)
3155 return gpg_error (GPG_ERR_INV_ID);
3156 else if (!*s)
3157 ; /* No fingerprint given: we allow this for now. */
3158 else if (*s == '/')
3159 ; /* We ignore a fingerprint. */
3160 else if (!strcmp (s, "[CHV3]") )
3161 admin_pin = 1;
3162 else
3163 return gpg_error (GPG_ERR_INV_ID);
3165 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3166 tmp_sn[n] = xtoi_2 (s);
3168 if (app->serialnolen != 16)
3169 return gpg_error (GPG_ERR_INV_CARD);
3170 if (memcmp (app->serialno, tmp_sn, 16))
3171 return gpg_error (GPG_ERR_WRONG_CARD);
3173 /* Yes, there is a race conditions: The user might pull the card
3174 right here and we won't notice that. However this is not a
3175 problem and the check above is merely for a graceful failure
3176 between operations. */
3178 if (admin_pin)
3180 void *relptr;
3181 unsigned char *value;
3182 size_t valuelen;
3183 int count;
3185 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3186 if (!relptr || valuelen < 7)
3188 log_error (_("error retrieving CHV status from card\n"));
3189 xfree (relptr);
3190 return gpg_error (GPG_ERR_CARD);
3192 count = value[6];
3193 xfree (relptr);
3195 if (!count)
3197 log_info (_("card is permanently locked!\n"));
3198 return gpg_error (GPG_ERR_BAD_PIN);
3200 else if (value[6] < 3)
3202 log_info (_("verification of Admin PIN is currently prohibited "
3203 "through this command\n"));
3204 return gpg_error (GPG_ERR_GENERAL);
3207 app->did_chv3 = 0; /* Force verification. */
3208 return verify_chv3 (app, pincb, pincb_arg);
3210 else
3211 return verify_chv2 (app, pincb, pincb_arg);
3215 /* Show information about card capabilities. */
3216 static void
3217 show_caps (struct app_local_s *s)
3219 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3220 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3221 if (s->extcap.get_challenge)
3222 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3223 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3224 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3225 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3226 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3227 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3228 if (s->extcap.sm_supported)
3229 log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3230 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3231 log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3232 log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3233 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3234 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3235 log_info ("Status Indicator: %02X\n", s->status_indicator);
3237 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
3238 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
3242 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3243 APPLOC. */
3244 static void
3245 parse_historical (struct app_local_s *apploc,
3246 const unsigned char * buffer, size_t buflen)
3248 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3249 if (buflen < 4)
3251 log_error ("warning: historical bytes are too short\n");
3252 return; /* Too short. */
3254 if (*buffer)
3256 log_error ("warning: bad category indicator in historical bytes\n");
3257 return;
3260 /* Skip category indicator. */
3261 buffer++;
3262 buflen--;
3264 /* Get the status indicator. */
3265 apploc->status_indicator = buffer[buflen-3];
3266 buflen -= 3;
3268 /* Parse the compact TLV. */
3269 while (buflen)
3271 unsigned int tag = (*buffer & 0xf0) >> 4;
3272 unsigned int len = (*buffer & 0x0f);
3273 if (len+1 > buflen)
3275 log_error ("warning: bad Compact-TLV in historical bytes\n");
3276 return; /* Error. */
3278 buffer++;
3279 buflen--;
3280 if (tag == 7 && len == 3)
3282 /* Card capabilities. */
3283 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3284 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
3286 buffer += len;
3287 buflen -= len;
3292 /* Parse and optionally show the algorithm attributes for KEYNO.
3293 KEYNO must be in the range 0..2. */
3294 static void
3295 parse_algorithm_attribute (app_t app, int keyno)
3297 unsigned char *buffer;
3298 size_t buflen;
3299 void *relptr;
3300 const char const desc[3][5] = {"sign", "encr", "auth"};
3302 assert (keyno >=0 && keyno <= 2);
3304 app->app_local->keyattr[keyno].n_bits = 0;
3306 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3307 if (!relptr)
3309 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3310 return;
3312 if (buflen < 1)
3314 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3315 xfree (relptr);
3316 return;
3319 if (opt.verbose)
3320 log_info ("Key-Attr-%s ..: ", desc[keyno]);
3321 if (*buffer == 1 && (buflen == 5 || buflen == 6))
3323 app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3324 app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3325 app->app_local->keyattr[keyno].format = 0;
3326 if (buflen < 6)
3327 app->app_local->keyattr[keyno].format = RSA_STD;
3328 else
3329 app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD :
3330 buffer[5] == 1? RSA_STD_N :
3331 buffer[5] == 2? RSA_CRT :
3332 buffer[5] == 3? RSA_CRT_N :
3333 RSA_UNKNOWN_FMT);
3335 if (opt.verbose)
3336 log_printf
3337 ("RSA, n=%u, e=%u, fmt=%s\n",
3338 app->app_local->keyattr[keyno].n_bits,
3339 app->app_local->keyattr[keyno].e_bits,
3340 app->app_local->keyattr[keyno].format == RSA_STD? "std" :
3341 app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3342 app->app_local->keyattr[keyno].format == RSA_CRT? "crt" :
3343 app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3345 else if (opt.verbose)
3346 log_printhex ("", buffer, buflen);
3348 xfree (relptr);
3351 /* Select the OpenPGP application on the card in SLOT. This function
3352 must be used before any other OpenPGP application functions. */
3353 gpg_error_t
3354 app_select_openpgp (app_t app)
3356 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3357 int slot = app->slot;
3358 int rc;
3359 unsigned char *buffer;
3360 size_t buflen;
3361 void *relptr;
3363 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3364 special flag value. */
3365 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3366 if (!rc)
3368 unsigned int manufacturer;
3370 app->apptype = "OPENPGP";
3372 app->did_chv1 = 0;
3373 app->did_chv2 = 0;
3374 app->did_chv3 = 0;
3375 app->app_local = NULL;
3377 /* The OpenPGP card returns the serial number as part of the
3378 AID; because we prefer to use OpenPGP serial numbers, we
3379 replace a possibly already set one from a EF.GDO with this
3380 one. Note, that for current OpenPGP cards, no EF.GDO exists
3381 and thus it won't matter at all. */
3382 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
3383 if (rc)
3384 goto leave;
3385 if (opt.verbose)
3387 log_info ("AID: ");
3388 log_printhex ("", buffer, buflen);
3391 app->card_version = buffer[6] << 8;
3392 app->card_version |= buffer[7];
3393 manufacturer = (buffer[8]<<8 | buffer[9]);
3395 xfree (app->serialno);
3396 app->serialno = buffer;
3397 app->serialnolen = buflen;
3398 buffer = NULL;
3399 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3400 if (!app->app_local)
3402 rc = gpg_error (gpg_err_code_from_errno (errno));
3403 goto leave;
3406 if (app->card_version >= 0x0200)
3407 app->app_local->extcap.is_v2 = 1;
3410 /* Read the historical bytes. */
3411 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3412 if (relptr)
3414 if (opt.verbose)
3416 log_info ("Historical Bytes: ");
3417 log_printhex ("", buffer, buflen);
3419 parse_historical (app->app_local, buffer, buflen);
3420 xfree (relptr);
3423 /* Read the force-chv1 flag. */
3424 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3425 if (!relptr)
3427 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3428 "CHV Status Bytes");
3429 goto leave;
3431 app->force_chv1 = (buflen && *buffer == 0);
3432 xfree (relptr);
3434 /* Read the extended capabilities. */
3435 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3436 if (!relptr)
3438 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3439 "Extended Capability Flags" );
3440 goto leave;
3442 if (buflen)
3444 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
3445 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
3446 app->app_local->extcap.key_import = !!(*buffer & 0x20);
3447 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3448 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
3449 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3451 if (buflen >= 10)
3453 /* Available with v2 cards. */
3454 app->app_local->extcap.sm_aes128 = (buffer[1] == 1);
3455 app->app_local->extcap.max_get_challenge
3456 = (buffer[2] << 8 | buffer[3]);
3457 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3458 app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
3459 app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
3461 xfree (relptr);
3463 /* Some of the first cards accidently don't set the
3464 CHANGE_FORCE_CHV bit but allow it anyway. */
3465 if (app->card_version <= 0x0100 && manufacturer == 1)
3466 app->app_local->extcap.change_force_chv = 1;
3468 parse_login_data (app);
3470 if (opt.verbose)
3471 show_caps (app->app_local);
3473 parse_algorithm_attribute (app, 0);
3474 parse_algorithm_attribute (app, 1);
3475 parse_algorithm_attribute (app, 2);
3477 if (opt.verbose > 1)
3478 dump_all_do (slot);
3480 app->fnc.deinit = do_deinit;
3481 app->fnc.learn_status = do_learn_status;
3482 app->fnc.readcert = do_readcert;
3483 app->fnc.readkey = do_readkey;
3484 app->fnc.getattr = do_getattr;
3485 app->fnc.setattr = do_setattr;
3486 app->fnc.writecert = do_writecert;
3487 app->fnc.writekey = do_writekey;
3488 app->fnc.genkey = do_genkey;
3489 app->fnc.sign = do_sign;
3490 app->fnc.auth = do_auth;
3491 app->fnc.decipher = do_decipher;
3492 app->fnc.change_pin = do_change_pin;
3493 app->fnc.check_pin = do_check_pin;
3496 leave:
3497 if (rc)
3498 do_deinit (app);
3499 return rc;