* exec.c (make_tempdir) [_WIN32]: Modified to properly handle
[gnupg.git] / g10 / app-openpgp.c
blobff0143c55c9b98d297d051376e4251e488bcdb40
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. Thsi
117 is usullay only required for corss 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);
150 /* Deconstructor. */
151 static void
152 do_deinit (app_t app)
154 if (app && app->app_local)
156 struct cache_s *c, *c2;
157 int i;
159 for (c = app->app_local->cache; c; c = c2)
161 c2 = c->next;
162 xfree (c);
165 for (i=0; i < DIM (app->app_local->pk); i++)
167 xfree (app->app_local->pk[i].key);
168 app->app_local->pk[i].read_done = 0;
170 xfree (app->app_local);
171 app->app_local = NULL;
176 /* Wrapper around iso7816_get_data which first tries to get the data
177 from the cache. With GET_IMMEDIATE passed as true, the cache is
178 bypassed. */
179 static gpg_error_t
180 get_cached_data (app_t app, int tag,
181 unsigned char **result, size_t *resultlen,
182 int get_immediate)
184 gpg_error_t err;
185 int i;
186 unsigned char *p;
187 size_t len;
188 struct cache_s *c;
190 *result = NULL;
191 *resultlen = 0;
193 if (!get_immediate)
195 for (c=app->app_local->cache; c; c = c->next)
196 if (c->tag == tag)
198 if(c->length)
200 p = xtrymalloc (c->length);
201 if (!p)
202 return gpg_error (gpg_err_code_from_errno (errno));
203 memcpy (p, c->data, c->length);
204 *result = p;
207 *resultlen = c->length;
209 return 0;
213 err = iso7816_get_data (app->slot, tag, &p, &len);
214 if (err)
215 return err;
216 *result = p;
217 *resultlen = len;
219 /* Check whether we should cache this object. */
220 if (get_immediate)
221 return 0;
223 for (i=0; data_objects[i].tag; i++)
224 if (data_objects[i].tag == tag)
226 if (data_objects[i].dont_cache)
227 return 0;
228 break;
231 /* Okay, cache it. */
232 for (c=app->app_local->cache; c; c = c->next)
233 assert (c->tag != tag);
235 c = xtrymalloc (sizeof *c + len);
236 if (c)
238 memcpy (c->data, p, len);
239 c->length = len;
240 c->tag = tag;
241 c->next = app->app_local->cache;
242 app->app_local->cache = c;
245 return 0;
248 /* Remove DO at TAG from the cache. */
249 static void
250 flush_cache_item (app_t app, int tag)
252 struct cache_s *c, *cprev;
253 int i;
255 if (!app->app_local)
256 return;
258 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
259 if (c->tag == tag)
261 if (cprev)
262 cprev->next = c->next;
263 else
264 app->app_local->cache = c->next;
265 xfree (c);
267 for (c=app->app_local->cache; c ; c = c->next)
269 assert (c->tag != tag); /* Oops: duplicated entry. */
271 return;
274 /* Try again if we have an outer tag. */
275 for (i=0; data_objects[i].tag; i++)
276 if (data_objects[i].tag == tag && data_objects[i].get_from
277 && data_objects[i].get_from != tag)
278 flush_cache_item (app, data_objects[i].get_from);
281 /* Flush all entries from the cache which might be out of sync after
282 an error. */
283 static void
284 flush_cache_after_error (app_t app)
286 int i;
288 for (i=0; data_objects[i].tag; i++)
289 if (data_objects[i].flush_on_error)
290 flush_cache_item (app, data_objects[i].tag);
294 /* Flush the entire cache. */
295 static void
296 flush_cache (app_t app)
298 if (app && app->app_local)
300 struct cache_s *c, *c2;
302 for (c = app->app_local->cache; c; c = c2)
304 c2 = c->next;
305 xfree (c);
307 app->app_local->cache = NULL;
312 /* Get the DO identified by TAG from the card in SLOT and return a
313 buffer with its content in RESULT and NBYTES. The return value is
314 NULL if not found or a pointer which must be used to release the
315 buffer holding value. */
316 static void *
317 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
318 int *r_rc)
320 int rc, i;
321 unsigned char *buffer;
322 size_t buflen;
323 unsigned char *value;
324 size_t valuelen;
325 int dummyrc;
327 if (!r_rc)
328 r_rc = &dummyrc;
330 *result = NULL;
331 *nbytes = 0;
332 *r_rc = 0;
333 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
336 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
338 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
339 if (rc)
341 *r_rc = rc;
342 return NULL;
344 *result = buffer;
345 *nbytes = buflen;
346 return buffer;
349 value = NULL;
350 rc = -1;
351 if (data_objects[i].tag && data_objects[i].get_from)
353 rc = get_cached_data (app, data_objects[i].get_from,
354 &buffer, &buflen,
355 (data_objects[i].dont_cache
356 || data_objects[i].get_immediate_in_v11));
357 if (!rc)
359 const unsigned char *s;
361 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
362 if (!s)
363 value = NULL; /* not found */
364 else if (valuelen > buflen - (s - buffer))
366 log_error ("warning: constructed DO too short\n");
367 value = NULL;
368 xfree (buffer); buffer = NULL;
370 else
371 value = buffer + (s - buffer);
375 if (!value) /* Not in a constructed DO, try simple. */
377 rc = get_cached_data (app, tag, &buffer, &buflen,
378 (data_objects[i].dont_cache
379 || data_objects[i].get_immediate_in_v11));
380 if (!rc)
382 value = buffer;
383 valuelen = buflen;
387 if (!rc)
389 *nbytes = valuelen;
390 *result = value;
391 return buffer;
393 *r_rc = rc;
394 return NULL;
398 static void
399 dump_all_do (int slot)
401 int rc, i, j;
402 unsigned char *buffer;
403 size_t buflen;
405 for (i=0; data_objects[i].tag; i++)
407 if (data_objects[i].get_from)
408 continue;
410 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
411 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
413 else if (rc)
414 log_info ("DO `%s' not available: %s\n",
415 data_objects[i].desc, gpg_strerror (rc));
416 else
418 if (data_objects[i].binary)
420 log_info ("DO `%s': ", data_objects[i].desc);
421 log_printhex ("", buffer, buflen);
423 else
424 log_info ("DO `%s': `%.*s'\n",
425 data_objects[i].desc,
426 (int)buflen, buffer); /* FIXME: sanitize */
428 if (data_objects[i].constructed)
430 for (j=0; data_objects[j].tag; j++)
432 const unsigned char *value;
433 size_t valuelen;
435 if (j==i || data_objects[i].tag != data_objects[j].get_from)
436 continue;
437 value = find_tlv_unchecked (buffer, buflen,
438 data_objects[j].tag, &valuelen);
439 if (!value)
440 ; /* not found */
441 else if (valuelen > buflen - (value - buffer))
442 log_error ("warning: constructed DO too short\n");
443 else
445 if (data_objects[j].binary)
447 log_info ("DO `%s': ", data_objects[j].desc);
448 log_printhex ("", value, valuelen);
450 else
451 log_info ("DO `%s': `%.*s'\n",
452 data_objects[j].desc,
453 (int)valuelen, value); /* FIXME: sanitize */
458 xfree (buffer); buffer = NULL;
463 /* Count the number of bits, assuming the A represents an unsigned big
464 integer of length LEN bytes. */
465 static unsigned int
466 count_bits (const unsigned char *a, size_t len)
468 unsigned int n = len * 8;
469 int i;
471 for (; len && !*a; len--, a++, n -=8)
473 if (len)
475 for (i=7; i && !(*a & (1<<i)); i--)
476 n--;
478 return n;
481 /* GnuPG makes special use of the login-data DO, this fucntion parses
482 the login data to store the flags for later use. It may be called
483 at any time and should be called after changing the login-data DO.
485 Everything up to a LF is considered a mailbox or account name. If
486 the first LF is followed by DC4 (0x14) control sequence are
487 expected up to the next LF. Control sequences are separated by FS
488 (0x28) and consist of key=value pairs. There is one key defined:
490 F=<flags>
492 Were FLAGS is a plain hexadecimal number representing flag values.
493 The lsb is here the rightmost bit. Defined flags bits are:
495 Bit 0 = CHV1 and CHV2 are not syncronized
496 Bit 1 = CHV2 has been been set to the default PIN of "123456"
497 (this implies that bit 0 is also set).
500 static void
501 parse_login_data (app_t app)
503 unsigned char *buffer, *p;
504 size_t buflen, len;
505 void *relptr;
507 /* Set defaults. */
508 app->app_local->flags.no_sync = 0;
509 app->app_local->flags.def_chv2 = 0;
511 /* Read the DO. */
512 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
513 if (!relptr)
514 return; /* Ooops. */
515 for (; buflen; buflen--, buffer++)
516 if (*buffer == '\n')
517 break;
518 if (buflen < 2 || buffer[1] != '\x14')
519 return; /* No control sequences. */
520 buflen--;
521 buffer++;
524 buflen--;
525 buffer++;
526 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
528 /* Flags control sequence found. */
529 int lastdig = 0;
531 /* For now we are only interested in the last digit, so skip
532 any leading digits but bail out on invalid characters. */
533 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
534 lastdig = xtoi_1 (p);
535 if (len && !(*p == '\n' || *p == '\x18'))
536 goto next; /* Invalid characters in field. */
537 app->app_local->flags.no_sync = !!(lastdig & 1);
538 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
540 next:
541 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
542 if (*buffer == '\n')
543 buflen = 1;
545 while (buflen);
547 xfree (relptr);
550 /* Note, that FPR must be at least 20 bytes. */
551 static gpg_error_t
552 store_fpr (int slot, int keynumber, u32 timestamp,
553 const unsigned char *m, size_t mlen,
554 const unsigned char *e, size_t elen,
555 unsigned char *fpr, unsigned int card_version)
557 unsigned int n, nbits;
558 unsigned char *buffer, *p;
559 int rc;
561 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
563 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
566 n = 6 + 2 + mlen + 2 + elen;
567 p = buffer = xtrymalloc (3 + n);
568 if (!buffer)
569 return gpg_error_from_errno (errno);
571 *p++ = 0x99; /* ctb */
572 *p++ = n >> 8; /* 2 byte length header */
573 *p++ = n;
574 *p++ = 4; /* key packet version */
575 *p++ = timestamp >> 24;
576 *p++ = timestamp >> 16;
577 *p++ = timestamp >> 8;
578 *p++ = timestamp;
579 *p++ = 1; /* RSA */
580 nbits = count_bits (m, mlen);
581 *p++ = nbits >> 8;
582 *p++ = nbits;
583 memcpy (p, m, mlen); p += mlen;
584 nbits = count_bits (e, elen);
585 *p++ = nbits >> 8;
586 *p++ = nbits;
587 memcpy (p, e, elen); p += elen;
589 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
591 xfree (buffer);
593 rc = iso7816_put_data (slot, (card_version > 0x0007? 0xC7 : 0xC6)
594 + keynumber, fpr, 20);
595 if (rc)
596 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
598 if (!rc && card_version > 0x0100)
600 unsigned char buf[4];
602 buf[0] = timestamp >> 24;
603 buf[1] = timestamp >> 16;
604 buf[2] = timestamp >> 8;
605 buf[3] = timestamp;
607 rc = iso7816_put_data (slot, 0xCE + keynumber, buf, 4);
608 if (rc)
609 log_error (_("failed to store the creation date: %s\n"),
610 gpg_strerror (rc));
613 return rc;
617 static void
618 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
619 int number, const unsigned char *fpr)
621 int i;
622 char buf[41];
623 char numbuf[25];
625 for (i=0; i < 20 && !fpr[i]; i++)
627 if (i==20)
628 return; /* All zero. */
629 for (i=0; i< 20; i++)
630 sprintf (buf+2*i, "%02X", fpr[i]);
631 if (number == -1)
632 *numbuf = 0; /* Don't print the key number */
633 else
634 sprintf (numbuf, "%d", number);
635 send_status_info (ctrl, keyword,
636 numbuf, (size_t)strlen(numbuf),
637 buf, (size_t)strlen (buf), NULL, 0);
640 static void
641 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
642 int number, const unsigned char *stamp)
644 char numbuf1[50], numbuf2[50];
645 unsigned long value;
647 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
648 if (!value)
649 return;
650 sprintf (numbuf1, "%d", number);
651 sprintf (numbuf2, "%lu", value);
652 send_status_info (ctrl, keyword,
653 numbuf1, (size_t)strlen(numbuf1),
654 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
657 static void
658 send_key_data (ctrl_t ctrl, const char *name,
659 const unsigned char *a, size_t alen)
661 char *p, *buf = xmalloc (alen*2+1);
663 for (p=buf; alen; a++, alen--, p += 2)
664 sprintf (p, "%02X", *a);
666 send_status_info (ctrl, "KEY-DATA",
667 name, (size_t)strlen(name),
668 buf, (size_t)strlen (buf),
669 NULL, 0);
670 xfree (buf);
673 /* Implement the GETATTR command. This is similar to the LEARN
674 command but returns just one value via the status interface. */
675 static gpg_error_t
676 do_getattr (app_t app, ctrl_t ctrl, const char *name)
678 static struct {
679 const char *name;
680 int tag;
681 int special;
682 } table[] = {
683 { "DISP-NAME", 0x005B },
684 { "LOGIN-DATA", 0x005E },
685 { "DISP-LANG", 0x5F2D },
686 { "DISP-SEX", 0x5F35 },
687 { "PUBKEY-URL", 0x5F50 },
688 { "KEY-FPR", 0x00C5, 3 },
689 { "KEY-TIME", 0x00CD, 4 },
690 { "CA-FPR", 0x00C6, 3 },
691 { "CHV-STATUS", 0x00C4, 1 },
692 { "SIG-COUNTER", 0x0093, 2 },
693 { "SERIALNO", 0x004F, -1 },
694 { "AID", 0x004F },
695 { "EXTCAP", 0x0000, -2 },
696 { "PRIVATE-DO-1", 0x0101 },
697 { "PRIVATE-DO-2", 0x0102 },
698 { "PRIVATE-DO-3", 0x0103 },
699 { "PRIVATE-DO-4", 0x0104 },
700 { NULL, 0 }
702 int idx, i, rc;
703 void *relptr;
704 unsigned char *value;
705 size_t valuelen;
707 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
709 if (!table[idx].name)
710 return gpg_error (GPG_ERR_INV_NAME);
712 if (table[idx].special == -1)
714 /* The serial number is very special. We could have used the
715 AID DO to retrieve it, but we have it already in the app
716 context and the stamp argument is required anyway which we
717 can't by other means. The AID DO is available anyway but not
718 hex formatted. */
719 char *serial;
720 time_t stamp;
721 char tmp[50];
723 if (!app_get_serial_and_stamp (app, &serial, &stamp))
725 sprintf (tmp, "%lu", (unsigned long)stamp);
726 send_status_info (ctrl, "SERIALNO",
727 serial, strlen (serial),
728 tmp, strlen (tmp),
729 NULL, 0);
730 xfree (serial);
732 return 0;
734 if (table[idx].special == -2)
736 char tmp[50];
738 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d",
739 app->app_local->extcap.get_challenge,
740 app->app_local->extcap.key_import,
741 app->app_local->extcap.change_force_chv,
742 app->app_local->extcap.private_dos);
743 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
744 return 0;
747 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
748 if (relptr)
750 if (table[idx].special == 1)
752 char numbuf[7*23];
754 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
755 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
756 send_status_info (ctrl, table[idx].name,
757 numbuf, strlen (numbuf), NULL, 0);
759 else if (table[idx].special == 2)
761 char numbuf[50];
763 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
764 send_status_info (ctrl, table[idx].name,
765 numbuf, strlen (numbuf), NULL, 0);
767 else if (table[idx].special == 3)
769 if (valuelen >= 60)
770 for (i=0; i < 3; i++)
771 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
773 else if (table[idx].special == 4)
775 if (valuelen >= 12)
776 for (i=0; i < 3; i++)
777 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
779 else
780 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
782 xfree (relptr);
784 return rc;
787 /* Retrieve the fingerprint from the card inserted in SLOT and write
788 the according hex representation to FPR. Caller must have provide
789 a buffer at FPR of least 41 bytes. Returns 0 on success or an
790 error code. */
791 #if GNUPG_MAJOR_VERSION > 1
792 static gpg_error_t
793 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
795 gpg_error_t err = 0;
796 void *relptr;
797 unsigned char *value;
798 size_t valuelen;
799 int i;
801 assert (keyno >=0 && keyno <= 2);
803 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
804 if (relptr && valuelen >= 60)
806 for (i = 0; i < 20; i++)
807 sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
809 else
810 err = gpg_error (GPG_ERR_NOT_FOUND);
811 xfree (relptr);
812 return err;
814 #endif /*GNUPG_MAJOR_VERSION > 1*/
817 /* Retrieve the public key material for the RSA key, whose fingerprint
818 is FPR, from gpg output, which can be read through the stream FP.
819 The RSA modulus will be stored at the address of M and MLEN, the
820 public exponent at E and ELEN. Returns zero on success, an error
821 code on failure. Caller must release the allocated buffers at M
822 and E if the function returns success. */
823 #if GNUPG_MAJOR_VERSION > 1
824 static gpg_error_t
825 retrieve_key_material (FILE *fp, const char *hexkeyid,
826 const unsigned char **m, size_t *mlen,
827 const unsigned char **e, size_t *elen)
829 gcry_error_t err = 0;
830 char *line = NULL; /* read_line() buffer. */
831 size_t line_size = 0; /* Helper for for read_line. */
832 int found_key = 0; /* Helper to find a matching key. */
833 unsigned char *m_new = NULL;
834 unsigned char *e_new = NULL;
835 size_t m_new_n = 0;
836 size_t e_new_n = 0;
838 /* Loop over all records until we have found the subkey
839 corresponsing to the fingerprint. Inm general the first record
840 should be the pub record, but we don't rely on that. Given that
841 we only need to look at one key, it is sufficient to compare the
842 keyid so that we don't need to look at "fpr" records. */
843 for (;;)
845 char *p;
846 char *fields[6];
847 int nfields;
848 size_t max_length;
849 gcry_mpi_t mpi;
850 int i;
852 max_length = 4096;
853 i = read_line (fp, &line, &line_size, &max_length);
854 if (!i)
855 break; /* EOF. */
856 if (i < 0)
858 err = gpg_error_from_errno (errno);
859 goto leave; /* Error. */
861 if (!max_length)
863 err = gpg_error (GPG_ERR_TRUNCATED);
864 goto leave; /* Line truncated - we better stop processing. */
867 /* Parse the line into fields. */
868 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
870 fields[nfields] = p;
871 p = strchr (p, ':');
872 if (p)
873 *(p++) = 0;
875 if (!nfields)
876 continue; /* No fields at all - skip line. */
878 if (!found_key)
880 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
881 && nfields > 4 && !strcmp (fields[4], hexkeyid))
882 found_key = 1;
883 continue;
886 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
887 break; /* Next key - stop. */
889 if ( strcmp (fields[0], "pkd") )
890 continue; /* Not a key data record. */
891 i = 0; /* Avoid erroneous compiler warning. */
892 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
893 || (!i && m_new) || (i && e_new))
895 err = gpg_error (GPG_ERR_GENERAL);
896 goto leave; /* Error: Invalid key data record or not an RSA key. */
899 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
900 if (err)
901 mpi = NULL;
902 else if (!i)
903 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
904 else
905 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
906 gcry_mpi_release (mpi);
907 if (err)
908 goto leave;
911 if (m_new && e_new)
913 *m = m_new;
914 *mlen = m_new_n;
915 m_new = NULL;
916 *e = e_new;
917 *elen = e_new_n;
918 e_new = NULL;
920 else
921 err = gpg_error (GPG_ERR_GENERAL);
923 leave:
924 xfree (m_new);
925 xfree (e_new);
926 xfree (line);
927 return err;
929 #endif /*GNUPG_MAJOR_VERSION > 1*/
932 /* Get the public key for KEYNO and store it as an S-expresion with
933 the APP handle. On error that field gets cleared. If we already
934 know about the public key we will just return. Note that this does
935 not mean a key is available; this is soley indicated by the
936 presence of the app->app_local->pk[KEYNO-1].key field.
938 Note that GnuPG 1.x does not need this and it would be too time
939 consuming to send it just for the fun of it. However, given that we
940 use the same code in gpg 1.4, we can't use the gcry S-expresion
941 here but need to open encode it. */
942 #if GNUPG_MAJOR_VERSION > 1
943 static gpg_error_t
944 get_public_key (app_t app, int keyno)
946 gpg_error_t err = 0;
947 unsigned char *buffer;
948 const unsigned char *keydata, *m, *e;
949 size_t buflen, keydatalen, mlen, elen;
950 unsigned char *mbuf = NULL;
951 unsigned char *ebuf = NULL;
952 unsigned char *keybuf = NULL;
953 unsigned char *keybuf_p;
955 if (keyno < 1 || keyno > 3)
956 return gpg_error (GPG_ERR_INV_ID);
957 keyno--;
959 /* Already cached? */
960 if (app->app_local->pk[keyno].read_done)
961 return 0;
963 xfree (app->app_local->pk[keyno].key);
964 app->app_local->pk[keyno].key = NULL;
965 app->app_local->pk[keyno].keylen = 0;
967 if (app->card_version > 0x0100)
969 /* We may simply read the public key out of these cards. */
970 err = iso7816_read_public_key (app->slot,
971 keyno == 0? "\xB6" :
972 keyno == 1? "\xB8" : "\xA4",
974 &buffer, &buflen);
975 if (err)
977 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
978 goto leave;
981 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
982 if (!keydata)
984 err = gpg_error (GPG_ERR_CARD);
985 log_error (_("response does not contain the public key data\n"));
986 goto leave;
989 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
990 if (!m)
992 err = gpg_error (GPG_ERR_CARD);
993 log_error (_("response does not contain the RSA modulus\n"));
994 goto leave;
998 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
999 if (!e)
1001 err = gpg_error (GPG_ERR_CARD);
1002 log_error (_("response does not contain the RSA public exponent\n"));
1003 goto leave;
1006 /* Prepend numbers with a 0 if needed. */
1007 if (mlen && (*m & 0x80))
1009 mbuf = xtrymalloc ( mlen + 1);
1010 if (!mbuf)
1012 err = gpg_error_from_errno (errno);
1013 goto leave;
1015 *mbuf = 0;
1016 memcpy (mbuf+1, m, mlen);
1017 mlen++;
1018 m = mbuf;
1020 if (elen && (*e & 0x80))
1022 ebuf = xtrymalloc ( elen + 1);
1023 if (!ebuf)
1025 err = gpg_error_from_errno (errno);
1026 goto leave;
1028 *ebuf = 0;
1029 memcpy (ebuf+1, e, elen);
1030 elen++;
1031 e = ebuf;
1035 else
1037 /* Due to a design problem in v1.0 cards we can't get the public
1038 key out of these cards without doing a verify on CHV3.
1039 Clearly that is not an option and thus we try to locate the
1040 key using an external helper.
1042 The helper we use here is gpg itself, which should know about
1043 the key in any case. */
1045 char fpr[41];
1046 char *hexkeyid;
1047 char *command = NULL;
1048 FILE *fp;
1049 int ret;
1051 buffer = NULL; /* We don't need buffer. */
1053 err = retrieve_fpr_from_card (app, keyno, fpr);
1054 if (err)
1056 log_error ("error while retrieving fpr from card: %s\n",
1057 gpg_strerror (err));
1058 goto leave;
1060 hexkeyid = fpr + 24;
1062 ret = asprintf (&command,
1063 "gpg --list-keys --with-colons --with-key-data '%s'",
1064 fpr);
1065 if (ret < 0)
1067 err = gpg_error_from_errno (errno);
1068 goto leave;
1071 fp = popen (command, "r");
1072 free (command);
1073 if (!fp)
1075 err = gpg_error_from_errno (errno);
1076 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1077 goto leave;
1080 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1081 fclose (fp);
1082 if (err)
1084 log_error ("error while retrieving key material through pipe: %s\n",
1085 gpg_strerror (err));
1086 goto leave;
1090 /* Allocate a buffer to construct the S-expression. */
1091 /* FIXME: We should provide a generalized S-expression creation
1092 mechanism. */
1093 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1094 if (!keybuf)
1096 err = gpg_error_from_errno (errno);
1097 goto leave;
1100 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1101 keybuf_p = keybuf + strlen (keybuf);
1102 memcpy (keybuf_p, m, mlen);
1103 keybuf_p += mlen;
1104 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1105 keybuf_p += strlen (keybuf_p);
1106 memcpy (keybuf_p, e, elen);
1107 keybuf_p += elen;
1108 strcpy (keybuf_p, ")))");
1109 keybuf_p += strlen (keybuf_p);
1111 app->app_local->pk[keyno].key = keybuf;
1112 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1114 leave:
1115 /* Set a flag to indicate that we tried to read the key. */
1116 app->app_local->pk[keyno].read_done = 1;
1118 xfree (buffer);
1119 xfree (mbuf);
1120 xfree (ebuf);
1121 return 0;
1123 #endif /* GNUPG_MAJOR_VERSION > 1 */
1127 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1128 This is used by the LEARN command. */
1129 static gpg_error_t
1130 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1132 gpg_error_t err = 0;
1133 /* Note that GnuPG 1.x does not need this and it would be too time
1134 consuming to send it just for the fun of it. */
1135 #if GNUPG_MAJOR_VERSION > 1
1136 unsigned char grip[20];
1137 char gripstr[41];
1138 char idbuf[50];
1139 int i;
1141 err = get_public_key (app, keyno);
1142 if (err)
1143 goto leave;
1145 assert (keyno >= 1 && keyno <= 3);
1146 if (!app->app_local->pk[keyno-1].key)
1147 goto leave; /* No such key - ignore. */
1149 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1150 app->app_local->pk[keyno-1].keylen,
1151 grip);
1152 if (err)
1153 goto leave;
1155 for (i=0; i < 20; i++)
1156 sprintf (gripstr+i*2, "%02X", grip[i]);
1158 sprintf (idbuf, "OPENPGP.%d", keyno);
1159 send_status_info (ctrl, "KEYPAIRINFO",
1160 gripstr, 40,
1161 idbuf, strlen (idbuf),
1162 NULL, (size_t)0);
1164 leave:
1165 #endif /* GNUPG_MAJOR_VERSION > 1 */
1167 return err;
1171 /* Handle the LEARN command for OpenPGP. */
1172 static gpg_error_t
1173 do_learn_status (app_t app, ctrl_t ctrl)
1175 do_getattr (app, ctrl, "EXTCAP");
1176 do_getattr (app, ctrl, "DISP-NAME");
1177 do_getattr (app, ctrl, "DISP-LANG");
1178 do_getattr (app, ctrl, "DISP-SEX");
1179 do_getattr (app, ctrl, "PUBKEY-URL");
1180 do_getattr (app, ctrl, "LOGIN-DATA");
1181 do_getattr (app, ctrl, "KEY-FPR");
1182 if (app->card_version > 0x0100)
1183 do_getattr (app, ctrl, "KEY-TIME");
1184 do_getattr (app, ctrl, "CA-FPR");
1185 do_getattr (app, ctrl, "CHV-STATUS");
1186 do_getattr (app, ctrl, "SIG-COUNTER");
1187 if (app->app_local->extcap.private_dos)
1189 do_getattr (app, ctrl, "PRIVATE-DO-1");
1190 do_getattr (app, ctrl, "PRIVATE-DO-2");
1191 if (app->did_chv2)
1192 do_getattr (app, ctrl, "PRIVATE-DO-3");
1193 if (app->did_chv3)
1194 do_getattr (app, ctrl, "PRIVATE-DO-4");
1196 send_keypair_info (app, ctrl, 1);
1197 send_keypair_info (app, ctrl, 2);
1198 send_keypair_info (app, ctrl, 3);
1199 return 0;
1203 /* Handle the READKEY command for OpenPGP. On success a canonical
1204 encoded S-expression with the public key will get stored at PK and
1205 its length (for assertions) at PKLEN; the caller must release that
1206 buffer. On error PK and PKLEN are not changed and an error code is
1207 returned. */
1208 static gpg_error_t
1209 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1211 #if GNUPG_MAJOR_VERSION > 1
1212 gpg_error_t err;
1213 int keyno;
1214 unsigned char *buf;
1216 if (!strcmp (keyid, "OPENPGP.1"))
1217 keyno = 1;
1218 else if (!strcmp (keyid, "OPENPGP.2"))
1219 keyno = 2;
1220 else if (!strcmp (keyid, "OPENPGP.3"))
1221 keyno = 3;
1222 else
1223 return gpg_error (GPG_ERR_INV_ID);
1225 err = get_public_key (app, keyno);
1226 if (err)
1227 return err;
1229 buf = app->app_local->pk[keyno-1].key;
1230 if (!buf)
1231 return gpg_error (GPG_ERR_NO_PUBKEY);
1232 *pk = buf;
1233 *pklen = app->app_local->pk[keyno-1].keylen;;
1234 return 0;
1235 #else
1236 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1237 #endif
1242 /* Verify CHV2 if required. Depending on the configuration of the
1243 card CHV1 will also be verified. */
1244 static gpg_error_t
1245 verify_chv2 (app_t app,
1246 gpg_error_t (*pincb)(void*, const char *, char **),
1247 void *pincb_arg)
1249 int rc = 0;
1251 if (!app->did_chv2)
1253 char *pinvalue;
1255 rc = pincb (pincb_arg, "PIN", &pinvalue);
1256 if (rc)
1258 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1259 return rc;
1262 if (strlen (pinvalue) < 6)
1264 log_error (_("PIN for CHV%d is too short;"
1265 " minimum length is %d\n"), 2, 6);
1266 xfree (pinvalue);
1267 return gpg_error (GPG_ERR_BAD_PIN);
1270 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
1271 if (rc)
1273 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
1274 xfree (pinvalue);
1275 flush_cache_after_error (app);
1276 return rc;
1278 app->did_chv2 = 1;
1280 if (!app->did_chv1 && !app->force_chv1)
1282 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1283 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1284 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1285 if (rc)
1287 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1288 xfree (pinvalue);
1289 flush_cache_after_error (app);
1290 return rc;
1292 app->did_chv1 = 1;
1294 xfree (pinvalue);
1296 return rc;
1299 /* Verify CHV3 if required. */
1300 static gpg_error_t
1301 verify_chv3 (app_t app,
1302 gpg_error_t (*pincb)(void*, const char *, char **),
1303 void *pincb_arg)
1305 int rc = 0;
1307 #if GNUPG_MAJOR_VERSION != 1
1308 if (!opt.allow_admin)
1310 log_info (_("access to admin commands is not configured\n"));
1311 return gpg_error (GPG_ERR_EACCES);
1313 #endif
1315 if (!app->did_chv3)
1317 char *pinvalue;
1318 void *relptr;
1319 unsigned char *value;
1320 size_t valuelen;
1322 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1323 if (!relptr || valuelen < 7)
1325 log_error (_("error retrieving CHV status from card\n"));
1326 xfree (relptr);
1327 return gpg_error (GPG_ERR_CARD);
1329 if (value[6] == 0)
1331 log_info (_("card is permanently locked!\n"));
1332 xfree (relptr);
1333 return gpg_error (GPG_ERR_BAD_PIN);
1336 log_info(_("%d Admin PIN attempts remaining before card"
1337 " is permanently locked\n"), value[6]);
1338 xfree (relptr);
1340 /* TRANSLATORS: Do not translate the "|A|" prefix but
1341 keep it at the start of the string. We need this elsewhere
1342 to get some infos on the string. */
1343 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1344 if (rc)
1346 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1347 return rc;
1350 if (strlen (pinvalue) < 8)
1352 log_error (_("PIN for CHV%d is too short;"
1353 " minimum length is %d\n"), 3, 8);
1354 xfree (pinvalue);
1355 return gpg_error (GPG_ERR_BAD_PIN);
1358 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1359 xfree (pinvalue);
1360 if (rc)
1362 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1363 flush_cache_after_error (app);
1364 return rc;
1366 app->did_chv3 = 1;
1368 return rc;
1372 /* Handle the SETATTR operation. All arguments are already basically
1373 checked. */
1374 static gpg_error_t
1375 do_setattr (app_t app, const char *name,
1376 gpg_error_t (*pincb)(void*, const char *, char **),
1377 void *pincb_arg,
1378 const unsigned char *value, size_t valuelen)
1380 gpg_error_t rc;
1381 int idx;
1382 static struct {
1383 const char *name;
1384 int tag;
1385 int need_chv;
1386 int special;
1387 } table[] = {
1388 { "DISP-NAME", 0x005B, 3 },
1389 { "LOGIN-DATA", 0x005E, 3, 2 },
1390 { "DISP-LANG", 0x5F2D, 3 },
1391 { "DISP-SEX", 0x5F35, 3 },
1392 { "PUBKEY-URL", 0x5F50, 3 },
1393 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1394 { "CA-FPR-1", 0x00CA, 3 },
1395 { "CA-FPR-2", 0x00CB, 3 },
1396 { "CA-FPR-3", 0x00CC, 3 },
1397 { "PRIVATE-DO-1", 0x0101, 2 },
1398 { "PRIVATE-DO-2", 0x0102, 3 },
1399 { "PRIVATE-DO-3", 0x0103, 2 },
1400 { "PRIVATE-DO-4", 0x0104, 3 },
1401 { NULL, 0 }
1405 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1407 if (!table[idx].name)
1408 return gpg_error (GPG_ERR_INV_NAME);
1410 switch (table[idx].need_chv)
1412 case 2:
1413 rc = verify_chv2 (app, pincb, pincb_arg);
1414 break;
1415 case 3:
1416 rc = verify_chv3 (app, pincb, pincb_arg);
1417 break;
1418 default:
1419 rc = 0;
1421 if (rc)
1422 return rc;
1424 /* Flush the cache before writing it, so that the next get operation
1425 will reread the data from the card and thus get synced in case of
1426 errors (e.g. data truncated by the card). */
1427 flush_cache_item (app, table[idx].tag);
1428 rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
1429 if (rc)
1430 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1432 if (table[idx].special == 1)
1433 app->force_chv1 = (valuelen && *value == 0);
1434 else if (table[idx].special == 2)
1435 parse_login_data (app);
1437 return rc;
1441 /* Handle the PASSWD command. */
1442 static gpg_error_t
1443 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
1444 gpg_error_t (*pincb)(void*, const char *, char **),
1445 void *pincb_arg)
1447 int rc = 0;
1448 int chvno = atoi (chvnostr);
1449 char *pinvalue;
1451 if (reset_mode && chvno == 3)
1453 rc = gpg_error (GPG_ERR_INV_ID);
1454 goto leave;
1456 else if (reset_mode || chvno == 3)
1458 /* we always require that the PIN is entered. */
1459 app->did_chv3 = 0;
1460 rc = verify_chv3 (app, pincb, pincb_arg);
1461 if (rc)
1462 goto leave;
1464 else if (chvno == 1 || chvno == 2)
1466 /* CHV1 and CVH2 should always have the same value, thus we
1467 enforce it here. */
1468 int save_force = app->force_chv1;
1470 app->force_chv1 = 0;
1471 app->did_chv1 = 0;
1472 app->did_chv2 = 0;
1473 rc = verify_chv2 (app, pincb, pincb_arg);
1474 app->force_chv1 = save_force;
1475 if (rc)
1476 goto leave;
1478 else
1480 rc = gpg_error (GPG_ERR_INV_ID);
1481 goto leave;
1484 if (chvno == 3)
1485 app->did_chv3 = 0;
1486 else
1487 app->did_chv1 = app->did_chv2 = 0;
1489 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1490 keep it at the start of the string. We need this elsewhere
1491 to get some infos on the string. */
1492 rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1493 &pinvalue);
1494 if (rc)
1496 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1497 goto leave;
1500 if (reset_mode)
1502 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1503 pinvalue, strlen (pinvalue));
1504 if (!rc)
1505 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1506 pinvalue, strlen (pinvalue));
1508 else
1510 if (chvno == 1 || chvno == 2)
1512 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1513 pinvalue, strlen (pinvalue));
1514 if (!rc)
1515 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1516 pinvalue, strlen (pinvalue));
1518 else
1519 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1520 pinvalue, strlen (pinvalue));
1522 xfree (pinvalue);
1523 if (rc)
1524 flush_cache_after_error (app);
1526 leave:
1527 return rc;
1531 /* Check whether a key already exists. KEYIDX is the index of the key
1532 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1533 error returned if the key already exists. */
1534 static gpg_error_t
1535 does_key_exist (app_t app, int keyidx, int force)
1537 const unsigned char *fpr;
1538 unsigned char *buffer;
1539 size_t buflen, n;
1540 int i;
1542 assert (keyidx >=0 && keyidx <= 2);
1544 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
1546 log_error (_("error reading application data\n"));
1547 return gpg_error (GPG_ERR_GENERAL);
1549 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1550 if (!fpr || n < 60)
1552 log_error (_("error reading fingerprint DO\n"));
1553 xfree (buffer);
1554 return gpg_error (GPG_ERR_GENERAL);
1556 fpr += 20*keyidx;
1557 for (i=0; i < 20 && !fpr[i]; i++)
1559 xfree (buffer);
1560 if (i!=20 && !force)
1562 log_error (_("key already exists\n"));
1563 return gpg_error (GPG_ERR_EEXIST);
1565 else if (i!=20)
1566 log_info (_("existing key will be replaced\n"));
1567 else
1568 log_info (_("generating new key\n"));
1569 return 0;
1574 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1575 canonical encoded S-expression with the secret key in KEYDATA and
1576 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1577 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1578 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1579 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1580 the pinentry callback. */
1581 static gpg_error_t
1582 do_writekey (app_t app, ctrl_t ctrl,
1583 const char *keyid, unsigned int flags,
1584 gpg_error_t (*pincb)(void*, const char *, char **),
1585 void *pincb_arg,
1586 const unsigned char *keydata, size_t keydatalen)
1588 gpg_error_t err;
1589 int force = (flags & 1);
1590 int keyno;
1591 const unsigned char *buf, *tok;
1592 size_t buflen, toklen;
1593 int depth, last_depth1, last_depth2;
1594 const unsigned char *rsa_n = NULL;
1595 const unsigned char *rsa_e = NULL;
1596 const unsigned char *rsa_p = NULL;
1597 const unsigned char *rsa_q = NULL;
1598 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
1599 unsigned int nbits;
1600 unsigned char *template = NULL;
1601 unsigned char *tp;
1602 size_t template_len;
1603 unsigned char fprbuf[20];
1604 u32 created_at = 0;
1606 if (!strcmp (keyid, "OPENPGP.1"))
1607 keyno = 0;
1608 else if (!strcmp (keyid, "OPENPGP.2"))
1609 keyno = 1;
1610 else if (!strcmp (keyid, "OPENPGP.3"))
1611 keyno = 2;
1612 else
1613 return gpg_error (GPG_ERR_INV_ID);
1615 err = does_key_exist (app, keyno, force);
1616 if (err)
1617 return err;
1621 Parse the S-expression
1623 buf = keydata;
1624 buflen = keydatalen;
1625 depth = 0;
1626 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1627 goto leave;
1628 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1629 goto leave;
1630 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
1632 if (!tok)
1634 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
1635 log_info ("protected-private-key passed to writekey\n");
1636 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
1637 log_info ("shadowed-private-key passed to writekey\n");
1638 err = gpg_error (GPG_ERR_BAD_SECKEY);
1639 goto leave;
1641 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1642 goto leave;
1643 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1644 goto leave;
1645 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
1647 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
1648 goto leave;
1650 last_depth1 = depth;
1651 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1652 && depth && depth >= last_depth1)
1654 if (tok)
1656 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1657 goto leave;
1659 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1660 goto leave;
1661 if (tok && toklen == 1)
1663 const unsigned char **mpi;
1664 size_t *mpi_len;
1666 switch (*tok)
1668 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
1669 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
1670 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
1671 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
1672 default: mpi = NULL; mpi_len = NULL; break;
1674 if (mpi && *mpi)
1676 err = gpg_error (GPG_ERR_DUP_VALUE);
1677 goto leave;
1679 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1680 goto leave;
1681 if (tok && mpi)
1683 /* Strip off leading zero bytes and save. */
1684 for (;toklen && !*tok; toklen--, tok++)
1686 *mpi = tok;
1687 *mpi_len = toklen;
1690 /* Skip until end of list. */
1691 last_depth2 = depth;
1692 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1693 && depth && depth >= last_depth2)
1695 if (err)
1696 goto leave;
1698 /* Parse other attributes. */
1699 last_depth1 = depth;
1700 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1701 && depth && depth >= last_depth1)
1703 if (tok)
1705 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1706 goto leave;
1708 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1709 goto leave;
1710 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
1712 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
1713 goto leave;
1714 if (tok)
1716 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
1717 tok++, toklen--)
1718 created_at = created_at*10 + (*tok - '0');
1721 /* Skip until end of list. */
1722 last_depth2 = depth;
1723 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1724 && depth && depth >= last_depth2)
1726 if (err)
1727 goto leave;
1731 /* Check that we have all parameters and that they match the card
1732 description. */
1733 if (!created_at)
1735 log_error (_("creation timestamp missing\n"));
1736 err = gpg_error (GPG_ERR_INV_VALUE);
1737 goto leave;
1739 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
1740 if (nbits != 1024)
1742 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1743 err = gpg_error (GPG_ERR_BAD_SECKEY);
1744 goto leave;
1746 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
1747 if (nbits < 2 || nbits > 32)
1749 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1750 32);
1751 err = gpg_error (GPG_ERR_BAD_SECKEY);
1752 goto leave;
1754 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
1755 if (nbits != 512)
1757 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1758 err = gpg_error (GPG_ERR_BAD_SECKEY);
1759 goto leave;
1761 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
1762 if (nbits != 512)
1764 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1765 err = gpg_error (GPG_ERR_BAD_SECKEY);
1766 goto leave;
1770 /* Build the private key template as described in section 4.3.3.6 of
1771 the OpenPGP card specs:
1772 0xC0 <length> public exponent
1773 0xC1 <length> prime p
1774 0xC2 <length> prime q
1776 assert (rsa_e_len <= 4);
1777 template_len = (1 + 1 + 4
1778 + 1 + 1 + rsa_p_len
1779 + 1 + 1 + rsa_q_len);
1780 template = tp = xtrymalloc_secure (template_len);
1781 if (!template)
1783 err = gpg_error_from_errno (errno);
1784 goto leave;
1786 *tp++ = 0xC0;
1787 *tp++ = 4;
1788 memcpy (tp, rsa_e, rsa_e_len);
1789 if (rsa_e_len < 4)
1791 /* Right justify E. */
1792 memmove (tp+4-rsa_e_len, tp, 4-rsa_e_len);
1793 memset (tp, 0, 4-rsa_e_len);
1795 tp += 4;
1797 *tp++ = 0xC1;
1798 *tp++ = rsa_p_len;
1799 memcpy (tp, rsa_p, rsa_p_len);
1800 tp += rsa_p_len;
1802 *tp++ = 0xC2;
1803 *tp++ = rsa_q_len;
1804 memcpy (tp, rsa_q, rsa_q_len);
1805 tp += rsa_q_len;
1807 assert (tp - template == template_len);
1810 /* Obviously we need to remove the cached public key. */
1811 xfree (app->app_local->pk[keyno].key);
1812 app->app_local->pk[keyno].key = NULL;
1813 app->app_local->pk[keyno].keylen = 0;
1814 app->app_local->pk[keyno].read_done = 0;
1816 /* Prepare for storing the key. */
1817 err = verify_chv3 (app, pincb, pincb_arg);
1818 if (err)
1819 goto leave;
1821 /* Store the key. */
1822 err = iso7816_put_data (app->slot,
1823 (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
1824 template, template_len);
1825 if (err)
1827 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
1828 goto leave;
1831 err = store_fpr (app->slot, keyno, created_at,
1832 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
1833 fprbuf, app->card_version);
1834 if (err)
1835 goto leave;
1838 leave:
1839 xfree (template);
1840 return err;
1844 /* Handle the GENKEY command. */
1845 static gpg_error_t
1846 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
1847 gpg_error_t (*pincb)(void*, const char *, char **),
1848 void *pincb_arg)
1850 int rc;
1851 char numbuf[30];
1852 unsigned char fprbuf[20];
1853 const unsigned char *keydata, *m, *e;
1854 unsigned char *buffer = NULL;
1855 size_t buflen, keydatalen, mlen, elen;
1856 time_t created_at;
1857 int keyno = atoi (keynostr);
1858 int force = (flags & 1);
1859 time_t start_at;
1861 if (keyno < 1 || keyno > 3)
1862 return gpg_error (GPG_ERR_INV_ID);
1863 keyno--;
1865 /* We flush the cache to increase the traffic before a key
1866 generation. This _might_ help a card to gather more entropy. */
1867 flush_cache (app);
1869 /* Obviously we need to remove the cached public key. */
1870 xfree (app->app_local->pk[keyno].key);
1871 app->app_local->pk[keyno].key = NULL;
1872 app->app_local->pk[keyno].keylen = 0;
1873 app->app_local->pk[keyno].read_done = 0;
1875 /* Check whether a key already exists. */
1876 rc = does_key_exist (app, keyno, force);
1877 if (rc)
1878 return rc;
1880 /* Prepare for key generation by verifying the ADmin PIN. */
1881 rc = verify_chv3 (app, pincb, pincb_arg);
1882 if (rc)
1883 goto leave;
1885 #if 1
1886 log_info (_("please wait while key is being generated ...\n"));
1887 start_at = time (NULL);
1888 rc = iso7816_generate_keypair
1889 #else
1890 #warning key generation temporary replaced by reading an existing key.
1891 rc = iso7816_read_public_key
1892 #endif
1893 (app->slot,
1894 keyno == 0? "\xB6" :
1895 keyno == 1? "\xB8" : "\xA4",
1897 &buffer, &buflen);
1898 if (rc)
1900 rc = gpg_error (GPG_ERR_CARD);
1901 log_error (_("generating key failed\n"));
1902 goto leave;
1904 log_info (_("key generation completed (%d seconds)\n"),
1905 (int)(time (NULL) - start_at));
1906 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1907 if (!keydata)
1909 rc = gpg_error (GPG_ERR_CARD);
1910 log_error (_("response does not contain the public key data\n"));
1911 goto leave;
1914 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1915 if (!m)
1917 rc = gpg_error (GPG_ERR_CARD);
1918 log_error (_("response does not contain the RSA modulus\n"));
1919 goto leave;
1921 /* log_printhex ("RSA n:", m, mlen); */
1922 send_key_data (ctrl, "n", m, mlen);
1924 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1925 if (!e)
1927 rc = gpg_error (GPG_ERR_CARD);
1928 log_error (_("response does not contain the RSA public exponent\n"));
1929 goto leave;
1931 /* log_printhex ("RSA e:", e, elen); */
1932 send_key_data (ctrl, "e", e, elen);
1934 created_at = gnupg_get_time ();
1935 sprintf (numbuf, "%lu", (unsigned long)created_at);
1936 send_status_info (ctrl, "KEY-CREATED-AT",
1937 numbuf, (size_t)strlen(numbuf), NULL, 0);
1939 rc = store_fpr (app->slot, keyno, (u32)created_at,
1940 m, mlen, e, elen, fprbuf, app->card_version);
1941 if (rc)
1942 goto leave;
1943 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1946 leave:
1947 xfree (buffer);
1948 return rc;
1952 static unsigned long
1953 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
1955 unsigned long ul;
1957 if (valuelen == 3 )
1958 ul = (value[0] << 16) | (value[1] << 8) | value[2];
1959 else
1961 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1962 ul = 0;
1964 return ul;
1967 static unsigned long
1968 get_sig_counter (app_t app)
1970 void *relptr;
1971 unsigned char *value;
1972 size_t valuelen;
1973 unsigned long ul;
1975 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
1976 if (!relptr)
1977 return 0;
1978 ul = convert_sig_counter_value (value, valuelen);
1979 xfree (relptr);
1980 return ul;
1983 static gpg_error_t
1984 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
1986 const unsigned char *fpr;
1987 unsigned char *buffer;
1988 size_t buflen, n;
1989 int rc, i;
1991 assert (keyno >= 1 && keyno <= 3);
1993 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
1994 if (rc)
1996 log_error (_("error reading application data\n"));
1997 return gpg_error (GPG_ERR_GENERAL);
1999 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2000 if (!fpr || n != 60)
2002 xfree (buffer);
2003 log_error (_("error reading fingerprint DO\n"));
2004 return gpg_error (GPG_ERR_GENERAL);
2006 fpr += (keyno-1)*20;
2007 for (i=0; i < 20; i++)
2008 if (sha1fpr[i] != fpr[i])
2010 xfree (buffer);
2011 return gpg_error (GPG_ERR_WRONG_SECKEY);
2013 xfree (buffer);
2014 return 0;
2018 /* If a fingerprint has been specified check it against the one on
2019 the card. This is allows for a meaningful error message in case
2020 the key on the card has been replaced but the shadow information
2021 known to gpg was not updated. If there is no fingerprint we
2022 assume that this is okay. */
2023 static gpg_error_t
2024 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2026 unsigned char tmp[20];
2027 const char *s;
2028 int n;
2030 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2032 if (n != 40)
2033 return gpg_error (GPG_ERR_INV_ID);
2034 else if (!*s)
2035 ; /* okay */
2036 else
2037 return gpg_error (GPG_ERR_INV_ID);
2039 for (s=fpr, n=0; n < 20; s += 2, n++)
2040 tmp[n] = xtoi_2 (s);
2041 return compare_fingerprint (app, keyno, tmp);
2046 /* Compute a digital signature on INDATA which is expected to be the
2047 raw message digest. For this application the KEYIDSTR consists of
2048 the serialnumber and the fingerprint delimited by a slash.
2050 Note that this fucntion may return the error code
2051 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2052 not match the one required for the requested action (e.g. the
2053 serial number does not match). */
2054 static gpg_error_t
2055 do_sign (app_t app, const char *keyidstr, int hashalgo,
2056 gpg_error_t (*pincb)(void*, const char *, char **),
2057 void *pincb_arg,
2058 const void *indata, size_t indatalen,
2059 unsigned char **outdata, size_t *outdatalen )
2061 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2062 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2063 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2064 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2065 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2066 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2067 int rc;
2068 unsigned char data[35];
2069 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2070 const char *s;
2071 int n;
2072 const char *fpr = NULL;
2073 unsigned long sigcount;
2075 if (!keyidstr || !*keyidstr)
2076 return gpg_error (GPG_ERR_INV_VALUE);
2077 if (indatalen == 20)
2079 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
2080 && !memcmp (indata, sha1_prefix, 15))
2082 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
2083 && !memcmp (indata, rmd160_prefix, 15))
2085 else
2087 log_error(_("card does not support digest algorithm %s\n"),
2088 digest_algo_to_string(hashalgo));
2089 return gpg_error (GPG_ERR_INV_VALUE);
2092 /* Check whether an OpenPGP card of any version has been requested. */
2093 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2094 return gpg_error (GPG_ERR_INV_ID);
2096 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2098 if (n != 32)
2099 return gpg_error (GPG_ERR_INV_ID);
2100 else if (!*s)
2101 ; /* no fingerprint given: we allow this for now. */
2102 else if (*s == '/')
2103 fpr = s + 1;
2104 else
2105 return gpg_error (GPG_ERR_INV_ID);
2107 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2108 tmp_sn[n] = xtoi_2 (s);
2110 if (app->serialnolen != 16)
2111 return gpg_error (GPG_ERR_INV_CARD);
2112 if (memcmp (app->serialno, tmp_sn, 16))
2113 return gpg_error (GPG_ERR_WRONG_CARD);
2115 /* If a fingerprint has been specified check it against the one on
2116 the card. This is allows for a meaningful error message in case
2117 the key on the card has been replaced but the shadow information
2118 known to gpg was not updated. If there is no fingerprint, gpg
2119 will detect a bogus signature anyway due to the
2120 verify-after-signing feature. */
2121 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2122 if (rc)
2123 return rc;
2125 if (hashalgo == GCRY_MD_SHA1)
2126 memcpy (data, sha1_prefix, 15);
2127 else if (hashalgo == GCRY_MD_RMD160)
2128 memcpy (data, rmd160_prefix, 15);
2129 else
2130 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2131 memcpy (data+15, indata, indatalen);
2133 sigcount = get_sig_counter (app);
2134 log_info (_("signatures created so far: %lu\n"), sigcount);
2136 if (!app->did_chv1 || app->force_chv1 )
2138 char *pinvalue;
2141 char *prompt;
2142 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
2144 prompt = malloc (strlen (PROMPTSTRING) + 50);
2145 if (!prompt)
2146 return gpg_error_from_errno (errno);
2147 sprintf (prompt, PROMPTSTRING, sigcount);
2148 rc = pincb (pincb_arg, prompt, &pinvalue);
2149 free (prompt);
2150 #undef PROMPTSTRING
2152 if (rc)
2154 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
2155 return rc;
2158 if (strlen (pinvalue) < 6)
2160 log_error (_("PIN for CHV%d is too short;"
2161 " minimum length is %d\n"), 1, 6);
2162 xfree (pinvalue);
2163 return gpg_error (GPG_ERR_BAD_PIN);
2166 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
2167 if (rc)
2169 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
2170 xfree (pinvalue);
2171 flush_cache_after_error (app);
2172 return rc;
2174 app->did_chv1 = 1;
2175 if (!app->did_chv2)
2177 /* We should also verify CHV2. */
2178 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2179 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2180 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2181 if (rc)
2183 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2184 xfree (pinvalue);
2185 flush_cache_after_error (app);
2186 return rc;
2188 app->did_chv2 = 1;
2190 xfree (pinvalue);
2193 rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
2194 return rc;
2197 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2198 on INDATA which is expected to be the raw message digest. For this
2199 application the KEYIDSTR consists of the serialnumber and the
2200 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2201 be given.
2203 Note that this fucntion may return the error code
2204 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2205 not match the one required for the requested action (e.g. the
2206 serial number does not match). */
2207 static gpg_error_t
2208 do_auth (app_t app, const char *keyidstr,
2209 gpg_error_t (*pincb)(void*, const char *, char **),
2210 void *pincb_arg,
2211 const void *indata, size_t indatalen,
2212 unsigned char **outdata, size_t *outdatalen )
2214 int rc;
2215 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2216 const char *s;
2217 int n;
2218 const char *fpr = NULL;
2220 if (!keyidstr || !*keyidstr)
2221 return gpg_error (GPG_ERR_INV_VALUE);
2222 if (indatalen > 50) /* For a 1024 bit key. */
2223 return gpg_error (GPG_ERR_INV_VALUE);
2225 /* Check whether an OpenPGP card of any version has been requested. */
2226 if (!strcmp (keyidstr, "OPENPGP.3"))
2228 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2229 return gpg_error (GPG_ERR_INV_ID);
2230 else
2232 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2234 if (n != 32)
2235 return gpg_error (GPG_ERR_INV_ID);
2236 else if (!*s)
2237 ; /* no fingerprint given: we allow this for now. */
2238 else if (*s == '/')
2239 fpr = s + 1;
2240 else
2241 return gpg_error (GPG_ERR_INV_ID);
2243 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2244 tmp_sn[n] = xtoi_2 (s);
2246 if (app->serialnolen != 16)
2247 return gpg_error (GPG_ERR_INV_CARD);
2248 if (memcmp (app->serialno, tmp_sn, 16))
2249 return gpg_error (GPG_ERR_WRONG_CARD);
2252 /* If a fingerprint has been specified check it against the one on
2253 the card. This is allows for a meaningful error message in case
2254 the key on the card has been replaced but the shadow information
2255 known to gpg was not updated. If there is no fingerprint, gpg
2256 will detect a bogus signature anyway due to the
2257 verify-after-signing feature. */
2258 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
2259 if (rc)
2260 return rc;
2262 rc = verify_chv2 (app, pincb, pincb_arg);
2263 if (!rc)
2264 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
2265 outdata, outdatalen);
2266 return rc;
2270 static gpg_error_t
2271 do_decipher (app_t app, const char *keyidstr,
2272 gpg_error_t (*pincb)(void*, const char *, char **),
2273 void *pincb_arg,
2274 const void *indata, size_t indatalen,
2275 unsigned char **outdata, size_t *outdatalen )
2277 int rc;
2278 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2279 const char *s;
2280 int n;
2281 const char *fpr = NULL;
2283 if (!keyidstr || !*keyidstr || !indatalen)
2284 return gpg_error (GPG_ERR_INV_VALUE);
2286 /* Check whether an OpenPGP card of any version has been requested. */
2287 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2288 return gpg_error (GPG_ERR_INV_ID);
2290 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2292 if (n != 32)
2293 return gpg_error (GPG_ERR_INV_ID);
2294 else if (!*s)
2295 ; /* no fingerprint given: we allow this for now. */
2296 else if (*s == '/')
2297 fpr = s + 1;
2298 else
2299 return gpg_error (GPG_ERR_INV_ID);
2301 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2302 tmp_sn[n] = xtoi_2 (s);
2304 if (app->serialnolen != 16)
2305 return gpg_error (GPG_ERR_INV_CARD);
2306 if (memcmp (app->serialno, tmp_sn, 16))
2307 return gpg_error (GPG_ERR_WRONG_CARD);
2309 /* If a fingerprint has been specified check it against the one on
2310 the card. This is allows for a meaningful error message in case
2311 the key on the card has been replaced but the shadow information
2312 known to gpg was not updated. If there is no fingerprint, the
2313 decryption will won't produce the right plaintext anyway. */
2314 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
2315 if (rc)
2316 return rc;
2318 rc = verify_chv2 (app, pincb, pincb_arg);
2319 if (!rc)
2320 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
2321 outdata, outdatalen);
2322 return rc;
2326 /* Perform a simple verify operation for CHV1 and CHV2, so that
2327 further operations won't ask for CHV2 and it is possible to do a
2328 cheap check on the PIN: If there is something wrong with the PIN
2329 entry system, only the regular CHV will get blocked and not the
2330 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2331 optional fingerprint part will be ignored.
2333 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2334 the "[CHV3]" being a literal string: The Admin Pin is checked if
2335 and only if the retry counter is still at 3. */
2336 static gpg_error_t
2337 do_check_pin (app_t app, const char *keyidstr,
2338 gpg_error_t (*pincb)(void*, const char *, char **),
2339 void *pincb_arg)
2341 unsigned char tmp_sn[20];
2342 const char *s;
2343 int n;
2344 int admin_pin = 0;
2346 if (!keyidstr || !*keyidstr)
2347 return gpg_error (GPG_ERR_INV_VALUE);
2349 /* Check whether an OpenPGP card of any version has been requested. */
2350 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2351 return gpg_error (GPG_ERR_INV_ID);
2353 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2355 if (n != 32)
2356 return gpg_error (GPG_ERR_INV_ID);
2357 else if (!*s)
2358 ; /* No fingerprint given: we allow this for now. */
2359 else if (*s == '/')
2360 ; /* We ignore a fingerprint. */
2361 else if (!strcmp (s, "[CHV3]") )
2362 admin_pin = 1;
2363 else
2364 return gpg_error (GPG_ERR_INV_ID);
2366 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2367 tmp_sn[n] = xtoi_2 (s);
2369 if (app->serialnolen != 16)
2370 return gpg_error (GPG_ERR_INV_CARD);
2371 if (memcmp (app->serialno, tmp_sn, 16))
2372 return gpg_error (GPG_ERR_WRONG_CARD);
2374 /* Yes, there is a race conditions: The user might pull the card
2375 right here and we won't notice that. However this is not a
2376 problem and the check above is merely for a graceful failure
2377 between operations. */
2379 if (admin_pin)
2381 void *relptr;
2382 unsigned char *value;
2383 size_t valuelen;
2384 int count;
2386 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2387 if (!relptr || valuelen < 7)
2389 log_error (_("error retrieving CHV status from card\n"));
2390 xfree (relptr);
2391 return gpg_error (GPG_ERR_CARD);
2393 count = value[6];
2394 xfree (relptr);
2396 if (!count)
2398 log_info (_("card is permanently locked!\n"));
2399 return gpg_error (GPG_ERR_BAD_PIN);
2401 else if (value[6] < 3)
2403 log_info (_("verification of Admin PIN is currently prohibited "
2404 "through this command\n"));
2405 return gpg_error (GPG_ERR_GENERAL);
2408 app->did_chv3 = 0; /* Force verification. */
2409 return verify_chv3 (app, pincb, pincb_arg);
2411 else
2412 return verify_chv2 (app, pincb, pincb_arg);
2418 /* Select the OpenPGP application on the card in SLOT. This function
2419 must be used before any other OpenPGP application functions. */
2420 gpg_error_t
2421 app_select_openpgp (app_t app)
2423 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2424 int slot = app->slot;
2425 int rc;
2426 unsigned char *buffer;
2427 size_t buflen;
2428 void *relptr;
2430 rc = iso7816_select_application (slot, aid, sizeof aid);
2431 if (!rc)
2433 unsigned int manufacturer;
2435 app->apptype = "OPENPGP";
2437 app->did_chv1 = 0;
2438 app->did_chv2 = 0;
2439 app->did_chv3 = 0;
2440 app->app_local = NULL;
2442 /* The OpenPGP card returns the serial number as part of the
2443 AID; because we prefer to use OpenPGP serial numbers, we
2444 replace a possibly already set one from a EF.GDO with this
2445 one. Note, that for current OpenPGP cards, no EF.GDO exists
2446 and thus it won't matter at all. */
2447 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
2448 if (rc)
2449 goto leave;
2450 if (opt.verbose)
2452 log_info ("AID: ");
2453 log_printhex ("", buffer, buflen);
2456 app->card_version = buffer[6] << 8;
2457 app->card_version |= buffer[7];
2458 manufacturer = (buffer[8]<<8 | buffer[9]);
2460 xfree (app->serialno);
2461 app->serialno = buffer;
2462 app->serialnolen = buflen;
2463 buffer = NULL;
2464 app->app_local = xtrycalloc (1, sizeof *app->app_local);
2465 if (!app->app_local)
2467 rc = gpg_error (gpg_err_code_from_errno (errno));
2468 goto leave;
2471 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
2472 if (!relptr)
2474 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2475 "CHV Status Bytes");
2476 goto leave;
2478 app->force_chv1 = (buflen && *buffer == 0);
2479 xfree (relptr);
2481 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
2482 if (!relptr)
2484 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2485 "Extended Capability Flags" );
2486 goto leave;
2488 if (buflen)
2490 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
2491 app->app_local->extcap.key_import = !!(*buffer & 0x20);
2492 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
2493 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
2495 xfree (relptr);
2497 /* Some of the first cards accidently don't set the
2498 CHANGE_FORCE_CHV bit but allow it anyway. */
2499 if (app->card_version <= 0x0100 && manufacturer == 1)
2500 app->app_local->extcap.change_force_chv = 1;
2502 parse_login_data (app);
2504 if (opt.verbose > 1)
2505 dump_all_do (slot);
2507 app->fnc.deinit = do_deinit;
2508 app->fnc.learn_status = do_learn_status;
2509 app->fnc.readkey = do_readkey;
2510 app->fnc.getattr = do_getattr;
2511 app->fnc.setattr = do_setattr;
2512 app->fnc.writekey = do_writekey;
2513 app->fnc.genkey = do_genkey;
2514 app->fnc.sign = do_sign;
2515 app->fnc.auth = do_auth;
2516 app->fnc.decipher = do_decipher;
2517 app->fnc.change_pin = do_change_pin;
2518 app->fnc.check_pin = do_check_pin;
2521 leave:
2522 if (rc)
2523 do_deinit (app);
2524 return rc;