1 /* app.c - Application selection.
2 * Copyright (C) 2003, 2004, 2005 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 <https://www.gnu.org/licenses/>.
28 #include "../common/exechelp.h"
31 #include "../common/tlv.h"
32 #include "../common/membuf.h"
35 /* Forward declaration of internal function. */
37 select_additional_application_internal (card_t card, apptype_t req_apptype);
39 send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl);
40 static gpg_error_t run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev);
43 * Multiple readers, single writer (MRSW) lock.
49 int num_readers_active;
50 int num_writers_waiting;
52 npth_cond_t notify_cond;
55 /* MRSW lock to protect the list of cards.
57 * This structure is used for serializing access to the list of cards
58 * (by CARD_TOP). While allowing multiple accesses by different
59 * connections as "r" access (for a CARD in the list), "w" access to
60 * update the list is only possible with a single thread.
62 * Each use of a CARD (in the list) does "r" access.
64 * For "w" access, the app_send_devinfo function may wait on any
65 * change of the list. For other cases of "w" access are opening new
66 * card or removal of card, updating the list of card.
68 * Note that for serializing access to each CARD (and its associated
69 * applications) itself, it is done separately by another mutex with
70 * lock_card/unlock_card.
72 static struct mrsw_lock card_list_lock;
74 /* A list of card contexts. A card is a collection of applications
75 * (described by app_t) on the same physical token. */
76 static card_t card_top;
79 /* The list of application names and their select function. If no
80 * specific application is selected the first available application on
81 * a card is selected. */
82 struct app_priority_list_s
86 gpg_error_t (*select_func)(app_t);
89 static struct app_priority_list_s app_priority_list[] =
90 {{ APPTYPE_OPENPGP , "openpgp", app_select_openpgp },
91 { APPTYPE_PIV , "piv", app_select_piv },
92 { APPTYPE_NKS , "nks", app_select_nks },
93 { APPTYPE_P15 , "p15", app_select_p15 },
94 { APPTYPE_GELDKARTE, "geldkarte", app_select_geldkarte },
95 { APPTYPE_DINSIG , "dinsig", app_select_dinsig },
96 { APPTYPE_SC_HSM , "sc-hsm", app_select_sc_hsm },
97 { APPTYPE_NONE , NULL, NULL }
98 /* APPTYPE_UNDEFINED is special and not listed here. */
105 /* Map a cardtype to a string. Never returns NULL. */
107 strcardtype (cardtype_t t)
111 case CARDTYPE_GENERIC: return "generic";
112 case CARDTYPE_GNUK: return "gnuk";
113 case CARDTYPE_YUBIKEY: return "yubikey";
114 case CARDTYPE_ZEITCONTROL: return "zeitcontrol";
120 /* Map an application type to a string. Never returns NULL. */
122 strapptype (apptype_t t)
126 for (i=0; app_priority_list[i].apptype; i++)
127 if (app_priority_list[i].apptype == t)
128 return app_priority_list[i].name;
129 return t == APPTYPE_UNDEFINED? "undefined" : t? "?" : "none";
134 xstrapptype (app_t app)
136 return app? strapptype (app->apptype) : "[no_app]";
140 /* Return the apptype for NAME. */
142 apptype_from_name (const char *name)
149 for (i=0; app_priority_list[i].apptype; i++)
150 if (!ascii_strcasecmp (app_priority_list[i].name, name))
151 return app_priority_list[i].apptype;
152 if (!ascii_strcasecmp ("undefined", name))
153 return APPTYPE_UNDEFINED;
158 /* Return the apptype for KEYREF. This is the first part of the
159 * KEYREF up to the dot. */
161 apptype_from_keyref (const char *keyref)
169 s = strchr (keyref, '.');
170 if (!s || s == keyref || !s[1])
171 return APPTYPE_NONE; /* Not a valid keyref. */
174 for (i=0; app_priority_list[i].apptype; i++)
175 if (strlen (app_priority_list[i].name) == n
176 && !ascii_strncasecmp (app_priority_list[i].name, keyref, n))
177 return app_priority_list[i].apptype;
183 /* Return true if both serilanumbers are the same. This function
184 * takes care of some peculiarities. */
186 is_same_serialno (const unsigned char *sna, size_t snalen,
187 const unsigned char *snb, size_t snblen)
189 if ((!sna && !snb) || (!snalen && !snblen))
192 return 0; /* One of them is NULL. (Both NULL tested above). */
194 if (snalen != snblen)
195 return 0; /* (No special cases for this below). */
197 /* The special case for OpenPGP cards where we ignore the version
198 * bytes (vvvv). Example: D276000124010304000500009D8A0000
199 * ^^^^^^^^^^^^vvvvmmmmssssssssrrrr */
200 if (snalen == 16 && !memcmp (sna, "\xD2\x76\x00\x01\x24\x01", 6))
202 if (memcmp (snb, "\xD2\x76\x00\x01\x24\x01", 6))
204 return !memcmp (sna + 8, snb + 8, 8);
207 return !memcmp (sna, snb, snalen);
212 /* Initialization function to change the default app_priority_list.
213 * LIST is a list of comma or space separated strings with application
214 * names. Unknown names will only result in warning message.
215 * Application not mentioned in LIST are used in their original order
216 * after the given once. */
218 app_update_priority_list (const char *arg)
220 struct app_priority_list_s save;
224 names = strtokenize (arg, ", ");
226 log_fatal ("strtokenize failed: %s\n",
227 gpg_strerror (gpg_error_from_syserror ()));
230 for (i=0; names[i]; i++)
232 ascii_strlwr (names[i]);
233 for (j=0; j < i; j++)
234 if (!strcmp (names[j], names[i]))
238 log_info ("warning: duplicate application '%s' in priority list\n",
243 for (j=idx; app_priority_list[j].name; j++)
244 if (!strcmp (names[i], app_priority_list[j].name))
246 if (!app_priority_list[j].name)
248 log_info ("warning: unknown application '%s' in priority list\n",
252 save = app_priority_list[idx];
253 app_priority_list[idx] = app_priority_list[j];
254 app_priority_list[j] = save;
257 log_assert (idx < DIM (app_priority_list));
260 for (i=0; app_priority_list[i].name; i++)
261 log_info ("app priority %d: %s\n", i, app_priority_list[i].name);
266 print_progress_line (void *opaque, const char *what, int pc, int cur, int tot)
268 ctrl_t ctrl = opaque;
273 snprintf (line, sizeof line, "%s %c %d %d", what, pc, cur, tot);
274 send_status_direct (ctrl, "PROGRESS", line);
279 /* Lock the CARD. This function shall be used right before calling
280 * any of the actual application functions to serialize access to the
281 * reader. We do this always even if the card is not actually used.
282 * This allows an actual connection to assume that it never shares a
283 * card (while performing one command). Returns 0 on success; only
284 * then the unlock_reader function must be called after returning from
285 * the handler. Right now we assume a that a reader has just one
286 * card; this may eventually need refinement. */
288 lock_card (card_t card, ctrl_t ctrl)
290 if (npth_mutex_lock (&card->lock))
292 gpg_error_t err = gpg_error_from_syserror ();
293 log_error ("failed to acquire CARD lock for %p: %s\n",
294 card, gpg_strerror (err));
298 apdu_set_progress_cb (card->slot, print_progress_line, ctrl);
299 apdu_set_prompt_cb (card->slot, popup_prompt, ctrl);
305 /* Release a lock on a card. See lock_reader(). */
307 unlock_card (card_t card)
309 apdu_set_progress_cb (card->slot, NULL, NULL);
310 apdu_set_prompt_cb (card->slot, NULL, NULL);
312 if (npth_mutex_unlock (&card->lock))
314 gpg_error_t err = gpg_error_from_syserror ();
315 log_error ("failed to release CARD lock for %p: %s\n",
316 card, gpg_strerror (err));
322 card_list_r_lock (void)
324 npth_mutex_lock (&card_list_lock.lock);
325 while (card_list_lock.num_writers_waiting
326 || card_list_lock.writer_active)
327 npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
328 card_list_lock.num_readers_active++;
329 npth_mutex_unlock (&card_list_lock.lock);
333 card_list_r_unlock (void)
335 npth_mutex_lock (&card_list_lock.lock);
336 if (--card_list_lock.num_readers_active == 0)
337 npth_cond_broadcast (&card_list_lock.cond);
338 npth_mutex_unlock (&card_list_lock.lock);
343 card_list_w_lock (void)
345 npth_mutex_lock (&card_list_lock.lock);
346 card_list_lock.num_writers_waiting++;
347 while (card_list_lock.num_readers_active
348 || card_list_lock.writer_active)
349 npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
350 card_list_lock.num_writers_waiting--;
351 card_list_lock.writer_active++;
352 npth_mutex_unlock (&card_list_lock.lock);
356 card_list_w_unlock (void)
358 npth_mutex_lock (&card_list_lock.lock);
359 card_list_lock.writer_active--;
360 npth_cond_broadcast (&card_list_lock.cond);
361 npth_mutex_unlock (&card_list_lock.lock);
366 card_list_signal (void)
368 npth_cond_broadcast (&card_list_lock.notify_cond);
372 card_list_wait (void)
374 npth_mutex_lock (&card_list_lock.lock);
375 card_list_lock.writer_active--;
376 npth_cond_broadcast (&card_list_lock.cond);
378 npth_cond_wait (&card_list_lock.notify_cond, &card_list_lock.lock);
380 card_list_lock.num_writers_waiting++;
381 while (card_list_lock.num_readers_active
382 || card_list_lock.writer_active)
383 npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
384 card_list_lock.num_writers_waiting--;
386 card_list_lock.writer_active++;
387 npth_mutex_unlock (&card_list_lock.lock);
391 /* This function may be called to print information pertaining to the
392 * current state of this module to the log. */
394 app_dump_state (void)
400 for (c = card_top; c; c = c->next)
402 log_info ("app_dump_state: card=%p slot=%d type=%s refcount=%u\n",
403 c, c->slot, strcardtype (c->cardtype), c->ref_count);
404 /* FIXME The use of log_info risks a race! */
405 for (a=c->app; a; a = a->next)
406 log_info ("app_dump_state: app=%p type='%s'\n",
407 a, strapptype (a->apptype));
409 card_list_r_unlock ();
414 * Send information for all available cards.
416 * With KEEP_LOOPING=0, it only outputs once.
417 * With KEEP_LOOPING<0, it keeps looping, until it detects no device.
418 * With KEEP_LOOPING>0, it keeps looping forever.
421 app_send_devinfo (ctrl_t ctrl, int keep_looping)
430 no_device = (card_top == NULL);
431 if (no_device && keep_looping < 0)
434 send_status_direct (ctrl, "DEVINFO_START", "");
435 for (c = card_top; c; c = c->next)
440 serialno = card_get_serialno (c);
441 snprintf (card_info, sizeof card_info, "DEVICE %s %s",
442 strcardtype (c->cardtype), serialno);
445 for (a = c->app; a; a = a->next)
446 send_status_direct (ctrl, card_info, strapptype (a->apptype));
448 send_status_direct (ctrl, "DEVINFO_END", "");
450 if (no_device && !keep_looping)
455 card_list_w_unlock ();
457 return no_device ? gpg_error (GPG_ERR_NOT_FOUND): 0;
460 /* Check whether the application NAME is allowed. This does not mean
461 we have support for it though. */
463 is_app_allowed (const char *name)
467 for (l=opt.disabled_applications; l; l = l->next)
468 if (!strcmp (l->d, name))
474 /* This function is mainly used by the serialno command to check for
475 * an application conflict which may appear if the serialno command is
476 * used to request a specific application and the connection has
477 * already done a select_application. Return values are:
479 * GPG_ERR_FALSE - Another application is in use but it is possible
480 * to switch to the requested application.
481 * Other code - Switching is not possible.
483 * If SERIALNO_BIN is not NULL a conflict is only asserted if the
484 * serialno of the card matches.
487 check_application_conflict (card_t card, const char *name,
488 const unsigned char *serialno_bin,
489 size_t serialno_bin_len)
496 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); /* Should not happen. */
498 if (serialno_bin && card->serialno)
500 if (!is_same_serialno (card->serialno, card->serialnolen,
501 serialno_bin, serialno_bin_len))
502 return 0; /* The card does not match the requested S/N. */
505 apptype = apptype_from_name (name);
506 if (card->app->apptype == apptype)
509 if (card->app->apptype == APPTYPE_UNDEFINED)
512 if (card->cardtype == CARDTYPE_YUBIKEY)
514 if (card->app->apptype == APPTYPE_OPENPGP)
516 /* Current app is OpenPGP. */
517 if (!ascii_strcasecmp (name, "piv"))
518 return gpg_error (GPG_ERR_FALSE); /* Switching allowed. */
520 else if (card->app->apptype == APPTYPE_PIV)
522 /* Current app is PIV. */
523 if (!ascii_strcasecmp (name, "openpgp"))
524 return gpg_error (GPG_ERR_FALSE); /* Switching allowed. */
528 log_info ("application '%s' in use - can't switch\n",
529 strapptype (card->app->apptype));
531 return gpg_error (GPG_ERR_CONFLICT);
536 card_reset (card_t card)
541 sw = apdu_reset (card->slot);
543 err = gpg_error (GPG_ERR_CARD_RESET);
545 card->reset_requested = 1;
546 scd_kick_the_loop ();
553 app_new_register (int slot, ctrl_t ctrl, const char *name,
554 int periodical_check_needed)
559 unsigned char *result = NULL;
564 /* Need to allocate a new card object */
565 card = xtrycalloc (1, sizeof *card);
568 err = gpg_error_from_syserror ();
569 log_info ("error allocating context: %s\n", gpg_strerror (err));
574 card->card_status = (unsigned int)-1;
576 if (npth_mutex_init (&card->lock, NULL))
578 err = gpg_error_from_syserror ();
579 log_error ("error initializing mutex: %s\n", gpg_strerror (err));
584 err = lock_card (card, ctrl);
591 want_undefined = (name && !strcmp (name, "undefined"));
593 /* Try to read the GDO file first to get a default serial number.
594 We skip this if the undefined application has been requested. */
597 err = iso7816_select_file (slot, 0x3F00, 1);
598 if (gpg_err_code (err) == GPG_ERR_CARD)
600 /* Might be SW==0x7D00. Let's test whether it is a Yubikey
601 * by selecting its manager application and then reading the
603 static char const yk_aid[] =
604 { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17 }; /*MGR*/
605 static char const otp_aid[] =
606 { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01 }; /*OTP*/
609 const unsigned char *s0;
610 unsigned char formfactor;
613 if (!iso7816_select_application (slot, yk_aid, sizeof yk_aid,
615 && !iso7816_apdu_direct (slot, "\x00\x1d\x00\x00\x00", 5, 0,
616 NULL, &buf, &buflen))
618 card->cardtype = CARDTYPE_YUBIKEY;
621 log_info ("Yubico: config=");
622 log_printhex (buf, buflen, "");
625 /* We skip the first byte which seems to be the total
626 * length of the config data. */
629 s0 = find_tlv (buf+1, buflen-1, 0x04, &n); /* Form factor */
630 formfactor = (s0 && n == 1)? *s0 : 0;
632 s0 = find_tlv (buf+1, buflen-1, 0x02, &n); /* Serial */
635 card->serialno = xtrymalloc (3 + 1 + 4);
638 card->serialnolen = 3 + 1 + 4;
639 card->serialno[0] = 0xff;
640 card->serialno[1] = 0x02;
641 card->serialno[2] = 0x0;
642 card->serialno[3] = formfactor;
643 memset (card->serialno + 4, 0, 4 - n);
644 memcpy (card->serialno + 4 + 4 - n, s0, n);
645 err = app_munge_serialno (card);
649 s0 = find_tlv (buf+1, buflen-1, 0x05, &n); /* version */
651 card->cardversion = ((s0[0]<<16)|(s0[1]<<8)|s0[2]);
654 /* No version - this is not a Yubikey 5. We now
655 * switch to the OTP app and take the first
656 * three bytes of the response as version
660 if (!iso7816_select_application_ext (slot,
661 otp_aid, sizeof otp_aid,
664 card->cardversion = ((buf[0]<<16)|(buf[1]<<8)|buf[2]);
675 /* This is heuristics to identify different implementations. */
676 atr = apdu_get_atr (slot, &atrlen);
679 if (atrlen == 21 && atr[2] == 0x11)
680 card->cardtype = CARDTYPE_GNUK;
681 else if (atrlen == 21 && atr[7] == 0x75)
682 card->cardtype = CARDTYPE_ZEITCONTROL;
687 if (!err && card->cardtype != CARDTYPE_YUBIKEY)
688 err = iso7816_select_file (slot, 0x2F02, 0);
689 if (!err && card->cardtype != CARDTYPE_YUBIKEY)
690 err = iso7816_read_binary (slot, 0, 0, &result, &resultlen);
691 if (!err && card->cardtype != CARDTYPE_YUBIKEY)
694 const unsigned char *p;
696 p = find_tlv_unchecked (result, resultlen, 0x5A, &n);
698 resultlen -= (p-result);
699 if (p && n > resultlen && n == 0x0d && resultlen+1 == n)
701 /* The object does not fit into the buffer. This is an
702 invalid encoding (or the buffer is too short. However, I
703 have some test cards with such an invalid encoding and
704 therefore I use this ugly workaround to return something
705 I can further experiment with. */
706 log_info ("enabling BMI testcard workaround\n");
710 if (p && n <= resultlen)
712 /* The GDO file is pretty short, thus we simply reuse it for
713 storing the serial number. */
714 memmove (result, p, n);
715 card->serialno = result;
716 card->serialnolen = n;
717 err = app_munge_serialno (card);
727 /* Allocate a new app object. */
728 app = xtrycalloc (1, sizeof *app);
731 err = gpg_error_from_syserror ();
732 log_info ("error allocating app context: %s\n", gpg_strerror (err));
738 /* Figure out the application to use. */
741 /* We switch to the "undefined" application only if explicitly
743 app->apptype = APPTYPE_UNDEFINED;
744 /* Clear the error so that we don't run through the application
745 * selection chain. */
750 /* For certain error codes, there is no need to try more. */
751 if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT
752 || gpg_err_code (err) == GPG_ERR_ENODEV)
755 /* Set a default error so that we run through the application
756 * selection chain. */
757 err = gpg_error (GPG_ERR_NOT_FOUND);
760 /* Find the first available app if NAME is NULL or the matching
761 * NAME but only if that application is also enabled. */
762 for (i=0; err && app_priority_list[i].name; i++)
764 if (is_app_allowed (app_priority_list[i].name)
765 && (!name || !strcmp (name, app_priority_list[i].name)))
766 err = app_priority_list[i].select_func (app);
768 if (err && name && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE)
769 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
775 log_info ("can't select application '%s': %s\n",
776 name, gpg_strerror (err));
778 log_info ("no supported card application found: %s\n",
786 card->periodical_check_needed = periodical_check_needed;
787 card->next = card_top;
795 /* If called with NAME as NULL, select the best fitting application
796 * and return its card context; otherwise select the application with
797 * NAME and return its card context. Returns an error code and stores
798 * NULL at R_CARD if no application was found or no card is present. */
800 select_application (ctrl_t ctrl, const char *name,
801 int scan, const unsigned char *serialno_bin,
802 size_t serialno_bin_len)
805 card_t card, card_prev = NULL;
809 ctrl->card_ctx = NULL;
811 if (scan || !card_top)
816 /* Scan the devices to find new device(s). */
817 err = apdu_dev_list_start (opt.reader_port, &l);
820 card_list_w_unlock ();
827 int periodical_check_needed_this;
829 slot = apdu_open_reader (l);
833 periodical_check_needed_this = apdu_connect (slot);
834 if (periodical_check_needed_this < 0)
836 /* We close a reader with no card. */
837 err = gpg_error (GPG_ERR_ENODEV);
841 err = app_new_register (slot, ctrl, name,
842 periodical_check_needed_this);
848 pincache_put (ctrl, slot, NULL, NULL, NULL, 0);
849 apdu_close_reader (slot);
853 apdu_dev_list_finish (l);
855 /* If new device(s), kick the scdaemon loop. */
857 scd_kick_the_loop ();
860 for (card = card_top; card; card = card->next)
862 lock_card (card, ctrl);
863 if (serialno_bin == NULL)
865 if (is_same_serialno (card->serialno, card->serialnolen,
866 serialno_bin, serialno_bin_len))
874 err = check_application_conflict (card, name, NULL, 0);
876 ctrl->current_apptype = card->app ? card->app->apptype : APPTYPE_NONE;
877 else if (gpg_err_code (err) == GPG_ERR_FALSE)
879 apptype_t req_apptype = apptype_from_name (name);
882 err = gpg_error (GPG_ERR_NOT_FOUND);
885 err = select_additional_application_internal (card, req_apptype);
887 ctrl->current_apptype = req_apptype;
894 ctrl->card_ctx = card;
897 card_prev->next = card->next;
898 card->next = card_top;
905 err = gpg_error (GPG_ERR_ENODEV);
907 card_list_w_unlock ();
913 /* Switch the current card for the session CTRL and print a SERIALNO
914 * status line on success. (SERIALNO, SERIALNOLEN) is the binary s/n
915 * of the card to switch to. */
917 app_switch_current_card (ctrl_t ctrl,
918 const unsigned char *serialno, size_t serialnolen)
921 card_t card, cardtmp;
925 cardtmp = ctrl->card_ctx;
928 err = gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
932 if (serialno && serialnolen)
934 for (card = card_top; card; card = card->next)
936 if (is_same_serialno (card->serialno, card->serialnolen,
937 serialno, serialnolen))
942 err = gpg_error (GPG_ERR_NOT_FOUND);
946 /* Note: We do not lock CARD and CARDTMP here because we only
947 * swap the context of the current session and there is no
948 * chance of a context switch. This also works if the card
950 ctrl->card_ctx = card;
952 card_unref_locked (cardtmp);
955 /* Print the status line. */
956 err = send_serialno_and_app_status (ctrl->card_ctx, 0, ctrl);
959 card_list_r_unlock ();
965 select_additional_application_internal (card_t card, apptype_t req_apptype)
971 /* Check that the requested app has not yet been put onto the list. */
972 for (app = card->app; app; app = app->next)
973 if (app->apptype == req_apptype)
975 /* We already got this one. Note that in this case we don't
976 * make it the current one but it doesn't matter because
977 * maybe_switch_app will do that anyway. */
983 /* Allocate a new app object. */
984 app = xtrycalloc (1, sizeof *app);
987 err = gpg_error_from_syserror ();
988 log_info ("error allocating app context: %s\n", gpg_strerror (err));
993 /* Find the app and run the select. */
994 for (i=0; app_priority_list[i].apptype; i++)
996 if (app_priority_list[i].apptype == req_apptype
997 && is_app_allowed (app_priority_list[i].name))
999 err = app_priority_list[i].select_func (app);
1003 if (!app_priority_list[i].apptype
1004 || (err && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE))
1005 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1010 /* Add this app. We make it the current one to avoid an extra
1011 * reselect by maybe_switch_app after the select we just did. */
1012 app->next = card->app;
1014 log_info ("added app '%s' to the card context and switched\n",
1015 strapptype (app->apptype));
1024 /* Add all possible additional applications to the card context but do
1025 * not change the current one. This currently works only for Yubikeys. */
1027 select_all_additional_applications_internal (ctrl_t ctrl, card_t card)
1029 gpg_error_t err = 0;
1030 apptype_t candidates[3];
1034 if (card->cardtype == CARDTYPE_YUBIKEY)
1036 candidates[0] = APPTYPE_OPENPGP;
1037 candidates[1] = APPTYPE_PIV;
1038 candidates[2] = APPTYPE_NONE;
1042 candidates[0] = APPTYPE_NONE;
1045 /* Find the app and run the select. */
1046 for (i=0; app_priority_list[i].apptype; i++)
1048 app_t app, app_r, app_prev;
1050 for (j=0; candidates[j]; j++)
1051 if (candidates[j] == app_priority_list[i].apptype
1052 && is_app_allowed (app_priority_list[i].name))
1057 for (app = card->app; app; app = app->next)
1058 if (app->apptype == candidates[j])
1061 continue; /* Already on the list of apps. */
1063 app = xtrycalloc (1, sizeof *app);
1066 err = gpg_error_from_syserror ();
1067 log_info ("error allocating app context: %s\n", gpg_strerror (err));
1071 err = app_priority_list[i].select_func (app);
1074 log_error ("error selecting additional app '%s': %s - skipped\n",
1075 strapptype (candidates[j]), gpg_strerror (err));
1081 /* Append to the list of apps. */
1082 app_prev = card->app;
1083 for (app_r=app_prev->next; app_r; app_prev=app_r, app_r=app_r->next)
1085 app_prev->next = app;
1086 log_info ("added app '%s' to the card context\n",
1087 strapptype (app->apptype));
1092 /* If we found a new application we need to reselect the original
1093 * application so that we are in a well defined state. */
1094 if (!err && any_new && card->app && card->app->fnc.reselect)
1095 err = run_reselect (ctrl, card, card->app, NULL);
1102 /* This function needs to be called with the NAME of the new
1103 * application to be selected on CARD. On success the application is
1104 * added to the list of the card's active applications as currently
1105 * active application. On error no new application is allocated.
1106 * Selecting an already selected application has no effect. */
1108 select_additional_application (card_t card, ctrl_t ctrl, const char *name)
1110 gpg_error_t err = 0;
1111 apptype_t req_apptype;
1117 req_apptype = apptype_from_name (name);
1119 return gpg_error (GPG_ERR_NOT_FOUND);
1124 err = select_additional_application_internal (card, req_apptype);
1127 ctrl->current_apptype = req_apptype;
1129 log_debug ("current_apptype is set to %s\n", name);
1134 err = select_all_additional_applications_internal (ctrl, card);
1142 get_supported_applications (void)
1149 for (nbytes=1, idx=0; (s=app_priority_list[idx].name); idx++)
1150 nbytes += strlen (s) + 1 + 1;
1152 buffer = xtrymalloc (nbytes);
1156 for (p=buffer, idx=0; (s=app_priority_list[idx].name); idx++)
1157 if (is_app_allowed (s))
1158 p = stpcpy (stpcpy (p, s), ":\n");
1165 /* Deallocate the application. */
1167 deallocate_card (card_t card)
1169 card_t c, c_prev = NULL;
1172 for (c = card_top; c; c = c->next)
1178 c_prev->next = c->next;
1184 if (card->ref_count)
1185 log_error ("releasing still used card context (%d)\n", card->ref_count);
1187 for (a = card->app; a; a = anext)
1192 a->fnc.deinit = NULL;
1198 xfree (card->serialno);
1205 do_with_keygrip (ctrl_t ctrl, int action, const char *keygrip_str,
1212 for (c = card_top; c; c = c->next)
1214 if (lock_card (c, ctrl))
1217 goto leave_the_loop;
1221 for (a = c->app; a; a = a->next)
1223 if (!a->fnc.with_keygrip || a->need_reset)
1226 /* Note that we need to do a re-select even for the current
1227 * app because the last selected application (e.g. after
1228 * init) might be a different one and we do not run
1229 * maybe_switch_app here. Of course we we do this only iff
1230 * we have an additional app. */
1233 if (run_reselect (ctrl, c, a, a_prev))
1239 log_debug ("slot %d, app %s: calling with_keygrip(%s)\n",
1240 c->slot, xstrapptype (a),
1241 action == KEYGRIP_ACTION_SEND_DATA? "send_data":
1242 action == KEYGRIP_ACTION_WRITE_STATUS? "status":
1243 action == KEYGRIP_ACTION_LOOKUP? "lookup":"?");
1244 if (!a->fnc.with_keygrip (a, ctrl, action, keygrip_str, capability))
1245 goto leave_the_loop; /* ACTION_LOOKUP succeeded. */
1248 /* Select the first app again. */
1250 run_reselect (ctrl, c, c->app, a_prev);
1257 /* Force switching of the app if the selected one is not the current
1258 * one. Changing the current apptype is sufficient to do this. */
1259 if (c && c->app && c->app->apptype != a->apptype)
1260 ctrl->current_apptype = a->apptype;
1271 /* Locking access to the card-list and CARD, returns CARD. */
1273 card_get (ctrl_t ctrl, const char *keygrip)
1277 card_list_r_lock ();
1279 card = do_with_keygrip (ctrl, KEYGRIP_ACTION_LOOKUP, keygrip, 0);
1281 card = ctrl->card_ctx;
1284 card_list_r_unlock ();
1288 lock_card (card, NULL);
1292 /* Release the lock of CARD and the card-list. */
1294 card_put (card_t card)
1296 /* We don't deallocate CARD here. Instead, we keep it. This is
1297 useful so that a card does not get reset even if only one session
1298 is using the card - this way the PIN cache and other cached data
1301 card_list_r_unlock ();
1305 /* This is the same as card_unref but assumes that CARD is already
1308 card_unref_locked (card_t card)
1313 if (!card->ref_count)
1314 log_bug ("tried to release an already released card context\n");
1321 /* The serial number may need some cosmetics. Do it here. This
1322 function shall only be called once after a new serial number has
1323 been put into APP->serialno.
1327 FF 00 00 = For serial numbers starting with an FF
1328 FF 01 00 = Some german p15 cards return an empty serial number so the
1329 serial number from the EF(TokenInfo) is used instead.
1330 FF 02 00 = Serial number from Yubikey config.
1331 This is normally not seen because we modify this here
1332 to an OpenPGP Card s/n.
1333 FF 7F 00 = No serialno.
1335 All other serial numbers not starting with FF are used as they are.
1338 app_munge_serialno (card_t card)
1340 if (card->cardtype == CARDTYPE_YUBIKEY
1341 && card->serialnolen == 3 + 1 + 4
1342 && !memcmp (card->serialno, "\xff\x02\x00", 3))
1344 /* An example for a serial number is
1347 * ! ! !--------- 4 byte s/n
1348 * ! !----------- Form factor
1349 * !----------------- Our prefix
1350 * Yubico seems to use the decimalized version of their S/N
1351 * as the OpenPGP card S/N. Thus in theory we can contruct the
1352 * number from this information so that we do not rely on having
1353 * the OpenPGP app enabled.
1356 sn = card->serialno[4] * 16777216;
1357 sn += card->serialno[5] * 65536;
1358 sn += card->serialno[6] * 256;
1359 sn += card->serialno[7];
1360 if (sn <= 99999999ul)
1362 char *buf = xtrymalloc (16);
1364 return gpg_error_from_syserror ();
1365 memcpy (buf, "\xD2\x76\x00\x01\x24\x01", 6);
1366 buf[6] = 0; /* Application version which we don't know */
1367 buf[7] = 0; /* thus we use 0.0 and don't use this directly. */
1368 buf[8] = 0; /* Manufacturer: Yubico (0x0006). */
1370 buf[13] = (sn % 10);
1372 buf[13] |= (sn % 10) << 4;
1374 buf[12] = (sn % 10);
1376 buf[12] |= (sn % 10) << 4;
1378 buf[11] = (sn % 10);
1380 buf[11] |= (sn % 10) << 4;
1382 buf[10] = (sn % 10);
1384 buf[10] |= (sn % 10) << 4;
1386 buf[14] = 0; /* Last two bytes are RFU. */
1388 xfree (card->serialno);
1389 card->serialno = buf;
1390 card->serialnolen = 16;
1393 else if (card->serialnolen && card->serialno[0] == 0xff)
1395 /* The serial number starts with our special prefix. This
1396 requires that we put our default prefix "FF0000" in front. */
1397 unsigned char *p = xtrymalloc (card->serialnolen + 3);
1399 return gpg_error_from_syserror ();
1400 memcpy (p, "\xff\0", 3);
1401 memcpy (p+3, card->serialno, card->serialnolen);
1402 card->serialnolen += 3;
1403 xfree (card->serialno);
1406 else if (!card->serialnolen)
1408 unsigned char *p = xtrymalloc (3);
1410 return gpg_error_from_syserror ();
1411 memcpy (p, "\xff\x7f", 3);
1412 card->serialnolen = 3;
1413 xfree (card->serialno);
1421 /* Retrieve the serial number of the card. The serial number is
1422 returned as a malloced string (hex encoded) in SERIAL. Caller must
1423 free SERIAL unless the function returns an error. */
1425 card_get_serialno (card_t card)
1432 if (!card->serialnolen)
1433 serial = xtrystrdup ("FF7F00");
1435 serial = bin2hex (card->serialno, card->serialnolen, NULL);
1440 /* Same as card_get_serialno but takes an APP object. */
1442 app_get_serialno (app_t app)
1444 if (!app || !app->card)
1446 gpg_err_set_errno (0);
1449 return card_get_serialno (app->card);
1453 /* Return an allocated string with the serial number in a format to be
1454 * show to the user. With NOFALLBACK set to true return NULL if such an
1455 * abbreviated S/N is not available, else return the full serial
1456 * number as a hex string. May return NULL on malloc problem. */
1458 card_get_dispserialno (card_t card, int nofallback)
1463 if (card && card->serialno && card->serialnolen == 3+1+4
1464 && !memcmp (card->serialno, "\xff\x02\x00", 3))
1466 /* This is a 4 byte S/N of a Yubikey which seems to be printed
1467 * on the token in decimal. Maybe they will print larger S/N
1468 * also in decimal but we can't be sure, thus do it only for
1469 * these 32 bit numbers. */
1470 sn = card->serialno[4] * 16777216;
1471 sn += card->serialno[5] * 65536;
1472 sn += card->serialno[6] * 256;
1473 sn += card->serialno[7];
1474 if ((card->cardversion >> 16) >= 5)
1475 result = xtryasprintf ("%lu %03lu %03lu",
1477 (sn/1000ul % 1000ul),
1480 result = xtryasprintf ("%lu", sn);
1482 else if (card && card->cardtype == CARDTYPE_YUBIKEY)
1484 /* Get back the printed Yubikey number from the OpenPGP AID
1485 * Example: D2760001240100000006120808620000
1487 result = card_get_serialno (card);
1488 if (result && strlen (result) >= 28 && !strncmp (result+16, "0006", 4))
1490 sn = atoi_4 (result+20) * 10000;
1491 sn += atoi_4 (result+24);
1492 if ((card->cardversion >> 16) >= 5)
1493 p = xtryasprintf ("%lu %03lu %03lu",
1495 (sn/1000ul % 1000ul),
1498 p = xtryasprintf ("%lu", sn);
1505 else if (nofallback)
1511 else if (card && card->app && card->app->apptype == APPTYPE_OPENPGP)
1513 /* Extract number from standard OpenPGP AID. */
1514 result = card_get_serialno (card);
1515 if (result && strlen (result) > 16+12)
1517 memcpy (result, result+16, 4);
1519 memcpy (result+5, result+20, 8);
1522 else if (nofallback)
1528 else if (nofallback)
1529 result = NULL; /* No Abbreviated S/N. */
1531 result = card_get_serialno (card);
1536 /* Same as card_get_dispserialno but takes an APP object. */
1538 app_get_dispserialno (app_t app, int nofallback)
1540 if (!app || !app->card)
1542 gpg_err_set_errno (0);
1545 return card_get_dispserialno (app->card, nofallback);
1549 /* Helper to run the reselect function. */
1551 run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev)
1555 if (!a->fnc.reselect)
1557 log_info ("slot %d, app %s: re-select not implemented\n",
1558 c->slot, xstrapptype (a));
1559 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
1562 /* Give the current app a chance to save some state before another
1563 * app is selected. We ignore errors here because that state saving
1564 * (e.g. putting PINs into a cache) is a convenience feature and not
1565 * required to always work. */
1566 if (a_prev && a_prev->fnc.prep_reselect)
1568 if (a_prev->need_reset)
1569 err = gpg_error (GPG_ERR_CARD_RESET);
1571 err = a_prev->fnc.prep_reselect (a_prev, ctrl);
1573 log_error ("slot %d, app %s: preparing re-select from %s failed: %s\n",
1574 c->slot, xstrapptype (a),
1575 xstrapptype (a_prev), gpg_strerror (err));
1579 err = gpg_error (GPG_ERR_CARD_RESET);
1581 err = a->fnc.reselect (a, ctrl);
1584 log_error ("slot %d, app %s: error re-selecting: %s\n",
1585 c->slot, xstrapptype (a), gpg_strerror (err));
1589 log_debug ("slot %d, app %s: re-selected\n", c->slot, xstrapptype (a));
1596 * Check external interference before each use of the application on
1597 * card. Returns -1 when detecting some external interference.
1600 * Note: This kind of detection can't be perfect. At most, it may be
1601 * possibly useful kludge, in some limited situations.
1604 check_external_interference (app_t app, ctrl_t ctrl)
1607 * Only when a user is using Yubikey with pcsc-shared configuration,
1608 * we need this detection. Otherwise, the card/token is under full
1609 * control of scdaemon, there's no problem at all.
1611 if (!opt.pcsc_shared || app->card->cardtype != CARDTYPE_YUBIKEY)
1614 if (app->fnc.check_aid)
1619 int slot = app_get_slot (app);
1621 err = iso7816_get_data (slot, 0, 0x004F, &aid, &aidlen);
1625 err = app->fnc.check_aid (app, ctrl, aid, aidlen);
1635 /* Check that the card has been initialized and whether we need to
1636 * switch to another application on the same card. Switching means
1637 * that the new active app will be moved to the head of the list at
1638 * CARD->app. This function must be called with the card lock held. */
1640 maybe_switch_app (ctrl_t ctrl, card_t card, const char *keyref)
1644 app_t app_prev = NULL;
1648 return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
1649 if (!ctrl->current_apptype)
1651 /* For whatever reasons the current apptype has not been set -
1652 * fix that and use the current app. */
1654 log_debug ("slot %d: no current app switching to %s\n",
1655 card->slot, strapptype (card->app->apptype));
1656 ctrl->current_apptype = card->app->apptype;
1659 for (app = card->app; app; app = app->next)
1660 if (app->apptype == ctrl->current_apptype)
1664 /* The current app is not supported by this card. Set the first
1665 * app of the card as current. */
1667 log_debug ("slot %d: current app %s not available switching to %s\n",
1668 card->slot, strapptype (ctrl->current_apptype),
1669 strapptype (card->app->apptype));
1670 ctrl->current_apptype = card->app->apptype;
1674 log_debug ("slot %d: have=%s want=%s keyref=%s\n",
1675 card->slot, strapptype (card->app->apptype),
1676 strapptype (ctrl->current_apptype),
1677 keyref? keyref:"[none]");
1682 /* Switch based on the requested KEYREF. */
1683 apptype = apptype_from_keyref (keyref);
1686 for (app = card->app; app; app_prev = app, app = app->next)
1687 if (app->apptype == apptype)
1689 if (!app_prev && ctrl->current_apptype == card->app->apptype)
1690 if (check_external_interference (app, ctrl) == 0)
1691 return 0; /* Already the first app - no need to switch. */
1693 else if (strlen (keyref) == 40)
1695 /* This looks like a keygrip. Iterate over all apps to find
1696 * the corresponding app. */
1697 for (app = card->app; app; app_prev = app, app = app->next)
1698 if (app->fnc.with_keygrip
1700 && !app->fnc.with_keygrip (app, ctrl,
1701 KEYGRIP_ACTION_LOOKUP, keyref, 0))
1703 if (!app_prev && ctrl->current_apptype == card->app->apptype)
1704 if (check_external_interference (app, ctrl) == 0)
1705 return 0; /* Already the first app - no need to switch. */
1711 /* Switch based on the current application of this connection or
1712 * if a keyref based switch didn't worked. */
1713 if (ctrl->current_apptype == card->app->apptype)
1714 return 0; /* No need to switch. */
1715 app_prev = card->app;
1716 for (app = app_prev->next; app; app_prev = app, app = app->next)
1717 if (app->apptype == ctrl->current_apptype)
1721 return gpg_error (GPG_ERR_WRONG_CARD);
1723 err = run_reselect (ctrl, card, app, app_prev);
1727 /* Swap APP with the head of the app list if needed. Note that APP
1728 * is not the head of the list. */
1731 app_prev->next = app->next;
1732 app->next = card->app;
1737 log_info ("slot %d, app %s: %s\n",
1738 card->slot, xstrapptype (app),
1739 app_prev? "switched":"re-selected");
1741 ctrl->current_apptype = app->apptype;
1747 /* Helper for app_write_learn_status. */
1749 write_learn_status_core (card_t card, app_t app, ctrl_t ctrl,
1754 /* We do not send CARD and APPTYPE if only keypairinfo is requested. */
1755 if (!(flags & APP_LEARN_FLAG_KEYPAIRINFO))
1757 if (card && card->cardtype)
1758 send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype));
1759 if (card && card->cardversion)
1760 send_status_printf (ctrl, "CARDVERSION", "%X", card->cardversion);
1762 send_status_direct (ctrl, "APPTYPE", strapptype (app->apptype));
1763 if (app->appversion)
1764 send_status_printf (ctrl, "APPVERSION", "%X", app->appversion);
1767 if (app->need_reset)
1768 err = gpg_error (GPG_ERR_CARD_RESET);
1771 err = app->fnc.learn_status (app, ctrl, flags);
1772 if (err && (flags & APP_LEARN_FLAG_REREAD))
1773 app->need_reset = 1;
1779 /* Write out the application specific status lines for the LEARN
1782 app_write_learn_status (card_t card, ctrl_t ctrl, unsigned int flags)
1784 gpg_error_t err, err2, tmperr;
1785 app_t app, last_app;
1786 int any_reselect = 0;
1788 /* Always make sure that the current app for this connection has
1789 * been selected and is at the top of the list. */
1790 if ((err = maybe_switch_app (ctrl, card, NULL)))
1792 else if (!card->app->fnc.learn_status)
1793 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1796 err = write_learn_status_core (card, card->app, ctrl, flags);
1797 if (!err && card->app->fnc.reselect && (flags & APP_LEARN_FLAG_MULTI))
1799 /* The current app has the reselect feature so that we can
1800 * loop over all other apps which are capable of a reselect
1801 * and finally reselect the first app again. Note that we
1802 * did the learn for the currently selected card above. */
1803 app = last_app = card->app;
1804 for (app = app->next; app && !err; app = app->next)
1805 if (app->fnc.reselect)
1807 if (last_app && last_app->fnc.prep_reselect)
1809 tmperr = last_app->fnc.prep_reselect (last_app, ctrl);
1811 log_info ("slot %d, app %s:"
1812 " preparing re-select from %s failed: %s\n",
1813 card->slot, xstrapptype (app),
1814 xstrapptype (last_app),
1815 gpg_strerror (tmperr));
1818 err = app->fnc.reselect (app, ctrl);
1822 err = write_learn_status_core (NULL, app, ctrl, flags);
1828 if (last_app && last_app->fnc.prep_reselect)
1830 tmperr = last_app->fnc.prep_reselect (last_app, ctrl);
1832 log_info ("slot %d, app %s:"
1833 " preparing re-select from %s failed: %s\n",
1834 card->slot, xstrapptype (app),
1835 xstrapptype (last_app), gpg_strerror (tmperr));
1837 err2 = app->fnc.reselect (app, ctrl);
1840 log_error ("error re-selecting '%s': %s\n",
1841 strapptype(app->apptype), gpg_strerror (err2));
1853 /* Read the certificate with id CERTID (as returned by learn_status in
1854 the CERTINFO status lines) and return it in the freshly allocated
1855 buffer put into CERT and the length of the certificate put into
1858 app_readcert (card_t card, ctrl_t ctrl, const char *certid,
1859 unsigned char **cert, size_t *certlen)
1863 if ((err = maybe_switch_app (ctrl, card, certid)))
1865 else if (!card->app->fnc.readcert)
1866 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1870 log_debug ("slot %d app %s: calling readcert(%s)\n",
1871 card->slot, xstrapptype (card->app), certid);
1872 if (card->app->need_reset)
1873 err = gpg_error (GPG_ERR_CARD_RESET);
1875 err = card->app->fnc.readcert (card->app, certid, cert, certlen);
1882 /* Read the key with ID KEYID. On success a canonical encoded
1883 * S-expression with the public key will get stored at PK and its
1884 * length (for assertions) at PKLEN; the caller must release that
1885 * buffer. On error NULL will be stored at PK and PKLEN and an error
1886 * code returned. If the key is not required NULL may be passed for
1887 * PK; this makes sense if the APP_READKEY_FLAG_INFO has also been set.
1889 * This function might not be supported by all applications. */
1891 app_readkey (card_t card, ctrl_t ctrl, const char *keyid, unsigned int flags,
1892 unsigned char **pk, size_t *pklen)
1902 return gpg_error (GPG_ERR_INV_VALUE);
1904 if ((err = maybe_switch_app (ctrl, card, keyid)))
1906 else if (!card->app->fnc.readkey)
1907 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1911 log_debug ("slot %d app %s: calling readkey(%s)\n",
1912 card->slot, xstrapptype (card->app), keyid);
1913 if (card->app->need_reset)
1914 err = gpg_error (GPG_ERR_CARD_RESET);
1916 err = card->app->fnc.readkey (card->app, ctrl, keyid, flags, pk, pklen);
1923 /* Perform a GETATTR operation. */
1925 app_getattr (card_t card, ctrl_t ctrl, const char *name)
1929 if (!name || !*name)
1930 return gpg_error (GPG_ERR_INV_VALUE);
1932 if ((err = maybe_switch_app (ctrl, card, NULL)))
1934 else if (name && !strcmp (name, "CARDTYPE"))
1936 send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype));
1938 else if (name && !strcmp (name, "APPTYPE"))
1940 send_status_direct (ctrl, "APPTYPE", strapptype (card->app->apptype));
1942 else if (name && !strcmp (name, "SERIALNO"))
1946 serial = app_get_serialno (card->app);
1948 err = gpg_error (GPG_ERR_INV_VALUE);
1951 send_status_direct (ctrl, "SERIALNO", serial);
1955 else if (!card->app->fnc.getattr)
1956 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1960 log_debug ("slot %d app %s: calling getattr(%s)\n",
1961 card->slot, xstrapptype (card->app), name);
1962 if (card->app->need_reset)
1963 err = gpg_error (GPG_ERR_CARD_RESET);
1965 err = card->app->fnc.getattr (card->app, ctrl, name);
1972 /* Perform a SETATTR operation. */
1974 app_setattr (card_t card, ctrl_t ctrl, const char *name,
1975 gpg_error_t (*pincb)(void*, const char *, char **),
1977 const unsigned char *value, size_t valuelen)
1981 if (!name || !*name || !value)
1982 return gpg_error (GPG_ERR_INV_VALUE);
1984 if ((err = maybe_switch_app (ctrl, card, NULL)))
1986 else if (!card->app->fnc.setattr)
1987 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1991 log_debug ("slot %d app %s: calling setattr(%s)\n",
1992 card->slot, xstrapptype (card->app), name);
1993 if (card->app->need_reset)
1994 err = gpg_error (GPG_ERR_CARD_RESET);
1996 err = card->app->fnc.setattr (card->app, ctrl, name, pincb, pincb_arg,
2004 /* Create the signature and return the allocated result in OUTDATA.
2005 If a PIN is required the PINCB will be used to ask for the PIN; it
2006 should return the PIN in an allocated buffer and put it into PIN. */
2008 app_sign (card_t card, ctrl_t ctrl, const char *keyidstr, int hashalgo,
2009 gpg_error_t (*pincb)(void*, const char *, char **),
2011 const void *indata, size_t indatalen,
2012 unsigned char **outdata, size_t *outdatalen )
2016 if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2017 return gpg_error (GPG_ERR_INV_VALUE);
2019 if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2021 else if (!card->app->fnc.sign)
2022 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2026 log_debug ("slot %d app %s: calling sign(%s)\n",
2027 card->slot, xstrapptype (card->app), keyidstr);
2028 if (card->app->need_reset)
2029 err = gpg_error (GPG_ERR_CARD_RESET);
2031 err = card->app->fnc.sign (card->app, ctrl, keyidstr, hashalgo,
2034 outdata, outdatalen);
2038 log_info ("operation sign result: %s\n", gpg_strerror (err));
2043 /* Create the signature using the INTERNAL AUTHENTICATE command and
2044 return the allocated result in OUTDATA. If a PIN is required the
2045 PINCB will be used to ask for the PIN; it should return the PIN in
2046 an allocated buffer and put it into PIN. */
2048 app_auth (card_t card, ctrl_t ctrl, const char *keyidstr,
2049 gpg_error_t (*pincb)(void*, const char *, char **),
2051 const void *indata, size_t indatalen,
2052 unsigned char **outdata, size_t *outdatalen )
2056 if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2057 return gpg_error (GPG_ERR_INV_VALUE);
2059 if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2061 else if (!card->app->fnc.auth)
2062 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2066 log_debug ("slot %d app %s: calling auth(%s)\n",
2067 card->slot, xstrapptype (card->app), keyidstr);
2068 if (card->app->need_reset)
2069 err = gpg_error (GPG_ERR_CARD_RESET);
2071 err = card->app->fnc.auth (card->app, ctrl, keyidstr,
2074 outdata, outdatalen);
2078 log_info ("operation auth result: %s\n", gpg_strerror (err));
2083 /* Decrypt the data in INDATA and return the allocated result in OUTDATA.
2084 If a PIN is required the PINCB will be used to ask for the PIN; it
2085 should return the PIN in an allocated buffer and put it into PIN. */
2087 app_decipher (card_t card, ctrl_t ctrl, const char *keyidstr,
2088 gpg_error_t (*pincb)(void*, const char *, char **),
2090 const void *indata, size_t indatalen,
2091 unsigned char **outdata, size_t *outdatalen,
2092 unsigned int *r_info)
2098 if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2099 return gpg_error (GPG_ERR_INV_VALUE);
2101 if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2103 else if (!card->app->fnc.decipher)
2104 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2108 log_debug ("slot %d app %s: calling decipher(%s)\n",
2109 card->slot, xstrapptype (card->app), keyidstr);
2110 if (card->app->need_reset)
2111 err = gpg_error (GPG_ERR_CARD_RESET);
2113 err = card->app->fnc.decipher (card->app, ctrl, keyidstr,
2116 outdata, outdatalen,
2121 log_info ("operation decipher result: %s\n", gpg_strerror (err));
2126 /* Perform the WRITECERT operation. */
2128 app_writecert (card_t card, ctrl_t ctrl,
2129 const char *certidstr,
2130 gpg_error_t (*pincb)(void*, const char *, char **),
2132 const unsigned char *data, size_t datalen)
2136 if (!certidstr || !*certidstr || !pincb)
2137 return gpg_error (GPG_ERR_INV_VALUE);
2139 if ((err = maybe_switch_app (ctrl, card, certidstr)))
2141 else if (!card->app->fnc.writecert)
2142 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2146 log_debug ("slot %d app %s: calling writecert(%s)\n",
2147 card->slot, xstrapptype (card->app), certidstr);
2148 if (card->app->need_reset)
2149 err = gpg_error (GPG_ERR_CARD_RESET);
2151 err = card->app->fnc.writecert (card->app, ctrl, certidstr,
2152 pincb, pincb_arg, data, datalen);
2156 log_info ("operation writecert result: %s\n", gpg_strerror (err));
2161 /* Perform the WRITEKEY operation. */
2163 app_writekey (card_t card, ctrl_t ctrl,
2164 const char *keyidstr, unsigned int flags,
2165 gpg_error_t (*pincb)(void*, const char *, char **),
2167 const unsigned char *keydata, size_t keydatalen)
2171 if (!keyidstr || !*keyidstr || !pincb)
2172 return gpg_error (GPG_ERR_INV_VALUE);
2174 if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2176 else if (!card->app->fnc.writekey)
2177 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2181 log_debug ("slot %d app %s: calling writekey(%s)\n",
2182 card->slot, xstrapptype (card->app), keyidstr);
2183 if (card->app->need_reset)
2184 err = gpg_error (GPG_ERR_CARD_RESET);
2186 err = card->app->fnc.writekey (card->app, ctrl, keyidstr, flags,
2187 pincb, pincb_arg, keydata, keydatalen);
2191 log_info ("operation writekey result: %s\n", gpg_strerror (err));
2196 /* Perform a GENKEY operation. */
2198 app_genkey (card_t card, ctrl_t ctrl, const char *keynostr,
2199 const char *keytype, unsigned int flags, time_t createtime,
2200 gpg_error_t (*pincb)(void*, const char *, char **),
2205 if (!keynostr || !*keynostr || !pincb)
2206 return gpg_error (GPG_ERR_INV_VALUE);
2208 if ((err = maybe_switch_app (ctrl, card, keynostr)))
2210 else if (!card->app->fnc.genkey)
2211 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2215 log_debug ("slot %d app %s: calling genkey(%s)\n",
2216 card->slot, xstrapptype (card->app), keynostr);
2217 if (card->app->need_reset)
2218 err = gpg_error (GPG_ERR_CARD_RESET);
2220 err = card->app->fnc.genkey (card->app, ctrl, keynostr, keytype, flags,
2221 createtime, pincb, pincb_arg);
2225 log_info ("operation genkey result: %s\n", gpg_strerror (err));
2230 /* Perform a GET CHALLENGE operation. This function is special as it
2231 directly accesses the card without any application specific
2234 app_get_challenge (card_t card, ctrl_t ctrl,
2235 size_t nbytes, unsigned char *buffer)
2238 if (!nbytes || !buffer)
2239 return gpg_error (GPG_ERR_INV_VALUE);
2241 return iso7816_get_challenge (card->slot, nbytes, buffer);
2245 /* Perform a CHANGE REFERENCE DATA or RESET RETRY COUNTER operation. */
2247 app_change_pin (card_t card, ctrl_t ctrl, const char *chvnostr,
2249 gpg_error_t (*pincb)(void*, const char *, char **),
2254 if (!chvnostr || !*chvnostr || !pincb)
2255 return gpg_error (GPG_ERR_INV_VALUE);
2257 if ((err = maybe_switch_app (ctrl, card, NULL)))
2259 else if (!card->app->fnc.change_pin)
2260 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2264 log_debug ("slot %d app %s: calling change_pin(%s)\n",
2265 card->slot, xstrapptype (card->app), chvnostr);
2266 if (card->app->need_reset)
2267 err = gpg_error (GPG_ERR_CARD_RESET);
2269 err = card->app->fnc.change_pin (card->app, ctrl,
2270 chvnostr, flags, pincb, pincb_arg);
2274 log_info ("operation change_pin result: %s\n", gpg_strerror (err));
2279 /* Perform a VERIFY operation without doing anything else. This may
2280 be used to initialize a the PIN cache for long lasting other
2281 operations. Its use is highly application dependent. */
2283 app_check_pin (card_t card, ctrl_t ctrl, const char *keyidstr,
2284 gpg_error_t (*pincb)(void*, const char *, char **),
2289 if (!keyidstr || !*keyidstr || !pincb)
2290 return gpg_error (GPG_ERR_INV_VALUE);
2292 if ((err = maybe_switch_app (ctrl, card, NULL)))
2294 else if (!card->app->fnc.check_pin)
2295 err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2299 log_debug ("slot %d app %s: calling check_pin(%s)\n",
2300 card->slot, xstrapptype (card->app), keyidstr);
2301 if (card->app->need_reset)
2302 err = gpg_error (GPG_ERR_CARD_RESET);
2304 err = card->app->fnc.check_pin (card->app, ctrl, keyidstr,
2309 log_info ("operation check_pin result: %s\n", gpg_strerror (err));
2315 report_change (int slot, int old_status, int cur_status)
2317 char *homestr, *envstr;
2322 snprintf (templ, sizeof templ, "reader_%d.status", slot);
2323 fname = make_filename (gnupg_homedir (), templ, NULL );
2324 fp = es_fopen (fname, "w");
2327 es_fprintf (fp, "%s\n",
2328 (cur_status & 1)? "USABLE":
2329 (cur_status & 4)? "ACTIVE":
2330 (cur_status & 2)? "PRESENT": "NOCARD");
2335 homestr = make_filename (gnupg_homedir (), NULL);
2336 if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2337 log_error ("out of core while building environment\n");
2341 const char *args[9], *envs[2];
2342 char numbuf1[30], numbuf2[30], numbuf3[30];
2347 sprintf (numbuf1, "%d", slot);
2348 sprintf (numbuf2, "0x%04X", old_status);
2349 sprintf (numbuf3, "0x%04X", cur_status);
2350 args[0] = "--reader-port";
2352 args[2] = "--old-code";
2354 args[4] = "--new-code";
2356 args[6] = "--status";
2357 args[7] = ((cur_status & 1)? "USABLE":
2358 (cur_status & 4)? "ACTIVE":
2359 (cur_status & 2)? "PRESENT": "NOCARD");
2362 fname = make_filename (gnupg_homedir (), "scd-event", NULL);
2363 err = gnupg_spawn_process_detached (fname, args, envs);
2364 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2365 log_error ("failed to run event handler '%s': %s\n",
2366 fname, gpg_strerror (err));
2375 scd_update_reader_status_file (void)
2377 card_t card, card_next;
2378 int periodical_check_needed = 0;
2381 card_list_w_lock ();
2382 for (card = card_top; card; card = card_next)
2385 unsigned int status;
2387 lock_card (card, NULL);
2388 card_next = card->next;
2390 if (card->reset_requested)
2392 /* Here is the post-processing of RESET request. */
2394 card->reset_requested = 0;
2398 sw = apdu_get_status (card->slot, 0, &status);
2399 if (sw == SW_HOST_NO_READER)
2401 /* Most likely the _reader_ has been unplugged. */
2406 /* Get status failed. Ignore that. */
2407 if (card->periodical_check_needed)
2408 periodical_check_needed = 1;
2414 if (card->card_status != status)
2416 report_change (card->slot, card->card_status, status);
2417 send_client_notifications (card, status == 0);
2423 log_debug ("Removal of a card: %d\n", card->slot);
2424 pincache_put (NULL, card->slot, NULL, NULL, NULL, 0);
2425 apdu_close_reader (card->slot);
2426 deallocate_card (card);
2430 card->card_status = status;
2431 if (card->periodical_check_needed)
2432 periodical_check_needed = 1;
2438 if (card->periodical_check_needed)
2439 periodical_check_needed = 1;
2445 card_list_signal ();
2447 card_list_w_unlock ();
2449 return periodical_check_needed;
2452 /* This function must be called once to initialize this module. This
2453 has to be done before a second thread is spawned. We can't do the
2454 static initialization because Pth emulation code might not be able
2455 to do a static init; in particular, it is not possible for W32. */
2457 initialize_module_command (void)
2461 card_list_lock.num_readers_active = 0;
2462 card_list_lock.num_writers_waiting = 0;
2463 card_list_lock.writer_active = 0;
2465 if (npth_mutex_init (&card_list_lock.lock, NULL))
2467 err = gpg_error_from_syserror ();
2468 log_error ("app: error initializing mutex: %s\n", gpg_strerror (err));
2472 err = npth_cond_init (&card_list_lock.cond, NULL);
2475 err = gpg_error_from_syserror ();
2476 log_error ("npth_cond_init failed: %s\n", gpg_strerror (err));
2480 err = npth_cond_init (&card_list_lock.notify_cond, NULL);
2483 err = gpg_error_from_syserror ();
2484 log_error ("npth_cond_init failed: %s\n", gpg_strerror (err));
2488 return apdu_init ();
2492 /* Sort helper for app_send_card_list. */
2494 compare_card_list_items (const void *arg_a, const void *arg_b)
2496 const card_t a = *(const card_t *)arg_a;
2497 const card_t b = *(const card_t *)arg_b;
2499 return a->slot - b->slot;
2503 /* Helper for send_card_and_app_list and app_switch_active_app. */
2505 send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl)
2514 serial = card_get_serialno (card);
2516 return 0; /* Oops. */
2520 /* Note that in case the additional applications have not yet been
2521 * added to the card context (which is commonly done by means of
2522 * "SERIALNO --all", we do that here. */
2523 err = select_all_additional_applications_internal (ctrl, card);
2530 init_membuf (&mb, 256);
2531 put_membuf_str (&mb, serial);
2532 for (a = card->app; a; a = a->next)
2534 if (!a->fnc.with_keygrip || a->need_reset)
2537 put_membuf (&mb, " ", 1);
2538 put_membuf_str (&mb, xstrapptype (a));
2540 if (!any && card->app)
2542 /* No card app supports the with_keygrip function. Use the
2543 * main app as fallback. */
2544 put_membuf (&mb, " ", 1);
2545 put_membuf_str (&mb, xstrapptype (card->app));
2547 put_membuf (&mb, "", 1);
2548 p = get_membuf (&mb, NULL);
2551 err = gpg_error_from_syserror ();
2555 send_status_direct (ctrl, "SERIALNO", p);
2559 send_status_direct (ctrl, "SERIALNO", serial);
2566 /* Common code for app_send_card_list and app_send_active_apps. */
2568 send_card_and_app_list (ctrl_t ctrl, card_t wantcard, int with_apps)
2572 card_t *cardlist = NULL;
2575 card_list_r_lock ();
2576 for (n=0, c = card_top; c; c = c->next)
2580 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
2583 cardlist = xtrycalloc (n, sizeof *cardlist);
2586 err = gpg_error_from_syserror ();
2589 for (ncardlist=0, c = card_top; c; c = c->next)
2590 cardlist[ncardlist++] = c;
2591 qsort (cardlist, ncardlist, sizeof *cardlist, compare_card_list_items);
2593 for (n=0; n < ncardlist; n++)
2595 if (wantcard && wantcard != cardlist[n])
2597 err = send_serialno_and_app_status (cardlist[n], with_apps, ctrl);
2605 card_list_r_unlock ();
2611 /* Send status lines with the serialno of all inserted cards. */
2613 app_send_card_list (ctrl_t ctrl)
2615 return send_card_and_app_list (ctrl, NULL, 0);
2619 /* Send status lines with the serialno and appname of the current card
2620 * or of all cards if CARD is NULL. */
2622 app_send_active_apps (card_t card, ctrl_t ctrl)
2624 return send_card_and_app_list (ctrl, card, 1);
2628 /* Switch to APPNAME and print a respective status line with that app
2629 * listed first. If APPNAME is NULL or the empty string no switching
2630 * is done but the status line is printed anyway. */
2632 app_switch_active_app (card_t card, ctrl_t ctrl, const char *appname)
2637 /* Note that in case the additional applications have not yet been
2638 * added to the card context (which is commonly done by means of
2639 * "SERIALNO --all", we do that here. */
2640 err = select_all_additional_applications_internal (ctrl, card);
2644 if (appname && *appname)
2646 apptype = apptype_from_name (appname);
2649 err = gpg_error (GPG_ERR_NOT_FOUND);
2653 ctrl->current_apptype = apptype;
2654 err = maybe_switch_app (ctrl, card, NULL);
2659 /* Print the status line. */
2660 err = send_serialno_and_app_status (card, 1, ctrl);
2667 /* Execute an action for each app. ACTION can be one of:
2669 * - KEYGRIP_ACTION_SEND_DATA
2671 * If KEYGRIP_STR matches a public key of any active application
2672 * send information as LF terminated data lines about the public
2673 * key. The format of these lines is
2674 * <keygrip> T <serialno> <idstr>
2675 * If a match was found a pointer to the matching application is
2676 * returned. With the KEYGRIP_STR given as NULL, lines for all
2677 * keys (with CAPABILITY) will be send and the return value is
2680 * - KEYGRIP_ACTION_WRITE_STATUS
2682 * Same as KEYGRIP_ACTION_SEND_DATA but uses status lines instead
2685 * - KEYGRIP_ACTION_LOOKUP
2687 * Returns a pointer to the application matching KEYGRIP_STR but
2688 * does not emit any status or data lines. If no key with that
2689 * keygrip is available or KEYGRIP_STR is NULL, GPG_ERR_NOT_FOUND
2693 app_do_with_keygrip (ctrl_t ctrl, int action, const char *keygrip_str,
2698 card_list_r_lock ();
2699 card = do_with_keygrip (ctrl, action, keygrip_str, capability);
2700 card_list_r_unlock ();