1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
24 CHV means Card Holder Verification and is nothing else than a PIN
25 or password. That term seems to have been used originally with GSM
26 cards. Version v2 of the specs changes the term to the clearer
27 term PW for password. We use the terms here interchangeable
28 because we do not want to change existing strings i18n wise.
30 Version 2 of the specs also drops the separate PW2 which was
31 required in v1 due to ISO requirements. It is now possible to have
32 one physical PW but two reference to it so that they can be
33 individually be verified (e.g. to implement a forced verification
34 for one key). Thus you will noticed the use of PW2 with the verify
35 command but not with change_reference_data because the latter
36 operates directly on the physical PW.
38 The Reset Code (RC) as implemented by v2 cards uses the same error
39 counter as the PW2 of v1 cards. By default no RC is set and thus
40 that error counter is set to 0. After setting the RC the error
41 counter will be initialized to 3.
53 #if GNUPG_MAJOR_VERSION == 1
54 /* This is used with GnuPG version < 1.9. The code has been source
55 copied from the current GnuPG >= 1.9 and is maintained over
62 #else /* GNUPG_MAJOR_VERSION != 1 */
64 #endif /* GNUPG_MAJOR_VERSION != 1 */
68 #include "app-common.h"
72 /* A table describing the DOs of the card. */
76 int get_from
; /* Constructed DO with this DO or 0 for direct access. */
80 int get_immediate_in_v11
; /* Enable a hack to bypass the cache of
81 this data object if it is used in 1.1
82 and later versions of the card. This
83 does not work with composite DO and is
84 currently only useful for the CHV
88 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
89 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
90 { 0x5F52, 0, 0, 1, 0, 0, 0, "Historical Bytes" },
91 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
92 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
93 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
94 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
95 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
96 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
97 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
98 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
99 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
100 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
101 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
102 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
103 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
104 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
105 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
106 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
107 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
108 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
109 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
110 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
111 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
112 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
113 { 0x7F21, 1, 0, 1, 0, 0, 0, "Cardholder certificate"},
118 /* The format of RSA private keys. */
130 /* One cache item for DOs. */
132 struct cache_s
*next
;
135 unsigned char data
[1];
139 /* Object with application (i.e. OpenPGP card) specific data. */
141 /* A linked list with cached DOs. */
142 struct cache_s
*cache
;
144 /* Keep track of the public keys. */
147 int read_done
; /* True if we have at least tried to read them. */
148 unsigned char *key
; /* This is a malloced buffer with a canonical
149 encoded S-expression encoding a public
150 key. Might be NULL if key is not
152 size_t keylen
; /* The length of the above S-expression. This
153 is usullay only required for cross checks
154 because the length of an S-expression is
155 implicitly available. */
158 unsigned char status_indicator
; /* The card status indicator. */
160 /* Keep track of the ISO card capabilities. */
163 unsigned int cmd_chaining
:1; /* Command chaining is supported. */
164 unsigned int ext_lc_le
:1; /* Extended Lc and Le are supported. */
167 /* Keep track of extended card capabilities. */
170 unsigned int is_v2
:1; /* This is a v2.0 compatible card. */
171 unsigned int get_challenge
:1;
172 unsigned int key_import
:1;
173 unsigned int change_force_chv
:1;
174 unsigned int private_dos
:1;
175 unsigned int algo_attr_change
:1; /* Algorithm attributes changeable. */
176 unsigned int sm_supported
:1; /* Secure Messaging is supported. */
177 unsigned int sm_aes128
:1; /* Use AES-128 for SM. */
178 unsigned int max_certlen_3
:16;
179 unsigned int max_get_challenge
:16; /* Maximum size for get_challenge. */
180 unsigned int max_cmd_data
:16; /* Maximum data size for a command. */
181 unsigned int max_rsp_data
:16; /* Maximum size of a response. */
184 /* Flags used to control the application. */
187 unsigned int no_sync
:1; /* Do not sync CHV1 and CHV2 */
188 unsigned int def_chv2
:1; /* Use 123456 for CHV2. */
193 unsigned int n_bits
; /* Size of the modulus in bits. The rest
194 of this strucuire is only valid if
196 unsigned int e_bits
; /* Size of the public exponent in bits. */
197 rsa_key_format_t format
;
204 /***** Local prototypes *****/
205 static unsigned long convert_sig_counter_value (const unsigned char *value
,
207 static unsigned long get_sig_counter (app_t app
);
208 static gpg_error_t
do_auth (app_t app
, const char *keyidstr
,
209 gpg_error_t (*pincb
)(void*, const char *, char **),
211 const void *indata
, size_t indatalen
,
212 unsigned char **outdata
, size_t *outdatalen
);
220 do_deinit (app_t app
)
222 if (app
&& app
->app_local
)
224 struct cache_s
*c
, *c2
;
227 for (c
= app
->app_local
->cache
; c
; c
= c2
)
233 for (i
=0; i
< DIM (app
->app_local
->pk
); i
++)
235 xfree (app
->app_local
->pk
[i
].key
);
236 app
->app_local
->pk
[i
].read_done
= 0;
238 xfree (app
->app_local
);
239 app
->app_local
= NULL
;
244 /* Wrapper around iso7816_get_data which first tries to get the data
245 from the cache. With GET_IMMEDIATE passed as true, the cache is
248 get_cached_data (app_t app
, int tag
,
249 unsigned char **result
, size_t *resultlen
,
263 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
268 p
= xtrymalloc (c
->length
);
270 return gpg_error (gpg_err_code_from_errno (errno
));
271 memcpy (p
, c
->data
, c
->length
);
275 *resultlen
= c
->length
;
281 err
= iso7816_get_data (app
->slot
, tag
, &p
, &len
);
287 /* Check whether we should cache this object. */
291 for (i
=0; data_objects
[i
].tag
; i
++)
292 if (data_objects
[i
].tag
== tag
)
294 if (data_objects
[i
].dont_cache
)
299 /* Okay, cache it. */
300 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
301 assert (c
->tag
!= tag
);
303 c
= xtrymalloc (sizeof *c
+ len
);
306 memcpy (c
->data
, p
, len
);
309 c
->next
= app
->app_local
->cache
;
310 app
->app_local
->cache
= c
;
316 /* Remove DO at TAG from the cache. */
318 flush_cache_item (app_t app
, int tag
)
320 struct cache_s
*c
, *cprev
;
326 for (c
=app
->app_local
->cache
, cprev
=NULL
; c
; cprev
=c
, c
= c
->next
)
330 cprev
->next
= c
->next
;
332 app
->app_local
->cache
= c
->next
;
335 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
337 assert (c
->tag
!= tag
); /* Oops: duplicated entry. */
342 /* Try again if we have an outer tag. */
343 for (i
=0; data_objects
[i
].tag
; i
++)
344 if (data_objects
[i
].tag
== tag
&& data_objects
[i
].get_from
345 && data_objects
[i
].get_from
!= tag
)
346 flush_cache_item (app
, data_objects
[i
].get_from
);
349 /* Flush all entries from the cache which might be out of sync after
352 flush_cache_after_error (app_t app
)
356 for (i
=0; data_objects
[i
].tag
; i
++)
357 if (data_objects
[i
].flush_on_error
)
358 flush_cache_item (app
, data_objects
[i
].tag
);
362 /* Flush the entire cache. */
364 flush_cache (app_t app
)
366 if (app
&& app
->app_local
)
368 struct cache_s
*c
, *c2
;
370 for (c
= app
->app_local
->cache
; c
; c
= c2
)
375 app
->app_local
->cache
= NULL
;
380 /* Get the DO identified by TAG from the card in SLOT and return a
381 buffer with its content in RESULT and NBYTES. The return value is
382 NULL if not found or a pointer which must be used to release the
383 buffer holding value. */
385 get_one_do (app_t app
, int tag
, unsigned char **result
, size_t *nbytes
,
389 unsigned char *buffer
;
391 unsigned char *value
;
401 for (i
=0; data_objects
[i
].tag
&& data_objects
[i
].tag
!= tag
; i
++)
404 if (app
->card_version
> 0x0100 && data_objects
[i
].get_immediate_in_v11
)
406 rc
= iso7816_get_data (app
->slot
, tag
, &buffer
, &buflen
);
419 if (data_objects
[i
].tag
&& data_objects
[i
].get_from
)
421 rc
= get_cached_data (app
, data_objects
[i
].get_from
,
423 (data_objects
[i
].dont_cache
424 || data_objects
[i
].get_immediate_in_v11
));
427 const unsigned char *s
;
429 s
= find_tlv_unchecked (buffer
, buflen
, tag
, &valuelen
);
431 value
= NULL
; /* not found */
432 else if (valuelen
> buflen
- (s
- buffer
))
434 log_error ("warning: constructed DO too short\n");
436 xfree (buffer
); buffer
= NULL
;
439 value
= buffer
+ (s
- buffer
);
443 if (!value
) /* Not in a constructed DO, try simple. */
445 rc
= get_cached_data (app
, tag
, &buffer
, &buflen
,
446 (data_objects
[i
].dont_cache
447 || data_objects
[i
].get_immediate_in_v11
));
467 dump_all_do (int slot
)
470 unsigned char *buffer
;
473 for (i
=0; data_objects
[i
].tag
; i
++)
475 if (data_objects
[i
].get_from
)
478 rc
= iso7816_get_data (slot
, data_objects
[i
].tag
, &buffer
, &buflen
);
479 if (gpg_err_code (rc
) == GPG_ERR_NO_OBJ
)
482 log_info ("DO `%s' not available: %s\n",
483 data_objects
[i
].desc
, gpg_strerror (rc
));
486 if (data_objects
[i
].binary
)
488 log_info ("DO `%s': ", data_objects
[i
].desc
);
489 log_printhex ("", buffer
, buflen
);
492 log_info ("DO `%s': `%.*s'\n",
493 data_objects
[i
].desc
,
494 (int)buflen
, buffer
); /* FIXME: sanitize */
496 if (data_objects
[i
].constructed
)
498 for (j
=0; data_objects
[j
].tag
; j
++)
500 const unsigned char *value
;
503 if (j
==i
|| data_objects
[i
].tag
!= data_objects
[j
].get_from
)
505 value
= find_tlv_unchecked (buffer
, buflen
,
506 data_objects
[j
].tag
, &valuelen
);
509 else if (valuelen
> buflen
- (value
- buffer
))
510 log_error ("warning: constructed DO too short\n");
513 if (data_objects
[j
].binary
)
515 log_info ("DO `%s': ", data_objects
[j
].desc
);
517 log_info ("[%u]\n", (unsigned int)valuelen
);
519 log_printhex ("", value
, valuelen
);
522 log_info ("DO `%s': `%.*s'\n",
523 data_objects
[j
].desc
,
524 (int)valuelen
, value
); /* FIXME: sanitize */
529 xfree (buffer
); buffer
= NULL
;
534 /* Count the number of bits, assuming the A represents an unsigned big
535 integer of length LEN bytes. */
537 count_bits (const unsigned char *a
, size_t len
)
539 unsigned int n
= len
* 8;
542 for (; len
&& !*a
; len
--, a
++, n
-=8)
546 for (i
=7; i
&& !(*a
& (1<<i
)); i
--)
552 /* GnuPG makes special use of the login-data DO, this function parses
553 the login data to store the flags for later use. It may be called
554 at any time and should be called after changing the login-data DO.
556 Everything up to a LF is considered a mailbox or account name. If
557 the first LF is followed by DC4 (0x14) control sequence are
558 expected up to the next LF. Control sequences are separated by FS
559 (0x18) and consist of key=value pairs. There is one key defined:
563 Were FLAGS is a plain hexadecimal number representing flag values.
564 The lsb is here the rightmost bit. Defined flags bits are:
566 Bit 0 = CHV1 and CHV2 are not syncronized
567 Bit 1 = CHV2 has been been set to the default PIN of "123456"
568 (this implies that bit 0 is also set).
572 parse_login_data (app_t app
)
574 unsigned char *buffer
, *p
;
579 app
->app_local
->flags
.no_sync
= 0;
580 app
->app_local
->flags
.def_chv2
= 0;
583 relptr
= get_one_do (app
, 0x005E, &buffer
, &buflen
, NULL
);
586 for (; buflen
; buflen
--, buffer
++)
589 if (buflen
< 2 || buffer
[1] != '\x14')
590 return; /* No control sequences. */
597 if (buflen
> 1 && *buffer
== 'F' && buffer
[1] == '=')
599 /* Flags control sequence found. */
602 /* For now we are only interested in the last digit, so skip
603 any leading digits but bail out on invalid characters. */
604 for (p
=buffer
+2, len
= buflen
-2; len
&& hexdigitp (p
); p
++, len
--)
605 lastdig
= xtoi_1 (p
);
606 if (len
&& !(*p
== '\n' || *p
== '\x18'))
607 goto next
; /* Invalid characters in field. */
608 app
->app_local
->flags
.no_sync
= !!(lastdig
& 1);
609 app
->app_local
->flags
.def_chv2
= (lastdig
& 3) == 3;
612 for (; buflen
&& *buffer
!= '\x18'; buflen
--, buffer
++)
621 /* Note, that FPR must be at least 20 bytes. */
623 store_fpr (int slot
, int keynumber
, u32 timestamp
,
624 const unsigned char *m
, size_t mlen
,
625 const unsigned char *e
, size_t elen
,
626 unsigned char *fpr
, unsigned int card_version
)
628 unsigned int n
, nbits
;
629 unsigned char *buffer
, *p
;
632 for (; mlen
&& !*m
; mlen
--, m
++) /* strip leading zeroes */
634 for (; elen
&& !*e
; elen
--, e
++) /* strip leading zeroes */
637 n
= 6 + 2 + mlen
+ 2 + elen
;
638 p
= buffer
= xtrymalloc (3 + n
);
640 return gpg_error_from_syserror ();
642 *p
++ = 0x99; /* ctb */
643 *p
++ = n
>> 8; /* 2 byte length header */
645 *p
++ = 4; /* key packet version */
646 *p
++ = timestamp
>> 24;
647 *p
++ = timestamp
>> 16;
648 *p
++ = timestamp
>> 8;
651 nbits
= count_bits (m
, mlen
);
654 memcpy (p
, m
, mlen
); p
+= mlen
;
655 nbits
= count_bits (e
, elen
);
658 memcpy (p
, e
, elen
); p
+= elen
;
660 gcry_md_hash_buffer (GCRY_MD_SHA1
, fpr
, buffer
, n
+3);
664 rc
= iso7816_put_data (slot
, 0,
665 (card_version
> 0x0007? 0xC7 : 0xC6)
666 + keynumber
, fpr
, 20);
668 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc
));
670 if (!rc
&& card_version
> 0x0100)
672 unsigned char buf
[4];
674 buf
[0] = timestamp
>> 24;
675 buf
[1] = timestamp
>> 16;
676 buf
[2] = timestamp
>> 8;
679 rc
= iso7816_put_data (slot
, 0, 0xCE + keynumber
, buf
, 4);
681 log_error (_("failed to store the creation date: %s\n"),
690 send_fpr_if_not_null (ctrl_t ctrl
, const char *keyword
,
691 int number
, const unsigned char *fpr
)
697 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
700 return; /* All zero. */
701 bin2hex (fpr
, 20, buf
);
703 *numbuf
= 0; /* Don't print the key number */
705 sprintf (numbuf
, "%d", number
);
706 send_status_info (ctrl
, keyword
,
707 numbuf
, (size_t)strlen(numbuf
),
708 buf
, (size_t)strlen (buf
), NULL
, 0);
712 send_fprtime_if_not_null (ctrl_t ctrl
, const char *keyword
,
713 int number
, const unsigned char *stamp
)
715 char numbuf1
[50], numbuf2
[50];
718 value
= (stamp
[0] << 24) | (stamp
[1]<<16) | (stamp
[2]<<8) | stamp
[3];
721 sprintf (numbuf1
, "%d", number
);
722 sprintf (numbuf2
, "%lu", value
);
723 send_status_info (ctrl
, keyword
,
724 numbuf1
, (size_t)strlen(numbuf1
),
725 numbuf2
, (size_t)strlen(numbuf2
), NULL
, 0);
729 send_key_data (ctrl_t ctrl
, const char *name
,
730 const unsigned char *a
, size_t alen
)
734 buf
= bin2hex (a
, alen
, NULL
);
737 log_error ("memory allocation error in send_key_data\n");
741 send_status_info (ctrl
, "KEY-DATA",
742 name
, (size_t)strlen(name
),
743 buf
, (size_t)strlen (buf
),
748 /* Implement the GETATTR command. This is similar to the LEARN
749 command but returns just one value via the status interface. */
751 do_getattr (app_t app
, ctrl_t ctrl
, const char *name
)
758 { "DISP-NAME", 0x005B },
759 { "LOGIN-DATA", 0x005E },
760 { "DISP-LANG", 0x5F2D },
761 { "DISP-SEX", 0x5F35 },
762 { "PUBKEY-URL", 0x5F50 },
763 { "KEY-FPR", 0x00C5, 3 },
764 { "KEY-TIME", 0x00CD, 4 },
765 { "CA-FPR", 0x00C6, 3 },
766 { "CHV-STATUS", 0x00C4, 1 },
767 { "SIG-COUNTER", 0x0093, 2 },
768 { "SERIALNO", 0x004F, -1 },
770 { "EXTCAP", 0x0000, -2 },
771 { "PRIVATE-DO-1", 0x0101 },
772 { "PRIVATE-DO-2", 0x0102 },
773 { "PRIVATE-DO-3", 0x0103 },
774 { "PRIVATE-DO-4", 0x0104 },
775 { "$AUTHKEYID", 0x0000, -3 },
776 { "$DISPSERIALNO",0x0000, -4 },
781 unsigned char *value
;
784 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
786 if (!table
[idx
].name
)
787 return gpg_error (GPG_ERR_INV_NAME
);
789 if (table
[idx
].special
== -1)
791 /* The serial number is very special. We could have used the
792 AID DO to retrieve it, but we have it already in the app
793 context and the stamp argument is required anyway which we
794 can't by other means. The AID DO is available anyway but not
800 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
802 sprintf (tmp
, "%lu", (unsigned long)stamp
);
803 send_status_info (ctrl
, "SERIALNO",
804 serial
, strlen (serial
),
811 if (table
[idx
].special
== -2)
815 sprintf (tmp
, "gc=%d ki=%d fc=%d pd=%d mcl3=%u",
816 app
->app_local
->extcap
.get_challenge
,
817 app
->app_local
->extcap
.key_import
,
818 app
->app_local
->extcap
.change_force_chv
,
819 app
->app_local
->extcap
.private_dos
,
820 app
->app_local
->extcap
.max_certlen_3
);
821 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
824 if (table
[idx
].special
== -3)
826 char const tmp
[] = "OPENPGP.3";
827 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
830 if (table
[idx
].special
== -4)
835 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
837 if (strlen (serial
) > 16+12)
839 send_status_info (ctrl
, table
[idx
].name
, serial
+16, 12, NULL
, 0);
845 return gpg_error (GPG_ERR_INV_NAME
);
848 relptr
= get_one_do (app
, table
[idx
].tag
, &value
, &valuelen
, &rc
);
851 if (table
[idx
].special
== 1)
855 for (i
=0,*numbuf
=0; i
< valuelen
&& i
< 7; i
++)
856 sprintf (numbuf
+strlen (numbuf
), " %d", value
[i
]);
857 send_status_info (ctrl
, table
[idx
].name
,
858 numbuf
, strlen (numbuf
), NULL
, 0);
860 else if (table
[idx
].special
== 2)
864 sprintf (numbuf
, "%lu", convert_sig_counter_value (value
, valuelen
));
865 send_status_info (ctrl
, table
[idx
].name
,
866 numbuf
, strlen (numbuf
), NULL
, 0);
868 else if (table
[idx
].special
== 3)
871 for (i
=0; i
< 3; i
++)
872 send_fpr_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*20);
874 else if (table
[idx
].special
== 4)
877 for (i
=0; i
< 3; i
++)
878 send_fprtime_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*4);
881 send_status_info (ctrl
, table
[idx
].name
, value
, valuelen
, NULL
, 0);
888 /* Retrieve the fingerprint from the card inserted in SLOT and write
889 the according hex representation to FPR. Caller must have provide
890 a buffer at FPR of least 41 bytes. Returns 0 on success or an
892 #if GNUPG_MAJOR_VERSION > 1
894 retrieve_fpr_from_card (app_t app
, int keyno
, char *fpr
)
898 unsigned char *value
;
901 assert (keyno
>=0 && keyno
<= 2);
903 relptr
= get_one_do (app
, 0x00C5, &value
, &valuelen
, NULL
);
904 if (relptr
&& valuelen
>= 60)
905 bin2hex (value
+keyno
*20, 20, fpr
);
907 err
= gpg_error (GPG_ERR_NOT_FOUND
);
911 #endif /*GNUPG_MAJOR_VERSION > 1*/
914 /* Retrieve the public key material for the RSA key, whose fingerprint
915 is FPR, from gpg output, which can be read through the stream FP.
916 The RSA modulus will be stored at the address of M and MLEN, the
917 public exponent at E and ELEN. Returns zero on success, an error
918 code on failure. Caller must release the allocated buffers at M
919 and E if the function returns success. */
920 #if GNUPG_MAJOR_VERSION > 1
922 retrieve_key_material (FILE *fp
, const char *hexkeyid
,
923 const unsigned char **m
, size_t *mlen
,
924 const unsigned char **e
, size_t *elen
)
926 gcry_error_t err
= 0;
927 char *line
= NULL
; /* read_line() buffer. */
928 size_t line_size
= 0; /* Helper for for read_line. */
929 int found_key
= 0; /* Helper to find a matching key. */
930 unsigned char *m_new
= NULL
;
931 unsigned char *e_new
= NULL
;
935 /* Loop over all records until we have found the subkey
936 corresponding to the fingerprint. Inm general the first record
937 should be the pub record, but we don't rely on that. Given that
938 we only need to look at one key, it is sufficient to compare the
939 keyid so that we don't need to look at "fpr" records. */
950 i
= read_line (fp
, &line
, &line_size
, &max_length
);
955 err
= gpg_error_from_syserror ();
956 goto leave
; /* Error. */
960 err
= gpg_error (GPG_ERR_TRUNCATED
);
961 goto leave
; /* Line truncated - we better stop processing. */
964 /* Parse the line into fields. */
965 for (nfields
=0, p
=line
; p
&& nfields
< DIM (fields
); nfields
++)
973 continue; /* No fields at all - skip line. */
977 if ( (!strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
978 && nfields
> 4 && !strcmp (fields
[4], hexkeyid
))
983 if ( !strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
984 break; /* Next key - stop. */
986 if ( strcmp (fields
[0], "pkd") )
987 continue; /* Not a key data record. */
988 i
= 0; /* Avoid erroneous compiler warning. */
989 if ( nfields
< 4 || (i
= atoi (fields
[1])) < 0 || i
> 1
990 || (!i
&& m_new
) || (i
&& e_new
))
992 err
= gpg_error (GPG_ERR_GENERAL
);
993 goto leave
; /* Error: Invalid key data record or not an RSA key. */
996 err
= gcry_mpi_scan (&mpi
, GCRYMPI_FMT_HEX
, fields
[3], 0, NULL
);
1000 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &m_new
, &m_new_n
, mpi
);
1002 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &e_new
, &e_new_n
, mpi
);
1003 gcry_mpi_release (mpi
);
1018 err
= gpg_error (GPG_ERR_GENERAL
);
1026 #endif /*GNUPG_MAJOR_VERSION > 1*/
1029 /* Get the public key for KEYNO and store it as an S-expresion with
1030 the APP handle. On error that field gets cleared. If we already
1031 know about the public key we will just return. Note that this does
1032 not mean a key is available; this is soley indicated by the
1033 presence of the app->app_local->pk[KEYNO-1].key field.
1035 Note that GnuPG 1.x does not need this and it would be too time
1036 consuming to send it just for the fun of it. However, given that we
1037 use the same code in gpg 1.4, we can't use the gcry S-expresion
1038 here but need to open encode it. */
1039 #if GNUPG_MAJOR_VERSION > 1
1041 get_public_key (app_t app
, int keyno
)
1043 gpg_error_t err
= 0;
1044 unsigned char *buffer
;
1045 const unsigned char *keydata
, *m
, *e
;
1046 size_t buflen
, keydatalen
, mlen
, elen
;
1047 unsigned char *mbuf
= NULL
;
1048 unsigned char *ebuf
= NULL
;
1049 char *keybuf
= NULL
;
1052 if (keyno
< 1 || keyno
> 3)
1053 return gpg_error (GPG_ERR_INV_ID
);
1056 /* Already cached? */
1057 if (app
->app_local
->pk
[keyno
].read_done
)
1060 xfree (app
->app_local
->pk
[keyno
].key
);
1061 app
->app_local
->pk
[keyno
].key
= NULL
;
1062 app
->app_local
->pk
[keyno
].keylen
= 0;
1064 m
= e
= NULL
; /* (avoid cc warning) */
1066 if (app
->card_version
> 0x0100)
1068 /* We may simply read the public key out of these cards. */
1069 err
= iso7816_read_public_key
1070 (app
->slot
, (const unsigned char*)(keyno
== 0? "\xB6" :
1071 keyno
== 1? "\xB8" : "\xA4"),
1076 log_error (_("reading public key failed: %s\n"), gpg_strerror (err
));
1080 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1083 err
= gpg_error (GPG_ERR_CARD
);
1084 log_error (_("response does not contain the public key data\n"));
1088 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1091 err
= gpg_error (GPG_ERR_CARD
);
1092 log_error (_("response does not contain the RSA modulus\n"));
1097 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1100 err
= gpg_error (GPG_ERR_CARD
);
1101 log_error (_("response does not contain the RSA public exponent\n"));
1105 /* Prepend numbers with a 0 if needed. */
1106 if (mlen
&& (*m
& 0x80))
1108 mbuf
= xtrymalloc ( mlen
+ 1);
1111 err
= gpg_error_from_syserror ();
1115 memcpy (mbuf
+1, m
, mlen
);
1119 if (elen
&& (*e
& 0x80))
1121 ebuf
= xtrymalloc ( elen
+ 1);
1124 err
= gpg_error_from_syserror ();
1128 memcpy (ebuf
+1, e
, elen
);
1136 /* Due to a design problem in v1.0 cards we can't get the public
1137 key out of these cards without doing a verify on CHV3.
1138 Clearly that is not an option and thus we try to locate the
1139 key using an external helper.
1141 The helper we use here is gpg itself, which should know about
1142 the key in any case. */
1146 char *command
= NULL
;
1150 buffer
= NULL
; /* We don't need buffer. */
1152 err
= retrieve_fpr_from_card (app
, keyno
, fpr
);
1155 log_error ("error while retrieving fpr from card: %s\n",
1156 gpg_strerror (err
));
1159 hexkeyid
= fpr
+ 24;
1161 ret
= estream_asprintf (&command
,
1162 "gpg --list-keys --with-colons --with-key-data '%s'",
1166 err
= gpg_error_from_syserror ();
1170 fp
= popen (command
, "r");
1174 err
= gpg_error_from_syserror ();
1175 log_error ("running gpg failed: %s\n", gpg_strerror (err
));
1179 err
= retrieve_key_material (fp
, hexkeyid
, &m
, &mlen
, &e
, &elen
);
1183 log_error ("error while retrieving key material through pipe: %s\n",
1184 gpg_strerror (err
));
1189 /* Allocate a buffer to construct the S-expression. */
1190 /* FIXME: We should provide a generalized S-expression creation
1192 keybuf
= xtrymalloc (50 + 2*35 + mlen
+ elen
+ 1);
1195 err
= gpg_error_from_syserror ();
1199 sprintf (keybuf
, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen
);
1200 keybuf_p
= keybuf
+ strlen (keybuf
);
1201 memcpy (keybuf_p
, m
, mlen
);
1203 sprintf (keybuf_p
, ")(1:e%u:", (unsigned int)elen
);
1204 keybuf_p
+= strlen (keybuf_p
);
1205 memcpy (keybuf_p
, e
, elen
);
1207 strcpy (keybuf_p
, ")))");
1208 keybuf_p
+= strlen (keybuf_p
);
1210 app
->app_local
->pk
[keyno
].key
= (unsigned char*)keybuf
;
1211 app
->app_local
->pk
[keyno
].keylen
= (keybuf_p
- keybuf
);
1214 /* Set a flag to indicate that we tried to read the key. */
1215 app
->app_local
->pk
[keyno
].read_done
= 1;
1222 #endif /* GNUPG_MAJOR_VERSION > 1 */
1226 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1227 This is used by the LEARN command. */
1229 send_keypair_info (app_t app
, ctrl_t ctrl
, int keyno
)
1231 gpg_error_t err
= 0;
1232 /* Note that GnuPG 1.x does not need this and it would be too time
1233 consuming to send it just for the fun of it. */
1234 #if GNUPG_MAJOR_VERSION > 1
1235 unsigned char grip
[20];
1239 err
= get_public_key (app
, keyno
);
1243 assert (keyno
>= 1 && keyno
<= 3);
1244 if (!app
->app_local
->pk
[keyno
-1].key
)
1245 goto leave
; /* No such key - ignore. */
1247 err
= keygrip_from_canon_sexp (app
->app_local
->pk
[keyno
-1].key
,
1248 app
->app_local
->pk
[keyno
-1].keylen
,
1253 bin2hex (grip
, 20, gripstr
);
1255 sprintf (idbuf
, "OPENPGP.%d", keyno
);
1256 send_status_info (ctrl
, "KEYPAIRINFO",
1258 idbuf
, strlen (idbuf
),
1262 #endif /* GNUPG_MAJOR_VERSION > 1 */
1268 /* Handle the LEARN command for OpenPGP. */
1270 do_learn_status (app_t app
, ctrl_t ctrl
)
1272 do_getattr (app
, ctrl
, "EXTCAP");
1273 do_getattr (app
, ctrl
, "DISP-NAME");
1274 do_getattr (app
, ctrl
, "DISP-LANG");
1275 do_getattr (app
, ctrl
, "DISP-SEX");
1276 do_getattr (app
, ctrl
, "PUBKEY-URL");
1277 do_getattr (app
, ctrl
, "LOGIN-DATA");
1278 do_getattr (app
, ctrl
, "KEY-FPR");
1279 if (app
->card_version
> 0x0100)
1280 do_getattr (app
, ctrl
, "KEY-TIME");
1281 do_getattr (app
, ctrl
, "CA-FPR");
1282 do_getattr (app
, ctrl
, "CHV-STATUS");
1283 do_getattr (app
, ctrl
, "SIG-COUNTER");
1284 if (app
->app_local
->extcap
.private_dos
)
1286 do_getattr (app
, ctrl
, "PRIVATE-DO-1");
1287 do_getattr (app
, ctrl
, "PRIVATE-DO-2");
1289 do_getattr (app
, ctrl
, "PRIVATE-DO-3");
1291 do_getattr (app
, ctrl
, "PRIVATE-DO-4");
1293 send_keypair_info (app
, ctrl
, 1);
1294 send_keypair_info (app
, ctrl
, 2);
1295 send_keypair_info (app
, ctrl
, 3);
1296 /* Note: We do not send the Cardholder Certificate, because that is
1297 relativly long and for OpenPGP applications not really needed. */
1302 /* Handle the READKEY command for OpenPGP. On success a canonical
1303 encoded S-expression with the public key will get stored at PK and
1304 its length (for assertions) at PKLEN; the caller must release that
1305 buffer. On error PK and PKLEN are not changed and an error code is
1308 do_readkey (app_t app
, const char *keyid
, unsigned char **pk
, size_t *pklen
)
1310 #if GNUPG_MAJOR_VERSION > 1
1315 if (!strcmp (keyid
, "OPENPGP.1"))
1317 else if (!strcmp (keyid
, "OPENPGP.2"))
1319 else if (!strcmp (keyid
, "OPENPGP.3"))
1322 return gpg_error (GPG_ERR_INV_ID
);
1324 err
= get_public_key (app
, keyno
);
1328 buf
= app
->app_local
->pk
[keyno
-1].key
;
1330 return gpg_error (GPG_ERR_NO_PUBKEY
);
1331 *pklen
= app
->app_local
->pk
[keyno
-1].keylen
;;
1332 *pk
= xtrymalloc (*pklen
);
1335 err
= gpg_error_from_syserror ();
1339 memcpy (*pk
, buf
, *pklen
);
1342 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1346 /* Read the standard certificate of an OpenPGP v2 card. It is
1347 returned in a freshly allocated buffer with that address stored at
1348 CERT and the length of the certificate stored at CERTLEN. CERTID
1349 needs to be set to "OPENPGP.3". */
1351 do_readcert (app_t app
, const char *certid
,
1352 unsigned char **cert
, size_t *certlen
)
1354 #if GNUPG_MAJOR_VERSION > 1
1356 unsigned char *buffer
;
1362 if (strcmp (certid
, "OPENPGP.3"))
1363 return gpg_error (GPG_ERR_INV_ID
);
1364 if (!app
->app_local
->extcap
.is_v2
)
1365 return gpg_error (GPG_ERR_NOT_FOUND
);
1367 relptr
= get_one_do (app
, 0x7F21, &buffer
, &buflen
, NULL
);
1369 return gpg_error (GPG_ERR_NOT_FOUND
);
1371 *cert
= xtrymalloc (buflen
);
1373 err
= gpg_error_from_syserror ();
1376 memcpy (*cert
, buffer
, buflen
);
1383 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1388 /* Verify a CHV either using using the pinentry or if possibile by
1389 using a keypad. PINCB and PINCB_ARG describe the usual callback
1390 for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1391 used with CHV1. PINVALUE is the address of a pointer which will
1392 receive a newly allocated block with the actual PIN (this is useful
1393 in case that PIN shall be used for another verifiy operation). The
1394 caller needs to free this value. If the function returns with
1395 success and NULL is stored at PINVALUE, the caller should take this
1396 as an indication that the keypad has been used.
1399 verify_a_chv (app_t app
,
1400 gpg_error_t (*pincb
)(void*, const char *, char **),
1402 int chvno
, unsigned long sigcount
, char **pinvalue
)
1406 iso7816_pininfo_t pininfo
;
1409 assert (chvno
== 1 || chvno
== 2);
1413 if (chvno
== 2 && app
->app_local
->flags
.def_chv2
)
1415 /* Special case for def_chv2 mechanism. */
1417 log_info (_("using default PIN as %s\n"), "CHV2");
1418 rc
= iso7816_verify (app
->slot
, 0x82, "123456", 6);
1421 /* Verification of CHV2 with the default PIN failed,
1422 although the card pretends to have the default PIN set as
1423 CHV2. We better disable the def_chv2 flag now. */
1424 log_info (_("failed to use default PIN as %s: %s"
1425 " - disabling further default use\n"),
1426 "CHV2", gpg_strerror (rc
));
1427 app
->app_local
->flags
.def_chv2
= 0;
1432 memset (&pininfo
, 0, sizeof pininfo
);
1434 pininfo
.minlen
= minlen
;
1436 if (!opt
.disable_keypad
1437 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1439 /* The reader supports the verify command through the keypad. */
1443 #define PROMPTSTRING _("||Please enter your PIN at the reader's keypad%%0A" \
1445 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1447 prompt
= xmalloc (promptsize
);
1449 return gpg_error_from_syserror ();
1450 snprintf (prompt
, promptsize
-1, PROMPTSTRING
, sigcount
);
1451 rc
= pincb (pincb_arg
, prompt
, NULL
);
1456 rc
= pincb (pincb_arg
,
1457 _("||Please enter your PIN at the reader's keypad"),
1461 log_info (_("PIN callback returned error: %s\n"),
1465 rc
= iso7816_verify_kp (app
->slot
, 0x80+chvno
, "", 0, &pininfo
);
1466 /* Dismiss the prompt. */
1467 pincb (pincb_arg
, NULL
, NULL
);
1469 assert (!*pinvalue
);
1473 /* The reader has no keypad or we don't want to use it. */
1477 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1478 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1480 prompt
= xtrymalloc (promptsize
);
1482 return gpg_error_from_syserror ();
1483 snprintf (prompt
, promptsize
-1, PROMPTSTRING
, sigcount
);
1484 rc
= pincb (pincb_arg
, prompt
, pinvalue
);
1489 rc
= pincb (pincb_arg
, _("||Please enter the PIN"), pinvalue
);
1493 log_info (_("PIN callback returned error: %s\n"),
1498 if (strlen (*pinvalue
) < minlen
)
1500 log_error (_("PIN for CHV%d is too short;"
1501 " minimum length is %d\n"), chvno
, minlen
);
1504 return gpg_error (GPG_ERR_BAD_PIN
);
1507 rc
= iso7816_verify (app
->slot
, 0x80+chvno
,
1508 *pinvalue
, strlen (*pinvalue
));
1513 log_error (_("verify CHV%d failed: %s\n"), chvno
, gpg_strerror (rc
));
1516 flush_cache_after_error (app
);
1523 /* Verify CHV2 if required. Depending on the configuration of the
1524 card CHV1 will also be verified. */
1526 verify_chv2 (app_t app
,
1527 gpg_error_t (*pincb
)(void*, const char *, char **),
1534 return 0; /* We already verified CHV2. */
1536 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 2, 0, &pinvalue
);
1542 if (!app
->did_chv1
&& !app
->force_chv1
&& pinvalue
)
1544 /* For convenience we verify CHV1 here too. We do this only if
1545 the card is not configured to require a verification before
1546 each CHV1 controlled operation (force_chv1) and if we are not
1547 using the keypad (PINVALUE == NULL). */
1548 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
1549 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
1550 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
1553 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
1554 flush_cache_after_error (app
);
1565 /* Verify CHV3 if required. */
1567 verify_chv3 (app_t app
,
1568 gpg_error_t (*pincb
)(void*, const char *, char **),
1573 #if GNUPG_MAJOR_VERSION != 1
1574 if (!opt
.allow_admin
)
1576 log_info (_("access to admin commands is not configured\n"));
1577 return gpg_error (GPG_ERR_EACCES
);
1584 unsigned char *value
;
1586 iso7816_pininfo_t pininfo
;
1590 memset (&pininfo
, 0, sizeof pininfo
);
1592 pininfo
.minlen
= minlen
;
1594 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1595 if (!relptr
|| valuelen
< 7)
1597 log_error (_("error retrieving CHV status from card\n"));
1599 return gpg_error (GPG_ERR_CARD
);
1603 log_info (_("card is permanently locked!\n"));
1605 return gpg_error (GPG_ERR_BAD_PIN
);
1607 remaining
= value
[6];
1610 log_info(_("%d Admin PIN attempts remaining before card"
1611 " is permanently locked\n"), remaining
);
1613 if (!opt
.disable_keypad
1614 && !iso7816_check_keypad (app
->slot
, ISO7816_VERIFY
, &pininfo
) )
1616 /* The reader supports the verify command through the keypad. */
1620 #define PROMPTSTRING _("|A|Please enter the Admin PIN" \
1621 " at the reader's keypad%%0A" \
1622 "[remaining attempts: %d]")
1623 size_t promptsize
= strlen (PROMPTSTRING
) + 50;
1626 prompt
= xmalloc (promptsize
);
1628 return gpg_error_from_syserror ();
1629 snprintf (prompt
, promptsize
-1, PROMPTSTRING
, remaining
);
1630 rc
= pincb (pincb_arg
, prompt
, NULL
);
1635 rc
= pincb (pincb_arg
, _("|A|Please enter the Admin PIN"
1636 " at the reader's keypad"), NULL
);
1640 log_info (_("PIN callback returned error: %s\n"),
1644 rc
= iso7816_verify_kp (app
->slot
, 0x83, "", 0, &pininfo
);
1645 /* Dismiss the prompt. */
1646 pincb (pincb_arg
, NULL
, NULL
);
1652 /* TRANSLATORS: Do not translate the "|A|" prefix but keep
1653 it at the start of the string. We need this elsewhere to
1654 get some infos on the string. */
1655 rc
= pincb (pincb_arg
, _("|A|Admin PIN"), &pinvalue
);
1658 log_info (_("PIN callback returned error: %s\n"),
1663 if (strlen (pinvalue
) < minlen
)
1665 log_error (_("PIN for CHV%d is too short;"
1666 " minimum length is %d\n"), 3, minlen
);
1668 return gpg_error (GPG_ERR_BAD_PIN
);
1671 rc
= iso7816_verify (app
->slot
, 0x83, pinvalue
, strlen (pinvalue
));
1677 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc
));
1678 flush_cache_after_error (app
);
1687 /* Handle the SETATTR operation. All arguments are already basically
1690 do_setattr (app_t app
, const char *name
,
1691 gpg_error_t (*pincb
)(void*, const char *, char **),
1693 const unsigned char *value
, size_t valuelen
)
1702 unsigned int need_v2
:1;
1704 { "DISP-NAME", 0x005B, 3 },
1705 { "LOGIN-DATA", 0x005E, 3, 2 },
1706 { "DISP-LANG", 0x5F2D, 3 },
1707 { "DISP-SEX", 0x5F35, 3 },
1708 { "PUBKEY-URL", 0x5F50, 3 },
1709 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1710 { "CA-FPR-1", 0x00CA, 3 },
1711 { "CA-FPR-2", 0x00CB, 3 },
1712 { "CA-FPR-3", 0x00CC, 3 },
1713 { "PRIVATE-DO-1", 0x0101, 2 },
1714 { "PRIVATE-DO-2", 0x0102, 3 },
1715 { "PRIVATE-DO-3", 0x0103, 2 },
1716 { "PRIVATE-DO-4", 0x0104, 3 },
1717 { "CERT-3", 0x7F21, 3, 0, 1 },
1718 { "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1719 { "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1724 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
1726 if (!table
[idx
].name
)
1727 return gpg_error (GPG_ERR_INV_NAME
);
1728 if (table
[idx
].need_v2
&& !app
->app_local
->extcap
.is_v2
)
1729 return gpg_error (GPG_ERR_NOT_SUPPORTED
); /* Not yet supported. */
1731 switch (table
[idx
].need_chv
)
1734 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1737 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1745 /* Flush the cache before writing it, so that the next get operation
1746 will reread the data from the card and thus get synced in case of
1747 errors (e.g. data truncated by the card). */
1748 flush_cache_item (app
, table
[idx
].tag
);
1749 /* For command chaining we use a value of 254 for this card. */
1750 if (app
->app_local
->cardcap
.cmd_chaining
&& valuelen
> 254)
1754 rc
= iso7816_put_data (app
->slot
, exmode
, table
[idx
].tag
, value
, valuelen
);
1756 log_error ("failed to set `%s': %s\n", table
[idx
].name
, gpg_strerror (rc
));
1758 if (table
[idx
].special
== 1)
1759 app
->force_chv1
= (valuelen
&& *value
== 0);
1760 else if (table
[idx
].special
== 2)
1761 parse_login_data (app
);
1767 /* Handle the WRITECERT command for OpenPGP. This rites the standard
1768 certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1769 PINCB and PINCB_ARG are the usual arguments for the pinentry
1772 do_writecert (app_t app
, ctrl_t ctrl
,
1773 const char *certidstr
,
1774 gpg_error_t (*pincb
)(void*, const char *, char **),
1776 const unsigned char *certdata
, size_t certdatalen
)
1779 #if GNUPG_MAJOR_VERSION > 1
1780 if (strcmp (certidstr
, "OPENPGP.3"))
1781 return gpg_error (GPG_ERR_INV_ID
);
1782 if (!certdata
|| !certdatalen
)
1783 return gpg_error (GPG_ERR_INV_ARG
);
1784 if (!app
->app_local
->extcap
.is_v2
)
1785 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
1786 if (certdatalen
> app
->app_local
->extcap
.max_certlen_3
)
1787 return gpg_error (GPG_ERR_TOO_LARGE
);
1788 return do_setattr (app
, "CERT-3", pincb
, pincb_arg
, certdata
, certdatalen
);
1790 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1796 /* Handle the PASSWD command. */
1798 do_change_pin (app_t app
, ctrl_t ctrl
, const char *chvnostr
,
1800 gpg_error_t (*pincb
)(void*, const char *, char **),
1804 int chvno
= atoi (chvnostr
);
1805 char *resetcode
= NULL
;
1807 int reset_mode
= !!(flags
& APP_CHANGE_FLAG_RESET
);
1808 int set_resetcode
= 0;
1812 if (reset_mode
&& chvno
== 3)
1814 rc
= gpg_error (GPG_ERR_INV_ID
);
1817 else if (reset_mode
|| chvno
== 3)
1819 /* We always require that the PIN is entered. */
1821 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1825 if (chvno
== 2 && app
->app_local
->extcap
.is_v2
)
1828 else if (chvno
== 2 && app
->app_local
->extcap
.is_v2
)
1830 /* There is no PW2 for v2 cards. We use this condition to allow
1831 a PW reset using the Reset Code. */
1833 unsigned char *value
;
1837 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1838 if (!relptr
|| valuelen
< 7)
1840 log_error (_("error retrieving CHV status from card\n"));
1842 rc
= gpg_error (GPG_ERR_CARD
);
1845 remaining
= value
[5];
1849 log_error (_("Reset Code not or not anymore available\n"));
1850 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1854 rc
= pincb (pincb_arg
, _("||Please enter the Reset Code for the card"),
1858 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1861 if (strlen (resetcode
) < 8)
1863 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1864 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1868 else if (chvno
== 1 || chvno
== 2)
1870 /* CHV1 and CVH2 should always have the same value, thus we
1872 int save_force
= app
->force_chv1
;
1874 app
->force_chv1
= 0;
1877 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1878 app
->force_chv1
= save_force
;
1884 rc
= gpg_error (GPG_ERR_INV_ID
);
1891 app
->did_chv1
= app
->did_chv2
= 0;
1893 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1894 keep it at the start of the string. We need this elsewhere
1895 to get some infos on the string. */
1896 rc
= pincb (pincb_arg
,
1897 set_resetcode
? _("|RN|New Reset Code") :
1898 chvno
== 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1902 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc
));
1910 buffer
= xtrymalloc (strlen (resetcode
) + strlen (pinvalue
) + 1);
1912 rc
= gpg_error_from_syserror ();
1915 strcpy (stpcpy (buffer
, resetcode
), pinvalue
);
1916 rc
= iso7816_reset_retry_counter_with_rc (app
->slot
, 0x81,
1917 buffer
, strlen (buffer
));
1918 wipememory (buffer
, strlen (buffer
));
1922 else if (set_resetcode
)
1924 if (strlen (pinvalue
) < 8)
1926 log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
1927 rc
= gpg_error (GPG_ERR_BAD_PIN
);
1930 rc
= iso7816_put_data (app
->slot
, 0, 0xD3,
1931 pinvalue
, strlen (pinvalue
));
1933 else if (reset_mode
)
1935 rc
= iso7816_reset_retry_counter (app
->slot
, 0x81,
1936 pinvalue
, strlen (pinvalue
));
1937 if (!rc
&& !app
->app_local
->extcap
.is_v2
)
1938 rc
= iso7816_reset_retry_counter (app
->slot
, 0x82,
1939 pinvalue
, strlen (pinvalue
));
1943 if (chvno
== 1 || chvno
== 2)
1945 rc
= iso7816_change_reference_data (app
->slot
, 0x81, NULL
, 0,
1946 pinvalue
, strlen (pinvalue
));
1947 if (!rc
&& !app
->app_local
->extcap
.is_v2
)
1948 rc
= iso7816_change_reference_data (app
->slot
, 0x82, NULL
, 0,
1949 pinvalue
, strlen (pinvalue
));
1952 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
, NULL
, 0,
1953 pinvalue
, strlen (pinvalue
));
1957 wipememory (pinvalue
, strlen (pinvalue
));
1961 flush_cache_after_error (app
);
1966 wipememory (resetcode
, strlen (resetcode
));
1973 /* Check whether a key already exists. KEYIDX is the index of the key
1974 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1975 error returned if the key already exists. */
1977 does_key_exist (app_t app
, int keyidx
, int force
)
1979 const unsigned char *fpr
;
1980 unsigned char *buffer
;
1984 assert (keyidx
>=0 && keyidx
<= 2);
1986 if (iso7816_get_data (app
->slot
, 0x006E, &buffer
, &buflen
))
1988 log_error (_("error reading application data\n"));
1989 return gpg_error (GPG_ERR_GENERAL
);
1991 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
1994 log_error (_("error reading fingerprint DO\n"));
1996 return gpg_error (GPG_ERR_GENERAL
);
1999 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
2002 if (i
!=20 && !force
)
2004 log_error (_("key already exists\n"));
2005 return gpg_error (GPG_ERR_EEXIST
);
2008 log_info (_("existing key will be replaced\n"));
2010 log_info (_("generating new key\n"));
2015 /* Create a TLV tag and value and store it at BUFFER. Return the length
2016 of tag and length. A LENGTH greater than 65535 is truncated. */
2018 add_tlv (unsigned char *buffer
, unsigned int tag
, size_t length
)
2020 unsigned char *p
= buffer
;
2022 assert (tag
<= 0xffff);
2028 else if (length
< 256)
2035 if (length
> 0xffff)
2046 /* Build the private key template as specified in the OpenPGP specs
2047 v2.0 section 4.3.3.7. */
2049 build_privkey_template (app_t app
, int keyno
,
2050 const unsigned char *rsa_n
, size_t rsa_n_len
,
2051 const unsigned char *rsa_e
, size_t rsa_e_len
,
2052 const unsigned char *rsa_p
, size_t rsa_p_len
,
2053 const unsigned char *rsa_q
, size_t rsa_q_len
,
2054 unsigned char **result
, size_t *resultlen
)
2056 size_t rsa_e_reqlen
;
2057 unsigned char privkey
[7*(1+3)];
2059 unsigned char exthdr
[2+2+3];
2061 unsigned char suffix
[2+3];
2065 unsigned char *template;
2066 size_t template_size
;
2071 switch (app
->app_local
->keyattr
[keyno
].format
)
2078 return gpg_error (GPG_ERR_NOT_SUPPORTED
);
2081 return gpg_error (GPG_ERR_INV_VALUE
);
2084 /* Get the required length for E. */
2085 rsa_e_reqlen
= app
->app_local
->keyattr
[keyno
].e_bits
/8;
2086 assert (rsa_e_len
<= rsa_e_reqlen
);
2088 /* Build the 7f48 cardholder private key template. */
2092 tp
+= add_tlv (tp
, 0x91, rsa_e_reqlen
);
2093 datalen
+= rsa_e_reqlen
;
2095 tp
+= add_tlv (tp
, 0x92, rsa_p_len
);
2096 datalen
+= rsa_p_len
;
2098 tp
+= add_tlv (tp
, 0x93, rsa_q_len
);
2099 datalen
+= rsa_q_len
;
2101 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2102 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2104 tp
+= add_tlv (tp
, 0x97, rsa_n_len
);
2105 datalen
+= rsa_n_len
;
2107 privkey_len
= tp
- privkey
;
2109 /* Build the extended header list without the private key template. */
2111 *tp
++ = keyno
==0 ? 0xb6 : keyno
== 1? 0xb8 : 0xa4;
2113 tp
+= add_tlv (tp
, 0x7f48, privkey_len
);
2114 exthdr_len
= tp
- exthdr
;
2116 /* Build the 5f48 suffix of the data. */
2118 tp
+= add_tlv (tp
, 0x5f48, datalen
);
2119 suffix_len
= tp
- suffix
;
2121 /* Now concatenate everything. */
2122 template_size
= (1 + 3 /* 0x4d and len. */
2127 tp
= template = xtrymalloc_secure (template_size
);
2129 return gpg_error_from_syserror ();
2131 tp
+= add_tlv (tp
, 0x4d, exthdr_len
+ privkey_len
+ suffix_len
+ datalen
);
2132 memcpy (tp
, exthdr
, exthdr_len
);
2134 memcpy (tp
, privkey
, privkey_len
);
2136 memcpy (tp
, suffix
, suffix_len
);
2139 memcpy (tp
, rsa_e
, rsa_e_len
);
2140 if (rsa_e_len
< rsa_e_reqlen
)
2142 /* Right justify E. */
2143 memmove (tp
+ rsa_e_reqlen
- rsa_e_len
, tp
, rsa_e_len
);
2144 memset (tp
, 0, rsa_e_reqlen
- rsa_e_len
);
2148 memcpy (tp
, rsa_p
, rsa_p_len
);
2151 memcpy (tp
, rsa_q
, rsa_q_len
);
2154 if (app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
2155 || app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
)
2157 memcpy (tp
, rsa_n
, rsa_n_len
);
2161 /* Sanity check. We don't know the exact length because we
2162 allocated 3 bytes for the first length header. */
2163 assert (tp
- template <= template_size
);
2166 *resultlen
= tp
- template;
2172 /* Handle the WRITEKEY command for OpenPGP. This function expects a
2173 canonical encoded S-expression with the secret key in KEYDATA and
2174 its length (for assertions) in KEYDATALEN. KEYID needs to be the
2175 usual keyid which for OpenPGP is the string "OPENPGP.n" with
2176 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2177 get overwritten. PINCB and PINCB_ARG are the usual arguments for
2178 the pinentry callback. */
2180 do_writekey (app_t app
, ctrl_t ctrl
,
2181 const char *keyid
, unsigned int flags
,
2182 gpg_error_t (*pincb
)(void*, const char *, char **),
2184 const unsigned char *keydata
, size_t keydatalen
)
2187 int force
= (flags
& 1);
2189 const unsigned char *buf
, *tok
;
2190 size_t buflen
, toklen
;
2191 int depth
, last_depth1
, last_depth2
;
2192 const unsigned char *rsa_n
= NULL
;
2193 const unsigned char *rsa_e
= NULL
;
2194 const unsigned char *rsa_p
= NULL
;
2195 const unsigned char *rsa_q
= NULL
;
2196 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
2198 unsigned int maxbits
;
2199 unsigned char *template = NULL
;
2201 size_t template_len
;
2202 unsigned char fprbuf
[20];
2207 if (!strcmp (keyid
, "OPENPGP.1"))
2209 else if (!strcmp (keyid
, "OPENPGP.2"))
2211 else if (!strcmp (keyid
, "OPENPGP.3"))
2214 return gpg_error (GPG_ERR_INV_ID
);
2216 err
= does_key_exist (app
, keyno
, force
);
2222 Parse the S-expression
2225 buflen
= keydatalen
;
2227 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2229 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2231 if (!tok
|| toklen
!= 11 || memcmp ("private-key", tok
, toklen
))
2235 else if (toklen
== 21 && !memcmp ("protected-private-key", tok
, toklen
))
2236 log_info ("protected-private-key passed to writekey\n");
2237 else if (toklen
== 20 && !memcmp ("shadowed-private-key", tok
, toklen
))
2238 log_info ("shadowed-private-key passed to writekey\n");
2239 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2242 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2244 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2246 if (!tok
|| toklen
!= 3 || memcmp ("rsa", tok
, toklen
))
2248 err
= gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO
);
2251 last_depth1
= depth
;
2252 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2253 && depth
&& depth
>= last_depth1
)
2257 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2260 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2262 if (tok
&& toklen
== 1)
2264 const unsigned char **mpi
;
2269 case 'n': mpi
= &rsa_n
; mpi_len
= &rsa_n_len
; break;
2270 case 'e': mpi
= &rsa_e
; mpi_len
= &rsa_e_len
; break;
2271 case 'p': mpi
= &rsa_p
; mpi_len
= &rsa_p_len
; break;
2272 case 'q': mpi
= &rsa_q
; mpi_len
= &rsa_q_len
;break;
2273 default: mpi
= NULL
; mpi_len
= NULL
; break;
2277 err
= gpg_error (GPG_ERR_DUP_VALUE
);
2280 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2284 /* Strip off leading zero bytes and save. */
2285 for (;toklen
&& !*tok
; toklen
--, tok
++)
2291 /* Skip until end of list. */
2292 last_depth2
= depth
;
2293 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2294 && depth
&& depth
>= last_depth2
)
2299 /* Parse other attributes. */
2300 last_depth1
= depth
;
2301 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2302 && depth
&& depth
>= last_depth1
)
2306 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
2309 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
2311 if (tok
&& toklen
== 10 && !memcmp ("created-at", tok
, toklen
))
2313 if ((err
= parse_sexp (&buf
,&buflen
,&depth
,&tok
,&toklen
)))
2317 for (created_at
=0; toklen
&& *tok
&& *tok
>= '0' && *tok
<= '9';
2319 created_at
= created_at
*10 + (*tok
- '0');
2322 /* Skip until end of list. */
2323 last_depth2
= depth
;
2324 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
2325 && depth
&& depth
>= last_depth2
)
2332 /* Check that we have all parameters and that they match the card
2336 log_error (_("creation timestamp missing\n"));
2337 err
= gpg_error (GPG_ERR_INV_VALUE
);
2341 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
;
2342 nbits
= rsa_n
? count_bits (rsa_n
, rsa_n_len
) : 0;
2343 if (nbits
!= maxbits
)
2345 log_error (_("RSA modulus missing or not of size %d bits\n"),
2347 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2351 maxbits
= app
->app_local
->keyattr
[keyno
].e_bits
;
2352 if (maxbits
> 32 && !app
->app_local
->extcap
.is_v2
)
2353 maxbits
= 32; /* Our code for v1 does only support 32 bits. */
2354 nbits
= rsa_e
? count_bits (rsa_e
, rsa_e_len
) : 0;
2355 if (nbits
< 2 || nbits
> maxbits
)
2357 log_error (_("RSA public exponent missing or larger than %d bits\n"),
2359 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2363 maxbits
= app
->app_local
->keyattr
[keyno
].n_bits
/2;
2364 nbits
= rsa_p
? count_bits (rsa_p
, rsa_p_len
) : 0;
2365 if (nbits
!= maxbits
)
2367 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2369 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2372 nbits
= rsa_q
? count_bits (rsa_q
, rsa_q_len
) : 0;
2373 if (nbits
!= maxbits
)
2375 log_error (_("RSA prime %s missing or not of size %d bits\n"),
2377 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
2381 /* We need to remove the cached public key. */
2382 xfree (app
->app_local
->pk
[keyno
].key
);
2383 app
->app_local
->pk
[keyno
].key
= NULL
;
2384 app
->app_local
->pk
[keyno
].keylen
= 0;
2385 app
->app_local
->pk
[keyno
].read_done
= 0;
2388 if (app
->app_local
->extcap
.is_v2
)
2390 /* Build the private key template as described in section 4.3.3.7 of
2391 the OpenPGP card specs version 2.0. */
2394 err
= build_privkey_template (app
, keyno
,
2399 &template, &template_len
);
2403 /* Prepare for storing the key. */
2404 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2408 /* Store the key. */
2409 if (app
->app_local
->cardcap
.cmd_chaining
&& template_len
> 254)
2413 err
= iso7816_put_data_odd (app
->slot
, exmode
, 0x3fff,
2414 template, template_len
);
2418 /* Build the private key template as described in section 4.3.3.6 of
2419 the OpenPGP card specs version 1.1:
2420 0xC0 <length> public exponent
2421 0xC1 <length> prime p
2422 0xC2 <length> prime q
2424 assert (rsa_e_len
<= 4);
2425 template_len
= (1 + 1 + 4
2427 + 1 + 1 + rsa_q_len
);
2428 template = tp
= xtrymalloc_secure (template_len
);
2431 err
= gpg_error_from_syserror ();
2436 memcpy (tp
, rsa_e
, rsa_e_len
);
2439 /* Right justify E. */
2440 memmove (tp
+4-rsa_e_len
, tp
, rsa_e_len
);
2441 memset (tp
, 0, 4-rsa_e_len
);
2447 memcpy (tp
, rsa_p
, rsa_p_len
);
2452 memcpy (tp
, rsa_q
, rsa_q_len
);
2455 assert (tp
- template == template_len
);
2457 /* Prepare for storing the key. */
2458 err
= verify_chv3 (app
, pincb
, pincb_arg
);
2462 /* Store the key. */
2463 err
= iso7816_put_data (app
->slot
, 0,
2464 (app
->card_version
> 0x0007? 0xE0:0xE9)+keyno
,
2465 template, template_len
);
2469 log_error (_("failed to store the key: %s\n"), gpg_strerror (err
));
2473 err
= store_fpr (app
->slot
, keyno
, created_at
,
2474 rsa_n
, rsa_n_len
, rsa_e
, rsa_e_len
,
2475 fprbuf
, app
->card_version
);
2486 /* Handle the GENKEY command. */
2488 do_genkey (app_t app
, ctrl_t ctrl
, const char *keynostr
, unsigned int flags
,
2490 gpg_error_t (*pincb
)(void*, const char *, char **),
2495 unsigned char fprbuf
[20];
2496 const unsigned char *keydata
, *m
, *e
;
2497 unsigned char *buffer
= NULL
;
2498 size_t buflen
, keydatalen
, mlen
, elen
;
2500 int keyno
= atoi (keynostr
);
2501 int force
= (flags
& 1);
2504 if (keyno
< 1 || keyno
> 3)
2505 return gpg_error (GPG_ERR_INV_ID
);
2508 /* We flush the cache to increase the traffic before a key
2509 generation. This _might_ help a card to gather more entropy. */
2512 /* Obviously we need to remove the cached public key. */
2513 xfree (app
->app_local
->pk
[keyno
].key
);
2514 app
->app_local
->pk
[keyno
].key
= NULL
;
2515 app
->app_local
->pk
[keyno
].keylen
= 0;
2516 app
->app_local
->pk
[keyno
].read_done
= 0;
2518 /* Check whether a key already exists. */
2519 rc
= does_key_exist (app
, keyno
, force
);
2523 /* Prepare for key generation by verifying the Admin PIN. */
2524 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
2529 log_info (_("please wait while key is being generated ...\n"));
2530 start_at
= time (NULL
);
2531 rc
= iso7816_generate_keypair
2533 # warning key generation temporary replaced by reading an existing key.
2534 rc
= iso7816_read_public_key
2536 (app
->slot
, (const unsigned char*)(keyno
== 0? "\xB6" :
2537 keyno
== 1? "\xB8" : "\xA4"),
2542 rc
= gpg_error (GPG_ERR_CARD
);
2543 log_error (_("generating key failed\n"));
2546 log_info (_("key generation completed (%d seconds)\n"),
2547 (int)(time (NULL
) - start_at
));
2548 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
2551 rc
= gpg_error (GPG_ERR_CARD
);
2552 log_error (_("response does not contain the public key data\n"));
2556 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
2559 rc
= gpg_error (GPG_ERR_CARD
);
2560 log_error (_("response does not contain the RSA modulus\n"));
2563 /* log_printhex ("RSA n:", m, mlen); */
2564 send_key_data (ctrl
, "n", m
, mlen
);
2566 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
2569 rc
= gpg_error (GPG_ERR_CARD
);
2570 log_error (_("response does not contain the RSA public exponent\n"));
2573 /* log_printhex ("RSA e:", e, elen); */
2574 send_key_data (ctrl
, "e", e
, elen
);
2576 created_at
= createtime
? createtime
: gnupg_get_time ();
2577 sprintf (numbuf
, "%lu", (unsigned long)created_at
);
2578 send_status_info (ctrl
, "KEY-CREATED-AT",
2579 numbuf
, (size_t)strlen(numbuf
), NULL
, 0);
2581 rc
= store_fpr (app
->slot
, keyno
, (u32
)created_at
,
2582 m
, mlen
, e
, elen
, fprbuf
, app
->card_version
);
2585 send_fpr_if_not_null (ctrl
, "KEY-FPR", -1, fprbuf
);
2594 static unsigned long
2595 convert_sig_counter_value (const unsigned char *value
, size_t valuelen
)
2600 ul
= (value
[0] << 16) | (value
[1] << 8) | value
[2];
2603 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2609 static unsigned long
2610 get_sig_counter (app_t app
)
2613 unsigned char *value
;
2617 relptr
= get_one_do (app
, 0x0093, &value
, &valuelen
, NULL
);
2620 ul
= convert_sig_counter_value (value
, valuelen
);
2626 compare_fingerprint (app_t app
, int keyno
, unsigned char *sha1fpr
)
2628 const unsigned char *fpr
;
2629 unsigned char *buffer
;
2633 assert (keyno
>= 1 && keyno
<= 3);
2635 rc
= get_cached_data (app
, 0x006E, &buffer
, &buflen
, 0);
2638 log_error (_("error reading application data\n"));
2639 return gpg_error (GPG_ERR_GENERAL
);
2641 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2642 if (!fpr
|| n
!= 60)
2645 log_error (_("error reading fingerprint DO\n"));
2646 return gpg_error (GPG_ERR_GENERAL
);
2648 fpr
+= (keyno
-1)*20;
2649 for (i
=0; i
< 20; i
++)
2650 if (sha1fpr
[i
] != fpr
[i
])
2653 log_info (_("fingerprint on card does not match requested one\n"));
2654 return gpg_error (GPG_ERR_WRONG_SECKEY
);
2661 /* If a fingerprint has been specified check it against the one on
2662 the card. This is allows for a meaningful error message in case
2663 the key on the card has been replaced but the shadow information
2664 known to gpg was not updated. If there is no fingerprint we
2665 assume that this is okay. */
2667 check_against_given_fingerprint (app_t app
, const char *fpr
, int keyno
)
2669 unsigned char tmp
[20];
2673 for (s
=fpr
, n
=0; hexdigitp (s
); s
++, n
++)
2676 return gpg_error (GPG_ERR_INV_ID
);
2680 return gpg_error (GPG_ERR_INV_ID
);
2682 for (s
=fpr
, n
=0; n
< 20; s
+= 2, n
++)
2683 tmp
[n
] = xtoi_2 (s
);
2684 return compare_fingerprint (app
, keyno
, tmp
);
2689 /* Compute a digital signature on INDATA which is expected to be the
2690 raw message digest. For this application the KEYIDSTR consists of
2691 the serialnumber and the fingerprint delimited by a slash.
2693 Note that this function may return the error code
2694 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2695 not match the one required for the requested action (e.g. the
2696 serial number does not match).
2698 As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
2699 operation to the auth command.
2702 do_sign (app_t app
, const char *keyidstr
, int hashalgo
,
2703 gpg_error_t (*pincb
)(void*, const char *, char **),
2705 const void *indata
, size_t indatalen
,
2706 unsigned char **outdata
, size_t *outdatalen
)
2708 static unsigned char rmd160_prefix
[15] = /* Object ID is 1.3.36.3.2.1 */
2709 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2710 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2711 static unsigned char sha1_prefix
[15] = /* (1.3.14.3.2.26) */
2712 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2713 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2714 static unsigned char sha224_prefix
[19] = /* (2.16.840.1.101.3.4.2.4) */
2715 { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
2716 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
2718 static unsigned char sha256_prefix
[19] = /* (2.16.840.1.101.3.4.2.1) */
2719 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2720 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
2722 static unsigned char sha384_prefix
[19] = /* (2.16.840.1.101.3.4.2.2) */
2723 { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2724 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
2726 static unsigned char sha512_prefix
[19] = /* (2.16.840.1.101.3.4.2.3) */
2727 { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
2728 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
2731 unsigned char data
[19+64];
2733 unsigned char tmp_sn
[20]; /* Actually 16 bytes but also for the fpr. */
2736 const char *fpr
= NULL
;
2737 unsigned long sigcount
;
2740 if (!keyidstr
|| !*keyidstr
)
2741 return gpg_error (GPG_ERR_INV_VALUE
);
2743 /* Strip off known prefixes. */
2744 #define X(a,b,c,d) \
2745 if (hashalgo == GCRY_MD_ ## a \
2747 && indatalen == sizeof b ## _prefix + (c) \
2748 && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
2750 indata = (const char*)indata + sizeof b ## _prefix; \
2751 indatalen -= sizeof b ## _prefix; \
2754 if (indatalen
== 20)
2755 ; /* Assume a plain SHA-1 or RMD160 digest has been given. */
2756 else X(SHA1
, sha1
, 20, 1)
2757 else X(RMD160
, rmd160
, 20, 1)
2758 else X(SHA224
, sha224
, 28, app
->app_local
->extcap
.is_v2
)
2759 else X(SHA256
, sha256
, 32, app
->app_local
->extcap
.is_v2
)
2760 else X(SHA384
, sha384
, 48, app
->app_local
->extcap
.is_v2
)
2761 else X(SHA512
, sha512
, 64, app
->app_local
->extcap
.is_v2
)
2762 else if ((indatalen
== 28 || indatalen
== 32
2763 || indatalen
== 48 || indatalen
==64)
2764 && app
->app_local
->extcap
.is_v2
)
2765 ; /* Assume a plain SHA-3 digest has been given. */
2768 log_error (_("card does not support digest algorithm %s\n"),
2769 gcry_md_algo_name (hashalgo
));
2770 /* Or the supplied digest length does not match an algorithm. */
2771 return gpg_error (GPG_ERR_INV_VALUE
);
2775 /* Check whether an OpenPGP card of any version has been requested. */
2776 if (!strcmp (keyidstr
, "OPENPGP.1"))
2778 else if (!strcmp (keyidstr
, "OPENPGP.3"))
2780 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2781 return gpg_error (GPG_ERR_INV_ID
);
2784 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2787 return gpg_error (GPG_ERR_INV_ID
);
2789 ; /* no fingerprint given: we allow this for now. */
2793 return gpg_error (GPG_ERR_INV_ID
);
2795 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2796 tmp_sn
[n
] = xtoi_2 (s
);
2798 if (app
->serialnolen
!= 16)
2799 return gpg_error (GPG_ERR_INV_CARD
);
2800 if (memcmp (app
->serialno
, tmp_sn
, 16))
2801 return gpg_error (GPG_ERR_WRONG_CARD
);
2804 /* If a fingerprint has been specified check it against the one on
2805 the card. This is allows for a meaningful error message in case
2806 the key on the card has been replaced but the shadow information
2807 known to gpg was not updated. If there is no fingerprint, gpg
2808 will detect a bogus signature anyway due to the
2809 verify-after-signing feature. */
2810 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 1) : 0;
2814 /* Concatenate prefix and digest. */
2816 if (hashalgo == GCRY_MD_ ## a && (d) ) \
2818 datalen = sizeof b ## _prefix + indatalen; \
2819 assert (datalen <= sizeof data); \
2820 memcpy (data, b ## _prefix, sizeof b ## _prefix); \
2821 memcpy (data + sizeof b ## _prefix, indata, indatalen); \
2825 else X(RMD160
, rmd160
, 1)
2826 else X(SHA224
, sha224
, app
->app_local
->extcap
.is_v2
)
2827 else X(SHA256
, sha256
, app
->app_local
->extcap
.is_v2
)
2828 else X(SHA384
, sha384
, app
->app_local
->extcap
.is_v2
)
2829 else X(SHA512
, sha512
, app
->app_local
->extcap
.is_v2
)
2831 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM
);
2834 /* Redirect to the AUTH command if asked to. */
2837 return do_auth (app
, "OPENPGP.3", pincb
, pincb_arg
,
2839 outdata
, outdatalen
);
2842 /* Show the number of signature done using this key. */
2843 sigcount
= get_sig_counter (app
);
2844 log_info (_("signatures created so far: %lu\n"), sigcount
);
2846 /* Check CHV if needed. */
2847 if (!app
->did_chv1
|| app
->force_chv1
)
2851 rc
= verify_a_chv (app
, pincb
, pincb_arg
, 1, sigcount
, &pinvalue
);
2857 /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
2858 sync, thus we verify CHV2 here using the given PIN. Cards
2859 with version2 to not have the need for a separate CHV2 and
2860 internally use just one. Obviously we can't do that if the
2861 keypad has been used. */
2862 if (!app
->did_chv2
&& pinvalue
&& !app
->app_local
->extcap
.is_v2
)
2864 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
2865 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
2866 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
2869 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
2871 flush_cache_after_error (app
);
2879 rc
= iso7816_compute_ds (app
->slot
, data
, datalen
, outdata
, outdatalen
);
2883 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2884 on INDATA which is expected to be the raw message digest. For this
2885 application the KEYIDSTR consists of the serialnumber and the
2886 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2889 Note that this function may return the error code
2890 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2891 not match the one required for the requested action (e.g. the
2892 serial number does not match). */
2894 do_auth (app_t app
, const char *keyidstr
,
2895 gpg_error_t (*pincb
)(void*, const char *, char **),
2897 const void *indata
, size_t indatalen
,
2898 unsigned char **outdata
, size_t *outdatalen
)
2901 unsigned char tmp_sn
[20]; /* Actually 16 but we use it also for the fpr. */
2904 const char *fpr
= NULL
;
2906 if (!keyidstr
|| !*keyidstr
)
2907 return gpg_error (GPG_ERR_INV_VALUE
);
2908 if (indatalen
> 101) /* For a 2048 bit key. */
2909 return gpg_error (GPG_ERR_INV_VALUE
);
2911 /* Check whether an OpenPGP card of any version has been requested. */
2912 if (!strcmp (keyidstr
, "OPENPGP.3"))
2914 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2915 return gpg_error (GPG_ERR_INV_ID
);
2918 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2921 return gpg_error (GPG_ERR_INV_ID
);
2923 ; /* no fingerprint given: we allow this for now. */
2927 return gpg_error (GPG_ERR_INV_ID
);
2929 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2930 tmp_sn
[n
] = xtoi_2 (s
);
2932 if (app
->serialnolen
!= 16)
2933 return gpg_error (GPG_ERR_INV_CARD
);
2934 if (memcmp (app
->serialno
, tmp_sn
, 16))
2935 return gpg_error (GPG_ERR_WRONG_CARD
);
2938 /* If a fingerprint has been specified check it against the one on
2939 the card. This is allows for a meaningful error message in case
2940 the key on the card has been replaced but the shadow information
2941 known to gpg was not updated. If there is no fingerprint, gpg
2942 will detect a bogus signature anyway due to the
2943 verify-after-signing feature. */
2944 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 3) : 0;
2948 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
2950 rc
= iso7816_internal_authenticate (app
->slot
, indata
, indatalen
,
2951 outdata
, outdatalen
);
2957 do_decipher (app_t app
, const char *keyidstr
,
2958 gpg_error_t (*pincb
)(void*, const char *, char **),
2960 const void *indata
, size_t indatalen
,
2961 unsigned char **outdata
, size_t *outdatalen
)
2964 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2967 const char *fpr
= NULL
;
2969 if (!keyidstr
|| !*keyidstr
|| !indatalen
)
2970 return gpg_error (GPG_ERR_INV_VALUE
);
2972 /* Check whether an OpenPGP card of any version has been requested. */
2973 if (!strcmp (keyidstr
, "OPENPGP.2"))
2975 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2976 return gpg_error (GPG_ERR_INV_ID
);
2979 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2982 return gpg_error (GPG_ERR_INV_ID
);
2984 ; /* no fingerprint given: we allow this for now. */
2988 return gpg_error (GPG_ERR_INV_ID
);
2990 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2991 tmp_sn
[n
] = xtoi_2 (s
);
2993 if (app
->serialnolen
!= 16)
2994 return gpg_error (GPG_ERR_INV_CARD
);
2995 if (memcmp (app
->serialno
, tmp_sn
, 16))
2996 return gpg_error (GPG_ERR_WRONG_CARD
);
2999 /* If a fingerprint has been specified check it against the one on
3000 the card. This is allows for a meaningful error message in case
3001 the key on the card has been replaced but the shadow information
3002 known to gpg was not updated. If there is no fingerprint, the
3003 decryption will won't produce the right plaintext anyway. */
3004 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 2) : 0;
3008 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
3013 /* We might encounter a couple of leading zeroes in the
3014 cryptogram. Due to internal use of MPIs thease leading
3015 zeroes are stripped. However the OpenPGP card expects
3016 exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3017 need to fix it up. We do this for up to 16 leading zero
3018 bytes; a cryptogram with more than this is with a very high
3019 probability anyway broken. */
3020 if (indatalen
>= (128-16) && indatalen
< 128) /* 1024 bit key. */
3021 fixuplen
= 128 - indatalen
;
3022 else if (indatalen
>= (256-16) && indatalen
< 256) /* 2048 bit key. */
3023 fixuplen
= 256 - indatalen
;
3024 else if (indatalen
>= (192-16) && indatalen
< 192) /* 1536 bit key. */
3025 fixuplen
= 192 - indatalen
;
3030 unsigned char *fixbuf
;
3032 /* While we have to prepend stuff anyway, we can also
3033 include the padding byte here so that iso1816_decipher
3034 does not need to do yet another data mangling. */
3036 fixbuf
= xtrymalloc (fixuplen
+ indatalen
);
3038 rc
= gpg_error_from_syserror ();
3041 memset (fixbuf
, 0, fixuplen
);
3042 memcpy (fixbuf
+fixuplen
, indata
, indatalen
);
3043 rc
= iso7816_decipher (app
->slot
, fixbuf
, fixuplen
+indatalen
, -1,
3044 outdata
, outdatalen
);
3050 rc
= iso7816_decipher (app
->slot
, indata
, indatalen
, 0,
3051 outdata
, outdatalen
);
3057 /* Perform a simple verify operation for CHV1 and CHV2, so that
3058 further operations won't ask for CHV2 and it is possible to do a
3059 cheap check on the PIN: If there is something wrong with the PIN
3060 entry system, only the regular CHV will get blocked and not the
3061 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3062 optional fingerprint part will be ignored.
3064 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3065 the "[CHV3]" being a literal string: The Admin Pin is checked if
3066 and only if the retry counter is still at 3. */
3068 do_check_pin (app_t app
, const char *keyidstr
,
3069 gpg_error_t (*pincb
)(void*, const char *, char **),
3072 unsigned char tmp_sn
[20];
3077 if (!keyidstr
|| !*keyidstr
)
3078 return gpg_error (GPG_ERR_INV_VALUE
);
3080 /* Check whether an OpenPGP card of any version has been requested. */
3081 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
3082 return gpg_error (GPG_ERR_INV_ID
);
3084 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
3087 return gpg_error (GPG_ERR_INV_ID
);
3089 ; /* No fingerprint given: we allow this for now. */
3091 ; /* We ignore a fingerprint. */
3092 else if (!strcmp (s
, "[CHV3]") )
3095 return gpg_error (GPG_ERR_INV_ID
);
3097 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
3098 tmp_sn
[n
] = xtoi_2 (s
);
3100 if (app
->serialnolen
!= 16)
3101 return gpg_error (GPG_ERR_INV_CARD
);
3102 if (memcmp (app
->serialno
, tmp_sn
, 16))
3103 return gpg_error (GPG_ERR_WRONG_CARD
);
3105 /* Yes, there is a race conditions: The user might pull the card
3106 right here and we won't notice that. However this is not a
3107 problem and the check above is merely for a graceful failure
3108 between operations. */
3113 unsigned char *value
;
3117 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
3118 if (!relptr
|| valuelen
< 7)
3120 log_error (_("error retrieving CHV status from card\n"));
3122 return gpg_error (GPG_ERR_CARD
);
3129 log_info (_("card is permanently locked!\n"));
3130 return gpg_error (GPG_ERR_BAD_PIN
);
3132 else if (value
[6] < 3)
3134 log_info (_("verification of Admin PIN is currently prohibited "
3135 "through this command\n"));
3136 return gpg_error (GPG_ERR_GENERAL
);
3139 app
->did_chv3
= 0; /* Force verification. */
3140 return verify_chv3 (app
, pincb
, pincb_arg
);
3143 return verify_chv2 (app
, pincb
, pincb_arg
);
3147 /* Show information about card capabilities. */
3149 show_caps (struct app_local_s
*s
)
3151 log_info ("Version-2 ......: %s\n", s
->extcap
.is_v2
? "yes":"no");
3152 log_info ("Get-Challenge ..: %s", s
->extcap
.get_challenge
? "yes":"no");
3153 if (s
->extcap
.get_challenge
)
3154 log_printf (" (%u bytes max)", s
->extcap
.max_get_challenge
);
3155 log_info ("Key-Import .....: %s\n", s
->extcap
.key_import
? "yes":"no");
3156 log_info ("Change-Force-PW1: %s\n", s
->extcap
.change_force_chv
? "yes":"no");
3157 log_info ("Private-DOs ....: %s\n", s
->extcap
.private_dos
? "yes":"no");
3158 log_info ("Algo-Attr-Change: %s\n", s
->extcap
.algo_attr_change
? "yes":"no");
3159 log_info ("SM-Support .....: %s", s
->extcap
.sm_supported
? "yes":"no");
3160 if (s
->extcap
.sm_supported
)
3161 log_printf (" (%s)", s
->extcap
.sm_aes128
? "AES-128":"3DES");
3162 log_info ("Max-Cert3-Len ..: %u\n", s
->extcap
.max_certlen_3
);
3163 log_info ("Max-Cmd-Data ...: %u\n", s
->extcap
.max_cmd_data
);
3164 log_info ("Max-Rsp-Data ...: %u\n", s
->extcap
.max_rsp_data
);
3165 log_info ("Cmd-Chaining ...: %s\n", s
->cardcap
.cmd_chaining
?"yes":"no");
3166 log_info ("Ext-Lc-Le ......: %s\n", s
->cardcap
.ext_lc_le
?"yes":"no");
3167 log_info ("Status Indicator: %02X\n", s
->status_indicator
);
3169 log_info ("GnuPG-No-Sync ..: %s\n", s
->flags
.no_sync
? "yes":"no");
3170 log_info ("GnuPG-Def-PW2 ..: %s\n", s
->flags
.def_chv2
? "yes":"no");
3174 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3177 parse_historical (struct app_local_s
*apploc
,
3178 const unsigned char * buffer
, size_t buflen
)
3180 /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3183 log_error ("warning: historical bytes are too short\n");
3184 return; /* Too short. */
3188 log_error ("warning: bad category indicator in historical bytes\n");
3192 /* Skip category indicator. */
3196 /* Get the status indicator. */
3197 apploc
->status_indicator
= buffer
[buflen
-3];
3200 /* Parse the compact TLV. */
3203 unsigned int tag
= (*buffer
& 0xf0) >> 4;
3204 unsigned int len
= (*buffer
& 0x0f);
3207 log_error ("warning: bad Compact-TLV in historical bytes\n");
3208 return; /* Error. */
3212 if (tag
== 7 && len
== 3)
3214 /* Card capabilities. */
3215 apploc
->cardcap
.cmd_chaining
= !!(buffer
[2] & 0x80);
3216 apploc
->cardcap
.ext_lc_le
= !!(buffer
[2] & 0x40);
3224 /* Parse and optionally show the algorithm attributes for KEYNO.
3225 KEYNO must be in the range 0..2. */
3227 parse_algorithm_attribute (app_t app
, int keyno
)
3229 unsigned char *buffer
;
3232 const char const desc
[3][5] = {"sign", "encr", "auth"};
3234 assert (keyno
>=0 && keyno
<= 2);
3236 app
->app_local
->keyattr
[keyno
].n_bits
= 0;
3238 relptr
= get_one_do (app
, 0xC1+keyno
, &buffer
, &buflen
, NULL
);
3241 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3246 log_error ("error reading DO 0x%02X\n", 0xc1+keyno
);
3252 log_info ("Key-Attr-%s ..: ", desc
[keyno
]);
3253 if (*buffer
== 1 && (buflen
== 5 || buflen
== 6))
3255 app
->app_local
->keyattr
[keyno
].n_bits
= (buffer
[1]<<8 | buffer
[2]);
3256 app
->app_local
->keyattr
[keyno
].e_bits
= (buffer
[3]<<8 | buffer
[4]);
3257 app
->app_local
->keyattr
[keyno
].format
= 0;
3259 app
->app_local
->keyattr
[keyno
].format
= RSA_STD
;
3261 app
->app_local
->keyattr
[keyno
].format
= (buffer
[5] == 0? RSA_STD
:
3262 buffer
[5] == 1? RSA_STD_N
:
3263 buffer
[5] == 2? RSA_CRT
:
3264 buffer
[5] == 3? RSA_CRT_N
:
3269 ("RSA, n=%u, e=%u, fmt=%s\n",
3270 app
->app_local
->keyattr
[keyno
].n_bits
,
3271 app
->app_local
->keyattr
[keyno
].e_bits
,
3272 app
->app_local
->keyattr
[keyno
].format
== RSA_STD
? "std" :
3273 app
->app_local
->keyattr
[keyno
].format
== RSA_STD_N
?"std+n":
3274 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT
? "crt" :
3275 app
->app_local
->keyattr
[keyno
].format
== RSA_CRT_N
?"crt+n":"?");
3277 else if (opt
.verbose
)
3278 log_printhex ("", buffer
, buflen
);
3283 /* Select the OpenPGP application on the card in SLOT. This function
3284 must be used before any other OpenPGP application functions. */
3286 app_select_openpgp (app_t app
)
3288 static char const aid
[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3289 int slot
= app
->slot
;
3291 unsigned char *buffer
;
3295 /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3296 special flag value. */
3297 rc
= iso7816_select_application (slot
, aid
, sizeof aid
, 0x0001);
3300 unsigned int manufacturer
;
3302 app
->apptype
= "OPENPGP";
3307 app
->app_local
= NULL
;
3309 /* The OpenPGP card returns the serial number as part of the
3310 AID; because we prefer to use OpenPGP serial numbers, we
3311 replace a possibly already set one from a EF.GDO with this
3312 one. Note, that for current OpenPGP cards, no EF.GDO exists
3313 and thus it won't matter at all. */
3314 rc
= iso7816_get_data (slot
, 0x004F, &buffer
, &buflen
);
3320 log_printhex ("", buffer
, buflen
);
3323 app
->card_version
= buffer
[6] << 8;
3324 app
->card_version
|= buffer
[7];
3325 manufacturer
= (buffer
[8]<<8 | buffer
[9]);
3327 xfree (app
->serialno
);
3328 app
->serialno
= buffer
;
3329 app
->serialnolen
= buflen
;
3331 app
->app_local
= xtrycalloc (1, sizeof *app
->app_local
);
3332 if (!app
->app_local
)
3334 rc
= gpg_error (gpg_err_code_from_errno (errno
));
3338 if (app
->card_version
>= 0x0200)
3339 app
->app_local
->extcap
.is_v2
= 1;
3342 /* Read the historical bytes. */
3343 relptr
= get_one_do (app
, 0x5f52, &buffer
, &buflen
, NULL
);
3348 log_info ("Historical Bytes: ");
3349 log_printhex ("", buffer
, buflen
);
3351 parse_historical (app
->app_local
, buffer
, buflen
);
3355 /* Read the force-chv1 flag. */
3356 relptr
= get_one_do (app
, 0x00C4, &buffer
, &buflen
, NULL
);
3359 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3360 "CHV Status Bytes");
3363 app
->force_chv1
= (buflen
&& *buffer
== 0);
3366 /* Read the extended capabilities. */
3367 relptr
= get_one_do (app
, 0x00C0, &buffer
, &buflen
, NULL
);
3370 log_error (_("can't access %s - invalid OpenPGP card?\n"),
3371 "Extended Capability Flags" );
3376 app
->app_local
->extcap
.sm_supported
= !!(*buffer
& 0x80);
3377 app
->app_local
->extcap
.get_challenge
= !!(*buffer
& 0x40);
3378 app
->app_local
->extcap
.key_import
= !!(*buffer
& 0x20);
3379 app
->app_local
->extcap
.change_force_chv
= !!(*buffer
& 0x10);
3380 app
->app_local
->extcap
.private_dos
= !!(*buffer
& 0x08);
3381 app
->app_local
->extcap
.algo_attr_change
= !!(*buffer
& 0x04);
3385 /* Available with v2 cards. */
3386 app
->app_local
->extcap
.sm_aes128
= (buffer
[1] == 1);
3387 app
->app_local
->extcap
.max_get_challenge
3388 = (buffer
[2] << 8 | buffer
[3]);
3389 app
->app_local
->extcap
.max_certlen_3
= (buffer
[4] << 8 | buffer
[5]);
3390 app
->app_local
->extcap
.max_cmd_data
= (buffer
[6] << 8 | buffer
[7]);
3391 app
->app_local
->extcap
.max_rsp_data
= (buffer
[8] << 8 | buffer
[9]);
3395 /* Some of the first cards accidently don't set the
3396 CHANGE_FORCE_CHV bit but allow it anyway. */
3397 if (app
->card_version
<= 0x0100 && manufacturer
== 1)
3398 app
->app_local
->extcap
.change_force_chv
= 1;
3400 parse_login_data (app
);
3403 show_caps (app
->app_local
);
3405 parse_algorithm_attribute (app
, 0);
3406 parse_algorithm_attribute (app
, 1);
3407 parse_algorithm_attribute (app
, 2);
3409 if (opt
.verbose
> 1)
3412 app
->fnc
.deinit
= do_deinit
;
3413 app
->fnc
.learn_status
= do_learn_status
;
3414 app
->fnc
.readcert
= do_readcert
;
3415 app
->fnc
.readkey
= do_readkey
;
3416 app
->fnc
.getattr
= do_getattr
;
3417 app
->fnc
.setattr
= do_setattr
;
3418 app
->fnc
.writecert
= do_writecert
;
3419 app
->fnc
.writekey
= do_writekey
;
3420 app
->fnc
.genkey
= do_genkey
;
3421 app
->fnc
.sign
= do_sign
;
3422 app
->fnc
.auth
= do_auth
;
3423 app
->fnc
.decipher
= do_decipher
;
3424 app
->fnc
.change_pin
= do_change_pin
;
3425 app
->fnc
.check_pin
= do_check_pin
;