2006-12-18 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / app-openpgp.c
blob6c2eb82fb88f3c1071cad6c9a9e30bcb2fe1d81b
1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
21 * $Id$
24 #include <config.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <time.h>
32 #if GNUPG_MAJOR_VERSION == 1
33 /* This is used with GnuPG version < 1.9. The code has been source
34 copied from the current GnuPG >= 1.9 and is maintained over
35 there. */
36 #include "options.h"
37 #include "errors.h"
38 #include "memory.h"
39 #include "util.h"
40 #include "cardglue.h"
41 #else /* GNUPG_MAJOR_VERSION != 1 */
42 #include "scdaemon.h"
43 #endif /* GNUPG_MAJOR_VERSION != 1 */
45 #include "i18n.h"
46 #include "iso7816.h"
47 #include "app-common.h"
48 #include "tlv.h"
51 static struct {
52 int tag;
53 int constructed;
54 int get_from; /* Constructed DO with this DO or 0 for direct access. */
55 int binary;
56 int dont_cache;
57 int flush_on_error;
58 int get_immediate_in_v11; /* Enable a hack to bypass the cache of
59 this data object if it is used in 1.1
60 and later versions of the card. This
61 does not work with composite DO and is
62 currently only useful for the CHV
63 status bytes. */
64 char *desc;
65 } data_objects[] = {
66 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
67 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
68 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
69 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
70 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
71 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
72 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
73 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
74 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
75 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
76 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
77 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
78 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
79 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
80 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
81 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
82 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
83 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
84 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
85 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
86 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
87 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
88 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
89 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
90 { 0 }
94 /* One cache item for DOs. */
95 struct cache_s {
96 struct cache_s *next;
97 int tag;
98 size_t length;
99 unsigned char data[1];
103 /* Object with application (i.e. OpenPGP card) specific data. */
104 struct app_local_s {
105 /* A linked list with cached DOs. */
106 struct cache_s *cache;
108 /* Keep track of the public keys. */
109 struct
111 int read_done; /* True if we have at least tried to read them. */
112 unsigned char *key; /* This is a malloced buffer with a canonical
113 encoded S-expression encoding a public
114 key. Might be NULL if key is not
115 available. */
116 size_t keylen; /* The length of the above S-expression. This
117 is usullay only required for cross checks
118 because the length of an S-expression is
119 implicitly available. */
120 } pk[3];
122 /* Keep track of card capabilities. */
123 struct
125 unsigned int get_challenge:1;
126 unsigned int key_import:1;
127 unsigned int change_force_chv:1;
128 unsigned int private_dos:1;
129 } extcap;
131 /* Flags used to control the application. */
132 struct
134 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
135 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
136 } flags;
141 /***** Local prototypes *****/
142 static unsigned long convert_sig_counter_value (const unsigned char *value,
143 size_t valuelen);
144 static unsigned long get_sig_counter (app_t app);
145 static gpg_error_t do_auth (app_t app, const char *keyidstr,
146 gpg_error_t (*pincb)(void*, const char *, char **),
147 void *pincb_arg,
148 const void *indata, size_t indatalen,
149 unsigned char **outdata, size_t *outdatalen);
155 /* Deconstructor. */
156 static void
157 do_deinit (app_t app)
159 if (app && app->app_local)
161 struct cache_s *c, *c2;
162 int i;
164 for (c = app->app_local->cache; c; c = c2)
166 c2 = c->next;
167 xfree (c);
170 for (i=0; i < DIM (app->app_local->pk); i++)
172 xfree (app->app_local->pk[i].key);
173 app->app_local->pk[i].read_done = 0;
175 xfree (app->app_local);
176 app->app_local = NULL;
181 /* Wrapper around iso7816_get_data which first tries to get the data
182 from the cache. With GET_IMMEDIATE passed as true, the cache is
183 bypassed. */
184 static gpg_error_t
185 get_cached_data (app_t app, int tag,
186 unsigned char **result, size_t *resultlen,
187 int get_immediate)
189 gpg_error_t err;
190 int i;
191 unsigned char *p;
192 size_t len;
193 struct cache_s *c;
195 *result = NULL;
196 *resultlen = 0;
198 if (!get_immediate)
200 for (c=app->app_local->cache; c; c = c->next)
201 if (c->tag == tag)
203 if(c->length)
205 p = xtrymalloc (c->length);
206 if (!p)
207 return gpg_error (gpg_err_code_from_errno (errno));
208 memcpy (p, c->data, c->length);
209 *result = p;
212 *resultlen = c->length;
214 return 0;
218 err = iso7816_get_data (app->slot, tag, &p, &len);
219 if (err)
220 return err;
221 *result = p;
222 *resultlen = len;
224 /* Check whether we should cache this object. */
225 if (get_immediate)
226 return 0;
228 for (i=0; data_objects[i].tag; i++)
229 if (data_objects[i].tag == tag)
231 if (data_objects[i].dont_cache)
232 return 0;
233 break;
236 /* Okay, cache it. */
237 for (c=app->app_local->cache; c; c = c->next)
238 assert (c->tag != tag);
240 c = xtrymalloc (sizeof *c + len);
241 if (c)
243 memcpy (c->data, p, len);
244 c->length = len;
245 c->tag = tag;
246 c->next = app->app_local->cache;
247 app->app_local->cache = c;
250 return 0;
253 /* Remove DO at TAG from the cache. */
254 static void
255 flush_cache_item (app_t app, int tag)
257 struct cache_s *c, *cprev;
258 int i;
260 if (!app->app_local)
261 return;
263 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
264 if (c->tag == tag)
266 if (cprev)
267 cprev->next = c->next;
268 else
269 app->app_local->cache = c->next;
270 xfree (c);
272 for (c=app->app_local->cache; c ; c = c->next)
274 assert (c->tag != tag); /* Oops: duplicated entry. */
276 return;
279 /* Try again if we have an outer tag. */
280 for (i=0; data_objects[i].tag; i++)
281 if (data_objects[i].tag == tag && data_objects[i].get_from
282 && data_objects[i].get_from != tag)
283 flush_cache_item (app, data_objects[i].get_from);
286 /* Flush all entries from the cache which might be out of sync after
287 an error. */
288 static void
289 flush_cache_after_error (app_t app)
291 int i;
293 for (i=0; data_objects[i].tag; i++)
294 if (data_objects[i].flush_on_error)
295 flush_cache_item (app, data_objects[i].tag);
299 /* Flush the entire cache. */
300 static void
301 flush_cache (app_t app)
303 if (app && app->app_local)
305 struct cache_s *c, *c2;
307 for (c = app->app_local->cache; c; c = c2)
309 c2 = c->next;
310 xfree (c);
312 app->app_local->cache = NULL;
317 /* Get the DO identified by TAG from the card in SLOT and return a
318 buffer with its content in RESULT and NBYTES. The return value is
319 NULL if not found or a pointer which must be used to release the
320 buffer holding value. */
321 static void *
322 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
323 int *r_rc)
325 int rc, i;
326 unsigned char *buffer;
327 size_t buflen;
328 unsigned char *value;
329 size_t valuelen;
330 int dummyrc;
332 if (!r_rc)
333 r_rc = &dummyrc;
335 *result = NULL;
336 *nbytes = 0;
337 *r_rc = 0;
338 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
341 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
343 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
344 if (rc)
346 *r_rc = rc;
347 return NULL;
349 *result = buffer;
350 *nbytes = buflen;
351 return buffer;
354 value = NULL;
355 rc = -1;
356 if (data_objects[i].tag && data_objects[i].get_from)
358 rc = get_cached_data (app, data_objects[i].get_from,
359 &buffer, &buflen,
360 (data_objects[i].dont_cache
361 || data_objects[i].get_immediate_in_v11));
362 if (!rc)
364 const unsigned char *s;
366 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
367 if (!s)
368 value = NULL; /* not found */
369 else if (valuelen > buflen - (s - buffer))
371 log_error ("warning: constructed DO too short\n");
372 value = NULL;
373 xfree (buffer); buffer = NULL;
375 else
376 value = buffer + (s - buffer);
380 if (!value) /* Not in a constructed DO, try simple. */
382 rc = get_cached_data (app, tag, &buffer, &buflen,
383 (data_objects[i].dont_cache
384 || data_objects[i].get_immediate_in_v11));
385 if (!rc)
387 value = buffer;
388 valuelen = buflen;
392 if (!rc)
394 *nbytes = valuelen;
395 *result = value;
396 return buffer;
398 *r_rc = rc;
399 return NULL;
403 static void
404 dump_all_do (int slot)
406 int rc, i, j;
407 unsigned char *buffer;
408 size_t buflen;
410 for (i=0; data_objects[i].tag; i++)
412 if (data_objects[i].get_from)
413 continue;
415 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
416 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
418 else if (rc)
419 log_info ("DO `%s' not available: %s\n",
420 data_objects[i].desc, gpg_strerror (rc));
421 else
423 if (data_objects[i].binary)
425 log_info ("DO `%s': ", data_objects[i].desc);
426 log_printhex ("", buffer, buflen);
428 else
429 log_info ("DO `%s': `%.*s'\n",
430 data_objects[i].desc,
431 (int)buflen, buffer); /* FIXME: sanitize */
433 if (data_objects[i].constructed)
435 for (j=0; data_objects[j].tag; j++)
437 const unsigned char *value;
438 size_t valuelen;
440 if (j==i || data_objects[i].tag != data_objects[j].get_from)
441 continue;
442 value = find_tlv_unchecked (buffer, buflen,
443 data_objects[j].tag, &valuelen);
444 if (!value)
445 ; /* not found */
446 else if (valuelen > buflen - (value - buffer))
447 log_error ("warning: constructed DO too short\n");
448 else
450 if (data_objects[j].binary)
452 log_info ("DO `%s': ", data_objects[j].desc);
453 log_printhex ("", value, valuelen);
455 else
456 log_info ("DO `%s': `%.*s'\n",
457 data_objects[j].desc,
458 (int)valuelen, value); /* FIXME: sanitize */
463 xfree (buffer); buffer = NULL;
468 /* Count the number of bits, assuming the A represents an unsigned big
469 integer of length LEN bytes. */
470 static unsigned int
471 count_bits (const unsigned char *a, size_t len)
473 unsigned int n = len * 8;
474 int i;
476 for (; len && !*a; len--, a++, n -=8)
478 if (len)
480 for (i=7; i && !(*a & (1<<i)); i--)
481 n--;
483 return n;
486 /* GnuPG makes special use of the login-data DO, this fucntion parses
487 the login data to store the flags for later use. It may be called
488 at any time and should be called after changing the login-data DO.
490 Everything up to a LF is considered a mailbox or account name. If
491 the first LF is followed by DC4 (0x14) control sequence are
492 expected up to the next LF. Control sequences are separated by FS
493 (0x18) and consist of key=value pairs. There is one key defined:
495 F=<flags>
497 Were FLAGS is a plain hexadecimal number representing flag values.
498 The lsb is here the rightmost bit. Defined flags bits are:
500 Bit 0 = CHV1 and CHV2 are not syncronized
501 Bit 1 = CHV2 has been been set to the default PIN of "123456"
502 (this implies that bit 0 is also set).
505 static void
506 parse_login_data (app_t app)
508 unsigned char *buffer, *p;
509 size_t buflen, len;
510 void *relptr;
512 /* Set defaults. */
513 app->app_local->flags.no_sync = 0;
514 app->app_local->flags.def_chv2 = 0;
516 /* Read the DO. */
517 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
518 if (!relptr)
519 return; /* Ooops. */
520 for (; buflen; buflen--, buffer++)
521 if (*buffer == '\n')
522 break;
523 if (buflen < 2 || buffer[1] != '\x14')
524 return; /* No control sequences. */
525 buflen--;
526 buffer++;
529 buflen--;
530 buffer++;
531 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
533 /* Flags control sequence found. */
534 int lastdig = 0;
536 /* For now we are only interested in the last digit, so skip
537 any leading digits but bail out on invalid characters. */
538 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
539 lastdig = xtoi_1 (p);
540 if (len && !(*p == '\n' || *p == '\x18'))
541 goto next; /* Invalid characters in field. */
542 app->app_local->flags.no_sync = !!(lastdig & 1);
543 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
545 next:
546 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
547 if (*buffer == '\n')
548 buflen = 1;
550 while (buflen);
552 xfree (relptr);
555 /* Note, that FPR must be at least 20 bytes. */
556 static gpg_error_t
557 store_fpr (int slot, int keynumber, u32 timestamp,
558 const unsigned char *m, size_t mlen,
559 const unsigned char *e, size_t elen,
560 unsigned char *fpr, unsigned int card_version)
562 unsigned int n, nbits;
563 unsigned char *buffer, *p;
564 int rc;
566 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
568 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
571 n = 6 + 2 + mlen + 2 + elen;
572 p = buffer = xtrymalloc (3 + n);
573 if (!buffer)
574 return gpg_error_from_syserror ();
576 *p++ = 0x99; /* ctb */
577 *p++ = n >> 8; /* 2 byte length header */
578 *p++ = n;
579 *p++ = 4; /* key packet version */
580 *p++ = timestamp >> 24;
581 *p++ = timestamp >> 16;
582 *p++ = timestamp >> 8;
583 *p++ = timestamp;
584 *p++ = 1; /* RSA */
585 nbits = count_bits (m, mlen);
586 *p++ = nbits >> 8;
587 *p++ = nbits;
588 memcpy (p, m, mlen); p += mlen;
589 nbits = count_bits (e, elen);
590 *p++ = nbits >> 8;
591 *p++ = nbits;
592 memcpy (p, e, elen); p += elen;
594 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
596 xfree (buffer);
598 rc = iso7816_put_data (slot, (card_version > 0x0007? 0xC7 : 0xC6)
599 + keynumber, fpr, 20);
600 if (rc)
601 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
603 if (!rc && card_version > 0x0100)
605 unsigned char buf[4];
607 buf[0] = timestamp >> 24;
608 buf[1] = timestamp >> 16;
609 buf[2] = timestamp >> 8;
610 buf[3] = timestamp;
612 rc = iso7816_put_data (slot, 0xCE + keynumber, buf, 4);
613 if (rc)
614 log_error (_("failed to store the creation date: %s\n"),
615 gpg_strerror (rc));
618 return rc;
622 static void
623 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
624 int number, const unsigned char *fpr)
626 int i;
627 char buf[41];
628 char numbuf[25];
630 for (i=0; i < 20 && !fpr[i]; i++)
632 if (i==20)
633 return; /* All zero. */
634 for (i=0; i< 20; i++)
635 sprintf (buf+2*i, "%02X", fpr[i]);
636 if (number == -1)
637 *numbuf = 0; /* Don't print the key number */
638 else
639 sprintf (numbuf, "%d", number);
640 send_status_info (ctrl, keyword,
641 numbuf, (size_t)strlen(numbuf),
642 buf, (size_t)strlen (buf), NULL, 0);
645 static void
646 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
647 int number, const unsigned char *stamp)
649 char numbuf1[50], numbuf2[50];
650 unsigned long value;
652 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
653 if (!value)
654 return;
655 sprintf (numbuf1, "%d", number);
656 sprintf (numbuf2, "%lu", value);
657 send_status_info (ctrl, keyword,
658 numbuf1, (size_t)strlen(numbuf1),
659 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
662 static void
663 send_key_data (ctrl_t ctrl, const char *name,
664 const unsigned char *a, size_t alen)
666 char *p, *buf = xmalloc (alen*2+1);
668 for (p=buf; alen; a++, alen--, p += 2)
669 sprintf (p, "%02X", *a);
671 send_status_info (ctrl, "KEY-DATA",
672 name, (size_t)strlen(name),
673 buf, (size_t)strlen (buf),
674 NULL, 0);
675 xfree (buf);
678 /* Implement the GETATTR command. This is similar to the LEARN
679 command but returns just one value via the status interface. */
680 static gpg_error_t
681 do_getattr (app_t app, ctrl_t ctrl, const char *name)
683 static struct {
684 const char *name;
685 int tag;
686 int special;
687 } table[] = {
688 { "DISP-NAME", 0x005B },
689 { "LOGIN-DATA", 0x005E },
690 { "DISP-LANG", 0x5F2D },
691 { "DISP-SEX", 0x5F35 },
692 { "PUBKEY-URL", 0x5F50 },
693 { "KEY-FPR", 0x00C5, 3 },
694 { "KEY-TIME", 0x00CD, 4 },
695 { "CA-FPR", 0x00C6, 3 },
696 { "CHV-STATUS", 0x00C4, 1 },
697 { "SIG-COUNTER", 0x0093, 2 },
698 { "SERIALNO", 0x004F, -1 },
699 { "AID", 0x004F },
700 { "EXTCAP", 0x0000, -2 },
701 { "PRIVATE-DO-1", 0x0101 },
702 { "PRIVATE-DO-2", 0x0102 },
703 { "PRIVATE-DO-3", 0x0103 },
704 { "PRIVATE-DO-4", 0x0104 },
705 { "$AUTHKEYID", 0x0000, -3 },
706 { "$DISPSERIALNO",0x0000, -4 },
707 { NULL, 0 }
709 int idx, i, rc;
710 void *relptr;
711 unsigned char *value;
712 size_t valuelen;
714 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
716 if (!table[idx].name)
717 return gpg_error (GPG_ERR_INV_NAME);
719 if (table[idx].special == -1)
721 /* The serial number is very special. We could have used the
722 AID DO to retrieve it, but we have it already in the app
723 context and the stamp argument is required anyway which we
724 can't by other means. The AID DO is available anyway but not
725 hex formatted. */
726 char *serial;
727 time_t stamp;
728 char tmp[50];
730 if (!app_get_serial_and_stamp (app, &serial, &stamp))
732 sprintf (tmp, "%lu", (unsigned long)stamp);
733 send_status_info (ctrl, "SERIALNO",
734 serial, strlen (serial),
735 tmp, strlen (tmp),
736 NULL, 0);
737 xfree (serial);
739 return 0;
741 if (table[idx].special == -2)
743 char tmp[50];
745 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d",
746 app->app_local->extcap.get_challenge,
747 app->app_local->extcap.key_import,
748 app->app_local->extcap.change_force_chv,
749 app->app_local->extcap.private_dos);
750 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
751 return 0;
753 if (table[idx].special == -3)
755 char const tmp[] = "OPENPGP.3";
756 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
757 return 0;
759 if (table[idx].special == -4)
761 char *serial;
762 time_t stamp;
764 if (!app_get_serial_and_stamp (app, &serial, &stamp))
766 if (strlen (serial) > 16+12)
768 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
769 xfree (serial);
770 return 0;
772 xfree (serial);
774 return gpg_error (GPG_ERR_INV_NAME);
777 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
778 if (relptr)
780 if (table[idx].special == 1)
782 char numbuf[7*23];
784 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
785 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
786 send_status_info (ctrl, table[idx].name,
787 numbuf, strlen (numbuf), NULL, 0);
789 else if (table[idx].special == 2)
791 char numbuf[50];
793 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
794 send_status_info (ctrl, table[idx].name,
795 numbuf, strlen (numbuf), NULL, 0);
797 else if (table[idx].special == 3)
799 if (valuelen >= 60)
800 for (i=0; i < 3; i++)
801 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
803 else if (table[idx].special == 4)
805 if (valuelen >= 12)
806 for (i=0; i < 3; i++)
807 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
809 else
810 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
812 xfree (relptr);
814 return rc;
817 /* Retrieve the fingerprint from the card inserted in SLOT and write
818 the according hex representation to FPR. Caller must have provide
819 a buffer at FPR of least 41 bytes. Returns 0 on success or an
820 error code. */
821 #if GNUPG_MAJOR_VERSION > 1
822 static gpg_error_t
823 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
825 gpg_error_t err = 0;
826 void *relptr;
827 unsigned char *value;
828 size_t valuelen;
829 int i;
831 assert (keyno >=0 && keyno <= 2);
833 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
834 if (relptr && valuelen >= 60)
836 for (i = 0; i < 20; i++)
837 sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
839 else
840 err = gpg_error (GPG_ERR_NOT_FOUND);
841 xfree (relptr);
842 return err;
844 #endif /*GNUPG_MAJOR_VERSION > 1*/
847 /* Retrieve the public key material for the RSA key, whose fingerprint
848 is FPR, from gpg output, which can be read through the stream FP.
849 The RSA modulus will be stored at the address of M and MLEN, the
850 public exponent at E and ELEN. Returns zero on success, an error
851 code on failure. Caller must release the allocated buffers at M
852 and E if the function returns success. */
853 #if GNUPG_MAJOR_VERSION > 1
854 static gpg_error_t
855 retrieve_key_material (FILE *fp, const char *hexkeyid,
856 const unsigned char **m, size_t *mlen,
857 const unsigned char **e, size_t *elen)
859 gcry_error_t err = 0;
860 char *line = NULL; /* read_line() buffer. */
861 size_t line_size = 0; /* Helper for for read_line. */
862 int found_key = 0; /* Helper to find a matching key. */
863 unsigned char *m_new = NULL;
864 unsigned char *e_new = NULL;
865 size_t m_new_n = 0;
866 size_t e_new_n = 0;
868 /* Loop over all records until we have found the subkey
869 corresponsing to the fingerprint. Inm general the first record
870 should be the pub record, but we don't rely on that. Given that
871 we only need to look at one key, it is sufficient to compare the
872 keyid so that we don't need to look at "fpr" records. */
873 for (;;)
875 char *p;
876 char *fields[6];
877 int nfields;
878 size_t max_length;
879 gcry_mpi_t mpi;
880 int i;
882 max_length = 4096;
883 i = read_line (fp, &line, &line_size, &max_length);
884 if (!i)
885 break; /* EOF. */
886 if (i < 0)
888 err = gpg_error_from_syserror ();
889 goto leave; /* Error. */
891 if (!max_length)
893 err = gpg_error (GPG_ERR_TRUNCATED);
894 goto leave; /* Line truncated - we better stop processing. */
897 /* Parse the line into fields. */
898 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
900 fields[nfields] = p;
901 p = strchr (p, ':');
902 if (p)
903 *(p++) = 0;
905 if (!nfields)
906 continue; /* No fields at all - skip line. */
908 if (!found_key)
910 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
911 && nfields > 4 && !strcmp (fields[4], hexkeyid))
912 found_key = 1;
913 continue;
916 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
917 break; /* Next key - stop. */
919 if ( strcmp (fields[0], "pkd") )
920 continue; /* Not a key data record. */
921 i = 0; /* Avoid erroneous compiler warning. */
922 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
923 || (!i && m_new) || (i && e_new))
925 err = gpg_error (GPG_ERR_GENERAL);
926 goto leave; /* Error: Invalid key data record or not an RSA key. */
929 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
930 if (err)
931 mpi = NULL;
932 else if (!i)
933 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
934 else
935 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
936 gcry_mpi_release (mpi);
937 if (err)
938 goto leave;
941 if (m_new && e_new)
943 *m = m_new;
944 *mlen = m_new_n;
945 m_new = NULL;
946 *e = e_new;
947 *elen = e_new_n;
948 e_new = NULL;
950 else
951 err = gpg_error (GPG_ERR_GENERAL);
953 leave:
954 xfree (m_new);
955 xfree (e_new);
956 xfree (line);
957 return err;
959 #endif /*GNUPG_MAJOR_VERSION > 1*/
962 /* Get the public key for KEYNO and store it as an S-expresion with
963 the APP handle. On error that field gets cleared. If we already
964 know about the public key we will just return. Note that this does
965 not mean a key is available; this is soley indicated by the
966 presence of the app->app_local->pk[KEYNO-1].key field.
968 Note that GnuPG 1.x does not need this and it would be too time
969 consuming to send it just for the fun of it. However, given that we
970 use the same code in gpg 1.4, we can't use the gcry S-expresion
971 here but need to open encode it. */
972 #if GNUPG_MAJOR_VERSION > 1
973 static gpg_error_t
974 get_public_key (app_t app, int keyno)
976 gpg_error_t err = 0;
977 unsigned char *buffer;
978 const unsigned char *keydata, *m, *e;
979 size_t buflen, keydatalen, mlen, elen;
980 unsigned char *mbuf = NULL;
981 unsigned char *ebuf = NULL;
982 char *keybuf = NULL;
983 char *keybuf_p;
985 if (keyno < 1 || keyno > 3)
986 return gpg_error (GPG_ERR_INV_ID);
987 keyno--;
989 /* Already cached? */
990 if (app->app_local->pk[keyno].read_done)
991 return 0;
993 xfree (app->app_local->pk[keyno].key);
994 app->app_local->pk[keyno].key = NULL;
995 app->app_local->pk[keyno].keylen = 0;
997 m = e = NULL; /* (avoid cc warning) */
999 if (app->card_version > 0x0100)
1001 /* We may simply read the public key out of these cards. */
1002 err = iso7816_read_public_key
1003 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
1004 keyno == 1? "\xB8" : "\xA4"),
1006 &buffer, &buflen);
1007 if (err)
1009 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1010 goto leave;
1013 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1014 if (!keydata)
1016 err = gpg_error (GPG_ERR_CARD);
1017 log_error (_("response does not contain the public key data\n"));
1018 goto leave;
1021 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1022 if (!m)
1024 err = gpg_error (GPG_ERR_CARD);
1025 log_error (_("response does not contain the RSA modulus\n"));
1026 goto leave;
1030 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1031 if (!e)
1033 err = gpg_error (GPG_ERR_CARD);
1034 log_error (_("response does not contain the RSA public exponent\n"));
1035 goto leave;
1038 /* Prepend numbers with a 0 if needed. */
1039 if (mlen && (*m & 0x80))
1041 mbuf = xtrymalloc ( mlen + 1);
1042 if (!mbuf)
1044 err = gpg_error_from_syserror ();
1045 goto leave;
1047 *mbuf = 0;
1048 memcpy (mbuf+1, m, mlen);
1049 mlen++;
1050 m = mbuf;
1052 if (elen && (*e & 0x80))
1054 ebuf = xtrymalloc ( elen + 1);
1055 if (!ebuf)
1057 err = gpg_error_from_syserror ();
1058 goto leave;
1060 *ebuf = 0;
1061 memcpy (ebuf+1, e, elen);
1062 elen++;
1063 e = ebuf;
1067 else
1069 /* Due to a design problem in v1.0 cards we can't get the public
1070 key out of these cards without doing a verify on CHV3.
1071 Clearly that is not an option and thus we try to locate the
1072 key using an external helper.
1074 The helper we use here is gpg itself, which should know about
1075 the key in any case. */
1077 char fpr[41];
1078 char *hexkeyid;
1079 char *command = NULL;
1080 FILE *fp;
1081 int ret;
1083 buffer = NULL; /* We don't need buffer. */
1085 err = retrieve_fpr_from_card (app, keyno, fpr);
1086 if (err)
1088 log_error ("error while retrieving fpr from card: %s\n",
1089 gpg_strerror (err));
1090 goto leave;
1092 hexkeyid = fpr + 24;
1094 ret = asprintf (&command,
1095 "gpg --list-keys --with-colons --with-key-data '%s'",
1096 fpr);
1097 if (ret < 0)
1099 err = gpg_error_from_syserror ();
1100 goto leave;
1103 fp = popen (command, "r");
1104 free (command);
1105 if (!fp)
1107 err = gpg_error_from_syserror ();
1108 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1109 goto leave;
1112 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1113 fclose (fp);
1114 if (err)
1116 log_error ("error while retrieving key material through pipe: %s\n",
1117 gpg_strerror (err));
1118 goto leave;
1122 /* Allocate a buffer to construct the S-expression. */
1123 /* FIXME: We should provide a generalized S-expression creation
1124 mechanism. */
1125 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1126 if (!keybuf)
1128 err = gpg_error_from_syserror ();
1129 goto leave;
1132 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1133 keybuf_p = keybuf + strlen (keybuf);
1134 memcpy (keybuf_p, m, mlen);
1135 keybuf_p += mlen;
1136 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1137 keybuf_p += strlen (keybuf_p);
1138 memcpy (keybuf_p, e, elen);
1139 keybuf_p += elen;
1140 strcpy (keybuf_p, ")))");
1141 keybuf_p += strlen (keybuf_p);
1143 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1144 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1146 leave:
1147 /* Set a flag to indicate that we tried to read the key. */
1148 app->app_local->pk[keyno].read_done = 1;
1150 xfree (buffer);
1151 xfree (mbuf);
1152 xfree (ebuf);
1153 return 0;
1155 #endif /* GNUPG_MAJOR_VERSION > 1 */
1159 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1160 This is used by the LEARN command. */
1161 static gpg_error_t
1162 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1164 gpg_error_t err = 0;
1165 /* Note that GnuPG 1.x does not need this and it would be too time
1166 consuming to send it just for the fun of it. */
1167 #if GNUPG_MAJOR_VERSION > 1
1168 unsigned char grip[20];
1169 char gripstr[41];
1170 char idbuf[50];
1171 int i;
1173 err = get_public_key (app, keyno);
1174 if (err)
1175 goto leave;
1177 assert (keyno >= 1 && keyno <= 3);
1178 if (!app->app_local->pk[keyno-1].key)
1179 goto leave; /* No such key - ignore. */
1181 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1182 app->app_local->pk[keyno-1].keylen,
1183 grip);
1184 if (err)
1185 goto leave;
1187 for (i=0; i < 20; i++)
1188 sprintf (gripstr+i*2, "%02X", grip[i]);
1190 sprintf (idbuf, "OPENPGP.%d", keyno);
1191 send_status_info (ctrl, "KEYPAIRINFO",
1192 gripstr, 40,
1193 idbuf, strlen (idbuf),
1194 NULL, (size_t)0);
1196 leave:
1197 #endif /* GNUPG_MAJOR_VERSION > 1 */
1199 return err;
1203 /* Handle the LEARN command for OpenPGP. */
1204 static gpg_error_t
1205 do_learn_status (app_t app, ctrl_t ctrl)
1207 do_getattr (app, ctrl, "EXTCAP");
1208 do_getattr (app, ctrl, "DISP-NAME");
1209 do_getattr (app, ctrl, "DISP-LANG");
1210 do_getattr (app, ctrl, "DISP-SEX");
1211 do_getattr (app, ctrl, "PUBKEY-URL");
1212 do_getattr (app, ctrl, "LOGIN-DATA");
1213 do_getattr (app, ctrl, "KEY-FPR");
1214 if (app->card_version > 0x0100)
1215 do_getattr (app, ctrl, "KEY-TIME");
1216 do_getattr (app, ctrl, "CA-FPR");
1217 do_getattr (app, ctrl, "CHV-STATUS");
1218 do_getattr (app, ctrl, "SIG-COUNTER");
1219 if (app->app_local->extcap.private_dos)
1221 do_getattr (app, ctrl, "PRIVATE-DO-1");
1222 do_getattr (app, ctrl, "PRIVATE-DO-2");
1223 if (app->did_chv2)
1224 do_getattr (app, ctrl, "PRIVATE-DO-3");
1225 if (app->did_chv3)
1226 do_getattr (app, ctrl, "PRIVATE-DO-4");
1228 send_keypair_info (app, ctrl, 1);
1229 send_keypair_info (app, ctrl, 2);
1230 send_keypair_info (app, ctrl, 3);
1231 return 0;
1235 /* Handle the READKEY command for OpenPGP. On success a canonical
1236 encoded S-expression with the public key will get stored at PK and
1237 its length (for assertions) at PKLEN; the caller must release that
1238 buffer. On error PK and PKLEN are not changed and an error code is
1239 returned. */
1240 static gpg_error_t
1241 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1243 #if GNUPG_MAJOR_VERSION > 1
1244 gpg_error_t err;
1245 int keyno;
1246 unsigned char *buf;
1248 if (!strcmp (keyid, "OPENPGP.1"))
1249 keyno = 1;
1250 else if (!strcmp (keyid, "OPENPGP.2"))
1251 keyno = 2;
1252 else if (!strcmp (keyid, "OPENPGP.3"))
1253 keyno = 3;
1254 else
1255 return gpg_error (GPG_ERR_INV_ID);
1257 err = get_public_key (app, keyno);
1258 if (err)
1259 return err;
1261 buf = app->app_local->pk[keyno-1].key;
1262 if (!buf)
1263 return gpg_error (GPG_ERR_NO_PUBKEY);
1264 *pklen = app->app_local->pk[keyno-1].keylen;;
1265 *pk = xtrymalloc (*pklen);
1266 if (!*pk)
1268 err = gpg_error_from_syserror ();
1269 *pklen = 0;
1270 return err;
1272 memcpy (*pk, buf, *pklen);
1273 return 0;
1274 #else
1275 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1276 #endif
1281 /* Verify CHV2 if required. Depending on the configuration of the
1282 card CHV1 will also be verified. */
1283 static gpg_error_t
1284 verify_chv2 (app_t app,
1285 gpg_error_t (*pincb)(void*, const char *, char **),
1286 void *pincb_arg)
1288 int rc = 0;
1290 if (!app->did_chv2)
1292 char *pinvalue;
1293 iso7816_pininfo_t pininfo;
1294 int did_keypad = 0;
1296 memset (&pininfo, 0, sizeof pininfo);
1297 pininfo.mode = 1;
1298 pininfo.minlen = 6;
1300 if (!opt.disable_keypad
1301 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1303 /* The reader supports the verify command through the keypad. */
1304 did_keypad = 1;
1305 rc = pincb (pincb_arg,
1306 _("||Please enter your PIN at the reader's keypad"),
1307 NULL);
1308 if (rc)
1310 log_info (_("PIN callback returned error: %s\n"),
1311 gpg_strerror (rc));
1312 return rc;
1314 rc = iso7816_verify_kp (app->slot, 0x82, "", 0, &pininfo);
1315 /* Dismiss the prompt. */
1316 pincb (pincb_arg, NULL, NULL);
1318 else
1320 /* The reader has no keypad or we don't want to use it. */
1321 rc = pincb (pincb_arg, "PIN", &pinvalue);
1322 if (rc)
1324 log_info (_("PIN callback returned error: %s\n"),
1325 gpg_strerror (rc));
1326 return rc;
1329 if (strlen (pinvalue) < 6)
1331 log_error (_("PIN for CHV%d is too short;"
1332 " minimum length is %d\n"), 2, 6);
1333 xfree (pinvalue);
1334 return gpg_error (GPG_ERR_BAD_PIN);
1337 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
1340 if (rc)
1342 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
1343 xfree (pinvalue);
1344 flush_cache_after_error (app);
1345 return rc;
1347 app->did_chv2 = 1;
1349 if (!app->did_chv1 && !app->force_chv1 && !did_keypad)
1351 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1352 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1353 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1354 if (rc)
1356 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1357 xfree (pinvalue);
1358 flush_cache_after_error (app);
1359 return rc;
1361 app->did_chv1 = 1;
1363 xfree (pinvalue);
1365 return rc;
1368 /* Verify CHV3 if required. */
1369 static gpg_error_t
1370 verify_chv3 (app_t app,
1371 gpg_error_t (*pincb)(void*, const char *, char **),
1372 void *pincb_arg)
1374 int rc = 0;
1376 #if GNUPG_MAJOR_VERSION != 1
1377 if (!opt.allow_admin)
1379 log_info (_("access to admin commands is not configured\n"));
1380 return gpg_error (GPG_ERR_EACCES);
1382 #endif
1384 if (!app->did_chv3)
1386 char *pinvalue;
1387 void *relptr;
1388 unsigned char *value;
1389 size_t valuelen;
1391 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1392 if (!relptr || valuelen < 7)
1394 log_error (_("error retrieving CHV status from card\n"));
1395 xfree (relptr);
1396 return gpg_error (GPG_ERR_CARD);
1398 if (value[6] == 0)
1400 log_info (_("card is permanently locked!\n"));
1401 xfree (relptr);
1402 return gpg_error (GPG_ERR_BAD_PIN);
1405 log_info(_("%d Admin PIN attempts remaining before card"
1406 " is permanently locked\n"), value[6]);
1407 xfree (relptr);
1409 /* TRANSLATORS: Do not translate the "|A|" prefix but
1410 keep it at the start of the string. We need this elsewhere
1411 to get some infos on the string. */
1412 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1413 if (rc)
1415 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1416 return rc;
1419 if (strlen (pinvalue) < 8)
1421 log_error (_("PIN for CHV%d is too short;"
1422 " minimum length is %d\n"), 3, 8);
1423 xfree (pinvalue);
1424 return gpg_error (GPG_ERR_BAD_PIN);
1427 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1428 xfree (pinvalue);
1429 if (rc)
1431 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1432 flush_cache_after_error (app);
1433 return rc;
1435 app->did_chv3 = 1;
1437 return rc;
1441 /* Handle the SETATTR operation. All arguments are already basically
1442 checked. */
1443 static gpg_error_t
1444 do_setattr (app_t app, const char *name,
1445 gpg_error_t (*pincb)(void*, const char *, char **),
1446 void *pincb_arg,
1447 const unsigned char *value, size_t valuelen)
1449 gpg_error_t rc;
1450 int idx;
1451 static struct {
1452 const char *name;
1453 int tag;
1454 int need_chv;
1455 int special;
1456 } table[] = {
1457 { "DISP-NAME", 0x005B, 3 },
1458 { "LOGIN-DATA", 0x005E, 3, 2 },
1459 { "DISP-LANG", 0x5F2D, 3 },
1460 { "DISP-SEX", 0x5F35, 3 },
1461 { "PUBKEY-URL", 0x5F50, 3 },
1462 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1463 { "CA-FPR-1", 0x00CA, 3 },
1464 { "CA-FPR-2", 0x00CB, 3 },
1465 { "CA-FPR-3", 0x00CC, 3 },
1466 { "PRIVATE-DO-1", 0x0101, 2 },
1467 { "PRIVATE-DO-2", 0x0102, 3 },
1468 { "PRIVATE-DO-3", 0x0103, 2 },
1469 { "PRIVATE-DO-4", 0x0104, 3 },
1470 { NULL, 0 }
1474 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1476 if (!table[idx].name)
1477 return gpg_error (GPG_ERR_INV_NAME);
1479 switch (table[idx].need_chv)
1481 case 2:
1482 rc = verify_chv2 (app, pincb, pincb_arg);
1483 break;
1484 case 3:
1485 rc = verify_chv3 (app, pincb, pincb_arg);
1486 break;
1487 default:
1488 rc = 0;
1490 if (rc)
1491 return rc;
1493 /* Flush the cache before writing it, so that the next get operation
1494 will reread the data from the card and thus get synced in case of
1495 errors (e.g. data truncated by the card). */
1496 flush_cache_item (app, table[idx].tag);
1497 rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
1498 if (rc)
1499 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1501 if (table[idx].special == 1)
1502 app->force_chv1 = (valuelen && *value == 0);
1503 else if (table[idx].special == 2)
1504 parse_login_data (app);
1506 return rc;
1510 /* Handle the PASSWD command. */
1511 static gpg_error_t
1512 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
1513 gpg_error_t (*pincb)(void*, const char *, char **),
1514 void *pincb_arg)
1516 int rc = 0;
1517 int chvno = atoi (chvnostr);
1518 char *pinvalue;
1520 if (reset_mode && chvno == 3)
1522 rc = gpg_error (GPG_ERR_INV_ID);
1523 goto leave;
1525 else if (reset_mode || chvno == 3)
1527 /* we always require that the PIN is entered. */
1528 app->did_chv3 = 0;
1529 rc = verify_chv3 (app, pincb, pincb_arg);
1530 if (rc)
1531 goto leave;
1533 else if (chvno == 1 || chvno == 2)
1535 /* CHV1 and CVH2 should always have the same value, thus we
1536 enforce it here. */
1537 int save_force = app->force_chv1;
1539 app->force_chv1 = 0;
1540 app->did_chv1 = 0;
1541 app->did_chv2 = 0;
1542 rc = verify_chv2 (app, pincb, pincb_arg);
1543 app->force_chv1 = save_force;
1544 if (rc)
1545 goto leave;
1547 else
1549 rc = gpg_error (GPG_ERR_INV_ID);
1550 goto leave;
1553 if (chvno == 3)
1554 app->did_chv3 = 0;
1555 else
1556 app->did_chv1 = app->did_chv2 = 0;
1558 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1559 keep it at the start of the string. We need this elsewhere
1560 to get some infos on the string. */
1561 rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1562 &pinvalue);
1563 if (rc)
1565 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1566 goto leave;
1569 if (reset_mode)
1571 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1572 pinvalue, strlen (pinvalue));
1573 if (!rc)
1574 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1575 pinvalue, strlen (pinvalue));
1577 else
1579 if (chvno == 1 || chvno == 2)
1581 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1582 pinvalue, strlen (pinvalue));
1583 if (!rc)
1584 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1585 pinvalue, strlen (pinvalue));
1587 else
1588 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1589 pinvalue, strlen (pinvalue));
1591 xfree (pinvalue);
1592 if (rc)
1593 flush_cache_after_error (app);
1595 leave:
1596 return rc;
1600 /* Check whether a key already exists. KEYIDX is the index of the key
1601 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1602 error returned if the key already exists. */
1603 static gpg_error_t
1604 does_key_exist (app_t app, int keyidx, int force)
1606 const unsigned char *fpr;
1607 unsigned char *buffer;
1608 size_t buflen, n;
1609 int i;
1611 assert (keyidx >=0 && keyidx <= 2);
1613 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
1615 log_error (_("error reading application data\n"));
1616 return gpg_error (GPG_ERR_GENERAL);
1618 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1619 if (!fpr || n < 60)
1621 log_error (_("error reading fingerprint DO\n"));
1622 xfree (buffer);
1623 return gpg_error (GPG_ERR_GENERAL);
1625 fpr += 20*keyidx;
1626 for (i=0; i < 20 && !fpr[i]; i++)
1628 xfree (buffer);
1629 if (i!=20 && !force)
1631 log_error (_("key already exists\n"));
1632 return gpg_error (GPG_ERR_EEXIST);
1634 else if (i!=20)
1635 log_info (_("existing key will be replaced\n"));
1636 else
1637 log_info (_("generating new key\n"));
1638 return 0;
1643 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1644 canonical encoded S-expression with the secret key in KEYDATA and
1645 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1646 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1647 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1648 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1649 the pinentry callback. */
1650 static gpg_error_t
1651 do_writekey (app_t app, ctrl_t ctrl,
1652 const char *keyid, unsigned int flags,
1653 gpg_error_t (*pincb)(void*, const char *, char **),
1654 void *pincb_arg,
1655 const unsigned char *keydata, size_t keydatalen)
1657 gpg_error_t err;
1658 int force = (flags & 1);
1659 int keyno;
1660 const unsigned char *buf, *tok;
1661 size_t buflen, toklen;
1662 int depth, last_depth1, last_depth2;
1663 const unsigned char *rsa_n = NULL;
1664 const unsigned char *rsa_e = NULL;
1665 const unsigned char *rsa_p = NULL;
1666 const unsigned char *rsa_q = NULL;
1667 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
1668 unsigned int nbits;
1669 unsigned char *template = NULL;
1670 unsigned char *tp;
1671 size_t template_len;
1672 unsigned char fprbuf[20];
1673 u32 created_at = 0;
1675 if (!strcmp (keyid, "OPENPGP.1"))
1676 keyno = 0;
1677 else if (!strcmp (keyid, "OPENPGP.2"))
1678 keyno = 1;
1679 else if (!strcmp (keyid, "OPENPGP.3"))
1680 keyno = 2;
1681 else
1682 return gpg_error (GPG_ERR_INV_ID);
1684 err = does_key_exist (app, keyno, force);
1685 if (err)
1686 return err;
1690 Parse the S-expression
1692 buf = keydata;
1693 buflen = keydatalen;
1694 depth = 0;
1695 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1696 goto leave;
1697 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1698 goto leave;
1699 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
1701 if (!tok)
1703 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
1704 log_info ("protected-private-key passed to writekey\n");
1705 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
1706 log_info ("shadowed-private-key passed to writekey\n");
1707 err = gpg_error (GPG_ERR_BAD_SECKEY);
1708 goto leave;
1710 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1711 goto leave;
1712 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1713 goto leave;
1714 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
1716 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
1717 goto leave;
1719 last_depth1 = depth;
1720 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1721 && depth && depth >= last_depth1)
1723 if (tok)
1725 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1726 goto leave;
1728 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1729 goto leave;
1730 if (tok && toklen == 1)
1732 const unsigned char **mpi;
1733 size_t *mpi_len;
1735 switch (*tok)
1737 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
1738 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
1739 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
1740 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
1741 default: mpi = NULL; mpi_len = NULL; break;
1743 if (mpi && *mpi)
1745 err = gpg_error (GPG_ERR_DUP_VALUE);
1746 goto leave;
1748 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1749 goto leave;
1750 if (tok && mpi)
1752 /* Strip off leading zero bytes and save. */
1753 for (;toklen && !*tok; toklen--, tok++)
1755 *mpi = tok;
1756 *mpi_len = toklen;
1759 /* Skip until end of list. */
1760 last_depth2 = depth;
1761 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1762 && depth && depth >= last_depth2)
1764 if (err)
1765 goto leave;
1767 /* Parse other attributes. */
1768 last_depth1 = depth;
1769 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1770 && depth && depth >= last_depth1)
1772 if (tok)
1774 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1775 goto leave;
1777 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1778 goto leave;
1779 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
1781 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
1782 goto leave;
1783 if (tok)
1785 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
1786 tok++, toklen--)
1787 created_at = created_at*10 + (*tok - '0');
1790 /* Skip until end of list. */
1791 last_depth2 = depth;
1792 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1793 && depth && depth >= last_depth2)
1795 if (err)
1796 goto leave;
1800 /* Check that we have all parameters and that they match the card
1801 description. */
1802 if (!created_at)
1804 log_error (_("creation timestamp missing\n"));
1805 err = gpg_error (GPG_ERR_INV_VALUE);
1806 goto leave;
1808 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
1809 if (nbits != 1024)
1811 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1812 err = gpg_error (GPG_ERR_BAD_SECKEY);
1813 goto leave;
1815 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
1816 if (nbits < 2 || nbits > 32)
1818 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1819 32);
1820 err = gpg_error (GPG_ERR_BAD_SECKEY);
1821 goto leave;
1823 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
1824 if (nbits != 512)
1826 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1827 err = gpg_error (GPG_ERR_BAD_SECKEY);
1828 goto leave;
1830 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
1831 if (nbits != 512)
1833 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1834 err = gpg_error (GPG_ERR_BAD_SECKEY);
1835 goto leave;
1839 /* Build the private key template as described in section 4.3.3.6 of
1840 the OpenPGP card specs:
1841 0xC0 <length> public exponent
1842 0xC1 <length> prime p
1843 0xC2 <length> prime q
1845 assert (rsa_e_len <= 4);
1846 template_len = (1 + 1 + 4
1847 + 1 + 1 + rsa_p_len
1848 + 1 + 1 + rsa_q_len);
1849 template = tp = xtrymalloc_secure (template_len);
1850 if (!template)
1852 err = gpg_error_from_syserror ();
1853 goto leave;
1855 *tp++ = 0xC0;
1856 *tp++ = 4;
1857 memcpy (tp, rsa_e, rsa_e_len);
1858 if (rsa_e_len < 4)
1860 /* Right justify E. */
1861 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
1862 memset (tp, 0, 4-rsa_e_len);
1864 tp += 4;
1866 *tp++ = 0xC1;
1867 *tp++ = rsa_p_len;
1868 memcpy (tp, rsa_p, rsa_p_len);
1869 tp += rsa_p_len;
1871 *tp++ = 0xC2;
1872 *tp++ = rsa_q_len;
1873 memcpy (tp, rsa_q, rsa_q_len);
1874 tp += rsa_q_len;
1876 assert (tp - template == template_len);
1879 /* Obviously we need to remove the cached public key. */
1880 xfree (app->app_local->pk[keyno].key);
1881 app->app_local->pk[keyno].key = NULL;
1882 app->app_local->pk[keyno].keylen = 0;
1883 app->app_local->pk[keyno].read_done = 0;
1885 /* Prepare for storing the key. */
1886 err = verify_chv3 (app, pincb, pincb_arg);
1887 if (err)
1888 goto leave;
1890 /* Store the key. */
1891 err = iso7816_put_data (app->slot,
1892 (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
1893 template, template_len);
1894 if (err)
1896 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
1897 goto leave;
1900 err = store_fpr (app->slot, keyno, created_at,
1901 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
1902 fprbuf, app->card_version);
1903 if (err)
1904 goto leave;
1907 leave:
1908 xfree (template);
1909 return err;
1913 /* Handle the GENKEY command. */
1914 static gpg_error_t
1915 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
1916 gpg_error_t (*pincb)(void*, const char *, char **),
1917 void *pincb_arg)
1919 int rc;
1920 char numbuf[30];
1921 unsigned char fprbuf[20];
1922 const unsigned char *keydata, *m, *e;
1923 unsigned char *buffer = NULL;
1924 size_t buflen, keydatalen, mlen, elen;
1925 time_t created_at;
1926 int keyno = atoi (keynostr);
1927 int force = (flags & 1);
1928 time_t start_at;
1930 if (keyno < 1 || keyno > 3)
1931 return gpg_error (GPG_ERR_INV_ID);
1932 keyno--;
1934 /* We flush the cache to increase the traffic before a key
1935 generation. This _might_ help a card to gather more entropy. */
1936 flush_cache (app);
1938 /* Obviously we need to remove the cached public key. */
1939 xfree (app->app_local->pk[keyno].key);
1940 app->app_local->pk[keyno].key = NULL;
1941 app->app_local->pk[keyno].keylen = 0;
1942 app->app_local->pk[keyno].read_done = 0;
1944 /* Check whether a key already exists. */
1945 rc = does_key_exist (app, keyno, force);
1946 if (rc)
1947 return rc;
1949 /* Prepare for key generation by verifying the ADmin PIN. */
1950 rc = verify_chv3 (app, pincb, pincb_arg);
1951 if (rc)
1952 goto leave;
1954 #if 1
1955 log_info (_("please wait while key is being generated ...\n"));
1956 start_at = time (NULL);
1957 rc = iso7816_generate_keypair
1958 #else
1959 # warning key generation temporary replaced by reading an existing key.
1960 rc = iso7816_read_public_key
1961 #endif
1962 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
1963 keyno == 1? "\xB8" : "\xA4"),
1965 &buffer, &buflen);
1966 if (rc)
1968 rc = gpg_error (GPG_ERR_CARD);
1969 log_error (_("generating key failed\n"));
1970 goto leave;
1972 log_info (_("key generation completed (%d seconds)\n"),
1973 (int)(time (NULL) - start_at));
1974 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1975 if (!keydata)
1977 rc = gpg_error (GPG_ERR_CARD);
1978 log_error (_("response does not contain the public key data\n"));
1979 goto leave;
1982 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1983 if (!m)
1985 rc = gpg_error (GPG_ERR_CARD);
1986 log_error (_("response does not contain the RSA modulus\n"));
1987 goto leave;
1989 /* log_printhex ("RSA n:", m, mlen); */
1990 send_key_data (ctrl, "n", m, mlen);
1992 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1993 if (!e)
1995 rc = gpg_error (GPG_ERR_CARD);
1996 log_error (_("response does not contain the RSA public exponent\n"));
1997 goto leave;
1999 /* log_printhex ("RSA e:", e, elen); */
2000 send_key_data (ctrl, "e", e, elen);
2002 created_at = gnupg_get_time ();
2003 sprintf (numbuf, "%lu", (unsigned long)created_at);
2004 send_status_info (ctrl, "KEY-CREATED-AT",
2005 numbuf, (size_t)strlen(numbuf), NULL, 0);
2007 rc = store_fpr (app->slot, keyno, (u32)created_at,
2008 m, mlen, e, elen, fprbuf, app->card_version);
2009 if (rc)
2010 goto leave;
2011 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2014 leave:
2015 xfree (buffer);
2016 return rc;
2020 static unsigned long
2021 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2023 unsigned long ul;
2025 if (valuelen == 3 )
2026 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2027 else
2029 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2030 ul = 0;
2032 return ul;
2035 static unsigned long
2036 get_sig_counter (app_t app)
2038 void *relptr;
2039 unsigned char *value;
2040 size_t valuelen;
2041 unsigned long ul;
2043 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2044 if (!relptr)
2045 return 0;
2046 ul = convert_sig_counter_value (value, valuelen);
2047 xfree (relptr);
2048 return ul;
2051 static gpg_error_t
2052 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2054 const unsigned char *fpr;
2055 unsigned char *buffer;
2056 size_t buflen, n;
2057 int rc, i;
2059 assert (keyno >= 1 && keyno <= 3);
2061 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
2062 if (rc)
2064 log_error (_("error reading application data\n"));
2065 return gpg_error (GPG_ERR_GENERAL);
2067 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2068 if (!fpr || n != 60)
2070 xfree (buffer);
2071 log_error (_("error reading fingerprint DO\n"));
2072 return gpg_error (GPG_ERR_GENERAL);
2074 fpr += (keyno-1)*20;
2075 for (i=0; i < 20; i++)
2076 if (sha1fpr[i] != fpr[i])
2078 xfree (buffer);
2079 return gpg_error (GPG_ERR_WRONG_SECKEY);
2081 xfree (buffer);
2082 return 0;
2086 /* If a fingerprint has been specified check it against the one on
2087 the card. This is allows for a meaningful error message in case
2088 the key on the card has been replaced but the shadow information
2089 known to gpg was not updated. If there is no fingerprint we
2090 assume that this is okay. */
2091 static gpg_error_t
2092 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2094 unsigned char tmp[20];
2095 const char *s;
2096 int n;
2098 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2100 if (n != 40)
2101 return gpg_error (GPG_ERR_INV_ID);
2102 else if (!*s)
2103 ; /* okay */
2104 else
2105 return gpg_error (GPG_ERR_INV_ID);
2107 for (s=fpr, n=0; n < 20; s += 2, n++)
2108 tmp[n] = xtoi_2 (s);
2109 return compare_fingerprint (app, keyno, tmp);
2114 /* Compute a digital signature on INDATA which is expected to be the
2115 raw message digest. For this application the KEYIDSTR consists of
2116 the serialnumber and the fingerprint delimited by a slash.
2118 Note that this function may return the error code
2119 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2120 not match the one required for the requested action (e.g. the
2121 serial number does not match).
2123 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2124 operation to the auth command.
2126 static gpg_error_t
2127 do_sign (app_t app, const char *keyidstr, int hashalgo,
2128 gpg_error_t (*pincb)(void*, const char *, char **),
2129 void *pincb_arg,
2130 const void *indata, size_t indatalen,
2131 unsigned char **outdata, size_t *outdatalen )
2133 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2134 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2135 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2136 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2137 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2138 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2139 int rc;
2140 unsigned char data[35];
2141 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2142 const char *s;
2143 int n;
2144 const char *fpr = NULL;
2145 unsigned long sigcount;
2146 int use_auth = 0;
2148 if (!keyidstr || !*keyidstr)
2149 return gpg_error (GPG_ERR_INV_VALUE);
2150 if (indatalen == 20)
2152 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
2153 && !memcmp (indata, sha1_prefix, 15))
2155 indata += 15;
2156 indatalen -= 15;
2158 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
2159 && !memcmp (indata, rmd160_prefix, 15))
2161 indata += 15;
2162 indatalen -= 15;
2164 else
2166 log_error (_("card does not support digest algorithm %s\n"),
2167 gcry_md_algo_name (hashalgo));
2168 return gpg_error (GPG_ERR_INV_VALUE);
2171 /* Check whether an OpenPGP card of any version has been requested. */
2172 if (!strcmp (keyidstr, "OPENPGP.1"))
2174 else if (!strcmp (keyidstr, "OPENPGP.3"))
2175 use_auth = 1;
2176 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2177 return gpg_error (GPG_ERR_INV_ID);
2178 else
2180 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2182 if (n != 32)
2183 return gpg_error (GPG_ERR_INV_ID);
2184 else if (!*s)
2185 ; /* no fingerprint given: we allow this for now. */
2186 else if (*s == '/')
2187 fpr = s + 1;
2188 else
2189 return gpg_error (GPG_ERR_INV_ID);
2191 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2192 tmp_sn[n] = xtoi_2 (s);
2194 if (app->serialnolen != 16)
2195 return gpg_error (GPG_ERR_INV_CARD);
2196 if (memcmp (app->serialno, tmp_sn, 16))
2197 return gpg_error (GPG_ERR_WRONG_CARD);
2200 /* If a fingerprint has been specified check it against the one on
2201 the card. This is allows for a meaningful error message in case
2202 the key on the card has been replaced but the shadow information
2203 known to gpg was not updated. If there is no fingerprint, gpg
2204 will detect a bogus signature anyway due to the
2205 verify-after-signing feature. */
2206 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2207 if (rc)
2208 return rc;
2210 if (hashalgo == GCRY_MD_SHA1)
2211 memcpy (data, sha1_prefix, 15);
2212 else if (hashalgo == GCRY_MD_RMD160)
2213 memcpy (data, rmd160_prefix, 15);
2214 else
2215 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2216 memcpy (data+15, indata, indatalen);
2218 if (use_auth)
2220 /* This is a hack to redirect to the internal authenticate command. */
2221 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
2222 data, 35,
2223 outdata, outdatalen);
2226 sigcount = get_sig_counter (app);
2227 log_info (_("signatures created so far: %lu\n"), sigcount);
2229 if (!app->did_chv1 || app->force_chv1 )
2231 char *pinvalue;
2234 char *prompt;
2235 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
2237 prompt = malloc (strlen (PROMPTSTRING) + 50);
2238 if (!prompt)
2239 return gpg_error_from_syserror ();
2240 sprintf (prompt, PROMPTSTRING, sigcount);
2241 rc = pincb (pincb_arg, prompt, &pinvalue);
2242 free (prompt);
2243 #undef PROMPTSTRING
2245 if (rc)
2247 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
2248 return rc;
2251 if (strlen (pinvalue) < 6)
2253 log_error (_("PIN for CHV%d is too short;"
2254 " minimum length is %d\n"), 1, 6);
2255 xfree (pinvalue);
2256 return gpg_error (GPG_ERR_BAD_PIN);
2259 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
2260 if (rc)
2262 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
2263 xfree (pinvalue);
2264 flush_cache_after_error (app);
2265 return rc;
2267 app->did_chv1 = 1;
2268 if (!app->did_chv2)
2270 /* We should also verify CHV2. */
2271 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2272 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2273 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2274 if (rc)
2276 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2277 xfree (pinvalue);
2278 flush_cache_after_error (app);
2279 return rc;
2281 app->did_chv2 = 1;
2283 xfree (pinvalue);
2286 rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
2287 return rc;
2290 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2291 on INDATA which is expected to be the raw message digest. For this
2292 application the KEYIDSTR consists of the serialnumber and the
2293 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2294 be given.
2296 Note that this function may return the error code
2297 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2298 not match the one required for the requested action (e.g. the
2299 serial number does not match). */
2300 static gpg_error_t
2301 do_auth (app_t app, const char *keyidstr,
2302 gpg_error_t (*pincb)(void*, const char *, char **),
2303 void *pincb_arg,
2304 const void *indata, size_t indatalen,
2305 unsigned char **outdata, size_t *outdatalen )
2307 int rc;
2308 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2309 const char *s;
2310 int n;
2311 const char *fpr = NULL;
2313 if (!keyidstr || !*keyidstr)
2314 return gpg_error (GPG_ERR_INV_VALUE);
2315 if (indatalen > 50) /* For a 1024 bit key. */
2316 return gpg_error (GPG_ERR_INV_VALUE);
2318 /* Check whether an OpenPGP card of any version has been requested. */
2319 if (!strcmp (keyidstr, "OPENPGP.3"))
2321 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2322 return gpg_error (GPG_ERR_INV_ID);
2323 else
2325 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2327 if (n != 32)
2328 return gpg_error (GPG_ERR_INV_ID);
2329 else if (!*s)
2330 ; /* no fingerprint given: we allow this for now. */
2331 else if (*s == '/')
2332 fpr = s + 1;
2333 else
2334 return gpg_error (GPG_ERR_INV_ID);
2336 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2337 tmp_sn[n] = xtoi_2 (s);
2339 if (app->serialnolen != 16)
2340 return gpg_error (GPG_ERR_INV_CARD);
2341 if (memcmp (app->serialno, tmp_sn, 16))
2342 return gpg_error (GPG_ERR_WRONG_CARD);
2345 /* If a fingerprint has been specified check it against the one on
2346 the card. This is allows for a meaningful error message in case
2347 the key on the card has been replaced but the shadow information
2348 known to gpg was not updated. If there is no fingerprint, gpg
2349 will detect a bogus signature anyway due to the
2350 verify-after-signing feature. */
2351 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
2352 if (rc)
2353 return rc;
2355 rc = verify_chv2 (app, pincb, pincb_arg);
2356 if (!rc)
2357 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
2358 outdata, outdatalen);
2359 return rc;
2363 static gpg_error_t
2364 do_decipher (app_t app, const char *keyidstr,
2365 gpg_error_t (*pincb)(void*, const char *, char **),
2366 void *pincb_arg,
2367 const void *indata, size_t indatalen,
2368 unsigned char **outdata, size_t *outdatalen )
2370 int rc;
2371 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2372 const char *s;
2373 int n;
2374 const char *fpr = NULL;
2376 if (!keyidstr || !*keyidstr || !indatalen)
2377 return gpg_error (GPG_ERR_INV_VALUE);
2379 /* Check whether an OpenPGP card of any version has been requested. */
2380 if (!strcmp (keyidstr, "OPENPGP.2"))
2382 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2383 return gpg_error (GPG_ERR_INV_ID);
2384 else
2386 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2388 if (n != 32)
2389 return gpg_error (GPG_ERR_INV_ID);
2390 else if (!*s)
2391 ; /* no fingerprint given: we allow this for now. */
2392 else if (*s == '/')
2393 fpr = s + 1;
2394 else
2395 return gpg_error (GPG_ERR_INV_ID);
2397 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2398 tmp_sn[n] = xtoi_2 (s);
2400 if (app->serialnolen != 16)
2401 return gpg_error (GPG_ERR_INV_CARD);
2402 if (memcmp (app->serialno, tmp_sn, 16))
2403 return gpg_error (GPG_ERR_WRONG_CARD);
2406 /* If a fingerprint has been specified check it against the one on
2407 the card. This is allows for a meaningful error message in case
2408 the key on the card has been replaced but the shadow information
2409 known to gpg was not updated. If there is no fingerprint, the
2410 decryption will won't produce the right plaintext anyway. */
2411 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
2412 if (rc)
2413 return rc;
2415 rc = verify_chv2 (app, pincb, pincb_arg);
2416 if (!rc)
2417 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
2418 outdata, outdatalen);
2419 return rc;
2423 /* Perform a simple verify operation for CHV1 and CHV2, so that
2424 further operations won't ask for CHV2 and it is possible to do a
2425 cheap check on the PIN: If there is something wrong with the PIN
2426 entry system, only the regular CHV will get blocked and not the
2427 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2428 optional fingerprint part will be ignored.
2430 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2431 the "[CHV3]" being a literal string: The Admin Pin is checked if
2432 and only if the retry counter is still at 3. */
2433 static gpg_error_t
2434 do_check_pin (app_t app, const char *keyidstr,
2435 gpg_error_t (*pincb)(void*, const char *, char **),
2436 void *pincb_arg)
2438 unsigned char tmp_sn[20];
2439 const char *s;
2440 int n;
2441 int admin_pin = 0;
2443 if (!keyidstr || !*keyidstr)
2444 return gpg_error (GPG_ERR_INV_VALUE);
2446 /* Check whether an OpenPGP card of any version has been requested. */
2447 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2448 return gpg_error (GPG_ERR_INV_ID);
2450 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2452 if (n != 32)
2453 return gpg_error (GPG_ERR_INV_ID);
2454 else if (!*s)
2455 ; /* No fingerprint given: we allow this for now. */
2456 else if (*s == '/')
2457 ; /* We ignore a fingerprint. */
2458 else if (!strcmp (s, "[CHV3]") )
2459 admin_pin = 1;
2460 else
2461 return gpg_error (GPG_ERR_INV_ID);
2463 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2464 tmp_sn[n] = xtoi_2 (s);
2466 if (app->serialnolen != 16)
2467 return gpg_error (GPG_ERR_INV_CARD);
2468 if (memcmp (app->serialno, tmp_sn, 16))
2469 return gpg_error (GPG_ERR_WRONG_CARD);
2471 /* Yes, there is a race conditions: The user might pull the card
2472 right here and we won't notice that. However this is not a
2473 problem and the check above is merely for a graceful failure
2474 between operations. */
2476 if (admin_pin)
2478 void *relptr;
2479 unsigned char *value;
2480 size_t valuelen;
2481 int count;
2483 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2484 if (!relptr || valuelen < 7)
2486 log_error (_("error retrieving CHV status from card\n"));
2487 xfree (relptr);
2488 return gpg_error (GPG_ERR_CARD);
2490 count = value[6];
2491 xfree (relptr);
2493 if (!count)
2495 log_info (_("card is permanently locked!\n"));
2496 return gpg_error (GPG_ERR_BAD_PIN);
2498 else if (value[6] < 3)
2500 log_info (_("verification of Admin PIN is currently prohibited "
2501 "through this command\n"));
2502 return gpg_error (GPG_ERR_GENERAL);
2505 app->did_chv3 = 0; /* Force verification. */
2506 return verify_chv3 (app, pincb, pincb_arg);
2508 else
2509 return verify_chv2 (app, pincb, pincb_arg);
2515 /* Select the OpenPGP application on the card in SLOT. This function
2516 must be used before any other OpenPGP application functions. */
2517 gpg_error_t
2518 app_select_openpgp (app_t app)
2520 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2521 int slot = app->slot;
2522 int rc;
2523 unsigned char *buffer;
2524 size_t buflen;
2525 void *relptr;
2527 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
2528 special flag value. */
2529 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
2530 if (!rc)
2532 unsigned int manufacturer;
2534 app->apptype = "OPENPGP";
2536 app->did_chv1 = 0;
2537 app->did_chv2 = 0;
2538 app->did_chv3 = 0;
2539 app->app_local = NULL;
2541 /* The OpenPGP card returns the serial number as part of the
2542 AID; because we prefer to use OpenPGP serial numbers, we
2543 replace a possibly already set one from a EF.GDO with this
2544 one. Note, that for current OpenPGP cards, no EF.GDO exists
2545 and thus it won't matter at all. */
2546 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
2547 if (rc)
2548 goto leave;
2549 if (opt.verbose)
2551 log_info ("AID: ");
2552 log_printhex ("", buffer, buflen);
2555 app->card_version = buffer[6] << 8;
2556 app->card_version |= buffer[7];
2557 manufacturer = (buffer[8]<<8 | buffer[9]);
2559 xfree (app->serialno);
2560 app->serialno = buffer;
2561 app->serialnolen = buflen;
2562 buffer = NULL;
2563 app->app_local = xtrycalloc (1, sizeof *app->app_local);
2564 if (!app->app_local)
2566 rc = gpg_error (gpg_err_code_from_errno (errno));
2567 goto leave;
2570 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
2571 if (!relptr)
2573 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2574 "CHV Status Bytes");
2575 goto leave;
2577 app->force_chv1 = (buflen && *buffer == 0);
2578 xfree (relptr);
2580 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
2581 if (!relptr)
2583 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2584 "Extended Capability Flags" );
2585 goto leave;
2587 if (buflen)
2589 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
2590 app->app_local->extcap.key_import = !!(*buffer & 0x20);
2591 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
2592 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
2594 xfree (relptr);
2596 /* Some of the first cards accidently don't set the
2597 CHANGE_FORCE_CHV bit but allow it anyway. */
2598 if (app->card_version <= 0x0100 && manufacturer == 1)
2599 app->app_local->extcap.change_force_chv = 1;
2601 parse_login_data (app);
2603 if (opt.verbose > 1)
2604 dump_all_do (slot);
2606 app->fnc.deinit = do_deinit;
2607 app->fnc.learn_status = do_learn_status;
2608 app->fnc.readkey = do_readkey;
2609 app->fnc.getattr = do_getattr;
2610 app->fnc.setattr = do_setattr;
2611 app->fnc.writekey = do_writekey;
2612 app->fnc.genkey = do_genkey;
2613 app->fnc.sign = do_sign;
2614 app->fnc.auth = do_auth;
2615 app->fnc.decipher = do_decipher;
2616 app->fnc.change_pin = do_change_pin;
2617 app->fnc.check_pin = do_check_pin;
2620 leave:
2621 if (rc)
2622 do_deinit (app);
2623 return rc;