2005-10-07 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / app-openpgp.c
blob5625c729b53beffe359712ffdabf609829234532
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20 * $Id$
23 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29 #include <time.h>
31 #if GNUPG_MAJOR_VERSION == 1
32 /* This is used with GnuPG version < 1.9. The code has been source
33 copied from the current GnuPG >= 1.9 and is maintained over
34 there. */
35 #include "options.h"
36 #include "errors.h"
37 #include "memory.h"
38 #include "util.h"
39 #include "cardglue.h"
40 #else /* GNUPG_MAJOR_VERSION != 1 */
41 #include "scdaemon.h"
42 #endif /* GNUPG_MAJOR_VERSION != 1 */
44 #include "i18n.h"
45 #include "iso7816.h"
46 #include "app-common.h"
47 #include "tlv.h"
50 static struct {
51 int tag;
52 int constructed;
53 int get_from; /* Constructed DO with this DO or 0 for direct access. */
54 int binary;
55 int dont_cache;
56 int flush_on_error;
57 int get_immediate_in_v11; /* Enable a hack to bypass the cache of
58 this data object if it is used in 1.1
59 and later versions of the card. This
60 does not work with composite DO and is
61 currently only useful for the CHV
62 status bytes. */
63 char *desc;
64 } data_objects[] = {
65 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
66 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
67 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
68 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
69 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
70 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
71 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
72 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
73 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
74 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
75 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
76 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
77 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
78 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
79 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
80 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
81 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
82 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
83 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
84 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
85 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
86 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
87 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
88 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
89 { 0 }
93 /* One cache item for DOs. */
94 struct cache_s {
95 struct cache_s *next;
96 int tag;
97 size_t length;
98 unsigned char data[1];
102 /* Object with application (i.e. OpenPGP card) specific data. */
103 struct app_local_s {
104 /* A linked list with cached DOs. */
105 struct cache_s *cache;
107 /* Keep track of the public keys. */
108 struct
110 int read_done; /* True if we have at least tried to read them. */
111 unsigned char *key; /* This is a malloced buffer with a canonical
112 encoded S-expression encoding a public
113 key. Might be NULL if key is not
114 available. */
115 size_t keylen; /* The length of the above S-expression. Thsi
116 is usullay only required for corss checks
117 because the length of an S-expression is
118 implicitly available. */
119 } pk[3];
121 /* Keep track of card capabilities. */
122 struct
124 unsigned int get_challenge:1;
125 unsigned int key_import:1;
126 unsigned int change_force_chv:1;
127 unsigned int private_dos:1;
128 } extcap;
130 /* Flags used to control the application. */
131 struct
133 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
134 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
135 } flags;
140 /***** Local prototypes *****/
141 static unsigned long convert_sig_counter_value (const unsigned char *value,
142 size_t valuelen);
143 static unsigned long get_sig_counter (app_t app);
149 /* Deconstructor. */
150 static void
151 do_deinit (app_t app)
153 if (app && app->app_local)
155 struct cache_s *c, *c2;
156 int i;
158 for (c = app->app_local->cache; c; c = c2)
160 c2 = c->next;
161 xfree (c);
164 for (i=0; i < DIM (app->app_local->pk); i++)
166 xfree (app->app_local->pk[i].key);
167 app->app_local->pk[i].read_done = 0;
169 xfree (app->app_local);
170 app->app_local = NULL;
175 /* Wrapper around iso7816_get_data which first tries to get the data
176 from the cache. With GET_IMMEDIATE passed as true, the cache is
177 bypassed. */
178 static gpg_error_t
179 get_cached_data (app_t app, int tag,
180 unsigned char **result, size_t *resultlen,
181 int get_immediate)
183 gpg_error_t err;
184 int i;
185 unsigned char *p;
186 size_t len;
187 struct cache_s *c;
189 *result = NULL;
190 *resultlen = 0;
192 if (!get_immediate)
194 for (c=app->app_local->cache; c; c = c->next)
195 if (c->tag == tag)
197 if(c->length)
199 p = xtrymalloc (c->length);
200 if (!p)
201 return gpg_error (gpg_err_code_from_errno (errno));
202 memcpy (p, c->data, c->length);
203 *result = p;
206 *resultlen = c->length;
208 return 0;
212 err = iso7816_get_data (app->slot, tag, &p, &len);
213 if (err)
214 return err;
215 *result = p;
216 *resultlen = len;
218 /* Check whether we should cache this object. */
219 if (get_immediate)
220 return 0;
222 for (i=0; data_objects[i].tag; i++)
223 if (data_objects[i].tag == tag)
225 if (data_objects[i].dont_cache)
226 return 0;
227 break;
230 /* Okay, cache it. */
231 for (c=app->app_local->cache; c; c = c->next)
232 assert (c->tag != tag);
234 c = xtrymalloc (sizeof *c + len);
235 if (c)
237 memcpy (c->data, p, len);
238 c->length = len;
239 c->tag = tag;
240 c->next = app->app_local->cache;
241 app->app_local->cache = c;
244 return 0;
247 /* Remove DO at TAG from the cache. */
248 static void
249 flush_cache_item (app_t app, int tag)
251 struct cache_s *c, *cprev;
252 int i;
254 if (!app->app_local)
255 return;
257 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
258 if (c->tag == tag)
260 if (cprev)
261 cprev->next = c->next;
262 else
263 app->app_local->cache = c->next;
264 xfree (c);
266 for (c=app->app_local->cache; c ; c = c->next)
268 assert (c->tag != tag); /* Oops: duplicated entry. */
270 return;
273 /* Try again if we have an outer tag. */
274 for (i=0; data_objects[i].tag; i++)
275 if (data_objects[i].tag == tag && data_objects[i].get_from
276 && data_objects[i].get_from != tag)
277 flush_cache_item (app, data_objects[i].get_from);
280 /* Flush all entries from the cache which might be out of sync after
281 an error. */
282 static void
283 flush_cache_after_error (app_t app)
285 int i;
287 for (i=0; data_objects[i].tag; i++)
288 if (data_objects[i].flush_on_error)
289 flush_cache_item (app, data_objects[i].tag);
293 /* Flush the entire cache. */
294 static void
295 flush_cache (app_t app)
297 if (app && app->app_local)
299 struct cache_s *c, *c2;
301 for (c = app->app_local->cache; c; c = c2)
303 c2 = c->next;
304 xfree (c);
306 app->app_local->cache = NULL;
311 /* Get the DO identified by TAG from the card in SLOT and return a
312 buffer with its content in RESULT and NBYTES. The return value is
313 NULL if not found or a pointer which must be used to release the
314 buffer holding value. */
315 static void *
316 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
317 int *r_rc)
319 int rc, i;
320 unsigned char *buffer;
321 size_t buflen;
322 unsigned char *value;
323 size_t valuelen;
324 int dummyrc;
326 if (!r_rc)
327 r_rc = &dummyrc;
329 *result = NULL;
330 *nbytes = 0;
331 *r_rc = 0;
332 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
335 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
337 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
338 if (rc)
340 *r_rc = rc;
341 return NULL;
343 *result = buffer;
344 *nbytes = buflen;
345 return buffer;
348 value = NULL;
349 rc = -1;
350 if (data_objects[i].tag && data_objects[i].get_from)
352 rc = get_cached_data (app, data_objects[i].get_from,
353 &buffer, &buflen,
354 (data_objects[i].dont_cache
355 || data_objects[i].get_immediate_in_v11));
356 if (!rc)
358 const unsigned char *s;
360 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
361 if (!s)
362 value = NULL; /* not found */
363 else if (valuelen > buflen - (s - buffer))
365 log_error ("warning: constructed DO too short\n");
366 value = NULL;
367 xfree (buffer); buffer = NULL;
369 else
370 value = buffer + (s - buffer);
374 if (!value) /* Not in a constructed DO, try simple. */
376 rc = get_cached_data (app, tag, &buffer, &buflen,
377 (data_objects[i].dont_cache
378 || data_objects[i].get_immediate_in_v11));
379 if (!rc)
381 value = buffer;
382 valuelen = buflen;
386 if (!rc)
388 *nbytes = valuelen;
389 *result = value;
390 return buffer;
392 *r_rc = rc;
393 return NULL;
397 static void
398 dump_all_do (int slot)
400 int rc, i, j;
401 unsigned char *buffer;
402 size_t buflen;
404 for (i=0; data_objects[i].tag; i++)
406 if (data_objects[i].get_from)
407 continue;
409 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
410 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
412 else if (rc)
413 log_info ("DO `%s' not available: %s\n",
414 data_objects[i].desc, gpg_strerror (rc));
415 else
417 if (data_objects[i].binary)
419 log_info ("DO `%s': ", data_objects[i].desc);
420 log_printhex ("", buffer, buflen);
422 else
423 log_info ("DO `%s': `%.*s'\n",
424 data_objects[i].desc,
425 (int)buflen, buffer); /* FIXME: sanitize */
427 if (data_objects[i].constructed)
429 for (j=0; data_objects[j].tag; j++)
431 const unsigned char *value;
432 size_t valuelen;
434 if (j==i || data_objects[i].tag != data_objects[j].get_from)
435 continue;
436 value = find_tlv_unchecked (buffer, buflen,
437 data_objects[j].tag, &valuelen);
438 if (!value)
439 ; /* not found */
440 else if (valuelen > buflen - (value - buffer))
441 log_error ("warning: constructed DO too short\n");
442 else
444 if (data_objects[j].binary)
446 log_info ("DO `%s': ", data_objects[j].desc);
447 log_printhex ("", value, valuelen);
449 else
450 log_info ("DO `%s': `%.*s'\n",
451 data_objects[j].desc,
452 (int)valuelen, value); /* FIXME: sanitize */
457 xfree (buffer); buffer = NULL;
462 /* Count the number of bits, assuming the A represents an unsigned big
463 integer of length LEN bytes. */
464 static unsigned int
465 count_bits (const unsigned char *a, size_t len)
467 unsigned int n = len * 8;
468 int i;
470 for (; len && !*a; len--, a++, n -=8)
472 if (len)
474 for (i=7; i && !(*a & (1<<i)); i--)
475 n--;
477 return n;
480 /* GnuPG makes special use of the login-data DO, this fucntion parses
481 the login data to store the flags for later use. It may be called
482 at any time and should be called after changing the login-data DO.
484 Everything up to a LF is considered a mailbox or account name. If
485 the first LF is followed by DC4 (0x14) control sequence are
486 expected up to the next LF. Control sequences are separated by FS
487 (0x28) and consist of key=value pairs. There is one key defined:
489 F=<flags>
491 Were FLAGS is a plain hexadecimal number representing flag values.
492 The lsb is here the rightmost bit. Defined flags bits are:
494 Bit 0 = CHV1 and CHV2 are not syncronized
495 Bit 1 = CHV2 has been been set to the default PIN of "123456"
496 (this implies that bit 0 is also set).
499 static void
500 parse_login_data (app_t app)
502 unsigned char *buffer, *p;
503 size_t buflen, len;
504 void *relptr;
506 /* Set defaults. */
507 app->app_local->flags.no_sync = 0;
508 app->app_local->flags.def_chv2 = 0;
510 /* Read the DO. */
511 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
512 if (!relptr)
513 return; /* Ooops. */
514 for (; buflen; buflen--, buffer++)
515 if (*buffer == '\n')
516 break;
517 if (buflen < 2 || buffer[1] != '\x14')
518 return; /* No control sequences. */
519 buflen--;
520 buffer++;
523 buflen--;
524 buffer++;
525 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
527 /* Flags control sequence found. */
528 int lastdig = 0;
530 /* For now we are only interested in the last digit, so skip
531 any leading digits but bail out on invalid characters. */
532 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
533 lastdig = xtoi_1 (p);
534 if (len && !(*p == '\n' || *p == '\x18'))
535 goto next; /* Invalid characters in field. */
536 app->app_local->flags.no_sync = !!(lastdig & 1);
537 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
539 next:
540 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
541 if (*buffer == '\n')
542 buflen = 1;
544 while (buflen);
546 xfree (relptr);
549 /* Note, that FPR must be at least 20 bytes. */
550 static gpg_error_t
551 store_fpr (int slot, int keynumber, u32 timestamp,
552 const unsigned char *m, size_t mlen,
553 const unsigned char *e, size_t elen,
554 unsigned char *fpr, unsigned int card_version)
556 unsigned int n, nbits;
557 unsigned char *buffer, *p;
558 int rc;
560 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
562 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
565 n = 6 + 2 + mlen + 2 + elen;
566 p = buffer = xtrymalloc (3 + n);
567 if (!buffer)
568 return gpg_error_from_errno (errno);
570 *p++ = 0x99; /* ctb */
571 *p++ = n >> 8; /* 2 byte length header */
572 *p++ = n;
573 *p++ = 4; /* key packet version */
574 *p++ = timestamp >> 24;
575 *p++ = timestamp >> 16;
576 *p++ = timestamp >> 8;
577 *p++ = timestamp;
578 *p++ = 1; /* RSA */
579 nbits = count_bits (m, mlen);
580 *p++ = nbits >> 8;
581 *p++ = nbits;
582 memcpy (p, m, mlen); p += mlen;
583 nbits = count_bits (e, elen);
584 *p++ = nbits >> 8;
585 *p++ = nbits;
586 memcpy (p, e, elen); p += elen;
588 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
590 xfree (buffer);
592 rc = iso7816_put_data (slot, (card_version > 0x0007? 0xC7 : 0xC6)
593 + keynumber, fpr, 20);
594 if (rc)
595 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
597 if (!rc && card_version > 0x0100)
599 unsigned char buf[4];
601 buf[0] = timestamp >> 24;
602 buf[1] = timestamp >> 16;
603 buf[2] = timestamp >> 8;
604 buf[3] = timestamp;
606 rc = iso7816_put_data (slot, 0xCE + keynumber, buf, 4);
607 if (rc)
608 log_error (_("failed to store the creation date: %s\n"),
609 gpg_strerror (rc));
612 return rc;
616 static void
617 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
618 int number, const unsigned char *fpr)
620 int i;
621 char buf[41];
622 char numbuf[25];
624 for (i=0; i < 20 && !fpr[i]; i++)
626 if (i==20)
627 return; /* All zero. */
628 for (i=0; i< 20; i++)
629 sprintf (buf+2*i, "%02X", fpr[i]);
630 if (number == -1)
631 *numbuf = 0; /* Don't print the key number */
632 else
633 sprintf (numbuf, "%d", number);
634 send_status_info (ctrl, keyword,
635 numbuf, (size_t)strlen(numbuf),
636 buf, (size_t)strlen (buf), NULL, 0);
639 static void
640 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
641 int number, const unsigned char *stamp)
643 char numbuf1[50], numbuf2[50];
644 unsigned long value;
646 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
647 if (!value)
648 return;
649 sprintf (numbuf1, "%d", number);
650 sprintf (numbuf2, "%lu", value);
651 send_status_info (ctrl, keyword,
652 numbuf1, (size_t)strlen(numbuf1),
653 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
656 static void
657 send_key_data (ctrl_t ctrl, const char *name,
658 const unsigned char *a, size_t alen)
660 char *p, *buf = xmalloc (alen*2+1);
662 for (p=buf; alen; a++, alen--, p += 2)
663 sprintf (p, "%02X", *a);
665 send_status_info (ctrl, "KEY-DATA",
666 name, (size_t)strlen(name),
667 buf, (size_t)strlen (buf),
668 NULL, 0);
669 xfree (buf);
672 /* Implement the GETATTR command. This is similar to the LEARN
673 command but returns just one value via the status interface. */
674 static gpg_error_t
675 do_getattr (app_t app, ctrl_t ctrl, const char *name)
677 static struct {
678 const char *name;
679 int tag;
680 int special;
681 } table[] = {
682 { "DISP-NAME", 0x005B },
683 { "LOGIN-DATA", 0x005E },
684 { "DISP-LANG", 0x5F2D },
685 { "DISP-SEX", 0x5F35 },
686 { "PUBKEY-URL", 0x5F50 },
687 { "KEY-FPR", 0x00C5, 3 },
688 { "KEY-TIME", 0x00CD, 4 },
689 { "CA-FPR", 0x00C6, 3 },
690 { "CHV-STATUS", 0x00C4, 1 },
691 { "SIG-COUNTER", 0x0093, 2 },
692 { "SERIALNO", 0x004F, -1 },
693 { "AID", 0x004F },
694 { "EXTCAP", 0x0000, -2 },
695 { "PRIVATE-DO-1", 0x0101 },
696 { "PRIVATE-DO-2", 0x0102 },
697 { "PRIVATE-DO-3", 0x0103 },
698 { "PRIVATE-DO-4", 0x0104 },
699 { "$AUTHKEYID", 0x0000, -3 },
700 { "$DISPSERIALNO",0x0000, -4 },
701 { NULL, 0 }
703 int idx, i, rc;
704 void *relptr;
705 unsigned char *value;
706 size_t valuelen;
708 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
710 if (!table[idx].name)
711 return gpg_error (GPG_ERR_INV_NAME);
713 if (table[idx].special == -1)
715 /* The serial number is very special. We could have used the
716 AID DO to retrieve it, but we have it already in the app
717 context and the stamp argument is required anyway which we
718 can't by other means. The AID DO is available anyway but not
719 hex formatted. */
720 char *serial;
721 time_t stamp;
722 char tmp[50];
724 if (!app_get_serial_and_stamp (app, &serial, &stamp))
726 sprintf (tmp, "%lu", (unsigned long)stamp);
727 send_status_info (ctrl, "SERIALNO",
728 serial, strlen (serial),
729 tmp, strlen (tmp),
730 NULL, 0);
731 xfree (serial);
733 return 0;
735 if (table[idx].special == -2)
737 char tmp[50];
739 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d",
740 app->app_local->extcap.get_challenge,
741 app->app_local->extcap.key_import,
742 app->app_local->extcap.change_force_chv,
743 app->app_local->extcap.private_dos);
744 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
745 return 0;
747 if (table[idx].special == -3)
749 char const tmp[] = "OPENPGP.3";
750 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
751 return 0;
753 if (table[idx].special == -4)
755 char *serial;
756 time_t stamp;
758 if (!app_get_serial_and_stamp (app, &serial, &stamp))
760 if (strlen (serial) > 16+12)
762 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
763 xfree (serial);
764 return 0;
766 xfree (serial);
768 return gpg_error (GPG_ERR_INV_NAME);
771 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
772 if (relptr)
774 if (table[idx].special == 1)
776 char numbuf[7*23];
778 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
779 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
780 send_status_info (ctrl, table[idx].name,
781 numbuf, strlen (numbuf), NULL, 0);
783 else if (table[idx].special == 2)
785 char numbuf[50];
787 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
788 send_status_info (ctrl, table[idx].name,
789 numbuf, strlen (numbuf), NULL, 0);
791 else if (table[idx].special == 3)
793 if (valuelen >= 60)
794 for (i=0; i < 3; i++)
795 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
797 else if (table[idx].special == 4)
799 if (valuelen >= 12)
800 for (i=0; i < 3; i++)
801 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
803 else
804 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
806 xfree (relptr);
808 return rc;
811 /* Retrieve the fingerprint from the card inserted in SLOT and write
812 the according hex representation to FPR. Caller must have provide
813 a buffer at FPR of least 41 bytes. Returns 0 on success or an
814 error code. */
815 #if GNUPG_MAJOR_VERSION > 1
816 static gpg_error_t
817 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
819 gpg_error_t err = 0;
820 void *relptr;
821 unsigned char *value;
822 size_t valuelen;
823 int i;
825 assert (keyno >=0 && keyno <= 2);
827 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
828 if (relptr && valuelen >= 60)
830 for (i = 0; i < 20; i++)
831 sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
833 else
834 err = gpg_error (GPG_ERR_NOT_FOUND);
835 xfree (relptr);
836 return err;
838 #endif /*GNUPG_MAJOR_VERSION > 1*/
841 /* Retrieve the public key material for the RSA key, whose fingerprint
842 is FPR, from gpg output, which can be read through the stream FP.
843 The RSA modulus will be stored at the address of M and MLEN, the
844 public exponent at E and ELEN. Returns zero on success, an error
845 code on failure. Caller must release the allocated buffers at M
846 and E if the function returns success. */
847 #if GNUPG_MAJOR_VERSION > 1
848 static gpg_error_t
849 retrieve_key_material (FILE *fp, const char *hexkeyid,
850 const unsigned char **m, size_t *mlen,
851 const unsigned char **e, size_t *elen)
853 gcry_error_t err = 0;
854 char *line = NULL; /* read_line() buffer. */
855 size_t line_size = 0; /* Helper for for read_line. */
856 int found_key = 0; /* Helper to find a matching key. */
857 unsigned char *m_new = NULL;
858 unsigned char *e_new = NULL;
859 size_t m_new_n = 0;
860 size_t e_new_n = 0;
862 /* Loop over all records until we have found the subkey
863 corresponsing to the fingerprint. Inm general the first record
864 should be the pub record, but we don't rely on that. Given that
865 we only need to look at one key, it is sufficient to compare the
866 keyid so that we don't need to look at "fpr" records. */
867 for (;;)
869 char *p;
870 char *fields[6];
871 int nfields;
872 size_t max_length;
873 gcry_mpi_t mpi;
874 int i;
876 max_length = 4096;
877 i = read_line (fp, &line, &line_size, &max_length);
878 if (!i)
879 break; /* EOF. */
880 if (i < 0)
882 err = gpg_error_from_errno (errno);
883 goto leave; /* Error. */
885 if (!max_length)
887 err = gpg_error (GPG_ERR_TRUNCATED);
888 goto leave; /* Line truncated - we better stop processing. */
891 /* Parse the line into fields. */
892 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
894 fields[nfields] = p;
895 p = strchr (p, ':');
896 if (p)
897 *(p++) = 0;
899 if (!nfields)
900 continue; /* No fields at all - skip line. */
902 if (!found_key)
904 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
905 && nfields > 4 && !strcmp (fields[4], hexkeyid))
906 found_key = 1;
907 continue;
910 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
911 break; /* Next key - stop. */
913 if ( strcmp (fields[0], "pkd") )
914 continue; /* Not a key data record. */
915 i = 0; /* Avoid erroneous compiler warning. */
916 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
917 || (!i && m_new) || (i && e_new))
919 err = gpg_error (GPG_ERR_GENERAL);
920 goto leave; /* Error: Invalid key data record or not an RSA key. */
923 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
924 if (err)
925 mpi = NULL;
926 else if (!i)
927 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
928 else
929 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
930 gcry_mpi_release (mpi);
931 if (err)
932 goto leave;
935 if (m_new && e_new)
937 *m = m_new;
938 *mlen = m_new_n;
939 m_new = NULL;
940 *e = e_new;
941 *elen = e_new_n;
942 e_new = NULL;
944 else
945 err = gpg_error (GPG_ERR_GENERAL);
947 leave:
948 xfree (m_new);
949 xfree (e_new);
950 xfree (line);
951 return err;
953 #endif /*GNUPG_MAJOR_VERSION > 1*/
956 /* Get the public key for KEYNO and store it as an S-expresion with
957 the APP handle. On error that field gets cleared. If we already
958 know about the public key we will just return. Note that this does
959 not mean a key is available; this is soley indicated by the
960 presence of the app->app_local->pk[KEYNO-1].key field.
962 Note that GnuPG 1.x does not need this and it would be too time
963 consuming to send it just for the fun of it. However, given that we
964 use the same code in gpg 1.4, we can't use the gcry S-expresion
965 here but need to open encode it. */
966 #if GNUPG_MAJOR_VERSION > 1
967 static gpg_error_t
968 get_public_key (app_t app, int keyno)
970 gpg_error_t err = 0;
971 unsigned char *buffer;
972 const unsigned char *keydata, *m, *e;
973 size_t buflen, keydatalen, mlen, elen;
974 unsigned char *mbuf = NULL;
975 unsigned char *ebuf = NULL;
976 char *keybuf = NULL;
977 char *keybuf_p;
979 if (keyno < 1 || keyno > 3)
980 return gpg_error (GPG_ERR_INV_ID);
981 keyno--;
983 /* Already cached? */
984 if (app->app_local->pk[keyno].read_done)
985 return 0;
987 xfree (app->app_local->pk[keyno].key);
988 app->app_local->pk[keyno].key = NULL;
989 app->app_local->pk[keyno].keylen = 0;
991 m = e = NULL; /* (avoid cc warning) */
993 if (app->card_version > 0x0100)
995 /* We may simply read the public key out of these cards. */
996 err = iso7816_read_public_key
997 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
998 keyno == 1? "\xB8" : "\xA4"),
1000 &buffer, &buflen);
1001 if (err)
1003 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1004 goto leave;
1007 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1008 if (!keydata)
1010 err = gpg_error (GPG_ERR_CARD);
1011 log_error (_("response does not contain the public key data\n"));
1012 goto leave;
1015 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1016 if (!m)
1018 err = gpg_error (GPG_ERR_CARD);
1019 log_error (_("response does not contain the RSA modulus\n"));
1020 goto leave;
1024 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1025 if (!e)
1027 err = gpg_error (GPG_ERR_CARD);
1028 log_error (_("response does not contain the RSA public exponent\n"));
1029 goto leave;
1032 /* Prepend numbers with a 0 if needed. */
1033 if (mlen && (*m & 0x80))
1035 mbuf = xtrymalloc ( mlen + 1);
1036 if (!mbuf)
1038 err = gpg_error_from_errno (errno);
1039 goto leave;
1041 *mbuf = 0;
1042 memcpy (mbuf+1, m, mlen);
1043 mlen++;
1044 m = mbuf;
1046 if (elen && (*e & 0x80))
1048 ebuf = xtrymalloc ( elen + 1);
1049 if (!ebuf)
1051 err = gpg_error_from_errno (errno);
1052 goto leave;
1054 *ebuf = 0;
1055 memcpy (ebuf+1, e, elen);
1056 elen++;
1057 e = ebuf;
1061 else
1063 /* Due to a design problem in v1.0 cards we can't get the public
1064 key out of these cards without doing a verify on CHV3.
1065 Clearly that is not an option and thus we try to locate the
1066 key using an external helper.
1068 The helper we use here is gpg itself, which should know about
1069 the key in any case. */
1071 char fpr[41];
1072 char *hexkeyid;
1073 char *command = NULL;
1074 FILE *fp;
1075 int ret;
1077 buffer = NULL; /* We don't need buffer. */
1079 err = retrieve_fpr_from_card (app, keyno, fpr);
1080 if (err)
1082 log_error ("error while retrieving fpr from card: %s\n",
1083 gpg_strerror (err));
1084 goto leave;
1086 hexkeyid = fpr + 24;
1088 ret = asprintf (&command,
1089 "gpg --list-keys --with-colons --with-key-data '%s'",
1090 fpr);
1091 if (ret < 0)
1093 err = gpg_error_from_errno (errno);
1094 goto leave;
1097 fp = popen (command, "r");
1098 free (command);
1099 if (!fp)
1101 err = gpg_error_from_errno (errno);
1102 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1103 goto leave;
1106 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1107 fclose (fp);
1108 if (err)
1110 log_error ("error while retrieving key material through pipe: %s\n",
1111 gpg_strerror (err));
1112 goto leave;
1116 /* Allocate a buffer to construct the S-expression. */
1117 /* FIXME: We should provide a generalized S-expression creation
1118 mechanism. */
1119 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1120 if (!keybuf)
1122 err = gpg_error_from_errno (errno);
1123 goto leave;
1126 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1127 keybuf_p = keybuf + strlen (keybuf);
1128 memcpy (keybuf_p, m, mlen);
1129 keybuf_p += mlen;
1130 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1131 keybuf_p += strlen (keybuf_p);
1132 memcpy (keybuf_p, e, elen);
1133 keybuf_p += elen;
1134 strcpy (keybuf_p, ")))");
1135 keybuf_p += strlen (keybuf_p);
1137 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1138 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1140 leave:
1141 /* Set a flag to indicate that we tried to read the key. */
1142 app->app_local->pk[keyno].read_done = 1;
1144 xfree (buffer);
1145 xfree (mbuf);
1146 xfree (ebuf);
1147 return 0;
1149 #endif /* GNUPG_MAJOR_VERSION > 1 */
1153 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1154 This is used by the LEARN command. */
1155 static gpg_error_t
1156 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1158 gpg_error_t err = 0;
1159 /* Note that GnuPG 1.x does not need this and it would be too time
1160 consuming to send it just for the fun of it. */
1161 #if GNUPG_MAJOR_VERSION > 1
1162 unsigned char grip[20];
1163 char gripstr[41];
1164 char idbuf[50];
1165 int i;
1167 err = get_public_key (app, keyno);
1168 if (err)
1169 goto leave;
1171 assert (keyno >= 1 && keyno <= 3);
1172 if (!app->app_local->pk[keyno-1].key)
1173 goto leave; /* No such key - ignore. */
1175 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1176 app->app_local->pk[keyno-1].keylen,
1177 grip);
1178 if (err)
1179 goto leave;
1181 for (i=0; i < 20; i++)
1182 sprintf (gripstr+i*2, "%02X", grip[i]);
1184 sprintf (idbuf, "OPENPGP.%d", keyno);
1185 send_status_info (ctrl, "KEYPAIRINFO",
1186 gripstr, 40,
1187 idbuf, strlen (idbuf),
1188 NULL, (size_t)0);
1190 leave:
1191 #endif /* GNUPG_MAJOR_VERSION > 1 */
1193 return err;
1197 /* Handle the LEARN command for OpenPGP. */
1198 static gpg_error_t
1199 do_learn_status (app_t app, ctrl_t ctrl)
1201 do_getattr (app, ctrl, "EXTCAP");
1202 do_getattr (app, ctrl, "DISP-NAME");
1203 do_getattr (app, ctrl, "DISP-LANG");
1204 do_getattr (app, ctrl, "DISP-SEX");
1205 do_getattr (app, ctrl, "PUBKEY-URL");
1206 do_getattr (app, ctrl, "LOGIN-DATA");
1207 do_getattr (app, ctrl, "KEY-FPR");
1208 if (app->card_version > 0x0100)
1209 do_getattr (app, ctrl, "KEY-TIME");
1210 do_getattr (app, ctrl, "CA-FPR");
1211 do_getattr (app, ctrl, "CHV-STATUS");
1212 do_getattr (app, ctrl, "SIG-COUNTER");
1213 if (app->app_local->extcap.private_dos)
1215 do_getattr (app, ctrl, "PRIVATE-DO-1");
1216 do_getattr (app, ctrl, "PRIVATE-DO-2");
1217 if (app->did_chv2)
1218 do_getattr (app, ctrl, "PRIVATE-DO-3");
1219 if (app->did_chv3)
1220 do_getattr (app, ctrl, "PRIVATE-DO-4");
1222 send_keypair_info (app, ctrl, 1);
1223 send_keypair_info (app, ctrl, 2);
1224 send_keypair_info (app, ctrl, 3);
1225 return 0;
1229 /* Handle the READKEY command for OpenPGP. On success a canonical
1230 encoded S-expression with the public key will get stored at PK and
1231 its length (for assertions) at PKLEN; the caller must release that
1232 buffer. On error PK and PKLEN are not changed and an error code is
1233 returned. */
1234 static gpg_error_t
1235 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1237 #if GNUPG_MAJOR_VERSION > 1
1238 gpg_error_t err;
1239 int keyno;
1240 unsigned char *buf;
1242 if (!strcmp (keyid, "OPENPGP.1"))
1243 keyno = 1;
1244 else if (!strcmp (keyid, "OPENPGP.2"))
1245 keyno = 2;
1246 else if (!strcmp (keyid, "OPENPGP.3"))
1247 keyno = 3;
1248 else
1249 return gpg_error (GPG_ERR_INV_ID);
1251 err = get_public_key (app, keyno);
1252 if (err)
1253 return err;
1255 buf = app->app_local->pk[keyno-1].key;
1256 if (!buf)
1257 return gpg_error (GPG_ERR_NO_PUBKEY);
1258 *pklen = app->app_local->pk[keyno-1].keylen;;
1259 *pk = xtrymalloc (*pklen);
1260 if (!*pk)
1262 err = gpg_error_from_errno (errno);
1263 *pklen = 0;
1264 return err;
1266 memcpy (*pk, buf, *pklen);
1267 return 0;
1268 #else
1269 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1270 #endif
1275 /* Verify CHV2 if required. Depending on the configuration of the
1276 card CHV1 will also be verified. */
1277 static gpg_error_t
1278 verify_chv2 (app_t app,
1279 gpg_error_t (*pincb)(void*, const char *, char **),
1280 void *pincb_arg)
1282 int rc = 0;
1284 if (!app->did_chv2)
1286 char *pinvalue;
1288 rc = pincb (pincb_arg, "PIN", &pinvalue);
1289 if (rc)
1291 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1292 return rc;
1295 if (strlen (pinvalue) < 6)
1297 log_error (_("PIN for CHV%d is too short;"
1298 " minimum length is %d\n"), 2, 6);
1299 xfree (pinvalue);
1300 return gpg_error (GPG_ERR_BAD_PIN);
1303 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
1304 if (rc)
1306 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
1307 xfree (pinvalue);
1308 flush_cache_after_error (app);
1309 return rc;
1311 app->did_chv2 = 1;
1313 if (!app->did_chv1 && !app->force_chv1)
1315 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1316 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1317 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1318 if (rc)
1320 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1321 xfree (pinvalue);
1322 flush_cache_after_error (app);
1323 return rc;
1325 app->did_chv1 = 1;
1327 xfree (pinvalue);
1329 return rc;
1332 /* Verify CHV3 if required. */
1333 static gpg_error_t
1334 verify_chv3 (app_t app,
1335 gpg_error_t (*pincb)(void*, const char *, char **),
1336 void *pincb_arg)
1338 int rc = 0;
1340 #if GNUPG_MAJOR_VERSION != 1
1341 if (!opt.allow_admin)
1343 log_info (_("access to admin commands is not configured\n"));
1344 return gpg_error (GPG_ERR_EACCES);
1346 #endif
1348 if (!app->did_chv3)
1350 char *pinvalue;
1351 void *relptr;
1352 unsigned char *value;
1353 size_t valuelen;
1355 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1356 if (!relptr || valuelen < 7)
1358 log_error (_("error retrieving CHV status from card\n"));
1359 xfree (relptr);
1360 return gpg_error (GPG_ERR_CARD);
1362 if (value[6] == 0)
1364 log_info (_("card is permanently locked!\n"));
1365 xfree (relptr);
1366 return gpg_error (GPG_ERR_BAD_PIN);
1369 log_info(_("%d Admin PIN attempts remaining before card"
1370 " is permanently locked\n"), value[6]);
1371 xfree (relptr);
1373 /* TRANSLATORS: Do not translate the "|A|" prefix but
1374 keep it at the start of the string. We need this elsewhere
1375 to get some infos on the string. */
1376 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1377 if (rc)
1379 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1380 return rc;
1383 if (strlen (pinvalue) < 8)
1385 log_error (_("PIN for CHV%d is too short;"
1386 " minimum length is %d\n"), 3, 8);
1387 xfree (pinvalue);
1388 return gpg_error (GPG_ERR_BAD_PIN);
1391 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1392 xfree (pinvalue);
1393 if (rc)
1395 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1396 flush_cache_after_error (app);
1397 return rc;
1399 app->did_chv3 = 1;
1401 return rc;
1405 /* Handle the SETATTR operation. All arguments are already basically
1406 checked. */
1407 static gpg_error_t
1408 do_setattr (app_t app, const char *name,
1409 gpg_error_t (*pincb)(void*, const char *, char **),
1410 void *pincb_arg,
1411 const unsigned char *value, size_t valuelen)
1413 gpg_error_t rc;
1414 int idx;
1415 static struct {
1416 const char *name;
1417 int tag;
1418 int need_chv;
1419 int special;
1420 } table[] = {
1421 { "DISP-NAME", 0x005B, 3 },
1422 { "LOGIN-DATA", 0x005E, 3, 2 },
1423 { "DISP-LANG", 0x5F2D, 3 },
1424 { "DISP-SEX", 0x5F35, 3 },
1425 { "PUBKEY-URL", 0x5F50, 3 },
1426 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1427 { "CA-FPR-1", 0x00CA, 3 },
1428 { "CA-FPR-2", 0x00CB, 3 },
1429 { "CA-FPR-3", 0x00CC, 3 },
1430 { "PRIVATE-DO-1", 0x0101, 2 },
1431 { "PRIVATE-DO-2", 0x0102, 3 },
1432 { "PRIVATE-DO-3", 0x0103, 2 },
1433 { "PRIVATE-DO-4", 0x0104, 3 },
1434 { NULL, 0 }
1438 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1440 if (!table[idx].name)
1441 return gpg_error (GPG_ERR_INV_NAME);
1443 switch (table[idx].need_chv)
1445 case 2:
1446 rc = verify_chv2 (app, pincb, pincb_arg);
1447 break;
1448 case 3:
1449 rc = verify_chv3 (app, pincb, pincb_arg);
1450 break;
1451 default:
1452 rc = 0;
1454 if (rc)
1455 return rc;
1457 /* Flush the cache before writing it, so that the next get operation
1458 will reread the data from the card and thus get synced in case of
1459 errors (e.g. data truncated by the card). */
1460 flush_cache_item (app, table[idx].tag);
1461 rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
1462 if (rc)
1463 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1465 if (table[idx].special == 1)
1466 app->force_chv1 = (valuelen && *value == 0);
1467 else if (table[idx].special == 2)
1468 parse_login_data (app);
1470 return rc;
1474 /* Handle the PASSWD command. */
1475 static gpg_error_t
1476 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
1477 gpg_error_t (*pincb)(void*, const char *, char **),
1478 void *pincb_arg)
1480 int rc = 0;
1481 int chvno = atoi (chvnostr);
1482 char *pinvalue;
1484 if (reset_mode && chvno == 3)
1486 rc = gpg_error (GPG_ERR_INV_ID);
1487 goto leave;
1489 else if (reset_mode || chvno == 3)
1491 /* we always require that the PIN is entered. */
1492 app->did_chv3 = 0;
1493 rc = verify_chv3 (app, pincb, pincb_arg);
1494 if (rc)
1495 goto leave;
1497 else if (chvno == 1 || chvno == 2)
1499 /* CHV1 and CVH2 should always have the same value, thus we
1500 enforce it here. */
1501 int save_force = app->force_chv1;
1503 app->force_chv1 = 0;
1504 app->did_chv1 = 0;
1505 app->did_chv2 = 0;
1506 rc = verify_chv2 (app, pincb, pincb_arg);
1507 app->force_chv1 = save_force;
1508 if (rc)
1509 goto leave;
1511 else
1513 rc = gpg_error (GPG_ERR_INV_ID);
1514 goto leave;
1517 if (chvno == 3)
1518 app->did_chv3 = 0;
1519 else
1520 app->did_chv1 = app->did_chv2 = 0;
1522 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1523 keep it at the start of the string. We need this elsewhere
1524 to get some infos on the string. */
1525 rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1526 &pinvalue);
1527 if (rc)
1529 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1530 goto leave;
1533 if (reset_mode)
1535 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1536 pinvalue, strlen (pinvalue));
1537 if (!rc)
1538 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1539 pinvalue, strlen (pinvalue));
1541 else
1543 if (chvno == 1 || chvno == 2)
1545 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1546 pinvalue, strlen (pinvalue));
1547 if (!rc)
1548 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1549 pinvalue, strlen (pinvalue));
1551 else
1552 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1553 pinvalue, strlen (pinvalue));
1555 xfree (pinvalue);
1556 if (rc)
1557 flush_cache_after_error (app);
1559 leave:
1560 return rc;
1564 /* Check whether a key already exists. KEYIDX is the index of the key
1565 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1566 error returned if the key already exists. */
1567 static gpg_error_t
1568 does_key_exist (app_t app, int keyidx, int force)
1570 const unsigned char *fpr;
1571 unsigned char *buffer;
1572 size_t buflen, n;
1573 int i;
1575 assert (keyidx >=0 && keyidx <= 2);
1577 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
1579 log_error (_("error reading application data\n"));
1580 return gpg_error (GPG_ERR_GENERAL);
1582 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1583 if (!fpr || n < 60)
1585 log_error (_("error reading fingerprint DO\n"));
1586 xfree (buffer);
1587 return gpg_error (GPG_ERR_GENERAL);
1589 fpr += 20*keyidx;
1590 for (i=0; i < 20 && !fpr[i]; i++)
1592 xfree (buffer);
1593 if (i!=20 && !force)
1595 log_error (_("key already exists\n"));
1596 return gpg_error (GPG_ERR_EEXIST);
1598 else if (i!=20)
1599 log_info (_("existing key will be replaced\n"));
1600 else
1601 log_info (_("generating new key\n"));
1602 return 0;
1607 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1608 canonical encoded S-expression with the secret key in KEYDATA and
1609 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1610 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1611 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1612 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1613 the pinentry callback. */
1614 static gpg_error_t
1615 do_writekey (app_t app, ctrl_t ctrl,
1616 const char *keyid, unsigned int flags,
1617 gpg_error_t (*pincb)(void*, const char *, char **),
1618 void *pincb_arg,
1619 const unsigned char *keydata, size_t keydatalen)
1621 gpg_error_t err;
1622 int force = (flags & 1);
1623 int keyno;
1624 const unsigned char *buf, *tok;
1625 size_t buflen, toklen;
1626 int depth, last_depth1, last_depth2;
1627 const unsigned char *rsa_n = NULL;
1628 const unsigned char *rsa_e = NULL;
1629 const unsigned char *rsa_p = NULL;
1630 const unsigned char *rsa_q = NULL;
1631 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
1632 unsigned int nbits;
1633 unsigned char *template = NULL;
1634 unsigned char *tp;
1635 size_t template_len;
1636 unsigned char fprbuf[20];
1637 u32 created_at = 0;
1639 if (!strcmp (keyid, "OPENPGP.1"))
1640 keyno = 0;
1641 else if (!strcmp (keyid, "OPENPGP.2"))
1642 keyno = 1;
1643 else if (!strcmp (keyid, "OPENPGP.3"))
1644 keyno = 2;
1645 else
1646 return gpg_error (GPG_ERR_INV_ID);
1648 err = does_key_exist (app, keyno, force);
1649 if (err)
1650 return err;
1654 Parse the S-expression
1656 buf = keydata;
1657 buflen = keydatalen;
1658 depth = 0;
1659 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1660 goto leave;
1661 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1662 goto leave;
1663 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
1665 if (!tok)
1667 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
1668 log_info ("protected-private-key passed to writekey\n");
1669 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
1670 log_info ("shadowed-private-key passed to writekey\n");
1671 err = gpg_error (GPG_ERR_BAD_SECKEY);
1672 goto leave;
1674 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1675 goto leave;
1676 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1677 goto leave;
1678 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
1680 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
1681 goto leave;
1683 last_depth1 = depth;
1684 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1685 && depth && depth >= last_depth1)
1687 if (tok)
1689 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1690 goto leave;
1692 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1693 goto leave;
1694 if (tok && toklen == 1)
1696 const unsigned char **mpi;
1697 size_t *mpi_len;
1699 switch (*tok)
1701 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
1702 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
1703 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
1704 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
1705 default: mpi = NULL; mpi_len = NULL; break;
1707 if (mpi && *mpi)
1709 err = gpg_error (GPG_ERR_DUP_VALUE);
1710 goto leave;
1712 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1713 goto leave;
1714 if (tok && mpi)
1716 /* Strip off leading zero bytes and save. */
1717 for (;toklen && !*tok; toklen--, tok++)
1719 *mpi = tok;
1720 *mpi_len = toklen;
1723 /* Skip until end of list. */
1724 last_depth2 = depth;
1725 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1726 && depth && depth >= last_depth2)
1728 if (err)
1729 goto leave;
1731 /* Parse other attributes. */
1732 last_depth1 = depth;
1733 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1734 && depth && depth >= last_depth1)
1736 if (tok)
1738 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
1739 goto leave;
1741 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
1742 goto leave;
1743 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
1745 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
1746 goto leave;
1747 if (tok)
1749 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
1750 tok++, toklen--)
1751 created_at = created_at*10 + (*tok - '0');
1754 /* Skip until end of list. */
1755 last_depth2 = depth;
1756 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
1757 && depth && depth >= last_depth2)
1759 if (err)
1760 goto leave;
1764 /* Check that we have all parameters and that they match the card
1765 description. */
1766 if (!created_at)
1768 log_error (_("creation timestamp missing\n"));
1769 err = gpg_error (GPG_ERR_INV_VALUE);
1770 goto leave;
1772 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
1773 if (nbits != 1024)
1775 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1776 err = gpg_error (GPG_ERR_BAD_SECKEY);
1777 goto leave;
1779 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
1780 if (nbits < 2 || nbits > 32)
1782 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1783 32);
1784 err = gpg_error (GPG_ERR_BAD_SECKEY);
1785 goto leave;
1787 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
1788 if (nbits != 512)
1790 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1791 err = gpg_error (GPG_ERR_BAD_SECKEY);
1792 goto leave;
1794 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
1795 if (nbits != 512)
1797 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1798 err = gpg_error (GPG_ERR_BAD_SECKEY);
1799 goto leave;
1803 /* Build the private key template as described in section 4.3.3.6 of
1804 the OpenPGP card specs:
1805 0xC0 <length> public exponent
1806 0xC1 <length> prime p
1807 0xC2 <length> prime q
1809 assert (rsa_e_len <= 4);
1810 template_len = (1 + 1 + 4
1811 + 1 + 1 + rsa_p_len
1812 + 1 + 1 + rsa_q_len);
1813 template = tp = xtrymalloc_secure (template_len);
1814 if (!template)
1816 err = gpg_error_from_errno (errno);
1817 goto leave;
1819 *tp++ = 0xC0;
1820 *tp++ = 4;
1821 memcpy (tp, rsa_e, rsa_e_len);
1822 if (rsa_e_len < 4)
1824 /* Right justify E. */
1825 memmove (tp+4-rsa_e_len, tp, 4-rsa_e_len);
1826 memset (tp, 0, 4-rsa_e_len);
1828 tp += 4;
1830 *tp++ = 0xC1;
1831 *tp++ = rsa_p_len;
1832 memcpy (tp, rsa_p, rsa_p_len);
1833 tp += rsa_p_len;
1835 *tp++ = 0xC2;
1836 *tp++ = rsa_q_len;
1837 memcpy (tp, rsa_q, rsa_q_len);
1838 tp += rsa_q_len;
1840 assert (tp - template == template_len);
1843 /* Obviously we need to remove the cached public key. */
1844 xfree (app->app_local->pk[keyno].key);
1845 app->app_local->pk[keyno].key = NULL;
1846 app->app_local->pk[keyno].keylen = 0;
1847 app->app_local->pk[keyno].read_done = 0;
1849 /* Prepare for storing the key. */
1850 err = verify_chv3 (app, pincb, pincb_arg);
1851 if (err)
1852 goto leave;
1854 /* Store the key. */
1855 err = iso7816_put_data (app->slot,
1856 (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
1857 template, template_len);
1858 if (err)
1860 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
1861 goto leave;
1864 err = store_fpr (app->slot, keyno, created_at,
1865 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
1866 fprbuf, app->card_version);
1867 if (err)
1868 goto leave;
1871 leave:
1872 xfree (template);
1873 return err;
1877 /* Handle the GENKEY command. */
1878 static gpg_error_t
1879 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
1880 gpg_error_t (*pincb)(void*, const char *, char **),
1881 void *pincb_arg)
1883 int rc;
1884 char numbuf[30];
1885 unsigned char fprbuf[20];
1886 const unsigned char *keydata, *m, *e;
1887 unsigned char *buffer = NULL;
1888 size_t buflen, keydatalen, mlen, elen;
1889 time_t created_at;
1890 int keyno = atoi (keynostr);
1891 int force = (flags & 1);
1892 time_t start_at;
1894 if (keyno < 1 || keyno > 3)
1895 return gpg_error (GPG_ERR_INV_ID);
1896 keyno--;
1898 /* We flush the cache to increase the traffic before a key
1899 generation. This _might_ help a card to gather more entropy. */
1900 flush_cache (app);
1902 /* Obviously we need to remove the cached public key. */
1903 xfree (app->app_local->pk[keyno].key);
1904 app->app_local->pk[keyno].key = NULL;
1905 app->app_local->pk[keyno].keylen = 0;
1906 app->app_local->pk[keyno].read_done = 0;
1908 /* Check whether a key already exists. */
1909 rc = does_key_exist (app, keyno, force);
1910 if (rc)
1911 return rc;
1913 /* Prepare for key generation by verifying the ADmin PIN. */
1914 rc = verify_chv3 (app, pincb, pincb_arg);
1915 if (rc)
1916 goto leave;
1918 #if 1
1919 log_info (_("please wait while key is being generated ...\n"));
1920 start_at = time (NULL);
1921 rc = iso7816_generate_keypair
1922 #else
1923 #warning key generation temporary replaced by reading an existing key.
1924 rc = iso7816_read_public_key
1925 #endif
1926 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
1927 keyno == 1? "\xB8" : "\xA4"),
1929 &buffer, &buflen);
1930 if (rc)
1932 rc = gpg_error (GPG_ERR_CARD);
1933 log_error (_("generating key failed\n"));
1934 goto leave;
1936 log_info (_("key generation completed (%d seconds)\n"),
1937 (int)(time (NULL) - start_at));
1938 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1939 if (!keydata)
1941 rc = gpg_error (GPG_ERR_CARD);
1942 log_error (_("response does not contain the public key data\n"));
1943 goto leave;
1946 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1947 if (!m)
1949 rc = gpg_error (GPG_ERR_CARD);
1950 log_error (_("response does not contain the RSA modulus\n"));
1951 goto leave;
1953 /* log_printhex ("RSA n:", m, mlen); */
1954 send_key_data (ctrl, "n", m, mlen);
1956 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1957 if (!e)
1959 rc = gpg_error (GPG_ERR_CARD);
1960 log_error (_("response does not contain the RSA public exponent\n"));
1961 goto leave;
1963 /* log_printhex ("RSA e:", e, elen); */
1964 send_key_data (ctrl, "e", e, elen);
1966 created_at = gnupg_get_time ();
1967 sprintf (numbuf, "%lu", (unsigned long)created_at);
1968 send_status_info (ctrl, "KEY-CREATED-AT",
1969 numbuf, (size_t)strlen(numbuf), NULL, 0);
1971 rc = store_fpr (app->slot, keyno, (u32)created_at,
1972 m, mlen, e, elen, fprbuf, app->card_version);
1973 if (rc)
1974 goto leave;
1975 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1978 leave:
1979 xfree (buffer);
1980 return rc;
1984 static unsigned long
1985 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
1987 unsigned long ul;
1989 if (valuelen == 3 )
1990 ul = (value[0] << 16) | (value[1] << 8) | value[2];
1991 else
1993 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1994 ul = 0;
1996 return ul;
1999 static unsigned long
2000 get_sig_counter (app_t app)
2002 void *relptr;
2003 unsigned char *value;
2004 size_t valuelen;
2005 unsigned long ul;
2007 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2008 if (!relptr)
2009 return 0;
2010 ul = convert_sig_counter_value (value, valuelen);
2011 xfree (relptr);
2012 return ul;
2015 static gpg_error_t
2016 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2018 const unsigned char *fpr;
2019 unsigned char *buffer;
2020 size_t buflen, n;
2021 int rc, i;
2023 assert (keyno >= 1 && keyno <= 3);
2025 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
2026 if (rc)
2028 log_error (_("error reading application data\n"));
2029 return gpg_error (GPG_ERR_GENERAL);
2031 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2032 if (!fpr || n != 60)
2034 xfree (buffer);
2035 log_error (_("error reading fingerprint DO\n"));
2036 return gpg_error (GPG_ERR_GENERAL);
2038 fpr += (keyno-1)*20;
2039 for (i=0; i < 20; i++)
2040 if (sha1fpr[i] != fpr[i])
2042 xfree (buffer);
2043 return gpg_error (GPG_ERR_WRONG_SECKEY);
2045 xfree (buffer);
2046 return 0;
2050 /* If a fingerprint has been specified check it against the one on
2051 the card. This is allows for a meaningful error message in case
2052 the key on the card has been replaced but the shadow information
2053 known to gpg was not updated. If there is no fingerprint we
2054 assume that this is okay. */
2055 static gpg_error_t
2056 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2058 unsigned char tmp[20];
2059 const char *s;
2060 int n;
2062 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2064 if (n != 40)
2065 return gpg_error (GPG_ERR_INV_ID);
2066 else if (!*s)
2067 ; /* okay */
2068 else
2069 return gpg_error (GPG_ERR_INV_ID);
2071 for (s=fpr, n=0; n < 20; s += 2, n++)
2072 tmp[n] = xtoi_2 (s);
2073 return compare_fingerprint (app, keyno, tmp);
2078 /* Compute a digital signature on INDATA which is expected to be the
2079 raw message digest. For this application the KEYIDSTR consists of
2080 the serialnumber and the fingerprint delimited by a slash.
2082 Note that this fucntion may return the error code
2083 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2084 not match the one required for the requested action (e.g. the
2085 serial number does not match). */
2086 static gpg_error_t
2087 do_sign (app_t app, const char *keyidstr, int hashalgo,
2088 gpg_error_t (*pincb)(void*, const char *, char **),
2089 void *pincb_arg,
2090 const void *indata, size_t indatalen,
2091 unsigned char **outdata, size_t *outdatalen )
2093 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2094 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2095 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2096 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2097 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2098 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2099 int rc;
2100 unsigned char data[35];
2101 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2102 const char *s;
2103 int n;
2104 const char *fpr = NULL;
2105 unsigned long sigcount;
2107 if (!keyidstr || !*keyidstr)
2108 return gpg_error (GPG_ERR_INV_VALUE);
2109 if (indatalen == 20)
2111 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
2112 && !memcmp (indata, sha1_prefix, 15))
2114 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
2115 && !memcmp (indata, rmd160_prefix, 15))
2117 else
2118 return gpg_error (GPG_ERR_INV_VALUE);
2120 /* Check whether an OpenPGP card of any version has been requested. */
2121 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2122 return gpg_error (GPG_ERR_INV_ID);
2124 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2126 if (n != 32)
2127 return gpg_error (GPG_ERR_INV_ID);
2128 else if (!*s)
2129 ; /* no fingerprint given: we allow this for now. */
2130 else if (*s == '/')
2131 fpr = s + 1;
2132 else
2133 return gpg_error (GPG_ERR_INV_ID);
2135 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2136 tmp_sn[n] = xtoi_2 (s);
2138 if (app->serialnolen != 16)
2139 return gpg_error (GPG_ERR_INV_CARD);
2140 if (memcmp (app->serialno, tmp_sn, 16))
2141 return gpg_error (GPG_ERR_WRONG_CARD);
2143 /* If a fingerprint has been specified check it against the one on
2144 the card. This is allows for a meaningful error message in case
2145 the key on the card has been replaced but the shadow information
2146 known to gpg was not updated. If there is no fingerprint, gpg
2147 will detect a bogus signature anyway due to the
2148 verify-after-signing feature. */
2149 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2150 if (rc)
2151 return rc;
2153 if (hashalgo == GCRY_MD_SHA1)
2154 memcpy (data, sha1_prefix, 15);
2155 else if (hashalgo == GCRY_MD_RMD160)
2156 memcpy (data, rmd160_prefix, 15);
2157 else
2158 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2159 memcpy (data+15, indata, indatalen);
2161 sigcount = get_sig_counter (app);
2162 log_info (_("signatures created so far: %lu\n"), sigcount);
2164 if (!app->did_chv1 || app->force_chv1 )
2166 char *pinvalue;
2169 char *prompt;
2170 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
2172 prompt = malloc (strlen (PROMPTSTRING) + 50);
2173 if (!prompt)
2174 return gpg_error_from_errno (errno);
2175 sprintf (prompt, PROMPTSTRING, sigcount);
2176 rc = pincb (pincb_arg, prompt, &pinvalue);
2177 free (prompt);
2178 #undef PROMPTSTRING
2180 if (rc)
2182 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
2183 return rc;
2186 if (strlen (pinvalue) < 6)
2188 log_error (_("PIN for CHV%d is too short;"
2189 " minimum length is %d\n"), 1, 6);
2190 xfree (pinvalue);
2191 return gpg_error (GPG_ERR_BAD_PIN);
2194 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
2195 if (rc)
2197 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
2198 xfree (pinvalue);
2199 flush_cache_after_error (app);
2200 return rc;
2202 app->did_chv1 = 1;
2203 if (!app->did_chv2)
2205 /* We should also verify CHV2. */
2206 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2207 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2208 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2209 if (rc)
2211 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2212 xfree (pinvalue);
2213 flush_cache_after_error (app);
2214 return rc;
2216 app->did_chv2 = 1;
2218 xfree (pinvalue);
2221 rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
2222 return rc;
2225 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2226 on INDATA which is expected to be the raw message digest. For this
2227 application the KEYIDSTR consists of the serialnumber and the
2228 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2229 be given.
2231 Note that this function may return the error code
2232 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2233 not match the one required for the requested action (e.g. the
2234 serial number does not match). */
2235 static gpg_error_t
2236 do_auth (app_t app, const char *keyidstr,
2237 gpg_error_t (*pincb)(void*, const char *, char **),
2238 void *pincb_arg,
2239 const void *indata, size_t indatalen,
2240 unsigned char **outdata, size_t *outdatalen )
2242 int rc;
2243 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2244 const char *s;
2245 int n;
2246 const char *fpr = NULL;
2248 if (!keyidstr || !*keyidstr)
2249 return gpg_error (GPG_ERR_INV_VALUE);
2250 if (indatalen > 50) /* For a 1024 bit key. */
2251 return gpg_error (GPG_ERR_INV_VALUE);
2253 /* Check whether an OpenPGP card of any version has been requested. */
2254 if (!strcmp (keyidstr, "OPENPGP.3"))
2256 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2257 return gpg_error (GPG_ERR_INV_ID);
2258 else
2260 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2262 if (n != 32)
2263 return gpg_error (GPG_ERR_INV_ID);
2264 else if (!*s)
2265 ; /* no fingerprint given: we allow this for now. */
2266 else if (*s == '/')
2267 fpr = s + 1;
2268 else
2269 return gpg_error (GPG_ERR_INV_ID);
2271 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2272 tmp_sn[n] = xtoi_2 (s);
2274 if (app->serialnolen != 16)
2275 return gpg_error (GPG_ERR_INV_CARD);
2276 if (memcmp (app->serialno, tmp_sn, 16))
2277 return gpg_error (GPG_ERR_WRONG_CARD);
2280 /* If a fingerprint has been specified check it against the one on
2281 the card. This is allows for a meaningful error message in case
2282 the key on the card has been replaced but the shadow information
2283 known to gpg was not updated. If there is no fingerprint, gpg
2284 will detect a bogus signature anyway due to the
2285 verify-after-signing feature. */
2286 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
2287 if (rc)
2288 return rc;
2290 rc = verify_chv2 (app, pincb, pincb_arg);
2291 if (!rc)
2292 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
2293 outdata, outdatalen);
2294 return rc;
2298 static gpg_error_t
2299 do_decipher (app_t app, const char *keyidstr,
2300 gpg_error_t (*pincb)(void*, const char *, char **),
2301 void *pincb_arg,
2302 const void *indata, size_t indatalen,
2303 unsigned char **outdata, size_t *outdatalen )
2305 int rc;
2306 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2307 const char *s;
2308 int n;
2309 const char *fpr = NULL;
2311 if (!keyidstr || !*keyidstr || !indatalen)
2312 return gpg_error (GPG_ERR_INV_VALUE);
2314 /* Check whether an OpenPGP card of any version has been requested. */
2315 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2316 return gpg_error (GPG_ERR_INV_ID);
2318 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2320 if (n != 32)
2321 return gpg_error (GPG_ERR_INV_ID);
2322 else if (!*s)
2323 ; /* no fingerprint given: we allow this for now. */
2324 else if (*s == '/')
2325 fpr = s + 1;
2326 else
2327 return gpg_error (GPG_ERR_INV_ID);
2329 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2330 tmp_sn[n] = xtoi_2 (s);
2332 if (app->serialnolen != 16)
2333 return gpg_error (GPG_ERR_INV_CARD);
2334 if (memcmp (app->serialno, tmp_sn, 16))
2335 return gpg_error (GPG_ERR_WRONG_CARD);
2337 /* If a fingerprint has been specified check it against the one on
2338 the card. This is allows for a meaningful error message in case
2339 the key on the card has been replaced but the shadow information
2340 known to gpg was not updated. If there is no fingerprint, the
2341 decryption will won't produce the right plaintext anyway. */
2342 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
2343 if (rc)
2344 return rc;
2346 rc = verify_chv2 (app, pincb, pincb_arg);
2347 if (!rc)
2348 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
2349 outdata, outdatalen);
2350 return rc;
2354 /* Perform a simple verify operation for CHV1 and CHV2, so that
2355 further operations won't ask for CHV2 and it is possible to do a
2356 cheap check on the PIN: If there is something wrong with the PIN
2357 entry system, only the regular CHV will get blocked and not the
2358 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2359 optional fingerprint part will be ignored.
2361 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2362 the "[CHV3]" being a literal string: The Admin Pin is checked if
2363 and only if the retry counter is still at 3. */
2364 static gpg_error_t
2365 do_check_pin (app_t app, const char *keyidstr,
2366 gpg_error_t (*pincb)(void*, const char *, char **),
2367 void *pincb_arg)
2369 unsigned char tmp_sn[20];
2370 const char *s;
2371 int n;
2372 int admin_pin = 0;
2374 if (!keyidstr || !*keyidstr)
2375 return gpg_error (GPG_ERR_INV_VALUE);
2377 /* Check whether an OpenPGP card of any version has been requested. */
2378 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2379 return gpg_error (GPG_ERR_INV_ID);
2381 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2383 if (n != 32)
2384 return gpg_error (GPG_ERR_INV_ID);
2385 else if (!*s)
2386 ; /* No fingerprint given: we allow this for now. */
2387 else if (*s == '/')
2388 ; /* We ignore a fingerprint. */
2389 else if (!strcmp (s, "[CHV3]") )
2390 admin_pin = 1;
2391 else
2392 return gpg_error (GPG_ERR_INV_ID);
2394 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2395 tmp_sn[n] = xtoi_2 (s);
2397 if (app->serialnolen != 16)
2398 return gpg_error (GPG_ERR_INV_CARD);
2399 if (memcmp (app->serialno, tmp_sn, 16))
2400 return gpg_error (GPG_ERR_WRONG_CARD);
2402 /* Yes, there is a race conditions: The user might pull the card
2403 right here and we won't notice that. However this is not a
2404 problem and the check above is merely for a graceful failure
2405 between operations. */
2407 if (admin_pin)
2409 void *relptr;
2410 unsigned char *value;
2411 size_t valuelen;
2412 int count;
2414 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2415 if (!relptr || valuelen < 7)
2417 log_error (_("error retrieving CHV status from card\n"));
2418 xfree (relptr);
2419 return gpg_error (GPG_ERR_CARD);
2421 count = value[6];
2422 xfree (relptr);
2424 if (!count)
2426 log_info (_("card is permanently locked!\n"));
2427 return gpg_error (GPG_ERR_BAD_PIN);
2429 else if (value[6] < 3)
2431 log_info (_("verification of Admin PIN is currently prohibited "
2432 "through this command\n"));
2433 return gpg_error (GPG_ERR_GENERAL);
2436 app->did_chv3 = 0; /* Force verification. */
2437 return verify_chv3 (app, pincb, pincb_arg);
2439 else
2440 return verify_chv2 (app, pincb, pincb_arg);
2446 /* Select the OpenPGP application on the card in SLOT. This function
2447 must be used before any other OpenPGP application functions. */
2448 gpg_error_t
2449 app_select_openpgp (app_t app)
2451 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2452 int slot = app->slot;
2453 int rc;
2454 unsigned char *buffer;
2455 size_t buflen;
2456 void *relptr;
2458 rc = iso7816_select_application (slot, aid, sizeof aid);
2459 if (!rc)
2461 unsigned int manufacturer;
2463 app->apptype = "OPENPGP";
2465 app->did_chv1 = 0;
2466 app->did_chv2 = 0;
2467 app->did_chv3 = 0;
2468 app->app_local = NULL;
2470 /* The OpenPGP card returns the serial number as part of the
2471 AID; because we prefer to use OpenPGP serial numbers, we
2472 replace a possibly already set one from a EF.GDO with this
2473 one. Note, that for current OpenPGP cards, no EF.GDO exists
2474 and thus it won't matter at all. */
2475 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
2476 if (rc)
2477 goto leave;
2478 if (opt.verbose)
2480 log_info ("AID: ");
2481 log_printhex ("", buffer, buflen);
2484 app->card_version = buffer[6] << 8;
2485 app->card_version |= buffer[7];
2486 manufacturer = (buffer[8]<<8 | buffer[9]);
2488 xfree (app->serialno);
2489 app->serialno = buffer;
2490 app->serialnolen = buflen;
2491 buffer = NULL;
2492 app->app_local = xtrycalloc (1, sizeof *app->app_local);
2493 if (!app->app_local)
2495 rc = gpg_error (gpg_err_code_from_errno (errno));
2496 goto leave;
2499 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
2500 if (!relptr)
2502 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2503 "CHV Status Bytes");
2504 goto leave;
2506 app->force_chv1 = (buflen && *buffer == 0);
2507 xfree (relptr);
2509 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
2510 if (!relptr)
2512 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2513 "Extended Capability Flags" );
2514 goto leave;
2516 if (buflen)
2518 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
2519 app->app_local->extcap.key_import = !!(*buffer & 0x20);
2520 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
2521 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
2523 xfree (relptr);
2525 /* Some of the first cards accidently don't set the
2526 CHANGE_FORCE_CHV bit but allow it anyway. */
2527 if (app->card_version <= 0x0100 && manufacturer == 1)
2528 app->app_local->extcap.change_force_chv = 1;
2530 parse_login_data (app);
2532 if (opt.verbose > 1)
2533 dump_all_do (slot);
2535 app->fnc.deinit = do_deinit;
2536 app->fnc.learn_status = do_learn_status;
2537 app->fnc.readkey = do_readkey;
2538 app->fnc.getattr = do_getattr;
2539 app->fnc.setattr = do_setattr;
2540 app->fnc.writekey = do_writekey;
2541 app->fnc.genkey = do_genkey;
2542 app->fnc.sign = do_sign;
2543 app->fnc.auth = do_auth;
2544 app->fnc.decipher = do_decipher;
2545 app->fnc.change_pin = do_change_pin;
2546 app->fnc.check_pin = do_check_pin;
2549 leave:
2550 if (rc)
2551 do_deinit (app);
2552 return rc;