2005-04-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / app-openpgp.c
blob0d80c41a76cd0f0d01d9fe13dd2b6908ae2d962c
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 (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 (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 int
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 (gpg_err_code_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 int
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 { NULL, 0 }
701 int idx, i, rc;
702 void *relptr;
703 unsigned char *value;
704 size_t valuelen;
706 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
708 if (!table[idx].name)
709 return gpg_error (GPG_ERR_INV_NAME);
711 if (table[idx].special == -1)
713 /* The serial number is very special. We could have used the
714 AID DO to retrieve it, but we have it already in the app
715 context and the stamp argument is required anyway which we
716 can't by other means. The AID DO is available anyway but not
717 hex formatted. */
718 char *serial;
719 time_t stamp;
720 char tmp[50];
722 if (!app_get_serial_and_stamp (app, &serial, &stamp))
724 sprintf (tmp, "%lu", (unsigned long)stamp);
725 send_status_info (ctrl, "SERIALNO",
726 serial, strlen (serial),
727 tmp, strlen (tmp),
728 NULL, 0);
729 xfree (serial);
731 return 0;
733 if (table[idx].special == -2)
735 char tmp[50];
737 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d",
738 app->app_local->extcap.get_challenge,
739 app->app_local->extcap.key_import,
740 app->app_local->extcap.change_force_chv,
741 app->app_local->extcap.private_dos);
742 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
743 return 0;
746 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
747 if (relptr)
749 if (table[idx].special == 1)
751 char numbuf[7*23];
753 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
754 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
755 send_status_info (ctrl, table[idx].name,
756 numbuf, strlen (numbuf), NULL, 0);
758 else if (table[idx].special == 2)
760 char numbuf[50];
762 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
763 send_status_info (ctrl, table[idx].name,
764 numbuf, strlen (numbuf), NULL, 0);
766 else if (table[idx].special == 3)
768 if (valuelen >= 60)
769 for (i=0; i < 3; i++)
770 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
772 else if (table[idx].special == 4)
774 if (valuelen >= 12)
775 for (i=0; i < 3; i++)
776 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
778 else
779 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
781 xfree (relptr);
783 return rc;
786 /* Retrieve the fingerprint from the card inserted in SLOT and write
787 the according hex representation to FPR. Caller must have provide
788 a buffer at FPR of least 41 bytes. Returns 0 on success or an
789 error code. */
790 #if GNUPG_MAJOR_VERSION > 1
791 static gpg_error_t
792 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
794 gpg_error_t err = 0;
795 void *relptr;
796 unsigned char *value;
797 size_t valuelen;
798 int i;
800 assert (keyno >=0 && keyno <= 2);
802 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
803 if (relptr && valuelen >= 60)
805 for (i = 0; i < 20; i++)
806 sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
808 else
809 err = gpg_error (GPG_ERR_NOT_FOUND);
810 xfree (relptr);
811 return err;
813 #endif /*GNUPG_MAJOR_VERSION > 1*/
816 /* Retrieve the public key material for the RSA key, whose fingerprint
817 is FPR, from gpg output, which can be read through the stream FP.
818 The RSA modulus will be stored at the address of M and MLEN, the
819 public exponent at E and ELEN. Returns zero on success, an error
820 code on failure. Caller must release the allocated buffers at M
821 and E if the function returns success. */
822 #if GNUPG_MAJOR_VERSION > 1
823 static gpg_error_t
824 retrieve_key_material (FILE *fp, const char *hexkeyid,
825 const unsigned char **m, size_t *mlen,
826 const unsigned char **e, size_t *elen)
828 gcry_error_t err = 0;
829 char *line = NULL; /* read_line() buffer. */
830 size_t line_size = 0; /* Helper for for read_line. */
831 int found_key = 0; /* Helper to find a matching key. */
832 unsigned char *m_new = NULL;
833 unsigned char *e_new = NULL;
834 size_t m_new_n = 0;
835 size_t e_new_n = 0;
837 /* Loop over all records until we have found the subkey
838 corresponsing to the fingerprint. Inm general the first record
839 should be the pub record, but we don't rely on that. Given that
840 we only need to look at one key, it is sufficient to compare the
841 keyid so that we don't need to look at "fpr" records. */
842 for (;;)
844 char *p;
845 char *fields[6];
846 int nfields;
847 size_t max_length;
848 gcry_mpi_t mpi;
849 int i;
851 max_length = 4096;
852 i = read_line (fp, &line, &line_size, &max_length);
853 if (!i)
854 break; /* EOF. */
855 if (i < 0)
857 err = gpg_error_from_errno (errno);
858 goto leave; /* Error. */
860 if (!max_length)
862 err = gpg_error (GPG_ERR_TRUNCATED);
863 goto leave; /* Line truncated - we better stop processing. */
866 /* Parse the line into fields. */
867 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
869 fields[nfields] = p;
870 p = strchr (p, ':');
871 if (p)
872 *(p++) = 0;
874 if (!nfields)
875 continue; /* No fields at all - skip line. */
877 if (!found_key)
879 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
880 && nfields > 4 && !strcmp (fields[4], hexkeyid))
881 found_key = 1;
882 continue;
885 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
886 break; /* Next key - stop. */
888 if ( strcmp (fields[0], "pkd") )
889 continue; /* Not a key data record. */
890 i = 0; /* Avoid erroneous compiler warning. */
891 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
892 || (!i && m_new) || (i && e_new))
894 err = gpg_error (GPG_ERR_GENERAL);
895 goto leave; /* Error: Invalid key data record or not an RSA key. */
898 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
899 if (err)
900 mpi = NULL;
901 else if (!i)
902 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
903 else
904 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
905 gcry_mpi_release (mpi);
906 if (err)
907 goto leave;
910 if (m_new && e_new)
912 *m = m_new;
913 *mlen = m_new_n;
914 m_new = NULL;
915 *e = e_new;
916 *elen = e_new_n;
917 e_new = NULL;
919 else
920 err = gpg_error (GPG_ERR_GENERAL);
922 leave:
923 xfree (m_new);
924 xfree (e_new);
925 xfree (line);
926 return err;
928 #endif /*GNUPG_MAJOR_VERSION > 1*/
931 /* Get the public key for KEYNO and store it as an S-expresion with
932 the APP handle. On error that field gets cleared. If we already
933 know about the public key we will just return. Note that this does
934 not mean a key is available; this is soley indicated by the
935 presence of the app->app_local->pk[KEYNO-1].key field.
937 Note that GnuPG 1.x does not need this and it would be too time
938 consuming to send it just for the fun of it. However, given that we
939 use the same code in gpg 1.4, we can't use the gcry S-expresion
940 here but need to open encode it. */
941 #if GNUPG_MAJOR_VERSION > 1
942 static gpg_error_t
943 get_public_key (app_t app, int keyno)
945 gpg_error_t err = 0;
946 unsigned char *buffer;
947 const unsigned char *keydata, *m, *e;
948 size_t buflen, keydatalen, mlen, elen;
949 unsigned char *mbuf = NULL;
950 unsigned char *ebuf = NULL;
951 unsigned char *keybuf = NULL;
952 unsigned char *keybuf_p;
954 if (keyno < 1 || keyno > 3)
955 return gpg_error (GPG_ERR_INV_ID);
956 keyno--;
958 /* Already cached? */
959 if (app->app_local->pk[keyno].read_done)
960 return 0;
962 xfree (app->app_local->pk[keyno].key);
963 app->app_local->pk[keyno].key = NULL;
964 app->app_local->pk[keyno].keylen = 0;
966 if (app->card_version > 0x0100)
968 /* We may simply read the public key out of these cards. */
969 err = iso7816_read_public_key (app->slot,
970 keyno == 0? "\xB6" :
971 keyno == 1? "\xB8" : "\xA4",
973 &buffer, &buflen);
974 if (err)
976 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
977 goto leave;
980 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
981 if (!keydata)
983 err = gpg_error (GPG_ERR_CARD);
984 log_error (_("response does not contain the public key data\n"));
985 goto leave;
988 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
989 if (!m)
991 err = gpg_error (GPG_ERR_CARD);
992 log_error (_("response does not contain the RSA modulus\n"));
993 goto leave;
997 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
998 if (!e)
1000 err = gpg_error (GPG_ERR_CARD);
1001 log_error (_("response does not contain the RSA public exponent\n"));
1002 goto leave;
1005 /* Prepend numbers with a 0 if needed. */
1006 if (mlen && (*m & 0x80))
1008 mbuf = xtrymalloc ( mlen + 1);
1009 if (!mbuf)
1011 err = gpg_error_from_errno (errno);
1012 goto leave;
1014 *mbuf = 0;
1015 memcpy (mbuf+1, m, mlen);
1016 mlen++;
1017 m = mbuf;
1019 if (elen && (*e & 0x80))
1021 ebuf = xtrymalloc ( elen + 1);
1022 if (!ebuf)
1024 err = gpg_error_from_errno (errno);
1025 goto leave;
1027 *ebuf = 0;
1028 memcpy (ebuf+1, e, elen);
1029 elen++;
1030 e = ebuf;
1034 else
1036 /* Due to a design problem in v1.0 cards we can't get the public
1037 key out of these cards without doing a verify on CHV3.
1038 Clearly that is not an option and thus we try to locate the
1039 key using an external helper.
1041 The helper we use here is gpg itself, which should know about
1042 the key in any case. */
1044 char fpr[41];
1045 char *hexkeyid;
1046 char *command = NULL;
1047 FILE *fp;
1048 int ret;
1050 buffer = NULL; /* We don't need buffer. */
1052 err = retrieve_fpr_from_card (app, keyno, fpr);
1053 if (err)
1055 log_error ("error while retrieving fpr from card: %s\n",
1056 gpg_strerror (err));
1057 goto leave;
1059 hexkeyid = fpr + 24;
1061 ret = asprintf (&command,
1062 "gpg --list-keys --with-colons --with-key-data '%s'",
1063 fpr);
1064 if (ret < 0)
1066 err = gpg_error_from_errno (errno);
1067 goto leave;
1070 fp = popen (command, "r");
1071 free (command);
1072 if (!fp)
1074 err = gpg_error_from_errno (errno);
1075 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1076 goto leave;
1079 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1080 fclose (fp);
1081 if (err)
1083 log_error ("error while retrieving key material through pipe: %s\n",
1084 gpg_strerror (err));
1085 goto leave;
1089 /* Allocate a buffer to construct the S-expression. */
1090 /* FIXME: We should provide a generalized S-expression creation
1091 mechanism. */
1092 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1093 if (!keybuf)
1095 err = gpg_error_from_errno (errno);
1096 goto leave;
1099 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1100 keybuf_p = keybuf + strlen (keybuf);
1101 memcpy (keybuf_p, m, mlen);
1102 keybuf_p += mlen;
1103 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1104 keybuf_p += strlen (keybuf_p);
1105 memcpy (keybuf_p, e, elen);
1106 keybuf_p += elen;
1107 strcpy (keybuf_p, ")))");
1108 keybuf_p += strlen (keybuf_p);
1110 app->app_local->pk[keyno].key = keybuf;
1111 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1113 leave:
1114 /* Set a flag to indicate that we tried to read the key. */
1115 app->app_local->pk[keyno].read_done = 1;
1117 xfree (buffer);
1118 xfree (mbuf);
1119 xfree (ebuf);
1120 return 0;
1122 #endif /* GNUPG_MAJOR_VERSION > 1 */
1126 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1127 This is used by the LEARN command. */
1128 static gpg_error_t
1129 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1131 gpg_error_t err = 0;
1132 /* Note that GnuPG 1.x does not need this and it would be too time
1133 consuming to send it just for the fun of it. */
1134 #if GNUPG_MAJOR_VERSION > 1
1135 unsigned char grip[20];
1136 char gripstr[41];
1137 char idbuf[50];
1138 int i;
1140 err = get_public_key (app, keyno);
1141 if (err)
1142 goto leave;
1144 assert (keyno >= 1 && keyno <= 3);
1145 if (!app->app_local->pk[keyno-1].key)
1146 goto leave; /* No such key - ignore. */
1148 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1149 app->app_local->pk[keyno-1].keylen,
1150 grip);
1151 if (err)
1152 goto leave;
1154 for (i=0; i < 20; i++)
1155 sprintf (gripstr+i*2, "%02X", grip[i]);
1157 sprintf (idbuf, "OPENPGP.%d", keyno);
1158 send_status_info (ctrl, "KEYPAIRINFO",
1159 gripstr, 40,
1160 idbuf, strlen (idbuf),
1161 NULL, (size_t)0);
1163 leave:
1164 #endif /* GNUPG_MAJOR_VERSION > 1 */
1166 return err;
1170 /* Handle the LEARN command for OpenPGP. */
1171 static int
1172 do_learn_status (app_t app, ctrl_t ctrl)
1174 do_getattr (app, ctrl, "EXTCAP");
1175 do_getattr (app, ctrl, "DISP-NAME");
1176 do_getattr (app, ctrl, "DISP-LANG");
1177 do_getattr (app, ctrl, "DISP-SEX");
1178 do_getattr (app, ctrl, "PUBKEY-URL");
1179 do_getattr (app, ctrl, "LOGIN-DATA");
1180 do_getattr (app, ctrl, "KEY-FPR");
1181 if (app->card_version > 0x0100)
1182 do_getattr (app, ctrl, "KEY-TIME");
1183 do_getattr (app, ctrl, "CA-FPR");
1184 do_getattr (app, ctrl, "CHV-STATUS");
1185 do_getattr (app, ctrl, "SIG-COUNTER");
1186 if (app->app_local->extcap.private_dos)
1188 do_getattr (app, ctrl, "PRIVATE-DO-1");
1189 do_getattr (app, ctrl, "PRIVATE-DO-2");
1190 if (app->did_chv2)
1191 do_getattr (app, ctrl, "PRIVATE-DO-3");
1192 if (app->did_chv3)
1193 do_getattr (app, ctrl, "PRIVATE-DO-4");
1195 send_keypair_info (app, ctrl, 1);
1196 send_keypair_info (app, ctrl, 2);
1197 send_keypair_info (app, ctrl, 3);
1198 return 0;
1202 /* Handle the READKEY command for OpenPGP. On success a canonical
1203 encoded S-expression with the public key will get stored at PK and
1204 its length (for assertions) at PKLEN; the caller must release that
1205 buffer. On error PK and PKLEN are not changed and an error code is
1206 returned. */
1207 static int
1208 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1210 gpg_error_t err;
1211 int keyno;
1212 unsigned char *buf;
1214 if (!strcmp (keyid, "OPENPGP.1"))
1215 keyno = 1;
1216 else if (!strcmp (keyid, "OPENPGP.2"))
1217 keyno = 2;
1218 else if (!strcmp (keyid, "OPENPGP.3"))
1219 keyno = 3;
1220 else
1221 return gpg_error (GPG_ERR_INV_ID);
1223 err = get_public_key (app, keyno);
1224 if (err)
1225 return err;
1227 buf = app->app_local->pk[keyno-1].key;
1228 if (!buf)
1229 return gpg_error (GPG_ERR_NO_PUBKEY);
1230 *pk = buf;
1231 *pklen = app->app_local->pk[keyno-1].keylen;;
1232 return 0;
1237 /* Verify CHV2 if required. Depending on the configuration of the
1238 card CHV1 will also be verified. */
1239 static int
1240 verify_chv2 (app_t app,
1241 int (*pincb)(void*, const char *, char **),
1242 void *pincb_arg)
1244 int rc = 0;
1246 if (!app->did_chv2)
1248 char *pinvalue;
1250 rc = pincb (pincb_arg, "PIN", &pinvalue);
1251 if (rc)
1253 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1254 return rc;
1257 if (strlen (pinvalue) < 6)
1259 log_error (_("PIN for CHV%d is too short;"
1260 " minimum length is %d\n"), 2, 6);
1261 xfree (pinvalue);
1262 return gpg_error (GPG_ERR_BAD_PIN);
1265 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
1266 if (rc)
1268 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
1269 xfree (pinvalue);
1270 flush_cache_after_error (app);
1271 return rc;
1273 app->did_chv2 = 1;
1275 if (!app->did_chv1 && !app->force_chv1)
1277 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1278 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1279 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1280 if (rc)
1282 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1283 xfree (pinvalue);
1284 flush_cache_after_error (app);
1285 return rc;
1287 app->did_chv1 = 1;
1289 xfree (pinvalue);
1291 return rc;
1294 /* Verify CHV3 if required. */
1295 static int
1296 verify_chv3 (app_t app,
1297 int (*pincb)(void*, const char *, char **),
1298 void *pincb_arg)
1300 int rc = 0;
1302 #if GNUPG_MAJOR_VERSION != 1
1303 if (!opt.allow_admin)
1305 log_info (_("access to admin commands is not configured\n"));
1306 return gpg_error (GPG_ERR_EACCES);
1308 #endif
1310 if (!app->did_chv3)
1312 char *pinvalue;
1313 void *relptr;
1314 unsigned char *value;
1315 size_t valuelen;
1317 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1318 if (!relptr || valuelen < 7)
1320 log_error (_("error retrieving CHV status from card\n"));
1321 xfree (relptr);
1322 return gpg_error (GPG_ERR_CARD);
1324 if (value[6] == 0)
1326 log_info (_("card is permanently locked!\n"));
1327 xfree (relptr);
1328 return gpg_error (GPG_ERR_BAD_PIN);
1331 log_info(_("%d Admin PIN attempts remaining before card"
1332 " is permanently locked\n"), value[6]);
1333 xfree (relptr);
1335 /* TRANSLATORS: Do not translate the "|A|" prefix but
1336 keep it at the start of the string. We need this elsewhere
1337 to get some infos on the string. */
1338 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1339 if (rc)
1341 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1342 return rc;
1345 if (strlen (pinvalue) < 8)
1347 log_error (_("PIN for CHV%d is too short;"
1348 " minimum length is %d\n"), 3, 8);
1349 xfree (pinvalue);
1350 return gpg_error (GPG_ERR_BAD_PIN);
1353 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1354 xfree (pinvalue);
1355 if (rc)
1357 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1358 flush_cache_after_error (app);
1359 return rc;
1361 app->did_chv3 = 1;
1363 return rc;
1367 /* Handle the SETATTR operation. All arguments are already basically
1368 checked. */
1369 static int
1370 do_setattr (app_t app, const char *name,
1371 int (*pincb)(void*, const char *, char **),
1372 void *pincb_arg,
1373 const unsigned char *value, size_t valuelen)
1375 gpg_error_t rc;
1376 int idx;
1377 static struct {
1378 const char *name;
1379 int tag;
1380 int need_chv;
1381 int special;
1382 } table[] = {
1383 { "DISP-NAME", 0x005B, 3 },
1384 { "LOGIN-DATA", 0x005E, 3, 2 },
1385 { "DISP-LANG", 0x5F2D, 3 },
1386 { "DISP-SEX", 0x5F35, 3 },
1387 { "PUBKEY-URL", 0x5F50, 3 },
1388 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1389 { "CA-FPR-1", 0x00CA, 3 },
1390 { "CA-FPR-2", 0x00CB, 3 },
1391 { "CA-FPR-3", 0x00CC, 3 },
1392 { "PRIVATE-DO-1", 0x0101, 2 },
1393 { "PRIVATE-DO-2", 0x0102, 3 },
1394 { "PRIVATE-DO-3", 0x0103, 2 },
1395 { "PRIVATE-DO-4", 0x0104, 3 },
1396 { NULL, 0 }
1400 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1402 if (!table[idx].name)
1403 return gpg_error (GPG_ERR_INV_NAME);
1405 switch (table[idx].need_chv)
1407 case 2:
1408 rc = verify_chv2 (app, pincb, pincb_arg);
1409 break;
1410 case 3:
1411 rc = verify_chv3 (app, pincb, pincb_arg);
1412 break;
1413 default:
1414 rc = 0;
1416 if (rc)
1417 return rc;
1419 /* Flush the cache before writing it, so that the next get operation
1420 will reread the data from the card and thus get synced in case of
1421 errors (e.g. data truncated by the card). */
1422 flush_cache_item (app, table[idx].tag);
1423 rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
1424 if (rc)
1425 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1427 if (table[idx].special == 1)
1428 app->force_chv1 = (valuelen && *value == 0);
1429 else if (table[idx].special == 2)
1430 parse_login_data (app);
1432 return rc;
1436 /* Handle the PASSWD command. */
1437 static int
1438 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
1439 int (*pincb)(void*, const char *, char **),
1440 void *pincb_arg)
1442 int rc = 0;
1443 int chvno = atoi (chvnostr);
1444 char *pinvalue;
1446 if (reset_mode && chvno == 3)
1448 rc = gpg_error (GPG_ERR_INV_ID);
1449 goto leave;
1451 else if (reset_mode || chvno == 3)
1453 /* we always require that the PIN is entered. */
1454 app->did_chv3 = 0;
1455 rc = verify_chv3 (app, pincb, pincb_arg);
1456 if (rc)
1457 goto leave;
1459 else if (chvno == 1 || chvno == 2)
1461 /* CHV1 and CVH2 should always have the same value, thus we
1462 enforce it here. */
1463 int save_force = app->force_chv1;
1465 app->force_chv1 = 0;
1466 app->did_chv1 = 0;
1467 app->did_chv2 = 0;
1468 rc = verify_chv2 (app, pincb, pincb_arg);
1469 app->force_chv1 = save_force;
1470 if (rc)
1471 goto leave;
1473 else
1475 rc = gpg_error (GPG_ERR_INV_ID);
1476 goto leave;
1479 if (chvno == 3)
1480 app->did_chv3 = 0;
1481 else
1482 app->did_chv1 = app->did_chv2 = 0;
1484 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1485 keep it at the start of the string. We need this elsewhere
1486 to get some infos on the string. */
1487 rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1488 &pinvalue);
1489 if (rc)
1491 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1492 goto leave;
1495 if (reset_mode)
1497 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1498 pinvalue, strlen (pinvalue));
1499 if (!rc)
1500 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1501 pinvalue, strlen (pinvalue));
1503 else
1505 if (chvno == 1 || chvno == 2)
1507 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1508 pinvalue, strlen (pinvalue));
1509 if (!rc)
1510 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1511 pinvalue, strlen (pinvalue));
1513 else
1514 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1515 pinvalue, strlen (pinvalue));
1517 xfree (pinvalue);
1518 if (rc)
1519 flush_cache_after_error (app);
1521 leave:
1522 return rc;
1527 /* Handle the GENKEY command. */
1528 static int
1529 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
1530 int (*pincb)(void*, const char *, char **),
1531 void *pincb_arg)
1533 int rc;
1534 int i;
1535 char numbuf[30];
1536 unsigned char fprbuf[20];
1537 const unsigned char *fpr;
1538 const unsigned char *keydata, *m, *e;
1539 unsigned char *buffer;
1540 size_t buflen, keydatalen, n, mlen, elen;
1541 time_t created_at;
1542 int keyno = atoi (keynostr);
1543 int force = (flags & 1);
1544 time_t start_at;
1546 if (keyno < 1 || keyno > 3)
1547 return gpg_error (GPG_ERR_INV_ID);
1548 keyno--;
1550 /* We flush the cache to increase the traffic before a key
1551 generation. This _might_ help a card to gather more entropy. */
1552 flush_cache (app);
1554 /* Obviously we need to remove the cached public key. */
1555 xfree (app->app_local->pk[keyno].key);
1556 app->app_local->pk[keyno].key = NULL;
1557 app->app_local->pk[keyno].keylen = 0;
1558 app->app_local->pk[keyno].read_done = 0;
1560 /* Check whether a key already exists. */
1561 rc = iso7816_get_data (app->slot, 0x006E, &buffer, &buflen);
1562 if (rc)
1564 log_error (_("error reading application data\n"));
1565 return gpg_error (GPG_ERR_GENERAL);
1567 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1568 if (!fpr || n != 60)
1570 rc = gpg_error (GPG_ERR_GENERAL);
1571 log_error (_("error reading fingerprint DO\n"));
1572 goto leave;
1574 fpr += 20*keyno;
1575 for (i=0; i < 20 && !fpr[i]; i++)
1577 if (i!=20 && !force)
1579 rc = gpg_error (GPG_ERR_EEXIST);
1580 log_error (_("key already exists\n"));
1581 goto leave;
1583 else if (i!=20)
1584 log_info (_("existing key will be replaced\n"));
1585 else
1586 log_info (_("generating new key\n"));
1589 /* Prepare for key generation by verifying the ADmin PIN. */
1590 rc = verify_chv3 (app, pincb, pincb_arg);
1591 if (rc)
1592 goto leave;
1594 xfree (buffer); buffer = NULL;
1596 #if 1
1597 log_info (_("please wait while key is being generated ...\n"));
1598 start_at = time (NULL);
1599 rc = iso7816_generate_keypair
1600 #else
1601 #warning key generation temporary replaced by reading an existing key.
1602 rc = iso7816_read_public_key
1603 #endif
1604 (app->slot,
1605 keyno == 0? "\xB6" :
1606 keyno == 1? "\xB8" : "\xA4",
1608 &buffer, &buflen);
1609 if (rc)
1611 rc = gpg_error (GPG_ERR_CARD);
1612 log_error (_("generating key failed\n"));
1613 goto leave;
1615 log_info (_("key generation completed (%d seconds)\n"),
1616 (int)(time (NULL) - start_at));
1617 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1618 if (!keydata)
1620 rc = gpg_error (GPG_ERR_CARD);
1621 log_error (_("response does not contain the public key data\n"));
1622 goto leave;
1625 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1626 if (!m)
1628 rc = gpg_error (GPG_ERR_CARD);
1629 log_error (_("response does not contain the RSA modulus\n"));
1630 goto leave;
1632 /* log_printhex ("RSA n:", m, mlen); */
1633 send_key_data (ctrl, "n", m, mlen);
1635 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1636 if (!e)
1638 rc = gpg_error (GPG_ERR_CARD);
1639 log_error (_("response does not contain the RSA public exponent\n"));
1640 goto leave;
1642 /* log_printhex ("RSA e:", e, elen); */
1643 send_key_data (ctrl, "e", e, elen);
1645 created_at = gnupg_get_time ();
1646 sprintf (numbuf, "%lu", (unsigned long)created_at);
1647 send_status_info (ctrl, "KEY-CREATED-AT",
1648 numbuf, (size_t)strlen(numbuf), NULL, 0);
1650 rc = store_fpr (app->slot, keyno, (u32)created_at,
1651 m, mlen, e, elen, fprbuf, app->card_version);
1652 if (rc)
1653 goto leave;
1654 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
1657 leave:
1658 xfree (buffer);
1659 return rc;
1663 static unsigned long
1664 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
1666 unsigned long ul;
1668 if (valuelen == 3 )
1669 ul = (value[0] << 16) | (value[1] << 8) | value[2];
1670 else
1672 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1673 ul = 0;
1675 return ul;
1678 static unsigned long
1679 get_sig_counter (app_t app)
1681 void *relptr;
1682 unsigned char *value;
1683 size_t valuelen;
1684 unsigned long ul;
1686 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
1687 if (!relptr)
1688 return 0;
1689 ul = convert_sig_counter_value (value, valuelen);
1690 xfree (relptr);
1691 return ul;
1694 static int
1695 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
1697 const unsigned char *fpr;
1698 unsigned char *buffer;
1699 size_t buflen, n;
1700 int rc, i;
1702 assert (keyno >= 1 && keyno <= 3);
1704 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
1705 if (rc)
1707 log_error (_("error reading application data\n"));
1708 return gpg_error (GPG_ERR_GENERAL);
1710 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1711 if (!fpr || n != 60)
1713 xfree (buffer);
1714 log_error (_("error reading fingerprint DO\n"));
1715 return gpg_error (GPG_ERR_GENERAL);
1717 fpr += (keyno-1)*20;
1718 for (i=0; i < 20; i++)
1719 if (sha1fpr[i] != fpr[i])
1721 xfree (buffer);
1722 return gpg_error (GPG_ERR_WRONG_SECKEY);
1724 xfree (buffer);
1725 return 0;
1729 /* If a fingerprint has been specified check it against the one on
1730 the card. This is allows for a meaningful error message in case
1731 the key on the card has been replaced but the shadow information
1732 known to gpg was not updated. If there is no fingerprint we
1733 assume that this is okay. */
1734 static int
1735 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
1737 unsigned char tmp[20];
1738 const char *s;
1739 int n;
1741 for (s=fpr, n=0; hexdigitp (s); s++, n++)
1743 if (n != 40)
1744 return gpg_error (GPG_ERR_INV_ID);
1745 else if (!*s)
1746 ; /* okay */
1747 else
1748 return gpg_error (GPG_ERR_INV_ID);
1750 for (s=fpr, n=0; n < 20; s += 2, n++)
1751 tmp[n] = xtoi_2 (s);
1752 return compare_fingerprint (app, keyno, tmp);
1757 /* Compute a digital signature on INDATA which is expected to be the
1758 raw message digest. For this application the KEYIDSTR consists of
1759 the serialnumber and the fingerprint delimited by a slash.
1761 Note that this fucntion may return the error code
1762 GPG_ERR_WRONG_CARD to indicate that the card currently present does
1763 not match the one required for the requested action (e.g. the
1764 serial number does not match). */
1765 static int
1766 do_sign (app_t app, const char *keyidstr, int hashalgo,
1767 int (*pincb)(void*, const char *, char **),
1768 void *pincb_arg,
1769 const void *indata, size_t indatalen,
1770 unsigned char **outdata, size_t *outdatalen )
1772 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
1773 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1774 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
1775 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
1776 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
1777 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
1778 int rc;
1779 unsigned char data[35];
1780 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
1781 const char *s;
1782 int n;
1783 const char *fpr = NULL;
1784 unsigned long sigcount;
1786 if (!keyidstr || !*keyidstr)
1787 return gpg_error (GPG_ERR_INV_VALUE);
1788 if (indatalen == 20)
1790 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
1791 && !memcmp (indata, sha1_prefix, 15))
1793 else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
1794 && !memcmp (indata, rmd160_prefix, 15))
1796 else
1797 return gpg_error (GPG_ERR_INV_VALUE);
1799 /* Check whether an OpenPGP card of any version has been requested. */
1800 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
1801 return gpg_error (GPG_ERR_INV_ID);
1803 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
1805 if (n != 32)
1806 return gpg_error (GPG_ERR_INV_ID);
1807 else if (!*s)
1808 ; /* no fingerprint given: we allow this for now. */
1809 else if (*s == '/')
1810 fpr = s + 1;
1811 else
1812 return gpg_error (GPG_ERR_INV_ID);
1814 for (s=keyidstr, n=0; n < 16; s += 2, n++)
1815 tmp_sn[n] = xtoi_2 (s);
1817 if (app->serialnolen != 16)
1818 return gpg_error (GPG_ERR_INV_CARD);
1819 if (memcmp (app->serialno, tmp_sn, 16))
1820 return gpg_error (GPG_ERR_WRONG_CARD);
1822 /* If a fingerprint has been specified check it against the one on
1823 the card. This is allows for a meaningful error message in case
1824 the key on the card has been replaced but the shadow information
1825 known to gpg was not updated. If there is no fingerprint, gpg
1826 will detect a bogus signature anyway due to the
1827 verify-after-signing feature. */
1828 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
1829 if (rc)
1830 return rc;
1832 if (hashalgo == GCRY_MD_SHA1)
1833 memcpy (data, sha1_prefix, 15);
1834 else if (hashalgo == GCRY_MD_RMD160)
1835 memcpy (data, rmd160_prefix, 15);
1836 else
1837 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
1838 memcpy (data+15, indata, indatalen);
1840 sigcount = get_sig_counter (app);
1841 log_info (_("signatures created so far: %lu\n"), sigcount);
1843 if (!app->did_chv1 || app->force_chv1 )
1845 char *pinvalue;
1848 char *prompt;
1849 #define PROMPTSTRING _("PIN [sigs done: %lu]")
1851 prompt = malloc (strlen (PROMPTSTRING) + 50);
1852 if (!prompt)
1853 return gpg_error_from_errno (errno);
1854 sprintf (prompt, PROMPTSTRING, sigcount);
1855 rc = pincb (pincb_arg, prompt, &pinvalue);
1856 free (prompt);
1857 #undef PROMPTSTRING
1859 if (rc)
1861 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1862 return rc;
1865 if (strlen (pinvalue) < 6)
1867 log_error (_("PIN for CHV%d is too short;"
1868 " minimum length is %d\n"), 1, 6);
1869 xfree (pinvalue);
1870 return gpg_error (GPG_ERR_BAD_PIN);
1873 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1874 if (rc)
1876 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1877 xfree (pinvalue);
1878 flush_cache_after_error (app);
1879 return rc;
1881 app->did_chv1 = 1;
1882 if (!app->did_chv2)
1884 /* We should also verify CHV2. */
1885 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
1886 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1887 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1888 if (rc)
1890 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
1891 xfree (pinvalue);
1892 flush_cache_after_error (app);
1893 return rc;
1895 app->did_chv2 = 1;
1897 xfree (pinvalue);
1900 rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
1901 return rc;
1904 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
1905 on INDATA which is expected to be the raw message digest. For this
1906 application the KEYIDSTR consists of the serialnumber and the
1907 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
1908 be given.
1910 Note that this fucntion may return the error code
1911 GPG_ERR_WRONG_CARD to indicate that the card currently present does
1912 not match the one required for the requested action (e.g. the
1913 serial number does not match). */
1914 static int
1915 do_auth (app_t app, const char *keyidstr,
1916 int (*pincb)(void*, const char *, char **),
1917 void *pincb_arg,
1918 const void *indata, size_t indatalen,
1919 unsigned char **outdata, size_t *outdatalen )
1921 int rc;
1922 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
1923 const char *s;
1924 int n;
1925 const char *fpr = NULL;
1927 if (!keyidstr || !*keyidstr)
1928 return gpg_error (GPG_ERR_INV_VALUE);
1929 if (indatalen > 50) /* For a 1024 bit key. */
1930 return gpg_error (GPG_ERR_INV_VALUE);
1932 /* Check whether an OpenPGP card of any version has been requested. */
1933 if (!strcmp (keyidstr, "OPENPGP.3"))
1935 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
1936 return gpg_error (GPG_ERR_INV_ID);
1937 else
1939 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
1941 if (n != 32)
1942 return gpg_error (GPG_ERR_INV_ID);
1943 else if (!*s)
1944 ; /* no fingerprint given: we allow this for now. */
1945 else if (*s == '/')
1946 fpr = s + 1;
1947 else
1948 return gpg_error (GPG_ERR_INV_ID);
1950 for (s=keyidstr, n=0; n < 16; s += 2, n++)
1951 tmp_sn[n] = xtoi_2 (s);
1953 if (app->serialnolen != 16)
1954 return gpg_error (GPG_ERR_INV_CARD);
1955 if (memcmp (app->serialno, tmp_sn, 16))
1956 return gpg_error (GPG_ERR_WRONG_CARD);
1959 /* If a fingerprint has been specified check it against the one on
1960 the card. This is allows for a meaningful error message in case
1961 the key on the card has been replaced but the shadow information
1962 known to gpg was not updated. If there is no fingerprint, gpg
1963 will detect a bogus signature anyway due to the
1964 verify-after-signing feature. */
1965 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
1966 if (rc)
1967 return rc;
1969 rc = verify_chv2 (app, pincb, pincb_arg);
1970 if (!rc)
1971 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
1972 outdata, outdatalen);
1973 return rc;
1977 static int
1978 do_decipher (app_t app, const char *keyidstr,
1979 int (pincb)(void*, const char *, char **),
1980 void *pincb_arg,
1981 const void *indata, size_t indatalen,
1982 unsigned char **outdata, size_t *outdatalen )
1984 int rc;
1985 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
1986 const char *s;
1987 int n;
1988 const char *fpr = NULL;
1990 if (!keyidstr || !*keyidstr || !indatalen)
1991 return gpg_error (GPG_ERR_INV_VALUE);
1993 /* Check whether an OpenPGP card of any version has been requested. */
1994 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
1995 return gpg_error (GPG_ERR_INV_ID);
1997 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
1999 if (n != 32)
2000 return gpg_error (GPG_ERR_INV_ID);
2001 else if (!*s)
2002 ; /* no fingerprint given: we allow this for now. */
2003 else if (*s == '/')
2004 fpr = s + 1;
2005 else
2006 return gpg_error (GPG_ERR_INV_ID);
2008 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2009 tmp_sn[n] = xtoi_2 (s);
2011 if (app->serialnolen != 16)
2012 return gpg_error (GPG_ERR_INV_CARD);
2013 if (memcmp (app->serialno, tmp_sn, 16))
2014 return gpg_error (GPG_ERR_WRONG_CARD);
2016 /* If a fingerprint has been specified check it against the one on
2017 the card. This is allows for a meaningful error message in case
2018 the key on the card has been replaced but the shadow information
2019 known to gpg was not updated. If there is no fingerprint, the
2020 decryption will won't produce the right plaintext anyway. */
2021 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
2022 if (rc)
2023 return rc;
2025 rc = verify_chv2 (app, pincb, pincb_arg);
2026 if (!rc)
2027 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
2028 outdata, outdatalen);
2029 return rc;
2033 /* Perform a simple verify operation for CHV1 and CHV2, so that
2034 further operations won't ask for CHV2 and it is possible to do a
2035 cheap check on the PIN: If there is something wrong with the PIN
2036 entry system, only the regular CHV will get blocked and not the
2037 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2038 optional fingerprint part will be ignored.
2040 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2041 the "[CHV3]" being a literal string: The Admin Pin is checked if
2042 and only if the retry counter is still at 3. */
2043 static int
2044 do_check_pin (app_t app, const char *keyidstr,
2045 int (pincb)(void*, const char *, char **),
2046 void *pincb_arg)
2048 unsigned char tmp_sn[20];
2049 const char *s;
2050 int n;
2051 int admin_pin = 0;
2053 if (!keyidstr || !*keyidstr)
2054 return gpg_error (GPG_ERR_INV_VALUE);
2056 /* Check whether an OpenPGP card of any version has been requested. */
2057 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2058 return gpg_error (GPG_ERR_INV_ID);
2060 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2062 if (n != 32)
2063 return gpg_error (GPG_ERR_INV_ID);
2064 else if (!*s)
2065 ; /* No fingerprint given: we allow this for now. */
2066 else if (*s == '/')
2067 ; /* We ignore a fingerprint. */
2068 else if (!strcmp (s, "[CHV3]") )
2069 admin_pin = 1;
2070 else
2071 return gpg_error (GPG_ERR_INV_ID);
2073 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2074 tmp_sn[n] = xtoi_2 (s);
2076 if (app->serialnolen != 16)
2077 return gpg_error (GPG_ERR_INV_CARD);
2078 if (memcmp (app->serialno, tmp_sn, 16))
2079 return gpg_error (GPG_ERR_WRONG_CARD);
2081 /* Yes, there is a race conditions: The user might pull the card
2082 right here and we won't notice that. However this is not a
2083 problem and the check above is merely for a graceful failure
2084 between operations. */
2086 if (admin_pin)
2088 void *relptr;
2089 unsigned char *value;
2090 size_t valuelen;
2091 int count;
2093 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2094 if (!relptr || valuelen < 7)
2096 log_error (_("error retrieving CHV status from card\n"));
2097 xfree (relptr);
2098 return gpg_error (GPG_ERR_CARD);
2100 count = value[6];
2101 xfree (relptr);
2103 if (!count)
2105 log_info (_("card is permanently locked!\n"));
2106 return gpg_error (GPG_ERR_BAD_PIN);
2108 else if (value[6] < 3)
2110 log_info (_("verification of Admin PIN is currently prohibited "
2111 "through this command\n"));
2112 return gpg_error (GPG_ERR_GENERAL);
2115 app->did_chv3 = 0; /* Force verification. */
2116 return verify_chv3 (app, pincb, pincb_arg);
2118 else
2119 return verify_chv2 (app, pincb, pincb_arg);
2125 /* Select the OpenPGP application on the card in SLOT. This function
2126 must be used before any other OpenPGP application functions. */
2128 app_select_openpgp (app_t app)
2130 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2131 int slot = app->slot;
2132 int rc;
2133 unsigned char *buffer;
2134 size_t buflen;
2135 void *relptr;
2137 rc = iso7816_select_application (slot, aid, sizeof aid);
2138 if (!rc)
2140 unsigned int manufacturer;
2142 app->apptype = "OPENPGP";
2144 app->did_chv1 = 0;
2145 app->did_chv2 = 0;
2146 app->did_chv3 = 0;
2147 app->app_local = NULL;
2149 /* The OpenPGP card returns the serial number as part of the
2150 AID; because we prefer to use OpenPGP serial numbers, we
2151 replace a possibly already set one from a EF.GDO with this
2152 one. Note, that for current OpenPGP cards, no EF.GDO exists
2153 and thus it won't matter at all. */
2154 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
2155 if (rc)
2156 goto leave;
2157 if (opt.verbose)
2159 log_info ("AID: ");
2160 log_printhex ("", buffer, buflen);
2163 app->card_version = buffer[6] << 8;
2164 app->card_version |= buffer[7];
2165 manufacturer = (buffer[8]<<8 | buffer[9]);
2167 xfree (app->serialno);
2168 app->serialno = buffer;
2169 app->serialnolen = buflen;
2170 buffer = NULL;
2171 app->app_local = xtrycalloc (1, sizeof *app->app_local);
2172 if (!app->app_local)
2174 rc = gpg_error (gpg_err_code_from_errno (errno));
2175 goto leave;
2178 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
2179 if (!relptr)
2181 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2182 "CHV Status Bytes");
2183 goto leave;
2185 app->force_chv1 = (buflen && *buffer == 0);
2186 xfree (relptr);
2188 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
2189 if (!relptr)
2191 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2192 "Extended Capability Flags" );
2193 goto leave;
2195 if (buflen)
2197 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
2198 app->app_local->extcap.key_import = !!(*buffer & 0x20);
2199 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
2200 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
2202 xfree (relptr);
2204 /* Some of the first cards accidently don't set the
2205 CHANGE_FORCE_CHV bit but allow it anyway. */
2206 if (app->card_version <= 0x0100 && manufacturer == 1)
2207 app->app_local->extcap.change_force_chv = 1;
2209 parse_login_data (app);
2211 if (opt.verbose > 1)
2212 dump_all_do (slot);
2214 app->fnc.deinit = do_deinit;
2215 app->fnc.learn_status = do_learn_status;
2216 app->fnc.readkey = do_readkey;
2217 app->fnc.getattr = do_getattr;
2218 app->fnc.setattr = do_setattr;
2219 app->fnc.genkey = do_genkey;
2220 app->fnc.sign = do_sign;
2221 app->fnc.auth = do_auth;
2222 app->fnc.decipher = do_decipher;
2223 app->fnc.change_pin = do_change_pin;
2224 app->fnc.check_pin = do_check_pin;
2227 leave:
2228 if (rc)
2229 do_deinit (app);
2230 return rc;
2235 /* This function is a hack to retrieve essential information about the
2236 card to be displayed by simple tools. It mostly resembles what the
2237 LEARN command returns. All parameters return allocated strings or
2238 buffers or NULL if the data object is not available. All returned
2239 values are sanitized. */
2241 app_openpgp_cardinfo (app_t app,
2242 char **serialno,
2243 char **disp_name,
2244 char **pubkey_url,
2245 unsigned char **fpr1,
2246 unsigned char **fpr2,
2247 unsigned char **fpr3)
2249 int rc;
2250 void *relptr;
2251 unsigned char *value;
2252 size_t valuelen;
2254 if (serialno)
2256 time_t dummy;
2258 *serialno = NULL;
2259 rc = app_get_serial_and_stamp (app, serialno, &dummy);
2260 if (rc)
2262 log_error (_("error getting serial number: %s\n"),
2263 gpg_strerror (rc));
2264 return rc;
2268 if (disp_name)
2270 *disp_name = NULL;
2271 relptr = get_one_do (app, 0x005B, &value, &valuelen, NULL);
2272 if (relptr)
2274 *disp_name = make_printable_string (value, valuelen, 0);
2275 xfree (relptr);
2279 if (pubkey_url)
2281 *pubkey_url = NULL;
2282 relptr = get_one_do (app, 0x5F50, &value, &valuelen, NULL);
2283 if (relptr)
2285 *pubkey_url = make_printable_string (value, valuelen, 0);
2286 xfree (relptr);
2290 if (fpr1)
2291 *fpr1 = NULL;
2292 if (fpr2)
2293 *fpr2 = NULL;
2294 if (fpr3)
2295 *fpr3 = NULL;
2296 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
2297 if (relptr && valuelen >= 60)
2299 if (fpr1)
2301 *fpr1 = xmalloc (20);
2302 memcpy (*fpr1, value + 0, 20);
2304 if (fpr2)
2306 *fpr2 = xmalloc (20);
2307 memcpy (*fpr2, value + 20, 20);
2309 if (fpr3)
2311 *fpr3 = xmalloc (20);
2312 memcpy (*fpr3, value + 40, 20);
2315 xfree (relptr);
2317 return 0;
2322 /* This function is currently only used by the sc-copykeys program to
2323 store a key on the smartcard. app_t ist the application handle,
2324 KEYNO is the number of the key and PINCB, PINCB_ARG are used to ask
2325 for the SO PIN. TEMPLATE and TEMPLATE_LEN describe a buffer with
2326 the key template to store. CREATED_AT is the timestamp used to
2327 create the fingerprint. M, MLEN is the RSA modulus and E, ELEN the
2328 RSA public exponent. This function silently overwrites an existing
2329 key.*/
2330 int
2331 app_openpgp_storekey (app_t app, int keyno,
2332 unsigned char *template, size_t template_len,
2333 time_t created_at,
2334 const unsigned char *m, size_t mlen,
2335 const unsigned char *e, size_t elen,
2336 int (*pincb)(void*, const char *, char **),
2337 void *pincb_arg)
2339 int rc;
2340 unsigned char fprbuf[20];
2342 if (keyno < 1 || keyno > 3)
2343 return gpg_error (GPG_ERR_INV_ID);
2344 keyno--;
2346 rc = verify_chv3 (app, pincb, pincb_arg);
2347 if (rc)
2348 goto leave;
2350 flush_cache (app);
2352 xfree (app->app_local->pk[keyno].key);
2353 app->app_local->pk[keyno].key = NULL;
2354 app->app_local->pk[keyno].keylen = 0;
2355 app->app_local->pk[keyno].read_done = 0;
2357 rc = iso7816_put_data (app->slot,
2358 (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
2359 template, template_len);
2360 if (rc)
2362 log_error (_("failed to store the key: %s\n"), gpg_strerror (rc));
2363 rc = gpg_error (GPG_ERR_CARD);
2364 goto leave;
2367 /* log_printhex ("RSA n:", m, mlen); */
2368 /* log_printhex ("RSA e:", e, elen); */
2370 rc = store_fpr (app->slot, keyno, (u32)created_at,
2371 m, mlen, e, elen, fprbuf, app->card_version);
2373 leave:
2374 return rc;
2378 /* Utility function for external tools: Read the public RSA key at
2379 KEYNO and return modulus and exponent in (M,MLEN) and (E,ELEN). */
2380 int
2381 app_openpgp_readkey (app_t app, int keyno, unsigned char **m, size_t *mlen,
2382 unsigned char **e, size_t *elen)
2384 int rc;
2385 const unsigned char *keydata, *a;
2386 unsigned char *buffer;
2387 size_t buflen, keydatalen, alen;
2389 *m = NULL;
2390 *e = NULL;
2392 if (keyno < 1 || keyno > 3)
2393 return gpg_error (GPG_ERR_INV_ID);
2394 keyno--;
2396 rc = iso7816_read_public_key(app->slot,
2397 keyno == 0? "\xB6" :
2398 keyno == 1? "\xB8" : "\xA4",
2400 &buffer, &buflen);
2401 if (rc)
2403 rc = gpg_error (GPG_ERR_CARD);
2404 log_error (_("reading the key failed\n"));
2405 goto leave;
2408 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2409 if (!keydata)
2411 log_error (_("response does not contain the public key data\n"));
2412 rc = gpg_error (GPG_ERR_CARD);
2413 goto leave;
2416 a = find_tlv (keydata, keydatalen, 0x0081, &alen);
2417 if (!a)
2419 log_error (_("response does not contain the RSA modulus\n"));
2420 rc = gpg_error (GPG_ERR_CARD);
2421 goto leave;
2423 *mlen = alen;
2424 *m = xmalloc (alen);
2425 memcpy (*m, a, alen);
2427 a = find_tlv (keydata, keydatalen, 0x0082, &alen);
2428 if (!a)
2430 log_error (_("response does not contain the RSA public exponent\n"));
2431 rc = gpg_error (GPG_ERR_CARD);
2432 goto leave;
2434 *elen = alen;
2435 *e = xmalloc (alen);
2436 memcpy (*e, a, alen);
2438 leave:
2439 xfree (buffer);
2440 if (rc)
2442 xfree (*m); *m = NULL;
2443 xfree (*e); *e = NULL;
2445 return rc;