1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3 * 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
25 CHV means Card Holder Verification and is nothing else than a PIN
26 or password. That term seems to have been used originally with GSM
27 cards. Version v2 of the specs changes the term to the clearer
28 term PW for password. We use the terms here interchangeable
29 because we do not want to change existing strings i18n wise.
31 Version 2 of the specs also drops the separate PW2 which was
32 required in v1 due to ISO requirements. It is now possible to have
33 one physical PW but two reference to it so that they can be
34 individually be verified (e.g. to implement a forced verification
35 for one key). Thus you will noticed the use of PW2 with the verify
36 command but not with change_reference_data because the latter
37 operates directly on the physical PW.
39 The Reset Code (RC) as implemented by v2 cards uses the same error
40 counter as the PW2 of v1 cards. By default no RC is set and thus
41 that error counter is set to 0. After setting the RC the error
42 counter will be initialized to 3.
54 #if GNUPG_MAJOR_VERSION == 1
55 /* This is used with GnuPG version < 1.9. The code has been source
56 copied from the current GnuPG >= 1.9 and is maintained over
63 #else /* GNUPG_MAJOR_VERSION != 1 */
65 #endif /* GNUPG_MAJOR_VERSION != 1 */
69 #include "app-common.h"
73 /* A table describing the DOs of the card. */
77 int get_from
; /* Constructed DO with this DO or 0 for direct access. */
81 int get_immediate_in_v11
; /* Enable a hack to bypass the cache of
82 this data object if it is used in 1.1
83 and later versions of the card. This
84 does not work with composite DO and is
85 currently only useful for the CHV
89 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
90 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
91 { 0x5F52, 0, 0, 1, 0, 0, 0, "Historical Bytes" },
92 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
93 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
94 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
95 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
96 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
97 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
98 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
99 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
100 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
101 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
102 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
103 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
104 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
105 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
106 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
107 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
108 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
109 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
110 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
111 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
112 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
113 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
114 { 0x7F21, 1, 0, 1, 0, 0, 0, "Cardholder certificate"},
119 /* The format of RSA private keys. */
131 /* One cache item for DOs. */
133 struct cache_s
*next
;
136 unsigned char data
[1];
140 /* Object with application (i.e. OpenPGP card) specific data. */
142 /* A linked list with cached DOs. */
143 struct cache_s
*cache
;
145 /* Keep track of the public keys. */
148 int read_done
; /* True if we have at least tried to read them. */
149 unsigned char *key
; /* This is a malloced buffer with a canonical
150 encoded S-expression encoding a public
151 key. Might be NULL if key is not
153 size_t keylen
; /* The length of the above S-expression. This
154 is usually only required for cross checks
155 because the length of an S-expression is
156 implicitly available. */
159 unsigned char status_indicator
; /* The card status indicator. */
161 /* Keep track of the ISO card capabilities. */
164 unsigned int cmd_chaining
:1; /* Command chaining is supported. */
165 unsigned int ext_lc_le
:1; /* Extended Lc and Le are supported. */
168 /* Keep track of extended card capabilities. */
171 unsigned int is_v2
:1; /* This is a v2.0 compatible card. */
172 unsigned int get_challenge
:1;
173 unsigned int key_import
:1;
174 unsigned int change_force_chv
:1;
175 unsigned int private_dos
:1;
176 unsigned int algo_attr_change
:1; /* Algorithm attributes changeable. */
177 unsigned int sm_supported
:1; /* Secure Messaging is supported. */
178 unsigned int sm_aes128
:1; /* Use AES-128 for SM. */
179 unsigned int max_certlen_3
:16;
180 unsigned int max_get_challenge
:16; /* Maximum size for get_challenge. */
181 unsigned int max_cmd_data
:16; /* Maximum data size for a command. */
182 unsigned int max_rsp_data
:16; /* Maximum size of a response. */
185 /* Flags used to control the application. */
188 unsigned int no_sync
:1; /* Do not sync CHV1 and CHV2 */
189 unsigned int def_chv2
:1; /* Use 123456 for CHV2. */
194 unsigned int n_bits
; /* Size of the modulus in bits. The rest
195 of this strucuire is only valid if
197 unsigned int e_bits
; /* Size of the public exponent in bits. */
198 rsa_key_format_t format
;
205 /***** Local prototypes *****/
206 static unsigned long convert_sig_counter_value (const unsigned char *value
,
208 static unsigned long get_sig_counter (app_t app
);
209 static gpg_error_t
do_auth (app_t app
, const char *keyidstr
,
210 gpg_error_t (*pincb
)(void*, const char *, char **),
212 const void *indata
, size_t indatalen
,
213 unsigned char **outdata
, size_t *outdatalen
);
221 do_deinit (app_t app
)
223 if (app
&& app
->app_local
)
225 struct cache_s
*c
, *c2
;
228 for (c
= app
->app_local
->cache
; c
; c
= c2
)
234 for (i
=0; i
< DIM (app
->app_local
->pk
); i
++)
236 xfree (app
->app_local
->pk
[i
].key
);
237 app
->app_local
->pk
[i
].read_done
= 0;
239 xfree (app
->app_local
);
240 app
->app_local
= NULL
;
245 /* Wrapper around iso7816_get_data which first tries to get the data
246 from the cache. With GET_IMMEDIATE passed as true, the cache is
249 get_cached_data (app_t app
, int tag
,
250 unsigned char **result
, size_t *resultlen
,
264 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
269 p
= xtrymalloc (c
->length
);
271 return gpg_error (gpg_err_code_from_errno (errno
));
272 memcpy (p
, c
->data
, c
->length
);
276 *resultlen
= c
->length
;
282 err
= iso7816_get_data (app
->slot
, tag
, &p
, &len
);
288 /* Check whether we should cache this object. */
292 for (i
=0; data_objects
[i
].tag
; i
++)
293 if (data_objects
[i
].tag
== tag
)
295 if (data_objects
[i
].dont_cache
)
300 /* Okay, cache it. */
301 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
302 assert (c
->tag
!= tag
);
304 c
= xtrymalloc (sizeof *c
+ len
);
307 memcpy (c
->data
, p
, len
);
310 c
->next
= app
->app_local
->cache
;
311 app
->app_local
->cache
= c
;
317 /* Remove DO at TAG from the cache. */
319 flush_cache_item (app_t app
, int tag
)
321 struct cache_s
*c
, *cprev
;
327 for (c
=app
->app_local
->cache
, cprev
=NULL
; c
; cprev
=c
, c
= c
->next
)
331 cprev
->next
= c
->next
;
333 app
->app_local
->cache
= c
->next
;
336 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
338 assert (c
->tag
!= tag
); /* Oops: duplicated entry. */
343 /* Try again if we have an outer tag. */
344 for (i
=0; data_objects
[i
].tag
; i
++)
345 if (data_objects
[i
].tag
== tag
&& data_objects
[i
].get_from
346 && data_objects
[i
].get_from
!= tag
)
347 flush_cache_item (app
, data_objects
[i
].get_from
);
350 /* Flush all entries from the cache which might be out of sync after
353 flush_cache_after_error (app_t app
)
357 for (i
=0; data_objects
[i
].tag
; i
++)
358 if (data_objects
[i
].flush_on_error
)
359 flush_cache_item (app
, data_objects
[i
].tag
);
363 /* Flush the entire cache. */
365 flush_cache (app_t app
)
367 if (app
&& app
->app_local
)
369 struct cache_s
*c
, *c2
;
371 for (c
= app
->app_local
->cache
; c
; c
= c2
)
376 app
->app_local
->cache
= NULL
;
381 /* Get the DO identified by TAG from the card in SLOT and return a
382 buffer with its content in RESULT and NBYTES. The return value is
383 NULL if not found or a pointer which must be used to release the
384 buffer holding value. */
386 get_one_do (app_t app
, int tag
, unsigned char **result
, size_t *nbytes
,
390 unsigned char *buffer
;
392 unsigned char *value
;
402 for (i
=0; data_objects
[i
].tag
&& data_objects
[i
].tag
!= tag
; i
++)
405 if (app
->card_version
> 0x0100 && data_objects
[i
].get_immediate_in_v11
)
407 rc
= iso7816_get_data (app
->slot
, tag
, &buffer
, &buflen
);
420 if (data_objects
[i
].tag
&& data_objects
[i
].get_from
)
422 rc
= get_cached_data (app
, data_objects
[i
].get_from
,
424 (data_objects
[i
].dont_cache
425 || data_objects
[i
].get_immediate_in_v11
));
428 const unsigned char *s
;
430 s
= find_tlv_unchecked (buffer
, buflen
, tag
, &valuelen
);
432 value
= NULL
; /* not found */
433 else if (valuelen
> buflen
- (s
- buffer
))
435 log_error ("warning: constructed DO too short\n");
437 xfree (buffer
); buffer
= NULL
;
440 value
= buffer
+ (s
- buffer
);
444 if (!value
) /* Not in a constructed DO, try simple. */
446 rc
= get_cached_data (app
, tag
, &buffer
, &buflen
,
447 (data_objects
[i
].dont_cache
448 || data_objects
[i
].get_immediate_in_v11
));
468 dump_all_do (int slot
)
471 unsigned char *buffer
;
474 for (i
=0; data_objects
[i
].tag
; i
++)
476 if (data_objects
[i
].get_from
)
479 rc
= iso7816_get_data (slot
, data_objects
[i
].tag
, &buffer
, &buflen
);
480 if (gpg_err_code (rc
) == GPG_ERR_NO_OBJ
)
483 log_info ("DO `%s' not available: %s\n",
484 data_objects
[i
].desc
, gpg_strerror (rc
));
487 if (data_objects
[i
].binary
)
489 log_info ("DO `%s': ", data_objects
[i
].desc
);
490 log_printhex ("", buffer
, buflen
);
493 log_info ("DO `%s': `%.*s'\n",
494 data_objects
[i
].desc
,
495 (int)buflen
, buffer
); /* FIXME: sanitize */
497 if (data_objects
[i
].constructed
)
499 for (j
=0; data_objects
[j
].tag
; j
++)
501 const unsigned char *value
;
504 if (j
==i
|| data_objects
[i
].tag
!= data_objects
[j
].get_from
)
506 value
= find_tlv_unchecked (buffer
, buflen
,
507 data_objects
[j
].tag
, &valuelen
);
510 else if (valuelen
> buflen
- (value
- buffer
))
511 log_error ("warning: constructed DO too short\n");
514 if (data_objects
[j
].binary
)
516 log_info ("DO `%s': ", data_objects
[j
].desc
);
518 log_info ("[%u]\n", (unsigned int)valuelen
);
520 log_printhex ("", value
, valuelen
);
523 log_info ("DO `%s': `%.*s'\n",
524 data_objects
[j
].desc
,
525 (int)valuelen
, value
); /* FIXME: sanitize */
530 xfree (buffer
); buffer
= NULL
;
535 /* Count the number of bits, assuming the A represents an unsigned big
536 integer of length LEN bytes. */
538 count_bits (const unsigned char *a
, size_t len
)
540 unsigned int n
= len
* 8;
543 for (; len
&& !*a
; len
--, a
++, n
-=8)
547 for (i
=7; i
&& !(*a
& (1<<i
)); i
--)
553 /* GnuPG makes special use of the login-data DO, this function parses
554 the login data to store the flags for later use. It may be called
555 at any time and should be called after changing the login-data DO.
557 Everything up to a LF is considered a mailbox or account name. If
558 the first LF is followed by DC4 (0x14) control sequence are
559 expected up to the next LF. Control sequences are separated by FS
560 (0x18) and consist of key=value pairs. There is one key defined:
564 Were FLAGS is a plain hexadecimal number representing flag values.
565 The lsb is here the rightmost bit. Defined flags bits are:
567 Bit 0 = CHV1 and CHV2 are not syncronized
568 Bit 1 = CHV2 has been been set to the default PIN of "123456"
569 (this implies that bit 0 is also set).
573 parse_login_data (app_t app
)
575 unsigned char *buffer
, *p
;
580 app
->app_local
->flags
.no_sync
= 0;
581 app
->app_local
->flags
.def_chv2
= 0;
584 relptr
= get_one_do (app
, 0x005E, &buffer
, &buflen
, NULL
);
587 for (; buflen
; buflen
--, buffer
++)
590 if (buflen
< 2 || buffer
[1] != '\x14')
591 return; /* No control sequences. */
598 if (buflen
> 1 && *buffer
== 'F' && buffer
[1] == '=')
600 /* Flags control sequence found. */
603 /* For now we are only interested in the last digit, so skip
604 any leading digits but bail out on invalid characters. */
605 for (p
=buffer
+2, len
= buflen
-2; len
&& hexdigitp (p
); p
++, len
--)
606 lastdig
= xtoi_1 (p
);
607 if (len
&& !(*p
== '\n' || *p
== '\x18'))
608 goto next
; /* Invalid characters in field. */
609 app
->app_local
->flags
.no_sync
= !!(lastdig
& 1);
610 app
->app_local
->flags
.def_chv2
= (lastdig
& 3) == 3;
613 for (; buflen
&& *buffer
!= '\x18'; buflen
--, buffer
++)
622 /* Note, that FPR must be at least 20 bytes. */
624 store_fpr (int slot
, int keynumber
, u32 timestamp
,
625 const unsigned char *m
, size_t mlen
,
626 const unsigned char *e
, size_t elen
,
627 unsigned char *fpr
, unsigned int card_version
)
629 unsigned int n
, nbits
;
630 unsigned char *buffer
, *p
;
633 for (; mlen
&& !*m
; mlen
--, m
++) /* strip leading zeroes */
635 for (; elen
&& !*e
; elen
--, e
++) /* strip leading zeroes */
638 n
= 6 + 2 + mlen
+ 2 + elen
;
639 p
= buffer
= xtrymalloc (3 + n
);
641 return gpg_error_from_syserror ();
643 *p
++ = 0x99; /* ctb */
644 *p
++ = n
>> 8; /* 2 byte length header */
646 *p
++ = 4; /* key packet version */
647 *p
++ = timestamp
>> 24;
648 *p
++ = timestamp
>> 16;
649 *p
++ = timestamp
>> 8;
652 nbits
= count_bits (m
, mlen
);
655 memcpy (p
, m
, mlen
); p
+= mlen
;
656 nbits
= count_bits (e
, elen
);
659 memcpy (p
, e
, elen
); p
+= elen
;
661 gcry_md_hash_buffer (GCRY_MD_SHA1
, fpr
, buffer
, n
+3);
665 rc
= iso7816_put_data (slot
, 0,
666 (card_version
> 0x0007? 0xC7 : 0xC6)
667 + keynumber
, fpr
, 20);
669 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc
));
671 if (!rc
&& card_version
> 0x0100)
673 unsigned char buf
[4];
675 buf
[0] = timestamp
>> 24;
676 buf
[1] = timestamp
>> 16;
677 buf
[2] = timestamp
>> 8;
680 rc
= iso7816_put_data (slot
, 0, 0xCE + keynumber
, buf
, 4);
682 log_error (_("failed to store the creation date: %s\n"),
691 send_fpr_if_not_null (ctrl_t ctrl
, const char *keyword
,
692 int number
, const unsigned char *fpr
)
698 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
701 return; /* All zero. */
702 bin2hex (fpr
, 20, buf
);
704 *numbuf
= 0; /* Don't print the key number */
706 sprintf (numbuf
, "%d", number
);
707 send_status_info (ctrl
, keyword
,
708 numbuf
, (size_t)strlen(numbuf
),
709 buf
, (size_t)strlen (buf
), NULL
, 0);
713 send_fprtime_if_not_null (ctrl_t ctrl
, const char *keyword
,
714 int number
, const unsigned char *stamp
)
716 char numbuf1
[50], numbuf2
[50];
719 value
= (stamp
[0] << 24) | (stamp
[1]<<16) | (stamp
[2]<<8) | stamp
[3];
722 sprintf (numbuf1
, "%d", number
);
723 sprintf (numbuf2
, "%lu", value
);
724 send_status_info (ctrl
, keyword
,
725 numbuf1
, (size_t)strlen(numbuf1
),
726 numbuf2
, (size_t)strlen(numbuf2
), NULL
, 0);
730 send_key_data (ctrl_t ctrl
, const char *name
,
731 const unsigned char *a
, size_t alen
)
735 buf
= bin2hex (a
, alen
, NULL
);
738 log_error ("memory allocation error in send_key_data\n");
742 send_status_info (ctrl
, "KEY-DATA",
743 name
, (size_t)strlen(name
),
744 buf
, (size_t)strlen (buf
),
751 send_key_attr (ctrl_t ctrl
, app_t app
, const char *keyword
, int number
)
755 assert (number
>=0 && number
< DIM(app
->app_local
->keyattr
));
757 /* We only support RSA thus the algo identifier is fixed to 1. */
758 snprintf (buffer
, sizeof buffer
, "%d 1 %u %u %d",
760 app
->app_local
->keyattr
[number
].n_bits
,
761 app
->app_local
->keyattr
[number
].e_bits
,
762 app
->app_local
->keyattr
[number
].format
);
763 send_status_direct (ctrl
, keyword
, buffer
);
767 /* Implement the GETATTR command. This is similar to the LEARN
768 command but returns just one value via the status interface. */
770 do_getattr (app_t app
, ctrl_t ctrl
, const char *name
)
777 { "DISP-NAME", 0x005B },
778 { "LOGIN-DATA", 0x005E },
779 { "DISP-LANG", 0x5F2D },
780 { "DISP-SEX", 0x5F35 },
781 { "PUBKEY-URL", 0x5F50 },
782 { "KEY-FPR", 0x00C5, 3 },
783 { "KEY-TIME", 0x00CD, 4 },
784 { "KEY-ATTR", 0x0000, -5 },
785 { "CA-FPR", 0x00C6, 3 },
786 { "CHV-STATUS", 0x00C4, 1 },
787 { "SIG-COUNTER", 0x0093, 2 },
788 { "SERIALNO", 0x004F, -1 },
790 { "EXTCAP", 0x0000, -2 },
791 { "PRIVATE-DO-1", 0x0101 },
792 { "PRIVATE-DO-2", 0x0102 },
793 { "PRIVATE-DO-3", 0x0103 },
794 { "PRIVATE-DO-4", 0x0104 },
795 { "$AUTHKEYID", 0x0000, -3 },
796 { "$DISPSERIALNO",0x0000, -4 },
801 unsigned char *value
;
804 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
806 if (!table
[idx
].name
)
807 return gpg_error (GPG_ERR_INV_NAME
);
809 if (table
[idx
].special
== -1)
811 /* The serial number is very special. We could have used the
812 AID DO to retrieve it, but we have it already in the app
813 context and the stamp argument is required anyway which we
814 can't by other means. The AID DO is available anyway but not
820 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
822 sprintf (tmp
, "%lu", (unsigned long)stamp
);
823 send_status_info (ctrl
, "SERIALNO",
824 serial
, strlen (serial
),
831 if (table
[idx
].special
== -2)
835 snprintf (tmp
, sizeof tmp
,
836 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d",
837 app
->app_local
->extcap
.get_challenge
,
838 app
->app_local
->extcap
.key_import
,
839 app
->app_local
->extcap
.change_force_chv
,
840 app
->app_local
->extcap
.private_dos
,
841 app
->app_local
->extcap
.max_certlen_3
,
842 app
->app_local
->extcap
.algo_attr_change
);
843 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
846 if (table
[idx
].special
== -3)
848 char const tmp
[] = "OPENPGP.3";
849 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
852 if (table
[idx
].special
== -4)
857 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
859 if (strlen (serial
) > 16+12)
861 send_status_info (ctrl
, table
[idx
].name
, serial
+16, 12, NULL
, 0);
867 return gpg_error (GPG_ERR_INV_NAME
);
869 if (table
[idx
].special
== -5)
871 for (i
=0; i
< 3; i
++)
872 send_key_attr (ctrl
, app
, table
[idx
].name
, i
);
876 relptr
= get_one_do (app
, table
[idx
].tag
, &value
, &valuelen
, &rc
);
879 if (table
[idx
].special
== 1)
883 for (i
=0,*numbuf
=0; i
< valuelen
&& i
< 7; i
++)
884 sprintf (numbuf
+strlen (numbuf
), " %d", value
[i
]);
885 send_status_info (ctrl
, table
[idx
].name
,
886 numbuf
, strlen (numbuf
), NULL
, 0);
888 else if (table
[idx
].special
== 2)
892 sprintf (numbuf
, "%lu", convert_sig_counter_value (value
, valuelen
));
893 send_status_info (ctrl
, table
[idx
].name
,
894 numbuf
, strlen (numbuf
), NULL
, 0);
896 else if (table
[idx
].special
== 3)
899 for (i
=0; i
< 3; i
++)
900 send_fpr_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*20);
902 else if (table
[idx
].special
== 4)
905 for (i
=0; i
< 3; i
++)
906 send_fprtime_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*4);
909 send_status_info (ctrl
, table
[idx
].name
, value
, valuelen
, NULL
, 0);
916 /* Retrieve the fingerprint from the card inserted in SLOT and write
917 the according hex representation to FPR. Caller must have provide
918 a buffer at FPR of least 41 bytes. Returns 0 on success or an
920 #if GNUPG_MAJOR_VERSION > 1
922 retrieve_fpr_from_card (app_t app
, int keyno
, char *fpr
)
926 unsigned char *value
;
929 assert (keyno
>=0 && keyno
<= 2);
931 relptr
= get_one_do (app
, 0x00C5, &value
, &valuelen
, NULL
);
932 if (relptr
&& valuelen
>= 60)
933 bin2hex (value
+keyno
*20, 20, fpr
);
935 err
= gpg_error (GPG_ERR_NOT_FOUND
);
939 #endif /*GNUPG_MAJOR_VERSION > 1*/
942 /* Retrieve the public key material for the RSA key, whose fingerprint
943 is FPR, from gpg output, which can be read through the stream FP.
944 The RSA modulus will be stored at the address of M and MLEN, the
945 public exponent at E and ELEN. Returns zero on success, an error
946 code on failure. Caller must release the allocated buffers at M
947 and E if the function returns success. */
948 #if GNUPG_MAJOR_VERSION > 1
950 retrieve_key_material (FILE *fp
, const char *hexkeyid
,
951 const unsigned char **m
, size_t *mlen
,
952 const unsigned char **e
, size_t *elen
)
954 gcry_error_t err
= 0;
955 char *line
= NULL
; /* read_line() buffer. */
956 size_t line_size
= 0; /* Helper for for read_line. */
957 int found_key
= 0; /* Helper to find a matching key. */
958 unsigned char *m_new
= NULL
;
959 unsigned char *e_new
= NULL
;
963 /* Loop over all records until we have found the subkey
964 corresponding to the fingerprint. Inm general the first record
965 should be the pub record, but we don't rely on that. Given that
966 we only need to look at one key, it is sufficient to compare the
967 keyid so that we don't need to look at "fpr" records. */
978 i
= read_line (fp
, &line
, &line_size
, &max_length
);
983 err
= gpg_error_from_syserror ();
984 goto leave
; /* Error. */
988 err
= gpg_error (GPG_ERR_TRUNCATED
);
989 goto leave
; /* Line truncated - we better stop processing. */
992 /* Parse the line into fields. */
993 for (nfields
=0, p
=line
; p
&& nfields
< DIM (fields
); nfields
++)
1001 continue; /* No fields at all - skip line. */
1005 if ( (!strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
1006 && nfields
> 4 && !strcmp (fields
[4], hexkeyid
))
1011 if ( !strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
1012 break; /* Next key - stop. */
1014 if ( strcmp (fields
[0], "pkd") )
1015 continue; /* Not a key data record. */
1016 i
= 0; /* Avoid erroneous compiler warning. */
1017 if ( nfields
< 4 || (i
= atoi (fields
[1])) < 0 || i
> 1
1018 || (!i
&& m_new
) || (i
&& e_new
))
1020 err
= gpg_error (GPG_ERR_GENERAL
);
1021 goto leave
; /* Error: Invalid key data record or not an RSA key. */
1024 err
= gcry_mpi_scan (&mpi
, GCRYMPI_FMT_HEX
, fields
[3], 0, NULL
);
1028 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &m_new
, &m_new_n
, mpi
);
1030 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &e_new
, &e_new_n
, mpi
);
1031 gcry_mpi_release (mpi
);
1046 err
= gpg_error (GPG_ERR_GENERAL
);
1054 #endif /*GNUPG_MAJOR_VERSION > 1*/
1057 /* Get the public key for KEYNO and store it as an S-expresion with
1058 the APP handle. On error that field gets cleared. If we already
1059 know about the public key we will just return. Note that this does
1060 not mean a key is available; this is soley indicated by the
1061 presence of the app->app_local->pk[KEYNO-1].key field.
1063 Note that GnuPG 1.x does not need this and it would be too time
1064 consuming to send it just for the fun of it. However, given that we
1065 use the same code in gpg 1.4, we can't use the gcry S-expresion
1066 here but need to open encode it. */
1067 #if GNUPG_MAJOR_VERSION > 1
1069 get_public_key (app_t app
, int keyno
)
1071 gpg_error_t err
= 0;
1072 unsigned char *buffer
;
1073 const unsigned char *keydata
, *m
, *e
;
1074 size_t buflen
, keydatalen
, mlen
, elen
;
1075 unsigned char *mbuf
= NULL
;
1076 unsigned char *ebuf
= NULL
;
1077 char *keybuf
= NULL
;
1080 if (keyno
< 1 || keyno
> 3)
1081 return gpg_error (GPG_ERR_INV_ID
);
1084 /* Already cached? */
1085 if (app
->app_local
->pk
[keyno
].read_done
)
1088 xfree (app
->app_local
->pk
[keyno
].key
);
1089 app
->app_local
->pk
[keyno
].key
= NULL
;
1090 app
->app_local
->pk
[keyno
].keylen
= 0;
1092 m
= e
= NULL
; /* (avoid cc warning) */
1094 if (app
->card_version
> 0x0100)
1096 /* We may simply read the public key out of these cards. */
1097 err
= iso7816_read_public_key
1098 (app
->slot
, 0, (const unsigned char*)(keyno
== 0? "\xB6" :
1099 keyno
== 1? "\xB8" : "\xA4"), 2,
1104 log_error (_("reading public key failed: %s\n"), gpg_strerror (err
));
1108 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1111 err
= gpg_error (GPG_ERR_CARD
);
1112 log_error (_("response does not contain the public key data\n"));
1116 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1119 err
= gpg_error (GPG_ERR_CARD
);
1120 log_error (_("response does not contain the RSA modulus\n"));
1125 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1128 err
= gpg_error (GPG_ERR_CARD
);
1129 log_error (_("response does not contain the RSA public exponent\n"));
1133 /* Prepend numbers with a 0 if needed. */
1134 if (mlen
&& (*m
& 0x80))
1136 mbuf
= xtrymalloc ( mlen
+ 1);
1139 err
= gpg_error_from_syserror ();
1143 memcpy (mbuf
+1, m
, mlen
);
1147 if (elen
&& (*e
& 0x80))
1149 ebuf
= xtrymalloc ( elen
+ 1);
1152 err
= gpg_error_from_syserror ();
1156 memcpy (ebuf
+1, e
, elen
);
1164 /* Due to a design problem in v1.0 cards we can't get the public
1165 key out of these cards without doing a verify on CHV3.
1166 Clearly that is not an option and thus we try to locate the
1167 key using an external helper.
1169 The helper we use here is gpg itself, which should know about
1170 the key in any case. */
1174 char *command
= NULL
;
1178 buffer
= NULL
; /* We don't need buffer. */
1180 err
= retrieve_fpr_from_card (app
, keyno
, fpr
);
1183 log_error ("error while retrieving fpr from card: %s\n",
1184 gpg_strerror (err
));
1187 hexkeyid
= fpr
+ 24;
1189 ret
= estream_asprintf (&command
,
1190 "gpg --list-keys --with-colons --with-key-data '%s'",
1194 err
= gpg_error_from_syserror ();
1198 fp
= popen (command
, "r");
1202 err
= gpg_error_from_syserror ();
1203 log_error ("running gpg failed: %s\n", gpg_strerror (err
));
1207 err
= retrieve_key_material (fp
, hexkeyid
, &m
, &mlen
, &e
, &elen
);
1211 log_error ("error while retrieving key material through pipe: %s\n",
1212 gpg_strerror (err
));
1217 /* Allocate a buffer to construct the S-expression. */
1218 /* FIXME: We should provide a generalized S-expression creation
1220 keybuf
= xtrymalloc (50 + 2*35 + mlen
+ elen
+ 1);
1223 err
= gpg_error_from_syserror ();
1227 sprintf (keybuf
, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen
);
1228 keybuf_p
= keybuf
+ strlen (keybuf
);
1229 memcpy (keybuf_p
, m
, mlen
);
1231 sprintf (keybuf_p
, ")(1:e%u:", (unsigned int)elen
);
1232 keybuf_p
+= strlen (keybuf_p
);
1233 memcpy (keybuf_p
, e
, elen
);
1235 strcpy (keybuf_p
, ")))");
1236 keybuf_p
+= strlen (keybuf_p
);
1238 app
->app_local
->pk
[keyno
].key
= (unsigned char*)keybuf
;
1239 app
->app_local
->pk
[keyno
].keylen
= (keybuf_p
- keybuf
);
1242 /* Set a flag to indicate that we tried to read the key. */
1243 app
->app_local
->pk
[keyno
].read_done
= 1;
1250 #endif /* GNUPG_MAJOR_VERSION > 1 */
1254 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1255 This is used by the LEARN command. */
1257 send_keypair_info (app_t app
, ctrl_t ctrl
, int keyno
)
1259 gpg_error_t err
= 0;
1260 /* Note that GnuPG 1.x does not need this and it would be too time
1261 consuming to send it just for the fun of it. */
1262 #if GNUPG_MAJOR_VERSION > 1
1263 unsigned char grip
[20];
1267 err
= get_public_key (app
, keyno
);
1271 assert (keyno
>= 1 && keyno
<= 3);
1272 if (!app
->app_local
->pk
[keyno
-1].key
)
1273 goto leave
; /* No such key - ignore. */
1275 err
= keygrip_from_canon_sexp (app
->app_local
->pk
[keyno
-1].key
,
1276 app
->app_local
->pk
[keyno
-1].keylen
,
1281 bin2hex (grip
, 20, gripstr
);
1283 sprintf (idbuf
, "OPENPGP.%d", keyno
);
1284 send_status_info (ctrl
, "KEYPAIRINFO",
1286 idbuf
, strlen (idbuf
),
1290 #endif /* GNUPG_MAJOR_VERSION > 1 */
1296 /* Handle the LEARN command for OpenPGP. */
1298 do_learn_status (app_t app
, ctrl_t ctrl
, unsigned int flags
)
1302 do_getattr (app
, ctrl
, "EXTCAP");
1303 do_getattr (app
, ctrl
, "DISP-NAME");
1304 do_getattr (app
, ctrl
, "DISP-LANG");
1305 do_getattr (app
, ctrl
, "DISP-SEX");
1306 do_getattr (app
, ctrl
, "PUBKEY-URL");
1307 do_getattr (app
, ctrl
, "LOGIN-DATA");
1308 do_getattr (app
, ctrl
, "KEY-FPR");
1309 if (app
->card_version
> 0x0100)
1310 do_getattr (app
, ctrl
, "KEY-TIME");
1311 do_getattr (app
, ctrl
, "CA-FPR");
1312 do_getattr (app
, ctrl
, "CHV-STATUS");
1313 do_getattr (app
, ctrl
, "SIG-COUNTER");
1314 if (app
->app_local
->extcap
.private_dos
)
1316 do_getattr (app
, ctrl
, "PRIVATE-DO-1");
1317 do_getattr (app
, ctrl
, "PRIVATE-DO-2");
1319 do_getattr (app
, ctrl
, "PRIVATE-DO-3");
1321 do_getattr (app
, ctrl
, "PRIVATE-DO-4");
1323 send_keypair_info (app
, ctrl
, 1);
1324 send_keypair_info (app
, ctrl
, 2);
1325 send_keypair_info (app
, ctrl
, 3);
1326 /* Note: We do not send the Cardholder Certificate, because that is
1327 relativly long and for OpenPGP applications not really needed. */
1332 /* Handle the READKEY command for OpenPGP. On success a canonical
1333 encoded S-expression with the public key will get stored at PK and
1334 its length (for assertions) at PKLEN; the caller must release that
1335 buffer. On error PK and PKLEN are not changed and an error code is
1338 do_readkey (app_t app
, const char *keyid
, unsigned char **pk
, size_t *pklen
)
1340 #if GNUPG_MAJOR_VERSION > 1
1345 if (!strcmp (keyid
, "OPENPGP.1"))
1347 else if (!strcmp (keyid
, "OPENPGP.2"))
1349 else if (!strcmp (keyid
, "OPENPGP.3"))
1352 return gpg_error (GPG_ERR_INV_ID
);
1354 err
= get_public_key (app
, keyno
);
1358 buf
= app
->app_local
->pk
[keyno
-1].key
;
1360 return gpg_error (GPG_ERR_NO_PUBKEY
);
1361 *pklen
= app
->app_local
->pk
[keyno
-1].keylen
;;
1362 *pk
= xtrymalloc (*pklen
);
1365 err
= gpg_error_from_syserror ();
1369 memcpy (*pk
, buf
, *pklen
);
1372 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1376 /* Read the standard certificate of an OpenPGP v2 card. It is
1377 returned in a freshly allocated buffer with that address stored at
1378 CERT and the length of the certificate stored at CERTLEN. CERTID
1379 needs to be set to "OPENPGP.3". */
1381 do_readcert (app_t app
, const char *certid
,
1382 unsigned char **cert
, size_t *certlen
)
1384 #if GNUPG_MAJOR_VERSION > 1
1386 unsigned char *buffer
;
1392 if (strcmp (certid
, "OPENPGP.3"))
1393 return gpg_error (GPG_ERR_INV_ID
);
1394 if (!app
->app_local
->extcap
.is_v2
)
1395 return gpg_error (GPG_ERR_NOT_FOUND
);
1397 relptr
= get_one_do (app
, 0x7F21, &buffer
, &buflen
, NULL
);
1399 return gpg_error (GPG_ERR_NOT_FOUND
);
1401 *cert
= xtrymalloc (buflen
);
1403 err
= gpg_error_from_syserror ();
1406 memcpy (*cert
, buffer
, buflen
);
1413 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1418 /* Verify a CHV either using using the pinentry or if possibile by
1419 using a keypad. PINCB and PINCB_ARG describe the usual callback
1420 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1421 used with CHV1. PINVALUE is the address of a pointer which will
1422 receive a newly allocated block with the actual PIN (this is useful
1423 in case that PIN shall be used for another verifiy operation). The
1424 caller needs to free this value. If the function returns with
1425 success and NULL is stored at PINVALUE, the caller should take this
1426 as an indication that the keypad has been used.
1429 verify_a_chv (app_t app
,
1430 gpg_error_t (*pincb
)(void*, const char *, char **),
1432 int chvno
, unsigned long sigcount
, char **pinvalue
)
1435 char *prompt_buffer
= NULL
;
1437 iso7816_pininfo_t pininfo
;
1440 assert (chvno
== 1 || chvno
== 2);
1444 if (chvno
== 2 && app
->app_local
->flags
.def_chv2
)
1446 /* Special case for def_chv2 mechanism. */
1448 log_info (_("using default PIN as %s\n"), "CHV2");
1449 rc
= iso7816_verify (app
->slot
, 0x82, "123456", 6);
1452 /* Verification of CHV2 with the default PIN failed,
1453 although the card pretends to have the default PIN set as
1454 CHV2. We better disable the def_chv2 flag now. */
1455 log_info (_("failed to use default PIN as %s: %s"
1456 " - disabling further default use\n"),
1457 "CHV2", gpg_strerror (rc
));
1458 app
->app_local
->flags
.def_chv2
= 0;
1463 memset (&pininfo
, 0, sizeof pininfo
);
1465 pininfo
.minlen
= minlen
;
1470 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1471 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1473 prompt_buffer
= xtrymalloc (promptsize
);
1475 return gpg_error_from_syserror ();
1476 snprintf (prompt_buffer
, promptsize
-1, PROMPTSTRING
, sigcount
);
1477 prompt
= prompt_buffer
;
1481 prompt
= _("||Please enter the PIN");
1484 if (!opt
.disable_keypad
1485 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1487 /* The reader supports the verify command through the keypad.
1488 Note that the pincb appends a text to the prompt telling the
1489 user to use the keypad. */
1490 rc
= pincb (pincb_arg
, prompt
, NULL
);
1492 xfree (prompt_buffer
);
1493 prompt_buffer
= NULL
;
1496 log_info (_("PIN callback returned error: %s\n"),
1500 rc
= iso7816_verify_kp (app
->slot
, 0x80+chvno
, "", 0, &pininfo
);
1501 /* Dismiss the prompt. */
1502 pincb (pincb_arg
, NULL
, NULL
);
1504 assert (!*pinvalue
);
1508 /* The reader has no keypad or we don't want to use it. */
1509 rc
= pincb (pincb_arg
, prompt
, pinvalue
);
1511 xfree (prompt_buffer
);
1512 prompt_buffer
= NULL
;
1515 log_info (_("PIN callback returned error: %s\n"),
1520 if (strlen (*pinvalue
) < minlen
)
1522 log_error (_("PIN for CHV%d is too short;"
1523 " minimum length is %d\n"), chvno
, minlen
);
1526 return gpg_error (GPG_ERR_BAD_PIN
);
1529 rc
= iso7816_verify (app
->slot
, 0x80+chvno
,
1530 *pinvalue
, strlen (*pinvalue
));
1535 log_error (_("verify CHV%d failed: %s\n"), chvno
, gpg_strerror (rc
));
1538 flush_cache_after_error (app
);
1545 /* Verify CHV2 if required. Depending on the configuration of the
1546 card CHV1 will also be verified. */
1548 verify_chv2 (app_t app
,
1549 gpg_error_t (*pincb
)(void*, const char *, char **),
1556 return 0; /* We already verified CHV2. */
1558 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 2, 0, &pinvalue
);
1564 if (!app
->did_chv1
&& !app
->force_chv1
&& pinvalue
)
1566 /* For convenience we verify CHV1 here too. We do this only if
1567 the card is not configured to require a verification before
1568 each CHV1 controlled operation (force_chv1) and if we are not
1569 using the keypad (PINVALUE == NULL). */
1570 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
1571 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
1572 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
1575 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
1576 flush_cache_after_error (app
);
1587 /* Verify CHV3 if required. */
1589 verify_chv3 (app_t app
,
1590 gpg_error_t (*pincb
)(void*, const char *, char **),
1595 #if GNUPG_MAJOR_VERSION != 1
1596 if (!opt
.allow_admin
)
1598 log_info (_("access to admin commands is not configured\n"));
1599 return gpg_error (GPG_ERR_EACCES
);
1606 unsigned char *value
;
1608 iso7816_pininfo_t pininfo
;
1611 char *prompt_buffer
= NULL
;
1614 memset (&pininfo
, 0, sizeof pininfo
);
1616 pininfo
.minlen
= minlen
;
1618 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1619 if (!relptr
|| valuelen
< 7)
1621 log_error (_("error retrieving CHV status from card\n"));
1623 return gpg_error (GPG_ERR_CARD
);
1627 log_info (_("card is permanently locked!\n"));
1629 return gpg_error (GPG_ERR_BAD_PIN
);
1631 remaining
= value
[6];
1634 log_info(_("%d Admin PIN attempts remaining before card"
1635 " is permanently locked\n"), remaining
);
1639 /* TRANSLATORS: Do not translate the "|A|" prefix but keep
1640 it at the start of the string. Use %%0A to force a
1642 #define PROMPTSTRING _("|A|Please enter the Admin PIN%%0A" \
1643 "[remaining attempts: %d]")
1644 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1646 prompt_buffer
= xtrymalloc (promptsize
);
1648 return gpg_error_from_syserror ();
1649 snprintf (prompt_buffer
, promptsize
-1, PROMPTSTRING
, remaining
);
1650 prompt
= prompt_buffer
;
1654 prompt
= _("|A|Please enter the Admin PIN");
1656 if (!opt
.disable_keypad
1657 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1659 /* The reader supports the verify command through the keypad. */
1660 rc
= pincb (pincb_arg
, prompt
, NULL
);
1662 xfree (prompt_buffer
);
1663 prompt_buffer
= NULL
;
1666 log_info (_("PIN callback returned error: %s\n"),
1670 rc
= iso7816_verify_kp (app
->slot
, 0x83, "", 0, &pininfo
);
1671 /* Dismiss the prompt. */
1672 pincb (pincb_arg
, NULL
, NULL
);
1678 rc
= pincb (pincb_arg
, prompt
, &pinvalue
);
1680 xfree (prompt_buffer
);
1681 prompt_buffer
= NULL
;
1684 log_info (_("PIN callback returned error: %s\n"),
1689 if (strlen (pinvalue
) < minlen
)
1691 log_error (_("PIN for CHV%d is too short;"
1692 " minimum length is %d\n"), 3, minlen
);
1694 return gpg_error (GPG_ERR_BAD_PIN
);
1697 rc
= iso7816_verify (app
->slot
, 0x83, pinvalue
, strlen (pinvalue
));
1703 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc
));
1704 flush_cache_after_error (app
);
1713 /* Handle the SETATTR operation. All arguments are already basically
1716 do_setattr (app_t app
, const char *name
,
1717 gpg_error_t (*pincb
)(void*, const char *, char **),
1719 const unsigned char *value
, size_t valuelen
)
1728 unsigned int need_v2
:1;
1730 { "DISP-NAME", 0x005B, 3 },
1731 { "LOGIN-DATA", 0x005E, 3, 2 },
1732 { "DISP-LANG", 0x5F2D, 3 },
1733 { "DISP-SEX", 0x5F35, 3 },
1734 { "PUBKEY-URL", 0x5F50, 3 },
1735 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1736 { "CA-FPR-1", 0x00CA, 3 },
1737 { "CA-FPR-2", 0x00CB, 3 },
1738 { "CA-FPR-3", 0x00CC, 3 },
1739 { "PRIVATE-DO-1", 0x0101, 2 },
1740 { "PRIVATE-DO-2", 0x0102, 3 },
1741 { "PRIVATE-DO-3", 0x0103, 2 },
1742 { "PRIVATE-DO-4", 0x0104, 3 },
1743 { "CERT-3", 0x7F21, 3, 0, 1 },
1744 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1745 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1750 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
1752 if (!table
[idx
].name
)
1753 return gpg_error (GPG_ERR_INV_NAME
);
1754 if (table
[idx
].need_v2
&& !app
->app_local
->extcap
.is_v2
)
1755 return gpg_error (GPG_ERR_NOT_SUPPORTED
); /* Not yet supported. */
1757 switch (table
[idx
].need_chv
)
1760 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1763 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1771 /* Flush the cache before writing it, so that the next get operation
1772 will reread the data from the card and thus get synced in case of
1773 errors (e.g. data truncated by the card). */
1774 flush_cache_item (app
, table
[idx
].tag
);
1776 if (app
->app_local
->cardcap
.ext_lc_le
&& valuelen
> 254)
1777 exmode
= 1; /* Use extended length w/o a limit. */
1778 else if (app
->app_local
->cardcap
.cmd_chaining
&& valuelen
> 254)
1779 exmode
= -254; /* Command chaining with max. 254 bytes. */
1782 rc
= iso7816_put_data (app
->slot
, exmode
, table
[idx
].tag
, value
, valuelen
);
1784 log_error ("failed to set `%s': %s\n", table
[idx
].name
, gpg_strerror (rc
));
1786 if (table
[idx
].special
== 1)
1787 app
->force_chv1
= (valuelen
&& *value
== 0);
1788 else if (table
[idx
].special
== 2)
1789 parse_login_data (app
);
1795 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1796 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1797 PINCB and PINCB_ARG are the usual arguments for the pinentry
1800 do_writecert (app_t app
, ctrl_t ctrl
,
1801 const char *certidstr
,
1802 gpg_error_t (*pincb
)(void*, const char *, char **),
1804 const unsigned char *certdata
, size_t certdatalen
)
1807 #if GNUPG_MAJOR_VERSION > 1
1808 if (strcmp (certidstr
, "OPENPGP.3"))
1809 return gpg_error (GPG_ERR_INV_ID
);
1810 if (!certdata
|| !certdatalen
)
1811 return gpg_error (GPG_ERR_INV_ARG
);
1812 if (!app
->app_local
->extcap
.is_v2
)
1813 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
1814 if (certdatalen
> app
->app_local
->extcap
.max_certlen_3
)
1815 return gpg_error (GPG_ERR_TOO_LARGE
);
1816 return do_setattr (app
, "CERT-3", pincb
, pincb_arg
, certdata
, certdatalen
);
1818 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1824 /* Handle the PASSWD command. */
1826 do_change_pin (app_t app
, ctrl_t ctrl
, const char *chvnostr
,
1828 gpg_error_t (*pincb
)(void*, const char *, char **),
1832 int chvno
= atoi (chvnostr
);
1833 char *resetcode
= NULL
;
1835 int reset_mode
= !!(flags
& APP_CHANGE_FLAG_RESET
);
1836 int set_resetcode
= 0;
1840 if (reset_mode
&& chvno
== 3)
1842 rc
= gpg_error (GPG_ERR_INV_ID
);
1845 else if (reset_mode
|| chvno
== 3)
1847 /* We always require that the PIN is entered. */
1849 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1853 if (chvno
== 2 && app
->app_local
->extcap
.is_v2
)
1856 else if (chvno
== 2 && app
->app_local
->extcap
.is_v2
)
1858 /* There is no PW2 for v2 cards. We use this condition to allow
1859 a PW reset using the Reset Code. */
1861 unsigned char *value
;
1865 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1866 if (!relptr
|| valuelen
< 7)
1868 log_error (_("error retrieving CHV status from card\n"));
1870 rc
= gpg_error (GPG_ERR_CARD
);
1873 remaining
= value
[5];
1877 log_error (_("Reset Code not or not anymore available\n"));
1878 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1882 rc
= pincb (pincb_arg
, _("||Please enter the Reset Code for the card"),
1886 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1889 if (strlen (resetcode
) < 8)
1891 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1892 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1896 else if (chvno
== 1 || chvno
== 2)
1898 /* CHV1 and CVH2 should always have the same value, thus we
1900 int save_force
= app
->force_chv1
;
1902 app
->force_chv1
= 0;
1905 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1906 app
->force_chv1
= save_force
;
1912 rc
= gpg_error (GPG_ERR_INV_ID
);
1919 app
->did_chv1
= app
->did_chv2
= 0;
1921 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1922 keep it at the start of the string. We need this elsewhere
1923 to get some infos on the string. */
1924 rc
= pincb (pincb_arg
,
1925 set_resetcode
? _("|RN|New Reset Code") :
1926 chvno
== 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1930 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc
));
1938 buffer
= xtrymalloc (strlen (resetcode
) + strlen (pinvalue
) + 1);
1940 rc
= gpg_error_from_syserror ();
1943 strcpy (stpcpy (buffer
, resetcode
), pinvalue
);
1944 rc
= iso7816_reset_retry_counter_with_rc (app
->slot
, 0x81,
1945 buffer
, strlen (buffer
));
1946 wipememory (buffer
, strlen (buffer
));
1950 else if (set_resetcode
)
1952 if (strlen (pinvalue
) < 8)
1954 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1955 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1958 rc
= iso7816_put_data (app
->slot
, 0, 0xD3,
1959 pinvalue
, strlen (pinvalue
));
1961 else if (reset_mode
)
1963 rc
= iso7816_reset_retry_counter (app
->slot
, 0x81,
1964 pinvalue
, strlen (pinvalue
));
1965 if (!rc
&& !app
->app_local
->extcap
.is_v2
)
1966 rc
= iso7816_reset_retry_counter (app
->slot
, 0x82,
1967 pinvalue
, strlen (pinvalue
));
1971 if (chvno
== 1 || chvno
== 2)
1973 rc
= iso7816_change_reference_data (app
->slot
, 0x81, NULL
, 0,
1974 pinvalue
, strlen (pinvalue
));
1975 if (!rc
&& !app
->app_local
->extcap
.is_v2
)
1976 rc
= iso7816_change_reference_data (app
->slot
, 0x82, NULL
, 0,
1977 pinvalue
, strlen (pinvalue
));
1980 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
, NULL
, 0,
1981 pinvalue
, strlen (pinvalue
));
1985 wipememory (pinvalue
, strlen (pinvalue
));
1989 flush_cache_after_error (app
);
1994 wipememory (resetcode
, strlen (resetcode
));
2001 /* Check whether a key already exists. KEYIDX is the index of the key
2002 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2003 error returned if the key already exists. */
2005 does_key_exist (app_t app
, int keyidx
, int force
)
2007 const unsigned char *fpr
;
2008 unsigned char *buffer
;
2012 assert (keyidx
>=0 && keyidx
<= 2);
2014 if (iso7816_get_data (app
->slot
, 0x006E, &buffer
, &buflen
))
2016 log_error (_("error reading application data\n"));
2017 return gpg_error (GPG_ERR_GENERAL
);
2019 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2022 log_error (_("error reading fingerprint DO\n"));
2024 return gpg_error (GPG_ERR_GENERAL
);
2027 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
2030 if (i
!=20 && !force
)
2032 log_error (_("key already exists\n"));
2033 return gpg_error (GPG_ERR_EEXIST
);
2036 log_info (_("existing key will be replaced\n"));
2038 log_info (_("generating new key\n"));
2043 /* Create a TLV tag and value and store it at BUFFER. Return the length
2044 of tag and length. A LENGTH greater than 65535 is truncated. */
2046 add_tlv (unsigned char *buffer
, unsigned int tag
, size_t length
)
2048 unsigned char *p
= buffer
;
2050 assert (tag
<= 0xffff);
2056 else if (length
< 256)
2063 if (length
> 0xffff)
2074 /* Build the private key template as specified in the OpenPGP specs
2075 v2.0 section 4.3.3.7. */
2077 build_privkey_template (app_t app
, int keyno
,
2078 const unsigned char *rsa_n
, size_t rsa_n_len
,
2079 const unsigned char *rsa_e
, size_t rsa_e_len
,
2080 const unsigned char *rsa_p
, size_t rsa_p_len
,
2081 const unsigned char *rsa_q
, size_t rsa_q_len
,
2082 unsigned char **result
, size_t *resultlen
)
2084 size_t rsa_e_reqlen
;
2085 unsigned char privkey
[7*(1+3)];
2087 unsigned char exthdr
[2+2+3];
2089 unsigned char suffix
[2+3];
2093 unsigned char *template;
2094 size_t template_size
;
2099 switch (app
->app_local
->keyattr
[keyno
].format
)
2106 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
2109 return gpg_error (GPG_ERR_INV_VALUE
);
2112 /* Get the required length for E. */
2113 rsa_e_reqlen
= app
->app_local
->keyattr
[keyno
].e_bits
/8;
2114 assert (rsa_e_len
<= rsa_e_reqlen
);
2116 /* Build the 7f48 cardholder private key template. */
2120 tp
+= add_tlv (tp
, 0x91, rsa_e_reqlen
);
2121 datalen
+= rsa_e_reqlen
;
2123 tp
+= add_tlv (tp
, 0x92, rsa_p_len
);
2124 datalen
+= rsa_p_len
;
2126 tp
+= add_tlv (tp
, 0x93, rsa_q_len
);
2127 datalen
+= rsa_q_len
;
2129 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2130 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2132 tp
+= add_tlv (tp
, 0x97, rsa_n_len
);
2133 datalen
+= rsa_n_len
;
2135 privkey_len
= tp
- privkey
;
2137 /* Build the extended header list without the private key template. */
2139 *tp
++ = keyno
==0 ? 0xb6 : keyno
== 1? 0xb8 : 0xa4;
2141 tp
+= add_tlv (tp
, 0x7f48, privkey_len
);
2142 exthdr_len
= tp
- exthdr
;
2144 /* Build the 5f48 suffix of the data. */
2146 tp
+= add_tlv (tp
, 0x5f48, datalen
);
2147 suffix_len
= tp
- suffix
;
2149 /* Now concatenate everything. */
2150 template_size
= (1 + 3 /* 0x4d and len. */
2155 tp
= template = xtrymalloc_secure (template_size
);
2157 return gpg_error_from_syserror ();
2159 tp
+= add_tlv (tp
, 0x4d, exthdr_len
+ privkey_len
+ suffix_len
+ datalen
);
2160 memcpy (tp
, exthdr
, exthdr_len
);
2162 memcpy (tp
, privkey
, privkey_len
);
2164 memcpy (tp
, suffix
, suffix_len
);
2167 memcpy (tp
, rsa_e
, rsa_e_len
);
2168 if (rsa_e_len
< rsa_e_reqlen
)
2170 /* Right justify E. */
2171 memmove (tp
+ rsa_e_reqlen
- rsa_e_len
, tp
, rsa_e_len
);
2172 memset (tp
, 0, rsa_e_reqlen
- rsa_e_len
);
2176 memcpy (tp
, rsa_p
, rsa_p_len
);
2179 memcpy (tp
, rsa_q
, rsa_q_len
);
2182 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2183 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2185 memcpy (tp
, rsa_n
, rsa_n_len
);
2189 /* Sanity check. We don't know the exact length because we
2190 allocated 3 bytes for the first length header. */
2191 assert (tp
- template <= template_size
);
2194 *resultlen
= tp
- template;
2200 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2201 canonical encoded S-expression with the secret key in KEYDATA and
2202 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2203 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2204 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2205 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2206 the pinentry callback. */
2208 do_writekey (app_t app
, ctrl_t ctrl
,
2209 const char *keyid
, unsigned int flags
,
2210 gpg_error_t (*pincb
)(void*, const char *, char **),
2212 const unsigned char *keydata
, size_t keydatalen
)
2215 int force
= (flags
& 1);
2217 const unsigned char *buf
, *tok
;
2218 size_t buflen
, toklen
;
2219 int depth
, last_depth1
, last_depth2
;
2220 const unsigned char *rsa_n
= NULL
;
2221 const unsigned char *rsa_e
= NULL
;
2222 const unsigned char *rsa_p
= NULL
;
2223 const unsigned char *rsa_q
= NULL
;
2224 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
2226 unsigned int maxbits
;
2227 unsigned char *template = NULL
;
2229 size_t template_len
;
2230 unsigned char fprbuf
[20];
2235 if (!strcmp (keyid
, "OPENPGP.1"))
2237 else if (!strcmp (keyid
, "OPENPGP.2"))
2239 else if (!strcmp (keyid
, "OPENPGP.3"))
2242 return gpg_error (GPG_ERR_INV_ID
);
2244 err
= does_key_exist (app
, keyno
, force
);
2250 Parse the S-expression
2253 buflen
= keydatalen
;
2255 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2257 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2259 if (!tok
|| toklen
!= 11 || memcmp ("private-key", tok
, toklen
))
2263 else if (toklen
== 21 && !memcmp ("protected-private-key", tok
, toklen
))
2264 log_info ("protected-private-key passed to writekey\n");
2265 else if (toklen
== 20 && !memcmp ("shadowed-private-key", tok
, toklen
))
2266 log_info ("shadowed-private-key passed to writekey\n");
2267 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2270 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2272 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2274 if (!tok
|| toklen
!= 3 || memcmp ("rsa", tok
, toklen
))
2276 err
= gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO
);
2279 last_depth1
= depth
;
2280 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2281 && depth
&& depth
>= last_depth1
)
2285 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2288 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2290 if (tok
&& toklen
== 1)
2292 const unsigned char **mpi
;
2297 case 'n': mpi
= &rsa_n
; mpi_len
= &rsa_n_len
; break;
2298 case 'e': mpi
= &rsa_e
; mpi_len
= &rsa_e_len
; break;
2299 case 'p': mpi
= &rsa_p
; mpi_len
= &rsa_p_len
; break;
2300 case 'q': mpi
= &rsa_q
; mpi_len
= &rsa_q_len
;break;
2301 default: mpi
= NULL
; mpi_len
= NULL
; break;
2305 err
= gpg_error (GPG_ERR_DUP_VALUE
);
2308 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2312 /* Strip off leading zero bytes and save. */
2313 for (;toklen
&& !*tok
; toklen
--, tok
++)
2319 /* Skip until end of list. */
2320 last_depth2
= depth
;
2321 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2322 && depth
&& depth
>= last_depth2
)
2327 /* Parse other attributes. */
2328 last_depth1
= depth
;
2329 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2330 && depth
&& depth
>= last_depth1
)
2334 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2337 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2339 if (tok
&& toklen
== 10 && !memcmp ("created-at", tok
, toklen
))
2341 if ((err
= parse_sexp (&buf
,&buflen
,&depth
,&tok
,&toklen
)))
2345 for (created_at
=0; toklen
&& *tok
&& *tok
>= '0' && *tok
<= '9';
2347 created_at
= created_at
*10 + (*tok
- '0');
2350 /* Skip until end of list. */
2351 last_depth2
= depth
;
2352 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2353 && depth
&& depth
>= last_depth2
)
2360 /* Check that we have all parameters and that they match the card
2364 log_error (_("creation timestamp missing\n"));
2365 err
= gpg_error (GPG_ERR_INV_VALUE
);
2369 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2370 nbits
= rsa_n
? count_bits (rsa_n
, rsa_n_len
) : 0;
2371 if (nbits
!= maxbits
)
2373 log_error (_("RSA modulus missing or not of size %d bits\n"),
2375 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2379 maxbits
= app
->app_local
->keyattr
[keyno
].e_bits
;
2380 if (maxbits
> 32 && !app
->app_local
->extcap
.is_v2
)
2381 maxbits
= 32; /* Our code for v1 does only support 32 bits. */
2382 nbits
= rsa_e
? count_bits (rsa_e
, rsa_e_len
) : 0;
2383 if (nbits
< 2 || nbits
> maxbits
)
2385 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2387 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2391 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
/2;
2392 nbits
= rsa_p
? count_bits (rsa_p
, rsa_p_len
) : 0;
2393 if (nbits
!= maxbits
)
2395 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2397 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2400 nbits
= rsa_q
? count_bits (rsa_q
, rsa_q_len
) : 0;
2401 if (nbits
!= maxbits
)
2403 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2405 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2409 /* We need to remove the cached public key. */
2410 xfree (app
->app_local
->pk
[keyno
].key
);
2411 app
->app_local
->pk
[keyno
].key
= NULL
;
2412 app
->app_local
->pk
[keyno
].keylen
= 0;
2413 app
->app_local
->pk
[keyno
].read_done
= 0;
2416 if (app
->app_local
->extcap
.is_v2
)
2418 /* Build the private key template as described in section 4.3.3.7 of
2419 the OpenPGP card specs version 2.0. */
2422 err
= build_privkey_template (app
, keyno
,
2427 &template, &template_len
);
2431 /* Prepare for storing the key. */
2432 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2436 /* Store the key. */
2437 if (app
->app_local
->cardcap
.ext_lc_le
&& template_len
> 254)
2438 exmode
= 1; /* Use extended length w/o a limit. */
2439 else if (app
->app_local
->cardcap
.cmd_chaining
&& template_len
> 254)
2443 err
= iso7816_put_data_odd (app
->slot
, exmode
, 0x3fff,
2444 template, template_len
);
2448 /* Build the private key template as described in section 4.3.3.6 of
2449 the OpenPGP card specs version 1.1:
2450 0xC0 <length> public exponent
2451 0xC1 <length> prime p
2452 0xC2 <length> prime q
2454 assert (rsa_e_len
<= 4);
2455 template_len
= (1 + 1 + 4
2457 + 1 + 1 + rsa_q_len
);
2458 template = tp
= xtrymalloc_secure (template_len
);
2461 err
= gpg_error_from_syserror ();
2466 memcpy (tp
, rsa_e
, rsa_e_len
);
2469 /* Right justify E. */
2470 memmove (tp
+4-rsa_e_len
, tp
, rsa_e_len
);
2471 memset (tp
, 0, 4-rsa_e_len
);
2477 memcpy (tp
, rsa_p
, rsa_p_len
);
2482 memcpy (tp
, rsa_q
, rsa_q_len
);
2485 assert (tp
- template == template_len
);
2487 /* Prepare for storing the key. */
2488 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2492 /* Store the key. */
2493 err
= iso7816_put_data (app
->slot
, 0,
2494 (app
->card_version
> 0x0007? 0xE0:0xE9)+keyno
,
2495 template, template_len
);
2499 log_error (_("failed to store the key: %s\n"), gpg_strerror (err
));
2503 err
= store_fpr (app
->slot
, keyno
, created_at
,
2504 rsa_n
, rsa_n_len
, rsa_e
, rsa_e_len
,
2505 fprbuf
, app
->card_version
);
2516 /* Handle the GENKEY command. */
2518 do_genkey (app_t app
, ctrl_t ctrl
, const char *keynostr
, unsigned int flags
,
2520 gpg_error_t (*pincb
)(void*, const char *, char **),
2525 unsigned char fprbuf
[20];
2526 const unsigned char *keydata
, *m
, *e
;
2527 unsigned char *buffer
= NULL
;
2528 size_t buflen
, keydatalen
, mlen
, elen
;
2530 int keyno
= atoi (keynostr
);
2531 int force
= (flags
& 1);
2535 unsigned int keybits
;
2537 if (keyno
< 1 || keyno
> 3)
2538 return gpg_error (GPG_ERR_INV_ID
);
2541 /* We flush the cache to increase the traffic before a key
2542 generation. This _might_ help a card to gather more entropy. */
2545 /* Obviously we need to remove the cached public key. */
2546 xfree (app
->app_local
->pk
[keyno
].key
);
2547 app
->app_local
->pk
[keyno
].key
= NULL
;
2548 app
->app_local
->pk
[keyno
].keylen
= 0;
2549 app
->app_local
->pk
[keyno
].read_done
= 0;
2551 /* Check whether a key already exists. */
2552 rc
= does_key_exist (app
, keyno
, force
);
2556 /* Because we send the key parameter back via status lines we need
2557 to put a limit on the max. allowed keysize. 2048 bit will
2558 already lead to a 527 byte long status line and thus a 4096 bit
2559 key would exceed the Assuan line length limit. */
2560 keybits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2562 return gpg_error (GPG_ERR_TOO_LARGE
);
2564 /* Prepare for key generation by verifying the Admin PIN. */
2565 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
2569 /* Test whether we will need extended length mode. (1900 is an
2570 arbitrary length which for sure fits into a short apdu.) */
2571 if (app
->app_local
->cardcap
.ext_lc_le
&& keybits
> 1900)
2573 exmode
= 1; /* Use extended length w/o a limit. */
2574 le_value
= app
->app_local
->extcap
.max_rsp_data
;
2575 /* No need to check le_value because it comes from a 16 bit
2576 value and thus can't create an overflow on a 32 bit
2582 le_value
= 256; /* Use legacy value. */
2585 log_info (_("please wait while key is being generated ...\n"));
2586 start_at
= time (NULL
);
2587 rc
= iso7816_generate_keypair
2588 /* # warning key generation temporary replaced by reading an existing key. */
2589 /* rc = iso7816_read_public_key */
2591 (const unsigned char*)(keyno
== 0? "\xB6" :
2592 keyno
== 1? "\xB8" : "\xA4"), 2,
2597 rc
= gpg_error (GPG_ERR_CARD
);
2598 log_error (_("generating key failed\n"));
2601 log_info (_("key generation completed (%d seconds)\n"),
2602 (int)(time (NULL
) - start_at
));
2604 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
2607 rc
= gpg_error (GPG_ERR_CARD
);
2608 log_error (_("response does not contain the public key data\n"));
2612 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
2615 rc
= gpg_error (GPG_ERR_CARD
);
2616 log_error (_("response does not contain the RSA modulus\n"));
2619 /* log_printhex ("RSA n:", m, mlen); */
2620 send_key_data (ctrl
, "n", m
, mlen
);
2622 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
2625 rc
= gpg_error (GPG_ERR_CARD
);
2626 log_error (_("response does not contain the RSA public exponent\n"));
2629 /* log_printhex ("RSA e:", e, elen); */
2630 send_key_data (ctrl
, "e", e
, elen
);
2632 created_at
= createtime
? createtime
: gnupg_get_time ();
2633 sprintf (numbuf
, "%lu", (unsigned long)created_at
);
2634 send_status_info (ctrl
, "KEY-CREATED-AT",
2635 numbuf
, (size_t)strlen(numbuf
), NULL
, 0);
2637 rc
= store_fpr (app
->slot
, keyno
, (u32
)created_at
,
2638 m
, mlen
, e
, elen
, fprbuf
, app
->card_version
);
2641 send_fpr_if_not_null (ctrl
, "KEY-FPR", -1, fprbuf
);
2650 static unsigned long
2651 convert_sig_counter_value (const unsigned char *value
, size_t valuelen
)
2656 ul
= (value
[0] << 16) | (value
[1] << 8) | value
[2];
2659 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2665 static unsigned long
2666 get_sig_counter (app_t app
)
2669 unsigned char *value
;
2673 relptr
= get_one_do (app
, 0x0093, &value
, &valuelen
, NULL
);
2676 ul
= convert_sig_counter_value (value
, valuelen
);
2682 compare_fingerprint (app_t app
, int keyno
, unsigned char *sha1fpr
)
2684 const unsigned char *fpr
;
2685 unsigned char *buffer
;
2689 assert (keyno
>= 1 && keyno
<= 3);
2691 rc
= get_cached_data (app
, 0x006E, &buffer
, &buflen
, 0);
2694 log_error (_("error reading application data\n"));
2695 return gpg_error (GPG_ERR_GENERAL
);
2697 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2698 if (!fpr
|| n
!= 60)
2701 log_error (_("error reading fingerprint DO\n"));
2702 return gpg_error (GPG_ERR_GENERAL
);
2704 fpr
+= (keyno
-1)*20;
2705 for (i
=0; i
< 20; i
++)
2706 if (sha1fpr
[i
] != fpr
[i
])
2709 log_info (_("fingerprint on card does not match requested one\n"));
2710 return gpg_error (GPG_ERR_WRONG_SECKEY
);
2717 /* If a fingerprint has been specified check it against the one on
2718 the card. This is allows for a meaningful error message in case
2719 the key on the card has been replaced but the shadow information
2720 known to gpg was not updated. If there is no fingerprint we
2721 assume that this is okay. */
2723 check_against_given_fingerprint (app_t app
, const char *fpr
, int keyno
)
2725 unsigned char tmp
[20];
2729 for (s
=fpr
, n
=0; hexdigitp (s
); s
++, n
++)
2732 return gpg_error (GPG_ERR_INV_ID
);
2736 return gpg_error (GPG_ERR_INV_ID
);
2738 for (s
=fpr
, n
=0; n
< 20; s
+= 2, n
++)
2739 tmp
[n
] = xtoi_2 (s
);
2740 return compare_fingerprint (app
, keyno
, tmp
);
2745 /* Compute a digital signature on INDATA which is expected to be the
2746 raw message digest. For this application the KEYIDSTR consists of
2747 the serialnumber and the fingerprint delimited by a slash.
2749 Note that this function may return the error code
2750 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2751 not match the one required for the requested action (e.g. the
2752 serial number does not match).
2754 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2755 operation to the auth command.
2758 do_sign (app_t app
, const char *keyidstr
, int hashalgo
,
2759 gpg_error_t (*pincb
)(void*, const char *, char **),
2761 const void *indata
, size_t indatalen
,
2762 unsigned char **outdata
, size_t *outdatalen
)
2764 static unsigned char rmd160_prefix
[15] = /* Object ID is 1.3.36.3.2.1 */
2765 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2766 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2767 static unsigned char sha1_prefix
[15] = /* (1.3.14.3.2.26) */
2768 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2769 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2770 static unsigned char sha224_prefix
[19] = /* (2.16.840.1.101.3.4.2.4) */
2771 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2772 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2774 static unsigned char sha256_prefix
[19] = /* (2.16.840.1.101.3.4.2.1) */
2775 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2776 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2778 static unsigned char sha384_prefix
[19] = /* (2.16.840.1.101.3.4.2.2) */
2779 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2780 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
2782 static unsigned char sha512_prefix
[19] = /* (2.16.840.1.101.3.4.2.3) */
2783 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2784 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
2787 unsigned char data
[19+64];
2789 unsigned char tmp_sn
[20]; /* Actually 16 bytes but also for the fpr. */
2792 const char *fpr
= NULL
;
2793 unsigned long sigcount
;
2796 if (!keyidstr
|| !*keyidstr
)
2797 return gpg_error (GPG_ERR_INV_VALUE
);
2799 /* Strip off known prefixes. */
2800 #define X(a,b,c,d) \
2801 if (hashalgo == GCRY_MD_ ## a \
2803 && indatalen == sizeof b ## _prefix + (c) \
2804 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
2806 indata = (const char*)indata + sizeof b ## _prefix; \
2807 indatalen -= sizeof b ## _prefix; \
2810 if (indatalen
== 20)
2811 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
2812 else X(SHA1
, sha1
, 20, 1)
2813 else X(RMD160
, rmd160
, 20, 1)
2814 else X(SHA224
, sha224
, 28, app
->app_local
->extcap
.is_v2
)
2815 else X(SHA256
, sha256
, 32, app
->app_local
->extcap
.is_v2
)
2816 else X(SHA384
, sha384
, 48, app
->app_local
->extcap
.is_v2
)
2817 else X(SHA512
, sha512
, 64, app
->app_local
->extcap
.is_v2
)
2818 else if ((indatalen
== 28 || indatalen
== 32
2819 || indatalen
== 48 || indatalen
==64)
2820 && app
->app_local
->extcap
.is_v2
)
2821 ; /* Assume a plain SHA-3 digest has been given. */
2824 log_error (_("card does not support digest algorithm %s\n"),
2825 gcry_md_algo_name (hashalgo
));
2826 /* Or the supplied digest length does not match an algorithm. */
2827 return gpg_error (GPG_ERR_INV_VALUE
);
2831 /* Check whether an OpenPGP card of any version has been requested. */
2832 if (!strcmp (keyidstr
, "OPENPGP.1"))
2834 else if (!strcmp (keyidstr
, "OPENPGP.3"))
2836 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2837 return gpg_error (GPG_ERR_INV_ID
);
2840 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2843 return gpg_error (GPG_ERR_INV_ID
);
2845 ; /* no fingerprint given: we allow this for now. */
2849 return gpg_error (GPG_ERR_INV_ID
);
2851 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2852 tmp_sn
[n
] = xtoi_2 (s
);
2854 if (app
->serialnolen
!= 16)
2855 return gpg_error (GPG_ERR_INV_CARD
);
2856 if (memcmp (app
->serialno
, tmp_sn
, 16))
2857 return gpg_error (GPG_ERR_WRONG_CARD
);
2860 /* If a fingerprint has been specified check it against the one on
2861 the card. This is allows for a meaningful error message in case
2862 the key on the card has been replaced but the shadow information
2863 known to gpg was not updated. If there is no fingerprint, gpg
2864 will detect a bogus signature anyway due to the
2865 verify-after-signing feature. */
2866 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 1) : 0;
2870 /* Concatenate prefix and digest. */
2872 if (hashalgo == GCRY_MD_ ## a && (d) ) \
2874 datalen = sizeof b ## _prefix + indatalen; \
2875 assert (datalen <= sizeof data); \
2876 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
2877 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
2881 else X(RMD160
, rmd160
, 1)
2882 else X(SHA224
, sha224
, app
->app_local
->extcap
.is_v2
)
2883 else X(SHA256
, sha256
, app
->app_local
->extcap
.is_v2
)
2884 else X(SHA384
, sha384
, app
->app_local
->extcap
.is_v2
)
2885 else X(SHA512
, sha512
, app
->app_local
->extcap
.is_v2
)
2887 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM
);
2890 /* Redirect to the AUTH command if asked to. */
2893 return do_auth (app
, "OPENPGP.3", pincb
, pincb_arg
,
2895 outdata
, outdatalen
);
2898 /* Show the number of signature done using this key. */
2899 sigcount
= get_sig_counter (app
);
2900 log_info (_("signatures created so far: %lu\n"), sigcount
);
2902 /* Check CHV if needed. */
2903 if (!app
->did_chv1
|| app
->force_chv1
)
2907 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 1, sigcount
, &pinvalue
);
2913 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
2914 sync, thus we verify CHV2 here using the given PIN. Cards
2915 with version2 to not have the need for a separate CHV2 and
2916 internally use just one. Obviously we can't do that if the
2917 keypad has been used. */
2918 if (!app
->did_chv2
&& pinvalue
&& !app
->app_local
->extcap
.is_v2
)
2920 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
2921 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
2922 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
2925 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
2927 flush_cache_after_error (app
);
2935 rc
= iso7816_compute_ds (app
->slot
, data
, datalen
, outdata
, outdatalen
);
2939 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2940 on INDATA which is expected to be the raw message digest. For this
2941 application the KEYIDSTR consists of the serialnumber and the
2942 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2945 Note that this function may return the error code
2946 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2947 not match the one required for the requested action (e.g. the
2948 serial number does not match). */
2950 do_auth (app_t app
, const char *keyidstr
,
2951 gpg_error_t (*pincb
)(void*, const char *, char **),
2953 const void *indata
, size_t indatalen
,
2954 unsigned char **outdata
, size_t *outdatalen
)
2957 unsigned char tmp_sn
[20]; /* Actually 16 but we use it also for the fpr. */
2960 const char *fpr
= NULL
;
2962 if (!keyidstr
|| !*keyidstr
)
2963 return gpg_error (GPG_ERR_INV_VALUE
);
2964 if (indatalen
> 101) /* For a 2048 bit key. */
2965 return gpg_error (GPG_ERR_INV_VALUE
);
2967 /* Check whether an OpenPGP card of any version has been requested. */
2968 if (!strcmp (keyidstr
, "OPENPGP.3"))
2970 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2971 return gpg_error (GPG_ERR_INV_ID
);
2974 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2977 return gpg_error (GPG_ERR_INV_ID
);
2979 ; /* no fingerprint given: we allow this for now. */
2983 return gpg_error (GPG_ERR_INV_ID
);
2985 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2986 tmp_sn
[n
] = xtoi_2 (s
);
2988 if (app
->serialnolen
!= 16)
2989 return gpg_error (GPG_ERR_INV_CARD
);
2990 if (memcmp (app
->serialno
, tmp_sn
, 16))
2991 return gpg_error (GPG_ERR_WRONG_CARD
);
2994 /* If a fingerprint has been specified check it against the one on
2995 the card. This is allows for a meaningful error message in case
2996 the key on the card has been replaced but the shadow information
2997 known to gpg was not updated. If there is no fingerprint, gpg
2998 will detect a bogus signature anyway due to the
2999 verify-after-signing feature. */
3000 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 3) : 0;
3004 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
3006 rc
= iso7816_internal_authenticate (app
->slot
, indata
, indatalen
,
3007 outdata
, outdatalen
);
3013 do_decipher (app_t app
, const char *keyidstr
,
3014 gpg_error_t (*pincb
)(void*, const char *, char **),
3016 const void *indata
, size_t indatalen
,
3017 unsigned char **outdata
, size_t *outdatalen
)
3020 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
3023 const char *fpr
= NULL
;
3026 if (!keyidstr
|| !*keyidstr
|| !indatalen
)
3027 return gpg_error (GPG_ERR_INV_VALUE
);
3029 /* Check whether an OpenPGP card of any version has been requested. */
3030 if (!strcmp (keyidstr
, "OPENPGP.2"))
3032 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3033 return gpg_error (GPG_ERR_INV_ID
);
3036 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3039 return gpg_error (GPG_ERR_INV_ID
);
3041 ; /* no fingerprint given: we allow this for now. */
3045 return gpg_error (GPG_ERR_INV_ID
);
3047 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3048 tmp_sn
[n
] = xtoi_2 (s
);
3050 if (app
->serialnolen
!= 16)
3051 return gpg_error (GPG_ERR_INV_CARD
);
3052 if (memcmp (app
->serialno
, tmp_sn
, 16))
3053 return gpg_error (GPG_ERR_WRONG_CARD
);
3056 /* If a fingerprint has been specified check it against the one on
3057 the card. This is allows for a meaningful error message in case
3058 the key on the card has been replaced but the shadow information
3059 known to gpg was not updated. If there is no fingerprint, the
3060 decryption won't produce the right plaintext anyway. */
3061 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 2) : 0;
3065 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
3069 unsigned char *fixbuf
= NULL
;
3072 /* We might encounter a couple of leading zeroes in the
3073 cryptogram. Due to internal use of MPIs thease leading
3074 zeroes are stripped. However the OpenPGP card expects
3075 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3076 need to fix it up. We do this for up to 16 leading zero
3077 bytes; a cryptogram with more than this is with a very high
3078 probability anyway broken. */
3079 if (indatalen
>= (128-16) && indatalen
< 128) /* 1024 bit key. */
3080 fixuplen
= 128 - indatalen
;
3081 else if (indatalen
>= (192-16) && indatalen
< 192) /* 1536 bit key. */
3082 fixuplen
= 192 - indatalen
;
3083 else if (indatalen
>= (256-16) && indatalen
< 256) /* 2048 bit key. */
3084 fixuplen
= 256 - indatalen
;
3085 else if (indatalen
>= (384-16) && indatalen
< 384) /* 3072 bit key. */
3086 fixuplen
= 384 - indatalen
;
3092 /* While we have to prepend stuff anyway, we can also
3093 include the padding byte here so that iso1816_decipher
3094 does not need to do another data mangling. */
3097 fixbuf
= xtrymalloc (fixuplen
+ indatalen
);
3099 return gpg_error_from_syserror ();
3101 memset (fixbuf
, 0, fixuplen
);
3102 memcpy (fixbuf
+fixuplen
, indata
, indatalen
);
3104 indatalen
= fixuplen
+ indatalen
;
3105 padind
= -1; /* Already padded. */
3108 if (app
->app_local
->cardcap
.ext_lc_le
&& indatalen
> 254 )
3109 exmode
= 1; /* Extended length w/o a limit. */
3110 else if (app
->app_local
->cardcap
.cmd_chaining
&& indatalen
> 254)
3111 exmode
= -254; /* Command chaining with max. 254 bytes. */
3115 rc
= iso7816_decipher (app
->slot
, exmode
,
3116 indata
, indatalen
, padind
,
3117 outdata
, outdatalen
);
3125 /* Perform a simple verify operation for CHV1 and CHV2, so that
3126 further operations won't ask for CHV2 and it is possible to do a
3127 cheap check on the PIN: If there is something wrong with the PIN
3128 entry system, only the regular CHV will get blocked and not the
3129 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3130 optional fingerprint part will be ignored.
3132 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3133 the "[CHV3]" being a literal string: The Admin Pin is checked if
3134 and only if the retry counter is still at 3. */
3136 do_check_pin (app_t app
, const char *keyidstr
,
3137 gpg_error_t (*pincb
)(void*, const char *, char **),
3140 unsigned char tmp_sn
[20];
3145 if (!keyidstr
|| !*keyidstr
)
3146 return gpg_error (GPG_ERR_INV_VALUE
);
3148 /* Check whether an OpenPGP card of any version has been requested. */
3149 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3150 return gpg_error (GPG_ERR_INV_ID
);
3152 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3155 return gpg_error (GPG_ERR_INV_ID
);
3157 ; /* No fingerprint given: we allow this for now. */
3159 ; /* We ignore a fingerprint. */
3160 else if (!strcmp (s
, "[CHV3]") )
3163 return gpg_error (GPG_ERR_INV_ID
);
3165 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3166 tmp_sn
[n
] = xtoi_2 (s
);
3168 if (app
->serialnolen
!= 16)
3169 return gpg_error (GPG_ERR_INV_CARD
);
3170 if (memcmp (app
->serialno
, tmp_sn
, 16))
3171 return gpg_error (GPG_ERR_WRONG_CARD
);
3173 /* Yes, there is a race conditions: The user might pull the card
3174 right here and we won't notice that. However this is not a
3175 problem and the check above is merely for a graceful failure
3176 between operations. */
3181 unsigned char *value
;
3185 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
3186 if (!relptr
|| valuelen
< 7)
3188 log_error (_("error retrieving CHV status from card\n"));
3190 return gpg_error (GPG_ERR_CARD
);
3197 log_info (_("card is permanently locked!\n"));
3198 return gpg_error (GPG_ERR_BAD_PIN
);
3200 else if (value
[6] < 3)
3202 log_info (_("verification of Admin PIN is currently prohibited "
3203 "through this command\n"));
3204 return gpg_error (GPG_ERR_GENERAL
);
3207 app
->did_chv3
= 0; /* Force verification. */
3208 return verify_chv3 (app
, pincb
, pincb_arg
);
3211 return verify_chv2 (app
, pincb
, pincb_arg
);
3215 /* Show information about card capabilities. */
3217 show_caps (struct app_local_s
*s
)
3219 log_info ("Version-2 ......: %s\n", s
->extcap
.is_v2
? "yes":"no");
3220 log_info ("Get-Challenge ..: %s", s
->extcap
.get_challenge
? "yes":"no");
3221 if (s
->extcap
.get_challenge
)
3222 log_printf (" (%u bytes max)", s
->extcap
.max_get_challenge
);
3223 log_info ("Key-Import .....: %s\n", s
->extcap
.key_import
? "yes":"no");
3224 log_info ("Change-Force-PW1: %s\n", s
->extcap
.change_force_chv
? "yes":"no");
3225 log_info ("Private-DOs ....: %s\n", s
->extcap
.private_dos
? "yes":"no");
3226 log_info ("Algo-Attr-Change: %s\n", s
->extcap
.algo_attr_change
? "yes":"no");
3227 log_info ("SM-Support .....: %s", s
->extcap
.sm_supported
? "yes":"no");
3228 if (s
->extcap
.sm_supported
)
3229 log_printf (" (%s)", s
->extcap
.sm_aes128
? "AES-128":"3DES");
3230 log_info ("Max-Cert3-Len ..: %u\n", s
->extcap
.max_certlen_3
);
3231 log_info ("Max-Cmd-Data ...: %u\n", s
->extcap
.max_cmd_data
);
3232 log_info ("Max-Rsp-Data ...: %u\n", s
->extcap
.max_rsp_data
);
3233 log_info ("Cmd-Chaining ...: %s\n", s
->cardcap
.cmd_chaining
?"yes":"no");
3234 log_info ("Ext-Lc-Le ......: %s\n", s
->cardcap
.ext_lc_le
?"yes":"no");
3235 log_info ("Status Indicator: %02X\n", s
->status_indicator
);
3237 log_info ("GnuPG-No-Sync ..: %s\n", s
->flags
.no_sync
? "yes":"no");
3238 log_info ("GnuPG-Def-PW2 ..: %s\n", s
->flags
.def_chv2
? "yes":"no");
3242 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3245 parse_historical (struct app_local_s
*apploc
,
3246 const unsigned char * buffer
, size_t buflen
)
3248 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3251 log_error ("warning: historical bytes are too short\n");
3252 return; /* Too short. */
3256 log_error ("warning: bad category indicator in historical bytes\n");
3260 /* Skip category indicator. */
3264 /* Get the status indicator. */
3265 apploc
->status_indicator
= buffer
[buflen
-3];
3268 /* Parse the compact TLV. */
3271 unsigned int tag
= (*buffer
& 0xf0) >> 4;
3272 unsigned int len
= (*buffer
& 0x0f);
3275 log_error ("warning: bad Compact-TLV in historical bytes\n");
3276 return; /* Error. */
3280 if (tag
== 7 && len
== 3)
3282 /* Card capabilities. */
3283 apploc
->cardcap
.cmd_chaining
= !!(buffer
[2] & 0x80);
3284 apploc
->cardcap
.ext_lc_le
= !!(buffer
[2] & 0x40);
3292 /* Parse and optionally show the algorithm attributes for KEYNO.
3293 KEYNO must be in the range 0..2. */
3295 parse_algorithm_attribute (app_t app
, int keyno
)
3297 unsigned char *buffer
;
3300 const char const desc
[3][5] = {"sign", "encr", "auth"};
3302 assert (keyno
>=0 && keyno
<= 2);
3304 app
->app_local
->keyattr
[keyno
].n_bits
= 0;
3306 relptr
= get_one_do (app
, 0xC1+keyno
, &buffer
, &buflen
, NULL
);
3309 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3314 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3320 log_info ("Key-Attr-%s ..: ", desc
[keyno
]);
3321 if (*buffer
== 1 && (buflen
== 5 || buflen
== 6))
3323 app
->app_local
->keyattr
[keyno
].n_bits
= (buffer
[1]<<8 | buffer
[2]);
3324 app
->app_local
->keyattr
[keyno
].e_bits
= (buffer
[3]<<8 | buffer
[4]);
3325 app
->app_local
->keyattr
[keyno
].format
= 0;
3327 app
->app_local
->keyattr
[keyno
].format
= RSA_STD
;
3329 app
->app_local
->keyattr
[keyno
].format
= (buffer
[5] == 0? RSA_STD
:
3330 buffer
[5] == 1? RSA_STD_N
:
3331 buffer
[5] == 2? RSA_CRT
:
3332 buffer
[5] == 3? RSA_CRT_N
:
3337 ("RSA, n=%u, e=%u, fmt=%s\n",
3338 app
->app_local
->keyattr
[keyno
].n_bits
,
3339 app
->app_local
->keyattr
[keyno
].e_bits
,
3340 app
->app_local
->keyattr
[keyno
].format
== RSA_STD
? "std" :
3341 app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
?"std+n":
3342 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT
? "crt" :
3343 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
?"crt+n":"?");
3345 else if (opt
.verbose
)
3346 log_printhex ("", buffer
, buflen
);
3351 /* Select the OpenPGP application on the card in SLOT. This function
3352 must be used before any other OpenPGP application functions. */
3354 app_select_openpgp (app_t app
)
3356 static char const aid
[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3357 int slot
= app
->slot
;
3359 unsigned char *buffer
;
3363 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3364 special flag value. */
3365 rc
= iso7816_select_application (slot
, aid
, sizeof aid
, 0x0001);
3368 unsigned int manufacturer
;
3370 app
->apptype
= "OPENPGP";
3375 app
->app_local
= NULL
;
3377 /* The OpenPGP card returns the serial number as part of the
3378 AID; because we prefer to use OpenPGP serial numbers, we
3379 replace a possibly already set one from a EF.GDO with this
3380 one. Note, that for current OpenPGP cards, no EF.GDO exists
3381 and thus it won't matter at all. */
3382 rc
= iso7816_get_data (slot
, 0x004F, &buffer
, &buflen
);
3388 log_printhex ("", buffer
, buflen
);
3391 app
->card_version
= buffer
[6] << 8;
3392 app
->card_version
|= buffer
[7];
3393 manufacturer
= (buffer
[8]<<8 | buffer
[9]);
3395 xfree (app
->serialno
);
3396 app
->serialno
= buffer
;
3397 app
->serialnolen
= buflen
;
3399 app
->app_local
= xtrycalloc (1, sizeof *app
->app_local
);
3400 if (!app
->app_local
)
3402 rc
= gpg_error (gpg_err_code_from_errno (errno
));
3406 if (app
->card_version
>= 0x0200)
3407 app
->app_local
->extcap
.is_v2
= 1;
3410 /* Read the historical bytes. */
3411 relptr
= get_one_do (app
, 0x5f52, &buffer
, &buflen
, NULL
);
3416 log_info ("Historical Bytes: ");
3417 log_printhex ("", buffer
, buflen
);
3419 parse_historical (app
->app_local
, buffer
, buflen
);
3423 /* Read the force-chv1 flag. */
3424 relptr
= get_one_do (app
, 0x00C4, &buffer
, &buflen
, NULL
);
3427 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3428 "CHV Status Bytes");
3431 app
->force_chv1
= (buflen
&& *buffer
== 0);
3434 /* Read the extended capabilities. */
3435 relptr
= get_one_do (app
, 0x00C0, &buffer
, &buflen
, NULL
);
3438 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3439 "Extended Capability Flags" );
3444 app
->app_local
->extcap
.sm_supported
= !!(*buffer
& 0x80);
3445 app
->app_local
->extcap
.get_challenge
= !!(*buffer
& 0x40);
3446 app
->app_local
->extcap
.key_import
= !!(*buffer
& 0x20);
3447 app
->app_local
->extcap
.change_force_chv
= !!(*buffer
& 0x10);
3448 app
->app_local
->extcap
.private_dos
= !!(*buffer
& 0x08);
3449 app
->app_local
->extcap
.algo_attr_change
= !!(*buffer
& 0x04);
3453 /* Available with v2 cards. */
3454 app
->app_local
->extcap
.sm_aes128
= (buffer
[1] == 1);
3455 app
->app_local
->extcap
.max_get_challenge
3456 = (buffer
[2] << 8 | buffer
[3]);
3457 app
->app_local
->extcap
.max_certlen_3
= (buffer
[4] << 8 | buffer
[5]);
3458 app
->app_local
->extcap
.max_cmd_data
= (buffer
[6] << 8 | buffer
[7]);
3459 app
->app_local
->extcap
.max_rsp_data
= (buffer
[8] << 8 | buffer
[9]);
3463 /* Some of the first cards accidently don't set the
3464 CHANGE_FORCE_CHV bit but allow it anyway. */
3465 if (app
->card_version
<= 0x0100 && manufacturer
== 1)
3466 app
->app_local
->extcap
.change_force_chv
= 1;
3468 parse_login_data (app
);
3471 show_caps (app
->app_local
);
3473 parse_algorithm_attribute (app
, 0);
3474 parse_algorithm_attribute (app
, 1);
3475 parse_algorithm_attribute (app
, 2);
3477 if (opt
.verbose
> 1)
3480 app
->fnc
.deinit
= do_deinit
;
3481 app
->fnc
.learn_status
= do_learn_status
;
3482 app
->fnc
.readcert
= do_readcert
;
3483 app
->fnc
.readkey
= do_readkey
;
3484 app
->fnc
.getattr
= do_getattr
;
3485 app
->fnc
.setattr
= do_setattr
;
3486 app
->fnc
.writecert
= do_writecert
;
3487 app
->fnc
.writekey
= do_writekey
;
3488 app
->fnc
.genkey
= do_genkey
;
3489 app
->fnc
.sign
= do_sign
;
3490 app
->fnc
.auth
= do_auth
;
3491 app
->fnc
.decipher
= do_decipher
;
3492 app
->fnc
.change_pin
= do_change_pin
;
3493 app
->fnc
.check_pin
= do_check_pin
;