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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
31 #if GNUPG_MAJOR_VERSION == 1
32 /* This is used with GnuPG version < 1.9. The code has been source
33 copied from the current GnuPG >= 1.9 and is maintained over
40 #else /* GNUPG_MAJOR_VERSION != 1 */
42 #endif /* GNUPG_MAJOR_VERSION != 1 */
46 #include "app-common.h"
53 int get_from
; /* Constructed DO with this DO or 0 for direct access. */
57 int get_immediate_in_v11
; /* Enable a hack to bypass the cache of
58 this data object if it is used in 1.1
59 and later versions of the card. This
60 does not work with composite DO and is
61 currently only useful for the CHV
65 { 0x005E, 0, 0, 1, 0, 0, 0, "Login Data" },
66 { 0x5F50, 0, 0, 0, 0, 0, 0, "URL" },
67 { 0x0065, 1, 0, 1, 0, 0, 0, "Cardholder Related Data"},
68 { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
69 { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
70 { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
71 { 0x006E, 1, 0, 1, 0, 0, 0, "Application Related Data" },
72 { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
73 { 0x0073, 1, 0, 1, 0, 0, 0, "Discretionary Data Objects" },
74 { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
75 { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
76 { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
77 { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
78 { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
79 { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
80 { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
81 { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
82 { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
83 { 0x007A, 1, 0, 1, 0, 0, 0, "Security Support Template" },
84 { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
85 { 0x0101, 0, 0, 0, 0, 0, 0, "Private DO 1"},
86 { 0x0102, 0, 0, 0, 0, 0, 0, "Private DO 2"},
87 { 0x0103, 0, 0, 0, 0, 0, 0, "Private DO 3"},
88 { 0x0104, 0, 0, 0, 0, 0, 0, "Private DO 4"},
93 /* One cache item for DOs. */
98 unsigned char data
[1];
102 /* Object with application (i.e. OpenPGP card) specific data. */
104 /* A linked list with cached DOs. */
105 struct cache_s
*cache
;
107 /* Keep track of the public keys. */
110 int read_done
; /* True if we have at least tried to read them. */
111 unsigned char *key
; /* This is a malloced buffer with a canonical
112 encoded S-expression encoding a public
113 key. Might be NULL if key is not
115 size_t keylen
; /* The length of the above S-expression. Thsi
116 is usullay only required for corss checks
117 because the length of an S-expression is
118 implicitly available. */
121 /* Keep track of card capabilities. */
124 unsigned int get_challenge
:1;
125 unsigned int key_import
:1;
126 unsigned int change_force_chv
:1;
127 unsigned int private_dos
:1;
130 /* Flags used to control the application. */
133 unsigned int no_sync
:1; /* Do not sync CHV1 and CHV2 */
134 unsigned int def_chv2
:1; /* Use 123456 for CHV2. */
140 /***** Local prototypes *****/
141 static unsigned long convert_sig_counter_value (const unsigned char *value
,
143 static unsigned long get_sig_counter (app_t app
);
151 do_deinit (app_t app
)
153 if (app
&& app
->app_local
)
155 struct cache_s
*c
, *c2
;
158 for (c
= app
->app_local
->cache
; c
; c
= c2
)
164 for (i
=0; i
< DIM (app
->app_local
->pk
); i
++)
166 xfree (app
->app_local
->pk
[i
].key
);
167 app
->app_local
->pk
[i
].read_done
= 0;
169 xfree (app
->app_local
);
170 app
->app_local
= NULL
;
175 /* Wrapper around iso7816_get_data which first tries to get the data
176 from the cache. With GET_IMMEDIATE passed as true, the cache is
179 get_cached_data (app_t app
, int tag
,
180 unsigned char **result
, size_t *resultlen
,
194 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
199 p
= xtrymalloc (c
->length
);
201 return gpg_error (gpg_err_code_from_errno (errno
));
202 memcpy (p
, c
->data
, c
->length
);
206 *resultlen
= c
->length
;
212 err
= iso7816_get_data (app
->slot
, tag
, &p
, &len
);
218 /* Check whether we should cache this object. */
222 for (i
=0; data_objects
[i
].tag
; i
++)
223 if (data_objects
[i
].tag
== tag
)
225 if (data_objects
[i
].dont_cache
)
230 /* Okay, cache it. */
231 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
232 assert (c
->tag
!= tag
);
234 c
= xtrymalloc (sizeof *c
+ len
);
237 memcpy (c
->data
, p
, len
);
240 c
->next
= app
->app_local
->cache
;
241 app
->app_local
->cache
= c
;
247 /* Remove DO at TAG from the cache. */
249 flush_cache_item (app_t app
, int tag
)
251 struct cache_s
*c
, *cprev
;
257 for (c
=app
->app_local
->cache
, cprev
=NULL
; c
; cprev
=c
, c
= c
->next
)
261 cprev
->next
= c
->next
;
263 app
->app_local
->cache
= c
->next
;
266 for (c
=app
->app_local
->cache
; c
; c
= c
->next
)
268 assert (c
->tag
!= tag
); /* Oops: duplicated entry. */
273 /* Try again if we have an outer tag. */
274 for (i
=0; data_objects
[i
].tag
; i
++)
275 if (data_objects
[i
].tag
== tag
&& data_objects
[i
].get_from
276 && data_objects
[i
].get_from
!= tag
)
277 flush_cache_item (app
, data_objects
[i
].get_from
);
280 /* Flush all entries from the cache which might be out of sync after
283 flush_cache_after_error (app_t app
)
287 for (i
=0; data_objects
[i
].tag
; i
++)
288 if (data_objects
[i
].flush_on_error
)
289 flush_cache_item (app
, data_objects
[i
].tag
);
293 /* Flush the entire cache. */
295 flush_cache (app_t app
)
297 if (app
&& app
->app_local
)
299 struct cache_s
*c
, *c2
;
301 for (c
= app
->app_local
->cache
; c
; c
= c2
)
306 app
->app_local
->cache
= NULL
;
311 /* Get the DO identified by TAG from the card in SLOT and return a
312 buffer with its content in RESULT and NBYTES. The return value is
313 NULL if not found or a pointer which must be used to release the
314 buffer holding value. */
316 get_one_do (app_t app
, int tag
, unsigned char **result
, size_t *nbytes
,
320 unsigned char *buffer
;
322 unsigned char *value
;
332 for (i
=0; data_objects
[i
].tag
&& data_objects
[i
].tag
!= tag
; i
++)
335 if (app
->card_version
> 0x0100 && data_objects
[i
].get_immediate_in_v11
)
337 rc
= iso7816_get_data (app
->slot
, tag
, &buffer
, &buflen
);
350 if (data_objects
[i
].tag
&& data_objects
[i
].get_from
)
352 rc
= get_cached_data (app
, data_objects
[i
].get_from
,
354 (data_objects
[i
].dont_cache
355 || data_objects
[i
].get_immediate_in_v11
));
358 const unsigned char *s
;
360 s
= find_tlv_unchecked (buffer
, buflen
, tag
, &valuelen
);
362 value
= NULL
; /* not found */
363 else if (valuelen
> buflen
- (s
- buffer
))
365 log_error ("warning: constructed DO too short\n");
367 xfree (buffer
); buffer
= NULL
;
370 value
= buffer
+ (s
- buffer
);
374 if (!value
) /* Not in a constructed DO, try simple. */
376 rc
= get_cached_data (app
, tag
, &buffer
, &buflen
,
377 (data_objects
[i
].dont_cache
378 || data_objects
[i
].get_immediate_in_v11
));
398 dump_all_do (int slot
)
401 unsigned char *buffer
;
404 for (i
=0; data_objects
[i
].tag
; i
++)
406 if (data_objects
[i
].get_from
)
409 rc
= iso7816_get_data (slot
, data_objects
[i
].tag
, &buffer
, &buflen
);
410 if (gpg_err_code (rc
) == GPG_ERR_NO_OBJ
)
413 log_info ("DO `%s' not available: %s\n",
414 data_objects
[i
].desc
, gpg_strerror (rc
));
417 if (data_objects
[i
].binary
)
419 log_info ("DO `%s': ", data_objects
[i
].desc
);
420 log_printhex ("", buffer
, buflen
);
423 log_info ("DO `%s': `%.*s'\n",
424 data_objects
[i
].desc
,
425 (int)buflen
, buffer
); /* FIXME: sanitize */
427 if (data_objects
[i
].constructed
)
429 for (j
=0; data_objects
[j
].tag
; j
++)
431 const unsigned char *value
;
434 if (j
==i
|| data_objects
[i
].tag
!= data_objects
[j
].get_from
)
436 value
= find_tlv_unchecked (buffer
, buflen
,
437 data_objects
[j
].tag
, &valuelen
);
440 else if (valuelen
> buflen
- (value
- buffer
))
441 log_error ("warning: constructed DO too short\n");
444 if (data_objects
[j
].binary
)
446 log_info ("DO `%s': ", data_objects
[j
].desc
);
447 log_printhex ("", value
, valuelen
);
450 log_info ("DO `%s': `%.*s'\n",
451 data_objects
[j
].desc
,
452 (int)valuelen
, value
); /* FIXME: sanitize */
457 xfree (buffer
); buffer
= NULL
;
462 /* Count the number of bits, assuming the A represents an unsigned big
463 integer of length LEN bytes. */
465 count_bits (const unsigned char *a
, size_t len
)
467 unsigned int n
= len
* 8;
470 for (; len
&& !*a
; len
--, a
++, n
-=8)
474 for (i
=7; i
&& !(*a
& (1<<i
)); i
--)
480 /* GnuPG makes special use of the login-data DO, this fucntion parses
481 the login data to store the flags for later use. It may be called
482 at any time and should be called after changing the login-data DO.
484 Everything up to a LF is considered a mailbox or account name. If
485 the first LF is followed by DC4 (0x14) control sequence are
486 expected up to the next LF. Control sequences are separated by FS
487 (0x28) and consist of key=value pairs. There is one key defined:
491 Were FLAGS is a plain hexadecimal number representing flag values.
492 The lsb is here the rightmost bit. Defined flags bits are:
494 Bit 0 = CHV1 and CHV2 are not syncronized
495 Bit 1 = CHV2 has been been set to the default PIN of "123456"
496 (this implies that bit 0 is also set).
500 parse_login_data (app_t app
)
502 unsigned char *buffer
, *p
;
507 app
->app_local
->flags
.no_sync
= 0;
508 app
->app_local
->flags
.def_chv2
= 0;
511 relptr
= get_one_do (app
, 0x005E, &buffer
, &buflen
, NULL
);
514 for (; buflen
; buflen
--, buffer
++)
517 if (buflen
< 2 || buffer
[1] != '\x14')
518 return; /* No control sequences. */
525 if (buflen
> 1 && *buffer
== 'F' && buffer
[1] == '=')
527 /* Flags control sequence found. */
530 /* For now we are only interested in the last digit, so skip
531 any leading digits but bail out on invalid characters. */
532 for (p
=buffer
+2, len
= buflen
-2; len
&& hexdigitp (p
); p
++, len
--)
533 lastdig
= xtoi_1 (p
);
534 if (len
&& !(*p
== '\n' || *p
== '\x18'))
535 goto next
; /* Invalid characters in field. */
536 app
->app_local
->flags
.no_sync
= !!(lastdig
& 1);
537 app
->app_local
->flags
.def_chv2
= (lastdig
& 3) == 3;
540 for (; buflen
&& *buffer
!= '\x18'; buflen
--, buffer
++)
549 /* Note, that FPR must be at least 20 bytes. */
551 store_fpr (int slot
, int keynumber
, u32 timestamp
,
552 const unsigned char *m
, size_t mlen
,
553 const unsigned char *e
, size_t elen
,
554 unsigned char *fpr
, unsigned int card_version
)
556 unsigned int n
, nbits
;
557 unsigned char *buffer
, *p
;
560 for (; mlen
&& !*m
; mlen
--, m
++) /* strip leading zeroes */
562 for (; elen
&& !*e
; elen
--, e
++) /* strip leading zeroes */
565 n
= 6 + 2 + mlen
+ 2 + elen
;
566 p
= buffer
= xtrymalloc (3 + n
);
568 return gpg_error_from_errno (errno
);
570 *p
++ = 0x99; /* ctb */
571 *p
++ = n
>> 8; /* 2 byte length header */
573 *p
++ = 4; /* key packet version */
574 *p
++ = timestamp
>> 24;
575 *p
++ = timestamp
>> 16;
576 *p
++ = timestamp
>> 8;
579 nbits
= count_bits (m
, mlen
);
582 memcpy (p
, m
, mlen
); p
+= mlen
;
583 nbits
= count_bits (e
, elen
);
586 memcpy (p
, e
, elen
); p
+= elen
;
588 gcry_md_hash_buffer (GCRY_MD_SHA1
, fpr
, buffer
, n
+3);
592 rc
= iso7816_put_data (slot
, (card_version
> 0x0007? 0xC7 : 0xC6)
593 + keynumber
, fpr
, 20);
595 log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc
));
597 if (!rc
&& card_version
> 0x0100)
599 unsigned char buf
[4];
601 buf
[0] = timestamp
>> 24;
602 buf
[1] = timestamp
>> 16;
603 buf
[2] = timestamp
>> 8;
606 rc
= iso7816_put_data (slot
, 0xCE + keynumber
, buf
, 4);
608 log_error (_("failed to store the creation date: %s\n"),
617 send_fpr_if_not_null (ctrl_t ctrl
, const char *keyword
,
618 int number
, const unsigned char *fpr
)
624 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
627 return; /* All zero. */
628 for (i
=0; i
< 20; i
++)
629 sprintf (buf
+2*i
, "%02X", fpr
[i
]);
631 *numbuf
= 0; /* Don't print the key number */
633 sprintf (numbuf
, "%d", number
);
634 send_status_info (ctrl
, keyword
,
635 numbuf
, (size_t)strlen(numbuf
),
636 buf
, (size_t)strlen (buf
), NULL
, 0);
640 send_fprtime_if_not_null (ctrl_t ctrl
, const char *keyword
,
641 int number
, const unsigned char *stamp
)
643 char numbuf1
[50], numbuf2
[50];
646 value
= (stamp
[0] << 24) | (stamp
[1]<<16) | (stamp
[2]<<8) | stamp
[3];
649 sprintf (numbuf1
, "%d", number
);
650 sprintf (numbuf2
, "%lu", value
);
651 send_status_info (ctrl
, keyword
,
652 numbuf1
, (size_t)strlen(numbuf1
),
653 numbuf2
, (size_t)strlen(numbuf2
), NULL
, 0);
657 send_key_data (ctrl_t ctrl
, const char *name
,
658 const unsigned char *a
, size_t alen
)
660 char *p
, *buf
= xmalloc (alen
*2+1);
662 for (p
=buf
; alen
; a
++, alen
--, p
+= 2)
663 sprintf (p
, "%02X", *a
);
665 send_status_info (ctrl
, "KEY-DATA",
666 name
, (size_t)strlen(name
),
667 buf
, (size_t)strlen (buf
),
672 /* Implement the GETATTR command. This is similar to the LEARN
673 command but returns just one value via the status interface. */
675 do_getattr (app_t app
, ctrl_t ctrl
, const char *name
)
682 { "DISP-NAME", 0x005B },
683 { "LOGIN-DATA", 0x005E },
684 { "DISP-LANG", 0x5F2D },
685 { "DISP-SEX", 0x5F35 },
686 { "PUBKEY-URL", 0x5F50 },
687 { "KEY-FPR", 0x00C5, 3 },
688 { "KEY-TIME", 0x00CD, 4 },
689 { "CA-FPR", 0x00C6, 3 },
690 { "CHV-STATUS", 0x00C4, 1 },
691 { "SIG-COUNTER", 0x0093, 2 },
692 { "SERIALNO", 0x004F, -1 },
694 { "EXTCAP", 0x0000, -2 },
695 { "PRIVATE-DO-1", 0x0101 },
696 { "PRIVATE-DO-2", 0x0102 },
697 { "PRIVATE-DO-3", 0x0103 },
698 { "PRIVATE-DO-4", 0x0104 },
699 { "$AUTHKEYID", 0x0000, -3 },
700 { "$DISPSERIALNO",0x0000, -4 },
705 unsigned char *value
;
708 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
710 if (!table
[idx
].name
)
711 return gpg_error (GPG_ERR_INV_NAME
);
713 if (table
[idx
].special
== -1)
715 /* The serial number is very special. We could have used the
716 AID DO to retrieve it, but we have it already in the app
717 context and the stamp argument is required anyway which we
718 can't by other means. The AID DO is available anyway but not
724 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
726 sprintf (tmp
, "%lu", (unsigned long)stamp
);
727 send_status_info (ctrl
, "SERIALNO",
728 serial
, strlen (serial
),
735 if (table
[idx
].special
== -2)
739 sprintf (tmp
, "gc=%d ki=%d fc=%d pd=%d",
740 app
->app_local
->extcap
.get_challenge
,
741 app
->app_local
->extcap
.key_import
,
742 app
->app_local
->extcap
.change_force_chv
,
743 app
->app_local
->extcap
.private_dos
);
744 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
747 if (table
[idx
].special
== -3)
749 char const tmp
[] = "OPENPGP.3";
750 send_status_info (ctrl
, table
[idx
].name
, tmp
, strlen (tmp
), NULL
, 0);
753 if (table
[idx
].special
== -4)
758 if (!app_get_serial_and_stamp (app
, &serial
, &stamp
))
760 if (strlen (serial
) > 16+12)
762 send_status_info (ctrl
, table
[idx
].name
, serial
+16, 12, NULL
, 0);
768 return gpg_error (GPG_ERR_INV_NAME
);
771 relptr
= get_one_do (app
, table
[idx
].tag
, &value
, &valuelen
, &rc
);
774 if (table
[idx
].special
== 1)
778 for (i
=0,*numbuf
=0; i
< valuelen
&& i
< 7; i
++)
779 sprintf (numbuf
+strlen (numbuf
), " %d", value
[i
]);
780 send_status_info (ctrl
, table
[idx
].name
,
781 numbuf
, strlen (numbuf
), NULL
, 0);
783 else if (table
[idx
].special
== 2)
787 sprintf (numbuf
, "%lu", convert_sig_counter_value (value
, valuelen
));
788 send_status_info (ctrl
, table
[idx
].name
,
789 numbuf
, strlen (numbuf
), NULL
, 0);
791 else if (table
[idx
].special
== 3)
794 for (i
=0; i
< 3; i
++)
795 send_fpr_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*20);
797 else if (table
[idx
].special
== 4)
800 for (i
=0; i
< 3; i
++)
801 send_fprtime_if_not_null (ctrl
, table
[idx
].name
, i
+1, value
+i
*4);
804 send_status_info (ctrl
, table
[idx
].name
, value
, valuelen
, NULL
, 0);
811 /* Retrieve the fingerprint from the card inserted in SLOT and write
812 the according hex representation to FPR. Caller must have provide
813 a buffer at FPR of least 41 bytes. Returns 0 on success or an
815 #if GNUPG_MAJOR_VERSION > 1
817 retrieve_fpr_from_card (app_t app
, int keyno
, char *fpr
)
821 unsigned char *value
;
825 assert (keyno
>=0 && keyno
<= 2);
827 relptr
= get_one_do (app
, 0x00C5, &value
, &valuelen
, NULL
);
828 if (relptr
&& valuelen
>= 60)
830 for (i
= 0; i
< 20; i
++)
831 sprintf (fpr
+ (i
* 2), "%02X", value
[(keyno
*20)+i
]);
834 err
= gpg_error (GPG_ERR_NOT_FOUND
);
838 #endif /*GNUPG_MAJOR_VERSION > 1*/
841 /* Retrieve the public key material for the RSA key, whose fingerprint
842 is FPR, from gpg output, which can be read through the stream FP.
843 The RSA modulus will be stored at the address of M and MLEN, the
844 public exponent at E and ELEN. Returns zero on success, an error
845 code on failure. Caller must release the allocated buffers at M
846 and E if the function returns success. */
847 #if GNUPG_MAJOR_VERSION > 1
849 retrieve_key_material (FILE *fp
, const char *hexkeyid
,
850 const unsigned char **m
, size_t *mlen
,
851 const unsigned char **e
, size_t *elen
)
853 gcry_error_t err
= 0;
854 char *line
= NULL
; /* read_line() buffer. */
855 size_t line_size
= 0; /* Helper for for read_line. */
856 int found_key
= 0; /* Helper to find a matching key. */
857 unsigned char *m_new
= NULL
;
858 unsigned char *e_new
= NULL
;
862 /* Loop over all records until we have found the subkey
863 corresponsing to the fingerprint. Inm general the first record
864 should be the pub record, but we don't rely on that. Given that
865 we only need to look at one key, it is sufficient to compare the
866 keyid so that we don't need to look at "fpr" records. */
877 i
= read_line (fp
, &line
, &line_size
, &max_length
);
882 err
= gpg_error_from_errno (errno
);
883 goto leave
; /* Error. */
887 err
= gpg_error (GPG_ERR_TRUNCATED
);
888 goto leave
; /* Line truncated - we better stop processing. */
891 /* Parse the line into fields. */
892 for (nfields
=0, p
=line
; p
&& nfields
< DIM (fields
); nfields
++)
900 continue; /* No fields at all - skip line. */
904 if ( (!strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
905 && nfields
> 4 && !strcmp (fields
[4], hexkeyid
))
910 if ( !strcmp (fields
[0], "sub") || !strcmp (fields
[0], "pub") )
911 break; /* Next key - stop. */
913 if ( strcmp (fields
[0], "pkd") )
914 continue; /* Not a key data record. */
915 i
= 0; /* Avoid erroneous compiler warning. */
916 if ( nfields
< 4 || (i
= atoi (fields
[1])) < 0 || i
> 1
917 || (!i
&& m_new
) || (i
&& e_new
))
919 err
= gpg_error (GPG_ERR_GENERAL
);
920 goto leave
; /* Error: Invalid key data record or not an RSA key. */
923 err
= gcry_mpi_scan (&mpi
, GCRYMPI_FMT_HEX
, fields
[3], 0, NULL
);
927 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &m_new
, &m_new_n
, mpi
);
929 err
= gcry_mpi_aprint (GCRYMPI_FMT_STD
, &e_new
, &e_new_n
, mpi
);
930 gcry_mpi_release (mpi
);
945 err
= gpg_error (GPG_ERR_GENERAL
);
953 #endif /*GNUPG_MAJOR_VERSION > 1*/
956 /* Get the public key for KEYNO and store it as an S-expresion with
957 the APP handle. On error that field gets cleared. If we already
958 know about the public key we will just return. Note that this does
959 not mean a key is available; this is soley indicated by the
960 presence of the app->app_local->pk[KEYNO-1].key field.
962 Note that GnuPG 1.x does not need this and it would be too time
963 consuming to send it just for the fun of it. However, given that we
964 use the same code in gpg 1.4, we can't use the gcry S-expresion
965 here but need to open encode it. */
966 #if GNUPG_MAJOR_VERSION > 1
968 get_public_key (app_t app
, int keyno
)
971 unsigned char *buffer
;
972 const unsigned char *keydata
, *m
, *e
;
973 size_t buflen
, keydatalen
, mlen
, elen
;
974 unsigned char *mbuf
= NULL
;
975 unsigned char *ebuf
= NULL
;
979 if (keyno
< 1 || keyno
> 3)
980 return gpg_error (GPG_ERR_INV_ID
);
983 /* Already cached? */
984 if (app
->app_local
->pk
[keyno
].read_done
)
987 xfree (app
->app_local
->pk
[keyno
].key
);
988 app
->app_local
->pk
[keyno
].key
= NULL
;
989 app
->app_local
->pk
[keyno
].keylen
= 0;
991 m
= e
= NULL
; /* (avoid cc warning) */
993 if (app
->card_version
> 0x0100)
995 /* We may simply read the public key out of these cards. */
996 err
= iso7816_read_public_key
997 (app
->slot
, (const unsigned char*)(keyno
== 0? "\xB6" :
998 keyno
== 1? "\xB8" : "\xA4"),
1003 log_error (_("reading public key failed: %s\n"), gpg_strerror (err
));
1007 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1010 err
= gpg_error (GPG_ERR_CARD
);
1011 log_error (_("response does not contain the public key data\n"));
1015 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1018 err
= gpg_error (GPG_ERR_CARD
);
1019 log_error (_("response does not contain the RSA modulus\n"));
1024 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1027 err
= gpg_error (GPG_ERR_CARD
);
1028 log_error (_("response does not contain the RSA public exponent\n"));
1032 /* Prepend numbers with a 0 if needed. */
1033 if (mlen
&& (*m
& 0x80))
1035 mbuf
= xtrymalloc ( mlen
+ 1);
1038 err
= gpg_error_from_errno (errno
);
1042 memcpy (mbuf
+1, m
, mlen
);
1046 if (elen
&& (*e
& 0x80))
1048 ebuf
= xtrymalloc ( elen
+ 1);
1051 err
= gpg_error_from_errno (errno
);
1055 memcpy (ebuf
+1, e
, elen
);
1063 /* Due to a design problem in v1.0 cards we can't get the public
1064 key out of these cards without doing a verify on CHV3.
1065 Clearly that is not an option and thus we try to locate the
1066 key using an external helper.
1068 The helper we use here is gpg itself, which should know about
1069 the key in any case. */
1073 char *command
= NULL
;
1077 buffer
= NULL
; /* We don't need buffer. */
1079 err
= retrieve_fpr_from_card (app
, keyno
, fpr
);
1082 log_error ("error while retrieving fpr from card: %s\n",
1083 gpg_strerror (err
));
1086 hexkeyid
= fpr
+ 24;
1088 ret
= asprintf (&command
,
1089 "gpg --list-keys --with-colons --with-key-data '%s'",
1093 err
= gpg_error_from_errno (errno
);
1097 fp
= popen (command
, "r");
1101 err
= gpg_error_from_errno (errno
);
1102 log_error ("running gpg failed: %s\n", gpg_strerror (err
));
1106 err
= retrieve_key_material (fp
, hexkeyid
, &m
, &mlen
, &e
, &elen
);
1110 log_error ("error while retrieving key material through pipe: %s\n",
1111 gpg_strerror (err
));
1116 /* Allocate a buffer to construct the S-expression. */
1117 /* FIXME: We should provide a generalized S-expression creation
1119 keybuf
= xtrymalloc (50 + 2*35 + mlen
+ elen
+ 1);
1122 err
= gpg_error_from_errno (errno
);
1126 sprintf (keybuf
, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen
);
1127 keybuf_p
= keybuf
+ strlen (keybuf
);
1128 memcpy (keybuf_p
, m
, mlen
);
1130 sprintf (keybuf_p
, ")(1:e%u:", (unsigned int)elen
);
1131 keybuf_p
+= strlen (keybuf_p
);
1132 memcpy (keybuf_p
, e
, elen
);
1134 strcpy (keybuf_p
, ")))");
1135 keybuf_p
+= strlen (keybuf_p
);
1137 app
->app_local
->pk
[keyno
].key
= (unsigned char*)keybuf
;
1138 app
->app_local
->pk
[keyno
].keylen
= (keybuf_p
- keybuf
);
1141 /* Set a flag to indicate that we tried to read the key. */
1142 app
->app_local
->pk
[keyno
].read_done
= 1;
1149 #endif /* GNUPG_MAJOR_VERSION > 1 */
1153 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1154 This is used by the LEARN command. */
1156 send_keypair_info (app_t app
, ctrl_t ctrl
, int keyno
)
1158 gpg_error_t err
= 0;
1159 /* Note that GnuPG 1.x does not need this and it would be too time
1160 consuming to send it just for the fun of it. */
1161 #if GNUPG_MAJOR_VERSION > 1
1162 unsigned char grip
[20];
1167 err
= get_public_key (app
, keyno
);
1171 assert (keyno
>= 1 && keyno
<= 3);
1172 if (!app
->app_local
->pk
[keyno
-1].key
)
1173 goto leave
; /* No such key - ignore. */
1175 err
= keygrip_from_canon_sexp (app
->app_local
->pk
[keyno
-1].key
,
1176 app
->app_local
->pk
[keyno
-1].keylen
,
1181 for (i
=0; i
< 20; i
++)
1182 sprintf (gripstr
+i
*2, "%02X", grip
[i
]);
1184 sprintf (idbuf
, "OPENPGP.%d", keyno
);
1185 send_status_info (ctrl
, "KEYPAIRINFO",
1187 idbuf
, strlen (idbuf
),
1191 #endif /* GNUPG_MAJOR_VERSION > 1 */
1197 /* Handle the LEARN command for OpenPGP. */
1199 do_learn_status (app_t app
, ctrl_t ctrl
)
1201 do_getattr (app
, ctrl
, "EXTCAP");
1202 do_getattr (app
, ctrl
, "DISP-NAME");
1203 do_getattr (app
, ctrl
, "DISP-LANG");
1204 do_getattr (app
, ctrl
, "DISP-SEX");
1205 do_getattr (app
, ctrl
, "PUBKEY-URL");
1206 do_getattr (app
, ctrl
, "LOGIN-DATA");
1207 do_getattr (app
, ctrl
, "KEY-FPR");
1208 if (app
->card_version
> 0x0100)
1209 do_getattr (app
, ctrl
, "KEY-TIME");
1210 do_getattr (app
, ctrl
, "CA-FPR");
1211 do_getattr (app
, ctrl
, "CHV-STATUS");
1212 do_getattr (app
, ctrl
, "SIG-COUNTER");
1213 if (app
->app_local
->extcap
.private_dos
)
1215 do_getattr (app
, ctrl
, "PRIVATE-DO-1");
1216 do_getattr (app
, ctrl
, "PRIVATE-DO-2");
1218 do_getattr (app
, ctrl
, "PRIVATE-DO-3");
1220 do_getattr (app
, ctrl
, "PRIVATE-DO-4");
1222 send_keypair_info (app
, ctrl
, 1);
1223 send_keypair_info (app
, ctrl
, 2);
1224 send_keypair_info (app
, ctrl
, 3);
1229 /* Handle the READKEY command for OpenPGP. On success a canonical
1230 encoded S-expression with the public key will get stored at PK and
1231 its length (for assertions) at PKLEN; the caller must release that
1232 buffer. On error PK and PKLEN are not changed and an error code is
1235 do_readkey (app_t app
, const char *keyid
, unsigned char **pk
, size_t *pklen
)
1237 #if GNUPG_MAJOR_VERSION > 1
1242 if (!strcmp (keyid
, "OPENPGP.1"))
1244 else if (!strcmp (keyid
, "OPENPGP.2"))
1246 else if (!strcmp (keyid
, "OPENPGP.3"))
1249 return gpg_error (GPG_ERR_INV_ID
);
1251 err
= get_public_key (app
, keyno
);
1255 buf
= app
->app_local
->pk
[keyno
-1].key
;
1257 return gpg_error (GPG_ERR_NO_PUBKEY
);
1258 *pklen
= app
->app_local
->pk
[keyno
-1].keylen
;;
1259 *pk
= xtrymalloc (*pklen
);
1262 err
= gpg_error_from_errno (errno
);
1266 memcpy (*pk
, buf
, *pklen
);
1269 return gpg_error (GPG_ERR_NOT_IMPLEMENTED
);
1275 /* Verify CHV2 if required. Depending on the configuration of the
1276 card CHV1 will also be verified. */
1278 verify_chv2 (app_t app
,
1279 gpg_error_t (*pincb
)(void*, const char *, char **),
1288 rc
= pincb (pincb_arg
, "PIN", &pinvalue
);
1291 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1295 if (strlen (pinvalue
) < 6)
1297 log_error (_("PIN for CHV%d is too short;"
1298 " minimum length is %d\n"), 2, 6);
1300 return gpg_error (GPG_ERR_BAD_PIN
);
1303 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
1306 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
1308 flush_cache_after_error (app
);
1313 if (!app
->did_chv1
&& !app
->force_chv1
)
1315 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
1316 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
1317 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
1320 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
1322 flush_cache_after_error (app
);
1332 /* Verify CHV3 if required. */
1334 verify_chv3 (app_t app
,
1335 gpg_error_t (*pincb
)(void*, const char *, char **),
1340 #if GNUPG_MAJOR_VERSION != 1
1341 if (!opt
.allow_admin
)
1343 log_info (_("access to admin commands is not configured\n"));
1344 return gpg_error (GPG_ERR_EACCES
);
1352 unsigned char *value
;
1355 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
1356 if (!relptr
|| valuelen
< 7)
1358 log_error (_("error retrieving CHV status from card\n"));
1360 return gpg_error (GPG_ERR_CARD
);
1364 log_info (_("card is permanently locked!\n"));
1366 return gpg_error (GPG_ERR_BAD_PIN
);
1369 log_info(_("%d Admin PIN attempts remaining before card"
1370 " is permanently locked\n"), value
[6]);
1373 /* TRANSLATORS: Do not translate the "|A|" prefix but
1374 keep it at the start of the string. We need this elsewhere
1375 to get some infos on the string. */
1376 rc
= pincb (pincb_arg
, _("|A|Admin PIN"), &pinvalue
);
1379 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
1383 if (strlen (pinvalue
) < 8)
1385 log_error (_("PIN for CHV%d is too short;"
1386 " minimum length is %d\n"), 3, 8);
1388 return gpg_error (GPG_ERR_BAD_PIN
);
1391 rc
= iso7816_verify (app
->slot
, 0x83, pinvalue
, strlen (pinvalue
));
1395 log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc
));
1396 flush_cache_after_error (app
);
1405 /* Handle the SETATTR operation. All arguments are already basically
1408 do_setattr (app_t app
, const char *name
,
1409 gpg_error_t (*pincb
)(void*, const char *, char **),
1411 const unsigned char *value
, size_t valuelen
)
1421 { "DISP-NAME", 0x005B, 3 },
1422 { "LOGIN-DATA", 0x005E, 3, 2 },
1423 { "DISP-LANG", 0x5F2D, 3 },
1424 { "DISP-SEX", 0x5F35, 3 },
1425 { "PUBKEY-URL", 0x5F50, 3 },
1426 { "CHV-STATUS-1", 0x00C4, 3, 1 },
1427 { "CA-FPR-1", 0x00CA, 3 },
1428 { "CA-FPR-2", 0x00CB, 3 },
1429 { "CA-FPR-3", 0x00CC, 3 },
1430 { "PRIVATE-DO-1", 0x0101, 2 },
1431 { "PRIVATE-DO-2", 0x0102, 3 },
1432 { "PRIVATE-DO-3", 0x0103, 2 },
1433 { "PRIVATE-DO-4", 0x0104, 3 },
1438 for (idx
=0; table
[idx
].name
&& strcmp (table
[idx
].name
, name
); idx
++)
1440 if (!table
[idx
].name
)
1441 return gpg_error (GPG_ERR_INV_NAME
);
1443 switch (table
[idx
].need_chv
)
1446 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1449 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1457 /* Flush the cache before writing it, so that the next get operation
1458 will reread the data from the card and thus get synced in case of
1459 errors (e.g. data truncated by the card). */
1460 flush_cache_item (app
, table
[idx
].tag
);
1461 rc
= iso7816_put_data (app
->slot
, table
[idx
].tag
, value
, valuelen
);
1463 log_error ("failed to set `%s': %s\n", table
[idx
].name
, gpg_strerror (rc
));
1465 if (table
[idx
].special
== 1)
1466 app
->force_chv1
= (valuelen
&& *value
== 0);
1467 else if (table
[idx
].special
== 2)
1468 parse_login_data (app
);
1474 /* Handle the PASSWD command. */
1476 do_change_pin (app_t app
, ctrl_t ctrl
, const char *chvnostr
, int reset_mode
,
1477 gpg_error_t (*pincb
)(void*, const char *, char **),
1481 int chvno
= atoi (chvnostr
);
1484 if (reset_mode
&& chvno
== 3)
1486 rc
= gpg_error (GPG_ERR_INV_ID
);
1489 else if (reset_mode
|| chvno
== 3)
1491 /* we always require that the PIN is entered. */
1493 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1497 else if (chvno
== 1 || chvno
== 2)
1499 /* CHV1 and CVH2 should always have the same value, thus we
1501 int save_force
= app
->force_chv1
;
1503 app
->force_chv1
= 0;
1506 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
1507 app
->force_chv1
= save_force
;
1513 rc
= gpg_error (GPG_ERR_INV_ID
);
1520 app
->did_chv1
= app
->did_chv2
= 0;
1522 /* TRANSLATORS: Do not translate the "|*|" prefixes but
1523 keep it at the start of the string. We need this elsewhere
1524 to get some infos on the string. */
1525 rc
= pincb (pincb_arg
, chvno
== 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
1529 log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc
));
1535 rc
= iso7816_reset_retry_counter (app
->slot
, 0x81,
1536 pinvalue
, strlen (pinvalue
));
1538 rc
= iso7816_reset_retry_counter (app
->slot
, 0x82,
1539 pinvalue
, strlen (pinvalue
));
1543 if (chvno
== 1 || chvno
== 2)
1545 rc
= iso7816_change_reference_data (app
->slot
, 0x81, NULL
, 0,
1546 pinvalue
, strlen (pinvalue
));
1548 rc
= iso7816_change_reference_data (app
->slot
, 0x82, NULL
, 0,
1549 pinvalue
, strlen (pinvalue
));
1552 rc
= iso7816_change_reference_data (app
->slot
, 0x80 + chvno
, NULL
, 0,
1553 pinvalue
, strlen (pinvalue
));
1557 flush_cache_after_error (app
);
1564 /* Check whether a key already exists. KEYIDX is the index of the key
1565 (0..2). If FORCE is TRUE a diagnositic will be printed but no
1566 error returned if the key already exists. */
1568 does_key_exist (app_t app
, int keyidx
, int force
)
1570 const unsigned char *fpr
;
1571 unsigned char *buffer
;
1575 assert (keyidx
>=0 && keyidx
<= 2);
1577 if (iso7816_get_data (app
->slot
, 0x006E, &buffer
, &buflen
))
1579 log_error (_("error reading application data\n"));
1580 return gpg_error (GPG_ERR_GENERAL
);
1582 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
1585 log_error (_("error reading fingerprint DO\n"));
1587 return gpg_error (GPG_ERR_GENERAL
);
1590 for (i
=0; i
< 20 && !fpr
[i
]; i
++)
1593 if (i
!=20 && !force
)
1595 log_error (_("key already exists\n"));
1596 return gpg_error (GPG_ERR_EEXIST
);
1599 log_info (_("existing key will be replaced\n"));
1601 log_info (_("generating new key\n"));
1607 /* Handle the WRITEKEY command for OpenPGP. This function expects a
1608 canonical encoded S-expression with the secret key in KEYDATA and
1609 its length (for assertions) in KEYDATALEN. KEYID needs to be the
1610 usual keyid which for OpenPGP is the string "OPENPGP.n" with
1611 n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
1612 get overwritten. PINCB and PINCB_ARG are the usual arguments for
1613 the pinentry callback. */
1615 do_writekey (app_t app
, ctrl_t ctrl
,
1616 const char *keyid
, unsigned int flags
,
1617 gpg_error_t (*pincb
)(void*, const char *, char **),
1619 const unsigned char *keydata
, size_t keydatalen
)
1622 int force
= (flags
& 1);
1624 const unsigned char *buf
, *tok
;
1625 size_t buflen
, toklen
;
1626 int depth
, last_depth1
, last_depth2
;
1627 const unsigned char *rsa_n
= NULL
;
1628 const unsigned char *rsa_e
= NULL
;
1629 const unsigned char *rsa_p
= NULL
;
1630 const unsigned char *rsa_q
= NULL
;
1631 size_t rsa_n_len
, rsa_e_len
, rsa_p_len
, rsa_q_len
;
1633 unsigned char *template = NULL
;
1635 size_t template_len
;
1636 unsigned char fprbuf
[20];
1639 if (!strcmp (keyid
, "OPENPGP.1"))
1641 else if (!strcmp (keyid
, "OPENPGP.2"))
1643 else if (!strcmp (keyid
, "OPENPGP.3"))
1646 return gpg_error (GPG_ERR_INV_ID
);
1648 err
= does_key_exist (app
, keyno
, force
);
1654 Parse the S-expression
1657 buflen
= keydatalen
;
1659 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1661 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1663 if (!tok
|| toklen
!= 11 || memcmp ("private-key", tok
, toklen
))
1667 else if (toklen
== 21 && !memcmp ("protected-private-key", tok
, toklen
))
1668 log_info ("protected-private-key passed to writekey\n");
1669 else if (toklen
== 20 && !memcmp ("shadowed-private-key", tok
, toklen
))
1670 log_info ("shadowed-private-key passed to writekey\n");
1671 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1674 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1676 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1678 if (!tok
|| toklen
!= 3 || memcmp ("rsa", tok
, toklen
))
1680 err
= gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO
);
1683 last_depth1
= depth
;
1684 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1685 && depth
&& depth
>= last_depth1
)
1689 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
1692 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1694 if (tok
&& toklen
== 1)
1696 const unsigned char **mpi
;
1701 case 'n': mpi
= &rsa_n
; mpi_len
= &rsa_n_len
; break;
1702 case 'e': mpi
= &rsa_e
; mpi_len
= &rsa_e_len
; break;
1703 case 'p': mpi
= &rsa_p
; mpi_len
= &rsa_p_len
; break;
1704 case 'q': mpi
= &rsa_q
; mpi_len
= &rsa_q_len
;break;
1705 default: mpi
= NULL
; mpi_len
= NULL
; break;
1709 err
= gpg_error (GPG_ERR_DUP_VALUE
);
1712 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1716 /* Strip off leading zero bytes and save. */
1717 for (;toklen
&& !*tok
; toklen
--, tok
++)
1723 /* Skip until end of list. */
1724 last_depth2
= depth
;
1725 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1726 && depth
&& depth
>= last_depth2
)
1731 /* Parse other attributes. */
1732 last_depth1
= depth
;
1733 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1734 && depth
&& depth
>= last_depth1
)
1738 err
= gpg_error (GPG_ERR_UNKNOWN_SEXP
);
1741 if ((err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
)))
1743 if (tok
&& toklen
== 10 && !memcmp ("created-at", tok
, toklen
))
1745 if ((err
= parse_sexp (&buf
,&buflen
,&depth
,&tok
,&toklen
)))
1749 for (created_at
=0; toklen
&& *tok
&& *tok
>= '0' && *tok
<= '9';
1751 created_at
= created_at
*10 + (*tok
- '0');
1754 /* Skip until end of list. */
1755 last_depth2
= depth
;
1756 while (!(err
= parse_sexp (&buf
, &buflen
, &depth
, &tok
, &toklen
))
1757 && depth
&& depth
>= last_depth2
)
1764 /* Check that we have all parameters and that they match the card
1768 log_error (_("creation timestamp missing\n"));
1769 err
= gpg_error (GPG_ERR_INV_VALUE
);
1772 nbits
= rsa_n
? count_bits (rsa_n
, rsa_n_len
) : 0;
1775 log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
1776 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1779 nbits
= rsa_e
? count_bits (rsa_e
, rsa_e_len
) : 0;
1780 if (nbits
< 2 || nbits
> 32)
1782 log_error (_("RSA public exponent missing or larger than %d bits\n"),
1784 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1787 nbits
= rsa_p
? count_bits (rsa_p
, rsa_p_len
) : 0;
1790 log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
1791 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1794 nbits
= rsa_q
? count_bits (rsa_q
, rsa_q_len
) : 0;
1797 log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
1798 err
= gpg_error (GPG_ERR_BAD_SECKEY
);
1803 /* Build the private key template as described in section 4.3.3.6 of
1804 the OpenPGP card specs:
1805 0xC0 <length> public exponent
1806 0xC1 <length> prime p
1807 0xC2 <length> prime q
1809 assert (rsa_e_len
<= 4);
1810 template_len
= (1 + 1 + 4
1812 + 1 + 1 + rsa_q_len
);
1813 template = tp
= xtrymalloc_secure (template_len
);
1816 err
= gpg_error_from_errno (errno
);
1821 memcpy (tp
, rsa_e
, rsa_e_len
);
1824 /* Right justify E. */
1825 memmove (tp
+4-rsa_e_len
, tp
, 4-rsa_e_len
);
1826 memset (tp
, 0, 4-rsa_e_len
);
1832 memcpy (tp
, rsa_p
, rsa_p_len
);
1837 memcpy (tp
, rsa_q
, rsa_q_len
);
1840 assert (tp
- template == template_len
);
1843 /* Obviously we need to remove the cached public key. */
1844 xfree (app
->app_local
->pk
[keyno
].key
);
1845 app
->app_local
->pk
[keyno
].key
= NULL
;
1846 app
->app_local
->pk
[keyno
].keylen
= 0;
1847 app
->app_local
->pk
[keyno
].read_done
= 0;
1849 /* Prepare for storing the key. */
1850 err
= verify_chv3 (app
, pincb
, pincb_arg
);
1854 /* Store the key. */
1855 err
= iso7816_put_data (app
->slot
,
1856 (app
->card_version
> 0x0007? 0xE0 : 0xE9) + keyno
,
1857 template, template_len
);
1860 log_error (_("failed to store the key: %s\n"), gpg_strerror (err
));
1864 err
= store_fpr (app
->slot
, keyno
, created_at
,
1865 rsa_n
, rsa_n_len
, rsa_e
, rsa_e_len
,
1866 fprbuf
, app
->card_version
);
1877 /* Handle the GENKEY command. */
1879 do_genkey (app_t app
, ctrl_t ctrl
, const char *keynostr
, unsigned int flags
,
1880 gpg_error_t (*pincb
)(void*, const char *, char **),
1885 unsigned char fprbuf
[20];
1886 const unsigned char *keydata
, *m
, *e
;
1887 unsigned char *buffer
= NULL
;
1888 size_t buflen
, keydatalen
, mlen
, elen
;
1890 int keyno
= atoi (keynostr
);
1891 int force
= (flags
& 1);
1894 if (keyno
< 1 || keyno
> 3)
1895 return gpg_error (GPG_ERR_INV_ID
);
1898 /* We flush the cache to increase the traffic before a key
1899 generation. This _might_ help a card to gather more entropy. */
1902 /* Obviously we need to remove the cached public key. */
1903 xfree (app
->app_local
->pk
[keyno
].key
);
1904 app
->app_local
->pk
[keyno
].key
= NULL
;
1905 app
->app_local
->pk
[keyno
].keylen
= 0;
1906 app
->app_local
->pk
[keyno
].read_done
= 0;
1908 /* Check whether a key already exists. */
1909 rc
= does_key_exist (app
, keyno
, force
);
1913 /* Prepare for key generation by verifying the ADmin PIN. */
1914 rc
= verify_chv3 (app
, pincb
, pincb_arg
);
1919 log_info (_("please wait while key is being generated ...\n"));
1920 start_at
= time (NULL
);
1921 rc
= iso7816_generate_keypair
1923 #warning key generation temporary replaced by reading an existing key.
1924 rc
= iso7816_read_public_key
1926 (app
->slot
, (const unsigned char*)(keyno
== 0? "\xB6" :
1927 keyno
== 1? "\xB8" : "\xA4"),
1932 rc
= gpg_error (GPG_ERR_CARD
);
1933 log_error (_("generating key failed\n"));
1936 log_info (_("key generation completed (%d seconds)\n"),
1937 (int)(time (NULL
) - start_at
));
1938 keydata
= find_tlv (buffer
, buflen
, 0x7F49, &keydatalen
);
1941 rc
= gpg_error (GPG_ERR_CARD
);
1942 log_error (_("response does not contain the public key data\n"));
1946 m
= find_tlv (keydata
, keydatalen
, 0x0081, &mlen
);
1949 rc
= gpg_error (GPG_ERR_CARD
);
1950 log_error (_("response does not contain the RSA modulus\n"));
1953 /* log_printhex ("RSA n:", m, mlen); */
1954 send_key_data (ctrl
, "n", m
, mlen
);
1956 e
= find_tlv (keydata
, keydatalen
, 0x0082, &elen
);
1959 rc
= gpg_error (GPG_ERR_CARD
);
1960 log_error (_("response does not contain the RSA public exponent\n"));
1963 /* log_printhex ("RSA e:", e, elen); */
1964 send_key_data (ctrl
, "e", e
, elen
);
1966 created_at
= gnupg_get_time ();
1967 sprintf (numbuf
, "%lu", (unsigned long)created_at
);
1968 send_status_info (ctrl
, "KEY-CREATED-AT",
1969 numbuf
, (size_t)strlen(numbuf
), NULL
, 0);
1971 rc
= store_fpr (app
->slot
, keyno
, (u32
)created_at
,
1972 m
, mlen
, e
, elen
, fprbuf
, app
->card_version
);
1975 send_fpr_if_not_null (ctrl
, "KEY-FPR", -1, fprbuf
);
1984 static unsigned long
1985 convert_sig_counter_value (const unsigned char *value
, size_t valuelen
)
1990 ul
= (value
[0] << 16) | (value
[1] << 8) | value
[2];
1993 log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1999 static unsigned long
2000 get_sig_counter (app_t app
)
2003 unsigned char *value
;
2007 relptr
= get_one_do (app
, 0x0093, &value
, &valuelen
, NULL
);
2010 ul
= convert_sig_counter_value (value
, valuelen
);
2016 compare_fingerprint (app_t app
, int keyno
, unsigned char *sha1fpr
)
2018 const unsigned char *fpr
;
2019 unsigned char *buffer
;
2023 assert (keyno
>= 1 && keyno
<= 3);
2025 rc
= get_cached_data (app
, 0x006E, &buffer
, &buflen
, 0);
2028 log_error (_("error reading application data\n"));
2029 return gpg_error (GPG_ERR_GENERAL
);
2031 fpr
= find_tlv (buffer
, buflen
, 0x00C5, &n
);
2032 if (!fpr
|| n
!= 60)
2035 log_error (_("error reading fingerprint DO\n"));
2036 return gpg_error (GPG_ERR_GENERAL
);
2038 fpr
+= (keyno
-1)*20;
2039 for (i
=0; i
< 20; i
++)
2040 if (sha1fpr
[i
] != fpr
[i
])
2043 return gpg_error (GPG_ERR_WRONG_SECKEY
);
2050 /* If a fingerprint has been specified check it against the one on
2051 the card. This is allows for a meaningful error message in case
2052 the key on the card has been replaced but the shadow information
2053 known to gpg was not updated. If there is no fingerprint we
2054 assume that this is okay. */
2056 check_against_given_fingerprint (app_t app
, const char *fpr
, int keyno
)
2058 unsigned char tmp
[20];
2062 for (s
=fpr
, n
=0; hexdigitp (s
); s
++, n
++)
2065 return gpg_error (GPG_ERR_INV_ID
);
2069 return gpg_error (GPG_ERR_INV_ID
);
2071 for (s
=fpr
, n
=0; n
< 20; s
+= 2, n
++)
2072 tmp
[n
] = xtoi_2 (s
);
2073 return compare_fingerprint (app
, keyno
, tmp
);
2078 /* Compute a digital signature on INDATA which is expected to be the
2079 raw message digest. For this application the KEYIDSTR consists of
2080 the serialnumber and the fingerprint delimited by a slash.
2082 Note that this fucntion may return the error code
2083 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2084 not match the one required for the requested action (e.g. the
2085 serial number does not match). */
2087 do_sign (app_t app
, const char *keyidstr
, int hashalgo
,
2088 gpg_error_t (*pincb
)(void*, const char *, char **),
2090 const void *indata
, size_t indatalen
,
2091 unsigned char **outdata
, size_t *outdatalen
)
2093 static unsigned char sha1_prefix
[15] = /* Object ID is 1.3.14.3.2.26 */
2094 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2095 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2096 static unsigned char rmd160_prefix
[15] = /* Object ID is 1.3.36.3.2.1 */
2097 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2098 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2100 unsigned char data
[35];
2101 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2104 const char *fpr
= NULL
;
2105 unsigned long sigcount
;
2107 if (!keyidstr
|| !*keyidstr
)
2108 return gpg_error (GPG_ERR_INV_VALUE
);
2109 if (indatalen
== 20)
2111 else if (indatalen
== (15 + 20) && hashalgo
== GCRY_MD_SHA1
2112 && !memcmp (indata
, sha1_prefix
, 15))
2114 else if (indatalen
== (15 + 20) && hashalgo
== GCRY_MD_RMD160
2115 && !memcmp (indata
, rmd160_prefix
, 15))
2118 return gpg_error (GPG_ERR_INV_VALUE
);
2120 /* Check whether an OpenPGP card of any version has been requested. */
2121 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2122 return gpg_error (GPG_ERR_INV_ID
);
2124 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2127 return gpg_error (GPG_ERR_INV_ID
);
2129 ; /* no fingerprint given: we allow this for now. */
2133 return gpg_error (GPG_ERR_INV_ID
);
2135 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2136 tmp_sn
[n
] = xtoi_2 (s
);
2138 if (app
->serialnolen
!= 16)
2139 return gpg_error (GPG_ERR_INV_CARD
);
2140 if (memcmp (app
->serialno
, tmp_sn
, 16))
2141 return gpg_error (GPG_ERR_WRONG_CARD
);
2143 /* If a fingerprint has been specified check it against the one on
2144 the card. This is allows for a meaningful error message in case
2145 the key on the card has been replaced but the shadow information
2146 known to gpg was not updated. If there is no fingerprint, gpg
2147 will detect a bogus signature anyway due to the
2148 verify-after-signing feature. */
2149 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 1) : 0;
2153 if (hashalgo
== GCRY_MD_SHA1
)
2154 memcpy (data
, sha1_prefix
, 15);
2155 else if (hashalgo
== GCRY_MD_RMD160
)
2156 memcpy (data
, rmd160_prefix
, 15);
2158 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM
);
2159 memcpy (data
+15, indata
, indatalen
);
2161 sigcount
= get_sig_counter (app
);
2162 log_info (_("signatures created so far: %lu\n"), sigcount
);
2164 if (!app
->did_chv1
|| app
->force_chv1
)
2170 #define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
2172 prompt
= malloc (strlen (PROMPTSTRING
) + 50);
2174 return gpg_error_from_errno (errno
);
2175 sprintf (prompt
, PROMPTSTRING
, sigcount
);
2176 rc
= pincb (pincb_arg
, prompt
, &pinvalue
);
2182 log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc
));
2186 if (strlen (pinvalue
) < 6)
2188 log_error (_("PIN for CHV%d is too short;"
2189 " minimum length is %d\n"), 1, 6);
2191 return gpg_error (GPG_ERR_BAD_PIN
);
2194 rc
= iso7816_verify (app
->slot
, 0x81, pinvalue
, strlen (pinvalue
));
2197 log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc
));
2199 flush_cache_after_error (app
);
2205 /* We should also verify CHV2. */
2206 rc
= iso7816_verify (app
->slot
, 0x82, pinvalue
, strlen (pinvalue
));
2207 if (gpg_err_code (rc
) == GPG_ERR_BAD_PIN
)
2208 rc
= gpg_error (GPG_ERR_PIN_NOT_SYNCED
);
2211 log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc
));
2213 flush_cache_after_error (app
);
2221 rc
= iso7816_compute_ds (app
->slot
, data
, 35, outdata
, outdatalen
);
2225 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
2226 on INDATA which is expected to be the raw message digest. For this
2227 application the KEYIDSTR consists of the serialnumber and the
2228 fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
2231 Note that this function may return the error code
2232 GPG_ERR_WRONG_CARD to indicate that the card currently present does
2233 not match the one required for the requested action (e.g. the
2234 serial number does not match). */
2236 do_auth (app_t app
, const char *keyidstr
,
2237 gpg_error_t (*pincb
)(void*, const char *, char **),
2239 const void *indata
, size_t indatalen
,
2240 unsigned char **outdata
, size_t *outdatalen
)
2243 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2246 const char *fpr
= NULL
;
2248 if (!keyidstr
|| !*keyidstr
)
2249 return gpg_error (GPG_ERR_INV_VALUE
);
2250 if (indatalen
> 50) /* For a 1024 bit key. */
2251 return gpg_error (GPG_ERR_INV_VALUE
);
2253 /* Check whether an OpenPGP card of any version has been requested. */
2254 if (!strcmp (keyidstr
, "OPENPGP.3"))
2256 else if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2257 return gpg_error (GPG_ERR_INV_ID
);
2260 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2263 return gpg_error (GPG_ERR_INV_ID
);
2265 ; /* no fingerprint given: we allow this for now. */
2269 return gpg_error (GPG_ERR_INV_ID
);
2271 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2272 tmp_sn
[n
] = xtoi_2 (s
);
2274 if (app
->serialnolen
!= 16)
2275 return gpg_error (GPG_ERR_INV_CARD
);
2276 if (memcmp (app
->serialno
, tmp_sn
, 16))
2277 return gpg_error (GPG_ERR_WRONG_CARD
);
2280 /* If a fingerprint has been specified check it against the one on
2281 the card. This is allows for a meaningful error message in case
2282 the key on the card has been replaced but the shadow information
2283 known to gpg was not updated. If there is no fingerprint, gpg
2284 will detect a bogus signature anyway due to the
2285 verify-after-signing feature. */
2286 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 3) : 0;
2290 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
2292 rc
= iso7816_internal_authenticate (app
->slot
, indata
, indatalen
,
2293 outdata
, outdatalen
);
2299 do_decipher (app_t app
, const char *keyidstr
,
2300 gpg_error_t (*pincb
)(void*, const char *, char **),
2302 const void *indata
, size_t indatalen
,
2303 unsigned char **outdata
, size_t *outdatalen
)
2306 unsigned char tmp_sn
[20]; /* actually 16 but we use it also for the fpr. */
2309 const char *fpr
= NULL
;
2311 if (!keyidstr
|| !*keyidstr
|| !indatalen
)
2312 return gpg_error (GPG_ERR_INV_VALUE
);
2314 /* Check whether an OpenPGP card of any version has been requested. */
2315 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2316 return gpg_error (GPG_ERR_INV_ID
);
2318 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2321 return gpg_error (GPG_ERR_INV_ID
);
2323 ; /* no fingerprint given: we allow this for now. */
2327 return gpg_error (GPG_ERR_INV_ID
);
2329 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2330 tmp_sn
[n
] = xtoi_2 (s
);
2332 if (app
->serialnolen
!= 16)
2333 return gpg_error (GPG_ERR_INV_CARD
);
2334 if (memcmp (app
->serialno
, tmp_sn
, 16))
2335 return gpg_error (GPG_ERR_WRONG_CARD
);
2337 /* If a fingerprint has been specified check it against the one on
2338 the card. This is allows for a meaningful error message in case
2339 the key on the card has been replaced but the shadow information
2340 known to gpg was not updated. If there is no fingerprint, the
2341 decryption will won't produce the right plaintext anyway. */
2342 rc
= fpr
? check_against_given_fingerprint (app
, fpr
, 2) : 0;
2346 rc
= verify_chv2 (app
, pincb
, pincb_arg
);
2348 rc
= iso7816_decipher (app
->slot
, indata
, indatalen
, 0,
2349 outdata
, outdatalen
);
2354 /* Perform a simple verify operation for CHV1 and CHV2, so that
2355 further operations won't ask for CHV2 and it is possible to do a
2356 cheap check on the PIN: If there is something wrong with the PIN
2357 entry system, only the regular CHV will get blocked and not the
2358 dangerous CHV3. KEYIDSTR is the usual card's serial number; an
2359 optional fingerprint part will be ignored.
2361 There is a special mode if the keyidstr is "<serialno>[CHV3]" with
2362 the "[CHV3]" being a literal string: The Admin Pin is checked if
2363 and only if the retry counter is still at 3. */
2365 do_check_pin (app_t app
, const char *keyidstr
,
2366 gpg_error_t (*pincb
)(void*, const char *, char **),
2369 unsigned char tmp_sn
[20];
2374 if (!keyidstr
|| !*keyidstr
)
2375 return gpg_error (GPG_ERR_INV_VALUE
);
2377 /* Check whether an OpenPGP card of any version has been requested. */
2378 if (strlen (keyidstr
) < 32 || strncmp (keyidstr
, "D27600012401", 12))
2379 return gpg_error (GPG_ERR_INV_ID
);
2381 for (s
=keyidstr
, n
=0; hexdigitp (s
); s
++, n
++)
2384 return gpg_error (GPG_ERR_INV_ID
);
2386 ; /* No fingerprint given: we allow this for now. */
2388 ; /* We ignore a fingerprint. */
2389 else if (!strcmp (s
, "[CHV3]") )
2392 return gpg_error (GPG_ERR_INV_ID
);
2394 for (s
=keyidstr
, n
=0; n
< 16; s
+= 2, n
++)
2395 tmp_sn
[n
] = xtoi_2 (s
);
2397 if (app
->serialnolen
!= 16)
2398 return gpg_error (GPG_ERR_INV_CARD
);
2399 if (memcmp (app
->serialno
, tmp_sn
, 16))
2400 return gpg_error (GPG_ERR_WRONG_CARD
);
2402 /* Yes, there is a race conditions: The user might pull the card
2403 right here and we won't notice that. However this is not a
2404 problem and the check above is merely for a graceful failure
2405 between operations. */
2410 unsigned char *value
;
2414 relptr
= get_one_do (app
, 0x00C4, &value
, &valuelen
, NULL
);
2415 if (!relptr
|| valuelen
< 7)
2417 log_error (_("error retrieving CHV status from card\n"));
2419 return gpg_error (GPG_ERR_CARD
);
2426 log_info (_("card is permanently locked!\n"));
2427 return gpg_error (GPG_ERR_BAD_PIN
);
2429 else if (value
[6] < 3)
2431 log_info (_("verification of Admin PIN is currently prohibited "
2432 "through this command\n"));
2433 return gpg_error (GPG_ERR_GENERAL
);
2436 app
->did_chv3
= 0; /* Force verification. */
2437 return verify_chv3 (app
, pincb
, pincb_arg
);
2440 return verify_chv2 (app
, pincb
, pincb_arg
);
2446 /* Select the OpenPGP application on the card in SLOT. This function
2447 must be used before any other OpenPGP application functions. */
2449 app_select_openpgp (app_t app
)
2451 static char const aid
[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
2452 int slot
= app
->slot
;
2454 unsigned char *buffer
;
2458 rc
= iso7816_select_application (slot
, aid
, sizeof aid
);
2461 unsigned int manufacturer
;
2463 app
->apptype
= "OPENPGP";
2468 app
->app_local
= NULL
;
2470 /* The OpenPGP card returns the serial number as part of the
2471 AID; because we prefer to use OpenPGP serial numbers, we
2472 replace a possibly already set one from a EF.GDO with this
2473 one. Note, that for current OpenPGP cards, no EF.GDO exists
2474 and thus it won't matter at all. */
2475 rc
= iso7816_get_data (slot
, 0x004F, &buffer
, &buflen
);
2481 log_printhex ("", buffer
, buflen
);
2484 app
->card_version
= buffer
[6] << 8;
2485 app
->card_version
|= buffer
[7];
2486 manufacturer
= (buffer
[8]<<8 | buffer
[9]);
2488 xfree (app
->serialno
);
2489 app
->serialno
= buffer
;
2490 app
->serialnolen
= buflen
;
2492 app
->app_local
= xtrycalloc (1, sizeof *app
->app_local
);
2493 if (!app
->app_local
)
2495 rc
= gpg_error (gpg_err_code_from_errno (errno
));
2499 relptr
= get_one_do (app
, 0x00C4, &buffer
, &buflen
, NULL
);
2502 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2503 "CHV Status Bytes");
2506 app
->force_chv1
= (buflen
&& *buffer
== 0);
2509 relptr
= get_one_do (app
, 0x00C0, &buffer
, &buflen
, NULL
);
2512 log_error (_("can't access %s - invalid OpenPGP card?\n"),
2513 "Extended Capability Flags" );
2518 app
->app_local
->extcap
.get_challenge
= !!(*buffer
& 0x40);
2519 app
->app_local
->extcap
.key_import
= !!(*buffer
& 0x20);
2520 app
->app_local
->extcap
.change_force_chv
= !!(*buffer
& 0x10);
2521 app
->app_local
->extcap
.private_dos
= !!(*buffer
& 0x08);
2525 /* Some of the first cards accidently don't set the
2526 CHANGE_FORCE_CHV bit but allow it anyway. */
2527 if (app
->card_version
<= 0x0100 && manufacturer
== 1)
2528 app
->app_local
->extcap
.change_force_chv
= 1;
2530 parse_login_data (app
);
2532 if (opt
.verbose
> 1)
2535 app
->fnc
.deinit
= do_deinit
;
2536 app
->fnc
.learn_status
= do_learn_status
;
2537 app
->fnc
.readkey
= do_readkey
;
2538 app
->fnc
.getattr
= do_getattr
;
2539 app
->fnc
.setattr
= do_setattr
;
2540 app
->fnc
.writekey
= do_writekey
;
2541 app
->fnc
.genkey
= do_genkey
;
2542 app
->fnc
.sign
= do_sign
;
2543 app
->fnc
.auth
= do_auth
;
2544 app
->fnc
.decipher
= do_decipher
;
2545 app
->fnc
.change_pin
= do_change_pin
;
2546 app
->fnc
.check_pin
= do_check_pin
;