2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / app-openpgp.c
blobe26a31e8d60e7d8f8a5ab4b1ed45178899d1739b
1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007 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 3 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, see <http://www.gnu.org/licenses/>.
19 * $Id$
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <time.h>
30 #if GNUPG_MAJOR_VERSION == 1
31 /* This is used with GnuPG version < 1.9. The code has been source
32 copied from the current GnuPG >= 1.9 and is maintained over
33 there. */
34 #include "options.h"
35 #include "errors.h"
36 #include "memory.h"
37 #include "util.h"
38 #include "cardglue.h"
39 #else /* GNUPG_MAJOR_VERSION != 1 */
40 #include "scdaemon.h"
41 #endif /* GNUPG_MAJOR_VERSION != 1 */
43 #include "i18n.h"
44 #include "iso7816.h"
45 #include "app-common.h"
46 #include "tlv.h"
49 static struct {
50 int tag;
51 int constructed;
52 int get_from; /* Constructed DO with this DO or 0 for direct access. */
53 int binary;
54 int dont_cache;
55 int flush_on_error;
56 int get_immediate_in_v11; /* Enable a hack to bypass the cache of
57 this data object if it is used in 1.1
58 and later versions of the card. This
59 does not work with composite DO and is
60 currently only useful for the CHV
61 status bytes. */
62 char *desc;
63 } data_objects[] = {
64 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
65 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
66 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
67 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
68 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
69 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
70 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
71 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
72 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
73 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
74 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
75 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
76 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
77 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
78 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
79 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
80 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
81 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
82 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
83 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
84 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
85 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
86 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
87 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
88 { 0 }
92 /* One cache item for DOs. */
93 struct cache_s {
94 struct cache_s *next;
95 int tag;
96 size_t length;
97 unsigned char data[1];
101 /* Object with application (i.e. OpenPGP card) specific data. */
102 struct app_local_s {
103 /* A linked list with cached DOs. */
104 struct cache_s *cache;
106 /* Keep track of the public keys. */
107 struct
109 int read_done; /* True if we have at least tried to read them. */
110 unsigned char *key; /* This is a malloced buffer with a canonical
111 encoded S-expression encoding a public
112 key. Might be NULL if key is not
113 available. */
114 size_t keylen; /* The length of the above S-expression. This
115 is usullay only required for cross checks
116 because the length of an S-expression is
117 implicitly available. */
118 } pk[3];
120 /* Keep track of card capabilities. */
121 struct
123 unsigned int get_challenge:1;
124 unsigned int key_import:1;
125 unsigned int change_force_chv:1;
126 unsigned int private_dos:1;
127 } extcap;
129 /* Flags used to control the application. */
130 struct
132 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
133 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
134 } flags;
139 /***** Local prototypes *****/
140 static unsigned long convert_sig_counter_value (const unsigned char *value,
141 size_t valuelen);
142 static unsigned long get_sig_counter (app_t app);
143 static gpg_error_t do_auth (app_t app, const char *keyidstr,
144 gpg_error_t (*pincb)(void*, const char *, char **),
145 void *pincb_arg,
146 const void *indata, size_t indatalen,
147 unsigned char **outdata, size_t *outdatalen);
153 /* Deconstructor. */
154 static void
155 do_deinit (app_t app)
157 if (app && app->app_local)
159 struct cache_s *c, *c2;
160 int i;
162 for (c = app->app_local->cache; c; c = c2)
164 c2 = c->next;
165 xfree (c);
168 for (i=0; i < DIM (app->app_local->pk); i++)
170 xfree (app->app_local->pk[i].key);
171 app->app_local->pk[i].read_done = 0;
173 xfree (app->app_local);
174 app->app_local = NULL;
179 /* Wrapper around iso7816_get_data which first tries to get the data
180 from the cache. With GET_IMMEDIATE passed as true, the cache is
181 bypassed. */
182 static gpg_error_t
183 get_cached_data (app_t app, int tag,
184 unsigned char **result, size_t *resultlen,
185 int get_immediate)
187 gpg_error_t err;
188 int i;
189 unsigned char *p;
190 size_t len;
191 struct cache_s *c;
193 *result = NULL;
194 *resultlen = 0;
196 if (!get_immediate)
198 for (c=app->app_local->cache; c; c = c->next)
199 if (c->tag == tag)
201 if(c->length)
203 p = xtrymalloc (c->length);
204 if (!p)
205 return gpg_error (gpg_err_code_from_errno (errno));
206 memcpy (p, c->data, c->length);
207 *result = p;
210 *resultlen = c->length;
212 return 0;
216 err = iso7816_get_data (app->slot, tag, &p, &len);
217 if (err)
218 return err;
219 *result = p;
220 *resultlen = len;
222 /* Check whether we should cache this object. */
223 if (get_immediate)
224 return 0;
226 for (i=0; data_objects[i].tag; i++)
227 if (data_objects[i].tag == tag)
229 if (data_objects[i].dont_cache)
230 return 0;
231 break;
234 /* Okay, cache it. */
235 for (c=app->app_local->cache; c; c = c->next)
236 assert (c->tag != tag);
238 c = xtrymalloc (sizeof *c + len);
239 if (c)
241 memcpy (c->data, p, len);
242 c->length = len;
243 c->tag = tag;
244 c->next = app->app_local->cache;
245 app->app_local->cache = c;
248 return 0;
251 /* Remove DO at TAG from the cache. */
252 static void
253 flush_cache_item (app_t app, int tag)
255 struct cache_s *c, *cprev;
256 int i;
258 if (!app->app_local)
259 return;
261 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
262 if (c->tag == tag)
264 if (cprev)
265 cprev->next = c->next;
266 else
267 app->app_local->cache = c->next;
268 xfree (c);
270 for (c=app->app_local->cache; c ; c = c->next)
272 assert (c->tag != tag); /* Oops: duplicated entry. */
274 return;
277 /* Try again if we have an outer tag. */
278 for (i=0; data_objects[i].tag; i++)
279 if (data_objects[i].tag == tag && data_objects[i].get_from
280 && data_objects[i].get_from != tag)
281 flush_cache_item (app, data_objects[i].get_from);
284 /* Flush all entries from the cache which might be out of sync after
285 an error. */
286 static void
287 flush_cache_after_error (app_t app)
289 int i;
291 for (i=0; data_objects[i].tag; i++)
292 if (data_objects[i].flush_on_error)
293 flush_cache_item (app, data_objects[i].tag);
297 /* Flush the entire cache. */
298 static void
299 flush_cache (app_t app)
301 if (app && app->app_local)
303 struct cache_s *c, *c2;
305 for (c = app->app_local->cache; c; c = c2)
307 c2 = c->next;
308 xfree (c);
310 app->app_local->cache = NULL;
315 /* Get the DO identified by TAG from the card in SLOT and return a
316 buffer with its content in RESULT and NBYTES. The return value is
317 NULL if not found or a pointer which must be used to release the
318 buffer holding value. */
319 static void *
320 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
321 int *r_rc)
323 int rc, i;
324 unsigned char *buffer;
325 size_t buflen;
326 unsigned char *value;
327 size_t valuelen;
328 int dummyrc;
330 if (!r_rc)
331 r_rc = &dummyrc;
333 *result = NULL;
334 *nbytes = 0;
335 *r_rc = 0;
336 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
339 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
341 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
342 if (rc)
344 *r_rc = rc;
345 return NULL;
347 *result = buffer;
348 *nbytes = buflen;
349 return buffer;
352 value = NULL;
353 rc = -1;
354 if (data_objects[i].tag && data_objects[i].get_from)
356 rc = get_cached_data (app, data_objects[i].get_from,
357 &buffer, &buflen,
358 (data_objects[i].dont_cache
359 || data_objects[i].get_immediate_in_v11));
360 if (!rc)
362 const unsigned char *s;
364 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
365 if (!s)
366 value = NULL; /* not found */
367 else if (valuelen > buflen - (s - buffer))
369 log_error ("warning: constructed DO too short\n");
370 value = NULL;
371 xfree (buffer); buffer = NULL;
373 else
374 value = buffer + (s - buffer);
378 if (!value) /* Not in a constructed DO, try simple. */
380 rc = get_cached_data (app, tag, &buffer, &buflen,
381 (data_objects[i].dont_cache
382 || data_objects[i].get_immediate_in_v11));
383 if (!rc)
385 value = buffer;
386 valuelen = buflen;
390 if (!rc)
392 *nbytes = valuelen;
393 *result = value;
394 return buffer;
396 *r_rc = rc;
397 return NULL;
401 static void
402 dump_all_do (int slot)
404 int rc, i, j;
405 unsigned char *buffer;
406 size_t buflen;
408 for (i=0; data_objects[i].tag; i++)
410 if (data_objects[i].get_from)
411 continue;
413 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
414 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
416 else if (rc)
417 log_info ("DO `%s' not available: %s\n",
418 data_objects[i].desc, gpg_strerror (rc));
419 else
421 if (data_objects[i].binary)
423 log_info ("DO `%s': ", data_objects[i].desc);
424 log_printhex ("", buffer, buflen);
426 else
427 log_info ("DO `%s': `%.*s'\n",
428 data_objects[i].desc,
429 (int)buflen, buffer); /* FIXME: sanitize */
431 if (data_objects[i].constructed)
433 for (j=0; data_objects[j].tag; j++)
435 const unsigned char *value;
436 size_t valuelen;
438 if (j==i || data_objects[i].tag != data_objects[j].get_from)
439 continue;
440 value = find_tlv_unchecked (buffer, buflen,
441 data_objects[j].tag, &valuelen);
442 if (!value)
443 ; /* not found */
444 else if (valuelen > buflen - (value - buffer))
445 log_error ("warning: constructed DO too short\n");
446 else
448 if (data_objects[j].binary)
450 log_info ("DO `%s': ", data_objects[j].desc);
451 log_printhex ("", value, valuelen);
453 else
454 log_info ("DO `%s': `%.*s'\n",
455 data_objects[j].desc,
456 (int)valuelen, value); /* FIXME: sanitize */
461 xfree (buffer); buffer = NULL;
466 /* Count the number of bits, assuming the A represents an unsigned big
467 integer of length LEN bytes. */
468 static unsigned int
469 count_bits (const unsigned char *a, size_t len)
471 unsigned int n = len * 8;
472 int i;
474 for (; len && !*a; len--, a++, n -=8)
476 if (len)
478 for (i=7; i && !(*a & (1<<i)); i--)
479 n--;
481 return n;
484 /* GnuPG makes special use of the login-data DO, this fucntion parses
485 the login data to store the flags for later use. It may be called
486 at any time and should be called after changing the login-data DO.
488 Everything up to a LF is considered a mailbox or account name. If
489 the first LF is followed by DC4 (0x14) control sequence are
490 expected up to the next LF. Control sequences are separated by FS
491 (0x18) and consist of key=value pairs. There is one key defined:
493 F=<flags>
495 Were FLAGS is a plain hexadecimal number representing flag values.
496 The lsb is here the rightmost bit. Defined flags bits are:
498 Bit 0 = CHV1 and CHV2 are not syncronized
499 Bit 1 = CHV2 has been been set to the default PIN of "123456"
500 (this implies that bit 0 is also set).
503 static void
504 parse_login_data (app_t app)
506 unsigned char *buffer, *p;
507 size_t buflen, len;
508 void *relptr;
510 /* Set defaults. */
511 app->app_local->flags.no_sync = 0;
512 app->app_local->flags.def_chv2 = 0;
514 /* Read the DO. */
515 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
516 if (!relptr)
517 return; /* Ooops. */
518 for (; buflen; buflen--, buffer++)
519 if (*buffer == '\n')
520 break;
521 if (buflen < 2 || buffer[1] != '\x14')
522 return; /* No control sequences. */
523 buflen--;
524 buffer++;
527 buflen--;
528 buffer++;
529 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
531 /* Flags control sequence found. */
532 int lastdig = 0;
534 /* For now we are only interested in the last digit, so skip
535 any leading digits but bail out on invalid characters. */
536 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
537 lastdig = xtoi_1 (p);
538 if (len && !(*p == '\n' || *p == '\x18'))
539 goto next; /* Invalid characters in field. */
540 app->app_local->flags.no_sync = !!(lastdig & 1);
541 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
543 next:
544 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
545 if (*buffer == '\n')
546 buflen = 1;
548 while (buflen);
550 xfree (relptr);
553 /* Note, that FPR must be at least 20 bytes. */
554 static gpg_error_t
555 store_fpr (int slot, int keynumber, u32 timestamp,
556 const unsigned char *m, size_t mlen,
557 const unsigned char *e, size_t elen,
558 unsigned char *fpr, unsigned int card_version)
560 unsigned int n, nbits;
561 unsigned char *buffer, *p;
562 int rc;
564 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
566 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
569 n = 6 + 2 + mlen + 2 + elen;
570 p = buffer = xtrymalloc (3 + n);
571 if (!buffer)
572 return gpg_error_from_syserror ();
574 *p++ = 0x99; /* ctb */
575 *p++ = n >> 8; /* 2 byte length header */
576 *p++ = n;
577 *p++ = 4; /* key packet version */
578 *p++ = timestamp >> 24;
579 *p++ = timestamp >> 16;
580 *p++ = timestamp >> 8;
581 *p++ = timestamp;
582 *p++ = 1; /* RSA */
583 nbits = count_bits (m, mlen);
584 *p++ = nbits >> 8;
585 *p++ = nbits;
586 memcpy (p, m, mlen); p += mlen;
587 nbits = count_bits (e, elen);
588 *p++ = nbits >> 8;
589 *p++ = nbits;
590 memcpy (p, e, elen); p += elen;
592 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
594 xfree (buffer);
596 rc = iso7816_put_data (slot, (card_version > 0x0007? 0xC7 : 0xC6)
597 + keynumber, fpr, 20);
598 if (rc)
599 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
601 if (!rc && card_version > 0x0100)
603 unsigned char buf[4];
605 buf[0] = timestamp >> 24;
606 buf[1] = timestamp >> 16;
607 buf[2] = timestamp >> 8;
608 buf[3] = timestamp;
610 rc = iso7816_put_data (slot, 0xCE + keynumber, buf, 4);
611 if (rc)
612 log_error (_("failed to store the creation date: %s\n"),
613 gpg_strerror (rc));
616 return rc;
620 static void
621 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
622 int number, const unsigned char *fpr)
624 int i;
625 char buf[41];
626 char numbuf[25];
628 for (i=0; i < 20 && !fpr[i]; i++)
630 if (i==20)
631 return; /* All zero. */
632 for (i=0; i< 20; i++)
633 sprintf (buf+2*i, "%02X", fpr[i]);
634 if (number == -1)
635 *numbuf = 0; /* Don't print the key number */
636 else
637 sprintf (numbuf, "%d", number);
638 send_status_info (ctrl, keyword,
639 numbuf, (size_t)strlen(numbuf),
640 buf, (size_t)strlen (buf), NULL, 0);
643 static void
644 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
645 int number, const unsigned char *stamp)
647 char numbuf1[50], numbuf2[50];
648 unsigned long value;
650 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
651 if (!value)
652 return;
653 sprintf (numbuf1, "%d", number);
654 sprintf (numbuf2, "%lu", value);
655 send_status_info (ctrl, keyword,
656 numbuf1, (size_t)strlen(numbuf1),
657 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
660 static void
661 send_key_data (ctrl_t ctrl, const char *name,
662 const unsigned char *a, size_t alen)
664 char *p, *buf = xmalloc (alen*2+1);
666 for (p=buf; alen; a++, alen--, p += 2)
667 sprintf (p, "%02X", *a);
669 send_status_info (ctrl, "KEY-DATA",
670 name, (size_t)strlen(name),
671 buf, (size_t)strlen (buf),
672 NULL, 0);
673 xfree (buf);
676 /* Implement the GETATTR command. This is similar to the LEARN
677 command but returns just one value via the status interface. */
678 static gpg_error_t
679 do_getattr (app_t app, ctrl_t ctrl, const char *name)
681 static struct {
682 const char *name;
683 int tag;
684 int special;
685 } table[] = {
686 { "DISP-NAME", 0x005B },
687 { "LOGIN-DATA", 0x005E },
688 { "DISP-LANG", 0x5F2D },
689 { "DISP-SEX", 0x5F35 },
690 { "PUBKEY-URL", 0x5F50 },
691 { "KEY-FPR", 0x00C5, 3 },
692 { "KEY-TIME", 0x00CD, 4 },
693 { "CA-FPR", 0x00C6, 3 },
694 { "CHV-STATUS", 0x00C4, 1 },
695 { "SIG-COUNTER", 0x0093, 2 },
696 { "SERIALNO", 0x004F, -1 },
697 { "AID", 0x004F },
698 { "EXTCAP", 0x0000, -2 },
699 { "PRIVATE-DO-1", 0x0101 },
700 { "PRIVATE-DO-2", 0x0102 },
701 { "PRIVATE-DO-3", 0x0103 },
702 { "PRIVATE-DO-4", 0x0104 },
703 { "$AUTHKEYID", 0x0000, -3 },
704 { "$DISPSERIALNO",0x0000, -4 },
705 { NULL, 0 }
707 int idx, i, rc;
708 void *relptr;
709 unsigned char *value;
710 size_t valuelen;
712 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
714 if (!table[idx].name)
715 return gpg_error (GPG_ERR_INV_NAME);
717 if (table[idx].special == -1)
719 /* The serial number is very special. We could have used the
720 AID DO to retrieve it, but we have it already in the app
721 context and the stamp argument is required anyway which we
722 can't by other means. The AID DO is available anyway but not
723 hex formatted. */
724 char *serial;
725 time_t stamp;
726 char tmp[50];
728 if (!app_get_serial_and_stamp (app, &serial, &stamp))
730 sprintf (tmp, "%lu", (unsigned long)stamp);
731 send_status_info (ctrl, "SERIALNO",
732 serial, strlen (serial),
733 tmp, strlen (tmp),
734 NULL, 0);
735 xfree (serial);
737 return 0;
739 if (table[idx].special == -2)
741 char tmp[50];
743 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d",
744 app->app_local->extcap.get_challenge,
745 app->app_local->extcap.key_import,
746 app->app_local->extcap.change_force_chv,
747 app->app_local->extcap.private_dos);
748 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
749 return 0;
751 if (table[idx].special == -3)
753 char const tmp[] = "OPENPGP.3";
754 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
755 return 0;
757 if (table[idx].special == -4)
759 char *serial;
760 time_t stamp;
762 if (!app_get_serial_and_stamp (app, &serial, &stamp))
764 if (strlen (serial) > 16+12)
766 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
767 xfree (serial);
768 return 0;
770 xfree (serial);
772 return gpg_error (GPG_ERR_INV_NAME);
775 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
776 if (relptr)
778 if (table[idx].special == 1)
780 char numbuf[7*23];
782 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
783 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
784 send_status_info (ctrl, table[idx].name,
785 numbuf, strlen (numbuf), NULL, 0);
787 else if (table[idx].special == 2)
789 char numbuf[50];
791 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
792 send_status_info (ctrl, table[idx].name,
793 numbuf, strlen (numbuf), NULL, 0);
795 else if (table[idx].special == 3)
797 if (valuelen >= 60)
798 for (i=0; i < 3; i++)
799 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
801 else if (table[idx].special == 4)
803 if (valuelen >= 12)
804 for (i=0; i < 3; i++)
805 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
807 else
808 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
810 xfree (relptr);
812 return rc;
815 /* Retrieve the fingerprint from the card inserted in SLOT and write
816 the according hex representation to FPR. Caller must have provide
817 a buffer at FPR of least 41 bytes. Returns 0 on success or an
818 error code. */
819 #if GNUPG_MAJOR_VERSION > 1
820 static gpg_error_t
821 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
823 gpg_error_t err = 0;
824 void *relptr;
825 unsigned char *value;
826 size_t valuelen;
827 int i;
829 assert (keyno >=0 && keyno <= 2);
831 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
832 if (relptr && valuelen >= 60)
834 for (i = 0; i < 20; i++)
835 sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
837 else
838 err = gpg_error (GPG_ERR_NOT_FOUND);
839 xfree (relptr);
840 return err;
842 #endif /*GNUPG_MAJOR_VERSION > 1*/
845 /* Retrieve the public key material for the RSA key, whose fingerprint
846 is FPR, from gpg output, which can be read through the stream FP.
847 The RSA modulus will be stored at the address of M and MLEN, the
848 public exponent at E and ELEN. Returns zero on success, an error
849 code on failure. Caller must release the allocated buffers at M
850 and E if the function returns success. */
851 #if GNUPG_MAJOR_VERSION > 1
852 static gpg_error_t
853 retrieve_key_material (FILE *fp, const char *hexkeyid,
854 const unsigned char **m, size_t *mlen,
855 const unsigned char **e, size_t *elen)
857 gcry_error_t err = 0;
858 char *line = NULL; /* read_line() buffer. */
859 size_t line_size = 0; /* Helper for for read_line. */
860 int found_key = 0; /* Helper to find a matching key. */
861 unsigned char *m_new = NULL;
862 unsigned char *e_new = NULL;
863 size_t m_new_n = 0;
864 size_t e_new_n = 0;
866 /* Loop over all records until we have found the subkey
867 corresponsing to the fingerprint. Inm general the first record
868 should be the pub record, but we don't rely on that. Given that
869 we only need to look at one key, it is sufficient to compare the
870 keyid so that we don't need to look at "fpr" records. */
871 for (;;)
873 char *p;
874 char *fields[6];
875 int nfields;
876 size_t max_length;
877 gcry_mpi_t mpi;
878 int i;
880 max_length = 4096;
881 i = read_line (fp, &line, &line_size, &max_length);
882 if (!i)
883 break; /* EOF. */
884 if (i < 0)
886 err = gpg_error_from_syserror ();
887 goto leave; /* Error. */
889 if (!max_length)
891 err = gpg_error (GPG_ERR_TRUNCATED);
892 goto leave; /* Line truncated - we better stop processing. */
895 /* Parse the line into fields. */
896 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
898 fields[nfields] = p;
899 p = strchr (p, ':');
900 if (p)
901 *(p++) = 0;
903 if (!nfields)
904 continue; /* No fields at all - skip line. */
906 if (!found_key)
908 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
909 && nfields > 4 && !strcmp (fields[4], hexkeyid))
910 found_key = 1;
911 continue;
914 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
915 break; /* Next key - stop. */
917 if ( strcmp (fields[0], "pkd") )
918 continue; /* Not a key data record. */
919 i = 0; /* Avoid erroneous compiler warning. */
920 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
921 || (!i && m_new) || (i && e_new))
923 err = gpg_error (GPG_ERR_GENERAL);
924 goto leave; /* Error: Invalid key data record or not an RSA key. */
927 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
928 if (err)
929 mpi = NULL;
930 else if (!i)
931 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
932 else
933 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
934 gcry_mpi_release (mpi);
935 if (err)
936 goto leave;
939 if (m_new && e_new)
941 *m = m_new;
942 *mlen = m_new_n;
943 m_new = NULL;
944 *e = e_new;
945 *elen = e_new_n;
946 e_new = NULL;
948 else
949 err = gpg_error (GPG_ERR_GENERAL);
951 leave:
952 xfree (m_new);
953 xfree (e_new);
954 xfree (line);
955 return err;
957 #endif /*GNUPG_MAJOR_VERSION > 1*/
960 /* Get the public key for KEYNO and store it as an S-expresion with
961 the APP handle. On error that field gets cleared. If we already
962 know about the public key we will just return. Note that this does
963 not mean a key is available; this is soley indicated by the
964 presence of the app->app_local->pk[KEYNO-1].key field.
966 Note that GnuPG 1.x does not need this and it would be too time
967 consuming to send it just for the fun of it. However, given that we
968 use the same code in gpg 1.4, we can't use the gcry S-expresion
969 here but need to open encode it. */
970 #if GNUPG_MAJOR_VERSION > 1
971 static gpg_error_t
972 get_public_key (app_t app, int keyno)
974 gpg_error_t err = 0;
975 unsigned char *buffer;
976 const unsigned char *keydata, *m, *e;
977 size_t buflen, keydatalen, mlen, elen;
978 unsigned char *mbuf = NULL;
979 unsigned char *ebuf = NULL;
980 char *keybuf = NULL;
981 char *keybuf_p;
983 if (keyno < 1 || keyno > 3)
984 return gpg_error (GPG_ERR_INV_ID);
985 keyno--;
987 /* Already cached? */
988 if (app->app_local->pk[keyno].read_done)
989 return 0;
991 xfree (app->app_local->pk[keyno].key);
992 app->app_local->pk[keyno].key = NULL;
993 app->app_local->pk[keyno].keylen = 0;
995 m = e = NULL; /* (avoid cc warning) */
997 if (app->card_version > 0x0100)
999 /* We may simply read the public key out of these cards. */
1000 err = iso7816_read_public_key
1001 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
1002 keyno == 1? "\xB8" : "\xA4"),
1004 &buffer, &buflen);
1005 if (err)
1007 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1008 goto leave;
1011 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1012 if (!keydata)
1014 err = gpg_error (GPG_ERR_CARD);
1015 log_error (_("response does not contain the public key data\n"));
1016 goto leave;
1019 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1020 if (!m)
1022 err = gpg_error (GPG_ERR_CARD);
1023 log_error (_("response does not contain the RSA modulus\n"));
1024 goto leave;
1028 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1029 if (!e)
1031 err = gpg_error (GPG_ERR_CARD);
1032 log_error (_("response does not contain the RSA public exponent\n"));
1033 goto leave;
1036 /* Prepend numbers with a 0 if needed. */
1037 if (mlen && (*m & 0x80))
1039 mbuf = xtrymalloc ( mlen + 1);
1040 if (!mbuf)
1042 err = gpg_error_from_syserror ();
1043 goto leave;
1045 *mbuf = 0;
1046 memcpy (mbuf+1, m, mlen);
1047 mlen++;
1048 m = mbuf;
1050 if (elen && (*e & 0x80))
1052 ebuf = xtrymalloc ( elen + 1);
1053 if (!ebuf)
1055 err = gpg_error_from_syserror ();
1056 goto leave;
1058 *ebuf = 0;
1059 memcpy (ebuf+1, e, elen);
1060 elen++;
1061 e = ebuf;
1065 else
1067 /* Due to a design problem in v1.0 cards we can't get the public
1068 key out of these cards without doing a verify on CHV3.
1069 Clearly that is not an option and thus we try to locate the
1070 key using an external helper.
1072 The helper we use here is gpg itself, which should know about
1073 the key in any case. */
1075 char fpr[41];
1076 char *hexkeyid;
1077 char *command = NULL;
1078 FILE *fp;
1079 int ret;
1081 buffer = NULL; /* We don't need buffer. */
1083 err = retrieve_fpr_from_card (app, keyno, fpr);
1084 if (err)
1086 log_error ("error while retrieving fpr from card: %s\n",
1087 gpg_strerror (err));
1088 goto leave;
1090 hexkeyid = fpr + 24;
1092 ret = asprintf (&command,
1093 "gpg --list-keys --with-colons --with-key-data '%s'",
1094 fpr);
1095 if (ret < 0)
1097 err = gpg_error_from_syserror ();
1098 goto leave;
1101 fp = popen (command, "r");
1102 free (command);
1103 if (!fp)
1105 err = gpg_error_from_syserror ();
1106 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1107 goto leave;
1110 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1111 fclose (fp);
1112 if (err)
1114 log_error ("error while retrieving key material through pipe: %s\n",
1115 gpg_strerror (err));
1116 goto leave;
1120 /* Allocate a buffer to construct the S-expression. */
1121 /* FIXME: We should provide a generalized S-expression creation
1122 mechanism. */
1123 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1124 if (!keybuf)
1126 err = gpg_error_from_syserror ();
1127 goto leave;
1130 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1131 keybuf_p = keybuf + strlen (keybuf);
1132 memcpy (keybuf_p, m, mlen);
1133 keybuf_p += mlen;
1134 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1135 keybuf_p += strlen (keybuf_p);
1136 memcpy (keybuf_p, e, elen);
1137 keybuf_p += elen;
1138 strcpy (keybuf_p, ")))");
1139 keybuf_p += strlen (keybuf_p);
1141 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1142 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1144 leave:
1145 /* Set a flag to indicate that we tried to read the key. */
1146 app->app_local->pk[keyno].read_done = 1;
1148 xfree (buffer);
1149 xfree (mbuf);
1150 xfree (ebuf);
1151 return 0;
1153 #endif /* GNUPG_MAJOR_VERSION > 1 */
1157 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1158 This is used by the LEARN command. */
1159 static gpg_error_t
1160 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1162 gpg_error_t err = 0;
1163 /* Note that GnuPG 1.x does not need this and it would be too time
1164 consuming to send it just for the fun of it. */
1165 #if GNUPG_MAJOR_VERSION > 1
1166 unsigned char grip[20];
1167 char gripstr[41];
1168 char idbuf[50];
1169 int i;
1171 err = get_public_key (app, keyno);
1172 if (err)
1173 goto leave;
1175 assert (keyno >= 1 && keyno <= 3);
1176 if (!app->app_local->pk[keyno-1].key)
1177 goto leave; /* No such key - ignore. */
1179 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1180 app->app_local->pk[keyno-1].keylen,
1181 grip);
1182 if (err)
1183 goto leave;
1185 for (i=0; i < 20; i++)
1186 sprintf (gripstr+i*2, "%02X", grip[i]);
1188 sprintf (idbuf, "OPENPGP.%d", keyno);
1189 send_status_info (ctrl, "KEYPAIRINFO",
1190 gripstr, 40,
1191 idbuf, strlen (idbuf),
1192 NULL, (size_t)0);
1194 leave:
1195 #endif /* GNUPG_MAJOR_VERSION > 1 */
1197 return err;
1201 /* Handle the LEARN command for OpenPGP. */
1202 static gpg_error_t
1203 do_learn_status (app_t app, ctrl_t ctrl)
1205 do_getattr (app, ctrl, "EXTCAP");
1206 do_getattr (app, ctrl, "DISP-NAME");
1207 do_getattr (app, ctrl, "DISP-LANG");
1208 do_getattr (app, ctrl, "DISP-SEX");
1209 do_getattr (app, ctrl, "PUBKEY-URL");
1210 do_getattr (app, ctrl, "LOGIN-DATA");
1211 do_getattr (app, ctrl, "KEY-FPR");
1212 if (app->card_version > 0x0100)
1213 do_getattr (app, ctrl, "KEY-TIME");
1214 do_getattr (app, ctrl, "CA-FPR");
1215 do_getattr (app, ctrl, "CHV-STATUS");
1216 do_getattr (app, ctrl, "SIG-COUNTER");
1217 if (app->app_local->extcap.private_dos)
1219 do_getattr (app, ctrl, "PRIVATE-DO-1");
1220 do_getattr (app, ctrl, "PRIVATE-DO-2");
1221 if (app->did_chv2)
1222 do_getattr (app, ctrl, "PRIVATE-DO-3");
1223 if (app->did_chv3)
1224 do_getattr (app, ctrl, "PRIVATE-DO-4");
1226 send_keypair_info (app, ctrl, 1);
1227 send_keypair_info (app, ctrl, 2);
1228 send_keypair_info (app, ctrl, 3);
1229 return 0;
1233 /* Handle the READKEY command for OpenPGP. On success a canonical
1234 encoded S-expression with the public key will get stored at PK and
1235 its length (for assertions) at PKLEN; the caller must release that
1236 buffer. On error PK and PKLEN are not changed and an error code is
1237 returned. */
1238 static gpg_error_t
1239 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1241 #if GNUPG_MAJOR_VERSION > 1
1242 gpg_error_t err;
1243 int keyno;
1244 unsigned char *buf;
1246 if (!strcmp (keyid, "OPENPGP.1"))
1247 keyno = 1;
1248 else if (!strcmp (keyid, "OPENPGP.2"))
1249 keyno = 2;
1250 else if (!strcmp (keyid, "OPENPGP.3"))
1251 keyno = 3;
1252 else
1253 return gpg_error (GPG_ERR_INV_ID);
1255 err = get_public_key (app, keyno);
1256 if (err)
1257 return err;
1259 buf = app->app_local->pk[keyno-1].key;
1260 if (!buf)
1261 return gpg_error (GPG_ERR_NO_PUBKEY);
1262 *pklen = app->app_local->pk[keyno-1].keylen;;
1263 *pk = xtrymalloc (*pklen);
1264 if (!*pk)
1266 err = gpg_error_from_syserror ();
1267 *pklen = 0;
1268 return err;
1270 memcpy (*pk, buf, *pklen);
1271 return 0;
1272 #else
1273 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1274 #endif
1278 /* Verify a CHV either using using the pinentry or if possibile by
1279 using a keypad. PINCB and PINCB_ARG describe the usual callback
1280 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1281 ised with CHV1. PINVALUE is the address of a pointer which will
1282 receive a newly allocated block with the actual PIN (this is useful
1283 in case that PIN shall be used for another verifiy operation). The
1284 caller needs to free this value. If the function returns with
1285 success and NULL is stored at PINVALUE, the caller should take this
1286 as an indication that the keypad has been used.
1288 static gpg_error_t
1289 verify_a_chv (app_t app,
1290 gpg_error_t (*pincb)(void*, const char *, char **),
1291 void *pincb_arg,
1292 int chvno, unsigned long sigcount, char **pinvalue)
1294 int rc = 0;
1295 char *prompt;
1296 iso7816_pininfo_t pininfo;
1297 int minlen = 6;
1299 assert (chvno == 1 || chvno == 2);
1301 *pinvalue = NULL;
1303 memset (&pininfo, 0, sizeof pininfo);
1304 pininfo.mode = 1;
1305 pininfo.minlen = minlen;
1307 if (!opt.disable_keypad
1308 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1310 /* The reader supports the verify command through the keypad. */
1312 if (chvno == 1)
1314 #define PROMPTSTRING _("||Please enter your PIN at the reader's keypad%%0A" \
1315 "[sigs done: %lu]")
1316 size_t promptsize = strlen (PROMPTSTRING) + 50;
1318 prompt = xmalloc (promptsize);
1319 if (!prompt)
1320 return gpg_error_from_syserror ();
1321 snprintf (prompt, promptsize-1, PROMPTSTRING, sigcount);
1322 rc = pincb (pincb_arg, prompt, NULL);
1323 xfree (prompt);
1324 #undef PROMPTSTRING
1326 else
1327 rc = pincb (pincb_arg,
1328 _("||Please enter your PIN at the reader's keypad"),
1329 NULL);
1330 if (rc)
1332 log_info (_("PIN callback returned error: %s\n"),
1333 gpg_strerror (rc));
1334 return rc;
1336 rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1337 /* Dismiss the prompt. */
1338 pincb (pincb_arg, NULL, NULL);
1340 assert (!*pinvalue);
1342 else
1344 /* The reader has no keypad or we don't want to use it. */
1346 if (chvno == 1)
1348 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1349 size_t promptsize = strlen (PROMPTSTRING) + 50;
1351 prompt = xmalloc (promptsize);
1352 if (!prompt)
1353 return gpg_error_from_syserror ();
1354 snprintf (prompt, promptsize-1, PROMPTSTRING, sigcount);
1355 rc = pincb (pincb_arg, prompt, pinvalue);
1356 xfree (prompt);
1357 #undef PROMPTSTRING
1359 else
1360 rc = pincb (pincb_arg, "PIN", pinvalue);
1362 if (rc)
1364 log_info (_("PIN callback returned error: %s\n"),
1365 gpg_strerror (rc));
1366 return rc;
1369 if (strlen (*pinvalue) < minlen)
1371 log_error (_("PIN for CHV%d is too short;"
1372 " minimum length is %d\n"), chvno, minlen);
1373 xfree (*pinvalue);
1374 *pinvalue = NULL;
1375 return gpg_error (GPG_ERR_BAD_PIN);
1378 rc = iso7816_verify (app->slot, 0x80+chvno,
1379 *pinvalue, strlen (*pinvalue));
1382 if (rc)
1384 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1385 xfree (*pinvalue);
1386 *pinvalue = NULL;
1387 flush_cache_after_error (app);
1390 return rc;
1394 /* Verify CHV2 if required. Depending on the configuration of the
1395 card CHV1 will also be verified. */
1396 static gpg_error_t
1397 verify_chv2 (app_t app,
1398 gpg_error_t (*pincb)(void*, const char *, char **),
1399 void *pincb_arg)
1401 int rc;
1402 char *pinvalue;
1404 if (app->did_chv2)
1405 return 0; /* We already verified CHV2. */
1407 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1408 if (rc)
1409 return rc;
1411 app->did_chv2 = 1;
1413 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1415 /* For convenience we verify CHV1 here too. We do this only if
1416 the card is not configured to require a verification before
1417 each CHV1 controlled operation (force_chv1) and if we are not
1418 using the keypad (PINVALUE == NULL). */
1419 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1420 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1421 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1422 if (rc)
1424 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1425 flush_cache_after_error (app);
1427 else
1428 app->did_chv1 = 1;
1430 xfree (pinvalue);
1432 return rc;
1436 /* Verify CHV3 if required. */
1437 static gpg_error_t
1438 verify_chv3 (app_t app,
1439 gpg_error_t (*pincb)(void*, const char *, char **),
1440 void *pincb_arg)
1442 int rc = 0;
1444 #if GNUPG_MAJOR_VERSION != 1
1445 if (!opt.allow_admin)
1447 log_info (_("access to admin commands is not configured\n"));
1448 return gpg_error (GPG_ERR_EACCES);
1450 #endif
1452 if (!app->did_chv3)
1454 char *pinvalue;
1455 void *relptr;
1456 unsigned char *value;
1457 size_t valuelen;
1459 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1460 if (!relptr || valuelen < 7)
1462 log_error (_("error retrieving CHV status from card\n"));
1463 xfree (relptr);
1464 return gpg_error (GPG_ERR_CARD);
1466 if (value[6] == 0)
1468 log_info (_("card is permanently locked!\n"));
1469 xfree (relptr);
1470 return gpg_error (GPG_ERR_BAD_PIN);
1473 log_info(_("%d Admin PIN attempts remaining before card"
1474 " is permanently locked\n"), value[6]);
1475 xfree (relptr);
1477 /* TRANSLATORS: Do not translate the "|A|" prefix but
1478 keep it at the start of the string. We need this elsewhere
1479 to get some infos on the string. */
1480 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1481 if (rc)
1483 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1484 return rc;
1487 if (strlen (pinvalue) < 8)
1489 log_error (_("PIN for CHV%d is too short;"
1490 " minimum length is %d\n"), 3, 8);
1491 xfree (pinvalue);
1492 return gpg_error (GPG_ERR_BAD_PIN);
1495 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1496 xfree (pinvalue);
1497 if (rc)
1499 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1500 flush_cache_after_error (app);
1501 return rc;
1503 app->did_chv3 = 1;
1505 return rc;
1509 /* Handle the SETATTR operation. All arguments are already basically
1510 checked. */
1511 static gpg_error_t
1512 do_setattr (app_t app, const char *name,
1513 gpg_error_t (*pincb)(void*, const char *, char **),
1514 void *pincb_arg,
1515 const unsigned char *value, size_t valuelen)
1517 gpg_error_t rc;
1518 int idx;
1519 static struct {
1520 const char *name;
1521 int tag;
1522 int need_chv;
1523 int special;
1524 } table[] = {
1525 { "DISP-NAME", 0x005B, 3 },
1526 { "LOGIN-DATA", 0x005E, 3, 2 },
1527 { "DISP-LANG", 0x5F2D, 3 },
1528 { "DISP-SEX", 0x5F35, 3 },
1529 { "PUBKEY-URL", 0x5F50, 3 },
1530 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1531 { "CA-FPR-1", 0x00CA, 3 },
1532 { "CA-FPR-2", 0x00CB, 3 },
1533 { "CA-FPR-3", 0x00CC, 3 },
1534 { "PRIVATE-DO-1", 0x0101, 2 },
1535 { "PRIVATE-DO-2", 0x0102, 3 },
1536 { "PRIVATE-DO-3", 0x0103, 2 },
1537 { "PRIVATE-DO-4", 0x0104, 3 },
1538 { NULL, 0 }
1542 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1544 if (!table[idx].name)
1545 return gpg_error (GPG_ERR_INV_NAME);
1547 switch (table[idx].need_chv)
1549 case 2:
1550 rc = verify_chv2 (app, pincb, pincb_arg);
1551 break;
1552 case 3:
1553 rc = verify_chv3 (app, pincb, pincb_arg);
1554 break;
1555 default:
1556 rc = 0;
1558 if (rc)
1559 return rc;
1561 /* Flush the cache before writing it, so that the next get operation
1562 will reread the data from the card and thus get synced in case of
1563 errors (e.g. data truncated by the card). */
1564 flush_cache_item (app, table[idx].tag);
1565 rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
1566 if (rc)
1567 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1569 if (table[idx].special == 1)
1570 app->force_chv1 = (valuelen && *value == 0);
1571 else if (table[idx].special == 2)
1572 parse_login_data (app);
1574 return rc;
1578 /* Handle the PASSWD command. */
1579 static gpg_error_t
1580 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
1581 gpg_error_t (*pincb)(void*, const char *, char **),
1582 void *pincb_arg)
1584 int rc = 0;
1585 int chvno = atoi (chvnostr);
1586 char *pinvalue;
1588 if (reset_mode && chvno == 3)
1590 rc = gpg_error (GPG_ERR_INV_ID);
1591 goto leave;
1593 else if (reset_mode || chvno == 3)
1595 /* we always require that the PIN is entered. */
1596 app->did_chv3 = 0;
1597 rc = verify_chv3 (app, pincb, pincb_arg);
1598 if (rc)
1599 goto leave;
1601 else if (chvno == 1 || chvno == 2)
1603 /* CHV1 and CVH2 should always have the same value, thus we
1604 enforce it here. */
1605 int save_force = app->force_chv1;
1607 app->force_chv1 = 0;
1608 app->did_chv1 = 0;
1609 app->did_chv2 = 0;
1610 rc = verify_chv2 (app, pincb, pincb_arg);
1611 app->force_chv1 = save_force;
1612 if (rc)
1613 goto leave;
1615 else
1617 rc = gpg_error (GPG_ERR_INV_ID);
1618 goto leave;
1621 if (chvno == 3)
1622 app->did_chv3 = 0;
1623 else
1624 app->did_chv1 = app->did_chv2 = 0;
1626 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1627 keep it at the start of the string. We need this elsewhere
1628 to get some infos on the string. */
1629 rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1630 &pinvalue);
1631 if (rc)
1633 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1634 goto leave;
1637 if (reset_mode)
1639 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1640 pinvalue, strlen (pinvalue));
1641 if (!rc)
1642 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1643 pinvalue, strlen (pinvalue));
1645 else
1647 if (chvno == 1 || chvno == 2)
1649 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1650 pinvalue, strlen (pinvalue));
1651 if (!rc)
1652 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1653 pinvalue, strlen (pinvalue));
1655 else
1656 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1657 pinvalue, strlen (pinvalue));
1659 xfree (pinvalue);
1660 if (rc)
1661 flush_cache_after_error (app);
1663 leave:
1664 return rc;
1668 /* Check whether a key already exists. KEYIDX is the index of the key
1669 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1670 error returned if the key already exists. */
1671 static gpg_error_t
1672 does_key_exist (app_t app, int keyidx, int force)
1674 const unsigned char *fpr;
1675 unsigned char *buffer;
1676 size_t buflen, n;
1677 int i;
1679 assert (keyidx >=0 && keyidx <= 2);
1681 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
1683 log_error (_("error reading application data\n"));
1684 return gpg_error (GPG_ERR_GENERAL);
1686 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1687 if (!fpr || n < 60)
1689 log_error (_("error reading fingerprint DO\n"));
1690 xfree (buffer);
1691 return gpg_error (GPG_ERR_GENERAL);
1693 fpr += 20*keyidx;
1694 for (i=0; i < 20 && !fpr[i]; i++)
1696 xfree (buffer);
1697 if (i!=20 && !force)
1699 log_error (_("key already exists\n"));
1700 return gpg_error (GPG_ERR_EEXIST);
1702 else if (i!=20)
1703 log_info (_("existing key will be replaced\n"));
1704 else
1705 log_info (_("generating new key\n"));
1706 return 0;
1711 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1712 canonical encoded S-expression with the secret key in KEYDATA and
1713 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1714 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1715 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1716 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1717 the pinentry callback. */
1718 static gpg_error_t
1719 do_writekey (app_t app, ctrl_t ctrl,
1720 const char *keyid, unsigned int flags,
1721 gpg_error_t (*pincb)(void*, const char *, char **),
1722 void *pincb_arg,
1723 const unsigned char *keydata, size_t keydatalen)
1725 gpg_error_t err;
1726 int force = (flags & 1);
1727 int keyno;
1728 const unsigned char *buf, *tok;
1729 size_t buflen, toklen;
1730 int depth, last_depth1, last_depth2;
1731 const unsigned char *rsa_n = NULL;
1732 const unsigned char *rsa_e = NULL;
1733 const unsigned char *rsa_p = NULL;
1734 const unsigned char *rsa_q = NULL;
1735 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
1736 unsigned int nbits;
1737 unsigned char *template = NULL;
1738 unsigned char *tp;
1739 size_t template_len;
1740 unsigned char fprbuf[20];
1741 u32 created_at = 0;
1743 if (!strcmp (keyid, "OPENPGP.1"))
1744 keyno = 0;
1745 else if (!strcmp (keyid, "OPENPGP.2"))
1746 keyno = 1;
1747 else if (!strcmp (keyid, "OPENPGP.3"))
1748 keyno = 2;
1749 else
1750 return gpg_error (GPG_ERR_INV_ID);
1752 err = does_key_exist (app, keyno, force);
1753 if (err)
1754 return err;
1758 Parse the S-expression
1760 buf = keydata;
1761 buflen = keydatalen;
1762 depth = 0;
1763 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1764 goto leave;
1765 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1766 goto leave;
1767 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
1769 if (!tok)
1771 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
1772 log_info ("protected-private-key passed to writekey\n");
1773 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
1774 log_info ("shadowed-private-key passed to writekey\n");
1775 err = gpg_error (GPG_ERR_BAD_SECKEY);
1776 goto leave;
1778 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1779 goto leave;
1780 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1781 goto leave;
1782 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
1784 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
1785 goto leave;
1787 last_depth1 = depth;
1788 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1789 && depth && depth >= last_depth1)
1791 if (tok)
1793 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1794 goto leave;
1796 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1797 goto leave;
1798 if (tok && toklen == 1)
1800 const unsigned char **mpi;
1801 size_t *mpi_len;
1803 switch (*tok)
1805 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
1806 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
1807 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
1808 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
1809 default: mpi = NULL; mpi_len = NULL; break;
1811 if (mpi && *mpi)
1813 err = gpg_error (GPG_ERR_DUP_VALUE);
1814 goto leave;
1816 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1817 goto leave;
1818 if (tok && mpi)
1820 /* Strip off leading zero bytes and save. */
1821 for (;toklen && !*tok; toklen--, tok++)
1823 *mpi = tok;
1824 *mpi_len = toklen;
1827 /* Skip until end of list. */
1828 last_depth2 = depth;
1829 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1830 && depth && depth >= last_depth2)
1832 if (err)
1833 goto leave;
1835 /* Parse other attributes. */
1836 last_depth1 = depth;
1837 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1838 && depth && depth >= last_depth1)
1840 if (tok)
1842 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1843 goto leave;
1845 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1846 goto leave;
1847 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
1849 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
1850 goto leave;
1851 if (tok)
1853 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
1854 tok++, toklen--)
1855 created_at = created_at*10 + (*tok - '0');
1858 /* Skip until end of list. */
1859 last_depth2 = depth;
1860 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1861 && depth && depth >= last_depth2)
1863 if (err)
1864 goto leave;
1868 /* Check that we have all parameters and that they match the card
1869 description. */
1870 if (!created_at)
1872 log_error (_("creation timestamp missing\n"));
1873 err = gpg_error (GPG_ERR_INV_VALUE);
1874 goto leave;
1876 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
1877 if (nbits != 1024)
1879 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1880 err = gpg_error (GPG_ERR_BAD_SECKEY);
1881 goto leave;
1883 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
1884 if (nbits < 2 || nbits > 32)
1886 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1887 32);
1888 err = gpg_error (GPG_ERR_BAD_SECKEY);
1889 goto leave;
1891 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
1892 if (nbits != 512)
1894 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1895 err = gpg_error (GPG_ERR_BAD_SECKEY);
1896 goto leave;
1898 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
1899 if (nbits != 512)
1901 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1902 err = gpg_error (GPG_ERR_BAD_SECKEY);
1903 goto leave;
1907 /* Build the private key template as described in section 4.3.3.6 of
1908 the OpenPGP card specs:
1909 0xC0 <length> public exponent
1910 0xC1 <length> prime p
1911 0xC2 <length> prime q
1913 assert (rsa_e_len <= 4);
1914 template_len = (1 + 1 + 4
1915 + 1 + 1 + rsa_p_len
1916 + 1 + 1 + rsa_q_len);
1917 template = tp = xtrymalloc_secure (template_len);
1918 if (!template)
1920 err = gpg_error_from_syserror ();
1921 goto leave;
1923 *tp++ = 0xC0;
1924 *tp++ = 4;
1925 memcpy (tp, rsa_e, rsa_e_len);
1926 if (rsa_e_len < 4)
1928 /* Right justify E. */
1929 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
1930 memset (tp, 0, 4-rsa_e_len);
1932 tp += 4;
1934 *tp++ = 0xC1;
1935 *tp++ = rsa_p_len;
1936 memcpy (tp, rsa_p, rsa_p_len);
1937 tp += rsa_p_len;
1939 *tp++ = 0xC2;
1940 *tp++ = rsa_q_len;
1941 memcpy (tp, rsa_q, rsa_q_len);
1942 tp += rsa_q_len;
1944 assert (tp - template == template_len);
1947 /* Obviously we need to remove the cached public key. */
1948 xfree (app->app_local->pk[keyno].key);
1949 app->app_local->pk[keyno].key = NULL;
1950 app->app_local->pk[keyno].keylen = 0;
1951 app->app_local->pk[keyno].read_done = 0;
1953 /* Prepare for storing the key. */
1954 err = verify_chv3 (app, pincb, pincb_arg);
1955 if (err)
1956 goto leave;
1958 /* Store the key. */
1959 err = iso7816_put_data (app->slot,
1960 (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
1961 template, template_len);
1962 if (err)
1964 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
1965 goto leave;
1968 err = store_fpr (app->slot, keyno, created_at,
1969 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
1970 fprbuf, app->card_version);
1971 if (err)
1972 goto leave;
1975 leave:
1976 xfree (template);
1977 return err;
1981 /* Handle the GENKEY command. */
1982 static gpg_error_t
1983 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
1984 time_t createtime,
1985 gpg_error_t (*pincb)(void*, const char *, char **),
1986 void *pincb_arg)
1988 int rc;
1989 char numbuf[30];
1990 unsigned char fprbuf[20];
1991 const unsigned char *keydata, *m, *e;
1992 unsigned char *buffer = NULL;
1993 size_t buflen, keydatalen, mlen, elen;
1994 time_t created_at;
1995 int keyno = atoi (keynostr);
1996 int force = (flags & 1);
1997 time_t start_at;
1999 if (keyno < 1 || keyno > 3)
2000 return gpg_error (GPG_ERR_INV_ID);
2001 keyno--;
2003 /* We flush the cache to increase the traffic before a key
2004 generation. This _might_ help a card to gather more entropy. */
2005 flush_cache (app);
2007 /* Obviously we need to remove the cached public key. */
2008 xfree (app->app_local->pk[keyno].key);
2009 app->app_local->pk[keyno].key = NULL;
2010 app->app_local->pk[keyno].keylen = 0;
2011 app->app_local->pk[keyno].read_done = 0;
2013 /* Check whether a key already exists. */
2014 rc = does_key_exist (app, keyno, force);
2015 if (rc)
2016 return rc;
2018 /* Prepare for key generation by verifying the Admin PIN. */
2019 rc = verify_chv3 (app, pincb, pincb_arg);
2020 if (rc)
2021 goto leave;
2023 #if 1
2024 log_info (_("please wait while key is being generated ...\n"));
2025 start_at = time (NULL);
2026 rc = iso7816_generate_keypair
2027 #else
2028 # warning key generation temporary replaced by reading an existing key.
2029 rc = iso7816_read_public_key
2030 #endif
2031 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
2032 keyno == 1? "\xB8" : "\xA4"),
2034 &buffer, &buflen);
2035 if (rc)
2037 rc = gpg_error (GPG_ERR_CARD);
2038 log_error (_("generating key failed\n"));
2039 goto leave;
2041 log_info (_("key generation completed (%d seconds)\n"),
2042 (int)(time (NULL) - start_at));
2043 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2044 if (!keydata)
2046 rc = gpg_error (GPG_ERR_CARD);
2047 log_error (_("response does not contain the public key data\n"));
2048 goto leave;
2051 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2052 if (!m)
2054 rc = gpg_error (GPG_ERR_CARD);
2055 log_error (_("response does not contain the RSA modulus\n"));
2056 goto leave;
2058 /* log_printhex ("RSA n:", m, mlen); */
2059 send_key_data (ctrl, "n", m, mlen);
2061 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2062 if (!e)
2064 rc = gpg_error (GPG_ERR_CARD);
2065 log_error (_("response does not contain the RSA public exponent\n"));
2066 goto leave;
2068 /* log_printhex ("RSA e:", e, elen); */
2069 send_key_data (ctrl, "e", e, elen);
2071 created_at = createtime? createtime : gnupg_get_time ();
2072 sprintf (numbuf, "%lu", (unsigned long)created_at);
2073 send_status_info (ctrl, "KEY-CREATED-AT",
2074 numbuf, (size_t)strlen(numbuf), NULL, 0);
2076 rc = store_fpr (app->slot, keyno, (u32)created_at,
2077 m, mlen, e, elen, fprbuf, app->card_version);
2078 if (rc)
2079 goto leave;
2080 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2083 leave:
2084 xfree (buffer);
2085 return rc;
2089 static unsigned long
2090 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2092 unsigned long ul;
2094 if (valuelen == 3 )
2095 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2096 else
2098 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2099 ul = 0;
2101 return ul;
2104 static unsigned long
2105 get_sig_counter (app_t app)
2107 void *relptr;
2108 unsigned char *value;
2109 size_t valuelen;
2110 unsigned long ul;
2112 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2113 if (!relptr)
2114 return 0;
2115 ul = convert_sig_counter_value (value, valuelen);
2116 xfree (relptr);
2117 return ul;
2120 static gpg_error_t
2121 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2123 const unsigned char *fpr;
2124 unsigned char *buffer;
2125 size_t buflen, n;
2126 int rc, i;
2128 assert (keyno >= 1 && keyno <= 3);
2130 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
2131 if (rc)
2133 log_error (_("error reading application data\n"));
2134 return gpg_error (GPG_ERR_GENERAL);
2136 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2137 if (!fpr || n != 60)
2139 xfree (buffer);
2140 log_error (_("error reading fingerprint DO\n"));
2141 return gpg_error (GPG_ERR_GENERAL);
2143 fpr += (keyno-1)*20;
2144 for (i=0; i < 20; i++)
2145 if (sha1fpr[i] != fpr[i])
2147 xfree (buffer);
2148 log_info (_("fingerprint on card does not match requested one\n"));
2149 return gpg_error (GPG_ERR_WRONG_SECKEY);
2151 xfree (buffer);
2152 return 0;
2156 /* If a fingerprint has been specified check it against the one on
2157 the card. This is allows for a meaningful error message in case
2158 the key on the card has been replaced but the shadow information
2159 known to gpg was not updated. If there is no fingerprint we
2160 assume that this is okay. */
2161 static gpg_error_t
2162 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2164 unsigned char tmp[20];
2165 const char *s;
2166 int n;
2168 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2170 if (n != 40)
2171 return gpg_error (GPG_ERR_INV_ID);
2172 else if (!*s)
2173 ; /* okay */
2174 else
2175 return gpg_error (GPG_ERR_INV_ID);
2177 for (s=fpr, n=0; n < 20; s += 2, n++)
2178 tmp[n] = xtoi_2 (s);
2179 return compare_fingerprint (app, keyno, tmp);
2184 /* Compute a digital signature on INDATA which is expected to be the
2185 raw message digest. For this application the KEYIDSTR consists of
2186 the serialnumber and the fingerprint delimited by a slash.
2188 Note that this function may return the error code
2189 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2190 not match the one required for the requested action (e.g. the
2191 serial number does not match).
2193 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2194 operation to the auth command.
2196 static gpg_error_t
2197 do_sign (app_t app, const char *keyidstr, int hashalgo,
2198 gpg_error_t (*pincb)(void*, const char *, char **),
2199 void *pincb_arg,
2200 const void *indata, size_t indatalen,
2201 unsigned char **outdata, size_t *outdatalen )
2203 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2204 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2205 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2206 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2207 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2208 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2209 int rc;
2210 unsigned char data[35];
2211 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2212 const char *s;
2213 int n;
2214 const char *fpr = NULL;
2215 unsigned long sigcount;
2216 int use_auth = 0;
2218 if (!keyidstr || !*keyidstr)
2219 return gpg_error (GPG_ERR_INV_VALUE);
2220 if (indatalen == 20)
2222 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
2223 && !memcmp (indata, sha1_prefix, 15))
2225 indata = (const char*)indata + 15;
2226 indatalen -= 15;
2228 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
2229 && !memcmp (indata, rmd160_prefix, 15))
2231 indata = (const char*)indata + 15;
2232 indatalen -= 15;
2234 else
2236 log_error (_("card does not support digest algorithm %s\n"),
2237 gcry_md_algo_name (hashalgo));
2238 return gpg_error (GPG_ERR_INV_VALUE);
2241 /* Check whether an OpenPGP card of any version has been requested. */
2242 if (!strcmp (keyidstr, "OPENPGP.1"))
2244 else if (!strcmp (keyidstr, "OPENPGP.3"))
2245 use_auth = 1;
2246 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2247 return gpg_error (GPG_ERR_INV_ID);
2248 else
2250 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2252 if (n != 32)
2253 return gpg_error (GPG_ERR_INV_ID);
2254 else if (!*s)
2255 ; /* no fingerprint given: we allow this for now. */
2256 else if (*s == '/')
2257 fpr = s + 1;
2258 else
2259 return gpg_error (GPG_ERR_INV_ID);
2261 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2262 tmp_sn[n] = xtoi_2 (s);
2264 if (app->serialnolen != 16)
2265 return gpg_error (GPG_ERR_INV_CARD);
2266 if (memcmp (app->serialno, tmp_sn, 16))
2267 return gpg_error (GPG_ERR_WRONG_CARD);
2270 /* If a fingerprint has been specified check it against the one on
2271 the card. This is allows for a meaningful error message in case
2272 the key on the card has been replaced but the shadow information
2273 known to gpg was not updated. If there is no fingerprint, gpg
2274 will detect a bogus signature anyway due to the
2275 verify-after-signing feature. */
2276 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2277 if (rc)
2278 return rc;
2280 if (hashalgo == GCRY_MD_SHA1)
2281 memcpy (data, sha1_prefix, 15);
2282 else if (hashalgo == GCRY_MD_RMD160)
2283 memcpy (data, rmd160_prefix, 15);
2284 else
2285 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2286 memcpy (data+15, indata, indatalen);
2288 if (use_auth)
2290 /* This is a hack to redirect to the internal authenticate command. */
2291 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
2292 data, 35,
2293 outdata, outdatalen);
2296 sigcount = get_sig_counter (app);
2297 log_info (_("signatures created so far: %lu\n"), sigcount);
2299 if (!app->did_chv1 || app->force_chv1 )
2301 char *pinvalue;
2303 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
2304 if (rc)
2305 return rc;
2307 app->did_chv1 = 1;
2309 if (!app->did_chv2 && pinvalue)
2311 /* We should also verify CHV2. Note, that we can't do that
2312 if the keypad has been used. */
2313 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2314 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2315 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2316 if (rc)
2318 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2319 xfree (pinvalue);
2320 flush_cache_after_error (app);
2321 return rc;
2323 app->did_chv2 = 1;
2325 xfree (pinvalue);
2328 rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
2329 return rc;
2332 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2333 on INDATA which is expected to be the raw message digest. For this
2334 application the KEYIDSTR consists of the serialnumber and the
2335 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2336 be given.
2338 Note that this function may return the error code
2339 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2340 not match the one required for the requested action (e.g. the
2341 serial number does not match). */
2342 static gpg_error_t
2343 do_auth (app_t app, const char *keyidstr,
2344 gpg_error_t (*pincb)(void*, const char *, char **),
2345 void *pincb_arg,
2346 const void *indata, size_t indatalen,
2347 unsigned char **outdata, size_t *outdatalen )
2349 int rc;
2350 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2351 const char *s;
2352 int n;
2353 const char *fpr = NULL;
2355 if (!keyidstr || !*keyidstr)
2356 return gpg_error (GPG_ERR_INV_VALUE);
2357 if (indatalen > 50) /* For a 1024 bit key. */
2358 return gpg_error (GPG_ERR_INV_VALUE);
2360 /* Check whether an OpenPGP card of any version has been requested. */
2361 if (!strcmp (keyidstr, "OPENPGP.3"))
2363 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2364 return gpg_error (GPG_ERR_INV_ID);
2365 else
2367 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2369 if (n != 32)
2370 return gpg_error (GPG_ERR_INV_ID);
2371 else if (!*s)
2372 ; /* no fingerprint given: we allow this for now. */
2373 else if (*s == '/')
2374 fpr = s + 1;
2375 else
2376 return gpg_error (GPG_ERR_INV_ID);
2378 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2379 tmp_sn[n] = xtoi_2 (s);
2381 if (app->serialnolen != 16)
2382 return gpg_error (GPG_ERR_INV_CARD);
2383 if (memcmp (app->serialno, tmp_sn, 16))
2384 return gpg_error (GPG_ERR_WRONG_CARD);
2387 /* If a fingerprint has been specified check it against the one on
2388 the card. This is allows for a meaningful error message in case
2389 the key on the card has been replaced but the shadow information
2390 known to gpg was not updated. If there is no fingerprint, gpg
2391 will detect a bogus signature anyway due to the
2392 verify-after-signing feature. */
2393 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
2394 if (rc)
2395 return rc;
2397 rc = verify_chv2 (app, pincb, pincb_arg);
2398 if (!rc)
2399 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
2400 outdata, outdatalen);
2401 return rc;
2405 static gpg_error_t
2406 do_decipher (app_t app, const char *keyidstr,
2407 gpg_error_t (*pincb)(void*, const char *, char **),
2408 void *pincb_arg,
2409 const void *indata, size_t indatalen,
2410 unsigned char **outdata, size_t *outdatalen )
2412 int rc;
2413 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2414 const char *s;
2415 int n;
2416 const char *fpr = NULL;
2418 if (!keyidstr || !*keyidstr || !indatalen)
2419 return gpg_error (GPG_ERR_INV_VALUE);
2421 /* Check whether an OpenPGP card of any version has been requested. */
2422 if (!strcmp (keyidstr, "OPENPGP.2"))
2424 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2425 return gpg_error (GPG_ERR_INV_ID);
2426 else
2428 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2430 if (n != 32)
2431 return gpg_error (GPG_ERR_INV_ID);
2432 else if (!*s)
2433 ; /* no fingerprint given: we allow this for now. */
2434 else if (*s == '/')
2435 fpr = s + 1;
2436 else
2437 return gpg_error (GPG_ERR_INV_ID);
2439 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2440 tmp_sn[n] = xtoi_2 (s);
2442 if (app->serialnolen != 16)
2443 return gpg_error (GPG_ERR_INV_CARD);
2444 if (memcmp (app->serialno, tmp_sn, 16))
2445 return gpg_error (GPG_ERR_WRONG_CARD);
2448 /* If a fingerprint has been specified check it against the one on
2449 the card. This is allows for a meaningful error message in case
2450 the key on the card has been replaced but the shadow information
2451 known to gpg was not updated. If there is no fingerprint, the
2452 decryption will won't produce the right plaintext anyway. */
2453 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
2454 if (rc)
2455 return rc;
2457 rc = verify_chv2 (app, pincb, pincb_arg);
2458 if (!rc)
2460 size_t fixuplen;
2462 /* We might encounter a couple of leading zeroes in the
2463 cryptogram. Due to internal use of MPIs thease leading
2464 zeroes are stripped. However the OpenPGP card expects
2465 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
2466 need to fix it up. We do this for up to 16 leading zero
2467 bytes; a cryptogram with more than this is with a very high
2468 probability anyway broken. */
2469 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
2470 fixuplen = 128 - indatalen;
2471 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
2472 fixuplen = 256 - indatalen;
2473 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
2474 fixuplen = 192 - indatalen;
2475 else
2476 fixuplen = 0;
2477 if (fixuplen)
2479 unsigned char *fixbuf;
2481 /* While we have to prepend stuff anyway, we can also
2482 include the padding byte here so that iso1816_decipher
2483 does not need to do yet another data mangling. */
2484 fixuplen++;
2485 fixbuf = xtrymalloc (fixuplen + indatalen);
2486 if (!fixbuf)
2487 rc = gpg_error_from_syserror ();
2488 else
2490 memset (fixbuf, 0, fixuplen);
2491 memcpy (fixbuf+fixuplen, indata, indatalen);
2492 rc = iso7816_decipher (app->slot, fixbuf, fixuplen+indatalen, -1,
2493 outdata, outdatalen);
2494 xfree (fixbuf);
2498 else
2499 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
2500 outdata, outdatalen);
2502 return rc;
2506 /* Perform a simple verify operation for CHV1 and CHV2, so that
2507 further operations won't ask for CHV2 and it is possible to do a
2508 cheap check on the PIN: If there is something wrong with the PIN
2509 entry system, only the regular CHV will get blocked and not the
2510 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2511 optional fingerprint part will be ignored.
2513 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2514 the "[CHV3]" being a literal string: The Admin Pin is checked if
2515 and only if the retry counter is still at 3. */
2516 static gpg_error_t
2517 do_check_pin (app_t app, const char *keyidstr,
2518 gpg_error_t (*pincb)(void*, const char *, char **),
2519 void *pincb_arg)
2521 unsigned char tmp_sn[20];
2522 const char *s;
2523 int n;
2524 int admin_pin = 0;
2526 if (!keyidstr || !*keyidstr)
2527 return gpg_error (GPG_ERR_INV_VALUE);
2529 /* Check whether an OpenPGP card of any version has been requested. */
2530 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2531 return gpg_error (GPG_ERR_INV_ID);
2533 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2535 if (n != 32)
2536 return gpg_error (GPG_ERR_INV_ID);
2537 else if (!*s)
2538 ; /* No fingerprint given: we allow this for now. */
2539 else if (*s == '/')
2540 ; /* We ignore a fingerprint. */
2541 else if (!strcmp (s, "[CHV3]") )
2542 admin_pin = 1;
2543 else
2544 return gpg_error (GPG_ERR_INV_ID);
2546 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2547 tmp_sn[n] = xtoi_2 (s);
2549 if (app->serialnolen != 16)
2550 return gpg_error (GPG_ERR_INV_CARD);
2551 if (memcmp (app->serialno, tmp_sn, 16))
2552 return gpg_error (GPG_ERR_WRONG_CARD);
2554 /* Yes, there is a race conditions: The user might pull the card
2555 right here and we won't notice that. However this is not a
2556 problem and the check above is merely for a graceful failure
2557 between operations. */
2559 if (admin_pin)
2561 void *relptr;
2562 unsigned char *value;
2563 size_t valuelen;
2564 int count;
2566 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2567 if (!relptr || valuelen < 7)
2569 log_error (_("error retrieving CHV status from card\n"));
2570 xfree (relptr);
2571 return gpg_error (GPG_ERR_CARD);
2573 count = value[6];
2574 xfree (relptr);
2576 if (!count)
2578 log_info (_("card is permanently locked!\n"));
2579 return gpg_error (GPG_ERR_BAD_PIN);
2581 else if (value[6] < 3)
2583 log_info (_("verification of Admin PIN is currently prohibited "
2584 "through this command\n"));
2585 return gpg_error (GPG_ERR_GENERAL);
2588 app->did_chv3 = 0; /* Force verification. */
2589 return verify_chv3 (app, pincb, pincb_arg);
2591 else
2592 return verify_chv2 (app, pincb, pincb_arg);
2598 /* Select the OpenPGP application on the card in SLOT. This function
2599 must be used before any other OpenPGP application functions. */
2600 gpg_error_t
2601 app_select_openpgp (app_t app)
2603 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2604 int slot = app->slot;
2605 int rc;
2606 unsigned char *buffer;
2607 size_t buflen;
2608 void *relptr;
2610 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
2611 special flag value. */
2612 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
2613 if (!rc)
2615 unsigned int manufacturer;
2617 app->apptype = "OPENPGP";
2619 app->did_chv1 = 0;
2620 app->did_chv2 = 0;
2621 app->did_chv3 = 0;
2622 app->app_local = NULL;
2624 /* The OpenPGP card returns the serial number as part of the
2625 AID; because we prefer to use OpenPGP serial numbers, we
2626 replace a possibly already set one from a EF.GDO with this
2627 one. Note, that for current OpenPGP cards, no EF.GDO exists
2628 and thus it won't matter at all. */
2629 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
2630 if (rc)
2631 goto leave;
2632 if (opt.verbose)
2634 log_info ("AID: ");
2635 log_printhex ("", buffer, buflen);
2638 app->card_version = buffer[6] << 8;
2639 app->card_version |= buffer[7];
2640 manufacturer = (buffer[8]<<8 | buffer[9]);
2642 xfree (app->serialno);
2643 app->serialno = buffer;
2644 app->serialnolen = buflen;
2645 buffer = NULL;
2646 app->app_local = xtrycalloc (1, sizeof *app->app_local);
2647 if (!app->app_local)
2649 rc = gpg_error (gpg_err_code_from_errno (errno));
2650 goto leave;
2653 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
2654 if (!relptr)
2656 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2657 "CHV Status Bytes");
2658 goto leave;
2660 app->force_chv1 = (buflen && *buffer == 0);
2661 xfree (relptr);
2663 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
2664 if (!relptr)
2666 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2667 "Extended Capability Flags" );
2668 goto leave;
2670 if (buflen)
2672 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
2673 app->app_local->extcap.key_import = !!(*buffer & 0x20);
2674 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
2675 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
2677 xfree (relptr);
2679 /* Some of the first cards accidently don't set the
2680 CHANGE_FORCE_CHV bit but allow it anyway. */
2681 if (app->card_version <= 0x0100 && manufacturer == 1)
2682 app->app_local->extcap.change_force_chv = 1;
2684 parse_login_data (app);
2686 if (opt.verbose > 1)
2687 dump_all_do (slot);
2689 app->fnc.deinit = do_deinit;
2690 app->fnc.learn_status = do_learn_status;
2691 app->fnc.readkey = do_readkey;
2692 app->fnc.getattr = do_getattr;
2693 app->fnc.setattr = do_setattr;
2694 app->fnc.writekey = do_writekey;
2695 app->fnc.genkey = do_genkey;
2696 app->fnc.sign = do_sign;
2697 app->fnc.auth = do_auth;
2698 app->fnc.decipher = do_decipher;
2699 app->fnc.change_pin = do_change_pin;
2700 app->fnc.check_pin = do_check_pin;
2703 leave:
2704 if (rc)
2705 do_deinit (app);
2706 return rc;