1 /* app-piv.c - The OpenPGP card application.
2  * Copyright (C) 2019, 2020 g10 Code GmbH
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
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.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19 
20 /* Some notes:
21  * - Specs for PIV are at http://dx.doi.org/10.6028/NIST.SP.800-73-4
22  * - https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
23  *
24  * - Access control matrix:
25  *   | Action       | 9B  | PIN | PUK |                              |
26  *   |--------------+-----+-----+-----+------------------------------|
27  *   | Generate key | yes |     |     |                              |
28  *   | Change 9B    | yes |     |     |                              |
29  *   | Change retry | yes | yes |     | Yubikey only                 |
30  *   | Import key   | yes |     |     |                              |
31  *   | Import cert  | yes |     |     |                              |
32  *   | Change CHUID | yes |     |     |                              |
33  *   | Reset card   |     |     |     | PIN and PUK in blocked state |
34  *   | Verify PIN   |     | yes |     |                              |
35  *   | Sign data    |     | yes |     |                              |
36  *   | Decrypt data |     | yes |     |                              |
37  *   | Change PIN   |     | yes |     |                              |
38  *   | Change PUK   |     |     | yes |                              |
39  *   | Unblock PIN  |     |     | yes | New PIN required             |
40  *   |---------------------------------------------------------------|
41  *   (9B indicates the 24 byte PIV Card Application Administration Key)
42  *
43  * - When generating a key we store the created public key in the
44  *   corresponding data object, so that gpg and gpgsm are able to get
45  *   the public key, create a certificate and store that then in that
46  *   data object.  That is not standard compliant but due to the use
47  *   of other tags, it should not harm.  See do_genkey for the actual
48  *   used tag structure.
49  */
50 
51 #include <config.h>
52 #include <errno.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <stdarg.h>
56 #include <string.h>
57 #include <time.h>
58 
59 #include "scdaemon.h"
60 
61 #include "../common/util.h"
62 #include "../common/i18n.h"
63 #include "iso7816.h"
64 #include "../common/tlv.h"
65 #include "../common/host2net.h"
66 #include "apdu.h" /* We use apdu_send_direct.  */
67 
68 #define PIV_ALGORITHM_3DES_ECB_0 0x00
69 #define PIV_ALGORITHM_2DES_ECB   0x01
70 #define PIV_ALGORITHM_2DES_CBC   0x02
71 #define PIV_ALGORITHM_3DES_ECB   0x03
72 #define PIV_ALGORITHM_3DES_CBC   0x04
73 #define PIV_ALGORITHM_RSA        0x07
74 #define PIV_ALGORITHM_AES128_ECB 0x08
75 #define PIV_ALGORITHM_AES128_CBC 0x09
76 #define PIV_ALGORITHM_AES192_ECB 0x0A
77 #define PIV_ALGORITHM_AES192_CBC 0x0B
78 #define PIV_ALGORITHM_AES256_ECB 0x0C
79 #define PIV_ALGORITHM_AES256_CBC 0x0D
80 #define PIV_ALGORITHM_ECC_P256   0x11
81 #define PIV_ALGORITHM_ECC_P384   0x14
82 
83 
84 /* The AID for PIV.  */
85 static char const piv_aid[] = { 0xA0, 0x00, 0x00, 0x03, 0x08, /* RID=NIST */
86                                 0x00, 0x00, 0x10, 0x00        /* PIX=PIV  */ };
87 
88 
89 /* A table describing the DOs of a PIV card.  */
90 struct data_object_s
91 {
92   unsigned int tag;
93   unsigned int mandatory:1;
94   unsigned int acr_contact:2;     /* 0=always, 1=VCI, 2=PIN, 3=PINorOCC */
95   unsigned int acr_contactless:2; /* 0=always, 1=VCI, 2=VCIandPIN,
96                                                       3=VCIand(PINorOCC) */
97   unsigned int dont_cache:1;      /* Data item will not be cached.  */
98   unsigned int flush_on_error:1;  /* Flush cached item on error.  */
99   unsigned int keypair:1;         /* Has a public key for a keypair.  */
100   const char keyref[3];           /* The key reference.  */
101   const char *oidsuffix;          /* Suffix of the OID. */
102   const char *usage;              /* Usage string for a keypair or NULL.  */
103   const char *desc;               /* Description of the DO.  */
104 };
105 typedef struct data_object_s *data_object_t;
106 static struct data_object_s data_objects[] = {
107   { 0x5FC107, 1, 0,1, 0,0, 0, "",   "1.219.0", NULL,
108     "Card Capability Container"},
109   { 0x5FC102, 1, 0,0, 0,0, 0, "",   "2.48.0",  NULL,
110     "Cardholder Unique Id" },
111   { 0x5FC105, 1, 0,1, 0,0, 1, "9A", "2.1.1",   "a",
112     "Cert PIV Authentication" },
113   { 0x5FC103, 1, 2,2, 0,0, 0, "",   "2.96.16", NULL,
114     "Cardholder Fingerprints" },
115   { 0x5FC106, 1, 0,1, 0,0, 0, "",   "2.144.0", NULL,
116     "Security Object" },
117   { 0x5FC108, 1, 2,2, 0,0, 0, "",   "2.96.48", NULL,
118     "Cardholder Facial Image" },
119   { 0x5FC101, 1, 0,0, 0,0, 1, "9E", "2.5.0",   "a",
120     "Cert Card Authentication"},
121   { 0x5FC10A, 0, 0,1, 0,0, 1, "9C", "2.1.0",   "sc",
122     "Cert Digital Signature" },
123   { 0x5FC10B, 0, 0,1, 0,0, 1, "9D", "2.1.2",   "e",
124     "Cert Key Management" },
125   { 0x5FC109, 0, 3,3, 0,0, 0, "",   "2.48.1",  NULL,
126     "Printed Information" },
127   { 0x7E,     0, 0,0, 0,0, 0, "",   "2.96.80", NULL,
128     "Discovery Object" },
129   { 0x5FC10C, 0, 0,1, 0,0, 0, "",   "2.96.96", NULL,
130     "Key History Object" },
131   { 0x5FC10D, 0, 0,1, 0,0, 0, "82", "2.16.1",  "e",
132     "Retired Cert Key Mgm 1" },
133   { 0x5FC10E, 0, 0,1, 0,0, 0, "83", "2.16.2",  "e",
134     "Retired Cert Key Mgm 2" },
135   { 0x5FC10F, 0, 0,1, 0,0, 0, "84", "2.16.3",  "e",
136     "Retired Cert Key Mgm 3" },
137   { 0x5FC110, 0, 0,1, 0,0, 0, "85", "2.16.4",  "e",
138     "Retired Cert Key Mgm 4" },
139   { 0x5FC111, 0, 0,1, 0,0, 0, "86", "2.16.5",  "e",
140     "Retired Cert Key Mgm 5" },
141   { 0x5FC112, 0, 0,1, 0,0, 0, "87", "2.16.6",  "e",
142     "Retired Cert Key Mgm 6" },
143   { 0x5FC113, 0, 0,1, 0,0, 0, "88", "2.16.7",  "e",
144     "Retired Cert Key Mgm 7" },
145   { 0x5FC114, 0, 0,1, 0,0, 0, "89", "2.16.8",  "e",
146     "Retired Cert Key Mgm 8" },
147   { 0x5FC115, 0, 0,1, 0,0, 0, "8A", "2.16.9",  "e",
148     "Retired Cert Key Mgm 9" },
149   { 0x5FC116, 0, 0,1, 0,0, 0, "8B", "2.16.10", "e",
150     "Retired Cert Key Mgm 10" },
151   { 0x5FC117, 0, 0,1, 0,0, 0, "8C", "2.16.11", "e",
152     "Retired Cert Key Mgm 11" },
153   { 0x5FC118, 0, 0,1, 0,0, 0, "8D", "2.16.12", "e",
154     "Retired Cert Key Mgm 12" },
155   { 0x5FC119, 0, 0,1, 0,0, 0, "8E", "2.16.13", "e",
156     "Retired Cert Key Mgm 13" },
157   { 0x5FC11A, 0, 0,1, 0,0, 0, "8F", "2.16.14", "e",
158     "Retired Cert Key Mgm 14" },
159   { 0x5FC11B, 0, 0,1, 0,0, 0, "90", "2.16.15", "e",
160     "Retired Cert Key Mgm 15" },
161   { 0x5FC11C, 0, 0,1, 0,0, 0, "91", "2.16.16", "e",
162     "Retired Cert Key Mgm 16" },
163   { 0x5FC11D, 0, 0,1, 0,0, 0, "92", "2.16.17", "e",
164     "Retired Cert Key Mgm 17" },
165   { 0x5FC11E, 0, 0,1, 0,0, 0, "93", "2.16.18", "e",
166     "Retired Cert Key Mgm 18" },
167   { 0x5FC11F, 0, 0,1, 0,0, 0, "94", "2.16.19", "e",
168     "Retired Cert Key Mgm 19" },
169   { 0x5FC120, 0, 0,1, 0,0, 0, "95", "2.16.20", "e",
170     "Retired Cert Key Mgm 20" },
171   { 0x5FC121, 0, 2,2, 0,0, 0, "",   "2.16.21", NULL,
172     "Cardholder Iris Images" },
173   { 0x7F61,   0, 0,0, 0,0, 0, "",   "2.16.22", NULL,
174     "BIT Group Template" },
175   { 0x5FC122, 0, 0,0, 0,0, 0, "",   "2.16.23", NULL,
176     "SM Cert Signer" },
177   { 0x5FC123, 0, 3,3, 0,0, 0, "",   "2.16.24", NULL,
178     "Pairing Code Ref Data" },
179   { 0 }
180   /* Other key reference values without a data object:
181    * "00" Global PIN (not cleared by application switching)
182    * "04" PIV Secure Messaging Key
183    * "80" PIV Application PIN
184    * "81" PIN Unblocking Key
185    * "96" Primary Finger OCC
186    * "97" Secondary Finger OCC
187    * "98" Pairing Code
188    * "9B" PIV Card Application Administration Key
189    *
190    * Yubikey specific data objects:
191    * "F9" Attestation key (preloaded can be replaced)
192    */
193 };
194 
195 
196 /* One cache item for DOs.  */
197 struct cache_s {
198   struct cache_s *next;
199   int tag;
200   size_t length;
201   unsigned char data[1];
202 };
203 
204 
205 /* Object with application specific data.  */
206 struct app_local_s {
207   /* A linked list with cached DOs.  */
208   struct cache_s *cache;
209 
210   /* Various flags.  */
211   struct
212   {
213     unsigned int yubikey:1;  /* This is on a Yubikey.  */
214   } flags;
215 
216   /* Keep track on whether we cache a certain PIN so that we get it
217    * from the cache only if we know we cached it.  This inhibits the
218    * use of the same cache entry for a card plugged in and out without
219    * gpg-agent having noticed that due to a bug.  */
220   struct
221   {
222     unsigned int maybe_00:1;
223     unsigned int maybe_80:1;
224     unsigned int maybe_81:1;
225     unsigned int maybe_96:1;
226     unsigned int maybe_97:1;
227     unsigned int maybe_98:1;
228     unsigned int maybe_9B:1;
229   } pincache;
230 
231 };
232 
233 
234 /***** Local prototypes  *****/
235 static gpg_error_t get_keygrip_by_tag (app_t app, unsigned int tag,
236                                        char **r_keygripstr, int *got_cert);
237 static gpg_error_t genkey_parse_rsa (const unsigned char *data, size_t datalen,
238                                      gcry_sexp_t *r_sexp);
239 static gpg_error_t genkey_parse_ecc (const unsigned char *data, size_t datalen,
240                                      int mechanism, gcry_sexp_t *r_sexp);
241 
242 
243 
244 
245 
246 /* Deconstructor. */
247 static void
do_deinit(app_t app)248 do_deinit (app_t app)
249 {
250   if (app && app->app_local)
251     {
252       struct cache_s *c, *c2;
253 
254       for (c = app->app_local->cache; c; c = c2)
255         {
256           c2 = c->next;
257           xfree (c);
258         }
259 
260       xfree (app->app_local);
261       app->app_local = NULL;
262     }
263 }
264 
265 
266 /* Wrapper around iso7816_get_data which first tries to get the data
267  * from the cache.  With GET_IMMEDIATE passed as true, the cache is
268  * bypassed.  The tag-53 container is also removed.  */
269 static gpg_error_t
get_cached_data(app_t app,int tag,unsigned char ** result,size_t * resultlen,int get_immediate)270 get_cached_data (app_t app, int tag,
271                  unsigned char **result, size_t *resultlen,
272                  int get_immediate)
273 {
274   gpg_error_t err;
275   int i;
276   unsigned char *p;
277   const unsigned char *s;
278   size_t len, n;
279   struct cache_s *c;
280 
281   *result = NULL;
282   *resultlen = 0;
283 
284   if (!get_immediate)
285     {
286       for (c=app->app_local->cache; c; c = c->next)
287         if (c->tag == tag)
288           {
289             if(c->length)
290               {
291                 p = xtrymalloc (c->length);
292                 if (!p)
293                   return gpg_error_from_syserror ();
294                 memcpy (p, c->data, c->length);
295                 *result = p;
296               }
297 
298             *resultlen = c->length;
299 
300             return 0;
301           }
302     }
303 
304   err = iso7816_get_data_odd (app_get_slot (app), 0, tag, &p, &len);
305   if (err)
306     return err;
307 
308   /* Unless the Discovery Object or the BIT Group Template is
309    * requested, remove the outer container.
310    * (SP800-73.4 Part 2, section 3.1.2)   */
311   if (tag == 0x7E || tag == 0x7F61)
312     ;
313   else if (len && *p == 0x53 && (s = find_tlv (p, len, 0x53, &n)))
314     {
315       memmove (p, s, n);
316       len = n;
317     }
318 
319   if (len)
320     *result = p;
321   *resultlen = len;
322 
323   /* Check whether we should cache this object. */
324   if (get_immediate)
325     return 0;
326 
327   for (i=0; data_objects[i].tag; i++)
328     if (data_objects[i].tag == tag)
329       {
330         if (data_objects[i].dont_cache)
331           return 0;
332         break;
333       }
334 
335   /* Okay, cache it. */
336   for (c=app->app_local->cache; c; c = c->next)
337     log_assert (c->tag != tag);
338 
339   c = xtrymalloc (sizeof *c + len);
340   if (c)
341     {
342       if (len)
343         memcpy (c->data, p, len);
344       else
345         xfree (p);
346       c->length = len;
347       c->tag = tag;
348       c->next = app->app_local->cache;
349       app->app_local->cache = c;
350     }
351 
352   return 0;
353 }
354 
355 
356 /* Remove data object described by TAG from the cache.  If TAG is 0
357  * all cache iterms are flushed.  */
358 static void
flush_cached_data(app_t app,int tag)359 flush_cached_data (app_t app, int tag)
360 {
361   struct cache_s *c, *cprev;
362 
363   for (c=app->app_local->cache, cprev=NULL; c; cprev=c, c = c->next)
364     if (c->tag == tag || !tag)
365       {
366         if (cprev)
367           cprev->next = c->next;
368         else
369           app->app_local->cache = c->next;
370         xfree (c);
371 
372         for (c=app->app_local->cache; c ; c = c->next)
373           {
374             log_assert (c->tag != tag); /* Oops: duplicated entry. */
375           }
376         return;
377       }
378 }
379 
380 
381 /* Get the DO identified by TAG from the card in SLOT and return a
382  * buffer with its content in RESULT and NBYTES.  The return value is
383  * NULL if not found or a pointer which must be used to release the
384  * buffer holding value.  */
385 static void *
get_one_do(app_t app,int tag,unsigned char ** result,size_t * nbytes,int * r_err)386 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
387             int *r_err)
388 {
389   gpg_error_t err;
390   int i;
391   unsigned char *buffer;
392   size_t buflen;
393   unsigned char *value;
394   size_t valuelen;
395   gpg_error_t dummyerr;
396 
397   if (!r_err)
398     r_err = &dummyerr;
399 
400   *result = NULL;
401   *nbytes = 0;
402   *r_err = 0;
403   for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
404     ;
405 
406   value = NULL;
407   err = gpg_error (GPG_ERR_ENOENT);
408 
409   if (!value) /* Not in a constructed DO, try simple. */
410     {
411       err = get_cached_data (app, tag, &buffer, &buflen,
412                              data_objects[i].dont_cache);
413       if (!err)
414         {
415           value = buffer;
416           valuelen = buflen;
417         }
418     }
419 
420   if (!err)
421     {
422       *nbytes = valuelen;
423       *result = value;
424       return buffer;
425     }
426 
427   *r_err = err;
428   return NULL;
429 }
430 
431 
432 static void
dump_all_do(int slot)433 dump_all_do (int slot)
434 {
435   gpg_error_t err;
436   int i;
437   unsigned char *buffer;
438   size_t buflen;
439 
440   for (i=0; data_objects[i].tag; i++)
441     {
442       /* We don't try extended length APDU because such large DO would
443          be pretty useless in a log file.  */
444       err = iso7816_get_data_odd (slot, 0, data_objects[i].tag,
445                                  &buffer, &buflen);
446       if (err)
447         {
448           if (gpg_err_code (err) == GPG_ERR_ENOENT
449               && !data_objects[i].mandatory)
450             ;
451           else
452             log_info ("DO '%s' not available: %s\n",
453                       data_objects[i].desc, gpg_strerror (err));
454         }
455       else
456         {
457           if (data_objects[i].tag == 0x5FC109)
458             log_info ("DO '%s': '%.*s'\n", data_objects[i].desc,
459                       (int)buflen, buffer);
460           else
461             {
462               log_info ("DO '%s': ", data_objects[i].desc);
463               if (buflen > 16 && opt.verbose < 2)
464                 {
465                   log_printhex (buffer, 16, NULL);
466                   log_printf ("[...]\n");
467                 }
468               else
469                 log_printhex (buffer, buflen, "");
470             }
471 
472         }
473       xfree (buffer); buffer = NULL;
474     }
475 }
476 
477 
478 /* Create a TLV tag and value and store it at BUFFER.  Return the
479  * length of tag and length.  A LENGTH greater than 65535 is
480  * truncated.  TAG must be less or equal to 2^16.  If BUFFER is NULL,
481  * only the required length is computed.  */
482 static size_t
add_tlv(unsigned char * buffer,unsigned int tag,size_t length)483 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
484 {
485   if (length > 0xffff)
486     length = 0xffff;
487 
488   if (buffer)
489     {
490       unsigned char *p = buffer;
491 
492       if (tag > 0xff)
493         *p++ = tag >> 8;
494       *p++ = tag;
495       if (length < 128)
496         *p++ = length;
497       else if (length < 256)
498         {
499           *p++ = 0x81;
500           *p++ = length;
501         }
502       else
503         {
504           *p++ = 0x82;
505           *p++ = length >> 8;
506           *p++ = length;
507         }
508 
509       return p - buffer;
510     }
511   else
512     {
513       size_t n = 0;
514 
515       if (tag > 0xff)
516         n++;
517       n++;
518       if (length < 128)
519         n++;
520       else if (length < 256)
521         n += 2;
522       else
523         n += 3;
524       return n;
525     }
526 }
527 
528 
529 /* Function to build a list of TLV and return the result in a malloced
530  * buffer.  The varargs are tuples of (int,size_t,void) each with the
531  * tag, the length and the actual data.  A (0,0,NULL) tuple terminates
532  * the list.  Up to 10 tuples are supported.  If SECMEM is true the
533  * returned buffer is allocated in secure memory.  */
534 static gpg_error_t
concat_tlv_list(int secure,unsigned char ** r_result,size_t * r_resultlen,...)535 concat_tlv_list (int secure, unsigned char **r_result, size_t *r_resultlen, ...)
536 {
537   gpg_error_t err;
538   va_list arg_ptr;
539   struct {
540     int tag;
541     unsigned int len;
542     unsigned int contlen;
543     const void *data;
544   } argv[10];
545   int i, j, argc;
546   unsigned char *data = NULL;
547   size_t datalen;
548   unsigned char *p;
549   size_t n;
550 
551   *r_result = NULL;
552   *r_resultlen = 0;
553 
554   /* Collect all args.  Check that length is <= 2^16 to match the
555    * behaviour of add_tlv.  */
556   va_start (arg_ptr, r_resultlen);
557   argc = 0;
558   while (((argv[argc].tag = va_arg (arg_ptr, int))))
559     {
560       argv[argc].len = va_arg (arg_ptr, size_t);
561       argv[argc].contlen = 0;
562       argv[argc].data = va_arg (arg_ptr, const void *);
563       if (argc >= DIM (argv)-1 || argv[argc].len > 0xffff)
564         {
565           va_end (arg_ptr);
566           err = gpg_error (GPG_ERR_EINVAL);
567           goto leave;
568         }
569       argc++;
570     }
571   va_end (arg_ptr);
572 
573   /* Compute the required buffer length and allocate the buffer.  */
574   datalen = 0;
575   for (i=0; i < argc; i++)
576     {
577       if (!argv[i].len && !argv[i].data)
578         {
579           /* Constructed tag.  Compute its length.  Note that we
580            * currently allow only one constructed tag in the list.  */
581           for (n=0, j = i + 1; j < argc; j++)
582             {
583               log_assert (!(!argv[j].len && !argv[j].data));
584               n += add_tlv (NULL, argv[j].tag, argv[j].len);
585               n += argv[j].len;
586             }
587           argv[i].contlen = n;
588           datalen += add_tlv (NULL, argv[i].tag, n);
589         }
590       else
591         {
592           datalen += add_tlv (NULL, argv[i].tag, argv[i].len);
593           datalen += argv[i].len;
594         }
595     }
596   data = secure? xtrymalloc_secure (datalen) : xtrymalloc (datalen);
597   if (!data)
598     {
599       err = gpg_error_from_syserror ();
600       goto leave;
601     }
602 
603   /* Copy that data to the buffer.  */
604   p = data;
605   for (i=0; i < argc; i++)
606     {
607       if (!argv[i].len && !argv[i].data)
608         {
609           /* Constructed tag.  */
610           p += add_tlv (p, argv[i].tag, argv[i].contlen);
611         }
612       else
613         {
614           p += add_tlv (p, argv[i].tag, argv[i].len);
615           memcpy (p, argv[i].data, argv[i].len);
616           p += argv[i].len;
617         }
618     }
619   log_assert ( data + datalen == p );
620   *r_result = data;
621   data = NULL;
622   *r_resultlen = datalen;
623   err = 0;
624 
625  leave:
626   xfree (data);
627   return err;
628 }
629 
630 
631 /* Wrapper around iso7816_put_data_odd which also sets the tag into
632  * the '5C' data object.  The varargs are tuples of (int,size_t,void)
633  * with the tag, the length and the actual data.  A (0,0,NULL) tuple
634  * terminates the list.  Up to 10 tuples are supported.  */
635 static gpg_error_t
put_data(int slot,unsigned int tag,...)636 put_data (int slot, unsigned int tag, ...)
637 {
638   gpg_error_t err;
639   va_list arg_ptr;
640   struct {
641     int tag;
642     size_t len;
643     const void *data;
644   } argv[10];
645   int i, argc;
646   unsigned char data5c[5];
647   size_t data5clen;
648   unsigned char *data = NULL;
649   size_t datalen;
650   unsigned char *p;
651   size_t n;
652 
653   /* Collect all args.  Check that length is <= 2^16 to match the
654    * behaviour of add_tlv.  */
655   va_start (arg_ptr, tag);
656   argc = 0;
657   while (((argv[argc].tag = va_arg (arg_ptr, int))))
658     {
659       argv[argc].len = va_arg (arg_ptr, size_t);
660       argv[argc].data = va_arg (arg_ptr, const void *);
661       if (argc >= DIM (argv)-1 || argv[argc].len > 0xffff)
662         {
663           va_end (arg_ptr);
664           return GPG_ERR_EINVAL;
665         }
666       argc++;
667     }
668   va_end (arg_ptr);
669 
670   /* Build the TLV with the tag to be updated.  */
671   data5c[0] = 0x5c; /* Tag list */
672   if (tag <= 0xff)
673     {
674       data5c[1] = 1;
675       data5c[2] = tag;
676       data5clen = 3;
677     }
678   else if (tag <= 0xffff)
679     {
680       data5c[1] = 2;
681       data5c[2] = (tag >> 8);
682       data5c[3] = tag;
683       data5clen = 4;
684     }
685   else
686     {
687       data5c[1] = 3;
688       data5c[2] = (tag >> 16);
689       data5c[3] = (tag >> 8);
690       data5c[4] = tag;
691       data5clen = 5;
692     }
693 
694   /* Compute the required buffer length and allocate the buffer.  */
695   n = 0;
696   for (i=0; i < argc; i++)
697     {
698       n += add_tlv (NULL, argv[i].tag, argv[i].len);
699       n += argv[i].len;
700     }
701   datalen = data5clen + add_tlv (NULL, 0x53, n) + n;
702   data = xtrymalloc (datalen);
703   if (!data)
704     {
705       err = gpg_error_from_syserror ();
706       goto leave;
707     }
708 
709   /* Copy that data to the buffer.  */
710   p = data;
711   memcpy (p, data5c, data5clen);
712   p += data5clen;
713   p += add_tlv (p, 0x53, n);
714   for (i=0; i < argc; i++)
715     {
716       p += add_tlv (p, argv[i].tag, argv[i].len);
717       memcpy (p, argv[i].data, argv[i].len);
718       p += argv[i].len;
719     }
720   log_assert ( data + datalen == p );
721   err = iso7816_put_data_odd (slot, -1 /* use command chaining */,
722                               0x3fff, data, datalen);
723 
724  leave:
725   xfree (data);
726   return err;
727 }
728 
729 
730 /* Parse the key reference KEYREFSTR which is expected to hold a key
731  * reference for a CHV object.  Return the one octet keyref or -1 for
732  * an invalid reference.  */
733 static int
parse_chv_keyref(const char * keyrefstr)734 parse_chv_keyref (const char *keyrefstr)
735 {
736   if (!keyrefstr)
737     return -1;
738   else if (!ascii_strcasecmp (keyrefstr, "PIV.00"))
739     return 0x00;
740   else if (!ascii_strcasecmp (keyrefstr, "PIV.80"))
741     return 0x80;
742   else if (!ascii_strcasecmp (keyrefstr, "PIV.81"))
743     return 0x81;
744   else
745     return -1;
746 }
747 
748 
749 /* The verify command can be used to retrieve the security status of
750  * the card.  Given the PIN name (e.g. "PIV.80" for the application
751  * pin, a ISO7817_VERIFY_* code is returned or a non-negative number
752  * of verification attempts left.  */
753 static int
get_chv_status(app_t app,const char * keyrefstr)754 get_chv_status (app_t app, const char *keyrefstr)
755 {
756   int keyref;
757 
758   keyref = parse_chv_keyref (keyrefstr);
759   if (!keyrefstr)
760     return ISO7816_VERIFY_ERROR;
761   return iso7816_verify_status (app_get_slot (app), keyref);
762 }
763 
764 
765 /* Implementation of the GETATTR command.  This is similar to the
766  * LEARN command but returns only one value via status lines.  */
767 static gpg_error_t
do_getattr(app_t app,ctrl_t ctrl,const char * name)768 do_getattr (app_t app, ctrl_t ctrl, const char *name)
769 {
770   static struct {
771     const char *name;
772     int tag;
773     int special;
774   } table[] = {
775     { "SERIALNO",     0x0000, -1 },
776     { "$AUTHKEYID",   0x0000, -2 }, /* Default ssh key.  */
777     { "$ENCRKEYID",   0x0000, -6 }, /* Default encryption key.  */
778     { "$SIGNKEYID",   0x0000, -7 }, /* Default signing key.  */
779     { "$DISPSERIALNO",0x0000, -3 },
780     { "CHV-STATUS",   0x0000, -4 },
781     { "CHV-USAGE",    0x007E, -5 }
782   };
783   gpg_error_t err = 0;
784   int idx;
785   void *relptr;
786   unsigned char *value;
787   size_t valuelen;
788   const unsigned char *s;
789   size_t n;
790 
791   for (idx=0; (idx < DIM (table)
792                && ascii_strcasecmp (table[idx].name, name)); idx++)
793     ;
794   if (!(idx < DIM (table)))
795     err = gpg_error (GPG_ERR_INV_NAME);
796   else if (table[idx].special == -1)
797     {
798       char *serial = app_get_serialno (app);
799 
800       if (serial)
801         {
802           send_status_direct (ctrl, "SERIALNO", serial);
803           xfree (serial);
804         }
805     }
806   else if (table[idx].special == -2)
807     {
808       char const tmp[] = "PIV.9A"; /* Cert PIV Authenticate.  */
809       send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
810     }
811   else if (table[idx].special == -3)
812     {
813       char *tmp = app_get_dispserialno (app, 1);
814 
815       if (tmp)
816         {
817           send_status_info (ctrl, table[idx].name,
818                             tmp, strlen (tmp),
819                             NULL, (size_t)0);
820           xfree (tmp);
821         }
822       else
823         err = gpg_error (GPG_ERR_INV_NAME);  /* No Abbreviated S/N.  */
824     }
825   else if (table[idx].special == -4) /* CHV-STATUS */
826     {
827       int tmp[4];
828 
829       tmp[0] = get_chv_status (app, "PIV.00");
830       tmp[1] = get_chv_status (app, "PIV.80");
831       tmp[2] = get_chv_status (app, "PIV.81");
832       err = send_status_printf (ctrl, table[idx].name, "%d %d %d",
833                                 tmp[0], tmp[1], tmp[2]);
834     }
835   else if (table[idx].special == -5) /* CHV-USAGE (aka PIN Usage Policy) */
836     {
837       /* We return 2 hex bytes or nothing in case the discovery object
838        * is not supported.  */
839       relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &err);
840       if (relptr)
841         {
842           s = find_tlv (value, valuelen, 0x7E, &n);
843           if (s && n && (s = find_tlv (s, n, 0x5F2F, &n)) && n >=2 )
844             err = send_status_printf (ctrl, table[idx].name, "%02X %02X",
845                                       s[0], s[1]);
846           xfree (relptr);
847         }
848     }
849   else if (table[idx].special == -6)
850     {
851       char const tmp[] = "PIV.9D"; /* Key Management.  */
852       send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
853     }
854   else if (table[idx].special == -7)
855     {
856       char const tmp[] = "PIV.9C"; /* Digital Signature.  */
857       send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
858     }
859   else
860     {
861       relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &err);
862       if (relptr)
863         {
864           send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
865           xfree (relptr);
866         }
867     }
868 
869   return err;
870 }
871 
872 
873 /* Authenticate the card using the Card Application Administration
874  * Key.  (VALUE,VALUELEN) has that 24 byte key.  */
875 static gpg_error_t
auth_adm_key(app_t app,const unsigned char * value,size_t valuelen)876 auth_adm_key (app_t app, const unsigned char *value, size_t valuelen)
877 {
878   gpg_error_t err;
879   unsigned char tmpl[4+24];
880   size_t tmpllen;
881   unsigned char *outdata = NULL;
882   size_t outdatalen;
883   const unsigned char *s;
884   char witness[8];
885   size_t n;
886   gcry_cipher_hd_t cipher = NULL;
887 
888   /* Prepare decryption.  */
889   err = gcry_cipher_open (&cipher, GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB, 0);
890   if (err)
891     goto leave;
892   err = gcry_cipher_setkey (cipher, value, valuelen);
893   if (err)
894     goto leave;
895 
896   /* Request a witness.  */
897   tmpl[0] = 0x7c;
898   tmpl[1] = 0x02;
899   tmpl[2] = 0x80;
900   tmpl[3] = 0;    /* (Empty witness requests a witness.)  */
901   tmpllen = 4;
902   err = iso7816_general_authenticate (app_get_slot (app), 0,
903                                       PIV_ALGORITHM_3DES_ECB_0, 0x9B,
904                                       tmpl, tmpllen, 0,
905                                       &outdata, &outdatalen);
906   if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
907     err = gpg_error (GPG_ERR_BAD_AUTH);
908   if (err)
909     goto leave;
910   if (!(outdatalen && *outdata == 0x7c
911         && (s = find_tlv (outdata, outdatalen, 0x80, &n))
912         && n == 8))
913     {
914       err = gpg_error (GPG_ERR_CARD);
915       log_error ("piv: improper witness received\n");
916       goto leave;
917     }
918   err = gcry_cipher_decrypt (cipher, witness, 8, s, 8);
919   if (err)
920     goto leave;
921 
922   /* Return decrypted witness and send our challenge.  */
923   tmpl[0] = 0x7c;
924   tmpl[1] = 22;
925   tmpl[2] = 0x80;
926   tmpl[3] = 8;
927   memcpy (tmpl+4, witness, 8);
928   tmpl[12] = 0x81;
929   tmpl[13] = 8;
930   gcry_create_nonce (tmpl+14, 8);
931   tmpl[22] = 0x80;
932   tmpl[23] = 0;
933   tmpllen = 24;
934   xfree (outdata);
935   err = iso7816_general_authenticate (app_get_slot (app), 0,
936                                       PIV_ALGORITHM_3DES_ECB_0, 0x9B,
937                                       tmpl, tmpllen, 0,
938                                       &outdata, &outdatalen);
939   if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
940     err = gpg_error (GPG_ERR_BAD_AUTH);
941   if (err)
942     goto leave;
943   if (!(outdatalen && *outdata == 0x7c
944         && (s = find_tlv (outdata, outdatalen, 0x82, &n))
945         && n == 8))
946     {
947       err = gpg_error (GPG_ERR_CARD);
948       log_error ("piv: improper challenge received\n");
949       goto leave;
950     }
951   /* (We reuse the witness buffer.) */
952   err = gcry_cipher_decrypt (cipher, witness, 8, s, 8);
953   if (err)
954     goto leave;
955   if (memcmp (witness, tmpl+14, 8))
956     {
957       err = gpg_error (GPG_ERR_BAD_AUTH);
958       goto leave;
959     }
960 
961  leave:
962    xfree (outdata);
963    gcry_cipher_close (cipher);
964    return err;
965 }
966 
967 
968 /* Set a new admin key.  */
969 static gpg_error_t
set_adm_key(app_t app,const unsigned char * value,size_t valuelen)970 set_adm_key (app_t app, const unsigned char *value, size_t valuelen)
971 {
972   gpg_error_t err;
973   unsigned char apdu[8+24];
974   unsigned int sw;
975 
976   /* Check whether it is a weak key and that it is of proper length.  */
977   {
978     gcry_cipher_hd_t cipher;
979 
980     err = gcry_cipher_open (&cipher, GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB, 0);
981     if (!err)
982       {
983         err = gcry_cipher_setkey (cipher, value, valuelen);
984         gcry_cipher_close (cipher);
985       }
986     if (err)
987       goto leave;
988   }
989 
990   if (app->app_local->flags.yubikey)
991     {
992       /* This is a Yubikey.  */
993       if (valuelen != 24)
994         {
995           err = gpg_error (GPG_ERR_INV_LENGTH);
996           goto leave;
997         }
998 
999       /* We use a proprietary Yubikey command.  */
1000       apdu[0] = 0;
1001       apdu[1] = 0xff;
1002       apdu[2] = 0xff;
1003       apdu[3] = 0xff;  /* touch policy: 0xff=never, 0xfe = always.  */
1004       apdu[4] = 3 + 24;
1005       apdu[5] = PIV_ALGORITHM_3DES_ECB;
1006       apdu[6] = 0x9b;
1007       apdu[7] = 24;
1008       memcpy (apdu+8, value, 24);
1009       err = iso7816_apdu_direct (app_get_slot (app), apdu, 8+24, 0,
1010                                  &sw, NULL, NULL);
1011       wipememory (apdu+8, 24);
1012       if (err)
1013         log_error ("piv: setting admin key failed; sw=%04x\n", sw);
1014       /* A PIN is not required, thus use a better error code.  */
1015       if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
1016         err = gpg_error (GPG_ERR_NO_AUTH);
1017     }
1018   else
1019     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1020 
1021 
1022  leave:
1023    return err;
1024 }
1025 
1026 /* Handle the SETATTR operation. All arguments are already basically
1027  * checked. */
1028 static gpg_error_t
do_setattr(app_t app,ctrl_t ctrl,const char * name,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * value,size_t valuelen)1029 do_setattr (app_t app, ctrl_t ctrl, const char *name,
1030             gpg_error_t (*pincb)(void*, const char *, char **),
1031             void *pincb_arg,
1032             const unsigned char *value, size_t valuelen)
1033 {
1034   gpg_error_t err;
1035   static struct {
1036     const char *name;
1037     unsigned short tag;
1038     unsigned short flush_tag;  /* The tag which needs to be flushed or 0. */
1039     int special;               /* Special mode to use for thus NAME.  */
1040   } table[] = {
1041     /* Authenticate using the PIV Card Application Administration Key
1042      * (0x0B).  Note that Yubico calls this key the "management key"
1043      * which we don't do because that term is too similar to "Cert
1044      * Management Key" (0x9D).  */
1045     { "AUTH-ADM-KEY", 0x0000, 0x0000, 1 },
1046     { "SET-ADM-KEY",  0x0000, 0x0000, 2 }
1047   };
1048   int idx;
1049 
1050   (void)ctrl;
1051   (void)pincb;
1052   (void)pincb_arg;
1053 
1054   for (idx=0; (idx < DIM (table)
1055                && ascii_strcasecmp (table[idx].name, name)); idx++)
1056     ;
1057   if (!(idx < DIM (table)))
1058     return gpg_error (GPG_ERR_INV_NAME);
1059 
1060   /* Flush the cache before writing it, so that the next get operation
1061    * will reread the data from the card and thus get synced in case of
1062    * errors (e.g. data truncated by the card). */
1063   if (table[idx].tag)
1064     flush_cached_data (app, table[idx].flush_tag? table[idx].flush_tag
1065                        /* */                    : table[idx].tag);
1066 
1067   switch (table[idx].special)
1068     {
1069     case 1:
1070       err = auth_adm_key (app, value, valuelen);
1071       break;
1072 
1073     case 2:
1074       err = set_adm_key (app, value, valuelen);
1075       break;
1076 
1077     default:
1078       err = gpg_error (GPG_ERR_BUG);
1079       break;
1080     }
1081 
1082   return err;
1083 }
1084 
1085 
1086 /* Send the KEYPAIRINFO back.  DOBJ describes the data object carrying
1087  * the key.  This is used by the LEARN command. */
1088 static gpg_error_t
send_keypair_and_cert_info(app_t app,ctrl_t ctrl,data_object_t dobj,int only_keypair)1089 send_keypair_and_cert_info (app_t app, ctrl_t ctrl, data_object_t dobj,
1090                             int only_keypair)
1091 {
1092   gpg_error_t err = 0;
1093   char *keygripstr = NULL;
1094   int got_cert;
1095   char idbuf[50];
1096   const char *usage;
1097 
1098   err = get_keygrip_by_tag (app, dobj->tag, &keygripstr, &got_cert);
1099   if (err)
1100     goto leave;
1101 
1102   usage = dobj->usage? dobj->usage : "";
1103 
1104   snprintf (idbuf, sizeof idbuf, "PIV.%s", dobj->keyref);
1105   send_status_info (ctrl, "KEYPAIRINFO",
1106                     keygripstr, strlen (keygripstr),
1107                     idbuf, strlen (idbuf),
1108                     usage, strlen (usage),
1109                     NULL, (size_t)0);
1110   if (!only_keypair && got_cert)
1111     {
1112       /* All certificates are of type 100 (Regular X.509 Cert).  */
1113       send_status_info (ctrl, "CERTINFO",
1114                         "100", 3,
1115                         idbuf, strlen (idbuf),
1116                         NULL, (size_t)0);
1117     }
1118 
1119  leave:
1120   xfree (keygripstr);
1121   return err;
1122 }
1123 
1124 
1125 /* Handle the LEARN command.  */
1126 static gpg_error_t
do_learn_status(app_t app,ctrl_t ctrl,unsigned int flags)1127 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1128 {
1129   int i;
1130 
1131   (void)flags;
1132 
1133   do_getattr (app, ctrl, "CHV-USAGE");
1134   do_getattr (app, ctrl, "CHV-STATUS");
1135 
1136   for (i=0; data_objects[i].tag; i++)
1137     if (data_objects[i].keypair)
1138       send_keypair_and_cert_info (app, ctrl, data_objects + i,
1139                                   !!(flags & APP_LEARN_FLAG_KEYPAIRINFO));
1140 
1141 
1142   return 0;
1143 }
1144 
1145 
1146 /* Core of do_readcert which fetches the certificate based on the
1147  * given tag and returns it in a freshly allocated buffer stored at
1148  * R_CERT and the length of the certificate stored at R_CERTLEN.  If
1149  * on success a non-zero value is stored at R_MECHANISM, the returned
1150  * data is not a certificate but a public key (in the format used by the
1151  * container '7f49').  */
1152 static gpg_error_t
readcert_by_tag(app_t app,unsigned int tag,unsigned char ** r_cert,size_t * r_certlen,int * r_mechanism)1153 readcert_by_tag (app_t app, unsigned int tag,
1154                  unsigned char **r_cert, size_t *r_certlen, int *r_mechanism)
1155 {
1156   gpg_error_t err;
1157   unsigned char *buffer;
1158   size_t buflen;
1159   void *relptr;
1160   const unsigned char *s, *s2;
1161   size_t n, n2;
1162 
1163   *r_cert = NULL;
1164   *r_certlen = 0;
1165   *r_mechanism = 0;
1166 
1167   relptr = get_one_do (app, tag, &buffer, &buflen, NULL);
1168   if (!relptr || !buflen)
1169    {
1170       err = gpg_error (GPG_ERR_NOT_FOUND);
1171       goto leave;
1172     }
1173 
1174   s = find_tlv (buffer, buflen, 0x71, &n);
1175   if (!s)
1176     {
1177       /* No certificate; check whether a public key has been stored
1178        * using our own scheme.  */
1179       s = find_tlv (buffer, buflen, 0x7f49, &n);
1180       if (!s || !n)
1181         {
1182           log_error ("piv: No public key in 0x%X\n", tag);
1183           err = gpg_error (GPG_ERR_NO_PUBKEY);
1184           goto leave;
1185         }
1186       s2 = find_tlv (buffer, buflen, 0x80, &n2);
1187       if (!s2 || n2 != 1 || !*s2)
1188         {
1189           log_error ("piv: No mechanism for public key in 0x%X\n", tag);
1190           err = gpg_error (GPG_ERR_NO_PUBKEY);
1191           goto leave;
1192         }
1193       *r_mechanism = *s2;
1194     }
1195   else
1196     {
1197       if (n != 1)
1198         {
1199           log_error ("piv: invalid CertInfo in 0x%X\n", tag);
1200           err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1201           goto leave;
1202         }
1203       if (*s == 0x01)
1204         {
1205           log_error ("piv: gzip compression not yet supported (tag 0x%X)\n",
1206                      tag);
1207           err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1208           goto leave;
1209         }
1210       if (*s)
1211         {
1212           log_error ("piv: invalid CertInfo 0x%02x in 0x%X\n", *s, tag);
1213           err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1214           goto leave;
1215         }
1216 
1217       /* Note: We don't check that the LRC octet has a length of zero
1218        * as required by the specs.  */
1219 
1220       /* Get the cert from the container.  */
1221       s = find_tlv (buffer, buflen, 0x70, &n);
1222       if (!s || !n)
1223         {
1224           err = gpg_error (GPG_ERR_NOT_FOUND);
1225           goto leave;
1226         }
1227     }
1228 
1229   /* The next is common for certificate and public key.  */
1230   if (!(*r_cert = xtrymalloc (n)))
1231     {
1232       err = gpg_error_from_syserror ();
1233       goto leave;
1234     }
1235 
1236   memcpy (*r_cert, s, n);
1237   *r_certlen = n;
1238   err = 0;
1239 
1240  leave:
1241   xfree (relptr);
1242   return err;
1243 }
1244 
1245 
1246 /* Get the keygrip in hex format of a key from the certificate stored
1247  * at TAG.  Caller must free the string at R_KEYGRIPSTR. */
1248 static gpg_error_t
get_keygrip_by_tag(app_t app,unsigned int tag,char ** r_keygripstr,int * r_got_cert)1249 get_keygrip_by_tag (app_t app, unsigned int tag,
1250                     char **r_keygripstr, int *r_got_cert)
1251 {
1252   gpg_error_t err;
1253   unsigned char *certbuf = NULL;
1254   size_t certbuflen;
1255   int mechanism;
1256   gcry_sexp_t s_pkey = NULL;
1257   ksba_cert_t cert = NULL;
1258   unsigned char grip[KEYGRIP_LEN];
1259 
1260   *r_got_cert = 0;
1261   *r_keygripstr = xtrymalloc (2*KEYGRIP_LEN+1);
1262   if (!r_keygripstr)
1263     {
1264       err = gpg_error_from_syserror ();
1265       goto leave;
1266     }
1267 
1268   /* We need to get the public key from the certificate.  */
1269   err = readcert_by_tag (app, tag, &certbuf, &certbuflen, &mechanism);
1270   if (err)
1271     goto leave;
1272   if (mechanism) /* Compute keygrip from public key.  */
1273     {
1274       if (mechanism == PIV_ALGORITHM_RSA)
1275         err = genkey_parse_rsa (certbuf, certbuflen, &s_pkey);
1276       else if (mechanism == PIV_ALGORITHM_ECC_P256
1277                || mechanism == PIV_ALGORITHM_ECC_P384)
1278         err = genkey_parse_ecc (certbuf, certbuflen, mechanism, &s_pkey);
1279       else
1280         err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1281       if (err)
1282         goto leave;
1283 
1284       if (!gcry_pk_get_keygrip (s_pkey, grip))
1285         {
1286           log_error ("piv: error computing keygrip\n");
1287           err = gpg_error (GPG_ERR_GENERAL);
1288           goto leave;
1289         }
1290 
1291       bin2hex (grip, sizeof grip, *r_keygripstr);
1292     }
1293   else /* Compute keygrip from certificate.  */
1294     {
1295       *r_got_cert = 0;
1296       err = ksba_cert_new (&cert);
1297       if (err)
1298         goto leave;
1299       err = ksba_cert_init_from_mem (cert, certbuf, certbuflen);
1300       if (err)
1301         goto leave;
1302       err = app_help_get_keygrip_string (cert, *r_keygripstr, NULL, NULL);
1303     }
1304 
1305  leave:
1306   gcry_sexp_release (s_pkey);
1307   ksba_cert_release (cert);
1308   xfree (certbuf);
1309   if (err)
1310     {
1311       xfree (*r_keygripstr);
1312       *r_keygripstr = NULL;
1313     }
1314   return err;
1315 }
1316 
1317 
1318 /* Locate the data object from the given KEYREF.  The KEYREF may also
1319  * be the corresponding OID of the key object.  Returns the data
1320  * object or NULL if not found.  */
1321 static data_object_t
find_dobj_by_keyref(app_t app,const char * keyref)1322 find_dobj_by_keyref (app_t app, const char *keyref)
1323 {
1324   int i;
1325 
1326   (void)app;
1327 
1328   if (!ascii_strncasecmp (keyref, "PIV.", 4))  /* Standard keyref */
1329     {
1330       keyref += 4;
1331       for (i=0; data_objects[i].tag; i++)
1332         if (*data_objects[i].keyref
1333             && !ascii_strcasecmp (keyref, data_objects[i].keyref))
1334           {
1335             return data_objects + i;
1336           }
1337     }
1338   else if (!strncmp (keyref, "2.16.840.1.101.3.7.", 19))  /* OID */
1339     {
1340       keyref += 19;
1341       for (i=0; data_objects[i].tag; i++)
1342         if (*data_objects[i].keyref
1343             && !strcmp (keyref, data_objects[i].oidsuffix))
1344           {
1345             return data_objects + i;
1346           }
1347     }
1348   else if (strlen (keyref) == 40)  /* A keygrip */
1349     {
1350       char *keygripstr = NULL;
1351       int tag, dummy_got_cert;
1352 
1353       for (i=0; (tag=data_objects[i].tag); i++)
1354         {
1355           if (!data_objects[i].keypair)
1356             continue;
1357           xfree (keygripstr);
1358           if (get_keygrip_by_tag (app, tag, &keygripstr, &dummy_got_cert))
1359             continue;
1360           if (!strcmp (keygripstr, keyref))
1361             {
1362               xfree (keygripstr);
1363               return data_objects + i;
1364             }
1365         }
1366       xfree (keygripstr);
1367     }
1368 
1369   return NULL;
1370 }
1371 
1372 
1373 /* Return the keyref from DOBJ as an integer.  If it does not exist,
1374  * return -1.  */
1375 static int
keyref_from_dobj(data_object_t dobj)1376 keyref_from_dobj (data_object_t dobj)
1377 {
1378   if (!dobj || !hexdigitp (dobj->keyref) || !hexdigitp (dobj->keyref+1))
1379     return -1;
1380   return xtoi_2 (dobj->keyref);
1381 }
1382 
1383 
1384 /* Read a certificate from the card and returned in a freshly
1385  * allocated buffer stored at R_CERT and the length of the certificate
1386  * stored at R_CERTLEN.  CERTID is either the OID of the cert's
1387  * container or of the form "PIV.<two_hexdigit_keyref>"  */
1388 static gpg_error_t
do_readcert(app_t app,const char * certid,unsigned char ** r_cert,size_t * r_certlen)1389 do_readcert (app_t app, const char *certid,
1390              unsigned char **r_cert, size_t *r_certlen)
1391 {
1392   gpg_error_t err;
1393   data_object_t dobj;
1394   int mechanism;
1395 
1396   *r_cert = NULL;
1397   *r_certlen = 0;
1398 
1399   /* Hack to read a Yubikey attestation certificate.  */
1400   if (app->app_local->flags.yubikey
1401       && strlen (certid) == 11
1402       && !ascii_strncasecmp (certid, "PIV.ATST.", 9)
1403       && hexdigitp (certid+9) && hexdigitp (certid+10))
1404     {
1405       unsigned char apdu[4];
1406       unsigned char *result;
1407       size_t resultlen;
1408 
1409       apdu[0] = 0;
1410       apdu[1] = 0xf9;  /* Yubikey: Get attestation cert.  */
1411       apdu[2] = xtoi_2 (certid+9);
1412       apdu[3] = 0;
1413       err = iso7816_apdu_direct (app_get_slot (app), apdu, 4, 1,
1414                                  NULL, &result, &resultlen);
1415       if (!err)
1416         {
1417           *r_cert = result;
1418           *r_certlen = resultlen;
1419         }
1420       return err;
1421     }
1422 
1423   dobj = find_dobj_by_keyref (app, certid);
1424   if (!dobj)
1425     return gpg_error (GPG_ERR_INV_ID);
1426 
1427   err = readcert_by_tag (app, dobj->tag, r_cert, r_certlen, &mechanism);
1428   if (!err && mechanism)
1429     {
1430       /* Well, no certificate but a public key - we don't want it.  */
1431       xfree (*r_cert);
1432       *r_cert = NULL;
1433       *r_certlen = 0;
1434       err = gpg_error (GPG_ERR_NOT_FOUND);
1435     }
1436   return err;
1437 }
1438 
1439 
1440 /* Return a public key in a freshly allocated buffer.  This will only
1441  * work for a freshly generated key as long as no reset of the
1442  * application has been performed.  This is because we return a cached
1443  * result from key generation.  If no cached result is available, the
1444  * error GPG_ERR_UNSUPPORTED_OPERATION is returned so that the higher
1445  * layer can then get the key by reading the matching certificate.
1446  * On success a canonical encoded s-expression with the public key is
1447  * stored at (R_PK,R_PKLEN); the caller must release that buffer.  On
1448  * error R_PK and R_PKLEN are not changed and an error code is
1449  * returned.
1450  */
1451 static gpg_error_t
do_readkey(app_t app,ctrl_t ctrl,const char * keyrefstr,unsigned int flags,unsigned char ** r_pk,size_t * r_pklen)1452 do_readkey (app_t app, ctrl_t ctrl, const char *keyrefstr, unsigned int flags,
1453             unsigned char **r_pk, size_t *r_pklen)
1454 {
1455   gpg_error_t err;
1456   data_object_t dobj;
1457   int keyref;
1458   unsigned char *cert = NULL;
1459   size_t certlen;
1460   int mechanism;
1461   gcry_sexp_t s_pkey = NULL;
1462   unsigned char *pk = NULL;
1463   size_t pklen;
1464 
1465   dobj = find_dobj_by_keyref (app, keyrefstr);
1466   if ((keyref = keyref_from_dobj (dobj)) == -1)
1467     {
1468       err = gpg_error (GPG_ERR_INV_ID);
1469       goto leave;
1470     }
1471 
1472   err = readcert_by_tag (app, dobj->tag, &cert, &certlen, &mechanism);
1473   if (err)
1474     goto leave;
1475   if (!mechanism)
1476     {
1477       /* We got a certificate.  Extract the pubkey from it.  */
1478       err = app_help_pubkey_from_cert (cert, certlen, &pk, &pklen);
1479       if (err)
1480         {
1481           log_error ("failed to parse the certificate: %s\n",
1482                      gpg_strerror (err));
1483           goto leave;
1484         }
1485     }
1486   else
1487     {
1488       /* Convert the public key into the expected s-expression.  */
1489       if (mechanism == PIV_ALGORITHM_RSA)
1490         err = genkey_parse_rsa (cert, certlen, &s_pkey);
1491       else if (mechanism == PIV_ALGORITHM_ECC_P256
1492                || mechanism == PIV_ALGORITHM_ECC_P384)
1493         err = genkey_parse_ecc (cert, certlen, mechanism, &s_pkey);
1494       else
1495         err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1496       if (err)
1497         goto leave;
1498 
1499       err = make_canon_sexp (s_pkey, &pk, &pklen);
1500       if (err)
1501         goto leave;
1502     }
1503 
1504   if ((flags & APP_READKEY_FLAG_INFO))
1505     {
1506       char keygripstr[KEYGRIP_LEN*2+1];
1507       char idbuf[50];
1508       const char *usage;
1509       char *algostr;
1510 
1511       err = app_help_get_keygrip_string_pk (pk, pklen, keygripstr,
1512                                             NULL, NULL, &algostr);
1513       if (err)
1514         {
1515           log_error ("app_help_get_keygrip_string_pk failed: %s\n",
1516                      gpg_strerror (err));
1517           goto leave;
1518         }
1519       usage = dobj->usage? dobj->usage : "";
1520 
1521       snprintf (idbuf, sizeof idbuf, "PIV.%s", dobj->keyref);
1522       send_status_info (ctrl, "KEYPAIRINFO",
1523                         keygripstr, strlen (keygripstr),
1524                         idbuf, strlen (idbuf),
1525                         usage, strlen (usage),
1526                         "-", (size_t)1,
1527                         algostr, strlen (algostr),
1528                         NULL, (size_t)0);
1529       xfree (algostr);
1530     }
1531 
1532   if (r_pk && r_pklen)
1533     {
1534       *r_pk = pk;
1535       pk = NULL;
1536       *r_pklen = pklen;
1537     }
1538 
1539  leave:
1540   gcry_sexp_release (s_pkey);
1541   xfree (pk);
1542   xfree (cert);
1543   return err;
1544 }
1545 
1546 
1547 /* Given a data object DOBJ return the corresponding PIV algorithm and
1548  * store it at R_ALGO.  The algorithm is taken from the corresponding
1549  * certificate or from a cache.  */
1550 static gpg_error_t
get_key_algorithm_by_dobj(app_t app,data_object_t dobj,int * r_mechanism)1551 get_key_algorithm_by_dobj (app_t app, data_object_t dobj, int *r_mechanism)
1552 {
1553   gpg_error_t err;
1554   unsigned char *certbuf = NULL;
1555   size_t certbuflen;
1556   int mechanism;
1557   ksba_cert_t cert = NULL;
1558   ksba_sexp_t k_pkey = NULL;
1559   gcry_sexp_t s_pkey = NULL;
1560   gcry_sexp_t l1 = NULL;
1561   char *algoname = NULL;
1562   int algo;
1563   size_t n;
1564   const char *curve_name;
1565 
1566   *r_mechanism = 0;
1567 
1568   err = readcert_by_tag (app, dobj->tag, &certbuf, &certbuflen, &mechanism);
1569   if (err)
1570     goto leave;
1571   if (mechanism)
1572     {
1573       /* A public key was found.  That makes it easy.  */
1574       switch (mechanism)
1575         {
1576         case PIV_ALGORITHM_RSA:
1577         case PIV_ALGORITHM_ECC_P256:
1578         case PIV_ALGORITHM_ECC_P384:
1579           *r_mechanism = mechanism;
1580           break;
1581 
1582         default:
1583           err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1584           log_error ("piv: unknown mechanism %d in public key at %s\n",
1585                      mechanism, dobj->keyref);
1586           break;
1587         }
1588       goto leave;
1589     }
1590 
1591   err = ksba_cert_new (&cert);
1592   if (err)
1593     goto leave;
1594 
1595   err = ksba_cert_init_from_mem (cert, certbuf, certbuflen);
1596   if (err)
1597     {
1598       log_error ("piv: failed to parse the certificate %s: %s\n",
1599                  dobj->keyref, gpg_strerror (err));
1600       goto leave;
1601     }
1602   xfree (certbuf);
1603   certbuf = NULL;
1604 
1605   k_pkey = ksba_cert_get_public_key (cert);
1606   if (!k_pkey)
1607     {
1608       err = gpg_error (GPG_ERR_NO_PUBKEY);
1609       goto leave;
1610     }
1611   n = gcry_sexp_canon_len (k_pkey, 0, NULL, NULL);
1612   err = gcry_sexp_new (&s_pkey, k_pkey, n, 0);
1613   if (err)
1614     goto leave;
1615 
1616   l1 = gcry_sexp_find_token (s_pkey, "public-key", 0);
1617   if (!l1)
1618     {
1619       err = gpg_error (GPG_ERR_NO_PUBKEY);
1620       goto leave;
1621     }
1622 
1623   {
1624     gcry_sexp_t l_tmp = gcry_sexp_cadr (l1);
1625     gcry_sexp_release (l1);
1626     l1 = l_tmp;
1627   }
1628   algoname = gcry_sexp_nth_string (l1, 0);
1629   if (!algoname)
1630     {
1631       err = gpg_error_from_syserror ();
1632       goto leave;
1633     }
1634 
1635   algo = gcry_pk_map_name (algoname);
1636   switch (algo)
1637     {
1638     case GCRY_PK_RSA:
1639       algo = PIV_ALGORITHM_RSA;
1640       break;
1641 
1642     case GCRY_PK_ECC:
1643     case GCRY_PK_ECDSA:
1644     case GCRY_PK_ECDH:
1645       curve_name = gcry_pk_get_curve (s_pkey, 0, NULL);
1646       if (curve_name && !strcmp (curve_name, "NIST P-256"))
1647         algo = PIV_ALGORITHM_ECC_P256;
1648       else if (curve_name && !strcmp (curve_name, "NIST P-384"))
1649         algo = PIV_ALGORITHM_ECC_P384;
1650       else
1651         {
1652           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1653           log_error ("piv: certificate %s, curve '%s': %s\n",
1654                      dobj->keyref, curve_name, gpg_strerror (err));
1655           goto leave;
1656         }
1657       break;
1658 
1659     default:
1660       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1661       log_error ("piv: certificate %s, pubkey algo '%s': %s\n",
1662                  dobj->keyref, algoname, gpg_strerror (err));
1663       goto leave;
1664     }
1665   *r_mechanism = algo;
1666 
1667  leave:
1668   gcry_free (algoname);
1669   gcry_sexp_release (l1);
1670   gcry_sexp_release (s_pkey);
1671   ksba_free (k_pkey);
1672   xfree (certbuf);
1673   return err;
1674 }
1675 
1676 
1677 /* Helper to cache the pin PINNO.  If PIN is NULL the cache is cleared. */
1678 static void
cache_pin(app_t app,ctrl_t ctrl,int pinno,const char * pin,unsigned int pinlen)1679 cache_pin (app_t app, ctrl_t ctrl, int pinno,
1680            const char *pin, unsigned int pinlen)
1681 {
1682   char pinref[20];
1683 
1684   if (opt.pcsc_shared)
1685     return;
1686 
1687   if (pinno < 0)
1688     return;
1689   switch (app->card->cardtype)
1690     {
1691     case CARDTYPE_YUBIKEY: break;
1692     default: return;
1693     }
1694 
1695 
1696 
1697   snprintf (pinref, sizeof pinref, "%02x", pinno);
1698   pincache_put (ctrl, app_get_slot (app), "piv", pinref, pin, pinlen);
1699 
1700   switch (pinno)
1701     {
1702     case 0x00: app->app_local->pincache.maybe_00 = !!pin; break;
1703     case 0x80: app->app_local->pincache.maybe_80 = !!pin; break;
1704     case 0x81: app->app_local->pincache.maybe_81 = !!pin; break;
1705     case 0x96: app->app_local->pincache.maybe_96 = !!pin; break;
1706     case 0x97: app->app_local->pincache.maybe_97 = !!pin; break;
1707     case 0x98: app->app_local->pincache.maybe_98 = !!pin; break;
1708     case 0x9B: app->app_local->pincache.maybe_9B = !!pin; break;
1709     }
1710 
1711 }
1712 
1713 
1714 /* If the PIN cache is available and really has a valid PIN return
1715  * that pin at R_PIN.  Returns true if that is the case; otherwise
1716  * false.  */
1717 static int
pin_from_cache(app_t app,ctrl_t ctrl,int pinno,char ** r_pin)1718 pin_from_cache (app_t app, ctrl_t ctrl, int pinno, char **r_pin)
1719 {
1720   char pinref[20];
1721   int maybe_cached;
1722 
1723   *r_pin = NULL;
1724 
1725   if (pinno < 0)
1726     return 0;
1727   switch (app->card->cardtype)
1728     {
1729     case CARDTYPE_YUBIKEY: break;
1730     default: return 0;
1731     }
1732 
1733   switch (pinno)
1734     {
1735     case 0x00: maybe_cached = app->app_local->pincache.maybe_00; break;
1736     case 0x80: maybe_cached = app->app_local->pincache.maybe_80; break;
1737     case 0x81: maybe_cached = app->app_local->pincache.maybe_81; break;
1738     case 0x96: maybe_cached = app->app_local->pincache.maybe_96; break;
1739     case 0x97: maybe_cached = app->app_local->pincache.maybe_97; break;
1740     case 0x98: maybe_cached = app->app_local->pincache.maybe_98; break;
1741     case 0x9B: maybe_cached = app->app_local->pincache.maybe_9B; break;
1742     default:   maybe_cached = 0;
1743     }
1744 
1745   if (!maybe_cached)
1746     return 0;
1747 
1748   snprintf (pinref, sizeof pinref, "%02x", pinno);
1749   if (pincache_get (ctrl, app_get_slot (app), "piv", pinref, r_pin))
1750     return 0;
1751 
1752   return 1;
1753 }
1754 
1755 
1756 /* Return an allocated string to be used as prompt.  Returns NULL on
1757  * malloc error.  */
1758 static char *
make_prompt(app_t app,int remaining,const char * firstline)1759 make_prompt (app_t app, int remaining, const char *firstline)
1760 {
1761   char *serial, *tmpbuf, *result;
1762 
1763   serial = app_get_dispserialno (app, 0);
1764   if (!serial)
1765     return NULL;
1766 
1767   /* TRANSLATORS: Put a \x1f right before a colon.  This can be
1768    * used by pinentry to nicely align the names and values.  Keep
1769    * the %s at the start and end of the string.  */
1770   result = xtryasprintf (_("%s"
1771                            "Number\x1f: %s%%0A"
1772                            "Holder\x1f: %s"
1773                            "%s"),
1774                          "\x1e",
1775                          serial,
1776                          "Unknown", /* Fixme */
1777                          "");
1778   xfree (serial);
1779 
1780   /* Append a "remaining attempts" info if needed.  */
1781   if (remaining != -1 && remaining < 3)
1782     {
1783       char *rembuf;
1784 
1785       /* TRANSLATORS: This is the number of remaining attempts to
1786        * enter a PIN.  Use %%0A (double-percent,0A) for a linefeed. */
1787       rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
1788       if (rembuf)
1789         {
1790           tmpbuf = strconcat (firstline, "%0A%0A", result,
1791                               "%0A%0A", rembuf, NULL);
1792           xfree (rembuf);
1793         }
1794       else
1795         tmpbuf = NULL;
1796       xfree (result);
1797       result = tmpbuf;
1798     }
1799   else
1800     {
1801       tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
1802       xfree (result);
1803       result = tmpbuf;
1804     }
1805 
1806   return result;
1807 }
1808 
1809 
1810 /* Helper for verify_chv to ask for the PIN and to prepare/pad it.  On
1811  * success the result is stored at (R_PIN,R_PINLEN).  */
1812 static gpg_error_t
ask_and_prepare_chv(app_t app,ctrl_t ctrl,int keyref,int ask_new,int remaining,int no_cache,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,char ** r_pin,unsigned int * r_pinlen,unsigned int * r_unpaddedpinlen)1813 ask_and_prepare_chv (app_t app, ctrl_t ctrl,
1814                      int keyref, int ask_new, int remaining, int no_cache,
1815                      gpg_error_t (*pincb)(void*,const char *,char **),
1816                      void *pincb_arg, char **r_pin, unsigned int *r_pinlen,
1817                      unsigned int *r_unpaddedpinlen)
1818 {
1819   gpg_error_t err;
1820   const char *label;
1821   char *prompt;
1822   char *pinvalue = NULL;
1823   unsigned int pinlen;
1824   char *pinbuffer = NULL;
1825   int minlen, maxlen, padding, onlydigits;
1826 
1827   *r_pin = NULL;
1828   *r_pinlen = 0;
1829   if (r_unpaddedpinlen)
1830     *r_unpaddedpinlen = 0;
1831 
1832   if (ask_new)
1833     remaining = -1;
1834 
1835   if (remaining != -1)
1836     log_debug ("piv: CHV %02X has %d attempts left\n", keyref, remaining);
1837 
1838   switch (keyref)
1839     {
1840     case 0x00:
1841       minlen = 6;
1842       maxlen = 8;
1843       padding = 1;
1844       onlydigits = 1;
1845       label = (ask_new? _("|N|Please enter the new Global-PIN")
1846                /**/   : _("||Please enter the Global-PIN of your PIV card"));
1847       break;
1848     case 0x80:
1849       minlen = 6;
1850       maxlen = 8;
1851       padding = 1;
1852       onlydigits = 1;
1853       label = (ask_new? _("|N|Please enter the new PIN")
1854                /**/   : _("||Please enter the PIN of your PIV card"));
1855       break;
1856     case 0x81:
1857       minlen = 8;
1858       maxlen = 8;
1859       padding = 0;
1860       onlydigits = 0;
1861       label = (ask_new? _("|N|Please enter the new Unblocking Key")
1862                /**/   :_("||Please enter the Unblocking Key of your PIV card"));
1863       break;
1864 
1865     case 0x96:
1866     case 0x97:
1867     case 0x98:
1868     case 0x9B:
1869       return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1870 
1871     default:
1872       return gpg_error (GPG_ERR_INV_ID);
1873     }
1874 
1875   /* Ask for the PIN.  */
1876   if (!no_cache && remaining >= 3
1877       && pin_from_cache (app, ctrl, keyref, &pinvalue))
1878     err = 0;
1879   else
1880     {
1881       prompt = make_prompt (app, remaining, label);
1882       err = pincb (pincb_arg, prompt, &pinvalue);
1883       xfree (prompt);
1884       prompt = NULL;
1885     }
1886   if (err)
1887     {
1888       log_info (_("PIN callback returned error: %s\n"), gpg_strerror (err));
1889       return err;
1890     }
1891 
1892   pinlen = pinvalue? strlen (pinvalue) : 0;
1893   if (pinlen < minlen)
1894     {
1895       log_error (_("PIN is too short; minimum length is %d\n"), minlen);
1896       if (pinvalue)
1897         wipememory (pinvalue, pinlen);
1898       xfree (pinvalue);
1899       return gpg_error (GPG_ERR_BAD_PIN);
1900     }
1901   if (pinlen > maxlen)
1902     {
1903       log_error (_("PIN is too long; maximum length is %d\n"), maxlen);
1904       wipememory (pinvalue, pinlen);
1905       xfree (pinvalue);
1906       return gpg_error (GPG_ERR_BAD_PIN);
1907     }
1908   if (onlydigits && strspn (pinvalue, "0123456789") != pinlen)
1909     {
1910       log_error (_("PIN has invalid characters; only digits are allowed\n"));
1911       wipememory (pinvalue, pinlen);
1912       xfree (pinvalue);
1913       return gpg_error (GPG_ERR_BAD_PIN);
1914     }
1915 
1916   pinbuffer = xtrymalloc_secure (maxlen);
1917   if (!pinbuffer)
1918     {
1919       err = gpg_error_from_syserror ();
1920       wipememory (pinvalue, pinlen);
1921       xfree (pinvalue);
1922       return err;
1923     }
1924 
1925   memcpy (pinbuffer, pinvalue, pinlen);
1926   wipememory (pinvalue, pinlen);
1927   xfree (pinvalue);
1928 
1929   if (r_unpaddedpinlen)
1930     *r_unpaddedpinlen = pinlen;
1931 
1932   if (padding)
1933     {
1934       memset (pinbuffer + pinlen, 0xff, maxlen - pinlen);
1935       pinlen = maxlen;
1936     }
1937 
1938   *r_pin = pinbuffer;
1939   *r_pinlen = pinlen;
1940 
1941   return 0;
1942 }
1943 
1944 
1945 /* Verify the card holder verification identified by KEYREF.  This is
1946  * either the Application PIN or the Global PIN.  If FORCE is true a
1947  * verification is always done.  */
1948 static gpg_error_t
verify_chv(app_t app,ctrl_t ctrl,int keyref,int force,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)1949 verify_chv (app_t app, ctrl_t ctrl, int keyref, int force,
1950             gpg_error_t (*pincb)(void*,const char *,char **), void *pincb_arg)
1951 {
1952   gpg_error_t err;
1953   int remaining;
1954   char *pin = NULL;
1955   unsigned int pinlen, unpaddedpinlen;
1956 
1957   /* First check whether a verify is at all needed.  */
1958   remaining = iso7816_verify_status (app_get_slot (app), keyref);
1959   if (remaining == ISO7816_VERIFY_NOT_NEEDED)
1960     {
1961       if (!force) /* No need to verification.  */
1962         return 0;  /* All fine.  */
1963       remaining = -1;
1964     }
1965   else if (remaining < 0)  /* We don't care about other errors. */
1966     remaining = -1;
1967 
1968 
1969   err = ask_and_prepare_chv (app, ctrl, keyref, 0, remaining, force,
1970                              pincb, pincb_arg,
1971                              &pin, &pinlen, &unpaddedpinlen);
1972   if (err)
1973     return err;
1974 
1975   err = iso7816_verify (app_get_slot (app), keyref, pin, pinlen);
1976   if (err)
1977     {
1978       log_error ("CHV %02X verification failed: %s\n",
1979                  keyref, gpg_strerror (err));
1980       cache_pin (app, ctrl, keyref, NULL, 0);
1981     }
1982   else
1983     cache_pin (app, ctrl, keyref, pin, unpaddedpinlen);
1984 
1985   wipememory (pin, pinlen);
1986   xfree (pin);
1987 
1988   return err;
1989 }
1990 
1991 
1992 /* Handle the PASSWD command.  Valid values for PWIDSTR are
1993  * key references related to PINs; in particular:
1994  *   PIV.00 - The Global PIN
1995  *   PIV.80 - The Application PIN
1996  *   PIV.81 - The PIN Unblocking key
1997  * The supported flags are:
1998  *   APP_CHANGE_FLAG_CLEAR   Clear the PIN verification state.
1999  *   APP_CHANGE_FLAG_RESET   Reset a PIN using the PUK.  Only
2000  *                           allowed with PIV.80.
2001  */
2002 static gpg_error_t
do_change_chv(app_t app,ctrl_t ctrl,const char * pwidstr,unsigned int flags,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)2003 do_change_chv (app_t app, ctrl_t ctrl, const char *pwidstr,
2004                unsigned int flags,
2005                gpg_error_t (*pincb)(void*, const char *, char **),
2006                void *pincb_arg)
2007 {
2008   gpg_error_t err;
2009   int keyref, targetkeyref;
2010   unsigned char apdu[4];
2011   unsigned int sw;
2012   int remaining;
2013   char *oldpin = NULL;
2014   unsigned int oldpinlen;
2015   char *newpin = NULL;
2016   unsigned int newpinlen;
2017 
2018   (void)ctrl;
2019 
2020   /* Check for unknown flags.  */
2021   if ((flags & ~(APP_CHANGE_FLAG_CLEAR|APP_CHANGE_FLAG_RESET)))
2022     {
2023       err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2024       goto leave;
2025     }
2026 
2027   /* Parse the keyref.  */
2028   targetkeyref = keyref = parse_chv_keyref (pwidstr);
2029   if (keyref == -1)
2030     {
2031       err = gpg_error (GPG_ERR_INV_ID);
2032       goto leave;
2033     }
2034 
2035   cache_pin (app, ctrl, keyref, NULL, 0);
2036 
2037   /* First see whether the special --clear mode has been requested.  */
2038   if ((flags & APP_CHANGE_FLAG_CLEAR))
2039     {
2040       apdu[0] = 0x00;
2041       apdu[1] = ISO7816_VERIFY;
2042       apdu[2] = 0xff;
2043       apdu[3] = keyref;
2044       err = iso7816_apdu_direct (app_get_slot (app), apdu, 4, 0,
2045                                  NULL, NULL, NULL);
2046       goto leave;
2047     }
2048 
2049   /* Prepare reset mode.  */
2050   if ((flags & APP_CHANGE_FLAG_RESET))
2051     {
2052       if (keyref == 0x81)
2053         {
2054           err = gpg_error (GPG_ERR_INV_ID); /* Can't reset the PUK.  */
2055           goto leave;
2056         }
2057       /* Set the keyref to the PUK and keep the TARGETKEYREF.  */
2058       keyref = 0x81;
2059     }
2060 
2061   /* Get the remaining tries count.  This is done by using the check
2062    * for verified state feature.  */
2063   apdu[0] = 0x00;
2064   apdu[1] = ISO7816_VERIFY;
2065   apdu[2] = 0x00;
2066   apdu[3] = keyref;
2067   if (!iso7816_apdu_direct (app_get_slot (app), apdu, 4, 0, &sw, NULL, NULL))
2068     remaining = -1; /* Already verified, thus full number of tries.  */
2069   else if ((sw & 0xfff0) == 0x63C0)
2070     remaining = (sw & 0x000f); /* PIN has REMAINING tries left.  */
2071   else
2072     remaining = -1;
2073 
2074   /* Ask for the old pin or puk.  */
2075   err = ask_and_prepare_chv (app, ctrl, keyref, 0, remaining, 0,
2076                              pincb, pincb_arg,
2077                              &oldpin, &oldpinlen, NULL);
2078   if (err)
2079     return err;
2080 
2081   /* Verify the old pin so that we don't prompt for the new pin if the
2082    * old is wrong.  This is not possible for the PUK, though. */
2083   if (keyref != 0x81)
2084     {
2085       err = iso7816_verify (app_get_slot (app), keyref, oldpin, oldpinlen);
2086       if (err)
2087         {
2088           log_error ("CHV %02X verification failed: %s\n",
2089                      keyref, gpg_strerror (err));
2090           goto leave;
2091         }
2092     }
2093 
2094   /* Ask for the new pin.  */
2095   err = ask_and_prepare_chv (app, ctrl, targetkeyref, 1, -1, 0,
2096                              pincb, pincb_arg,
2097                              &newpin, &newpinlen, NULL);
2098   if (err)
2099     return err;
2100 
2101   if ((flags & APP_CHANGE_FLAG_RESET))
2102     {
2103       char *buf = xtrymalloc_secure (oldpinlen + newpinlen);
2104       if (!buf)
2105         {
2106           err = gpg_error_from_syserror ();
2107           goto leave;
2108         }
2109       memcpy (buf, oldpin, oldpinlen);
2110       memcpy (buf+oldpinlen, newpin, newpinlen);
2111       err = iso7816_reset_retry_counter_with_rc (app_get_slot (app),
2112                                                  targetkeyref,
2113                                                  buf, oldpinlen+newpinlen);
2114       xfree (buf);
2115       if (err)
2116         log_error ("resetting CHV %02X using CHV %02X failed: %s\n",
2117                    targetkeyref, keyref, gpg_strerror (err));
2118     }
2119   else
2120     {
2121       err = iso7816_change_reference_data (app_get_slot (app), keyref,
2122                                            oldpin, oldpinlen,
2123                                            newpin, newpinlen);
2124       if (err)
2125         log_error ("CHV %02X changing PIN failed: %s\n",
2126                    keyref, gpg_strerror (err));
2127     }
2128 
2129  leave:
2130   xfree (oldpin);
2131   xfree (newpin);
2132   return err;
2133 }
2134 
2135 
2136 /* Perform a simple verify operation for the PIN specified by PWIDSTR.
2137  * For valid values see do_change_chv.  */
2138 static gpg_error_t
do_check_chv(app_t app,ctrl_t ctrl,const char * pwidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)2139 do_check_chv (app_t app, ctrl_t ctrl, const char *pwidstr,
2140               gpg_error_t (*pincb)(void*, const char *, char **),
2141               void *pincb_arg)
2142 {
2143   int keyref;
2144 
2145   (void)ctrl;
2146 
2147   keyref = parse_chv_keyref (pwidstr);
2148   if (keyref == -1)
2149     return gpg_error (GPG_ERR_INV_ID);
2150 
2151   return verify_chv (app, ctrl, keyref, 0, pincb, pincb_arg);
2152 }
2153 
2154 
2155 /* Compute a digital signature using the GENERAL AUTHENTICATE command
2156  * on INDATA which is expected to be the raw message digest.  The
2157  * KEYIDSTR has the key reference or its OID (e.g. "PIV.9A").  The
2158  * result is stored at (R_OUTDATA,R_OUTDATALEN); on error (NULL,0) is
2159  * stored there and an error code returned.  For ECDSA the result is
2160  * the simple concatenation of R and S without any DER encoding.  R
2161  * and S are left extended with zeroes to make sure they have an equal
2162  * length.  If HASHALGO is not zero, the function prepends the hash's
2163  * OID to the indata or checks that it is consistent.
2164  */
2165 static gpg_error_t
do_sign(app_t app,ctrl_t ctrl,const char * keyidstr,int hashalgo,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata_arg,size_t indatalen,unsigned char ** r_outdata,size_t * r_outdatalen)2166 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
2167          gpg_error_t (*pincb)(void*, const char *, char **),
2168          void *pincb_arg,
2169          const void *indata_arg, size_t indatalen,
2170          unsigned char **r_outdata, size_t *r_outdatalen)
2171 {
2172   const unsigned char *indata = indata_arg;
2173   gpg_error_t err;
2174   data_object_t dobj;
2175   unsigned char oidbuf[64];
2176   size_t oidbuflen;
2177   unsigned char *outdata = NULL;
2178   size_t outdatalen = 0;
2179   const unsigned char *s;
2180   size_t n;
2181   int keyref, mechanism;
2182   unsigned char *indata_buffer = NULL; /* Malloced helper.  */
2183   unsigned char *apdudata = NULL;
2184   size_t apdudatalen;
2185   int force_verify;
2186 
2187   (void)ctrl;
2188 
2189   if (!keyidstr || !*keyidstr)
2190     {
2191       err = gpg_error (GPG_ERR_INV_VALUE);
2192       goto leave;
2193     }
2194 
2195   dobj = find_dobj_by_keyref (app, keyidstr);
2196   if ((keyref = keyref_from_dobj (dobj)) == -1)
2197     {
2198       err = gpg_error (GPG_ERR_INV_ID);
2199       goto leave;
2200     }
2201 
2202   /* According to table 4b of SP800-73-4 the signing key always
2203    * requires a verify.  */
2204   switch (keyref)
2205     {
2206     case 0x9c: force_verify = 1; break;
2207     default: force_verify = 0; break;
2208     }
2209 
2210 
2211   err = get_key_algorithm_by_dobj (app, dobj, &mechanism);
2212   if (err)
2213     goto leave;
2214 
2215    /* For ECC we need to remove the ASN.1 prefix from INDATA.  For RSA
2216     * we need to add the padding and possible also the ASN.1 prefix.  */
2217   if (mechanism == PIV_ALGORITHM_ECC_P256
2218       || mechanism == PIV_ALGORITHM_ECC_P384)
2219     {
2220       int need_algo, need_digestlen;
2221 
2222       if (mechanism == PIV_ALGORITHM_ECC_P256)
2223         {
2224           need_algo = GCRY_MD_SHA256;
2225           need_digestlen = 32;
2226         }
2227       else
2228         {
2229           need_algo = GCRY_MD_SHA384;
2230           need_digestlen = 48;
2231         }
2232 
2233       if (hashalgo && hashalgo != need_algo)
2234         {
2235           err = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2236           log_error ("piv: hash algo %d does not match mechanism %d\n",
2237                      need_algo, mechanism);
2238           goto leave;
2239         }
2240 
2241       if (indatalen > need_digestlen)
2242         {
2243           oidbuflen = sizeof oidbuf;
2244           err = gcry_md_get_asnoid (need_algo, &oidbuf, &oidbuflen);
2245           if (err)
2246             {
2247               err = gpg_error (GPG_ERR_INTERNAL);
2248               log_debug ("piv: no OID for hash algo %d\n", need_algo);
2249               goto leave;
2250             }
2251           if (indatalen != oidbuflen + need_digestlen
2252               || memcmp (indata, oidbuf, oidbuflen))
2253             {
2254               err = gpg_error (GPG_ERR_INV_VALUE);
2255               log_error ("piv: bad input for signing with mechanism %d\n",
2256                          mechanism);
2257               goto leave;
2258             }
2259           indata += oidbuflen;
2260           indatalen -= oidbuflen;
2261         }
2262     }
2263   else if (mechanism == PIV_ALGORITHM_RSA
2264            && indatalen == 2048/8 && indata[indatalen-1] == 0xBC)
2265     {
2266       /* If the provided data length matches the supported RSA
2267        * framelen and the last octet of the data is 0xBC, we assume
2268        * this is PSS formatted data and we use it verbatim; PIV cards
2269        * accept PSS as well as PKCS#1.  */
2270     }
2271   else if (mechanism == PIV_ALGORITHM_RSA)
2272     {
2273       /* PIV requires 2048 bit RSA.  */
2274       unsigned int framelen = 2048 / 8;
2275       unsigned char *frame;
2276       int i;
2277 
2278       oidbuflen = sizeof oidbuf;
2279       if (!hashalgo)
2280         {
2281           /* We assume that indata already has the required
2282            * digestinfo; thus merely prepend the padding below.  */
2283         }
2284       else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
2285         {
2286           log_debug ("piv: no OID for hash algo %d\n", hashalgo);
2287           goto leave;
2288         }
2289       else
2290         {
2291           unsigned int digestlen = gcry_md_get_algo_dlen (hashalgo);
2292 
2293           if (indatalen == digestlen)
2294             {
2295               /* Plain hash in INDATA; prepend the digestinfo.  */
2296               indata_buffer = xtrymalloc (oidbuflen + indatalen);
2297               if (!indata_buffer)
2298                 {
2299                   err = gpg_error_from_syserror ();
2300                   goto leave;
2301                 }
2302               memcpy (indata_buffer, oidbuf, oidbuflen);
2303               memcpy (indata_buffer+oidbuflen, indata, indatalen);
2304               indata = indata_buffer;
2305               indatalen = oidbuflen + indatalen;
2306             }
2307           else if (indatalen == oidbuflen + digestlen
2308                    && !memcmp (indata, oidbuf, oidbuflen))
2309             ; /* Correct prefix.  */
2310           else
2311             {
2312               err = gpg_error (GPG_ERR_INV_VALUE);
2313               log_error ("piv: bad input for signing with RSA and hash %d\n",
2314                          hashalgo);
2315               goto leave;
2316             }
2317         }
2318       /* Now prepend the pkcs#v1.5 padding.  We require at least 8
2319        * byte of padding and 3 extra bytes for the prefix and the
2320        * delimiting nul.  */
2321       if (!indatalen || indatalen + 8 + 4 > framelen)
2322         {
2323           err = gpg_error (GPG_ERR_INV_VALUE);
2324           log_error ("piv: input does not fit into a %u bit PKCS#v1.5 frame\n",
2325                      8*framelen);
2326           goto leave;
2327         }
2328       frame = xtrymalloc (framelen);
2329       if (!frame)
2330         {
2331           err = gpg_error_from_syserror ();
2332           goto leave;
2333         }
2334       n = 0;
2335       frame[n++] = 0;
2336       frame[n++] = 1; /* Block type. */
2337       i = framelen - indatalen - 3 ;
2338       memset (frame+n, 0xff, i);
2339       n += i;
2340       frame[n++] = 0; /* Delimiter.  */
2341       memcpy (frame+n, indata, indatalen);
2342       n += indatalen;
2343       log_assert (n == framelen);
2344       /* And now put it into the indata_buffer.  */
2345       xfree (indata_buffer);
2346       indata_buffer = frame;
2347       indata = indata_buffer;
2348       indatalen = framelen;
2349     }
2350   else
2351     {
2352       err = gpg_error (GPG_ERR_INTERNAL);
2353       log_debug ("piv: unknown PIV mechanism %d while signing\n", mechanism);
2354       goto leave;
2355     }
2356 
2357   /* Now verify the Application PIN.  */
2358   err = verify_chv (app, ctrl, 0x80, force_verify, pincb, pincb_arg);
2359   if (err)
2360     goto leave;
2361 
2362   /* Build the Dynamic Authentication Template.  */
2363   err = concat_tlv_list (0, &apdudata, &apdudatalen,
2364                          (int)0x7c, (size_t)0, NULL, /* Constructed. */
2365                          (int)0x82, (size_t)0, "",
2366                          (int)0x81, (size_t)indatalen, indata,
2367                          (int)0, (size_t)0, NULL);
2368   if (err)
2369     goto leave;
2370 
2371   /* Note: the -1 requests command chaining.  */
2372   err = iso7816_general_authenticate (app_get_slot (app), -1,
2373                                       mechanism, keyref,
2374                                       apdudata, (int)apdudatalen, 0,
2375                                       &outdata, &outdatalen);
2376   if (err)
2377     goto leave;
2378 
2379   /* Parse the response.  */
2380   if (outdatalen && *outdata == 0x7c
2381       && (s = find_tlv (outdata, outdatalen, 0x82, &n)))
2382     {
2383       if (mechanism == PIV_ALGORITHM_RSA)
2384         {
2385           memmove (outdata, outdata + (s - outdata), n);
2386           outdatalen = n;
2387         }
2388       else /* ECC */
2389         {
2390           const unsigned char *rval, *sval;
2391           size_t rlen, rlenx, slen, slenx, resultlen;
2392           char *result;
2393           /* The result of an ECDSA signature is
2394            *   SEQUENCE { r INTEGER, s INTEGER }
2395            * We re-pack that by concatenating R and S and making sure
2396            * that both have the same length.  We simplify parsing by
2397            * using find_tlv and not a proper DER parser.  */
2398           s = find_tlv (s, n, 0x30, &n);
2399           if (!s)
2400             goto bad_der;
2401           rval = find_tlv (s, n, 0x02, &rlen);
2402           if (!rval)
2403             goto bad_der;
2404           log_assert (n >= (rval-s)+rlen);
2405           sval = find_tlv (rval+rlen, n-((rval-s)+rlen), 0x02, &slen);
2406           if (!sval)
2407             goto bad_der;
2408           rlenx = slenx = 0;
2409           if (rlen > slen)
2410             slenx = rlen - slen;
2411           else if (slen > rlen)
2412             rlenx = slen - rlen;
2413 
2414           resultlen = rlen + rlenx + slen + slenx;
2415           result = xtrycalloc (1, resultlen);
2416           if (!result)
2417             {
2418               err = gpg_error_from_syserror ();
2419               goto leave;
2420             }
2421           memcpy (result + rlenx, rval, rlen);
2422           memcpy (result + rlenx + rlen + slenx, sval, slen);
2423           xfree (outdata);
2424           outdata = result;
2425           outdatalen = resultlen;
2426         }
2427     }
2428   else
2429     {
2430     bad_der:
2431       err = gpg_error (GPG_ERR_CARD);
2432       log_error ("piv: response does not contain a proper result\n");
2433       goto leave;
2434     }
2435 
2436  leave:
2437   if (err)
2438     {
2439       xfree (outdata);
2440       *r_outdata = NULL;
2441       *r_outdatalen = 0;
2442     }
2443   else
2444     {
2445       *r_outdata = outdata;
2446       *r_outdatalen = outdatalen;
2447     }
2448   xfree (apdudata);
2449   xfree (indata_buffer);
2450   return err;
2451 }
2452 
2453 
2454 /* AUTH for PIV cards is actually the same as SIGN.  The difference
2455  * between AUTH and SIGN is that AUTH expects that pkcs#1.5 padding
2456  * for RSA has already been done (digestInfo part w/o the padding)
2457  * whereas SIGN may accept a plain digest and does the padding if
2458  * needed.  This is also the reason why SIGN takes a hashalgo.  For
2459  * both it is also acceptable to receive fully prepared PSS data.  */
2460 static gpg_error_t
do_auth(app_t app,ctrl_t ctrl,const char * keyidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata,size_t indatalen,unsigned char ** r_outdata,size_t * r_outdatalen)2461 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
2462          gpg_error_t (*pincb)(void*, const char *, char **),
2463          void *pincb_arg,
2464          const void *indata, size_t indatalen,
2465          unsigned char **r_outdata, size_t *r_outdatalen)
2466 {
2467   return do_sign (app, ctrl, keyidstr, 0, pincb, pincb_arg, indata, indatalen,
2468                   r_outdata, r_outdatalen);
2469 }
2470 
2471 
2472 /* Decrypt the data in (INDATA,INDATALEN) and on success store the
2473  * mallocated result at (R_OUTDATA,R_OUTDATALEN).  */
2474 static gpg_error_t
do_decipher(app_t app,ctrl_t ctrl,const char * keyidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata_arg,size_t indatalen,unsigned char ** r_outdata,size_t * r_outdatalen,unsigned int * r_info)2475 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
2476              gpg_error_t (*pincb)(void*, const char *, char **),
2477              void *pincb_arg,
2478              const void *indata_arg, size_t indatalen,
2479              unsigned char **r_outdata, size_t *r_outdatalen,
2480              unsigned int *r_info)
2481 {
2482   const unsigned char *indata = indata_arg;
2483   gpg_error_t err;
2484   data_object_t dobj;
2485   unsigned char *outdata = NULL;
2486   size_t outdatalen;
2487   const unsigned char *s;
2488   size_t n;
2489   int keyref, mechanism;
2490   unsigned int framelen;
2491   unsigned char *indata_buffer = NULL; /* Malloced helper.  */
2492   unsigned char *apdudata = NULL;
2493   size_t apdudatalen;
2494 
2495   (void)ctrl;
2496 
2497   if (!keyidstr || !*keyidstr)
2498     {
2499       err = gpg_error (GPG_ERR_INV_VALUE);
2500       goto leave;
2501     }
2502 
2503   dobj = find_dobj_by_keyref (app, keyidstr);
2504   if ((keyref = keyref_from_dobj (dobj)) == -1)
2505     {
2506       err = gpg_error (GPG_ERR_INV_ID);
2507       goto leave;
2508     }
2509   if (keyref == 0x9A || keyref == 0x9C || keyref == 0x9E)
2510     {
2511       /* Signing only reference.  We only allow '9D' and the retired
2512        * cert key management DOs.  */
2513       err = gpg_error (GPG_ERR_INV_ID);
2514       goto leave;
2515     }
2516 
2517   err = get_key_algorithm_by_dobj (app, dobj, &mechanism);
2518   if (err)
2519     goto leave;
2520 
2521   switch (mechanism)
2522     {
2523     case PIV_ALGORITHM_ECC_P256:
2524       framelen = 1+32+32;
2525       break;
2526     case PIV_ALGORITHM_ECC_P384:
2527       framelen = 1+48+48;
2528       break;
2529     case PIV_ALGORITHM_RSA:
2530       framelen = 2048 / 8;
2531       break;
2532     default:
2533       err = gpg_error (GPG_ERR_INTERNAL);
2534       log_debug ("piv: unknown PIV mechanism %d while decrypting\n", mechanism);
2535       goto leave;
2536     }
2537 
2538   /* Check that the ciphertext has the right length; due to internal
2539    * convey mechanism using MPIs leading zero bytes might have been
2540    * lost.  Adjust for this.  Unfortunately the ciphertext might have
2541    * also been prefixed with a leading zero to make it a positive
2542    * number; that may be a too long frame and we need to adjust for
2543    * this too.  Note that for ECC those fixes are not reqquired
2544    * because the first octet is always '04' to indicate an
2545    * uncompressed point.  */
2546   if (indatalen > framelen)
2547     {
2548       if (mechanism == PIV_ALGORITHM_RSA
2549           && indatalen == framelen + 1 && !*indata)
2550         {
2551           indata_buffer = xtrycalloc (1, framelen);
2552           if (!indata_buffer)
2553             {
2554               err = gpg_error_from_syserror ();
2555               goto leave;
2556             }
2557           memcpy (indata_buffer, indata+1, framelen);
2558           indata = indata_buffer;
2559           indatalen = framelen;
2560         }
2561       else
2562         {
2563           err = gpg_error (GPG_ERR_INV_VALUE);
2564           log_error ("piv: input of %zu octets too large for mechanism %d\n",
2565                      indatalen, mechanism);
2566           goto leave;
2567         }
2568     }
2569   if (indatalen < framelen)
2570     {
2571       indata_buffer = xtrycalloc (1, framelen);
2572       if (!indata_buffer)
2573         {
2574           err = gpg_error_from_syserror ();
2575           goto leave;
2576         }
2577       memcpy (indata_buffer+(framelen-indatalen), indata, indatalen);
2578       indata = indata_buffer;
2579       indatalen = framelen;
2580     }
2581 
2582   /* Now verify the Application PIN.  */
2583   err = verify_chv (app, ctrl, 0x80, 0, pincb, pincb_arg);
2584   if (err)
2585     return err;
2586 
2587   /* Build the Dynamic Authentication Template.  */
2588   err = concat_tlv_list (0, &apdudata, &apdudatalen,
2589                          (int)0x7c, (size_t)0, NULL, /* Constructed. */
2590                          (int)0x82, (size_t)0, "",
2591                          mechanism == PIV_ALGORITHM_RSA?
2592                          (int)0x81 : (int)0x85, (size_t)indatalen, indata,
2593                          (int)0, (size_t)0, NULL);
2594   if (err)
2595     goto leave;
2596 
2597   /* Note: the -1 requests command chaining.  */
2598   err = iso7816_general_authenticate (app_get_slot (app), -1,
2599                                       mechanism, keyref,
2600                                       apdudata, (int)apdudatalen, 0,
2601                                       &outdata, &outdatalen);
2602   if (err)
2603     goto leave;
2604 
2605   /* Parse the response.  */
2606   if (outdatalen && *outdata == 0x7c
2607       && (s = find_tlv (outdata, outdatalen, 0x82, &n)))
2608     {
2609       memmove (outdata, outdata + (s - outdata), n);
2610       outdatalen = n;
2611     }
2612   else
2613     {
2614       err = gpg_error (GPG_ERR_CARD);
2615       log_error ("piv: response does not contain a proper result\n");
2616       goto leave;
2617     }
2618 
2619  leave:
2620   if (err)
2621     {
2622       xfree (outdata);
2623       *r_outdata = NULL;
2624       *r_outdatalen = 0;
2625     }
2626   else
2627     {
2628       *r_outdata = outdata;
2629       *r_outdatalen = outdatalen;
2630     }
2631   *r_info = 0;
2632   xfree (apdudata);
2633   xfree (indata_buffer);
2634   return err;
2635 }
2636 
2637 
2638 /* Check whether a key for DOBJ already exists.  We detect this by
2639  * reading the certificate described by DOBJ.  If FORCE is TRUE a
2640  * diagnositic will be printed but no error returned if the key
2641  * already exists.  The flag GENERATING is used to select a
2642  * diagnositic. */
2643 static gpg_error_t
does_key_exist(app_t app,data_object_t dobj,int generating,int force)2644 does_key_exist (app_t app, data_object_t dobj, int generating, int force)
2645 {
2646   void *relptr;
2647   unsigned char *buffer;
2648   size_t buflen;
2649   int found;
2650 
2651   relptr = get_one_do (app, dobj->tag, &buffer, &buflen, NULL);
2652   found = (relptr && buflen);
2653   xfree (relptr);
2654 
2655   if (found && !force)
2656     {
2657       log_error (_("key already exists\n"));
2658       return gpg_error (GPG_ERR_EEXIST);
2659     }
2660 
2661   if (found)
2662     log_info (_("existing key will be replaced\n"));
2663   else if (generating)
2664     log_info (_("generating new key\n"));
2665   else
2666     log_info (_("writing new key\n"));
2667   return 0;
2668 }
2669 
2670 
2671 /* Helper for do_writekey; here the RSA part.  BUF, BUFLEN, and DEPTH
2672  * are the current parser state of the S-expression with the key. */
2673 static gpg_error_t
writekey_rsa(app_t app,data_object_t dobj,int keyref,const unsigned char * buf,size_t buflen,int depth)2674 writekey_rsa (app_t app, data_object_t dobj, int keyref,
2675               const unsigned char *buf, size_t buflen, int depth)
2676 {
2677   gpg_error_t err;
2678   const unsigned char *tok;
2679   size_t toklen;
2680   int last_depth1, last_depth2;
2681   const unsigned char *rsa_n = NULL;
2682   const unsigned char *rsa_e = NULL;
2683   const unsigned char *rsa_p = NULL;
2684   const unsigned char *rsa_q = NULL;
2685   unsigned char *rsa_dpm1 = NULL;
2686   unsigned char *rsa_dqm1 = NULL;
2687   unsigned char *rsa_qinv = NULL;
2688   size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2689   size_t rsa_dpm1_len, rsa_dqm1_len, rsa_qinv_len;
2690   unsigned char *apdudata = NULL;
2691   size_t apdudatalen;
2692   unsigned char tmpl[1];
2693 
2694   last_depth1 = depth;
2695   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2696          && depth && depth >= last_depth1)
2697     {
2698       if (tok)
2699         {
2700           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2701           goto leave;
2702         }
2703       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2704         goto leave;
2705 
2706       if (tok && toklen == 1)
2707         {
2708           const unsigned char **mpi;
2709           size_t *mpi_len;
2710 
2711           switch (*tok)
2712             {
2713             case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2714             case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2715             case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2716             case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len; break;
2717             default: mpi = NULL;  mpi_len = NULL; break;
2718             }
2719           if (mpi && *mpi)
2720             {
2721               err = gpg_error (GPG_ERR_DUP_VALUE);
2722               goto leave;
2723             }
2724 
2725           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2726             goto leave;
2727           if (tok && mpi)
2728             {
2729               /* Strip off leading zero bytes and save. */
2730               for (;toklen && !*tok; toklen--, tok++)
2731                 ;
2732               *mpi = tok;
2733               *mpi_len = toklen;
2734             }
2735         }
2736       /* Skip until end of list. */
2737       last_depth2 = depth;
2738       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2739              && depth && depth >= last_depth2)
2740         ;
2741       if (err)
2742         goto leave;
2743     }
2744 
2745   /* Check that we have all parameters.  */
2746   if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
2747     {
2748       err = gpg_error (GPG_ERR_BAD_SECKEY);
2749       goto leave;
2750     }
2751   /* Fixme: Shall we check whether  n == pq ? */
2752 
2753   if (opt.verbose)
2754     log_info ("RSA private key size is %u bytes\n", (unsigned int)rsa_n_len);
2755 
2756   /* Compute the dp, dq and u components.  */
2757   {
2758     gcry_mpi_t mpi_e, mpi_p, mpi_q;
2759     gcry_mpi_t mpi_dpm1 = gcry_mpi_snew (0);
2760     gcry_mpi_t mpi_dqm1 = gcry_mpi_snew (0);
2761     gcry_mpi_t mpi_qinv = gcry_mpi_snew (0);
2762     gcry_mpi_t mpi_tmp  = gcry_mpi_snew (0);
2763 
2764     gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
2765     gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
2766     gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
2767 
2768     gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
2769     gcry_mpi_invm (mpi_dpm1, mpi_e, mpi_tmp);
2770 
2771     gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
2772     gcry_mpi_invm (mpi_dqm1, mpi_e, mpi_tmp);
2773 
2774     gcry_mpi_invm (mpi_qinv, mpi_q, mpi_p);
2775 
2776     gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dpm1, &rsa_dpm1_len, mpi_dpm1);
2777     gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dqm1, &rsa_dqm1_len, mpi_dqm1);
2778     gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_qinv, &rsa_qinv_len, mpi_qinv);
2779 
2780     gcry_mpi_release (mpi_e);
2781     gcry_mpi_release (mpi_p);
2782     gcry_mpi_release (mpi_q);
2783     gcry_mpi_release (mpi_dpm1);
2784     gcry_mpi_release (mpi_dqm1);
2785     gcry_mpi_release (mpi_qinv);
2786     gcry_mpi_release (mpi_tmp);
2787   }
2788 
2789   err = concat_tlv_list (1, &apdudata, &apdudatalen,
2790                          (int)0x01, (size_t)rsa_p_len, rsa_p,
2791                          (int)0x02, (size_t)rsa_q_len, rsa_q,
2792                          (int)0x03, (size_t)rsa_dpm1_len, rsa_dpm1,
2793                          (int)0x04, (size_t)rsa_dqm1_len, rsa_dqm1,
2794                          (int)0x05, (size_t)rsa_qinv_len, rsa_qinv,
2795                          (int)0, (size_t)0, NULL);
2796   if (err)
2797     goto leave;
2798 
2799   err = iso7816_send_apdu (app_get_slot (app),
2800                            -1,         /* Use command chaining.  */
2801                            0,          /* Class */
2802                            0xfe,       /* Ins: Yubikey Import Asym. Key.  */
2803                            PIV_ALGORITHM_RSA, /* P1 */
2804                            keyref,     /* P2 */
2805                            apdudatalen,/* Lc */
2806                            apdudata,   /* data */
2807                            NULL, NULL, NULL);
2808   if (err)
2809     goto leave;
2810 
2811   /* Write the public key to the cert object.  */
2812   xfree (apdudata);
2813   err = concat_tlv_list (0, &apdudata, &apdudatalen,
2814                          (int)0x81, (size_t)rsa_n_len, rsa_n,
2815                          (int)0x82, (size_t)rsa_e_len, rsa_e,
2816                          (int)0, (size_t)0, NULL);
2817 
2818   if (err)
2819     goto leave;
2820   tmpl[0] = PIV_ALGORITHM_RSA;
2821   err = put_data (app_get_slot (app), dobj->tag,
2822                   (int)0x80,   (size_t)1, tmpl,
2823                   (int)0x7f49, (size_t)apdudatalen, apdudata,
2824                   (int)0,      (size_t)0, NULL);
2825 
2826  leave:
2827   xfree (rsa_dpm1);
2828   xfree (rsa_dqm1);
2829   xfree (rsa_qinv);
2830   xfree (apdudata);
2831   return err;
2832 }
2833 
2834 
2835 /* Helper for do_writekey; here the ECC part.  BUF, BUFLEN, and DEPTH
2836  * are the current parser state of the S-expression with the key. */
2837 static gpg_error_t
writekey_ecc(app_t app,data_object_t dobj,int keyref,const unsigned char * buf,size_t buflen,int depth)2838 writekey_ecc (app_t app, data_object_t dobj, int keyref,
2839               const unsigned char *buf, size_t buflen, int depth)
2840 {
2841   gpg_error_t err;
2842   const unsigned char *tok;
2843   size_t toklen;
2844   int last_depth1, last_depth2;
2845   int mechanism = 0;
2846   const unsigned char *ecc_q = NULL;
2847   const unsigned char *ecc_d = NULL;
2848   size_t ecc_q_len, ecc_d_len;
2849   unsigned char *apdudata = NULL;
2850   size_t apdudatalen;
2851   unsigned char tmpl[1];
2852 
2853   last_depth1 = depth;
2854   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2855          && depth && depth >= last_depth1)
2856     {
2857       if (tok)
2858         {
2859           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2860           goto leave;
2861         }
2862       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2863         goto leave;
2864 
2865       if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
2866         {
2867           char *name;
2868           const char *xname;
2869 
2870           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2871             goto leave;
2872 
2873           name = xtrymalloc (toklen+1);
2874           if (!name)
2875             {
2876               err = gpg_error_from_syserror ();
2877               goto leave;
2878             }
2879           memcpy (name, tok, toklen);
2880           name[toklen] = 0;
2881           /* Canonicalize the curve name.  We use the openpgp
2882            * functions here because Libgcrypt has no generic curve
2883            * alias lookup feature and the PIV supported curves are
2884            * also supported by OpenPGP.  */
2885           xname = openpgp_oid_to_curve (openpgp_curve_to_oid (name, NULL, NULL),
2886                                         0);
2887           xfree (name);
2888 
2889           if (xname && !strcmp (xname, "nistp256"))
2890             mechanism = PIV_ALGORITHM_ECC_P256;
2891           else if (xname && !strcmp (xname, "nistp384"))
2892             mechanism = PIV_ALGORITHM_ECC_P384;
2893           else
2894             {
2895               err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2896               goto leave;
2897             }
2898         }
2899       else if (tok && toklen == 1)
2900         {
2901           const unsigned char **mpi;
2902           size_t *mpi_len;
2903 
2904           switch (*tok)
2905             {
2906             case 'q': mpi = &ecc_q; mpi_len = &ecc_q_len; break;
2907             case 'd': mpi = &ecc_d; mpi_len = &ecc_d_len; break;
2908             default:  mpi = NULL;  mpi_len = NULL; break;
2909             }
2910           if (mpi && *mpi)
2911             {
2912               err = gpg_error (GPG_ERR_DUP_VALUE);
2913               goto leave;
2914             }
2915 
2916           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2917             goto leave;
2918           if (tok && mpi)
2919             {
2920               /* Strip off leading zero bytes and save. */
2921               for (;toklen && !*tok; toklen--, tok++)
2922                 ;
2923               *mpi = tok;
2924               *mpi_len = toklen;
2925             }
2926         }
2927       /* Skip until end of list. */
2928       last_depth2 = depth;
2929       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2930              && depth && depth >= last_depth2)
2931         ;
2932       if (err)
2933         goto leave;
2934     }
2935 
2936   /* Check that we have all parameters.  */
2937   if (!mechanism || !ecc_q || !ecc_d)
2938     {
2939       err = gpg_error (GPG_ERR_BAD_SECKEY);
2940       goto leave;
2941     }
2942 
2943   if (opt.verbose)
2944     log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
2945 
2946   err = concat_tlv_list (1, &apdudata, &apdudatalen,
2947                          (int)0x06, (size_t)ecc_d_len, ecc_d,
2948                          (int)0, (size_t)0, NULL);
2949   if (err)
2950     goto leave;
2951 
2952   err = iso7816_send_apdu (app_get_slot (app),
2953                            -1,         /* Use command chaining.  */
2954                            0,          /* Class */
2955                            0xfe,       /* Ins: Yubikey Import Asym. Key.  */
2956                            mechanism,  /* P1 */
2957                            keyref,     /* P2 */
2958                            apdudatalen,/* Lc */
2959                            apdudata,   /* data */
2960                            NULL, NULL, NULL);
2961   if (err)
2962     goto leave;
2963 
2964   /* Write the public key to the cert object.  */
2965   xfree (apdudata);
2966   err = concat_tlv_list (0, &apdudata, &apdudatalen,
2967                          (int)0x86, (size_t)ecc_q_len, ecc_q,
2968                          (int)0, (size_t)0, NULL);
2969 
2970   if (err)
2971     goto leave;
2972   tmpl[0] = mechanism;
2973   err = put_data (app_get_slot (app), dobj->tag,
2974                   (int)0x80,   (size_t)1, tmpl,
2975                   (int)0x7f49, (size_t)apdudatalen, apdudata,
2976                   (int)0,      (size_t)0, NULL);
2977 
2978 
2979  leave:
2980   xfree (apdudata);
2981   return err;
2982 }
2983 
2984 
2985 /* Write a key to a slot.  This command requires proprietary
2986  * extensions of the PIV specification and is thus only implemnted for
2987  * supported card types.  The input is a canonical encoded
2988  * S-expression with the secret key in KEYDATA and its length (for
2989  * assertion) in KEYDATALEN.  KEYREFSTR needs to be the usual 2
2990  * hexdigit slot number prefixed with "PIV."  PINCB and PINCB_ARG are
2991  * not used for PIV cards.
2992  *
2993  * Supported FLAGS are:
2994  *   APP_WRITEKEY_FLAG_FORCE   Overwrite existing key.
2995  */
2996 static gpg_error_t
do_writekey(app_t app,ctrl_t ctrl,const char * keyrefstr,unsigned int flags,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * keydata,size_t keydatalen)2997 do_writekey (app_t app, ctrl_t ctrl,
2998              const char *keyrefstr, unsigned int flags,
2999              gpg_error_t (*pincb)(void*, const char *, char **),
3000              void *pincb_arg,
3001              const unsigned char *keydata, size_t keydatalen)
3002 {
3003   gpg_error_t err;
3004   int force = !!(flags & APP_WRITEKEY_FLAG_FORCE);
3005   data_object_t dobj;
3006   int keyref;
3007   const unsigned char *buf, *tok;
3008   size_t buflen, toklen;
3009   int depth;
3010 
3011   (void)ctrl;
3012   (void)pincb;
3013   (void)pincb_arg;
3014 
3015   if (!app->app_local->flags.yubikey)
3016     {
3017       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3018       goto leave;
3019     }
3020 
3021   /* Check keyref and test whether a key already exists.  */
3022   dobj = find_dobj_by_keyref (app, keyrefstr);
3023   if ((keyref = keyref_from_dobj (dobj)) == -1)
3024     {
3025       err = gpg_error (GPG_ERR_INV_ID);
3026       goto leave;
3027     }
3028   err = does_key_exist (app, dobj, 0, force);
3029   if (err)
3030     goto leave;
3031 
3032   /* Parse the S-expression with the key. */
3033   buf = keydata;
3034   buflen = keydatalen;
3035   depth = 0;
3036   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3037     goto leave;
3038   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3039     goto leave;
3040   if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
3041     {
3042       if (!tok)
3043         ;
3044       else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
3045         log_info ("protected-private-key passed to writekey\n");
3046       else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
3047         log_info ("shadowed-private-key passed to writekey\n");
3048       err = gpg_error (GPG_ERR_BAD_SECKEY);
3049       goto leave;
3050     }
3051   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3052     goto leave;
3053   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
3054     goto leave;
3055 
3056   /* First clear an existing key.  We do this by writing an empty 7f49
3057    * tag.  This will return GPG_ERR_NO_PUBKEY on a later read.  */
3058   flush_cached_data (app, dobj->tag);
3059   err = put_data (app_get_slot (app), dobj->tag,
3060                   (int)0x7f49, (size_t)0, "",
3061                   (int)0,      (size_t)0, NULL);
3062   if (err)
3063     {
3064       log_error ("piv: failed to clear the cert DO %s: %s\n",
3065                  dobj->keyref, gpg_strerror (err));
3066       goto leave;
3067     }
3068 
3069   /* Divert to the algo specific implementation.  */
3070   if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
3071     err = writekey_rsa (app, dobj, keyref, buf, buflen, depth);
3072   else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
3073     err = writekey_ecc (app, dobj, keyref, buf, buflen, depth);
3074   else
3075     err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
3076 
3077   if (err)
3078     {
3079       /* A PIN is not required, thus use a better error code.  */
3080       if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
3081         err = gpg_error (GPG_ERR_NO_AUTH);
3082       log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
3083     }
3084 
3085  leave:
3086   return err;
3087 }
3088 
3089 
3090 /* Parse an RSA response object, consisting of the content of tag
3091  * 0x7f49, into a gcrypt s-expression object and store that R_SEXP.
3092  * On error NULL is stored at R_SEXP. */
3093 static gpg_error_t
genkey_parse_rsa(const unsigned char * data,size_t datalen,gcry_sexp_t * r_sexp)3094 genkey_parse_rsa (const unsigned char *data, size_t datalen,
3095                   gcry_sexp_t *r_sexp)
3096 {
3097   gpg_error_t err;
3098   const unsigned char *m, *e;
3099   unsigned char *mbuf = NULL;
3100   unsigned char *ebuf = NULL;
3101   size_t mlen, elen;
3102 
3103   *r_sexp = NULL;
3104 
3105   m = find_tlv (data, datalen, 0x0081, &mlen);
3106   if (!m)
3107     {
3108       log_error (_("response does not contain the RSA modulus\n"));
3109       err = gpg_error (GPG_ERR_CARD);
3110       goto leave;
3111     }
3112 
3113   e = find_tlv (data, datalen, 0x0082, &elen);
3114   if (!e)
3115     {
3116       log_error (_("response does not contain the RSA public exponent\n"));
3117       err = gpg_error (GPG_ERR_CARD);
3118       goto leave;
3119     }
3120 
3121   for (; mlen && !*m; mlen--, m++) /* Strip leading zeroes */
3122     ;
3123   for (; elen && !*e; elen--, e++) /* Strip leading zeroes */
3124     ;
3125 
3126   mbuf = xtrymalloc (mlen + 1);
3127   if (!mbuf)
3128     {
3129       err = gpg_error_from_syserror ();
3130       goto leave;
3131     }
3132   /* Prepend numbers with a 0 if needed.  */
3133   if (mlen && (*m & 0x80))
3134     {
3135       *mbuf = 0;
3136       memcpy (mbuf+1, m, mlen);
3137       mlen++;
3138     }
3139   else
3140     memcpy (mbuf, m, mlen);
3141 
3142   ebuf = xtrymalloc (elen + 1);
3143   if (!ebuf)
3144     {
3145       err = gpg_error_from_syserror ();
3146       goto leave;
3147     }
3148   /* Prepend numbers with a 0 if needed.  */
3149   if (elen && (*e & 0x80))
3150     {
3151       *ebuf = 0;
3152       memcpy (ebuf+1, e, elen);
3153       elen++;
3154     }
3155   else
3156     memcpy (ebuf, e, elen);
3157 
3158   err = gcry_sexp_build (r_sexp, NULL, "(public-key(rsa(n%b)(e%b)))",
3159                          (int)mlen, mbuf, (int)elen, ebuf);
3160 
3161  leave:
3162   xfree (mbuf);
3163   xfree (ebuf);
3164   return err;
3165 }
3166 
3167 
3168 /* Parse an ECC response object, consisting of the content of tag
3169  * 0x7f49, into a gcrypt s-expression object and store that R_SEXP.
3170  * On error NULL is stored at R_SEXP.  MECHANISM specifies the
3171  * curve.  */
3172 static gpg_error_t
genkey_parse_ecc(const unsigned char * data,size_t datalen,int mechanism,gcry_sexp_t * r_sexp)3173 genkey_parse_ecc (const unsigned char *data, size_t datalen, int mechanism,
3174                   gcry_sexp_t *r_sexp)
3175 {
3176   gpg_error_t err;
3177   const unsigned char *ecc_q;
3178   size_t ecc_qlen;
3179   const char *curve;
3180 
3181   *r_sexp = NULL;
3182 
3183   ecc_q = find_tlv (data, datalen, 0x0086, &ecc_qlen);
3184   if (!ecc_q)
3185     {
3186       log_error (_("response does not contain the EC public key\n"));
3187       err = gpg_error (GPG_ERR_CARD);
3188       goto leave;
3189     }
3190 
3191   if (mechanism == PIV_ALGORITHM_ECC_P256)
3192     curve = "nistp256";
3193   else if (mechanism == PIV_ALGORITHM_ECC_P384)
3194     curve = "nistp384";
3195   else
3196     {
3197       err = gpg_error (GPG_ERR_BUG); /* Call with wrong parameters.  */
3198       goto leave;
3199     }
3200 
3201 
3202   err = gcry_sexp_build (r_sexp, NULL, "(public-key(ecc(curve%s)(q%b)))",
3203                          curve, (int)ecc_qlen, ecc_q);
3204 
3205  leave:
3206   return err;
3207 }
3208 
3209 
3210 /* Create a new keypair for KEYREF.  If KEYTYPE is NULL a default
3211  * keytype is selected, else it may be one of the strings:
3212  *  "rsa2048", "nistp256, or "nistp384".
3213  *
3214  * Supported FLAGS are:
3215  *   APP_GENKEY_FLAG_FORCE   Overwrite existing key.
3216  *
3217  * Note that CREATETIME is not used for PIV cards.
3218  *
3219  * Because there seems to be no way to read the public key we need to
3220  * retrieve it from a certificate.  The GnuPG system however requires
3221  * the use of app_readkey to fetch the public key from the card to
3222  * create the certificate; to support this we temporary store the
3223  * generated public key in the local context for use by app_readkey.
3224  */
3225 static gpg_error_t
do_genkey(app_t app,ctrl_t ctrl,const char * keyrefstr,const char * keytype,unsigned int flags,time_t createtime,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)3226 do_genkey (app_t app, ctrl_t ctrl, const char *keyrefstr, const char *keytype,
3227            unsigned int flags, time_t createtime,
3228            gpg_error_t (*pincb)(void*, const char *, char **),
3229            void *pincb_arg)
3230 {
3231   gpg_error_t err;
3232   data_object_t dobj;
3233   unsigned char *buffer = NULL;
3234   size_t buflen;
3235   int force = !!(flags & APP_GENKEY_FLAG_FORCE);
3236   int mechanism;
3237   time_t start_at;
3238   int keyref;
3239   unsigned char tmpl[5];
3240   size_t tmpllen;
3241   const unsigned char *keydata;
3242   size_t keydatalen;
3243 
3244   (void)ctrl;
3245   (void)createtime;
3246   (void)pincb;
3247   (void)pincb_arg;
3248 
3249   if (!keytype)
3250     keytype = "rsa2048";
3251 
3252   if (!strcmp (keytype, "rsa2048"))
3253     mechanism = PIV_ALGORITHM_RSA;
3254   else if (!strcmp (keytype, "nistp256"))
3255     mechanism = PIV_ALGORITHM_ECC_P256;
3256   else if (!strcmp (keytype, "nistp384"))
3257     mechanism = PIV_ALGORITHM_ECC_P384;
3258   else
3259     return gpg_error (GPG_ERR_UNKNOWN_CURVE);
3260 
3261   /* We flush the cache to increase the I/O traffic before a key
3262    * generation.  This _might_ help the card to gather more entropy
3263    * and is anyway a prerequisite for does_key_exist. */
3264   flush_cached_data (app, 0);
3265 
3266   /* Check whether a key already exists.  */
3267   dobj = find_dobj_by_keyref (app, keyrefstr);
3268   if ((keyref = keyref_from_dobj (dobj)) == -1)
3269     {
3270       err = gpg_error (GPG_ERR_INV_ID);
3271       goto leave;
3272     }
3273   err = does_key_exist (app, dobj, 1, force);
3274   if (err)
3275     goto leave;
3276 
3277 
3278   /* Create the key. */
3279   log_info (_("please wait while key is being generated ...\n"));
3280   start_at = time (NULL);
3281   tmpl[0] = 0xac;
3282   tmpl[1] = 3;
3283   tmpl[2] = 0x80;
3284   tmpl[3] = 1;
3285   tmpl[4] = mechanism;
3286   tmpllen = 5;
3287   err = iso7816_generate_keypair (app_get_slot (app), 0, 0, keyref,
3288                                   tmpl, tmpllen, 0, &buffer, &buflen);
3289   if (err)
3290     {
3291       /* A PIN is not required, thus use a better error code.  */
3292       if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
3293         err = gpg_error (GPG_ERR_NO_AUTH);
3294       log_error (_("generating key failed\n"));
3295       return err;
3296     }
3297 
3298   {
3299     int nsecs = (int)(time (NULL) - start_at);
3300     log_info (ngettext("key generation completed (%d second)\n",
3301                        "key generation completed (%d seconds)\n",
3302                        nsecs), nsecs);
3303   }
3304 
3305   /* Parse the result and store it as an s-expression in a dedicated
3306    * cache for later retrieval by app_readkey.  */
3307   keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
3308   if (!keydata || !keydatalen)
3309     {
3310       err = gpg_error (GPG_ERR_CARD);
3311       log_error (_("response does not contain the public key data\n"));
3312       goto leave;
3313     }
3314 
3315   tmpl[0] = mechanism;
3316   flush_cached_data (app, dobj->tag);
3317   err = put_data (app_get_slot (app), dobj->tag,
3318                   (int)0x80,   (size_t)1,          tmpl,
3319                   (int)0x7f49, (size_t)keydatalen, keydata,
3320                   (int)0,      (size_t)0,          NULL);
3321   if (err)
3322     {
3323       log_error ("piv: failed to write key to the cert DO %s: %s\n",
3324                  dobj->keyref, gpg_strerror (err));
3325       goto leave;
3326     }
3327 
3328  leave:
3329   xfree (buffer);
3330   return err;
3331 }
3332 
3333 
3334 
3335 /* Map some names to an OID.  */
3336 static const unsigned char *
map_curve_name_to_oid(const unsigned char * name,size_t * namelenp)3337 map_curve_name_to_oid (const unsigned char *name, size_t *namelenp)
3338 {
3339   if (*namelenp == 8 && !memcmp (name, "nistp256", 8))
3340     {
3341       *namelenp = 19;
3342       return "1.2.840.10045.3.1.7";
3343     }
3344   if (*namelenp == 8 && !memcmp (name, "nistp384", 8))
3345     {
3346       *namelenp = 12;
3347       return "1.3.132.0.34";
3348     }
3349   if (*namelenp == 8 && !memcmp (name, "nistp521", 8))
3350     {
3351       *namelenp = 12;
3352       return "1.3.132.0.35";
3353     }
3354   return name;
3355 }
3356 
3357 
3358 /* Communication object for my_cmp_public_key. */
3359 struct my_cmp_public_key_parm_s {
3360   int curve_seen;
3361 };
3362 
3363 /* Compare function used with cmp_canon_sexp.  */
3364 static int
my_cmp_public_key(void * opaque,int depth,const unsigned char * aval,size_t alen,const unsigned char * bval,size_t blen)3365 my_cmp_public_key (void *opaque, int depth,
3366                    const unsigned char *aval, size_t alen,
3367                    const unsigned char *bval, size_t blen)
3368 {
3369   struct my_cmp_public_key_parm_s *parm = opaque;
3370 
3371   (void)depth;
3372 
3373   if (parm->curve_seen)
3374     {
3375       /* Last token was "curve" - canonicalize its argument.  */
3376       parm->curve_seen = 0;
3377       aval = map_curve_name_to_oid (aval, &alen);
3378       bval = map_curve_name_to_oid (bval, &blen);
3379     }
3380   else if (alen == 5 && !memcmp (aval, "curve", 5))
3381     parm->curve_seen = 1;
3382   else
3383     parm->curve_seen = 0;
3384 
3385   if (alen > blen)
3386     return 1;
3387   else if (alen < blen)
3388     return -1;
3389   else
3390     return memcmp (aval, bval, alen);
3391 }
3392 
3393 
3394 /* Write the certificate (CERT,CERTLEN) to the card at CERTREFSTR.
3395  * CERTREFSTR is either the OID of the certificate's container data
3396  * object or of the form "PIV.<two_hexdigit_keyref>". */
3397 static gpg_error_t
do_writecert(app_t app,ctrl_t ctrl,const char * certrefstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * cert,size_t certlen)3398 do_writecert (app_t app, ctrl_t ctrl,
3399               const char *certrefstr,
3400               gpg_error_t (*pincb)(void*, const char *, char **),
3401               void *pincb_arg,
3402               const unsigned char *cert, size_t certlen)
3403 {
3404   gpg_error_t err;
3405   data_object_t dobj;
3406   unsigned char *pk = NULL;
3407   unsigned char *orig_pk = NULL;
3408   size_t pklen, orig_pklen;
3409   struct my_cmp_public_key_parm_s cmp_parm = { 0 };
3410 
3411   (void)ctrl;
3412   (void)pincb;     /* Not used; instead authentication is needed.  */
3413   (void)pincb_arg;
3414 
3415   if (!certlen)
3416     return gpg_error (GPG_ERR_INV_CERT_OBJ);
3417 
3418   dobj = find_dobj_by_keyref (app, certrefstr);
3419   if (!dobj || !*dobj->keyref)
3420     return gpg_error (GPG_ERR_INV_ID);
3421 
3422   flush_cached_data (app, dobj->tag);
3423 
3424   /* Check that the public key parameters from the certificate match
3425    * an already stored key.  Note that we do not allow writing a
3426    * certificate if no key has yet been created (GPG_ERR_NOT_FOUND) or
3427    * if there is a problem reading the public key from the certificate
3428    * GPG_ERR_NO_PUBKEY).  We enforce this because otherwise the only
3429    * way to detect whether a key exists is by trying to use that
3430    * key. */
3431   err = do_readkey (app, ctrl, certrefstr, 0, &orig_pk, &orig_pklen);
3432   if (err)
3433     {
3434       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3435         err = gpg_error (GPG_ERR_NO_SECKEY); /* Use a better error code.  */
3436       goto leave;
3437     }
3438 
3439   /* Compare pubkeys.  */
3440   err = app_help_pubkey_from_cert (cert, certlen, &pk, &pklen);
3441   if (err)
3442     goto leave;  /* No public key in new certificate. */
3443   if (cmp_canon_sexp (orig_pk, orig_pklen, pk, pklen,
3444                       my_cmp_public_key, &cmp_parm))
3445     {
3446       err = gpg_error (GPG_ERR_CONFLICT);
3447       goto leave;
3448     }
3449 
3450   flush_cached_data (app, dobj->tag);
3451   err = put_data (app_get_slot (app), dobj->tag,
3452                   (int)0x70, (size_t)certlen, cert,/* Certificate */
3453                   (int)0x71, (size_t)1,       "",  /* No compress */
3454                   (int)0xfe, (size_t)0,       "",  /* Empty LRC. */
3455                   (int)0,    (size_t)0,       NULL);
3456   /* A PIN is not required, thus use a better error code.  */
3457   if (gpg_err_code (err) == GPG_ERR_BAD_PIN)
3458     err = gpg_error (GPG_ERR_NO_AUTH);
3459   if (err)
3460     log_error ("piv: failed to write cert to %s: %s\n",
3461                dobj->keyref, gpg_strerror (err));
3462 
3463  leave:
3464   xfree (pk);
3465   xfree (orig_pk);
3466   return err;
3467 }
3468 
3469 
3470 /* Process the various keygrip based info requests.  */
3471 static gpg_error_t
do_with_keygrip(app_t app,ctrl_t ctrl,int action,const char * want_keygripstr,int capability)3472 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
3473                  const char *want_keygripstr, int capability)
3474 {
3475   gpg_error_t err;
3476   char *keygripstr = NULL;
3477   char *serialno = NULL;
3478   char idbuf[20];
3479   int data = 0;
3480   int i, tag, dummy_got_cert;
3481 
3482   /* First a quick check for valid parameters.  */
3483   switch (action)
3484     {
3485     case KEYGRIP_ACTION_LOOKUP:
3486       if (!want_keygripstr)
3487         {
3488           err = gpg_error (GPG_ERR_NOT_FOUND);
3489           goto leave;
3490         }
3491       break;
3492     case KEYGRIP_ACTION_SEND_DATA:
3493       data = 1;
3494       break;
3495     case KEYGRIP_ACTION_WRITE_STATUS:
3496       break;
3497     default:
3498       err = gpg_error (GPG_ERR_INV_ARG);
3499       goto leave;
3500     }
3501 
3502   /* Allocate the s/n string if needed.  */
3503   if (action != KEYGRIP_ACTION_LOOKUP)
3504     {
3505       serialno = app_get_serialno (app);
3506       if (!serialno)
3507         {
3508           err = gpg_error_from_syserror ();
3509           goto leave;
3510         }
3511     }
3512 
3513   for (i = 0; (tag = data_objects[i].tag); i++)
3514     {
3515       if (!data_objects[i].keypair)
3516         continue;
3517 
3518       xfree (keygripstr);
3519       if (get_keygrip_by_tag (app, tag, &keygripstr, &dummy_got_cert))
3520         continue;
3521 
3522       if (action == KEYGRIP_ACTION_LOOKUP)
3523         {
3524           if (!strcmp (keygripstr, want_keygripstr))
3525             {
3526               err = 0; /* Found */
3527               goto leave;
3528             }
3529         }
3530       else if (!want_keygripstr || !strcmp (keygripstr, want_keygripstr))
3531         {
3532           if (capability == GCRY_PK_USAGE_SIGN)
3533             {
3534               if (strcmp (data_objects[i].keyref, "9C"))
3535                 continue;
3536             }
3537           if (capability == GCRY_PK_USAGE_ENCR)
3538             {
3539               if (strcmp (data_objects[i].keyref, "9D"))
3540                 continue;
3541             }
3542           if (capability == GCRY_PK_USAGE_AUTH)
3543             {
3544               if (strcmp (data_objects[i].keyref, "9A"))
3545                 continue;
3546             }
3547 
3548           snprintf (idbuf, sizeof idbuf, "PIV.%s", data_objects[i].keyref);
3549           send_keyinfo (ctrl, data, keygripstr, serialno, idbuf);
3550           if (want_keygripstr)
3551             {
3552               err = 0; /* Found */
3553               goto leave;
3554             }
3555         }
3556     }
3557 
3558   /* Return an error so that the dispatcher keeps on looping over the
3559    * other applications.  For clarity we use a different error code
3560    * when listing all keys.  Note that in lookup mode WANT_KEYGRIPSTR
3561    * is not NULL.  */
3562   if (!want_keygripstr)
3563     err = gpg_error (GPG_ERR_TRUE);
3564   else
3565     err = gpg_error (GPG_ERR_NOT_FOUND);
3566 
3567  leave:
3568   xfree (keygripstr);
3569   xfree (serialno);
3570   return err;
3571 }
3572 
3573 
3574 /* Prepare a reselect of another application.  This is used by cards
3575  * which support on-the-fly switching between applications.  The
3576  * function is called to give us a chance to save state for a future
3577  * reselect of us again.  */
3578 static gpg_error_t
do_prep_reselect(app_t app,ctrl_t ctrl)3579 do_prep_reselect (app_t app, ctrl_t ctrl)
3580 {
3581   gpg_error_t err;
3582 
3583   (void)app;
3584   (void)ctrl;
3585 
3586   err = 0;
3587   return err;
3588 }
3589 
3590 
3591 /* Reselect the application.  This is used by cards which support
3592  * on-the-fly switching between applications.  */
3593 static gpg_error_t
do_reselect(app_t app,ctrl_t ctrl)3594 do_reselect (app_t app, ctrl_t ctrl)
3595 {
3596   gpg_error_t err;
3597 
3598   (void)ctrl;
3599 
3600   /* An extra check which should not be necessary because the caller
3601    * should have made sure that a re-select is only called for
3602    * appropriate cards.  */
3603   if (!app->app_local->flags.yubikey)
3604     return gpg_error (GPG_ERR_NOT_SUPPORTED);
3605 
3606   err = iso7816_select_application (app_get_slot (app),
3607                                     piv_aid, sizeof piv_aid, 0x0001);
3608   return err;
3609 }
3610 
3611 
3612 /* Check if AID is the correct one.  */
3613 static gpg_error_t
do_check_aid(app_t app,ctrl_t ctrl,const unsigned char * aid,size_t aidlen)3614 do_check_aid (app_t app, ctrl_t ctrl, const unsigned char *aid, size_t aidlen)
3615 {
3616   (void)app;
3617   (void)ctrl;
3618 
3619   if (aidlen >= sizeof piv_aid
3620       && memcmp (aid, piv_aid, sizeof piv_aid) == 0)
3621     return 0;
3622 
3623   return gpg_error (GPG_ERR_WRONG_CARD);
3624 }
3625 
3626 
3627 /* Select the PIV application on the card in SLOT.  This function must
3628  * be used before any other PIV application functions. */
3629 gpg_error_t
app_select_piv(app_t app)3630 app_select_piv (app_t app)
3631 {
3632   int slot = app_get_slot (app);
3633   gpg_error_t err;
3634   unsigned char *apt = NULL;
3635   size_t aptlen;
3636   const unsigned char *s;
3637   size_t n;
3638 
3639   /* Note that we select using the AID without the 2 octet version
3640    * number.  This allows for better reporting of future specs.  We
3641    * need to use the use-zero-for-P2-flag.  */
3642   err = iso7816_select_application_ext (slot, piv_aid, sizeof piv_aid, 0x0001,
3643                                         &apt, &aptlen);
3644   if (err)
3645     goto leave;
3646 
3647   app->apptype = APPTYPE_PIV;
3648   app->did_chv1 = 0;
3649   app->did_chv2 = 0;
3650   app->did_chv3 = 0;
3651   app->app_local = NULL;
3652 
3653   /* Check the Application Property Template.  */
3654   if (opt.verbose)
3655     {
3656       /* We  use a separate log_info to avoid the "DBG:" prefix.  */
3657       log_info ("piv: APT=");
3658       log_printhex (apt, aptlen, "");
3659     }
3660 
3661   s = find_tlv (apt, aptlen, 0x4F, &n);
3662   /* Some cards (new Yubikey) return only the PIX, while others
3663    * (old Yubikey, PivApplet) return the RID+PIX. */
3664   if (!s || !((n == 6 && !memcmp (s, piv_aid+5, 4))
3665               || (n == 11 && !memcmp (s, piv_aid, 9))))
3666     {
3667       /* The PIX does not match.  */
3668       log_error ("piv: missing or invalid DO 0x4F in APT\n");
3669       err = gpg_error (GPG_ERR_CARD);
3670       goto leave;
3671     }
3672   if (s[n-2] != 1 || s[n-1] != 0)
3673     {
3674       log_error ("piv: unknown PIV version %u.%u\n", s[4], s[5]);
3675       err = gpg_error (GPG_ERR_CARD);
3676       goto leave;
3677     }
3678   app->appversion = ((s[n-2] << 8) | s[n-1]);
3679 
3680   s = find_tlv (apt, aptlen, 0x79, &n);
3681   if (!s || n < 7)
3682     {
3683       log_error ("piv: missing or invalid DO 0x79 in APT\n");
3684       err = gpg_error (GPG_ERR_CARD);
3685       goto leave;
3686     }
3687   s = find_tlv (s, n, 0x4F, &n);
3688   /* Some cards may also return the full AID instead of just
3689    * the 5-byte RID here. */
3690   if (!s || !(n == 5 || n == 11) || memcmp (s, piv_aid, 5))
3691     {
3692       /* The RID does not match.  */
3693       log_error ("piv: missing or invalid DO 0x79.4F in APT\n");
3694       err = gpg_error (GPG_ERR_CARD);
3695       goto leave;
3696     }
3697 
3698   app->app_local = xtrycalloc (1, sizeof *app->app_local);
3699   if (!app->app_local)
3700     {
3701       err = gpg_error_from_syserror ();
3702       goto leave;
3703     }
3704 
3705   if (app->card->cardtype == CARDTYPE_YUBIKEY)
3706     app->app_local->flags.yubikey = 1;
3707 
3708 
3709   /* FIXME: Parse the optional and conditional DOs in the APT.  */
3710 
3711   if (opt.verbose)
3712     dump_all_do (slot);
3713 
3714   app->fnc.deinit = do_deinit;
3715   app->fnc.prep_reselect = do_prep_reselect;
3716   app->fnc.reselect = do_reselect;
3717   app->fnc.learn_status = do_learn_status;
3718   app->fnc.readcert = do_readcert;
3719   app->fnc.readkey = do_readkey;
3720   app->fnc.getattr = do_getattr;
3721   app->fnc.setattr = do_setattr;
3722   app->fnc.writecert = do_writecert;
3723   app->fnc.writekey = do_writekey;
3724   app->fnc.genkey = do_genkey;
3725   app->fnc.sign = do_sign;
3726   app->fnc.auth = do_auth;
3727   app->fnc.decipher = do_decipher;
3728   app->fnc.change_pin = do_change_chv;
3729   app->fnc.check_pin = do_check_chv;
3730   app->fnc.with_keygrip = do_with_keygrip;
3731   app->fnc.check_aid = do_check_aid;
3732 
3733 
3734 leave:
3735   xfree (apt);
3736   if (err)
3737     do_deinit (app);
3738   return err;
3739 }
3740