diff --git a/common/asshelp.c b/common/asshelp.c index fe49aa83a..0d903fd5f 100644 --- a/common/asshelp.c +++ b/common/asshelp.c @@ -1,698 +1,752 @@ /* asshelp.c - Helper functions for Assuan * Copyright (C) 2002, 2004, 2007, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "i18n.h" #include "util.h" #include "exechelp.h" #include "sysutils.h" #include "status.h" #include "membuf.h" #include "asshelp.h" /* The type we use for lock_agent_spawning. */ #ifdef HAVE_W32_SYSTEM # define lock_spawn_t HANDLE #else # define lock_spawn_t dotlock_t #endif /* The time we wait until the agent or the dirmngr are ready for operation after we started them before giving up. */ #ifdef HAVE_W32CE_SYSTEM # define SECS_TO_WAIT_FOR_AGENT 30 # define SECS_TO_WAIT_FOR_KEYBOXD 30 # define SECS_TO_WAIT_FOR_DIRMNGR 30 #else # define SECS_TO_WAIT_FOR_AGENT 5 # define SECS_TO_WAIT_FOR_KEYBOXD 5 # define SECS_TO_WAIT_FOR_DIRMNGR 5 #endif /* A bitfield that specifies the assuan categories to log. This is identical to the default log handler of libassuan. We need to do it ourselves because we use a custom log handler and want to use the same assuan variables to select the categories to log. */ static int log_cats; #define TEST_LOG_CAT(x) (!! (log_cats & (1 << (x - 1)))) /* The assuan log monitor used to temporary inhibit log messages from * assuan. */ static int (*my_log_monitor) (assuan_context_t ctx, unsigned int cat, const char *msg); static int my_libassuan_log_handler (assuan_context_t ctx, void *hook, unsigned int cat, const char *msg) { unsigned int dbgval; if (! TEST_LOG_CAT (cat)) return 0; dbgval = hook? *(unsigned int*)hook : 0; if (!(dbgval & 1024)) return 0; /* Assuan debugging is not enabled. */ if (ctx && my_log_monitor && !my_log_monitor (ctx, cat, msg)) return 0; /* Temporary disabled. */ if (msg) log_string (GPGRT_LOGLVL_DEBUG, msg); return 1; } /* Setup libassuan to use our own logging functions. Should be used early at startup. */ void setup_libassuan_logging (unsigned int *debug_var_address, int (*log_monitor)(assuan_context_t ctx, unsigned int cat, const char *msg)) { char *flagstr; flagstr = getenv ("ASSUAN_DEBUG"); if (flagstr) log_cats = atoi (flagstr); else /* Default to log the control channel. */ log_cats = (1 << (ASSUAN_LOG_CONTROL - 1)); my_log_monitor = log_monitor; assuan_set_log_cb (my_libassuan_log_handler, debug_var_address); } /* Change the Libassuan log categories to those given by NEWCATS. NEWCATS is 0 the default category of ASSUAN_LOG_CONTROL is selected. Note, that setup_libassuan_logging overrides the values given here. */ void set_libassuan_log_cats (unsigned int newcats) { if (newcats) log_cats = newcats; else /* Default to log the control channel. */ log_cats = (1 << (ASSUAN_LOG_CONTROL - 1)); } static gpg_error_t send_one_option (assuan_context_t ctx, gpg_err_source_t errsource, const char *name, const char *value, int use_putenv) { gpg_error_t err; char *optstr; (void)errsource; if (!value || !*value) err = 0; /* Avoid sending empty strings. */ else if (asprintf (&optstr, "OPTION %s%s=%s", use_putenv? "putenv=":"", name, value) < 0) err = gpg_error_from_syserror (); else { err = assuan_transact (ctx, optstr, NULL, NULL, NULL, NULL, NULL, NULL); xfree (optstr); } return err; } /* Send the assuan commands pertaining to the pinentry environment. The OPT_* arguments are optional and may be used to override the defaults taken from the current locale. */ gpg_error_t send_pinentry_environment (assuan_context_t ctx, gpg_err_source_t errsource, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env) { gpg_error_t err = 0; #if defined(HAVE_SETLOCALE) char *old_lc = NULL; #endif char *dft_lc = NULL; const char *dft_ttyname; int iterator; const char *name, *assname, *value; int is_default; iterator = 0; while ((name = session_env_list_stdenvnames (&iterator, &assname))) { value = session_env_getenv_or_default (session_env, name, NULL); if (!value) continue; if (assname) err = send_one_option (ctx, errsource, assname, value, 0); else { err = send_one_option (ctx, errsource, name, value, 1); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Server too old; can't pass the new envvars. */ } if (err) return err; } dft_ttyname = session_env_getenv_or_default (session_env, "GPG_TTY", &is_default); if (dft_ttyname && !is_default) dft_ttyname = NULL; /* We need the default value. */ /* Send the value for LC_CTYPE. */ #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) old_lc = setlocale (LC_CTYPE, NULL); if (old_lc) { old_lc = xtrystrdup (old_lc); if (!old_lc) return gpg_error_from_syserror (); } dft_lc = setlocale (LC_CTYPE, ""); #endif if (opt_lc_ctype || (dft_ttyname && dft_lc)) { err = send_one_option (ctx, errsource, "lc-ctype", opt_lc_ctype ? opt_lc_ctype : dft_lc, 0); } #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) if (old_lc) { setlocale (LC_CTYPE, old_lc); xfree (old_lc); } #endif if (err) return err; /* Send the value for LC_MESSAGES. */ #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) old_lc = setlocale (LC_MESSAGES, NULL); if (old_lc) { old_lc = xtrystrdup (old_lc); if (!old_lc) return gpg_error_from_syserror (); } dft_lc = setlocale (LC_MESSAGES, ""); #endif if (opt_lc_messages || (dft_ttyname && dft_lc)) { err = send_one_option (ctx, errsource, "lc-messages", opt_lc_messages ? opt_lc_messages : dft_lc, 0); } #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) if (old_lc) { setlocale (LC_MESSAGES, old_lc); xfree (old_lc); } #endif if (err) return err; return 0; } /* Lock a spawning process. The caller needs to provide the address of a variable to store the lock information and the name or the process. */ static gpg_error_t lock_spawning (lock_spawn_t *lock, const char *homedir, const char *name, int verbose) { char *fname; (void)verbose; *lock = NULL; fname = make_absfilename_try (homedir, !strcmp (name, "agent")? "gnupg_spawn_agent_sentinel": !strcmp (name, "dirmngr")? "gnupg_spawn_dirmngr_sentinel": /* */ "gnupg_spawn_unknown_sentinel", NULL); if (!fname) return gpg_error_from_syserror (); *lock = dotlock_create (fname, 0); xfree (fname); if (!*lock) return gpg_error_from_syserror (); /* FIXME: We should use a timeout of 5000 here - however make_dotlock does not yet support values other than -1 and 0. */ if (dotlock_take (*lock, -1)) return gpg_error_from_syserror (); return 0; } /* Unlock the spawning process. */ static void unlock_spawning (lock_spawn_t *lock, const char *name) { if (*lock) { (void)name; dotlock_destroy (*lock); *lock = NULL; } } /* Helper to start a service. SECS gives the number of seconds to * wait. SOCKNAME is the name of the socket to connect. VERBOSE is * the usual verbose flag. CTX is the assuan context. CONNECT_FLAGS * are the assuan connect flags. DID_SUCCESS_MSG will be set to 1 if * a success messages has been printed. */ static gpg_error_t wait_for_sock (int secs, int module_name_id, const char *sockname, unsigned int connect_flags, int verbose, assuan_context_t ctx, int *did_success_msg) { gpg_error_t err = 0; int target_us = secs * 1000000; int elapsed_us = 0; /* * 977us * 1024 = just a little more than 1s. * so we will double this timeout 10 times in the first * second, and then switch over to 1s checkins. */ int next_sleep_us = 977; int lastalert = secs+1; int secsleft; while (elapsed_us < target_us) { if (verbose) { secsleft = (target_us - elapsed_us + 999999)/1000000; /* log_clock ("left=%d last=%d targ=%d elap=%d next=%d\n", */ /* secsleft, lastalert, target_us, elapsed_us, */ /* next_sleep_us); */ if (secsleft < lastalert) { log_info (module_name_id == GNUPG_MODULE_NAME_DIRMNGR? _("waiting for the dirmngr to come up ... (%ds)\n"): module_name_id == GNUPG_MODULE_NAME_KEYBOXD? _("waiting for the keyboxd to come up ... (%ds)\n"): _("waiting for the agent to come up ... (%ds)\n"), secsleft); lastalert = secsleft; } } gnupg_usleep (next_sleep_us); elapsed_us += next_sleep_us; err = assuan_socket_connect (ctx, sockname, 0, connect_flags); if (!err) { if (verbose) { log_info (module_name_id == GNUPG_MODULE_NAME_DIRMNGR? _("connection to the dirmngr established\n"): module_name_id == GNUPG_MODULE_NAME_KEYBOXD? _("connection to the keyboxd established\n"): _("connection to the agent established\n")); *did_success_msg = 1; } break; } next_sleep_us *= 2; if (next_sleep_us > 1000000) next_sleep_us = 1000000; } return err; } /* Try to connect to a new service via socket or start it if it is not * running and AUTOSTART is set. Handle the server's initial * greeting. Returns a new assuan context at R_CTX or an error code. * MODULE_NAME_ID is one of: * GNUPG_MODULE_NAME_AGENT * GNUPG_MODULE_NAME_DIRMNGR */ static gpg_error_t start_new_service (assuan_context_t *r_ctx, int module_name_id, gpg_err_source_t errsource, const char *program_name, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg) { gpg_error_t err; assuan_context_t ctx; int did_success_msg = 0; char *sockname; const char *printed_name; const char *lock_name; const char *status_start_line; int no_service_err; int seconds_to_wait; unsigned int connect_flags = 0; const char *argv[6]; *r_ctx = NULL; err = assuan_new (&ctx); if (err) { log_error ("error allocating assuan context: %s\n", gpg_strerror (err)); return err; } switch (module_name_id) { case GNUPG_MODULE_NAME_AGENT: sockname = make_filename (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); lock_name = "agent"; printed_name = "gpg-agent"; status_start_line = "starting_agent ? 0 0"; no_service_err = GPG_ERR_NO_AGENT; seconds_to_wait = SECS_TO_WAIT_FOR_AGENT; break; case GNUPG_MODULE_NAME_DIRMNGR: sockname = make_filename (gnupg_socketdir (), DIRMNGR_SOCK_NAME, NULL); lock_name = "dirmngr"; printed_name = "dirmngr"; status_start_line = "starting_dirmngr ? 0 0"; no_service_err = GPG_ERR_NO_DIRMNGR; seconds_to_wait = SECS_TO_WAIT_FOR_DIRMNGR; break; case GNUPG_MODULE_NAME_KEYBOXD: sockname = make_filename (gnupg_socketdir (), KEYBOXD_SOCK_NAME, NULL); lock_name = "keyboxd"; printed_name = "keyboxd"; status_start_line = "starting_keyboxd ? 0 0"; no_service_err = GPG_ERR_NO_KEYBOXD; seconds_to_wait = SECS_TO_WAIT_FOR_KEYBOXD; connect_flags |= ASSUAN_SOCKET_CONNECT_FDPASSING; break; default: err = gpg_error (GPG_ERR_INV_ARG); assuan_release (ctx); return err; } err = assuan_socket_connect (ctx, sockname, 0, connect_flags); if (err && autostart) { char *abs_homedir; lock_spawn_t lock; char *program = NULL; const char *program_arg = NULL; char *p; const char *s; int i; /* With no success start a new server. */ if (!program_name || !*program_name) program_name = gnupg_module_name (module_name_id); else if ((s=strchr (program_name, '|')) && s[1] == '-' && s[2]=='-') { /* Hack to insert an additional option on the command line. */ program = xtrystrdup (program_name); if (!program) { gpg_error_t tmperr = gpg_err_make (errsource, gpg_err_code_from_syserror ()); xfree (sockname); assuan_release (ctx); return tmperr; } p = strchr (program, '|'); *p++ = 0; program_arg = p; } if (verbose) log_info (_("no running %s - starting '%s'\n"), printed_name, program_name); if (status_cb) status_cb (status_cb_arg, STATUS_PROGRESS, status_start_line, NULL); /* We better pass an absolute home directory to the service just * in case the service does not convert the passed name to an * absolute one (which it should do). */ abs_homedir = make_absfilename_try (gnupg_homedir (), NULL); if (!abs_homedir) { gpg_error_t tmperr = gpg_err_make (errsource, gpg_err_code_from_syserror ()); log_error ("error building filename: %s\n", gpg_strerror (tmperr)); xfree (sockname); assuan_release (ctx); xfree (program); return tmperr; } if (fflush (NULL)) { gpg_error_t tmperr = gpg_err_make (errsource, gpg_err_code_from_syserror ()); log_error ("error flushing pending output: %s\n", strerror (errno)); xfree (sockname); assuan_release (ctx); xfree (abs_homedir); xfree (program); return tmperr; } i = 0; argv[i++] = "--homedir"; argv[i++] = abs_homedir; if (module_name_id == GNUPG_MODULE_NAME_AGENT) argv[i++] = "--use-standard-socket"; if (program_arg) argv[i++] = program_arg; argv[i++] = "--daemon"; argv[i++] = NULL; if (!(err = lock_spawning (&lock, gnupg_homedir (), lock_name, verbose)) && assuan_socket_connect (ctx, sockname, 0, connect_flags)) { #ifdef HAVE_W32_SYSTEM err = gnupg_spawn_process_detached (program? program : program_name, argv, NULL); #else /*!W32*/ pid_t pid; err = gnupg_spawn_process_fd (program? program : program_name, argv, -1, -1, -1, &pid); if (!err) err = gnupg_wait_process (program? program : program_name, pid, 1, NULL); #endif /*!W32*/ if (err) log_error ("failed to start %s '%s': %s\n", printed_name, program? program : program_name, gpg_strerror (err)); else err = wait_for_sock (seconds_to_wait, module_name_id, sockname, connect_flags, verbose, ctx, &did_success_msg); } unlock_spawning (&lock, lock_name); xfree (abs_homedir); xfree (program); } xfree (sockname); if (err) { if (autostart || gpg_err_code (err) != GPG_ERR_ASS_CONNECT_FAILED) log_error ("can't connect to the %s: %s\n", printed_name, gpg_strerror (err)); assuan_release (ctx); return gpg_err_make (errsource, no_service_err); } if (debug && !did_success_msg) log_debug ("connection to the %s established\n", printed_name); if (module_name_id == GNUPG_MODULE_NAME_AGENT) err = assuan_transact (ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (!err && module_name_id == GNUPG_MODULE_NAME_AGENT) { err = send_pinentry_environment (ctx, errsource, opt_lc_ctype, opt_lc_messages, session_env); if (gpg_err_code (err) == GPG_ERR_FORBIDDEN && gpg_err_source (err) == GPG_ERR_SOURCE_GPGAGENT) { /* Check whether the agent is in restricted mode. */ if (!assuan_transact (ctx, "GETINFO restricted", NULL, NULL, NULL, NULL, NULL, NULL)) { if (verbose) log_info (_("connection to the agent is in restricted mode\n")); err = 0; } } } if (err) { assuan_release (ctx); return err; } *r_ctx = ctx; return 0; } /* Try to connect to the agent or start a new one. */ gpg_error_t start_new_gpg_agent (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *agent_program, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg) { return start_new_service (r_ctx, GNUPG_MODULE_NAME_AGENT, errsource, agent_program, opt_lc_ctype, opt_lc_messages, session_env, autostart, verbose, debug, status_cb, status_cb_arg); } /* Try to connect to the dirmngr via a socket. On platforms supporting it, start it up if needed and if AUTOSTART is true. Returns a new assuan context at R_CTX or an error code. */ gpg_error_t start_new_keyboxd (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *keyboxd_program, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg) { return start_new_service (r_ctx, GNUPG_MODULE_NAME_KEYBOXD, errsource, keyboxd_program, NULL, NULL, NULL, autostart, verbose, debug, status_cb, status_cb_arg); } /* Try to connect to the dirmngr via a socket. On platforms supporting it, start it up if needed and if AUTOSTART is true. Returns a new assuan context at R_CTX or an error code. */ gpg_error_t start_new_dirmngr (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *dirmngr_program, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg) { #ifndef USE_DIRMNGR_AUTO_START autostart = 0; #endif return start_new_service (r_ctx, GNUPG_MODULE_NAME_DIRMNGR, errsource, dirmngr_program, NULL, NULL, NULL, autostart, verbose, debug, status_cb, status_cb_arg); } /* Return the version of a server using "GETINFO version". On success 0 is returned and R_VERSION receives a malloced string with the version which must be freed by the caller. On error NULL is stored at R_VERSION and an error code returned. Mode is in general 0 but certain values may be used to modify the used version command: MODE == 0 = Use "GETINFO version" MODE == 2 - Use "SCD GETINFO version" */ gpg_error_t get_assuan_server_version (assuan_context_t ctx, int mode, char **r_version) { gpg_error_t err; membuf_t data; init_membuf (&data, 64); err = assuan_transact (ctx, mode == 2? "SCD GETINFO version" /**/ : "GETINFO version", put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) { xfree (get_membuf (&data, NULL)); *r_version = NULL; } else { put_membuf (&data, "", 1); *r_version = get_membuf (&data, NULL); if (!*r_version) err = gpg_error_from_syserror (); } return err; } + + +/* Print a warning if the server's version number is less than our + * version number. Returns an error code on a connection problem. + * CTX is the Assuan context, SERVERNAME is the name of teh server, + * STATUS_FUNC and STATUS_FUNC_DATA is a callback to emit status + * messages. If PRINT_HINTS is set additional hints are printed. For + * MODE see get_assuan_server_version. */ +gpg_error_t +warn_server_version_mismatch (assuan_context_t ctx, + const char *servername, int mode, + gpg_error_t (*status_func)(ctrl_t ctrl, + int status_no, + ...), + void *status_func_ctrl, + int print_hints) +{ + gpg_error_t err; + char *serverversion; + const char *myversion = gpgrt_strusage (13); + + err = get_assuan_server_version (ctx, mode, &serverversion); + if (err) + log_log (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED? + GPGRT_LOGLVL_INFO : GPGRT_LOGLVL_ERROR, + _("error getting version from '%s': %s\n"), + servername, gpg_strerror (err)); + else if (compare_version_strings (serverversion, myversion) < 0) + { + char *warn; + + warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), + servername, serverversion, myversion); + if (!warn) + err = gpg_error_from_syserror (); + else + { + log_info (_("WARNING: %s\n"), warn); + if (print_hints) + { + log_info (_("Note: Outdated servers may lack important" + " security fixes.\n")); + log_info (_("Note: Use the command \"%s\" to restart them.\n"), + "gpgconf --kill all"); + } + if (status_func) + status_func (status_func_ctrl, STATUS_WARNING, + "server_version_mismatch 0", warn, NULL); + xfree (warn); + } + } + xfree (serverversion); + return err; +} diff --git a/common/asshelp.h b/common/asshelp.h index b2f4e538f..e7e43bd1b 100644 --- a/common/asshelp.h +++ b/common/asshelp.h @@ -1,122 +1,132 @@ /* asshelp.h - Helper functions for Assuan * Copyright (C) 2004, 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_ASSHELP_H #define GNUPG_COMMON_ASSHELP_H #include #include #include "session-env.h" #include "util.h" /*-- asshelp.c --*/ void setup_libassuan_logging (unsigned int *debug_var_address, int (*log_monitor)(assuan_context_t ctx, unsigned int cat, const char *msg)); void set_libassuan_log_cats (unsigned int newcats); gpg_error_t send_pinentry_environment (assuan_context_t ctx, gpg_err_source_t errsource, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env); /* This function is used by the call-agent.c modules to fire up a new agent. */ gpg_error_t start_new_gpg_agent (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *agent_program, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg); /* This function is used to connect to the keyboxd. If needed the * keyboxd is started. */ gpg_error_t start_new_keyboxd (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *keyboxd_program, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg); /* This function is used to connect to the dirmngr. On some platforms the function is able starts a dirmngr process if needed. */ gpg_error_t start_new_dirmngr (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *dirmngr_program, int autostart, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg); /* Return the version of a server using "GETINFO version". */ gpg_error_t get_assuan_server_version (assuan_context_t ctx, int mode, char **r_version); +/* Print a server version mismatch warning. */ +gpg_error_t warn_server_version_mismatch (assuan_context_t ctx, + const char *servername, int mode, + gpg_error_t (*status_fnc) + (ctrl_t ctrl, + int status_id, + ...), + void *status_func_ctrl, + int print_hints); + /*-- asshelp2.c --*/ void set_assuan_context_func (assuan_context_t (*func)(ctrl_t ctrl)); /* Helper function to print an assuan status line using a printf format string. */ gpg_error_t status_printf (ctrl_t ctrl, const char *keyword, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); gpg_error_t status_no_printf (ctrl_t ctrl, int no, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); gpg_error_t print_assuan_status (assuan_context_t ctx, const char *keyword, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); gpg_error_t vprint_assuan_status (assuan_context_t ctx, const char *keyword, const char *format, va_list arg_ptr) GPGRT_ATTR_PRINTF(3,0); gpg_error_t vprint_assuan_status_strings (assuan_context_t ctx, const char *keyword, va_list arg_ptr); gpg_error_t print_assuan_status_strings (assuan_context_t ctx, const char *keyword, ...) GPGRT_ATTR_SENTINEL(1); #endif /*GNUPG_COMMON_ASSHELP_H*/ diff --git a/common/asshelp2.c b/common/asshelp2.c index a62189df9..4aad8a242 100644 --- a/common/asshelp2.c +++ b/common/asshelp2.c @@ -1,192 +1,192 @@ /* asshelp2.c - More helper functions for Assuan * Copyright (C) 2012 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "util.h" #include "asshelp.h" #include "status.h" /* A variable with a function to be used to return the current assuan * context for a CTRL variable. This needs to be set using the * set_assuan_ctx_func function. */ static assuan_context_t (*the_assuan_ctx_func)(ctrl_t ctrl); /* Set FUNC to be used as a mapping function from CTRL to an assuan * context. Pass NULL for FUNC to disable the use of the assuan * context in this module. */ void set_assuan_context_func (assuan_context_t (*func)(ctrl_t ctrl)) { the_assuan_ctx_func = func; } /* Helper function to print an assuan status line using a printf format string. */ gpg_error_t vprint_assuan_status (assuan_context_t ctx, const char *keyword, const char *format, va_list arg_ptr) { int rc; char *buf; rc = gpgrt_vasprintf (&buf, format, arg_ptr); if (rc < 0) return gpg_err_make (default_errsource, gpg_err_code_from_syserror ()); rc = assuan_write_status (ctx, keyword, buf); xfree (buf); return rc; } /* Helper function to print an assuan status line using a printf format string. */ gpg_error_t print_assuan_status (assuan_context_t ctx, const char *keyword, const char *format, ...) { va_list arg_ptr; gpg_error_t err; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, keyword, format, arg_ptr); va_end (arg_ptr); return err; } /* Helper function to print a list of strings as an assuan status * line. KEYWORD is the first item on the status line. ARG_PTR is a * list of strings which are all separated by a space in the output. * The last argument must be a NULL. Linefeeds and carriage returns * characters (which are not allowed in an Assuan status line) are * silently quoted in C-style. */ gpg_error_t vprint_assuan_status_strings (assuan_context_t ctx, const char *keyword, va_list arg_ptr) { gpg_error_t err = 0; const char *text; char buf[950], *p; size_t n; p = buf; n = 0; while ((text = va_arg (arg_ptr, const char *)) && n < DIM (buf)-3 ) { if (n) { *p++ = ' '; n++; } for ( ; *text && n < DIM (buf)-3; n++, text++) { if (*text == '\n') { *p++ = '\\'; *p++ = 'n'; n++; } else if (*text == '\r') { *p++ = '\\'; *p++ = 'r'; n++; } else *p++ = *text; } } *p = 0; err = assuan_write_status (ctx, keyword, buf); return err; } /* See vprint_assuan_status_strings. */ gpg_error_t print_assuan_status_strings (assuan_context_t ctx, const char *keyword, ...) { va_list arg_ptr; gpg_error_t err; va_start (arg_ptr, keyword); err = vprint_assuan_status_strings (ctx, keyword, arg_ptr); va_end (arg_ptr); return err; } /* This function is similar to print_assuan_status but takes a CTRL * arg instead of an assuan context as first argument. */ gpg_error_t status_printf (ctrl_t ctrl, const char *keyword, const char *format, ...) { gpg_error_t err; va_list arg_ptr; assuan_context_t ctx; if (!ctrl || !the_assuan_ctx_func || !(ctx = the_assuan_ctx_func (ctrl))) return 0; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, keyword, format, arg_ptr); va_end (arg_ptr); return err; } -/* Same as sytus_printf but takes a status number instead of a +/* Same as status_printf but takes a status number instead of a * keyword. */ gpg_error_t status_no_printf (ctrl_t ctrl, int no, const char *format, ...) { gpg_error_t err; va_list arg_ptr; assuan_context_t ctx; if (!ctrl || !the_assuan_ctx_func || !(ctx = the_assuan_ctx_func (ctrl))) return 0; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, get_status_string (no), format, arg_ptr); va_end (arg_ptr); return err; } diff --git a/common/status.c b/common/status.c index 269ffea5d..b752c12c6 100644 --- a/common/status.c +++ b/common/status.c @@ -1,134 +1,175 @@ /* status.c - status code helper functions * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include "util.h" #include "status.h" #include "status-codes.h" /* The stream to output the status information. Output is disabled if * this is NULL. */ static estream_t statusfp; /* Return the status string for code NO. */ const char * get_status_string ( int no ) { int idx = statusstr_msgidxof (no); if (idx == -1) return "?"; else return statusstr_msgstr + statusstr_msgidx[idx]; } /* Set a global status FD. */ void gnupg_set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (statusfp && statusfp != es_stdout && statusfp != es_stderr) es_fclose (statusfp); statusfp = NULL; if (fd == -1) return; if (fd == 1) statusfp = es_stdout; else if (fd == 2) statusfp = es_stderr; else statusfp = es_fdopen (fd, "w"); if (!statusfp) { log_fatal ("can't open fd %d for status output: %s\n", fd, gpg_strerror (gpg_error_from_syserror ())); } last_fd = fd; } /* Write a status line with code NO followed by the output of the * printf style FORMAT. The caller needs to make sure that LFs and * CRs are not printed. */ void gnupg_status_printf (int no, const char *format, ...) { va_list arg_ptr; if (!statusfp) return; /* Not enabled. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if (format) { es_putc (' ', statusfp); va_start (arg_ptr, format); es_vfprintf (statusfp, format, arg_ptr); va_end (arg_ptr); } es_putc ('\n', statusfp); } +/* Write a status line with code NO followed by the remaining + * arguments which must be a list of strings terminated by a NULL. + * Embedded CR and LFs in the strings are C-style escaped. All + * strings are printed with a space as delimiter. */ +gpg_error_t +gnupg_status_strings (ctrl_t dummy, int no, ...) +{ + va_list arg_ptr; + const char *s; + + (void)dummy; + + if (!statusfp) + return 0; /* Not enabled. */ + + va_start (arg_ptr, no); + + es_fputs ("[GNUPG:] ", statusfp); + es_fputs (get_status_string (no), statusfp); + while ((s = va_arg (arg_ptr, const char*))) + { + if (*s) + es_putc (' ', statusfp); + for (; *s; s++) + { + if (*s == '\n') + es_fputs ("\\n", statusfp); + else if (*s == '\r') + es_fputs ("\\r", statusfp); + else + es_fputc (*(const byte *)s, statusfp); + } + } + es_putc ('\n', statusfp); + es_fflush (statusfp); + + va_end (arg_ptr); + return 0; +} + + const char * get_inv_recpsgnr_code (gpg_error_t err) { const char *errstr; switch (gpg_err_code (err)) { case GPG_ERR_NO_PUBKEY: errstr = "1"; break; case GPG_ERR_AMBIGUOUS_NAME: errstr = "2"; break; case GPG_ERR_WRONG_KEY_USAGE: errstr = "3"; break; case GPG_ERR_CERT_REVOKED: errstr = "4"; break; case GPG_ERR_CERT_EXPIRED: errstr = "5"; break; case GPG_ERR_NO_CRL_KNOWN: errstr = "6"; break; case GPG_ERR_CRL_TOO_OLD: errstr = "7"; break; case GPG_ERR_NO_POLICY_MATCH: errstr = "8"; break; case GPG_ERR_UNUSABLE_SECKEY: case GPG_ERR_NO_SECKEY: errstr = "9"; break; case GPG_ERR_NOT_TRUSTED: errstr = "10"; break; case GPG_ERR_MISSING_CERT: errstr = "11"; break; case GPG_ERR_MISSING_ISSUER_CERT: errstr = "12"; break; default: errstr = "0"; break; } return errstr; } diff --git a/common/status.h b/common/status.h index aeab54202..477b29eaa 100644 --- a/common/status.h +++ b/common/status.h @@ -1,173 +1,177 @@ /* status.h - Status codes * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_STATUS_H #define GNUPG_COMMON_STATUS_H +#include "../common/fwddecl.h" + enum { STATUS_ENTER, STATUS_LEAVE, STATUS_ABORT, STATUS_GOODSIG, STATUS_BADSIG, STATUS_ERRSIG, STATUS_BADARMOR, STATUS_TRUST_UNDEFINED, STATUS_TRUST_NEVER, STATUS_TRUST_MARGINAL, STATUS_TRUST_FULLY, STATUS_TRUST_ULTIMATE, STATUS_NEED_PASSPHRASE, STATUS_VALIDSIG, STATUS_SIG_ID, STATUS_ENC_TO, STATUS_NODATA, STATUS_BAD_PASSPHRASE, STATUS_NO_PUBKEY, STATUS_NO_SECKEY, STATUS_NEED_PASSPHRASE_SYM, STATUS_DECRYPTION_KEY, STATUS_DECRYPTION_INFO, STATUS_DECRYPTION_FAILED, STATUS_DECRYPTION_OKAY, STATUS_MISSING_PASSPHRASE, STATUS_GOOD_PASSPHRASE, STATUS_GOODMDC, STATUS_BADMDC, STATUS_ERRMDC, STATUS_IMPORTED, STATUS_IMPORT_OK, STATUS_IMPORT_PROBLEM, STATUS_IMPORT_RES, STATUS_IMPORT_CHECK, STATUS_EXPORTED, STATUS_EXPORT_RES, STATUS_FILE_START, STATUS_FILE_DONE, STATUS_FILE_ERROR, STATUS_BEGIN_DECRYPTION, STATUS_END_DECRYPTION, STATUS_BEGIN_ENCRYPTION, STATUS_END_ENCRYPTION, STATUS_BEGIN_SIGNING, STATUS_DELETE_PROBLEM, STATUS_GET_BOOL, STATUS_GET_LINE, STATUS_GET_HIDDEN, STATUS_GOT_IT, STATUS_PROGRESS, STATUS_SIG_CREATED, STATUS_SESSION_KEY, STATUS_NOTATION_NAME, STATUS_NOTATION_FLAGS, STATUS_NOTATION_DATA, STATUS_POLICY_URL, STATUS_KEY_CREATED, STATUS_USERID_HINT, STATUS_UNEXPECTED, STATUS_INV_RECP, STATUS_INV_SGNR, STATUS_NO_RECP, STATUS_NO_SGNR, STATUS_KEY_CONSIDERED, STATUS_ALREADY_SIGNED, STATUS_KEYEXPIRED, STATUS_KEYREVOKED, STATUS_EXPSIG, STATUS_EXPKEYSIG, STATUS_ATTRIBUTE, STATUS_REVKEYSIG, STATUS_NEWSIG, STATUS_SIG_SUBPACKET, STATUS_PLAINTEXT, STATUS_PLAINTEXT_LENGTH, STATUS_KEY_NOT_CREATED, STATUS_NEED_PASSPHRASE_PIN, STATUS_CARDCTRL, STATUS_SC_OP_FAILURE, STATUS_SC_OP_SUCCESS, STATUS_BACKUP_KEY_CREATED, STATUS_PKA_TRUST_BAD, STATUS_PKA_TRUST_GOOD, STATUS_TOFU_USER, STATUS_TOFU_STATS, STATUS_TOFU_STATS_SHORT, STATUS_TOFU_STATS_LONG, STATUS_ENCRYPTION_COMPLIANCE_MODE, STATUS_DECRYPTION_COMPLIANCE_MODE, STATUS_VERIFICATION_COMPLIANCE_MODE, STATUS_TRUNCATED, STATUS_MOUNTPOINT, STATUS_BLOCKDEV, STATUS_PINENTRY_LAUNCHED, STATUS_PLAINTEXT_FOLLOWS, /* Used by g13-syshelp */ STATUS_ERROR, STATUS_WARNING, STATUS_SUCCESS, STATUS_FAILURE, STATUS_INQUIRE_MAXLEN }; const char *get_status_string (int code); void gnupg_set_status_fd (int fd); void gnupg_status_printf (int no, const char *format, ...) GPGRT_ATTR_PRINTF(2,3); +gpg_error_t gnupg_status_strings (ctrl_t dummy, int no, + ...) GPGRT_ATTR_SENTINEL(0); const char *get_inv_recpsgnr_code (gpg_error_t err); #endif /*GNUPG_COMMON_STATUS_H*/ diff --git a/g10/call-agent.c b/g10/call-agent.c index 806475de9..4e3bdf9e4 100644 --- a/g10/call-agent.c +++ b/g10/call-agent.c @@ -1,3071 +1,3039 @@ /* call-agent.c - Divert GPG operations to the agent. * Copyright (C) 2001-2003, 2006-2011, 2013 Free Software Foundation, Inc. * Copyright (C) 2013-2015 Werner Koch * Copyright (C) 2020 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "call-agent.h" #include "../common/status.h" #include "../common/shareddefs.h" #include "../common/host2net.h" #include "../common/ttyio.h" #define CONTROL_D ('D' - 'A' + 1) static assuan_context_t agent_ctx = NULL; static int did_early_card_test; struct confirm_parm_s { char *desc; char *ok; char *notok; }; struct default_inq_parm_s { ctrl_t ctrl; assuan_context_t ctx; struct { u32 *keyid; u32 *mainkeyid; int pubkey_algo; } keyinfo; struct confirm_parm_s *confirm; }; struct cipher_parm_s { struct default_inq_parm_s *dflt; assuan_context_t ctx; unsigned char *ciphertext; size_t ciphertextlen; }; struct writecert_parm_s { struct default_inq_parm_s *dflt; const unsigned char *certdata; size_t certdatalen; }; struct writekey_parm_s { struct default_inq_parm_s *dflt; const unsigned char *keydata; size_t keydatalen; }; struct genkey_parm_s { struct default_inq_parm_s *dflt; const char *keyparms; const char *passphrase; }; struct import_key_parm_s { struct default_inq_parm_s *dflt; const void *key; size_t keylen; }; struct cache_nonce_parm_s { char **cache_nonce_addr; char **passwd_nonce_addr; }; static gpg_error_t learn_status_cb (void *opaque, const char *line); /* If RC is not 0, write an appropriate status message. */ static void status_sc_op_failure (int rc) { switch (gpg_err_code (rc)) { case 0: break; case GPG_ERR_CANCELED: case GPG_ERR_FULLY_CANCELED: write_status_text (STATUS_SC_OP_FAILURE, "1"); break; case GPG_ERR_BAD_PIN: write_status_text (STATUS_SC_OP_FAILURE, "2"); break; default: write_status (STATUS_SC_OP_FAILURE); break; } } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct default_inq_parm_s *parm = opaque; const char *s; if (has_leading_keyword (line, "PINENTRY_LAUNCHED")) { err = gpg_proxy_pinentry_notify (parm->ctrl, line); if (err) log_error (_("failed to proxy %s inquiry to client\n"), "PINENTRY_LAUNCHED"); /* We do not pass errors to avoid breaking other code. */ } else if ((has_leading_keyword (line, "PASSPHRASE") || has_leading_keyword (line, "NEW_PASSPHRASE")) && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK) { if (have_static_passphrase ()) { s = get_static_passphrase (); err = assuan_send_data (parm->ctx, s, strlen (s)); } else { char *pw; char buf[32]; if (parm->keyinfo.keyid) emit_status_need_passphrase (parm->ctrl, parm->keyinfo.keyid, parm->keyinfo.mainkeyid, parm->keyinfo.pubkey_algo); snprintf (buf, sizeof (buf), "%u", 100); write_status_text (STATUS_INQUIRE_MAXLEN, buf); pw = cpr_get_hidden ("passphrase.enter", _("Enter passphrase: ")); cpr_kill_prompt (); if (*pw == CONTROL_D && !pw[1]) err = gpg_error (GPG_ERR_CANCELED); else err = assuan_send_data (parm->ctx, pw, strlen (pw)); xfree (pw); } } else if ((s = has_leading_keyword (line, "CONFIRM")) && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK && parm->confirm) { int ask = atoi (s); int yes; if (ask) { yes = cpr_get_answer_is_yes (NULL, parm->confirm->desc); if (yes) err = assuan_send_data (parm->ctx, NULL, 0); else err = gpg_error (GPG_ERR_NOT_CONFIRMED); } else { tty_printf ("%s", parm->confirm->desc); err = assuan_send_data (parm->ctx, NULL, 0); } } else log_debug ("ignoring gpg-agent inquiry '%s'\n", line); return err; } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername, int mode) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, mode, &serverversion); - if (err) - log_log (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED? - GPGRT_LOGLVL_INFO : GPGRT_LOGLVL_ERROR, - _("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - write_status_strings (STATUS_WARNING, "server_version_mismatch 0", - " ", warn, NULL); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, mode, + write_status_strings2, NULL, + !opt.quiet); } #define FLAG_FOR_CARD_SUPPRESS_ERRORS 2 /* Try to connect to the agent via socket or fork it off and work by pipes. Handle the server's initial greeting */ static int start_agent (ctrl_t ctrl, int flag_for_card) { int rc; (void)ctrl; /* Not yet used. */ /* Fixme: We need a context for each thread or serialize the access to the agent. */ if (agent_ctx) rc = 0; else { rc = start_new_gpg_agent (&agent_ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, opt.lc_ctype, opt.lc_messages, opt.session_env, opt.autostart, opt.verbose, DBG_IPC, NULL, NULL); if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT) { static int shown; if (!shown) { shown = 1; log_info (_("no gpg-agent running in this session\n")); } } else if (!rc && !(rc = warn_version_mismatch (agent_ctx, GPG_AGENT_NAME, 0))) { /* Tell the agent that we support Pinentry notifications. No error checking so that it will work also with older agents. */ assuan_transact (agent_ctx, "OPTION allow-pinentry-notify", NULL, NULL, NULL, NULL, NULL, NULL); /* Tell the agent about what version we are aware. This is here used to indirectly enable GPG_ERR_FULLY_CANCELED. */ assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0", NULL, NULL, NULL, NULL, NULL, NULL); /* Pass on the pinentry mode. */ if (opt.pinentry_mode) { char *tmp = xasprintf ("OPTION pinentry-mode=%s", str_pinentry_mode (opt.pinentry_mode)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) { log_error ("setting pinentry mode '%s' failed: %s\n", str_pinentry_mode (opt.pinentry_mode), gpg_strerror (rc)); write_status_error ("set_pinentry_mode", rc); } } /* Pass on the request origin. */ if (opt.request_origin) { char *tmp = xasprintf ("OPTION pretend-request-origin=%s", str_request_origin (opt.request_origin)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) { log_error ("setting request origin '%s' failed: %s\n", str_request_origin (opt.request_origin), gpg_strerror (rc)); write_status_error ("set_request_origin", rc); } } /* In DE_VS mode under Windows we require that the JENT RNG * is active. */ #ifdef HAVE_W32_SYSTEM if (!rc && opt.compliance == CO_DE_VS) { if (assuan_transact (agent_ctx, "GETINFO jent_active", NULL, NULL, NULL, NULL, NULL, NULL)) { rc = gpg_error (GPG_ERR_FORBIDDEN); log_error (_("%s is not compliant with %s mode\n"), GPG_AGENT_NAME, gnupg_compliance_option_string (opt.compliance)); write_status_error ("random-compliance", rc); } } #endif /*HAVE_W32_SYSTEM*/ } } if (!rc && flag_for_card && !did_early_card_test) { /* Request the serial number of the card for an early test. */ struct agent_card_info_s info; memset (&info, 0, sizeof info); if (!(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS)) rc = warn_version_mismatch (agent_ctx, SCDAEMON_NAME, 2); if (!rc) rc = assuan_transact (agent_ctx, opt.flags.use_only_openpgp_card? "SCD SERIALNO openpgp" : "SCD SERIALNO", NULL, NULL, NULL, NULL, learn_status_cb, &info); if (rc && !(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS)) { switch (gpg_err_code (rc)) { case GPG_ERR_NOT_SUPPORTED: case GPG_ERR_NO_SCDAEMON: write_status_text (STATUS_CARDCTRL, "6"); break; case GPG_ERR_OBJ_TERM_STATE: write_status_text (STATUS_CARDCTRL, "7"); break; default: write_status_text (STATUS_CARDCTRL, "4"); log_info ("selecting card failed: %s\n", gpg_strerror (rc)); break; } } if (!rc && is_status_enabled () && info.serialno) { char *buf; buf = xasprintf ("3 %s", info.serialno); write_status_text (STATUS_CARDCTRL, buf); xfree (buf); } agent_release_card_info (&info); if (!rc) did_early_card_test = 1; } return rc; } /* Return a new malloced string by unescaping the string S. Escaping is percent escaping and '+'/space mapping. A binary nul will silently be replaced by a 0xFF. Function returns NULL to indicate an out of memory status. */ static char * unescape_status_string (const unsigned char *s) { return percent_plus_unescape (s, 0xff); } /* Take a 20 or 32 byte hexencoded string and put it into the provided * FPRLEN byte long buffer FPR in binary format. Returns the actual * used length of the FPR buffer or 0 on error. */ static unsigned int unhexify_fpr (const char *hexstr, unsigned char *fpr, unsigned int fprlen) { const char *s; int n; for (s=hexstr, n=0; hexdigitp (s); s++, n++) ; if ((*s && *s != ' ') || !(n == 40 || n == 64)) return 0; /* no fingerprint (invalid or wrong length). */ for (s=hexstr, n=0; *s && n < fprlen; s += 2, n++) fpr[n] = xtoi_2 (s); return (n == 20 || n == 32)? n : 0; } /* Take the serial number from LINE and return it verbatim in a newly allocated string. We make sure that only hex characters are returned. */ static char * store_serialno (const char *line) { const char *s; char *p; for (s=line; hexdigitp (s); s++) ; p = xtrymalloc (s + 1 - line); if (p) { memcpy (p, line, s-line); p[s-line] = 0; } return p; } /* This is a dummy data line callback. */ static gpg_error_t dummy_data_cb (void *opaque, const void *buffer, size_t length) { (void)opaque; (void)buffer; (void)length; return 0; } /* A simple callback used to return the serialnumber of a card. */ static gpg_error_t get_serialno_cb (void *opaque, const char *line) { char **serialno = opaque; const char *keyword = line; const char *s; int keywordlen, n; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { if (*serialno) return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */ for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1)|| !(spacep (s) || !*s) ) return gpg_error (GPG_ERR_ASS_PARAMETER); *serialno = xtrymalloc (n+1); if (!*serialno) return out_of_core (); memcpy (*serialno, line, n); (*serialno)[n] = 0; } return 0; } /* Release the card info structure INFO. */ void agent_release_card_info (struct agent_card_info_s *info) { int i; if (!info) return; xfree (info->reader); info->reader = NULL; xfree (info->manufacturer_name); info->manufacturer_name = NULL; xfree (info->serialno); info->serialno = NULL; xfree (info->apptype); info->apptype = NULL; xfree (info->disp_name); info->disp_name = NULL; xfree (info->disp_lang); info->disp_lang = NULL; xfree (info->pubkey_url); info->pubkey_url = NULL; xfree (info->login_data); info->login_data = NULL; info->cafpr1len = info->cafpr2len = info->cafpr3len = 0; info->fpr1len = info->fpr2len = info->fpr3len = 0; for (i=0; i < DIM(info->private_do); i++) { xfree (info->private_do[i]); info->private_do[i] = NULL; } } static gpg_error_t learn_status_cb (void *opaque, const char *line) { struct agent_card_info_s *parm = opaque; const char *keyword = line; int keywordlen; int i; char *endp; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 6 && !memcmp (keyword, "READER", keywordlen)) { xfree (parm->reader); parm->reader = unescape_status_string (line); } else if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { xfree (parm->serialno); parm->serialno = store_serialno (line); parm->is_v2 = (strlen (parm->serialno) >= 16 && xtoi_2 (parm->serialno+12) >= 2 ); } else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen)) { xfree (parm->apptype); parm->apptype = unescape_status_string (line); } else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen)) { xfree (parm->disp_name); parm->disp_name = unescape_status_string (line); } else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen)) { xfree (parm->disp_lang); parm->disp_lang = unescape_status_string (line); } else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen)) { parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0; } else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen)) { xfree (parm->pubkey_url); parm->pubkey_url = unescape_status_string (line); } else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen)) { xfree (parm->login_data); parm->login_data = unescape_status_string (line); } else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen)) { parm->sig_counter = strtoul (line, NULL, 0); } else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen)) { char *p, *buf; buf = p = unescape_status_string (line); if (buf) { while (spacep (p)) p++; parm->chv1_cached = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; for (i=0; *p && i < 3; i++) { parm->chvmaxlen[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } for (i=0; *p && i < 3; i++) { parm->chvretry[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } xfree (buf); } } else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen)) { char *p, *p2, *buf; int abool; buf = p = unescape_status_string (line); if (buf) { for (p = strtok (buf, " "); p; p = strtok (NULL, " ")) { p2 = strchr (p, '='); if (p2) { *p2++ = 0; abool = (*p2 == '1'); if (!strcmp (p, "ki")) parm->extcap.ki = abool; else if (!strcmp (p, "aac")) parm->extcap.aac = abool; else if (!strcmp (p, "bt")) parm->extcap.bt = abool; else if (!strcmp (p, "kdf")) parm->extcap.kdf = abool; else if (!strcmp (p, "si")) parm->status_indicator = strtoul (p2, NULL, 10); } } xfree (buf); } } else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->fpr1len = unhexify_fpr (line, parm->fpr1, sizeof parm->fpr1); else if (no == 2) parm->fpr2len = unhexify_fpr (line, parm->fpr2, sizeof parm->fpr2); else if (no == 3) parm->fpr3len = unhexify_fpr (line, parm->fpr3, sizeof parm->fpr3); } else if (keywordlen == 8 && !memcmp (keyword, "KEY-TIME", keywordlen)) { int no = atoi (line); while (* line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->fpr1time = strtoul (line, NULL, 10); else if (no == 2) parm->fpr2time = strtoul (line, NULL, 10); else if (no == 3) parm->fpr3time = strtoul (line, NULL, 10); } else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { const char *hexgrp = line; int no; while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (strncmp (line, "OPENPGP.", 8)) ; else if ((no = atoi (line+8)) == 1) unhexify_fpr (hexgrp, parm->grp1, sizeof parm->grp1); else if (no == 2) unhexify_fpr (hexgrp, parm->grp2, sizeof parm->grp2); else if (no == 3) unhexify_fpr (hexgrp, parm->grp3, sizeof parm->grp3); } else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->cafpr1len = unhexify_fpr (line, parm->cafpr1,sizeof parm->cafpr1); else if (no == 2) parm->cafpr2len = unhexify_fpr (line, parm->cafpr2,sizeof parm->cafpr2); else if (no == 3) parm->cafpr3len = unhexify_fpr (line, parm->cafpr3,sizeof parm->cafpr3); } else if (keywordlen == 8 && !memcmp (keyword, "KEY-ATTR", keywordlen)) { int keyno = 0; int algo = PUBKEY_ALGO_RSA; int n = 0; sscanf (line, "%d %d %n", &keyno, &algo, &n); keyno--; if (keyno < 0 || keyno >= DIM (parm->key_attr)) return 0; parm->key_attr[keyno].algo = algo; if (algo == PUBKEY_ALGO_RSA) parm->key_attr[keyno].nbits = strtoul (line+n+3, NULL, 10); else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA) parm->key_attr[keyno].curve = openpgp_is_curve_supported (line + n, NULL, NULL); } else if (keywordlen == 12 && !memcmp (keyword, "PRIVATE-DO-", 11) && strchr("1234", keyword[11])) { int no = keyword[11] - '1'; log_assert (no >= 0 && no <= 3); xfree (parm->private_do[no]); parm->private_do[no] = unescape_status_string (line); } else if (keywordlen == 12 && !memcmp (keyword, "MANUFACTURER", 12)) { xfree (parm->manufacturer_name); parm->manufacturer_name = NULL; parm->manufacturer_id = strtoul (line, &endp, 0); while (endp && spacep (endp)) endp++; if (endp && *endp) parm->manufacturer_name = xstrdup (endp); } else if (keywordlen == 3 && !memcmp (keyword, "KDF", 3)) { unsigned char *data = unescape_status_string (line); if (data[2] != 0x03) parm->kdf_do_enabled = 0; else if (data[22] != 0x85) parm->kdf_do_enabled = 1; else parm->kdf_do_enabled = 2; xfree (data); } else if (keywordlen == 5 && !memcmp (keyword, "UIF-", 4) && strchr("123", keyword[4])) { unsigned char *data; int no = keyword[4] - '1'; log_assert (no >= 0 && no <= 2); data = unescape_status_string (line); parm->uif[no] = (data[0] != 0xff); xfree (data); } return 0; } /* Call the scdaemon to learn about a smartcard. Note that in * contradiction to the function's name, gpg-agent's LEARN command is * used and not the low-level "SCD LEARN". * Used by: * card-util.c * keyedit_menu * card_store_key_with_backup (Woth force to remove secret key data) */ int agent_scd_learn (struct agent_card_info_s *info, int force) { int rc; struct default_inq_parm_s parm; struct agent_card_info_s dummyinfo; if (!info) info = &dummyinfo; memset (info, 0, sizeof *info); memset (&parm, 0, sizeof parm); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, force ? "LEARN --sendinfo --force" : "LEARN --sendinfo", dummy_data_cb, NULL, default_inq_cb, &parm, learn_status_cb, info); /* Also try to get the key attributes. */ if (!rc) agent_scd_getattr ("KEY-ATTR", info); if (info == &dummyinfo) agent_release_card_info (info); return rc; } struct keypairinfo_cb_parm_s { keypair_info_t kpinfo; keypair_info_t *kpinfo_tail; }; /* Callback for the agent_scd_keypairinfo function. */ static gpg_error_t scd_keypairinfo_status_cb (void *opaque, const char *line) { struct keypairinfo_cb_parm_s *parm = opaque; gpg_error_t err = 0; const char *keyword = line; int keywordlen; char *line_buffer = NULL; keypair_info_t kpi = NULL; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { /* The format of such a line is: * KEYPAIRINFO [usage] [keytime] */ char *fields[4]; int nfields; const char *hexgrp, *keyref, *usage; time_t atime; u32 keytime; line_buffer = xtrystrdup (line); if (!line_buffer) { err = gpg_error_from_syserror (); goto leave; } if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 2) goto leave; /* not enough args - invalid status line - ignore */ hexgrp = fields[0]; keyref = fields[1]; if (nfields > 2) usage = fields[2]; else usage = ""; if (nfields > 3) { atime = parse_timestamp (fields[3], NULL); if (atime == (time_t)(-1)) atime = 0; keytime = atime; } else keytime = 0; kpi = xtrycalloc (1, sizeof *kpi); if (!kpi) { err = gpg_error_from_syserror (); goto leave; } if (*hexgrp == 'X' && !hexgrp[1]) *kpi->keygrip = 0; /* No hexgrip. */ else if (strlen (hexgrp) == 2*KEYGRIP_LEN) mem2str (kpi->keygrip, hexgrp, sizeof kpi->keygrip); else { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } if (!*keyref) { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } kpi->idstr = xtrystrdup (keyref); if (!kpi->idstr) { err = gpg_error_from_syserror (); goto leave; } /* Parse and set the usage. */ for (; *usage; usage++) { switch (*usage) { case 's': kpi->usage |= GCRY_PK_USAGE_SIGN; break; case 'c': kpi->usage |= GCRY_PK_USAGE_CERT; break; case 'a': kpi->usage |= GCRY_PK_USAGE_AUTH; break; case 'e': kpi->usage |= GCRY_PK_USAGE_ENCR; break; } } kpi->keytime = keytime; /* Append to the list. */ *parm->kpinfo_tail = kpi; parm->kpinfo_tail = &kpi->next; kpi = NULL; } leave: free_keypair_info (kpi); xfree (line_buffer); return err; } /* Read the keypairinfo lines of the current card directly from * scdaemon. The list is returned as a string made up of the keygrip, * a space and the keyref. The flags of the string carry the usage * bits. If KEYREF is not NULL, only a single string is returned * which matches the given keyref. */ gpg_error_t agent_scd_keypairinfo (ctrl_t ctrl, const char *keyref, keypair_info_t *r_list) { gpg_error_t err; struct keypairinfo_cb_parm_s parm; struct default_inq_parm_s inq_parm; char line[ASSUAN_LINELENGTH]; *r_list = NULL; err= start_agent (ctrl, 1); if (err) return err; memset (&inq_parm, 0, sizeof inq_parm); inq_parm.ctx = agent_ctx; parm.kpinfo = NULL; parm.kpinfo_tail = &parm.kpinfo; if (keyref) snprintf (line, DIM(line), "SCD READKEY --info-only %s", keyref); else snprintf (line, DIM(line), "SCD LEARN --keypairinfo"); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inq_parm, scd_keypairinfo_status_cb, &parm); if (!err && !parm.kpinfo) err = gpg_error (GPG_ERR_NO_DATA); if (err) free_keypair_info (parm.kpinfo); else *r_list = parm.kpinfo; return err; } /* Send an APDU to the current card. On success the status word is * stored at R_SW. With HEXAPDU being NULL only a RESET command is * send to scd. With HEXAPDU being the string "undefined" the command * "SERIALNO undefined" is send to scd. * Used by: * card-util.c */ gpg_error_t agent_scd_apdu (const char *hexapdu, unsigned int *r_sw) { gpg_error_t err; /* Start the agent but not with the card flag so that we do not autoselect the openpgp application. */ err = start_agent (NULL, 0); if (err) return err; if (!hexapdu) { err = assuan_transact (agent_ctx, "SCD RESET", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "undefined")) { err = assuan_transact (agent_ctx, "SCD SERIALNO undefined", NULL, NULL, NULL, NULL, NULL, NULL); } else { char line[ASSUAN_LINELENGTH]; membuf_t mb; unsigned char *data; size_t datalen; init_membuf (&mb, 256); snprintf (line, DIM(line), "SCD APDU %s", hexapdu); err = assuan_transact (agent_ctx, line, put_membuf_cb, &mb, NULL, NULL, NULL, NULL); if (!err) { data = get_membuf (&mb, &datalen); if (!data) err = gpg_error_from_syserror (); else if (datalen < 2) /* Ooops */ err = gpg_error (GPG_ERR_CARD); else { *r_sw = buf16_to_uint (data+datalen-2); } xfree (data); } } return err; } /* Used by: * card_store_subkey * card_store_key_with_backup */ int agent_keytocard (const char *hexgrip, int keyno, int force, const char *serialno, const char *timestamp) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); snprintf (line, DIM(line), "KEYTOCARD %s%s %s OPENPGP.%d %s", force?"--force ": "", hexgrip, serialno, keyno, timestamp); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); if (rc) return rc; return rc; } /* Object used with the agent_scd_getattr_one. */ struct getattr_one_parm_s { const char *keyword; /* Keyword to look for. */ char *data; /* Malloced and unescaped data. */ gpg_error_t err; /* Error code or 0 on success. */ }; /* Callback for agent_scd_getattr_one. */ static gpg_error_t getattr_one_status_cb (void *opaque, const char *line) { struct getattr_one_parm_s *parm = opaque; const char *s; if (parm->data) return 0; /* We want only the first occurrence. */ if ((s=has_leading_keyword (line, parm->keyword))) { parm->data = percent_plus_unescape (s, 0xff); if (!parm->data) parm->err = gpg_error_from_syserror (); } return 0; } /* Simplified version of agent_scd_getattr. This function returns * only the first occurrence of the attribute NAME and stores it at * R_VALUE. A nul in the result is silennly replaced by 0xff. On * error NULL is stored at R_VALUE. */ gpg_error_t agent_scd_getattr_one (const char *name, char **r_value) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inqparm; struct getattr_one_parm_s parm; *r_value = NULL; if (!*name) return gpg_error (GPG_ERR_INV_VALUE); memset (&inqparm, 0, sizeof inqparm); inqparm.ctx = agent_ctx; memset (&parm, 0, sizeof parm); parm.keyword = name; /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); stpcpy (stpcpy (line, "SCD GETATTR "), name); err = start_agent (NULL, 1); if (err) return err; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inqparm, getattr_one_status_cb, &parm); if (!err && parm.err) err = parm.err; else if (!err && !parm.data) err = gpg_error (GPG_ERR_NO_DATA); if (!err) *r_value = parm.data; else xfree (parm.data); return err; } /* Call the agent to retrieve a data object. This function returns * the data in the same structure as used by the learn command. It is * allowed to update such a structure using this command. * * Used by: * build_sk_list * enum_secret_keys * get_signature_count * card-util.c * generate_keypair (KEY-ATTR) * card_store_key_with_backup (SERIALNO) * generate_card_subkeypair (KEY-ATTR) */ int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); if (!*name) return gpg_error (GPG_ERR_INV_VALUE); /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); stpcpy (stpcpy (line, "SCD GETATTR "), name); rc = start_agent (NULL, 1); if (rc) return rc; parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, learn_status_cb, info); return rc; } /* Send an setattr command to the SCdaemon. * Used by: * card-util.c */ gpg_error_t agent_scd_setattr (const char *name, const void *value_arg, size_t valuelen) { gpg_error_t err; const unsigned char *value = value_arg; char line[ASSUAN_LINELENGTH]; char *p; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); if (!*name || !valuelen) return gpg_error (GPG_ERR_INV_VALUE); /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); p = stpcpy (stpcpy (line, "SCD SETATTR "), name); *p++ = ' '; for (; valuelen; value++, valuelen--) { if (p >= line + DIM(line)-5 ) return gpg_error (GPG_ERR_TOO_LARGE); if (*value < ' ' || *value == '+' || *value == '%') { sprintf (p, "%%%02X", *value); p += 3; } else if (*value == ' ') *p++ = '+'; else *p++ = *value; } *p = 0; err = start_agent (NULL, 1); if (!err) { parm.ctx = agent_ctx; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); } status_sc_op_failure (err); return err; } /* Handle a CERTDATA inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the END command. */ static gpg_error_t inq_writecert_parms (void *opaque, const char *line) { int rc; struct writecert_parm_s *parm = opaque; if (has_leading_keyword (line, "CERTDATA")) { rc = assuan_send_data (parm->dflt->ctx, parm->certdata, parm->certdatalen); } else rc = default_inq_cb (parm->dflt, line); return rc; } /* Send a WRITECERT command to the SCdaemon. * Used by: * card-util.c */ int agent_scd_writecert (const char *certidstr, const unsigned char *certdata, size_t certdatalen) { int rc; char line[ASSUAN_LINELENGTH]; struct writecert_parm_s parms; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; memset (&parms, 0, sizeof parms); snprintf (line, DIM(line), "SCD WRITECERT %s", certidstr); dfltparm.ctx = agent_ctx; parms.dflt = &dfltparm; parms.certdata = certdata; parms.certdatalen = certdatalen; rc = assuan_transact (agent_ctx, line, NULL, NULL, inq_writecert_parms, &parms, NULL, NULL); return rc; } /* Status callback for the SCD GENKEY command. */ static gpg_error_t scd_genkey_cb (void *opaque, const char *line) { u32 *createtime = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen)) { *createtime = (u32)strtoul (line, NULL, 10); } else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen)) { write_status_text (STATUS_PROGRESS, line); } return 0; } /* Send a GENKEY command to the SCdaemon. If *CREATETIME is not 0, * the value will be passed to SCDAEMON with --timestamp option so that * the key is created with this. Otherwise, timestamp was generated by * SCDEAMON. On success, creation time is stored back to * CREATETIME. * Used by: * gen_card_key */ int agent_scd_genkey (int keyno, int force, u32 *createtime) { int rc; char line[ASSUAN_LINELENGTH]; gnupg_isotime_t tbuf; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; if (*createtime) epoch2isotime (tbuf, *createtime); else *tbuf = 0; snprintf (line, DIM(line), "SCD GENKEY %s%s %s %d", *tbuf? "--timestamp=":"", tbuf, force? "--force":"", keyno); dfltparm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, scd_genkey_cb, createtime); status_sc_op_failure (rc); return rc; } /* Return the serial number of the card or an appropriate error. The * serial number is returned as a hexstring. With DEMAND the active * card is switched to the card with that serialno. * Used by: * card-util.c * build_sk_list * enum_secret_keys */ int agent_scd_serialno (char **r_serialno, const char *demand) { int err; char *serialno = NULL; char line[ASSUAN_LINELENGTH]; err = start_agent (NULL, (1 | FLAG_FOR_CARD_SUPPRESS_ERRORS)); if (err) return err; if (!demand) strcpy (line, "SCD SERIALNO"); else snprintf (line, DIM(line), "SCD SERIALNO --demand=%s", demand); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, get_serialno_cb, &serialno); if (err) { xfree (serialno); return err; } *r_serialno = serialno; return 0; } /* Send a READCERT command to the SCdaemon. * Used by: * card-util.c */ int agent_scd_readcert (const char *certidstr, void **r_buf, size_t *r_buflen) { int rc; char line[ASSUAN_LINELENGTH]; membuf_t data; size_t len; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); *r_buf = NULL; rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; init_membuf (&data, 2048); snprintf (line, DIM(line), "SCD READCERT %s", certidstr); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } *r_buf = get_membuf (&data, r_buflen); if (!*r_buf) return gpg_error (GPG_ERR_ENOMEM); return 0; } /* Callback for the agent_scd_readkey function. */ static gpg_error_t readkey_status_cb (void *opaque, const char *line) { u32 *keytimep = opaque; gpg_error_t err = 0; const char *args; char *line_buffer = NULL; /* FIXME: Get that info from the KEYPAIRINFO line. */ if ((args = has_leading_keyword (line, "KEYPAIRINFO")) && !*keytimep) { /* The format of such a line is: * KEYPAIRINFO [usage] [keytime] * * Note that we use only the first valid KEYPAIRINFO line. More * lines are possible if a second card carries the same key. */ char *fields[4]; int nfields; time_t atime; line_buffer = xtrystrdup (line); if (!line_buffer) { err = gpg_error_from_syserror (); goto leave; } if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 4) goto leave; /* not enough args - ignore */ if (nfields > 3) { atime = parse_timestamp (fields[3], NULL); if (atime == (time_t)(-1)) atime = 0; *keytimep = atime; } else *keytimep = 0; } leave: xfree (line_buffer); return err; } /* This is a variant of agent_readkey which sends a READKEY command * directly Scdaemon. On success a new s-expression is stored at * R_RESULT. If R_KEYTIME is not NULL the key cresation time of an * OpenPGP card is stored there - if that is not known 0 is stored. * In the latter case it is allowed to pass NULL for R_RESULT. */ gpg_error_t agent_scd_readkey (ctrl_t ctrl, const char *keyrefstr, gcry_sexp_t *r_result, u32 *r_keytime) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; unsigned char *buf; size_t len, buflen; struct default_inq_parm_s dfltparm; u32 keytime; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctx = agent_ctx; if (r_result) *r_result = NULL; if (r_keytime) *r_keytime = 0; err = start_agent (ctrl, 1); if (err) return err; init_membuf (&data, 1024); snprintf (line, DIM(line), "SCD READKEY --info%s -- %s", r_result? "":"-only", keyrefstr); keytime = 0; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, readkey_status_cb, &keytime); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &buflen); if (!buf) return gpg_error_from_syserror (); if (r_result) err = gcry_sexp_new (r_result, buf, buflen, 0); else err = 0; xfree (buf); if (!err && r_keytime) *r_keytime = keytime; return err; } struct card_cardlist_parm_s { int error; strlist_t list; }; /* Callback function for agent_card_cardlist. */ static gpg_error_t card_cardlist_cb (void *opaque, const char *line) { struct card_cardlist_parm_s *parm = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { const char *s; int n; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1) || *s) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); else add_to_strlist (&parm->list, line); } return 0; } /* Return a list of currently available cards. * Used by: * card-util.c * skclist.c */ int agent_scd_cardlist (strlist_t *result) { int err; char line[ASSUAN_LINELENGTH]; struct card_cardlist_parm_s parm; memset (&parm, 0, sizeof parm); *result = NULL; err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS); if (err) return err; strcpy (line, "SCD GETINFO card_list"); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, card_cardlist_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_strlist (parm.list); return 0; } struct card_keyinfo_parm_s { int error; keypair_info_t list; }; /* Callback function for agent_card_keylist. */ static gpg_error_t card_keyinfo_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct card_keyinfo_parm_s *parm = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 7 && !memcmp (keyword, "KEYINFO", keywordlen)) { const char *s; int n; keypair_info_t keyinfo; keypair_info_t *l_p = &parm->list; while ((*l_p)) l_p = &(*l_p)->next; keyinfo = xtrycalloc (1, sizeof *keyinfo); if (!keyinfo) { alloc_error: if (!parm->error) parm->error = gpg_error_from_syserror (); return 0; } for (n=0,s=line; hexdigitp (s); s++, n++) ; if (n != 40) { parm_error: if (!parm->error) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); return 0; } memcpy (keyinfo->keygrip, line, 40); keyinfo->keygrip[40] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (*line++ != 'T') goto parm_error; if (!*line) goto parm_error; while (spacep (line)) line++; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n) goto parm_error; keyinfo->serialno = xtrymalloc (n+1); if (!keyinfo->serialno) goto alloc_error; memcpy (keyinfo->serialno, line, n); keyinfo->serialno[n] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (!*line) goto parm_error; keyinfo->idstr = xtrystrdup (line); if (!keyinfo->idstr) goto alloc_error; *l_p = keyinfo; } return err; } /* Free a keypair info list. */ void free_keypair_info (keypair_info_t l) { keypair_info_t l_next; for (; l; l = l_next) { l_next = l->next; xfree (l->serialno); xfree (l->idstr); xfree (l); } } /* Call the scdaemon to check if a key of KEYGRIP is available, or retrieve list of available keys on cards. With CAP, we can limit keys with specified capability. On success, the allocated structure is stored at RESULT. On error, an error code is returned and NULL is stored at RESULT. */ gpg_error_t agent_scd_keyinfo (const char *keygrip, int cap, keypair_info_t *result) { int err; struct card_keyinfo_parm_s parm; char line[ASSUAN_LINELENGTH]; char *list_option; *result = NULL; switch (cap) { case 0: list_option = "--list"; break; case GCRY_PK_USAGE_SIGN: list_option = "--list=sign"; break; case GCRY_PK_USAGE_ENCR: list_option = "--list=encr"; break; case GCRY_PK_USAGE_AUTH: list_option = "--list=auth"; break; default: return gpg_error (GPG_ERR_INV_VALUE); } memset (&parm, 0, sizeof parm); snprintf (line, sizeof line, "SCD KEYINFO %s", keygrip ? keygrip : list_option); err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS); if (err) return err; err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, card_keyinfo_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_keypair_info (parm.list); return err; } /* Change the PIN of an OpenPGP card or reset the retry counter. * CHVNO 1: Change the PIN * 2: For v1 cards: Same as 1. * For v2 cards: Reset the PIN using the Reset Code. * 3: Change the admin PIN * 101: Set a new PIN and reset the retry counter * 102: For v1 cars: Same as 101. * For v2 cards: Set a new Reset Code. * SERIALNO is not used. * Used by: * card-util.c */ int agent_scd_change_pin (int chvno, const char *serialno) { int rc; char line[ASSUAN_LINELENGTH]; const char *reset = ""; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); (void)serialno; if (chvno >= 100) reset = "--reset"; chvno %= 100; rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "SCD PASSWD %s %d", reset, chvno); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); status_sc_op_failure (rc); return rc; } /* Perform a CHECKPIN operation. SERIALNO should be the serial * number of the card - optionally followed by the fingerprint; * however the fingerprint is ignored here. * Used by: * card-util.c */ int agent_scd_checkpin (const char *serialno) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 1); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "SCD CHECKPIN %s", serialno); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); status_sc_op_failure (rc); return rc; } /* Note: All strings shall be UTF-8. On success the caller needs to free the string stored at R_PASSPHRASE. On error NULL will be stored at R_PASSPHRASE and an appropriate error code returned. Only called from passphrase.c:passphrase_get - see there for more comments on this ugly API. */ gpg_error_t agent_get_passphrase (const char *cache_id, const char *err_msg, const char *prompt, const char *desc_msg, int newsymkey, int repeat, int check, char **r_passphrase) { int rc; char line[ASSUAN_LINELENGTH]; char *arg1 = NULL; char *arg2 = NULL; char *arg3 = NULL; char *arg4 = NULL; membuf_t data; struct default_inq_parm_s dfltparm; int have_newsymkey; memset (&dfltparm, 0, sizeof dfltparm); *r_passphrase = NULL; rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; /* Check that the gpg-agent understands the repeat option. */ if (assuan_transact (agent_ctx, "GETINFO cmd_has_option GET_PASSPHRASE repeat", NULL, NULL, NULL, NULL, NULL, NULL)) return gpg_error (GPG_ERR_NOT_SUPPORTED); have_newsymkey = !(assuan_transact (agent_ctx, "GETINFO cmd_has_option GET_PASSPHRASE newsymkey", NULL, NULL, NULL, NULL, NULL, NULL)); if (cache_id && *cache_id) if (!(arg1 = percent_plus_escape (cache_id))) goto no_mem; if (err_msg && *err_msg) if (!(arg2 = percent_plus_escape (err_msg))) goto no_mem; if (prompt && *prompt) if (!(arg3 = percent_plus_escape (prompt))) goto no_mem; if (desc_msg && *desc_msg) if (!(arg4 = percent_plus_escape (desc_msg))) goto no_mem; /* CHECK && REPEAT or NEWSYMKEY is here an indication that a new * passphrase for symmetric encryption is requested; if the agent * supports this we enable the modern API by also passing --newsymkey. */ snprintf (line, DIM(line), "GET_PASSPHRASE --data --repeat=%d%s%s -- %s %s %s %s", repeat, ((repeat && check) || newsymkey)? " --check":"", (have_newsymkey && newsymkey)? " --newsymkey":"", arg1? arg1:"X", arg2? arg2:"X", arg3? arg3:"X", arg4? arg4:"X"); xfree (arg1); xfree (arg2); xfree (arg3); xfree (arg4); init_membuf_secure (&data, 64); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (rc) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); *r_passphrase = get_membuf (&data, NULL); if (!*r_passphrase) rc = gpg_error_from_syserror (); } return rc; no_mem: rc = gpg_error_from_syserror (); xfree (arg1); xfree (arg2); xfree (arg3); xfree (arg4); return rc; } gpg_error_t agent_clear_passphrase (const char *cache_id) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); if (!cache_id || !*cache_id) return 0; rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "CLEAR_PASSPHRASE %s", cache_id); return assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); } /* Ask the agent to pop up a confirmation dialog with the text DESC and an okay and cancel button. */ gpg_error_t gpg_agent_get_confirmation (const char *desc) { int rc; char *tmp; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); rc = start_agent (NULL, 0); if (rc) return rc; dfltparm.ctx = agent_ctx; tmp = percent_plus_escape (desc); if (!tmp) return gpg_error_from_syserror (); snprintf (line, DIM(line), "GET_CONFIRMATION %s", tmp); xfree (tmp); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); return rc; } /* Return the S2K iteration count as computed by gpg-agent. On error * print a warning and return a default value. */ unsigned long agent_get_s2k_count (void) { gpg_error_t err; membuf_t data; char *buf; unsigned long count = 0; err = start_agent (NULL, 0); if (err) goto leave; init_membuf (&data, 32); err = assuan_transact (agent_ctx, "GETINFO s2k_count", put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); buf = get_membuf (&data, NULL); if (!buf) err = gpg_error_from_syserror (); else { count = strtoul (buf, NULL, 10); xfree (buf); } } leave: if (err || count < 65536) { /* Don't print an error if an older agent is used. */ if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER) log_error (_("problem with the agent: %s\n"), gpg_strerror (err)); /* Default to 65536 which was used up to 2.0.13. */ count = 65536; } return count; } struct keyinfo_data_parm_s { char *serialno; int is_smartcard; int passphrase_cached; int cleartext; int card_available; }; static gpg_error_t keyinfo_status_cb (void *opaque, const char *line) { struct keyinfo_data_parm_s *data = opaque; char *s; if ((s = has_leading_keyword (line, "KEYINFO")) && data) { /* Parse the arguments: * 0 1 2 3 4 5 * * * 6 7 8 * */ char *fields[9]; if (split_fields (s, fields, DIM (fields)) == 9) { data->is_smartcard = (fields[1][0] == 'T'); if (data->is_smartcard && !data->serialno && strcmp (fields[2], "-")) data->serialno = xtrystrdup (fields[2]); /* '1' for cached */ data->passphrase_cached = (fields[4][0] == '1'); /* 'P' for protected, 'C' for clear */ data->cleartext = (fields[5][0] == 'C'); /* 'A' for card is available */ data->card_available = (fields[8][0] == 'A'); } } return 0; } /* Ask the agent whether a secret key for the given public key is available. Returns 0 if not available. Bigger value is preferred. */ int agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *hexgrip; struct keyinfo_data_parm_s keyinfo; memset (&keyinfo, 0, sizeof keyinfo); err = start_agent (ctrl, 0); if (err) return err; err = hexkeygrip_from_pk (pk, &hexgrip); if (err) return err; snprintf (line, sizeof line, "KEYINFO %s", hexgrip); xfree (hexgrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, keyinfo_status_cb, &keyinfo); xfree (keyinfo.serialno); if (err) return 0; if (keyinfo.card_available) return 4; if (keyinfo.passphrase_cached) return 3; if (keyinfo.is_smartcard) return 2; return 1; } /* Ask the agent whether a secret key is available for any of the keys (primary or sub) in KEYBLOCK. Returns 0 if available. */ gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *p; kbnode_t kbctx, node; int nkeys; unsigned char grip[KEYGRIP_LEN]; err = start_agent (ctrl, 0); if (err) return err; err = gpg_error (GPG_ERR_NO_SECKEY); /* Just in case no key was found in KEYBLOCK. */ p = stpcpy (line, "HAVEKEY"); for (kbctx=NULL, nkeys=0; (node = walk_kbnode (keyblock, &kbctx, 0)); ) if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { if (nkeys && ((p - line) + 41) > (ASSUAN_LINELENGTH - 2)) { err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err != gpg_err_code (GPG_ERR_NO_SECKEY)) break; /* Seckey available or unexpected error - ready. */ p = stpcpy (line, "HAVEKEY"); nkeys = 0; } err = keygrip_from_pk (node->pkt->pkt.public_key, grip); if (err) return err; *p++ = ' '; bin2hex (grip, 20, p); p += 40; nkeys++; } if (!err && nkeys) err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); return err; } /* Return the serial number for a secret key. If the returned serial number is NULL, the key is not stored on a smartcard. Caller needs to free R_SERIALNO. if r_cleartext is not NULL, the referenced int will be set to 1 if the agent's copy of the key is stored in the clear, or 0 otherwise */ gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct keyinfo_data_parm_s keyinfo; memset (&keyinfo, 0,sizeof keyinfo); *r_serialno = NULL; err = start_agent (ctrl, 0); if (err) return err; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, keyinfo_status_cb, &keyinfo); if (!err && keyinfo.serialno) { /* Sanity check for bad characters. */ if (strpbrk (keyinfo.serialno, ":\n\r")) err = GPG_ERR_INV_VALUE; } if (err) xfree (keyinfo.serialno); else { *r_serialno = keyinfo.serialno; if (r_cleartext) *r_cleartext = keyinfo.cleartext; } return err; } /* Status callback for agent_import_key, agent_export_key and agent_genkey. */ static gpg_error_t cache_nonce_status_cb (void *opaque, const char *line) { struct cache_nonce_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "CACHE_NONCE"))) { if (parm->cache_nonce_addr) { xfree (*parm->cache_nonce_addr); *parm->cache_nonce_addr = xtrystrdup (s); } } else if ((s = has_leading_keyword (line, "PASSWD_NONCE"))) { if (parm->passwd_nonce_addr) { xfree (*parm->passwd_nonce_addr); *parm->passwd_nonce_addr = xtrystrdup (s); } } else if ((s = has_leading_keyword (line, "PROGRESS"))) { if (opt.enable_progress_filter) write_status_text (STATUS_PROGRESS, s); } return 0; } /* Handle a KEYPARMS inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the end */ static gpg_error_t inq_genkey_parms (void *opaque, const char *line) { struct genkey_parm_s *parm = opaque; gpg_error_t err; if (has_leading_keyword (line, "KEYPARAM")) { err = assuan_send_data (parm->dflt->ctx, parm->keyparms, strlen (parm->keyparms)); } else if (has_leading_keyword (line, "NEWPASSWD") && parm->passphrase) { err = assuan_send_data (parm->dflt->ctx, parm->passphrase, strlen (parm->passphrase)); } else err = default_inq_cb (parm->dflt, line); return err; } /* Call the agent to generate a new key. KEYPARMS is the usual S-expression giving the parameters of the key. gpg-agent passes it gcry_pk_genkey. If NO_PROTECTION is true the agent is advised not to protect the generated key. If NO_PROTECTION is not set and PASSPHRASE is not NULL the agent is requested to protect the key with that passphrase instead of asking for one. TIMESTAMP is the creation time of the key or zero. */ gpg_error_t agent_genkey (ctrl_t ctrl, char **cache_nonce_addr, char **passwd_nonce_addr, const char *keyparms, int no_protection, const char *passphrase, time_t timestamp, gcry_sexp_t *r_pubkey) { gpg_error_t err; struct genkey_parm_s gk_parm; struct cache_nonce_parm_s cn_parm; struct default_inq_parm_s dfltparm; membuf_t data; size_t len; unsigned char *buf; char timestamparg[16 + 16]; /* The 2nd 16 is sizeof(gnupg_isotime_t) */ char line[ASSUAN_LINELENGTH]; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_pubkey = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (timestamp) { strcpy (timestamparg, " --timestamp="); epoch2isotime (timestamparg+13, timestamp); } else *timestamparg = 0; if (passwd_nonce_addr && *passwd_nonce_addr) ; /* A RESET would flush the passwd nonce cache. */ else { err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } init_membuf (&data, 1024); gk_parm.dflt = &dfltparm; gk_parm.keyparms = keyparms; gk_parm.passphrase = passphrase; snprintf (line, sizeof line, "GENKEY%s%s%s%s%s%s", *timestamparg? timestamparg : "", no_protection? " --no-protection" : passphrase ? " --inq-passwd" : /* */ "", passwd_nonce_addr && *passwd_nonce_addr? " --passwd-nonce=":"", passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"", cache_nonce_addr && *cache_nonce_addr? " ":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:""); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, inq_genkey_parms, &gk_parm, cache_nonce_status_cb, &cn_parm); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) err = gpg_error_from_syserror (); else { err = gcry_sexp_sscan (r_pubkey, NULL, buf, len); xfree (buf); } return err; } /* Call the agent to read the public key part for a given keygrip. * Values from FROMCARD: * 0 - Standard * 1 - The key is read from the current card * via the agent and a stub file is created. */ gpg_error_t agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip, unsigned char **r_pubkey) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_pubkey = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; err = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (fromcard) snprintf (line, DIM(line), "READKEY --card -- %s", hexkeygrip); else snprintf (line, DIM(line), "READKEY -- %s", hexkeygrip); init_membuf (&data, 1024); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); if (!gcry_sexp_canon_len (buf, len, NULL, NULL)) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } *r_pubkey = buf; return 0; } /* Call the agent to do a sign operation using the key identified by the hex string KEYGRIP. DESC is a description of the key to be displayed if the agent needs to ask for the PIN. DIGEST and DIGESTLEN is the hash value to sign and DIGESTALGO the algorithm id used to compute the digest. If CACHE_NONCE is used the agent is advised to first try a passphrase associated with that nonce. */ gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *keygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, unsigned char *digest, size_t digestlen, int digestalgo, gcry_sexp_t *r_sigval) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; *r_sigval = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (digestlen*2 + 50 > DIM(line)) return gpg_error (GPG_ERR_GENERAL); err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; snprintf (line, DIM(line), "SIGKEY %s", keygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, sizeof line, "SETHASH %d ", digestalgo); bin2hex (digest, digestlen, line + strlen (line)); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; init_membuf (&data, 1024); snprintf (line, sizeof line, "PKSIGN%s%s", cache_nonce? " -- ":"", cache_nonce? cache_nonce:""); if (DBG_CLOCK) log_clock ("enter signing"); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (DBG_CLOCK) log_clock ("leave signing"); if (err) xfree (get_membuf (&data, NULL)); else { unsigned char *buf; size_t len; buf = get_membuf (&data, &len); if (!buf) err = gpg_error_from_syserror (); else { err = gcry_sexp_sscan (r_sigval, NULL, buf, len); xfree (buf); } } return err; } /* Handle a CIPHERTEXT inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the END. */ static gpg_error_t inq_ciphertext_cb (void *opaque, const char *line) { struct cipher_parm_s *parm = opaque; int rc; if (has_leading_keyword (line, "CIPHERTEXT")) { assuan_begin_confidential (parm->ctx); rc = assuan_send_data (parm->dflt->ctx, parm->ciphertext, parm->ciphertextlen); assuan_end_confidential (parm->ctx); } else rc = default_inq_cb (parm->dflt, line); return rc; } /* Check whether there is any padding info from the agent. */ static gpg_error_t padding_info_cb (void *opaque, const char *line) { int *r_padding = opaque; const char *s; if ((s=has_leading_keyword (line, "PADDING"))) { *r_padding = atoi (s); } return 0; } /* Call the agent to do a decrypt operation using the key identified by the hex string KEYGRIP and the input data S_CIPHERTEXT. On the success the decoded value is stored verbatim at R_BUF and its length at R_BUF; the callers needs to release it. KEYID, MAINKEYID and PUBKEY_ALGO are used to construct additional promots or status messages. The padding information is stored at R_PADDING with -1 for not known. */ gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc, u32 *keyid, u32 *mainkeyid, int pubkey_algo, gcry_sexp_t s_ciphertext, unsigned char **r_buf, size_t *r_buflen, int *r_padding) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; size_t n, len; char *p, *buf, *endp; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; if (!keygrip || strlen(keygrip) != 40 || !s_ciphertext || !r_buf || !r_buflen || !r_padding) return gpg_error (GPG_ERR_INV_VALUE); *r_buf = NULL; *r_padding = -1; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; err = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; snprintf (line, sizeof line, "SETKEY %s", keygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } init_membuf_secure (&data, 1024); { struct cipher_parm_s parm; parm.dflt = &dfltparm; parm.ctx = agent_ctx; err = make_canon_sexp (s_ciphertext, &parm.ciphertext, &parm.ciphertextlen); if (err) return err; err = assuan_transact (agent_ctx, "PKDECRYPT", put_membuf_cb, &data, inq_ciphertext_cb, &parm, padding_info_cb, r_padding); xfree (parm.ciphertext); } if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); if (len == 0 || *buf != '(') { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } if (len < 12 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)" */ { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } while (buf[len-1] == 0) len--; if (buf[len-1] != ')') return gpg_error (GPG_ERR_INV_SEXP); len--; /* Drop the final close-paren. */ p = buf + 8; /* Skip leading parenthesis and the value tag. */ len -= 8; /* Count only the data of the second part. */ n = strtoul (p, &endp, 10); if (!n || *endp != ':') { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } endp++; if (endp-p+n > len) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */ } memmove (buf, endp, n); *r_buflen = n; *r_buf = buf; return 0; } /* Retrieve a key encryption key from the agent. With FOREXPORT true the key shall be used for export, with false for import. On success the new key is stored at R_KEY and its length at R_KEKLEN. */ gpg_error_t agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; *r_kek = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; snprintf (line, DIM(line), "KEYWRAP_KEY %s", forexport? "--export":"--import"); init_membuf_secure (&data, 64); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_kek = buf; *r_keklen = len; return 0; } /* Handle the inquiry for an IMPORT_KEY command. */ static gpg_error_t inq_import_key_parms (void *opaque, const char *line) { struct import_key_parm_s *parm = opaque; gpg_error_t err; if (has_leading_keyword (line, "KEYDATA")) { err = assuan_send_data (parm->dflt->ctx, parm->key, parm->keylen); } else err = default_inq_cb (parm->dflt, line); return err; } /* Call the agent to import a key into the agent. */ gpg_error_t agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr, const void *key, size_t keylen, int unattended, int force, u32 *keyid, u32 *mainkeyid, int pubkey_algo, u32 timestamp) { gpg_error_t err; struct import_key_parm_s parm; struct cache_nonce_parm_s cn_parm; char timestamparg[16 + 16]; /* The 2nd 16 is sizeof(gnupg_isotime_t) */ char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (timestamp) { strcpy (timestamparg, " --timestamp="); epoch2isotime (timestamparg+13, timestamp); } else *timestamparg = 0; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } parm.dflt = &dfltparm; parm.key = key; parm.keylen = keylen; snprintf (line, sizeof line, "IMPORT_KEY%s%s%s%s%s", *timestamparg? timestamparg : "", unattended? " --unattended":"", force? " --force":"", cache_nonce_addr && *cache_nonce_addr? " ":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:""); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, NULL, NULL, inq_import_key_parms, &parm, cache_nonce_status_cb, &cn_parm); return err; } /* Receive a secret key from the agent. HEXKEYGRIP is the hexified keygrip, DESC a prompt to be displayed with the agent's passphrase question (needs to be plus+percent escaped). if OPENPGP_PROTECTED is not zero, ensure that the key material is returned in RFC 4880-compatible passphrased-protected form. If CACHE_NONCE_ADDR is not NULL the agent is advised to first try a passphrase associated with that nonce. On success the key is stored as a canonical S-expression at R_RESULT and R_RESULTLEN. */ gpg_error_t agent_export_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int openpgp_protected, char **cache_nonce_addr, unsigned char **r_result, size_t *r_resultlen, u32 *keyid, u32 *mainkeyid, int pubkey_algo) { gpg_error_t err; struct cache_nonce_parm_s cn_parm; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.keyinfo.keyid = keyid; dfltparm.keyinfo.mainkeyid = mainkeyid; dfltparm.keyinfo.pubkey_algo = pubkey_algo; *r_result = NULL; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, DIM(line), "EXPORT_KEY %s%s%s %s", openpgp_protected ? "--openpgp ":"", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", hexkeygrip); init_membuf_secure (&data, 1024); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = NULL; err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, cache_nonce_status_cb, &cn_parm); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_result = buf; *r_resultlen = len; return 0; } /* Status callback for handling confirmation. */ static gpg_error_t confirm_status_cb (void *opaque, const char *line) { struct confirm_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "SETDESC"))) { xfree (parm->desc); parm->desc = unescape_status_string (s); } else if ((s = has_leading_keyword (line, "SETOK"))) { xfree (parm->ok); parm->ok = unescape_status_string (s); } else if ((s = has_leading_keyword (line, "SETNOTOK"))) { xfree (parm->notok); parm->notok = unescape_status_string (s); } return 0; } /* Ask the agent to delete the key identified by HEXKEYGRIP. If DESC is not NULL, display DESC instead of the default description message. If FORCE is true the agent is advised not to ask for confirmation. */ gpg_error_t agent_delete_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int force) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; struct confirm_parm_s confirm_parm; memset (&confirm_parm, 0, sizeof confirm_parm); memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; dfltparm.confirm = &confirm_parm; err = start_agent (ctrl, 0); if (err) return err; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, DIM(line), "DELETE_KEY%s %s", force? " --force":"", hexkeygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, confirm_status_cb, &confirm_parm); xfree (confirm_parm.desc); xfree (confirm_parm.ok); xfree (confirm_parm.notok); return err; } /* Ask the agent to change the passphrase of the key identified by * HEXKEYGRIP. If DESC is not NULL, display DESC instead of the * default description message. If CACHE_NONCE_ADDR is not NULL the * agent is advised to first try a passphrase associated with that * nonce. If PASSWD_NONCE_ADDR is not NULL the agent will try to use * the passphrase associated with that nonce for the new passphrase. * If VERIFY is true the passphrase is only verified. */ gpg_error_t agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int verify, char **cache_nonce_addr, char **passwd_nonce_addr) { gpg_error_t err; struct cache_nonce_parm_s cn_parm; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); dfltparm.ctrl = ctrl; err = start_agent (ctrl, 0); if (err) return err; dfltparm.ctx = agent_ctx; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } if (verify) snprintf (line, DIM(line), "PASSWD %s%s --verify %s", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", hexkeygrip); else snprintf (line, DIM(line), "PASSWD %s%s %s%s %s", cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"", cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"", passwd_nonce_addr && *passwd_nonce_addr? "--passwd-nonce=":"", passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"", hexkeygrip); cn_parm.cache_nonce_addr = cache_nonce_addr; cn_parm.passwd_nonce_addr = passwd_nonce_addr; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, cache_nonce_status_cb, &cn_parm); return err; } /* Return the version reported by gpg-agent. */ gpg_error_t agent_get_version (ctrl_t ctrl, char **r_version) { gpg_error_t err; err = start_agent (ctrl, 0); if (err) return err; err = get_assuan_server_version (agent_ctx, 0, r_version); return err; } diff --git a/g10/call-dirmngr.c b/g10/call-dirmngr.c index 02d1edb9f..1282ae192 100644 --- a/g10/call-dirmngr.c +++ b/g10/call-dirmngr.c @@ -1,1433 +1,1402 @@ /* call-dirmngr.c - GPG operations to the Dirmngr. * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/keyserver.h" #include "../common/status.h" #include "call-dirmngr.h" /* Keys retrieved from the web key directory should be small. There * is only one UID and we can expect that the number of subkeys is * reasonable. So we set a generous limit of 256 KiB. */ #define MAX_WKD_RESULT_LENGTH (256 * 1024) /* Parameter structure used to gather status info. Note that it is * also used for WKD requests. */ struct ks_status_parm_s { const char *keyword; /* Look for this keyword or NULL for "SOURCE". */ char *source; }; /* Parameter structure used with the KS_SEARCH command. */ struct ks_search_parm_s { gpg_error_t lasterr; /* Last error code. */ membuf_t saveddata; /* Buffer to build complete lines. */ char *helpbuf; /* NULL or malloced buffer. */ size_t helpbufsize; /* Allocated size of HELPBUF. */ gpg_error_t (*data_cb)(void*, int, char*); /* Callback. */ void *data_cb_value; /* First argument for DATA_CB. */ struct ks_status_parm_s *stparm; /* Link to the status parameter. */ }; /* Parameter structure used with the KS_GET command. */ struct ks_get_parm_s { estream_t memfp; }; /* Parameter structure used with the KS_PUT command. */ struct ks_put_parm_s { assuan_context_t ctx; kbnode_t keyblock; /* The optional keyblock. */ const void *data; /* The key in OpenPGP binary format. */ size_t datalen; /* The length of DATA. */ }; /* Parameter structure used with the DNS_CERT command. */ struct dns_cert_parm_s { estream_t memfp; unsigned char *fpr; size_t fprlen; char *url; }; /* Data used to associate an session with dirmngr contexts. We can't use a simple one to one mapping because we sometimes need two connections to the dirmngr; for example while doing a listing and being in a data callback we may want to retrieve a key. The local dirmngr data takes care of this. At the end of the session the function dirmngr_deinit_session_data is called by gpg.c to cleanup these resources. Note that gpg.h defines a typedef dirmngr_local_t for this structure. */ struct dirmngr_local_s { /* Link to other contexts which are used simultaneously. */ struct dirmngr_local_s *next; /* The active Assuan context. */ assuan_context_t ctx; /* Flag set when the keyserver names have been send. */ int set_keyservers_done; /* Flag set to true while an operation is running on CTX. */ int is_active; }; /* Deinitialize all session data of dirmngr pertaining to CTRL. */ void gpg_dirmngr_deinit_session_data (ctrl_t ctrl) { dirmngr_local_t dml; while ((dml = ctrl->dirmngr_local)) { ctrl->dirmngr_local = dml->next; if (dml->is_active) log_error ("oops: trying to cleanup an active dirmngr context\n"); else assuan_release (dml->ctx); xfree (dml); } } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, 0, &serverversion); - if (err) - log_error (_("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - - write_status_strings (STATUS_WARNING, "server_version_mismatch 0", - " ", warn, NULL); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, 0, + write_status_strings2, NULL, + !opt.quiet); } /* Try to connect to the Dirmngr via a socket or spawn it if possible. Handle the server's initial greeting and set global options. */ static gpg_error_t create_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; assuan_context_t ctx; *r_ctx = NULL; if (opt.disable_dirmngr) return gpg_error (GPG_ERR_NO_DIRMNGR); err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, opt.verbose, DBG_IPC, NULL /*gpg_status2*/, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR) { static int shown; if (!shown) { shown = 1; log_info (_("no dirmngr running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (ctx, DIRMNGR_NAME))) { char *line; /* Tell the dirmngr that we want to collect audit event. */ /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */ /* NULL, NULL, NULL, NULL, NULL, NULL); */ if (opt.keyserver_options.http_proxy) { line = xtryasprintf ("OPTION http-proxy=%s", opt.keyserver_options.http_proxy); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } } if (err) ; else if ((opt.keyserver_options.options & KEYSERVER_HONOR_KEYSERVER_URL)) { /* Tell the dirmngr that this possibly privacy invading option is in use. If Dirmngr is running in Tor mode, it will return an error. */ err = assuan_transact (ctx, "OPTION honor-keyserver-url-used", NULL, NULL, NULL, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_FORBIDDEN) log_error (_("keyserver option \"honor-keyserver-url\"" " may not be used in Tor mode\n")); else if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Old dirmngr versions do not support this option. */ } } if (err) assuan_release (ctx); else { /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */ *r_ctx = ctx; } return err; } /* Get a context for accessing dirmngr. If no context is available a new one is created and - if required - dirmngr started. On success an assuan context is stored at R_CTX. This context may only be released by means of close_context. Note that NULL is stored at R_CTX on error. */ static gpg_error_t open_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; dirmngr_local_t dml; *r_ctx = NULL; for (;;) { for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next) ; if (dml) { /* Found an inactive local session - return that. */ log_assert (!dml->is_active); /* But first do the per session init if not yet done. */ if (!dml->set_keyservers_done) { keyserver_spec_t ksi; /* Set all configured keyservers. We clear existing keyservers so that any keyserver configured in GPG overrides keyservers possibly still configured in Dirmngr for the session (Note that the keyserver list of a session in Dirmngr survives a RESET. */ for (ksi = opt.keyserver; ksi; ksi = ksi->next) { char *line; line = xtryasprintf ("KEYSERVER%s %s", ksi == opt.keyserver? " --clear":"", ksi->uri); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (dml->ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } if (err) return err; } dml->set_keyservers_done = 1; } dml->is_active = 1; *r_ctx = dml->ctx; return 0; } dml = xtrycalloc (1, sizeof *dml); if (!dml) return gpg_error_from_syserror (); err = create_context (ctrl, &dml->ctx); if (err) { xfree (dml); return err; } /* To be on the nPth thread safe site we need to add it to a list; this is far easier than to have a lock for this function. It should not happen anyway but the code is free because we need it for the is_active check above. */ dml->next = ctrl->dirmngr_local; ctrl->dirmngr_local = dml; } } /* Close the assuan context CTX or return it to a pool of unused contexts. If CTX is NULL, the function does nothing. */ static void close_context (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("closing inactive dirmngr context %p\n", ctx); dml->is_active = 0; return; } } log_fatal ("closing unknown dirmngr ctx %p\n", ctx); } /* Clear the set_keyservers_done flag on context CTX. */ static void clear_context_flags (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("clear_context_flags on inactive dirmngr ctx %p\n", ctx); dml->set_keyservers_done = 0; return; } } log_fatal ("clear_context_flags on unknown dirmngr ctx %p\n", ctx); } /* Status callback for ks_list, ks_get, ks_search, and wkd_get */ static gpg_error_t ks_status_cb (void *opaque, const char *line) { struct ks_status_parm_s *parm = opaque; gpg_error_t err = 0; const char *s, *s2; const char *warn = NULL; int is_note = 0; if ((s = has_leading_keyword (line, parm->keyword? parm->keyword : "SOURCE"))) { /* Note that the arg for "S SOURCE" is the URL of a keyserver. */ if (!parm->source) { parm->source = xtrystrdup (s); if (!parm->source) err = gpg_error_from_syserror (); } } else if ((s = has_leading_keyword (line, "WARNING")) || (is_note = !!(s = has_leading_keyword (line, "NOTE")))) { if ((s2 = has_leading_keyword (s, "wkd_cached_result"))) { if (opt.verbose) warn = _("WKD uses a cached result"); } else if ((s2 = has_leading_keyword (s, "tor_not_running"))) warn = _("Tor is not running"); else if ((s2 = has_leading_keyword (s, "tor_config_problem"))) warn = _("Tor is not properly configured"); else if ((s2 = has_leading_keyword (s, "dns_config_problem"))) warn = _("DNS is not properly configured"); else if ((s2 = has_leading_keyword (s, "http_redirect"))) warn = _("unacceptable HTTP redirect from server"); else if ((s2 = has_leading_keyword (s, "http_redirect_cleanup"))) warn = _("unacceptable HTTP redirect from server was cleaned up"); else if ((s2 = has_leading_keyword (s, "tls_cert_error"))) warn = _("server uses an invalid certificate"); else warn = NULL; if (warn) { if (is_note) log_info (_("Note: %s\n"), warn); else log_info (_("WARNING: %s\n"), warn); if (s2) { while (*s2 && !spacep (s2)) s2++; while (*s2 && spacep (s2)) s2++; if (*s2) print_further_info ("%s", s2); } } } return err; } /* Run the "KEYSERVER" command to return the name of the used keyserver at R_KEYSERVER. */ gpg_error_t gpg_dirmngr_ks_list (ctrl_t ctrl, char **r_keyserver) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; memset (&stparm, 0, sizeof stparm); stparm.keyword = "KEYSERVER"; if (r_keyserver) *r_keyserver = NULL; err = open_context (ctrl, &ctx); if (err) return err; err = assuan_transact (ctx, "KEYSERVER", NULL, NULL, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; if (!stparm.source) { err = gpg_error (GPG_ERR_NO_KEYSERVER); goto leave; } if (r_keyserver) *r_keyserver = stparm.source; else xfree (stparm.source); stparm.source = NULL; leave: xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_SEARCH command. */ static gpg_error_t ks_search_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_search_parm_s *parm = opaque; const char *line, *s; size_t rawlen, linelen; char fixedbuf[256]; if (parm->lasterr) return 0; if (parm->stparm->source) { err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source); if (err) { parm->lasterr = err; return err; } /* Clear it so that we won't get back here unless the server accidentally sends a second source status line. Note that will not see all accidentally sent source lines because it depends on whether data lines have been send in between. */ xfree (parm->stparm->source); parm->stparm->source = NULL; } if (!data) return 0; /* Ignore END commands. */ put_membuf (&parm->saveddata, data, datalen); again: line = peek_membuf (&parm->saveddata, &rawlen); if (!line) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; /* Tell the server about our problem. */ } if ((s = memchr (line, '\n', rawlen))) { linelen = s - line; /* That is the length excluding the LF. */ if (linelen + 1 < sizeof fixedbuf) { /* We can use the static buffer. */ memcpy (fixedbuf, line, linelen); fixedbuf[linelen] = 0; if (linelen && fixedbuf[linelen-1] == '\r') fixedbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, fixedbuf); } else { if (linelen + 1 >= parm->helpbufsize) { xfree (parm->helpbuf); parm->helpbufsize = linelen + 1 + 1024; parm->helpbuf = xtrymalloc (parm->helpbufsize); if (!parm->helpbuf) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; } } memcpy (parm->helpbuf, line, linelen); parm->helpbuf[linelen] = 0; if (linelen && parm->helpbuf[linelen-1] == '\r') parm->helpbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf); } if (err) parm->lasterr = err; else { clear_membuf (&parm->saveddata, linelen+1); goto again; /* There might be another complete line. */ } } return err; } /* Run the KS_SEARCH command using the search string SEARCHSTR. All data lines are passed to the CB function. That function is called with CB_VALUE as its first argument, a 0 as second argument, and the decoded data line as third argument. The callback function may modify the data line and it is guaranteed that this data line is a complete line with a terminating 0 character but without the linefeed. NULL is passed to the callback to indicate EOF. */ gpg_error_t gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr, gpg_error_t (*cb)(void*, int, char *), void *cb_value) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_search_parm_s parm; char line[ASSUAN_LINELENGTH]; err = open_context (ctrl, &ctx); if (err) return err; { char *escsearchstr = percent_plus_escape (searchstr); if (!escsearchstr) { err = gpg_error_from_syserror (); close_context (ctrl, ctx); return err; } snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr); xfree (escsearchstr); } memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); init_membuf (&parm.saveddata, 1024); parm.data_cb = cb; parm.data_cb_value = cb_value; parm.stparm = &stparm; err = assuan_transact (ctx, line, ks_search_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (!err) err = cb (cb_value, 0, NULL); /* Send EOF. */ else if (parm.stparm->source) { /* Error but we received a SOURCE status. Tell via callback but * ignore errors. */ parm.data_cb (parm.data_cb_value, 1, parm.stparm->source); } xfree (get_membuf (&parm.saveddata, NULL)); xfree (parm.helpbuf); xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_GET and KS_FETCH commands. */ static gpg_error_t ks_get_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_get_parm_s *parm = opaque; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Run the KS_GET command using the patterns in the array PATTERN. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The pattern may only use search specification which a keyserver can use to retrieve keys. Because we know the format of the pattern we don't need to escape the patterns before sending them to the server. If QUICK is set the dirmngr is advised to use a shorter timeout. If R_SOURCE is not NULL the source of the data is stored as a malloced string there. If a source is not known NULL is stored. Note that this may even be returned after an error. If there are too many patterns the function returns an error. That could be fixed by issuing several search commands or by implementing a different interface. However with long keyids we are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once. */ gpg_error_t gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern, keyserver_spec_t override_keyserver, int quick, estream_t *r_fp, char **r_source) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_get_parm_s parm; char *line = NULL; size_t linelen; membuf_t mb; int idx; memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); *r_fp = NULL; if (r_source) *r_source = NULL; err = open_context (ctrl, &ctx); if (err) return err; /* If we have an override keyserver we first indicate that the next user of the context needs to again setup the global keyservers and them we send the override keyserver. */ if (override_keyserver) { clear_context_flags (ctrl, ctx); line = xtryasprintf ("KEYSERVER --clear %s", override_keyserver->uri); if (!line) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) goto leave; xfree (line); line = NULL; } /* Lump all patterns into one string. */ init_membuf (&mb, 1024); put_membuf_str (&mb, quick? "KS_GET --quick --" : "KS_GET --"); for (idx=0; pattern[idx]; idx++) { put_membuf (&mb, " ", 1); /* Append Delimiter. */ put_membuf_str (&mb, pattern[idx]); } put_membuf (&mb, "", 1); /* Append Nul. */ line = get_membuf (&mb, &linelen); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (linelen + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_MANY); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: if (r_source && stparm.source) { *r_source = stparm.source; stparm.source = NULL; } es_fclose (parm.memfp); xfree (stparm.source); xfree (line); close_context (ctrl, ctx); return err; } /* Run the KS_FETCH and pass URL as argument. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The url is expected to point to a small set of keys; in many cases only to one key. However, schemes like finger may return several keys. Note that the configured keyservers are ignored by the KS_FETCH command. */ gpg_error_t gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp) { gpg_error_t err; assuan_context_t ctx; struct ks_get_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); *r_fp = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = strconcat ("KS_FETCH -- ", url, NULL); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, NULL, NULL); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } static void record_output (estream_t output, pkttype_t type, const char *validity, /* The public key length or -1. */ int pub_key_length, /* The public key algo or -1. */ int pub_key_algo, /* 2 ulongs or NULL. */ const u32 *keyid, /* The creation / expiration date or 0. */ u32 creation_date, u32 expiration_date, const char *userid) { const char *type_str = NULL; char *pub_key_length_str = NULL; char *pub_key_algo_str = NULL; char *keyid_str = NULL; char *creation_date_str = NULL; char *expiration_date_str = NULL; char *userid_escaped = NULL; switch (type) { case PKT_PUBLIC_KEY: type_str = "pub"; break; case PKT_PUBLIC_SUBKEY: type_str = "sub"; break; case PKT_USER_ID: type_str = "uid"; break; case PKT_SIGNATURE: type_str = "sig"; break; default: log_assert (! "Unhandled type."); } if (pub_key_length > 0) pub_key_length_str = xasprintf ("%d", pub_key_length); if (pub_key_algo != -1) pub_key_algo_str = xasprintf ("%d", pub_key_algo); if (keyid) keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]); if (creation_date) creation_date_str = xstrdup (colon_strtime (creation_date)); if (expiration_date) expiration_date_str = xstrdup (colon_strtime (expiration_date)); /* Quote ':', '%', and any 8-bit characters. */ if (userid) { int r; int w = 0; int len = strlen (userid); /* A 100k character limit on the uid should be way more than enough. */ if (len > 100 * 1024) len = 100 * 1024; /* The minimum amount of space that we need. */ userid_escaped = xmalloc (len * 3 + 1); for (r = 0; r < len; r++) { if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80)) { sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]); w += 3; } else userid_escaped[w ++] = userid[r]; } userid_escaped[w] = '\0'; } es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", type_str, validity ?: "", pub_key_length_str ?: "", pub_key_algo_str ?: "", keyid_str ?: "", creation_date_str ?: "", expiration_date_str ?: "", "" /* Certificate S/N */, "" /* Ownertrust. */, userid_escaped ?: "", "" /* Signature class. */, "" /* Key capabilities. */, "" /* Issuer certificate fingerprint. */, "" /* Flag field. */, "" /* S/N of a token. */, "" /* Hash algo. */, "" /* Curve name. */); xfree (userid_escaped); xfree (expiration_date_str); xfree (creation_date_str); xfree (keyid_str); xfree (pub_key_algo_str); xfree (pub_key_length_str); } /* Handle the KS_PUT inquiries. */ static gpg_error_t ks_put_inq_cb (void *opaque, const char *line) { struct ks_put_parm_s *parm = opaque; gpg_error_t err = 0; if (has_leading_keyword (line, "KEYBLOCK")) { if (parm->data) err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else if (has_leading_keyword (line, "KEYBLOCK_INFO")) { kbnode_t node; estream_t fp; /* Parse the keyblock and send info lines back to the server. */ fp = es_fopenmem (0, "rw,samethread"); if (!fp) err = gpg_error_from_syserror (); /* Note: the output format for the INFO block follows the colon format as described in doc/DETAILS. We don't actually reuse the functionality from g10/keylist.c to produce the output, because we don't need all of it and some of it is quite expensive to generate. The fields are (the starred fields are the ones we need): * Field 1 - Type of record * Field 2 - Validity * Field 3 - Key length * Field 4 - Public key algorithm * Field 5 - KeyID * Field 6 - Creation date * Field 7 - Expiration date Field 8 - Certificate S/N, UID hash, trust signature info Field 9 - Ownertrust * Field 10 - User-ID Field 11 - Signature class Field 12 - Key capabilities Field 13 - Issuer certificate fingerprint or other info Field 14 - Flag field Field 15 - S/N of a token Field 16 - Hash algorithm Field 17 - Curve name */ for (node = parm->keyblock; !err && node; node=node->next) { switch (node->pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: { PKT_public_key *pk = node->pkt->pkt.public_key; char validity[3]; int i; i = 0; if (pk->flags.revoked) validity[i ++] = 'r'; if (pk->has_expired) validity[i ++] = 'e'; validity[i] = '\0'; keyid_from_pk (pk, NULL); record_output (fp, node->pkt->pkttype, validity, nbits_from_pk (pk), pk->pubkey_algo, pk->keyid, pk->timestamp, pk->expiredate, NULL); } break; case PKT_USER_ID: { PKT_user_id *uid = node->pkt->pkt.user_id; if (!uid->attrib_data) { char validity[3]; int i; i = 0; if (uid->flags.revoked) validity[i ++] = 'r'; if (uid->flags.expired) validity[i ++] = 'e'; validity[i] = '\0'; record_output (fp, node->pkt->pkttype, validity, -1, -1, NULL, uid->created, uid->expiredate, uid->name); } } break; /* This bit is really for the benefit of people who store their keys in LDAP servers. It makes it easy to do queries for things like "all keys signed by Isabella". */ case PKT_SIGNATURE: { PKT_signature *sig = node->pkt->pkt.signature; if (IS_UID_SIG (sig)) record_output (fp, node->pkt->pkttype, NULL, -1, -1, sig->keyid, sig->timestamp, sig->expiredate, NULL); } break; default: continue; } /* Given that the last operation was an es_fprintf we should get the correct ERRNO if ferror indicates an error. */ if (es_ferror (fp)) err = gpg_error_from_syserror (); } /* Without an error and if we have an keyblock at all, send the data back. */ if (!err && parm->keyblock) { int rc; char buffer[512]; size_t nread; es_rewind (fp); while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread) { err = assuan_send_data (parm->ctx, buffer, nread); if (err) break; } if (!err && rc) err = gpg_error_from_syserror (); } es_fclose (fp); } else return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); return err; } /* Send a key to the configured server. {DATA,DATLEN} contains the key in OpenPGP binary transport format. If KEYBLOCK is not NULL it has the internal representation of that key; this is for example used to convey meta data to LDAP keyservers. */ gpg_error_t gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock) { gpg_error_t err; assuan_context_t ctx; struct ks_put_parm_s parm; memset (&parm, 0, sizeof parm); /* We are going to parse the keyblock, thus we better make sure the all information is readily available. */ if (keyblock) merge_keys_and_selfsig (ctrl, keyblock); err = open_context (ctrl, &ctx); if (err) return err; parm.ctx = ctx; parm.keyblock = keyblock; parm.data = data; parm.datalen = datalen; err = assuan_transact (ctx, "KS_PUT", NULL, NULL, ks_put_inq_cb, &parm, NULL, NULL); close_context (ctrl, ctx); return err; } /* Data callback for the DNS_CERT and WKD_GET commands. */ static gpg_error_t dns_cert_data_cb (void *opaque, const void *data, size_t datalen) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (!parm->memfp) return 0; /* Data is not required. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Status callback for the DNS_CERT command. */ static gpg_error_t dns_cert_status_cb (void *opaque, const char *line) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; const char *s; size_t nbytes; if ((s = has_leading_keyword (line, "FPR"))) { char *buf; if (!(buf = xtrystrdup (s))) err = gpg_error_from_syserror (); else if (parm->fpr) err = gpg_error (GPG_ERR_DUP_KEY); else if (!hex2str (buf, buf, strlen (buf)+1, &nbytes)) err = gpg_error_from_syserror (); else if (nbytes < 20) err = gpg_error (GPG_ERR_TOO_SHORT); else { parm->fpr = xtrymalloc (nbytes); if (!parm->fpr) err = gpg_error_from_syserror (); else memcpy (parm->fpr, buf, (parm->fprlen = nbytes)); } xfree (buf); } else if ((s = has_leading_keyword (line, "URL")) && *s) { if (parm->url) err = gpg_error (GPG_ERR_DUP_KEY); else if (!(parm->url = xtrystrdup (s))) err = gpg_error_from_syserror (); } return err; } /* Ask the dirmngr for a DNS CERT record. Depending on the found subtypes different return values are set: - For a PGP subtype a new estream with that key will be returned at R_KEY and the other return parameters are set to NULL/0. - For an IPGP subtype the fingerprint is stored as a malloced block at (R_FPR,R_FPRLEN). If an URL is available it is stored as a malloced string at R_URL; NULL is stored if there is no URL. If CERTTYPE is DNS_CERTTYPE_ANY this function returns the first CERT record found with a supported type; it is expected that only one CERT record is used. If CERTTYPE is one of the supported certtypes, only records with this certtype are considered and the first one found is returned. All R_* args are optional. If CERTTYPE is NULL the DANE method is used to fetch the key. */ gpg_error_t gpg_dirmngr_dns_cert (ctrl_t ctrl, const char *name, const char *certtype, estream_t *r_key, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct dns_cert_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); if (r_key) *r_key = NULL; if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("DNS_CERT %s %s", certtype? certtype : "--dane", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, dns_cert_status_cb, &parm); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_fpr && parm.fpr) { *r_fpr = parm.fpr; parm.fpr = NULL; } if (r_fprlen) *r_fprlen = parm.fprlen; if (r_url && parm.url) { *r_url = parm.url; parm.url = NULL; } leave: xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } /* Ask the dirmngr for PKA info. On success the retrieved fingerprint is returned in a malloced buffer at R_FPR and its length is stored at R_FPRLEN. If an URL is available it is stored as a malloced string at R_URL. On error all return values are set to NULL/0. */ gpg_error_t gpg_dirmngr_get_pka (ctrl_t ctrl, const char *userid, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct dns_cert_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("DNS_CERT --pka -- %s", userid); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, dns_cert_status_cb, &parm); if (err) goto leave; if (r_fpr && parm.fpr) { *r_fpr = parm.fpr; parm.fpr = NULL; } if (r_fprlen) *r_fprlen = parm.fprlen; if (r_url && parm.url) { *r_url = parm.url; parm.url = NULL; } leave: xfree (parm.fpr); xfree (parm.url); xfree (line); close_context (ctrl, ctx); return err; } /* Ask the dirmngr to retrieve a key via the Web Key Directory * protocol. If QUICK is set the dirmngr is advised to use a shorter * timeout. On success a new estream with the key stored at R_KEY and the * url of the lookup (if any) stored at R_URL. Note that */ gpg_error_t gpg_dirmngr_wkd_get (ctrl_t ctrl, const char *name, int quick, estream_t *r_key, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm = { NULL }; struct dns_cert_parm_s parm = { NULL }; char *line = NULL; if (r_key) *r_key = NULL; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("WKD_GET%s -- %s", quick?" --quick":"", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (MAX_WKD_RESULT_LENGTH, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (gpg_err_code (err) == GPG_ERR_ENOSPC) err = gpg_error (GPG_ERR_TOO_LARGE); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_url) { *r_url = stparm.source; stparm.source = NULL; } leave: xfree (stparm.source); xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } diff --git a/g10/call-keyboxd.c b/g10/call-keyboxd.c index 181f33fed..e09fa20e3 100644 --- a/g10/call-keyboxd.c +++ b/g10/call-keyboxd.c @@ -1,1234 +1,1203 @@ /* call-keyboxd.c - Access to the keyboxd storage server * Copyright (C) 2019 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #include #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/host2net.h" #include "../common/exechelp.h" #include "../common/status.h" #include "keydb.h" #include "keydb-private.h" /* For struct keydb_handle_s */ /* Data used to keep track of keybox daemon sessions. This allows us * to use several sessions with the keyboxd and also to re-use already * established sessions. Note that gpg.h defines the type * keyboxd_local_t for this structure. */ struct keyboxd_local_s { /* Link to other keyboxd contexts which are used simultaneously. */ struct keyboxd_local_s *next; /* The active Assuan context. */ assuan_context_t ctx; /* This object is used if fd-passing is used to convey the * keyblocks. */ struct { /* NULL or a stream used to receive data. */ estream_t fp; /* Condition variable to sync the datastream with the command. */ npth_mutex_t mutex; npth_cond_t cond; /* The found keyblock or the parsing error. */ kbnode_t found_keyblock; gpg_error_t found_err; } datastream; /* I/O buffer with the last search result or NULL. Used if * D-lines are used to convey the keyblocks. */ iobuf_t search_result; /* This flag set while an operation is running on this context. */ unsigned int is_active : 1; /* This flag is set to record that the standard per session init has * been done. */ unsigned int per_session_init_done : 1; /* Flag indicating that a search reset is required. */ unsigned int need_search_reset : 1; }; /* Local prototypes. */ static void *datastream_thread (void *arg); static void lock_datastream (keyboxd_local_t kbl) { int rc = npth_mutex_lock (&kbl->datastream.mutex); if (rc) log_fatal ("%s: failed to acquire mutex: %s\n", __func__, gpg_strerror (gpg_error_from_errno (rc))); } static void unlock_datastream (keyboxd_local_t kbl) { int rc = npth_mutex_unlock (&kbl->datastream.mutex); if (rc) log_fatal ("%s: failed to release mutex: %s\n", __func__, gpg_strerror (gpg_error_from_errno (rc))); } /* Deinitialize all session resources pertaining to the keyboxd. */ void gpg_keyboxd_deinit_session_data (ctrl_t ctrl) { keyboxd_local_t kbl; while ((kbl = ctrl->keyboxd_local)) { ctrl->keyboxd_local = kbl->next; if (kbl->is_active) log_error ("oops: trying to cleanup an active keyboxd context\n"); else { es_fclose (kbl->datastream.fp); kbl->datastream.fp = NULL; assuan_release (kbl->ctx); kbl->ctx = NULL; } xfree (kbl); } } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, 0, &serverversion); - if (err) - log_error (_("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - - write_status_strings (STATUS_WARNING, "server_version_mismatch 0", - " ", warn, NULL); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, 0, + write_status_strings2, NULL, + !opt.quiet); } /* Connect to the keybox daemon and launch it if necessary. Handle * the server's initial greeting and set global options. Returns a * new assuan context or an error. */ static gpg_error_t create_new_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; assuan_context_t ctx; *r_ctx = NULL; err = start_new_keyboxd (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.keyboxd_program, opt.autostart, opt.verbose, DBG_IPC, NULL, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_KEYBOXD) { static int shown; if (!shown) { shown = 1; log_info (_("no keyboxd running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (ctx, KEYBOXD_NAME))) { /* Place to emit global options. */ } if (err) assuan_release (ctx); else *r_ctx = ctx; return err; } /* Setup the pipe used for receiving data from the keyboxd. Store the * info on KBL. */ static gpg_error_t prepare_data_pipe (keyboxd_local_t kbl) { gpg_error_t err; int rc; int inpipe[2]; estream_t infp; npth_t thread; npth_attr_t tattr; err = gnupg_create_inbound_pipe (inpipe, &infp, 0); if (err) { log_error ("error creating inbound pipe: %s\n", gpg_strerror (err)); return err; /* That should not happen. */ } err = assuan_sendfd (kbl->ctx, INT2FD (inpipe[1])); if (err) { log_error ("sending sending fd %d to keyboxd: %s <%s>\n", inpipe[1], gpg_strerror (err), gpg_strsource (err)); es_fclose (infp); close (inpipe[1]); return 0; /* Server may not support fd-passing. */ } err = assuan_transact (kbl->ctx, "OUTPUT FD", NULL, NULL, NULL, NULL, NULL, NULL); if (err) { log_info ("keyboxd does not accept our fd: %s <%s>\n", gpg_strerror (err), gpg_strsource (err)); es_fclose (infp); return 0; } kbl->datastream.fp = infp; kbl->datastream.found_keyblock = NULL; kbl->datastream.found_err = 0; rc = npth_attr_init (&tattr); if (rc) { err = gpg_error_from_errno (rc); log_error ("error preparing thread for keyboxd: %s\n",gpg_strerror (err)); es_fclose (infp); kbl->datastream.fp = NULL; return err; } npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); rc = npth_create (&thread, &tattr, datastream_thread, kbl); if (rc) { err = gpg_error_from_errno (rc); log_error ("error spawning thread for keyboxd: %s\n", gpg_strerror (err)); npth_attr_destroy (&tattr); es_fclose (infp); kbl->datastream.fp = NULL; return err; } return 0; } /* Get a context for accessing keyboxd. If no context is available a * new one is created and if necessary keyboxd is started. R_KBL * receives a pointer to the local context object. */ static gpg_error_t open_context (ctrl_t ctrl, keyboxd_local_t *r_kbl) { gpg_error_t err; int rc; keyboxd_local_t kbl; *r_kbl = NULL; for (;;) { for (kbl = ctrl->keyboxd_local; kbl && kbl->is_active; kbl = kbl->next) ; if (kbl) { /* Found an inactive keyboxd session - return that. */ log_assert (!kbl->is_active); /* But first do the per session init if not yet done. */ if (!kbl->per_session_init_done) { err = prepare_data_pipe (kbl); if (err) return err; kbl->per_session_init_done = 1; } kbl->is_active = 1; kbl->need_search_reset = 1; *r_kbl = kbl; return 0; } /* None found. Create a new session and retry. */ kbl = xtrycalloc (1, sizeof *kbl); if (!kbl) return gpg_error_from_syserror (); rc = npth_mutex_init (&kbl->datastream.mutex, NULL); if (rc) { err = gpg_error_from_errno (rc); log_error ("error initializing mutex: %s\n", gpg_strerror (err)); xfree (kbl); return err; } rc = npth_cond_init (&kbl->datastream.cond, NULL); if (rc) { err = gpg_error_from_errno (rc); log_error ("error initializing condition: %s\n", gpg_strerror (err)); npth_mutex_destroy (&kbl->datastream.mutex); xfree (kbl); return err; } err = create_new_context (ctrl, &kbl->ctx); if (err) { npth_cond_destroy (&kbl->datastream.cond); npth_mutex_destroy (&kbl->datastream.mutex); xfree (kbl); return err; } /* For thread-saftey we add it to the list and retry; this is * easier than to employ a lock. */ kbl->next = ctrl->keyboxd_local; ctrl->keyboxd_local = kbl; } /*NOTREACHED*/ } /* Create a new database handle. A database handle is similar to a * file handle: it contains a local file position. This is used when * searching: subsequent searches resume where the previous search * left off. To rewind the position, use keydb_search_reset(). This * function returns NULL on error, sets ERRNO, and prints an error * diagnostic. Depending on --use-keyboxd either the old internal * keydb code is used (keydb.c) or, if set, the processing is diverted * to the keyboxd. */ /* FIXME: We should change the interface to return a gpg_error_t. */ KEYDB_HANDLE keydb_new (ctrl_t ctrl) { gpg_error_t err; KEYDB_HANDLE hd; if (DBG_CLOCK) log_clock ("keydb_new"); hd = xtrycalloc (1, sizeof *hd); if (!hd) { err = gpg_error_from_syserror (); goto leave; } if (!opt.use_keyboxd) { err = internal_keydb_init (hd); goto leave; } hd->use_keyboxd = 1; hd->ctrl = ctrl; err = open_context (ctrl, &hd->kbl); leave: if (err) { int rc; log_error (_("error opening key DB: %s\n"), gpg_strerror (err)); xfree (hd); hd = NULL; if (!(rc = gpg_err_code_to_errno (err))) rc = gpg_err_code_to_errno (GPG_ERR_EIO); gpg_err_set_errno (rc); } return hd; } /* Release a keydb handle. */ void keydb_release (KEYDB_HANDLE hd) { keyboxd_local_t kbl; if (!hd) return; if (DBG_CLOCK) log_clock ("keydb_release"); if (!hd->use_keyboxd) internal_keydb_deinit (hd); else { kbl = hd->kbl; if (DBG_CLOCK) log_clock ("close_context (found)"); if (!kbl->is_active) log_fatal ("closing inactive keyboxd context %p\n", kbl); kbl->is_active = 0; hd->kbl = NULL; hd->ctrl = NULL; } xfree (hd); } /* Take a lock if we are not using the keyboxd. */ gpg_error_t keydb_lock (KEYDB_HANDLE hd) { if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (!hd->use_keyboxd) return internal_keydb_lock (hd); return 0; } /* FIXME: This helper is duplicates code of partse_keyblock_image. */ static gpg_error_t keydb_get_keyblock_do_parse (iobuf_t iobuf, int pk_no, int uid_no, kbnode_t *r_keyblock) { gpg_error_t err; struct parse_packet_ctx_s parsectx; PACKET *pkt; kbnode_t keyblock = NULL; kbnode_t node, *tail; int in_cert, save_mode; int pk_count, uid_count; *r_keyblock = NULL; pkt = xtrymalloc (sizeof *pkt); if (!pkt) return gpg_error_from_syserror (); init_packet (pkt); init_parse_packet (&parsectx, iobuf); save_mode = set_packet_list_mode (0); in_cert = 0; tail = NULL; pk_count = uid_count = 0; while ((err = parse_packet (&parsectx, pkt)) != -1) { if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET) { free_packet (pkt, &parsectx); init_packet (pkt); continue; } if (err) { es_fflush (es_stdout); log_error ("parse_keyblock_image: read error: %s\n", gpg_strerror (err)); if (gpg_err_code (err) == GPG_ERR_INV_PACKET) { free_packet (pkt, &parsectx); init_packet (pkt); continue; } err = gpg_error (GPG_ERR_INV_KEYRING); break; } /* Filter allowed packets. */ switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: case PKT_USER_ID: case PKT_ATTRIBUTE: case PKT_SIGNATURE: case PKT_RING_TRUST: break; /* Allowed per RFC. */ default: log_info ("skipped packet of type %d in keybox\n", (int)pkt->pkttype); free_packet(pkt, &parsectx); init_packet(pkt); continue; } /* Other sanity checks. */ if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY) { log_error ("parse_keyblock_image: first packet in a keybox blob " "is not a public key packet\n"); err = gpg_error (GPG_ERR_INV_KEYRING); break; } if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY || pkt->pkttype == PKT_SECRET_KEY)) { log_error ("parse_keyblock_image: " "multiple keyblocks in a keybox blob\n"); err = gpg_error (GPG_ERR_INV_KEYRING); break; } in_cert = 1; node = new_kbnode (pkt); switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: if (++pk_count == pk_no) node->flag |= 1; break; case PKT_USER_ID: if (++uid_count == uid_no) node->flag |= 2; break; default: break; } if (!keyblock) keyblock = node; else *tail = node; tail = &node->next; pkt = xtrymalloc (sizeof *pkt); if (!pkt) { err = gpg_error_from_syserror (); break; } init_packet (pkt); } set_packet_list_mode (save_mode); if (err == -1 && keyblock) err = 0; /* Got the entire keyblock. */ if (err) release_kbnode (keyblock); else { *r_keyblock = keyblock; } free_packet (pkt, &parsectx); deinit_parse_packet (&parsectx); xfree (pkt); return err; } /* The thread used to read from the data stream. This is running as * long as the connection and its datastream exists. */ static void * datastream_thread (void *arg) { keyboxd_local_t kbl = arg; gpg_error_t err; int rc; unsigned char lenbuf[4]; size_t nread, datalen; iobuf_t iobuf; int pk_no, uid_no; kbnode_t keyblock, tmpkeyblock; log_debug ("Datastream_thread started\n"); while (kbl->datastream.fp) { /* log_debug ("Datastream_thread waiting ...\n"); */ if (es_read (kbl->datastream.fp, lenbuf, 4, &nread)) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_EAGAIN) continue; log_error ("error reading data length from keyboxd: %s\n", gpg_strerror (err)); gnupg_sleep (1); continue; } if (nread != 4) { err = gpg_error (GPG_ERR_EIO); log_error ("error reading data length from keyboxd: %s\n", "short read"); continue; } datalen = buf32_to_size_t (lenbuf); /* log_debug ("keyboxd announced %zu bytes\n", datalen); */ iobuf = iobuf_esopen (kbl->datastream.fp, "rb", 1, datalen); pk_no = uid_no = 0; /* FIXME: Get this from the keyboxd. */ err = keydb_get_keyblock_do_parse (iobuf, pk_no, uid_no, &keyblock); iobuf_close (iobuf); if (!err) { /* log_debug ("parsing datastream succeeded\n"); */ /* Thread-safe assignment to the result var: */ tmpkeyblock = kbl->datastream.found_keyblock; kbl->datastream.found_keyblock = keyblock; release_kbnode (tmpkeyblock); } else { /* log_debug ("parsing datastream failed: %s <%s>\n", */ /* gpg_strerror (err), gpg_strsource (err)); */ tmpkeyblock = kbl->datastream.found_keyblock; kbl->datastream.found_keyblock = NULL; kbl->datastream.found_err = err; release_kbnode (tmpkeyblock); } /* Tell the main thread. */ lock_datastream (kbl); rc = npth_cond_signal (&kbl->datastream.cond); if (rc) { err = gpg_error_from_errno (rc); log_error ("%s: signaling condition failed: %s\n", __func__, gpg_strerror (err)); } unlock_datastream (kbl); } log_debug ("Datastream_thread finished\n"); return NULL; } /* Return the keyblock last found by keydb_search() in *RET_KB. * * On success, the function returns 0 and the caller must free *RET_KB * using release_kbnode(). Otherwise, the function returns an error * code. * * The returned keyblock has the kbnode flag bit 0 set for the node * with the public key used to locate the keyblock or flag bit 1 set * for the user ID node. */ gpg_error_t keydb_get_keyblock (KEYDB_HANDLE hd, kbnode_t *ret_kb) { gpg_error_t err; int pk_no, uid_no; *ret_kb = NULL; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (DBG_CLOCK) log_clock ("%s enter", __func__); if (!hd->use_keyboxd) { err = internal_keydb_get_keyblock (hd, ret_kb); goto leave; } if (hd->kbl->search_result) { pk_no = uid_no = 0; /*FIXME: Get this from the keyboxd. */ err = keydb_get_keyblock_do_parse (hd->kbl->search_result, pk_no, uid_no, ret_kb); /* In contrast to the old code we close the iobuf here and thus * this function may be called only once to get a keyblock. */ iobuf_close (hd->kbl->search_result); hd->kbl->search_result = NULL; } else if (hd->kbl->datastream.found_keyblock) { *ret_kb = hd->kbl->datastream.found_keyblock; hd->kbl->datastream.found_keyblock = NULL; err = 0; } else { err = gpg_error (GPG_ERR_VALUE_NOT_FOUND); goto leave; } leave: if (DBG_CLOCK) log_clock ("%s leave%s", __func__, err? " (failed)":""); return err; } /* Communication object for STORE commands. */ struct store_parm_s { assuan_context_t ctx; const void *data; /* The key in OpenPGP binary format. */ size_t datalen; /* The length of DATA. */ }; /* Handle the inquiries from the STORE command. */ static gpg_error_t store_inq_cb (void *opaque, const char *line) { struct store_parm_s *parm = opaque; gpg_error_t err = 0; if (has_leading_keyword (line, "BLOB")) { if (parm->data) err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); return err; } /* Update the keyblock KB (i.e., extract the fingerprint and find the * corresponding keyblock in the keyring). * * This doesn't do anything if --dry-run was specified. * * Returns 0 on success. Otherwise, it returns an error code. Note: * if there isn't a keyblock in the keyring corresponding to KB, then * this function returns GPG_ERR_VALUE_NOT_FOUND. * * This function selects the matching record and modifies the current * file position to point to the record just after the selected entry. * Thus, if you do a subsequent search using HD, you should first do a * keydb_search_reset. Further, if the selected record is important, * you should use keydb_push_found_state and keydb_pop_found_state to * save and restore it. */ gpg_error_t keydb_update_keyblock (ctrl_t ctrl, KEYDB_HANDLE hd, kbnode_t kb) { gpg_error_t err; iobuf_t iobuf = NULL; struct store_parm_s parm = {NULL}; log_assert (kb); log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY); if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (!hd->use_keyboxd) { err = internal_keydb_update_keyblock (ctrl, hd, kb); goto leave; } if (opt.dry_run) { err = 0; goto leave; } err = build_keyblock_image (kb, &iobuf); if (err) goto leave; parm.ctx = hd->kbl->ctx; parm.data = iobuf_get_temp_buffer (iobuf); parm.datalen = iobuf_get_temp_length (iobuf); err = assuan_transact (hd->kbl->ctx, "STORE --update", NULL, NULL, store_inq_cb, &parm, NULL, NULL); leave: iobuf_close (iobuf); return err; } /* Insert a keyblock into one of the underlying keyrings or keyboxes. * * By default, the keyring / keybox from which the last search result * came is used. If there was no previous search result (or * keydb_search_reset was called), then the keyring / keybox where the * next search would start is used (i.e., the current file position). * In keyboxd mode the keyboxd decides where to store it. * * Note: this doesn't do anything if --dry-run was specified. * * Returns 0 on success. Otherwise, it returns an error code. */ gpg_error_t keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb) { gpg_error_t err; iobuf_t iobuf = NULL; struct store_parm_s parm = {NULL}; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (!hd->use_keyboxd) { err = internal_keydb_insert_keyblock (hd, kb); goto leave; } if (opt.dry_run) { err = 0; goto leave; } err = build_keyblock_image (kb, &iobuf); if (err) goto leave; parm.ctx = hd->kbl->ctx; parm.data = iobuf_get_temp_buffer (iobuf); parm.datalen = iobuf_get_temp_length (iobuf); err = assuan_transact (hd->kbl->ctx, "STORE --insert", NULL, NULL, store_inq_cb, &parm, NULL, NULL); leave: iobuf_close (iobuf); return err; } /* Delete the currently selected keyblock. If you haven't done a * search yet on this database handle (or called keydb_search_reset), * then this function returns an error. * * Returns 0 on success or an error code, if an error occurred. */ gpg_error_t keydb_delete_keyblock (KEYDB_HANDLE hd) { gpg_error_t err; unsigned char hexubid[UBID_LEN * 2 + 1]; char line[ASSUAN_LINELENGTH]; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (!hd->use_keyboxd) { err = internal_keydb_delete_keyblock (hd); goto leave; } if (opt.dry_run) { err = 0; goto leave; } if (!hd->last_ubid_valid) { err = gpg_error (GPG_ERR_VALUE_NOT_FOUND); goto leave; } bin2hex (hd->last_ubid, UBID_LEN, hexubid); snprintf (line, sizeof line, "DELETE %s", hexubid); err = assuan_transact (hd->kbl->ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); leave: return err; } /* Clears the current search result and resets the handle's position * so that the next search starts at the beginning of the database. * * Returns 0 on success and an error code if an error occurred. */ gpg_error_t keydb_search_reset (KEYDB_HANDLE hd) { gpg_error_t err; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (DBG_CLOCK) log_clock ("%s", __func__); if (DBG_CACHE) log_debug ("%s (hd=%p)", __func__, hd); if (!hd->use_keyboxd) { err = internal_keydb_search_reset (hd); goto leave; } /* All we need is to tell search that a reset is pending. Note that * keydb_new sets this flag as well. To comply with the * specification of keydb_delete_keyblock we also need to clear the * ubid flag so that after a reset a delete can't be performed. */ hd->kbl->need_search_reset = 1; hd->last_ubid_valid = 0; err = 0; leave: return err; } /* Status callback for SEARCH and NEXT operaions. */ static gpg_error_t search_status_cb (void *opaque, const char *line) { KEYDB_HANDLE hd = opaque; gpg_error_t err = 0; const char *s; if ((s = has_leading_keyword (line, "PUBKEY_INFO"))) { if (atoi (s) != PUBKEY_TYPE_OPGP) err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE); else { hd->last_ubid_valid = 0; while (*s && !spacep (s)) s++; if (hex2fixedbuf (s, hd->last_ubid, sizeof hd->last_ubid)) hd->last_ubid_valid = 1; else err = gpg_error (GPG_ERR_INV_VALUE); } } return err; } /* Search the database for keys matching the search description. If * the DB contains any legacy keys, these are silently ignored. * * DESC is an array of search terms with NDESC entries. The search * terms are or'd together. That is, the next entry in the DB that * matches any of the descriptions will be returned. * * Note: this function resumes searching where the last search left * off (i.e., at the current file position). If you want to search * from the start of the database, then you need to first call * keydb_search_reset(). * * If no key matches the search description, returns * GPG_ERR_NOT_FOUND. If there was a match, returns 0. If an error * occurred, returns an error code. * * The returned key is considered to be selected and the raw data can, * for instance, be returned by calling keydb_get_keyblock(). */ gpg_error_t keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc, size_t *descindex) { gpg_error_t err; int i; char line[ASSUAN_LINELENGTH]; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (descindex) *descindex = 0; /* Make sure it is always set on return. */ if (DBG_CLOCK) log_clock ("%s enter", __func__); if (DBG_LOOKUP) { log_debug ("%s: %zd search descriptions:\n", __func__, ndesc); for (i = 0; i < ndesc; i ++) { char *t = keydb_search_desc_dump (&desc[i]); log_debug ("%s %d: %s\n", __func__, i, t); xfree (t); } } if (!hd->use_keyboxd) { err = internal_keydb_search (hd, desc, ndesc, descindex); goto leave; } /* Clear the result objects. */ if (hd->kbl->search_result) { iobuf_close (hd->kbl->search_result); hd->kbl->search_result = NULL; } if (hd->kbl->datastream.found_keyblock) { release_kbnode (hd->kbl->datastream.found_keyblock); hd->kbl->datastream.found_keyblock = NULL; } /* Check whether this is a NEXT search. */ if (!hd->kbl->need_search_reset) { /* No reset requested thus continue the search. The keyboxd * keeps the context of the search and thus the NEXT operates on * the last search pattern. This is how we always used the * keydb.c functions. In theory we were able to modify the * search pattern between searches but that is not anymore * supported by keyboxd and a cursory check does not show that * we actually made used of that misfeature. */ snprintf (line, sizeof line, "NEXT"); goto do_search; } hd->kbl->need_search_reset = 0; if (!ndesc) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } /* FIXME: Implement --multi */ switch (desc->mode) { case KEYDB_SEARCH_MODE_EXACT: snprintf (line, sizeof line, "SEARCH =%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SUBSTR: snprintf (line, sizeof line, "SEARCH *%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAIL: snprintf (line, sizeof line, "SEARCH <%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAILSUB: snprintf (line, sizeof line, "SEARCH @%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAILEND: snprintf (line, sizeof line, "SEARCH .%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_WORDS: snprintf (line, sizeof line, "SEARCH +%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SHORT_KID: snprintf (line, sizeof line, "SEARCH 0x%08lX", (ulong)desc->u.kid[1]); break; case KEYDB_SEARCH_MODE_LONG_KID: snprintf (line, sizeof line, "SEARCH 0x%08lX%08lX", (ulong)desc->u.kid[0], (ulong)desc->u.kid[1]); break; case KEYDB_SEARCH_MODE_FPR: { unsigned char hexfpr[MAX_FINGERPRINT_LEN * 2 + 1]; log_assert (desc[0].fprlen <= MAX_FINGERPRINT_LEN); bin2hex (desc[0].u.fpr, desc[0].fprlen, hexfpr); snprintf (line, sizeof line, "SEARCH 0x%s", hexfpr); } break; case KEYDB_SEARCH_MODE_ISSUER: snprintf (line, sizeof line, "SEARCH #/%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_ISSUER_SN: case KEYDB_SEARCH_MODE_SN: snprintf (line, sizeof line, "SEARCH #%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SUBJECT: snprintf (line, sizeof line, "SEARCH /%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_KEYGRIP: { unsigned char hexgrip[KEYGRIP_LEN * 2 + 1]; bin2hex (desc[0].u.grip, KEYGRIP_LEN, hexgrip); snprintf (line, sizeof line, "SEARCH &%s", hexgrip); } break; case KEYDB_SEARCH_MODE_UBID: { unsigned char hexubid[UBID_LEN * 2 + 1]; bin2hex (desc[0].u.ubid, UBID_LEN, hexubid); snprintf (line, sizeof line, "SEARCH ^%s", hexubid); } break; case KEYDB_SEARCH_MODE_FIRST: snprintf (line, sizeof line, "SEARCH"); break; case KEYDB_SEARCH_MODE_NEXT: log_debug ("%s: mode next - we should not get to here!\n", __func__); snprintf (line, sizeof line, "NEXT"); break; default: err = gpg_error (GPG_ERR_INV_ARG); goto leave; } do_search: hd->last_ubid_valid = 0; if (hd->kbl->datastream.fp) { /* log_debug ("Sending command '%s'\n", line); */ err = assuan_transact (hd->kbl->ctx, line, NULL, NULL, NULL, NULL, search_status_cb, hd); if (err) { /* log_debug ("Finished command with error: %s\n", gpg_strerror (err)); */ /* Fixme: On unexpected errors we need a way to cancel the * data stream. Probably it will be best to close and * reopen it. */ } else { int rc; /* log_debug ("Finished command .. telling data stream\n"); */ lock_datastream (hd->kbl); if (!hd->kbl->datastream.found_keyblock) { /* log_debug ("%s: waiting on datastream_cond ...\n", __func__); */ rc = npth_cond_wait (&hd->kbl->datastream.cond, &hd->kbl->datastream.mutex); /* log_debug ("%s: waiting on datastream.cond done\n", __func__); */ if (rc) { err = gpg_error_from_errno (rc); log_error ("%s: waiting on condition failed: %s\n", __func__, gpg_strerror (err)); } } unlock_datastream (hd->kbl); } } else /* Slower D-line version if fd-passing was not successful. */ { membuf_t data; void *buffer; size_t len; init_membuf (&data, 8192); err = assuan_transact (hd->kbl->ctx, line, put_membuf_cb, &data, NULL, NULL, search_status_cb, hd); if (err) { xfree (get_membuf (&data, &len)); goto leave; } buffer = get_membuf (&data, &len); if (!buffer) { err = gpg_error_from_syserror (); goto leave; } hd->kbl->search_result = iobuf_temp_with_content (buffer, len); xfree (buffer); } /* if (hd->last_ubid_valid) */ /* log_printhex (hd->last_ubid, 20, "found UBID:"); */ leave: if (DBG_CLOCK) log_clock ("%s leave (%sfound)", __func__, err? "not ":""); return err; } diff --git a/g10/cpr.c b/g10/cpr.c index d502e8b52..5a39913c5 100644 --- a/g10/cpr.c +++ b/g10/cpr.c @@ -1,664 +1,708 @@ /* status.c - Status message and command-fd interface * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, * 2004, 2005, 2006, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #ifdef HAVE_SIGNAL_H # include #endif #include "gpg.h" #include "../common/util.h" #include "../common/status.h" #include "../common/ttyio.h" #include "options.h" #include "main.h" #include "../common/i18n.h" #define CONTROL_D ('D' - 'A' + 1) /* The stream to output the status information. Output is disabled if this is NULL. */ static estream_t statusfp; static void progress_cb (void *ctx, const char *what, int printchar, int current, int total) { char buf[50]; (void)ctx; if ( printchar == '\n' && !strcmp (what, "primegen") ) snprintf (buf, sizeof buf, "%.20s X 100 100", what ); else snprintf (buf, sizeof buf, "%.20s %c %d %d", what, printchar=='\n'?'X':printchar, current, total ); write_status_text (STATUS_PROGRESS, buf); } /* Return true if the status message NO may currently be issued. We need this to avoid synchronization problem while auto retrieving a key. There it may happen that a status NODATA is issued for a non available key and the user may falsely interpret this has a missing signature. */ static int status_currently_allowed (int no) { if (!glo_ctrl.in_auto_key_retrieve) return 1; /* Yes. */ /* We allow some statis anyway, so that import statistics are correct and to avoid problems if the retrieval subsystem will prompt the user. */ switch (no) { case STATUS_GET_BOOL: case STATUS_GET_LINE: case STATUS_GET_HIDDEN: case STATUS_GOT_IT: case STATUS_IMPORTED: case STATUS_IMPORT_OK: case STATUS_IMPORT_CHECK: case STATUS_IMPORT_RES: return 1; /* Yes. */ default: break; } return 0; /* No. */ } void set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (statusfp && statusfp != es_stdout && statusfp != es_stderr ) es_fclose (statusfp); statusfp = NULL; if (fd == -1) return; if (! gnupg_fd_valid (fd)) log_fatal ("status-fd is invalid: %s\n", strerror (errno)); if (fd == 1) statusfp = es_stdout; else if (fd == 2) statusfp = es_stderr; else statusfp = es_fdopen (fd, "w"); if (!statusfp) { log_fatal ("can't open fd %d for status output: %s\n", fd, strerror (errno)); } last_fd = fd; gcry_set_progress_handler (progress_cb, NULL); } int is_status_enabled () { return !!statusfp; } void write_status ( int no ) { write_status_text( no, NULL ); } /* Write a status line with code NO followed by the string TEXT and * directly followed by the remaining strings up to a NULL. Embedded * CR and LFs in the strings (but not in TEXT) are C-style escaped.*/ void write_status_strings (int no, const char *text, ...) { va_list arg_ptr; const char *s; if (!statusfp || !status_currently_allowed (no) ) return; /* Not enabled or allowed. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if ( text ) { es_putc ( ' ', statusfp); va_start (arg_ptr, text); s = text; do { for (; *s; s++) { if (*s == '\n') es_fputs ("\\n", statusfp); else if (*s == '\r') es_fputs ("\\r", statusfp); else es_fputc (*(const byte *)s, statusfp); } } while ((s = va_arg (arg_ptr, const char*))); va_end (arg_ptr); } es_putc ('\n', statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } +/* Write a status line with code NO followed by the remaining + * arguments which must be a list of strings terminated by a NULL. + * Embedded CR and LFs in the strings are C-style escaped. All + * strings are printed with a space as delimiter. */ +gpg_error_t +write_status_strings2 (ctrl_t dummy, int no, ...) +{ + va_list arg_ptr; + const char *s; + + (void)dummy; + + if (!statusfp || !status_currently_allowed (no) ) + return 0; /* Not enabled or allowed. */ + + va_start (arg_ptr, no); + + es_fputs ("[GNUPG:] ", statusfp); + es_fputs (get_status_string (no), statusfp); + while ((s = va_arg (arg_ptr, const char*))) + { + if (*s) + es_putc (' ', statusfp); + for (; *s; s++) + { + if (*s == '\n') + es_fputs ("\\n", statusfp); + else if (*s == '\r') + es_fputs ("\\r", statusfp); + else + es_fputc (*(const byte *)s, statusfp); + } + } + es_putc ('\n', statusfp); + + va_end (arg_ptr); + + if (es_fflush (statusfp) && opt.exit_on_status_write_error) + g10_exit (0); + + return 0; +} + + void write_status_text (int no, const char *text) { write_status_strings (no, text, NULL); } /* Write a status line with code NO followed by the output of the * printf style FORMAT. Embedded CR and LFs are C-style escaped. */ void write_status_printf (int no, const char *format, ...) { va_list arg_ptr; char *buf; if (!statusfp || !status_currently_allowed (no) ) return; /* Not enabled or allowed. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if (format) { es_putc ( ' ', statusfp); va_start (arg_ptr, format); buf = gpgrt_vbsprintf (format, arg_ptr); if (!buf) log_error ("error printing status line: %s\n", gpg_strerror (gpg_err_code_from_syserror ())); else { if (strpbrk (buf, "\r\n")) { const byte *s; for (s=buf; *s; s++) { if (*s == '\n') es_fputs ("\\n", statusfp); else if (*s == '\r') es_fputs ("\\r", statusfp); else es_fputc (*s, statusfp); } } else es_fputs (buf, statusfp); gpgrt_free (buf); } va_end (arg_ptr); } es_putc ('\n', statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Write an ERROR status line using a full gpg-error error value. */ void write_status_error (const char *where, gpg_error_t err) { if (!statusfp || !status_currently_allowed (STATUS_ERROR)) return; /* Not enabled or allowed. */ es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_ERROR), where, err); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Same as above but outputs the error code only. */ void write_status_errcode (const char *where, int errcode) { if (!statusfp || !status_currently_allowed (STATUS_ERROR)) return; /* Not enabled or allowed. */ es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_ERROR), where, gpg_err_code (errcode)); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Write a FAILURE status line. */ void write_status_failure (const char *where, gpg_error_t err) { static int any_failure_printed; if (!statusfp || !status_currently_allowed (STATUS_FAILURE)) return; /* Not enabled or allowed. */ if (any_failure_printed) return; any_failure_printed = 1; es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_FAILURE), where, err); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* * Write a status line with a buffer using %XX escapes. If WRAP is > * 0 wrap the line after this length. If STRING is not NULL it will * be prepended to the buffer, no escaping is done for string. * A wrap of -1 forces spaces not to be encoded as %20. */ void write_status_text_and_buffer (int no, const char *string, const char *buffer, size_t len, int wrap) { const char *s, *text; int esc, first; int lower_limit = ' '; size_t n, count, dowrap; if (!statusfp || !status_currently_allowed (no)) return; /* Not enabled or allowed. */ if (wrap == -1) { lower_limit--; wrap = 0; } text = get_status_string (no); count = dowrap = first = 1; do { if (dowrap) { es_fprintf (statusfp, "[GNUPG:] %s ", text); count = dowrap = 0; if (first && string) { es_fputs (string, statusfp); count += strlen (string); /* Make sure that there is a space after the string. */ if (*string && string[strlen (string)-1] != ' ') { es_putc (' ', statusfp); count++; } } first = 0; } for (esc=0, s=buffer, n=len; n && !esc; s++, n--) { if (*s == '%' || *(const byte*)s <= lower_limit || *(const byte*)s == 127 ) esc = 1; if (wrap && ++count > wrap) { dowrap=1; break; } } if (esc) { s--; n++; } if (s != buffer) es_fwrite (buffer, s-buffer, 1, statusfp); if ( esc ) { es_fprintf (statusfp, "%%%02X", *(const byte*)s ); s++; n--; } buffer = s; len = n; if (dowrap && len) es_putc ('\n', statusfp); } while (len); es_putc ('\n',statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } void write_status_buffer (int no, const char *buffer, size_t len, int wrap) { write_status_text_and_buffer (no, NULL, buffer, len, wrap); } /* Print the BEGIN_SIGNING status message. If MD is not NULL it is used to retrieve the hash algorithms used for the message. */ void write_status_begin_signing (gcry_md_hd_t md) { if (md) { char buf[100]; size_t buflen; int i, ga; buflen = 0; for (i=1; i <= 110; i++) { ga = map_md_openpgp_to_gcry (i); if (ga && gcry_md_is_enabled (md, ga) && buflen+10 < DIM(buf)) { snprintf (buf+buflen, DIM(buf) - buflen, "%sH%d", buflen? " ":"",i); buflen += strlen (buf+buflen); } } write_status_text (STATUS_BEGIN_SIGNING, buf); } else write_status ( STATUS_BEGIN_SIGNING ); } static int myread(int fd, void *buf, size_t count) { int rc; do { rc = read( fd, buf, count ); } while (rc == -1 && errno == EINTR); if (!rc && count) { static int eof_emmited=0; if ( eof_emmited < 3 ) { *(char*)buf = CONTROL_D; rc = 1; eof_emmited++; } else /* Ctrl-D not caught - do something reasonable */ { #ifdef HAVE_DOSISH_SYSTEM #ifndef HAVE_W32CE_SYSTEM raise (SIGINT); /* Nothing to hangup under DOS. */ #endif #else raise (SIGHUP); /* No more input data. */ #endif } } return rc; } /* Request a string from the client over the command-fd. If GETBOOL is set the function returns a static string (do not free) if the entered value was true or NULL if the entered value was false. */ static char * do_get_from_fd ( const char *keyword, int hidden, int getbool ) { int i, len; char *string; if (statusfp != es_stdout) es_fflush (es_stdout); write_status_text (getbool? STATUS_GET_BOOL : hidden? STATUS_GET_HIDDEN : STATUS_GET_LINE, keyword); for (string = NULL, i = len = 200; ; i++ ) { if (i >= len-1 ) { /* On the first iteration allocate a new buffer. If that * buffer is too short at further iterations do a poor man's * realloc. */ char *save = string; len += 100; string = hidden? xmalloc_secure ( len ) : xmalloc ( len ); if (save) { memcpy (string, save, i); xfree (save); } else i = 0; } /* Fixme: why not use our read_line function here? */ if ( myread( opt.command_fd, string+i, 1) != 1 || string[i] == '\n' ) break; else if ( string[i] == CONTROL_D ) { /* Found ETX - Cancel the line and return a sole ETX. */ string[0] = CONTROL_D; i = 1; break; } } string[i] = 0; write_status (STATUS_GOT_IT); if (getbool) /* Fixme: is this correct??? */ return (string[0] == 'Y' || string[0] == 'y') ? "" : NULL; return string; } int cpr_enabled() { if( opt.command_fd != -1 ) return 1; return 0; } char * cpr_get_no_help( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 0, 0 ); for(;;) { p = tty_get( prompt ); return p; } } char * cpr_get( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 0, 0 ); for(;;) { p = tty_get( prompt ); if( *p=='?' && !p[1] && !(keyword && !*keyword)) { xfree(p); display_online_help( keyword ); } else return p; } } char * cpr_get_utf8( const char *keyword, const char *prompt ) { char *p; p = cpr_get( keyword, prompt ); if( p ) { char *utf8 = native_to_utf8( p ); xfree( p ); p = utf8; } return p; } char * cpr_get_hidden( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 1, 0 ); for(;;) { p = tty_get_hidden( prompt ); if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else return p; } } void cpr_kill_prompt(void) { if( opt.command_fd != -1 ) return; tty_kill_prompt(); return; } int cpr_get_answer_is_yes_def (const char *keyword, const char *prompt, int def_yes) { int yes; char *p; if( opt.command_fd != -1 ) return !!do_get_from_fd ( keyword, 0, 1 ); for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else { tty_kill_prompt(); yes = answer_is_yes_no_default (p, def_yes); xfree(p); return yes; } } } int cpr_get_answer_is_yes (const char *keyword, const char *prompt) { return cpr_get_answer_is_yes_def (keyword, prompt, 0); } int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt ) { int yes; char *p; if( opt.command_fd != -1 ) return !!do_get_from_fd ( keyword, 0, 1 ); for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else { tty_kill_prompt(); yes = answer_is_yes_no_quit(p); xfree(p); return yes; } } } int cpr_get_answer_okay_cancel (const char *keyword, const char *prompt, int def_answer) { int yes; char *answer = NULL; char *p; if( opt.command_fd != -1 ) answer = do_get_from_fd ( keyword, 0, 0 ); if (answer) { yes = answer_is_okay_cancel (answer, def_answer); xfree (answer); return yes; } for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if (*p == '?' && !p[1]) { xfree(p); display_online_help (keyword); } else { tty_kill_prompt(); yes = answer_is_okay_cancel (p, def_answer); xfree(p); return yes; } } } diff --git a/g10/main.h b/g10/main.h index f13b1b929..7b5754648 100644 --- a/g10/main.h +++ b/g10/main.h @@ -1,520 +1,522 @@ /* main.h * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef G10_MAIN_H #define G10_MAIN_H #include "../common/types.h" #include "../common/iobuf.h" #include "../common/util.h" #include "keydb.h" #include "keyedit.h" /* It could be argued that the default cipher should be 3DES rather than AES128, and the default compression should be 0 (i.e. uncompressed) rather than 1 (zip). However, the real world issues of speed and size come into play here. */ #if GPG_USE_AES256 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_AES256 #elif GPG_USE_AES128 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_AES #elif GPG_USE_CAST5 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_CAST5 #else # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_3DES #endif #define DEFAULT_AEAD_ALGO AEAD_ALGO_OCB #define DEFAULT_DIGEST_ALGO ((GNUPG)? DIGEST_ALGO_SHA256:DIGEST_ALGO_SHA1) #define DEFAULT_S2K_DIGEST_ALGO DIGEST_ALGO_SHA1 #ifdef HAVE_ZIP # define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_ZIP #else # define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_NONE #endif #define S2K_DIGEST_ALGO (opt.s2k_digest_algo?opt.s2k_digest_algo:DEFAULT_S2K_DIGEST_ALGO) /* Various data objects. */ typedef struct { ctrl_t ctrl; int header_okay; PK_LIST pk_list; DEK *symkey_dek; STRING2KEY *symkey_s2k; cipher_filter_context_t cfx; } encrypt_filter_context_t; struct groupitem { char *name; strlist_t values; struct groupitem *next; }; struct weakhash { enum gcry_md_algos algo; int rejection_shown; struct weakhash *next; }; /*-- gpg.c --*/ extern int g10_errors_seen; #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) void g10_exit(int rc) __attribute__ ((noreturn)); #else void g10_exit(int rc); #endif void print_pubkey_algo_note (pubkey_algo_t algo); void print_cipher_algo_note (cipher_algo_t algo); void print_digest_algo_note (digest_algo_t algo); void print_digest_rejected_note (enum gcry_md_algos algo); void print_sha1_keysig_rejected_note (void); void print_reported_error (gpg_error_t err, gpg_err_code_t skip_if_ec); void print_further_info (const char *format, ...) GPGRT_ATTR_PRINTF(1,2); void additional_weak_digest (const char* digestname); /*-- armor.c --*/ char *make_radix64_string( const byte *data, size_t len ); /*-- misc.c --*/ void trap_unaligned(void); void register_secured_file (const char *fname); void unregister_secured_file (const char *fname); int is_secured_file (int fd); int is_secured_filename (const char *fname); u16 checksum_u16( unsigned n ); u16 checksum( byte *p, unsigned n ); u16 checksum_mpi( gcry_mpi_t a ); u32 buffer_to_u32( const byte *buffer ); const byte *get_session_marker( size_t *rlen ); enum gcry_cipher_algos map_cipher_openpgp_to_gcry (cipher_algo_t algo); #define openpgp_cipher_open(_a,_b,_c,_d) \ gcry_cipher_open((_a),map_cipher_openpgp_to_gcry((_b)),(_c),(_d)) #define openpgp_cipher_get_algo_keylen(_a) \ gcry_cipher_get_algo_keylen(map_cipher_openpgp_to_gcry((_a))) #define openpgp_cipher_get_algo_blklen(_a) \ gcry_cipher_get_algo_blklen(map_cipher_openpgp_to_gcry((_a))) int openpgp_cipher_blocklen (cipher_algo_t algo); int openpgp_cipher_test_algo(cipher_algo_t algo); const char *openpgp_cipher_algo_name (cipher_algo_t algo); gpg_error_t openpgp_aead_test_algo (aead_algo_t algo); const char *openpgp_aead_algo_name (aead_algo_t algo); gpg_error_t openpgp_aead_algo_info (aead_algo_t algo, enum gcry_cipher_modes *r_mode, unsigned int *r_noncelen); int openpgp_pk_test_algo (pubkey_algo_t algo); int openpgp_pk_test_algo2 (pubkey_algo_t algo, unsigned int use); int openpgp_pk_algo_usage ( int algo ); const char *openpgp_pk_algo_name (pubkey_algo_t algo); enum gcry_md_algos map_md_openpgp_to_gcry (digest_algo_t algo); int openpgp_md_test_algo (digest_algo_t algo); const char *openpgp_md_algo_name (int algo); struct expando_args { PKT_public_key *pk; PKT_public_key *pksk; byte imagetype; int validity_info; const char *validity_string; const byte *namehash; }; char *pct_expando (ctrl_t ctrl, const char *string,struct expando_args *args); void deprecated_warning(const char *configname,unsigned int configlineno, const char *option,const char *repl1,const char *repl2); void deprecated_command (const char *name); void obsolete_scdaemon_option (const char *configname, unsigned int configlineno, const char *name); int string_to_cipher_algo (const char *string); aead_algo_t string_to_aead_algo (const char *string); int string_to_digest_algo (const char *string); const char *compress_algo_to_string(int algo); int string_to_compress_algo(const char *string); int check_compress_algo(int algo); int default_cipher_algo(void); aead_algo_t default_aead_algo(void); int default_compress_algo(void); void compliance_failure(void); struct parse_options { char *name; unsigned int bit; char **value; char *help; }; char *optsep(char **stringp); char *argsplit(char *string); int parse_options(char *str,unsigned int *options, struct parse_options *opts,int noisy); const char *get_libexecdir (void); int path_access(const char *file,int mode); int pubkey_get_npkey (pubkey_algo_t algo); int pubkey_get_nskey (pubkey_algo_t algo); int pubkey_get_nsig (pubkey_algo_t algo); int pubkey_get_nenc (pubkey_algo_t algo); /* Temporary helpers. */ unsigned int pubkey_nbits( int algo, gcry_mpi_t *pkey ); int mpi_print (estream_t stream, gcry_mpi_t a, int mode); unsigned int ecdsa_qbits_from_Q (unsigned int qbits); /*-- cpr.c --*/ void set_status_fd ( int fd ); int is_status_enabled ( void ); void write_status ( int no ); void write_status_error (const char *where, gpg_error_t err); void write_status_errcode (const char *where, int errcode); void write_status_failure (const char *where, gpg_error_t err); void write_status_text ( int no, const char *text ); void write_status_printf (int no, const char *format, ...) GPGRT_ATTR_PRINTF(2,3); void write_status_strings (int no, const char *text, ...) GPGRT_ATTR_SENTINEL(0); +gpg_error_t write_status_strings2 (ctrl_t dummy, int no, + ...) GPGRT_ATTR_SENTINEL(0); void write_status_buffer ( int no, const char *buffer, size_t len, int wrap ); void write_status_text_and_buffer ( int no, const char *text, const char *buffer, size_t len, int wrap ); void write_status_begin_signing (gcry_md_hd_t md); int cpr_enabled(void); char *cpr_get( const char *keyword, const char *prompt ); char *cpr_get_no_help( const char *keyword, const char *prompt ); char *cpr_get_utf8( const char *keyword, const char *prompt ); char *cpr_get_hidden( const char *keyword, const char *prompt ); void cpr_kill_prompt(void); int cpr_get_answer_is_yes_def (const char *keyword, const char *prompt, int def_yes); int cpr_get_answer_is_yes( const char *keyword, const char *prompt ); int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt ); int cpr_get_answer_okay_cancel (const char *keyword, const char *prompt, int def_answer); /*-- helptext.c --*/ void display_online_help( const char *keyword ); /*-- encode.c --*/ gpg_error_t setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek); gpg_error_t encrypt_seskey (DEK *dek, aead_algo_t aead_algo, DEK **r_seskey, void **r_enckey, size_t *r_enckeylen); aead_algo_t use_aead (pk_list_t pk_list, int algo); int use_mdc (pk_list_t pk_list,int algo); int encrypt_symmetric (const char *filename ); int encrypt_store (const char *filename ); int encrypt_crypt (ctrl_t ctrl, int filefd, const char *filename, strlist_t remusr, int use_symkey, pk_list_t provided_keys, int outputfd); void encrypt_crypt_files (ctrl_t ctrl, int nfiles, char **files, strlist_t remusr); int encrypt_filter (void *opaque, int control, iobuf_t a, byte *buf, size_t *ret_len); int write_pubkey_enc (ctrl_t ctrl, PKT_public_key *pk, int throw_keyid, DEK *dek, iobuf_t out); /*-- sign.c --*/ int sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr, int do_encrypt, strlist_t remusr, const char *outfile ); int clearsign_file (ctrl_t ctrl, const char *fname, strlist_t locusr, const char *outfile); int sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr); /*-- sig-check.c --*/ void sig_check_dump_stats (void); /* SIG is a revocation signature. Check if any of PK's designated revokers generated it. If so, return 0. Note: this function (correctly) doesn't care if the designated revoker is revoked. */ int check_revocation_keys (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig); /* Check that the backsig BACKSIG from the subkey SUB_PK to its primary key MAIN_PK is valid. */ int check_backsig(PKT_public_key *main_pk,PKT_public_key *sub_pk, PKT_signature *backsig); /* Check that the signature SIG over a key (e.g., a key binding or a key revocation) is valid. (To check signatures over data, use check_signature.) */ int check_key_signature (ctrl_t ctrl, kbnode_t root, kbnode_t sig, int *is_selfsig ); /* Like check_key_signature, but with the ability to specify some additional parameters and get back additional information. See the documentation for the implementation for details. */ int check_key_signature2 (ctrl_t ctrl, kbnode_t root, kbnode_t node, PKT_public_key *check_pk, PKT_public_key *ret_pk, int *is_selfsig, u32 *r_expiredate, int *r_expired); /* Returns whether SIGNER generated the signature SIG over the packet PACKET, which is a key, subkey or uid, and comes from the key block KB. If SIGNER is NULL, it is looked up based on the information in SIG. If not NULL, sets *IS_SELFSIG to indicate whether the signature is a self-signature and *RET_PK to a copy of the signer's key. */ gpg_error_t check_signature_over_key_or_uid (ctrl_t ctrl, PKT_public_key *signer, PKT_signature *sig, KBNODE kb, PACKET *packet, int *is_selfsig, PKT_public_key *ret_pk); /*-- delkey.c --*/ gpg_error_t delete_keys (ctrl_t ctrl, strlist_t names, int secret, int allow_both); /*-- keygen.c --*/ const char *get_default_pubkey_algo (void); u32 parse_expire_string(const char *string); u32 ask_expire_interval(int object,const char *def_expire); u32 ask_expiredate(void); unsigned int ask_key_flags (int algo, int subkey, unsigned int current); const char *ask_curve (int *algo, int *subkey_algo, const char *current); void quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr, const char *usagestr, const char *expirestr); void generate_keypair (ctrl_t ctrl, int full, const char *fname, const char *card_serialno, int card_backup_key); int keygen_set_std_prefs (const char *string,int personal); PKT_user_id *keygen_get_std_prefs (void); int keygen_add_key_expire( PKT_signature *sig, void *opaque ); int keygen_add_key_flags (PKT_signature *sig, void *opaque); int keygen_add_std_prefs( PKT_signature *sig, void *opaque ); int keygen_upd_std_prefs( PKT_signature *sig, void *opaque ); int keygen_add_keyserver_url(PKT_signature *sig, void *opaque); int keygen_add_notations(PKT_signature *sig,void *opaque); int keygen_add_revkey(PKT_signature *sig, void *opaque); gpg_error_t make_backsig (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pk, PKT_public_key *sub_pk, PKT_public_key *sub_psk, u32 timestamp, const char *cache_nonce); gpg_error_t generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr, const char *usagestr, const char *expirestr); #ifdef ENABLE_CARD_SUPPORT gpg_error_t generate_card_subkeypair (ctrl_t ctrl, kbnode_t pub_keyblock, int keyno, const char *serialno); #endif /*-- openfile.c --*/ int overwrite_filep( const char *fname ); char *make_outfile_name( const char *iname ); char *ask_outfile_name( const char *name, size_t namelen ); int open_outfile (int out_fd, const char *iname, int mode, int restrictedperm, iobuf_t *a); char *get_matching_datafile (const char *sigfilename); iobuf_t open_sigfile (const char *sigfilename, progress_filter_context_t *pfx); void try_make_homedir( const char *fname ); char *get_openpgp_revocdir (const char *home); /*-- seskey.c --*/ void make_session_key( DEK *dek ); gcry_mpi_t encode_session_key( int openpgp_pk_algo, DEK *dek, unsigned nbits ); gcry_mpi_t encode_md_value (PKT_public_key *pk, gcry_md_hd_t md, int hash_algo ); /*-- import.c --*/ struct import_stats_s; typedef struct import_stats_s *import_stats_t; struct import_filter_s; typedef struct import_filter_s *import_filter_t; typedef gpg_error_t (*import_screener_t)(kbnode_t keyblock, void *arg); int parse_import_options(char *str,unsigned int *options,int noisy); gpg_error_t parse_and_set_import_filter (const char *string); import_filter_t save_and_clear_import_filter (void); void restore_import_filter (import_filter_t filt); gpg_error_t read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname, const void *buffer, size_t buflen, kbnode_t *r_keyblock); gpg_error_t import_included_key_block (ctrl_t ctrl, kbnode_t keyblock); void import_keys (ctrl_t ctrl, char **fnames, int nnames, import_stats_t stats_hd, unsigned int options, int origin, const char *url); gpg_error_t import_keys_es_stream (ctrl_t ctrl, estream_t fp, import_stats_t stats_handle, unsigned char **fpr, size_t *fpr_len, unsigned int options, import_screener_t screener, void *screener_arg, int origin, const char *url); gpg_error_t import_old_secring (ctrl_t ctrl, const char *fname); import_stats_t import_new_stats_handle (void); void import_release_stats_handle (import_stats_t hd); void import_print_stats (import_stats_t hd); /* Communication for impex_filter_getval */ struct impex_filter_parm_s { ctrl_t ctrl; kbnode_t node; char hexfpr[2*MAX_FINGERPRINT_LEN + 1]; }; const char *impex_filter_getval (void *cookie, const char *propname); gpg_error_t transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats, kbnode_t sec_keyblock, int batch, int force, int only_marked); int collapse_uids (kbnode_t *keyblock); int collapse_subkeys (kbnode_t *keyblock); int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen); /*-- export.c --*/ struct export_stats_s; typedef struct export_stats_s *export_stats_t; export_stats_t export_new_stats (void); void export_release_stats (export_stats_t stats); void export_print_stats (export_stats_t stats); int parse_export_options(char *str,unsigned int *options,int noisy); gpg_error_t parse_and_set_export_filter (const char *string); void push_export_filters (void); void pop_export_filters (void); int exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, kbnode_t node); int export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); int export_seckeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); int export_secsubkeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, const void *prefix, size_t prefixlen, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen); gpg_error_t receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd, int cleartext, char **cache_nonce_addr, const char *hexgrip, PKT_public_key *pk); gpg_error_t write_keyblock_to_output (kbnode_t keyblock, int with_armor, unsigned int options); gpg_error_t export_ssh_key (ctrl_t ctrl, const char *userid); /*-- dearmor.c --*/ int dearmor_file( const char *fname ); int enarmor_file( const char *fname ); /*-- revoke.c --*/ struct revocation_reason_info; int gen_standard_revoke (ctrl_t ctrl, PKT_public_key *psk, const char *cache_nonce); int gen_revoke (ctrl_t ctrl, const char *uname); int gen_desig_revoke (ctrl_t ctrl, const char *uname, strlist_t locusr); int revocation_reason_build_cb( PKT_signature *sig, void *opaque ); struct revocation_reason_info * ask_revocation_reason( int key_rev, int cert_rev, int hint ); struct revocation_reason_info * get_default_uid_revocation_reason(void); void release_revocation_reason_info( struct revocation_reason_info *reason ); /*-- keylist.c --*/ void public_key_list (ctrl_t ctrl, strlist_t list, int locate_mode, int no_local); void secret_key_list (ctrl_t ctrl, strlist_t list ); void print_subpackets_colon(PKT_signature *sig); void reorder_keyblock (KBNODE keyblock); void list_keyblock_direct (ctrl_t ctrl, kbnode_t keyblock, int secret, int has_secret, int fpr, int no_validity); void print_fingerprint (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int mode); void print_revokers (estream_t fp, PKT_public_key *pk); void show_policy_url(PKT_signature *sig,int indent,int mode); void show_keyserver_url(PKT_signature *sig,int indent,int mode); void show_notation(PKT_signature *sig,int indent,int mode,int which); void dump_attribs (const PKT_user_id *uid, PKT_public_key *pk); void set_attrib_fd(int fd); void print_key_info (ctrl_t ctrl, estream_t fp, int indent, PKT_public_key *pk, int secret); void print_key_info_log (ctrl_t ctrl, int loglevel, int indent, PKT_public_key *pk, int secret); void print_card_key_info (estream_t fp, KBNODE keyblock); void print_key_line (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int secret); /*-- verify.c --*/ void print_file_status( int status, const char *name, int what ); int verify_signatures (ctrl_t ctrl, int nfiles, char **files ); int verify_files (ctrl_t ctrl, int nfiles, char **files ); int gpg_verify (ctrl_t ctrl, int sig_fd, int data_fd, estream_t out_fp); /*-- decrypt.c --*/ int decrypt_message (ctrl_t ctrl, const char *filename ); gpg_error_t decrypt_message_fd (ctrl_t ctrl, int input_fd, int output_fd); void decrypt_messages (ctrl_t ctrl, int nfiles, char *files[]); /*-- plaintext.c --*/ int hash_datafiles( gcry_md_hd_t md, gcry_md_hd_t md2, strlist_t files, const char *sigfilename, int textmode); int hash_datafile_by_fd ( gcry_md_hd_t md, gcry_md_hd_t md2, int data_fd, int textmode ); PKT_plaintext *setup_plaintext_name(const char *filename,IOBUF iobuf); /*-- server.c --*/ int gpg_server (ctrl_t); gpg_error_t gpg_proxy_pinentry_notify (ctrl_t ctrl, const unsigned char *line); #ifdef ENABLE_CARD_SUPPORT /*-- card-util.c --*/ void change_pin (int no, int allow_admin); void card_status (ctrl_t ctrl, estream_t fp, const char *serialno); void card_edit (ctrl_t ctrl, strlist_t commands); gpg_error_t card_generate_subkey (ctrl_t ctrl, kbnode_t pub_keyblock); int card_store_subkey (KBNODE node, int use); #endif /*-- migrate.c --*/ void migrate_secring (ctrl_t ctrl); #endif /*G10_MAIN_H*/ diff --git a/sm/call-agent.c b/sm/call-agent.c index 0b556a7e5..868497e0d 100644 --- a/sm/call-agent.c +++ b/sm/call-agent.c @@ -1,1495 +1,1464 @@ /* call-agent.c - Divert GPGSM operations to the agent * Copyright (C) 2001, 2002, 2003, 2005, 2007, * 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "gpgsm.h" #include #include #include "../common/i18n.h" #include "../common/asshelp.h" #include "keydb.h" /* fixme: Move this to import.c */ #include "../common/membuf.h" #include "../common/shareddefs.h" #include "passphrase.h" static assuan_context_t agent_ctx = NULL; struct cipher_parm_s { ctrl_t ctrl; assuan_context_t ctx; const unsigned char *ciphertext; size_t ciphertextlen; }; struct genkey_parm_s { ctrl_t ctrl; assuan_context_t ctx; const unsigned char *sexp; size_t sexplen; }; struct learn_parm_s { int error; ctrl_t ctrl; assuan_context_t ctx; membuf_t *data; }; struct import_key_parm_s { ctrl_t ctrl; assuan_context_t ctx; const void *key; size_t keylen; }; struct sethash_inq_parm_s { assuan_context_t ctx; const void *data; size_t datalen; }; struct default_inq_parm_s { ctrl_t ctrl; assuan_context_t ctx; }; /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (ctrl_t ctrl, assuan_context_t ctx, const char *servername, int mode) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, mode, &serverversion); - if (err) - log_error (_("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - gpgsm_status2 (ctrl, STATUS_WARNING, "server_version_mismatch 0", - warn, NULL); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, mode, + gpgsm_status2, ctrl, + !opt.quiet); } - /* Try to connect to the agent via socket or fork it off and work by pipes. Handle the server's initial greeting */ static int start_agent (ctrl_t ctrl) { int rc; if (agent_ctx) rc = 0; /* fixme: We need a context for each thread or serialize the access to the agent (which is suitable given that the agent is not MT. */ else { rc = start_new_gpg_agent (&agent_ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, opt.lc_ctype, opt.lc_messages, opt.session_env, opt.autostart, opt.verbose, DBG_IPC, gpgsm_status2, ctrl); if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT) { static int shown; if (!shown) { shown = 1; log_info (_("no gpg-agent running in this session\n")); } } else if (!rc && !(rc = warn_version_mismatch (ctrl, agent_ctx, GPG_AGENT_NAME, 0))) { /* Tell the agent that we support Pinentry notifications. No error checking so that it will work also with older agents. */ assuan_transact (agent_ctx, "OPTION allow-pinentry-notify", NULL, NULL, NULL, NULL, NULL, NULL); /* Pass on the pinentry mode. */ if (opt.pinentry_mode) { char *tmp = xasprintf ("OPTION pinentry-mode=%s", str_pinentry_mode (opt.pinentry_mode)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) log_error ("setting pinentry mode '%s' failed: %s\n", str_pinentry_mode (opt.pinentry_mode), gpg_strerror (rc)); } /* Pass on the request origin. */ if (opt.request_origin) { char *tmp = xasprintf ("OPTION pretend-request-origin=%s", str_request_origin (opt.request_origin)); rc = assuan_transact (agent_ctx, tmp, NULL, NULL, NULL, NULL, NULL, NULL); xfree (tmp); if (rc) log_error ("setting request origin '%s' failed: %s\n", str_request_origin (opt.request_origin), gpg_strerror (rc)); } /* In DE_VS mode under Windows we require that the JENT RNG * is active. */ #ifdef HAVE_W32_SYSTEM if (!rc && opt.compliance == CO_DE_VS) { if (assuan_transact (agent_ctx, "GETINFO jent_active", NULL, NULL, NULL, NULL, NULL, NULL)) { rc = gpg_error (GPG_ERR_FORBIDDEN); log_error (_("%s is not compliant with %s mode\n"), GPG_AGENT_NAME, gnupg_compliance_option_string (opt.compliance)); gpgsm_status_with_error (ctrl, STATUS_ERROR, "random-compliance", rc); } } #endif /*HAVE_W32_SYSTEM*/ } } if (!ctrl->agent_seen) { ctrl->agent_seen = 1; audit_log_ok (ctrl->audit, AUDIT_AGENT_READY, rc); } return rc; } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct default_inq_parm_s *parm = opaque; ctrl_t ctrl = parm->ctrl; if (has_leading_keyword (line, "PINENTRY_LAUNCHED")) { err = gpgsm_proxy_pinentry_notify (ctrl, line); if (err) log_error (_("failed to proxy %s inquiry to client\n"), "PINENTRY_LAUNCHED"); /* We do not pass errors to avoid breaking other code. */ } else if ((has_leading_keyword (line, "PASSPHRASE") || has_leading_keyword (line, "NEW_PASSPHRASE")) && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK && have_static_passphrase ()) { const char *s = get_static_passphrase (); err = assuan_send_data (parm->ctx, s, strlen (s)); } else log_error ("ignoring gpg-agent inquiry '%s'\n", line); return err; } /* This is the inquiry callback required by the SETHASH command. */ static gpg_error_t sethash_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct sethash_inq_parm_s *parm = opaque; if (has_leading_keyword (line, "TBSDATA")) { err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else log_error ("ignoring gpg-agent inquiry '%s'\n", line); return err; } /* Call the agent to do a sign operation using the key identified by * the hex string KEYGRIP. If DIGESTALGO is given (DIGEST,DIGESTLEN) * gives the to be signed hash created using the given algo. If * DIGESTALGO is not given (i.e. zero) (DIGEST,DIGESTALGO) give the * entire data to-be-signed. */ int gpgsm_agent_pksign (ctrl_t ctrl, const char *keygrip, const char *desc, unsigned char *digest, size_t digestlen, int digestalgo, unsigned char **r_buf, size_t *r_buflen ) { int rc, i; char *p, line[ASSUAN_LINELENGTH]; membuf_t data; size_t len; struct default_inq_parm_s inq_parm; *r_buf = NULL; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; if (digestalgo && digestlen*2 + 50 > DIM(line)) return gpg_error (GPG_ERR_GENERAL); rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; snprintf (line, DIM(line), "SIGKEY %s", keygrip); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; } if (!digestalgo) { struct sethash_inq_parm_s sethash_inq_parm; sethash_inq_parm.ctx = agent_ctx; sethash_inq_parm.data = digest; sethash_inq_parm.datalen = digestlen; rc = assuan_transact (agent_ctx, "SETHASH --inquire", NULL, NULL, sethash_inq_cb, &sethash_inq_parm, NULL, NULL); } else { snprintf (line, sizeof line, "SETHASH %d ", digestalgo); p = line + strlen (line); for (i=0; i < digestlen ; i++, p += 2 ) sprintf (p, "%02X", digest[i]); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); } if (rc) return rc; init_membuf (&data, 1024); rc = assuan_transact (agent_ctx, "PKSIGN", put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } *r_buf = get_membuf (&data, r_buflen); if (!gcry_sexp_canon_len (*r_buf, *r_buflen, NULL, NULL)) { xfree (*r_buf); *r_buf = NULL; return gpg_error (GPG_ERR_INV_VALUE); } return *r_buf? 0 : out_of_core (); } /* Call the scdaemon to do a sign operation using the key identified by the hex string KEYID. */ int gpgsm_scd_pksign (ctrl_t ctrl, const char *keyid, const char *desc, unsigned char *digest, size_t digestlen, int digestalgo, unsigned char **r_buf, size_t *r_buflen ) { int rc, i, pkalgo; char *p, line[ASSUAN_LINELENGTH]; membuf_t data; size_t len; const char *hashopt; unsigned char *sigbuf; size_t sigbuflen; struct default_inq_parm_s inq_parm; gcry_sexp_t sig; (void)desc; *r_buf = NULL; switch(digestalgo) { case GCRY_MD_SHA1: hashopt = "--hash=sha1"; break; case GCRY_MD_RMD160:hashopt = "--hash=rmd160"; break; case GCRY_MD_MD5: hashopt = "--hash=md5"; break; case GCRY_MD_SHA256:hashopt = "--hash=sha256"; break; case GCRY_MD_SHA512:hashopt = "--hash=sha512"; break; default: return gpg_error (GPG_ERR_DIGEST_ALGO); } rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; if (digestlen*2 + 50 > DIM(line)) return gpg_error (GPG_ERR_GENERAL); /* Get the key type from the scdaemon. */ snprintf (line, DIM(line), "SCD READKEY %s", keyid); init_membuf (&data, 1024); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } p = get_membuf (&data, &len); pkalgo = get_pk_algo_from_canon_sexp (p, len); xfree (p); if (!pkalgo) return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); p = stpcpy (line, "SCD SETDATA " ); for (i=0; i < digestlen ; i++, p += 2 ) sprintf (p, "%02X", digest[i]); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; init_membuf (&data, 1024); snprintf (line, DIM(line), "SCD PKSIGN %s %s", hashopt, keyid); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } sigbuf = get_membuf (&data, &sigbuflen); switch(pkalgo) { case GCRY_PK_RSA: rc = gcry_sexp_build (&sig, NULL, "(sig-val(rsa(s%b)))", (int)sigbuflen, sigbuf); break; case GCRY_PK_ECC: rc = gcry_sexp_build (&sig, NULL, "(sig-val(ecdsa(r%b)(s%b)))", (int)sigbuflen/2, sigbuf, (int)sigbuflen/2, sigbuf + sigbuflen/2); break; case GCRY_PK_EDDSA: rc = gcry_sexp_build (&sig, NULL, "(sig-val(eddsa(r%b)(s%b)))", (int)sigbuflen/2, sigbuf, (int)sigbuflen/2, sigbuf + sigbuflen/2); break; default: rc = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); break; } xfree (sigbuf); if (rc) return rc; rc = make_canon_sexp (sig, r_buf, r_buflen); gcry_sexp_release (sig); if (rc) return rc; log_assert (gcry_sexp_canon_len (*r_buf, *r_buflen, NULL, NULL)); return 0; } /* Handle a CIPHERTEXT inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the end */ static gpg_error_t inq_ciphertext_cb (void *opaque, const char *line) { struct cipher_parm_s *parm = opaque; int rc; if (has_leading_keyword (line, "CIPHERTEXT")) { assuan_begin_confidential (parm->ctx); rc = assuan_send_data (parm->ctx, parm->ciphertext, parm->ciphertextlen); assuan_end_confidential (parm->ctx); } else { struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx }; rc = default_inq_cb (&inq_parm, line); } return rc; } /* Call the agent to do a decrypt operation using the key identified by the hex string KEYGRIP. */ int gpgsm_agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc, ksba_const_sexp_t ciphertext, char **r_buf, size_t *r_buflen ) { int rc; char line[ASSUAN_LINELENGTH]; membuf_t data; struct cipher_parm_s cipher_parm; size_t n, len; char *p, *buf, *endp; size_t ciphertextlen; if (!keygrip || strlen(keygrip) != 40 || !ciphertext || !r_buf || !r_buflen) return gpg_error (GPG_ERR_INV_VALUE); *r_buf = NULL; ciphertextlen = gcry_sexp_canon_len (ciphertext, 0, NULL, NULL); if (!ciphertextlen) return gpg_error (GPG_ERR_INV_VALUE); rc = start_agent (ctrl); if (rc) return rc; rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; log_assert ( DIM(line) >= 50 ); snprintf (line, DIM(line), "SETKEY %s", keygrip); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; } init_membuf (&data, 1024); cipher_parm.ctrl = ctrl; cipher_parm.ctx = agent_ctx; cipher_parm.ciphertext = ciphertext; cipher_parm.ciphertextlen = ciphertextlen; rc = assuan_transact (agent_ctx, "PKDECRYPT", put_membuf_cb, &data, inq_ciphertext_cb, &cipher_parm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } /* Make sure it is 0 terminated so we can invoke strtoul safely. */ put_membuf (&data, "", 1); buf = get_membuf (&data, &len); if (!buf) return gpg_error (GPG_ERR_ENOMEM); log_assert (len); /* (we forced Nul termination.) */ if (*buf == '(') { if (len < 13 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)\0" */ return gpg_error (GPG_ERR_INV_SEXP); /* Trim any spurious trailing Nuls: */ while (buf[len-1] == 0) len--; if (buf[len-1] != ')') return gpg_error (GPG_ERR_INV_SEXP); len--; /* Drop the final close-paren: */ p = buf + 8; /* Skip leading parenthesis and the value tag. */ len -= 8; /* Count only the data of the second part. */ } else { /* For compatibility with older gpg-agents handle the old style incomplete S-exps. */ len--; /* Do not count the Nul. */ p = buf; } n = strtoul (p, &endp, 10); if (!n || *endp != ':') return gpg_error (GPG_ERR_INV_SEXP); endp++; if (endp-p+n != len) return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */ memmove (buf, endp, n); *r_buflen = n; *r_buf = buf; return 0; } /* Handle a KEYPARMS inquiry. Note, we only send the data, assuan_transact takes care of flushing and writing the end */ static gpg_error_t inq_genkey_parms (void *opaque, const char *line) { struct genkey_parm_s *parm = opaque; int rc; if (has_leading_keyword (line, "KEYPARAM")) { rc = assuan_send_data (parm->ctx, parm->sexp, parm->sexplen); } else { struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx }; rc = default_inq_cb (&inq_parm, line); } return rc; } /* Call the agent to generate a new key */ int gpgsm_agent_genkey (ctrl_t ctrl, ksba_const_sexp_t keyparms, ksba_sexp_t *r_pubkey) { int rc; struct genkey_parm_s gk_parm; membuf_t data; size_t len; unsigned char *buf; gnupg_isotime_t timebuf; char line[ASSUAN_LINELENGTH]; *r_pubkey = NULL; rc = start_agent (ctrl); if (rc) return rc; rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; init_membuf (&data, 1024); gk_parm.ctrl = ctrl; gk_parm.ctx = agent_ctx; gk_parm.sexp = keyparms; gk_parm.sexplen = gcry_sexp_canon_len (keyparms, 0, NULL, NULL); if (!gk_parm.sexplen) return gpg_error (GPG_ERR_INV_VALUE); gnupg_get_isotime (timebuf); snprintf (line, sizeof line, "GENKEY --timestamp=%s", timebuf); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, inq_genkey_parms, &gk_parm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } buf = get_membuf (&data, &len); if (!buf) return gpg_error (GPG_ERR_ENOMEM); if (!gcry_sexp_canon_len (buf, len, NULL, NULL)) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } *r_pubkey = buf; return 0; } /* Call the agent to read the public key part for a given keygrip. If FROMCARD is true, the key is directly read from the current smartcard. In this case HEXKEYGRIP should be the keyID (e.g. OPENPGP.3). */ int gpgsm_agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip, ksba_sexp_t *r_pubkey) { int rc; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; *r_pubkey = NULL; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; snprintf (line, DIM(line), "%sREADKEY %s", fromcard? "SCD ":"", hexkeygrip); init_membuf (&data, 1024); rc = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (rc) { xfree (get_membuf (&data, &len)); return rc; } buf = get_membuf (&data, &len); if (!buf) return gpg_error (GPG_ERR_ENOMEM); if (!gcry_sexp_canon_len (buf, len, NULL, NULL)) { xfree (buf); return gpg_error (GPG_ERR_INV_SEXP); } *r_pubkey = buf; return 0; } /* Take the serial number from LINE and return it verbatim in a newly allocated string. We make sure that only hex characters are returned. */ static char * store_serialno (const char *line) { const char *s; char *p; for (s=line; hexdigitp (s); s++) ; p = xtrymalloc (s + 1 - line); if (p) { memcpy (p, line, s-line); p[s-line] = 0; } return p; } /* Callback for the gpgsm_agent_serialno function. */ static gpg_error_t scd_serialno_status_cb (void *opaque, const char *line) { char **r_serialno = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { xfree (*r_serialno); *r_serialno = store_serialno (line); } return 0; } /* Call the agent to read the serial number of the current card. */ int gpgsm_agent_scd_serialno (ctrl_t ctrl, char **r_serialno) { int rc; char *serialno = NULL; struct default_inq_parm_s inq_parm; *r_serialno = NULL; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, "SCD SERIALNO", NULL, NULL, default_inq_cb, &inq_parm, scd_serialno_status_cb, &serialno); if (!rc && !serialno) rc = gpg_error (GPG_ERR_INTERNAL); if (rc) { xfree (serialno); return rc; } *r_serialno = serialno; return 0; } /* Callback for the gpgsm_agent_serialno function. */ static gpg_error_t scd_keypairinfo_status_cb (void *opaque, const char *line) { strlist_t *listaddr = opaque; const char *keyword = line; int keywordlen; strlist_t sl; char *p; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { sl = append_to_strlist (listaddr, line); p = sl->d; /* Make sure that we only have two tokens so that future * extensions of the format won't change the format expected by * the caller. */ while (*p && !spacep (p)) p++; if (*p) { while (spacep (p)) p++; while (*p && !spacep (p)) p++; if (*p) { *p++ = 0; while (spacep (p)) p++; while (*p && !spacep (p)) { switch (*p++) { case 'c': sl->flags |= GCRY_PK_USAGE_CERT; break; case 's': sl->flags |= GCRY_PK_USAGE_SIGN; break; case 'e': sl->flags |= GCRY_PK_USAGE_ENCR; break; case 'a': sl->flags |= GCRY_PK_USAGE_AUTH; break; } } } } } return 0; } /* Call the agent to read the keypairinfo lines of the current card. The list is returned as a string made up of the keygrip, a space and the keyid. The flags of the string carry the usage bits. */ int gpgsm_agent_scd_keypairinfo (ctrl_t ctrl, strlist_t *r_list) { int rc; strlist_t list = NULL; struct default_inq_parm_s inq_parm; *r_list = NULL; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; rc = assuan_transact (agent_ctx, "SCD LEARN --keypairinfo", NULL, NULL, default_inq_cb, &inq_parm, scd_keypairinfo_status_cb, &list); if (!rc && !list) rc = gpg_error (GPG_ERR_NO_DATA); if (rc) { free_strlist (list); return rc; } *r_list = list; return 0; } static gpg_error_t istrusted_status_cb (void *opaque, const char *line) { struct rootca_flags_s *flags = opaque; const char *s; if ((s = has_leading_keyword (line, "TRUSTLISTFLAG"))) { line = s; if (has_leading_keyword (line, "relax")) flags->relax = 1; else if (has_leading_keyword (line, "cm")) flags->chain_model = 1; } return 0; } /* Ask the agent whether the certificate is in the list of trusted keys. The certificate is either specified by the CERT object or by the fingerprint HEXFPR. ROOTCA_FLAGS is guaranteed to be cleared on error. */ int gpgsm_agent_istrusted (ctrl_t ctrl, ksba_cert_t cert, const char *hexfpr, struct rootca_flags_s *rootca_flags) { int rc; char line[ASSUAN_LINELENGTH]; memset (rootca_flags, 0, sizeof *rootca_flags); if (cert && hexfpr) return gpg_error (GPG_ERR_INV_ARG); rc = start_agent (ctrl); if (rc) return rc; if (hexfpr) { snprintf (line, DIM(line), "ISTRUSTED %s", hexfpr); } else { char *fpr; fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); if (!fpr) { log_error ("error getting the fingerprint\n"); return gpg_error (GPG_ERR_GENERAL); } snprintf (line, DIM(line), "ISTRUSTED %s", fpr); xfree (fpr); } rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, istrusted_status_cb, rootca_flags); if (!rc) rootca_flags->valid = 1; return rc; } /* Ask the agent to mark CERT as a trusted Root-CA one */ int gpgsm_agent_marktrusted (ctrl_t ctrl, ksba_cert_t cert) { int rc; char *fpr, *dn, *dnfmt; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); if (!fpr) { log_error ("error getting the fingerprint\n"); return gpg_error (GPG_ERR_GENERAL); } dn = ksba_cert_get_issuer (cert, 0); if (!dn) { xfree (fpr); return gpg_error (GPG_ERR_GENERAL); } dnfmt = gpgsm_format_name2 (dn, 0); xfree (dn); if (!dnfmt) return gpg_error_from_syserror (); snprintf (line, DIM(line), "MARKTRUSTED %s S %s", fpr, dnfmt); ksba_free (dnfmt); xfree (fpr); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inq_parm, NULL, NULL); return rc; } /* Ask the agent whether the a corresponding secret key is available for the given keygrip */ int gpgsm_agent_havekey (ctrl_t ctrl, const char *hexkeygrip) { int rc; char line[ASSUAN_LINELENGTH]; rc = start_agent (ctrl); if (rc) return rc; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); snprintf (line, DIM(line), "HAVEKEY %s", hexkeygrip); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); return rc; } static gpg_error_t learn_status_cb (void *opaque, const char *line) { struct learn_parm_s *parm = opaque; const char *s; /* Pass progress data to the caller. */ if ((s = has_leading_keyword (line, "PROGRESS"))) { line = s; if (parm->ctrl) { if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, line)) return gpg_error (GPG_ERR_ASS_CANCELED); } } return 0; } static gpg_error_t learn_cb (void *opaque, const void *buffer, size_t length) { struct learn_parm_s *parm = opaque; size_t len; char *buf; ksba_cert_t cert; int rc; if (parm->error) return 0; if (buffer) { put_membuf (parm->data, buffer, length); return 0; } /* END encountered - process what we have */ buf = get_membuf (parm->data, &len); if (!buf) { parm->error = gpg_error (GPG_ERR_ENOMEM); return 0; } if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, "learncard C 0 0")) return gpg_error (GPG_ERR_ASS_CANCELED); /* FIXME: this should go into import.c */ rc = ksba_cert_new (&cert); if (rc) { parm->error = rc; return 0; } rc = ksba_cert_init_from_mem (cert, buf, len); if (rc) { log_error ("failed to parse a certificate: %s\n", gpg_strerror (rc)); ksba_cert_release (cert); parm->error = rc; return 0; } /* We do not store a certifciate with missing issuers as ephemeral because we can assume that the --learn-card command has been used on purpose. */ rc = gpgsm_basic_cert_check (parm->ctrl, cert); if (rc && gpg_err_code (rc) != GPG_ERR_MISSING_CERT && gpg_err_code (rc) != GPG_ERR_MISSING_ISSUER_CERT) log_error ("invalid certificate: %s\n", gpg_strerror (rc)); else { int existed; if (!keydb_store_cert (parm->ctrl, cert, 0, &existed)) { if (opt.verbose > 1 && existed) log_info ("certificate already in DB\n"); else if (opt.verbose && !existed) log_info ("certificate imported\n"); } } ksba_cert_release (cert); init_membuf (parm->data, 4096); return 0; } /* Call the agent to learn about a smartcard */ int gpgsm_agent_learn (ctrl_t ctrl) { int rc; struct learn_parm_s learn_parm; membuf_t data; size_t len; rc = start_agent (ctrl); if (rc) return rc; rc = warn_version_mismatch (ctrl, agent_ctx, SCDAEMON_NAME, 2); if (rc) return rc; init_membuf (&data, 4096); learn_parm.error = 0; learn_parm.ctrl = ctrl; learn_parm.ctx = agent_ctx; learn_parm.data = &data; rc = assuan_transact (agent_ctx, "LEARN --send", learn_cb, &learn_parm, NULL, NULL, learn_status_cb, &learn_parm); xfree (get_membuf (&data, &len)); if (rc) return rc; return learn_parm.error; } /* Ask the agent to change the passphrase of the key identified by HEXKEYGRIP. If DESC is not NULL, display instead of the default description message. */ int gpgsm_agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (rc) return rc; } snprintf (line, DIM(line), "PASSWD %s", hexkeygrip); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inq_parm, NULL, NULL); return rc; } /* Ask the agent to pop up a confirmation dialog with the text DESC and an okay and cancel button. */ gpg_error_t gpgsm_agent_get_confirmation (ctrl_t ctrl, const char *desc) { int rc; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; rc = start_agent (ctrl); if (rc) return rc; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; snprintf (line, DIM(line), "GET_CONFIRMATION %s", desc); rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &inq_parm, NULL, NULL); return rc; } /* Return 0 if the agent is alive. This is useful to make sure that an agent has been started. */ gpg_error_t gpgsm_agent_send_nop (ctrl_t ctrl) { int rc; rc = start_agent (ctrl); if (!rc) rc = assuan_transact (agent_ctx, "NOP", NULL, NULL, NULL, NULL, NULL, NULL); return rc; } static gpg_error_t keyinfo_status_cb (void *opaque, const char *line) { char **serialno = opaque; const char *s, *s2; if ((s = has_leading_keyword (line, "KEYINFO")) && !*serialno) { s = strchr (s, ' '); if (s && s[1] == 'T' && s[2] == ' ' && s[3]) { s += 3; s2 = strchr (s, ' '); if ( s2 > s ) { *serialno = xtrymalloc ((s2 - s)+1); if (*serialno) { memcpy (*serialno, s, s2 - s); (*serialno)[s2 - s] = 0; } } } } return 0; } /* Return the serial number for a secret key. If the returned serial number is NULL, the key is not stored on a smartcard. Caller needs to free R_SERIALNO. */ gpg_error_t gpgsm_agent_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *serialno = NULL; *r_serialno = NULL; err = start_agent (ctrl); if (err) return err; if (!hexkeygrip || strlen (hexkeygrip) != 40) return gpg_error (GPG_ERR_INV_VALUE); snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, keyinfo_status_cb, &serialno); if (!err && serialno) { /* Sanity check for bad characters. */ if (strpbrk (serialno, ":\n\r")) err = GPG_ERR_INV_VALUE; } if (err) xfree (serialno); else *r_serialno = serialno; return err; } /* Ask for the passphrase (this is used for pkcs#12 import/export. On success the caller needs to free the string stored at R_PASSPHRASE. On error NULL will be stored at R_PASSPHRASE and an appropriate error code returned. If REPEAT is true the agent tries to get a new passphrase (i.e. asks the user to confirm it). */ gpg_error_t gpgsm_agent_ask_passphrase (ctrl_t ctrl, const char *desc_msg, int repeat, char **r_passphrase) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char *arg4 = NULL; membuf_t data; struct default_inq_parm_s inq_parm; *r_passphrase = NULL; err = start_agent (ctrl); if (err) return err; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; if (desc_msg && *desc_msg && !(arg4 = percent_plus_escape (desc_msg))) return gpg_error_from_syserror (); snprintf (line, DIM(line), "GET_PASSPHRASE --data%s -- X X X %s", repeat? " --repeat=1 --check":"", arg4); xfree (arg4); init_membuf_secure (&data, 64); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (err) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); *r_passphrase = get_membuf (&data, NULL); if (!*r_passphrase) err = gpg_error_from_syserror (); } return err; } /* Retrieve a key encryption key from the agent. With FOREXPORT true the key shall be use for export, with false for import. On success the new key is stored at R_KEY and its length at R_KEKLEN. */ gpg_error_t gpgsm_agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; *r_kek = NULL; err = start_agent (ctrl); if (err) return err; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; snprintf (line, DIM(line), "KEYWRAP_KEY %s", forexport? "--export":"--import"); init_membuf_secure (&data, 64); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_kek = buf; *r_keklen = len; return 0; } /* Handle the inquiry for an IMPORT_KEY command. */ static gpg_error_t inq_import_key_parms (void *opaque, const char *line) { struct import_key_parm_s *parm = opaque; gpg_error_t err; if (has_leading_keyword (line, "KEYDATA")) { assuan_begin_confidential (parm->ctx); err = assuan_send_data (parm->ctx, parm->key, parm->keylen); assuan_end_confidential (parm->ctx); } else { struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx }; err = default_inq_cb (&inq_parm, line); } return err; } /* Call the agent to import a key into the agent. */ gpg_error_t gpgsm_agent_import_key (ctrl_t ctrl, const void *key, size_t keylen) { gpg_error_t err; struct import_key_parm_s parm; gnupg_isotime_t timebuf; char line[ASSUAN_LINELENGTH]; err = start_agent (ctrl); if (err) return err; parm.ctrl = ctrl; parm.ctx = agent_ctx; parm.key = key; parm.keylen = keylen; gnupg_get_isotime (timebuf); snprintf (line, sizeof line, "IMPORT_KEY --timestamp=%s", timebuf); err = assuan_transact (agent_ctx, line, NULL, NULL, inq_import_key_parms, &parm, NULL, NULL); return err; } /* Receive a secret key from the agent. KEYGRIP is the hexified keygrip, DESC a prompt to be displayed with the agent's passphrase question (needs to be plus+percent escaped). On success the key is stored as a canonical S-expression at R_RESULT and R_RESULTLEN. */ gpg_error_t gpgsm_agent_export_key (ctrl_t ctrl, const char *keygrip, const char *desc, unsigned char **r_result, size_t *r_resultlen) { gpg_error_t err; membuf_t data; size_t len; unsigned char *buf; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s inq_parm; *r_result = NULL; err = start_agent (ctrl); if (err) return err; inq_parm.ctrl = ctrl; inq_parm.ctx = agent_ctx; if (desc) { snprintf (line, DIM(line), "SETKEYDESC %s", desc); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) return err; } snprintf (line, DIM(line), "EXPORT_KEY %s", keygrip); init_membuf_secure (&data, 1024); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &inq_parm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &len); if (!buf) return gpg_error_from_syserror (); *r_result = buf; *r_resultlen = len; return 0; } diff --git a/sm/call-dirmngr.c b/sm/call-dirmngr.c index c9ec8f1e7..7619f60df 100644 --- a/sm/call-dirmngr.c +++ b/sm/call-dirmngr.c @@ -1,1068 +1,1038 @@ /* call-dirmngr.c - Communication with the dirmngr * Copyright (C) 2002, 2003, 2005, 2007, 2008, * 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include "gpgsm.h" #include #include #include "../common/i18n.h" #include "keydb.h" #include "../common/asshelp.h" struct membuf { size_t len; size_t size; char *buf; int out_of_core; }; /* fixme: We need a context for each thread or serialize the access to the dirmngr. */ static assuan_context_t dirmngr_ctx = NULL; static assuan_context_t dirmngr2_ctx = NULL; static int dirmngr_ctx_locked; static int dirmngr2_ctx_locked; struct inq_certificate_parm_s { ctrl_t ctrl; assuan_context_t ctx; ksba_cert_t cert; ksba_cert_t issuer_cert; }; struct isvalid_status_parm_s { ctrl_t ctrl; int seen; unsigned char fpr[20]; }; struct lookup_parm_s { ctrl_t ctrl; assuan_context_t ctx; void (*cb)(void *, ksba_cert_t); void *cb_value; struct membuf data; int error; }; struct run_command_parm_s { ctrl_t ctrl; assuan_context_t ctx; }; static gpg_error_t get_cached_cert (assuan_context_t ctx, const unsigned char *fpr, ksba_cert_t *r_cert); /* A simple implementation of a dynamic buffer. Use init_membuf() to create a buffer, put_membuf to append bytes and get_membuf to release and return the buffer. Allocation errors are detected but only returned at the final get_membuf(), this helps not to clutter the code with out of core checks. */ static void init_membuf (struct membuf *mb, int initiallen) { mb->len = 0; mb->size = initiallen; mb->out_of_core = 0; mb->buf = xtrymalloc (initiallen); if (!mb->buf) mb->out_of_core = 1; } static void put_membuf (struct membuf *mb, const void *buf, size_t len) { if (mb->out_of_core) return; if (mb->len + len >= mb->size) { char *p; mb->size += len + 1024; p = xtryrealloc (mb->buf, mb->size); if (!p) { mb->out_of_core = 1; return; } mb->buf = p; } memcpy (mb->buf + mb->len, buf, len); mb->len += len; } static void * get_membuf (struct membuf *mb, size_t *len) { char *p; if (mb->out_of_core) { xfree (mb->buf); mb->buf = NULL; return NULL; } p = mb->buf; *len = mb->len; mb->buf = NULL; mb->out_of_core = 1; /* don't allow a reuse */ return p; } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (ctrl_t ctrl, assuan_context_t ctx, const char *servername, int mode) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, mode, &serverversion); - if (err) - log_error (_("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - gpgsm_status2 (ctrl, STATUS_WARNING, "server_version_mismatch 0", - warn, NULL); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, mode, + gpgsm_status2, ctrl, + !opt.quiet); } /* This function prepares the dirmngr for a new session. The audit-events option is used so that other dirmngr clients won't get disturbed by such events. */ static void prepare_dirmngr (ctrl_t ctrl, assuan_context_t ctx, gpg_error_t err) { struct keyserver_spec *server; if (!err) err = warn_version_mismatch (ctrl, ctx, DIRMNGR_NAME, 0); if (!err) { err = assuan_transact (ctx, "OPTION audit-events=1", NULL, NULL, NULL, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Allow the use of old dirmngr versions. */ } audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); if (!ctx || err) return; server = opt.keyserver; while (server) { char line[ASSUAN_LINELENGTH]; char *user = server->user ? server->user : ""; char *pass = server->pass ? server->pass : ""; char *base = server->base ? server->base : ""; snprintf (line, DIM (line), "LDAPSERVER %s:%i:%s:%s:%s:%s", server->host, server->port, user, pass, base, server->use_ldaps? "ldaps":""); assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); /* The code below is not required because we don't return an error. */ /* err = [above call] */ /* if (gpg_err_code (err) == GPG_ERR_ASS_UNKNOWN_CMD) */ /* err = 0; /\* Allow the use of old dirmngr versions. *\/ */ server = server->next; } } /* Return a new assuan context for a Dirmngr connection. */ static gpg_error_t start_dirmngr_ext (ctrl_t ctrl, assuan_context_t *ctx_r) { gpg_error_t err; assuan_context_t ctx; if (opt.disable_dirmngr || ctrl->offline) return gpg_error (GPG_ERR_NO_DIRMNGR); if (*ctx_r) return 0; /* Note: if you change this to multiple connections, you also need to take care of the implicit option sending caching. */ err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, opt.verbose, DBG_IPC, gpgsm_status2, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR) { static int shown; if (!shown) { shown = 1; log_info (_("no dirmngr running in this session\n")); } } prepare_dirmngr (ctrl, ctx, err); if (err) return err; *ctx_r = ctx; return 0; } static int start_dirmngr (ctrl_t ctrl) { gpg_error_t err; log_assert (! dirmngr_ctx_locked); dirmngr_ctx_locked = 1; err = start_dirmngr_ext (ctrl, &dirmngr_ctx); /* We do not check ERR but the existence of a context because the error might come from a failed command send to the dirmngr. Fixme: Why don't we close the drimngr context if we encountered an error in prepare_dirmngr? */ if (!dirmngr_ctx) dirmngr_ctx_locked = 0; return err; } static void release_dirmngr (ctrl_t ctrl) { (void)ctrl; if (!dirmngr_ctx_locked) log_error ("WARNING: trying to release a non-locked dirmngr ctx\n"); dirmngr_ctx_locked = 0; } static int start_dirmngr2 (ctrl_t ctrl) { gpg_error_t err; log_assert (! dirmngr2_ctx_locked); dirmngr2_ctx_locked = 1; err = start_dirmngr_ext (ctrl, &dirmngr2_ctx); if (!dirmngr2_ctx) dirmngr2_ctx_locked = 0; return err; } static void release_dirmngr2 (ctrl_t ctrl) { (void)ctrl; if (!dirmngr2_ctx_locked) log_error ("WARNING: trying to release a non-locked dirmngr2 ctx\n"); dirmngr2_ctx_locked = 0; } /* Handle a SENDCERT inquiry. */ static gpg_error_t inq_certificate (void *opaque, const char *line) { struct inq_certificate_parm_s *parm = opaque; const char *s; int rc; size_t n; const unsigned char *der; size_t derlen; int issuer_mode = 0; ksba_sexp_t ski = NULL; if ((s = has_leading_keyword (line, "SENDCERT"))) { line = s; } else if ((s = has_leading_keyword (line, "SENDCERT_SKI"))) { /* Send a certificate where a sourceKeyIdentifier is included. */ line = s; ski = make_simple_sexp_from_hexstr (line, &n); line += n; while (*line == ' ') line++; } else if ((s = has_leading_keyword (line, "SENDISSUERCERT"))) { line = s; issuer_mode = 1; } else if ((s = has_leading_keyword (line, "ISTRUSTED"))) { /* The server is asking us whether the certificate is a trusted root certificate. */ char fpr[41]; struct rootca_flags_s rootca_flags; line = s; for (s=line,n=0; hexdigitp (s); s++, n++) ; if (*s || n != 40) return gpg_error (GPG_ERR_ASS_PARAMETER); for (s=line, n=0; n < 40; s++, n++) fpr[n] = (*s >= 'a')? (*s & 0xdf): *s; fpr[n] = 0; if (!gpgsm_agent_istrusted (parm->ctrl, NULL, fpr, &rootca_flags)) rc = assuan_send_data (parm->ctx, "1", 1); else rc = 0; return rc; } else { log_error ("unsupported inquiry '%s'\n", line); return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); } if (!*line) { /* Send the current certificate. */ der = ksba_cert_get_image (issuer_mode? parm->issuer_cert : parm->cert, &derlen); if (!der) rc = gpg_error (GPG_ERR_INV_CERT_OBJ); else rc = assuan_send_data (parm->ctx, der, derlen); } else if (issuer_mode) { log_error ("sending specific issuer certificate back " "is not yet implemented\n"); rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); } else { /* Send the given certificate. */ int err; ksba_cert_t cert; err = gpgsm_find_cert (parm->ctrl, line, ski, &cert, 1); if (err) { log_error ("certificate not found: %s\n", gpg_strerror (err)); rc = gpg_error (GPG_ERR_NOT_FOUND); } else { der = ksba_cert_get_image (cert, &derlen); if (!der) rc = gpg_error (GPG_ERR_INV_CERT_OBJ); else rc = assuan_send_data (parm->ctx, der, derlen); ksba_cert_release (cert); } } xfree (ski); return rc; } /* Take a 20 byte hexencoded string and put it into the provided 20 byte buffer FPR in binary format. */ static int unhexify_fpr (const char *hexstr, unsigned char *fpr) { const char *s; int n; for (s=hexstr, n=0; hexdigitp (s); s++, n++) ; if (*s || (n != 40)) return 0; /* no fingerprint (invalid or wrong length). */ for (s=hexstr, n=0; *s; s += 2, n++) fpr[n] = xtoi_2 (s); return 1; /* okay */ } static gpg_error_t isvalid_status_cb (void *opaque, const char *line) { struct isvalid_status_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "PROGRESS"))) { if (parm->ctrl) { line = s; if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, line)) return gpg_error (GPG_ERR_ASS_CANCELED); } } else if ((s = has_leading_keyword (line, "ONLY_VALID_IF_CERT_VALID"))) { parm->seen++; if (!*s || !unhexify_fpr (s, parm->fpr)) parm->seen++; /* Bump it to indicate an error. */ } return 0; } /* Call the directory manager to check whether the certificate is valid Returns 0 for valid or usually one of the errors: GPG_ERR_CERTIFICATE_REVOKED GPG_ERR_NO_CRL_KNOWN GPG_ERR_CRL_TOO_OLD Values for USE_OCSP: 0 = Do CRL check. 1 = Do an OCSP check but fallback to CRL unless CRLS are disabled. 2 = Do only an OCSP check using only the default responder. */ int gpgsm_dirmngr_isvalid (ctrl_t ctrl, ksba_cert_t cert, ksba_cert_t issuer_cert, int use_ocsp) { static int did_options; int rc; char *certid, *certfpr; char line[ASSUAN_LINELENGTH]; struct inq_certificate_parm_s parm; struct isvalid_status_parm_s stparm; rc = start_dirmngr (ctrl); if (rc) return rc; certfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); certid = gpgsm_get_certid (cert); if (!certid) { log_error ("error getting the certificate ID\n"); release_dirmngr (ctrl); return gpg_error (GPG_ERR_GENERAL); } if (opt.verbose > 1) { char *fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1); log_info ("asking dirmngr about %s%s\n", fpr, use_ocsp? " (using OCSP)":""); xfree (fpr); } parm.ctx = dirmngr_ctx; parm.ctrl = ctrl; parm.cert = cert; parm.issuer_cert = issuer_cert; stparm.ctrl = ctrl; stparm.seen = 0; memset (stparm.fpr, 0, 20); /* It is sufficient to send the options only once because we have * one connection per process only. */ if (!did_options) { if (opt.force_crl_refresh) assuan_transact (dirmngr_ctx, "OPTION force-crl-refresh=1", NULL, NULL, NULL, NULL, NULL, NULL); did_options = 1; } snprintf (line, DIM(line), "ISVALID%s%s %s%s%s", use_ocsp == 2 || opt.no_crl_check ? " --only-ocsp":"", use_ocsp == 2? " --force-default-responder":"", certid, use_ocsp? " ":"", use_ocsp? certfpr:""); xfree (certid); xfree (certfpr); rc = assuan_transact (dirmngr_ctx, line, NULL, NULL, inq_certificate, &parm, isvalid_status_cb, &stparm); if (opt.verbose > 1) log_info ("response of dirmngr: %s\n", rc? gpg_strerror (rc): "okay"); if (!rc && stparm.seen) { /* Need to also check the certificate validity. */ if (stparm.seen != 1) { log_error ("communication problem with dirmngr detected\n"); rc = gpg_error (GPG_ERR_INV_CRL); } else { ksba_cert_t rspcert = NULL; if (get_cached_cert (dirmngr_ctx, stparm.fpr, &rspcert)) { /* Ooops: Something went wrong getting the certificate from the dirmngr. Try our own cert store now. */ KEYDB_HANDLE kh; kh = keydb_new (); if (!kh) rc = gpg_error (GPG_ERR_ENOMEM); if (!rc) rc = keydb_search_fpr (ctrl, kh, stparm.fpr); if (!rc) rc = keydb_get_cert (kh, &rspcert); if (rc) { log_error ("unable to find the certificate used " "by the dirmngr: %s\n", gpg_strerror (rc)); rc = gpg_error (GPG_ERR_INV_CRL); } keydb_release (kh); } if (!rc) { rc = gpgsm_cert_use_ocsp_p (rspcert); if (rc) rc = gpg_error (GPG_ERR_INV_CRL); else { /* Note the no_dirmngr flag: This avoids checking this certificate over and over again. */ rc = gpgsm_validate_chain (ctrl, rspcert, "", NULL, 0, NULL, VALIDATE_FLAG_NO_DIRMNGR, NULL); if (rc) { log_error ("invalid certificate used for CRL/OCSP: %s\n", gpg_strerror (rc)); rc = gpg_error (GPG_ERR_INV_CRL); } } } ksba_cert_release (rspcert); } } release_dirmngr (ctrl); return rc; } /* Lookup helpers*/ static gpg_error_t lookup_cb (void *opaque, const void *buffer, size_t length) { struct lookup_parm_s *parm = opaque; size_t len; char *buf; ksba_cert_t cert; int rc; if (parm->error) return 0; if (buffer) { put_membuf (&parm->data, buffer, length); return 0; } /* END encountered - process what we have */ buf = get_membuf (&parm->data, &len); if (!buf) { parm->error = gpg_error (GPG_ERR_ENOMEM); return 0; } rc = ksba_cert_new (&cert); if (rc) { parm->error = rc; return 0; } rc = ksba_cert_init_from_mem (cert, buf, len); if (rc) { log_error ("failed to parse a certificate: %s\n", gpg_strerror (rc)); } else { parm->cb (parm->cb_value, cert); } ksba_cert_release (cert); init_membuf (&parm->data, 4096); return 0; } /* Return a properly escaped pattern from NAMES. The only error return is NULL to indicate a malloc failure. */ static char * pattern_from_strlist (strlist_t names) { strlist_t sl; int n; const char *s; char *pattern, *p; for (n=0, sl=names; sl; sl = sl->next) { for (s=sl->d; *s; s++, n++) { if (*s == '%' || *s == ' ' || *s == '+') n += 2; } n++; } p = pattern = xtrymalloc (n+1); if (!pattern) return NULL; for (sl=names; sl; sl = sl->next) { for (s=sl->d; *s; s++) { switch (*s) { case '%': *p++ = '%'; *p++ = '2'; *p++ = '5'; break; case ' ': *p++ = '%'; *p++ = '2'; *p++ = '0'; break; case '+': *p++ = '%'; *p++ = '2'; *p++ = 'B'; break; default: *p++ = *s; break; } } *p++ = ' '; } if (p == pattern) *pattern = 0; /* is empty */ else p[-1] = '\0'; /* remove trailing blank */ return pattern; } static gpg_error_t lookup_status_cb (void *opaque, const char *line) { struct lookup_parm_s *parm = opaque; const char *s; if ((s = has_leading_keyword (line, "PROGRESS"))) { if (parm->ctrl) { line = s; if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, line)) return gpg_error (GPG_ERR_ASS_CANCELED); } } else if ((s = has_leading_keyword (line, "TRUNCATED"))) { if (parm->ctrl) { line = s; gpgsm_status (parm->ctrl, STATUS_TRUNCATED, line); } } return 0; } /* Run the Directory Manager's lookup command using the pattern compiled from the strings given in NAMES or from URI. The caller must provide the callback CB which will be passed cert by cert. Note that CTRL is optional. With CACHE_ONLY the dirmngr will search only its own key cache. */ int gpgsm_dirmngr_lookup (ctrl_t ctrl, strlist_t names, const char *uri, int cache_only, void (*cb)(void*, ksba_cert_t), void *cb_value) { int rc; char line[ASSUAN_LINELENGTH]; struct lookup_parm_s parm; size_t len; assuan_context_t ctx; const char *s; if ((names && uri) || (!names && !uri)) return gpg_error (GPG_ERR_INV_ARG); /* The lookup function can be invoked from the callback of a lookup function, for example to walk the chain. */ if (!dirmngr_ctx_locked) { rc = start_dirmngr (ctrl); if (rc) return rc; ctx = dirmngr_ctx; } else if (!dirmngr2_ctx_locked) { rc = start_dirmngr2 (ctrl); if (rc) return rc; ctx = dirmngr2_ctx; } else { log_fatal ("both dirmngr contexts are in use\n"); } if (names) { char *pattern = pattern_from_strlist (names); if (!pattern) { if (ctx == dirmngr_ctx) release_dirmngr (ctrl); else release_dirmngr2 (ctrl); return out_of_core (); } snprintf (line, DIM(line), "LOOKUP%s %s", cache_only? " --cache-only":"", pattern); xfree (pattern); } else { for (s=uri; *s; s++) if (*s <= ' ') { if (ctx == dirmngr_ctx) release_dirmngr (ctrl); else release_dirmngr2 (ctrl); return gpg_error (GPG_ERR_INV_URI); } snprintf (line, DIM(line), "LOOKUP --url %s", uri); } parm.ctrl = ctrl; parm.ctx = ctx; parm.cb = cb; parm.cb_value = cb_value; parm.error = 0; init_membuf (&parm.data, 4096); rc = assuan_transact (ctx, line, lookup_cb, &parm, NULL, NULL, lookup_status_cb, &parm); xfree (get_membuf (&parm.data, &len)); if (ctx == dirmngr_ctx) release_dirmngr (ctrl); else release_dirmngr2 (ctrl); if (rc) return rc; return parm.error; } static gpg_error_t get_cached_cert_data_cb (void *opaque, const void *buffer, size_t length) { struct membuf *mb = opaque; if (buffer) put_membuf (mb, buffer, length); return 0; } /* Return a certificate from the Directory Manager's cache. This function only returns one certificate which must be specified using the fingerprint FPR and will be stored at R_CERT. On error NULL is stored at R_CERT and an error code returned. Note that the caller must provide the locked dirmngr context CTX. */ static gpg_error_t get_cached_cert (assuan_context_t ctx, const unsigned char *fpr, ksba_cert_t *r_cert) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; char hexfpr[2*20+1]; struct membuf mb; char *buf; size_t buflen = 0; ksba_cert_t cert; *r_cert = NULL; bin2hex (fpr, 20, hexfpr); snprintf (line, DIM(line), "LOOKUP --single --cache-only 0x%s", hexfpr); init_membuf (&mb, 4096); err = assuan_transact (ctx, line, get_cached_cert_data_cb, &mb, NULL, NULL, NULL, NULL); buf = get_membuf (&mb, &buflen); if (err) { xfree (buf); return err; } if (!buf) return gpg_error (GPG_ERR_ENOMEM); err = ksba_cert_new (&cert); if (err) { xfree (buf); return err; } err = ksba_cert_init_from_mem (cert, buf, buflen); xfree (buf); if (err) { log_error ("failed to parse a certificate: %s\n", gpg_strerror (err)); ksba_cert_release (cert); return err; } *r_cert = cert; return 0; } /* Run Command helpers*/ /* Fairly simple callback to write all output of dirmngr to stdout. */ static gpg_error_t run_command_cb (void *opaque, const void *buffer, size_t length) { (void)opaque; if (buffer) { if ( fwrite (buffer, length, 1, stdout) != 1 ) log_error ("error writing to stdout: %s\n", strerror (errno)); } return 0; } /* Handle inquiries from the dirmngr COMMAND. */ static gpg_error_t run_command_inq_cb (void *opaque, const char *line) { struct run_command_parm_s *parm = opaque; const char *s; int rc = 0; if ((s = has_leading_keyword (line, "SENDCERT"))) { /* send the given certificate */ int err; ksba_cert_t cert; const unsigned char *der; size_t derlen; line = s; if (!*line) return gpg_error (GPG_ERR_ASS_PARAMETER); err = gpgsm_find_cert (parm->ctrl, line, NULL, &cert, 1); if (err) { log_error ("certificate not found: %s\n", gpg_strerror (err)); rc = gpg_error (GPG_ERR_NOT_FOUND); } else { der = ksba_cert_get_image (cert, &derlen); if (!der) rc = gpg_error (GPG_ERR_INV_CERT_OBJ); else rc = assuan_send_data (parm->ctx, der, derlen); ksba_cert_release (cert); } } else if ((s = has_leading_keyword (line, "PRINTINFO"))) { /* Simply show the message given in the argument. */ line = s; log_info ("dirmngr: %s\n", line); } else { log_error ("unsupported inquiry '%s'\n", line); rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); } return rc; } static gpg_error_t run_command_status_cb (void *opaque, const char *line) { ctrl_t ctrl = opaque; const char *s; if (opt.verbose) { log_info ("dirmngr status: %s\n", line); } if ((s = has_leading_keyword (line, "PROGRESS"))) { if (ctrl) { line = s; if (gpgsm_status (ctrl, STATUS_PROGRESS, line)) return gpg_error (GPG_ERR_ASS_CANCELED); } } return 0; } /* Pass COMMAND to dirmngr and print all output generated by Dirmngr to stdout. A couple of inquiries are defined (see above). ARGC arguments in ARGV are given to the Dirmngr. Spaces, plus and percent characters within the argument strings are percent escaped so that blanks can act as delimiters. */ int gpgsm_dirmngr_run_command (ctrl_t ctrl, const char *command, int argc, char **argv) { int rc; int i; const char *s; char *line, *p; size_t len; struct run_command_parm_s parm; rc = start_dirmngr (ctrl); if (rc) return rc; parm.ctrl = ctrl; parm.ctx = dirmngr_ctx; len = strlen (command) + 1; for (i=0; i < argc; i++) len += 1 + 3*strlen (argv[i]); /* enough space for percent escaping */ line = xtrymalloc (len); if (!line) { release_dirmngr (ctrl); return out_of_core (); } p = stpcpy (line, command); for (i=0; i < argc; i++) { *p++ = ' '; for (s=argv[i]; *s; s++) { if (!isascii (*s)) *p++ = *s; else if (*s == ' ') *p++ = '+'; else if (!isprint (*s) || *s == '+') { sprintf (p, "%%%02X", *(const unsigned char *)s); p += 3; } else *p++ = *s; } } *p = 0; rc = assuan_transact (dirmngr_ctx, line, run_command_cb, NULL, run_command_inq_cb, &parm, run_command_status_cb, ctrl); xfree (line); log_info ("response of dirmngr: %s\n", rc? gpg_strerror (rc): "okay"); release_dirmngr (ctrl); return rc; } diff --git a/tools/card-call-scd.c b/tools/card-call-scd.c index 160d9480e..8800c5b52 100644 --- a/tools/card-call-scd.c +++ b/tools/card-call-scd.c @@ -1,1691 +1,1659 @@ /* card-call-scd.c - IPC calls to scdaemon. * Copyright (C) 2019, 2020 g10 Code GmbH * Copyright (C) 2001-2003, 2006-2011, 2013 Free Software Foundation, Inc. * Copyright (C) 2013-2015 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "../common/util.h" #include "../common/membuf.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "../common/status.h" #include "../common/host2net.h" #include "../common/openpgpdefs.h" #include "gpg-card.h" #define CONTROL_D ('D' - 'A' + 1) #define START_AGENT_NO_STARTUP_CMDS 1 #define START_AGENT_SUPPRESS_ERRORS 2 struct default_inq_parm_s { assuan_context_t ctx; struct { u32 *keyid; u32 *mainkeyid; int pubkey_algo; } keyinfo; }; struct cipher_parm_s { struct default_inq_parm_s *dflt; assuan_context_t ctx; unsigned char *ciphertext; size_t ciphertextlen; }; struct writecert_parm_s { struct default_inq_parm_s *dflt; const unsigned char *certdata; size_t certdatalen; }; struct writekey_parm_s { struct default_inq_parm_s *dflt; const unsigned char *keydata; size_t keydatalen; }; struct genkey_parm_s { struct default_inq_parm_s *dflt; const char *keyparms; const char *passphrase; }; struct card_cardlist_parm_s { gpg_error_t error; int with_apps; strlist_t list; }; struct import_key_parm_s { struct default_inq_parm_s *dflt; const void *key; size_t keylen; }; struct cache_nonce_parm_s { char **cache_nonce_addr; char **passwd_nonce_addr; }; /* * File local variables */ /* The established context to the agent. Note that all calls to * scdaemon are routed via the agent and thus we only need to care * about the IPC with the agent. */ static assuan_context_t agent_ctx; /* * Local prototypes */ static gpg_error_t learn_status_cb (void *opaque, const char *line); /* Release the card info structure INFO. */ void release_card_info (card_info_t info) { int i; if (!info) return; xfree (info->reader); info->reader = NULL; xfree (info->cardtype); info->cardtype = NULL; xfree (info->manufacturer_name); info->manufacturer_name = NULL; xfree (info->serialno); info->serialno = NULL; xfree (info->dispserialno); info->dispserialno = NULL; xfree (info->apptypestr); info->apptypestr = NULL; info->apptype = APP_TYPE_NONE; xfree (info->disp_name); info->disp_name = NULL; xfree (info->disp_lang); info->disp_lang = NULL; xfree (info->pubkey_url); info->pubkey_url = NULL; xfree (info->login_data); info->login_data = NULL; info->cafpr1len = info->cafpr2len = info->cafpr3len = 0; for (i=0; i < DIM(info->private_do); i++) { xfree (info->private_do[i]); info->private_do[i] = NULL; } while (info->kinfo) { key_info_t kinfo = info->kinfo->next; xfree (info->kinfo); info->kinfo = kinfo; } info->chvusage[0] = info->chvusage[1] = 0; } /* Map an application type string to an integer. */ static app_type_t map_apptypestr (const char *string) { app_type_t result; if (!string) result = APP_TYPE_NONE; else if (!ascii_strcasecmp (string, "OPENPGP")) result = APP_TYPE_OPENPGP; else if (!ascii_strcasecmp (string, "NKS")) result = APP_TYPE_NKS; else if (!ascii_strcasecmp (string, "DINSIG")) result = APP_TYPE_DINSIG; else if (!ascii_strcasecmp (string, "P15")) result = APP_TYPE_P15; else if (!ascii_strcasecmp (string, "GELDKARTE")) result = APP_TYPE_GELDKARTE; else if (!ascii_strcasecmp (string, "SC-HSM")) result = APP_TYPE_SC_HSM; else if (!ascii_strcasecmp (string, "PIV")) result = APP_TYPE_PIV; else result = APP_TYPE_UNKNOWN; return result; } /* Return a string representation of the application type. */ const char * app_type_string (app_type_t app_type) { const char *result = "?"; switch (app_type) { case APP_TYPE_NONE: result = "None"; break; case APP_TYPE_OPENPGP: result = "OpenPGP"; break; case APP_TYPE_NKS: result = "NetKey"; break; case APP_TYPE_DINSIG: result = "DINSIG"; break; case APP_TYPE_P15: result = "P15"; break; case APP_TYPE_GELDKARTE: result = "Geldkarte"; break; case APP_TYPE_SC_HSM: result = "SC-HSM"; break; case APP_TYPE_PIV: result = "PIV"; break; case APP_TYPE_UNKNOWN: result = "Unknown"; break; } return result; } /* If RC is not 0, write an appropriate status message. */ static gpg_error_t status_sc_op_failure (gpg_error_t err) { switch (gpg_err_code (err)) { case 0: break; case GPG_ERR_CANCELED: case GPG_ERR_FULLY_CANCELED: gnupg_status_printf (STATUS_SC_OP_FAILURE, "1"); break; case GPG_ERR_BAD_PIN: gnupg_status_printf (STATUS_SC_OP_FAILURE, "2"); break; default: gnupg_status_printf (STATUS_SC_OP_FAILURE, NULL); break; } return err; } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct default_inq_parm_s *parm = opaque; (void)parm; if (has_leading_keyword (line, "PINENTRY_LAUNCHED")) { /* err = gpg_proxy_pinentry_notify (parm->ctrl, line); */ /* if (err) */ /* log_error (_("failed to proxy %s inquiry to client\n"), */ /* "PINENTRY_LAUNCHED"); */ /* We do not pass errors to avoid breaking other code. */ } else log_debug ("ignoring gpg-agent inquiry '%s'\n", line); return err; } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername, int mode) { - gpg_error_t err; - char *serverversion; - const char *myversion = gpgrt_strusage (13); - - err = get_assuan_server_version (ctx, mode, &serverversion); - if (err) - log_log (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED? - GPGRT_LOGLVL_INFO : GPGRT_LOGLVL_ERROR, - _("error getting version from '%s': %s\n"), - servername, gpg_strerror (err)); - else if (compare_version_strings (serverversion, myversion) < 0) - { - char *warn; - - warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), - servername, serverversion, myversion); - if (!warn) - err = gpg_error_from_syserror (); - else - { - log_info (_("WARNING: %s\n"), warn); - if (!opt.quiet) - { - log_info (_("Note: Outdated servers may lack important" - " security fixes.\n")); - log_info (_("Note: Use the command \"%s\" to restart them.\n"), - "gpgconf --kill all"); - } - gnupg_status_printf (STATUS_WARNING, "server_version_mismatch 0 %s", - warn); - xfree (warn); - } - } - xfree (serverversion); - return err; + return warn_server_version_mismatch (ctx, servername, mode, + gnupg_status_strings, NULL, + !opt.quiet); } /* Try to connect to the agent via socket or fork it off and work by * pipes. Handle the server's initial greeting. */ static gpg_error_t start_agent (unsigned int flags) { gpg_error_t err; int started = 0; if (agent_ctx) err = 0; else { started = 1; err = start_new_gpg_agent (&agent_ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, opt.lc_ctype, opt.lc_messages, opt.session_env, opt.autostart, opt.verbose, DBG_IPC, NULL, NULL); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_AGENT) { static int shown; if (!shown) { shown = 1; log_info (_("no gpg-agent running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (agent_ctx, GPG_AGENT_NAME, 0))) { /* Tell the agent that we support Pinentry notifications. No error checking so that it will work also with older agents. */ assuan_transact (agent_ctx, "OPTION allow-pinentry-notify", NULL, NULL, NULL, NULL, NULL, NULL); /* Tell the agent about what version we are aware. This is here used to indirectly enable GPG_ERR_FULLY_CANCELED. */ assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0", NULL, NULL, NULL, NULL, NULL, NULL); } } if (started && !err && !(flags & START_AGENT_NO_STARTUP_CMDS)) { /* Request the serial number of the card for an early test. */ struct card_info_s info; memset (&info, 0, sizeof info); if (!(flags & START_AGENT_SUPPRESS_ERRORS)) err = warn_version_mismatch (agent_ctx, SCDAEMON_NAME, 2); if (!err) err = assuan_transact (agent_ctx, "SCD SERIALNO --all", NULL, NULL, NULL, NULL, learn_status_cb, &info); if (err && !(flags & START_AGENT_SUPPRESS_ERRORS)) { switch (gpg_err_code (err)) { case GPG_ERR_NOT_SUPPORTED: case GPG_ERR_NO_SCDAEMON: gnupg_status_printf (STATUS_CARDCTRL, "6"); /* No card support. */ break; case GPG_ERR_OBJ_TERM_STATE: /* Card is in termination state. */ gnupg_status_printf (STATUS_CARDCTRL, "7"); break; default: gnupg_status_printf (STATUS_CARDCTRL, "4"); /* No card. */ break; } } if (!err && info.serialno) gnupg_status_printf (STATUS_CARDCTRL, "3 %s", info.serialno); release_card_info (&info); } return err; } /* Return a new malloced string by unescaping the string S. Escaping * is percent escaping and '+'/space mapping. A binary nul will * silently be replaced by a 0xFF. Function returns NULL to indicate * an out of memory status. */ static char * unescape_status_string (const unsigned char *s) { return percent_plus_unescape (s, 0xff); } /* Take a 20 or 32 byte hexencoded string and put it into the provided * FPRLEN byte long buffer FPR in binary format. Returns the actual * used length of the FPR buffer or 0 on error. */ static unsigned int unhexify_fpr (const char *hexstr, unsigned char *fpr, unsigned int fprlen) { const char *s; int n; for (s=hexstr, n=0; hexdigitp (s); s++, n++) ; if ((*s && *s != ' ') || !(n == 40 || n == 64)) return 0; /* no fingerprint (invalid or wrong length). */ for (s=hexstr, n=0; *s && n < fprlen; s += 2, n++) fpr[n] = xtoi_2 (s); return (n == 20 || n == 32)? n : 0; } /* Take the serial number from LINE and return it verbatim in a newly * allocated string. We make sure that only hex characters are * returned. Returns NULL on error. */ static char * store_serialno (const char *line) { const char *s; char *p; for (s=line; hexdigitp (s); s++) ; p = xtrymalloc (s + 1 - line); if (p) { memcpy (p, line, s-line); p[s-line] = 0; } return p; } /* Send an APDU to the current card. On success the status word is * stored at R_SW inless R_SW is NULL. With HEXAPDU being NULL only a * RESET command is send to scd. With HEXAPDU being the string * "undefined" the command "SERIALNO undefined" is send to scd. If * R_DATA is not NULL the data without the status code is stored * there. Caller must release it. If OPTIONS is not NULL, this will * be passed verbatim to the SCDaemon's APDU command. */ gpg_error_t scd_apdu (const char *hexapdu, const char *options, unsigned int *r_sw, unsigned char **r_data, size_t *r_datalen) { gpg_error_t err; if (r_data) *r_data = NULL; if (r_datalen) *r_datalen = 0; err = start_agent (START_AGENT_NO_STARTUP_CMDS); if (err) return err; if (!hexapdu) { err = assuan_transact (agent_ctx, "SCD RESET", NULL, NULL, NULL, NULL, NULL, NULL); } else if (!strcmp (hexapdu, "undefined")) { err = assuan_transact (agent_ctx, "SCD SERIALNO undefined", NULL, NULL, NULL, NULL, NULL, NULL); } else { char line[ASSUAN_LINELENGTH]; membuf_t mb; unsigned char *data; size_t datalen; int no_sw; init_membuf (&mb, 256); no_sw = (options && (strstr (options, "--dump-atr") || strstr (options, "--data-atr"))); snprintf (line, DIM(line), "SCD APDU %s%s%s", options?options:"", options?" -- ":"", hexapdu); err = assuan_transact (agent_ctx, line, put_membuf_cb, &mb, NULL, NULL, NULL, NULL); if (!err) { data = get_membuf (&mb, &datalen); if (!data) err = gpg_error_from_syserror (); else if (datalen < (no_sw?1:2)) /* Ooops */ err = gpg_error (GPG_ERR_CARD); else { if (r_sw) *r_sw = no_sw? 0 : buf16_to_uint (data+datalen-2); if (r_data && r_datalen) { *r_data = data; *r_datalen = datalen - (no_sw?0:2); data = NULL; } } xfree (data); } } return err; } /* This is a dummy data line callback. */ static gpg_error_t dummy_data_cb (void *opaque, const void *buffer, size_t length) { (void)opaque; (void)buffer; (void)length; return 0; } /* A simple callback used to return the serialnumber of a card. */ static gpg_error_t get_serialno_cb (void *opaque, const char *line) { char **serialno = opaque; const char *keyword = line; const char *s; int keywordlen, n; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; /* FIXME: Should we use has_leading_keyword? */ if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { if (*serialno) return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */ for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1)|| !(spacep (s) || !*s) ) return gpg_error (GPG_ERR_ASS_PARAMETER); *serialno = xtrymalloc (n+1); if (!*serialno) return out_of_core (); memcpy (*serialno, line, n); (*serialno)[n] = 0; } return 0; } /* Make the card with SERIALNO the current one. */ gpg_error_t scd_switchcard (const char *serialno) { int err; char line[ASSUAN_LINELENGTH]; err = start_agent (START_AGENT_SUPPRESS_ERRORS); if (err) return err; snprintf (line, DIM(line), "SCD SWITCHCARD -- %s", serialno); return assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); } /* Make the app APPNAME the one on the card. */ gpg_error_t scd_switchapp (const char *appname) { int err; char line[ASSUAN_LINELENGTH]; if (appname && !*appname) appname = NULL; err = start_agent (START_AGENT_SUPPRESS_ERRORS); if (err) return err; snprintf (line, DIM(line), "SCD SWITCHAPP --%s%s", appname? " ":"", appname? appname:""); return assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); } /* For historical reasons OpenPGP cards simply use the numbers 1 to 3 * for the . Other cards and future versions of * scd/app-openpgp.c may print the full keyref; i.e. "OpenPGP.1" * instead of "1". This is a helper to cope with that. */ static const char * parse_keyref_helper (const char *string) { if (*string == '1' && spacep (string+1)) return "OPENPGP.1"; else if (*string == '2' && spacep (string+1)) return "OPENPGP.2"; else if (*string == '3' && spacep (string+1)) return "OPENPGP.3"; else return string; } /* Create a new key info object with KEYREF. All fields but the * keyref are zeroed out. Never returns NULL. The created object is * appended to the list at INFO. */ static key_info_t create_kinfo (card_info_t info, const char *keyref) { key_info_t kinfo, ki; kinfo = xcalloc (1, sizeof *kinfo + strlen (keyref)); strcpy (kinfo->keyref, keyref); if (!info->kinfo) info->kinfo = kinfo; else { for (ki=info->kinfo; ki->next; ki = ki->next) ; ki->next = kinfo; } return kinfo; } /* The status callback to handle the LEARN and GETATTR commands. */ static gpg_error_t learn_status_cb (void *opaque, const char *line) { struct card_info_s *parm = opaque; const char *keyword = line; int keywordlen; char *line_buffer = NULL; /* In case we need a copy. */ char *pline, *endp; key_info_t kinfo; const char *keyref; int i; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; switch (keywordlen) { case 3: if (!memcmp (keyword, "KDF", 3)) { parm->kdf_do_enabled = 1; } break; case 5: if (!memcmp (keyword, "UIF-", 4) && strchr("123", keyword[4])) { unsigned char *data; int no = keyword[4] - '1'; log_assert (no >= 0 && no <= 2); data = unescape_status_string (line); /* I am not sure why we test for 0xff but we better keep * that in case of bogus card versions which did not * initialize that DO correctly. */ parm->uif[no] = (data[0] == 0xff)? 0 : data[0]; xfree (data); } break; case 6: if (!memcmp (keyword, "READER", keywordlen)) { xfree (parm->reader); parm->reader = unescape_status_string (line); } else if (!memcmp (keyword, "EXTCAP", keywordlen)) { char *p, *p2, *buf; int abool; unsigned long number; buf = p = unescape_status_string (line); if (buf) { for (p = strtok (buf, " "); p; p = strtok (NULL, " ")) { p2 = strchr (p, '='); if (p2) { *p2++ = 0; abool = (*p2 == '1'); if (!strcmp (p, "ki")) parm->extcap.ki = abool; else if (!strcmp (p, "aac")) parm->extcap.aac = abool; else if (!strcmp (p, "bt")) parm->extcap.bt = abool; else if (!strcmp (p, "kdf")) parm->extcap.kdf = abool; else if (!strcmp (p, "si")) parm->status_indicator = strtoul (p2, NULL, 10); else if (!strcmp (p, "pd")) parm->extcap.private_dos = abool; else if (!strcmp (p, "mcl3")) parm->extcap.mcl3 = strtoul (p2, NULL, 10); else if (!strcmp (p, "sm")) { /* Unfortunately this uses OpenPGP algorithm * ids so that we need to map them to Gcrypt * ids. The mapping is limited to what * OpenPGP cards support. Other cards * should use a different tag than "sm". */ parm->extcap.sm = 1; number = strtoul (p2, NULL, 10); switch (number) { case CIPHER_ALGO_3DES: parm->extcap.smalgo = GCRY_CIPHER_3DES; break; case CIPHER_ALGO_AES: parm->extcap.smalgo = GCRY_CIPHER_AES; break; case CIPHER_ALGO_AES192: parm->extcap.smalgo = GCRY_CIPHER_AES192; break; case CIPHER_ALGO_AES256: parm->extcap.smalgo = GCRY_CIPHER_AES256; break; default: /* Unknown algorithm; dont claim SM support. */ parm->extcap.sm = 0; break; } } } } xfree (buf); } } else if (!memcmp (keyword, "CA-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->cafpr1len = unhexify_fpr (line, parm->cafpr1, sizeof parm->cafpr1); else if (no == 2) parm->cafpr2len = unhexify_fpr (line, parm->cafpr2, sizeof parm->cafpr2); else if (no == 3) parm->cafpr3len = unhexify_fpr (line, parm->cafpr3, sizeof parm->cafpr3); } break; case 7: if (!memcmp (keyword, "APPTYPE", keywordlen)) { xfree (parm->apptypestr); parm->apptypestr = unescape_status_string (line); parm->apptype = map_apptypestr (parm->apptypestr); } else if (!memcmp (keyword, "KEY-FPR", keywordlen)) { /* The format of such a line is: * KEY-FPR */ const char *fpr; line_buffer = pline = xstrdup (line); keyref = parse_keyref_helper (pline); while (*pline && !spacep (pline)) pline++; if (*pline) *pline++ = 0; /* Terminate keyref. */ while (spacep (pline)) /* Skip to the fingerprint. */ pline++; fpr = pline; /* Check whether we already have an item for the keyref. */ kinfo = find_kinfo (parm, keyref); if (!kinfo) /* No: new entry. */ kinfo = create_kinfo (parm, keyref); else /* Existing entry - clear the fpr. */ memset (kinfo->fpr, 0, sizeof kinfo->fpr); /* Set or update or the fingerprint. */ kinfo->fprlen = unhexify_fpr (fpr, kinfo->fpr, sizeof kinfo->fpr); } break; case 8: if (!memcmp (keyword, "SERIALNO", keywordlen)) { xfree (parm->serialno); parm->serialno = store_serialno (line); parm->is_v2 = (strlen (parm->serialno) >= 16 && xtoi_2 (parm->serialno+12) >= 2 ); } else if (!memcmp (keyword, "CARDTYPE", keywordlen)) { xfree (parm->cardtype); parm->cardtype = unescape_status_string (line); } else if (!memcmp (keyword, "DISP-SEX", keywordlen)) { parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0; } else if (!memcmp (keyword, "KEY-ATTR", keywordlen)) { char keyrefbuf[20]; int keyno, algo, n; const char *curve; unsigned int nbits; /* To prepare for future changes we allow for a full OpenPGP * keyref here. */ if (!ascii_strncasecmp (line, "OPENPGP.", 8)) line += 8; /* Note that KEY-ATTR returns OpenPGP algorithm numbers but * we want to use the Gcrypt numbers here. A compatible * change would be to add another parameter along with a * magic algo number to indicate that. */ algo = PUBKEY_ALGO_RSA; keyno = n = 0; sscanf (line, "%d %d %n", &keyno, &algo, &n); algo = map_openpgp_pk_to_gcry (algo); if (keyno < 1 || keyno > 3) ; /* Out of range - ignore. */ else { snprintf (keyrefbuf, sizeof keyrefbuf, "OPENPGP.%d", keyno); keyref = keyrefbuf; kinfo = find_kinfo (parm, keyref); if (!kinfo) /* No: new entry. */ kinfo = create_kinfo (parm, keyref); /* Although we could use the the value at %n directly as * keyalgo string, we want to use the standard * keyalgo_string function and thus we reconstruct it * here to make sure the displayed form of the curve * names is used. */ nbits = 0; curve = NULL; if (algo == GCRY_PK_ECDH || algo == GCRY_PK_ECDSA || algo == GCRY_PK_EDDSA || algo == GCRY_PK_ECC) { curve = openpgp_is_curve_supported (line + n, NULL, NULL); } else /* For rsa we see here for example "rsa2048". */ { if (line[n] && line[n+1] && line[n+2]) nbits = strtoul (line+n+3, NULL, 10); } kinfo->keyalgo = get_keyalgo_string (algo, nbits, curve); kinfo->keyalgo_id = algo; } } break; case 9: if (!memcmp (keyword, "DISP-NAME", keywordlen)) { xfree (parm->disp_name); parm->disp_name = unescape_status_string (line); } else if (!memcmp (keyword, "DISP-LANG", keywordlen)) { xfree (parm->disp_lang); parm->disp_lang = unescape_status_string (line); } else if (!memcmp (keyword, "CHV-USAGE", keywordlen)) { unsigned int byte1, byte2; byte1 = byte2 = 0; sscanf (line, "%x %x", &byte1, &byte2); parm->chvusage[0] = byte1; parm->chvusage[1] = byte2; } break; case 10: if (!memcmp (keyword, "PUBKEY-URL", keywordlen)) { xfree (parm->pubkey_url); parm->pubkey_url = unescape_status_string (line); } else if (!memcmp (keyword, "LOGIN-DATA", keywordlen)) { xfree (parm->login_data); parm->login_data = unescape_status_string (line); } else if (!memcmp (keyword, "CHV-STATUS", keywordlen)) { char *p, *buf; buf = p = unescape_status_string (line); if (buf) while (spacep (p)) p++; if (!buf) ; else if (parm->apptype == APP_TYPE_OPENPGP) { parm->chv1_cached = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; for (i=0; *p && i < 3; i++) { parm->chvmaxlen[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } for (i=0; *p && i < 3; i++) { parm->chvinfo[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } } else { for (i=0; *p && i < DIM (parm->chvinfo); i++) { parm->chvinfo[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } } xfree (buf); } else if (!memcmp (keyword, "APPVERSION", keywordlen)) { unsigned int val = 0; sscanf (line, "%x", &val); parm->appversion = val; } break; case 11: if (!memcmp (keyword, "SIG-COUNTER", keywordlen)) { parm->sig_counter = strtoul (line, NULL, 0); } else if (!memcmp (keyword, "KEYPAIRINFO", keywordlen)) { /* The format of such a line is: * KEYPAIRINFO [usage] [keytime] */ char *fields[4]; int nfields; const char *hexgrp, *usage; time_t keytime; line_buffer = pline = xstrdup (line); if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 2) goto leave; /* not enough args - invalid status line. */ hexgrp = fields[0]; keyref = fields[1]; if (nfields > 2) usage = fields[2]; else usage = ""; if (nfields > 3) keytime = parse_timestamp (fields[3], NULL); else keytime = 0; /* Check whether we already have an item for the keyref. */ kinfo = find_kinfo (parm, keyref); if (!kinfo) /* New entry. */ kinfo = create_kinfo (parm, keyref); else /* Existing entry - clear grip and usage */ { memset (kinfo->grip, 0, sizeof kinfo->grip); kinfo->usage = 0; } /* Set or update the grip. Note that due to the * calloc/memset an erroneous too short grip will be nul * padded on the right. */ unhexify_fpr (hexgrp, kinfo->grip, sizeof kinfo->grip); /* Parse and set the usage. */ for (; *usage; usage++) { switch (*usage) { case 's': kinfo->usage |= GCRY_PK_USAGE_SIGN; break; case 'c': kinfo->usage |= GCRY_PK_USAGE_CERT; break; case 'a': kinfo->usage |= GCRY_PK_USAGE_AUTH; break; case 'e': kinfo->usage |= GCRY_PK_USAGE_ENCR; break; } } /* Store the keytime. */ kinfo->created = keytime == (time_t)(-1)? 0 : (u32)keytime; } else if (!memcmp (keyword, "CARDVERSION", keywordlen)) { unsigned int val = 0; sscanf (line, "%x", &val); parm->cardversion = val; } break; case 12: if (!memcmp (keyword, "PRIVATE-DO-", 11) && strchr("1234", keyword[11])) { int no = keyword[11] - '1'; log_assert (no >= 0 && no <= 3); xfree (parm->private_do[no]); parm->private_do[no] = unescape_status_string (line); } else if (!memcmp (keyword, "MANUFACTURER", 12)) { xfree (parm->manufacturer_name); parm->manufacturer_name = NULL; parm->manufacturer_id = strtoul (line, &endp, 0); while (endp && spacep (endp)) endp++; if (endp && *endp) parm->manufacturer_name = xstrdup (endp); } break; case 13: if (!memcmp (keyword, "$DISPSERIALNO", keywordlen)) { xfree (parm->dispserialno); parm->dispserialno = unescape_status_string (line); } break; default: /* Unknown. */ break; } leave: xfree (line_buffer); return 0; } /* Call the scdaemon to learn about a smartcard. This fills INFO * with data from the card. */ gpg_error_t scd_learn (card_info_t info) { gpg_error_t err; struct default_inq_parm_s parm; struct card_info_s dummyinfo; if (!info) info = &dummyinfo; memset (info, 0, sizeof *info); memset (&parm, 0, sizeof parm); err = start_agent (0); if (err) return err; parm.ctx = agent_ctx; err = assuan_transact (agent_ctx, "SCD LEARN --force", dummy_data_cb, NULL, default_inq_cb, &parm, learn_status_cb, info); /* Also try to get some other key attributes. */ if (!err) { info->initialized = 1; err = scd_getattr ("KEY-ATTR", info); if (gpg_err_code (err) == GPG_ERR_INV_NAME || gpg_err_code (err) == GPG_ERR_UNSUPPORTED_OPERATION) err = 0; /* Not implemented or GETATTR not supported. */ err = scd_getattr ("$DISPSERIALNO", info); if (gpg_err_code (err) == GPG_ERR_INV_NAME || gpg_err_code (err) == GPG_ERR_UNSUPPORTED_OPERATION) err = 0; /* Not implemented or GETATTR not supported. */ } if (info == &dummyinfo) release_card_info (info); return err; } /* Call the agent to retrieve a data object. This function returns * the data in the same structure as used by the learn command. It is * allowed to update such a structure using this command. */ gpg_error_t scd_getattr (const char *name, struct card_info_s *info) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s parm; memset (&parm, 0, sizeof parm); if (!*name) return gpg_error (GPG_ERR_INV_VALUE); /* We assume that NAME does not need escaping. */ if (12 + strlen (name) > DIM(line)-1) return gpg_error (GPG_ERR_TOO_LARGE); stpcpy (stpcpy (line, "SCD GETATTR "), name); err = start_agent (0); if (err) return err; parm.ctx = agent_ctx; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, learn_status_cb, info); return err; } /* Send an setattr command to the SCdaemon. */ gpg_error_t scd_setattr (const char *name, const unsigned char *value, size_t valuelen) { gpg_error_t err; char *tmp; char *line = NULL; struct default_inq_parm_s parm; if (!*name || !valuelen) return gpg_error (GPG_ERR_INV_VALUE); tmp = strconcat ("SCD SETATTR ", name, " ", NULL); if (!tmp) { err = gpg_error_from_syserror (); goto leave; } line = percent_data_escape (1, tmp, value, valuelen); xfree (tmp); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 10 > ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } err = start_agent (0); if (err ) goto leave; memset (&parm, 0, sizeof parm); parm.ctx = agent_ctx; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); leave: xfree (line); return status_sc_op_failure (err); } /* Handle a CERTDATA inquiry. Note, we only send the data, * assuan_transact takes care of flushing and writing the END * command. */ static gpg_error_t inq_writecert_parms (void *opaque, const char *line) { gpg_error_t err; struct writecert_parm_s *parm = opaque; if (has_leading_keyword (line, "CERTDATA")) { err = assuan_send_data (parm->dflt->ctx, parm->certdata, parm->certdatalen); } else err = default_inq_cb (parm->dflt, line); return err; } /* Send a WRITECERT command to the SCdaemon. */ gpg_error_t scd_writecert (const char *certidstr, const unsigned char *certdata, size_t certdatalen) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct writecert_parm_s parms; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); err = start_agent (0); if (err) return err; memset (&parms, 0, sizeof parms); snprintf (line, sizeof line, "SCD WRITECERT %s", certidstr); dfltparm.ctx = agent_ctx; parms.dflt = &dfltparm; parms.certdata = certdata; parms.certdatalen = certdatalen; err = assuan_transact (agent_ctx, line, NULL, NULL, inq_writecert_parms, &parms, NULL, NULL); return status_sc_op_failure (err); } /* Send a WRITEKEY command to the agent (so that the agent can fetch * the key to write). KEYGRIP is the hexified keygrip of the source * key which will be written to the slot KEYREF. FORCE must be true * to overwrite an existing key. */ gpg_error_t scd_writekey (const char *keyref, int force, const char *keygrip) { gpg_error_t err; struct default_inq_parm_s parm; char line[ASSUAN_LINELENGTH]; memset (&parm, 0, sizeof parm); err = start_agent (0); if (err) return err; /* Note: We don't send the s/n but "-" because gpg-agent has * currently no use for it. */ /* FIXME: For OpenPGP we should provide the creation time. */ snprintf (line, sizeof line, "KEYTOCARD%s %s - %s", force? " --force":"", keygrip, keyref); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm, NULL, NULL); return status_sc_op_failure (err); } /* Status callback for the SCD GENKEY command. */ static gpg_error_t scd_genkey_cb (void *opaque, const char *line) { u32 *createtime = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen)) { if (createtime) *createtime = (u32)strtoul (line, NULL, 10); } else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen)) { gnupg_status_printf (STATUS_PROGRESS, "%s", line); } return 0; } /* Send a GENKEY command to the SCdaemon. If *CREATETIME is not 0, * the value will be passed to SCDAEMON with --timestamp option so that * the key is created with this. Otherwise, timestamp was generated by * SCDAEMON. On success, creation time is stored back to CREATETIME. */ gpg_error_t scd_genkey (const char *keyref, int force, const char *algo, u32 *createtime) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; gnupg_isotime_t tbuf; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); err = start_agent (0); if (err) return err; if (createtime && *createtime) epoch2isotime (tbuf, *createtime); else *tbuf = 0; snprintf (line, sizeof line, "SCD GENKEY %s%s %s %s%s -- %s", *tbuf? "--timestamp=":"", tbuf, force? "--force":"", algo? "--algo=":"", algo? algo:"", keyref); dfltparm.ctx = agent_ctx; err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, scd_genkey_cb, createtime); return status_sc_op_failure (err); } /* Return the serial number of the card or an appropriate error. The * serial number is returned as a hexstring. If DEMAND is not NULL * the reader with the a card of the serial number DEMAND is * requested. */ gpg_error_t scd_serialno (char **r_serialno, const char *demand) { int err; char *serialno = NULL; char line[ASSUAN_LINELENGTH]; err = start_agent (START_AGENT_SUPPRESS_ERRORS); if (err) return err; if (!demand) strcpy (line, "SCD SERIALNO --all"); else snprintf (line, DIM(line), "SCD SERIALNO --demand=%s --all", demand); err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, get_serialno_cb, &serialno); if (err) { xfree (serialno); return err; } if (r_serialno) *r_serialno = serialno; else xfree (serialno); return 0; } /* Send a READCERT command to the SCdaemon. */ gpg_error_t scd_readcert (const char *certidstr, void **r_buf, size_t *r_buflen) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; size_t len; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); *r_buf = NULL; err = start_agent (0); if (err) return err; dfltparm.ctx = agent_ctx; init_membuf (&data, 2048); snprintf (line, sizeof line, "SCD READCERT %s", certidstr); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, default_inq_cb, &dfltparm, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } *r_buf = get_membuf (&data, r_buflen); if (!*r_buf) return gpg_error_from_syserror (); return 0; } /* Send a READKEY command to the SCdaemon. On success a new * s-expression is stored at R_RESULT. */ gpg_error_t scd_readkey (const char *keyrefstr, gcry_sexp_t *r_result) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; membuf_t data; unsigned char *buf; size_t len, buflen; *r_result = NULL; err = start_agent (0); if (err) return err; init_membuf (&data, 1024); snprintf (line, DIM(line), "SCD READKEY %s", keyrefstr); err = assuan_transact (agent_ctx, line, put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) { xfree (get_membuf (&data, &len)); return err; } buf = get_membuf (&data, &buflen); if (!buf) return gpg_error_from_syserror (); err = gcry_sexp_new (r_result, buf, buflen, 0); xfree (buf); return err; } /* Callback function for card_cardlist. */ static gpg_error_t card_cardlist_cb (void *opaque, const char *line) { struct card_cardlist_parm_s *parm = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { const char *s; int n; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n || (n&1)) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); if (parm->with_apps) { /* Format of the stored string is the S/N, a space, and a * space separated list of appnames. */ if (*s && (*s != ' ' || spacep (s+1) || !s[1])) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); else /* We assume the rest of the line is well formatted. */ add_to_strlist (&parm->list, line); } else { if (*s) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); else add_to_strlist (&parm->list, line); } } return 0; } /* Return the serial numbers of all cards currently inserted. */ gpg_error_t scd_cardlist (strlist_t *result) { gpg_error_t err; struct card_cardlist_parm_s parm; memset (&parm, 0, sizeof parm); *result = NULL; err = start_agent (START_AGENT_SUPPRESS_ERRORS); if (err) return err; err = assuan_transact (agent_ctx, "SCD GETINFO card_list", NULL, NULL, NULL, NULL, card_cardlist_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_strlist (parm.list); return err; } /* Return the serial numbers and appnames of the current card or, with * ALL given has true, of all cards currently inserted. */ gpg_error_t scd_applist (strlist_t *result, int all) { gpg_error_t err; struct card_cardlist_parm_s parm; memset (&parm, 0, sizeof parm); *result = NULL; err = start_agent (START_AGENT_SUPPRESS_ERRORS); if (err) return err; parm.with_apps = 1; err = assuan_transact (agent_ctx, all ? "SCD GETINFO all_active_apps" /**/: "SCD GETINFO active_apps", NULL, NULL, NULL, NULL, card_cardlist_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *result = parm.list; else free_strlist (parm.list); return err; } /* Change the PIN of a card or reset the retry counter. If NULLPIN is * set the TCOS specific NullPIN is changed. */ gpg_error_t scd_change_pin (const char *pinref, int reset_mode, int nullpin) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); err = start_agent (0); if (err) return err; dfltparm.ctx = agent_ctx; snprintf (line, sizeof line, "SCD PASSWD%s %s", nullpin? " --nullpin": reset_mode? " --reset":"", pinref); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); return status_sc_op_failure (err); } /* Perform a CHECKPIN operation. SERIALNO should be the serial * number of the card - optionally followed by the fingerprint; * however the fingerprint is ignored here. */ gpg_error_t scd_checkpin (const char *serialno) { gpg_error_t err; char line[ASSUAN_LINELENGTH]; struct default_inq_parm_s dfltparm; memset (&dfltparm, 0, sizeof dfltparm); err = start_agent (0); if (err) return err; dfltparm.ctx = agent_ctx; snprintf (line, sizeof line, "SCD CHECKPIN %s", serialno); err = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &dfltparm, NULL, NULL); return status_sc_op_failure (err); } /* Return the S2K iteration count as computed by gpg-agent. On error * print a warning and return a default value. */ unsigned long agent_get_s2k_count (void) { gpg_error_t err; membuf_t data; char *buf; unsigned long count = 0; err = start_agent (0); if (err) goto leave; init_membuf (&data, 32); err = assuan_transact (agent_ctx, "GETINFO s2k_count", put_membuf_cb, &data, NULL, NULL, NULL, NULL); if (err) xfree (get_membuf (&data, NULL)); else { put_membuf (&data, "", 1); buf = get_membuf (&data, NULL); if (!buf) err = gpg_error_from_syserror (); else { count = strtoul (buf, NULL, 10); xfree (buf); } } leave: if (err || count < 65536) { /* Don't print an error if an older agent is used. */ if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER) log_error (_("problem with the agent: %s\n"), gpg_strerror (err)); /* Default to 65536 which was used up to 2.0.13. */ count = 65536; } return count; }