typo fixes.
[gnupg.git] / scd / app-openpgp.c
blob6b90795bba27d02c708a8e0b26c1541b4c4f0fd7
1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 * $Id$
22 /* Some notes:
24 CHV means Card Holder Verification and is nothing else than a PIN
25 or password. That term seems to have been used originally with GSM
26 cards. Version v2 of the specs changes the term to the clearer
27 term PW for password. We use the terms here interchangeable
28 because we do not want to change existing strings i18n wise.
30 Version 2 of the specs also drops the separate PW2 which was
31 required in v1 due to ISO requirements. It is now possible to have
32 one physical PW but two reference to it so that they can be
33 individually be verified (e.g. to implement a forced verification
34 for one key). Thus you will noticed the use of PW2 with the verify
35 command but not with change_reference_data because the latter
36 operates directly on the physical PW.
38 The Reset Code (RC) as implemented by v2 cards uses the same error
39 counter as the PW2 of v1 cards. By default no RC is set and thus
40 that error counter is set to 0. After setting the RC the error
41 counter will be initialized to 3.
45 #include <config.h>
46 #include <errno.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <assert.h>
51 #include <time.h>
53 #if GNUPG_MAJOR_VERSION == 1
54 /* This is used with GnuPG version < 1.9. The code has been source
55 copied from the current GnuPG >= 1.9 and is maintained over
56 there. */
57 #include "options.h"
58 #include "errors.h"
59 #include "memory.h"
60 #include "util.h"
61 #include "cardglue.h"
62 #else /* GNUPG_MAJOR_VERSION != 1 */
63 #include "scdaemon.h"
64 #endif /* GNUPG_MAJOR_VERSION != 1 */
66 #include "i18n.h"
67 #include "iso7816.h"
68 #include "app-common.h"
69 #include "tlv.h"
72 /* A table describing the DOs of the card. */
73 static struct {
74 int tag;
75 int constructed;
76 int get_from; /* Constructed DO with this DO or 0 for direct access. */
77 int binary;
78 int dont_cache;
79 int flush_on_error;
80 int get_immediate_in_v11; /* Enable a hack to bypass the cache of
81 this data object if it is used in 1.1
82 and later versions of the card. This
83 does not work with composite DO and is
84 currently only useful for the CHV
85 status bytes. */
86 char *desc;
87 } data_objects[] = {
88 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
89 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
90 { 0x5F52, 0, 0, 1, 0, 0, 0, "Historical Bytes" },
91 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
92 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
93 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
94 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
95 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
96 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
97 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
98 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
99 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
100 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
101 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
102 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
103 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
104 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
105 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
106 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
107 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
108 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
109 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
110 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
111 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
112 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
113 { 0x7F21, 1, 0, 1, 0, 0, 0, "Cardholder certificate"},
114 { 0 }
118 /* The format of RSA private keys. */
119 typedef enum
121 RSA_UNKNOWN_FMT,
122 RSA_STD,
123 RSA_STD_N,
124 RSA_CRT,
125 RSA_CRT_N
127 rsa_key_format_t;
130 /* One cache item for DOs. */
131 struct cache_s {
132 struct cache_s *next;
133 int tag;
134 size_t length;
135 unsigned char data[1];
139 /* Object with application (i.e. OpenPGP card) specific data. */
140 struct app_local_s {
141 /* A linked list with cached DOs. */
142 struct cache_s *cache;
144 /* Keep track of the public keys. */
145 struct
147 int read_done; /* True if we have at least tried to read them. */
148 unsigned char *key; /* This is a malloced buffer with a canonical
149 encoded S-expression encoding a public
150 key. Might be NULL if key is not
151 available. */
152 size_t keylen; /* The length of the above S-expression. This
153 is usullay only required for cross checks
154 because the length of an S-expression is
155 implicitly available. */
156 } pk[3];
158 unsigned char status_indicator; /* The card status indicator. */
160 /* Keep track of the ISO card capabilities. */
161 struct
163 unsigned int cmd_chaining:1; /* Command chaining is supported. */
164 unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
165 } cardcap;
167 /* Keep track of extended card capabilities. */
168 struct
170 unsigned int is_v2:1; /* This is a v2.0 compatible card. */
171 unsigned int get_challenge:1;
172 unsigned int key_import:1;
173 unsigned int change_force_chv:1;
174 unsigned int private_dos:1;
175 unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
176 unsigned int sm_supported:1; /* Secure Messaging is supported. */
177 unsigned int sm_aes128:1; /* Use AES-128 for SM. */
178 unsigned int max_certlen_3:16;
179 unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
180 unsigned int max_cmd_data:16; /* Maximum data size for a command. */
181 unsigned int max_rsp_data:16; /* Maximum size of a response. */
182 } extcap;
184 /* Flags used to control the application. */
185 struct
187 unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
188 unsigned int def_chv2:1; /* Use 123456 for CHV2. */
189 } flags;
191 struct
193 unsigned int n_bits; /* Size of the modulus in bits. The rest
194 of this strucuire is only valid if
195 this is not 0. */
196 unsigned int e_bits; /* Size of the public exponent in bits. */
197 rsa_key_format_t format;
198 } keyattr[3];
204 /***** Local prototypes *****/
205 static unsigned long convert_sig_counter_value (const unsigned char *value,
206 size_t valuelen);
207 static unsigned long get_sig_counter (app_t app);
208 static gpg_error_t do_auth (app_t app, const char *keyidstr,
209 gpg_error_t (*pincb)(void*, const char *, char **),
210 void *pincb_arg,
211 const void *indata, size_t indatalen,
212 unsigned char **outdata, size_t *outdatalen);
218 /* Deconstructor. */
219 static void
220 do_deinit (app_t app)
222 if (app && app->app_local)
224 struct cache_s *c, *c2;
225 int i;
227 for (c = app->app_local->cache; c; c = c2)
229 c2 = c->next;
230 xfree (c);
233 for (i=0; i < DIM (app->app_local->pk); i++)
235 xfree (app->app_local->pk[i].key);
236 app->app_local->pk[i].read_done = 0;
238 xfree (app->app_local);
239 app->app_local = NULL;
244 /* Wrapper around iso7816_get_data which first tries to get the data
245 from the cache. With GET_IMMEDIATE passed as true, the cache is
246 bypassed. */
247 static gpg_error_t
248 get_cached_data (app_t app, int tag,
249 unsigned char **result, size_t *resultlen,
250 int get_immediate)
252 gpg_error_t err;
253 int i;
254 unsigned char *p;
255 size_t len;
256 struct cache_s *c;
258 *result = NULL;
259 *resultlen = 0;
261 if (!get_immediate)
263 for (c=app->app_local->cache; c; c = c->next)
264 if (c->tag == tag)
266 if(c->length)
268 p = xtrymalloc (c->length);
269 if (!p)
270 return gpg_error (gpg_err_code_from_errno (errno));
271 memcpy (p, c->data, c->length);
272 *result = p;
275 *resultlen = c->length;
277 return 0;
281 err = iso7816_get_data (app->slot, tag, &p, &len);
282 if (err)
283 return err;
284 *result = p;
285 *resultlen = len;
287 /* Check whether we should cache this object. */
288 if (get_immediate)
289 return 0;
291 for (i=0; data_objects[i].tag; i++)
292 if (data_objects[i].tag == tag)
294 if (data_objects[i].dont_cache)
295 return 0;
296 break;
299 /* Okay, cache it. */
300 for (c=app->app_local->cache; c; c = c->next)
301 assert (c->tag != tag);
303 c = xtrymalloc (sizeof *c + len);
304 if (c)
306 memcpy (c->data, p, len);
307 c->length = len;
308 c->tag = tag;
309 c->next = app->app_local->cache;
310 app->app_local->cache = c;
313 return 0;
316 /* Remove DO at TAG from the cache. */
317 static void
318 flush_cache_item (app_t app, int tag)
320 struct cache_s *c, *cprev;
321 int i;
323 if (!app->app_local)
324 return;
326 for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
327 if (c->tag == tag)
329 if (cprev)
330 cprev->next = c->next;
331 else
332 app->app_local->cache = c->next;
333 xfree (c);
335 for (c=app->app_local->cache; c ; c = c->next)
337 assert (c->tag != tag); /* Oops: duplicated entry. */
339 return;
342 /* Try again if we have an outer tag. */
343 for (i=0; data_objects[i].tag; i++)
344 if (data_objects[i].tag == tag && data_objects[i].get_from
345 && data_objects[i].get_from != tag)
346 flush_cache_item (app, data_objects[i].get_from);
349 /* Flush all entries from the cache which might be out of sync after
350 an error. */
351 static void
352 flush_cache_after_error (app_t app)
354 int i;
356 for (i=0; data_objects[i].tag; i++)
357 if (data_objects[i].flush_on_error)
358 flush_cache_item (app, data_objects[i].tag);
362 /* Flush the entire cache. */
363 static void
364 flush_cache (app_t app)
366 if (app && app->app_local)
368 struct cache_s *c, *c2;
370 for (c = app->app_local->cache; c; c = c2)
372 c2 = c->next;
373 xfree (c);
375 app->app_local->cache = NULL;
380 /* Get the DO identified by TAG from the card in SLOT and return a
381 buffer with its content in RESULT and NBYTES. The return value is
382 NULL if not found or a pointer which must be used to release the
383 buffer holding value. */
384 static void *
385 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
386 int *r_rc)
388 int rc, i;
389 unsigned char *buffer;
390 size_t buflen;
391 unsigned char *value;
392 size_t valuelen;
393 int dummyrc;
395 if (!r_rc)
396 r_rc = &dummyrc;
398 *result = NULL;
399 *nbytes = 0;
400 *r_rc = 0;
401 for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
404 if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
406 rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
407 if (rc)
409 *r_rc = rc;
410 return NULL;
412 *result = buffer;
413 *nbytes = buflen;
414 return buffer;
417 value = NULL;
418 rc = -1;
419 if (data_objects[i].tag && data_objects[i].get_from)
421 rc = get_cached_data (app, data_objects[i].get_from,
422 &buffer, &buflen,
423 (data_objects[i].dont_cache
424 || data_objects[i].get_immediate_in_v11));
425 if (!rc)
427 const unsigned char *s;
429 s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
430 if (!s)
431 value = NULL; /* not found */
432 else if (valuelen > buflen - (s - buffer))
434 log_error ("warning: constructed DO too short\n");
435 value = NULL;
436 xfree (buffer); buffer = NULL;
438 else
439 value = buffer + (s - buffer);
443 if (!value) /* Not in a constructed DO, try simple. */
445 rc = get_cached_data (app, tag, &buffer, &buflen,
446 (data_objects[i].dont_cache
447 || data_objects[i].get_immediate_in_v11));
448 if (!rc)
450 value = buffer;
451 valuelen = buflen;
455 if (!rc)
457 *nbytes = valuelen;
458 *result = value;
459 return buffer;
461 *r_rc = rc;
462 return NULL;
466 static void
467 dump_all_do (int slot)
469 int rc, i, j;
470 unsigned char *buffer;
471 size_t buflen;
473 for (i=0; data_objects[i].tag; i++)
475 if (data_objects[i].get_from)
476 continue;
478 rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
479 if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
481 else if (rc)
482 log_info ("DO `%s' not available: %s\n",
483 data_objects[i].desc, gpg_strerror (rc));
484 else
486 if (data_objects[i].binary)
488 log_info ("DO `%s': ", data_objects[i].desc);
489 log_printhex ("", buffer, buflen);
491 else
492 log_info ("DO `%s': `%.*s'\n",
493 data_objects[i].desc,
494 (int)buflen, buffer); /* FIXME: sanitize */
496 if (data_objects[i].constructed)
498 for (j=0; data_objects[j].tag; j++)
500 const unsigned char *value;
501 size_t valuelen;
503 if (j==i || data_objects[i].tag != data_objects[j].get_from)
504 continue;
505 value = find_tlv_unchecked (buffer, buflen,
506 data_objects[j].tag, &valuelen);
507 if (!value)
508 ; /* not found */
509 else if (valuelen > buflen - (value - buffer))
510 log_error ("warning: constructed DO too short\n");
511 else
513 if (data_objects[j].binary)
515 log_info ("DO `%s': ", data_objects[j].desc);
516 if (valuelen > 200)
517 log_info ("[%u]\n", (unsigned int)valuelen);
518 else
519 log_printhex ("", value, valuelen);
521 else
522 log_info ("DO `%s': `%.*s'\n",
523 data_objects[j].desc,
524 (int)valuelen, value); /* FIXME: sanitize */
529 xfree (buffer); buffer = NULL;
534 /* Count the number of bits, assuming the A represents an unsigned big
535 integer of length LEN bytes. */
536 static unsigned int
537 count_bits (const unsigned char *a, size_t len)
539 unsigned int n = len * 8;
540 int i;
542 for (; len && !*a; len--, a++, n -=8)
544 if (len)
546 for (i=7; i && !(*a & (1<<i)); i--)
547 n--;
549 return n;
552 /* GnuPG makes special use of the login-data DO, this function parses
553 the login data to store the flags for later use. It may be called
554 at any time and should be called after changing the login-data DO.
556 Everything up to a LF is considered a mailbox or account name. If
557 the first LF is followed by DC4 (0x14) control sequence are
558 expected up to the next LF. Control sequences are separated by FS
559 (0x18) and consist of key=value pairs. There is one key defined:
561 F=<flags>
563 Were FLAGS is a plain hexadecimal number representing flag values.
564 The lsb is here the rightmost bit. Defined flags bits are:
566 Bit 0 = CHV1 and CHV2 are not syncronized
567 Bit 1 = CHV2 has been been set to the default PIN of "123456"
568 (this implies that bit 0 is also set).
571 static void
572 parse_login_data (app_t app)
574 unsigned char *buffer, *p;
575 size_t buflen, len;
576 void *relptr;
578 /* Set defaults. */
579 app->app_local->flags.no_sync = 0;
580 app->app_local->flags.def_chv2 = 0;
582 /* Read the DO. */
583 relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
584 if (!relptr)
585 return; /* Ooops. */
586 for (; buflen; buflen--, buffer++)
587 if (*buffer == '\n')
588 break;
589 if (buflen < 2 || buffer[1] != '\x14')
590 return; /* No control sequences. */
591 buflen--;
592 buffer++;
595 buflen--;
596 buffer++;
597 if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
599 /* Flags control sequence found. */
600 int lastdig = 0;
602 /* For now we are only interested in the last digit, so skip
603 any leading digits but bail out on invalid characters. */
604 for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
605 lastdig = xtoi_1 (p);
606 if (len && !(*p == '\n' || *p == '\x18'))
607 goto next; /* Invalid characters in field. */
608 app->app_local->flags.no_sync = !!(lastdig & 1);
609 app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
611 next:
612 for (; buflen && *buffer != '\x18'; buflen--, buffer++)
613 if (*buffer == '\n')
614 buflen = 1;
616 while (buflen);
618 xfree (relptr);
621 /* Note, that FPR must be at least 20 bytes. */
622 static gpg_error_t
623 store_fpr (int slot, int keynumber, u32 timestamp,
624 const unsigned char *m, size_t mlen,
625 const unsigned char *e, size_t elen,
626 unsigned char *fpr, unsigned int card_version)
628 unsigned int n, nbits;
629 unsigned char *buffer, *p;
630 int rc;
632 for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
634 for (; elen && !*e; elen--, e++) /* strip leading zeroes */
637 n = 6 + 2 + mlen + 2 + elen;
638 p = buffer = xtrymalloc (3 + n);
639 if (!buffer)
640 return gpg_error_from_syserror ();
642 *p++ = 0x99; /* ctb */
643 *p++ = n >> 8; /* 2 byte length header */
644 *p++ = n;
645 *p++ = 4; /* key packet version */
646 *p++ = timestamp >> 24;
647 *p++ = timestamp >> 16;
648 *p++ = timestamp >> 8;
649 *p++ = timestamp;
650 *p++ = 1; /* RSA */
651 nbits = count_bits (m, mlen);
652 *p++ = nbits >> 8;
653 *p++ = nbits;
654 memcpy (p, m, mlen); p += mlen;
655 nbits = count_bits (e, elen);
656 *p++ = nbits >> 8;
657 *p++ = nbits;
658 memcpy (p, e, elen); p += elen;
660 gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
662 xfree (buffer);
664 rc = iso7816_put_data (slot, 0,
665 (card_version > 0x0007? 0xC7 : 0xC6)
666 + keynumber, fpr, 20);
667 if (rc)
668 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
670 if (!rc && card_version > 0x0100)
672 unsigned char buf[4];
674 buf[0] = timestamp >> 24;
675 buf[1] = timestamp >> 16;
676 buf[2] = timestamp >> 8;
677 buf[3] = timestamp;
679 rc = iso7816_put_data (slot, 0, 0xCE + keynumber, buf, 4);
680 if (rc)
681 log_error (_("failed to store the creation date: %s\n"),
682 gpg_strerror (rc));
685 return rc;
689 static void
690 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
691 int number, const unsigned char *fpr)
693 int i;
694 char buf[41];
695 char numbuf[25];
697 for (i=0; i < 20 && !fpr[i]; i++)
699 if (i==20)
700 return; /* All zero. */
701 bin2hex (fpr, 20, buf);
702 if (number == -1)
703 *numbuf = 0; /* Don't print the key number */
704 else
705 sprintf (numbuf, "%d", number);
706 send_status_info (ctrl, keyword,
707 numbuf, (size_t)strlen(numbuf),
708 buf, (size_t)strlen (buf), NULL, 0);
711 static void
712 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
713 int number, const unsigned char *stamp)
715 char numbuf1[50], numbuf2[50];
716 unsigned long value;
718 value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
719 if (!value)
720 return;
721 sprintf (numbuf1, "%d", number);
722 sprintf (numbuf2, "%lu", value);
723 send_status_info (ctrl, keyword,
724 numbuf1, (size_t)strlen(numbuf1),
725 numbuf2, (size_t)strlen(numbuf2), NULL, 0);
728 static void
729 send_key_data (ctrl_t ctrl, const char *name,
730 const unsigned char *a, size_t alen)
732 char *buf;
734 buf = bin2hex (a, alen, NULL);
735 if (!buf)
737 log_error ("memory allocation error in send_key_data\n");
738 return;
741 send_status_info (ctrl, "KEY-DATA",
742 name, (size_t)strlen(name),
743 buf, (size_t)strlen (buf),
744 NULL, 0);
745 xfree (buf);
748 /* Implement the GETATTR command. This is similar to the LEARN
749 command but returns just one value via the status interface. */
750 static gpg_error_t
751 do_getattr (app_t app, ctrl_t ctrl, const char *name)
753 static struct {
754 const char *name;
755 int tag;
756 int special;
757 } table[] = {
758 { "DISP-NAME", 0x005B },
759 { "LOGIN-DATA", 0x005E },
760 { "DISP-LANG", 0x5F2D },
761 { "DISP-SEX", 0x5F35 },
762 { "PUBKEY-URL", 0x5F50 },
763 { "KEY-FPR", 0x00C5, 3 },
764 { "KEY-TIME", 0x00CD, 4 },
765 { "CA-FPR", 0x00C6, 3 },
766 { "CHV-STATUS", 0x00C4, 1 },
767 { "SIG-COUNTER", 0x0093, 2 },
768 { "SERIALNO", 0x004F, -1 },
769 { "AID", 0x004F },
770 { "EXTCAP", 0x0000, -2 },
771 { "PRIVATE-DO-1", 0x0101 },
772 { "PRIVATE-DO-2", 0x0102 },
773 { "PRIVATE-DO-3", 0x0103 },
774 { "PRIVATE-DO-4", 0x0104 },
775 { "$AUTHKEYID", 0x0000, -3 },
776 { "$DISPSERIALNO",0x0000, -4 },
777 { NULL, 0 }
779 int idx, i, rc;
780 void *relptr;
781 unsigned char *value;
782 size_t valuelen;
784 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
786 if (!table[idx].name)
787 return gpg_error (GPG_ERR_INV_NAME);
789 if (table[idx].special == -1)
791 /* The serial number is very special. We could have used the
792 AID DO to retrieve it, but we have it already in the app
793 context and the stamp argument is required anyway which we
794 can't by other means. The AID DO is available anyway but not
795 hex formatted. */
796 char *serial;
797 time_t stamp;
798 char tmp[50];
800 if (!app_get_serial_and_stamp (app, &serial, &stamp))
802 sprintf (tmp, "%lu", (unsigned long)stamp);
803 send_status_info (ctrl, "SERIALNO",
804 serial, strlen (serial),
805 tmp, strlen (tmp),
806 NULL, 0);
807 xfree (serial);
809 return 0;
811 if (table[idx].special == -2)
813 char tmp[50];
815 sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d mcl3=%u",
816 app->app_local->extcap.get_challenge,
817 app->app_local->extcap.key_import,
818 app->app_local->extcap.change_force_chv,
819 app->app_local->extcap.private_dos,
820 app->app_local->extcap.max_certlen_3);
821 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
822 return 0;
824 if (table[idx].special == -3)
826 char const tmp[] = "OPENPGP.3";
827 send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
828 return 0;
830 if (table[idx].special == -4)
832 char *serial;
833 time_t stamp;
835 if (!app_get_serial_and_stamp (app, &serial, &stamp))
837 if (strlen (serial) > 16+12)
839 send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
840 xfree (serial);
841 return 0;
843 xfree (serial);
845 return gpg_error (GPG_ERR_INV_NAME);
848 relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
849 if (relptr)
851 if (table[idx].special == 1)
853 char numbuf[7*23];
855 for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
856 sprintf (numbuf+strlen (numbuf), " %d", value[i]);
857 send_status_info (ctrl, table[idx].name,
858 numbuf, strlen (numbuf), NULL, 0);
860 else if (table[idx].special == 2)
862 char numbuf[50];
864 sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
865 send_status_info (ctrl, table[idx].name,
866 numbuf, strlen (numbuf), NULL, 0);
868 else if (table[idx].special == 3)
870 if (valuelen >= 60)
871 for (i=0; i < 3; i++)
872 send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
874 else if (table[idx].special == 4)
876 if (valuelen >= 12)
877 for (i=0; i < 3; i++)
878 send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
880 else
881 send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
883 xfree (relptr);
885 return rc;
888 /* Retrieve the fingerprint from the card inserted in SLOT and write
889 the according hex representation to FPR. Caller must have provide
890 a buffer at FPR of least 41 bytes. Returns 0 on success or an
891 error code. */
892 #if GNUPG_MAJOR_VERSION > 1
893 static gpg_error_t
894 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
896 gpg_error_t err = 0;
897 void *relptr;
898 unsigned char *value;
899 size_t valuelen;
901 assert (keyno >=0 && keyno <= 2);
903 relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
904 if (relptr && valuelen >= 60)
905 bin2hex (value+keyno*20, 20, fpr);
906 else
907 err = gpg_error (GPG_ERR_NOT_FOUND);
908 xfree (relptr);
909 return err;
911 #endif /*GNUPG_MAJOR_VERSION > 1*/
914 /* Retrieve the public key material for the RSA key, whose fingerprint
915 is FPR, from gpg output, which can be read through the stream FP.
916 The RSA modulus will be stored at the address of M and MLEN, the
917 public exponent at E and ELEN. Returns zero on success, an error
918 code on failure. Caller must release the allocated buffers at M
919 and E if the function returns success. */
920 #if GNUPG_MAJOR_VERSION > 1
921 static gpg_error_t
922 retrieve_key_material (FILE *fp, const char *hexkeyid,
923 const unsigned char **m, size_t *mlen,
924 const unsigned char **e, size_t *elen)
926 gcry_error_t err = 0;
927 char *line = NULL; /* read_line() buffer. */
928 size_t line_size = 0; /* Helper for for read_line. */
929 int found_key = 0; /* Helper to find a matching key. */
930 unsigned char *m_new = NULL;
931 unsigned char *e_new = NULL;
932 size_t m_new_n = 0;
933 size_t e_new_n = 0;
935 /* Loop over all records until we have found the subkey
936 corresponding to the fingerprint. Inm general the first record
937 should be the pub record, but we don't rely on that. Given that
938 we only need to look at one key, it is sufficient to compare the
939 keyid so that we don't need to look at "fpr" records. */
940 for (;;)
942 char *p;
943 char *fields[6];
944 int nfields;
945 size_t max_length;
946 gcry_mpi_t mpi;
947 int i;
949 max_length = 4096;
950 i = read_line (fp, &line, &line_size, &max_length);
951 if (!i)
952 break; /* EOF. */
953 if (i < 0)
955 err = gpg_error_from_syserror ();
956 goto leave; /* Error. */
958 if (!max_length)
960 err = gpg_error (GPG_ERR_TRUNCATED);
961 goto leave; /* Line truncated - we better stop processing. */
964 /* Parse the line into fields. */
965 for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
967 fields[nfields] = p;
968 p = strchr (p, ':');
969 if (p)
970 *(p++) = 0;
972 if (!nfields)
973 continue; /* No fields at all - skip line. */
975 if (!found_key)
977 if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
978 && nfields > 4 && !strcmp (fields[4], hexkeyid))
979 found_key = 1;
980 continue;
983 if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
984 break; /* Next key - stop. */
986 if ( strcmp (fields[0], "pkd") )
987 continue; /* Not a key data record. */
988 i = 0; /* Avoid erroneous compiler warning. */
989 if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
990 || (!i && m_new) || (i && e_new))
992 err = gpg_error (GPG_ERR_GENERAL);
993 goto leave; /* Error: Invalid key data record or not an RSA key. */
996 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
997 if (err)
998 mpi = NULL;
999 else if (!i)
1000 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1001 else
1002 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1003 gcry_mpi_release (mpi);
1004 if (err)
1005 goto leave;
1008 if (m_new && e_new)
1010 *m = m_new;
1011 *mlen = m_new_n;
1012 m_new = NULL;
1013 *e = e_new;
1014 *elen = e_new_n;
1015 e_new = NULL;
1017 else
1018 err = gpg_error (GPG_ERR_GENERAL);
1020 leave:
1021 xfree (m_new);
1022 xfree (e_new);
1023 xfree (line);
1024 return err;
1026 #endif /*GNUPG_MAJOR_VERSION > 1*/
1029 /* Get the public key for KEYNO and store it as an S-expresion with
1030 the APP handle. On error that field gets cleared. If we already
1031 know about the public key we will just return. Note that this does
1032 not mean a key is available; this is soley indicated by the
1033 presence of the app->app_local->pk[KEYNO-1].key field.
1035 Note that GnuPG 1.x does not need this and it would be too time
1036 consuming to send it just for the fun of it. However, given that we
1037 use the same code in gpg 1.4, we can't use the gcry S-expresion
1038 here but need to open encode it. */
1039 #if GNUPG_MAJOR_VERSION > 1
1040 static gpg_error_t
1041 get_public_key (app_t app, int keyno)
1043 gpg_error_t err = 0;
1044 unsigned char *buffer;
1045 const unsigned char *keydata, *m, *e;
1046 size_t buflen, keydatalen, mlen, elen;
1047 unsigned char *mbuf = NULL;
1048 unsigned char *ebuf = NULL;
1049 char *keybuf = NULL;
1050 char *keybuf_p;
1052 if (keyno < 1 || keyno > 3)
1053 return gpg_error (GPG_ERR_INV_ID);
1054 keyno--;
1056 /* Already cached? */
1057 if (app->app_local->pk[keyno].read_done)
1058 return 0;
1060 xfree (app->app_local->pk[keyno].key);
1061 app->app_local->pk[keyno].key = NULL;
1062 app->app_local->pk[keyno].keylen = 0;
1064 m = e = NULL; /* (avoid cc warning) */
1066 if (app->card_version > 0x0100)
1068 /* We may simply read the public key out of these cards. */
1069 err = iso7816_read_public_key
1070 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
1071 keyno == 1? "\xB8" : "\xA4"),
1073 &buffer, &buflen);
1074 if (err)
1076 log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1077 goto leave;
1080 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1081 if (!keydata)
1083 err = gpg_error (GPG_ERR_CARD);
1084 log_error (_("response does not contain the public key data\n"));
1085 goto leave;
1088 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1089 if (!m)
1091 err = gpg_error (GPG_ERR_CARD);
1092 log_error (_("response does not contain the RSA modulus\n"));
1093 goto leave;
1097 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1098 if (!e)
1100 err = gpg_error (GPG_ERR_CARD);
1101 log_error (_("response does not contain the RSA public exponent\n"));
1102 goto leave;
1105 /* Prepend numbers with a 0 if needed. */
1106 if (mlen && (*m & 0x80))
1108 mbuf = xtrymalloc ( mlen + 1);
1109 if (!mbuf)
1111 err = gpg_error_from_syserror ();
1112 goto leave;
1114 *mbuf = 0;
1115 memcpy (mbuf+1, m, mlen);
1116 mlen++;
1117 m = mbuf;
1119 if (elen && (*e & 0x80))
1121 ebuf = xtrymalloc ( elen + 1);
1122 if (!ebuf)
1124 err = gpg_error_from_syserror ();
1125 goto leave;
1127 *ebuf = 0;
1128 memcpy (ebuf+1, e, elen);
1129 elen++;
1130 e = ebuf;
1134 else
1136 /* Due to a design problem in v1.0 cards we can't get the public
1137 key out of these cards without doing a verify on CHV3.
1138 Clearly that is not an option and thus we try to locate the
1139 key using an external helper.
1141 The helper we use here is gpg itself, which should know about
1142 the key in any case. */
1144 char fpr[41];
1145 char *hexkeyid;
1146 char *command = NULL;
1147 FILE *fp;
1148 int ret;
1150 buffer = NULL; /* We don't need buffer. */
1152 err = retrieve_fpr_from_card (app, keyno, fpr);
1153 if (err)
1155 log_error ("error while retrieving fpr from card: %s\n",
1156 gpg_strerror (err));
1157 goto leave;
1159 hexkeyid = fpr + 24;
1161 ret = estream_asprintf (&command,
1162 "gpg --list-keys --with-colons --with-key-data '%s'",
1163 fpr);
1164 if (ret < 0)
1166 err = gpg_error_from_syserror ();
1167 goto leave;
1170 fp = popen (command, "r");
1171 xfree (command);
1172 if (!fp)
1174 err = gpg_error_from_syserror ();
1175 log_error ("running gpg failed: %s\n", gpg_strerror (err));
1176 goto leave;
1179 err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1180 fclose (fp);
1181 if (err)
1183 log_error ("error while retrieving key material through pipe: %s\n",
1184 gpg_strerror (err));
1185 goto leave;
1189 /* Allocate a buffer to construct the S-expression. */
1190 /* FIXME: We should provide a generalized S-expression creation
1191 mechanism. */
1192 keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1193 if (!keybuf)
1195 err = gpg_error_from_syserror ();
1196 goto leave;
1199 sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1200 keybuf_p = keybuf + strlen (keybuf);
1201 memcpy (keybuf_p, m, mlen);
1202 keybuf_p += mlen;
1203 sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1204 keybuf_p += strlen (keybuf_p);
1205 memcpy (keybuf_p, e, elen);
1206 keybuf_p += elen;
1207 strcpy (keybuf_p, ")))");
1208 keybuf_p += strlen (keybuf_p);
1210 app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1211 app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1213 leave:
1214 /* Set a flag to indicate that we tried to read the key. */
1215 app->app_local->pk[keyno].read_done = 1;
1217 xfree (buffer);
1218 xfree (mbuf);
1219 xfree (ebuf);
1220 return 0;
1222 #endif /* GNUPG_MAJOR_VERSION > 1 */
1226 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1227 This is used by the LEARN command. */
1228 static gpg_error_t
1229 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1231 gpg_error_t err = 0;
1232 /* Note that GnuPG 1.x does not need this and it would be too time
1233 consuming to send it just for the fun of it. */
1234 #if GNUPG_MAJOR_VERSION > 1
1235 unsigned char grip[20];
1236 char gripstr[41];
1237 char idbuf[50];
1239 err = get_public_key (app, keyno);
1240 if (err)
1241 goto leave;
1243 assert (keyno >= 1 && keyno <= 3);
1244 if (!app->app_local->pk[keyno-1].key)
1245 goto leave; /* No such key - ignore. */
1247 err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1248 app->app_local->pk[keyno-1].keylen,
1249 grip);
1250 if (err)
1251 goto leave;
1253 bin2hex (grip, 20, gripstr);
1255 sprintf (idbuf, "OPENPGP.%d", keyno);
1256 send_status_info (ctrl, "KEYPAIRINFO",
1257 gripstr, 40,
1258 idbuf, strlen (idbuf),
1259 NULL, (size_t)0);
1261 leave:
1262 #endif /* GNUPG_MAJOR_VERSION > 1 */
1264 return err;
1268 /* Handle the LEARN command for OpenPGP. */
1269 static gpg_error_t
1270 do_learn_status (app_t app, ctrl_t ctrl)
1272 do_getattr (app, ctrl, "EXTCAP");
1273 do_getattr (app, ctrl, "DISP-NAME");
1274 do_getattr (app, ctrl, "DISP-LANG");
1275 do_getattr (app, ctrl, "DISP-SEX");
1276 do_getattr (app, ctrl, "PUBKEY-URL");
1277 do_getattr (app, ctrl, "LOGIN-DATA");
1278 do_getattr (app, ctrl, "KEY-FPR");
1279 if (app->card_version > 0x0100)
1280 do_getattr (app, ctrl, "KEY-TIME");
1281 do_getattr (app, ctrl, "CA-FPR");
1282 do_getattr (app, ctrl, "CHV-STATUS");
1283 do_getattr (app, ctrl, "SIG-COUNTER");
1284 if (app->app_local->extcap.private_dos)
1286 do_getattr (app, ctrl, "PRIVATE-DO-1");
1287 do_getattr (app, ctrl, "PRIVATE-DO-2");
1288 if (app->did_chv2)
1289 do_getattr (app, ctrl, "PRIVATE-DO-3");
1290 if (app->did_chv3)
1291 do_getattr (app, ctrl, "PRIVATE-DO-4");
1293 send_keypair_info (app, ctrl, 1);
1294 send_keypair_info (app, ctrl, 2);
1295 send_keypair_info (app, ctrl, 3);
1296 /* Note: We do not send the Cardholder Certificate, because that is
1297 relativly long and for OpenPGP applications not really needed. */
1298 return 0;
1302 /* Handle the READKEY command for OpenPGP. On success a canonical
1303 encoded S-expression with the public key will get stored at PK and
1304 its length (for assertions) at PKLEN; the caller must release that
1305 buffer. On error PK and PKLEN are not changed and an error code is
1306 returned. */
1307 static gpg_error_t
1308 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1310 #if GNUPG_MAJOR_VERSION > 1
1311 gpg_error_t err;
1312 int keyno;
1313 unsigned char *buf;
1315 if (!strcmp (keyid, "OPENPGP.1"))
1316 keyno = 1;
1317 else if (!strcmp (keyid, "OPENPGP.2"))
1318 keyno = 2;
1319 else if (!strcmp (keyid, "OPENPGP.3"))
1320 keyno = 3;
1321 else
1322 return gpg_error (GPG_ERR_INV_ID);
1324 err = get_public_key (app, keyno);
1325 if (err)
1326 return err;
1328 buf = app->app_local->pk[keyno-1].key;
1329 if (!buf)
1330 return gpg_error (GPG_ERR_NO_PUBKEY);
1331 *pklen = app->app_local->pk[keyno-1].keylen;;
1332 *pk = xtrymalloc (*pklen);
1333 if (!*pk)
1335 err = gpg_error_from_syserror ();
1336 *pklen = 0;
1337 return err;
1339 memcpy (*pk, buf, *pklen);
1340 return 0;
1341 #else
1342 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1343 #endif
1346 /* Read the standard certificate of an OpenPGP v2 card. It is
1347 returned in a freshly allocated buffer with that address stored at
1348 CERT and the length of the certificate stored at CERTLEN. CERTID
1349 needs to be set to "OPENPGP.3". */
1350 static gpg_error_t
1351 do_readcert (app_t app, const char *certid,
1352 unsigned char **cert, size_t *certlen)
1354 #if GNUPG_MAJOR_VERSION > 1
1355 gpg_error_t err;
1356 unsigned char *buffer;
1357 size_t buflen;
1358 void *relptr;
1360 *cert = NULL;
1361 *certlen = 0;
1362 if (strcmp (certid, "OPENPGP.3"))
1363 return gpg_error (GPG_ERR_INV_ID);
1364 if (!app->app_local->extcap.is_v2)
1365 return gpg_error (GPG_ERR_NOT_FOUND);
1367 relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1368 if (!relptr)
1369 return gpg_error (GPG_ERR_NOT_FOUND);
1371 *cert = xtrymalloc (buflen);
1372 if (!*cert)
1373 err = gpg_error_from_syserror ();
1374 else
1376 memcpy (*cert, buffer, buflen);
1377 *certlen = buflen;
1378 err = 0;
1380 xfree (relptr);
1381 return err;
1382 #else
1383 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1384 #endif
1388 /* Verify a CHV either using using the pinentry or if possibile by
1389 using a keypad. PINCB and PINCB_ARG describe the usual callback
1390 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1391 used with CHV1. PINVALUE is the address of a pointer which will
1392 receive a newly allocated block with the actual PIN (this is useful
1393 in case that PIN shall be used for another verifiy operation). The
1394 caller needs to free this value. If the function returns with
1395 success and NULL is stored at PINVALUE, the caller should take this
1396 as an indication that the keypad has been used.
1398 static gpg_error_t
1399 verify_a_chv (app_t app,
1400 gpg_error_t (*pincb)(void*, const char *, char **),
1401 void *pincb_arg,
1402 int chvno, unsigned long sigcount, char **pinvalue)
1404 int rc = 0;
1405 char *prompt;
1406 iso7816_pininfo_t pininfo;
1407 int minlen = 6;
1409 assert (chvno == 1 || chvno == 2);
1411 *pinvalue = NULL;
1413 if (chvno == 2 && app->app_local->flags.def_chv2)
1415 /* Special case for def_chv2 mechanism. */
1416 if (opt.verbose)
1417 log_info (_("using default PIN as %s\n"), "CHV2");
1418 rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1419 if (rc)
1421 /* Verification of CHV2 with the default PIN failed,
1422 although the card pretends to have the default PIN set as
1423 CHV2. We better disable the def_chv2 flag now. */
1424 log_info (_("failed to use default PIN as %s: %s"
1425 " - disabling further default use\n"),
1426 "CHV2", gpg_strerror (rc));
1427 app->app_local->flags.def_chv2 = 0;
1429 return rc;
1432 memset (&pininfo, 0, sizeof pininfo);
1433 pininfo.mode = 1;
1434 pininfo.minlen = minlen;
1436 if (!opt.disable_keypad
1437 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1439 /* The reader supports the verify command through the keypad. */
1441 if (chvno == 1)
1443 #define PROMPTSTRING _("||Please enter your PIN at the reader's keypad%%0A" \
1444 "[sigs done: %lu]")
1445 size_t promptsize = strlen (PROMPTSTRING) + 50;
1447 prompt = xmalloc (promptsize);
1448 if (!prompt)
1449 return gpg_error_from_syserror ();
1450 snprintf (prompt, promptsize-1, PROMPTSTRING, sigcount);
1451 rc = pincb (pincb_arg, prompt, NULL);
1452 xfree (prompt);
1453 #undef PROMPTSTRING
1455 else
1456 rc = pincb (pincb_arg,
1457 _("||Please enter your PIN at the reader's keypad"),
1458 NULL);
1459 if (rc)
1461 log_info (_("PIN callback returned error: %s\n"),
1462 gpg_strerror (rc));
1463 return rc;
1465 rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1466 /* Dismiss the prompt. */
1467 pincb (pincb_arg, NULL, NULL);
1469 assert (!*pinvalue);
1471 else
1473 /* The reader has no keypad or we don't want to use it. */
1475 if (chvno == 1)
1477 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1478 size_t promptsize = strlen (PROMPTSTRING) + 50;
1480 prompt = xtrymalloc (promptsize);
1481 if (!prompt)
1482 return gpg_error_from_syserror ();
1483 snprintf (prompt, promptsize-1, PROMPTSTRING, sigcount);
1484 rc = pincb (pincb_arg, prompt, pinvalue);
1485 xfree (prompt);
1486 #undef PROMPTSTRING
1488 else
1489 rc = pincb (pincb_arg, _("||Please enter the PIN"), pinvalue);
1491 if (rc)
1493 log_info (_("PIN callback returned error: %s\n"),
1494 gpg_strerror (rc));
1495 return rc;
1498 if (strlen (*pinvalue) < minlen)
1500 log_error (_("PIN for CHV%d is too short;"
1501 " minimum length is %d\n"), chvno, minlen);
1502 xfree (*pinvalue);
1503 *pinvalue = NULL;
1504 return gpg_error (GPG_ERR_BAD_PIN);
1507 rc = iso7816_verify (app->slot, 0x80+chvno,
1508 *pinvalue, strlen (*pinvalue));
1511 if (rc)
1513 log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1514 xfree (*pinvalue);
1515 *pinvalue = NULL;
1516 flush_cache_after_error (app);
1519 return rc;
1523 /* Verify CHV2 if required. Depending on the configuration of the
1524 card CHV1 will also be verified. */
1525 static gpg_error_t
1526 verify_chv2 (app_t app,
1527 gpg_error_t (*pincb)(void*, const char *, char **),
1528 void *pincb_arg)
1530 int rc;
1531 char *pinvalue;
1533 if (app->did_chv2)
1534 return 0; /* We already verified CHV2. */
1536 rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1537 if (rc)
1538 return rc;
1540 app->did_chv2 = 1;
1542 if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1544 /* For convenience we verify CHV1 here too. We do this only if
1545 the card is not configured to require a verification before
1546 each CHV1 controlled operation (force_chv1) and if we are not
1547 using the keypad (PINVALUE == NULL). */
1548 rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1549 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1550 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1551 if (rc)
1553 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1554 flush_cache_after_error (app);
1556 else
1557 app->did_chv1 = 1;
1559 xfree (pinvalue);
1561 return rc;
1565 /* Verify CHV3 if required. */
1566 static gpg_error_t
1567 verify_chv3 (app_t app,
1568 gpg_error_t (*pincb)(void*, const char *, char **),
1569 void *pincb_arg)
1571 int rc = 0;
1573 #if GNUPG_MAJOR_VERSION != 1
1574 if (!opt.allow_admin)
1576 log_info (_("access to admin commands is not configured\n"));
1577 return gpg_error (GPG_ERR_EACCES);
1579 #endif
1581 if (!app->did_chv3)
1583 void *relptr;
1584 unsigned char *value;
1585 size_t valuelen;
1586 iso7816_pininfo_t pininfo;
1587 int minlen = 8;
1588 int remaining;
1590 memset (&pininfo, 0, sizeof pininfo);
1591 pininfo.mode = 1;
1592 pininfo.minlen = minlen;
1594 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1595 if (!relptr || valuelen < 7)
1597 log_error (_("error retrieving CHV status from card\n"));
1598 xfree (relptr);
1599 return gpg_error (GPG_ERR_CARD);
1601 if (value[6] == 0)
1603 log_info (_("card is permanently locked!\n"));
1604 xfree (relptr);
1605 return gpg_error (GPG_ERR_BAD_PIN);
1607 remaining = value[6];
1608 xfree (relptr);
1610 log_info(_("%d Admin PIN attempts remaining before card"
1611 " is permanently locked\n"), remaining);
1613 if (!opt.disable_keypad
1614 && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1616 /* The reader supports the verify command through the keypad. */
1618 if (remaining < 3)
1620 #define PROMPTSTRING _("|A|Please enter the Admin PIN" \
1621 " at the reader's keypad%%0A" \
1622 "[remaining attempts: %d]")
1623 size_t promptsize = strlen (PROMPTSTRING) + 50;
1624 char *prompt;
1626 prompt = xmalloc (promptsize);
1627 if (!prompt)
1628 return gpg_error_from_syserror ();
1629 snprintf (prompt, promptsize-1, PROMPTSTRING, remaining);
1630 rc = pincb (pincb_arg, prompt, NULL);
1631 xfree (prompt);
1632 #undef PROMPTSTRING
1634 else
1635 rc = pincb (pincb_arg, _("|A|Please enter the Admin PIN"
1636 " at the reader's keypad"), NULL);
1638 if (rc)
1640 log_info (_("PIN callback returned error: %s\n"),
1641 gpg_strerror (rc));
1642 return rc;
1644 rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1645 /* Dismiss the prompt. */
1646 pincb (pincb_arg, NULL, NULL);
1648 else
1650 char *pinvalue;
1652 /* TRANSLATORS: Do not translate the "|A|" prefix but keep
1653 it at the start of the string. We need this elsewhere to
1654 get some infos on the string. */
1655 rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue);
1656 if (rc)
1658 log_info (_("PIN callback returned error: %s\n"),
1659 gpg_strerror (rc));
1660 return rc;
1663 if (strlen (pinvalue) < minlen)
1665 log_error (_("PIN for CHV%d is too short;"
1666 " minimum length is %d\n"), 3, minlen);
1667 xfree (pinvalue);
1668 return gpg_error (GPG_ERR_BAD_PIN);
1671 rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1672 xfree (pinvalue);
1675 if (rc)
1677 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1678 flush_cache_after_error (app);
1679 return rc;
1681 app->did_chv3 = 1;
1683 return rc;
1687 /* Handle the SETATTR operation. All arguments are already basically
1688 checked. */
1689 static gpg_error_t
1690 do_setattr (app_t app, const char *name,
1691 gpg_error_t (*pincb)(void*, const char *, char **),
1692 void *pincb_arg,
1693 const unsigned char *value, size_t valuelen)
1695 gpg_error_t rc;
1696 int idx;
1697 static struct {
1698 const char *name;
1699 int tag;
1700 int need_chv;
1701 int special;
1702 unsigned int need_v2:1;
1703 } table[] = {
1704 { "DISP-NAME", 0x005B, 3 },
1705 { "LOGIN-DATA", 0x005E, 3, 2 },
1706 { "DISP-LANG", 0x5F2D, 3 },
1707 { "DISP-SEX", 0x5F35, 3 },
1708 { "PUBKEY-URL", 0x5F50, 3 },
1709 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1710 { "CA-FPR-1", 0x00CA, 3 },
1711 { "CA-FPR-2", 0x00CB, 3 },
1712 { "CA-FPR-3", 0x00CC, 3 },
1713 { "PRIVATE-DO-1", 0x0101, 2 },
1714 { "PRIVATE-DO-2", 0x0102, 3 },
1715 { "PRIVATE-DO-3", 0x0103, 2 },
1716 { "PRIVATE-DO-4", 0x0104, 3 },
1717 { "CERT-3", 0x7F21, 3, 0, 1 },
1718 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1719 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1720 { NULL, 0 }
1722 int exmode;
1724 for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1726 if (!table[idx].name)
1727 return gpg_error (GPG_ERR_INV_NAME);
1728 if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1729 return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1731 switch (table[idx].need_chv)
1733 case 2:
1734 rc = verify_chv2 (app, pincb, pincb_arg);
1735 break;
1736 case 3:
1737 rc = verify_chv3 (app, pincb, pincb_arg);
1738 break;
1739 default:
1740 rc = 0;
1742 if (rc)
1743 return rc;
1745 /* Flush the cache before writing it, so that the next get operation
1746 will reread the data from the card and thus get synced in case of
1747 errors (e.g. data truncated by the card). */
1748 flush_cache_item (app, table[idx].tag);
1749 /* For command chaining we use a value of 254 for this card. */
1750 if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1751 exmode = -254;
1752 else
1753 exmode = 0;
1754 rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1755 if (rc)
1756 log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1758 if (table[idx].special == 1)
1759 app->force_chv1 = (valuelen && *value == 0);
1760 else if (table[idx].special == 2)
1761 parse_login_data (app);
1763 return rc;
1767 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1768 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1769 PINCB and PINCB_ARG are the usual arguments for the pinentry
1770 callback. */
1771 static gpg_error_t
1772 do_writecert (app_t app, ctrl_t ctrl,
1773 const char *certidstr,
1774 gpg_error_t (*pincb)(void*, const char *, char **),
1775 void *pincb_arg,
1776 const unsigned char *certdata, size_t certdatalen)
1778 (void)ctrl;
1779 #if GNUPG_MAJOR_VERSION > 1
1780 if (strcmp (certidstr, "OPENPGP.3"))
1781 return gpg_error (GPG_ERR_INV_ID);
1782 if (!certdata || !certdatalen)
1783 return gpg_error (GPG_ERR_INV_ARG);
1784 if (!app->app_local->extcap.is_v2)
1785 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1786 if (certdatalen > app->app_local->extcap.max_certlen_3)
1787 return gpg_error (GPG_ERR_TOO_LARGE);
1788 return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1789 #else
1790 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1791 #endif
1796 /* Handle the PASSWD command. */
1797 static gpg_error_t
1798 do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
1799 unsigned int flags,
1800 gpg_error_t (*pincb)(void*, const char *, char **),
1801 void *pincb_arg)
1803 int rc = 0;
1804 int chvno = atoi (chvnostr);
1805 char *resetcode = NULL;
1806 char *pinvalue;
1807 int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1808 int set_resetcode = 0;
1810 (void)ctrl;
1812 if (reset_mode && chvno == 3)
1814 rc = gpg_error (GPG_ERR_INV_ID);
1815 goto leave;
1817 else if (reset_mode || chvno == 3)
1819 /* We always require that the PIN is entered. */
1820 app->did_chv3 = 0;
1821 rc = verify_chv3 (app, pincb, pincb_arg);
1822 if (rc)
1823 goto leave;
1825 if (chvno == 2 && app->app_local->extcap.is_v2)
1826 set_resetcode = 1;
1828 else if (chvno == 2 && app->app_local->extcap.is_v2)
1830 /* There is no PW2 for v2 cards. We use this condition to allow
1831 a PW reset using the Reset Code. */
1832 void *relptr;
1833 unsigned char *value;
1834 size_t valuelen;
1835 int remaining;
1837 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1838 if (!relptr || valuelen < 7)
1840 log_error (_("error retrieving CHV status from card\n"));
1841 xfree (relptr);
1842 rc = gpg_error (GPG_ERR_CARD);
1843 goto leave;
1845 remaining = value[5];
1846 xfree (relptr);
1847 if (!remaining)
1849 log_error (_("Reset Code not or not anymore available\n"));
1850 rc = gpg_error (GPG_ERR_BAD_PIN);
1851 goto leave;
1854 rc = pincb (pincb_arg, _("||Please enter the Reset Code for the card"),
1855 &resetcode);
1856 if (rc)
1858 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
1859 goto leave;
1861 if (strlen (resetcode) < 8)
1863 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1864 rc = gpg_error (GPG_ERR_BAD_PIN);
1865 goto leave;
1868 else if (chvno == 1 || chvno == 2)
1870 /* CHV1 and CVH2 should always have the same value, thus we
1871 enforce it here. */
1872 int save_force = app->force_chv1;
1874 app->force_chv1 = 0;
1875 app->did_chv1 = 0;
1876 app->did_chv2 = 0;
1877 rc = verify_chv2 (app, pincb, pincb_arg);
1878 app->force_chv1 = save_force;
1879 if (rc)
1880 goto leave;
1882 else
1884 rc = gpg_error (GPG_ERR_INV_ID);
1885 goto leave;
1888 if (chvno == 3)
1889 app->did_chv3 = 0;
1890 else
1891 app->did_chv1 = app->did_chv2 = 0;
1893 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1894 keep it at the start of the string. We need this elsewhere
1895 to get some infos on the string. */
1896 rc = pincb (pincb_arg,
1897 set_resetcode? _("|RN|New Reset Code") :
1898 chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1899 &pinvalue);
1900 if (rc)
1902 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
1903 goto leave;
1906 if (resetcode)
1908 char *buffer;
1910 buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
1911 if (!buffer)
1912 rc = gpg_error_from_syserror ();
1913 else
1915 strcpy (stpcpy (buffer, resetcode), pinvalue);
1916 rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
1917 buffer, strlen (buffer));
1918 wipememory (buffer, strlen (buffer));
1919 xfree (buffer);
1922 else if (set_resetcode)
1924 if (strlen (pinvalue) < 8)
1926 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1927 rc = gpg_error (GPG_ERR_BAD_PIN);
1929 else
1930 rc = iso7816_put_data (app->slot, 0, 0xD3,
1931 pinvalue, strlen (pinvalue));
1933 else if (reset_mode)
1935 rc = iso7816_reset_retry_counter (app->slot, 0x81,
1936 pinvalue, strlen (pinvalue));
1937 if (!rc && !app->app_local->extcap.is_v2)
1938 rc = iso7816_reset_retry_counter (app->slot, 0x82,
1939 pinvalue, strlen (pinvalue));
1941 else
1943 if (chvno == 1 || chvno == 2)
1945 rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
1946 pinvalue, strlen (pinvalue));
1947 if (!rc && !app->app_local->extcap.is_v2)
1948 rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
1949 pinvalue, strlen (pinvalue));
1951 else
1952 rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
1953 pinvalue, strlen (pinvalue));
1955 if (pinvalue)
1957 wipememory (pinvalue, strlen (pinvalue));
1958 xfree (pinvalue);
1960 if (rc)
1961 flush_cache_after_error (app);
1963 leave:
1964 if (resetcode)
1966 wipememory (resetcode, strlen (resetcode));
1967 xfree (resetcode);
1969 return rc;
1973 /* Check whether a key already exists. KEYIDX is the index of the key
1974 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1975 error returned if the key already exists. */
1976 static gpg_error_t
1977 does_key_exist (app_t app, int keyidx, int force)
1979 const unsigned char *fpr;
1980 unsigned char *buffer;
1981 size_t buflen, n;
1982 int i;
1984 assert (keyidx >=0 && keyidx <= 2);
1986 if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
1988 log_error (_("error reading application data\n"));
1989 return gpg_error (GPG_ERR_GENERAL);
1991 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1992 if (!fpr || n < 60)
1994 log_error (_("error reading fingerprint DO\n"));
1995 xfree (buffer);
1996 return gpg_error (GPG_ERR_GENERAL);
1998 fpr += 20*keyidx;
1999 for (i=0; i < 20 && !fpr[i]; i++)
2001 xfree (buffer);
2002 if (i!=20 && !force)
2004 log_error (_("key already exists\n"));
2005 return gpg_error (GPG_ERR_EEXIST);
2007 else if (i!=20)
2008 log_info (_("existing key will be replaced\n"));
2009 else
2010 log_info (_("generating new key\n"));
2011 return 0;
2015 /* Create a TLV tag and value and store it at BUFFER. Return the length
2016 of tag and length. A LENGTH greater than 65535 is truncated. */
2017 static size_t
2018 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2020 unsigned char *p = buffer;
2022 assert (tag <= 0xffff);
2023 if ( tag > 0xff )
2024 *p++ = tag >> 8;
2025 *p++ = tag;
2026 if (length < 128)
2027 *p++ = length;
2028 else if (length < 256)
2030 *p++ = 0x81;
2031 *p++ = length;
2033 else
2035 if (length > 0xffff)
2036 length = 0xffff;
2037 *p++ = 0x82;
2038 *p++ = length >> 8;
2039 *p++ = length;
2042 return p - buffer;
2046 /* Build the private key template as specified in the OpenPGP specs
2047 v2.0 section 4.3.3.7. */
2048 static gpg_error_t
2049 build_privkey_template (app_t app, int keyno,
2050 const unsigned char *rsa_n, size_t rsa_n_len,
2051 const unsigned char *rsa_e, size_t rsa_e_len,
2052 const unsigned char *rsa_p, size_t rsa_p_len,
2053 const unsigned char *rsa_q, size_t rsa_q_len,
2054 unsigned char **result, size_t *resultlen)
2056 size_t rsa_e_reqlen;
2057 unsigned char privkey[7*(1+3)];
2058 size_t privkey_len;
2059 unsigned char exthdr[2+2+3];
2060 size_t exthdr_len;
2061 unsigned char suffix[2+3];
2062 size_t suffix_len;
2063 unsigned char *tp;
2064 size_t datalen;
2065 unsigned char *template;
2066 size_t template_size;
2068 *result = NULL;
2069 *resultlen = 0;
2071 switch (app->app_local->keyattr[keyno].format)
2073 case RSA_STD:
2074 case RSA_STD_N:
2075 break;
2076 case RSA_CRT:
2077 case RSA_CRT_N:
2078 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2080 default:
2081 return gpg_error (GPG_ERR_INV_VALUE);
2084 /* Get the required length for E. */
2085 rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2086 assert (rsa_e_len <= rsa_e_reqlen);
2088 /* Build the 7f48 cardholder private key template. */
2089 datalen = 0;
2090 tp = privkey;
2092 tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2093 datalen += rsa_e_reqlen;
2095 tp += add_tlv (tp, 0x92, rsa_p_len);
2096 datalen += rsa_p_len;
2098 tp += add_tlv (tp, 0x93, rsa_q_len);
2099 datalen += rsa_q_len;
2101 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2102 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2104 tp += add_tlv (tp, 0x97, rsa_n_len);
2105 datalen += rsa_n_len;
2107 privkey_len = tp - privkey;
2109 /* Build the extended header list without the private key template. */
2110 tp = exthdr;
2111 *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2112 *tp++ = 0;
2113 tp += add_tlv (tp, 0x7f48, privkey_len);
2114 exthdr_len = tp - exthdr;
2116 /* Build the 5f48 suffix of the data. */
2117 tp = suffix;
2118 tp += add_tlv (tp, 0x5f48, datalen);
2119 suffix_len = tp - suffix;
2121 /* Now concatenate everything. */
2122 template_size = (1 + 3 /* 0x4d and len. */
2123 + exthdr_len
2124 + privkey_len
2125 + suffix_len
2126 + datalen);
2127 tp = template = xtrymalloc_secure (template_size);
2128 if (!template)
2129 return gpg_error_from_syserror ();
2131 tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2132 memcpy (tp, exthdr, exthdr_len);
2133 tp += exthdr_len;
2134 memcpy (tp, privkey, privkey_len);
2135 tp += privkey_len;
2136 memcpy (tp, suffix, suffix_len);
2137 tp += suffix_len;
2139 memcpy (tp, rsa_e, rsa_e_len);
2140 if (rsa_e_len < rsa_e_reqlen)
2142 /* Right justify E. */
2143 memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2144 memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2146 tp += rsa_e_reqlen;
2148 memcpy (tp, rsa_p, rsa_p_len);
2149 tp += rsa_p_len;
2151 memcpy (tp, rsa_q, rsa_q_len);
2152 tp += rsa_q_len;
2154 if (app->app_local->keyattr[keyno].format == RSA_STD_N
2155 || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2157 memcpy (tp, rsa_n, rsa_n_len);
2158 tp += rsa_n_len;
2161 /* Sanity check. We don't know the exact length because we
2162 allocated 3 bytes for the first length header. */
2163 assert (tp - template <= template_size);
2165 *result = template;
2166 *resultlen = tp - template;
2167 return 0;
2172 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2173 canonical encoded S-expression with the secret key in KEYDATA and
2174 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2175 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2176 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2177 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2178 the pinentry callback. */
2179 static gpg_error_t
2180 do_writekey (app_t app, ctrl_t ctrl,
2181 const char *keyid, unsigned int flags,
2182 gpg_error_t (*pincb)(void*, const char *, char **),
2183 void *pincb_arg,
2184 const unsigned char *keydata, size_t keydatalen)
2186 gpg_error_t err;
2187 int force = (flags & 1);
2188 int keyno;
2189 const unsigned char *buf, *tok;
2190 size_t buflen, toklen;
2191 int depth, last_depth1, last_depth2;
2192 const unsigned char *rsa_n = NULL;
2193 const unsigned char *rsa_e = NULL;
2194 const unsigned char *rsa_p = NULL;
2195 const unsigned char *rsa_q = NULL;
2196 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2197 unsigned int nbits;
2198 unsigned int maxbits;
2199 unsigned char *template = NULL;
2200 unsigned char *tp;
2201 size_t template_len;
2202 unsigned char fprbuf[20];
2203 u32 created_at = 0;
2205 (void)ctrl;
2207 if (!strcmp (keyid, "OPENPGP.1"))
2208 keyno = 0;
2209 else if (!strcmp (keyid, "OPENPGP.2"))
2210 keyno = 1;
2211 else if (!strcmp (keyid, "OPENPGP.3"))
2212 keyno = 2;
2213 else
2214 return gpg_error (GPG_ERR_INV_ID);
2216 err = does_key_exist (app, keyno, force);
2217 if (err)
2218 return err;
2222 Parse the S-expression
2224 buf = keydata;
2225 buflen = keydatalen;
2226 depth = 0;
2227 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2228 goto leave;
2229 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2230 goto leave;
2231 if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2233 if (!tok)
2235 else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2236 log_info ("protected-private-key passed to writekey\n");
2237 else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2238 log_info ("shadowed-private-key passed to writekey\n");
2239 err = gpg_error (GPG_ERR_BAD_SECKEY);
2240 goto leave;
2242 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2243 goto leave;
2244 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2245 goto leave;
2246 if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2248 err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2249 goto leave;
2251 last_depth1 = depth;
2252 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2253 && depth && depth >= last_depth1)
2255 if (tok)
2257 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2258 goto leave;
2260 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2261 goto leave;
2262 if (tok && toklen == 1)
2264 const unsigned char **mpi;
2265 size_t *mpi_len;
2267 switch (*tok)
2269 case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2270 case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2271 case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2272 case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2273 default: mpi = NULL; mpi_len = NULL; break;
2275 if (mpi && *mpi)
2277 err = gpg_error (GPG_ERR_DUP_VALUE);
2278 goto leave;
2280 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2281 goto leave;
2282 if (tok && mpi)
2284 /* Strip off leading zero bytes and save. */
2285 for (;toklen && !*tok; toklen--, tok++)
2287 *mpi = tok;
2288 *mpi_len = toklen;
2291 /* Skip until end of list. */
2292 last_depth2 = depth;
2293 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2294 && depth && depth >= last_depth2)
2296 if (err)
2297 goto leave;
2299 /* Parse other attributes. */
2300 last_depth1 = depth;
2301 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2302 && depth && depth >= last_depth1)
2304 if (tok)
2306 err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2307 goto leave;
2309 if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2310 goto leave;
2311 if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2313 if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2314 goto leave;
2315 if (tok)
2317 for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2318 tok++, toklen--)
2319 created_at = created_at*10 + (*tok - '0');
2322 /* Skip until end of list. */
2323 last_depth2 = depth;
2324 while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2325 && depth && depth >= last_depth2)
2327 if (err)
2328 goto leave;
2332 /* Check that we have all parameters and that they match the card
2333 description. */
2334 if (!created_at)
2336 log_error (_("creation timestamp missing\n"));
2337 err = gpg_error (GPG_ERR_INV_VALUE);
2338 goto leave;
2341 maxbits = app->app_local->keyattr[keyno].n_bits;
2342 nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2343 if (nbits != maxbits)
2345 log_error (_("RSA modulus missing or not of size %d bits\n"),
2346 (int)maxbits);
2347 err = gpg_error (GPG_ERR_BAD_SECKEY);
2348 goto leave;
2351 maxbits = app->app_local->keyattr[keyno].e_bits;
2352 if (maxbits > 32 && !app->app_local->extcap.is_v2)
2353 maxbits = 32; /* Our code for v1 does only support 32 bits. */
2354 nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2355 if (nbits < 2 || nbits > maxbits)
2357 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2358 (int)maxbits);
2359 err = gpg_error (GPG_ERR_BAD_SECKEY);
2360 goto leave;
2363 maxbits = app->app_local->keyattr[keyno].n_bits/2;
2364 nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2365 if (nbits != maxbits)
2367 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2368 "P", (int)maxbits);
2369 err = gpg_error (GPG_ERR_BAD_SECKEY);
2370 goto leave;
2372 nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2373 if (nbits != maxbits)
2375 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2376 "Q", (int)maxbits);
2377 err = gpg_error (GPG_ERR_BAD_SECKEY);
2378 goto leave;
2381 /* We need to remove the cached public key. */
2382 xfree (app->app_local->pk[keyno].key);
2383 app->app_local->pk[keyno].key = NULL;
2384 app->app_local->pk[keyno].keylen = 0;
2385 app->app_local->pk[keyno].read_done = 0;
2388 if (app->app_local->extcap.is_v2)
2390 /* Build the private key template as described in section 4.3.3.7 of
2391 the OpenPGP card specs version 2.0. */
2392 int exmode;
2394 err = build_privkey_template (app, keyno,
2395 rsa_n, rsa_n_len,
2396 rsa_e, rsa_e_len,
2397 rsa_p, rsa_p_len,
2398 rsa_q, rsa_q_len,
2399 &template, &template_len);
2400 if (err)
2401 goto leave;
2403 /* Prepare for storing the key. */
2404 err = verify_chv3 (app, pincb, pincb_arg);
2405 if (err)
2406 goto leave;
2408 /* Store the key. */
2409 if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2410 exmode = -254;
2411 else
2412 exmode = 0;
2413 err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2414 template, template_len);
2416 else
2418 /* Build the private key template as described in section 4.3.3.6 of
2419 the OpenPGP card specs version 1.1:
2420 0xC0 <length> public exponent
2421 0xC1 <length> prime p
2422 0xC2 <length> prime q
2424 assert (rsa_e_len <= 4);
2425 template_len = (1 + 1 + 4
2426 + 1 + 1 + rsa_p_len
2427 + 1 + 1 + rsa_q_len);
2428 template = tp = xtrymalloc_secure (template_len);
2429 if (!template)
2431 err = gpg_error_from_syserror ();
2432 goto leave;
2434 *tp++ = 0xC0;
2435 *tp++ = 4;
2436 memcpy (tp, rsa_e, rsa_e_len);
2437 if (rsa_e_len < 4)
2439 /* Right justify E. */
2440 memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2441 memset (tp, 0, 4-rsa_e_len);
2443 tp += 4;
2445 *tp++ = 0xC1;
2446 *tp++ = rsa_p_len;
2447 memcpy (tp, rsa_p, rsa_p_len);
2448 tp += rsa_p_len;
2450 *tp++ = 0xC2;
2451 *tp++ = rsa_q_len;
2452 memcpy (tp, rsa_q, rsa_q_len);
2453 tp += rsa_q_len;
2455 assert (tp - template == template_len);
2457 /* Prepare for storing the key. */
2458 err = verify_chv3 (app, pincb, pincb_arg);
2459 if (err)
2460 goto leave;
2462 /* Store the key. */
2463 err = iso7816_put_data (app->slot, 0,
2464 (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2465 template, template_len);
2467 if (err)
2469 log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2470 goto leave;
2473 err = store_fpr (app->slot, keyno, created_at,
2474 rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2475 fprbuf, app->card_version);
2476 if (err)
2477 goto leave;
2480 leave:
2481 xfree (template);
2482 return err;
2486 /* Handle the GENKEY command. */
2487 static gpg_error_t
2488 do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
2489 time_t createtime,
2490 gpg_error_t (*pincb)(void*, const char *, char **),
2491 void *pincb_arg)
2493 int rc;
2494 char numbuf[30];
2495 unsigned char fprbuf[20];
2496 const unsigned char *keydata, *m, *e;
2497 unsigned char *buffer = NULL;
2498 size_t buflen, keydatalen, mlen, elen;
2499 time_t created_at;
2500 int keyno = atoi (keynostr);
2501 int force = (flags & 1);
2502 time_t start_at;
2504 if (keyno < 1 || keyno > 3)
2505 return gpg_error (GPG_ERR_INV_ID);
2506 keyno--;
2508 /* We flush the cache to increase the traffic before a key
2509 generation. This _might_ help a card to gather more entropy. */
2510 flush_cache (app);
2512 /* Obviously we need to remove the cached public key. */
2513 xfree (app->app_local->pk[keyno].key);
2514 app->app_local->pk[keyno].key = NULL;
2515 app->app_local->pk[keyno].keylen = 0;
2516 app->app_local->pk[keyno].read_done = 0;
2518 /* Check whether a key already exists. */
2519 rc = does_key_exist (app, keyno, force);
2520 if (rc)
2521 return rc;
2523 /* Prepare for key generation by verifying the Admin PIN. */
2524 rc = verify_chv3 (app, pincb, pincb_arg);
2525 if (rc)
2526 goto leave;
2528 #if 1
2529 log_info (_("please wait while key is being generated ...\n"));
2530 start_at = time (NULL);
2531 rc = iso7816_generate_keypair
2532 #else
2533 # warning key generation temporary replaced by reading an existing key.
2534 rc = iso7816_read_public_key
2535 #endif
2536 (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
2537 keyno == 1? "\xB8" : "\xA4"),
2539 &buffer, &buflen);
2540 if (rc)
2542 rc = gpg_error (GPG_ERR_CARD);
2543 log_error (_("generating key failed\n"));
2544 goto leave;
2546 log_info (_("key generation completed (%d seconds)\n"),
2547 (int)(time (NULL) - start_at));
2548 keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2549 if (!keydata)
2551 rc = gpg_error (GPG_ERR_CARD);
2552 log_error (_("response does not contain the public key data\n"));
2553 goto leave;
2556 m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2557 if (!m)
2559 rc = gpg_error (GPG_ERR_CARD);
2560 log_error (_("response does not contain the RSA modulus\n"));
2561 goto leave;
2563 /* log_printhex ("RSA n:", m, mlen); */
2564 send_key_data (ctrl, "n", m, mlen);
2566 e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2567 if (!e)
2569 rc = gpg_error (GPG_ERR_CARD);
2570 log_error (_("response does not contain the RSA public exponent\n"));
2571 goto leave;
2573 /* log_printhex ("RSA e:", e, elen); */
2574 send_key_data (ctrl, "e", e, elen);
2576 created_at = createtime? createtime : gnupg_get_time ();
2577 sprintf (numbuf, "%lu", (unsigned long)created_at);
2578 send_status_info (ctrl, "KEY-CREATED-AT",
2579 numbuf, (size_t)strlen(numbuf), NULL, 0);
2581 rc = store_fpr (app->slot, keyno, (u32)created_at,
2582 m, mlen, e, elen, fprbuf, app->card_version);
2583 if (rc)
2584 goto leave;
2585 send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2588 leave:
2589 xfree (buffer);
2590 return rc;
2594 static unsigned long
2595 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2597 unsigned long ul;
2599 if (valuelen == 3 )
2600 ul = (value[0] << 16) | (value[1] << 8) | value[2];
2601 else
2603 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2604 ul = 0;
2606 return ul;
2609 static unsigned long
2610 get_sig_counter (app_t app)
2612 void *relptr;
2613 unsigned char *value;
2614 size_t valuelen;
2615 unsigned long ul;
2617 relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2618 if (!relptr)
2619 return 0;
2620 ul = convert_sig_counter_value (value, valuelen);
2621 xfree (relptr);
2622 return ul;
2625 static gpg_error_t
2626 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2628 const unsigned char *fpr;
2629 unsigned char *buffer;
2630 size_t buflen, n;
2631 int rc, i;
2633 assert (keyno >= 1 && keyno <= 3);
2635 rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
2636 if (rc)
2638 log_error (_("error reading application data\n"));
2639 return gpg_error (GPG_ERR_GENERAL);
2641 fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2642 if (!fpr || n != 60)
2644 xfree (buffer);
2645 log_error (_("error reading fingerprint DO\n"));
2646 return gpg_error (GPG_ERR_GENERAL);
2648 fpr += (keyno-1)*20;
2649 for (i=0; i < 20; i++)
2650 if (sha1fpr[i] != fpr[i])
2652 xfree (buffer);
2653 log_info (_("fingerprint on card does not match requested one\n"));
2654 return gpg_error (GPG_ERR_WRONG_SECKEY);
2656 xfree (buffer);
2657 return 0;
2661 /* If a fingerprint has been specified check it against the one on
2662 the card. This is allows for a meaningful error message in case
2663 the key on the card has been replaced but the shadow information
2664 known to gpg was not updated. If there is no fingerprint we
2665 assume that this is okay. */
2666 static gpg_error_t
2667 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2669 unsigned char tmp[20];
2670 const char *s;
2671 int n;
2673 for (s=fpr, n=0; hexdigitp (s); s++, n++)
2675 if (n != 40)
2676 return gpg_error (GPG_ERR_INV_ID);
2677 else if (!*s)
2678 ; /* okay */
2679 else
2680 return gpg_error (GPG_ERR_INV_ID);
2682 for (s=fpr, n=0; n < 20; s += 2, n++)
2683 tmp[n] = xtoi_2 (s);
2684 return compare_fingerprint (app, keyno, tmp);
2689 /* Compute a digital signature on INDATA which is expected to be the
2690 raw message digest. For this application the KEYIDSTR consists of
2691 the serialnumber and the fingerprint delimited by a slash.
2693 Note that this function may return the error code
2694 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2695 not match the one required for the requested action (e.g. the
2696 serial number does not match).
2698 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2699 operation to the auth command.
2701 static gpg_error_t
2702 do_sign (app_t app, const char *keyidstr, int hashalgo,
2703 gpg_error_t (*pincb)(void*, const char *, char **),
2704 void *pincb_arg,
2705 const void *indata, size_t indatalen,
2706 unsigned char **outdata, size_t *outdatalen )
2708 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2709 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2710 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2711 static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
2712 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2713 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2714 static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
2715 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2716 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2717 0x1C };
2718 static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
2719 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2720 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2721 0x00, 0x04, 0x20 };
2722 static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
2723 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2724 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
2725 0x00, 0x04, 0x30 };
2726 static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
2727 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2728 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
2729 0x00, 0x04, 0x40 };
2730 int rc;
2731 unsigned char data[19+64];
2732 size_t datalen;
2733 unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
2734 const char *s;
2735 int n;
2736 const char *fpr = NULL;
2737 unsigned long sigcount;
2738 int use_auth = 0;
2740 if (!keyidstr || !*keyidstr)
2741 return gpg_error (GPG_ERR_INV_VALUE);
2743 /* Strip off known prefixes. */
2744 #define X(a,b,c,d) \
2745 if (hashalgo == GCRY_MD_ ## a \
2746 && (d) \
2747 && indatalen == sizeof b ## _prefix + (c) \
2748 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
2750 indata = (const char*)indata + sizeof b ## _prefix; \
2751 indatalen -= sizeof b ## _prefix; \
2754 if (indatalen == 20)
2755 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
2756 else X(SHA1, sha1, 20, 1)
2757 else X(RMD160, rmd160, 20, 1)
2758 else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
2759 else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
2760 else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
2761 else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
2762 else if ((indatalen == 28 || indatalen == 32
2763 || indatalen == 48 || indatalen ==64)
2764 && app->app_local->extcap.is_v2)
2765 ; /* Assume a plain SHA-3 digest has been given. */
2766 else
2768 log_error (_("card does not support digest algorithm %s\n"),
2769 gcry_md_algo_name (hashalgo));
2770 /* Or the supplied digest length does not match an algorithm. */
2771 return gpg_error (GPG_ERR_INV_VALUE);
2773 #undef X
2775 /* Check whether an OpenPGP card of any version has been requested. */
2776 if (!strcmp (keyidstr, "OPENPGP.1"))
2778 else if (!strcmp (keyidstr, "OPENPGP.3"))
2779 use_auth = 1;
2780 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2781 return gpg_error (GPG_ERR_INV_ID);
2782 else
2784 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2786 if (n != 32)
2787 return gpg_error (GPG_ERR_INV_ID);
2788 else if (!*s)
2789 ; /* no fingerprint given: we allow this for now. */
2790 else if (*s == '/')
2791 fpr = s + 1;
2792 else
2793 return gpg_error (GPG_ERR_INV_ID);
2795 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2796 tmp_sn[n] = xtoi_2 (s);
2798 if (app->serialnolen != 16)
2799 return gpg_error (GPG_ERR_INV_CARD);
2800 if (memcmp (app->serialno, tmp_sn, 16))
2801 return gpg_error (GPG_ERR_WRONG_CARD);
2804 /* If a fingerprint has been specified check it against the one on
2805 the card. This is allows for a meaningful error message in case
2806 the key on the card has been replaced but the shadow information
2807 known to gpg was not updated. If there is no fingerprint, gpg
2808 will detect a bogus signature anyway due to the
2809 verify-after-signing feature. */
2810 rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
2811 if (rc)
2812 return rc;
2814 /* Concatenate prefix and digest. */
2815 #define X(a,b,d) \
2816 if (hashalgo == GCRY_MD_ ## a && (d) ) \
2818 datalen = sizeof b ## _prefix + indatalen; \
2819 assert (datalen <= sizeof data); \
2820 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
2821 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
2824 X(SHA1, sha1, 1)
2825 else X(RMD160, rmd160, 1)
2826 else X(SHA224, sha224, app->app_local->extcap.is_v2)
2827 else X(SHA256, sha256, app->app_local->extcap.is_v2)
2828 else X(SHA384, sha384, app->app_local->extcap.is_v2)
2829 else X(SHA512, sha512, app->app_local->extcap.is_v2)
2830 else
2831 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2832 #undef X
2834 /* Redirect to the AUTH command if asked to. */
2835 if (use_auth)
2837 return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
2838 data, datalen,
2839 outdata, outdatalen);
2842 /* Show the number of signature done using this key. */
2843 sigcount = get_sig_counter (app);
2844 log_info (_("signatures created so far: %lu\n"), sigcount);
2846 /* Check CHV if needed. */
2847 if (!app->did_chv1 || app->force_chv1 )
2849 char *pinvalue;
2851 rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
2852 if (rc)
2853 return rc;
2855 app->did_chv1 = 1;
2857 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
2858 sync, thus we verify CHV2 here using the given PIN. Cards
2859 with version2 to not have the need for a separate CHV2 and
2860 internally use just one. Obviously we can't do that if the
2861 keypad has been used. */
2862 if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
2864 rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
2865 if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
2866 rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
2867 if (rc)
2869 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
2870 xfree (pinvalue);
2871 flush_cache_after_error (app);
2872 return rc;
2874 app->did_chv2 = 1;
2876 xfree (pinvalue);
2879 rc = iso7816_compute_ds (app->slot, data, datalen, outdata, outdatalen);
2880 return rc;
2883 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2884 on INDATA which is expected to be the raw message digest. For this
2885 application the KEYIDSTR consists of the serialnumber and the
2886 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2887 be given.
2889 Note that this function may return the error code
2890 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2891 not match the one required for the requested action (e.g. the
2892 serial number does not match). */
2893 static gpg_error_t
2894 do_auth (app_t app, const char *keyidstr,
2895 gpg_error_t (*pincb)(void*, const char *, char **),
2896 void *pincb_arg,
2897 const void *indata, size_t indatalen,
2898 unsigned char **outdata, size_t *outdatalen )
2900 int rc;
2901 unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
2902 const char *s;
2903 int n;
2904 const char *fpr = NULL;
2906 if (!keyidstr || !*keyidstr)
2907 return gpg_error (GPG_ERR_INV_VALUE);
2908 if (indatalen > 101) /* For a 2048 bit key. */
2909 return gpg_error (GPG_ERR_INV_VALUE);
2911 /* Check whether an OpenPGP card of any version has been requested. */
2912 if (!strcmp (keyidstr, "OPENPGP.3"))
2914 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2915 return gpg_error (GPG_ERR_INV_ID);
2916 else
2918 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2920 if (n != 32)
2921 return gpg_error (GPG_ERR_INV_ID);
2922 else if (!*s)
2923 ; /* no fingerprint given: we allow this for now. */
2924 else if (*s == '/')
2925 fpr = s + 1;
2926 else
2927 return gpg_error (GPG_ERR_INV_ID);
2929 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2930 tmp_sn[n] = xtoi_2 (s);
2932 if (app->serialnolen != 16)
2933 return gpg_error (GPG_ERR_INV_CARD);
2934 if (memcmp (app->serialno, tmp_sn, 16))
2935 return gpg_error (GPG_ERR_WRONG_CARD);
2938 /* If a fingerprint has been specified check it against the one on
2939 the card. This is allows for a meaningful error message in case
2940 the key on the card has been replaced but the shadow information
2941 known to gpg was not updated. If there is no fingerprint, gpg
2942 will detect a bogus signature anyway due to the
2943 verify-after-signing feature. */
2944 rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
2945 if (rc)
2946 return rc;
2948 rc = verify_chv2 (app, pincb, pincb_arg);
2949 if (!rc)
2950 rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
2951 outdata, outdatalen);
2952 return rc;
2956 static gpg_error_t
2957 do_decipher (app_t app, const char *keyidstr,
2958 gpg_error_t (*pincb)(void*, const char *, char **),
2959 void *pincb_arg,
2960 const void *indata, size_t indatalen,
2961 unsigned char **outdata, size_t *outdatalen )
2963 int rc;
2964 unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
2965 const char *s;
2966 int n;
2967 const char *fpr = NULL;
2969 if (!keyidstr || !*keyidstr || !indatalen)
2970 return gpg_error (GPG_ERR_INV_VALUE);
2972 /* Check whether an OpenPGP card of any version has been requested. */
2973 if (!strcmp (keyidstr, "OPENPGP.2"))
2975 else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
2976 return gpg_error (GPG_ERR_INV_ID);
2977 else
2979 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
2981 if (n != 32)
2982 return gpg_error (GPG_ERR_INV_ID);
2983 else if (!*s)
2984 ; /* no fingerprint given: we allow this for now. */
2985 else if (*s == '/')
2986 fpr = s + 1;
2987 else
2988 return gpg_error (GPG_ERR_INV_ID);
2990 for (s=keyidstr, n=0; n < 16; s += 2, n++)
2991 tmp_sn[n] = xtoi_2 (s);
2993 if (app->serialnolen != 16)
2994 return gpg_error (GPG_ERR_INV_CARD);
2995 if (memcmp (app->serialno, tmp_sn, 16))
2996 return gpg_error (GPG_ERR_WRONG_CARD);
2999 /* If a fingerprint has been specified check it against the one on
3000 the card. This is allows for a meaningful error message in case
3001 the key on the card has been replaced but the shadow information
3002 known to gpg was not updated. If there is no fingerprint, the
3003 decryption will won't produce the right plaintext anyway. */
3004 rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3005 if (rc)
3006 return rc;
3008 rc = verify_chv2 (app, pincb, pincb_arg);
3009 if (!rc)
3011 size_t fixuplen;
3013 /* We might encounter a couple of leading zeroes in the
3014 cryptogram. Due to internal use of MPIs thease leading
3015 zeroes are stripped. However the OpenPGP card expects
3016 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3017 need to fix it up. We do this for up to 16 leading zero
3018 bytes; a cryptogram with more than this is with a very high
3019 probability anyway broken. */
3020 if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
3021 fixuplen = 128 - indatalen;
3022 else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
3023 fixuplen = 256 - indatalen;
3024 else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
3025 fixuplen = 192 - indatalen;
3026 else
3027 fixuplen = 0;
3028 if (fixuplen)
3030 unsigned char *fixbuf;
3032 /* While we have to prepend stuff anyway, we can also
3033 include the padding byte here so that iso1816_decipher
3034 does not need to do yet another data mangling. */
3035 fixuplen++;
3036 fixbuf = xtrymalloc (fixuplen + indatalen);
3037 if (!fixbuf)
3038 rc = gpg_error_from_syserror ();
3039 else
3041 memset (fixbuf, 0, fixuplen);
3042 memcpy (fixbuf+fixuplen, indata, indatalen);
3043 rc = iso7816_decipher (app->slot, fixbuf, fixuplen+indatalen, -1,
3044 outdata, outdatalen);
3045 xfree (fixbuf);
3049 else
3050 rc = iso7816_decipher (app->slot, indata, indatalen, 0,
3051 outdata, outdatalen);
3053 return rc;
3057 /* Perform a simple verify operation for CHV1 and CHV2, so that
3058 further operations won't ask for CHV2 and it is possible to do a
3059 cheap check on the PIN: If there is something wrong with the PIN
3060 entry system, only the regular CHV will get blocked and not the
3061 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3062 optional fingerprint part will be ignored.
3064 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3065 the "[CHV3]" being a literal string: The Admin Pin is checked if
3066 and only if the retry counter is still at 3. */
3067 static gpg_error_t
3068 do_check_pin (app_t app, const char *keyidstr,
3069 gpg_error_t (*pincb)(void*, const char *, char **),
3070 void *pincb_arg)
3072 unsigned char tmp_sn[20];
3073 const char *s;
3074 int n;
3075 int admin_pin = 0;
3077 if (!keyidstr || !*keyidstr)
3078 return gpg_error (GPG_ERR_INV_VALUE);
3080 /* Check whether an OpenPGP card of any version has been requested. */
3081 if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3082 return gpg_error (GPG_ERR_INV_ID);
3084 for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3086 if (n != 32)
3087 return gpg_error (GPG_ERR_INV_ID);
3088 else if (!*s)
3089 ; /* No fingerprint given: we allow this for now. */
3090 else if (*s == '/')
3091 ; /* We ignore a fingerprint. */
3092 else if (!strcmp (s, "[CHV3]") )
3093 admin_pin = 1;
3094 else
3095 return gpg_error (GPG_ERR_INV_ID);
3097 for (s=keyidstr, n=0; n < 16; s += 2, n++)
3098 tmp_sn[n] = xtoi_2 (s);
3100 if (app->serialnolen != 16)
3101 return gpg_error (GPG_ERR_INV_CARD);
3102 if (memcmp (app->serialno, tmp_sn, 16))
3103 return gpg_error (GPG_ERR_WRONG_CARD);
3105 /* Yes, there is a race conditions: The user might pull the card
3106 right here and we won't notice that. However this is not a
3107 problem and the check above is merely for a graceful failure
3108 between operations. */
3110 if (admin_pin)
3112 void *relptr;
3113 unsigned char *value;
3114 size_t valuelen;
3115 int count;
3117 relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3118 if (!relptr || valuelen < 7)
3120 log_error (_("error retrieving CHV status from card\n"));
3121 xfree (relptr);
3122 return gpg_error (GPG_ERR_CARD);
3124 count = value[6];
3125 xfree (relptr);
3127 if (!count)
3129 log_info (_("card is permanently locked!\n"));
3130 return gpg_error (GPG_ERR_BAD_PIN);
3132 else if (value[6] < 3)
3134 log_info (_("verification of Admin PIN is currently prohibited "
3135 "through this command\n"));
3136 return gpg_error (GPG_ERR_GENERAL);
3139 app->did_chv3 = 0; /* Force verification. */
3140 return verify_chv3 (app, pincb, pincb_arg);
3142 else
3143 return verify_chv2 (app, pincb, pincb_arg);
3147 /* Show information about card capabilities. */
3148 static void
3149 show_caps (struct app_local_s *s)
3151 log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3152 log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3153 if (s->extcap.get_challenge)
3154 log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3155 log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3156 log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3157 log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3158 log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3159 log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3160 if (s->extcap.sm_supported)
3161 log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3162 log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3163 log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3164 log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3165 log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3166 log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3167 log_info ("Status Indicator: %02X\n", s->status_indicator);
3169 log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
3170 log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
3174 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3175 APPLOC. */
3176 static void
3177 parse_historical (struct app_local_s *apploc,
3178 const unsigned char * buffer, size_t buflen)
3180 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3181 if (buflen < 4)
3183 log_error ("warning: historical bytes are too short\n");
3184 return; /* Too short. */
3186 if (*buffer)
3188 log_error ("warning: bad category indicator in historical bytes\n");
3189 return;
3192 /* Skip category indicator. */
3193 buffer++;
3194 buflen--;
3196 /* Get the status indicator. */
3197 apploc->status_indicator = buffer[buflen-3];
3198 buflen -= 3;
3200 /* Parse the compact TLV. */
3201 while (buflen)
3203 unsigned int tag = (*buffer & 0xf0) >> 4;
3204 unsigned int len = (*buffer & 0x0f);
3205 if (len+1 > buflen)
3207 log_error ("warning: bad Compact-TLV in historical bytes\n");
3208 return; /* Error. */
3210 buffer++;
3211 buflen--;
3212 if (tag == 7 && len == 3)
3214 /* Card capabilities. */
3215 apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3216 apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
3218 buffer += len;
3219 buflen -= len;
3224 /* Parse and optionally show the algorithm attributes for KEYNO.
3225 KEYNO must be in the range 0..2. */
3226 static void
3227 parse_algorithm_attribute (app_t app, int keyno)
3229 unsigned char *buffer;
3230 size_t buflen;
3231 void *relptr;
3232 const char const desc[3][5] = {"sign", "encr", "auth"};
3234 assert (keyno >=0 && keyno <= 2);
3236 app->app_local->keyattr[keyno].n_bits = 0;
3238 relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3239 if (!relptr)
3241 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3242 return;
3244 if (buflen < 1)
3246 log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3247 xfree (relptr);
3248 return;
3251 if (opt.verbose)
3252 log_info ("Key-Attr-%s ..: ", desc[keyno]);
3253 if (*buffer == 1 && (buflen == 5 || buflen == 6))
3255 app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3256 app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3257 app->app_local->keyattr[keyno].format = 0;
3258 if (buflen < 6)
3259 app->app_local->keyattr[keyno].format = RSA_STD;
3260 else
3261 app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD :
3262 buffer[5] == 1? RSA_STD_N :
3263 buffer[5] == 2? RSA_CRT :
3264 buffer[5] == 3? RSA_CRT_N :
3265 RSA_UNKNOWN_FMT);
3267 if (opt.verbose)
3268 log_printf
3269 ("RSA, n=%u, e=%u, fmt=%s\n",
3270 app->app_local->keyattr[keyno].n_bits,
3271 app->app_local->keyattr[keyno].e_bits,
3272 app->app_local->keyattr[keyno].format == RSA_STD? "std" :
3273 app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3274 app->app_local->keyattr[keyno].format == RSA_CRT? "crt" :
3275 app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3277 else if (opt.verbose)
3278 log_printhex ("", buffer, buflen);
3280 xfree (relptr);
3283 /* Select the OpenPGP application on the card in SLOT. This function
3284 must be used before any other OpenPGP application functions. */
3285 gpg_error_t
3286 app_select_openpgp (app_t app)
3288 static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3289 int slot = app->slot;
3290 int rc;
3291 unsigned char *buffer;
3292 size_t buflen;
3293 void *relptr;
3295 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3296 special flag value. */
3297 rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3298 if (!rc)
3300 unsigned int manufacturer;
3302 app->apptype = "OPENPGP";
3304 app->did_chv1 = 0;
3305 app->did_chv2 = 0;
3306 app->did_chv3 = 0;
3307 app->app_local = NULL;
3309 /* The OpenPGP card returns the serial number as part of the
3310 AID; because we prefer to use OpenPGP serial numbers, we
3311 replace a possibly already set one from a EF.GDO with this
3312 one. Note, that for current OpenPGP cards, no EF.GDO exists
3313 and thus it won't matter at all. */
3314 rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
3315 if (rc)
3316 goto leave;
3317 if (opt.verbose)
3319 log_info ("AID: ");
3320 log_printhex ("", buffer, buflen);
3323 app->card_version = buffer[6] << 8;
3324 app->card_version |= buffer[7];
3325 manufacturer = (buffer[8]<<8 | buffer[9]);
3327 xfree (app->serialno);
3328 app->serialno = buffer;
3329 app->serialnolen = buflen;
3330 buffer = NULL;
3331 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3332 if (!app->app_local)
3334 rc = gpg_error (gpg_err_code_from_errno (errno));
3335 goto leave;
3338 if (app->card_version >= 0x0200)
3339 app->app_local->extcap.is_v2 = 1;
3342 /* Read the historical bytes. */
3343 relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3344 if (relptr)
3346 if (opt.verbose)
3348 log_info ("Historical Bytes: ");
3349 log_printhex ("", buffer, buflen);
3351 parse_historical (app->app_local, buffer, buflen);
3352 xfree (relptr);
3355 /* Read the force-chv1 flag. */
3356 relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3357 if (!relptr)
3359 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3360 "CHV Status Bytes");
3361 goto leave;
3363 app->force_chv1 = (buflen && *buffer == 0);
3364 xfree (relptr);
3366 /* Read the extended capabilities. */
3367 relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3368 if (!relptr)
3370 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3371 "Extended Capability Flags" );
3372 goto leave;
3374 if (buflen)
3376 app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
3377 app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
3378 app->app_local->extcap.key_import = !!(*buffer & 0x20);
3379 app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3380 app->app_local->extcap.private_dos = !!(*buffer & 0x08);
3381 app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3383 if (buflen >= 10)
3385 /* Available with v2 cards. */
3386 app->app_local->extcap.sm_aes128 = (buffer[1] == 1);
3387 app->app_local->extcap.max_get_challenge
3388 = (buffer[2] << 8 | buffer[3]);
3389 app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3390 app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
3391 app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
3393 xfree (relptr);
3395 /* Some of the first cards accidently don't set the
3396 CHANGE_FORCE_CHV bit but allow it anyway. */
3397 if (app->card_version <= 0x0100 && manufacturer == 1)
3398 app->app_local->extcap.change_force_chv = 1;
3400 parse_login_data (app);
3402 if (opt.verbose)
3403 show_caps (app->app_local);
3405 parse_algorithm_attribute (app, 0);
3406 parse_algorithm_attribute (app, 1);
3407 parse_algorithm_attribute (app, 2);
3409 if (opt.verbose > 1)
3410 dump_all_do (slot);
3412 app->fnc.deinit = do_deinit;
3413 app->fnc.learn_status = do_learn_status;
3414 app->fnc.readcert = do_readcert;
3415 app->fnc.readkey = do_readkey;
3416 app->fnc.getattr = do_getattr;
3417 app->fnc.setattr = do_setattr;
3418 app->fnc.writecert = do_writecert;
3419 app->fnc.writekey = do_writekey;
3420 app->fnc.genkey = do_genkey;
3421 app->fnc.sign = do_sign;
3422 app->fnc.auth = do_auth;
3423 app->fnc.decipher = do_decipher;
3424 app->fnc.change_pin = do_change_pin;
3425 app->fnc.check_pin = do_check_pin;
3428 leave:
3429 if (rc)
3430 do_deinit (app);
3431 return rc;