2007-09-14 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / card.c
bloba0213483f6719597a781a50bb8f7fadef90e7132
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 3 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, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
27 #ifdef HAVE_OPENSC
28 #include <opensc/pkcs15.h>
29 #endif
31 #include "scdaemon.h"
32 #include <ksba.h>
34 #include "card-common.h"
36 /* Map the SC error codes to the GNUPG ones */
37 gpg_error_t
38 map_sc_err (int rc)
40 gpg_err_code_t e;
42 switch (rc)
44 case 0: e = 0; break;
45 #ifdef HAVE_OPENSC
46 case SC_ERROR_NOT_SUPPORTED: e = GPG_ERR_NOT_SUPPORTED; break;
47 case SC_ERROR_PKCS15_APP_NOT_FOUND: e = GPG_ERR_NO_PKCS15_APP; break;
48 case SC_ERROR_OUT_OF_MEMORY: e = GPG_ERR_ENOMEM; break;
49 case SC_ERROR_CARD_NOT_PRESENT: e = GPG_ERR_CARD_NOT_PRESENT; break;
50 case SC_ERROR_CARD_REMOVED: e = GPG_ERR_CARD_REMOVED; break;
51 case SC_ERROR_INVALID_CARD: e = GPG_ERR_INV_CARD; break;
52 #endif
53 default: e = GPG_ERR_CARD; break;
55 /* It does not make much sense to further distingusih the error
56 source between OpenSC and SCD. Thus we use SCD as source
57 here. */
58 return gpg_err_make (GPG_ERR_SOURCE_SCD, e);
61 /* Get the keygrip from CERT, return 0 on success */
62 int
63 card_help_get_keygrip (ksba_cert_t cert, unsigned char *array)
65 gcry_sexp_t s_pkey;
66 int rc;
67 ksba_sexp_t p;
68 size_t n;
70 p = ksba_cert_get_public_key (cert);
71 if (!p)
72 return -1; /* oops */
73 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
74 if (!n)
75 return -1; /* libksba did not return a proper S-expression */
76 rc = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
77 xfree (p);
78 if (rc)
79 return -1; /* can't parse that S-expression */
80 array = gcry_pk_get_keygrip (s_pkey, array);
81 gcry_sexp_release (s_pkey);
82 if (!array)
83 return -1; /* failed to calculate the keygrip */
84 return 0;
93 /* Create a new context for the card and figures out some basic
94 information of the card. Detects whether a PKCS_15 application is
95 stored.
97 Common errors: GPG_ERR_CARD_NOT_PRESENT */
98 int
99 card_open (CARD *rcard)
101 #ifdef HAVE_OPENSC
102 CARD card;
103 int rc;
105 if (opt.disable_opensc)
106 return gpg_error (GPG_ERR_NOT_SUPPORTED);
108 card = xtrycalloc (1, sizeof *card);
109 if (!card)
110 return gpg_error (gpg_err_code_from_errno (errno));
111 card->reader = 0;
113 rc = sc_establish_context (&card->ctx, "scdaemon");
114 if (rc)
116 log_error ("failed to establish SC context: %s\n", sc_strerror (rc));
117 rc = map_sc_err (rc);
118 goto leave;
120 if (card->reader >= card->ctx->reader_count)
122 log_error ("no card reader available\n");
123 rc = gpg_error (GPG_ERR_CARD);
124 goto leave;
126 card->ctx->error_file = log_get_stream ();
127 card->ctx->debug = opt.debug_sc;
128 card->ctx->debug_file = log_get_stream ();
130 if (sc_detect_card_presence (card->ctx->reader[card->reader], 0) != 1)
132 rc = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
133 goto leave;
136 rc = sc_connect_card (card->ctx->reader[card->reader], 0, &card->scard);
137 if (rc)
139 log_error ("failed to connect card in reader %d: %s\n",
140 card->reader, sc_strerror (rc));
141 rc = map_sc_err (rc);
142 goto leave;
144 if (opt.verbose)
145 log_info ("connected to card in reader %d using driver `%s'\n",
146 card->reader, card->scard->driver->name);
148 rc = sc_lock (card->scard);
149 if (rc)
151 log_error ("can't lock card in reader %d: %s\n",
152 card->reader, sc_strerror (rc));
153 rc = map_sc_err (rc);
154 goto leave;
158 leave:
159 if (rc)
160 card_close (card);
161 else
162 *rcard = card;
164 return rc;
165 #else
166 return gpg_error (GPG_ERR_NOT_SUPPORTED);
167 #endif
171 /* Close a card and release all resources */
172 void
173 card_close (CARD card)
175 if (card)
177 #ifdef HAVE_OPENSC
178 if (card->p15card)
180 sc_pkcs15_unbind (card->p15card);
181 card->p15card = NULL;
183 if (card->p15priv)
184 p15_release_private_data (card);
185 if (card->scard)
187 sc_unlock (card->scard);
188 sc_disconnect_card (card->scard, 0);
189 card->scard = NULL;
191 if (card->ctx)
193 sc_release_context (card->ctx);
194 card->ctx = NULL;
196 #endif
197 xfree (card);
201 /* Locate a simple TLV encoded data object in BUFFER of LENGTH and
202 return a pointer to value as well as its length in NBYTES. Return
203 NULL if it was not found. Note, that the function does not check
204 whether the value fits into the provided buffer. */
205 #ifdef HAVE_OPENSC
206 static const char *
207 find_simple_tlv (const unsigned char *buffer, size_t length,
208 int tag, size_t *nbytes)
210 const char *s = buffer;
211 size_t n = length;
212 size_t len;
214 for (;;)
216 buffer = s;
217 if (n < 2)
218 return NULL; /* buffer too short for tag and length. */
219 len = s[1];
220 s += 2; n -= 2;
221 if (len == 255)
223 if (n < 2)
224 return NULL; /* we expected 2 more bytes with the length. */
225 len = (s[0] << 8) | s[1];
226 s += 2; n -= 2;
228 if (*buffer == tag)
230 *nbytes = len;
231 return s;
233 if (len > n)
234 return NULL; /* buffer too short to skip to the next tag. */
235 s += len; n -= len;
238 #endif /*HAVE_OPENSC*/
240 /* Find the ICC Serial Number within the provided BUFFER of LENGTH
241 (which should contain the GDO file) and return it as a hex encoded
242 string and allocated string in SERIAL. Return an error code when
243 the ICCSN was not found. */
244 #ifdef HAVE_OPENSC
245 static int
246 find_iccsn (const unsigned char *buffer, size_t length, char **serial)
248 size_t n;
249 const unsigned char *s;
250 char *p;
252 s = find_simple_tlv (buffer, length, 0x5A, &n);
253 if (!s)
254 return gpg_error (GPG_ERR_CARD);
255 length -= s - buffer;
256 if (n > length)
258 /* Oops, it does not fit into the buffer. This is an invalid
259 encoding (or the buffer is too short. However, I have some
260 test cards with such an invalid encoding and therefore I use
261 this ugly workaround to return something I can further
262 experiment with. */
263 if (n == 0x0D && length+1 == n)
265 log_debug ("enabling BMI testcard workaround\n");
266 n--;
268 else
269 return gpg_error (GPG_ERR_CARD); /* Bad encoding; does
270 not fit into buffer. */
272 if (!n)
273 return gpg_error (GPG_ERR_CARD); /* Well, that is too short. */
275 *serial = p = xtrymalloc (2*n+1);
276 if (!*serial)
277 return gpg_error (gpg_err_code_from_errno (errno));
278 for (; n; n--, p += 2, s++)
279 sprintf (p, "%02X", *s);
280 *p = 0;
281 return 0;
283 #endif /*HAVE_OPENSC*/
285 /* Retrieve the serial number and the time of the last update of the
286 card. The serial number is returned as a malloced string (hex
287 encoded) in SERIAL and the time of update is returned in STAMP.
288 If no update time is available the returned value is 0. The serial
289 is mandatory for a PKCS_15 application and an error will be
290 returned if this value is not availbale. For non-PKCS-15 cards a
291 serial number is constructed by other means. Caller must free
292 SERIAL unless the function returns an error. */
293 int
294 card_get_serial_and_stamp (CARD card, char **serial, time_t *stamp)
296 #ifdef HAVE_OPENSC
297 int rc;
298 struct sc_path path;
299 struct sc_file *file;
300 unsigned char buf[256];
301 int buflen;
302 #endif
304 if (!card || !serial || !stamp)
305 return gpg_error (GPG_ERR_INV_VALUE);
307 *serial = NULL;
308 *stamp = 0; /* not available */
310 #ifdef HAVE_OPENSC
311 if (!card->fnc.initialized)
313 card->fnc.initialized = 1;
314 /* The first use of this card tries to figure out the type of the card
315 and sets up the function pointers. */
316 rc = sc_pkcs15_bind (card->scard, &card->p15card);
317 if (rc)
319 if (rc != SC_ERROR_PKCS15_APP_NOT_FOUND)
320 log_error ("binding of existing PKCS-15 failed in reader %d: %s\n",
321 card->reader, sc_strerror (rc));
322 card->p15card = NULL;
323 rc = 0;
325 if (card->p15card)
326 card_p15_bind (card);
327 card->fnc.initialized = 1;
331 /* We should lookup the iso 7812-1 and 8583-3 - argh ISO
332 practice is suppressing innovation - IETF rules! So we
333 always get the serialnumber from the 2F02 GDO file. */
334 /* FIXME: in case we can't parse the 2F02 EF and we have a P15 card,
335 we should get the serial number from the respective P15 file */
336 sc_format_path ("3F002F02", &path);
337 rc = sc_select_file (card->scard, &path, &file);
338 if (rc)
340 log_error ("sc_select_file failed: %s\n", sc_strerror (rc));
341 return gpg_error (GPG_ERR_CARD);
343 if (file->type != SC_FILE_TYPE_WORKING_EF
344 || file->ef_structure != SC_FILE_EF_TRANSPARENT)
346 log_error ("wrong type or structure of GDO file\n");
347 sc_file_free (file);
348 return gpg_error (GPG_ERR_CARD);
351 if (!file->size || file->size >= DIM(buf) )
352 { /* FIXME: Use a real parser */
353 log_error ("unsupported size of GDO file (%d)\n", file->size);
354 sc_file_free (file);
355 return gpg_error (GPG_ERR_CARD);
357 buflen = file->size;
359 rc = sc_read_binary (card->scard, 0, buf, buflen, 0);
360 sc_file_free (file);
361 if (rc < 0)
363 log_error ("error reading GDO file: %s\n", sc_strerror (rc));
364 return gpg_error (GPG_ERR_CARD);
366 if (rc != buflen)
368 log_error ("short read on GDO file\n");
369 return gpg_error (GPG_ERR_CARD);
372 rc = find_iccsn (buf, buflen, serial);
373 if (gpg_err_code (rc) == GPG_ERR_CARD)
374 log_error ("invalid structure of GDO file\n");
375 if (!rc && card->p15card && !strcmp (*serial, "D27600000000000000000000"))
376 { /* This is a German card with a silly serial number. Try to get
377 the serial number from the EF(TokenInfo). We indicate such a
378 serial number by the using the prefix: "FF0100". */
379 const char *efser = card->p15card->serial_number;
380 char *p;
382 if (!efser)
383 efser = "";
385 xfree (*serial);
386 *serial = NULL;
387 p = xtrymalloc (strlen (efser) + 7);
388 if (!p)
389 rc = gpg_error (gpg_err_code_from_errno (errno));
390 else
392 strcpy (p, "FF0100");
393 strcpy (p+6, efser);
394 *serial = p;
397 else if (!rc && **serial == 'F' && (*serial)[1] == 'F')
398 { /* The serial number starts with our special prefix. This
399 requires that we put our default prefix "FF0000" in front. */
400 char *p = xtrymalloc (strlen (*serial) + 7);
401 if (!p)
403 xfree (*serial);
404 *serial = NULL;
405 rc = gpg_error (gpg_err_code_from_errno (errno));
407 else
409 strcpy (p, "FF0000");
410 strcpy (p+6, *serial);
411 xfree (*serial);
412 *serial = p;
415 return rc;
416 #else
417 return gpg_error (GPG_ERR_NOT_SUPPORTED);
418 #endif
422 /* Enumerate all keypairs on the card and return the Keygrip as well
423 as the internal identification of the key. KEYGRIP must be a
424 caller provided buffer with a size of 20 bytes which will receive
425 the KEYGRIP of the keypair. If KEYID is not NULL, it returns the
426 ID field of the key in allocated memory; this is a string without
427 spaces. The function returns -1 when all keys have been
428 enumerated. Note that the error GPG_ERR_MISSING_CERTIFICATE may be
429 returned if there is just the private key but no public key (ie.e a
430 certificate) available. Applications might want to continue
431 enumerating after this error.*/
433 card_enum_keypairs (CARD card, int idx,
434 unsigned char *keygrip,
435 char **keyid)
437 int rc;
439 if (keyid)
440 *keyid = NULL;
442 if (!card || !keygrip)
443 return gpg_error (GPG_ERR_INV_VALUE);
444 if (idx < 0)
445 return gpg_error (GPG_ERR_INV_INDEX);
446 if (!card->fnc.initialized)
447 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
448 if (!card->fnc.enum_keypairs)
449 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
450 rc = card->fnc.enum_keypairs (card, idx, keygrip, keyid);
451 if (opt.verbose)
452 log_info ("card operation enum_keypairs result: %s\n",
453 gpg_strerror (rc));
454 return rc;
458 /* Enumerate all trusted certificates available on the card, return
459 their ID in CERT and the type in CERTTYPE. Types of certificates
460 are:
461 0 := Unknown
462 100 := Regular X.509 cert
463 101 := Trusted X.509 cert
464 102 := Useful X.509 cert
465 110 := Root CA cert (DINSIG)
468 card_enum_certs (CARD card, int idx, char **certid, int *certtype)
470 int rc;
472 if (certid)
473 *certid = NULL;
475 if (!card)
476 return gpg_error (GPG_ERR_INV_VALUE);
477 if (idx < 0)
478 return gpg_error (GPG_ERR_INV_INDEX);
479 if (!card->fnc.initialized)
480 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
481 if (!card->fnc.enum_certs)
482 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
483 rc = card->fnc.enum_certs (card, idx, certid, certtype);
484 if (opt.verbose)
485 log_info ("card operation enum_certs result: %s\n",
486 gpg_strerror (rc));
487 return rc;
492 /* Read the certificate identified by CERTIDSTR which is the
493 hexadecimal encoded ID of the certificate, prefixed with the string
494 "3F005015.". The certificate is return in DER encoded form in CERT
495 and NCERT. */
497 card_read_cert (CARD card, const char *certidstr,
498 unsigned char **cert, size_t *ncert)
500 int rc;
502 if (!card || !certidstr || !cert || !ncert)
503 return gpg_error (GPG_ERR_INV_VALUE);
504 if (!card->fnc.initialized)
505 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
506 if (!card->fnc.read_cert)
507 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
508 rc = card->fnc.read_cert (card, certidstr, cert, ncert);
509 if (opt.verbose)
510 log_info ("card operation read_cert result: %s\n", gpg_strerror (rc));
511 return rc;
515 /* Create the signature and return the allocated result in OUTDATA.
516 If a PIN is required the PINCB will be used to ask for the PIN; it
517 should return the PIN in an allocated buffer and put it into PIN. */
518 int
519 card_sign (CARD card, const char *keyidstr, int hashalgo,
520 int (pincb)(void*, const char *, char **),
521 void *pincb_arg,
522 const void *indata, size_t indatalen,
523 unsigned char **outdata, size_t *outdatalen )
525 int rc;
527 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
528 return gpg_error (GPG_ERR_INV_VALUE);
529 if (!card->fnc.initialized)
530 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
531 if (!card->fnc.sign)
532 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
533 rc = card->fnc.sign (card, keyidstr, hashalgo,
534 pincb, pincb_arg,
535 indata, indatalen,
536 outdata, outdatalen);
537 if (opt.verbose)
538 log_info ("card operation sign result: %s\n", gpg_strerror (rc));
539 return rc;
543 /* Create the signature and return the allocated result in OUTDATA.
544 If a PIN is required the PINCB will be used to ask for the PIN; it
545 should return the PIN in an allocated buffer and put it into PIN. */
546 int
547 card_decipher (CARD card, const char *keyidstr,
548 int (pincb)(void*, const char *, char **),
549 void *pincb_arg,
550 const void *indata, size_t indatalen,
551 unsigned char **outdata, size_t *outdatalen )
553 int rc;
555 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
556 return gpg_error (GPG_ERR_INV_VALUE);
557 if (!card->fnc.initialized)
558 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
559 if (!card->fnc.decipher)
560 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
561 rc = card->fnc.decipher (card, keyidstr,
562 pincb, pincb_arg,
563 indata, indatalen,
564 outdata, outdatalen);
565 if (opt.verbose)
566 log_info ("card operation decipher result: %s\n", gpg_strerror (rc));
567 return rc;