2005-04-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / card.c
blob9ec2a52c520920d785011ee7edf923c43e8d3c77
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <time.h>
28 #ifdef HAVE_OPENSC
29 #include <opensc/pkcs15.h>
30 #endif
32 #include "scdaemon.h"
33 #include <ksba.h>
35 #include "card-common.h"
37 /* Map the SC error codes to the GNUPG ones */
38 gpg_error_t
39 map_sc_err (int rc)
41 gpg_err_code_t e;
43 switch (rc)
45 case 0: e = 0; break;
46 #ifdef HAVE_OPENSC
47 case SC_ERROR_NOT_SUPPORTED: e = GPG_ERR_NOT_SUPPORTED; break;
48 case SC_ERROR_PKCS15_APP_NOT_FOUND: e = GPG_ERR_NO_PKCS15_APP; break;
49 case SC_ERROR_OUT_OF_MEMORY: e = GPG_ERR_ENOMEM; break;
50 case SC_ERROR_CARD_NOT_PRESENT: e = GPG_ERR_CARD_NOT_PRESENT; break;
51 case SC_ERROR_CARD_REMOVED: e = GPG_ERR_CARD_REMOVED; break;
52 case SC_ERROR_INVALID_CARD: e = GPG_ERR_INV_CARD; break;
53 #endif
54 default: e = GPG_ERR_CARD; break;
56 /* It does not make much sense to further distingusih the error
57 source between OpenSC and SCD. Thus we use SCD as source
58 here. */
59 return gpg_err_make (GPG_ERR_SOURCE_SCD, e);
62 /* Get the keygrip from CERT, return 0 on success */
63 int
64 card_help_get_keygrip (ksba_cert_t cert, unsigned char *array)
66 gcry_sexp_t s_pkey;
67 int rc;
68 ksba_sexp_t p;
69 size_t n;
71 p = ksba_cert_get_public_key (cert);
72 if (!p)
73 return -1; /* oops */
74 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
75 if (!n)
76 return -1; /* libksba did not return a proper S-expression */
77 rc = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
78 xfree (p);
79 if (rc)
80 return -1; /* can't parse that S-expression */
81 array = gcry_pk_get_keygrip (s_pkey, array);
82 gcry_sexp_release (s_pkey);
83 if (!array)
84 return -1; /* failed to calculate the keygrip */
85 return 0;
94 /* Create a new context for the card and figures out some basic
95 information of the card. Detects whether a PKCS_15 application is
96 stored.
98 Common errors: GPG_ERR_CARD_NOT_PRESENT */
99 int
100 card_open (CARD *rcard)
102 #ifdef HAVE_OPENSC
103 CARD card;
104 int rc;
106 if (opt.disable_opensc)
107 return gpg_error (GPG_ERR_NOT_SUPPORTED);
109 card = xtrycalloc (1, sizeof *card);
110 if (!card)
111 return gpg_error (gpg_err_code_from_errno (errno));
112 card->reader = 0;
114 rc = sc_establish_context (&card->ctx, "scdaemon");
115 if (rc)
117 log_error ("failed to establish SC context: %s\n", sc_strerror (rc));
118 rc = map_sc_err (rc);
119 goto leave;
121 if (card->reader >= card->ctx->reader_count)
123 log_error ("no card reader available\n");
124 rc = gpg_error (GPG_ERR_CARD);
125 goto leave;
127 card->ctx->error_file = log_get_stream ();
128 card->ctx->debug = opt.debug_sc;
129 card->ctx->debug_file = log_get_stream ();
131 if (sc_detect_card_presence (card->ctx->reader[card->reader], 0) != 1)
133 rc = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
134 goto leave;
137 rc = sc_connect_card (card->ctx->reader[card->reader], 0, &card->scard);
138 if (rc)
140 log_error ("failed to connect card in reader %d: %s\n",
141 card->reader, sc_strerror (rc));
142 rc = map_sc_err (rc);
143 goto leave;
145 if (opt.verbose)
146 log_info ("connected to card in reader %d using driver `%s'\n",
147 card->reader, card->scard->driver->name);
149 rc = sc_lock (card->scard);
150 if (rc)
152 log_error ("can't lock card in reader %d: %s\n",
153 card->reader, sc_strerror (rc));
154 rc = map_sc_err (rc);
155 goto leave;
159 leave:
160 if (rc)
161 card_close (card);
162 else
163 *rcard = card;
165 return rc;
166 #else
167 return gpg_error (GPG_ERR_NOT_SUPPORTED);
168 #endif
172 /* Close a card and release all resources */
173 void
174 card_close (CARD card)
176 if (card)
178 #ifdef HAVE_OPENSC
179 if (card->p15card)
181 sc_pkcs15_unbind (card->p15card);
182 card->p15card = NULL;
184 if (card->p15priv)
185 p15_release_private_data (card);
186 if (card->scard)
188 sc_unlock (card->scard);
189 sc_disconnect_card (card->scard, 0);
190 card->scard = NULL;
192 if (card->ctx)
194 sc_release_context (card->ctx);
195 card->ctx = NULL;
197 #endif
198 xfree (card);
202 /* Locate a simple TLV encoded data object in BUFFER of LENGTH and
203 return a pointer to value as well as its length in NBYTES. Return
204 NULL if it was not found. Note, that the function does not check
205 whether the value fits into the provided buffer. */
206 #ifdef HAVE_OPENSC
207 static const char *
208 find_simple_tlv (const unsigned char *buffer, size_t length,
209 int tag, size_t *nbytes)
211 const char *s = buffer;
212 size_t n = length;
213 size_t len;
215 for (;;)
217 buffer = s;
218 if (n < 2)
219 return NULL; /* buffer too short for tag and length. */
220 len = s[1];
221 s += 2; n -= 2;
222 if (len == 255)
224 if (n < 2)
225 return NULL; /* we expected 2 more bytes with the length. */
226 len = (s[0] << 8) | s[1];
227 s += 2; n -= 2;
229 if (*buffer == tag)
231 *nbytes = len;
232 return s;
234 if (len > n)
235 return NULL; /* buffer too short to skip to the next tag. */
236 s += len; n -= len;
239 #endif /*HAVE_OPENSC*/
241 /* Find the ICC Serial Number within the provided BUFFER of LENGTH
242 (which should contain the GDO file) and return it as a hex encoded
243 string and allocated string in SERIAL. Return an error code when
244 the ICCSN was not found. */
245 #ifdef HAVE_OPENSC
246 static int
247 find_iccsn (const unsigned char *buffer, size_t length, char **serial)
249 size_t n;
250 const unsigned char *s;
251 char *p;
253 s = find_simple_tlv (buffer, length, 0x5A, &n);
254 if (!s)
255 return gpg_error (GPG_ERR_CARD);
256 length -= s - buffer;
257 if (n > length)
259 /* Oops, it does not fit into the buffer. This is an invalid
260 encoding (or the buffer is too short. However, I have some
261 test cards with such an invalid encoding and therefore I use
262 this ugly workaround to return something I can further
263 experiment with. */
264 if (n == 0x0D && length+1 == n)
266 log_debug ("enabling BMI testcard workaround\n");
267 n--;
269 else
270 return gpg_error (GPG_ERR_CARD); /* Bad encoding; does
271 not fit into buffer. */
273 if (!n)
274 return gpg_error (GPG_ERR_CARD); /* Well, that is too short. */
276 *serial = p = xtrymalloc (2*n+1);
277 if (!*serial)
278 return gpg_error (gpg_err_code_from_errno (errno));
279 for (; n; n--, p += 2, s++)
280 sprintf (p, "%02X", *s);
281 *p = 0;
282 return 0;
284 #endif /*HAVE_OPENSC*/
286 /* Retrieve the serial number and the time of the last update of the
287 card. The serial number is returned as a malloced string (hex
288 encoded) in SERIAL and the time of update is returned in STAMP.
289 If no update time is available the returned value is 0. The serial
290 is mandatory for a PKCS_15 application and an error will be
291 returned if this value is not availbale. For non-PKCS-15 cards a
292 serial number is constructed by other means. Caller must free
293 SERIAL unless the function returns an error. */
294 int
295 card_get_serial_and_stamp (CARD card, char **serial, time_t *stamp)
297 #ifdef HAVE_OPENSC
298 int rc;
299 struct sc_path path;
300 struct sc_file *file;
301 unsigned char buf[256];
302 int buflen;
303 #endif
305 if (!card || !serial || !stamp)
306 return gpg_error (GPG_ERR_INV_VALUE);
308 *serial = NULL;
309 *stamp = 0; /* not available */
311 #ifdef HAVE_OPENSC
312 if (!card->fnc.initialized)
314 card->fnc.initialized = 1;
315 /* The first use of this card tries to figure out the type of the card
316 and sets up the function pointers. */
317 rc = sc_pkcs15_bind (card->scard, &card->p15card);
318 if (rc)
320 if (rc != SC_ERROR_PKCS15_APP_NOT_FOUND)
321 log_error ("binding of existing PKCS-15 failed in reader %d: %s\n",
322 card->reader, sc_strerror (rc));
323 card->p15card = NULL;
324 rc = 0;
326 if (card->p15card)
327 card_p15_bind (card);
328 card->fnc.initialized = 1;
332 /* We should lookup the iso 7812-1 and 8583-3 - argh ISO
333 practice is suppressing innovation - IETF rules! So we
334 always get the serialnumber from the 2F02 GDO file. */
335 /* FIXME: in case we can't parse the 2F02 EF and we have a P15 card,
336 we should get the serial number from the respective P15 file */
337 sc_format_path ("3F002F02", &path);
338 rc = sc_select_file (card->scard, &path, &file);
339 if (rc)
341 log_error ("sc_select_file failed: %s\n", sc_strerror (rc));
342 return gpg_error (GPG_ERR_CARD);
344 if (file->type != SC_FILE_TYPE_WORKING_EF
345 || file->ef_structure != SC_FILE_EF_TRANSPARENT)
347 log_error ("wrong type or structure of GDO file\n");
348 sc_file_free (file);
349 return gpg_error (GPG_ERR_CARD);
352 if (!file->size || file->size >= DIM(buf) )
353 { /* FIXME: Use a real parser */
354 log_error ("unsupported size of GDO file (%d)\n", file->size);
355 sc_file_free (file);
356 return gpg_error (GPG_ERR_CARD);
358 buflen = file->size;
360 rc = sc_read_binary (card->scard, 0, buf, buflen, 0);
361 sc_file_free (file);
362 if (rc < 0)
364 log_error ("error reading GDO file: %s\n", sc_strerror (rc));
365 return gpg_error (GPG_ERR_CARD);
367 if (rc != buflen)
369 log_error ("short read on GDO file\n");
370 return gpg_error (GPG_ERR_CARD);
373 rc = find_iccsn (buf, buflen, serial);
374 if (gpg_err_code (rc) == GPG_ERR_CARD)
375 log_error ("invalid structure of GDO file\n");
376 if (!rc && card->p15card && !strcmp (*serial, "D27600000000000000000000"))
377 { /* This is a German card with a silly serial number. Try to get
378 the serial number from the EF(TokenInfo). We indicate such a
379 serial number by the using the prefix: "FF0100". */
380 const char *efser = card->p15card->serial_number;
381 char *p;
383 if (!efser)
384 efser = "";
386 xfree (*serial);
387 *serial = NULL;
388 p = xtrymalloc (strlen (efser) + 7);
389 if (!p)
390 rc = gpg_error (gpg_err_code_from_errno (errno));
391 else
393 strcpy (p, "FF0100");
394 strcpy (p+6, efser);
395 *serial = p;
398 else if (!rc && **serial == 'F' && (*serial)[1] == 'F')
399 { /* The serial number starts with our special prefix. This
400 requires that we put our default prefix "FF0000" in front. */
401 char *p = xtrymalloc (strlen (*serial) + 7);
402 if (!p)
404 xfree (*serial);
405 *serial = NULL;
406 rc = gpg_error (gpg_err_code_from_errno (errno));
408 else
410 strcpy (p, "FF0000");
411 strcpy (p+6, *serial);
412 xfree (*serial);
413 *serial = p;
416 return rc;
417 #else
418 return gpg_error (GPG_ERR_NOT_SUPPORTED);
419 #endif
423 /* Enumerate all keypairs on the card and return the Keygrip as well
424 as the internal identification of the key. KEYGRIP must be a
425 caller provided buffer with a size of 20 bytes which will receive
426 the KEYGRIP of the keypair. If KEYID is not NULL, it returns the
427 ID field of the key in allocated memory; this is a string without
428 spaces. The function returns -1 when all keys have been
429 enumerated. Note that the error GPG_ERR_MISSING_CERTIFICATE may be
430 returned if there is just the private key but no public key (ie.e a
431 certificate) available. Applications might want to continue
432 enumerating after this error.*/
434 card_enum_keypairs (CARD card, int idx,
435 unsigned char *keygrip,
436 char **keyid)
438 int rc;
440 if (keyid)
441 *keyid = NULL;
443 if (!card || !keygrip)
444 return gpg_error (GPG_ERR_INV_VALUE);
445 if (idx < 0)
446 return gpg_error (GPG_ERR_INV_INDEX);
447 if (!card->fnc.initialized)
448 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
449 if (!card->fnc.enum_keypairs)
450 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
451 rc = card->fnc.enum_keypairs (card, idx, keygrip, keyid);
452 if (opt.verbose)
453 log_info ("card operation enum_keypairs result: %s\n",
454 gpg_strerror (rc));
455 return rc;
459 /* Enumerate all trusted certificates available on the card, return
460 their ID in CERT and the type in CERTTYPE. Types of certificates
461 are:
462 0 := Unknown
463 100 := Regular X.509 cert
464 101 := Trusted X.509 cert
465 102 := Useful X.509 cert
466 110 := Root CA cert (DINSIG)
469 card_enum_certs (CARD card, int idx, char **certid, int *certtype)
471 int rc;
473 if (certid)
474 *certid = NULL;
476 if (!card)
477 return gpg_error (GPG_ERR_INV_VALUE);
478 if (idx < 0)
479 return gpg_error (GPG_ERR_INV_INDEX);
480 if (!card->fnc.initialized)
481 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
482 if (!card->fnc.enum_certs)
483 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
484 rc = card->fnc.enum_certs (card, idx, certid, certtype);
485 if (opt.verbose)
486 log_info ("card operation enum_certs result: %s\n",
487 gpg_strerror (rc));
488 return rc;
493 /* Read the certificate identified by CERTIDSTR which is the
494 hexadecimal encoded ID of the certificate, prefixed with the string
495 "3F005015.". The certificate is return in DER encoded form in CERT
496 and NCERT. */
498 card_read_cert (CARD card, const char *certidstr,
499 unsigned char **cert, size_t *ncert)
501 int rc;
503 if (!card || !certidstr || !cert || !ncert)
504 return gpg_error (GPG_ERR_INV_VALUE);
505 if (!card->fnc.initialized)
506 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
507 if (!card->fnc.read_cert)
508 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
509 rc = card->fnc.read_cert (card, certidstr, cert, ncert);
510 if (opt.verbose)
511 log_info ("card operation read_cert result: %s\n", gpg_strerror (rc));
512 return rc;
516 /* Create the signature and return the allocated result in OUTDATA.
517 If a PIN is required the PINCB will be used to ask for the PIN; it
518 should return the PIN in an allocated buffer and put it into PIN. */
519 int
520 card_sign (CARD card, const char *keyidstr, int hashalgo,
521 int (pincb)(void*, const char *, char **),
522 void *pincb_arg,
523 const void *indata, size_t indatalen,
524 unsigned char **outdata, size_t *outdatalen )
526 int rc;
528 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
529 return gpg_error (GPG_ERR_INV_VALUE);
530 if (!card->fnc.initialized)
531 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
532 if (!card->fnc.sign)
533 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
534 rc = card->fnc.sign (card, keyidstr, hashalgo,
535 pincb, pincb_arg,
536 indata, indatalen,
537 outdata, outdatalen);
538 if (opt.verbose)
539 log_info ("card operation sign result: %s\n", gpg_strerror (rc));
540 return rc;
544 /* Create the signature and return the allocated result in OUTDATA.
545 If a PIN is required the PINCB will be used to ask for the PIN; it
546 should return the PIN in an allocated buffer and put it into PIN. */
547 int
548 card_decipher (CARD card, const char *keyidstr,
549 int (pincb)(void*, const char *, char **),
550 void *pincb_arg,
551 const void *indata, size_t indatalen,
552 unsigned char **outdata, size_t *outdatalen )
554 int rc;
556 if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
557 return gpg_error (GPG_ERR_INV_VALUE);
558 if (!card->fnc.initialized)
559 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
560 if (!card->fnc.decipher)
561 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
562 rc = card->fnc.decipher (card, keyidstr,
563 pincb, pincb_arg,
564 indata, indatalen,
565 outdata, outdatalen);
566 if (opt.verbose)
567 log_info ("card operation decipher result: %s\n", gpg_strerror (rc));
568 return rc;