chiark / gitweb /
asshelp.c: add a lot of debug logging
[gnupg2.git] / scd / app-sc-hsm.c
1 /* app-sc-hsm.c - The SmartCard-HSM card application (www.smartcard-hsm.com).
2  *      Copyright (C) 2005 Free Software Foundation, Inc.
3  *      Copyright (C) 2014 Andreas Schwier <andreas.schwier@cardcontact.de>
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 /*
22    Code in this driver is based on app-p15.c with modifications.
23  */
24
25 #include <config.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <assert.h>
31 #include <time.h>
32
33 #include "scdaemon.h"
34
35 #include "iso7816.h"
36 #include "app-common.h"
37 #include "tlv.h"
38 #include "apdu.h"
39
40
41 /* The AID of the SmartCard-HSM applet. */
42 static char const sc_hsm_aid[] = { 0xE8, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x81,
43                                    0xC3, 0x1F, 0x02, 0x01  };
44
45
46 /* Special file identifier for SmartCard-HSM */
47 typedef enum
48 {
49     SC_HSM_PRKD_PREFIX = 0xC4,
50     SC_HSM_CD_PREFIX = 0xC8,
51     SC_HSM_DCOD_PREFIX = 0xC9,
52     SC_HSM_CA_PREFIX = 0xCA,
53     SC_HSM_KEY_PREFIX = 0xCC,
54     SC_HSM_EE_PREFIX = 0xCE
55 } fid_prefix_type_t;
56
57
58 /* The key types supported by the SmartCard-HSM */
59 typedef enum
60   {
61     KEY_TYPE_RSA,
62     KEY_TYPE_ECC
63   } key_type_t;
64
65
66 /* A bit array with for the key usage flags from the
67    commonKeyAttributes. */
68 struct keyusage_flags_s
69 {
70     unsigned int encrypt: 1;
71     unsigned int decrypt: 1;
72     unsigned int sign: 1;
73     unsigned int sign_recover: 1;
74     unsigned int wrap: 1;
75     unsigned int unwrap: 1;
76     unsigned int verify: 1;
77     unsigned int verify_recover: 1;
78     unsigned int derive: 1;
79     unsigned int non_repudiation: 1;
80 };
81 typedef struct keyusage_flags_s keyusage_flags_t;
82
83
84
85 /* This is an object to store information about a Certificate
86    Directory File (CDF) in a format suitable for further processing by
87    us. To keep memory management, simple we use a linked list of
88    items; i.e. one such object represents one certificate and the list
89    the entire CDF. */
90 struct cdf_object_s
91 {
92   /* Link to next item when used in a linked list. */
93   struct cdf_object_s *next;
94
95   /* Length and allocated buffer with the Id of this object. */
96   size_t objidlen;
97   unsigned char *objid;
98
99   /* To avoid reading a certificate more than once, we cache it in an
100      allocated memory IMAGE of IMAGELEN. */
101   size_t imagelen;
102   unsigned char *image;
103
104   /* EF containing certificate */
105   unsigned short fid;
106 };
107 typedef struct cdf_object_s *cdf_object_t;
108
109
110
111 /* This is an object to store information about a Private Key
112    Directory File (PrKDF) in a format suitable for further processing
113    by us. To keep memory management, simple we use a linked list of
114    items; i.e. one such object represents one certificate and the list
115    the entire PrKDF. */
116 struct prkdf_object_s
117 {
118   /* Link to next item when used in a linked list. */
119   struct prkdf_object_s *next;
120
121   /* Key type */
122   key_type_t keytype;
123
124   /* Key size in bits or 0 if unknown */
125   size_t keysize;
126
127   /* Length and allocated buffer with the Id of this object. */
128   size_t objidlen;
129   unsigned char *objid;
130
131   /* The key's usage flags. */
132   keyusage_flags_t usageflags;
133
134   /* The keyReference */
135   unsigned char key_reference;
136 };
137 typedef struct prkdf_object_s *prkdf_object_t;
138
139
140
141 /* Context local to this application. */
142 struct app_local_s
143 {
144   /* Information on all certificates. */
145   cdf_object_t certificate_info;
146   /* Information on all trusted certificates. */
147   cdf_object_t trusted_certificate_info;
148   /* Information on all private keys. */
149   prkdf_object_t private_key_info;
150 };
151
152
153
154 /*** Local prototypes.  ***/
155 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
156                                     unsigned char **r_cert, size_t *r_certlen);
157
158
159
160 /* Release the CDF object A  */
161 static void
162 release_cdflist (cdf_object_t a)
163 {
164   while (a)
165     {
166       cdf_object_t tmp = a->next;
167       xfree (a->image);
168       xfree (a->objid);
169       xfree (a);
170       a = tmp;
171     }
172 }
173
174
175
176 /* Release the PrKDF object A.  */
177 static void
178 release_prkdflist (prkdf_object_t a)
179 {
180   while (a)
181     {
182       prkdf_object_t tmp = a->next;
183       xfree (a->objid);
184       xfree (a);
185       a = tmp;
186     }
187 }
188
189
190
191 /* Release all local resources.  */
192 static void
193 do_deinit (app_t app)
194 {
195   if (app && app->app_local)
196     {
197       release_cdflist (app->app_local->certificate_info);
198       release_cdflist (app->app_local->trusted_certificate_info);
199       release_prkdflist (app->app_local->private_key_info);
200       xfree (app->app_local);
201       app->app_local = NULL;
202     }
203 }
204
205
206
207 /* Get the list of EFs from the SmartCard-HSM.
208  * On success a dynamically buffer containing the EF list is returned.
209  * The caller is responsible for freeing the buffer.
210  */
211 static gpg_error_t
212 list_ef (int slot, unsigned char **result, size_t *resultlen)
213 {
214   int sw;
215
216   if (!result || !resultlen)
217     return gpg_error (GPG_ERR_INV_VALUE);
218   *result = NULL;
219   *resultlen = 0;
220
221   sw = apdu_send_le (slot, 1, 0x80, 0x58, 0x00, 0x00, -1, NULL, 65536,
222                      result, resultlen);
223   if (sw != SW_SUCCESS)
224     {
225       /* Make sure that pending buffers are released. */
226       xfree (*result);
227       *result = NULL;
228       *resultlen = 0;
229     }
230   return iso7816_map_sw (sw);
231 }
232
233
234
235 /* Do a select and a read for the file with EFID.  EFID_DESC is a
236    description of the EF to be used with error messages.  On success
237    BUFFER and BUFLEN contain the entire content of the EF.  The caller
238    must free BUFFER only on success. */
239 static gpg_error_t
240 select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
241                         unsigned char **buffer, size_t *buflen, int maxread)
242 {
243   gpg_error_t err;
244   unsigned char cdata[4];
245   int sw;
246
247   cdata[0] = 0x54;      /* Create ISO 7861-4 odd ins READ BINARY */
248   cdata[1] = 0x02;
249   cdata[2] = 0x00;
250   cdata[3] = 0x00;
251
252   sw = apdu_send_le(slot, 1, 0x00, 0xB1, efid >> 8, efid & 0xFF,
253                     4, cdata, maxread, buffer, buflen);
254
255   if (sw == SW_EOF_REACHED)
256     sw = SW_SUCCESS;
257
258   err = iso7816_map_sw (sw);
259   if (err)
260     {
261       log_error ("error reading %s (0x%04X): %s\n",
262                  efid_desc, efid, gpg_strerror (err));
263       return err;
264     }
265   return 0;
266 }
267
268
269
270 /* Parse a cert Id string (or a key Id string) and return the binary
271    object Id string in a newly allocated buffer stored at R_OBJID and
272    R_OBJIDLEN.  On Error NULL will be stored there and an error code
273    returned. On success caller needs to free the buffer at R_OBJID. */
274 static gpg_error_t
275 parse_certid (const char *certid, unsigned char **r_objid, size_t *r_objidlen)
276 {
277   const char *s;
278   size_t objidlen;
279   unsigned char *objid;
280   int i;
281
282   *r_objid = NULL;
283   *r_objidlen = 0;
284
285   if (strncmp (certid, "HSM.", 4))
286     return gpg_error (GPG_ERR_INV_ID);
287   certid += 4;
288
289   for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
290     ;
291   if (*s || !objidlen || (objidlen%2))
292     return gpg_error (GPG_ERR_INV_ID);
293   objidlen /= 2;
294   objid = xtrymalloc (objidlen);
295   if (!objid)
296     return gpg_error_from_syserror ();
297   for (s=certid, i=0; i < objidlen; i++, s+=2)
298     objid[i] = xtoi_2 (s);
299   *r_objid = objid;
300   *r_objidlen = objidlen;
301   return 0;
302 }
303
304
305
306 /* Find a certificate object by the certificate ID CERTID and store a
307    pointer to it at R_CDF. */
308 static gpg_error_t
309 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
310 {
311   gpg_error_t err;
312   size_t objidlen;
313   unsigned char *objid;
314   cdf_object_t cdf;
315
316   err = parse_certid (certid, &objid, &objidlen);
317   if (err)
318     return err;
319
320   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
321     if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
322       break;
323   if (!cdf)
324     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
325       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
326         break;
327   xfree (objid);
328   if (!cdf)
329     return gpg_error (GPG_ERR_NOT_FOUND);
330   *r_cdf = cdf;
331   return 0;
332 }
333
334
335
336 /* Find a private key object by the key Id string KEYIDSTR and store a
337    pointer to it at R_PRKDF. */
338 static gpg_error_t
339 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
340                             prkdf_object_t *r_prkdf)
341 {
342   gpg_error_t err;
343   size_t objidlen;
344   unsigned char *objid;
345   prkdf_object_t prkdf;
346
347   err = parse_certid (keyidstr, &objid, &objidlen);
348   if (err)
349     return err;
350
351   for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
352     if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
353       break;
354   xfree (objid);
355   if (!prkdf)
356     return gpg_error (GPG_ERR_NOT_FOUND);
357   *r_prkdf = prkdf;
358   return 0;
359 }
360
361
362
363 /* Parse the BIT STRING with the keyUsageFlags from the
364    CommonKeyAttributes. */
365 static gpg_error_t
366 parse_keyusage_flags (const unsigned char *der, size_t derlen,
367                       keyusage_flags_t *usageflags)
368 {
369   unsigned int bits, mask;
370   int i, unused, full;
371
372   memset (usageflags, 0, sizeof *usageflags);
373   if (!derlen)
374     return gpg_error (GPG_ERR_INV_OBJ);
375
376   unused = *der++; derlen--;
377   if ((!derlen && unused) || unused/8 > derlen)
378     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
379   full = derlen - (unused+7)/8;
380   unused %= 8;
381   mask = 0;
382   for (i=1; unused; i <<= 1, unused--)
383     mask |= i;
384
385   /* First octet */
386   if (derlen)
387     {
388       bits = *der++; derlen--;
389       if (full)
390         full--;
391       else
392         {
393           bits &= ~mask;
394           mask = 0;
395         }
396     }
397   else
398     bits = 0;
399   if ((bits & 0x80)) usageflags->encrypt = 1;
400   if ((bits & 0x40)) usageflags->decrypt = 1;
401   if ((bits & 0x20)) usageflags->sign = 1;
402   if ((bits & 0x10)) usageflags->sign_recover = 1;
403   if ((bits & 0x08)) usageflags->wrap = 1;
404   if ((bits & 0x04)) usageflags->unwrap = 1;
405   if ((bits & 0x02)) usageflags->verify = 1;
406   if ((bits & 0x01)) usageflags->verify_recover = 1;
407
408   /* Second octet. */
409   if (derlen)
410     {
411       bits = *der++; derlen--;
412       if (full)
413         full--;
414       else
415         {
416           bits &= ~mask;
417           mask = 0;
418         }
419     }
420   else
421     bits = 0;
422   if ((bits & 0x80)) usageflags->derive = 1;
423   if ((bits & 0x40)) usageflags->non_repudiation = 1;
424
425   return 0;
426 }
427
428
429
430 /* Read and parse a Private Key Directory File containing a single key
431    description in PKCS#15 format.  For each private key a matching
432    certificate description is created, if the certificate EF exists
433    and contains a X.509 certificate.
434
435    Example data:
436
437 0000  30 2A 30 13 0C 11 4A 6F 65 20 44 6F 65 20 28 52  0*0...Joe Doe (R
438 0010  53 41 32 30 34 38 29 30 07 04 01 01 03 02 02 74  SA2048)0.......t
439 0020  A1 0A 30 08 30 02 04 00 02 02 08 00              ..0.0.......
440
441    Decoded example:
442
443 SEQUENCE SIZE( 42 )
444   SEQUENCE SIZE( 19 )
445     UTF8-STRING SIZE( 17 )                -- label
446       0000  4A 6F 65 20 44 6F 65 20 28 52 53 41 32 30 34 38  Joe Doe (RSA2048
447       0010  29                                               )
448   SEQUENCE SIZE( 7 )
449     OCTET-STRING SIZE( 1 )                -- id
450       0000  01
451     BIT-STRING SIZE( 2 )                  -- key usage
452       0000  02 74
453   A1 [ CONTEXT 1 ] IMPLICIT SEQUENCE SIZE( 10 )
454     SEQUENCE SIZE( 8 )
455       SEQUENCE SIZE( 2 )
456         OCTET-STRING SIZE( 0 )            -- empty path, req object in PKCS#15
457       INTEGER SIZE( 2 )                   -- modulus size in bits
458         0000  08 00
459 */
460 static gpg_error_t
461 read_ef_prkd (app_t app, unsigned short fid, prkdf_object_t *prkdresult,
462               cdf_object_t *cdresult)
463 {
464   gpg_error_t err;
465   unsigned char *buffer = NULL;
466   size_t buflen;
467   const unsigned char *p;
468   size_t n, objlen, hdrlen;
469   int class, tag, constructed, ndef;
470   int i;
471   const unsigned char *pp;
472   size_t nn;
473   int where;
474   const char *errstr = NULL;
475   prkdf_object_t prkdf = NULL;
476   cdf_object_t cdf = NULL;
477   unsigned long ul;
478   const unsigned char *objid;
479   size_t objidlen;
480   keyusage_flags_t usageflags;
481   const char *s;
482   key_type_t keytype;
483   size_t keysize;
484
485   if (!fid)
486     return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
487
488   err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen, 255);
489   if (err)
490     return err;
491
492   p = buffer;
493   n = buflen;
494
495   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
496                           &ndef, &objlen, &hdrlen);
497   if (!err && (objlen > n || (tag != TAG_SEQUENCE && tag != 0x00)))
498     err = gpg_error (GPG_ERR_INV_OBJ);
499   if (err)
500     {
501       log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
502       goto leave;
503     }
504
505   keytype = tag == 0x00 ? KEY_TYPE_ECC : KEY_TYPE_RSA;
506
507   pp = p;
508   nn = objlen;
509   p += objlen;
510   n -= objlen;
511
512   /* Parse the commonObjectAttributes.  */
513   where = __LINE__;
514   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
515                           &ndef, &objlen, &hdrlen);
516   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
517     err = gpg_error (GPG_ERR_INV_OBJ);
518   if (err)
519     goto parse_error;
520
521   {
522     const unsigned char *ppp = pp;
523     size_t nnn = objlen;
524
525     pp += objlen;
526     nn -= objlen;
527
528     /* Search the optional AuthId.  We need to skip the optional Label
529        (UTF8STRING) and the optional CommonObjectFlags (BITSTRING). */
530     where = __LINE__;
531     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
532                             &ndef, &objlen, &hdrlen);
533     if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
534       err = gpg_error (GPG_ERR_INV_OBJ);
535     if (gpg_err_code (err) == GPG_ERR_EOF)
536       goto no_authid;
537     if (err)
538       goto parse_error;
539
540     if (tag == TAG_UTF8_STRING)
541       {
542         ppp += objlen; /* Skip the Label. */
543         nnn -= objlen;
544
545         where = __LINE__;
546         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
547                                 &ndef, &objlen, &hdrlen);
548         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
549           err = gpg_error (GPG_ERR_INV_OBJ);
550         if (gpg_err_code (err) == GPG_ERR_EOF)
551           goto no_authid;
552         if (err)
553           goto parse_error;
554       }
555     if (tag == TAG_BIT_STRING)
556       {
557         ppp += objlen; /* Skip the CommonObjectFlags.  */
558         nnn -= objlen;
559
560         where = __LINE__;
561         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
562                                 &ndef, &objlen, &hdrlen);
563         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
564           err = gpg_error (GPG_ERR_INV_OBJ);
565         if (gpg_err_code (err) == GPG_ERR_EOF)
566           goto no_authid;
567         if (err)
568           goto parse_error;
569       }
570     if (tag == TAG_OCTET_STRING && objlen)
571       {
572         /* AuthId ignored */
573       }
574   no_authid:
575     ;
576   }
577
578   /* Parse the commonKeyAttributes.  */
579   where = __LINE__;
580   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
581       &ndef, &objlen, &hdrlen);
582   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
583     err = gpg_error (GPG_ERR_INV_OBJ);
584   if (err)
585     goto parse_error;
586
587   {
588     const unsigned char *ppp = pp;
589     size_t nnn = objlen;
590
591     pp += objlen;
592     nn -= objlen;
593
594     /* Get the Id. */
595     where = __LINE__;
596     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
597                             &ndef, &objlen, &hdrlen);
598     if (!err && (objlen > nnn
599                  || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
600       err = gpg_error (GPG_ERR_INV_OBJ);
601     if (err)
602       goto parse_error;
603
604     objid = ppp;
605     objidlen = objlen;
606     ppp += objlen;
607     nnn -= objlen;
608
609     /* Get the KeyUsageFlags. */
610     where = __LINE__;
611     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
612                             &ndef, &objlen, &hdrlen);
613     if (!err && (objlen > nnn
614                  || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
615       err = gpg_error (GPG_ERR_INV_OBJ);
616     if (err)
617       goto parse_error;
618
619     err = parse_keyusage_flags (ppp, objlen, &usageflags);
620     if (err)
621       goto parse_error;
622
623     ppp += objlen;
624     nnn -= objlen;
625
626     /* Find the keyReference */
627     where = __LINE__;
628     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
629                             &ndef, &objlen, &hdrlen);
630     if (gpg_err_code (err) == GPG_ERR_EOF)
631       goto leave_cki;
632     if (!err && objlen > nnn)
633       err = gpg_error (GPG_ERR_INV_OBJ);
634     if (err)
635       goto parse_error;
636
637     if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
638       {
639         /* Skip the native element. */
640         ppp += objlen;
641         nnn -= objlen;
642
643         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
644                                 &ndef, &objlen, &hdrlen);
645         if (gpg_err_code (err) == GPG_ERR_EOF)
646           goto leave_cki;
647         if (!err && objlen > nnn)
648           err = gpg_error (GPG_ERR_INV_OBJ);
649         if (err)
650           goto parse_error;
651       }
652     if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
653       {
654         /* Skip the accessFlags. */
655         ppp += objlen;
656         nnn -= objlen;
657
658         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
659                                 &ndef, &objlen, &hdrlen);
660         if (gpg_err_code (err) == GPG_ERR_EOF)
661           goto leave_cki;
662         if (!err && objlen > nnn)
663           err = gpg_error (GPG_ERR_INV_OBJ);
664         if (err)
665           goto parse_error;
666       }
667     if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
668       {
669         /* Yep, this is the keyReference.
670            Note: UL is currently not used. */
671         for (ul=0; objlen; objlen--)
672           {
673             ul <<= 8;
674             ul |= (*ppp++) & 0xff;
675             nnn--;
676           }
677       }
678
679   leave_cki:
680     ;
681   }
682
683
684   /* Skip subClassAttributes.  */
685   where = __LINE__;
686   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
687                           &ndef, &objlen, &hdrlen);
688   if (!err && objlen > nn)
689     err = gpg_error (GPG_ERR_INV_OBJ);
690   if (err)
691     goto parse_error;
692   if (class == CLASS_CONTEXT && tag == 0)
693     {
694       pp += objlen;
695       nn -= objlen;
696
697       where = __LINE__;
698       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
699                               &ndef, &objlen, &hdrlen);
700     }
701
702   /* Parse the keyAttributes.  */
703   if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
704     err = gpg_error (GPG_ERR_INV_OBJ);
705   if (err)
706     goto parse_error;
707
708   nn = objlen;
709
710   where = __LINE__;
711   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
712                           &ndef, &objlen, &hdrlen);
713   if (!err && objlen > nn)
714     err = gpg_error (GPG_ERR_INV_OBJ);
715   if (err)
716     goto parse_error;
717
718   nn = objlen;
719
720   /* Check that the reference is a Path object.  */
721   where = __LINE__;
722   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
723                           &ndef, &objlen, &hdrlen);
724   if (!err && objlen > nn)
725     err = gpg_error (GPG_ERR_INV_OBJ);
726   if (err)
727     goto parse_error;
728   if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
729     {
730       errstr = "unsupported reference type";
731       goto parse_error;
732     }
733
734   pp += objlen;
735   nn -= objlen;
736
737   /* Parse the key size object. */
738   where = __LINE__;
739   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
740                           &ndef, &objlen, &hdrlen);
741   if (!err && objlen > nn)
742     err = gpg_error (GPG_ERR_INV_OBJ);
743   if (err)
744     goto parse_error;
745   keysize = 0;
746   if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER && objlen == 2)
747     {
748       keysize  = *pp++ << 8;
749       keysize += *pp++;
750     }
751
752   /* Create a new PrKDF list item. */
753   prkdf = xtrycalloc (1, sizeof *prkdf);
754   if (!prkdf)
755     {
756       err = gpg_error_from_syserror ();
757       goto leave;
758     }
759   prkdf->keytype = keytype;
760   prkdf->keysize = keysize;
761   prkdf->objidlen = objidlen;
762   prkdf->objid = xtrymalloc (objidlen);
763   if (!prkdf->objid)
764     {
765       err = gpg_error_from_syserror ();
766       xfree (prkdf);
767       prkdf = NULL;
768       goto leave;
769     }
770   memcpy (prkdf->objid, objid, objidlen);
771
772   prkdf->usageflags = usageflags;
773   prkdf->key_reference = fid & 0xFF;
774
775   log_debug ("PrKDF %04hX: id=", fid);
776   for (i=0; i < prkdf->objidlen; i++)
777     log_printf ("%02X", prkdf->objid[i]);
778   log_printf (" keyref=0x%02X", prkdf->key_reference);
779   log_printf (" keysize=%zu", prkdf->keysize);
780   log_printf (" usage=");
781   s = "";
782   if (prkdf->usageflags.encrypt)
783     {
784       log_printf ("%sencrypt", s);
785       s = ",";
786     }
787   if (prkdf->usageflags.decrypt)
788     {
789       log_printf ("%sdecrypt", s);
790       s = ",";
791     }
792   if (prkdf->usageflags.sign)
793     {
794       log_printf ("%ssign", s);
795       s = ",";
796     }
797   if (prkdf->usageflags.sign_recover)
798     {
799       log_printf ("%ssign_recover", s);
800       s = ",";
801     }
802   if (prkdf->usageflags.wrap   )
803     {
804       log_printf ("%swrap", s);
805       s = ",";
806     }
807   if (prkdf->usageflags.unwrap )
808     {
809       log_printf ("%sunwrap", s);
810       s = ",";
811     }
812   if (prkdf->usageflags.verify )
813     {
814       log_printf ("%sverify", s);
815       s = ",";
816     }
817   if (prkdf->usageflags.verify_recover)
818     {
819       log_printf ("%sverify_recover", s);
820       s = ",";
821     }
822   if (prkdf->usageflags.derive )
823     {
824       log_printf ("%sderive", s);
825       s = ",";
826     }
827   if (prkdf->usageflags.non_repudiation)
828     {
829       log_printf ("%snon_repudiation", s);
830       s = ",";
831     }
832   log_printf ("\n");
833
834   xfree (buffer);
835   buffer = NULL;
836   buflen = 0;
837   err = select_and_read_binary (app->slot,
838                                 ((SC_HSM_EE_PREFIX << 8) | (fid & 0xFF)),
839                                 "CertEF", &buffer, &buflen, 1);
840   if (!err && buffer[0] == 0x30)
841     {
842       /* Create a matching CDF list item. */
843       cdf = xtrycalloc (1, sizeof *cdf);
844       if (!cdf)
845         {
846           err = gpg_error_from_syserror ();
847           goto leave;
848         }
849       cdf->objidlen = prkdf->objidlen;
850       cdf->objid = xtrymalloc (cdf->objidlen);
851       if (!cdf->objid)
852         {
853           err = gpg_error_from_syserror ();
854           xfree (cdf);
855           cdf = NULL;
856           goto leave;
857         }
858       memcpy (cdf->objid, prkdf->objid, objidlen);
859
860       cdf->fid = (SC_HSM_EE_PREFIX << 8) | (fid & 0xFF);
861
862       log_debug ("CDF %04hX: id=", fid);
863       for (i=0; i < cdf->objidlen; i++)
864         log_printf ("%02X", cdf->objid[i]);
865       log_printf (" fid=%04X\n", cdf->fid);
866     }
867
868   goto leave; /* Ready. */
869
870  parse_error:
871   log_error ("error parsing PrKDF record (%d): %s - skipped\n",
872              where, errstr? errstr : gpg_strerror (err));
873   err = 0;
874
875  leave:
876   xfree (buffer);
877   if (err)
878     {
879       if (prkdf)
880         {
881           if (prkdf->objid)
882             xfree (prkdf->objid);
883           xfree (prkdf);
884         }
885       if (cdf)
886         {
887           if (cdf->objid)
888             xfree (cdf->objid);
889           xfree (cdf);
890         }
891     }
892   else
893     {
894       prkdf->next = *prkdresult;
895       *prkdresult = prkdf;
896       if (cdf)
897         {
898           cdf->next = *cdresult;
899           *cdresult = cdf;
900         }
901     }
902   return err;
903 }
904
905
906
907 /* Read and parse the Certificate Description File identified by FID.
908    On success a the CDF list gets stored at RESULT and the caller is
909    then responsible of releasing the object.
910
911    Example data:
912
913 0000  30 35 30 11 0C 0B 43 65 72 74 69 66 69 63 61 74  050...Certificat
914 0010  65 03 02 06 40 30 16 04 14 C2 01 7C 2F BA A4 4A  e...@0.....|/..J
915 0020  4A BB B8 49 11 DB 4A CA AA 7E 6A 2D 1B A1 08 30  J..I..J..~j-...0
916 0030  06 30 04 04 02 CA 00                             .0.....
917
918    Decoded example:
919
920 SEQUENCE SIZE( 53 )
921   SEQUENCE SIZE( 17 )
922     UTF8-STRING SIZE( 11 )                      -- label
923       0000  43 65 72 74 69 66 69 63 61 74 65                 Certificate
924     BIT-STRING SIZE( 2 )                        -- common object attributes
925       0000  06 40
926   SEQUENCE SIZE( 22 )
927     OCTET-STRING SIZE( 20 )                     -- id
928       0000  C2 01 7C 2F BA A4 4A 4A BB B8 49 11 DB 4A CA AA
929       0010  7E 6A 2D 1B
930   A1 [ CONTEXT 1 ] IMPLICIT SEQUENCE SIZE( 8 )
931     SEQUENCE SIZE( 6 )
932       SEQUENCE SIZE( 4 )
933         OCTET-STRING SIZE( 2 )                  -- path
934           0000  CA 00                                            ..
935  */
936 static gpg_error_t
937 read_ef_cd (app_t app, unsigned short fid, cdf_object_t *result)
938 {
939   gpg_error_t err;
940   unsigned char *buffer = NULL;
941   size_t buflen;
942   const unsigned char *p;
943   size_t n, objlen, hdrlen;
944   int class, tag, constructed, ndef;
945   int i;
946   const unsigned char *pp;
947   size_t nn;
948   int where;
949   const char *errstr = NULL;
950   cdf_object_t cdf = NULL;
951   const unsigned char *objid;
952   size_t objidlen;
953
954   if (!fid)
955     return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
956
957   err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen, 255);
958   if (err)
959     return err;
960
961   p = buffer;
962   n = buflen;
963
964   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
965                           &ndef, &objlen, &hdrlen);
966   if (!err && (objlen > n || tag != TAG_SEQUENCE))
967     err = gpg_error (GPG_ERR_INV_OBJ);
968   if (err)
969     {
970       log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
971       goto leave;
972     }
973   pp = p;
974   nn = objlen;
975   p += objlen;
976   n -= objlen;
977
978   /* Skip the commonObjectAttributes.  */
979   where = __LINE__;
980   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
981                           &ndef, &objlen, &hdrlen);
982   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
983     err = gpg_error (GPG_ERR_INV_OBJ);
984   if (err)
985     goto parse_error;
986   pp += objlen;
987   nn -= objlen;
988
989   /* Parse the commonCertificateAttributes.  */
990   where = __LINE__;
991   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
992                           &ndef, &objlen, &hdrlen);
993   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
994     err = gpg_error (GPG_ERR_INV_OBJ);
995   if (err)
996     goto parse_error;
997
998   {
999     const unsigned char *ppp = pp;
1000     size_t nnn = objlen;
1001
1002     pp += objlen;
1003     nn -= objlen;
1004
1005     /* Get the Id. */
1006     where = __LINE__;
1007     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1008                             &ndef, &objlen, &hdrlen);
1009     if (!err && (objlen > nnn
1010                  || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1011       err = gpg_error (GPG_ERR_INV_OBJ);
1012     if (err)
1013       goto parse_error;
1014
1015     objid = ppp;
1016     objidlen = objlen;
1017   }
1018
1019   /* Parse the certAttribute.  */
1020   where = __LINE__;
1021   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1022                           &ndef, &objlen, &hdrlen);
1023   if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1024     err = gpg_error (GPG_ERR_INV_OBJ);
1025   if (err)
1026     goto parse_error;
1027   nn = objlen;
1028
1029   where = __LINE__;
1030   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1031                           &ndef, &objlen, &hdrlen);
1032   if (!err && (objlen > nn
1033                || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1034     err = gpg_error (GPG_ERR_INV_OBJ);
1035   if (err)
1036     goto parse_error;
1037   nn = objlen;
1038
1039   /* Check that the reference is a Path object.  */
1040   where = __LINE__;
1041   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1042                           &ndef, &objlen, &hdrlen);
1043   if (!err && objlen > nn)
1044     err = gpg_error (GPG_ERR_INV_OBJ);
1045   if (err)
1046     goto parse_error;
1047   if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1048     {
1049       err = gpg_error (GPG_ERR_INV_OBJ);
1050       goto parse_error;
1051     }
1052   nn = objlen;
1053
1054   /* Parse the Path object. */
1055   where = __LINE__;
1056   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1057                           &ndef, &objlen, &hdrlen);
1058   if (!err && objlen > nn)
1059     err = gpg_error (GPG_ERR_INV_OBJ);
1060   if (err)
1061     goto parse_error;
1062
1063   /* Make sure that the next element is a non zero path and of
1064      even length (FID are two bytes each). */
1065   if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1066       || (objlen & 1) )
1067     {
1068       errstr = "invalid path reference";
1069       goto parse_error;
1070     }
1071   /* Create a new CDF list item. */
1072   cdf = xtrycalloc (1, sizeof *cdf);
1073   if (!cdf)
1074     {
1075       err = gpg_error_from_syserror ();
1076       goto leave;
1077     }
1078   cdf->objidlen = objidlen;
1079   cdf->objid = xtrymalloc (objidlen);
1080   if (!cdf->objid)
1081     {
1082       err = gpg_error_from_syserror ();
1083       xfree (cdf);
1084       cdf = NULL;
1085       goto leave;
1086     }
1087   memcpy (cdf->objid, objid, objidlen);
1088
1089   cdf->fid = (SC_HSM_CA_PREFIX << 8) | (fid & 0xFF);
1090
1091   log_debug ("CDF %04hX: id=", fid);
1092   for (i=0; i < cdf->objidlen; i++)
1093     log_printf ("%02X", cdf->objid[i]);
1094
1095   goto leave;
1096
1097  parse_error:
1098   log_error ("error parsing CDF record (%d): %s - skipped\n",
1099              where, errstr? errstr : gpg_strerror (err));
1100   err = 0;
1101
1102  leave:
1103   xfree (buffer);
1104   if (err)
1105     {
1106       if (cdf)
1107         {
1108           if (cdf->objid)
1109             xfree (cdf->objid);
1110           xfree (cdf);
1111         }
1112     }
1113   else
1114     {
1115       cdf->next = *result;
1116       *result = cdf;
1117     }
1118   return err;
1119 }
1120
1121
1122
1123 /* Read the device certificate and extract the serial number.
1124
1125    EF.C_DevAut (2F02) contains two CVCs, the first is the device
1126    certificate, the second is the issuer certificate.
1127
1128    Example data:
1129
1130 0000  7F 21 81 E2 7F 4E 81 9B 5F 29 01 00 42 0B 55 54  .!...N.._)..B.UT
1131 0010  43 43 30 32 30 30 30 30 32 7F 49 4F 06 0A 04 00  CC0200002.IO....
1132 0020  7F 00 07 02 02 02 02 03 86 41 04 6D FF D6 85 57  .........A.m...W
1133 0030  40 FB 10 5D 94 71 8A 94 D2 5E 50 33 E7 1E C0 6C  @..].q...^P3...l
1134 0040  63 D5 C8 FC BA F3 02 1D 70 23 F6 47 E8 35 48 EF  c.......p#.G.5H.
1135 0050  B5 94 72 3C 6F BE C0 EB 9A C7 FB 06 59 26 CF 65  ..r<o.......Y&.e
1136 0060  EF A1 72 E0 98 F3 F0 44 1B B7 71 5F 20 10 55 54  ..r....D..q_ .UT
1137 0070  43 43 30 32 30 30 30 31 33 30 30 30 30 30 7F 4C  CC020001300000.L
1138 0080  10 06 0B 2B 06 01 04 01 81 C3 1F 03 01 01 53 01  ...+..........S.
1139 0090  00 5F 25 06 01 04 00 07 01 01 5F 24 06 02 01 00  ._%......._$....
1140 00A0  03 02 07 5F 37 40 7F 73 04 3B 06 63 79 41 BE 1A  ..._7@.s.;.cyA..
1141 00B0  9F FC F6 77 67 2B 8A 41 D1 11 F6 9B 54 44 AD 19  ...wg+.A....TD..
1142 00C0  FB B8 0C C6 2F 34 71 8E 4F F6 92 59 34 61 D9 4F  ..../4q.O..Y4a.O
1143 00D0  4A 86 36 A8 D8 9A C6 3C 17 7E 71 CE A8 26 D0 C5  J.6....<.~q..&..
1144 00E0  25 61 78 9D 01 F8 7F 21 81 E0 7F 4E 81 99 5F 29  %ax....!...N.._)
1145 00F0  01 00 42 0E 55 54 53 52 43 41 43 43 31 30 30 30  ..B.UTSRCACC1000
1146 0100  30 31 7F 49 4F 06 0A 04 00 7F 00 07 02 02 02 02  01.IO...........
1147 0110  03 86 41 04 2F EA 33 47 7F 45 81 E2 FC CB 66 87  ..A./.3G.E....f.
1148 0120  4B 96 21 1D 68 81 73 F2 9F 8F 6B 91 F0 DE 4B 54  K.!.h.s...k...KT
1149 0130  8E D8 F0 82 3D CB BE 10 98 A3 1E 4F F0 72 5C E5  ....=......O.r\.
1150 0140  7B 1E F7 3C 68 09 03 E8 A0 3F 3E 06 C1 B0 3C 18  {..<h....?>...<.
1151 0150  6B AC 06 EA 5F 20 0B 55 54 43 43 30 32 30 30 30  k..._ .UTCC02000
1152 0160  30 32 7F 4C 10 06 0B 2B 06 01 04 01 81 C3 1F 03  02.L...+........
1153 0170  01 01 53 01 80 5F 25 06 01 03 00 03 02 08 5F 24  ..S.._%......._$
1154 0180  06 02 01 00 03 02 07 5F 37 40 93 C1 42 8B B3 8E  ......._7@..B...
1155 0190  42 61 6F 2C 19 E6 98 41 BD AA 60 BD E0 DD 4E F0  Bao,...A..`...N.
1156 01A0  15 D5 4F 71 B7 BB C3 3A F2 AD 27 5E DD EE 6D 12  ..Oq...:..'^..m.
1157 01B0  76 E6 2B A0 4C 01 CA C1 26 0C 45 6D C6 CB EC 92  v.+.L...&.Em....
1158 01C0  BF 38 18 AD 8F B2 29 40 A9 51                    .8....)@.Q
1159
1160    The certificate format is defined in BSI TR-03110:
1161
1162 7F21 [ APPLICATION 33 ] IMPLICIT SEQUENCE SIZE( 226 )
1163   7F4E [ APPLICATION 78 ] IMPLICIT SEQUENCE SIZE( 155 )
1164     5F29 [ APPLICATION 41 ] SIZE( 1 )                           -- profile id
1165       0000  00
1166     42 [ APPLICATION 2 ] SIZE( 11 )                             -- CAR
1167       0000  55 54 43 43 30 32 30 30 30 30 32                 UTCC0200002
1168     7F49 [ APPLICATION 73 ] IMPLICIT SEQUENCE SIZE( 79 )        -- public key
1169       OBJECT IDENTIFIER = { id-TA-ECDSA-SHA-256 }
1170       86 [ CONTEXT 6 ] SIZE( 65 )
1171         0000  04 6D FF D6 85 57 40 FB 10 5D 94 71 8A 94 D2 5E
1172         0010  50 33 E7 1E C0 6C 63 D5 C8 FC BA F3 02 1D 70 23
1173         0020  F6 47 E8 35 48 EF B5 94 72 3C 6F BE C0 EB 9A C7
1174         0030  FB 06 59 26 CF 65 EF A1 72 E0 98 F3 F0 44 1B B7
1175         0040  71
1176     5F20 [ APPLICATION 32 ] SIZE( 16 )                          -- CHR
1177       0000  55 54 43 43 30 32 30 30 30 31 33 30 30 30 30 30  UTCC020001300000
1178     7F4C [ APPLICATION 76 ] IMPLICIT SEQUENCE SIZE( 16 )        -- CHAT
1179       OBJECT IDENTIFIER = { 1 3 6 1 4 1 24991 3 1 1 }
1180       53 [ APPLICATION 19 ] SIZE( 1 )
1181         0000  00
1182     5F25 [ APPLICATION 37 ] SIZE( 6 )                           -- Valid from
1183       0000  01 04 00 07 01 01
1184     5F24 [ APPLICATION 36 ] SIZE( 6 )                           -- Valid to
1185       0000  02 01 00 03 02 07
1186   5F37 [ APPLICATION 55 ] SIZE( 64 )                            -- Signature
1187     0000  7F 73 04 3B 06 63 79 41 BE 1A 9F FC F6 77 67 2B
1188     0010  8A 41 D1 11 F6 9B 54 44 AD 19 FB B8 0C C6 2F 34
1189     0020  71 8E 4F F6 92 59 34 61 D9 4F 4A 86 36 A8 D8 9A
1190     0030  C6 3C 17 7E 71 CE A8 26 D0 C5 25 61 78 9D 01 F8
1191
1192    The serial number is contained in tag 5F20, while the last 5 digits
1193    are truncated.
1194  */
1195 static gpg_error_t
1196 read_serialno(app_t app)
1197 {
1198   gpg_error_t err;
1199   unsigned char *buffer = NULL;
1200   size_t buflen;
1201   const unsigned char *p,*chr;
1202   size_t n, objlen, hdrlen, chrlen;
1203   int class, tag, constructed, ndef;
1204
1205   err = select_and_read_binary (app->slot, 0x2F02, "EF.C_DevAut",
1206                                 &buffer, &buflen, 512);
1207   if (err)
1208     return err;
1209
1210   p = buffer;
1211   n = buflen;
1212
1213   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1214                           &ndef, &objlen, &hdrlen);
1215   if (!err && (objlen > n || tag != 0x21))
1216     err = gpg_error (GPG_ERR_INV_OBJ);
1217   if (err)
1218     {
1219       log_error ("error parsing C_DevAut: %s\n", gpg_strerror (err));
1220       goto leave;
1221     }
1222
1223   chr = find_tlv (p, objlen, 0x5F20, &chrlen);
1224   if (!chr || chrlen <= 5)
1225     {
1226       err = gpg_error (GPG_ERR_INV_OBJ);
1227       log_error ("CHR not found in CVC\n");
1228       goto leave;
1229     }
1230   chrlen -= 5;
1231
1232   app->serialno = xtrymalloc (chrlen);
1233   if (!app->serialno)
1234     {
1235       err = gpg_error_from_syserror ();
1236       goto leave;
1237     }
1238
1239   app->serialnolen = chrlen;
1240   memcpy (app->serialno, chr, chrlen);
1241
1242  leave:
1243   xfree (buffer);
1244   return err;
1245 }
1246
1247
1248 /* Get all the basic information from the SmartCard-HSM, check the
1249    structure and initialize our local context.  This is used once at
1250    application initialization.  */
1251 static gpg_error_t
1252 read_meta (app_t app)
1253 {
1254   gpg_error_t err;
1255   unsigned char *eflist = NULL;
1256   size_t eflistlen = 0;
1257   int i;
1258
1259   err = read_serialno(app);
1260   if (err)
1261     return err;
1262
1263   err = list_ef (app->slot, &eflist, &eflistlen);
1264   if (err)
1265     return err;
1266
1267   for (i = 0; i < eflistlen; i += 2)
1268     {
1269       switch(eflist[i])
1270         {
1271         case SC_HSM_KEY_PREFIX:
1272           if (eflist[i + 1] == 0)    /* No key with ID=0 */
1273             break;
1274           err = read_ef_prkd (app, ((SC_HSM_PRKD_PREFIX << 8) | eflist[i + 1]),
1275                               &app->app_local->private_key_info,
1276                               &app->app_local->certificate_info);
1277           if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1278             err = 0;
1279           if (err)
1280             return err;
1281           break;
1282         case SC_HSM_CD_PREFIX:
1283           err = read_ef_cd (app, ((eflist[i] << 8) | eflist[i + 1]),
1284                             &app->app_local->trusted_certificate_info);
1285           if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1286             err = 0;
1287           if (err)
1288             return err;
1289           break;
1290         }
1291     }
1292
1293   xfree (eflist);
1294
1295   return err;
1296 }
1297
1298
1299
1300 /* Helper to do_learn_status: Send information about all certificates
1301    listed in CERTINFO back.  Use CERTTYPE as type of the
1302    certificate. */
1303 static gpg_error_t
1304 send_certinfo (ctrl_t ctrl, const char *certtype, cdf_object_t certinfo)
1305 {
1306   for (; certinfo; certinfo = certinfo->next)
1307     {
1308       char *buf, *p;
1309
1310       buf = xtrymalloc (4 + certinfo->objidlen*2 + 1);
1311       if (!buf)
1312         return gpg_error_from_syserror ();
1313       p = stpcpy (buf, "HSM.");
1314       bin2hex (certinfo->objid, certinfo->objidlen, p);
1315
1316       send_status_info (ctrl, "CERTINFO",
1317                         certtype, strlen (certtype),
1318                         buf, strlen (buf),
1319                         NULL, (size_t)0);
1320       xfree (buf);
1321     }
1322   return 0;
1323 }
1324
1325
1326
1327 /* Get the keygrip of the private key object PRKDF.  On success the
1328    keygrip gets returned in the caller provided 41 byte buffer
1329    R_GRIPSTR. */
1330 static gpg_error_t
1331 keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
1332 {
1333   gpg_error_t err;
1334   cdf_object_t cdf;
1335   unsigned char *der;
1336   size_t derlen;
1337   ksba_cert_t cert;
1338
1339   /* Look for a matching certificate. A certificate matches if the Id
1340      matches the one of the private key info. */
1341   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
1342     if (cdf->objidlen == prkdf->objidlen
1343         && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
1344       break;
1345   if (!cdf)
1346     return gpg_error (GPG_ERR_NOT_FOUND);
1347
1348   err = readcert_by_cdf (app, cdf, &der, &derlen);
1349   if (err)
1350     return err;
1351
1352   err = ksba_cert_new (&cert);
1353   if (!err)
1354     err = ksba_cert_init_from_mem (cert, der, derlen);
1355   xfree (der);
1356   if (!err)
1357     err = app_help_get_keygrip_string (cert, r_gripstr);
1358   ksba_cert_release (cert);
1359
1360   return err;
1361 }
1362
1363
1364
1365 /* Helper to do_learn_status: Send information about all known
1366    keypairs back. */
1367 static gpg_error_t
1368 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
1369 {
1370   gpg_error_t err;
1371
1372   for (; keyinfo; keyinfo = keyinfo->next)
1373     {
1374       char gripstr[40+1];
1375       char *buf, *p;
1376
1377       buf = xtrymalloc (4 + keyinfo->objidlen*2 + 1);
1378       if (!buf)
1379         return gpg_error_from_syserror ();
1380       p = stpcpy (buf, "HSM.");
1381       bin2hex (keyinfo->objid, keyinfo->objidlen, p);
1382
1383       err = keygripstr_from_prkdf (app, keyinfo, gripstr);
1384       if (err)
1385         {
1386           log_error ("can't get keygrip from %04X\n", keyinfo->key_reference);
1387         }
1388       else
1389         {
1390           assert (strlen (gripstr) == 40);
1391           send_status_info (ctrl, "KEYPAIRINFO",
1392                             gripstr, 40,
1393                             buf, strlen (buf),
1394                             NULL, (size_t)0);
1395         }
1396       xfree (buf);
1397     }
1398   return 0;
1399 }
1400
1401
1402
1403 /* This is the handler for the LEARN command. */
1404 static gpg_error_t
1405 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1406 {
1407   gpg_error_t err;
1408
1409   if ((flags & 1))
1410     err = 0;
1411   else
1412     {
1413       err = send_certinfo (ctrl, "100", app->app_local->certificate_info);
1414       if (!err)
1415         err = send_certinfo (ctrl, "101",
1416             app->app_local->trusted_certificate_info);
1417     }
1418
1419   if (!err)
1420     err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
1421
1422   return err;
1423 }
1424
1425
1426
1427 /* Read a certificate using the information in CDF and return the
1428    certificate in a newly allocated buffer R_CERT and its length
1429    R_CERTLEN. */
1430 static gpg_error_t
1431 readcert_by_cdf (app_t app, cdf_object_t cdf,
1432                  unsigned char **r_cert, size_t *r_certlen)
1433 {
1434   gpg_error_t err;
1435   unsigned char *buffer = NULL;
1436   const unsigned char *p, *save_p;
1437   size_t buflen, n;
1438   int class, tag, constructed, ndef;
1439   size_t totobjlen, objlen, hdrlen;
1440   int rootca;
1441   int i;
1442
1443   *r_cert = NULL;
1444   *r_certlen = 0;
1445
1446   /* First check whether it has been cached. */
1447   if (cdf->image)
1448     {
1449       *r_cert = xtrymalloc (cdf->imagelen);
1450       if (!*r_cert)
1451         return gpg_error_from_syserror ();
1452       memcpy (*r_cert, cdf->image, cdf->imagelen);
1453       *r_certlen = cdf->imagelen;
1454       return 0;
1455     }
1456
1457   err = select_and_read_binary (app->slot, cdf->fid, "CD",
1458                                 &buffer, &buflen, 4096);
1459   if (err)
1460     {
1461       log_error ("error reading certificate with Id ");
1462       for (i=0; i < cdf->objidlen; i++)
1463         log_printf ("%02X", cdf->objid[i]);
1464       log_printf (": %s\n", gpg_strerror (err));
1465       goto leave;
1466     }
1467
1468   /* Check whether this is really a certificate.  */
1469   p = buffer;
1470   n = buflen;
1471   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1472                           &ndef, &objlen, &hdrlen);
1473   if (err)
1474     goto leave;
1475
1476   if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
1477     rootca = 0;
1478   else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
1479     rootca = 1;
1480   else
1481     {
1482       err = gpg_error (GPG_ERR_INV_OBJ);
1483       goto leave;
1484     }
1485   totobjlen = objlen + hdrlen;
1486   assert (totobjlen <= buflen);
1487
1488   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1489                           &ndef, &objlen, &hdrlen);
1490   if (err)
1491     goto leave;
1492
1493   if (!rootca
1494       && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
1495     {
1496       /* The certificate seems to be contained in a userCertificate
1497          container.  Skip this and assume the following sequence is
1498          the certificate. */
1499       if (n < objlen)
1500         {
1501           err = gpg_error (GPG_ERR_INV_OBJ);
1502           goto leave;
1503         }
1504       p += objlen;
1505       n -= objlen;
1506       save_p = p;
1507       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1508                               &ndef, &objlen, &hdrlen);
1509       if (err)
1510         goto leave;
1511       if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
1512         {
1513           err = gpg_error (GPG_ERR_INV_OBJ);
1514           goto leave;
1515         }
1516       totobjlen = objlen + hdrlen;
1517       assert (save_p + totobjlen <= buffer + buflen);
1518       memmove (buffer, save_p, totobjlen);
1519     }
1520
1521   *r_cert = buffer;
1522   buffer = NULL;
1523   *r_certlen = totobjlen;
1524
1525   /* Try to cache it. */
1526   if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
1527     {
1528       memcpy (cdf->image, *r_cert, *r_certlen);
1529       cdf->imagelen = *r_certlen;
1530     }
1531
1532
1533  leave:
1534   xfree (buffer);
1535   return err;
1536 }
1537
1538
1539
1540 /* Handler for the READCERT command.
1541
1542    Read the certificate with id CERTID (as returned by learn_status in
1543    the CERTINFO status lines) and return it in the freshly allocated
1544    buffer to be stored at R_CERT and its length at R_CERTLEN.  A error
1545    code will be returned on failure and R_CERT and R_CERTLEN will be
1546    set to (NULL,0). */
1547 static gpg_error_t
1548 do_readcert (app_t app, const char *certid,
1549              unsigned char **r_cert, size_t *r_certlen)
1550 {
1551   gpg_error_t err;
1552   cdf_object_t cdf;
1553
1554   *r_cert = NULL;
1555   *r_certlen = 0;
1556   err = cdf_object_from_certid (app, certid, &cdf);
1557   if (!err)
1558     err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
1559   return err;
1560 }
1561
1562
1563
1564 /* Implement the GETATTR command.  This is similar to the LEARN
1565    command but returns just one value via the status interface. */
1566 static gpg_error_t
1567 do_getattr (app_t app, ctrl_t ctrl, const char *name)
1568 {
1569   if (!strcmp (name, "$AUTHKEYID"))
1570     {
1571       char *buf, *p;
1572       prkdf_object_t prkdf;
1573
1574       /* We return the ID of the first private key capable of
1575          signing. */
1576       for (prkdf = app->app_local->private_key_info; prkdf;
1577            prkdf = prkdf->next)
1578         if (prkdf->usageflags.sign)
1579           break;
1580       if (prkdf)
1581         {
1582           buf = xtrymalloc (4 + prkdf->objidlen*2 + 1);
1583           if (!buf)
1584             return gpg_error_from_syserror ();
1585           p = stpcpy (buf, "HSM.");
1586           bin2hex (prkdf->objid, prkdf->objidlen, p);
1587
1588           send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
1589           xfree (buf);
1590           return 0;
1591         }
1592     }
1593   else if (!strcmp (name, "$DISPSERIALNO"))
1594     {
1595       send_status_info (ctrl, name, app->serialno, app->serialnolen, NULL, 0);
1596       return 0;
1597     }
1598
1599   return gpg_error (GPG_ERR_INV_NAME);
1600 }
1601
1602
1603
1604 /* Apply PKCS#1 V1.5 padding for signature operation.  The function
1605  * combines padding, digest info and the hash value.  The buffer must
1606  * be allocated by the caller matching the key size.  */
1607 static void
1608 apply_PKCS_padding(const unsigned char *dig, int diglen,
1609                    const unsigned char *prefix, int prefixlen,
1610                    unsigned char *buff, int bufflen)
1611 {
1612   int i, n_ff;
1613
1614   /* Caller must ensure a sufficient buffer.  */
1615   if (diglen + prefixlen + 4 > bufflen)
1616     return;
1617   n_ff = bufflen - diglen - prefixlen - 3;
1618
1619   *buff++ = 0x00;
1620   *buff++ = 0x01;
1621   for (i=0; i < n_ff; i++)
1622     *buff++ = 0xFF;
1623   *buff++ = 0x00;
1624
1625   if (prefix)
1626     memcpy (buff, prefix, prefixlen);
1627   buff += prefixlen;
1628   memcpy (buff, dig, diglen);
1629 }
1630
1631
1632
1633 /* Decode a digest info structure (DI,DILEN) to extract the hash
1634  * value.  The buffer HASH to receive the digest must be provided by
1635  * the caller with HASHLEN pointing to the inbound length.  HASHLEN is
1636  * updated to the outbound length.  */
1637 static int
1638 hash_from_digestinfo (const unsigned char *di, size_t dilen,
1639                       unsigned char *hash, size_t *hashlen)
1640 {
1641   const unsigned char *p,*pp;
1642   size_t n, nn, objlen, hdrlen;
1643   int class, tag, constructed, ndef;
1644   gpg_error_t err;
1645
1646   p = di;
1647   n = dilen;
1648
1649   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1650                           &ndef, &objlen, &hdrlen);
1651   if (!err && (objlen > n || tag != TAG_SEQUENCE))
1652     err = gpg_error (GPG_ERR_INV_OBJ);
1653   if ( err )
1654     return err;
1655
1656   pp = p;
1657   nn = objlen;
1658
1659   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1660                           &ndef, &objlen, &hdrlen);
1661   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1662     err = gpg_error (GPG_ERR_INV_OBJ);
1663   if ( err )
1664     return err;
1665
1666   pp += objlen;
1667   nn -= objlen;
1668
1669   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1670                           &ndef, &objlen, &hdrlen);
1671   if (!err && (objlen > nn || tag != TAG_OCTET_STRING))
1672     err = gpg_error (GPG_ERR_INV_OBJ);
1673   if ( err )
1674     return err;
1675
1676   if (*hashlen < objlen)
1677     return gpg_error (GPG_ERR_TOO_SHORT);
1678   memcpy (hash, pp, objlen);
1679   *hashlen = objlen;
1680   return 0;
1681 }
1682
1683
1684 /* Perform PIN verification
1685  */
1686 static gpg_error_t
1687 verify_pin (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
1688             void *pincb_arg)
1689 {
1690   gpg_error_t err;
1691   pininfo_t pininfo;
1692   char *pinvalue;
1693   char *prompt;
1694   int sw;
1695
1696   sw = apdu_send_simple (app->slot, 0, 0x00, ISO7816_VERIFY, 0x00, 0x81,
1697                          -1, NULL);
1698
1699   if (sw == SW_SUCCESS)
1700     return 0;                   /* PIN already verified */
1701
1702   if (sw == SW_REF_DATA_INV)
1703     {
1704       log_error ("SmartCard-HSM not initialized. Run sc-hsm-tool first\n");
1705       return gpg_error (GPG_ERR_NO_PIN);
1706     }
1707
1708   if (sw == SW_CHV_BLOCKED)
1709     {
1710       log_error ("PIN Blocked\n");
1711       return gpg_error (GPG_ERR_PIN_BLOCKED);
1712     }
1713
1714   memset (&pininfo, 0, sizeof pininfo);
1715   pininfo.fixedlen = 0;
1716   pininfo.minlen = 6;
1717   pininfo.maxlen = 15;
1718
1719   prompt = "||Please enter the PIN";
1720
1721   if (!opt.disable_pinpad
1722       && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo) )
1723     {
1724       err = pincb (pincb_arg, prompt, NULL);
1725       if (err)
1726         {
1727           log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
1728           return err;
1729         }
1730
1731       err = iso7816_verify_kp (app->slot, 0x81, &pininfo);
1732       pincb (pincb_arg, NULL, NULL);  /* Dismiss the prompt. */
1733     }
1734   else
1735     {
1736       err = pincb (pincb_arg, prompt, &pinvalue);
1737       if (err)
1738         {
1739           log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
1740           return err;
1741         }
1742
1743       err = iso7816_verify (app->slot, 0x81, pinvalue, strlen(pinvalue));
1744       xfree (pinvalue);
1745     }
1746   if (err)
1747     {
1748       log_error ("PIN verification failed: %s\n", gpg_strerror (err));
1749       return err;
1750     }
1751   log_debug ("PIN verification succeeded\n");
1752   return err;
1753 }
1754
1755
1756
1757 /* Handler for the PKSIGN command.
1758
1759    Create the signature and return the allocated result in OUTDATA.
1760    If a PIN is required, the PINCB will be used to ask for the PIN;
1761    that callback should return the PIN in an allocated buffer and
1762    store that as the 3rd argument.
1763
1764    The API is somewhat inconsistent: The caller can either supply
1765    a plain hash and the algorithm in hashalgo or a complete
1766    DigestInfo structure. The former is detect by characteristic length
1767    of the provided data (20,28,32,48 or 64 byte).
1768
1769    The function returns the RSA block in the size of the modulus or
1770    the ECDSA signature in X9.62 format (SEQ/INT(r)/INT(s))
1771 */
1772 static gpg_error_t
1773 do_sign (app_t app, const char *keyidstr, int hashalgo,
1774          gpg_error_t (*pincb)(void*, const char *, char **),
1775          void *pincb_arg,
1776          const void *indata, size_t indatalen,
1777          unsigned char **outdata, size_t *outdatalen )
1778 {
1779   static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
1780     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
1781       0x02, 0x01, 0x05, 0x00, 0x04, 0x14  };
1782   static unsigned char sha1_prefix[15] =   /* (1.3.14.3.2.26) */
1783     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1784       0x02, 0x1a, 0x05, 0x00, 0x04, 0x14  };
1785   static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
1786     { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
1787       0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
1788       0x1C  };
1789   static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
1790     { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1791       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
1792       0x00, 0x04, 0x20  };
1793   static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
1794     { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1795       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
1796       0x00, 0x04, 0x30  };
1797   static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
1798     { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1799       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
1800       0x00, 0x04, 0x40  };
1801
1802   gpg_error_t err;
1803   unsigned char cdsblk[256]; /* Raw PKCS#1 V1.5 block with padding
1804                                 (RSA) or hash.  */
1805   prkdf_object_t prkdf;      /* The private key object. */
1806   size_t cdsblklen;
1807   unsigned char algoid;
1808   int sw;
1809
1810   if (!keyidstr || !*keyidstr)
1811     return gpg_error (GPG_ERR_INV_VALUE);
1812
1813   if (indatalen > 124)          /* Limit for 1024 bit key */
1814     return gpg_error (GPG_ERR_INV_VALUE);
1815
1816   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
1817   if (err)
1818     return err;
1819   if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
1820         ||prkdf->usageflags.non_repudiation))
1821     {
1822       log_error ("key %s may not be used for signing\n", keyidstr);
1823       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1824     }
1825
1826   if (prkdf->keytype == KEY_TYPE_RSA)
1827     {
1828       algoid = 0x20;
1829
1830       cdsblklen = prkdf->keysize >> 3;
1831       if (!cdsblklen)
1832         cdsblklen = 256;
1833
1834       if (hashalgo == GCRY_MD_SHA1 && indatalen == 20)
1835         apply_PKCS_padding (indata, indatalen,
1836                             sha1_prefix, sizeof(sha1_prefix),
1837                             cdsblk, cdsblklen);
1838       else if (hashalgo == GCRY_MD_MD5 && indatalen == 20)
1839         apply_PKCS_padding (indata, indatalen,
1840                             rmd160_prefix, sizeof(rmd160_prefix),
1841                             cdsblk, cdsblklen);
1842       else if (hashalgo == GCRY_MD_SHA224 && indatalen == 28)
1843         apply_PKCS_padding (indata, indatalen,
1844                             sha224_prefix, sizeof(sha224_prefix),
1845                             cdsblk, cdsblklen);
1846       else if (hashalgo == GCRY_MD_SHA256 && indatalen == 32)
1847         apply_PKCS_padding (indata, indatalen,
1848                             sha256_prefix, sizeof(sha256_prefix),
1849                             cdsblk, cdsblklen);
1850       else if (hashalgo == GCRY_MD_SHA384 && indatalen == 48)
1851         apply_PKCS_padding (indata, indatalen,
1852                             sha384_prefix, sizeof(sha384_prefix),
1853                             cdsblk, cdsblklen);
1854       else if (hashalgo == GCRY_MD_SHA512 && indatalen == 64)
1855         apply_PKCS_padding (indata, indatalen,
1856                             sha512_prefix, sizeof(sha512_prefix),
1857                             cdsblk, cdsblklen);
1858       else  /* Assume it's already a digest info or TLS_MD5SHA1 */
1859         apply_PKCS_padding (indata, indatalen, NULL, 0, cdsblk, cdsblklen);
1860     }
1861   else
1862     {
1863       algoid = 0x70;
1864       if (indatalen != 20 && indatalen != 28 && indatalen != 32
1865           && indatalen != 48 && indatalen != 64)
1866         {
1867           cdsblklen = sizeof(cdsblk);
1868           err = hash_from_digestinfo (indata, indatalen, cdsblk, &cdsblklen);
1869           if (err)
1870             {
1871               log_error ("DigestInfo invalid: %s\n", gpg_strerror (err));
1872               return err;
1873             }
1874         }
1875       else
1876         {
1877           memcpy (cdsblk, indata, indatalen);
1878           cdsblklen = indatalen;
1879         }
1880     }
1881
1882   err = verify_pin (app, pincb, pincb_arg);
1883   if (err)
1884     return err;
1885
1886   sw = apdu_send_le (app->slot, 1, 0x80, 0x68, prkdf->key_reference, algoid,
1887                      cdsblklen, cdsblk, 0, outdata, outdatalen);
1888   return iso7816_map_sw (sw);
1889 }
1890
1891
1892
1893 /* Handler for the PKAUTH command.
1894
1895    This is basically the same as the PKSIGN command but we first check
1896    that the requested key is suitable for authentication; that is, it
1897    must match the criteria used for the attribute $AUTHKEYID.  See
1898    do_sign for calling conventions; there is no HASHALGO, though. */
1899 static gpg_error_t
1900 do_auth (app_t app, const char *keyidstr,
1901          gpg_error_t (*pincb)(void*, const char *, char **),
1902          void *pincb_arg,
1903          const void *indata, size_t indatalen,
1904          unsigned char **outdata, size_t *outdatalen )
1905 {
1906   gpg_error_t err;
1907   prkdf_object_t prkdf;
1908   int algo;
1909
1910   if (!keyidstr || !*keyidstr)
1911     return gpg_error (GPG_ERR_INV_VALUE);
1912
1913   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
1914   if (err)
1915     return err;
1916   if (!prkdf->usageflags.sign)
1917     {
1918       log_error ("key %s may not be used for authentication\n", keyidstr);
1919       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1920     }
1921
1922   algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
1923   return do_sign (app, keyidstr, algo, pincb, pincb_arg,
1924                   indata, indatalen, outdata, outdatalen);
1925 }
1926
1927
1928
1929 /* Check PKCS#1 V1.5 padding and extract plain text.  The function
1930  * allocates a buffer for the plain text.  The caller must release the
1931  * buffer.  */
1932 static gpg_error_t
1933 strip_PKCS15_padding(unsigned char *src, int srclen, unsigned char **dst,
1934                      size_t *dstlen)
1935 {
1936   unsigned char *p;
1937
1938   if (srclen < 2)
1939     return gpg_error (GPG_ERR_DECRYPT_FAILED);
1940   if (*src++ != 0x00)
1941     return gpg_error (GPG_ERR_DECRYPT_FAILED);
1942   if (*src++ != 0x02)
1943     return gpg_error (GPG_ERR_DECRYPT_FAILED);
1944   srclen -= 2;
1945   while ((srclen > 0) && *src)
1946     {
1947       src++;
1948       srclen--;
1949     }
1950
1951   if (srclen < 2)
1952     return gpg_error (GPG_ERR_DECRYPT_FAILED);
1953
1954   src++;
1955   srclen--;
1956
1957   p = xtrymalloc (srclen);
1958   if (!p)
1959     return gpg_error_from_syserror ();
1960
1961   memcpy (p, src, srclen);
1962   *dst = p;
1963   *dstlen = srclen;
1964
1965   return 0;
1966 }
1967
1968
1969 /* Decrypt a PKCS#1 V1.5 formatted cryptogram using the referenced
1970    key.  */
1971 static gpg_error_t
1972 do_decipher (app_t app, const char *keyidstr,
1973              gpg_error_t (*pincb)(void*, const char *, char **),
1974              void *pincb_arg,
1975              const void *indata, size_t indatalen,
1976              unsigned char **outdata, size_t *outdatalen,
1977              unsigned int *r_info)
1978 {
1979   gpg_error_t err;
1980   unsigned char p1blk[256]; /* Enciphered P1 block */
1981   prkdf_object_t prkdf;     /* The private key object. */
1982   unsigned char *rspdata;
1983   size_t rspdatalen;
1984   size_t p1blklen;
1985   int sw;
1986
1987   if (!keyidstr || !*keyidstr || !indatalen)
1988     return gpg_error (GPG_ERR_INV_VALUE);
1989
1990   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
1991   if (err)
1992     return err;
1993   if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
1994     {
1995       log_error ("key %s may not be used for deciphering\n", keyidstr);
1996       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1997     }
1998
1999   if (prkdf->keytype != KEY_TYPE_RSA)
2000     return gpg_error (GPG_ERR_NOT_SUPPORTED);
2001
2002   p1blklen = prkdf->keysize >> 3;
2003   if (!p1blklen)
2004     p1blklen = 256;
2005
2006   /* The input may be shorter (due to MPIs not storing leading zeroes)
2007      or longer than the block size.  We put INDATA right aligned into
2008      the buffer.  If INDATA is longer than the block size we truncate
2009      it on the left. */
2010   memset (p1blk, 0, sizeof(p1blk));
2011   if (indatalen > p1blklen)
2012     memcpy (p1blk, (unsigned char *)indata + (indatalen - p1blklen), p1blklen);
2013   else
2014     memcpy (p1blk + (p1blklen - indatalen), indata, indatalen);
2015
2016
2017   err = verify_pin(app, pincb, pincb_arg);
2018   if (err)
2019     return err;
2020
2021   sw = apdu_send_le (app->slot, 1, 0x80, 0x62, prkdf->key_reference, 0x21,
2022                      p1blklen, p1blk, 0, &rspdata, &rspdatalen);
2023   err = iso7816_map_sw (sw);
2024   if (err)
2025     {
2026       log_error ("Decrypt failed: %s\n", gpg_strerror (err));
2027       return err;
2028     }
2029
2030   err = strip_PKCS15_padding (rspdata, rspdatalen, outdata, outdatalen);
2031   xfree (rspdata);
2032
2033   if (!err)
2034     *r_info |= APP_DECIPHER_INFO_NOPAD;
2035
2036   return err;
2037 }
2038
2039
2040
2041 /*
2042  * Select the SmartCard-HSM application on the card in SLOT.
2043  */
2044 gpg_error_t
2045 app_select_sc_hsm (app_t app)
2046 {
2047   int slot = app->slot;
2048   int rc;
2049
2050   rc = iso7816_select_application (slot, sc_hsm_aid, sizeof sc_hsm_aid, 0);
2051   if (!rc)
2052     {
2053       app->apptype = "SC-HSM";
2054
2055       app->app_local = xtrycalloc (1, sizeof *app->app_local);
2056       if (!app->app_local)
2057         {
2058           rc = gpg_error_from_syserror ();
2059           goto leave;
2060         }
2061
2062       rc = read_meta (app);
2063       if (rc)
2064         goto leave;
2065
2066       app->fnc.deinit = do_deinit;
2067       app->fnc.learn_status = do_learn_status;
2068       app->fnc.readcert = do_readcert;
2069       app->fnc.getattr = do_getattr;
2070       app->fnc.setattr = NULL;
2071       app->fnc.genkey = NULL;
2072       app->fnc.sign = do_sign;
2073       app->fnc.auth = do_auth;
2074       app->fnc.decipher = do_decipher;
2075       app->fnc.change_pin = NULL;
2076       app->fnc.check_pin = NULL;
2077
2078     leave:
2079       if (rc)
2080         do_deinit (app);
2081    }
2082
2083   return rc;
2084 }