1 /* command.c - SCdaemon command handler
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2007, 2008, 2009, 2011 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
36 #include "app-common.h"
38 #include "apdu.h" /* Required for apdu_*_reader (). */
42 #include "ccid-driver.h"
46 /* Maximum length allowed as a PIN; used for INQUIRE NEEDPIN */
47 #define MAXLEN_PIN 100
49 /* Maximum allowed size of key data as used in inquiries. */
50 #define MAXLEN_KEYDATA 4096
52 /* Maximum allowed total data size for SETDATA. */
53 #define MAXLEN_SETDATA 4096
55 /* Maximum allowed size of certificate data as used in inquiries. */
56 #define MAXLEN_CERTDATA 16384
59 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
62 /* Macro to flag a removed card. ENODEV is also tested to catch teh
63 case of a removed reader. */
64 #define TEST_CARD_REMOVAL(c,r) \
67 if (gpg_err_code (_r) == GPG_ERR_CARD_NOT_PRESENT \
68 || gpg_err_code (_r) == GPG_ERR_CARD_REMOVED \
69 || gpg_err_code (_r) == GPG_ERR_CARD_RESET \
70 || gpg_err_code (_r) == GPG_ERR_ENODEV ) \
71 update_card_removed ((c)->server_local->vreader_idx, 1); \
74 #define IS_LOCKED(c) \
76 && locked_session != (c)->server_local \
77 && (c)->server_local->vreader_idx != -1 \
78 && locked_session->ctrl_backlink \
79 && ((c)->server_local->vreader_idx \
80 == locked_session->ctrl_backlink->server_local->vreader_idx))
83 /* This structure is used to keep track of user readers. To
84 eventually accommodate this structure for RFID cards, where more
85 than one card is used per reader, we name it virtual reader. */
88 int valid; /* True if the other objects are valid. */
89 int slot; /* APDU slot number of the reader or -1 if not open. */
91 int reset_failed; /* A reset failed. */
93 int any; /* Flag indicating whether any status check has been
94 done. This is set once to indicate that the status
95 tracking for the slot has been initialized. */
96 unsigned int status; /* Last status of the reader. */
97 unsigned int changed; /* Last change counter of the reader. */
101 /* Data used to associate an Assuan context with local server data.
102 This object describes the local properties of one session. */
103 struct server_local_s
105 /* We keep a list of all active sessions with the anchor at
106 SESSION_LIST (see below). This field is used for linking. */
107 struct server_local_s *next_session;
109 /* This object is usually assigned to a CTRL object (which is
110 globally visible). While enumerating all sessions we sometimes
111 need to access data of the CTRL object; thus we keep a
113 ctrl_t ctrl_backlink;
115 /* The Assuan context used by this session/server. */
116 assuan_context_t assuan_ctx;
118 #ifdef HAVE_W32_SYSTEM
119 unsigned long event_signal; /* Or 0 if not used. */
121 int event_signal; /* Or 0 if not used. */
124 /* Index into the vreader table (command.c) or -1 if not open. */
127 /* True if the card has been removed and a reset is required to
128 continue operation. */
131 /* Flag indicating that the application context needs to be released
132 at the next opportunity. */
133 int app_ctx_marked_for_release;
135 /* A disconnect command has been sent. */
136 int disconnect_allowed;
138 /* If set to true we will be terminate ourself at the end of the
145 /* The table with information on all used virtual readers. */
146 static struct vreader_s vreader_table[10];
149 /* To keep track of all running sessions, we link all active server
150 contexts and the anchor in this variable. */
151 static struct server_local_s *session_list;
153 /* If a session has been locked we store a link to its server object
155 static struct server_local_s *locked_session;
157 /* While doing a reset we need to make sure that the ticker does not
158 call scd_update_reader_status_file while we are using it. */
159 static npth_mutex_t status_file_update_lock;
162 /*-- Local prototypes --*/
163 static void update_reader_status_file (int set_card_removed_flag);
168 /* This function must be called once to initialize this module. This
169 has to be done before a second thread is spawned. We can't do the
170 static initialization because Pth emulation code might not be able
171 to do a static init; in particular, it is not possible for W32. */
173 initialize_module_command (void)
175 static int initialized;
180 err = npth_mutex_init (&status_file_update_lock, NULL);
187 /* Helper to return the slot number for a given virtual reader index
188 VRDR. In case on an error -1 is returned. */
190 vreader_slot (int vrdr)
192 if (vrdr == -1 || !(vrdr >= 0 && vrdr < DIM(vreader_table)))
194 if (!vreader_table [vrdr].valid)
196 return vreader_table[vrdr].slot;
200 /* Update the CARD_REMOVED element of all sessions using the virtual
201 reader given by VRDR to VALUE. */
203 update_card_removed (int vrdr, int value)
205 struct server_local_s *sl;
210 for (sl=session_list; sl; sl = sl->next_session)
211 if (sl->ctrl_backlink
212 && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
214 sl->card_removed = value;
216 /* Let the card application layer know about the removal. */
218 application_notify_card_reset (vreader_slot (vrdr));
222 /* Check whether the option NAME appears in LINE. Returns 1 or 0. */
224 has_option (const char *line, const char *name)
227 int n = strlen (name);
229 s = strstr (line, name);
230 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
233 /* Same as has_option but does only test for the name of the option
234 and ignores an argument, i.e. with NAME being "--hash" it would
235 return a pointer for "--hash" as well as for "--hash=foo". If
236 there is no such option NULL is returned. The pointer returned
237 points right behind the option name, this may be an equal sign, Nul
240 has_option_name (const char *line, const char *name)
243 int n = strlen (name);
245 s = strstr (line, name);
246 return (s && (s == line || spacep (s-1))
247 && (!s[n] || spacep (s+n) || s[n] == '=')) ? (s+n) : NULL;
251 /* Skip over options. It is assumed that leading spaces have been
252 removed (this is the case for lines passed to a handler from
253 assuan). Blanks after the options are also removed. */
255 skip_options (char *line)
257 while ( *line == '-' && line[1] == '-' )
259 while (*line && !spacep (line))
261 while (spacep (line))
269 /* Convert the STRING into a newly allocated buffer while translating
270 the hex numbers. Stops at the first invalid character. Blanks and
271 colons are allowed to separate the hex digits. Returns NULL on
272 error or a newly malloced buffer and its length in LENGTH. */
273 static unsigned char *
274 hex_to_buffer (const char *string, size_t *r_length)
276 unsigned char *buffer;
280 buffer = xtrymalloc (strlen (string)+1);
283 for (s=string, n=0; *s; s++)
285 if (spacep (s) || *s == ':')
287 if (hexdigitp (s) && hexdigitp (s+1))
289 buffer[n++] = xtoi_2 (s);
301 /* Reset the card and free the application context. With SEND_RESET
302 set to true actually send a RESET to the reader; this is the normal
303 way of calling the function. */
305 do_reset (ctrl_t ctrl, int send_reset)
307 int vrdr = ctrl->server_local->vreader_idx;
311 if (!(vrdr == -1 || (vrdr >= 0 && vrdr < DIM(vreader_table))))
314 /* If there is an active application, release it. Tell all other
315 sessions using the same application to release the
319 release_application (ctrl->app_ctx);
320 ctrl->app_ctx = NULL;
323 struct server_local_s *sl;
325 for (sl=session_list; sl; sl = sl->next_session)
326 if (sl->ctrl_backlink
327 && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
329 sl->app_ctx_marked_for_release = 1;
334 /* If we want a real reset for the card, send the reset APDU and
335 tell the application layer about it. */
336 slot = vreader_slot (vrdr);
337 if (slot != -1 && send_reset && !IS_LOCKED (ctrl) )
339 application_notify_card_reset (slot);
340 switch (apdu_reset (slot))
344 case SW_HOST_NO_CARD:
345 case SW_HOST_CARD_INACTIVE:
348 apdu_close_reader (slot);
349 vreader_table[vrdr].slot = slot = -1;
354 /* If we hold a lock, unlock now. */
355 if (locked_session && ctrl->server_local == locked_session)
357 locked_session = NULL;
358 log_info ("implicitly unlocking due to RESET\n");
361 /* Reset the card removed flag for the current reader. We need to
362 take the lock here so that the ticker thread won't concurrently
363 try to update the file. Calling update_reader_status_file is
364 required to get hold of the new status of the card in the vreader
366 err = npth_mutex_lock (&status_file_update_lock);
369 log_error ("failed to acquire status_file_update lock\n");
370 ctrl->server_local->vreader_idx = -1;
373 update_reader_status_file (0); /* Update slot status table. */
374 update_card_removed (vrdr, 0); /* Clear card_removed flag. */
375 err = npth_mutex_unlock (&status_file_update_lock);
377 log_error ("failed to release status_file_update lock: %s\n",
380 /* Do this last, so that the update_card_removed above does its job. */
381 ctrl->server_local->vreader_idx = -1;
386 reset_notify (assuan_context_t ctx, char *line)
388 ctrl_t ctrl = assuan_get_pointer (ctx);
398 option_handler (assuan_context_t ctx, const char *key, const char *value)
400 ctrl_t ctrl = assuan_get_pointer (ctx);
402 if (!strcmp (key, "event-signal"))
404 /* A value of 0 is allowed to reset the event signal. */
405 #ifdef HAVE_W32_SYSTEM
407 return gpg_error (GPG_ERR_ASS_PARAMETER);
408 ctrl->server_local->event_signal = strtoul (value, NULL, 16);
410 int i = *value? atoi (value) : -1;
412 return gpg_error (GPG_ERR_ASS_PARAMETER);
413 ctrl->server_local->event_signal = i;
421 /* Return the index of the current reader or open the reader if no
422 other sessions are using that reader. If it is not possible to
423 open the reader -1 is returned. Note, that we currently support
424 only one reader but most of the code (except for this function)
425 should be able to cope with several readers. */
427 get_current_reader (void)
429 struct vreader_s *vr;
431 /* We only support one reader for now. */
432 vr = &vreader_table[0];
434 /* Initialize the vreader item if not yet done. */
441 /* Try to open the reader. */
444 vr->slot = apdu_open_reader (opt.reader_port);
446 /* If we still don't have a slot, we have no readers.
447 Invalidate for now until a reader is attached. */
454 /* Return the vreader index or -1. */
455 return vr->valid ? 0 : -1;
459 /* If the card has not yet been opened, do it. */
461 open_card (ctrl_t ctrl, const char *apptype)
466 /* If we ever got a card not present error code, return that. Only
467 the SERIALNO command and a reset are able to clear from that
469 if (ctrl->server_local->card_removed)
470 return gpg_error (GPG_ERR_CARD_REMOVED);
472 if ( IS_LOCKED (ctrl) )
473 return gpg_error (GPG_ERR_LOCKED);
475 /* If the application has been marked for release do it now. We
476 can't do it immediately in do_reset because the application may
478 if (ctrl->server_local->app_ctx_marked_for_release)
480 ctrl->server_local->app_ctx_marked_for_release = 0;
481 release_application (ctrl->app_ctx);
482 ctrl->app_ctx = NULL;
485 /* If we are already initialized for one specific application we
486 need to check that the client didn't requested a specific
487 application different from the one in use before we continue. */
490 return check_application_conflict
491 (ctrl, vreader_slot (ctrl->server_local->vreader_idx), apptype);
494 /* Setup the vreader and select the application. */
495 if (ctrl->server_local->vreader_idx != -1)
496 vrdr = ctrl->server_local->vreader_idx;
498 vrdr = get_current_reader ();
499 ctrl->server_local->vreader_idx = vrdr;
501 err = gpg_error (GPG_ERR_CARD);
504 /* Fixme: We should move the apdu_connect call to
505 select_application. */
507 int slot = vreader_slot (vrdr);
509 ctrl->server_local->disconnect_allowed = 0;
510 sw = apdu_connect (slot);
511 if (sw && sw != SW_HOST_ALREADY_CONNECTED)
513 if (sw == SW_HOST_NO_CARD)
514 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
515 else if (sw == SW_HOST_CARD_INACTIVE)
516 err = gpg_error (GPG_ERR_CARD_RESET);
518 err = gpg_error (GPG_ERR_CARD);
521 err = select_application (ctrl, slot, apptype, &ctrl->app_ctx);
524 TEST_CARD_REMOVAL (ctrl, err);
529 static const char hlp_serialno[] =
530 "SERIALNO [<apptype>]\n"
532 "Return the serial number of the card using a status reponse. This\n"
533 "function should be used to check for the presence of a card.\n"
535 "If APPTYPE is given, an application of that type is selected and an\n"
536 "error is returned if the application is not supported or available.\n"
537 "The default is to auto-select the application using a hardwired\n"
538 "preference system. Note, that a future extension to this function\n"
539 "may allow to specify a list and order of applications to try.\n"
541 "This function is special in that it can be used to reset the card.\n"
542 "Most other functions will return an error when a card change has\n"
543 "been detected and the use of this function is therefore required.\n"
545 "Background: We want to keep the client clear of handling card\n"
546 "changes between operations; i.e. the client can assume that all\n"
547 "operations are done on the same card unless he calls this function.";
549 cmd_serialno (assuan_context_t ctx, char *line)
551 ctrl_t ctrl = assuan_get_pointer (ctx);
557 /* Clear the remove flag so that the open_card is able to reread it. */
559 if (ctrl->server_local->card_removed)
561 if ( IS_LOCKED (ctrl) )
562 return gpg_error (GPG_ERR_LOCKED);
566 if ((rc = open_card (ctrl, *line? line:NULL)))
568 /* In case of an inactive card, retry once. */
569 if (gpg_err_code (rc) == GPG_ERR_CARD_RESET && retries++ < 1)
574 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
578 rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
579 serial, (unsigned long)stamp);
585 static const char hlp_learn[] =
586 "LEARN [--force] [--keypairinfo]\n"
588 "Learn all useful information of the currently inserted card. When\n"
589 "used without the force options, the command might do an INQUIRE\n"
592 " INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>\n"
594 "The client should just send an \"END\" if the processing should go on\n"
595 "or a \"CANCEL\" to force the function to terminate with a Cancel\n"
598 "With the option --keypairinfo only KEYPARIINFO lstatus lines are\n"
601 "The response of this command is a list of status lines formatted as\n"
604 " S APPTYPE <apptype>\n"
606 "This returns the type of the application, currently the strings:\n"
608 " P15 = PKCS-15 structure used\n"
609 " DINSIG = DIN SIG\n"
610 " OPENPGP = OpenPGP card\n"
611 " NKS = NetKey card\n"
613 "are implemented. These strings are aliases for the AID\n"
615 " S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>\n"
617 "If there is no certificate yet stored on the card a single 'X' is\n"
618 "returned as the keygrip. In addition to the keypair info, information\n"
619 "about all certificates stored on the card is also returned:\n"
621 " S CERTINFO <certtype> <hexstring_with_id>\n"
623 "Where CERTTYPE is a number indicating the type of certificate:\n"
625 " 100 := Regular X.509 cert\n"
626 " 101 := Trusted X.509 cert\n"
627 " 102 := Useful X.509 cert\n"
628 " 110 := Root CA cert in a special format (e.g. DINSIG)\n"
629 " 111 := Root CA cert as standard X509 cert.\n"
631 "For certain cards, more information will be returned:\n"
633 " S KEY-FPR <no> <hexstring>\n"
635 "For OpenPGP cards this returns the stored fingerprints of the\n"
636 "keys. This can be used check whether a key is available on the\n"
637 "card. NO may be 1, 2 or 3.\n"
639 " S CA-FPR <no> <hexstring>\n"
641 "Similar to above, these are the fingerprints of keys assumed to be\n"
642 "ultimately trusted.\n"
644 " S DISP-NAME <name_of_card_holder>\n"
646 "The name of the card holder as stored on the card; percent\n"
647 "escaping takes place, spaces are encoded as '+'\n"
649 " S PUBKEY-URL <url>\n"
651 "The URL to be used for locating the entire public key.\n"
653 "Note, that this function may even be used on a locked card.";
655 cmd_learn (assuan_context_t ctx, char *line)
657 ctrl_t ctrl = assuan_get_pointer (ctx);
659 int only_keypairinfo = has_option (line, "--keypairinfo");
661 if ((rc = open_card (ctrl, NULL)))
664 /* Unless the force option is used we try a shortcut by identifying
665 the card using a serial number and inquiring the client with
666 that. The client may choose to cancel the operation if he already
667 knows about this card */
668 if (!only_keypairinfo)
673 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
677 rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
678 serial, (unsigned long)stamp);
682 return out_of_core ();
685 if (!has_option (line, "--force"))
689 rc = gpgrt_asprintf (&command, "KNOWNCARDP %s %lu",
690 serial, (unsigned long)stamp);
694 return out_of_core ();
696 rc = assuan_inquire (ctx, command, NULL, NULL, 0);
700 if (gpg_err_code (rc) != GPG_ERR_ASS_CANCELED)
701 log_error ("inquire KNOWNCARDP failed: %s\n",
706 /* Not canceled, so we have to proceeed. */
711 /* Let the application print out its collection of useful status
714 rc = app_write_learn_status (ctrl->app_ctx, ctrl, only_keypairinfo);
716 TEST_CARD_REMOVAL (ctrl, rc);
722 static const char hlp_readcert[] =
723 "READCERT <hexified_certid>|<keyid>\n"
725 "Note, that this function may even be used on a locked card.";
727 cmd_readcert (assuan_context_t ctx, char *line)
729 ctrl_t ctrl = assuan_get_pointer (ctx);
734 if ((rc = open_card (ctrl, NULL)))
737 line = xstrdup (line); /* Need a copy of the line. */
738 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
740 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
745 rc = assuan_send_data (ctx, cert, ncert);
751 TEST_CARD_REMOVAL (ctrl, rc);
756 static const char hlp_readkey[] =
759 "Return the public key for the given cert or key ID as a standard\n"
762 "Note, that this function may even be used on a locked card.";
764 cmd_readkey (assuan_context_t ctx, char *line)
766 ctrl_t ctrl = assuan_get_pointer (ctx);
768 unsigned char *cert = NULL;
770 ksba_cert_t kc = NULL;
775 if ((rc = open_card (ctrl, NULL)))
778 line = xstrdup (line); /* Need a copy of the line. */
779 /* If the application supports the READKEY function we use that.
780 Otherwise we use the old way by extracting it from the
782 rc = app_readkey (ctrl->app_ctx, line, &pk, &pklen);
784 { /* Yeah, got that key - send it back. */
785 rc = assuan_send_data (ctx, pk, pklen);
792 if (gpg_err_code (rc) != GPG_ERR_UNSUPPORTED_OPERATION)
793 log_error ("app_readkey failed: %s\n", gpg_strerror (rc));
796 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
798 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
805 rc = ksba_cert_new (&kc);
811 rc = ksba_cert_init_from_mem (kc, cert, ncert);
814 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc));
818 p = ksba_cert_get_public_key (kc);
821 rc = gpg_error (GPG_ERR_NO_PUBKEY);
825 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
826 rc = assuan_send_data (ctx, p, n);
831 ksba_cert_release (kc);
833 TEST_CARD_REMOVAL (ctrl, rc);
839 static const char hlp_setdata[] =
840 "SETDATA [--append] <hexstring>\n"
842 "The client should use this command to tell us the data he want to sign.\n"
843 "With the option --append, the data is appended to the data set by a\n"
844 "previous SETDATA command.";
846 cmd_setdata (assuan_context_t ctx, char *line)
848 ctrl_t ctrl = assuan_get_pointer (ctx);
854 append = (ctrl->in_data.value && has_option (line, "--append"));
856 line = skip_options (line);
858 if (locked_session && locked_session != ctrl->server_local)
859 return gpg_error (GPG_ERR_LOCKED);
861 /* Parse the hexstring. */
862 for (p=line,n=0; hexdigitp (p); p++, n++)
865 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
867 return set_error (GPG_ERR_ASS_PARAMETER, "no data given");
869 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
873 if (ctrl->in_data.valuelen + n > MAXLEN_SETDATA)
874 return set_error (GPG_ERR_TOO_LARGE,
875 "limit on total size of data reached");
876 buf = xtrymalloc (ctrl->in_data.valuelen + n);
879 buf = xtrymalloc (n);
881 return out_of_core ();
885 memcpy (buf, ctrl->in_data.value, ctrl->in_data.valuelen);
886 off = ctrl->in_data.valuelen;
890 for (p=line, i=0; i < n; p += 2, i++)
891 buf[off+i] = xtoi_2 (p);
893 xfree (ctrl->in_data.value);
894 ctrl->in_data.value = buf;
895 ctrl->in_data.valuelen = off+n;
902 pin_cb (void *opaque, const char *info, char **retstr)
904 assuan_context_t ctx = opaque;
907 unsigned char *value;
912 /* We prompt for pinpad entry. To make sure that the popup has
913 been show we use an inquire and not just a status message.
914 We ignore any value returned. */
917 log_debug ("prompting for pinpad entry '%s'\n", info);
918 rc = gpgrt_asprintf (&command, "POPUPPINPADPROMPT %s", info);
920 return gpg_error (gpg_err_code_from_errno (errno));
921 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
926 log_debug ("dismiss pinpad entry prompt\n");
927 rc = assuan_inquire (ctx, "DISMISSPINPADPROMPT",
928 &value, &valuelen, MAXLEN_PIN);
936 log_debug ("asking for PIN '%s'\n", info);
938 rc = gpgrt_asprintf (&command, "NEEDPIN %s", info);
940 return gpg_error (gpg_err_code_from_errno (errno));
942 /* Fixme: Write an inquire function which returns the result in
943 secure memory and check all further handling of the PIN. */
944 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
949 if (!valuelen || value[valuelen-1])
951 /* We require that the returned value is an UTF-8 string */
953 return gpg_error (GPG_ERR_INV_RESPONSE);
955 *retstr = (char*)value;
960 static const char hlp_pksign[] =
961 "PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>\n"
963 "The --hash option is optional; the default is SHA1.";
965 cmd_pksign (assuan_context_t ctx, char *line)
967 ctrl_t ctrl = assuan_get_pointer (ctx);
969 unsigned char *outdata;
974 if (has_option (line, "--hash=rmd160"))
975 hash_algo = GCRY_MD_RMD160;
976 else if (has_option (line, "--hash=sha1"))
977 hash_algo = GCRY_MD_SHA1;
978 else if (has_option (line, "--hash=sha224"))
979 hash_algo = GCRY_MD_SHA224;
980 else if (has_option (line, "--hash=sha256"))
981 hash_algo = GCRY_MD_SHA256;
982 else if (has_option (line, "--hash=sha384"))
983 hash_algo = GCRY_MD_SHA384;
984 else if (has_option (line, "--hash=sha512"))
985 hash_algo = GCRY_MD_SHA512;
986 else if (has_option (line, "--hash=md5"))
987 hash_algo = GCRY_MD_MD5;
988 else if (!strstr (line, "--"))
989 hash_algo = GCRY_MD_SHA1;
991 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
993 line = skip_options (line);
995 if ( IS_LOCKED (ctrl) )
996 return gpg_error (GPG_ERR_LOCKED);
998 if ((rc = open_card (ctrl, NULL)))
1001 /* We have to use a copy of the key ID because the function may use
1002 the pin_cb which in turn uses the assuan line buffer and thus
1003 overwriting the original line with the keyid */
1004 keyidstr = xtrystrdup (line);
1006 return out_of_core ();
1008 rc = app_sign (ctrl->app_ctx,
1009 keyidstr, hash_algo,
1011 ctrl->in_data.value, ctrl->in_data.valuelen,
1012 &outdata, &outdatalen);
1017 log_error ("app_sign failed: %s\n", gpg_strerror (rc));
1021 rc = assuan_send_data (ctx, outdata, outdatalen);
1024 return rc; /* that is already an assuan error code */
1027 TEST_CARD_REMOVAL (ctrl, rc);
1032 static const char hlp_pkauth[] =
1033 "PKAUTH <hexified_id>";
1035 cmd_pkauth (assuan_context_t ctx, char *line)
1037 ctrl_t ctrl = assuan_get_pointer (ctx);
1039 unsigned char *outdata;
1043 if ( IS_LOCKED (ctrl) )
1044 return gpg_error (GPG_ERR_LOCKED);
1046 if ((rc = open_card (ctrl, NULL)))
1050 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1052 /* We have to use a copy of the key ID because the function may use
1053 the pin_cb which in turn uses the assuan line buffer and thus
1054 overwriting the original line with the keyid */
1055 keyidstr = xtrystrdup (line);
1057 return out_of_core ();
1059 rc = app_auth (ctrl->app_ctx,
1062 ctrl->in_data.value, ctrl->in_data.valuelen,
1063 &outdata, &outdatalen);
1067 log_error ("app_auth failed: %s\n", gpg_strerror (rc));
1071 rc = assuan_send_data (ctx, outdata, outdatalen);
1074 return rc; /* that is already an assuan error code */
1077 TEST_CARD_REMOVAL (ctrl, rc);
1082 static const char hlp_pkdecrypt[] =
1083 "PKDECRYPT <hexified_id>";
1085 cmd_pkdecrypt (assuan_context_t ctx, char *line)
1087 ctrl_t ctrl = assuan_get_pointer (ctx);
1089 unsigned char *outdata;
1092 unsigned int infoflags;
1094 if ( IS_LOCKED (ctrl) )
1095 return gpg_error (GPG_ERR_LOCKED);
1097 if ((rc = open_card (ctrl, NULL)))
1100 keyidstr = xtrystrdup (line);
1102 return out_of_core ();
1103 rc = app_decipher (ctrl->app_ctx,
1106 ctrl->in_data.value, ctrl->in_data.valuelen,
1107 &outdata, &outdatalen, &infoflags);
1112 log_error ("app_decipher failed: %s\n", gpg_strerror (rc));
1116 /* If the card driver told us that there is no padding, send a
1117 status line. If there is a padding it is assumed that the
1118 caller knows what padding is used. It would have been better
1119 to always send that information but for backward
1120 compatibility we can't do that. */
1121 if ((infoflags & APP_DECIPHER_INFO_NOPAD))
1122 send_status_direct (ctrl, "PADDING", "0");
1123 rc = assuan_send_data (ctx, outdata, outdatalen);
1126 return rc; /* that is already an assuan error code */
1129 TEST_CARD_REMOVAL (ctrl, rc);
1134 static const char hlp_getattr[] =
1137 "This command is used to retrieve data from a smartcard. The\n"
1138 "allowed names depend on the currently selected smartcard\n"
1139 "application. NAME must be percent and '+' escaped. The value is\n"
1140 "returned through status message, see the LEARN command for details.\n"
1142 "However, the current implementation assumes that Name is not escaped;\n"
1143 "this works as long as noone uses arbitrary escaping. \n"
1145 "Note, that this function may even be used on a locked card.";
1147 cmd_getattr (assuan_context_t ctx, char *line)
1149 ctrl_t ctrl = assuan_get_pointer (ctx);
1151 const char *keyword;
1153 if ((rc = open_card (ctrl, NULL)))
1157 for (; *line && !spacep (line); line++)
1162 /* (We ignore any garbage for now.) */
1164 /* FIXME: Applications should not return sensitive data if the card
1166 rc = app_getattr (ctrl->app_ctx, ctrl, keyword);
1168 TEST_CARD_REMOVAL (ctrl, rc);
1173 static const char hlp_setattr[] =
1174 "SETATTR <name> <value> \n"
1176 "This command is used to store data on a a smartcard. The allowed\n"
1177 "names and values are depend on the currently selected smartcard\n"
1178 "application. NAME and VALUE must be percent and '+' escaped.\n"
1180 "However, the current implementation assumes that NAME is not\n"
1181 "escaped; this works as long as noone uses arbitrary escaping.\n"
1183 "A PIN will be requested for most NAMEs. See the corresponding\n"
1184 "setattr function of the actually used application (app-*.c) for\n"
1187 cmd_setattr (assuan_context_t ctx, char *orig_line)
1189 ctrl_t ctrl = assuan_get_pointer (ctx);
1194 char *line, *linebuf;
1196 if ( IS_LOCKED (ctrl) )
1197 return gpg_error (GPG_ERR_LOCKED);
1199 if ((rc = open_card (ctrl, NULL)))
1202 /* We need to use a copy of LINE, because PIN_CB uses the same
1203 context and thus reuses the Assuan provided LINE. */
1204 line = linebuf = xtrystrdup (orig_line);
1206 return out_of_core ();
1209 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1213 while (spacep (line))
1215 nbytes = percent_plus_unescape_inplace (line, 0);
1217 rc = app_setattr (ctrl->app_ctx, keyword, pin_cb, ctx,
1218 (const unsigned char*)line, nbytes);
1221 TEST_CARD_REMOVAL (ctrl, rc);
1226 static const char hlp_writecert[] =
1227 "WRITECERT <hexified_certid>\n"
1229 "This command is used to store a certifciate on a smartcard. The\n"
1230 "allowed certids depend on the currently selected smartcard\n"
1231 "application. The actual certifciate is requested using the inquiry\n"
1232 "\"CERTDATA\" and needs to be provided in its raw (e.g. DER) form.\n"
1234 "In almost all cases a a PIN will be requested. See the related\n"
1235 "writecert function of the actually used application (app-*.c) for\n"
1238 cmd_writecert (assuan_context_t ctx, char *line)
1240 ctrl_t ctrl = assuan_get_pointer (ctx);
1243 unsigned char *certdata;
1246 if ( IS_LOCKED (ctrl) )
1247 return gpg_error (GPG_ERR_LOCKED);
1249 line = skip_options (line);
1252 return set_error (GPG_ERR_ASS_PARAMETER, "no certid given");
1254 while (*line && !spacep (line))
1258 if ((rc = open_card (ctrl, NULL)))
1262 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1264 certid = xtrystrdup (certid);
1266 return out_of_core ();
1268 /* Now get the actual keydata. */
1269 rc = assuan_inquire (ctx, "CERTDATA",
1270 &certdata, &certdatalen, MAXLEN_CERTDATA);
1277 /* Write the certificate to the card. */
1278 rc = app_writecert (ctrl->app_ctx, ctrl, certid,
1279 pin_cb, ctx, certdata, certdatalen);
1283 TEST_CARD_REMOVAL (ctrl, rc);
1288 static const char hlp_writekey[] =
1289 "WRITEKEY [--force] <keyid> \n"
1291 "This command is used to store a secret key on a a smartcard. The\n"
1292 "allowed keyids depend on the currently selected smartcard\n"
1293 "application. The actual keydata is requested using the inquiry\n"
1294 "\"KEYDATA\" and need to be provided without any protection. With\n"
1295 "--force set an existing key under this KEYID will get overwritten.\n"
1296 "The keydata is expected to be the usual canonical encoded\n"
1299 "A PIN will be requested for most NAMEs. See the corresponding\n"
1300 "writekey function of the actually used application (app-*.c) for\n"
1303 cmd_writekey (assuan_context_t ctx, char *line)
1305 ctrl_t ctrl = assuan_get_pointer (ctx);
1308 int force = has_option (line, "--force");
1309 unsigned char *keydata;
1312 if ( IS_LOCKED (ctrl) )
1313 return gpg_error (GPG_ERR_LOCKED);
1315 line = skip_options (line);
1318 return set_error (GPG_ERR_ASS_PARAMETER, "no keyid given");
1320 while (*line && !spacep (line))
1324 if ((rc = open_card (ctrl, NULL)))
1328 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1330 keyid = xtrystrdup (keyid);
1332 return out_of_core ();
1334 /* Now get the actual keydata. */
1335 assuan_begin_confidential (ctx);
1336 rc = assuan_inquire (ctx, "KEYDATA", &keydata, &keydatalen, MAXLEN_KEYDATA);
1337 assuan_end_confidential (ctx);
1344 /* Write the key to the card. */
1345 rc = app_writekey (ctrl->app_ctx, ctrl, keyid, force? 1:0,
1346 pin_cb, ctx, keydata, keydatalen);
1350 TEST_CARD_REMOVAL (ctrl, rc);
1355 static const char hlp_genkey[] =
1356 "GENKEY [--force] [--timestamp=<isodate>] <no>\n"
1358 "Generate a key on-card identified by NO, which is application\n"
1359 "specific. Return values are application specific. For OpenPGP\n"
1360 "cards 3 status lines are returned:\n"
1362 " S KEY-FPR <hexstring>\n"
1363 " S KEY-CREATED-AT <seconds_since_epoch>\n"
1364 " S KEY-DATA [-|p|n] <hexdata>\n"
1366 " 'p' and 'n' are the names of the RSA parameters; '-' is used to\n"
1367 " indicate that HEXDATA is the first chunk of a parameter given\n"
1368 " by the next KEY-DATA.\n"
1370 "--force is required to overwrite an already existing key. The\n"
1371 "KEY-CREATED-AT is required for further processing because it is\n"
1372 "part of the hashed key material for the fingerprint.\n"
1374 "If --timestamp is given an OpenPGP key will be created using this\n"
1375 "value. The value needs to be in ISO Format; e.g.\n"
1376 "\"--timestamp=20030316T120000\" and after 1970-01-01 00:00:00.\n"
1378 "The public part of the key can also later be retrieved using the\n"
1381 cmd_genkey (assuan_context_t ctx, char *line)
1383 ctrl_t ctrl = assuan_get_pointer (ctx);
1390 if ( IS_LOCKED (ctrl) )
1391 return gpg_error (GPG_ERR_LOCKED);
1393 force = has_option (line, "--force");
1395 if ((s=has_option_name (line, "--timestamp")))
1398 return set_error (GPG_ERR_ASS_PARAMETER, "missing value for option");
1399 timestamp = isotime2epoch (s+1);
1401 return set_error (GPG_ERR_ASS_PARAMETER, "invalid time value");
1407 line = skip_options (line);
1409 return set_error (GPG_ERR_ASS_PARAMETER, "no key number given");
1411 while (*line && !spacep (line))
1415 if ((rc = open_card (ctrl, NULL)))
1419 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1421 keyno = xtrystrdup (keyno);
1423 return out_of_core ();
1424 rc = app_genkey (ctrl->app_ctx, ctrl, keyno, force? 1:0,
1425 timestamp, pin_cb, ctx);
1428 TEST_CARD_REMOVAL (ctrl, rc);
1433 static const char hlp_random[] =
1436 "Get NBYTES of random from the card and send them back as data.\n"
1437 "This usually involves EEPROM write on the card and thus excessive\n"
1438 "use of this command may destroy the card.\n"
1440 "Note, that this function may be even be used on a locked card.";
1442 cmd_random (assuan_context_t ctx, char *line)
1444 ctrl_t ctrl = assuan_get_pointer (ctx);
1447 unsigned char *buffer;
1450 return set_error (GPG_ERR_ASS_PARAMETER,
1451 "number of requested bytes missing");
1452 nbytes = strtoul (line, NULL, 0);
1454 if ((rc = open_card (ctrl, NULL)))
1458 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1460 buffer = xtrymalloc (nbytes);
1462 return out_of_core ();
1464 rc = app_get_challenge (ctrl->app_ctx, nbytes, buffer);
1467 rc = assuan_send_data (ctx, buffer, nbytes);
1469 return rc; /* that is already an assuan error code */
1473 TEST_CARD_REMOVAL (ctrl, rc);
1479 static const char hlp_passwd[] =
1480 "PASSWD [--reset] [--nullpin] <chvno>\n"
1482 "Change the PIN or, if --reset is given, reset the retry counter of\n"
1483 "the card holder verfication vector CHVNO. The option --nullpin is\n"
1484 "used for TCOS cards to set the initial PIN. The format of CHVNO\n"
1485 "depends on the card application.";
1487 cmd_passwd (assuan_context_t ctx, char *line)
1489 ctrl_t ctrl = assuan_get_pointer (ctx);
1492 unsigned int flags = 0;
1494 if (has_option (line, "--reset"))
1495 flags |= APP_CHANGE_FLAG_RESET;
1496 if (has_option (line, "--nullpin"))
1497 flags |= APP_CHANGE_FLAG_NULLPIN;
1499 if ( IS_LOCKED (ctrl) )
1500 return gpg_error (GPG_ERR_LOCKED);
1502 line = skip_options (line);
1505 return set_error (GPG_ERR_ASS_PARAMETER, "no CHV number given");
1507 while (*line && !spacep (line))
1511 if ((rc = open_card (ctrl, NULL)))
1515 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1517 chvnostr = xtrystrdup (chvnostr);
1519 return out_of_core ();
1520 rc = app_change_pin (ctrl->app_ctx, ctrl, chvnostr, flags, pin_cb, ctx);
1522 log_error ("command passwd failed: %s\n", gpg_strerror (rc));
1525 TEST_CARD_REMOVAL (ctrl, rc);
1530 static const char hlp_checkpin[] =
1531 "CHECKPIN <idstr>\n"
1533 "Perform a VERIFY operation without doing anything else. This may\n"
1534 "be used to initialize a the PIN cache earlier to long lasting\n"
1535 "operations. Its use is highly application dependent.\n"
1539 " Perform a simple verify operation for CHV1 and CHV2, so that\n"
1540 " further operations won't ask for CHV2 and it is possible to do a\n"
1541 " cheap check on the PIN: If there is something wrong with the PIN\n"
1542 " entry system, only the regular CHV will get blocked and not the\n"
1543 " dangerous CHV3. IDSTR is the usual card's serial number in hex\n"
1544 " notation; an optional fingerprint part will get ignored. There\n"
1545 " is however a special mode if the IDSTR is sffixed with the\n"
1546 " literal string \"[CHV3]\": In this case the Admin PIN is checked\n"
1547 " if and only if the retry counter is still at 3.\n"
1551 " Any of the valid PIN Ids may be used. These are the strings:\n"
1553 " PW1.CH - Global password 1\n"
1554 " PW2.CH - Global password 2\n"
1555 " PW1.CH.SIG - SigG password 1\n"
1556 " PW2.CH.SIG - SigG password 2\n"
1558 " For a definitive list, see the implementation in app-nks.c.\n"
1559 " Note that we call a PW2.* PIN a \"PUK\" despite that since TCOS\n"
1560 " 3.0 they are technically alternative PINs used to mutally\n"
1561 " unblock each other.";
1563 cmd_checkpin (assuan_context_t ctx, char *line)
1565 ctrl_t ctrl = assuan_get_pointer (ctx);
1569 if ( IS_LOCKED (ctrl) )
1570 return gpg_error (GPG_ERR_LOCKED);
1572 if ((rc = open_card (ctrl, NULL)))
1576 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1578 /* We have to use a copy of the key ID because the function may use
1579 the pin_cb which in turn uses the assuan line buffer and thus
1580 overwriting the original line with the keyid. */
1581 idstr = xtrystrdup (line);
1583 return out_of_core ();
1585 rc = app_check_pin (ctrl->app_ctx, idstr, pin_cb, ctx);
1588 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc));
1590 TEST_CARD_REMOVAL (ctrl, rc);
1595 static const char hlp_lock[] =
1598 "Grant exclusive card access to this session. Note that there is\n"
1599 "no lock counter used and a second lock from the same session will\n"
1600 "be ignored. A single unlock (or RESET) unlocks the session.\n"
1601 "Return GPG_ERR_LOCKED if another session has locked the reader.\n"
1603 "If the option --wait is given the command will wait until a\n"
1604 "lock has been released.";
1606 cmd_lock (assuan_context_t ctx, char *line)
1608 ctrl_t ctrl = assuan_get_pointer (ctx);
1614 if (locked_session != ctrl->server_local)
1615 rc = gpg_error (GPG_ERR_LOCKED);
1618 locked_session = ctrl->server_local;
1621 if (rc && has_option (line, "--wait"))
1624 npth_sleep (1); /* Better implement an event mechanism. However,
1625 for card operations this should be
1627 /* FIXME: Need to check that the connection is still alive.
1628 This can be done by issuing status messages. */
1634 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc));
1639 static const char hlp_unlock[] =
1642 "Release exclusive card access.";
1644 cmd_unlock (assuan_context_t ctx, char *line)
1646 ctrl_t ctrl = assuan_get_pointer (ctx);
1653 if (locked_session != ctrl->server_local)
1654 rc = gpg_error (GPG_ERR_LOCKED);
1656 locked_session = NULL;
1659 rc = gpg_error (GPG_ERR_NOT_LOCKED);
1662 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc));
1667 static const char hlp_getinfo[] =
1670 "Multi purpose command to return certain information. \n"
1671 "Supported values of WHAT are:\n"
1673 "version - Return the version of the program.\n"
1674 "pid - Return the process id of the server.\n"
1676 "socket_name - Return the name of the socket.\n"
1678 "status - Return the status of the current reader (in the future, may\n"
1679 "also return the status of all readers). The status is a list of\n"
1680 "one-character flags. The following flags are currently defined:\n"
1681 " 'u' Usable card present. This is the normal state during operation.\n"
1682 " 'r' Card removed. A reset is necessary.\n"
1683 "These flags are exclusive.\n"
1685 "reader_list - Return a list of detected card readers. Does\n"
1686 " currently only work with the internal CCID driver.\n"
1688 "deny_admin - Returns OK if admin commands are not allowed or\n"
1689 " GPG_ERR_GENERAL if admin commands are allowed.\n"
1691 "app_list - Return a list of supported applications. One\n"
1692 " application per line, fields delimited by colons,\n"
1693 " first field is the name.";
1695 cmd_getinfo (assuan_context_t ctx, char *line)
1699 if (!strcmp (line, "version"))
1701 const char *s = VERSION;
1702 rc = assuan_send_data (ctx, s, strlen (s));
1704 else if (!strcmp (line, "pid"))
1708 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
1709 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
1711 else if (!strcmp (line, "socket_name"))
1713 const char *s = scd_get_socket_name ();
1716 rc = assuan_send_data (ctx, s, strlen (s));
1718 rc = gpg_error (GPG_ERR_NO_DATA);
1720 else if (!strcmp (line, "status"))
1722 ctrl_t ctrl = assuan_get_pointer (ctx);
1723 int vrdr = ctrl->server_local->vreader_idx;
1726 if (!ctrl->server_local->card_removed && vrdr != -1)
1728 struct vreader_s *vr;
1730 if (!(vrdr >= 0 && vrdr < DIM(vreader_table)))
1733 vr = &vreader_table[vrdr];
1734 if (vr->valid && vr->any && (vr->status & 1))
1737 rc = assuan_send_data (ctx, &flag, 1);
1739 else if (!strcmp (line, "reader_list"))
1742 char *s = ccid_get_reader_list ();
1748 rc = assuan_send_data (ctx, s, strlen (s));
1750 rc = gpg_error (GPG_ERR_NO_DATA);
1753 else if (!strcmp (line, "deny_admin"))
1754 rc = opt.allow_admin? gpg_error (GPG_ERR_GENERAL) : 0;
1755 else if (!strcmp (line, "app_list"))
1757 char *s = get_supported_applications ();
1759 rc = assuan_send_data (ctx, s, strlen (s));
1765 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
1770 static const char hlp_restart[] =
1773 "Restart the current connection; this is a kind of warm reset. It\n"
1774 "deletes the context used by this connection but does not send a\n"
1775 "RESET to the card. Thus the card itself won't get reset. \n"
1777 "This is used by gpg-agent to reuse a primary pipe connection and\n"
1778 "may be used by clients to backup from a conflict in the serial\n"
1779 "command; i.e. to select another application.";
1781 cmd_restart (assuan_context_t ctx, char *line)
1783 ctrl_t ctrl = assuan_get_pointer (ctx);
1789 release_application (ctrl->app_ctx);
1790 ctrl->app_ctx = NULL;
1792 if (locked_session && ctrl->server_local == locked_session)
1794 locked_session = NULL;
1795 log_info ("implicitly unlocking due to RESTART\n");
1801 static const char hlp_disconnect[] =
1804 "Disconnect the card if it is not any longer used by other\n"
1805 "connections and the backend supports a disconnect operation.";
1807 cmd_disconnect (assuan_context_t ctx, char *line)
1809 ctrl_t ctrl = assuan_get_pointer (ctx);
1813 ctrl->server_local->disconnect_allowed = 1;
1819 static const char hlp_apdu[] =
1820 "APDU [--[dump-]atr] [--more] [--exlen[=N]] [hexstring]\n"
1822 "Send an APDU to the current reader. This command bypasses the high\n"
1823 "level functions and sends the data directly to the card. HEXSTRING\n"
1824 "is expected to be a proper APDU. If HEXSTRING is not given no\n"
1825 "commands are set to the card but the command will implictly check\n"
1826 "whether the card is ready for use. \n"
1828 "Using the option \"--atr\" returns the ATR of the card as a status\n"
1829 "message before any data like this:\n"
1830 " S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1\n"
1832 "Using the option --more handles the card status word MORE_DATA\n"
1833 "(61xx) and concatenates all reponses to one block.\n"
1835 "Using the option \"--exlen\" the returned APDU may use extended\n"
1836 "length up to N bytes. If N is not given a default value is used\n"
1837 "(currently 4096).";
1839 cmd_apdu (assuan_context_t ctx, char *line)
1841 ctrl_t ctrl = assuan_get_pointer (ctx);
1843 unsigned char *apdu;
1851 if (has_option (line, "--dump-atr"))
1854 with_atr = has_option (line, "--atr");
1855 handle_more = has_option (line, "--more");
1857 if ((s=has_option_name (line, "--exlen")))
1860 exlen = strtoul (s+1, NULL, 0);
1867 line = skip_options (line);
1869 if ( IS_LOCKED (ctrl) )
1870 return gpg_error (GPG_ERR_LOCKED);
1872 if ((rc = open_card (ctrl, NULL)))
1875 slot = vreader_slot (ctrl->server_local->vreader_idx);
1883 atr = apdu_get_atr (slot, &atrlen);
1884 if (!atr || atrlen > sizeof hexbuf - 2 )
1886 rc = gpg_error (GPG_ERR_INV_CARD);
1891 char *string, *p, *pend;
1893 string = atr_dump (atr, atrlen);
1896 for (rc=0, p=string; !rc && (pend = strchr (p, '\n')); p = pend+1)
1898 rc = assuan_send_data (ctx, p, pend - p + 1);
1900 rc = assuan_send_data (ctx, NULL, 0);
1903 rc = assuan_send_data (ctx, p, strlen (p));
1911 bin2hex (atr, atrlen, hexbuf);
1912 send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
1917 apdu = hex_to_buffer (line, &apdulen);
1920 rc = gpg_error_from_syserror ();
1925 unsigned char *result = NULL;
1928 rc = apdu_send_direct (slot, exlen,
1929 apdu, apdulen, handle_more,
1930 &result, &resultlen);
1932 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc));
1935 rc = assuan_send_data (ctx, result, resultlen);
1942 TEST_CARD_REMOVAL (ctrl, rc);
1947 static const char hlp_killscd[] =
1952 cmd_killscd (assuan_context_t ctx, char *line)
1954 ctrl_t ctrl = assuan_get_pointer (ctx);
1958 ctrl->server_local->stopme = 1;
1959 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
1965 /* Tell the assuan library about our commands */
1967 register_commands (assuan_context_t ctx)
1971 assuan_handler_t handler;
1972 const char * const help;
1974 { "SERIALNO", cmd_serialno, hlp_serialno },
1975 { "LEARN", cmd_learn, hlp_learn },
1976 { "READCERT", cmd_readcert, hlp_readcert },
1977 { "READKEY", cmd_readkey, hlp_readkey },
1978 { "SETDATA", cmd_setdata, hlp_setdata },
1979 { "PKSIGN", cmd_pksign, hlp_pksign },
1980 { "PKAUTH", cmd_pkauth, hlp_pkauth },
1981 { "PKDECRYPT", cmd_pkdecrypt,hlp_pkdecrypt },
1984 { "GETATTR", cmd_getattr, hlp_getattr },
1985 { "SETATTR", cmd_setattr, hlp_setattr },
1986 { "WRITECERT", cmd_writecert,hlp_writecert },
1987 { "WRITEKEY", cmd_writekey, hlp_writekey },
1988 { "GENKEY", cmd_genkey, hlp_genkey },
1989 { "RANDOM", cmd_random, hlp_random },
1990 { "PASSWD", cmd_passwd, hlp_passwd },
1991 { "CHECKPIN", cmd_checkpin, hlp_checkpin },
1992 { "LOCK", cmd_lock, hlp_lock },
1993 { "UNLOCK", cmd_unlock, hlp_unlock },
1994 { "GETINFO", cmd_getinfo, hlp_getinfo },
1995 { "RESTART", cmd_restart, hlp_restart },
1996 { "DISCONNECT", cmd_disconnect,hlp_disconnect },
1997 { "APDU", cmd_apdu, hlp_apdu },
1998 { "KILLSCD", cmd_killscd, hlp_killscd },
2003 for (i=0; table[i].name; i++)
2005 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
2010 assuan_set_hello_line (ctx, "GNU Privacy Guard's Smartcard server ready");
2012 assuan_register_reset_notify (ctx, reset_notify);
2013 assuan_register_option_handler (ctx, option_handler);
2018 /* Startup the server. If FD is given as -1 this is simple pipe
2019 server, otherwise it is a regular server. Returns true if there
2020 are no more active asessions. */
2022 scd_command_handler (ctrl_t ctrl, int fd)
2025 assuan_context_t ctx = NULL;
2028 rc = assuan_new (&ctx);
2031 log_error ("failed to allocate assuan context: %s\n",
2038 assuan_fd_t filedes[2];
2040 filedes[0] = assuan_fdopen (0);
2041 filedes[1] = assuan_fdopen (1);
2042 rc = assuan_init_pipe_server (ctx, filedes);
2046 rc = assuan_init_socket_server (ctx, INT2FD(fd),
2047 ASSUAN_SOCKET_SERVER_ACCEPTED);
2051 log_error ("failed to initialize the server: %s\n",
2055 rc = register_commands (ctx);
2058 log_error ("failed to register commands with Assuan: %s\n",
2062 assuan_set_pointer (ctx, ctrl);
2064 /* Allocate and initialize the server object. Put it into the list
2065 of active sessions. */
2066 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
2067 ctrl->server_local->next_session = session_list;
2068 session_list = ctrl->server_local;
2069 ctrl->server_local->ctrl_backlink = ctrl;
2070 ctrl->server_local->assuan_ctx = ctx;
2071 ctrl->server_local->vreader_idx = -1;
2073 /* We open the reader right at startup so that the ticker is able to
2074 update the status file. */
2075 if (ctrl->server_local->vreader_idx == -1)
2077 ctrl->server_local->vreader_idx = get_current_reader ();
2080 /* Command processing loop. */
2083 rc = assuan_accept (ctx);
2090 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
2094 rc = assuan_process (ctx);
2097 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
2102 /* Cleanup. We don't send an explicit reset to the card. */
2105 /* Release the server object. */
2106 if (session_list == ctrl->server_local)
2107 session_list = ctrl->server_local->next_session;
2110 struct server_local_s *sl;
2112 for (sl=session_list; sl->next_session; sl = sl->next_session)
2113 if (sl->next_session == ctrl->server_local)
2115 if (!sl->next_session)
2117 sl->next_session = ctrl->server_local->next_session;
2119 stopme = ctrl->server_local->stopme;
2120 xfree (ctrl->server_local);
2121 ctrl->server_local = NULL;
2123 /* Release the Assuan context. */
2124 assuan_release (ctx);
2129 /* If there are no more sessions return true. */
2130 return !session_list;
2134 /* Send a line with status information via assuan and escape all given
2135 buffers. The variable elements are pairs of (char *, size_t),
2136 terminated with a (NULL, 0). */
2138 send_status_info (ctrl_t ctrl, const char *keyword, ...)
2141 const unsigned char *value;
2145 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2147 va_start (arg_ptr, keyword);
2151 while ( (value = va_arg (arg_ptr, const unsigned char *)) )
2153 valuelen = va_arg (arg_ptr, size_t);
2155 continue; /* empty buffer */
2161 for ( ; valuelen && n < DIM (buf)-2; n++, valuelen--, value++)
2163 if (*value < ' ' || *value == '+')
2165 sprintf (p, "%%%02X", *value);
2168 else if (*value == ' ')
2175 assuan_write_status (ctx, keyword, buf);
2181 /* Send a ready formatted status line via assuan. */
2183 send_status_direct (ctrl_t ctrl, const char *keyword, const char *args)
2185 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2187 if (strchr (args, '\n'))
2188 log_error ("error: LF detected in status line - not sending\n");
2190 assuan_write_status (ctx, keyword, args);
2194 /* Helper to send the clients a status change notification. */
2196 send_client_notifications (void)
2200 #ifdef HAVE_W32_SYSTEM
2208 struct server_local_s *sl;
2210 for (sl=session_list; sl; sl = sl->next_session)
2212 if (sl->event_signal && sl->assuan_ctx)
2214 pid_t pid = assuan_get_pid (sl->assuan_ctx);
2215 #ifdef HAVE_W32_SYSTEM
2216 HANDLE handle = (void *)sl->event_signal;
2218 for (kidx=0; kidx < killidx; kidx++)
2219 if (killed[kidx].pid == pid
2220 && killed[kidx].handle == handle)
2223 log_info ("event %lx (%p) already triggered for client %d\n",
2224 sl->event_signal, handle, (int)pid);
2227 log_info ("triggering event %lx (%p) for client %d\n",
2228 sl->event_signal, handle, (int)pid);
2229 if (!SetEvent (handle))
2230 log_error ("SetEvent(%lx) failed: %s\n",
2231 sl->event_signal, w32_strerror (-1));
2232 if (killidx < DIM (killed))
2234 killed[killidx].pid = pid;
2235 killed[killidx].handle = handle;
2239 #else /*!HAVE_W32_SYSTEM*/
2240 int signo = sl->event_signal;
2242 if (pid != (pid_t)(-1) && pid && signo > 0)
2244 for (kidx=0; kidx < killidx; kidx++)
2245 if (killed[kidx].pid == pid
2246 && killed[kidx].signo == signo)
2249 log_info ("signal %d already sent to client %d\n",
2253 log_info ("sending signal %d to client %d\n",
2256 if (killidx < DIM (killed))
2258 killed[killidx].pid = pid;
2259 killed[killidx].signo = signo;
2264 #endif /*!HAVE_W32_SYSTEM*/
2271 /* This is the core of scd_update_reader_status_file but the caller
2272 needs to take care of the locking. */
2274 update_reader_status_file (int set_card_removed_flag)
2277 unsigned int status, changed;
2279 /* Note, that we only try to get the status, because it does not
2280 make sense to wait here for a operation to complete. If we are
2281 busy working with a card, delays in the status file update should
2283 for (idx=0; idx < DIM(vreader_table); idx++)
2285 struct vreader_s *vr = vreader_table + idx;
2286 struct server_local_s *sl;
2289 if (!vr->valid || vr->slot == -1)
2290 continue; /* Not valid or reader not yet open. */
2292 sw_apdu = apdu_get_status (vr->slot, 0, &status, &changed);
2293 if (sw_apdu == SW_HOST_NO_READER)
2295 /* Most likely the _reader_ has been unplugged. */
2296 application_notify_card_reset (vr->slot);
2297 apdu_close_reader (vr->slot);
2300 changed = vr->changed;
2304 /* Get status failed. Ignore that. */
2308 if (!vr->any || vr->status != status || vr->changed != changed )
2314 log_info ("updating reader %d (%d) status: 0x%04X->0x%04X (%u->%u)\n",
2315 idx, vr->slot, vr->status, status, vr->changed, changed);
2316 vr->status = status;
2317 vr->changed = changed;
2319 /* FIXME: Should this be IDX instead of vr->slot? This
2320 depends on how client sessions will associate the reader
2321 status with their session. */
2322 snprintf (templ, sizeof templ, "reader_%d.status", vr->slot);
2323 fname = make_filename (opt.homedir, templ, NULL );
2324 fp = fopen (fname, "w");
2327 fprintf (fp, "%s\n",
2328 (status & 1)? "USABLE":
2329 (status & 4)? "ACTIVE":
2330 (status & 2)? "PRESENT": "NOCARD");
2335 /* If a status script is executable, run it. */
2337 const char *args[9], *envs[2];
2338 char numbuf1[30], numbuf2[30], numbuf3[30];
2339 char *homestr, *envstr;
2342 homestr = make_filename (opt.homedir, NULL);
2343 if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2344 log_error ("out of core while building environment\n");
2350 sprintf (numbuf1, "%d", vr->slot);
2351 sprintf (numbuf2, "0x%04X", vr->status);
2352 sprintf (numbuf3, "0x%04X", status);
2353 args[0] = "--reader-port";
2355 args[2] = "--old-code";
2357 args[4] = "--new-code";
2359 args[6] = "--status";
2360 args[7] = ((status & 1)? "USABLE":
2361 (status & 4)? "ACTIVE":
2362 (status & 2)? "PRESENT": "NOCARD");
2365 fname = make_filename (opt.homedir, "scd-event", NULL);
2366 err = gnupg_spawn_process_detached (fname, args, envs);
2367 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2368 log_error ("failed to run event handler '%s': %s\n",
2369 fname, gpg_strerror (err));
2376 /* Set the card removed flag for all current sessions. */
2377 if (vr->any && vr->status == 0 && set_card_removed_flag)
2378 update_card_removed (idx, 1);
2382 /* Send a signal to all clients who applied for it. */
2383 send_client_notifications ();
2386 /* Check whether a disconnect is pending. */
2387 if (opt.card_timeout)
2389 for (sl=session_list; sl; sl = sl->next_session)
2390 if (!sl->disconnect_allowed)
2392 if (session_list && !sl)
2394 /* FIXME: Use a real timeout. */
2395 /* At least one connection and all allow a disconnect. */
2396 log_info ("disconnecting card in reader %d (%d)\n",
2398 apdu_disconnect (vr->slot);
2405 /* This function is called by the ticker thread to check for changes
2406 of the reader stati. It updates the reader status files and if
2407 requested by the caller also send a signal to the caller. */
2409 scd_update_reader_status_file (void)
2412 err = npth_mutex_lock (&status_file_update_lock);
2414 return; /* locked - give up. */
2415 update_reader_status_file (1);
2416 err = npth_mutex_unlock (&status_file_update_lock);
2418 log_error ("failed to release status_file_update lock: %s\n",