1 /* app-openpgp.c - The OpenPGP card application.
2 * Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
32 #if GNUPG_MAJOR_VERSION == 1
33 /* This is used with GnuPG version < 1.9. The code has been source
34 copied from the current GnuPG >= 1.9 and is maintained over
41 #else /* GNUPG_MAJOR_VERSION != 1 */
43 #endif /* GNUPG_MAJOR_VERSION != 1 */
47 #include "app-common.h"
54 int get_from
; /* Constructed DO with this DO or 0 for direct access. */
58 int get_immediate_in_v11
; /* Enable a hack to bypass the cache of
59 this data object if it is used in 1.1
60 and later versions of the card. This
61 does not work with composite DO and is
62 currently only useful for the CHV
66 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
67 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
68 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
69 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
70 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
71 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
72 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
73 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
74 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
75 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
76 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
77 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
78 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
79 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
80 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
81 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
82 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
83 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
84 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
85 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
86 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
87 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
88 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
89 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
94 /* One cache item for DOs. */
99 unsigned char data
[1];
103 /* Object with application (i.e. OpenPGP card) specific data. */
105 /* A linked list with cached DOs. */
106 struct cache_s
*cache
;
108 /* Keep track of the public keys. */
111 int read_done
; /* True if we have at least tried to read them. */
112 unsigned char *key
; /* This is a malloced buffer with a canonical
113 encoded S-expression encoding a public
114 key. Might be NULL if key is not
116 size_t keylen
; /* The length of the above S-expression. Thsi
117 is usullay only required for corss checks
118 because the length of an S-expression is
119 implicitly available. */
122 /* Keep track of card capabilities. */
125 unsigned int get_challenge
:1;
126 unsigned int key_import
:1;
127 unsigned int change_force_chv
:1;
128 unsigned int private_dos
:1;
131 /* Flags used to control the application. */
134 unsigned int no_sync
:1; /* Do not sync CHV1 and CHV2 */
135 unsigned int def_chv2
:1; /* Use 123456 for CHV2. */
141 /***** Local prototypes *****/
142 static unsigned long convert_sig_counter_value (const unsigned char *value
,
144 static unsigned long get_sig_counter (app_t app
);
152 do_deinit (app_t app
)
154 if (app
&& app
->app_local
)
156 struct cache_s
*c
, *c2
;
159 for (c
= app
->app_local
->cache
; c
; c
= c2
)
165 for (i
=0; i
< DIM (app
->app_local
->pk
); i
++)
167 xfree (app
->app_local
->pk
[i
].key
);
168 app
->app_local
->pk
[i
].read_done
= 0;
170 xfree (app
->app_local
);
171 app
->app_local
= NULL
;
176 /* Wrapper around iso7816_get_data which first tries to get the data
177 from the cache. With GET_IMMEDIATE passed as true, the cache is
180 get_cached_data (app_t app
, int tag
,
181 unsigned char **result
, size_t *resultlen
,
195 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
200 p
= xtrymalloc (c
->length
);
202 return gpg_error (gpg_err_code_from_errno (errno
));
203 memcpy (p
, c
->data
, c
->length
);
207 *resultlen
= c
->length
;
213 err
= iso7816_get_data (app
->slot
, tag
, &p
, &len
);
219 /* Check whether we should cache this object. */
223 for (i
=0; data_objects
[i
].tag
; i
++)
224 if (data_objects
[i
].tag
== tag
)
226 if (data_objects
[i
].dont_cache
)
231 /* Okay, cache it. */
232 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
233 assert (c
->tag
!= tag
);
235 c
= xtrymalloc (sizeof *c
+ len
);
238 memcpy (c
->data
, p
, len
);
241 c
->next
= app
->app_local
->cache
;
242 app
->app_local
->cache
= c
;
248 /* Remove DO at TAG from the cache. */
250 flush_cache_item (app_t app
, int tag
)
252 struct cache_s
*c
, *cprev
;
258 for (c
=app
->app_local
->cache
, cprev
=NULL
; c
; cprev
=c
, c
= c
->next
)
262 cprev
->next
= c
->next
;
264 app
->app_local
->cache
= c
->next
;
267 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
269 assert (c
->tag
!= tag
); /* Oops: duplicated entry. */
274 /* Try again if we have an outer tag. */
275 for (i
=0; data_objects
[i
].tag
; i
++)
276 if (data_objects
[i
].tag
== tag
&& data_objects
[i
].get_from
277 && data_objects
[i
].get_from
!= tag
)
278 flush_cache_item (app
, data_objects
[i
].get_from
);
281 /* Flush all entries from the cache which might be out of sync after
284 flush_cache_after_error (app_t app
)
288 for (i
=0; data_objects
[i
].tag
; i
++)
289 if (data_objects
[i
].flush_on_error
)
290 flush_cache_item (app
, data_objects
[i
].tag
);
294 /* Flush the entire cache. */
296 flush_cache (app_t app
)
298 if (app
&& app
->app_local
)
300 struct cache_s
*c
, *c2
;
302 for (c
= app
->app_local
->cache
; c
; c
= c2
)
307 app
->app_local
->cache
= NULL
;
312 /* Get the DO identified by TAG from the card in SLOT and return a
313 buffer with its content in RESULT and NBYTES. The return value is
314 NULL if not found or a pointer which must be used to release the
315 buffer holding value. */
317 get_one_do (app_t app
, int tag
, unsigned char **result
, size_t *nbytes
,
321 unsigned char *buffer
;
323 unsigned char *value
;
333 for (i
=0; data_objects
[i
].tag
&& data_objects
[i
].tag
!= tag
; i
++)
336 if (app
->card_version
> 0x0100 && data_objects
[i
].get_immediate_in_v11
)
338 rc
= iso7816_get_data (app
->slot
, tag
, &buffer
, &buflen
);
351 if (data_objects
[i
].tag
&& data_objects
[i
].get_from
)
353 rc
= get_cached_data (app
, data_objects
[i
].get_from
,
355 (data_objects
[i
].dont_cache
356 || data_objects
[i
].get_immediate_in_v11
));
359 const unsigned char *s
;
361 s
= find_tlv_unchecked (buffer
, buflen
, tag
, &valuelen
);
363 value
= NULL
; /* not found */
364 else if (valuelen
> buflen
- (s
- buffer
))
366 log_error ("warning: constructed DO too short\n");
368 xfree (buffer
); buffer
= NULL
;
371 value
= buffer
+ (s
- buffer
);
375 if (!value
) /* Not in a constructed DO, try simple. */
377 rc
= get_cached_data (app
, tag
, &buffer
, &buflen
,
378 (data_objects
[i
].dont_cache
379 || data_objects
[i
].get_immediate_in_v11
));
399 dump_all_do (int slot
)
402 unsigned char *buffer
;
405 for (i
=0; data_objects
[i
].tag
; i
++)
407 if (data_objects
[i
].get_from
)
410 rc
= iso7816_get_data (slot
, data_objects
[i
].tag
, &buffer
, &buflen
);
411 if (gpg_err_code (rc
) == GPG_ERR_NO_OBJ
)
414 log_info ("DO `%s' not available: %s\n",
415 data_objects
[i
].desc
, gpg_strerror (rc
));
418 if (data_objects
[i
].binary
)
420 log_info ("DO `%s': ", data_objects
[i
].desc
);
421 log_printhex ("", buffer
, buflen
);
424 log_info ("DO `%s': `%.*s'\n",
425 data_objects
[i
].desc
,
426 (int)buflen
, buffer
); /* FIXME: sanitize */
428 if (data_objects
[i
].constructed
)
430 for (j
=0; data_objects
[j
].tag
; j
++)
432 const unsigned char *value
;
435 if (j
==i
|| data_objects
[i
].tag
!= data_objects
[j
].get_from
)
437 value
= find_tlv_unchecked (buffer
, buflen
,
438 data_objects
[j
].tag
, &valuelen
);
441 else if (valuelen
> buflen
- (value
- buffer
))
442 log_error ("warning: constructed DO too short\n");
445 if (data_objects
[j
].binary
)
447 log_info ("DO `%s': ", data_objects
[j
].desc
);
448 log_printhex ("", value
, valuelen
);
451 log_info ("DO `%s': `%.*s'\n",
452 data_objects
[j
].desc
,
453 (int)valuelen
, value
); /* FIXME: sanitize */
458 xfree (buffer
); buffer
= NULL
;
463 /* Count the number of bits, assuming the A represents an unsigned big
464 integer of length LEN bytes. */
466 count_bits (const unsigned char *a
, size_t len
)
468 unsigned int n
= len
* 8;
471 for (; len
&& !*a
; len
--, a
++, n
-=8)
475 for (i
=7; i
&& !(*a
& (1<<i
)); i
--)
481 /* GnuPG makes special use of the login-data DO, this fucntion parses
482 the login data to store the flags for later use. It may be called
483 at any time and should be called after changing the login-data DO.
485 Everything up to a LF is considered a mailbox or account name. If
486 the first LF is followed by DC4 (0x14) control sequence are
487 expected up to the next LF. Control sequences are separated by FS
488 (0x28) and consist of key=value pairs. There is one key defined:
492 Were FLAGS is a plain hexadecimal number representing flag values.
493 The lsb is here the rightmost bit. Defined flags bits are:
495 Bit 0 = CHV1 and CHV2 are not syncronized
496 Bit 1 = CHV2 has been been set to the default PIN of "123456"
497 (this implies that bit 0 is also set).
501 parse_login_data (app_t app
)
503 unsigned char *buffer
, *p
;
508 app
->app_local
->flags
.no_sync
= 0;
509 app
->app_local
->flags
.def_chv2
= 0;
512 relptr
= get_one_do (app
, 0x005E, &buffer
, &buflen
, NULL
);
515 for (; buflen
; buflen
--, buffer
++)
518 if (buflen
< 2 || buffer
[1] != '\x14')
519 return; /* No control sequences. */
526 if (buflen
> 1 && *buffer
== 'F' && buffer
[1] == '=')
528 /* Flags control sequence found. */
531 /* For now we are only interested in the last digit, so skip
532 any leading digits but bail out on invalid characters. */
533 for (p
=buffer
+2, len
= buflen
-2; len
&& hexdigitp (p
); p
++, len
--)
534 lastdig
= xtoi_1 (p
);
535 if (len
&& !(*p
== '\n' || *p
== '\x18'))
536 goto next
; /* Invalid characters in field. */
537 app
->app_local
->flags
.no_sync
= !!(lastdig
& 1);
538 app
->app_local
->flags
.def_chv2
= (lastdig
& 3) == 3;
541 for (; buflen
&& *buffer
!= '\x18'; buflen
--, buffer
++)
550 /* Note, that FPR must be at least 20 bytes. */
552 store_fpr (int slot
, int keynumber
, u32 timestamp
,
553 const unsigned char *m
, size_t mlen
,
554 const unsigned char *e
, size_t elen
,
555 unsigned char *fpr
, unsigned int card_version
)
557 unsigned int n
, nbits
;
558 unsigned char *buffer
, *p
;
561 for (; mlen
&& !*m
; mlen
--, m
++) /* strip leading zeroes */
563 for (; elen
&& !*e
; elen
--, e
++) /* strip leading zeroes */
566 n
= 6 + 2 + mlen
+ 2 + elen
;
567 p
= buffer
= xtrymalloc (3 + n
);
569 return gpg_error_from_errno (errno
);
571 *p
++ = 0x99; /* ctb */
572 *p
++ = n
>> 8; /* 2 byte length header */
574 *p
++ = 4; /* key packet version */
575 *p
++ = timestamp
>> 24;
576 *p
++ = timestamp
>> 16;
577 *p
++ = timestamp
>> 8;
580 nbits
= count_bits (m
, mlen
);
583 memcpy (p
, m
, mlen
); p
+= mlen
;
584 nbits
= count_bits (e
, elen
);
587 memcpy (p
, e
, elen
); p
+= elen
;
589 gcry_md_hash_buffer (GCRY_MD_SHA1
, fpr
, buffer
, n
+3);
593 rc
= iso7816_put_data (slot
, (card_version
> 0x0007? 0xC7 : 0xC6)
594 + keynumber
, fpr
, 20);
596 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc
));
598 if (!rc
&& card_version
> 0x0100)
600 unsigned char buf
[4];
602 buf
[0] = timestamp
>> 24;
603 buf
[1] = timestamp
>> 16;
604 buf
[2] = timestamp
>> 8;
607 rc
= iso7816_put_data (slot
, 0xCE + keynumber
, buf
, 4);
609 log_error (_("failed to store the creation date: %s\n"),
618 send_fpr_if_not_null (ctrl_t ctrl
, const char *keyword
,
619 int number
, const unsigned char *fpr
)
625 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
628 return; /* All zero. */
629 for (i
=0; i
< 20; i
++)
630 sprintf (buf
+2*i
, "%02X", fpr
[i
]);
632 *numbuf
= 0; /* Don't print the key number */
634 sprintf (numbuf
, "%d", number
);
635 send_status_info (ctrl
, keyword
,
636 numbuf
, (size_t)strlen(numbuf
),
637 buf
, (size_t)strlen (buf
), NULL
, 0);
641 send_fprtime_if_not_null (ctrl_t ctrl
, const char *keyword
,
642 int number
, const unsigned char *stamp
)
644 char numbuf1
[50], numbuf2
[50];
647 value
= (stamp
[0] << 24) | (stamp
[1]<<16) | (stamp
[2]<<8) | stamp
[3];
650 sprintf (numbuf1
, "%d", number
);
651 sprintf (numbuf2
, "%lu", value
);
652 send_status_info (ctrl
, keyword
,
653 numbuf1
, (size_t)strlen(numbuf1
),
654 numbuf2
, (size_t)strlen(numbuf2
), NULL
, 0);
658 send_key_data (ctrl_t ctrl
, const char *name
,
659 const unsigned char *a
, size_t alen
)
661 char *p
, *buf
= xmalloc (alen
*2+1);
663 for (p
=buf
; alen
; a
++, alen
--, p
+= 2)
664 sprintf (p
, "%02X", *a
);
666 send_status_info (ctrl
, "KEY-DATA",
667 name
, (size_t)strlen(name
),
668 buf
, (size_t)strlen (buf
),
673 /* Implement the GETATTR command. This is similar to the LEARN
674 command but returns just one value via the status interface. */
676 do_getattr (app_t app
, ctrl_t ctrl
, const char *name
)
683 { "DISP-NAME", 0x005B },
684 { "LOGIN-DATA", 0x005E },
685 { "DISP-LANG", 0x5F2D },
686 { "DISP-SEX", 0x5F35 },
687 { "PUBKEY-URL", 0x5F50 },
688 { "KEY-FPR", 0x00C5, 3 },
689 { "KEY-TIME", 0x00CD, 4 },
690 { "CA-FPR", 0x00C6, 3 },
691 { "CHV-STATUS", 0x00C4, 1 },
692 { "SIG-COUNTER", 0x0093, 2 },
693 { "SERIALNO", 0x004F, -1 },
695 { "EXTCAP", 0x0000, -2 },
696 { "PRIVATE-DO-1", 0x0101 },
697 { "PRIVATE-DO-2", 0x0102 },
698 { "PRIVATE-DO-3", 0x0103 },
699 { "PRIVATE-DO-4", 0x0104 },
704 unsigned char *value
;
707 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
709 if (!table
[idx
].name
)
710 return gpg_error (GPG_ERR_INV_NAME
);
712 if (table
[idx
].special
== -1)
714 /* The serial number is very special. We could have used the
715 AID DO to retrieve it, but we have it already in the app
716 context and the stamp argument is required anyway which we
717 can't by other means. The AID DO is available anyway but not
723 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
725 sprintf (tmp
, "%lu", (unsigned long)stamp
);
726 send_status_info (ctrl
, "SERIALNO",
727 serial
, strlen (serial
),
734 if (table
[idx
].special
== -2)
738 sprintf (tmp
, "gc=%d ki=%d fc=%d pd=%d",
739 app
->app_local
->extcap
.get_challenge
,
740 app
->app_local
->extcap
.key_import
,
741 app
->app_local
->extcap
.change_force_chv
,
742 app
->app_local
->extcap
.private_dos
);
743 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
747 relptr
= get_one_do (app
, table
[idx
].tag
, &value
, &valuelen
, &rc
);
750 if (table
[idx
].special
== 1)
754 for (i
=0,*numbuf
=0; i
< valuelen
&& i
< 7; i
++)
755 sprintf (numbuf
+strlen (numbuf
), " %d", value
[i
]);
756 send_status_info (ctrl
, table
[idx
].name
,
757 numbuf
, strlen (numbuf
), NULL
, 0);
759 else if (table
[idx
].special
== 2)
763 sprintf (numbuf
, "%lu", convert_sig_counter_value (value
, valuelen
));
764 send_status_info (ctrl
, table
[idx
].name
,
765 numbuf
, strlen (numbuf
), NULL
, 0);
767 else if (table
[idx
].special
== 3)
770 for (i
=0; i
< 3; i
++)
771 send_fpr_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*20);
773 else if (table
[idx
].special
== 4)
776 for (i
=0; i
< 3; i
++)
777 send_fprtime_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*4);
780 send_status_info (ctrl
, table
[idx
].name
, value
, valuelen
, NULL
, 0);
787 /* Retrieve the fingerprint from the card inserted in SLOT and write
788 the according hex representation to FPR. Caller must have provide
789 a buffer at FPR of least 41 bytes. Returns 0 on success or an
791 #if GNUPG_MAJOR_VERSION > 1
793 retrieve_fpr_from_card (app_t app
, int keyno
, char *fpr
)
797 unsigned char *value
;
801 assert (keyno
>=0 && keyno
<= 2);
803 relptr
= get_one_do (app
, 0x00C5, &value
, &valuelen
, NULL
);
804 if (relptr
&& valuelen
>= 60)
806 for (i
= 0; i
< 20; i
++)
807 sprintf (fpr
+ (i
* 2), "%02X", value
[(keyno
*20)+i
]);
810 err
= gpg_error (GPG_ERR_NOT_FOUND
);
814 #endif /*GNUPG_MAJOR_VERSION > 1*/
817 /* Retrieve the public key material for the RSA key, whose fingerprint
818 is FPR, from gpg output, which can be read through the stream FP.
819 The RSA modulus will be stored at the address of M and MLEN, the
820 public exponent at E and ELEN. Returns zero on success, an error
821 code on failure. Caller must release the allocated buffers at M
822 and E if the function returns success. */
823 #if GNUPG_MAJOR_VERSION > 1
825 retrieve_key_material (FILE *fp
, const char *hexkeyid
,
826 const unsigned char **m
, size_t *mlen
,
827 const unsigned char **e
, size_t *elen
)
829 gcry_error_t err
= 0;
830 char *line
= NULL
; /* read_line() buffer. */
831 size_t line_size
= 0; /* Helper for for read_line. */
832 int found_key
= 0; /* Helper to find a matching key. */
833 unsigned char *m_new
= NULL
;
834 unsigned char *e_new
= NULL
;
838 /* Loop over all records until we have found the subkey
839 corresponsing to the fingerprint. Inm general the first record
840 should be the pub record, but we don't rely on that. Given that
841 we only need to look at one key, it is sufficient to compare the
842 keyid so that we don't need to look at "fpr" records. */
853 i
= read_line (fp
, &line
, &line_size
, &max_length
);
858 err
= gpg_error_from_errno (errno
);
859 goto leave
; /* Error. */
863 err
= gpg_error (GPG_ERR_TRUNCATED
);
864 goto leave
; /* Line truncated - we better stop processing. */
867 /* Parse the line into fields. */
868 for (nfields
=0, p
=line
; p
&& nfields
< DIM (fields
); nfields
++)
876 continue; /* No fields at all - skip line. */
880 if ( (!strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
881 && nfields
> 4 && !strcmp (fields
[4], hexkeyid
))
886 if ( !strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
887 break; /* Next key - stop. */
889 if ( strcmp (fields
[0], "pkd") )
890 continue; /* Not a key data record. */
891 i
= 0; /* Avoid erroneous compiler warning. */
892 if ( nfields
< 4 || (i
= atoi (fields
[1])) < 0 || i
> 1
893 || (!i
&& m_new
) || (i
&& e_new
))
895 err
= gpg_error (GPG_ERR_GENERAL
);
896 goto leave
; /* Error: Invalid key data record or not an RSA key. */
899 err
= gcry_mpi_scan (&mpi
, GCRYMPI_FMT_HEX
, fields
[3], 0, NULL
);
903 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &m_new
, &m_new_n
, mpi
);
905 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &e_new
, &e_new_n
, mpi
);
906 gcry_mpi_release (mpi
);
921 err
= gpg_error (GPG_ERR_GENERAL
);
929 #endif /*GNUPG_MAJOR_VERSION > 1*/
932 /* Get the public key for KEYNO and store it as an S-expresion with
933 the APP handle. On error that field gets cleared. If we already
934 know about the public key we will just return. Note that this does
935 not mean a key is available; this is soley indicated by the
936 presence of the app->app_local->pk[KEYNO-1].key field.
938 Note that GnuPG 1.x does not need this and it would be too time
939 consuming to send it just for the fun of it. However, given that we
940 use the same code in gpg 1.4, we can't use the gcry S-expresion
941 here but need to open encode it. */
942 #if GNUPG_MAJOR_VERSION > 1
944 get_public_key (app_t app
, int keyno
)
947 unsigned char *buffer
;
948 const unsigned char *keydata
, *m
, *e
;
949 size_t buflen
, keydatalen
, mlen
, elen
;
950 unsigned char *mbuf
= NULL
;
951 unsigned char *ebuf
= NULL
;
952 unsigned char *keybuf
= NULL
;
953 unsigned char *keybuf_p
;
955 if (keyno
< 1 || keyno
> 3)
956 return gpg_error (GPG_ERR_INV_ID
);
959 /* Already cached? */
960 if (app
->app_local
->pk
[keyno
].read_done
)
963 xfree (app
->app_local
->pk
[keyno
].key
);
964 app
->app_local
->pk
[keyno
].key
= NULL
;
965 app
->app_local
->pk
[keyno
].keylen
= 0;
967 if (app
->card_version
> 0x0100)
969 /* We may simply read the public key out of these cards. */
970 err
= iso7816_read_public_key (app
->slot
,
972 keyno
== 1? "\xB8" : "\xA4",
977 log_error (_("reading public key failed: %s\n"), gpg_strerror (err
));
981 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
984 err
= gpg_error (GPG_ERR_CARD
);
985 log_error (_("response does not contain the public key data\n"));
989 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
992 err
= gpg_error (GPG_ERR_CARD
);
993 log_error (_("response does not contain the RSA modulus\n"));
998 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1001 err
= gpg_error (GPG_ERR_CARD
);
1002 log_error (_("response does not contain the RSA public exponent\n"));
1006 /* Prepend numbers with a 0 if needed. */
1007 if (mlen
&& (*m
& 0x80))
1009 mbuf
= xtrymalloc ( mlen
+ 1);
1012 err
= gpg_error_from_errno (errno
);
1016 memcpy (mbuf
+1, m
, mlen
);
1020 if (elen
&& (*e
& 0x80))
1022 ebuf
= xtrymalloc ( elen
+ 1);
1025 err
= gpg_error_from_errno (errno
);
1029 memcpy (ebuf
+1, e
, elen
);
1037 /* Due to a design problem in v1.0 cards we can't get the public
1038 key out of these cards without doing a verify on CHV3.
1039 Clearly that is not an option and thus we try to locate the
1040 key using an external helper.
1042 The helper we use here is gpg itself, which should know about
1043 the key in any case. */
1047 char *command
= NULL
;
1051 buffer
= NULL
; /* We don't need buffer. */
1053 err
= retrieve_fpr_from_card (app
, keyno
, fpr
);
1056 log_error ("error while retrieving fpr from card: %s\n",
1057 gpg_strerror (err
));
1060 hexkeyid
= fpr
+ 24;
1062 ret
= asprintf (&command
,
1063 "gpg --list-keys --with-colons --with-key-data '%s'",
1067 err
= gpg_error_from_errno (errno
);
1071 fp
= popen (command
, "r");
1075 err
= gpg_error_from_errno (errno
);
1076 log_error ("running gpg failed: %s\n", gpg_strerror (err
));
1080 err
= retrieve_key_material (fp
, hexkeyid
, &m
, &mlen
, &e
, &elen
);
1084 log_error ("error while retrieving key material through pipe: %s\n",
1085 gpg_strerror (err
));
1090 /* Allocate a buffer to construct the S-expression. */
1091 /* FIXME: We should provide a generalized S-expression creation
1093 keybuf
= xtrymalloc (50 + 2*35 + mlen
+ elen
+ 1);
1096 err
= gpg_error_from_errno (errno
);
1100 sprintf (keybuf
, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen
);
1101 keybuf_p
= keybuf
+ strlen (keybuf
);
1102 memcpy (keybuf_p
, m
, mlen
);
1104 sprintf (keybuf_p
, ")(1:e%u:", (unsigned int)elen
);
1105 keybuf_p
+= strlen (keybuf_p
);
1106 memcpy (keybuf_p
, e
, elen
);
1108 strcpy (keybuf_p
, ")))");
1109 keybuf_p
+= strlen (keybuf_p
);
1111 app
->app_local
->pk
[keyno
].key
= keybuf
;
1112 app
->app_local
->pk
[keyno
].keylen
= (keybuf_p
- keybuf
);
1115 /* Set a flag to indicate that we tried to read the key. */
1116 app
->app_local
->pk
[keyno
].read_done
= 1;
1123 #endif /* GNUPG_MAJOR_VERSION > 1 */
1127 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1128 This is used by the LEARN command. */
1130 send_keypair_info (app_t app
, ctrl_t ctrl
, int keyno
)
1132 gpg_error_t err
= 0;
1133 /* Note that GnuPG 1.x does not need this and it would be too time
1134 consuming to send it just for the fun of it. */
1135 #if GNUPG_MAJOR_VERSION > 1
1136 unsigned char grip
[20];
1141 err
= get_public_key (app
, keyno
);
1145 assert (keyno
>= 1 && keyno
<= 3);
1146 if (!app
->app_local
->pk
[keyno
-1].key
)
1147 goto leave
; /* No such key - ignore. */
1149 err
= keygrip_from_canon_sexp (app
->app_local
->pk
[keyno
-1].key
,
1150 app
->app_local
->pk
[keyno
-1].keylen
,
1155 for (i
=0; i
< 20; i
++)
1156 sprintf (gripstr
+i
*2, "%02X", grip
[i
]);
1158 sprintf (idbuf
, "OPENPGP.%d", keyno
);
1159 send_status_info (ctrl
, "KEYPAIRINFO",
1161 idbuf
, strlen (idbuf
),
1165 #endif /* GNUPG_MAJOR_VERSION > 1 */
1171 /* Handle the LEARN command for OpenPGP. */
1173 do_learn_status (app_t app
, ctrl_t ctrl
)
1175 do_getattr (app
, ctrl
, "EXTCAP");
1176 do_getattr (app
, ctrl
, "DISP-NAME");
1177 do_getattr (app
, ctrl
, "DISP-LANG");
1178 do_getattr (app
, ctrl
, "DISP-SEX");
1179 do_getattr (app
, ctrl
, "PUBKEY-URL");
1180 do_getattr (app
, ctrl
, "LOGIN-DATA");
1181 do_getattr (app
, ctrl
, "KEY-FPR");
1182 if (app
->card_version
> 0x0100)
1183 do_getattr (app
, ctrl
, "KEY-TIME");
1184 do_getattr (app
, ctrl
, "CA-FPR");
1185 do_getattr (app
, ctrl
, "CHV-STATUS");
1186 do_getattr (app
, ctrl
, "SIG-COUNTER");
1187 if (app
->app_local
->extcap
.private_dos
)
1189 do_getattr (app
, ctrl
, "PRIVATE-DO-1");
1190 do_getattr (app
, ctrl
, "PRIVATE-DO-2");
1192 do_getattr (app
, ctrl
, "PRIVATE-DO-3");
1194 do_getattr (app
, ctrl
, "PRIVATE-DO-4");
1196 send_keypair_info (app
, ctrl
, 1);
1197 send_keypair_info (app
, ctrl
, 2);
1198 send_keypair_info (app
, ctrl
, 3);
1203 /* Handle the READKEY command for OpenPGP. On success a canonical
1204 encoded S-expression with the public key will get stored at PK and
1205 its length (for assertions) at PKLEN; the caller must release that
1206 buffer. On error PK and PKLEN are not changed and an error code is
1209 do_readkey (app_t app
, const char *keyid
, unsigned char **pk
, size_t *pklen
)
1211 #if GNUPG_MAJOR_VERSION > 1
1216 if (!strcmp (keyid
, "OPENPGP.1"))
1218 else if (!strcmp (keyid
, "OPENPGP.2"))
1220 else if (!strcmp (keyid
, "OPENPGP.3"))
1223 return gpg_error (GPG_ERR_INV_ID
);
1225 err
= get_public_key (app
, keyno
);
1229 buf
= app
->app_local
->pk
[keyno
-1].key
;
1231 return gpg_error (GPG_ERR_NO_PUBKEY
);
1233 *pklen
= app
->app_local
->pk
[keyno
-1].keylen
;;
1236 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1242 /* Verify CHV2 if required. Depending on the configuration of the
1243 card CHV1 will also be verified. */
1245 verify_chv2 (app_t app
,
1246 gpg_error_t (*pincb
)(void*, const char *, char **),
1255 rc
= pincb (pincb_arg
, "PIN", &pinvalue
);
1258 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1262 if (strlen (pinvalue
) < 6)
1264 log_error (_("PIN for CHV%d is too short;"
1265 " minimum length is %d\n"), 2, 6);
1267 return gpg_error (GPG_ERR_BAD_PIN
);
1270 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
1273 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
1275 flush_cache_after_error (app
);
1280 if (!app
->did_chv1
&& !app
->force_chv1
)
1282 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
1283 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
1284 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
1287 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
1289 flush_cache_after_error (app
);
1299 /* Verify CHV3 if required. */
1301 verify_chv3 (app_t app
,
1302 gpg_error_t (*pincb
)(void*, const char *, char **),
1307 #if GNUPG_MAJOR_VERSION != 1
1308 if (!opt
.allow_admin
)
1310 log_info (_("access to admin commands is not configured\n"));
1311 return gpg_error (GPG_ERR_EACCES
);
1319 unsigned char *value
;
1322 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1323 if (!relptr
|| valuelen
< 7)
1325 log_error (_("error retrieving CHV status from card\n"));
1327 return gpg_error (GPG_ERR_CARD
);
1331 log_info (_("card is permanently locked!\n"));
1333 return gpg_error (GPG_ERR_BAD_PIN
);
1336 log_info(_("%d Admin PIN attempts remaining before card"
1337 " is permanently locked\n"), value
[6]);
1340 /* TRANSLATORS: Do not translate the "|A|" prefix but
1341 keep it at the start of the string. We need this elsewhere
1342 to get some infos on the string. */
1343 rc
= pincb (pincb_arg
, _("|A|Admin PIN"), &pinvalue
);
1346 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1350 if (strlen (pinvalue
) < 8)
1352 log_error (_("PIN for CHV%d is too short;"
1353 " minimum length is %d\n"), 3, 8);
1355 return gpg_error (GPG_ERR_BAD_PIN
);
1358 rc
= iso7816_verify (app
->slot
, 0x83, pinvalue
, strlen (pinvalue
));
1362 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc
));
1363 flush_cache_after_error (app
);
1372 /* Handle the SETATTR operation. All arguments are already basically
1375 do_setattr (app_t app
, const char *name
,
1376 gpg_error_t (*pincb
)(void*, const char *, char **),
1378 const unsigned char *value
, size_t valuelen
)
1388 { "DISP-NAME", 0x005B, 3 },
1389 { "LOGIN-DATA", 0x005E, 3, 2 },
1390 { "DISP-LANG", 0x5F2D, 3 },
1391 { "DISP-SEX", 0x5F35, 3 },
1392 { "PUBKEY-URL", 0x5F50, 3 },
1393 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1394 { "CA-FPR-1", 0x00CA, 3 },
1395 { "CA-FPR-2", 0x00CB, 3 },
1396 { "CA-FPR-3", 0x00CC, 3 },
1397 { "PRIVATE-DO-1", 0x0101, 2 },
1398 { "PRIVATE-DO-2", 0x0102, 3 },
1399 { "PRIVATE-DO-3", 0x0103, 2 },
1400 { "PRIVATE-DO-4", 0x0104, 3 },
1405 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
1407 if (!table
[idx
].name
)
1408 return gpg_error (GPG_ERR_INV_NAME
);
1410 switch (table
[idx
].need_chv
)
1413 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1416 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1424 /* Flush the cache before writing it, so that the next get operation
1425 will reread the data from the card and thus get synced in case of
1426 errors (e.g. data truncated by the card). */
1427 flush_cache_item (app
, table
[idx
].tag
);
1428 rc
= iso7816_put_data (app
->slot
, table
[idx
].tag
, value
, valuelen
);
1430 log_error ("failed to set `%s': %s\n", table
[idx
].name
, gpg_strerror (rc
));
1432 if (table
[idx
].special
== 1)
1433 app
->force_chv1
= (valuelen
&& *value
== 0);
1434 else if (table
[idx
].special
== 2)
1435 parse_login_data (app
);
1441 /* Handle the PASSWD command. */
1443 do_change_pin (app_t app
, ctrl_t ctrl
, const char *chvnostr
, int reset_mode
,
1444 gpg_error_t (*pincb
)(void*, const char *, char **),
1448 int chvno
= atoi (chvnostr
);
1451 if (reset_mode
&& chvno
== 3)
1453 rc
= gpg_error (GPG_ERR_INV_ID
);
1456 else if (reset_mode
|| chvno
== 3)
1458 /* we always require that the PIN is entered. */
1460 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1464 else if (chvno
== 1 || chvno
== 2)
1466 /* CHV1 and CVH2 should always have the same value, thus we
1468 int save_force
= app
->force_chv1
;
1470 app
->force_chv1
= 0;
1473 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1474 app
->force_chv1
= save_force
;
1480 rc
= gpg_error (GPG_ERR_INV_ID
);
1487 app
->did_chv1
= app
->did_chv2
= 0;
1489 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1490 keep it at the start of the string. We need this elsewhere
1491 to get some infos on the string. */
1492 rc
= pincb (pincb_arg
, chvno
== 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1496 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc
));
1502 rc
= iso7816_reset_retry_counter (app
->slot
, 0x81,
1503 pinvalue
, strlen (pinvalue
));
1505 rc
= iso7816_reset_retry_counter (app
->slot
, 0x82,
1506 pinvalue
, strlen (pinvalue
));
1510 if (chvno
== 1 || chvno
== 2)
1512 rc
= iso7816_change_reference_data (app
->slot
, 0x81, NULL
, 0,
1513 pinvalue
, strlen (pinvalue
));
1515 rc
= iso7816_change_reference_data (app
->slot
, 0x82, NULL
, 0,
1516 pinvalue
, strlen (pinvalue
));
1519 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
, NULL
, 0,
1520 pinvalue
, strlen (pinvalue
));
1524 flush_cache_after_error (app
);
1531 /* Check whether a key already exists. KEYIDX is the index of the key
1532 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1533 error returned if the key already exists. */
1535 does_key_exist (app_t app
, int keyidx
, int force
)
1537 const unsigned char *fpr
;
1538 unsigned char *buffer
;
1542 assert (keyidx
>=0 && keyidx
<= 2);
1544 if (iso7816_get_data (app
->slot
, 0x006E, &buffer
, &buflen
))
1546 log_error (_("error reading application data\n"));
1547 return gpg_error (GPG_ERR_GENERAL
);
1549 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
1552 log_error (_("error reading fingerprint DO\n"));
1554 return gpg_error (GPG_ERR_GENERAL
);
1557 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
1560 if (i
!=20 && !force
)
1562 log_error (_("key already exists\n"));
1563 return gpg_error (GPG_ERR_EEXIST
);
1566 log_info (_("existing key will be replaced\n"));
1568 log_info (_("generating new key\n"));
1574 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1575 canonical encoded S-expression with the secret key in KEYDATA and
1576 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1577 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1578 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1579 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1580 the pinentry callback. */
1582 do_writekey (app_t app
, ctrl_t ctrl
,
1583 const char *keyid
, unsigned int flags
,
1584 gpg_error_t (*pincb
)(void*, const char *, char **),
1586 const unsigned char *keydata
, size_t keydatalen
)
1589 int force
= (flags
& 1);
1591 const unsigned char *buf
, *tok
;
1592 size_t buflen
, toklen
;
1593 int depth
, last_depth1
, last_depth2
;
1594 const unsigned char *rsa_n
= NULL
;
1595 const unsigned char *rsa_e
= NULL
;
1596 const unsigned char *rsa_p
= NULL
;
1597 const unsigned char *rsa_q
= NULL
;
1598 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
1600 unsigned char *template = NULL
;
1602 size_t template_len
;
1603 unsigned char fprbuf
[20];
1606 if (!strcmp (keyid
, "OPENPGP.1"))
1608 else if (!strcmp (keyid
, "OPENPGP.2"))
1610 else if (!strcmp (keyid
, "OPENPGP.3"))
1613 return gpg_error (GPG_ERR_INV_ID
);
1615 err
= does_key_exist (app
, keyno
, force
);
1621 Parse the S-expression
1624 buflen
= keydatalen
;
1626 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1628 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1630 if (!tok
|| toklen
!= 11 || memcmp ("private-key", tok
, toklen
))
1634 else if (toklen
== 21 && !memcmp ("protected-private-key", tok
, toklen
))
1635 log_info ("protected-private-key passed to writekey\n");
1636 else if (toklen
== 20 && !memcmp ("shadowed-private-key", tok
, toklen
))
1637 log_info ("shadowed-private-key passed to writekey\n");
1638 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1641 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1643 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1645 if (!tok
|| toklen
!= 3 || memcmp ("rsa", tok
, toklen
))
1647 err
= gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO
);
1650 last_depth1
= depth
;
1651 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1652 && depth
&& depth
>= last_depth1
)
1656 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
1659 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1661 if (tok
&& toklen
== 1)
1663 const unsigned char **mpi
;
1668 case 'n': mpi
= &rsa_n
; mpi_len
= &rsa_n_len
; break;
1669 case 'e': mpi
= &rsa_e
; mpi_len
= &rsa_e_len
; break;
1670 case 'p': mpi
= &rsa_p
; mpi_len
= &rsa_p_len
; break;
1671 case 'q': mpi
= &rsa_q
; mpi_len
= &rsa_q_len
;break;
1672 default: mpi
= NULL
; mpi_len
= NULL
; break;
1676 err
= gpg_error (GPG_ERR_DUP_VALUE
);
1679 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1683 /* Strip off leading zero bytes and save. */
1684 for (;toklen
&& !*tok
; toklen
--, tok
++)
1690 /* Skip until end of list. */
1691 last_depth2
= depth
;
1692 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1693 && depth
&& depth
>= last_depth2
)
1698 /* Parse other attributes. */
1699 last_depth1
= depth
;
1700 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1701 && depth
&& depth
>= last_depth1
)
1705 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
1708 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1710 if (tok
&& toklen
== 10 && !memcmp ("created-at", tok
, toklen
))
1712 if ((err
= parse_sexp (&buf
,&buflen
,&depth
,&tok
,&toklen
)))
1716 for (created_at
=0; toklen
&& *tok
&& *tok
>= '0' && *tok
<= '9';
1718 created_at
= created_at
*10 + (*tok
- '0');
1721 /* Skip until end of list. */
1722 last_depth2
= depth
;
1723 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1724 && depth
&& depth
>= last_depth2
)
1731 /* Check that we have all parameters and that they match the card
1735 log_error (_("creation timestamp missing\n"));
1736 err
= gpg_error (GPG_ERR_INV_VALUE
);
1739 nbits
= rsa_n
? count_bits (rsa_n
, rsa_n_len
) : 0;
1742 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1743 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1746 nbits
= rsa_e
? count_bits (rsa_e
, rsa_e_len
) : 0;
1747 if (nbits
< 2 || nbits
> 32)
1749 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1751 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1754 nbits
= rsa_p
? count_bits (rsa_p
, rsa_p_len
) : 0;
1757 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1758 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1761 nbits
= rsa_q
? count_bits (rsa_q
, rsa_q_len
) : 0;
1764 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1765 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1770 /* Build the private key template as described in section 4.3.3.6 of
1771 the OpenPGP card specs:
1772 0xC0 <length> public exponent
1773 0xC1 <length> prime p
1774 0xC2 <length> prime q
1776 assert (rsa_e_len
<= 4);
1777 template_len
= (1 + 1 + 4
1779 + 1 + 1 + rsa_q_len
);
1780 template = tp
= xtrymalloc_secure (template_len
);
1783 err
= gpg_error_from_errno (errno
);
1788 memcpy (tp
, rsa_e
, rsa_e_len
);
1791 /* Right justify E. */
1792 memmove (tp
+4-rsa_e_len
, tp
, 4-rsa_e_len
);
1793 memset (tp
, 0, 4-rsa_e_len
);
1799 memcpy (tp
, rsa_p
, rsa_p_len
);
1804 memcpy (tp
, rsa_q
, rsa_q_len
);
1807 assert (tp
- template == template_len
);
1810 /* Obviously we need to remove the cached public key. */
1811 xfree (app
->app_local
->pk
[keyno
].key
);
1812 app
->app_local
->pk
[keyno
].key
= NULL
;
1813 app
->app_local
->pk
[keyno
].keylen
= 0;
1814 app
->app_local
->pk
[keyno
].read_done
= 0;
1816 /* Prepare for storing the key. */
1817 err
= verify_chv3 (app
, pincb
, pincb_arg
);
1821 /* Store the key. */
1822 err
= iso7816_put_data (app
->slot
,
1823 (app
->card_version
> 0x0007? 0xE0 : 0xE9) + keyno
,
1824 template, template_len
);
1827 log_error (_("failed to store the key: %s\n"), gpg_strerror (err
));
1831 err
= store_fpr (app
->slot
, keyno
, created_at
,
1832 rsa_n
, rsa_n_len
, rsa_e
, rsa_e_len
,
1833 fprbuf
, app
->card_version
);
1844 /* Handle the GENKEY command. */
1846 do_genkey (app_t app
, ctrl_t ctrl
, const char *keynostr
, unsigned int flags
,
1847 gpg_error_t (*pincb
)(void*, const char *, char **),
1852 unsigned char fprbuf
[20];
1853 const unsigned char *keydata
, *m
, *e
;
1854 unsigned char *buffer
= NULL
;
1855 size_t buflen
, keydatalen
, mlen
, elen
;
1857 int keyno
= atoi (keynostr
);
1858 int force
= (flags
& 1);
1861 if (keyno
< 1 || keyno
> 3)
1862 return gpg_error (GPG_ERR_INV_ID
);
1865 /* We flush the cache to increase the traffic before a key
1866 generation. This _might_ help a card to gather more entropy. */
1869 /* Obviously we need to remove the cached public key. */
1870 xfree (app
->app_local
->pk
[keyno
].key
);
1871 app
->app_local
->pk
[keyno
].key
= NULL
;
1872 app
->app_local
->pk
[keyno
].keylen
= 0;
1873 app
->app_local
->pk
[keyno
].read_done
= 0;
1875 /* Check whether a key already exists. */
1876 rc
= does_key_exist (app
, keyno
, force
);
1880 /* Prepare for key generation by verifying the ADmin PIN. */
1881 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1886 log_info (_("please wait while key is being generated ...\n"));
1887 start_at
= time (NULL
);
1888 rc
= iso7816_generate_keypair
1890 #warning key generation temporary replaced by reading an existing key.
1891 rc
= iso7816_read_public_key
1894 keyno
== 0? "\xB6" :
1895 keyno
== 1? "\xB8" : "\xA4",
1900 rc
= gpg_error (GPG_ERR_CARD
);
1901 log_error (_("generating key failed\n"));
1904 log_info (_("key generation completed (%d seconds)\n"),
1905 (int)(time (NULL
) - start_at
));
1906 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1909 rc
= gpg_error (GPG_ERR_CARD
);
1910 log_error (_("response does not contain the public key data\n"));
1914 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1917 rc
= gpg_error (GPG_ERR_CARD
);
1918 log_error (_("response does not contain the RSA modulus\n"));
1921 /* log_printhex ("RSA n:", m, mlen); */
1922 send_key_data (ctrl
, "n", m
, mlen
);
1924 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1927 rc
= gpg_error (GPG_ERR_CARD
);
1928 log_error (_("response does not contain the RSA public exponent\n"));
1931 /* log_printhex ("RSA e:", e, elen); */
1932 send_key_data (ctrl
, "e", e
, elen
);
1934 created_at
= gnupg_get_time ();
1935 sprintf (numbuf
, "%lu", (unsigned long)created_at
);
1936 send_status_info (ctrl
, "KEY-CREATED-AT",
1937 numbuf
, (size_t)strlen(numbuf
), NULL
, 0);
1939 rc
= store_fpr (app
->slot
, keyno
, (u32
)created_at
,
1940 m
, mlen
, e
, elen
, fprbuf
, app
->card_version
);
1943 send_fpr_if_not_null (ctrl
, "KEY-FPR", -1, fprbuf
);
1952 static unsigned long
1953 convert_sig_counter_value (const unsigned char *value
, size_t valuelen
)
1958 ul
= (value
[0] << 16) | (value
[1] << 8) | value
[2];
1961 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1967 static unsigned long
1968 get_sig_counter (app_t app
)
1971 unsigned char *value
;
1975 relptr
= get_one_do (app
, 0x0093, &value
, &valuelen
, NULL
);
1978 ul
= convert_sig_counter_value (value
, valuelen
);
1984 compare_fingerprint (app_t app
, int keyno
, unsigned char *sha1fpr
)
1986 const unsigned char *fpr
;
1987 unsigned char *buffer
;
1991 assert (keyno
>= 1 && keyno
<= 3);
1993 rc
= get_cached_data (app
, 0x006E, &buffer
, &buflen
, 0);
1996 log_error (_("error reading application data\n"));
1997 return gpg_error (GPG_ERR_GENERAL
);
1999 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2000 if (!fpr
|| n
!= 60)
2003 log_error (_("error reading fingerprint DO\n"));
2004 return gpg_error (GPG_ERR_GENERAL
);
2006 fpr
+= (keyno
-1)*20;
2007 for (i
=0; i
< 20; i
++)
2008 if (sha1fpr
[i
] != fpr
[i
])
2011 return gpg_error (GPG_ERR_WRONG_SECKEY
);
2018 /* If a fingerprint has been specified check it against the one on
2019 the card. This is allows for a meaningful error message in case
2020 the key on the card has been replaced but the shadow information
2021 known to gpg was not updated. If there is no fingerprint we
2022 assume that this is okay. */
2024 check_against_given_fingerprint (app_t app
, const char *fpr
, int keyno
)
2026 unsigned char tmp
[20];
2030 for (s
=fpr
, n
=0; hexdigitp (s
); s
++, n
++)
2033 return gpg_error (GPG_ERR_INV_ID
);
2037 return gpg_error (GPG_ERR_INV_ID
);
2039 for (s
=fpr
, n
=0; n
< 20; s
+= 2, n
++)
2040 tmp
[n
] = xtoi_2 (s
);
2041 return compare_fingerprint (app
, keyno
, tmp
);
2046 /* Compute a digital signature on INDATA which is expected to be the
2047 raw message digest. For this application the KEYIDSTR consists of
2048 the serialnumber and the fingerprint delimited by a slash.
2050 Note that this fucntion may return the error code
2051 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2052 not match the one required for the requested action (e.g. the
2053 serial number does not match). */
2055 do_sign (app_t app
, const char *keyidstr
, int hashalgo
,
2056 gpg_error_t (*pincb
)(void*, const char *, char **),
2058 const void *indata
, size_t indatalen
,
2059 unsigned char **outdata
, size_t *outdatalen
)
2061 static unsigned char sha1_prefix
[15] = /* Object ID is 1.3.14.3.2.26 */
2062 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2063 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2064 static unsigned char rmd160_prefix
[15] = /* Object ID is 1.3.36.3.2.1 */
2065 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2066 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2068 unsigned char data
[35];
2069 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2072 const char *fpr
= NULL
;
2073 unsigned long sigcount
;
2075 if (!keyidstr
|| !*keyidstr
)
2076 return gpg_error (GPG_ERR_INV_VALUE
);
2077 if (indatalen
== 20)
2079 else if (indatalen
== (15 + 20) && hashalgo
== GCRY_MD_SHA1
2080 && !memcmp (indata
, sha1_prefix
, 15))
2082 else if (indatalen
== (15 + 20) && hashalgo
== GCRY_MD_RMD160
2083 && !memcmp (indata
, rmd160_prefix
, 15))
2087 log_error(_("card does not support digest algorithm %s\n"),
2088 digest_algo_to_string(hashalgo
));
2089 return gpg_error (GPG_ERR_INV_VALUE
);
2092 /* Check whether an OpenPGP card of any version has been requested. */
2093 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2094 return gpg_error (GPG_ERR_INV_ID
);
2096 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2099 return gpg_error (GPG_ERR_INV_ID
);
2101 ; /* no fingerprint given: we allow this for now. */
2105 return gpg_error (GPG_ERR_INV_ID
);
2107 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2108 tmp_sn
[n
] = xtoi_2 (s
);
2110 if (app
->serialnolen
!= 16)
2111 return gpg_error (GPG_ERR_INV_CARD
);
2112 if (memcmp (app
->serialno
, tmp_sn
, 16))
2113 return gpg_error (GPG_ERR_WRONG_CARD
);
2115 /* If a fingerprint has been specified check it against the one on
2116 the card. This is allows for a meaningful error message in case
2117 the key on the card has been replaced but the shadow information
2118 known to gpg was not updated. If there is no fingerprint, gpg
2119 will detect a bogus signature anyway due to the
2120 verify-after-signing feature. */
2121 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 1) : 0;
2125 if (hashalgo
== GCRY_MD_SHA1
)
2126 memcpy (data
, sha1_prefix
, 15);
2127 else if (hashalgo
== GCRY_MD_RMD160
)
2128 memcpy (data
, rmd160_prefix
, 15);
2130 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM
);
2131 memcpy (data
+15, indata
, indatalen
);
2133 sigcount
= get_sig_counter (app
);
2134 log_info (_("signatures created so far: %lu\n"), sigcount
);
2136 if (!app
->did_chv1
|| app
->force_chv1
)
2142 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
2144 prompt
= malloc (strlen (PROMPTSTRING
) + 50);
2146 return gpg_error_from_errno (errno
);
2147 sprintf (prompt
, PROMPTSTRING
, sigcount
);
2148 rc
= pincb (pincb_arg
, prompt
, &pinvalue
);
2154 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
2158 if (strlen (pinvalue
) < 6)
2160 log_error (_("PIN for CHV%d is too short;"
2161 " minimum length is %d\n"), 1, 6);
2163 return gpg_error (GPG_ERR_BAD_PIN
);
2166 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
2169 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
2171 flush_cache_after_error (app
);
2177 /* We should also verify CHV2. */
2178 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
2179 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
2180 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
2183 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
2185 flush_cache_after_error (app
);
2193 rc
= iso7816_compute_ds (app
->slot
, data
, 35, outdata
, outdatalen
);
2197 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2198 on INDATA which is expected to be the raw message digest. For this
2199 application the KEYIDSTR consists of the serialnumber and the
2200 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2203 Note that this fucntion may return the error code
2204 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2205 not match the one required for the requested action (e.g. the
2206 serial number does not match). */
2208 do_auth (app_t app
, const char *keyidstr
,
2209 gpg_error_t (*pincb
)(void*, const char *, char **),
2211 const void *indata
, size_t indatalen
,
2212 unsigned char **outdata
, size_t *outdatalen
)
2215 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2218 const char *fpr
= NULL
;
2220 if (!keyidstr
|| !*keyidstr
)
2221 return gpg_error (GPG_ERR_INV_VALUE
);
2222 if (indatalen
> 50) /* For a 1024 bit key. */
2223 return gpg_error (GPG_ERR_INV_VALUE
);
2225 /* Check whether an OpenPGP card of any version has been requested. */
2226 if (!strcmp (keyidstr
, "OPENPGP.3"))
2228 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2229 return gpg_error (GPG_ERR_INV_ID
);
2232 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2235 return gpg_error (GPG_ERR_INV_ID
);
2237 ; /* no fingerprint given: we allow this for now. */
2241 return gpg_error (GPG_ERR_INV_ID
);
2243 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2244 tmp_sn
[n
] = xtoi_2 (s
);
2246 if (app
->serialnolen
!= 16)
2247 return gpg_error (GPG_ERR_INV_CARD
);
2248 if (memcmp (app
->serialno
, tmp_sn
, 16))
2249 return gpg_error (GPG_ERR_WRONG_CARD
);
2252 /* If a fingerprint has been specified check it against the one on
2253 the card. This is allows for a meaningful error message in case
2254 the key on the card has been replaced but the shadow information
2255 known to gpg was not updated. If there is no fingerprint, gpg
2256 will detect a bogus signature anyway due to the
2257 verify-after-signing feature. */
2258 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 3) : 0;
2262 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
2264 rc
= iso7816_internal_authenticate (app
->slot
, indata
, indatalen
,
2265 outdata
, outdatalen
);
2271 do_decipher (app_t app
, const char *keyidstr
,
2272 gpg_error_t (*pincb
)(void*, const char *, char **),
2274 const void *indata
, size_t indatalen
,
2275 unsigned char **outdata
, size_t *outdatalen
)
2278 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2281 const char *fpr
= NULL
;
2283 if (!keyidstr
|| !*keyidstr
|| !indatalen
)
2284 return gpg_error (GPG_ERR_INV_VALUE
);
2286 /* Check whether an OpenPGP card of any version has been requested. */
2287 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2288 return gpg_error (GPG_ERR_INV_ID
);
2290 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2293 return gpg_error (GPG_ERR_INV_ID
);
2295 ; /* no fingerprint given: we allow this for now. */
2299 return gpg_error (GPG_ERR_INV_ID
);
2301 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2302 tmp_sn
[n
] = xtoi_2 (s
);
2304 if (app
->serialnolen
!= 16)
2305 return gpg_error (GPG_ERR_INV_CARD
);
2306 if (memcmp (app
->serialno
, tmp_sn
, 16))
2307 return gpg_error (GPG_ERR_WRONG_CARD
);
2309 /* If a fingerprint has been specified check it against the one on
2310 the card. This is allows for a meaningful error message in case
2311 the key on the card has been replaced but the shadow information
2312 known to gpg was not updated. If there is no fingerprint, the
2313 decryption will won't produce the right plaintext anyway. */
2314 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 2) : 0;
2318 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
2320 rc
= iso7816_decipher (app
->slot
, indata
, indatalen
, 0,
2321 outdata
, outdatalen
);
2326 /* Perform a simple verify operation for CHV1 and CHV2, so that
2327 further operations won't ask for CHV2 and it is possible to do a
2328 cheap check on the PIN: If there is something wrong with the PIN
2329 entry system, only the regular CHV will get blocked and not the
2330 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2331 optional fingerprint part will be ignored.
2333 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2334 the "[CHV3]" being a literal string: The Admin Pin is checked if
2335 and only if the retry counter is still at 3. */
2337 do_check_pin (app_t app
, const char *keyidstr
,
2338 gpg_error_t (*pincb
)(void*, const char *, char **),
2341 unsigned char tmp_sn
[20];
2346 if (!keyidstr
|| !*keyidstr
)
2347 return gpg_error (GPG_ERR_INV_VALUE
);
2349 /* Check whether an OpenPGP card of any version has been requested. */
2350 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2351 return gpg_error (GPG_ERR_INV_ID
);
2353 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2356 return gpg_error (GPG_ERR_INV_ID
);
2358 ; /* No fingerprint given: we allow this for now. */
2360 ; /* We ignore a fingerprint. */
2361 else if (!strcmp (s
, "[CHV3]") )
2364 return gpg_error (GPG_ERR_INV_ID
);
2366 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2367 tmp_sn
[n
] = xtoi_2 (s
);
2369 if (app
->serialnolen
!= 16)
2370 return gpg_error (GPG_ERR_INV_CARD
);
2371 if (memcmp (app
->serialno
, tmp_sn
, 16))
2372 return gpg_error (GPG_ERR_WRONG_CARD
);
2374 /* Yes, there is a race conditions: The user might pull the card
2375 right here and we won't notice that. However this is not a
2376 problem and the check above is merely for a graceful failure
2377 between operations. */
2382 unsigned char *value
;
2386 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
2387 if (!relptr
|| valuelen
< 7)
2389 log_error (_("error retrieving CHV status from card\n"));
2391 return gpg_error (GPG_ERR_CARD
);
2398 log_info (_("card is permanently locked!\n"));
2399 return gpg_error (GPG_ERR_BAD_PIN
);
2401 else if (value
[6] < 3)
2403 log_info (_("verification of Admin PIN is currently prohibited "
2404 "through this command\n"));
2405 return gpg_error (GPG_ERR_GENERAL
);
2408 app
->did_chv3
= 0; /* Force verification. */
2409 return verify_chv3 (app
, pincb
, pincb_arg
);
2412 return verify_chv2 (app
, pincb
, pincb_arg
);
2418 /* Select the OpenPGP application on the card in SLOT. This function
2419 must be used before any other OpenPGP application functions. */
2421 app_select_openpgp (app_t app
)
2423 static char const aid
[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2424 int slot
= app
->slot
;
2426 unsigned char *buffer
;
2430 rc
= iso7816_select_application (slot
, aid
, sizeof aid
);
2433 unsigned int manufacturer
;
2435 app
->apptype
= "OPENPGP";
2440 app
->app_local
= NULL
;
2442 /* The OpenPGP card returns the serial number as part of the
2443 AID; because we prefer to use OpenPGP serial numbers, we
2444 replace a possibly already set one from a EF.GDO with this
2445 one. Note, that for current OpenPGP cards, no EF.GDO exists
2446 and thus it won't matter at all. */
2447 rc
= iso7816_get_data (slot
, 0x004F, &buffer
, &buflen
);
2453 log_printhex ("", buffer
, buflen
);
2456 app
->card_version
= buffer
[6] << 8;
2457 app
->card_version
|= buffer
[7];
2458 manufacturer
= (buffer
[8]<<8 | buffer
[9]);
2460 xfree (app
->serialno
);
2461 app
->serialno
= buffer
;
2462 app
->serialnolen
= buflen
;
2464 app
->app_local
= xtrycalloc (1, sizeof *app
->app_local
);
2465 if (!app
->app_local
)
2467 rc
= gpg_error (gpg_err_code_from_errno (errno
));
2471 relptr
= get_one_do (app
, 0x00C4, &buffer
, &buflen
, NULL
);
2474 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2475 "CHV Status Bytes");
2478 app
->force_chv1
= (buflen
&& *buffer
== 0);
2481 relptr
= get_one_do (app
, 0x00C0, &buffer
, &buflen
, NULL
);
2484 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2485 "Extended Capability Flags" );
2490 app
->app_local
->extcap
.get_challenge
= !!(*buffer
& 0x40);
2491 app
->app_local
->extcap
.key_import
= !!(*buffer
& 0x20);
2492 app
->app_local
->extcap
.change_force_chv
= !!(*buffer
& 0x10);
2493 app
->app_local
->extcap
.private_dos
= !!(*buffer
& 0x08);
2497 /* Some of the first cards accidently don't set the
2498 CHANGE_FORCE_CHV bit but allow it anyway. */
2499 if (app
->card_version
<= 0x0100 && manufacturer
== 1)
2500 app
->app_local
->extcap
.change_force_chv
= 1;
2502 parse_login_data (app
);
2504 if (opt
.verbose
> 1)
2507 app
->fnc
.deinit
= do_deinit
;
2508 app
->fnc
.learn_status
= do_learn_status
;
2509 app
->fnc
.readkey
= do_readkey
;
2510 app
->fnc
.getattr
= do_getattr
;
2511 app
->fnc
.setattr
= do_setattr
;
2512 app
->fnc
.writekey
= do_writekey
;
2513 app
->fnc
.genkey
= do_genkey
;
2514 app
->fnc
.sign
= do_sign
;
2515 app
->fnc
.auth
= do_auth
;
2516 app
->fnc
.decipher
= do_decipher
;
2517 app
->fnc
.change_pin
= do_change_pin
;
2518 app
->fnc
.check_pin
= do_check_pin
;