1
/* app-openpgp.c - The OpenPGP card application.
2
* Copyright (C) 2003, 2004, 2005, 2007, 2008,
3
* 2009 Free Software Foundation, Inc.
5
* This file is part of GnuPG.
7
* GnuPG is free software; you can redistribute it and/or modify
8
* it under the terms of the GNU General Public License as published by
9
* the Free Software Foundation; either version 3 of the License, or
10
* (at your option) any later version.
12
* GnuPG is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
* GNU General Public License for more details.
17
* You should have received a copy of the GNU General Public License
18
* along with this program; if not, see <http://www.gnu.org/licenses/>.
23
CHV means Card Holder Verification and is nothing else than a PIN
24
or password. That term seems to have been used originally with GSM
25
cards. Version v2 of the specs changes the term to the clearer
26
term PW for password. We use the terms here interchangeable
27
because we do not want to change existing strings i18n wise.
29
Version 2 of the specs also drops the separate PW2 which was
30
required in v1 due to ISO requirements. It is now possible to have
31
one physical PW but two reference to it so that they can be
32
individually be verified (e.g. to implement a forced verification
33
for one key). Thus you will noticed the use of PW2 with the verify
34
command but not with change_reference_data because the latter
35
operates directly on the physical PW.
37
The Reset Code (RC) as implemented by v2 cards uses the same error
38
counter as the PW2 of v1 cards. By default no RC is set and thus
39
that error counter is set to 0. After setting the RC the error
40
counter will be initialized to 3.
52
#if GNUPG_MAJOR_VERSION == 1
53
/* This is used with GnuPG version < 1.9. The code has been source
54
copied from the current GnuPG >= 1.9 and is maintained over
61
#else /* GNUPG_MAJOR_VERSION != 1 */
63
#endif /* GNUPG_MAJOR_VERSION != 1 */
67
#include "app-common.h"
71
/* A table describing the DOs of the card. */
75
int get_from; /* Constructed DO with this DO or 0 for direct access. */
79
int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
80
this data object if it is used in 1.1
81
and later versions of the card. This
82
does not work with composite DO and
83
is currently only useful for the CHV
85
int try_extlen:1; /* Large object; try to use an extended
89
{ 0x005E, 0, 0, 1, 0, 0, 0, 0, "Login Data" },
90
{ 0x5F50, 0, 0, 0, 0, 0, 0, 0, "URL" },
91
{ 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" },
92
{ 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
93
{ 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
94
{ 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
95
{ 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
96
{ 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" },
97
{ 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
98
{ 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
99
{ 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
100
{ 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
101
{ 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
102
{ 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
103
{ 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
104
{ 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
105
{ 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
106
{ 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
107
{ 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
108
{ 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" },
109
{ 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
110
{ 0x0101, 0, 0, 0, 0, 0, 0, 0, "Private DO 1"},
111
{ 0x0102, 0, 0, 0, 0, 0, 0, 0, "Private DO 2"},
112
{ 0x0103, 0, 0, 0, 0, 0, 0, 0, "Private DO 3"},
113
{ 0x0104, 0, 0, 0, 0, 0, 0, 0, "Private DO 4"},
114
{ 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"},
119
/* The format of RSA private keys. */
131
/* One cache item for DOs. */
133
struct cache_s *next;
136
unsigned char data[1];
140
/* Object with application (i.e. OpenPGP card) specific data. */
142
/* A linked list with cached DOs. */
143
struct cache_s *cache;
145
/* Keep track of the public keys. */
148
int read_done; /* True if we have at least tried to read them. */
149
unsigned char *key; /* This is a malloced buffer with a canonical
150
encoded S-expression encoding a public
151
key. Might be NULL if key is not
153
size_t keylen; /* The length of the above S-expression. This
154
is usually only required for cross checks
155
because the length of an S-expression is
156
implicitly available. */
159
unsigned char status_indicator; /* The card status indicator. */
161
/* Keep track of the ISO card capabilities. */
164
unsigned int cmd_chaining:1; /* Command chaining is supported. */
165
unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */
168
/* Keep track of extended card capabilities. */
171
unsigned int is_v2:1; /* This is a v2.0 compatible card. */
172
unsigned int get_challenge:1;
173
unsigned int key_import:1;
174
unsigned int change_force_chv:1;
175
unsigned int private_dos:1;
176
unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */
177
unsigned int sm_supported:1; /* Secure Messaging is supported. */
178
unsigned int sm_aes128:1; /* Use AES-128 for SM. */
179
unsigned int max_certlen_3:16;
180
unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */
181
unsigned int max_cmd_data:16; /* Maximum data size for a command. */
182
unsigned int max_rsp_data:16; /* Maximum size of a response. */
185
/* Flags used to control the application. */
188
unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */
189
unsigned int def_chv2:1; /* Use 123456 for CHV2. */
194
unsigned int n_bits; /* Size of the modulus in bits. The rest
195
of this strucuire is only valid if
197
unsigned int e_bits; /* Size of the public exponent in bits. */
198
rsa_key_format_t format;
205
/***** Local prototypes *****/
206
static unsigned long convert_sig_counter_value (const unsigned char *value,
208
static unsigned long get_sig_counter (app_t app);
209
static gpg_error_t do_auth (app_t app, const char *keyidstr,
210
gpg_error_t (*pincb)(void*, const char *, char **),
212
const void *indata, size_t indatalen,
213
unsigned char **outdata, size_t *outdatalen);
214
static void parse_algorithm_attribute (app_t app, int keyno);
215
static gpg_error_t change_keyattr_from_string
217
gpg_error_t (*pincb)(void*, const char *, char **),
219
const void *value, size_t valuelen);
227
do_deinit (app_t app)
229
if (app && app->app_local)
231
struct cache_s *c, *c2;
234
for (c = app->app_local->cache; c; c = c2)
240
for (i=0; i < DIM (app->app_local->pk); i++)
242
xfree (app->app_local->pk[i].key);
243
app->app_local->pk[i].read_done = 0;
245
xfree (app->app_local);
246
app->app_local = NULL;
251
/* Wrapper around iso7816_get_data which first tries to get the data
252
from the cache. With GET_IMMEDIATE passed as true, the cache is
253
bypassed. With TRY_EXTLEN extended lengths APDUs are use if
254
supported by the card. */
256
get_cached_data (app_t app, int tag,
257
unsigned char **result, size_t *resultlen,
258
int get_immediate, int try_extlen)
272
for (c=app->app_local->cache; c; c = c->next)
277
p = xtrymalloc (c->length);
279
return gpg_error (gpg_err_code_from_errno (errno));
280
memcpy (p, c->data, c->length);
284
*resultlen = c->length;
290
if (try_extlen && app->app_local->cardcap.ext_lc_le)
291
exmode = app->app_local->extcap.max_rsp_data;
295
err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
301
/* Check whether we should cache this object. */
305
for (i=0; data_objects[i].tag; i++)
306
if (data_objects[i].tag == tag)
308
if (data_objects[i].dont_cache)
313
/* Okay, cache it. */
314
for (c=app->app_local->cache; c; c = c->next)
315
assert (c->tag != tag);
317
c = xtrymalloc (sizeof *c + len);
320
memcpy (c->data, p, len);
323
c->next = app->app_local->cache;
324
app->app_local->cache = c;
330
/* Remove DO at TAG from the cache. */
332
flush_cache_item (app_t app, int tag)
334
struct cache_s *c, *cprev;
340
for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
344
cprev->next = c->next;
346
app->app_local->cache = c->next;
349
for (c=app->app_local->cache; c ; c = c->next)
351
assert (c->tag != tag); /* Oops: duplicated entry. */
356
/* Try again if we have an outer tag. */
357
for (i=0; data_objects[i].tag; i++)
358
if (data_objects[i].tag == tag && data_objects[i].get_from
359
&& data_objects[i].get_from != tag)
360
flush_cache_item (app, data_objects[i].get_from);
363
/* Flush all entries from the cache which might be out of sync after
366
flush_cache_after_error (app_t app)
370
for (i=0; data_objects[i].tag; i++)
371
if (data_objects[i].flush_on_error)
372
flush_cache_item (app, data_objects[i].tag);
376
/* Flush the entire cache. */
378
flush_cache (app_t app)
380
if (app && app->app_local)
382
struct cache_s *c, *c2;
384
for (c = app->app_local->cache; c; c = c2)
389
app->app_local->cache = NULL;
394
/* Get the DO identified by TAG from the card in SLOT and return a
395
buffer with its content in RESULT and NBYTES. The return value is
396
NULL if not found or a pointer which must be used to release the
397
buffer holding value. */
399
get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
403
unsigned char *buffer;
405
unsigned char *value;
416
for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
419
if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
421
if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
422
exmode = app->app_local->extcap.max_rsp_data;
425
rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
438
if (data_objects[i].tag && data_objects[i].get_from)
440
rc = get_cached_data (app, data_objects[i].get_from,
442
(data_objects[i].dont_cache
443
|| data_objects[i].get_immediate_in_v11),
444
data_objects[i].try_extlen);
447
const unsigned char *s;
449
s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
451
value = NULL; /* not found */
452
else if (valuelen > buflen - (s - buffer))
454
log_error ("warning: constructed DO too short\n");
456
xfree (buffer); buffer = NULL;
459
value = buffer + (s - buffer);
463
if (!value) /* Not in a constructed DO, try simple. */
465
rc = get_cached_data (app, tag, &buffer, &buflen,
466
(data_objects[i].dont_cache
467
|| data_objects[i].get_immediate_in_v11),
468
data_objects[i].try_extlen);
488
dump_all_do (int slot)
491
unsigned char *buffer;
494
for (i=0; data_objects[i].tag; i++)
496
if (data_objects[i].get_from)
499
/* We don't try extended length APDU because such large DO would
500
be pretty useless in a log file. */
501
rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
502
if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
505
log_info ("DO `%s' not available: %s\n",
506
data_objects[i].desc, gpg_strerror (rc));
509
if (data_objects[i].binary)
511
log_info ("DO `%s': ", data_objects[i].desc);
512
log_printhex ("", buffer, buflen);
515
log_info ("DO `%s': `%.*s'\n",
516
data_objects[i].desc,
517
(int)buflen, buffer); /* FIXME: sanitize */
519
if (data_objects[i].constructed)
521
for (j=0; data_objects[j].tag; j++)
523
const unsigned char *value;
526
if (j==i || data_objects[i].tag != data_objects[j].get_from)
528
value = find_tlv_unchecked (buffer, buflen,
529
data_objects[j].tag, &valuelen);
532
else if (valuelen > buflen - (value - buffer))
533
log_error ("warning: constructed DO too short\n");
536
if (data_objects[j].binary)
538
log_info ("DO `%s': ", data_objects[j].desc);
540
log_info ("[%u]\n", (unsigned int)valuelen);
542
log_printhex ("", value, valuelen);
545
log_info ("DO `%s': `%.*s'\n",
546
data_objects[j].desc,
547
(int)valuelen, value); /* FIXME: sanitize */
552
xfree (buffer); buffer = NULL;
557
/* Count the number of bits, assuming the A represents an unsigned big
558
integer of length LEN bytes. */
560
count_bits (const unsigned char *a, size_t len)
562
unsigned int n = len * 8;
565
for (; len && !*a; len--, a++, n -=8)
569
for (i=7; i && !(*a & (1<<i)); i--)
575
/* GnuPG makes special use of the login-data DO, this function parses
576
the login data to store the flags for later use. It may be called
577
at any time and should be called after changing the login-data DO.
579
Everything up to a LF is considered a mailbox or account name. If
580
the first LF is followed by DC4 (0x14) control sequence are
581
expected up to the next LF. Control sequences are separated by FS
582
(0x18) and consist of key=value pairs. There is one key defined:
586
Were FLAGS is a plain hexadecimal number representing flag values.
587
The lsb is here the rightmost bit. Defined flags bits are:
589
Bit 0 = CHV1 and CHV2 are not syncronized
590
Bit 1 = CHV2 has been been set to the default PIN of "123456"
591
(this implies that bit 0 is also set).
595
parse_login_data (app_t app)
597
unsigned char *buffer, *p;
602
app->app_local->flags.no_sync = 0;
603
app->app_local->flags.def_chv2 = 0;
606
relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
609
for (; buflen; buflen--, buffer++)
612
if (buflen < 2 || buffer[1] != '\x14')
613
return; /* No control sequences. */
620
if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
622
/* Flags control sequence found. */
625
/* For now we are only interested in the last digit, so skip
626
any leading digits but bail out on invalid characters. */
627
for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
628
lastdig = xtoi_1 (p);
629
if (len && !(*p == '\n' || *p == '\x18'))
630
goto next; /* Invalid characters in field. */
631
app->app_local->flags.no_sync = !!(lastdig & 1);
632
app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
635
for (; buflen && *buffer != '\x18'; buflen--, buffer++)
644
/* Note, that FPR must be at least 20 bytes. */
646
store_fpr (app_t app, int keynumber, u32 timestamp,
647
const unsigned char *m, size_t mlen,
648
const unsigned char *e, size_t elen,
649
unsigned char *fpr, unsigned int card_version)
651
unsigned int n, nbits;
652
unsigned char *buffer, *p;
656
for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
658
for (; elen && !*e; elen--, e++) /* strip leading zeroes */
661
n = 6 + 2 + mlen + 2 + elen;
662
p = buffer = xtrymalloc (3 + n);
664
return gpg_error_from_syserror ();
666
*p++ = 0x99; /* ctb */
667
*p++ = n >> 8; /* 2 byte length header */
669
*p++ = 4; /* key packet version */
670
*p++ = timestamp >> 24;
671
*p++ = timestamp >> 16;
672
*p++ = timestamp >> 8;
675
nbits = count_bits (m, mlen);
678
memcpy (p, m, mlen); p += mlen;
679
nbits = count_bits (e, elen);
682
memcpy (p, e, elen); p += elen;
684
gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
688
tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
689
flush_cache_item (app, tag);
690
tag2 = 0xCE + keynumber;
691
flush_cache_item (app, tag2);
693
rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
695
log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
697
if (!rc && card_version > 0x0100)
699
unsigned char buf[4];
701
buf[0] = timestamp >> 24;
702
buf[1] = timestamp >> 16;
703
buf[2] = timestamp >> 8;
706
rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
708
log_error (_("failed to store the creation date: %s\n"),
717
send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
718
int number, const unsigned char *fpr)
724
for (i=0; i < 20 && !fpr[i]; i++)
727
return; /* All zero. */
728
bin2hex (fpr, 20, buf);
730
*numbuf = 0; /* Don't print the key number */
732
sprintf (numbuf, "%d", number);
733
send_status_info (ctrl, keyword,
734
numbuf, (size_t)strlen(numbuf),
735
buf, (size_t)strlen (buf), NULL, 0);
739
send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
740
int number, const unsigned char *stamp)
742
char numbuf1[50], numbuf2[50];
745
value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
748
sprintf (numbuf1, "%d", number);
749
sprintf (numbuf2, "%lu", value);
750
send_status_info (ctrl, keyword,
751
numbuf1, (size_t)strlen(numbuf1),
752
numbuf2, (size_t)strlen(numbuf2), NULL, 0);
756
send_key_data (ctrl_t ctrl, const char *name,
757
const unsigned char *a, size_t alen)
761
buf = bin2hex (a, alen, NULL);
764
log_error ("memory allocation error in send_key_data\n");
768
send_status_info (ctrl, "KEY-DATA",
769
name, (size_t)strlen(name),
770
buf, (size_t)strlen (buf),
777
send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
781
assert (number >=0 && number < DIM(app->app_local->keyattr));
783
/* We only support RSA thus the algo identifier is fixed to 1. */
784
snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
786
app->app_local->keyattr[number].n_bits,
787
app->app_local->keyattr[number].e_bits,
788
app->app_local->keyattr[number].format);
789
send_status_direct (ctrl, keyword, buffer);
793
/* Implement the GETATTR command. This is similar to the LEARN
794
command but returns just one value via the status interface. */
796
do_getattr (app_t app, ctrl_t ctrl, const char *name)
803
{ "DISP-NAME", 0x005B },
804
{ "LOGIN-DATA", 0x005E },
805
{ "DISP-LANG", 0x5F2D },
806
{ "DISP-SEX", 0x5F35 },
807
{ "PUBKEY-URL", 0x5F50 },
808
{ "KEY-FPR", 0x00C5, 3 },
809
{ "KEY-TIME", 0x00CD, 4 },
810
{ "KEY-ATTR", 0x0000, -5 },
811
{ "CA-FPR", 0x00C6, 3 },
812
{ "CHV-STATUS", 0x00C4, 1 },
813
{ "SIG-COUNTER", 0x0093, 2 },
814
{ "SERIALNO", 0x004F, -1 },
816
{ "EXTCAP", 0x0000, -2 },
817
{ "PRIVATE-DO-1", 0x0101 },
818
{ "PRIVATE-DO-2", 0x0102 },
819
{ "PRIVATE-DO-3", 0x0103 },
820
{ "PRIVATE-DO-4", 0x0104 },
821
{ "$AUTHKEYID", 0x0000, -3 },
822
{ "$DISPSERIALNO",0x0000, -4 },
827
unsigned char *value;
830
for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
832
if (!table[idx].name)
833
return gpg_error (GPG_ERR_INV_NAME);
835
if (table[idx].special == -1)
837
/* The serial number is very special. We could have used the
838
AID DO to retrieve it, but we have it already in the app
839
context and the stamp argument is required anyway which we
840
can't by other means. The AID DO is available anyway but not
846
if (!app_get_serial_and_stamp (app, &serial, &stamp))
848
sprintf (tmp, "%lu", (unsigned long)stamp);
849
send_status_info (ctrl, "SERIALNO",
850
serial, strlen (serial),
857
if (table[idx].special == -2)
861
snprintf (tmp, sizeof tmp,
862
"gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
863
app->app_local->extcap.get_challenge,
864
app->app_local->extcap.key_import,
865
app->app_local->extcap.change_force_chv,
866
app->app_local->extcap.private_dos,
867
app->app_local->extcap.max_certlen_3,
868
app->app_local->extcap.algo_attr_change,
869
(app->app_local->extcap.sm_supported
870
? (app->app_local->extcap.sm_aes128? 7 : 2)
872
send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
875
if (table[idx].special == -3)
877
char const tmp[] = "OPENPGP.3";
878
send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
881
if (table[idx].special == -4)
886
if (!app_get_serial_and_stamp (app, &serial, &stamp))
888
if (strlen (serial) > 16+12)
890
send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
896
return gpg_error (GPG_ERR_INV_NAME);
898
if (table[idx].special == -5)
900
for (i=0; i < 3; i++)
901
send_key_attr (ctrl, app, table[idx].name, i);
905
relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
908
if (table[idx].special == 1)
912
for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
913
sprintf (numbuf+strlen (numbuf), " %d", value[i]);
914
send_status_info (ctrl, table[idx].name,
915
numbuf, strlen (numbuf), NULL, 0);
917
else if (table[idx].special == 2)
921
sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
922
send_status_info (ctrl, table[idx].name,
923
numbuf, strlen (numbuf), NULL, 0);
925
else if (table[idx].special == 3)
928
for (i=0; i < 3; i++)
929
send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
931
else if (table[idx].special == 4)
934
for (i=0; i < 3; i++)
935
send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
938
send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
945
/* Retrieve the fingerprint from the card inserted in SLOT and write
946
the according hex representation to FPR. Caller must have provide
947
a buffer at FPR of least 41 bytes. Returns 0 on success or an
949
#if GNUPG_MAJOR_VERSION > 1
951
retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
955
unsigned char *value;
958
assert (keyno >=0 && keyno <= 2);
960
relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
961
if (relptr && valuelen >= 60)
962
bin2hex (value+keyno*20, 20, fpr);
964
err = gpg_error (GPG_ERR_NOT_FOUND);
968
#endif /*GNUPG_MAJOR_VERSION > 1*/
971
/* Retrieve the public key material for the RSA key, whose fingerprint
972
is FPR, from gpg output, which can be read through the stream FP.
973
The RSA modulus will be stored at the address of M and MLEN, the
974
public exponent at E and ELEN. Returns zero on success, an error
975
code on failure. Caller must release the allocated buffers at M
976
and E if the function returns success. */
977
#if GNUPG_MAJOR_VERSION > 1
979
retrieve_key_material (FILE *fp, const char *hexkeyid,
980
const unsigned char **m, size_t *mlen,
981
const unsigned char **e, size_t *elen)
983
gcry_error_t err = 0;
984
char *line = NULL; /* read_line() buffer. */
985
size_t line_size = 0; /* Helper for for read_line. */
986
int found_key = 0; /* Helper to find a matching key. */
987
unsigned char *m_new = NULL;
988
unsigned char *e_new = NULL;
992
/* Loop over all records until we have found the subkey
993
corresponding to the fingerprint. Inm general the first record
994
should be the pub record, but we don't rely on that. Given that
995
we only need to look at one key, it is sufficient to compare the
996
keyid so that we don't need to look at "fpr" records. */
1007
i = read_line (fp, &line, &line_size, &max_length);
1012
err = gpg_error_from_syserror ();
1013
goto leave; /* Error. */
1017
err = gpg_error (GPG_ERR_TRUNCATED);
1018
goto leave; /* Line truncated - we better stop processing. */
1021
/* Parse the line into fields. */
1022
for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1024
fields[nfields] = p;
1025
p = strchr (p, ':');
1030
continue; /* No fields at all - skip line. */
1034
if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1035
&& nfields > 4 && !strcmp (fields[4], hexkeyid))
1040
if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1041
break; /* Next key - stop. */
1043
if ( strcmp (fields[0], "pkd") )
1044
continue; /* Not a key data record. */
1045
i = 0; /* Avoid erroneous compiler warning. */
1046
if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1047
|| (!i && m_new) || (i && e_new))
1049
err = gpg_error (GPG_ERR_GENERAL);
1050
goto leave; /* Error: Invalid key data record or not an RSA key. */
1053
err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1057
err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1059
err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1060
gcry_mpi_release (mpi);
1075
err = gpg_error (GPG_ERR_GENERAL);
1083
#endif /*GNUPG_MAJOR_VERSION > 1*/
1086
/* Get the public key for KEYNO and store it as an S-expresion with
1087
the APP handle. On error that field gets cleared. If we already
1088
know about the public key we will just return. Note that this does
1089
not mean a key is available; this is soley indicated by the
1090
presence of the app->app_local->pk[KEYNO-1].key field.
1092
Note that GnuPG 1.x does not need this and it would be too time
1093
consuming to send it just for the fun of it. However, given that we
1094
use the same code in gpg 1.4, we can't use the gcry S-expresion
1095
here but need to open encode it. */
1096
#if GNUPG_MAJOR_VERSION > 1
1098
get_public_key (app_t app, int keyno)
1100
gpg_error_t err = 0;
1101
unsigned char *buffer;
1102
const unsigned char *keydata, *m, *e;
1103
size_t buflen, keydatalen, mlen, elen;
1104
unsigned char *mbuf = NULL;
1105
unsigned char *ebuf = NULL;
1106
char *keybuf = NULL;
1109
if (keyno < 1 || keyno > 3)
1110
return gpg_error (GPG_ERR_INV_ID);
1113
/* Already cached? */
1114
if (app->app_local->pk[keyno].read_done)
1117
xfree (app->app_local->pk[keyno].key);
1118
app->app_local->pk[keyno].key = NULL;
1119
app->app_local->pk[keyno].keylen = 0;
1121
m = e = NULL; /* (avoid cc warning) */
1123
if (app->card_version > 0x0100)
1125
int exmode, le_value;
1127
/* We may simply read the public key out of these cards. */
1128
if (app->app_local->cardcap.ext_lc_le)
1130
exmode = 1; /* Use extended length. */
1131
le_value = app->app_local->extcap.max_rsp_data;
1136
le_value = 256; /* Use legacy value. */
1139
err = iso7816_read_public_key
1141
(const unsigned char*)(keyno == 0? "\xB6" :
1142
keyno == 1? "\xB8" : "\xA4"), 2,
1147
log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1151
keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1154
err = gpg_error (GPG_ERR_CARD);
1155
log_error (_("response does not contain the public key data\n"));
1159
m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1162
err = gpg_error (GPG_ERR_CARD);
1163
log_error (_("response does not contain the RSA modulus\n"));
1168
e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1171
err = gpg_error (GPG_ERR_CARD);
1172
log_error (_("response does not contain the RSA public exponent\n"));
1176
/* Prepend numbers with a 0 if needed. */
1177
if (mlen && (*m & 0x80))
1179
mbuf = xtrymalloc ( mlen + 1);
1182
err = gpg_error_from_syserror ();
1186
memcpy (mbuf+1, m, mlen);
1190
if (elen && (*e & 0x80))
1192
ebuf = xtrymalloc ( elen + 1);
1195
err = gpg_error_from_syserror ();
1199
memcpy (ebuf+1, e, elen);
1207
/* Due to a design problem in v1.0 cards we can't get the public
1208
key out of these cards without doing a verify on CHV3.
1209
Clearly that is not an option and thus we try to locate the
1210
key using an external helper.
1212
The helper we use here is gpg itself, which should know about
1213
the key in any case. */
1217
char *command = NULL;
1221
buffer = NULL; /* We don't need buffer. */
1223
err = retrieve_fpr_from_card (app, keyno, fpr);
1226
log_error ("error while retrieving fpr from card: %s\n",
1227
gpg_strerror (err));
1230
hexkeyid = fpr + 24;
1232
ret = estream_asprintf (&command,
1233
"gpg --list-keys --with-colons --with-key-data '%s'",
1237
err = gpg_error_from_syserror ();
1241
fp = popen (command, "r");
1245
err = gpg_error_from_syserror ();
1246
log_error ("running gpg failed: %s\n", gpg_strerror (err));
1250
err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1254
log_error ("error while retrieving key material through pipe: %s\n",
1255
gpg_strerror (err));
1260
/* Allocate a buffer to construct the S-expression. */
1261
/* FIXME: We should provide a generalized S-expression creation
1263
keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1266
err = gpg_error_from_syserror ();
1270
sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1271
keybuf_p = keybuf + strlen (keybuf);
1272
memcpy (keybuf_p, m, mlen);
1274
sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1275
keybuf_p += strlen (keybuf_p);
1276
memcpy (keybuf_p, e, elen);
1278
strcpy (keybuf_p, ")))");
1279
keybuf_p += strlen (keybuf_p);
1281
app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1282
app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1285
/* Set a flag to indicate that we tried to read the key. */
1286
app->app_local->pk[keyno].read_done = 1;
1293
#endif /* GNUPG_MAJOR_VERSION > 1 */
1297
/* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1298
This is used by the LEARN command. */
1300
send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1302
gpg_error_t err = 0;
1303
/* Note that GnuPG 1.x does not need this and it would be too time
1304
consuming to send it just for the fun of it. */
1305
#if GNUPG_MAJOR_VERSION > 1
1306
unsigned char grip[20];
1310
err = get_public_key (app, keyno);
1314
assert (keyno >= 1 && keyno <= 3);
1315
if (!app->app_local->pk[keyno-1].key)
1316
goto leave; /* No such key - ignore. */
1318
err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1319
app->app_local->pk[keyno-1].keylen,
1324
bin2hex (grip, 20, gripstr);
1326
sprintf (idbuf, "OPENPGP.%d", keyno);
1327
send_status_info (ctrl, "KEYPAIRINFO",
1329
idbuf, strlen (idbuf),
1333
#endif /* GNUPG_MAJOR_VERSION > 1 */
1339
/* Handle the LEARN command for OpenPGP. */
1341
do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1345
do_getattr (app, ctrl, "EXTCAP");
1346
do_getattr (app, ctrl, "DISP-NAME");
1347
do_getattr (app, ctrl, "DISP-LANG");
1348
do_getattr (app, ctrl, "DISP-SEX");
1349
do_getattr (app, ctrl, "PUBKEY-URL");
1350
do_getattr (app, ctrl, "LOGIN-DATA");
1351
do_getattr (app, ctrl, "KEY-FPR");
1352
if (app->card_version > 0x0100)
1353
do_getattr (app, ctrl, "KEY-TIME");
1354
do_getattr (app, ctrl, "CA-FPR");
1355
do_getattr (app, ctrl, "CHV-STATUS");
1356
do_getattr (app, ctrl, "SIG-COUNTER");
1357
if (app->app_local->extcap.private_dos)
1359
do_getattr (app, ctrl, "PRIVATE-DO-1");
1360
do_getattr (app, ctrl, "PRIVATE-DO-2");
1362
do_getattr (app, ctrl, "PRIVATE-DO-3");
1364
do_getattr (app, ctrl, "PRIVATE-DO-4");
1366
send_keypair_info (app, ctrl, 1);
1367
send_keypair_info (app, ctrl, 2);
1368
send_keypair_info (app, ctrl, 3);
1369
/* Note: We do not send the Cardholder Certificate, because that is
1370
relativly long and for OpenPGP applications not really needed. */
1375
/* Handle the READKEY command for OpenPGP. On success a canonical
1376
encoded S-expression with the public key will get stored at PK and
1377
its length (for assertions) at PKLEN; the caller must release that
1378
buffer. On error PK and PKLEN are not changed and an error code is
1381
do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1383
#if GNUPG_MAJOR_VERSION > 1
1388
if (!strcmp (keyid, "OPENPGP.1"))
1390
else if (!strcmp (keyid, "OPENPGP.2"))
1392
else if (!strcmp (keyid, "OPENPGP.3"))
1395
return gpg_error (GPG_ERR_INV_ID);
1397
err = get_public_key (app, keyno);
1401
buf = app->app_local->pk[keyno-1].key;
1403
return gpg_error (GPG_ERR_NO_PUBKEY);
1404
*pklen = app->app_local->pk[keyno-1].keylen;;
1405
*pk = xtrymalloc (*pklen);
1408
err = gpg_error_from_syserror ();
1412
memcpy (*pk, buf, *pklen);
1415
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1419
/* Read the standard certificate of an OpenPGP v2 card. It is
1420
returned in a freshly allocated buffer with that address stored at
1421
CERT and the length of the certificate stored at CERTLEN. CERTID
1422
needs to be set to "OPENPGP.3". */
1424
do_readcert (app_t app, const char *certid,
1425
unsigned char **cert, size_t *certlen)
1427
#if GNUPG_MAJOR_VERSION > 1
1429
unsigned char *buffer;
1435
if (strcmp (certid, "OPENPGP.3"))
1436
return gpg_error (GPG_ERR_INV_ID);
1437
if (!app->app_local->extcap.is_v2)
1438
return gpg_error (GPG_ERR_NOT_FOUND);
1440
relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1442
return gpg_error (GPG_ERR_NOT_FOUND);
1445
err = gpg_error (GPG_ERR_NOT_FOUND);
1446
else if (!(*cert = xtrymalloc (buflen)))
1447
err = gpg_error_from_syserror ();
1450
memcpy (*cert, buffer, buflen);
1457
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1462
/* Verify a CHV either using using the pinentry or if possibile by
1463
using a keypad. PINCB and PINCB_ARG describe the usual callback
1464
for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only
1465
used with CHV1. PINVALUE is the address of a pointer which will
1466
receive a newly allocated block with the actual PIN (this is useful
1467
in case that PIN shall be used for another verify operation). The
1468
caller needs to free this value. If the function returns with
1469
success and NULL is stored at PINVALUE, the caller should take this
1470
as an indication that the keypad has been used.
1473
verify_a_chv (app_t app,
1474
gpg_error_t (*pincb)(void*, const char *, char **),
1476
int chvno, unsigned long sigcount, char **pinvalue)
1479
char *prompt_buffer = NULL;
1481
iso7816_pininfo_t pininfo;
1484
assert (chvno == 1 || chvno == 2);
1488
if (chvno == 2 && app->app_local->flags.def_chv2)
1490
/* Special case for def_chv2 mechanism. */
1492
log_info (_("using default PIN as %s\n"), "CHV2");
1493
rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1496
/* Verification of CHV2 with the default PIN failed,
1497
although the card pretends to have the default PIN set as
1498
CHV2. We better disable the def_chv2 flag now. */
1499
log_info (_("failed to use default PIN as %s: %s"
1500
" - disabling further default use\n"),
1501
"CHV2", gpg_strerror (rc));
1502
app->app_local->flags.def_chv2 = 0;
1507
memset (&pininfo, 0, sizeof pininfo);
1509
pininfo.minlen = minlen;
1514
#define PROMPTSTRING _("||Please enter the PIN%%0A[sigs done: %lu]")
1515
size_t promptsize = strlen (PROMPTSTRING) + 50;
1517
prompt_buffer = xtrymalloc (promptsize);
1519
return gpg_error_from_syserror ();
1520
snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1521
prompt = prompt_buffer;
1525
prompt = _("||Please enter the PIN");
1528
if (!opt.disable_keypad
1529
&& !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1531
/* The reader supports the verify command through the keypad.
1532
Note that the pincb appends a text to the prompt telling the
1533
user to use the keypad. */
1534
rc = pincb (pincb_arg, prompt, NULL);
1536
xfree (prompt_buffer);
1537
prompt_buffer = NULL;
1540
log_info (_("PIN callback returned error: %s\n"),
1544
rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1545
/* Dismiss the prompt. */
1546
pincb (pincb_arg, NULL, NULL);
1548
assert (!*pinvalue);
1552
/* The reader has no keypad or we don't want to use it. */
1553
rc = pincb (pincb_arg, prompt, pinvalue);
1555
xfree (prompt_buffer);
1556
prompt_buffer = NULL;
1559
log_info (_("PIN callback returned error: %s\n"),
1564
if (strlen (*pinvalue) < minlen)
1566
log_error (_("PIN for CHV%d is too short;"
1567
" minimum length is %d\n"), chvno, minlen);
1570
return gpg_error (GPG_ERR_BAD_PIN);
1573
rc = iso7816_verify (app->slot, 0x80+chvno,
1574
*pinvalue, strlen (*pinvalue));
1579
log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1582
flush_cache_after_error (app);
1589
/* Verify CHV2 if required. Depending on the configuration of the
1590
card CHV1 will also be verified. */
1592
verify_chv2 (app_t app,
1593
gpg_error_t (*pincb)(void*, const char *, char **),
1600
return 0; /* We already verified CHV2. */
1602
rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1607
if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1609
/* For convenience we verify CHV1 here too. We do this only if
1610
the card is not configured to require a verification before
1611
each CHV1 controlled operation (force_chv1) and if we are not
1612
using the keypad (PINVALUE == NULL). */
1613
rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1614
if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1615
rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1618
log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1619
flush_cache_after_error (app);
1631
/* Build the prompt to enter the Admin PIN. The prompt depends on the
1632
current sdtate of the card. */
1634
build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1637
unsigned char *value;
1644
relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1645
if (!relptr || valuelen < 7)
1647
log_error (_("error retrieving CHV status from card\n"));
1649
return gpg_error (GPG_ERR_CARD);
1653
log_info (_("card is permanently locked!\n"));
1655
return gpg_error (GPG_ERR_BAD_PIN);
1657
remaining = value[6];
1660
log_info(_("%d Admin PIN attempts remaining before card"
1661
" is permanently locked\n"), remaining);
1665
/* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1666
the start of the string. Use %%0A to force a linefeed. */
1667
prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1668
"[remaining attempts: %d]"), remaining);
1671
prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1674
return gpg_error_from_syserror ();
1681
/* Verify CHV3 if required. */
1683
verify_chv3 (app_t app,
1684
gpg_error_t (*pincb)(void*, const char *, char **),
1689
#if GNUPG_MAJOR_VERSION != 1
1690
if (!opt.allow_admin)
1692
log_info (_("access to admin commands is not configured\n"));
1693
return gpg_error (GPG_ERR_EACCES);
1699
iso7816_pininfo_t pininfo;
1703
memset (&pininfo, 0, sizeof pininfo);
1705
pininfo.minlen = minlen;
1707
rc = build_enter_admin_pin_prompt (app, &prompt);
1711
if (!opt.disable_keypad
1712
&& !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1714
/* The reader supports the verify command through the keypad. */
1715
rc = pincb (pincb_arg, prompt, NULL);
1720
log_info (_("PIN callback returned error: %s\n"),
1724
rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1725
/* Dismiss the prompt. */
1726
pincb (pincb_arg, NULL, NULL);
1732
rc = pincb (pincb_arg, prompt, &pinvalue);
1737
log_info (_("PIN callback returned error: %s\n"),
1742
if (strlen (pinvalue) < minlen)
1744
log_error (_("PIN for CHV%d is too short;"
1745
" minimum length is %d\n"), 3, minlen);
1747
return gpg_error (GPG_ERR_BAD_PIN);
1750
rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1756
log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1757
flush_cache_after_error (app);
1766
/* Handle the SETATTR operation. All arguments are already basically
1769
do_setattr (app_t app, const char *name,
1770
gpg_error_t (*pincb)(void*, const char *, char **),
1772
const unsigned char *value, size_t valuelen)
1781
unsigned int need_v2:1;
1783
{ "DISP-NAME", 0x005B, 3 },
1784
{ "LOGIN-DATA", 0x005E, 3, 2 },
1785
{ "DISP-LANG", 0x5F2D, 3 },
1786
{ "DISP-SEX", 0x5F35, 3 },
1787
{ "PUBKEY-URL", 0x5F50, 3 },
1788
{ "CHV-STATUS-1", 0x00C4, 3, 1 },
1789
{ "CA-FPR-1", 0x00CA, 3 },
1790
{ "CA-FPR-2", 0x00CB, 3 },
1791
{ "CA-FPR-3", 0x00CC, 3 },
1792
{ "PRIVATE-DO-1", 0x0101, 2 },
1793
{ "PRIVATE-DO-2", 0x0102, 3 },
1794
{ "PRIVATE-DO-3", 0x0103, 2 },
1795
{ "PRIVATE-DO-4", 0x0104, 3 },
1796
{ "CERT-3", 0x7F21, 3, 0, 1 },
1797
{ "SM-KEY-ENC", 0x00D1, 3, 0, 1 },
1798
{ "SM-KEY-MAC", 0x00D2, 3, 0, 1 },
1799
{ "KEY-ATTR", 0, 0, 3, 1 },
1804
for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1806
if (!table[idx].name)
1807
return gpg_error (GPG_ERR_INV_NAME);
1808
if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1809
return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */
1811
if (table[idx].special == 3)
1812
return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
1814
switch (table[idx].need_chv)
1817
rc = verify_chv2 (app, pincb, pincb_arg);
1820
rc = verify_chv3 (app, pincb, pincb_arg);
1828
/* Flush the cache before writing it, so that the next get operation
1829
will reread the data from the card and thus get synced in case of
1830
errors (e.g. data truncated by the card). */
1831
flush_cache_item (app, table[idx].tag);
1833
if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1834
exmode = 1; /* Use extended length w/o a limit. */
1835
else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1836
exmode = -254; /* Command chaining with max. 254 bytes. */
1839
rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1841
log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1843
if (table[idx].special == 1)
1844
app->force_chv1 = (valuelen && *value == 0);
1845
else if (table[idx].special == 2)
1846
parse_login_data (app);
1852
/* Handle the WRITECERT command for OpenPGP. This rites the standard
1853
certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1854
PINCB and PINCB_ARG are the usual arguments for the pinentry
1857
do_writecert (app_t app, ctrl_t ctrl,
1858
const char *certidstr,
1859
gpg_error_t (*pincb)(void*, const char *, char **),
1861
const unsigned char *certdata, size_t certdatalen)
1864
#if GNUPG_MAJOR_VERSION > 1
1865
if (strcmp (certidstr, "OPENPGP.3"))
1866
return gpg_error (GPG_ERR_INV_ID);
1867
if (!certdata || !certdatalen)
1868
return gpg_error (GPG_ERR_INV_ARG);
1869
if (!app->app_local->extcap.is_v2)
1870
return gpg_error (GPG_ERR_NOT_SUPPORTED);
1871
if (certdatalen > app->app_local->extcap.max_certlen_3)
1872
return gpg_error (GPG_ERR_TOO_LARGE);
1873
return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1875
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1881
/* Handle the PASSWD command. The following combinations are
1884
Flags CHVNO Vers. Description
1885
RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2
1886
RESET 1 2 Verify PW3 and set a new PW1.
1887
RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2.
1888
RESET 2 2 Verify PW3 and set a new Reset Code.
1889
RESET 3 any Returns GPG_ERR_INV_ID.
1890
- 1 1 Verify CHV2 and set a new CHV1 and CHV2.
1891
- 1 2 Verify PW1 and set a new PW1.
1892
- 2 1 Verify CHV2 and set a new CHV1 and CHV2.
1893
- 2 2 Verify Reset Code and set a new PW1.
1894
- 3 any Verify CHV3/PW3 and set a new CHV3/PW3.
1897
do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr,
1899
gpg_error_t (*pincb)(void*, const char *, char **),
1903
int chvno = atoi (chvnostr);
1904
char *resetcode = NULL;
1905
char *oldpinvalue = NULL;
1907
int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1908
int set_resetcode = 0;
1912
if (reset_mode && chvno == 3)
1914
rc = gpg_error (GPG_ERR_INV_ID);
1918
if (!app->app_local->extcap.is_v2)
1920
/* Version 1 cards. */
1922
if (reset_mode || chvno == 3)
1924
/* We always require that the PIN is entered. */
1926
rc = verify_chv3 (app, pincb, pincb_arg);
1930
else if (chvno == 1 || chvno == 2)
1932
/* On a v1.x card CHV1 and CVH2 should always have the same
1933
value, thus we enforce it here. */
1934
int save_force = app->force_chv1;
1936
app->force_chv1 = 0;
1939
rc = verify_chv2 (app, pincb, pincb_arg);
1940
app->force_chv1 = save_force;
1946
rc = gpg_error (GPG_ERR_INV_ID);
1952
/* Version 2 cards. */
1956
/* To reset a PIN the Admin PIN is required. */
1958
rc = verify_chv3 (app, pincb, pincb_arg);
1965
else if (chvno == 1 || chvno == 3)
1967
int minlen = (chvno ==3)? 8 : 6;
1968
char *promptbuf = NULL;
1973
rc = build_enter_admin_pin_prompt (app, &promptbuf);
1979
prompt = _("||Please enter the PIN");
1980
rc = pincb (pincb_arg, prompt, &oldpinvalue);
1985
log_info (_("PIN callback returned error: %s\n"),
1990
if (strlen (oldpinvalue) < minlen)
1992
log_info (_("PIN for CHV%d is too short;"
1993
" minimum length is %d\n"), chvno, minlen);
1994
rc = gpg_error (GPG_ERR_BAD_PIN);
1998
else if (chvno == 2)
2000
/* There is no PW2 for v2 cards. We use this condition to
2001
allow a PW reset using the Reset Code. */
2003
unsigned char *value;
2008
relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2009
if (!relptr || valuelen < 7)
2011
log_error (_("error retrieving CHV status from card\n"));
2013
rc = gpg_error (GPG_ERR_CARD);
2016
remaining = value[5];
2020
log_error (_("Reset Code not or not anymore available\n"));
2021
rc = gpg_error (GPG_ERR_BAD_PIN);
2025
rc = pincb (pincb_arg,
2026
_("||Please enter the Reset Code for the card"),
2030
log_info (_("PIN callback returned error: %s\n"),
2034
if (strlen (resetcode) < minlen)
2036
log_info (_("Reset Code is too short; minimum length is %d\n"),
2038
rc = gpg_error (GPG_ERR_BAD_PIN);
2044
rc = gpg_error (GPG_ERR_INV_ID);
2052
app->did_chv1 = app->did_chv2 = 0;
2054
/* TRANSLATORS: Do not translate the "|*|" prefixes but
2055
keep it at the start of the string. We need this elsewhere
2056
to get some infos on the string. */
2057
rc = pincb (pincb_arg,
2058
set_resetcode? _("|RN|New Reset Code") :
2059
chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2063
log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2072
buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2074
rc = gpg_error_from_syserror ();
2077
strcpy (stpcpy (buffer, resetcode), pinvalue);
2078
rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2079
buffer, strlen (buffer));
2080
wipememory (buffer, strlen (buffer));
2084
else if (set_resetcode)
2086
if (strlen (pinvalue) < 8)
2088
log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2089
rc = gpg_error (GPG_ERR_BAD_PIN);
2092
rc = iso7816_put_data (app->slot, 0, 0xD3,
2093
pinvalue, strlen (pinvalue));
2095
else if (reset_mode)
2097
rc = iso7816_reset_retry_counter (app->slot, 0x81,
2098
pinvalue, strlen (pinvalue));
2099
if (!rc && !app->app_local->extcap.is_v2)
2100
rc = iso7816_reset_retry_counter (app->slot, 0x82,
2101
pinvalue, strlen (pinvalue));
2103
else if (!app->app_local->extcap.is_v2)
2105
/* Version 1 cards. */
2106
if (chvno == 1 || chvno == 2)
2108
rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2109
pinvalue, strlen (pinvalue));
2111
rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2112
pinvalue, strlen (pinvalue));
2114
else /* CHVNO == 3 */
2116
rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2117
pinvalue, strlen (pinvalue));
2122
/* Version 2 cards. */
2123
assert (chvno == 1 || chvno == 3);
2125
rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2126
oldpinvalue, strlen (oldpinvalue),
2127
pinvalue, strlen (pinvalue));
2132
wipememory (pinvalue, strlen (pinvalue));
2136
flush_cache_after_error (app);
2141
wipememory (resetcode, strlen (resetcode));
2146
wipememory (oldpinvalue, strlen (oldpinvalue));
2147
xfree (oldpinvalue);
2153
/* Check whether a key already exists. KEYIDX is the index of the key
2154
(0..2). If FORCE is TRUE a diagnositic will be printed but no
2155
error returned if the key already exists. The flag GENERATING is
2156
only used to print correct messages. */
2158
does_key_exist (app_t app, int keyidx, int generating, int force)
2160
const unsigned char *fpr;
2161
unsigned char *buffer;
2165
assert (keyidx >=0 && keyidx <= 2);
2167
if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2169
log_error (_("error reading application data\n"));
2170
return gpg_error (GPG_ERR_GENERAL);
2172
fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2175
log_error (_("error reading fingerprint DO\n"));
2177
return gpg_error (GPG_ERR_GENERAL);
2180
for (i=0; i < 20 && !fpr[i]; i++)
2183
if (i!=20 && !force)
2185
log_error (_("key already exists\n"));
2186
return gpg_error (GPG_ERR_EEXIST);
2189
log_info (_("existing key will be replaced\n"));
2190
else if (generating)
2191
log_info (_("generating new key\n"));
2193
log_info (_("writing new key\n"));
2198
/* Create a TLV tag and value and store it at BUFFER. Return the length
2199
of tag and length. A LENGTH greater than 65535 is truncated. */
2201
add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2203
unsigned char *p = buffer;
2205
assert (tag <= 0xffff);
2211
else if (length < 256)
2218
if (length > 0xffff)
2229
/* Build the private key template as specified in the OpenPGP specs
2230
v2.0 section 4.3.3.7. */
2232
build_privkey_template (app_t app, int keyno,
2233
const unsigned char *rsa_n, size_t rsa_n_len,
2234
const unsigned char *rsa_e, size_t rsa_e_len,
2235
const unsigned char *rsa_p, size_t rsa_p_len,
2236
const unsigned char *rsa_q, size_t rsa_q_len,
2237
unsigned char **result, size_t *resultlen)
2239
size_t rsa_e_reqlen;
2240
unsigned char privkey[7*(1+3)];
2242
unsigned char exthdr[2+2+3];
2244
unsigned char suffix[2+3];
2248
unsigned char *template;
2249
size_t template_size;
2254
switch (app->app_local->keyattr[keyno].format)
2261
return gpg_error (GPG_ERR_NOT_SUPPORTED);
2264
return gpg_error (GPG_ERR_INV_VALUE);
2267
/* Get the required length for E. */
2268
rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2269
assert (rsa_e_len <= rsa_e_reqlen);
2271
/* Build the 7f48 cardholder private key template. */
2275
tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2276
datalen += rsa_e_reqlen;
2278
tp += add_tlv (tp, 0x92, rsa_p_len);
2279
datalen += rsa_p_len;
2281
tp += add_tlv (tp, 0x93, rsa_q_len);
2282
datalen += rsa_q_len;
2284
if (app->app_local->keyattr[keyno].format == RSA_STD_N
2285
|| app->app_local->keyattr[keyno].format == RSA_CRT_N)
2287
tp += add_tlv (tp, 0x97, rsa_n_len);
2288
datalen += rsa_n_len;
2290
privkey_len = tp - privkey;
2292
/* Build the extended header list without the private key template. */
2294
*tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2296
tp += add_tlv (tp, 0x7f48, privkey_len);
2297
exthdr_len = tp - exthdr;
2299
/* Build the 5f48 suffix of the data. */
2301
tp += add_tlv (tp, 0x5f48, datalen);
2302
suffix_len = tp - suffix;
2304
/* Now concatenate everything. */
2305
template_size = (1 + 3 /* 0x4d and len. */
2310
tp = template = xtrymalloc_secure (template_size);
2312
return gpg_error_from_syserror ();
2314
tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2315
memcpy (tp, exthdr, exthdr_len);
2317
memcpy (tp, privkey, privkey_len);
2319
memcpy (tp, suffix, suffix_len);
2322
memcpy (tp, rsa_e, rsa_e_len);
2323
if (rsa_e_len < rsa_e_reqlen)
2325
/* Right justify E. */
2326
memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2327
memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2331
memcpy (tp, rsa_p, rsa_p_len);
2334
memcpy (tp, rsa_q, rsa_q_len);
2337
if (app->app_local->keyattr[keyno].format == RSA_STD_N
2338
|| app->app_local->keyattr[keyno].format == RSA_CRT_N)
2340
memcpy (tp, rsa_n, rsa_n_len);
2344
/* Sanity check. We don't know the exact length because we
2345
allocated 3 bytes for the first length header. */
2346
assert (tp - template <= template_size);
2349
*resultlen = tp - template;
2354
/* Helper for do_writekley to change the size of a key. Not ethat
2355
this deletes the entire key without asking. */
2357
change_keyattr (app_t app, int keyno, unsigned int nbits,
2358
gpg_error_t (*pincb)(void*, const char *, char **),
2362
unsigned char *buffer;
2366
assert (keyno >=0 && keyno <= 2);
2369
return gpg_error (GPG_ERR_TOO_LARGE);
2371
/* Read the current attributes into a buffer. */
2372
relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
2374
return gpg_error (GPG_ERR_CARD);
2375
if (buflen < 6 || buffer[0] != 1)
2377
/* Attriutes too short or not an RSA key. */
2379
return gpg_error (GPG_ERR_CARD);
2382
/* We only change n_bits and don't touch anything else. Before we
2383
do so, we round up NBITS to a sensible way in the same way as
2384
gpg's key generation does it. This may help to sort out problems
2385
with a few bits too short keys. */
2386
nbits = ((nbits + 31) / 32) * 32;
2387
buffer[1] = (nbits >> 8);
2390
/* Prepare for storing the key. */
2391
err = verify_chv3 (app, pincb, pincb_arg);
2398
/* Change the attribute. */
2399
err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
2402
log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
2404
log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
2406
parse_algorithm_attribute (app, keyno);
2414
/* Helper to process an setattr command for name KEY-ATTR. It expects
2415
a string "--force <keyno> <algo> <nbits>" in (VALUE,VALUELEN). */
2417
change_keyattr_from_string (app_t app,
2418
gpg_error_t (*pincb)(void*, const char *, char **),
2420
const void *value, size_t valuelen)
2427
/* VALUE is expected to be a string but not guaranteed to be
2428
terminated. Thus copy it to an allocated buffer first. */
2429
string = xtrymalloc (valuelen+1);
2431
return gpg_error_from_syserror ();
2432
memcpy (string, value, valuelen);
2433
string[valuelen] = 0;
2435
/* Because this function deletes the key we require the string
2436
"--force" in the data to make clear that something serious might
2438
if (sscanf (string, " --force %d %d %u", &keyno, &algo, &nbits) != 3)
2439
err = gpg_error (GPG_ERR_INV_DATA);
2440
else if (keyno < 1 || keyno > 3)
2441
err = gpg_error (GPG_ERR_INV_ID);
2443
err = gpg_error (GPG_ERR_PUBKEY_ALGO); /* Not RSA. */
2444
else if (nbits < 1024)
2445
err = gpg_error (GPG_ERR_TOO_SHORT);
2447
err = change_keyattr (app, keyno-1, nbits, pincb, pincb_arg);
2454
/* Handle the WRITEKEY command for OpenPGP. This function expects a
2455
canonical encoded S-expression with the secret key in KEYDATA and
2456
its length (for assertions) in KEYDATALEN. KEYID needs to be the
2457
usual keyid which for OpenPGP is the string "OPENPGP.n" with
2458
n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall
2459
get overwritten. PINCB and PINCB_ARG are the usual arguments for
2460
the pinentry callback. */
2462
do_writekey (app_t app, ctrl_t ctrl,
2463
const char *keyid, unsigned int flags,
2464
gpg_error_t (*pincb)(void*, const char *, char **),
2466
const unsigned char *keydata, size_t keydatalen)
2469
int force = (flags & 1);
2471
const unsigned char *buf, *tok;
2472
size_t buflen, toklen;
2473
int depth, last_depth1, last_depth2;
2474
const unsigned char *rsa_n = NULL;
2475
const unsigned char *rsa_e = NULL;
2476
const unsigned char *rsa_p = NULL;
2477
const unsigned char *rsa_q = NULL;
2478
size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2480
unsigned int maxbits;
2481
unsigned char *template = NULL;
2483
size_t template_len;
2484
unsigned char fprbuf[20];
2489
if (!strcmp (keyid, "OPENPGP.1"))
2491
else if (!strcmp (keyid, "OPENPGP.2"))
2493
else if (!strcmp (keyid, "OPENPGP.3"))
2496
return gpg_error (GPG_ERR_INV_ID);
2498
err = does_key_exist (app, keyno, 0, force);
2504
Parse the S-expression
2507
buflen = keydatalen;
2509
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2511
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2513
if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2517
else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2518
log_info ("protected-private-key passed to writekey\n");
2519
else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2520
log_info ("shadowed-private-key passed to writekey\n");
2521
err = gpg_error (GPG_ERR_BAD_SECKEY);
2524
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2526
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2528
if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2530
err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2533
last_depth1 = depth;
2534
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2535
&& depth && depth >= last_depth1)
2539
err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2542
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2544
if (tok && toklen == 1)
2546
const unsigned char **mpi;
2551
case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2552
case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2553
case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2554
case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2555
default: mpi = NULL; mpi_len = NULL; break;
2559
err = gpg_error (GPG_ERR_DUP_VALUE);
2562
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2566
/* Strip off leading zero bytes and save. */
2567
for (;toklen && !*tok; toklen--, tok++)
2573
/* Skip until end of list. */
2574
last_depth2 = depth;
2575
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2576
&& depth && depth >= last_depth2)
2581
/* Parse other attributes. */
2582
last_depth1 = depth;
2583
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2584
&& depth && depth >= last_depth1)
2588
err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2591
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2593
if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2595
if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2599
for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2601
created_at = created_at*10 + (*tok - '0');
2604
/* Skip until end of list. */
2605
last_depth2 = depth;
2606
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2607
&& depth && depth >= last_depth2)
2614
/* Check that we have all parameters and that they match the card
2618
log_error (_("creation timestamp missing\n"));
2619
err = gpg_error (GPG_ERR_INV_VALUE);
2623
maxbits = app->app_local->keyattr[keyno].n_bits;
2624
nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2626
log_info ("RSA modulus size is %u bits (%u bytes)\n",
2627
nbits, (unsigned int)rsa_n_len);
2628
if (nbits && nbits != maxbits
2629
&& app->app_local->extcap.algo_attr_change)
2631
/* Try to switch the key to a new length. */
2632
err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2634
maxbits = app->app_local->keyattr[keyno].n_bits;
2636
if (nbits != maxbits)
2638
log_error (_("RSA modulus missing or not of size %d bits\n"),
2640
err = gpg_error (GPG_ERR_BAD_SECKEY);
2644
maxbits = app->app_local->keyattr[keyno].e_bits;
2645
if (maxbits > 32 && !app->app_local->extcap.is_v2)
2646
maxbits = 32; /* Our code for v1 does only support 32 bits. */
2647
nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2648
if (nbits < 2 || nbits > maxbits)
2650
log_error (_("RSA public exponent missing or larger than %d bits\n"),
2652
err = gpg_error (GPG_ERR_BAD_SECKEY);
2656
maxbits = app->app_local->keyattr[keyno].n_bits/2;
2657
nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2658
if (nbits != maxbits)
2660
log_error (_("RSA prime %s missing or not of size %d bits\n"),
2662
err = gpg_error (GPG_ERR_BAD_SECKEY);
2665
nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2666
if (nbits != maxbits)
2668
log_error (_("RSA prime %s missing or not of size %d bits\n"),
2670
err = gpg_error (GPG_ERR_BAD_SECKEY);
2674
/* We need to remove the cached public key. */
2675
xfree (app->app_local->pk[keyno].key);
2676
app->app_local->pk[keyno].key = NULL;
2677
app->app_local->pk[keyno].keylen = 0;
2678
app->app_local->pk[keyno].read_done = 0;
2681
if (app->app_local->extcap.is_v2)
2683
/* Build the private key template as described in section 4.3.3.7 of
2684
the OpenPGP card specs version 2.0. */
2687
err = build_privkey_template (app, keyno,
2692
&template, &template_len);
2696
/* Prepare for storing the key. */
2697
err = verify_chv3 (app, pincb, pincb_arg);
2701
/* Store the key. */
2702
if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2703
exmode = 1; /* Use extended length w/o a limit. */
2704
else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2708
err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2709
template, template_len);
2713
/* Build the private key template as described in section 4.3.3.6 of
2714
the OpenPGP card specs version 1.1:
2715
0xC0 <length> public exponent
2716
0xC1 <length> prime p
2717
0xC2 <length> prime q
2719
assert (rsa_e_len <= 4);
2720
template_len = (1 + 1 + 4
2722
+ 1 + 1 + rsa_q_len);
2723
template = tp = xtrymalloc_secure (template_len);
2726
err = gpg_error_from_syserror ();
2731
memcpy (tp, rsa_e, rsa_e_len);
2734
/* Right justify E. */
2735
memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2736
memset (tp, 0, 4-rsa_e_len);
2742
memcpy (tp, rsa_p, rsa_p_len);
2747
memcpy (tp, rsa_q, rsa_q_len);
2750
assert (tp - template == template_len);
2752
/* Prepare for storing the key. */
2753
err = verify_chv3 (app, pincb, pincb_arg);
2757
/* Store the key. */
2758
err = iso7816_put_data (app->slot, 0,
2759
(app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2760
template, template_len);
2764
log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2768
err = store_fpr (app, keyno, created_at,
2769
rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2770
fprbuf, app->card_version);
2781
/* Handle the GENKEY command. */
2783
do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
2785
gpg_error_t (*pincb)(void*, const char *, char **),
2790
unsigned char fprbuf[20];
2791
const unsigned char *keydata, *m, *e;
2792
unsigned char *buffer = NULL;
2793
size_t buflen, keydatalen, mlen, elen;
2795
int keyno = atoi (keynostr);
2796
int force = (flags & 1);
2800
unsigned int keybits;
2802
if (keyno < 1 || keyno > 3)
2803
return gpg_error (GPG_ERR_INV_ID);
2806
/* We flush the cache to increase the traffic before a key
2807
generation. This _might_ help a card to gather more entropy. */
2810
/* Obviously we need to remove the cached public key. */
2811
xfree (app->app_local->pk[keyno].key);
2812
app->app_local->pk[keyno].key = NULL;
2813
app->app_local->pk[keyno].keylen = 0;
2814
app->app_local->pk[keyno].read_done = 0;
2816
/* Check whether a key already exists. */
2817
rc = does_key_exist (app, keyno, 1, force);
2821
/* Because we send the key parameter back via status lines we need
2822
to put a limit on the max. allowed keysize. 2048 bit will
2823
already lead to a 527 byte long status line and thus a 4096 bit
2824
key would exceed the Assuan line length limit. */
2825
keybits = app->app_local->keyattr[keyno].n_bits;
2827
return gpg_error (GPG_ERR_TOO_LARGE);
2829
/* Prepare for key generation by verifying the Admin PIN. */
2830
rc = verify_chv3 (app, pincb, pincb_arg);
2834
/* Test whether we will need extended length mode. (1900 is an
2835
arbitrary length which for sure fits into a short apdu.) */
2836
if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
2838
exmode = 1; /* Use extended length w/o a limit. */
2839
le_value = app->app_local->extcap.max_rsp_data;
2840
/* No need to check le_value because it comes from a 16 bit
2841
value and thus can't create an overflow on a 32 bit
2847
le_value = 256; /* Use legacy value. */
2850
log_info (_("please wait while key is being generated ...\n"));
2851
start_at = time (NULL);
2852
rc = iso7816_generate_keypair
2853
/* # warning key generation temporary replaced by reading an existing key. */
2854
/* rc = iso7816_read_public_key */
2856
(const unsigned char*)(keyno == 0? "\xB6" :
2857
keyno == 1? "\xB8" : "\xA4"), 2,
2862
rc = gpg_error (GPG_ERR_CARD);
2863
log_error (_("generating key failed\n"));
2866
log_info (_("key generation completed (%d seconds)\n"),
2867
(int)(time (NULL) - start_at));
2869
keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2872
rc = gpg_error (GPG_ERR_CARD);
2873
log_error (_("response does not contain the public key data\n"));
2877
m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2880
rc = gpg_error (GPG_ERR_CARD);
2881
log_error (_("response does not contain the RSA modulus\n"));
2884
/* log_printhex ("RSA n:", m, mlen); */
2885
send_key_data (ctrl, "n", m, mlen);
2887
e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2890
rc = gpg_error (GPG_ERR_CARD);
2891
log_error (_("response does not contain the RSA public exponent\n"));
2894
/* log_printhex ("RSA e:", e, elen); */
2895
send_key_data (ctrl, "e", e, elen);
2897
created_at = createtime? createtime : gnupg_get_time ();
2898
sprintf (numbuf, "%lu", (unsigned long)created_at);
2899
send_status_info (ctrl, "KEY-CREATED-AT",
2900
numbuf, (size_t)strlen(numbuf), NULL, 0);
2902
rc = store_fpr (app, keyno, (u32)created_at,
2903
m, mlen, e, elen, fprbuf, app->card_version);
2906
send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2915
static unsigned long
2916
convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2921
ul = (value[0] << 16) | (value[1] << 8) | value[2];
2924
log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2930
static unsigned long
2931
get_sig_counter (app_t app)
2934
unsigned char *value;
2938
relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2941
ul = convert_sig_counter_value (value, valuelen);
2947
compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2949
const unsigned char *fpr;
2950
unsigned char *buffer;
2954
assert (keyno >= 1 && keyno <= 3);
2956
rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
2959
log_error (_("error reading application data\n"));
2960
return gpg_error (GPG_ERR_GENERAL);
2962
fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2963
if (!fpr || n != 60)
2966
log_error (_("error reading fingerprint DO\n"));
2967
return gpg_error (GPG_ERR_GENERAL);
2969
fpr += (keyno-1)*20;
2970
for (i=0; i < 20; i++)
2971
if (sha1fpr[i] != fpr[i])
2974
log_info (_("fingerprint on card does not match requested one\n"));
2975
return gpg_error (GPG_ERR_WRONG_SECKEY);
2982
/* If a fingerprint has been specified check it against the one on the
2983
card. This allows for a meaningful error message in case the key
2984
on the card has been replaced but the shadow information known to
2985
gpg has not been updated. If there is no fingerprint we assume
2986
that this is okay. */
2988
check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2990
unsigned char tmp[20];
2994
for (s=fpr, n=0; hexdigitp (s); s++, n++)
2997
return gpg_error (GPG_ERR_INV_ID);
3001
return gpg_error (GPG_ERR_INV_ID);
3003
for (s=fpr, n=0; n < 20; s += 2, n++)
3004
tmp[n] = xtoi_2 (s);
3005
return compare_fingerprint (app, keyno, tmp);
3010
/* Compute a digital signature on INDATA which is expected to be the
3011
raw message digest. For this application the KEYIDSTR consists of
3012
the serialnumber and the fingerprint delimited by a slash.
3014
Note that this function may return the error code
3015
GPG_ERR_WRONG_CARD to indicate that the card currently present does
3016
not match the one required for the requested action (e.g. the
3017
serial number does not match).
3019
As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3020
operation to the auth command.
3023
do_sign (app_t app, const char *keyidstr, int hashalgo,
3024
gpg_error_t (*pincb)(void*, const char *, char **),
3026
const void *indata, size_t indatalen,
3027
unsigned char **outdata, size_t *outdatalen )
3029
static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3030
{ 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3031
0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3032
static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */
3033
{ 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3034
0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3035
static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3036
{ 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3037
0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3039
static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3040
{ 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3041
0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3043
static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3044
{ 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3045
0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3047
static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3048
{ 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3049
0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3052
unsigned char data[19+64];
3054
unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3057
const char *fpr = NULL;
3058
unsigned long sigcount;
3060
int exmode, le_value;
3062
if (!keyidstr || !*keyidstr)
3063
return gpg_error (GPG_ERR_INV_VALUE);
3065
/* Strip off known prefixes. */
3066
#define X(a,b,c,d) \
3067
if (hashalgo == GCRY_MD_ ## a \
3069
&& indatalen == sizeof b ## _prefix + (c) \
3070
&& !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3072
indata = (const char*)indata + sizeof b ## _prefix; \
3073
indatalen -= sizeof b ## _prefix; \
3076
if (indatalen == 20)
3077
; /* Assume a plain SHA-1 or RMD160 digest has been given. */
3078
else X(SHA1, sha1, 20, 1)
3079
else X(RMD160, rmd160, 20, 1)
3080
else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3081
else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3082
else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3083
else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3084
else if ((indatalen == 28 || indatalen == 32
3085
|| indatalen == 48 || indatalen ==64)
3086
&& app->app_local->extcap.is_v2)
3087
; /* Assume a plain SHA-3 digest has been given. */
3090
log_error (_("card does not support digest algorithm %s\n"),
3091
gcry_md_algo_name (hashalgo));
3092
/* Or the supplied digest length does not match an algorithm. */
3093
return gpg_error (GPG_ERR_INV_VALUE);
3097
/* Check whether an OpenPGP card of any version has been requested. */
3098
if (!strcmp (keyidstr, "OPENPGP.1"))
3100
else if (!strcmp (keyidstr, "OPENPGP.3"))
3102
else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3103
return gpg_error (GPG_ERR_INV_ID);
3106
for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3109
return gpg_error (GPG_ERR_INV_ID);
3111
; /* no fingerprint given: we allow this for now. */
3115
return gpg_error (GPG_ERR_INV_ID);
3117
for (s=keyidstr, n=0; n < 16; s += 2, n++)
3118
tmp_sn[n] = xtoi_2 (s);
3120
if (app->serialnolen != 16)
3121
return gpg_error (GPG_ERR_INV_CARD);
3122
if (memcmp (app->serialno, tmp_sn, 16))
3123
return gpg_error (GPG_ERR_WRONG_CARD);
3126
/* If a fingerprint has been specified check it against the one on
3127
the card. This is allows for a meaningful error message in case
3128
the key on the card has been replaced but the shadow information
3129
known to gpg was not updated. If there is no fingerprint, gpg
3130
will detect a bogus signature anyway due to the
3131
verify-after-signing feature. */
3132
rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3136
/* Concatenate prefix and digest. */
3138
if (hashalgo == GCRY_MD_ ## a && (d) ) \
3140
datalen = sizeof b ## _prefix + indatalen; \
3141
assert (datalen <= sizeof data); \
3142
memcpy (data, b ## _prefix, sizeof b ## _prefix); \
3143
memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3147
else X(RMD160, rmd160, 1)
3148
else X(SHA224, sha224, app->app_local->extcap.is_v2)
3149
else X(SHA256, sha256, app->app_local->extcap.is_v2)
3150
else X(SHA384, sha384, app->app_local->extcap.is_v2)
3151
else X(SHA512, sha512, app->app_local->extcap.is_v2)
3153
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3156
/* Redirect to the AUTH command if asked to. */
3159
return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3161
outdata, outdatalen);
3164
/* Show the number of signature done using this key. */
3165
sigcount = get_sig_counter (app);
3166
log_info (_("signatures created so far: %lu\n"), sigcount);
3168
/* Check CHV if needed. */
3169
if (!app->did_chv1 || app->force_chv1 )
3173
rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3179
/* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3180
sync, thus we verify CHV2 here using the given PIN. Cards
3181
with version2 to not have the need for a separate CHV2 and
3182
internally use just one. Obviously we can't do that if the
3183
keypad has been used. */
3184
if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3186
rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3187
if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3188
rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3191
log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3193
flush_cache_after_error (app);
3202
if (app->app_local->cardcap.ext_lc_le)
3204
exmode = 1; /* Use extended length. */
3205
le_value = app->app_local->extcap.max_rsp_data;
3212
rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3213
outdata, outdatalen);
3217
/* Compute a digital signature using the INTERNAL AUTHENTICATE command
3218
on INDATA which is expected to be the raw message digest. For this
3219
application the KEYIDSTR consists of the serialnumber and the
3220
fingerprint delimited by a slash. Optionally the id OPENPGP.3 may
3223
Note that this function may return the error code
3224
GPG_ERR_WRONG_CARD to indicate that the card currently present does
3225
not match the one required for the requested action (e.g. the
3226
serial number does not match). */
3228
do_auth (app_t app, const char *keyidstr,
3229
gpg_error_t (*pincb)(void*, const char *, char **),
3231
const void *indata, size_t indatalen,
3232
unsigned char **outdata, size_t *outdatalen )
3235
unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3238
const char *fpr = NULL;
3240
if (!keyidstr || !*keyidstr)
3241
return gpg_error (GPG_ERR_INV_VALUE);
3242
if (indatalen > 101) /* For a 2048 bit key. */
3243
return gpg_error (GPG_ERR_INV_VALUE);
3245
/* Check whether an OpenPGP card of any version has been requested. */
3246
if (!strcmp (keyidstr, "OPENPGP.3"))
3248
else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3249
return gpg_error (GPG_ERR_INV_ID);
3252
for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3255
return gpg_error (GPG_ERR_INV_ID);
3257
; /* no fingerprint given: we allow this for now. */
3261
return gpg_error (GPG_ERR_INV_ID);
3263
for (s=keyidstr, n=0; n < 16; s += 2, n++)
3264
tmp_sn[n] = xtoi_2 (s);
3266
if (app->serialnolen != 16)
3267
return gpg_error (GPG_ERR_INV_CARD);
3268
if (memcmp (app->serialno, tmp_sn, 16))
3269
return gpg_error (GPG_ERR_WRONG_CARD);
3272
/* If a fingerprint has been specified check it against the one on
3273
the card. This is allows for a meaningful error message in case
3274
the key on the card has been replaced but the shadow information
3275
known to gpg was not updated. If there is no fingerprint, gpg
3276
will detect a bogus signature anyway due to the
3277
verify-after-signing feature. */
3278
rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3282
rc = verify_chv2 (app, pincb, pincb_arg);
3285
int exmode, le_value;
3287
if (app->app_local->cardcap.ext_lc_le)
3289
exmode = 1; /* Use extended length. */
3290
le_value = app->app_local->extcap.max_rsp_data;
3297
rc = iso7816_internal_authenticate (app->slot, exmode,
3298
indata, indatalen, le_value,
3299
outdata, outdatalen);
3306
do_decipher (app_t app, const char *keyidstr,
3307
gpg_error_t (*pincb)(void*, const char *, char **),
3309
const void *indata, size_t indatalen,
3310
unsigned char **outdata, size_t *outdatalen )
3313
unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3316
const char *fpr = NULL;
3317
int exmode, le_value;
3319
if (!keyidstr || !*keyidstr || !indatalen)
3320
return gpg_error (GPG_ERR_INV_VALUE);
3322
/* Check whether an OpenPGP card of any version has been requested. */
3323
if (!strcmp (keyidstr, "OPENPGP.2"))
3325
else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3326
return gpg_error (GPG_ERR_INV_ID);
3329
for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3332
return gpg_error (GPG_ERR_INV_ID);
3334
; /* no fingerprint given: we allow this for now. */
3338
return gpg_error (GPG_ERR_INV_ID);
3340
for (s=keyidstr, n=0; n < 16; s += 2, n++)
3341
tmp_sn[n] = xtoi_2 (s);
3343
if (app->serialnolen != 16)
3344
return gpg_error (GPG_ERR_INV_CARD);
3345
if (memcmp (app->serialno, tmp_sn, 16))
3346
return gpg_error (GPG_ERR_WRONG_CARD);
3349
/* If a fingerprint has been specified check it against the one on
3350
the card. This is allows for a meaningful error message in case
3351
the key on the card has been replaced but the shadow information
3352
known to gpg was not updated. If there is no fingerprint, the
3353
decryption won't produce the right plaintext anyway. */
3354
rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3358
rc = verify_chv2 (app, pincb, pincb_arg);
3362
unsigned char *fixbuf = NULL;
3365
/* We might encounter a couple of leading zeroes in the
3366
cryptogram. Due to internal use of MPIs thease leading
3367
zeroes are stripped. However the OpenPGP card expects
3368
exactly 128 bytes for the cryptogram (for a 1k key). Thus we
3369
need to fix it up. We do this for up to 16 leading zero
3370
bytes; a cryptogram with more than this is with a very high
3371
probability anyway broken. */
3372
if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */
3373
fixuplen = 128 - indatalen;
3374
else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */
3375
fixuplen = 192 - indatalen;
3376
else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */
3377
fixuplen = 256 - indatalen;
3378
else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */
3379
fixuplen = 384 - indatalen;
3385
/* While we have to prepend stuff anyway, we can also
3386
include the padding byte here so that iso1816_decipher
3387
does not need to do another data mangling. */
3390
fixbuf = xtrymalloc (fixuplen + indatalen);
3392
return gpg_error_from_syserror ();
3394
memset (fixbuf, 0, fixuplen);
3395
memcpy (fixbuf+fixuplen, indata, indatalen);
3397
indatalen = fixuplen + indatalen;
3398
padind = -1; /* Already padded. */
3401
if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
3403
exmode = 1; /* Extended length w/o a limit. */
3404
le_value = app->app_local->extcap.max_rsp_data;
3406
else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
3408
exmode = -254; /* Command chaining with max. 254 bytes. */
3412
exmode = le_value = 0;
3414
rc = iso7816_decipher (app->slot, exmode,
3415
indata, indatalen, le_value, padind,
3416
outdata, outdatalen);
3424
/* Perform a simple verify operation for CHV1 and CHV2, so that
3425
further operations won't ask for CHV2 and it is possible to do a
3426
cheap check on the PIN: If there is something wrong with the PIN
3427
entry system, only the regular CHV will get blocked and not the
3428
dangerous CHV3. KEYIDSTR is the usual card's serial number; an
3429
optional fingerprint part will be ignored.
3431
There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3432
the "[CHV3]" being a literal string: The Admin Pin is checked if
3433
and only if the retry counter is still at 3. */
3435
do_check_pin (app_t app, const char *keyidstr,
3436
gpg_error_t (*pincb)(void*, const char *, char **),
3439
unsigned char tmp_sn[20];
3444
if (!keyidstr || !*keyidstr)
3445
return gpg_error (GPG_ERR_INV_VALUE);
3447
/* Check whether an OpenPGP card of any version has been requested. */
3448
if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3449
return gpg_error (GPG_ERR_INV_ID);
3451
for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3454
return gpg_error (GPG_ERR_INV_ID);
3456
; /* No fingerprint given: we allow this for now. */
3458
; /* We ignore a fingerprint. */
3459
else if (!strcmp (s, "[CHV3]") )
3462
return gpg_error (GPG_ERR_INV_ID);
3464
for (s=keyidstr, n=0; n < 16; s += 2, n++)
3465
tmp_sn[n] = xtoi_2 (s);
3467
if (app->serialnolen != 16)
3468
return gpg_error (GPG_ERR_INV_CARD);
3469
if (memcmp (app->serialno, tmp_sn, 16))
3470
return gpg_error (GPG_ERR_WRONG_CARD);
3472
/* Yes, there is a race conditions: The user might pull the card
3473
right here and we won't notice that. However this is not a
3474
problem and the check above is merely for a graceful failure
3475
between operations. */
3480
unsigned char *value;
3484
relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3485
if (!relptr || valuelen < 7)
3487
log_error (_("error retrieving CHV status from card\n"));
3489
return gpg_error (GPG_ERR_CARD);
3496
log_info (_("card is permanently locked!\n"));
3497
return gpg_error (GPG_ERR_BAD_PIN);
3499
else if (value[6] < 3)
3501
log_info (_("verification of Admin PIN is currently prohibited "
3502
"through this command\n"));
3503
return gpg_error (GPG_ERR_GENERAL);
3506
app->did_chv3 = 0; /* Force verification. */
3507
return verify_chv3 (app, pincb, pincb_arg);
3510
return verify_chv2 (app, pincb, pincb_arg);
3514
/* Show information about card capabilities. */
3516
show_caps (struct app_local_s *s)
3518
log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3519
log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3520
if (s->extcap.get_challenge)
3521
log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3522
log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3523
log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3524
log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3525
log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3526
log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3527
if (s->extcap.sm_supported)
3528
log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3529
log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3530
log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3531
log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3532
log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3533
log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3534
log_info ("Status Indicator: %02X\n", s->status_indicator);
3536
log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no");
3537
log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no");
3541
/* Parse the historical bytes in BUFFER of BUFLEN and store them in
3544
parse_historical (struct app_local_s *apploc,
3545
const unsigned char * buffer, size_t buflen)
3547
/* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */
3550
log_error ("warning: historical bytes are too short\n");
3551
return; /* Too short. */
3555
log_error ("warning: bad category indicator in historical bytes\n");
3559
/* Skip category indicator. */
3563
/* Get the status indicator. */
3564
apploc->status_indicator = buffer[buflen-3];
3567
/* Parse the compact TLV. */
3570
unsigned int tag = (*buffer & 0xf0) >> 4;
3571
unsigned int len = (*buffer & 0x0f);
3574
log_error ("warning: bad Compact-TLV in historical bytes\n");
3575
return; /* Error. */
3579
if (tag == 7 && len == 3)
3581
/* Card capabilities. */
3582
apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3583
apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40);
3591
/* Parse and optionally show the algorithm attributes for KEYNO.
3592
KEYNO must be in the range 0..2. */
3594
parse_algorithm_attribute (app_t app, int keyno)
3596
unsigned char *buffer;
3599
const char const desc[3][5] = {"sign", "encr", "auth"};
3601
assert (keyno >=0 && keyno <= 2);
3603
app->app_local->keyattr[keyno].n_bits = 0;
3605
relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3608
log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3613
log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3619
log_info ("Key-Attr-%s ..: ", desc[keyno]);
3620
if (*buffer == 1 && (buflen == 5 || buflen == 6))
3622
app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3623
app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3624
app->app_local->keyattr[keyno].format = 0;
3626
app->app_local->keyattr[keyno].format = RSA_STD;
3628
app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD :
3629
buffer[5] == 1? RSA_STD_N :
3630
buffer[5] == 2? RSA_CRT :
3631
buffer[5] == 3? RSA_CRT_N :
3636
("RSA, n=%u, e=%u, fmt=%s\n",
3637
app->app_local->keyattr[keyno].n_bits,
3638
app->app_local->keyattr[keyno].e_bits,
3639
app->app_local->keyattr[keyno].format == RSA_STD? "std" :
3640
app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3641
app->app_local->keyattr[keyno].format == RSA_CRT? "crt" :
3642
app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3644
else if (opt.verbose)
3645
log_printhex ("", buffer, buflen);
3650
/* Select the OpenPGP application on the card in SLOT. This function
3651
must be used before any other OpenPGP application functions. */
3653
app_select_openpgp (app_t app)
3655
static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3656
int slot = app->slot;
3658
unsigned char *buffer;
3662
/* Note that the card can't cope with P2=0xCO, thus we need to pass a
3663
special flag value. */
3664
rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3667
unsigned int manufacturer;
3669
app->apptype = "OPENPGP";
3674
app->app_local = NULL;
3676
/* The OpenPGP card returns the serial number as part of the
3677
AID; because we prefer to use OpenPGP serial numbers, we
3678
replace a possibly already set one from a EF.GDO with this
3679
one. Note, that for current OpenPGP cards, no EF.GDO exists
3680
and thus it won't matter at all. */
3681
rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
3687
log_printhex ("", buffer, buflen);
3690
app->card_version = buffer[6] << 8;
3691
app->card_version |= buffer[7];
3692
manufacturer = (buffer[8]<<8 | buffer[9]);
3694
xfree (app->serialno);
3695
app->serialno = buffer;
3696
app->serialnolen = buflen;
3698
app->app_local = xtrycalloc (1, sizeof *app->app_local);
3699
if (!app->app_local)
3701
rc = gpg_error (gpg_err_code_from_errno (errno));
3705
if (app->card_version >= 0x0200)
3706
app->app_local->extcap.is_v2 = 1;
3709
/* Read the historical bytes. */
3710
relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3715
log_info ("Historical Bytes: ");
3716
log_printhex ("", buffer, buflen);
3718
parse_historical (app->app_local, buffer, buflen);
3722
/* Read the force-chv1 flag. */
3723
relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3726
log_error (_("can't access %s - invalid OpenPGP card?\n"),
3727
"CHV Status Bytes");
3730
app->force_chv1 = (buflen && *buffer == 0);
3733
/* Read the extended capabilities. */
3734
relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3737
log_error (_("can't access %s - invalid OpenPGP card?\n"),
3738
"Extended Capability Flags" );
3743
app->app_local->extcap.sm_supported = !!(*buffer & 0x80);
3744
app->app_local->extcap.get_challenge = !!(*buffer & 0x40);
3745
app->app_local->extcap.key_import = !!(*buffer & 0x20);
3746
app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3747
app->app_local->extcap.private_dos = !!(*buffer & 0x08);
3748
app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3752
/* Available with v2 cards. */
3753
app->app_local->extcap.sm_aes128 = (buffer[1] == 1);
3754
app->app_local->extcap.max_get_challenge
3755
= (buffer[2] << 8 | buffer[3]);
3756
app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3757
app->app_local->extcap.max_cmd_data = (buffer[6] << 8 | buffer[7]);
3758
app->app_local->extcap.max_rsp_data = (buffer[8] << 8 | buffer[9]);
3762
/* Some of the first cards accidently don't set the
3763
CHANGE_FORCE_CHV bit but allow it anyway. */
3764
if (app->card_version <= 0x0100 && manufacturer == 1)
3765
app->app_local->extcap.change_force_chv = 1;
3767
parse_login_data (app);
3770
show_caps (app->app_local);
3772
parse_algorithm_attribute (app, 0);
3773
parse_algorithm_attribute (app, 1);
3774
parse_algorithm_attribute (app, 2);
3776
if (opt.verbose > 1)
3779
app->fnc.deinit = do_deinit;
3780
app->fnc.learn_status = do_learn_status;
3781
app->fnc.readcert = do_readcert;
3782
app->fnc.readkey = do_readkey;
3783
app->fnc.getattr = do_getattr;
3784
app->fnc.setattr = do_setattr;
3785
app->fnc.writecert = do_writecert;
3786
app->fnc.writekey = do_writekey;
3787
app->fnc.genkey = do_genkey;
3788
app->fnc.sign = do_sign;
3789
app->fnc.auth = do_auth;
3790
app->fnc.decipher = do_decipher;
3791
app->fnc.change_pin = do_change_pin;
3792
app->fnc.check_pin = do_check_pin;