2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / card.c
blob7a41ab7bbfe34847d4042b472c0baf32ec86b682
1 /* card.c - SCdaemon card functions
2 * Copyright (C) 2002 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
29 #ifdef HAVE_OPENSC
30 #include <opensc/pkcs15.h>
31 #endif
33 #include "scdaemon.h"
34 #include <ksba.h>
36 #include "card-common.h"
38 /* Map the SC error codes to the GNUPG ones */
39 gpg_error_t
40 map_sc_err (int rc)
42 gpg_err_code_t e;
44 switch (rc)
46 case 0: e = 0; break;
47 #ifdef HAVE_OPENSC
48 case SC_ERROR_NOT_SUPPORTED: e = GPG_ERR_NOT_SUPPORTED; break;
49 case SC_ERROR_PKCS15_APP_NOT_FOUND: e = GPG_ERR_NO_PKCS15_APP; break;
50 case SC_ERROR_OUT_OF_MEMORY: e = GPG_ERR_ENOMEM; break;
51 case SC_ERROR_CARD_NOT_PRESENT: e = GPG_ERR_CARD_NOT_PRESENT; break;
52 case SC_ERROR_CARD_REMOVED: e = GPG_ERR_CARD_REMOVED; break;
53 case SC_ERROR_INVALID_CARD: e = GPG_ERR_INV_CARD; break;
54 #endif
55 default: e = GPG_ERR_CARD; break;
57 /* It does not make much sense to further distingusih the error
58 source between OpenSC and SCD. Thus we use SCD as source
59 here. */
60 return gpg_err_make (GPG_ERR_SOURCE_SCD, e);
63 /* Get the keygrip from CERT, return 0 on success */
64 int
65 card_help_get_keygrip (ksba_cert_t cert, unsigned char *array)
67 gcry_sexp_t s_pkey;
68 int rc;
69 ksba_sexp_t p;
70 size_t n;
72 p = ksba_cert_get_public_key (cert);
73 if (!p)
74 return -1; /* oops */
75 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
76 if (!n)
77 return -1; /* libksba did not return a proper S-expression */
78 rc = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
79 xfree (p);
80 if (rc)
81 return -1; /* can't parse that S-expression */
82 array = gcry_pk_get_keygrip (s_pkey, array);
83 gcry_sexp_release (s_pkey);
84 if (!array)
85 return -1; /* failed to calculate the keygrip */
86 return 0;
95 /* Create a new context for the card and figures out some basic
96 information of the card. Detects whether a PKCS_15 application is
97 stored.
99 Common errors: GPG_ERR_CARD_NOT_PRESENT */
101 card_open (CARD *rcard)
103 #ifdef HAVE_OPENSC
104 CARD card;
105 int rc;
107 if (opt.disable_opensc)
108 return gpg_error (GPG_ERR_NOT_SUPPORTED);
110 card = xtrycalloc (1, sizeof *card);
111 if (!card)
112 return gpg_error (gpg_err_code_from_errno (errno));
113 card->reader = 0;
115 rc = sc_establish_context (&card->ctx, "scdaemon");
116 if (rc)
118 log_error ("failed to establish SC context: %s\n", sc_strerror (rc));
119 rc = map_sc_err (rc);
120 goto leave;
122 if (card->reader >= card->ctx->reader_count)
124 log_error ("no card reader available\n");
125 rc = gpg_error (GPG_ERR_CARD);
126 goto leave;
128 card->ctx->error_file = log_get_stream ();
129 card->ctx->debug = opt.debug_sc;
130 card->ctx->debug_file = log_get_stream ();
132 if (sc_detect_card_presence (card->ctx->reader[card->reader], 0) != 1)
134 rc = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
135 goto leave;
138 rc = sc_connect_card (card->ctx->reader[card->reader], 0, &card->scard);
139 if (rc)
141 log_error ("failed to connect card in reader %d: %s\n",
142 card->reader, sc_strerror (rc));
143 rc = map_sc_err (rc);
144 goto leave;
146 if (opt.verbose)
147 log_info ("connected to card in reader %d using driver `%s'\n",
148 card->reader, card->scard->driver->name);
150 rc = sc_lock (card->scard);
151 if (rc)
153 log_error ("can't lock card in reader %d: %s\n",
154 card->reader, sc_strerror (rc));
155 rc = map_sc_err (rc);
156 goto leave;
160 leave:
161 if (rc)
162 card_close (card);
163 else
164 *rcard = card;
166 return rc;
167 #else
168 return gpg_error (GPG_ERR_NOT_SUPPORTED);
169 #endif
173 /* Close a card and release all resources */
174 void
175 card_close (CARD card)
177 if (card)
179 #ifdef HAVE_OPENSC
180 if (card->p15card)
182 sc_pkcs15_unbind (card->p15card);
183 card->p15card = NULL;
185 if (card->p15priv)
186 p15_release_private_data (card);
187 if (card->scard)
189 sc_unlock (card->scard);
190 sc_disconnect_card (card->scard, 0);
191 card->scard = NULL;
193 if (card->ctx)
195 sc_release_context (card->ctx);
196 card->ctx = NULL;
198 #endif
199 xfree (card);
203 /* Locate a simple TLV encoded data object in BUFFER of LENGTH and
204 return a pointer to value as well as its length in NBYTES. Return
205 NULL if it was not found. Note, that the function does not check
206 whether the value fits into the provided buffer. */
207 #ifdef HAVE_OPENSC
208 static const char *
209 find_simple_tlv (const unsigned char *buffer, size_t length,
210 int tag, size_t *nbytes)
212 const char *s = buffer;
213 size_t n = length;
214 size_t len;
216 for (;;)
218 buffer = s;
219 if (n < 2)
220 return NULL; /* buffer too short for tag and length. */
221 len = s[1];
222 s += 2; n -= 2;
223 if (len == 255)
225 if (n < 2)
226 return NULL; /* we expected 2 more bytes with the length. */
227 len = (s[0] << 8) | s[1];
228 s += 2; n -= 2;
230 if (*buffer == tag)
232 *nbytes = len;
233 return s;
235 if (len > n)
236 return NULL; /* buffer too short to skip to the next tag. */
237 s += len; n -= len;
240 #endif /*HAVE_OPENSC*/
242 /* Find the ICC Serial Number within the provided BUFFER of LENGTH
243 (which should contain the GDO file) and return it as a hex encoded
244 string and allocated string in SERIAL. Return an error code when
245 the ICCSN was not found. */
246 #ifdef HAVE_OPENSC
247 static int
248 find_iccsn (const unsigned char *buffer, size_t length, char **serial)
250 size_t n;
251 const unsigned char *s;
252 char *p;
254 s = find_simple_tlv (buffer, length, 0x5A, &n);
255 if (!s)
256 return gpg_error (GPG_ERR_CARD);
257 length -= s - buffer;
258 if (n > length)
260 /* Oops, it does not fit into the buffer. This is an invalid
261 encoding (or the buffer is too short. However, I have some
262 test cards with such an invalid encoding and therefore I use
263 this ugly workaround to return something I can further
264 experiment with. */
265 if (n == 0x0D && length+1 == n)
267 log_debug ("enabling BMI testcard workaround\n");
268 n--;
270 else
271 return gpg_error (GPG_ERR_CARD); /* Bad encoding; does
272 not fit into buffer. */
274 if (!n)
275 return gpg_error (GPG_ERR_CARD); /* Well, that is too short. */
277 *serial = p = xtrymalloc (2*n+1);
278 if (!*serial)
279 return gpg_error (gpg_err_code_from_errno (errno));
280 for (; n; n--, p += 2, s++)
281 sprintf (p, "%02X", *s);
282 *p = 0;
283 return 0;
285 #endif /*HAVE_OPENSC*/
287 /* Retrieve the serial number and the time of the last update of the
288 card. The serial number is returned as a malloced string (hex
289 encoded) in SERIAL and the time of update is returned in STAMP.
290 If no update time is available the returned value is 0. The serial
291 is mandatory for a PKCS_15 application and an error will be
292 returned if this value is not availbale. For non-PKCS-15 cards a
293 serial number is constructed by other means. Caller must free
294 SERIAL unless the function returns an error. */
295 int
296 card_get_serial_and_stamp (CARD card, char **serial, time_t *stamp)
298 #ifdef HAVE_OPENSC
299 int rc;
300 struct sc_path path;
301 struct sc_file *file;
302 unsigned char buf[256];
303 int buflen;
304 #endif
306 if (!card || !serial || !stamp)
307 return gpg_error (GPG_ERR_INV_VALUE);
309 *serial = NULL;
310 *stamp = 0; /* not available */
312 #ifdef HAVE_OPENSC
313 if (!card->fnc.initialized)
315 card->fnc.initialized = 1;
316 /* The first use of this card tries to figure out the type of the card
317 and sets up the function pointers. */
318 rc = sc_pkcs15_bind (card->scard, &card->p15card);
319 if (rc)
321 if (rc != SC_ERROR_PKCS15_APP_NOT_FOUND)
322 log_error ("binding of existing PKCS-15 failed in reader %d: %s\n",
323 card->reader, sc_strerror (rc));
324 card->p15card = NULL;
325 rc = 0;
327 if (card->p15card)
328 card_p15_bind (card);
329 card->fnc.initialized = 1;
333 /* We should lookup the iso 7812-1 and 8583-3 - argh ISO
334 practice is suppressing innovation - IETF rules! So we
335 always get the serialnumber from the 2F02 GDO file. */
336 /* FIXME: in case we can't parse the 2F02 EF and we have a P15 card,
337 we should get the serial number from the respective P15 file */
338 sc_format_path ("3F002F02", &path);
339 rc = sc_select_file (card->scard, &path, &file);
340 if (rc)
342 log_error ("sc_select_file failed: %s\n", sc_strerror (rc));
343 return gpg_error (GPG_ERR_CARD);
345 if (file->type != SC_FILE_TYPE_WORKING_EF
346 || file->ef_structure != SC_FILE_EF_TRANSPARENT)
348 log_error ("wrong type or structure of GDO file\n");
349 sc_file_free (file);
350 return gpg_error (GPG_ERR_CARD);
353 if (!file->size || file->size >= DIM(buf) )
354 { /* FIXME: Use a real parser */
355 log_error ("unsupported size of GDO file (%d)\n", file->size);
356 sc_file_free (file);
357 return gpg_error (GPG_ERR_CARD);
359 buflen = file->size;
361 rc = sc_read_binary (card->scard, 0, buf, buflen, 0);
362 sc_file_free (file);
363 if (rc < 0)
365 log_error ("error reading GDO file: %s\n", sc_strerror (rc));
366 return gpg_error (GPG_ERR_CARD);
368 if (rc != buflen)
370 log_error ("short read on GDO file\n");
371 return gpg_error (GPG_ERR_CARD);
374 rc = find_iccsn (buf, buflen, serial);
375 if (gpg_err_code (rc) == GPG_ERR_CARD)
376 log_error ("invalid structure of GDO file\n");
377 if (!rc && card->p15card && !strcmp (*serial, "D27600000000000000000000"))
378 { /* This is a German card with a silly serial number. Try to get
379 the serial number from the EF(TokenInfo). We indicate such a
380 serial number by the using the prefix: "FF0100". */
381 const char *efser = card->p15card->serial_number;
382 char *p;
384 if (!efser)
385 efser = "";
387 xfree (*serial);
388 *serial = NULL;
389 p = xtrymalloc (strlen (efser) + 7);
390 if (!p)
391 rc = gpg_error (gpg_err_code_from_errno (errno));
392 else
394 strcpy (p, "FF0100");
395 strcpy (p+6, efser);
396 *serial = p;
399 else if (!rc && **serial == 'F' && (*serial)[1] == 'F')
400 { /* The serial number starts with our special prefix. This
401 requires that we put our default prefix "FF0000" in front. */
402 char *p = xtrymalloc (strlen (*serial) + 7);
403 if (!p)
405 xfree (*serial);
406 *serial = NULL;
407 rc = gpg_error (gpg_err_code_from_errno (errno));
409 else
411 strcpy (p, "FF0000");
412 strcpy (p+6, *serial);
413 xfree (*serial);
414 *serial = p;
417 return rc;
418 #else
419 return gpg_error (GPG_ERR_NOT_SUPPORTED);
420 #endif
424 /* Enumerate all keypairs on the card and return the Keygrip as well
425 as the internal identification of the key. KEYGRIP must be a
426 caller provided buffer with a size of 20 bytes which will receive
427 the KEYGRIP of the keypair. If KEYID is not NULL, it returns the
428 ID field of the key in allocated memory; this is a string without
429 spaces. The function returns -1 when all keys have been
430 enumerated. Note that the error GPG_ERR_MISSING_CERTIFICATE may be
431 returned if there is just the private key but no public key (ie.e a
432 certificate) available. Applications might want to continue
433 enumerating after this error.*/
435 card_enum_keypairs (CARD card, int idx,
436 unsigned char *keygrip,
437 char **keyid)
439 int rc;
441 if (keyid)
442 *keyid = NULL;
444 if (!card || !keygrip)
445 return gpg_error (GPG_ERR_INV_VALUE);
446 if (idx < 0)
447 return gpg_error (GPG_ERR_INV_INDEX);
448 if (!card->fnc.initialized)
449 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
450 if (!card->fnc.enum_keypairs)
451 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
452 rc = card->fnc.enum_keypairs (card, idx, keygrip, keyid);
453 if (opt.verbose)
454 log_info ("card operation enum_keypairs result: %s\n",
455 gpg_strerror (rc));
456 return rc;
460 /* Enumerate all trusted certificates available on the card, return
461 their ID in CERT and the type in CERTTYPE. Types of certificates
462 are:
463 0 := Unknown
464 100 := Regular X.509 cert
465 101 := Trusted X.509 cert
466 102 := Useful X.509 cert
467 110 := Root CA cert (DINSIG)
470 card_enum_certs (CARD card, int idx, char **certid, int *certtype)
472 int rc;
474 if (certid)
475 *certid = NULL;
477 if (!card)
478 return gpg_error (GPG_ERR_INV_VALUE);
479 if (idx < 0)
480 return gpg_error (GPG_ERR_INV_INDEX);
481 if (!card->fnc.initialized)
482 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
483 if (!card->fnc.enum_certs)
484 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
485 rc = card->fnc.enum_certs (card, idx, certid, certtype);
486 if (opt.verbose)
487 log_info ("card operation enum_certs result: %s\n",
488 gpg_strerror (rc));
489 return rc;
494 /* Read the certificate identified by CERTIDSTR which is the
495 hexadecimal encoded ID of the certificate, prefixed with the string
496 "3F005015.". The certificate is return in DER encoded form in CERT
497 and NCERT. */
499 card_read_cert (CARD card, const char *certidstr,
500 unsigned char **cert, size_t *ncert)
502 int rc;
504 if (!card || !certidstr || !cert || !ncert)
505 return gpg_error (GPG_ERR_INV_VALUE);
506 if (!card->fnc.initialized)
507 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
508 if (!card->fnc.read_cert)
509 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
510 rc = card->fnc.read_cert (card, certidstr, cert, ncert);
511 if (opt.verbose)
512 log_info ("card operation read_cert result: %s\n", gpg_strerror (rc));
513 return rc;
517 /* Create the signature and return the allocated result in OUTDATA.
518 If a PIN is required the PINCB will be used to ask for the PIN; it
519 should return the PIN in an allocated buffer and put it into PIN. */
520 int
521 card_sign (CARD card, const char *keyidstr, int hashalgo,
522 int (pincb)(void*, const char *, char **),
523 void *pincb_arg,
524 const void *indata, size_t indatalen,
525 unsigned char **outdata, size_t *outdatalen )
527 int rc;
529 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
530 return gpg_error (GPG_ERR_INV_VALUE);
531 if (!card->fnc.initialized)
532 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
533 if (!card->fnc.sign)
534 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
535 rc = card->fnc.sign (card, keyidstr, hashalgo,
536 pincb, pincb_arg,
537 indata, indatalen,
538 outdata, outdatalen);
539 if (opt.verbose)
540 log_info ("card operation sign result: %s\n", gpg_strerror (rc));
541 return rc;
545 /* Create the signature and return the allocated result in OUTDATA.
546 If a PIN is required the PINCB will be used to ask for the PIN; it
547 should return the PIN in an allocated buffer and put it into PIN. */
548 int
549 card_decipher (CARD card, const char *keyidstr,
550 int (pincb)(void*, const char *, char **),
551 void *pincb_arg,
552 const void *indata, size_t indatalen,
553 unsigned char **outdata, size_t *outdatalen )
555 int rc;
557 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
558 return gpg_error (GPG_ERR_INV_VALUE);
559 if (!card->fnc.initialized)
560 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
561 if (!card->fnc.decipher)
562 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
563 rc = card->fnc.decipher (card, keyidstr,
564 pincb, pincb_arg,
565 indata, indatalen,
566 outdata, outdatalen);
567 if (opt.verbose)
568 log_info ("card operation decipher result: %s\n", gpg_strerror (rc));
569 return rc;