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
:1; /* 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
85 is currently only useful for the CHV
87 int try_extlen
:1; /* Large object; try to use an extended
91 { 0x005E, 0, 0, 1, 0, 0, 0, 0, "Login Data" },
92 { 0x5F50, 0, 0, 0, 0, 0, 0, 0, "URL" },
93 { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
94 { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
95 { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
96 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
97 { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
98 { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
99 { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
100 { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
101 { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
102 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
103 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
104 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
105 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
106 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
107 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
108 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
109 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
110 { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
111 { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
112 { 0x0101, 0, 0, 0, 0, 0, 0, 0, "Private DO 1"},
113 { 0x0102, 0, 0, 0, 0, 0, 0, 0, "Private DO 2"},
114 { 0x0103, 0, 0, 0, 0, 0, 0, 0, "Private DO 3"},
115 { 0x0104, 0, 0, 0, 0, 0, 0, 0, "Private DO 4"},
116 { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
121 /* The format of RSA private keys. */
133 /* One cache item for DOs. */
135 struct cache_s
*next
;
138 unsigned char data
[1];
142 /* Object with application (i.e. OpenPGP card) specific data. */
144 /* A linked list with cached DOs. */
145 struct cache_s
*cache
;
147 /* Keep track of the public keys. */
150 int read_done
; /* True if we have at least tried to read them. */
151 unsigned char *key
; /* This is a malloced buffer with a canonical
152 encoded S-expression encoding a public
153 key. Might be NULL if key is not
155 size_t keylen
; /* The length of the above S-expression. This
156 is usually only required for cross checks
157 because the length of an S-expression is
158 implicitly available. */
161 unsigned char status_indicator
; /* The card status indicator. */
163 /* Keep track of the ISO card capabilities. */
166 unsigned int cmd_chaining
:1; /* Command chaining is supported. */
167 unsigned int ext_lc_le
:1; /* Extended Lc and Le are supported. */
170 /* Keep track of extended card capabilities. */
173 unsigned int is_v2
:1; /* This is a v2.0 compatible card. */
174 unsigned int get_challenge
:1;
175 unsigned int key_import
:1;
176 unsigned int change_force_chv
:1;
177 unsigned int private_dos
:1;
178 unsigned int algo_attr_change
:1; /* Algorithm attributes changeable. */
179 unsigned int sm_supported
:1; /* Secure Messaging is supported. */
180 unsigned int sm_aes128
:1; /* Use AES-128 for SM. */
181 unsigned int max_certlen_3
:16;
182 unsigned int max_get_challenge
:16; /* Maximum size for get_challenge. */
183 unsigned int max_cmd_data
:16; /* Maximum data size for a command. */
184 unsigned int max_rsp_data
:16; /* Maximum size of a response. */
187 /* Flags used to control the application. */
190 unsigned int no_sync
:1; /* Do not sync CHV1 and CHV2 */
191 unsigned int def_chv2
:1; /* Use 123456 for CHV2. */
196 unsigned int n_bits
; /* Size of the modulus in bits. The rest
197 of this strucuire is only valid if
199 unsigned int e_bits
; /* Size of the public exponent in bits. */
200 rsa_key_format_t format
;
207 /***** Local prototypes *****/
208 static unsigned long convert_sig_counter_value (const unsigned char *value
,
210 static unsigned long get_sig_counter (app_t app
);
211 static gpg_error_t
do_auth (app_t app
, const char *keyidstr
,
212 gpg_error_t (*pincb
)(void*, const char *, char **),
214 const void *indata
, size_t indatalen
,
215 unsigned char **outdata
, size_t *outdatalen
);
216 static void parse_algorithm_attribute (app_t app
, int keyno
);
224 do_deinit (app_t app
)
226 if (app
&& app
->app_local
)
228 struct cache_s
*c
, *c2
;
231 for (c
= app
->app_local
->cache
; c
; c
= c2
)
237 for (i
=0; i
< DIM (app
->app_local
->pk
); i
++)
239 xfree (app
->app_local
->pk
[i
].key
);
240 app
->app_local
->pk
[i
].read_done
= 0;
242 xfree (app
->app_local
);
243 app
->app_local
= NULL
;
248 /* Wrapper around iso7816_get_data which first tries to get the data
249 from the cache. With GET_IMMEDIATE passed as true, the cache is
250 bypassed. With TRY_EXTLEN extended lengths APDUs are use if
251 supported by the card. */
253 get_cached_data (app_t app
, int tag
,
254 unsigned char **result
, size_t *resultlen
,
255 int get_immediate
, int try_extlen
)
269 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
274 p
= xtrymalloc (c
->length
);
276 return gpg_error (gpg_err_code_from_errno (errno
));
277 memcpy (p
, c
->data
, c
->length
);
281 *resultlen
= c
->length
;
287 if (try_extlen
&& app
->app_local
->cardcap
.ext_lc_le
)
288 exmode
= app
->app_local
->extcap
.max_rsp_data
;
292 err
= iso7816_get_data (app
->slot
, exmode
, tag
, &p
, &len
);
298 /* Check whether we should cache this object. */
302 for (i
=0; data_objects
[i
].tag
; i
++)
303 if (data_objects
[i
].tag
== tag
)
305 if (data_objects
[i
].dont_cache
)
310 /* Okay, cache it. */
311 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
312 assert (c
->tag
!= tag
);
314 c
= xtrymalloc (sizeof *c
+ len
);
317 memcpy (c
->data
, p
, len
);
320 c
->next
= app
->app_local
->cache
;
321 app
->app_local
->cache
= c
;
327 /* Remove DO at TAG from the cache. */
329 flush_cache_item (app_t app
, int tag
)
331 struct cache_s
*c
, *cprev
;
337 for (c
=app
->app_local
->cache
, cprev
=NULL
; c
; cprev
=c
, c
= c
->next
)
341 cprev
->next
= c
->next
;
343 app
->app_local
->cache
= c
->next
;
346 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
348 assert (c
->tag
!= tag
); /* Oops: duplicated entry. */
353 /* Try again if we have an outer tag. */
354 for (i
=0; data_objects
[i
].tag
; i
++)
355 if (data_objects
[i
].tag
== tag
&& data_objects
[i
].get_from
356 && data_objects
[i
].get_from
!= tag
)
357 flush_cache_item (app
, data_objects
[i
].get_from
);
360 /* Flush all entries from the cache which might be out of sync after
363 flush_cache_after_error (app_t app
)
367 for (i
=0; data_objects
[i
].tag
; i
++)
368 if (data_objects
[i
].flush_on_error
)
369 flush_cache_item (app
, data_objects
[i
].tag
);
373 /* Flush the entire cache. */
375 flush_cache (app_t app
)
377 if (app
&& app
->app_local
)
379 struct cache_s
*c
, *c2
;
381 for (c
= app
->app_local
->cache
; c
; c
= c2
)
386 app
->app_local
->cache
= NULL
;
391 /* Get the DO identified by TAG from the card in SLOT and return a
392 buffer with its content in RESULT and NBYTES. The return value is
393 NULL if not found or a pointer which must be used to release the
394 buffer holding value. */
396 get_one_do (app_t app
, int tag
, unsigned char **result
, size_t *nbytes
,
400 unsigned char *buffer
;
402 unsigned char *value
;
413 for (i
=0; data_objects
[i
].tag
&& data_objects
[i
].tag
!= tag
; i
++)
416 if (app
->card_version
> 0x0100 && data_objects
[i
].get_immediate_in_v11
)
418 if (data_objects
[i
].try_extlen
&& app
->app_local
->cardcap
.ext_lc_le
)
419 exmode
= app
->app_local
->extcap
.max_rsp_data
;
422 rc
= iso7816_get_data (app
->slot
, exmode
, tag
, &buffer
, &buflen
);
435 if (data_objects
[i
].tag
&& data_objects
[i
].get_from
)
437 rc
= get_cached_data (app
, data_objects
[i
].get_from
,
439 (data_objects
[i
].dont_cache
440 || data_objects
[i
].get_immediate_in_v11
),
441 data_objects
[i
].try_extlen
);
444 const unsigned char *s
;
446 s
= find_tlv_unchecked (buffer
, buflen
, tag
, &valuelen
);
448 value
= NULL
; /* not found */
449 else if (valuelen
> buflen
- (s
- buffer
))
451 log_error ("warning: constructed DO too short\n");
453 xfree (buffer
); buffer
= NULL
;
456 value
= buffer
+ (s
- buffer
);
460 if (!value
) /* Not in a constructed DO, try simple. */
462 rc
= get_cached_data (app
, tag
, &buffer
, &buflen
,
463 (data_objects
[i
].dont_cache
464 || data_objects
[i
].get_immediate_in_v11
),
465 data_objects
[i
].try_extlen
);
485 dump_all_do (int slot
)
488 unsigned char *buffer
;
491 for (i
=0; data_objects
[i
].tag
; i
++)
493 if (data_objects
[i
].get_from
)
496 /* We don't try extended length APDU because such large DO would
497 be pretty useless in a log file. */
498 rc
= iso7816_get_data (slot
, 0, data_objects
[i
].tag
, &buffer
, &buflen
);
499 if (gpg_err_code (rc
) == GPG_ERR_NO_OBJ
)
502 log_info ("DO `%s' not available: %s\n",
503 data_objects
[i
].desc
, gpg_strerror (rc
));
506 if (data_objects
[i
].binary
)
508 log_info ("DO `%s': ", data_objects
[i
].desc
);
509 log_printhex ("", buffer
, buflen
);
512 log_info ("DO `%s': `%.*s'\n",
513 data_objects
[i
].desc
,
514 (int)buflen
, buffer
); /* FIXME: sanitize */
516 if (data_objects
[i
].constructed
)
518 for (j
=0; data_objects
[j
].tag
; j
++)
520 const unsigned char *value
;
523 if (j
==i
|| data_objects
[i
].tag
!= data_objects
[j
].get_from
)
525 value
= find_tlv_unchecked (buffer
, buflen
,
526 data_objects
[j
].tag
, &valuelen
);
529 else if (valuelen
> buflen
- (value
- buffer
))
530 log_error ("warning: constructed DO too short\n");
533 if (data_objects
[j
].binary
)
535 log_info ("DO `%s': ", data_objects
[j
].desc
);
537 log_info ("[%u]\n", (unsigned int)valuelen
);
539 log_printhex ("", value
, valuelen
);
542 log_info ("DO `%s': `%.*s'\n",
543 data_objects
[j
].desc
,
544 (int)valuelen
, value
); /* FIXME: sanitize */
549 xfree (buffer
); buffer
= NULL
;
554 /* Count the number of bits, assuming the A represents an unsigned big
555 integer of length LEN bytes. */
557 count_bits (const unsigned char *a
, size_t len
)
559 unsigned int n
= len
* 8;
562 for (; len
&& !*a
; len
--, a
++, n
-=8)
566 for (i
=7; i
&& !(*a
& (1<<i
)); i
--)
572 /* GnuPG makes special use of the login-data DO, this function parses
573 the login data to store the flags for later use. It may be called
574 at any time and should be called after changing the login-data DO.
576 Everything up to a LF is considered a mailbox or account name. If
577 the first LF is followed by DC4 (0x14) control sequence are
578 expected up to the next LF. Control sequences are separated by FS
579 (0x18) and consist of key=value pairs. There is one key defined:
583 Were FLAGS is a plain hexadecimal number representing flag values.
584 The lsb is here the rightmost bit. Defined flags bits are:
586 Bit 0 = CHV1 and CHV2 are not syncronized
587 Bit 1 = CHV2 has been been set to the default PIN of "123456"
588 (this implies that bit 0 is also set).
592 parse_login_data (app_t app
)
594 unsigned char *buffer
, *p
;
599 app
->app_local
->flags
.no_sync
= 0;
600 app
->app_local
->flags
.def_chv2
= 0;
603 relptr
= get_one_do (app
, 0x005E, &buffer
, &buflen
, NULL
);
606 for (; buflen
; buflen
--, buffer
++)
609 if (buflen
< 2 || buffer
[1] != '\x14')
610 return; /* No control sequences. */
617 if (buflen
> 1 && *buffer
== 'F' && buffer
[1] == '=')
619 /* Flags control sequence found. */
622 /* For now we are only interested in the last digit, so skip
623 any leading digits but bail out on invalid characters. */
624 for (p
=buffer
+2, len
= buflen
-2; len
&& hexdigitp (p
); p
++, len
--)
625 lastdig
= xtoi_1 (p
);
626 if (len
&& !(*p
== '\n' || *p
== '\x18'))
627 goto next
; /* Invalid characters in field. */
628 app
->app_local
->flags
.no_sync
= !!(lastdig
& 1);
629 app
->app_local
->flags
.def_chv2
= (lastdig
& 3) == 3;
632 for (; buflen
&& *buffer
!= '\x18'; buflen
--, buffer
++)
641 /* Note, that FPR must be at least 20 bytes. */
643 store_fpr (app_t app
, int keynumber
, u32 timestamp
,
644 const unsigned char *m
, size_t mlen
,
645 const unsigned char *e
, size_t elen
,
646 unsigned char *fpr
, unsigned int card_version
)
648 unsigned int n
, nbits
;
649 unsigned char *buffer
, *p
;
653 for (; mlen
&& !*m
; mlen
--, m
++) /* strip leading zeroes */
655 for (; elen
&& !*e
; elen
--, e
++) /* strip leading zeroes */
658 n
= 6 + 2 + mlen
+ 2 + elen
;
659 p
= buffer
= xtrymalloc (3 + n
);
661 return gpg_error_from_syserror ();
663 *p
++ = 0x99; /* ctb */
664 *p
++ = n
>> 8; /* 2 byte length header */
666 *p
++ = 4; /* key packet version */
667 *p
++ = timestamp
>> 24;
668 *p
++ = timestamp
>> 16;
669 *p
++ = timestamp
>> 8;
672 nbits
= count_bits (m
, mlen
);
675 memcpy (p
, m
, mlen
); p
+= mlen
;
676 nbits
= count_bits (e
, elen
);
679 memcpy (p
, e
, elen
); p
+= elen
;
681 gcry_md_hash_buffer (GCRY_MD_SHA1
, fpr
, buffer
, n
+3);
685 tag
= (card_version
> 0x0007? 0xC7 : 0xC6) + keynumber
;
686 flush_cache_item (app
, tag
);
687 tag2
= 0xCE + keynumber
;
688 flush_cache_item (app
, tag2
);
690 rc
= iso7816_put_data (app
->slot
, 0, tag
, fpr
, 20);
692 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc
));
694 if (!rc
&& card_version
> 0x0100)
696 unsigned char buf
[4];
698 buf
[0] = timestamp
>> 24;
699 buf
[1] = timestamp
>> 16;
700 buf
[2] = timestamp
>> 8;
703 rc
= iso7816_put_data (app
->slot
, 0, tag2
, buf
, 4);
705 log_error (_("failed to store the creation date: %s\n"),
714 send_fpr_if_not_null (ctrl_t ctrl
, const char *keyword
,
715 int number
, const unsigned char *fpr
)
721 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
724 return; /* All zero. */
725 bin2hex (fpr
, 20, buf
);
727 *numbuf
= 0; /* Don't print the key number */
729 sprintf (numbuf
, "%d", number
);
730 send_status_info (ctrl
, keyword
,
731 numbuf
, (size_t)strlen(numbuf
),
732 buf
, (size_t)strlen (buf
), NULL
, 0);
736 send_fprtime_if_not_null (ctrl_t ctrl
, const char *keyword
,
737 int number
, const unsigned char *stamp
)
739 char numbuf1
[50], numbuf2
[50];
742 value
= (stamp
[0] << 24) | (stamp
[1]<<16) | (stamp
[2]<<8) | stamp
[3];
745 sprintf (numbuf1
, "%d", number
);
746 sprintf (numbuf2
, "%lu", value
);
747 send_status_info (ctrl
, keyword
,
748 numbuf1
, (size_t)strlen(numbuf1
),
749 numbuf2
, (size_t)strlen(numbuf2
), NULL
, 0);
753 send_key_data (ctrl_t ctrl
, const char *name
,
754 const unsigned char *a
, size_t alen
)
758 buf
= bin2hex (a
, alen
, NULL
);
761 log_error ("memory allocation error in send_key_data\n");
765 send_status_info (ctrl
, "KEY-DATA",
766 name
, (size_t)strlen(name
),
767 buf
, (size_t)strlen (buf
),
774 send_key_attr (ctrl_t ctrl
, app_t app
, const char *keyword
, int number
)
778 assert (number
>=0 && number
< DIM(app
->app_local
->keyattr
));
780 /* We only support RSA thus the algo identifier is fixed to 1. */
781 snprintf (buffer
, sizeof buffer
, "%d 1 %u %u %d",
783 app
->app_local
->keyattr
[number
].n_bits
,
784 app
->app_local
->keyattr
[number
].e_bits
,
785 app
->app_local
->keyattr
[number
].format
);
786 send_status_direct (ctrl
, keyword
, buffer
);
790 /* Implement the GETATTR command. This is similar to the LEARN
791 command but returns just one value via the status interface. */
793 do_getattr (app_t app
, ctrl_t ctrl
, const char *name
)
800 { "DISP-NAME", 0x005B },
801 { "LOGIN-DATA", 0x005E },
802 { "DISP-LANG", 0x5F2D },
803 { "DISP-SEX", 0x5F35 },
804 { "PUBKEY-URL", 0x5F50 },
805 { "KEY-FPR", 0x00C5, 3 },
806 { "KEY-TIME", 0x00CD, 4 },
807 { "KEY-ATTR", 0x0000, -5 },
808 { "CA-FPR", 0x00C6, 3 },
809 { "CHV-STATUS", 0x00C4, 1 },
810 { "SIG-COUNTER", 0x0093, 2 },
811 { "SERIALNO", 0x004F, -1 },
813 { "EXTCAP", 0x0000, -2 },
814 { "PRIVATE-DO-1", 0x0101 },
815 { "PRIVATE-DO-2", 0x0102 },
816 { "PRIVATE-DO-3", 0x0103 },
817 { "PRIVATE-DO-4", 0x0104 },
818 { "$AUTHKEYID", 0x0000, -3 },
819 { "$DISPSERIALNO",0x0000, -4 },
824 unsigned char *value
;
827 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
829 if (!table
[idx
].name
)
830 return gpg_error (GPG_ERR_INV_NAME
);
832 if (table
[idx
].special
== -1)
834 /* The serial number is very special. We could have used the
835 AID DO to retrieve it, but we have it already in the app
836 context and the stamp argument is required anyway which we
837 can't by other means. The AID DO is available anyway but not
843 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
845 sprintf (tmp
, "%lu", (unsigned long)stamp
);
846 send_status_info (ctrl
, "SERIALNO",
847 serial
, strlen (serial
),
854 if (table
[idx
].special
== -2)
858 snprintf (tmp
, sizeof tmp
,
859 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
860 app
->app_local
->extcap
.get_challenge
,
861 app
->app_local
->extcap
.key_import
,
862 app
->app_local
->extcap
.change_force_chv
,
863 app
->app_local
->extcap
.private_dos
,
864 app
->app_local
->extcap
.max_certlen_3
,
865 app
->app_local
->extcap
.algo_attr_change
,
866 (app
->app_local
->extcap
.sm_supported
867 ? (app
->app_local
->extcap
.sm_aes128
? 7 : 2)
869 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
872 if (table
[idx
].special
== -3)
874 char const tmp
[] = "OPENPGP.3";
875 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
878 if (table
[idx
].special
== -4)
883 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
885 if (strlen (serial
) > 16+12)
887 send_status_info (ctrl
, table
[idx
].name
, serial
+16, 12, NULL
, 0);
893 return gpg_error (GPG_ERR_INV_NAME
);
895 if (table
[idx
].special
== -5)
897 for (i
=0; i
< 3; i
++)
898 send_key_attr (ctrl
, app
, table
[idx
].name
, i
);
902 relptr
= get_one_do (app
, table
[idx
].tag
, &value
, &valuelen
, &rc
);
905 if (table
[idx
].special
== 1)
909 for (i
=0,*numbuf
=0; i
< valuelen
&& i
< 7; i
++)
910 sprintf (numbuf
+strlen (numbuf
), " %d", value
[i
]);
911 send_status_info (ctrl
, table
[idx
].name
,
912 numbuf
, strlen (numbuf
), NULL
, 0);
914 else if (table
[idx
].special
== 2)
918 sprintf (numbuf
, "%lu", convert_sig_counter_value (value
, valuelen
));
919 send_status_info (ctrl
, table
[idx
].name
,
920 numbuf
, strlen (numbuf
), NULL
, 0);
922 else if (table
[idx
].special
== 3)
925 for (i
=0; i
< 3; i
++)
926 send_fpr_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*20);
928 else if (table
[idx
].special
== 4)
931 for (i
=0; i
< 3; i
++)
932 send_fprtime_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*4);
935 send_status_info (ctrl
, table
[idx
].name
, value
, valuelen
, NULL
, 0);
942 /* Retrieve the fingerprint from the card inserted in SLOT and write
943 the according hex representation to FPR. Caller must have provide
944 a buffer at FPR of least 41 bytes. Returns 0 on success or an
946 #if GNUPG_MAJOR_VERSION > 1
948 retrieve_fpr_from_card (app_t app
, int keyno
, char *fpr
)
952 unsigned char *value
;
955 assert (keyno
>=0 && keyno
<= 2);
957 relptr
= get_one_do (app
, 0x00C5, &value
, &valuelen
, NULL
);
958 if (relptr
&& valuelen
>= 60)
959 bin2hex (value
+keyno
*20, 20, fpr
);
961 err
= gpg_error (GPG_ERR_NOT_FOUND
);
965 #endif /*GNUPG_MAJOR_VERSION > 1*/
968 /* Retrieve the public key material for the RSA key, whose fingerprint
969 is FPR, from gpg output, which can be read through the stream FP.
970 The RSA modulus will be stored at the address of M and MLEN, the
971 public exponent at E and ELEN. Returns zero on success, an error
972 code on failure. Caller must release the allocated buffers at M
973 and E if the function returns success. */
974 #if GNUPG_MAJOR_VERSION > 1
976 retrieve_key_material (FILE *fp
, const char *hexkeyid
,
977 const unsigned char **m
, size_t *mlen
,
978 const unsigned char **e
, size_t *elen
)
980 gcry_error_t err
= 0;
981 char *line
= NULL
; /* read_line() buffer. */
982 size_t line_size
= 0; /* Helper for for read_line. */
983 int found_key
= 0; /* Helper to find a matching key. */
984 unsigned char *m_new
= NULL
;
985 unsigned char *e_new
= NULL
;
989 /* Loop over all records until we have found the subkey
990 corresponding to the fingerprint. Inm general the first record
991 should be the pub record, but we don't rely on that. Given that
992 we only need to look at one key, it is sufficient to compare the
993 keyid so that we don't need to look at "fpr" records. */
1004 i
= read_line (fp
, &line
, &line_size
, &max_length
);
1009 err
= gpg_error_from_syserror ();
1010 goto leave
; /* Error. */
1014 err
= gpg_error (GPG_ERR_TRUNCATED
);
1015 goto leave
; /* Line truncated - we better stop processing. */
1018 /* Parse the line into fields. */
1019 for (nfields
=0, p
=line
; p
&& nfields
< DIM (fields
); nfields
++)
1021 fields
[nfields
] = p
;
1022 p
= strchr (p
, ':');
1027 continue; /* No fields at all - skip line. */
1031 if ( (!strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
1032 && nfields
> 4 && !strcmp (fields
[4], hexkeyid
))
1037 if ( !strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
1038 break; /* Next key - stop. */
1040 if ( strcmp (fields
[0], "pkd") )
1041 continue; /* Not a key data record. */
1042 i
= 0; /* Avoid erroneous compiler warning. */
1043 if ( nfields
< 4 || (i
= atoi (fields
[1])) < 0 || i
> 1
1044 || (!i
&& m_new
) || (i
&& e_new
))
1046 err
= gpg_error (GPG_ERR_GENERAL
);
1047 goto leave
; /* Error: Invalid key data record or not an RSA key. */
1050 err
= gcry_mpi_scan (&mpi
, GCRYMPI_FMT_HEX
, fields
[3], 0, NULL
);
1054 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &m_new
, &m_new_n
, mpi
);
1056 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &e_new
, &e_new_n
, mpi
);
1057 gcry_mpi_release (mpi
);
1072 err
= gpg_error (GPG_ERR_GENERAL
);
1080 #endif /*GNUPG_MAJOR_VERSION > 1*/
1083 /* Get the public key for KEYNO and store it as an S-expresion with
1084 the APP handle. On error that field gets cleared. If we already
1085 know about the public key we will just return. Note that this does
1086 not mean a key is available; this is soley indicated by the
1087 presence of the app->app_local->pk[KEYNO-1].key field.
1089 Note that GnuPG 1.x does not need this and it would be too time
1090 consuming to send it just for the fun of it. However, given that we
1091 use the same code in gpg 1.4, we can't use the gcry S-expresion
1092 here but need to open encode it. */
1093 #if GNUPG_MAJOR_VERSION > 1
1095 get_public_key (app_t app
, int keyno
)
1097 gpg_error_t err
= 0;
1098 unsigned char *buffer
;
1099 const unsigned char *keydata
, *m
, *e
;
1100 size_t buflen
, keydatalen
, mlen
, elen
;
1101 unsigned char *mbuf
= NULL
;
1102 unsigned char *ebuf
= NULL
;
1103 char *keybuf
= NULL
;
1106 if (keyno
< 1 || keyno
> 3)
1107 return gpg_error (GPG_ERR_INV_ID
);
1110 /* Already cached? */
1111 if (app
->app_local
->pk
[keyno
].read_done
)
1114 xfree (app
->app_local
->pk
[keyno
].key
);
1115 app
->app_local
->pk
[keyno
].key
= NULL
;
1116 app
->app_local
->pk
[keyno
].keylen
= 0;
1118 m
= e
= NULL
; /* (avoid cc warning) */
1120 if (app
->card_version
> 0x0100)
1122 int exmode
, le_value
;
1124 /* We may simply read the public key out of these cards. */
1125 if (app
->app_local
->cardcap
.ext_lc_le
)
1127 exmode
= 1; /* Use extended length. */
1128 le_value
= app
->app_local
->extcap
.max_rsp_data
;
1133 le_value
= 256; /* Use legacy value. */
1136 err
= iso7816_read_public_key
1138 (const unsigned char*)(keyno
== 0? "\xB6" :
1139 keyno
== 1? "\xB8" : "\xA4"), 2,
1144 log_error (_("reading public key failed: %s\n"), gpg_strerror (err
));
1148 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1151 err
= gpg_error (GPG_ERR_CARD
);
1152 log_error (_("response does not contain the public key data\n"));
1156 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1159 err
= gpg_error (GPG_ERR_CARD
);
1160 log_error (_("response does not contain the RSA modulus\n"));
1165 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1168 err
= gpg_error (GPG_ERR_CARD
);
1169 log_error (_("response does not contain the RSA public exponent\n"));
1173 /* Prepend numbers with a 0 if needed. */
1174 if (mlen
&& (*m
& 0x80))
1176 mbuf
= xtrymalloc ( mlen
+ 1);
1179 err
= gpg_error_from_syserror ();
1183 memcpy (mbuf
+1, m
, mlen
);
1187 if (elen
&& (*e
& 0x80))
1189 ebuf
= xtrymalloc ( elen
+ 1);
1192 err
= gpg_error_from_syserror ();
1196 memcpy (ebuf
+1, e
, elen
);
1204 /* Due to a design problem in v1.0 cards we can't get the public
1205 key out of these cards without doing a verify on CHV3.
1206 Clearly that is not an option and thus we try to locate the
1207 key using an external helper.
1209 The helper we use here is gpg itself, which should know about
1210 the key in any case. */
1214 char *command
= NULL
;
1218 buffer
= NULL
; /* We don't need buffer. */
1220 err
= retrieve_fpr_from_card (app
, keyno
, fpr
);
1223 log_error ("error while retrieving fpr from card: %s\n",
1224 gpg_strerror (err
));
1227 hexkeyid
= fpr
+ 24;
1229 ret
= estream_asprintf (&command
,
1230 "gpg --list-keys --with-colons --with-key-data '%s'",
1234 err
= gpg_error_from_syserror ();
1238 fp
= popen (command
, "r");
1242 err
= gpg_error_from_syserror ();
1243 log_error ("running gpg failed: %s\n", gpg_strerror (err
));
1247 err
= retrieve_key_material (fp
, hexkeyid
, &m
, &mlen
, &e
, &elen
);
1251 log_error ("error while retrieving key material through pipe: %s\n",
1252 gpg_strerror (err
));
1257 /* Allocate a buffer to construct the S-expression. */
1258 /* FIXME: We should provide a generalized S-expression creation
1260 keybuf
= xtrymalloc (50 + 2*35 + mlen
+ elen
+ 1);
1263 err
= gpg_error_from_syserror ();
1267 sprintf (keybuf
, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen
);
1268 keybuf_p
= keybuf
+ strlen (keybuf
);
1269 memcpy (keybuf_p
, m
, mlen
);
1271 sprintf (keybuf_p
, ")(1:e%u:", (unsigned int)elen
);
1272 keybuf_p
+= strlen (keybuf_p
);
1273 memcpy (keybuf_p
, e
, elen
);
1275 strcpy (keybuf_p
, ")))");
1276 keybuf_p
+= strlen (keybuf_p
);
1278 app
->app_local
->pk
[keyno
].key
= (unsigned char*)keybuf
;
1279 app
->app_local
->pk
[keyno
].keylen
= (keybuf_p
- keybuf
);
1282 /* Set a flag to indicate that we tried to read the key. */
1283 app
->app_local
->pk
[keyno
].read_done
= 1;
1290 #endif /* GNUPG_MAJOR_VERSION > 1 */
1294 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1295 This is used by the LEARN command. */
1297 send_keypair_info (app_t app
, ctrl_t ctrl
, int keyno
)
1299 gpg_error_t err
= 0;
1300 /* Note that GnuPG 1.x does not need this and it would be too time
1301 consuming to send it just for the fun of it. */
1302 #if GNUPG_MAJOR_VERSION > 1
1303 unsigned char grip
[20];
1307 err
= get_public_key (app
, keyno
);
1311 assert (keyno
>= 1 && keyno
<= 3);
1312 if (!app
->app_local
->pk
[keyno
-1].key
)
1313 goto leave
; /* No such key - ignore. */
1315 err
= keygrip_from_canon_sexp (app
->app_local
->pk
[keyno
-1].key
,
1316 app
->app_local
->pk
[keyno
-1].keylen
,
1321 bin2hex (grip
, 20, gripstr
);
1323 sprintf (idbuf
, "OPENPGP.%d", keyno
);
1324 send_status_info (ctrl
, "KEYPAIRINFO",
1326 idbuf
, strlen (idbuf
),
1330 #endif /* GNUPG_MAJOR_VERSION > 1 */
1336 /* Handle the LEARN command for OpenPGP. */
1338 do_learn_status (app_t app
, ctrl_t ctrl
, unsigned int flags
)
1342 do_getattr (app
, ctrl
, "EXTCAP");
1343 do_getattr (app
, ctrl
, "DISP-NAME");
1344 do_getattr (app
, ctrl
, "DISP-LANG");
1345 do_getattr (app
, ctrl
, "DISP-SEX");
1346 do_getattr (app
, ctrl
, "PUBKEY-URL");
1347 do_getattr (app
, ctrl
, "LOGIN-DATA");
1348 do_getattr (app
, ctrl
, "KEY-FPR");
1349 if (app
->card_version
> 0x0100)
1350 do_getattr (app
, ctrl
, "KEY-TIME");
1351 do_getattr (app
, ctrl
, "CA-FPR");
1352 do_getattr (app
, ctrl
, "CHV-STATUS");
1353 do_getattr (app
, ctrl
, "SIG-COUNTER");
1354 if (app
->app_local
->extcap
.private_dos
)
1356 do_getattr (app
, ctrl
, "PRIVATE-DO-1");
1357 do_getattr (app
, ctrl
, "PRIVATE-DO-2");
1359 do_getattr (app
, ctrl
, "PRIVATE-DO-3");
1361 do_getattr (app
, ctrl
, "PRIVATE-DO-4");
1363 send_keypair_info (app
, ctrl
, 1);
1364 send_keypair_info (app
, ctrl
, 2);
1365 send_keypair_info (app
, ctrl
, 3);
1366 /* Note: We do not send the Cardholder Certificate, because that is
1367 relativly long and for OpenPGP applications not really needed. */
1372 /* Handle the READKEY command for OpenPGP. On success a canonical
1373 encoded S-expression with the public key will get stored at PK and
1374 its length (for assertions) at PKLEN; the caller must release that
1375 buffer. On error PK and PKLEN are not changed and an error code is
1378 do_readkey (app_t app
, const char *keyid
, unsigned char **pk
, size_t *pklen
)
1380 #if GNUPG_MAJOR_VERSION > 1
1385 if (!strcmp (keyid
, "OPENPGP.1"))
1387 else if (!strcmp (keyid
, "OPENPGP.2"))
1389 else if (!strcmp (keyid
, "OPENPGP.3"))
1392 return gpg_error (GPG_ERR_INV_ID
);
1394 err
= get_public_key (app
, keyno
);
1398 buf
= app
->app_local
->pk
[keyno
-1].key
;
1400 return gpg_error (GPG_ERR_NO_PUBKEY
);
1401 *pklen
= app
->app_local
->pk
[keyno
-1].keylen
;;
1402 *pk
= xtrymalloc (*pklen
);
1405 err
= gpg_error_from_syserror ();
1409 memcpy (*pk
, buf
, *pklen
);
1412 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1416 /* Read the standard certificate of an OpenPGP v2 card. It is
1417 returned in a freshly allocated buffer with that address stored at
1418 CERT and the length of the certificate stored at CERTLEN. CERTID
1419 needs to be set to "OPENPGP.3". */
1421 do_readcert (app_t app
, const char *certid
,
1422 unsigned char **cert
, size_t *certlen
)
1424 #if GNUPG_MAJOR_VERSION > 1
1426 unsigned char *buffer
;
1432 if (strcmp (certid
, "OPENPGP.3"))
1433 return gpg_error (GPG_ERR_INV_ID
);
1434 if (!app
->app_local
->extcap
.is_v2
)
1435 return gpg_error (GPG_ERR_NOT_FOUND
);
1437 relptr
= get_one_do (app
, 0x7F21, &buffer
, &buflen
, NULL
);
1439 return gpg_error (GPG_ERR_NOT_FOUND
);
1442 err
= gpg_error (GPG_ERR_NOT_FOUND
);
1443 else if (!(*cert
= xtrymalloc (buflen
)))
1444 err
= gpg_error_from_syserror ();
1447 memcpy (*cert
, buffer
, buflen
);
1454 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1459 /* Verify a CHV either using using the pinentry or if possibile by
1460 using a keypad. PINCB and PINCB_ARG describe the usual callback
1461 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1462 used with CHV1. PINVALUE is the address of a pointer which will
1463 receive a newly allocated block with the actual PIN (this is useful
1464 in case that PIN shall be used for another verify operation). The
1465 caller needs to free this value. If the function returns with
1466 success and NULL is stored at PINVALUE, the caller should take this
1467 as an indication that the keypad has been used.
1470 verify_a_chv (app_t app
,
1471 gpg_error_t (*pincb
)(void*, const char *, char **),
1473 int chvno
, unsigned long sigcount
, char **pinvalue
)
1476 char *prompt_buffer
= NULL
;
1478 iso7816_pininfo_t pininfo
;
1481 assert (chvno
== 1 || chvno
== 2);
1485 if (chvno
== 2 && app
->app_local
->flags
.def_chv2
)
1487 /* Special case for def_chv2 mechanism. */
1489 log_info (_("using default PIN as %s\n"), "CHV2");
1490 rc
= iso7816_verify (app
->slot
, 0x82, "123456", 6);
1493 /* Verification of CHV2 with the default PIN failed,
1494 although the card pretends to have the default PIN set as
1495 CHV2. We better disable the def_chv2 flag now. */
1496 log_info (_("failed to use default PIN as %s: %s"
1497 " - disabling further default use\n"),
1498 "CHV2", gpg_strerror (rc
));
1499 app
->app_local
->flags
.def_chv2
= 0;
1504 memset (&pininfo
, 0, sizeof pininfo
);
1506 pininfo
.minlen
= minlen
;
1511 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1512 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1514 prompt_buffer
= xtrymalloc (promptsize
);
1516 return gpg_error_from_syserror ();
1517 snprintf (prompt_buffer
, promptsize
-1, PROMPTSTRING
, sigcount
);
1518 prompt
= prompt_buffer
;
1522 prompt
= _("||Please enter the PIN");
1525 if (!opt
.disable_keypad
1526 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1528 /* The reader supports the verify command through the keypad.
1529 Note that the pincb appends a text to the prompt telling the
1530 user to use the keypad. */
1531 rc
= pincb (pincb_arg
, prompt
, NULL
);
1533 xfree (prompt_buffer
);
1534 prompt_buffer
= NULL
;
1537 log_info (_("PIN callback returned error: %s\n"),
1541 rc
= iso7816_verify_kp (app
->slot
, 0x80+chvno
, "", 0, &pininfo
);
1542 /* Dismiss the prompt. */
1543 pincb (pincb_arg
, NULL
, NULL
);
1545 assert (!*pinvalue
);
1549 /* The reader has no keypad or we don't want to use it. */
1550 rc
= pincb (pincb_arg
, prompt
, pinvalue
);
1552 xfree (prompt_buffer
);
1553 prompt_buffer
= NULL
;
1556 log_info (_("PIN callback returned error: %s\n"),
1561 if (strlen (*pinvalue
) < minlen
)
1563 log_error (_("PIN for CHV%d is too short;"
1564 " minimum length is %d\n"), chvno
, minlen
);
1567 return gpg_error (GPG_ERR_BAD_PIN
);
1570 rc
= iso7816_verify (app
->slot
, 0x80+chvno
,
1571 *pinvalue
, strlen (*pinvalue
));
1576 log_error (_("verify CHV%d failed: %s\n"), chvno
, gpg_strerror (rc
));
1579 flush_cache_after_error (app
);
1586 /* Verify CHV2 if required. Depending on the configuration of the
1587 card CHV1 will also be verified. */
1589 verify_chv2 (app_t app
,
1590 gpg_error_t (*pincb
)(void*, const char *, char **),
1597 return 0; /* We already verified CHV2. */
1599 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 2, 0, &pinvalue
);
1604 if (!app
->did_chv1
&& !app
->force_chv1
&& pinvalue
)
1606 /* For convenience we verify CHV1 here too. We do this only if
1607 the card is not configured to require a verification before
1608 each CHV1 controlled operation (force_chv1) and if we are not
1609 using the keypad (PINVALUE == NULL). */
1610 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
1611 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
1612 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
1615 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
1616 flush_cache_after_error (app
);
1628 /* Build the prompt to enter the Admin PIN. The prompt depends on the
1629 current sdtate of the card. */
1631 build_enter_admin_pin_prompt (app_t app
, char **r_prompt
)
1634 unsigned char *value
;
1641 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1642 if (!relptr
|| valuelen
< 7)
1644 log_error (_("error retrieving CHV status from card\n"));
1646 return gpg_error (GPG_ERR_CARD
);
1650 log_info (_("card is permanently locked!\n"));
1652 return gpg_error (GPG_ERR_BAD_PIN
);
1654 remaining
= value
[6];
1657 log_info(_("%d Admin PIN attempts remaining before card"
1658 " is permanently locked\n"), remaining
);
1662 /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1663 the start of the string. Use %%0A to force a linefeed. */
1664 prompt
= xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1665 "[remaining attempts: %d]"), remaining
);
1668 prompt
= xtrystrdup (_("|A|Please enter the Admin PIN"));
1671 return gpg_error_from_syserror ();
1678 /* Verify CHV3 if required. */
1680 verify_chv3 (app_t app
,
1681 gpg_error_t (*pincb
)(void*, const char *, char **),
1686 #if GNUPG_MAJOR_VERSION != 1
1687 if (!opt
.allow_admin
)
1689 log_info (_("access to admin commands is not configured\n"));
1690 return gpg_error (GPG_ERR_EACCES
);
1696 iso7816_pininfo_t pininfo
;
1700 memset (&pininfo
, 0, sizeof pininfo
);
1702 pininfo
.minlen
= minlen
;
1704 rc
= build_enter_admin_pin_prompt (app
, &prompt
);
1708 if (!opt
.disable_keypad
1709 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1711 /* The reader supports the verify command through the keypad. */
1712 rc
= pincb (pincb_arg
, prompt
, NULL
);
1717 log_info (_("PIN callback returned error: %s\n"),
1721 rc
= iso7816_verify_kp (app
->slot
, 0x83, "", 0, &pininfo
);
1722 /* Dismiss the prompt. */
1723 pincb (pincb_arg
, NULL
, NULL
);
1729 rc
= pincb (pincb_arg
, prompt
, &pinvalue
);
1734 log_info (_("PIN callback returned error: %s\n"),
1739 if (strlen (pinvalue
) < minlen
)
1741 log_error (_("PIN for CHV%d is too short;"
1742 " minimum length is %d\n"), 3, minlen
);
1744 return gpg_error (GPG_ERR_BAD_PIN
);
1747 rc
= iso7816_verify (app
->slot
, 0x83, pinvalue
, strlen (pinvalue
));
1753 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc
));
1754 flush_cache_after_error (app
);
1763 /* Handle the SETATTR operation. All arguments are already basically
1766 do_setattr (app_t app
, const char *name
,
1767 gpg_error_t (*pincb
)(void*, const char *, char **),
1769 const unsigned char *value
, size_t valuelen
)
1778 unsigned int need_v2
:1;
1780 { "DISP-NAME", 0x005B, 3 },
1781 { "LOGIN-DATA", 0x005E, 3, 2 },
1782 { "DISP-LANG", 0x5F2D, 3 },
1783 { "DISP-SEX", 0x5F35, 3 },
1784 { "PUBKEY-URL", 0x5F50, 3 },
1785 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1786 { "CA-FPR-1", 0x00CA, 3 },
1787 { "CA-FPR-2", 0x00CB, 3 },
1788 { "CA-FPR-3", 0x00CC, 3 },
1789 { "PRIVATE-DO-1", 0x0101, 2 },
1790 { "PRIVATE-DO-2", 0x0102, 3 },
1791 { "PRIVATE-DO-3", 0x0103, 2 },
1792 { "PRIVATE-DO-4", 0x0104, 3 },
1793 { "CERT-3", 0x7F21, 3, 0, 1 },
1794 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1795 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1800 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
1802 if (!table
[idx
].name
)
1803 return gpg_error (GPG_ERR_INV_NAME
);
1804 if (table
[idx
].need_v2
&& !app
->app_local
->extcap
.is_v2
)
1805 return gpg_error (GPG_ERR_NOT_SUPPORTED
); /* Not yet supported. */
1807 switch (table
[idx
].need_chv
)
1810 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1813 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1821 /* Flush the cache before writing it, so that the next get operation
1822 will reread the data from the card and thus get synced in case of
1823 errors (e.g. data truncated by the card). */
1824 flush_cache_item (app
, table
[idx
].tag
);
1826 if (app
->app_local
->cardcap
.ext_lc_le
&& valuelen
> 254)
1827 exmode
= 1; /* Use extended length w/o a limit. */
1828 else if (app
->app_local
->cardcap
.cmd_chaining
&& valuelen
> 254)
1829 exmode
= -254; /* Command chaining with max. 254 bytes. */
1832 rc
= iso7816_put_data (app
->slot
, exmode
, table
[idx
].tag
, value
, valuelen
);
1834 log_error ("failed to set `%s': %s\n", table
[idx
].name
, gpg_strerror (rc
));
1836 if (table
[idx
].special
== 1)
1837 app
->force_chv1
= (valuelen
&& *value
== 0);
1838 else if (table
[idx
].special
== 2)
1839 parse_login_data (app
);
1845 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1846 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1847 PINCB and PINCB_ARG are the usual arguments for the pinentry
1850 do_writecert (app_t app
, ctrl_t ctrl
,
1851 const char *certidstr
,
1852 gpg_error_t (*pincb
)(void*, const char *, char **),
1854 const unsigned char *certdata
, size_t certdatalen
)
1857 #if GNUPG_MAJOR_VERSION > 1
1858 if (strcmp (certidstr
, "OPENPGP.3"))
1859 return gpg_error (GPG_ERR_INV_ID
);
1860 if (!certdata
|| !certdatalen
)
1861 return gpg_error (GPG_ERR_INV_ARG
);
1862 if (!app
->app_local
->extcap
.is_v2
)
1863 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
1864 if (certdatalen
> app
->app_local
->extcap
.max_certlen_3
)
1865 return gpg_error (GPG_ERR_TOO_LARGE
);
1866 return do_setattr (app
, "CERT-3", pincb
, pincb_arg
, certdata
, certdatalen
);
1868 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1874 /* Handle the PASSWD command. The following combinations are
1877 Flags CHVNO Vers. Description
1878 RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
1879 RESET 1 2 Verify PW3 and set a new PW1.
1880 RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
1881 RESET 2 2 Verify PW3 and set a new Reset Code.
1882 RESET 3 any Returns GPG_ERR_INV_ID.
1883 - 1 1 Verify CHV2 and set a new CHV1 and CHV2.
1884 - 1 2 Verify PW1 and set a new PW1.
1885 - 2 1 Verify CHV2 and set a new CHV1 and CHV2.
1886 - 2 2 Verify Reset Code and set a new PW1.
1887 - 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
1890 do_change_pin (app_t app
, ctrl_t ctrl
, const char *chvnostr
,
1892 gpg_error_t (*pincb
)(void*, const char *, char **),
1896 int chvno
= atoi (chvnostr
);
1897 char *resetcode
= NULL
;
1898 char *oldpinvalue
= NULL
;
1900 int reset_mode
= !!(flags
& APP_CHANGE_FLAG_RESET
);
1901 int set_resetcode
= 0;
1905 if (reset_mode
&& chvno
== 3)
1907 rc
= gpg_error (GPG_ERR_INV_ID
);
1911 if (!app
->app_local
->extcap
.is_v2
)
1913 /* Version 1 cards. */
1915 if (reset_mode
|| chvno
== 3)
1917 /* We always require that the PIN is entered. */
1919 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1923 else if (chvno
== 1 || chvno
== 2)
1925 /* On a v1.x card CHV1 and CVH2 should always have the same
1926 value, thus we enforce it here. */
1927 int save_force
= app
->force_chv1
;
1929 app
->force_chv1
= 0;
1932 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1933 app
->force_chv1
= save_force
;
1939 rc
= gpg_error (GPG_ERR_INV_ID
);
1945 /* Version 2 cards. */
1949 /* To reset a PIN the Admin PIN is required. */
1951 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1958 else if (chvno
== 1 || chvno
== 3)
1960 int minlen
= (chvno
==3)? 8 : 6;
1961 char *promptbuf
= NULL
;
1966 rc
= build_enter_admin_pin_prompt (app
, &promptbuf
);
1972 prompt
= _("||Please enter the PIN");
1973 rc
= pincb (pincb_arg
, prompt
, &oldpinvalue
);
1978 log_info (_("PIN callback returned error: %s\n"),
1983 if (strlen (oldpinvalue
) < minlen
)
1985 log_info (_("PIN for CHV%d is too short;"
1986 " minimum length is %d\n"), chvno
, minlen
);
1987 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1991 else if (chvno
== 2)
1993 /* There is no PW2 for v2 cards. We use this condition to
1994 allow a PW reset using the Reset Code. */
1996 unsigned char *value
;
2001 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
2002 if (!relptr
|| valuelen
< 7)
2004 log_error (_("error retrieving CHV status from card\n"));
2006 rc
= gpg_error (GPG_ERR_CARD
);
2009 remaining
= value
[5];
2013 log_error (_("Reset Code not or not anymore available\n"));
2014 rc
= gpg_error (GPG_ERR_BAD_PIN
);
2018 rc
= pincb (pincb_arg
,
2019 _("||Please enter the Reset Code for the card"),
2023 log_info (_("PIN callback returned error: %s\n"),
2027 if (strlen (resetcode
) < minlen
)
2029 log_info (_("Reset Code is too short; minimum length is %d\n"),
2031 rc
= gpg_error (GPG_ERR_BAD_PIN
);
2037 rc
= gpg_error (GPG_ERR_INV_ID
);
2045 app
->did_chv1
= app
->did_chv2
= 0;
2047 /* TRANSLATORS: Do not translate the "|*|" prefixes but
2048 keep it at the start of the string. We need this elsewhere
2049 to get some infos on the string. */
2050 rc
= pincb (pincb_arg
,
2051 set_resetcode
? _("|RN|New Reset Code") :
2052 chvno
== 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2056 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc
));
2065 buffer
= xtrymalloc (strlen (resetcode
) + strlen (pinvalue
) + 1);
2067 rc
= gpg_error_from_syserror ();
2070 strcpy (stpcpy (buffer
, resetcode
), pinvalue
);
2071 rc
= iso7816_reset_retry_counter_with_rc (app
->slot
, 0x81,
2072 buffer
, strlen (buffer
));
2073 wipememory (buffer
, strlen (buffer
));
2077 else if (set_resetcode
)
2079 if (strlen (pinvalue
) < 8)
2081 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2082 rc
= gpg_error (GPG_ERR_BAD_PIN
);
2085 rc
= iso7816_put_data (app
->slot
, 0, 0xD3,
2086 pinvalue
, strlen (pinvalue
));
2088 else if (reset_mode
)
2090 rc
= iso7816_reset_retry_counter (app
->slot
, 0x81,
2091 pinvalue
, strlen (pinvalue
));
2092 if (!rc
&& !app
->app_local
->extcap
.is_v2
)
2093 rc
= iso7816_reset_retry_counter (app
->slot
, 0x82,
2094 pinvalue
, strlen (pinvalue
));
2096 else if (!app
->app_local
->extcap
.is_v2
)
2098 /* Version 1 cards. */
2099 if (chvno
== 1 || chvno
== 2)
2101 rc
= iso7816_change_reference_data (app
->slot
, 0x81, NULL
, 0,
2102 pinvalue
, strlen (pinvalue
));
2104 rc
= iso7816_change_reference_data (app
->slot
, 0x82, NULL
, 0,
2105 pinvalue
, strlen (pinvalue
));
2107 else /* CHVNO == 3 */
2109 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
, NULL
, 0,
2110 pinvalue
, strlen (pinvalue
));
2115 /* Version 2 cards. */
2116 assert (chvno
== 1 || chvno
== 3);
2118 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
,
2119 oldpinvalue
, strlen (oldpinvalue
),
2120 pinvalue
, strlen (pinvalue
));
2125 wipememory (pinvalue
, strlen (pinvalue
));
2129 flush_cache_after_error (app
);
2134 wipememory (resetcode
, strlen (resetcode
));
2139 wipememory (oldpinvalue
, strlen (oldpinvalue
));
2140 xfree (oldpinvalue
);
2146 /* Check whether a key already exists. KEYIDX is the index of the key
2147 (0..2). If FORCE is TRUE a diagnositic will be printed but no
2148 error returned if the key already exists. The flag GENERATING is
2149 only used to print correct messages. */
2151 does_key_exist (app_t app
, int keyidx
, int generating
, int force
)
2153 const unsigned char *fpr
;
2154 unsigned char *buffer
;
2158 assert (keyidx
>=0 && keyidx
<= 2);
2160 if (iso7816_get_data (app
->slot
, 0, 0x006E, &buffer
, &buflen
))
2162 log_error (_("error reading application data\n"));
2163 return gpg_error (GPG_ERR_GENERAL
);
2165 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2168 log_error (_("error reading fingerprint DO\n"));
2170 return gpg_error (GPG_ERR_GENERAL
);
2173 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
2176 if (i
!=20 && !force
)
2178 log_error (_("key already exists\n"));
2179 return gpg_error (GPG_ERR_EEXIST
);
2182 log_info (_("existing key will be replaced\n"));
2183 else if (generating
)
2184 log_info (_("generating new key\n"));
2186 log_info (_("writing new key\n"));
2191 /* Create a TLV tag and value and store it at BUFFER. Return the length
2192 of tag and length. A LENGTH greater than 65535 is truncated. */
2194 add_tlv (unsigned char *buffer
, unsigned int tag
, size_t length
)
2196 unsigned char *p
= buffer
;
2198 assert (tag
<= 0xffff);
2204 else if (length
< 256)
2211 if (length
> 0xffff)
2222 /* Build the private key template as specified in the OpenPGP specs
2223 v2.0 section 4.3.3.7. */
2225 build_privkey_template (app_t app
, int keyno
,
2226 const unsigned char *rsa_n
, size_t rsa_n_len
,
2227 const unsigned char *rsa_e
, size_t rsa_e_len
,
2228 const unsigned char *rsa_p
, size_t rsa_p_len
,
2229 const unsigned char *rsa_q
, size_t rsa_q_len
,
2230 unsigned char **result
, size_t *resultlen
)
2232 size_t rsa_e_reqlen
;
2233 unsigned char privkey
[7*(1+3)];
2235 unsigned char exthdr
[2+2+3];
2237 unsigned char suffix
[2+3];
2241 unsigned char *template;
2242 size_t template_size
;
2247 switch (app
->app_local
->keyattr
[keyno
].format
)
2254 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
2257 return gpg_error (GPG_ERR_INV_VALUE
);
2260 /* Get the required length for E. */
2261 rsa_e_reqlen
= app
->app_local
->keyattr
[keyno
].e_bits
/8;
2262 assert (rsa_e_len
<= rsa_e_reqlen
);
2264 /* Build the 7f48 cardholder private key template. */
2268 tp
+= add_tlv (tp
, 0x91, rsa_e_reqlen
);
2269 datalen
+= rsa_e_reqlen
;
2271 tp
+= add_tlv (tp
, 0x92, rsa_p_len
);
2272 datalen
+= rsa_p_len
;
2274 tp
+= add_tlv (tp
, 0x93, rsa_q_len
);
2275 datalen
+= rsa_q_len
;
2277 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2278 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2280 tp
+= add_tlv (tp
, 0x97, rsa_n_len
);
2281 datalen
+= rsa_n_len
;
2283 privkey_len
= tp
- privkey
;
2285 /* Build the extended header list without the private key template. */
2287 *tp
++ = keyno
==0 ? 0xb6 : keyno
== 1? 0xb8 : 0xa4;
2289 tp
+= add_tlv (tp
, 0x7f48, privkey_len
);
2290 exthdr_len
= tp
- exthdr
;
2292 /* Build the 5f48 suffix of the data. */
2294 tp
+= add_tlv (tp
, 0x5f48, datalen
);
2295 suffix_len
= tp
- suffix
;
2297 /* Now concatenate everything. */
2298 template_size
= (1 + 3 /* 0x4d and len. */
2303 tp
= template = xtrymalloc_secure (template_size
);
2305 return gpg_error_from_syserror ();
2307 tp
+= add_tlv (tp
, 0x4d, exthdr_len
+ privkey_len
+ suffix_len
+ datalen
);
2308 memcpy (tp
, exthdr
, exthdr_len
);
2310 memcpy (tp
, privkey
, privkey_len
);
2312 memcpy (tp
, suffix
, suffix_len
);
2315 memcpy (tp
, rsa_e
, rsa_e_len
);
2316 if (rsa_e_len
< rsa_e_reqlen
)
2318 /* Right justify E. */
2319 memmove (tp
+ rsa_e_reqlen
- rsa_e_len
, tp
, rsa_e_len
);
2320 memset (tp
, 0, rsa_e_reqlen
- rsa_e_len
);
2324 memcpy (tp
, rsa_p
, rsa_p_len
);
2327 memcpy (tp
, rsa_q
, rsa_q_len
);
2330 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2331 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2333 memcpy (tp
, rsa_n
, rsa_n_len
);
2337 /* Sanity check. We don't know the exact length because we
2338 allocated 3 bytes for the first length header. */
2339 assert (tp
- template <= template_size
);
2342 *resultlen
= tp
- template;
2347 /* Helper for do_writekley to change the size of a key. Not ethat
2348 this deletes the entire key without asking. */
2350 change_keyattr (app_t app
, int keyno
, unsigned int nbits
,
2351 gpg_error_t (*pincb
)(void*, const char *, char **),
2355 unsigned char *buffer
;
2359 assert (keyno
>=0 && keyno
<= 2);
2362 return gpg_error (GPG_ERR_TOO_LARGE
);
2364 /* Read the current attributes into a buffer. */
2365 relptr
= get_one_do (app
, 0xC1+keyno
, &buffer
, &buflen
, NULL
);
2367 return gpg_error (GPG_ERR_CARD
);
2368 if (buflen
< 6 || buffer
[0] != 1)
2370 /* Attriutes too short or not an RSA key. */
2372 return gpg_error (GPG_ERR_CARD
);
2375 /* We only change n_bits and don't touch anything else. Before we
2376 do so, we round up NBITS to a sensible way in the same way as
2377 gpg's key generation does it. This may help to sort out problems
2378 with a few bits too short keys. */
2379 nbits
= ((nbits
+ 31) / 32) * 32;
2380 buffer
[1] = (nbits
>> 8);
2383 /* Prepare for storing the key. */
2384 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2391 /* Change the attribute. */
2392 err
= iso7816_put_data (app
->slot
, 0, 0xC1+keyno
, buffer
, buflen
);
2395 log_error ("error changing size of key %d to %u bits\n", keyno
+1, nbits
);
2397 log_info ("size of key %d changed to %u bits\n", keyno
+1, nbits
);
2399 parse_algorithm_attribute (app
, keyno
);
2408 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2409 canonical encoded S-expression with the secret key in KEYDATA and
2410 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2411 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2412 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2413 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2414 the pinentry callback. */
2416 do_writekey (app_t app
, ctrl_t ctrl
,
2417 const char *keyid
, unsigned int flags
,
2418 gpg_error_t (*pincb
)(void*, const char *, char **),
2420 const unsigned char *keydata
, size_t keydatalen
)
2423 int force
= (flags
& 1);
2425 const unsigned char *buf
, *tok
;
2426 size_t buflen
, toklen
;
2427 int depth
, last_depth1
, last_depth2
;
2428 const unsigned char *rsa_n
= NULL
;
2429 const unsigned char *rsa_e
= NULL
;
2430 const unsigned char *rsa_p
= NULL
;
2431 const unsigned char *rsa_q
= NULL
;
2432 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
2434 unsigned int maxbits
;
2435 unsigned char *template = NULL
;
2437 size_t template_len
;
2438 unsigned char fprbuf
[20];
2443 if (!strcmp (keyid
, "OPENPGP.1"))
2445 else if (!strcmp (keyid
, "OPENPGP.2"))
2447 else if (!strcmp (keyid
, "OPENPGP.3"))
2450 return gpg_error (GPG_ERR_INV_ID
);
2452 err
= does_key_exist (app
, keyno
, 0, force
);
2458 Parse the S-expression
2461 buflen
= keydatalen
;
2463 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2465 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2467 if (!tok
|| toklen
!= 11 || memcmp ("private-key", tok
, toklen
))
2471 else if (toklen
== 21 && !memcmp ("protected-private-key", tok
, toklen
))
2472 log_info ("protected-private-key passed to writekey\n");
2473 else if (toklen
== 20 && !memcmp ("shadowed-private-key", tok
, toklen
))
2474 log_info ("shadowed-private-key passed to writekey\n");
2475 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2478 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2480 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2482 if (!tok
|| toklen
!= 3 || memcmp ("rsa", tok
, toklen
))
2484 err
= gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO
);
2487 last_depth1
= depth
;
2488 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2489 && depth
&& depth
>= last_depth1
)
2493 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2496 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2498 if (tok
&& toklen
== 1)
2500 const unsigned char **mpi
;
2505 case 'n': mpi
= &rsa_n
; mpi_len
= &rsa_n_len
; break;
2506 case 'e': mpi
= &rsa_e
; mpi_len
= &rsa_e_len
; break;
2507 case 'p': mpi
= &rsa_p
; mpi_len
= &rsa_p_len
; break;
2508 case 'q': mpi
= &rsa_q
; mpi_len
= &rsa_q_len
;break;
2509 default: mpi
= NULL
; mpi_len
= NULL
; break;
2513 err
= gpg_error (GPG_ERR_DUP_VALUE
);
2516 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2520 /* Strip off leading zero bytes and save. */
2521 for (;toklen
&& !*tok
; toklen
--, tok
++)
2527 /* Skip until end of list. */
2528 last_depth2
= depth
;
2529 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2530 && depth
&& depth
>= last_depth2
)
2535 /* Parse other attributes. */
2536 last_depth1
= depth
;
2537 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2538 && depth
&& depth
>= last_depth1
)
2542 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2545 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2547 if (tok
&& toklen
== 10 && !memcmp ("created-at", tok
, toklen
))
2549 if ((err
= parse_sexp (&buf
,&buflen
,&depth
,&tok
,&toklen
)))
2553 for (created_at
=0; toklen
&& *tok
&& *tok
>= '0' && *tok
<= '9';
2555 created_at
= created_at
*10 + (*tok
- '0');
2558 /* Skip until end of list. */
2559 last_depth2
= depth
;
2560 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2561 && depth
&& depth
>= last_depth2
)
2568 /* Check that we have all parameters and that they match the card
2572 log_error (_("creation timestamp missing\n"));
2573 err
= gpg_error (GPG_ERR_INV_VALUE
);
2577 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2578 nbits
= rsa_n
? count_bits (rsa_n
, rsa_n_len
) : 0;
2580 log_info ("RSA modulus size is %u bits (%u bytes)\n",
2581 nbits
, (unsigned int)rsa_n_len
);
2582 if (nbits
&& nbits
!= maxbits
2583 && app
->app_local
->extcap
.algo_attr_change
)
2585 /* Try to switch the key to a new length. */
2586 err
= change_keyattr (app
, keyno
, nbits
, pincb
, pincb_arg
);
2588 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2590 if (nbits
!= maxbits
)
2592 log_error (_("RSA modulus missing or not of size %d bits\n"),
2594 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2598 maxbits
= app
->app_local
->keyattr
[keyno
].e_bits
;
2599 if (maxbits
> 32 && !app
->app_local
->extcap
.is_v2
)
2600 maxbits
= 32; /* Our code for v1 does only support 32 bits. */
2601 nbits
= rsa_e
? count_bits (rsa_e
, rsa_e_len
) : 0;
2602 if (nbits
< 2 || nbits
> maxbits
)
2604 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2606 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2610 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
/2;
2611 nbits
= rsa_p
? count_bits (rsa_p
, rsa_p_len
) : 0;
2612 if (nbits
!= maxbits
)
2614 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2616 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2619 nbits
= rsa_q
? count_bits (rsa_q
, rsa_q_len
) : 0;
2620 if (nbits
!= maxbits
)
2622 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2624 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2628 /* We need to remove the cached public key. */
2629 xfree (app
->app_local
->pk
[keyno
].key
);
2630 app
->app_local
->pk
[keyno
].key
= NULL
;
2631 app
->app_local
->pk
[keyno
].keylen
= 0;
2632 app
->app_local
->pk
[keyno
].read_done
= 0;
2635 if (app
->app_local
->extcap
.is_v2
)
2637 /* Build the private key template as described in section 4.3.3.7 of
2638 the OpenPGP card specs version 2.0. */
2641 err
= build_privkey_template (app
, keyno
,
2646 &template, &template_len
);
2650 /* Prepare for storing the key. */
2651 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2655 /* Store the key. */
2656 if (app
->app_local
->cardcap
.ext_lc_le
&& template_len
> 254)
2657 exmode
= 1; /* Use extended length w/o a limit. */
2658 else if (app
->app_local
->cardcap
.cmd_chaining
&& template_len
> 254)
2662 err
= iso7816_put_data_odd (app
->slot
, exmode
, 0x3fff,
2663 template, template_len
);
2667 /* Build the private key template as described in section 4.3.3.6 of
2668 the OpenPGP card specs version 1.1:
2669 0xC0 <length> public exponent
2670 0xC1 <length> prime p
2671 0xC2 <length> prime q
2673 assert (rsa_e_len
<= 4);
2674 template_len
= (1 + 1 + 4
2676 + 1 + 1 + rsa_q_len
);
2677 template = tp
= xtrymalloc_secure (template_len
);
2680 err
= gpg_error_from_syserror ();
2685 memcpy (tp
, rsa_e
, rsa_e_len
);
2688 /* Right justify E. */
2689 memmove (tp
+4-rsa_e_len
, tp
, rsa_e_len
);
2690 memset (tp
, 0, 4-rsa_e_len
);
2696 memcpy (tp
, rsa_p
, rsa_p_len
);
2701 memcpy (tp
, rsa_q
, rsa_q_len
);
2704 assert (tp
- template == template_len
);
2706 /* Prepare for storing the key. */
2707 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2711 /* Store the key. */
2712 err
= iso7816_put_data (app
->slot
, 0,
2713 (app
->card_version
> 0x0007? 0xE0:0xE9)+keyno
,
2714 template, template_len
);
2718 log_error (_("failed to store the key: %s\n"), gpg_strerror (err
));
2722 err
= store_fpr (app
, keyno
, created_at
,
2723 rsa_n
, rsa_n_len
, rsa_e
, rsa_e_len
,
2724 fprbuf
, app
->card_version
);
2735 /* Handle the GENKEY command. */
2737 do_genkey (app_t app
, ctrl_t ctrl
, const char *keynostr
, unsigned int flags
,
2739 gpg_error_t (*pincb
)(void*, const char *, char **),
2744 unsigned char fprbuf
[20];
2745 const unsigned char *keydata
, *m
, *e
;
2746 unsigned char *buffer
= NULL
;
2747 size_t buflen
, keydatalen
, mlen
, elen
;
2749 int keyno
= atoi (keynostr
);
2750 int force
= (flags
& 1);
2754 unsigned int keybits
;
2756 if (keyno
< 1 || keyno
> 3)
2757 return gpg_error (GPG_ERR_INV_ID
);
2760 /* We flush the cache to increase the traffic before a key
2761 generation. This _might_ help a card to gather more entropy. */
2764 /* Obviously we need to remove the cached public key. */
2765 xfree (app
->app_local
->pk
[keyno
].key
);
2766 app
->app_local
->pk
[keyno
].key
= NULL
;
2767 app
->app_local
->pk
[keyno
].keylen
= 0;
2768 app
->app_local
->pk
[keyno
].read_done
= 0;
2770 /* Check whether a key already exists. */
2771 rc
= does_key_exist (app
, keyno
, 1, force
);
2775 /* Because we send the key parameter back via status lines we need
2776 to put a limit on the max. allowed keysize. 2048 bit will
2777 already lead to a 527 byte long status line and thus a 4096 bit
2778 key would exceed the Assuan line length limit. */
2779 keybits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2781 return gpg_error (GPG_ERR_TOO_LARGE
);
2783 /* Prepare for key generation by verifying the Admin PIN. */
2784 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
2788 /* Test whether we will need extended length mode. (1900 is an
2789 arbitrary length which for sure fits into a short apdu.) */
2790 if (app
->app_local
->cardcap
.ext_lc_le
&& keybits
> 1900)
2792 exmode
= 1; /* Use extended length w/o a limit. */
2793 le_value
= app
->app_local
->extcap
.max_rsp_data
;
2794 /* No need to check le_value because it comes from a 16 bit
2795 value and thus can't create an overflow on a 32 bit
2801 le_value
= 256; /* Use legacy value. */
2804 log_info (_("please wait while key is being generated ...\n"));
2805 start_at
= time (NULL
);
2806 rc
= iso7816_generate_keypair
2807 /* # warning key generation temporary replaced by reading an existing key. */
2808 /* rc = iso7816_read_public_key */
2810 (const unsigned char*)(keyno
== 0? "\xB6" :
2811 keyno
== 1? "\xB8" : "\xA4"), 2,
2816 rc
= gpg_error (GPG_ERR_CARD
);
2817 log_error (_("generating key failed\n"));
2820 log_info (_("key generation completed (%d seconds)\n"),
2821 (int)(time (NULL
) - start_at
));
2823 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
2826 rc
= gpg_error (GPG_ERR_CARD
);
2827 log_error (_("response does not contain the public key data\n"));
2831 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
2834 rc
= gpg_error (GPG_ERR_CARD
);
2835 log_error (_("response does not contain the RSA modulus\n"));
2838 /* log_printhex ("RSA n:", m, mlen); */
2839 send_key_data (ctrl
, "n", m
, mlen
);
2841 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
2844 rc
= gpg_error (GPG_ERR_CARD
);
2845 log_error (_("response does not contain the RSA public exponent\n"));
2848 /* log_printhex ("RSA e:", e, elen); */
2849 send_key_data (ctrl
, "e", e
, elen
);
2851 created_at
= createtime
? createtime
: gnupg_get_time ();
2852 sprintf (numbuf
, "%lu", (unsigned long)created_at
);
2853 send_status_info (ctrl
, "KEY-CREATED-AT",
2854 numbuf
, (size_t)strlen(numbuf
), NULL
, 0);
2856 rc
= store_fpr (app
, keyno
, (u32
)created_at
,
2857 m
, mlen
, e
, elen
, fprbuf
, app
->card_version
);
2860 send_fpr_if_not_null (ctrl
, "KEY-FPR", -1, fprbuf
);
2869 static unsigned long
2870 convert_sig_counter_value (const unsigned char *value
, size_t valuelen
)
2875 ul
= (value
[0] << 16) | (value
[1] << 8) | value
[2];
2878 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2884 static unsigned long
2885 get_sig_counter (app_t app
)
2888 unsigned char *value
;
2892 relptr
= get_one_do (app
, 0x0093, &value
, &valuelen
, NULL
);
2895 ul
= convert_sig_counter_value (value
, valuelen
);
2901 compare_fingerprint (app_t app
, int keyno
, unsigned char *sha1fpr
)
2903 const unsigned char *fpr
;
2904 unsigned char *buffer
;
2908 assert (keyno
>= 1 && keyno
<= 3);
2910 rc
= get_cached_data (app
, 0x006E, &buffer
, &buflen
, 0, 0);
2913 log_error (_("error reading application data\n"));
2914 return gpg_error (GPG_ERR_GENERAL
);
2916 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2917 if (!fpr
|| n
!= 60)
2920 log_error (_("error reading fingerprint DO\n"));
2921 return gpg_error (GPG_ERR_GENERAL
);
2923 fpr
+= (keyno
-1)*20;
2924 for (i
=0; i
< 20; i
++)
2925 if (sha1fpr
[i
] != fpr
[i
])
2928 log_info (_("fingerprint on card does not match requested one\n"));
2929 return gpg_error (GPG_ERR_WRONG_SECKEY
);
2936 /* If a fingerprint has been specified check it against the one on the
2937 card. This allows for a meaningful error message in case the key
2938 on the card has been replaced but the shadow information known to
2939 gpg has not been updated. If there is no fingerprint we assume
2940 that this is okay. */
2942 check_against_given_fingerprint (app_t app
, const char *fpr
, int keyno
)
2944 unsigned char tmp
[20];
2948 for (s
=fpr
, n
=0; hexdigitp (s
); s
++, n
++)
2951 return gpg_error (GPG_ERR_INV_ID
);
2955 return gpg_error (GPG_ERR_INV_ID
);
2957 for (s
=fpr
, n
=0; n
< 20; s
+= 2, n
++)
2958 tmp
[n
] = xtoi_2 (s
);
2959 return compare_fingerprint (app
, keyno
, tmp
);
2964 /* Compute a digital signature on INDATA which is expected to be the
2965 raw message digest. For this application the KEYIDSTR consists of
2966 the serialnumber and the fingerprint delimited by a slash.
2968 Note that this function may return the error code
2969 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2970 not match the one required for the requested action (e.g. the
2971 serial number does not match).
2973 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2974 operation to the auth command.
2977 do_sign (app_t app
, const char *keyidstr
, int hashalgo
,
2978 gpg_error_t (*pincb
)(void*, const char *, char **),
2980 const void *indata
, size_t indatalen
,
2981 unsigned char **outdata
, size_t *outdatalen
)
2983 static unsigned char rmd160_prefix
[15] = /* Object ID is 1.3.36.3.2.1 */
2984 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2985 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2986 static unsigned char sha1_prefix
[15] = /* (1.3.14.3.2.26) */
2987 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2988 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2989 static unsigned char sha224_prefix
[19] = /* (2.16.840.1.101.3.4.2.4) */
2990 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2991 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2993 static unsigned char sha256_prefix
[19] = /* (2.16.840.1.101.3.4.2.1) */
2994 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2995 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2997 static unsigned char sha384_prefix
[19] = /* (2.16.840.1.101.3.4.2.2) */
2998 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2999 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3001 static unsigned char sha512_prefix
[19] = /* (2.16.840.1.101.3.4.2.3) */
3002 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3003 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3006 unsigned char data
[19+64];
3008 unsigned char tmp_sn
[20]; /* Actually 16 bytes but also for the fpr. */
3011 const char *fpr
= NULL
;
3012 unsigned long sigcount
;
3014 int exmode
, le_value
;
3016 if (!keyidstr
|| !*keyidstr
)
3017 return gpg_error (GPG_ERR_INV_VALUE
);
3019 /* Strip off known prefixes. */
3020 #define X(a,b,c,d) \
3021 if (hashalgo == GCRY_MD_ ## a \
3023 && indatalen == sizeof b ## _prefix + (c) \
3024 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3026 indata = (const char*)indata + sizeof b ## _prefix; \
3027 indatalen -= sizeof b ## _prefix; \
3030 if (indatalen
== 20)
3031 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3032 else X(SHA1
, sha1
, 20, 1)
3033 else X(RMD160
, rmd160
, 20, 1)
3034 else X(SHA224
, sha224
, 28, app
->app_local
->extcap
.is_v2
)
3035 else X(SHA256
, sha256
, 32, app
->app_local
->extcap
.is_v2
)
3036 else X(SHA384
, sha384
, 48, app
->app_local
->extcap
.is_v2
)
3037 else X(SHA512
, sha512
, 64, app
->app_local
->extcap
.is_v2
)
3038 else if ((indatalen
== 28 || indatalen
== 32
3039 || indatalen
== 48 || indatalen
==64)
3040 && app
->app_local
->extcap
.is_v2
)
3041 ; /* Assume a plain SHA-3 digest has been given. */
3044 log_error (_("card does not support digest algorithm %s\n"),
3045 gcry_md_algo_name (hashalgo
));
3046 /* Or the supplied digest length does not match an algorithm. */
3047 return gpg_error (GPG_ERR_INV_VALUE
);
3051 /* Check whether an OpenPGP card of any version has been requested. */
3052 if (!strcmp (keyidstr
, "OPENPGP.1"))
3054 else if (!strcmp (keyidstr
, "OPENPGP.3"))
3056 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3057 return gpg_error (GPG_ERR_INV_ID
);
3060 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3063 return gpg_error (GPG_ERR_INV_ID
);
3065 ; /* no fingerprint given: we allow this for now. */
3069 return gpg_error (GPG_ERR_INV_ID
);
3071 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3072 tmp_sn
[n
] = xtoi_2 (s
);
3074 if (app
->serialnolen
!= 16)
3075 return gpg_error (GPG_ERR_INV_CARD
);
3076 if (memcmp (app
->serialno
, tmp_sn
, 16))
3077 return gpg_error (GPG_ERR_WRONG_CARD
);
3080 /* If a fingerprint has been specified check it against the one on
3081 the card. This is allows for a meaningful error message in case
3082 the key on the card has been replaced but the shadow information
3083 known to gpg was not updated. If there is no fingerprint, gpg
3084 will detect a bogus signature anyway due to the
3085 verify-after-signing feature. */
3086 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 1) : 0;
3090 /* Concatenate prefix and digest. */
3092 if (hashalgo == GCRY_MD_ ## a && (d) ) \
3094 datalen = sizeof b ## _prefix + indatalen; \
3095 assert (datalen <= sizeof data); \
3096 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3097 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3101 else X(RMD160
, rmd160
, 1)
3102 else X(SHA224
, sha224
, app
->app_local
->extcap
.is_v2
)
3103 else X(SHA256
, sha256
, app
->app_local
->extcap
.is_v2
)
3104 else X(SHA384
, sha384
, app
->app_local
->extcap
.is_v2
)
3105 else X(SHA512
, sha512
, app
->app_local
->extcap
.is_v2
)
3107 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM
);
3110 /* Redirect to the AUTH command if asked to. */
3113 return do_auth (app
, "OPENPGP.3", pincb
, pincb_arg
,
3115 outdata
, outdatalen
);
3118 /* Show the number of signature done using this key. */
3119 sigcount
= get_sig_counter (app
);
3120 log_info (_("signatures created so far: %lu\n"), sigcount
);
3122 /* Check CHV if needed. */
3123 if (!app
->did_chv1
|| app
->force_chv1
)
3127 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 1, sigcount
, &pinvalue
);
3133 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3134 sync, thus we verify CHV2 here using the given PIN. Cards
3135 with version2 to not have the need for a separate CHV2 and
3136 internally use just one. Obviously we can't do that if the
3137 keypad has been used. */
3138 if (!app
->did_chv2
&& pinvalue
&& !app
->app_local
->extcap
.is_v2
)
3140 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
3141 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
3142 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
3145 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
3147 flush_cache_after_error (app
);
3156 if (app
->app_local
->cardcap
.ext_lc_le
)
3158 exmode
= 1; /* Use extended length. */
3159 le_value
= app
->app_local
->extcap
.max_rsp_data
;
3166 rc
= iso7816_compute_ds (app
->slot
, exmode
, data
, datalen
, le_value
,
3167 outdata
, outdatalen
);
3171 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3172 on INDATA which is expected to be the raw message digest. For this
3173 application the KEYIDSTR consists of the serialnumber and the
3174 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3177 Note that this function may return the error code
3178 GPG_ERR_WRONG_CARD to indicate that the card currently present does
3179 not match the one required for the requested action (e.g. the
3180 serial number does not match). */
3182 do_auth (app_t app
, const char *keyidstr
,
3183 gpg_error_t (*pincb
)(void*, const char *, char **),
3185 const void *indata
, size_t indatalen
,
3186 unsigned char **outdata
, size_t *outdatalen
)
3189 unsigned char tmp_sn
[20]; /* Actually 16 but we use it also for the fpr. */
3192 const char *fpr
= NULL
;
3194 if (!keyidstr
|| !*keyidstr
)
3195 return gpg_error (GPG_ERR_INV_VALUE
);
3196 if (indatalen
> 101) /* For a 2048 bit key. */
3197 return gpg_error (GPG_ERR_INV_VALUE
);
3199 /* Check whether an OpenPGP card of any version has been requested. */
3200 if (!strcmp (keyidstr
, "OPENPGP.3"))
3202 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3203 return gpg_error (GPG_ERR_INV_ID
);
3206 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3209 return gpg_error (GPG_ERR_INV_ID
);
3211 ; /* no fingerprint given: we allow this for now. */
3215 return gpg_error (GPG_ERR_INV_ID
);
3217 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3218 tmp_sn
[n
] = xtoi_2 (s
);
3220 if (app
->serialnolen
!= 16)
3221 return gpg_error (GPG_ERR_INV_CARD
);
3222 if (memcmp (app
->serialno
, tmp_sn
, 16))
3223 return gpg_error (GPG_ERR_WRONG_CARD
);
3226 /* If a fingerprint has been specified check it against the one on
3227 the card. This is allows for a meaningful error message in case
3228 the key on the card has been replaced but the shadow information
3229 known to gpg was not updated. If there is no fingerprint, gpg
3230 will detect a bogus signature anyway due to the
3231 verify-after-signing feature. */
3232 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 3) : 0;
3236 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
3239 int exmode
, le_value
;
3241 if (app
->app_local
->cardcap
.ext_lc_le
)
3243 exmode
= 1; /* Use extended length. */
3244 le_value
= app
->app_local
->extcap
.max_rsp_data
;
3251 rc
= iso7816_internal_authenticate (app
->slot
, exmode
,
3252 indata
, indatalen
, le_value
,
3253 outdata
, outdatalen
);
3260 do_decipher (app_t app
, const char *keyidstr
,
3261 gpg_error_t (*pincb
)(void*, const char *, char **),
3263 const void *indata
, size_t indatalen
,
3264 unsigned char **outdata
, size_t *outdatalen
)
3267 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
3270 const char *fpr
= NULL
;
3273 if (!keyidstr
|| !*keyidstr
|| !indatalen
)
3274 return gpg_error (GPG_ERR_INV_VALUE
);
3276 /* Check whether an OpenPGP card of any version has been requested. */
3277 if (!strcmp (keyidstr
, "OPENPGP.2"))
3279 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3280 return gpg_error (GPG_ERR_INV_ID
);
3283 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3286 return gpg_error (GPG_ERR_INV_ID
);
3288 ; /* no fingerprint given: we allow this for now. */
3292 return gpg_error (GPG_ERR_INV_ID
);
3294 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3295 tmp_sn
[n
] = xtoi_2 (s
);
3297 if (app
->serialnolen
!= 16)
3298 return gpg_error (GPG_ERR_INV_CARD
);
3299 if (memcmp (app
->serialno
, tmp_sn
, 16))
3300 return gpg_error (GPG_ERR_WRONG_CARD
);
3303 /* If a fingerprint has been specified check it against the one on
3304 the card. This is allows for a meaningful error message in case
3305 the key on the card has been replaced but the shadow information
3306 known to gpg was not updated. If there is no fingerprint, the
3307 decryption won't produce the right plaintext anyway. */
3308 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 2) : 0;
3312 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
3316 unsigned char *fixbuf
= NULL
;
3319 /* We might encounter a couple of leading zeroes in the
3320 cryptogram. Due to internal use of MPIs thease leading
3321 zeroes are stripped. However the OpenPGP card expects
3322 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3323 need to fix it up. We do this for up to 16 leading zero
3324 bytes; a cryptogram with more than this is with a very high
3325 probability anyway broken. */
3326 if (indatalen
>= (128-16) && indatalen
< 128) /* 1024 bit key. */
3327 fixuplen
= 128 - indatalen
;
3328 else if (indatalen
>= (192-16) && indatalen
< 192) /* 1536 bit key. */
3329 fixuplen
= 192 - indatalen
;
3330 else if (indatalen
>= (256-16) && indatalen
< 256) /* 2048 bit key. */
3331 fixuplen
= 256 - indatalen
;
3332 else if (indatalen
>= (384-16) && indatalen
< 384) /* 3072 bit key. */
3333 fixuplen
= 384 - indatalen
;
3339 /* While we have to prepend stuff anyway, we can also
3340 include the padding byte here so that iso1816_decipher
3341 does not need to do another data mangling. */
3344 fixbuf
= xtrymalloc (fixuplen
+ indatalen
);
3346 return gpg_error_from_syserror ();
3348 memset (fixbuf
, 0, fixuplen
);
3349 memcpy (fixbuf
+fixuplen
, indata
, indatalen
);
3351 indatalen
= fixuplen
+ indatalen
;
3352 padind
= -1; /* Already padded. */
3355 if (app
->app_local
->cardcap
.ext_lc_le
&& indatalen
> 254 )
3356 exmode
= 1; /* Extended length w/o a limit. */
3357 else if (app
->app_local
->cardcap
.cmd_chaining
&& indatalen
> 254)
3358 exmode
= -254; /* Command chaining with max. 254 bytes. */
3362 rc
= iso7816_decipher (app
->slot
, exmode
,
3363 indata
, indatalen
, padind
,
3364 outdata
, outdatalen
);
3372 /* Perform a simple verify operation for CHV1 and CHV2, so that
3373 further operations won't ask for CHV2 and it is possible to do a
3374 cheap check on the PIN: If there is something wrong with the PIN
3375 entry system, only the regular CHV will get blocked and not the
3376 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3377 optional fingerprint part will be ignored.
3379 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3380 the "[CHV3]" being a literal string: The Admin Pin is checked if
3381 and only if the retry counter is still at 3. */
3383 do_check_pin (app_t app
, const char *keyidstr
,
3384 gpg_error_t (*pincb
)(void*, const char *, char **),
3387 unsigned char tmp_sn
[20];
3392 if (!keyidstr
|| !*keyidstr
)
3393 return gpg_error (GPG_ERR_INV_VALUE
);
3395 /* Check whether an OpenPGP card of any version has been requested. */
3396 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3397 return gpg_error (GPG_ERR_INV_ID
);
3399 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3402 return gpg_error (GPG_ERR_INV_ID
);
3404 ; /* No fingerprint given: we allow this for now. */
3406 ; /* We ignore a fingerprint. */
3407 else if (!strcmp (s
, "[CHV3]") )
3410 return gpg_error (GPG_ERR_INV_ID
);
3412 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3413 tmp_sn
[n
] = xtoi_2 (s
);
3415 if (app
->serialnolen
!= 16)
3416 return gpg_error (GPG_ERR_INV_CARD
);
3417 if (memcmp (app
->serialno
, tmp_sn
, 16))
3418 return gpg_error (GPG_ERR_WRONG_CARD
);
3420 /* Yes, there is a race conditions: The user might pull the card
3421 right here and we won't notice that. However this is not a
3422 problem and the check above is merely for a graceful failure
3423 between operations. */
3428 unsigned char *value
;
3432 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
3433 if (!relptr
|| valuelen
< 7)
3435 log_error (_("error retrieving CHV status from card\n"));
3437 return gpg_error (GPG_ERR_CARD
);
3444 log_info (_("card is permanently locked!\n"));
3445 return gpg_error (GPG_ERR_BAD_PIN
);
3447 else if (value
[6] < 3)
3449 log_info (_("verification of Admin PIN is currently prohibited "
3450 "through this command\n"));
3451 return gpg_error (GPG_ERR_GENERAL
);
3454 app
->did_chv3
= 0; /* Force verification. */
3455 return verify_chv3 (app
, pincb
, pincb_arg
);
3458 return verify_chv2 (app
, pincb
, pincb_arg
);
3462 /* Show information about card capabilities. */
3464 show_caps (struct app_local_s
*s
)
3466 log_info ("Version-2 ......: %s\n", s
->extcap
.is_v2
? "yes":"no");
3467 log_info ("Get-Challenge ..: %s", s
->extcap
.get_challenge
? "yes":"no");
3468 if (s
->extcap
.get_challenge
)
3469 log_printf (" (%u bytes max)", s
->extcap
.max_get_challenge
);
3470 log_info ("Key-Import .....: %s\n", s
->extcap
.key_import
? "yes":"no");
3471 log_info ("Change-Force-PW1: %s\n", s
->extcap
.change_force_chv
? "yes":"no");
3472 log_info ("Private-DOs ....: %s\n", s
->extcap
.private_dos
? "yes":"no");
3473 log_info ("Algo-Attr-Change: %s\n", s
->extcap
.algo_attr_change
? "yes":"no");
3474 log_info ("SM-Support .....: %s", s
->extcap
.sm_supported
? "yes":"no");
3475 if (s
->extcap
.sm_supported
)
3476 log_printf (" (%s)", s
->extcap
.sm_aes128
? "AES-128":"3DES");
3477 log_info ("Max-Cert3-Len ..: %u\n", s
->extcap
.max_certlen_3
);
3478 log_info ("Max-Cmd-Data ...: %u\n", s
->extcap
.max_cmd_data
);
3479 log_info ("Max-Rsp-Data ...: %u\n", s
->extcap
.max_rsp_data
);
3480 log_info ("Cmd-Chaining ...: %s\n", s
->cardcap
.cmd_chaining
?"yes":"no");
3481 log_info ("Ext-Lc-Le ......: %s\n", s
->cardcap
.ext_lc_le
?"yes":"no");
3482 log_info ("Status Indicator: %02X\n", s
->status_indicator
);
3484 log_info ("GnuPG-No-Sync ..: %s\n", s
->flags
.no_sync
? "yes":"no");
3485 log_info ("GnuPG-Def-PW2 ..: %s\n", s
->flags
.def_chv2
? "yes":"no");
3489 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3492 parse_historical (struct app_local_s
*apploc
,
3493 const unsigned char * buffer
, size_t buflen
)
3495 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3498 log_error ("warning: historical bytes are too short\n");
3499 return; /* Too short. */
3503 log_error ("warning: bad category indicator in historical bytes\n");
3507 /* Skip category indicator. */
3511 /* Get the status indicator. */
3512 apploc
->status_indicator
= buffer
[buflen
-3];
3515 /* Parse the compact TLV. */
3518 unsigned int tag
= (*buffer
& 0xf0) >> 4;
3519 unsigned int len
= (*buffer
& 0x0f);
3522 log_error ("warning: bad Compact-TLV in historical bytes\n");
3523 return; /* Error. */
3527 if (tag
== 7 && len
== 3)
3529 /* Card capabilities. */
3530 apploc
->cardcap
.cmd_chaining
= !!(buffer
[2] & 0x80);
3531 apploc
->cardcap
.ext_lc_le
= !!(buffer
[2] & 0x40);
3539 /* Parse and optionally show the algorithm attributes for KEYNO.
3540 KEYNO must be in the range 0..2. */
3542 parse_algorithm_attribute (app_t app
, int keyno
)
3544 unsigned char *buffer
;
3547 const char const desc
[3][5] = {"sign", "encr", "auth"};
3549 assert (keyno
>=0 && keyno
<= 2);
3551 app
->app_local
->keyattr
[keyno
].n_bits
= 0;
3553 relptr
= get_one_do (app
, 0xC1+keyno
, &buffer
, &buflen
, NULL
);
3556 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3561 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3567 log_info ("Key-Attr-%s ..: ", desc
[keyno
]);
3568 if (*buffer
== 1 && (buflen
== 5 || buflen
== 6))
3570 app
->app_local
->keyattr
[keyno
].n_bits
= (buffer
[1]<<8 | buffer
[2]);
3571 app
->app_local
->keyattr
[keyno
].e_bits
= (buffer
[3]<<8 | buffer
[4]);
3572 app
->app_local
->keyattr
[keyno
].format
= 0;
3574 app
->app_local
->keyattr
[keyno
].format
= RSA_STD
;
3576 app
->app_local
->keyattr
[keyno
].format
= (buffer
[5] == 0? RSA_STD
:
3577 buffer
[5] == 1? RSA_STD_N
:
3578 buffer
[5] == 2? RSA_CRT
:
3579 buffer
[5] == 3? RSA_CRT_N
:
3584 ("RSA, n=%u, e=%u, fmt=%s\n",
3585 app
->app_local
->keyattr
[keyno
].n_bits
,
3586 app
->app_local
->keyattr
[keyno
].e_bits
,
3587 app
->app_local
->keyattr
[keyno
].format
== RSA_STD
? "std" :
3588 app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
?"std+n":
3589 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT
? "crt" :
3590 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
?"crt+n":"?");
3592 else if (opt
.verbose
)
3593 log_printhex ("", buffer
, buflen
);
3598 /* Select the OpenPGP application on the card in SLOT. This function
3599 must be used before any other OpenPGP application functions. */
3601 app_select_openpgp (app_t app
)
3603 static char const aid
[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3604 int slot
= app
->slot
;
3606 unsigned char *buffer
;
3610 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3611 special flag value. */
3612 rc
= iso7816_select_application (slot
, aid
, sizeof aid
, 0x0001);
3615 unsigned int manufacturer
;
3617 app
->apptype
= "OPENPGP";
3622 app
->app_local
= NULL
;
3624 /* The OpenPGP card returns the serial number as part of the
3625 AID; because we prefer to use OpenPGP serial numbers, we
3626 replace a possibly already set one from a EF.GDO with this
3627 one. Note, that for current OpenPGP cards, no EF.GDO exists
3628 and thus it won't matter at all. */
3629 rc
= iso7816_get_data (slot
, 0, 0x004F, &buffer
, &buflen
);
3635 log_printhex ("", buffer
, buflen
);
3638 app
->card_version
= buffer
[6] << 8;
3639 app
->card_version
|= buffer
[7];
3640 manufacturer
= (buffer
[8]<<8 | buffer
[9]);
3642 xfree (app
->serialno
);
3643 app
->serialno
= buffer
;
3644 app
->serialnolen
= buflen
;
3646 app
->app_local
= xtrycalloc (1, sizeof *app
->app_local
);
3647 if (!app
->app_local
)
3649 rc
= gpg_error (gpg_err_code_from_errno (errno
));
3653 if (app
->card_version
>= 0x0200)
3654 app
->app_local
->extcap
.is_v2
= 1;
3657 /* Read the historical bytes. */
3658 relptr
= get_one_do (app
, 0x5f52, &buffer
, &buflen
, NULL
);
3663 log_info ("Historical Bytes: ");
3664 log_printhex ("", buffer
, buflen
);
3666 parse_historical (app
->app_local
, buffer
, buflen
);
3670 /* Read the force-chv1 flag. */
3671 relptr
= get_one_do (app
, 0x00C4, &buffer
, &buflen
, NULL
);
3674 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3675 "CHV Status Bytes");
3678 app
->force_chv1
= (buflen
&& *buffer
== 0);
3681 /* Read the extended capabilities. */
3682 relptr
= get_one_do (app
, 0x00C0, &buffer
, &buflen
, NULL
);
3685 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3686 "Extended Capability Flags" );
3691 app
->app_local
->extcap
.sm_supported
= !!(*buffer
& 0x80);
3692 app
->app_local
->extcap
.get_challenge
= !!(*buffer
& 0x40);
3693 app
->app_local
->extcap
.key_import
= !!(*buffer
& 0x20);
3694 app
->app_local
->extcap
.change_force_chv
= !!(*buffer
& 0x10);
3695 app
->app_local
->extcap
.private_dos
= !!(*buffer
& 0x08);
3696 app
->app_local
->extcap
.algo_attr_change
= !!(*buffer
& 0x04);
3700 /* Available with v2 cards. */
3701 app
->app_local
->extcap
.sm_aes128
= (buffer
[1] == 1);
3702 app
->app_local
->extcap
.max_get_challenge
3703 = (buffer
[2] << 8 | buffer
[3]);
3704 app
->app_local
->extcap
.max_certlen_3
= (buffer
[4] << 8 | buffer
[5]);
3705 app
->app_local
->extcap
.max_cmd_data
= (buffer
[6] << 8 | buffer
[7]);
3706 app
->app_local
->extcap
.max_rsp_data
= (buffer
[8] << 8 | buffer
[9]);
3710 /* Some of the first cards accidently don't set the
3711 CHANGE_FORCE_CHV bit but allow it anyway. */
3712 if (app
->card_version
<= 0x0100 && manufacturer
== 1)
3713 app
->app_local
->extcap
.change_force_chv
= 1;
3715 parse_login_data (app
);
3718 show_caps (app
->app_local
);
3720 parse_algorithm_attribute (app
, 0);
3721 parse_algorithm_attribute (app
, 1);
3722 parse_algorithm_attribute (app
, 2);
3724 if (opt
.verbose
> 1)
3727 app
->fnc
.deinit
= do_deinit
;
3728 app
->fnc
.learn_status
= do_learn_status
;
3729 app
->fnc
.readcert
= do_readcert
;
3730 app
->fnc
.readkey
= do_readkey
;
3731 app
->fnc
.getattr
= do_getattr
;
3732 app
->fnc
.setattr
= do_setattr
;
3733 app
->fnc
.writecert
= do_writecert
;
3734 app
->fnc
.writekey
= do_writekey
;
3735 app
->fnc
.genkey
= do_genkey
;
3736 app
->fnc
.sign
= do_sign
;
3737 app
->fnc
.auth
= do_auth
;
3738 app
->fnc
.decipher
= do_decipher
;
3739 app
->fnc
.change_pin
= do_change_pin
;
3740 app
->fnc
.check_pin
= do_check_pin
;