diff --git a/agent/agent.h b/agent/agent.h index 4ee8e40c5..f1c9b83b6 100644 --- a/agent/agent.h +++ b/agent/agent.h @@ -1,745 +1,744 @@ /* agent.h - Global definitions for the agent * Copyright (C) 2001, 2002, 2003, 2005, 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 . */ #ifndef AGENT_H #define AGENT_H #ifdef GPG_ERR_SOURCE_DEFAULT #error GPG_ERR_SOURCE_DEFAULT already defined #endif #define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GPGAGENT #include #define map_assuan_err(a) \ map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a)) #include #include #include #include "../common/util.h" #include "../common/membuf.h" #include "../common/sysutils.h" /* (gnupg_fd_t) */ #include "../common/session-env.h" #include "../common/shareddefs.h" /* To convey some special hash algorithms we use algorithm numbers reserved for application use. */ #ifndef GCRY_MODULE_ID_USER #define GCRY_MODULE_ID_USER 1024 #endif #define MD_USER_TLS_MD5SHA1 (GCRY_MODULE_ID_USER+1) /* Maximum length of a digest. */ #define MAX_DIGEST_LEN 64 /* The maximum length of a passphrase (in bytes). Note: this is further constrained by the Assuan line length (and any other text on the same line). However, the Assuan line length is 1k bytes so this shouldn't be a problem in practice. */ #define MAX_PASSPHRASE_LEN 255 /* The daemons we support. When you add a new daemon, add to both the daemon_type and the daemon_modules array in call-daemon.c */ enum daemon_type { DAEMON_SCD, DAEMON_TPM2D, DAEMON_MAX_TYPE }; /* A large struct name "opt" to keep global flags */ EXTERN_UNLESS_MAIN_MODULE struct { unsigned int debug; /* Debug flags (DBG_foo_VALUE) */ int verbose; /* Verbosity level */ int quiet; /* Be as quiet as possible */ int dry_run; /* Don't change any persistent data */ int batch; /* Batch mode */ /* True if we handle sigusr2. */ int sigusr2_enabled; /* Environment settings gathered at program start or changed using the Assuan command UPDATESTARTUPTTY. */ session_env_t startup_env; char *startup_lc_ctype; char *startup_lc_messages; /* Enable pinentry debugging (--debug 1024 should also be used). */ int debug_pinentry; /* Filename of the program to start as pinentry. */ const char *pinentry_program; /* Filename of the program to handle daemon tasks. */ const char *daemon_program[DAEMON_MAX_TYPE]; int disable_daemon[DAEMON_MAX_TYPE]; /* Never use the daemon. */ int no_grab; /* Don't let the pinentry grab the keyboard */ /* The name of the file pinentry shall touch before exiting. If this is not set the file name of the standard socket is used. */ const char *pinentry_touch_file; /* A string where the first character is used by the pinentry as a custom invisible character. */ char *pinentry_invisible_char; /* The timeout value for the Pinentry in seconds. This is passed to the pinentry if it is not 0. It is up to the pinentry to act upon this timeout value. */ unsigned long pinentry_timeout; /* If set, then passphrase formatting is enabled in pinentry. */ int pinentry_formatted_passphrase; /* The default and maximum TTL of cache entries. */ unsigned long def_cache_ttl; /* Default. */ unsigned long def_cache_ttl_ssh; /* for SSH. */ unsigned long max_cache_ttl; /* Default. */ unsigned long max_cache_ttl_ssh; /* for SSH. */ /* Flag disallowing bypassing of the warning. */ int enforce_passphrase_constraints; /* The require minmum length of a passphrase. */ unsigned int min_passphrase_len; /* The minimum number of non-alpha characters in a passphrase. */ unsigned int min_passphrase_nonalpha; /* File name with a patternfile or NULL if not enabled. If the * second one is set, it is used for symmetric only encryption * instead of the former. */ const char *check_passphrase_pattern; const char *check_sym_passphrase_pattern; /* If not 0 the user is asked to change his passphrase after these number of days. */ unsigned int max_passphrase_days; /* If set, a passphrase history will be written and checked at each passphrase change. */ int enable_passphrase_history; /* If set the extended key format is used for new keys. Note that * this may have the value 2 in which case * --disable-extended-key-format won't have any effect and thus * effectivley locking it. This is required to support existing * profiles which lock the use of --enable-extended-key-format. */ int enable_extended_key_format; int running_detached; /* We are running detached from the tty. */ /* If this global option is true, the passphrase cache is ignored for signing operations. */ int ignore_cache_for_signing; /* If this global option is true, the user is allowed to interactively mark certificate in trustlist.txt as trusted. */ int allow_mark_trusted; /* If this global option is true, the Assuan command PRESET_PASSPHRASE is allowed. */ int allow_preset_passphrase; /* If this global option is true, the Assuan option pinentry-mode=loopback is allowed. */ int allow_loopback_pinentry; /* Allow the use of an external password cache. If this option is enabled (which is the default) we send an option to Pinentry to allow it to enable such a cache. */ int allow_external_cache; /* If this global option is true, the Assuan option of Pinentry allow-emacs-prompt is allowed. */ int allow_emacs_pinentry; int keep_tty; /* Don't switch the TTY (for pinentry) on request */ int keep_display; /* Don't switch the DISPLAY (for pinentry) on request */ /* This global option indicates the use of an extra socket. Note that we use a hack for cleanup handling in gpg-agent.c: If the value is less than 2 the name has not yet been malloced. */ int extra_socket; /* This global option indicates the use of an extra socket for web browsers. Note that we use a hack for cleanup handling in gpg-agent.c: If the value is less than 2 the name has not yet been malloced. */ int browser_socket; /* The digest algorithm to use for ssh fingerprints when * communicating with the user. */ int ssh_fingerprint_digest; /* The value of the option --s2k-count. If this option is not given * or 0 an auto-calibrated value is used. */ unsigned long s2k_count; } opt; /* Bit values for the --debug option. */ #define DBG_MPI_VALUE 2 /* debug mpi details */ #define DBG_CRYPTO_VALUE 4 /* debug low level crypto */ #define DBG_MEMORY_VALUE 32 /* debug memory allocation stuff */ #define DBG_CACHE_VALUE 64 /* debug the caching */ #define DBG_MEMSTAT_VALUE 128 /* show memory statistics */ #define DBG_HASHING_VALUE 512 /* debug hashing operations */ #define DBG_IPC_VALUE 1024 /* Enable Assuan debugging. */ /* Test macros for the debug option. */ #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE) #define DBG_CACHE (opt.debug & DBG_CACHE_VALUE) #define DBG_HASHING (opt.debug & DBG_HASHING_VALUE) #define DBG_IPC (opt.debug & DBG_IPC_VALUE) /* Forward reference for local definitions in command.c. */ struct server_local_s; /* Declaration of objects from command-ssh.c. */ struct ssh_control_file_s; typedef struct ssh_control_file_s *ssh_control_file_t; /* Forward reference for local definitions in call-scd.c. */ struct daemon_local_s; /* Collection of data per session (aka connection). */ struct server_control_s { /* Private data used to fire up the connection thread. We use this structure do avoid an extra allocation for only a few bytes while spawning a new connection thread. */ struct { gnupg_fd_t fd; } thread_startup; /* Flag indicating the connection is run in restricted mode. A value of 1 if used for --extra-socket, a value of 2 is used for --browser-socket. */ int restricted; /* Private data of the server (command.c). */ struct server_local_s *server_local; /* Private data of the daemon (call-XXX.c). */ struct daemon_local_s *d_local[DAEMON_MAX_TYPE]; /* Environment settings for the connection. */ session_env_t session_env; char *lc_ctype; char *lc_messages; unsigned long client_pid; int client_uid; /* The current pinentry mode. */ pinentry_mode_t pinentry_mode; /* The TTL used for the --preset option of certain commands. */ int cache_ttl_opt_preset; /* Information on the currently used digest (for signing commands). */ struct { char *data; /* NULL or malloced data of length VALUELEN. If this is set the other fields are ignored. Used for PureEdDSA and RSA with PSS (in which case data_is_pss is also set). */ int valuelen; int algo; unsigned char value[MAX_DIGEST_LEN]; unsigned int raw_value: 1; unsigned int is_pss: 1; /* DATA holds PSS formated data. */ } digest; unsigned char keygrip[20]; int have_keygrip; /* A flag to enable a hack to send the PKAUTH command instead of the PKSIGN command to the scdaemon. */ int use_auth_call; /* A flag to inhibit enforced passphrase change during an explicit passwd command. */ int in_passwd; /* The current S2K which might be different from the calibrated count. */ unsigned long s2k_count; /* If pinentry is active for this thread. It can be more than 1, when pinentry is called recursively. */ int pinentry_active; }; /* Status of pinentry. */ enum { PINENTRY_STATUS_CLOSE_BUTTON = 1 << 0, PINENTRY_STATUS_PIN_REPEATED = 1 << 8, PINENTRY_STATUS_PASSWORD_FROM_CACHE = 1 << 9, PINENTRY_STATUS_PASSWORD_GENERATED = 1 << 10 }; /* Information pertaining to pinentry requests. */ struct pin_entry_info_s { int min_digits; /* min. number of digits required or 0 for freeform entry */ int max_digits; /* max. number of allowed digits allowed*/ int max_tries; /* max. number of allowed tries. */ unsigned int constraints_flags; /* CHECK_CONSTRAINTS_... */ int failed_tries; /* Number of tries so far failed. */ int with_qualitybar; /* Set if the quality bar should be displayed. */ int with_repeat; /* Request repetition of the passphrase. */ int repeat_okay; /* Repetition worked. */ unsigned int status; /* Status. */ gpg_error_t (*check_cb)(struct pin_entry_info_s *); /* CB used to check the PIN */ void *check_cb_arg; /* optional argument which might be of use in the CB */ const char *cb_errtext; /* used by the cb to display a specific error */ size_t max_length; /* Allocated length of the buffer PIN. */ char pin[1]; /* The buffer to hold the PIN or passphrase. It's actual allocated length is given by MAX_LENGTH (above). */ }; /* Types of the private keys. */ enum { PRIVATE_KEY_UNKNOWN = 0, /* Type of key is not known. */ PRIVATE_KEY_CLEAR = 1, /* The key is not protected. */ PRIVATE_KEY_PROTECTED = 2, /* The key is protected. */ PRIVATE_KEY_SHADOWED = 3, /* The key is a stub for a smartcard based key. */ PROTECTED_SHARED_SECRET = 4, /* RFU. */ PRIVATE_KEY_OPENPGP_NONE = 5 /* openpgp-native with protection "none". */ }; /* Values for the cache_mode arguments. */ typedef enum { CACHE_MODE_IGNORE = 0, /* Special mode to bypass the cache. */ CACHE_MODE_ANY, /* Any mode except ignore and data matches. */ CACHE_MODE_NORMAL, /* Normal cache (gpg-agent). */ CACHE_MODE_USER, /* GET_PASSPHRASE related cache. */ CACHE_MODE_SSH, /* SSH related cache. */ CACHE_MODE_NONCE, /* This is a non-predictable nonce. */ CACHE_MODE_PIN, /* PINs stored/retrieved by scdaemon. */ CACHE_MODE_DATA /* Arbitrary data. */ } cache_mode_t; /* The TTL is seconds used for adding a new nonce mode cache item. */ #define CACHE_TTL_NONCE 120 /* The TTL in seconds used by the --preset option of some commands. This is the default value changeable by an OPTION command. */ #define CACHE_TTL_OPT_PRESET 900 /* The type of a function to lookup a TTL by a keygrip. */ typedef int (*lookup_ttl_t)(const char *hexgrip); /* This is a special version of the usual _() gettext macro. It assumes a server connection control variable with the name "ctrl" and uses that to translate a string according to the locale set for the connection. The macro LunderscoreIMPL is used by i18n to actually define the inline function when needed. */ #if defined (ENABLE_NLS) || defined (USE_SIMPLE_GETTEXT) #define L_(a) agent_Lunderscore (ctrl, (a)) #define LunderscorePROTO \ static inline const char *agent_Lunderscore (ctrl_t ctrl, \ const char *string) \ GNUPG_GCC_ATTR_FORMAT_ARG(2); #define LunderscoreIMPL \ static inline const char * \ agent_Lunderscore (ctrl_t ctrl, const char *string) \ { \ return ctrl? i18n_localegettext (ctrl->lc_messages, string) \ /* */: gettext (string); \ } #else #define L_(a) (a) #endif /* Information from scdaemon for card keys. */ struct card_key_info_s { struct card_key_info_s *next; char keygrip[41]; char *serialno; char *idstr; }; /*-- gpg-agent.c --*/ void agent_exit (int rc) GPGRT_ATTR_NORETURN; /* Also implemented in other tools */ void agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total), ctrl_t ctrl); gpg_error_t agent_copy_startup_env (ctrl_t ctrl); const char *get_agent_socket_name (void); const char *get_agent_ssh_socket_name (void); int get_agent_active_connection_count (void); #ifdef HAVE_W32_SYSTEM void *get_agent_daemon_notify_event (void); #endif void agent_sighup_action (void); int map_pk_openpgp_to_gcry (int openpgp_algo); /*-- command.c --*/ gpg_error_t agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid, const char *extra); gpg_error_t agent_write_status (ctrl_t ctrl, const char *keyword, ...) GPGRT_ATTR_SENTINEL(0); gpg_error_t agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); void bump_key_eventcounter (void); void bump_card_eventcounter (void); void start_command_handler (ctrl_t, gnupg_fd_t, gnupg_fd_t); gpg_error_t pinentry_loopback (ctrl_t, const char *keyword, unsigned char **buffer, size_t *size, size_t max_length); gpg_error_t pinentry_loopback_confirm (ctrl_t ctrl, const char *desc, int ask_confirmation, const char *ok, const char *notok); #ifdef HAVE_W32_SYSTEM int serve_mmapped_ssh_request (ctrl_t ctrl, unsigned char *request, size_t maxreqlen); #endif /*HAVE_W32_SYSTEM*/ /*-- command-ssh.c --*/ ssh_control_file_t ssh_open_control_file (void); void ssh_close_control_file (ssh_control_file_t cf); gpg_error_t ssh_read_control_file (ssh_control_file_t cf, char *r_hexgrip, int *r_disabled, int *r_ttl, int *r_confirm); gpg_error_t ssh_search_control_file (ssh_control_file_t cf, const char *hexgrip, int *r_disabled, int *r_ttl, int *r_confirm); void start_command_handler_ssh (ctrl_t, gnupg_fd_t); /*-- findkey.c --*/ gpg_error_t agent_modify_description (const char *in, const char *comment, const gcry_sexp_t key, char **result); int agent_write_private_key (const unsigned char *grip, const void *buffer, size_t length, int force, const char *serialno, const char *keyref, time_t timestamp); gpg_error_t agent_key_from_file (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, const unsigned char *grip, unsigned char **shadow_info, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, gcry_sexp_t *result, char **r_passphrase, time_t *r_timestamp); gpg_error_t agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t *result); gpg_error_t agent_public_key_from_file (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t *result); int agent_pk_get_algo (gcry_sexp_t s_key); int agent_is_tpm2_key(gcry_sexp_t s_key); int agent_key_available (const unsigned char *grip); gpg_error_t agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip, int *r_keytype, unsigned char **r_shadow_info, unsigned char **r_shadow_info_type); gpg_error_t agent_delete_key (ctrl_t ctrl, const char *desc_text, const unsigned char *grip, int force, int only_stubs); /*-- call-pinentry.c --*/ void initialize_module_call_pinentry (void); void agent_query_dump_state (void); void agent_reset_query (ctrl_t ctrl); int pinentry_active_p (ctrl_t ctrl, int waitseconds); gpg_error_t agent_askpin (ctrl_t ctrl, const char *desc_text, const char *prompt_text, const char *inital_errtext, struct pin_entry_info_s *pininfo, const char *keyinfo, cache_mode_t cache_mode); int agent_get_passphrase (ctrl_t ctrl, char **retpass, const char *desc, const char *prompt, const char *errtext, int with_qualitybar, const char *keyinfo, cache_mode_t cache_mode, struct pin_entry_info_s *pininfo); int agent_get_confirmation (ctrl_t ctrl, const char *desc, const char *ok, const char *notokay, int with_cancel); int agent_show_message (ctrl_t ctrl, const char *desc, const char *ok_btn); int agent_popup_message_start (ctrl_t ctrl, const char *desc, const char *ok_btn); void agent_popup_message_stop (ctrl_t ctrl); int agent_clear_passphrase (ctrl_t ctrl, const char *keyinfo, cache_mode_t cache_mode); /*-- cache.c --*/ void initialize_module_cache (void); void deinitialize_module_cache (void); void agent_cache_housekeeping (void); void agent_flush_cache (int pincache_only); int agent_put_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode, const char *data, int ttl); char *agent_get_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode); void agent_store_cache_hit (const char *key); /*-- pksign.c --*/ gpg_error_t agent_pksign_do (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, gcry_sexp_t *signature_sexp, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, const void *overridedata, size_t overridedatalen); gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, membuf_t *outbuf, cache_mode_t cache_mode); /*-- pkdecrypt.c --*/ gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *desc_text, const unsigned char *ciphertext, size_t ciphertextlen, membuf_t *outbuf, int *r_padding); /*-- genkey.c --*/ #define CHECK_CONSTRAINTS_NOT_EMPTY 1 #define CHECK_CONSTRAINTS_NEW_SYMKEY 2 int check_passphrase_constraints (ctrl_t ctrl, const char *pw, unsigned int flags, char **failed_constraint); gpg_error_t agent_ask_new_passphrase (ctrl_t ctrl, const char *prompt, char **r_passphrase); int agent_genkey (ctrl_t ctrl, const char *cache_nonce, time_t timestamp, const char *keyparam, size_t keyparmlen, int no_protection, const char *override_passphrase, int preset, membuf_t *outbuf); gpg_error_t agent_protect_and_store (ctrl_t ctrl, gcry_sexp_t s_skey, char **passphrase_addr); /*-- protect.c --*/ void set_s2k_calibration_time (unsigned int milliseconds); unsigned long get_calibrated_s2k_count (void); unsigned long get_standard_s2k_count (void); unsigned char get_standard_s2k_count_rfc4880 (void); unsigned long get_standard_s2k_time (void); int agent_protect (const unsigned char *plainkey, const char *passphrase, unsigned char **result, size_t *resultlen, unsigned long s2k_count, int use_ocb); gpg_error_t agent_unprotect (ctrl_t ctrl, const unsigned char *protectedkey, const char *passphrase, gnupg_isotime_t protected_at, unsigned char **result, size_t *resultlen); int agent_private_key_type (const unsigned char *privatekey); unsigned char *make_shadow_info (const char *serialno, const char *idstring); int agent_shadow_key (const unsigned char *pubkey, const unsigned char *shadow_info, unsigned char **result); int agent_shadow_key_type (const unsigned char *pubkey, const unsigned char *shadow_info, const unsigned char *type, unsigned char **result); gpg_error_t agent_get_shadow_info (const unsigned char *shadowkey, unsigned char const **shadow_info); gpg_error_t agent_get_shadow_info_type (const unsigned char *shadowkey, unsigned char const **shadow_info, unsigned char **shadow_type); gpg_error_t parse_shadow_info (const unsigned char *shadow_info, char **r_hexsn, char **r_idstr, int *r_pinlen); gpg_error_t s2k_hash_passphrase (const char *passphrase, int hashalgo, int s2kmode, const unsigned char *s2ksalt, unsigned int s2kcount, unsigned char *key, size_t keylen); gpg_error_t agent_write_shadow_key (const unsigned char *grip, const char *serialno, const char *keyid, const unsigned char *pkbuf, int force); /*-- trustlist.c --*/ void initialize_module_trustlist (void); gpg_error_t agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled); gpg_error_t agent_listtrusted (void *assuan_context); gpg_error_t agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag); void agent_reload_trustlist (void); /*-- divert-tpm2.c --*/ #ifdef HAVE_LIBTSS -int divert_tpm2_pksign (ctrl_t ctrl, const char *desc_text, +int divert_tpm2_pksign (ctrl_t ctrl, const unsigned char *digest, size_t digestlen, int algo, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen); -int divert_tpm2_pkdecrypt (ctrl_t ctrl, const char *desc_text, +int divert_tpm2_pkdecrypt (ctrl_t ctrl, const unsigned char *cipher, const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding); int divert_tpm2_writekey (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t s_skey); #else /*!HAVE_LIBTSS*/ static inline int -divert_tpm2_pksign (ctrl_t ctrl, const char *desc_text, +divert_tpm2_pksign (ctrl_t ctrl, const unsigned char *digest, size_t digestlen, int algo, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen) { - (void)ctrl; (void)desc_text; (void)digest; (void)digestlen; + (void)ctrl; (void)digest; (void)digestlen; (void)algo; (void)shadow_info; (void)r_sig; (void)r_siglen; return gpg_error (GPG_ERR_NOT_SUPPORTED); } static inline int -divert_tpm2_pkdecrypt (ctrl_t ctrl, const char *desc_text, +divert_tpm2_pkdecrypt (ctrl_t ctrl, const unsigned char *cipher, const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding) { - (void)ctrl; (void)desc_text; (void)cipher; (void)shadow_info; + (void)ctrl; (void)cipher; (void)shadow_info; (void)r_buf; (void)r_len; (void)r_padding; return gpg_error (GPG_ERR_NOT_SUPPORTED); } static inline int divert_tpm2_writekey (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t s_skey) { (void)ctrl; (void)grip; (void)s_skey; return gpg_error (GPG_ERR_NOT_SUPPORTED); } #endif /*!HAVE_LIBTSS*/ /*-- divert-scd.c --*/ -int divert_pksign (ctrl_t ctrl, const char *desc_text, +int divert_pksign (ctrl_t ctrl, const unsigned char *grip, const unsigned char *digest, size_t digestlen, int algo, - const unsigned char *shadow_info, unsigned char **r_sig, + unsigned char **r_sig, size_t *r_siglen); -int divert_pkdecrypt (ctrl_t ctrl, const char *desc_text, +int divert_pkdecrypt (ctrl_t ctrl, const unsigned char *grip, const unsigned char *cipher, - const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding); int divert_generic_cmd (ctrl_t ctrl, const char *cmdline, void *assuan_context); gpg_error_t divert_writekey (ctrl_t ctrl, int force, const char *serialno, const char *keyref, const char *keydata, size_t keydatalen); /*-- call-daemon.c --*/ gpg_error_t daemon_start (enum daemon_type type, ctrl_t ctrl); assuan_context_t daemon_type_ctx (enum daemon_type type, ctrl_t ctrl); gpg_error_t daemon_unlock (enum daemon_type type, ctrl_t ctrl, gpg_error_t rc); void initialize_module_daemon (void); void agent_daemon_dump_state (void); int agent_daemon_check_running (enum daemon_type type); void agent_daemon_check_aliveness (void); void agent_reset_daemon (ctrl_t ctrl); void agent_kill_daemon (enum daemon_type type); /*-- call-tpm2d.c --*/ int agent_tpm2d_writekey (ctrl_t ctrl, unsigned char **shadow_info, gcry_sexp_t s_skey); int agent_tpm2d_pksign (ctrl_t ctrl, const unsigned char *digest, size_t digestlen, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen); int agent_tpm2d_pkdecrypt (ctrl_t ctrl, const unsigned char *cipher, size_t cipherlen, const unsigned char *shadow_info, char **r_buf, size_t *r_len); /*-- call-scd.c --*/ int agent_card_learn (ctrl_t ctrl, void (*kpinfo_cb)(void*, const char *), void *kpinfo_cb_arg, void (*certinfo_cb)(void*, const char *), void *certinfo_cb_arg, void (*sinfo_cb)(void*, const char *, size_t, const char *), void *sinfo_cb_arg); int agent_card_serialno (ctrl_t ctrl, char **r_serialno, const char *demand); int agent_card_pksign (ctrl_t ctrl, const char *keyid, int (*getpin_cb)(void *, const char *, const char *, char*, size_t), void *getpin_cb_arg, const char *desc_text, int mdalgo, const unsigned char *indata, size_t indatalen, unsigned char **r_buf, size_t *r_buflen); int agent_card_pkdecrypt (ctrl_t ctrl, const char *keyid, int (*getpin_cb)(void *, const char *, const char *, char*,size_t), void *getpin_cb_arg, const char *desc_text, const unsigned char *indata, size_t indatalen, char **r_buf, size_t *r_buflen, int *r_padding); int agent_card_readcert (ctrl_t ctrl, const char *id, char **r_buf, size_t *r_buflen); int agent_card_readkey (ctrl_t ctrl, const char *id, unsigned char **r_buf, char **r_keyref); gpg_error_t agent_card_writekey (ctrl_t ctrl, int force, const char *serialno, const char *keyref, const char *keydata, size_t keydatalen, int (*getpin_cb)(void *, const char *, const char *, char*, size_t), void *getpin_cb_arg); gpg_error_t agent_card_getattr (ctrl_t ctrl, const char *name, char **result, const char *keygrip); int agent_card_scd (ctrl_t ctrl, const char *cmdline, int (*getpin_cb)(void *, const char *, const char *, char*, size_t), void *getpin_cb_arg, void *assuan_context); void agent_card_free_keyinfo (struct card_key_info_s *l); gpg_error_t agent_card_keyinfo (ctrl_t ctrl, const char *keygrip, int cap, struct card_key_info_s **result); /*-- learncard.c --*/ int agent_handle_learn (ctrl_t ctrl, int send, void *assuan_context, int force); /*-- cvt-openpgp.c --*/ gpg_error_t extract_private_key (gcry_sexp_t s_key, int req_private_key_data, const char **r_algoname, int *r_npkey, int *r_nskey, const char **r_format, gcry_mpi_t *mpi_array, int arraysize, gcry_sexp_t *r_curve, gcry_sexp_t *r_flags); /*-- sexp-secret.c --*/ gpg_error_t fixup_when_ecc_private_key (unsigned char *buf, size_t *buflen_p); gpg_error_t sexp_sscan_private_key (gcry_sexp_t *result, size_t *r_erroff, unsigned char *buf); #endif /*AGENT_H*/ diff --git a/agent/divert-scd.c b/agent/divert-scd.c index 273f3a869..ed0173ea1 100644 --- a/agent/divert-scd.c +++ b/agent/divert-scd.c @@ -1,623 +1,501 @@ /* divert-scd.c - divert operations to the scdaemon * Copyright (C) 2002, 2003, 2009 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 #include "agent.h" #include "../common/i18n.h" #include "../common/sexp-parse.h" -static gpg_error_t -ask_for_card (ctrl_t ctrl, const unsigned char *shadow_info, - const unsigned char *grip, char **r_kid) -{ - char *serialno; - char *desc; - char *want_sn; - int len; - gpg_error_t err; - char hexgrip[41]; - - *r_kid = NULL; - bin2hex (grip, 20, hexgrip); - - if (shadow_info) - { - err = parse_shadow_info (shadow_info, &want_sn, NULL, NULL); - if (err) - return err; - } - else - want_sn = NULL; - - len = want_sn? strlen (want_sn) : 0; - if (len == 32 && !strncmp (want_sn, "D27600012401", 12)) - { - /* This is an OpenPGP card - reformat */ - if (!strncmp (want_sn+16, "0006", 4)) - { - /* This is a Yubikey. Print the s/n as it would be printed - * on Yubikey 5. Example: D2760001240100000006120808620000 - * mmmm^^^^^^^^ */ - unsigned long sn; - - sn = atoi_4 (want_sn+20) * 10000; - sn += atoi_4 (want_sn+24); - snprintf (want_sn, 32, "%lu %03lu %03lu", - (sn/1000000ul), (sn/1000ul % 1000ul), (sn % 1000ul)); - } - else /* Default is the Zeitcontrol card print format. */ - { - memmove (want_sn, want_sn+16, 4); - want_sn[4] = ' '; - memmove (want_sn+5, want_sn+20, 8); - want_sn[13] = 0; - } - } - else if (len == 20 && want_sn[19] == '0') - { - /* We assume that a 20 byte serial number is a standard one - * which has the property to have a zero in the last nibble (Due - * to BCD representation). We don't display this '0' because it - * may confuse the user. */ - want_sn[19] = 0; - } - - for (;;) - { - /* Scan device(s), and check if key for GRIP is available. */ - err = agent_card_serialno (ctrl, &serialno, NULL); - if (!err) - { - struct card_key_info_s *keyinfo; - - xfree (serialno); - err = agent_card_keyinfo (ctrl, hexgrip, 0, &keyinfo); - if (!err) - { - /* Key for GRIP found, use it directly. */ - agent_card_free_keyinfo (keyinfo); - xfree (want_sn); - if ((*r_kid = xtrystrdup (hexgrip))) - return 0; - else - return gpg_error_from_syserror (); - } - } - - if (!want_sn) - ; /* No shadow info so we can't ask; ERR is already set. */ - else if (asprintf (&desc, - "%s:%%0A%%0A" - " %s", - L_("Please insert the card with serial number"), - want_sn) < 0) - { - err = out_of_core (); - } - else - { - err = agent_get_confirmation (ctrl, desc, NULL, NULL, 0); - if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK && - gpg_err_code (err) == GPG_ERR_NO_PIN_ENTRY) - err = gpg_error (GPG_ERR_CARD_NOT_PRESENT); - - xfree (desc); - } - - if (err) - { - xfree (want_sn); - return err; - } - } -} - - /* Put the DIGEST into an DER encoded container and return it in R_VAL. */ static int encode_md_for_card (const unsigned char *digest, size_t digestlen, int algo, unsigned char **r_val, size_t *r_len) { unsigned char *frame; unsigned char asn[100]; size_t asnlen; *r_val = NULL; *r_len = 0; asnlen = DIM(asn); if (!algo || gcry_md_test_algo (algo)) return gpg_error (GPG_ERR_DIGEST_ALGO); if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen)) { log_error ("no object identifier for algo %d\n", algo); return gpg_error (GPG_ERR_INTERNAL); } frame = xtrymalloc (asnlen + digestlen); if (!frame) return out_of_core (); memcpy (frame, asn, asnlen); memcpy (frame+asnlen, digest, digestlen); if (DBG_CRYPTO) log_printhex (frame, asnlen+digestlen, "encoded hash:"); *r_val = frame; *r_len = asnlen+digestlen; return 0; } /* Return true if STRING ends in "%0A". */ static int has_percent0A_suffix (const char *string) { size_t n; return (string && (n = strlen (string)) >= 3 && !strcmp (string + n - 3, "%0A")); } /* Callback used to ask for the PIN which should be set into BUF. The buf has been allocated by the caller and is of size MAXBUF which includes the terminating null. The function should return an UTF-8 string with the passphrase, the buffer may optionally be padded with arbitrary characters. If DESC_TEXT is not NULL it can be used as further information shown atop of the INFO message. INFO gets displayed as part of a generic string. However if the first character of INFO is a vertical bar all up to the next verical bar are considered flags and only everything after the second vertical bar gets displayed as the full prompt. Flags: 'N' = New PIN, this requests a second prompt to repeat the PIN. If the PIN is not correctly repeated it starts from all over. 'A' = The PIN is an Admin PIN, SO-PIN or alike. 'P' = The PIN is a PUK (Personal Unblocking Key). 'R' = The PIN is a Reset Code. Example: "|AN|Please enter the new security officer's PIN" The text "Please ..." will get displayed and the flags 'A' and 'N' are considered. */ static int getpin_cb (void *opaque, const char *desc_text, const char *info, char *buf, size_t maxbuf) { struct pin_entry_info_s *pi; int rc; ctrl_t ctrl = opaque; const char *ends, *s; int any_flags = 0; int newpin = 0; int resetcode = 0; int is_puk = 0; const char *again_text = NULL; const char *prompt = "PIN"; if (buf && maxbuf < 2) return gpg_error (GPG_ERR_INV_VALUE); /* Parse the flags. */ if (info && *info =='|' && (ends=strchr (info+1, '|'))) { for (s=info+1; s < ends; s++) { if (*s == 'A') prompt = L_("Admin PIN"); else if (*s == 'P') { /* TRANSLATORS: A PUK is the Personal Unblocking Code used to unblock a PIN. */ prompt = L_("PUK"); is_puk = 1; } else if (*s == 'N') newpin = 1; else if (*s == 'R') { prompt = L_("Reset Code"); resetcode = 1; } } info = ends+1; any_flags = 1; } else if (info && *info == '|') log_debug ("pin_cb called without proper PIN info hack\n"); /* If BUF has been passed as NULL, we are in pinpad mode: The callback opens the popup and immediately returns. */ if (!buf) { if (maxbuf == 0) /* Close the pinentry. */ { agent_popup_message_stop (ctrl); rc = 0; } else if (maxbuf == 1) /* Open the pinentry. */ { if (info) { char *desc; const char *desc2; if (!strcmp (info, "--ack")) { desc2 = L_("Push ACK button on card/token."); if (desc_text) { desc = strconcat (desc_text, has_percent0A_suffix (desc_text) ? "%0A" : "%0A%0A", desc2, NULL); desc2 = NULL; } else desc = NULL; } else { desc2 = NULL; if (desc_text) desc = strconcat (desc_text, has_percent0A_suffix (desc_text) ? "%0A" : "%0A%0A", info, "%0A%0A", L_("Use the reader's pinpad for input."), NULL); else desc = strconcat (info, "%0A%0A", L_("Use the reader's pinpad for input."), NULL); } if (!desc2 && !desc) rc = gpg_error_from_syserror (); else { rc = agent_popup_message_start (ctrl, desc2? desc2:desc, NULL); xfree (desc); } } else rc = agent_popup_message_start (ctrl, desc_text, NULL); } else rc = gpg_error (GPG_ERR_INV_VALUE); return rc; } /* FIXME: keep PI and TRIES in OPAQUE. Frankly this is a whole mess because we should call the card's verify function from the pinentry check pin CB. */ again: pi = gcry_calloc_secure (1, sizeof (*pi) + maxbuf + 10); if (!pi) return gpg_error_from_syserror (); pi->max_length = maxbuf-1; pi->min_digits = 0; /* we want a real passphrase */ pi->max_digits = 16; pi->max_tries = 3; if (any_flags) { { char *desc2; if (desc_text) desc2 = strconcat (desc_text, has_percent0A_suffix (desc_text) ? "%0A" : "%0A%0A", info, NULL); else desc2 = NULL; rc = agent_askpin (ctrl, desc2? desc2 : info, prompt, again_text, pi, NULL, 0); xfree (desc2); } again_text = NULL; if (!rc && newpin) { struct pin_entry_info_s *pi2; pi2 = gcry_calloc_secure (1, sizeof (*pi) + maxbuf + 10); if (!pi2) { rc = gpg_error_from_syserror (); xfree (pi); return rc; } pi2->max_length = maxbuf-1; pi2->min_digits = 0; pi2->max_digits = 16; pi2->max_tries = 1; rc = agent_askpin (ctrl, (resetcode? L_("Repeat this Reset Code"): is_puk? L_("Repeat this PUK"): L_("Repeat this PIN")), prompt, NULL, pi2, NULL, 0); if (!rc && strcmp (pi->pin, pi2->pin)) { again_text = (resetcode? L_("Reset Code not correctly repeated; try again"): is_puk? L_("PUK not correctly repeated; try again"): L_("PIN not correctly repeated; try again")); xfree (pi2); xfree (pi); goto again; } xfree (pi2); } } else { char *desc, *desc2; if ( asprintf (&desc, L_("Please enter the PIN%s%s%s to unlock the card"), info? " (":"", info? info:"", info? ")":"") < 0) desc = NULL; if (desc_text) desc2 = strconcat (desc_text, has_percent0A_suffix (desc_text) ? "%0A" : "%0A%0A", desc, NULL); else desc2 = NULL; rc = agent_askpin (ctrl, desc2? desc2 : desc? desc : info, prompt, NULL, pi, NULL, 0); xfree (desc2); xfree (desc); } if (!rc) { strncpy (buf, pi->pin, maxbuf-1); buf[maxbuf-1] = 0; } xfree (pi); return rc; } /* This function is used when a sign operation has been diverted to a - * smartcard. DESC_TEXT is the original text for a prompt has send by - * gpg to gpg-agent. + * smartcard. * * Note: If SHADOW_INFO is NULL the user can't be asked to insert the * card, we simply try to use an inserted card with the given keygrip. * * FIXME: Explain the other args. */ int -divert_pksign (ctrl_t ctrl, const char *desc_text, const unsigned char *grip, +divert_pksign (ctrl_t ctrl, const unsigned char *grip, const unsigned char *digest, size_t digestlen, int algo, - const unsigned char *shadow_info, unsigned char **r_sig, + unsigned char **r_sig, size_t *r_siglen) { int rc; - char *kid; + char hexgrip[41]; size_t siglen; unsigned char *sigval = NULL; - (void)desc_text; - - rc = ask_for_card (ctrl, shadow_info, grip, &kid); - if (rc) - return rc; - /* Note that the KID may be an keyref or a keygrip. The signing - * functions handle both. */ + bin2hex (grip, 20, hexgrip); if (!algo) { /* This is the PureEdDSA case. (DIGEST,DIGESTLEN) this the * entire data which will be signed. */ - rc = agent_card_pksign (ctrl, kid, getpin_cb, ctrl, NULL, + rc = agent_card_pksign (ctrl, hexgrip, getpin_cb, ctrl, NULL, 0, digest, digestlen, &sigval, &siglen); } else if (algo == MD_USER_TLS_MD5SHA1) { int save = ctrl->use_auth_call; ctrl->use_auth_call = 1; - rc = agent_card_pksign (ctrl, kid, getpin_cb, ctrl, NULL, + rc = agent_card_pksign (ctrl, hexgrip, getpin_cb, ctrl, NULL, algo, digest, digestlen, &sigval, &siglen); ctrl->use_auth_call = save; } else { unsigned char *data; size_t ndata; rc = encode_md_for_card (digest, digestlen, algo, &data, &ndata); if (!rc) { - rc = agent_card_pksign (ctrl, kid, getpin_cb, ctrl, NULL, + rc = agent_card_pksign (ctrl, hexgrip, getpin_cb, ctrl, NULL, algo, data, ndata, &sigval, &siglen); xfree (data); } } if (!rc) { *r_sig = sigval; *r_siglen = siglen; } - xfree (kid); - return rc; } /* Decrypt the value given asn an S-expression in CIPHER using the key identified by SHADOW_INFO and return the plaintext in an allocated buffer in R_BUF. The padding information is stored at R_PADDING with -1 for not known. */ int -divert_pkdecrypt (ctrl_t ctrl, const char *desc_text, +divert_pkdecrypt (ctrl_t ctrl, const unsigned char *grip, const unsigned char *cipher, - const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding) { int rc; - char *kid; + char hexgrip[41]; const unsigned char *s; size_t n; int depth; const unsigned char *ciphertext; size_t ciphertextlen; char *plaintext; size_t plaintextlen; - (void)desc_text; + bin2hex (grip, 20, hexgrip); *r_padding = -1; s = cipher; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "enc-val")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); /* First check whether we have a flags parameter and skip it. */ if (smatch (&s, n, "flags")) { depth = 1; if (sskip (&s, &depth) || depth) return gpg_error (GPG_ERR_INV_SEXP); if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); } if (smatch (&s, n, "rsa")) { if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "a")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); } else if (smatch (&s, n, "ecdh")) { if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "s")) { n = snext (&s); s += n; if (*s++ != ')') return gpg_error (GPG_ERR_INV_SEXP); if (*s++ != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); } if (!smatch (&s, n, "e")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); } else return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); if (!n) return gpg_error (GPG_ERR_UNKNOWN_SEXP); ciphertext = s; ciphertextlen = n; - rc = ask_for_card (ctrl, shadow_info, grip, &kid); - if (rc) - return rc; - - rc = agent_card_pkdecrypt (ctrl, kid, getpin_cb, ctrl, NULL, + rc = agent_card_pkdecrypt (ctrl, hexgrip, getpin_cb, ctrl, NULL, ciphertext, ciphertextlen, &plaintext, &plaintextlen, r_padding); if (!rc) { *r_buf = plaintext; *r_len = plaintextlen; } - xfree (kid); return rc; } gpg_error_t divert_writekey (ctrl_t ctrl, int force, const char *serialno, const char *keyref, const char *keydata, size_t keydatalen) { return agent_card_writekey (ctrl, force, serialno, keyref, keydata, keydatalen, getpin_cb, ctrl); } int divert_generic_cmd (ctrl_t ctrl, const char *cmdline, void *assuan_context) { return agent_card_scd (ctrl, cmdline, getpin_cb, ctrl, assuan_context); } diff --git a/agent/divert-tpm2.c b/agent/divert-tpm2.c index 0741c6847..4cae66218 100644 --- a/agent/divert-tpm2.c +++ b/agent/divert-tpm2.c @@ -1,147 +1,144 @@ #include #include #include #include #include #include #include #include #include #include "agent.h" #include "../common/i18n.h" #include "../common/sexp-parse.h" int -divert_tpm2_pksign (ctrl_t ctrl, const char *desc_text, +divert_tpm2_pksign (ctrl_t ctrl, const unsigned char *digest, size_t digestlen, int algo, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen) { - (void)desc_text; (void)algo; return agent_tpm2d_pksign(ctrl, digest, digestlen, shadow_info, r_sig, r_siglen); } static gpg_error_t agent_write_tpm2_shadow_key (ctrl_t ctrl, const unsigned char *grip, unsigned char *shadow_info) { gpg_error_t err; unsigned char *shdkey; unsigned char *pkbuf; size_t len; gcry_sexp_t s_pkey; err = agent_public_key_from_file (ctrl, grip, &s_pkey); len = gcry_sexp_sprint(s_pkey, GCRYSEXP_FMT_CANON, NULL, 0); pkbuf = xtrymalloc (len); gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, pkbuf, len); gcry_sexp_release (s_pkey); err = agent_shadow_key_type (pkbuf, shadow_info, "tpm2-v1", &shdkey); xfree (pkbuf); if (err) { log_error ("shadowing the key failed: %s\n", gpg_strerror (err)); return err; } len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL); err = agent_write_private_key (grip, shdkey, len, 1 /*force*/, NULL, NULL, 0); xfree (shdkey); if (err) log_error ("error writing key: %s\n", gpg_strerror (err)); return err; } int divert_tpm2_writekey (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t s_skey) { int ret; /* shadow_info is always shielded so no special handling required */ unsigned char *shadow_info; ret = agent_tpm2d_writekey(ctrl, &shadow_info, s_skey); if (!ret) { ret = agent_write_tpm2_shadow_key (ctrl, grip, shadow_info); xfree (shadow_info); } return ret; } int -divert_tpm2_pkdecrypt (ctrl_t ctrl, const char *desc_text, +divert_tpm2_pkdecrypt (ctrl_t ctrl, const unsigned char *cipher, const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding) { const unsigned char *s; size_t n; *r_padding = -1; - (void)desc_text; - s = cipher; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "enc-val")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "rsa")) { *r_padding = 0; if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "a")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); } else if (smatch (&s, n, "ecdh")) { if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "s")) { n = snext (&s); s += n; if (*s++ != ')') return gpg_error (GPG_ERR_INV_SEXP); if (*s++ != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); } if (!smatch (&s, n, "e")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); } else return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); return agent_tpm2d_pkdecrypt (ctrl, s, n, shadow_info, r_buf, r_len); } diff --git a/agent/findkey.c b/agent/findkey.c index 2612383b5..eadf283d3 100644 --- a/agent/findkey.c +++ b/agent/findkey.c @@ -1,1620 +1,1738 @@ /* findkey.c - Locate the secret key * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007, * 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2014, 2019 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 . */ #include #include #include #include #include #include #include #include #include #include /* (we use pth_sleep) */ #include "agent.h" #include "../common/i18n.h" #include "../common/ssh-utils.h" #include "../common/name-value.h" #ifndef O_BINARY #define O_BINARY 0 #endif /* Helper to pass data to the check callback of the unprotect function. */ struct try_unprotect_arg_s { ctrl_t ctrl; const unsigned char *protected_key; unsigned char *unprotected_key; int change_required; /* Set by the callback to indicate that the user should change the passphrase. */ }; /* Repalce all linefeeds in STRING by "%0A" and return a new malloced * string. May return NULL on memory error. */ static char * linefeed_to_percent0A (const char *string) { const char *s; size_t n; char *buf, *p; for (n=0, s=string; *s; s++) if (*s == '\n') n += 3; else n++; p = buf = xtrymalloc (n+1); if (!buf) return NULL; for (s=string; *s; s++) if (*s == '\n') { memcpy (p, "%0A", 3); p += 3; } else *p++ = *s; *p = 0; return buf; } /* Note: Ownership of FNAME and FP are moved to this function. */ static gpg_error_t write_extended_private_key (char *fname, estream_t fp, int update, int newkey, const void *buf, size_t len, const char *serialno, const char *keyref, time_t timestamp) { gpg_error_t err; nvc_t pk = NULL; gcry_sexp_t key = NULL; int remove = 0; char *token = NULL; if (update) { int line; err = nvc_parse_private_key (&pk, &line, fp); if (err && gpg_err_code (err) != GPG_ERR_ENOENT) { log_error ("error parsing '%s' line %d: %s\n", fname, line, gpg_strerror (err)); goto leave; } } else { pk = nvc_new_private_key (); if (!pk) { err = gpg_error_from_syserror (); goto leave; } } es_clearerr (fp); err = gcry_sexp_sscan (&key, NULL, buf, len); if (err) goto leave; err = nvc_set_private_key (pk, key); if (err) goto leave; /* If requested write a Token line. */ if (serialno && keyref) { nve_t item; const char *s; token = strconcat (serialno, " ", keyref, NULL); if (!token) { err = gpg_error_from_syserror (); goto leave; } /* fixme: the strcmp should compare only the first two strings. */ for (item = nvc_lookup (pk, "Token:"); item; item = nve_next_value (item, "Token:")) if ((s = nve_value (item)) && !strcmp (s, token)) break; if (!item) { /* No token or no token with that value exists. Add a new * one so that keys which have been stored on several cards * are well supported. */ err = nvc_add (pk, "Token:", token); if (err) goto leave; } } /* If a timestamp has been supplied and the key is new write a * creation timestamp. (We douple check that there is no Created * item yet.)*/ if (timestamp && newkey && !nvc_lookup (pk, "Created:")) { gnupg_isotime_t timebuf; epoch2isotime (timebuf, timestamp); err = nvc_add (pk, "Created:", timebuf); if (err) goto leave; } err = es_fseek (fp, 0, SEEK_SET); if (err) goto leave; err = nvc_write (pk, fp); if (err) { log_error ("error writing '%s': %s\n", fname, gpg_strerror (err)); remove = 1; goto leave; } if (ftruncate (es_fileno (fp), es_ftello (fp))) { err = gpg_error_from_syserror (); log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err)); remove = 1; goto leave; } if (es_fclose (fp)) { err = gpg_error_from_syserror (); log_error ("error closing '%s': %s\n", fname, gpg_strerror (err)); remove = 1; goto leave; } else fp = NULL; bump_key_eventcounter (); leave: es_fclose (fp); if (remove) gnupg_remove (fname); xfree (fname); gcry_sexp_release (key); nvc_release (pk); xfree (token); return err; } /* Write an S-expression formatted key to our key storage. With FORCE * passed as true an existing key with the given GRIP will get * overwritten. If SERIALNO and KEYREF are given a Token line is * added to the key if the extended format is used. If TIMESTAMP is * not zero and the key doies not yet exists it will be recorded as * creation date. */ int agent_write_private_key (const unsigned char *grip, const void *buffer, size_t length, int force, const char *serialno, const char *keyref, time_t timestamp) { char *fname; estream_t fp; char hexgrip[40+4+1]; bin2hex (grip, 20, hexgrip); strcpy (hexgrip+40, ".key"); fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL); /* FIXME: Write to a temp file first so that write failures during key updates won't lead to a key loss. */ if (!force && !gnupg_access (fname, F_OK)) { log_error ("secret key file '%s' already exists\n", fname); xfree (fname); return gpg_error (GPG_ERR_EEXIST); } fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw"); if (!fp) { gpg_error_t tmperr = gpg_error_from_syserror (); if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT) { fp = es_fopen (fname, "wbx,mode=-rw"); if (!fp) tmperr = gpg_error_from_syserror (); } if (!fp) { log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr)); xfree (fname); return tmperr; } } else if (force) { gpg_error_t rc; char first; /* See if an existing key is in extended format. */ if (es_fread (&first, 1, 1, fp) != 1) { rc = gpg_error_from_syserror (); log_error ("error reading first byte from '%s': %s\n", fname, strerror (errno)); xfree (fname); es_fclose (fp); return rc; } rc = es_fseek (fp, 0, SEEK_SET); if (rc) { log_error ("error seeking in '%s': %s\n", fname, strerror (errno)); xfree (fname); es_fclose (fp); return rc; } if (first != '(') { /* Key is already in the extended format. */ return write_extended_private_key (fname, fp, 1, 0, buffer, length, serialno, keyref, timestamp); } if (first == '(' && opt.enable_extended_key_format) { /* Key is in the old format - but we want the extended format. */ return write_extended_private_key (fname, fp, 0, 0, buffer, length, serialno, keyref, timestamp); } } if (opt.enable_extended_key_format) return write_extended_private_key (fname, fp, 0, 1, buffer, length, serialno, keyref, timestamp); if (es_fwrite (buffer, length, 1, fp) != 1) { gpg_error_t tmperr = gpg_error_from_syserror (); log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr)); es_fclose (fp); gnupg_remove (fname); xfree (fname); return tmperr; } /* When force is given, the file might have to be truncated. */ if (force && ftruncate (es_fileno (fp), es_ftello (fp))) { gpg_error_t tmperr = gpg_error_from_syserror (); log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr)); es_fclose (fp); gnupg_remove (fname); xfree (fname); return tmperr; } if (es_fclose (fp)) { gpg_error_t tmperr = gpg_error_from_syserror (); log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr)); gnupg_remove (fname); xfree (fname); return tmperr; } bump_key_eventcounter (); xfree (fname); return 0; } /* Callback function to try the unprotection from the passphrase query code. */ static gpg_error_t try_unprotect_cb (struct pin_entry_info_s *pi) { struct try_unprotect_arg_s *arg = pi->check_cb_arg; ctrl_t ctrl = arg->ctrl; size_t dummy; gpg_error_t err; gnupg_isotime_t now, protected_at, tmptime; char *desc = NULL; log_assert (!arg->unprotected_key); arg->change_required = 0; err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at, &arg->unprotected_key, &dummy); if (err) return err; if (!opt.max_passphrase_days || ctrl->in_passwd) return 0; /* No regular passphrase change required. */ if (!*protected_at) { /* No protection date known - must force passphrase change. */ desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A" "Please change it now.")); if (!desc) return gpg_error_from_syserror (); } else { gnupg_get_isotime (now); gnupg_copy_time (tmptime, protected_at); err = add_days_to_isotime (tmptime, opt.max_passphrase_days); if (err) return err; if (strcmp (now, tmptime) > 0 ) { /* Passphrase "expired". */ desc = xtryasprintf (L_("This passphrase has not been changed%%0A" "since %.4s-%.2s-%.2s. Please change it now."), protected_at, protected_at+4, protected_at+6); if (!desc) return gpg_error_from_syserror (); } } if (desc) { /* Change required. */ if (opt.enforce_passphrase_constraints) { err = agent_get_confirmation (ctrl, desc, L_("Change passphrase"), NULL, 0); if (!err) arg->change_required = 1; } else { err = agent_get_confirmation (ctrl, desc, L_("Change passphrase"), L_("I'll change it later"), 0); if (!err) arg->change_required = 1; else if (gpg_err_code (err) == GPG_ERR_CANCELED || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED) err = 0; } xfree (desc); } return err; } /* Return true if the STRING has an %C or %c expando. */ static int has_comment_expando (const char *string) { const char *s; int percent = 0; if (!string) return 0; for (s = string; *s; s++) { if (percent) { if (*s == 'c' || *s == 'C') return 1; percent = 0; } else if (*s == '%') percent = 1; } return 0; } /* Modify a Key description, replacing certain special format characters. List of currently supported replacements: %% - Replaced by a single % %c - Replaced by the content of COMMENT. %C - Same as %c but put into parentheses. %F - Replaced by an ssh style fingerprint computed from KEY. The functions returns 0 on success or an error code. On success a newly allocated string is stored at the address of RESULT. */ gpg_error_t agent_modify_description (const char *in, const char *comment, const gcry_sexp_t key, char **result) { size_t comment_length; size_t in_len; size_t out_len; char *out; size_t i; int special, pass; char *ssh_fpr = NULL; char *p; *result = NULL; if (!comment) comment = ""; comment_length = strlen (comment); in_len = strlen (in); /* First pass calculates the length, second pass does the actual copying. */ /* FIXME: This can be simplified by using es_fopenmem. */ out = NULL; out_len = 0; for (pass=0; pass < 2; pass++) { special = 0; for (i = 0; i < in_len; i++) { if (special) { special = 0; switch (in[i]) { case '%': if (out) *out++ = '%'; else out_len++; break; case 'c': /* Comment. */ if (out) { memcpy (out, comment, comment_length); out += comment_length; } else out_len += comment_length; break; case 'C': /* Comment. */ if (!comment_length) ; else if (out) { *out++ = '('; memcpy (out, comment, comment_length); out += comment_length; *out++ = ')'; } else out_len += comment_length + 2; break; case 'F': /* SSH style fingerprint. */ if (!ssh_fpr && key) ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest, &ssh_fpr); if (ssh_fpr) { if (out) out = stpcpy (out, ssh_fpr); else out_len += strlen (ssh_fpr); } break; default: /* Invalid special sequences are kept as they are. */ if (out) { *out++ = '%'; *out++ = in[i]; } else out_len+=2; break; } } else if (in[i] == '%') special = 1; else { if (out) *out++ = in[i]; else out_len++; } } if (!pass) { *result = out = xtrymalloc (out_len + 1); if (!out) { xfree (ssh_fpr); return gpg_error_from_syserror (); } } } *out = 0; log_assert (*result + out_len == out); xfree (ssh_fpr); /* The ssh prompt may sometimes end in * "...%0A ()" * The empty parentheses doesn't look very good. We use this hack * here to remove them as well as the indentation spaces. */ p = *result; i = strlen (p); if (i > 2 && !strcmp (p + i - 2, "()")) { p += i - 2; *p-- = 0; while (p > *result && spacep (p)) *p-- = 0; } return 0; } /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP should be the hex encoded keygrip of that key to be used with the caching mechanism. DESC_TEXT may be set to override the default description used for the pinentry. If LOOKUP_TTL is given this function is used to lookup the default ttl. If R_PASSPHRASE is not NULL, the function succeeded and the key was protected the used passphrase (entered or from the cache) is stored there; if not NULL will be stored. The caller needs to free the returned passphrase. */ static gpg_error_t unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, unsigned char **keybuf, const unsigned char *grip, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, char **r_passphrase) { struct pin_entry_info_s *pi; struct try_unprotect_arg_s arg; int rc; unsigned char *result; size_t resultlen; char hexgrip[40+1]; if (r_passphrase) *r_passphrase = NULL; bin2hex (grip, 20, hexgrip); /* Initially try to get it using a cache nonce. */ if (cache_nonce) { char *pw; pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE); if (pw) { rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen); if (!rc) { if (r_passphrase) *r_passphrase = pw; else xfree (pw); xfree (*keybuf); *keybuf = result; return 0; } xfree (pw); } } /* First try to get it from the cache - if there is none or we can't unprotect it, we fall back to ask the user */ if (cache_mode != CACHE_MODE_IGNORE) { char *pw; retry: pw = agent_get_cache (ctrl, hexgrip, cache_mode); if (pw) { rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen); if (!rc) { if (cache_mode == CACHE_MODE_NORMAL) agent_store_cache_hit (hexgrip); if (r_passphrase) *r_passphrase = pw; else xfree (pw); xfree (*keybuf); *keybuf = result; return 0; } xfree (pw); } else if (cache_mode == CACHE_MODE_NORMAL) { /* The standard use of GPG keys is to have a signing and an encryption subkey. Commonly both use the same passphrase. We try to help the user to enter the passphrase only once by silently trying the last correctly entered passphrase. Checking one additional passphrase should be acceptable; despite the S2K introduced delays. The assumed workflow is: 1. Read encrypted message in a MUA and thus enter a passphrase for the encryption subkey. 2. Reply to that mail with an encrypted and signed mail, thus entering the passphrase for the signing subkey. We can often avoid the passphrase entry in the second step. We do this only in normal mode, so not to interfere with unrelated cache entries. */ pw = agent_get_cache (ctrl, NULL, cache_mode); if (pw) { rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen); if (!rc) { if (r_passphrase) *r_passphrase = pw; else xfree (pw); xfree (*keybuf); *keybuf = result; return 0; } xfree (pw); } } /* If the pinentry is currently in use, we wait up to 60 seconds for it to close and check the cache again. This solves a common situation where several requests for unprotecting a key have been made but the user is still entering the passphrase for the first request. Because all requests to agent_askpin are serialized they would then pop up one after the other to request the passphrase - despite that the user has already entered it and is then available in the cache. This implementation is not race free but in the worst case the user has to enter the passphrase only once more. */ if (pinentry_active_p (ctrl, 0)) { /* Active - wait */ if (!pinentry_active_p (ctrl, 60)) { /* We need to give the other thread a chance to actually put it into the cache. */ gnupg_sleep (1); goto retry; } /* Timeout - better call pinentry now the plain way. */ } } pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1); if (!pi) return gpg_error_from_syserror (); pi->max_length = MAX_PASSPHRASE_LEN + 1; pi->min_digits = 0; /* we want a real passphrase */ pi->max_digits = 16; pi->max_tries = 3; pi->check_cb = try_unprotect_cb; arg.ctrl = ctrl; arg.protected_key = *keybuf; arg.unprotected_key = NULL; arg.change_required = 0; pi->check_cb_arg = &arg; rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode); if (rc) { if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE)) { log_error ("Clearing pinentry cache which caused error %s\n", gpg_strerror (rc)); agent_clear_passphrase (ctrl, hexgrip, cache_mode); } } else { log_assert (arg.unprotected_key); if (arg.change_required) { /* The callback told as that the user should change their passphrase. Present the dialog to do. */ size_t canlen, erroff; gcry_sexp_t s_skey; log_assert (arg.unprotected_key); canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL); rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)arg.unprotected_key, canlen); if (rc) { log_error ("failed to build S-Exp (off=%u): %s\n", (unsigned int)erroff, gpg_strerror (rc)); wipememory (arg.unprotected_key, canlen); xfree (arg.unprotected_key); xfree (pi); return rc; } rc = agent_protect_and_store (ctrl, s_skey, NULL); gcry_sexp_release (s_skey); if (rc) { log_error ("changing the passphrase failed: %s\n", gpg_strerror (rc)); wipememory (arg.unprotected_key, canlen); xfree (arg.unprotected_key); xfree (pi); return rc; } } else { /* Passphrase is fine. */ agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin, lookup_ttl? lookup_ttl (hexgrip) : 0); agent_store_cache_hit (hexgrip); if (r_passphrase && *pi->pin) *r_passphrase = xtrystrdup (pi->pin); } xfree (*keybuf); *keybuf = arg.unprotected_key; } xfree (pi); return rc; } /* Read the key identified by GRIP from the private key directory and * return it as an gcrypt S-expression object in RESULT. If R_KEYMETA * is not NULl and the extended key format is used, the meta data * items are stored there. However the "Key:" item is removed from * it. On failure returns an error code and stores NULL at RESULT and * R_KEYMETA. */ static gpg_error_t read_key_file (const unsigned char *grip, gcry_sexp_t *result, nvc_t *r_keymeta) { gpg_error_t err; char *fname; estream_t fp; struct stat st; unsigned char *buf; size_t buflen, erroff; gcry_sexp_t s_skey; char hexgrip[40+4+1]; char first; *result = NULL; if (r_keymeta) *r_keymeta = NULL; bin2hex (grip, 20, hexgrip); strcpy (hexgrip+40, ".key"); fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL); fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) != GPG_ERR_ENOENT) log_error ("can't open '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); return err; } if (es_fread (&first, 1, 1, fp) != 1) { err = gpg_error_from_syserror (); log_error ("error reading first byte from '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); es_fclose (fp); return err; } if (es_fseek (fp, 0, SEEK_SET)) { err = gpg_error_from_syserror (); log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); es_fclose (fp); return err; } if (first != '(') { /* Key is in extended format. */ nvc_t pk = NULL; int line; err = nvc_parse_private_key (&pk, &line, fp); es_fclose (fp); if (err) log_error ("error parsing '%s' line %d: %s\n", fname, line, gpg_strerror (err)); else { err = nvc_get_private_key (pk, result); if (err) log_error ("error getting private key from '%s': %s\n", fname, gpg_strerror (err)); else nvc_delete_named (pk, "Key:"); } if (!err && r_keymeta) *r_keymeta = pk; else nvc_release (pk); xfree (fname); return err; } if (fstat (es_fileno (fp), &st)) { err = gpg_error_from_syserror (); log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); es_fclose (fp); return err; } buflen = st.st_size; buf = xtrymalloc (buflen+1); if (!buf) { err = gpg_error_from_syserror (); log_error ("error allocating %zu bytes for '%s': %s\n", buflen, fname, gpg_strerror (err)); xfree (fname); es_fclose (fp); xfree (buf); return err; } if (es_fread (buf, buflen, 1, fp) != 1) { err = gpg_error_from_syserror (); log_error ("error reading %zu bytes from '%s': %s\n", buflen, fname, gpg_strerror (err)); xfree (fname); es_fclose (fp); xfree (buf); return err; } /* Convert the file into a gcrypt S-expression object. */ err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen); xfree (fname); es_fclose (fp); xfree (buf); if (err) { log_error ("failed to build S-Exp (off=%u): %s\n", (unsigned int)erroff, gpg_strerror (err)); return err; } *result = s_skey; return 0; } /* Remove the key identified by GRIP from the private key directory. */ static gpg_error_t remove_key_file (const unsigned char *grip) { gpg_error_t err = 0; char *fname; char hexgrip[40+4+1]; bin2hex (grip, 20, hexgrip); strcpy (hexgrip+40, ".key"); fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL); if (gnupg_remove (fname)) err = gpg_error_from_syserror (); xfree (fname); return err; } +/* + * Prompt a user the card insertion, when it's not available yet. + */ +static gpg_error_t +prompt_for_card (ctrl_t ctrl, const unsigned char *shadow_info, + const unsigned char *grip) +{ + char *serialno; + char *desc; + char *want_sn; + int len; + gpg_error_t err; + char hexgrip[41]; + + bin2hex (grip, 20, hexgrip); + + if (shadow_info) + { + err = parse_shadow_info (shadow_info, &want_sn, NULL, NULL); + if (err) + return err; + } + else + want_sn = NULL; + + len = want_sn? strlen (want_sn) : 0; + if (len == 32 && !strncmp (want_sn, "D27600012401", 12)) + { + /* This is an OpenPGP card - reformat */ + if (!strncmp (want_sn+16, "0006", 4)) + { + /* This is a Yubikey. Print the s/n as it would be printed + * on Yubikey 5. Example: D2760001240100000006120808620000 + * mmmm^^^^^^^^ */ + unsigned long sn; + + sn = atoi_4 (want_sn+20) * 10000; + sn += atoi_4 (want_sn+24); + snprintf (want_sn, 32, "%lu %03lu %03lu", + (sn/1000000ul), (sn/1000ul % 1000ul), (sn % 1000ul)); + } + else /* Default is the Zeitcontrol card print format. */ + { + memmove (want_sn, want_sn+16, 4); + want_sn[4] = ' '; + memmove (want_sn+5, want_sn+20, 8); + want_sn[13] = 0; + } + } + else if (len == 20 && want_sn[19] == '0') + { + /* We assume that a 20 byte serial number is a standard one + * which has the property to have a zero in the last nibble (Due + * to BCD representation). We don't display this '0' because it + * may confuse the user. */ + want_sn[19] = 0; + } + + for (;;) + { + /* Scan device(s), and check if key for GRIP is available. */ + err = agent_card_serialno (ctrl, &serialno, NULL); + if (!err) + { + struct card_key_info_s *keyinfo; + + xfree (serialno); + err = agent_card_keyinfo (ctrl, hexgrip, 0, &keyinfo); + if (!err) + { + /* Key for GRIP found, use it directly. */ + agent_card_free_keyinfo (keyinfo); + xfree (want_sn); + return 0; + } + } + + if (!want_sn) + ; /* No shadow info so we can't ask; ERR is already set. */ + else if (asprintf (&desc, + "%s:%%0A%%0A" + " %s", + L_("Please insert the card with serial number"), + want_sn) < 0) + { + err = out_of_core (); + } + else + { + err = agent_get_confirmation (ctrl, desc, NULL, NULL, 0); + if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK && + gpg_err_code (err) == GPG_ERR_NO_PIN_ENTRY) + err = gpg_error (GPG_ERR_CARD_NOT_PRESENT); + + xfree (desc); + } + + if (err) + { + xfree (want_sn); + return err; + } + } +} + + /* Return the secret key as an S-Exp in RESULT after locating it using the GRIP. Caller should set GRIP=NULL, when a key in a file is intended to be used for cryptographic operation. In this case, CTRL->keygrip is used to locate the file, and it may ask a user for confirmation. If the operation shall be diverted to a token, an allocated S-expression with the shadow_info part from the file is stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO. CACHE_MODE defines now the cache shall be used. DESC_TEXT may be set to present a custom description for the pinentry. LOOKUP_TTL is an optional function to convey a TTL to the cache manager; we do not simply pass the TTL value because the value is only needed if an unprotect action was needed and looking up the TTL may have some overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is given that cache item is first tried to get a passphrase. If R_PASSPHRASE is not NULL, the function succeeded and the key was protected the used passphrase (entered or from the cache) is stored there; if not NULL will be stored. The caller needs to free the returned passphrase. */ gpg_error_t agent_key_from_file (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, const unsigned char *grip, unsigned char **shadow_info, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, gcry_sexp_t *result, char **r_passphrase, time_t *r_timestamp) { gpg_error_t err; unsigned char *buf; size_t len, erroff; gcry_sexp_t s_skey; nvc_t keymeta = NULL; char *desc_text_buffer = NULL; /* Used in case we extend DESC_TEXT. */ *result = NULL; if (shadow_info) *shadow_info = NULL; if (r_passphrase) *r_passphrase = NULL; if (r_timestamp) *r_timestamp = (time_t)(-1); if (!grip && !ctrl->have_keygrip) return gpg_error (GPG_ERR_NO_SECKEY); err = read_key_file (grip? grip : ctrl->keygrip, &s_skey, &keymeta); /* For use with the protection functions we also need the key as an canonical encoded S-expression in a buffer. Create this buffer now. */ err = make_canon_sexp (s_skey, &buf, &len); if (err) { nvc_release (keymeta); xfree (desc_text_buffer); return err; } if (r_timestamp && keymeta) { const char *created = nvc_get_string (keymeta, "Created:"); if (created) *r_timestamp = isotime2epoch (created); } if (!grip && keymeta) { const char *ask_confirmation = nvc_get_string (keymeta, "Confirm:"); if (ask_confirmation && ((!strcmp (ask_confirmation, "restricted") && ctrl->restricted) || !strcmp (ask_confirmation, "yes"))) { char hexgrip[40+4+1]; char *prompt; char *comment_buffer = NULL; const char *comment = NULL; bin2hex (ctrl->keygrip, 20, hexgrip); if ((comment = nvc_get_string (keymeta, "Label:"))) { if (strchr (comment, '\n') && (comment_buffer = linefeed_to_percent0A (comment))) comment = comment_buffer; } prompt = xtryasprintf (L_("Requested the use of key%%0A" " %s%%0A" " %s%%0A" "Do you want to allow this?"), hexgrip, comment? comment:""); gcry_free (comment_buffer); err = agent_get_confirmation (ctrl, prompt, L_("Allow"), L_("Deny"), 0); xfree (prompt); if (err) return err; } } switch (agent_private_key_type (buf)) { case PRIVATE_KEY_CLEAR: break; /* no unprotection needed */ case PRIVATE_KEY_OPENPGP_NONE: { unsigned char *buf_new; size_t buf_newlen; err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen); if (err) log_error ("failed to convert unprotected openpgp key: %s\n", gpg_strerror (err)); else { xfree (buf); buf = buf_new; } } break; case PRIVATE_KEY_PROTECTED: { char *desc_text_final; char *comment_buffer = NULL; const char *comment = NULL; /* Note, that we will take the comment as a C string for * display purposes; i.e. all stuff beyond a Nul character is * ignored. If a "Label" entry is available in the meta data * this is used instead of the s-expression comment. */ if (keymeta && (comment = nvc_get_string (keymeta, "Label:"))) { if (strchr (comment, '\n') && (comment_buffer = linefeed_to_percent0A (comment))) comment = comment_buffer; /* In case DESC_TEXT has no escape pattern for a comment * we append one. */ if (desc_text && !has_comment_expando (desc_text)) { desc_text_buffer = strconcat (desc_text, "%0A%C", NULL); if (desc_text_buffer) desc_text = desc_text_buffer; } } else { gcry_sexp_t comment_sexp; comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0); if (comment_sexp) comment_buffer = gcry_sexp_nth_string (comment_sexp, 1); gcry_sexp_release (comment_sexp); comment = comment_buffer; } desc_text_final = NULL; if (desc_text) err = agent_modify_description (desc_text, comment, s_skey, &desc_text_final); gcry_free (comment_buffer); if (!err) { err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip? grip : ctrl->keygrip, cache_mode, lookup_ttl, r_passphrase); if (err) log_error ("failed to unprotect the secret key: %s\n", gpg_strerror (err)); } xfree (desc_text_final); } break; case PRIVATE_KEY_SHADOWED: if (shadow_info) { const unsigned char *s; + unsigned char *shadow_type; size_t n; - err = agent_get_shadow_info (buf, &s); + err = agent_get_shadow_info_type (buf, &s, &shadow_type); if (!err) { n = gcry_sexp_canon_len (s, 0, NULL,NULL); log_assert (n); *shadow_info = xtrymalloc (n); if (!*shadow_info) - err = out_of_core (); + { + err = out_of_core (); + goto shadow_error; + } else { memcpy (*shadow_info, s, n); - err = 0; + /* + * When it's a key on card (not on tpm2), maks sure + * it's available. + */ + if (strcmp (shadow_type, "t1-v1") == 0 && !grip) + err = prompt_for_card (ctrl, *shadow_info, ctrl->keygrip); } } - if (err) + else + shadow_error: log_error ("get_shadow_info failed: %s\n", gpg_strerror (err)); + + xfree (shadow_type); } else err = gpg_error (GPG_ERR_UNUSABLE_SECKEY); break; default: log_error ("invalid private key format\n"); err = gpg_error (GPG_ERR_BAD_SECKEY); break; } gcry_sexp_release (s_skey); s_skey = NULL; if (err) { xfree (buf); if (r_passphrase) { xfree (*r_passphrase); *r_passphrase = NULL; } nvc_release (keymeta); xfree (desc_text_buffer); return err; } err = sexp_sscan_private_key (result, &erroff, buf); xfree (buf); nvc_release (keymeta); xfree (desc_text_buffer); if (err) { log_error ("failed to build S-Exp (off=%u): %s\n", (unsigned int)erroff, gpg_strerror (err)); if (r_passphrase) { xfree (*r_passphrase); *r_passphrase = NULL; } } return err; } /* Return the key for the keygrip GRIP. The result is stored at RESULT. This function extracts the key from the private key database and returns it as an S-expression object as it is. On failure an error code is returned and NULL stored at RESULT. */ gpg_error_t agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t *result) { gpg_error_t err; gcry_sexp_t s_skey; (void)ctrl; *result = NULL; err = read_key_file (grip, &s_skey, NULL); if (!err) *result = s_skey; return err; } /* Return the public key for the keygrip GRIP. The result is stored at RESULT. This function extracts the public key from the private key database. On failure an error code is returned and NULL stored at RESULT. */ gpg_error_t agent_public_key_from_file (ctrl_t ctrl, const unsigned char *grip, gcry_sexp_t *result) { gpg_error_t err; int i, idx; gcry_sexp_t s_skey; const char *algoname, *elems; int npkey; gcry_mpi_t array[10]; gcry_sexp_t curve = NULL; gcry_sexp_t flags = NULL; gcry_sexp_t uri_sexp, comment_sexp; const char *uri, *comment; size_t uri_length, comment_length; int uri_intlen, comment_intlen; membuf_t format_mb; char *format; void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2 for comment + end-of-list. */ int argidx; gcry_sexp_t list = NULL; const char *s; (void)ctrl; *result = NULL; err = read_key_file (grip, &s_skey, NULL); if (err) return err; for (i=0; i < DIM (array); i++) array[i] = NULL; err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems, array, DIM (array), &curve, &flags); if (err) { gcry_sexp_release (s_skey); return err; } uri = NULL; uri_length = 0; uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0); if (uri_sexp) uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length); comment = NULL; comment_length = 0; comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0); if (comment_sexp) comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length); gcry_sexp_release (s_skey); s_skey = NULL; log_assert (sizeof (size_t) <= sizeof (void*)); init_membuf (&format_mb, 256); argidx = 0; put_membuf_printf (&format_mb, "(public-key(%s%%S%%S", algoname); args[argidx++] = &curve; args[argidx++] = &flags; for (idx=0, s=elems; idx < npkey; idx++) { put_membuf_printf (&format_mb, "(%c %%m)", *s++); log_assert (argidx < DIM (args)); args[argidx++] = &array[idx]; } put_membuf_str (&format_mb, ")"); if (uri) { put_membuf_str (&format_mb, "(uri %b)"); log_assert (argidx+1 < DIM (args)); uri_intlen = (int)uri_length; args[argidx++] = (void *)&uri_intlen; args[argidx++] = (void *)&uri; } if (comment) { put_membuf_str (&format_mb, "(comment %b)"); log_assert (argidx+1 < DIM (args)); comment_intlen = (int)comment_length; args[argidx++] = (void *)&comment_intlen; args[argidx++] = (void *)&comment; } put_membuf (&format_mb, ")", 2); log_assert (argidx < DIM (args)); args[argidx] = NULL; format = get_membuf (&format_mb, NULL); if (!format) { err = gpg_error_from_syserror (); for (i=0; array[i]; i++) gcry_mpi_release (array[i]); gcry_sexp_release (curve); gcry_sexp_release (flags); gcry_sexp_release (uri_sexp); gcry_sexp_release (comment_sexp); return err; } err = gcry_sexp_build_array (&list, NULL, format, args); xfree (format); for (i=0; array[i]; i++) gcry_mpi_release (array[i]); gcry_sexp_release (curve); gcry_sexp_release (flags); gcry_sexp_release (uri_sexp); gcry_sexp_release (comment_sexp); if (!err) *result = list; return err; } /* Check whether the secret key identified by GRIP is available. Returns 0 is the key is available. */ int agent_key_available (const unsigned char *grip) { int result; char *fname; char hexgrip[40+4+1]; bin2hex (grip, 20, hexgrip); strcpy (hexgrip+40, ".key"); fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL); result = !gnupg_access (fname, R_OK)? 0 : -1; xfree (fname); return result; } /* Return the information about the secret key specified by the binary keygrip GRIP. If the key is a shadowed one the shadow information will be stored at the address R_SHADOW_INFO as an allocated S-expression. */ gpg_error_t agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip, int *r_keytype, unsigned char **r_shadow_info, unsigned char **r_shadow_info_type) { gpg_error_t err; unsigned char *buf; size_t len; int keytype; (void)ctrl; if (r_keytype) *r_keytype = PRIVATE_KEY_UNKNOWN; if (r_shadow_info) *r_shadow_info = NULL; { gcry_sexp_t sexp; err = read_key_file (grip, &sexp, NULL); if (err) { if (gpg_err_code (err) == GPG_ERR_ENOENT) return gpg_error (GPG_ERR_NOT_FOUND); else return err; } err = make_canon_sexp (sexp, &buf, &len); gcry_sexp_release (sexp); if (err) return err; } keytype = agent_private_key_type (buf); switch (keytype) { case PRIVATE_KEY_CLEAR: case PRIVATE_KEY_OPENPGP_NONE: break; case PRIVATE_KEY_PROTECTED: /* If we ever require it we could retrieve the comment fields from such a key. */ break; case PRIVATE_KEY_SHADOWED: if (r_shadow_info) { const unsigned char *s; size_t n; err = agent_get_shadow_info_type (buf, &s, r_shadow_info_type); if (!err) { n = gcry_sexp_canon_len (s, 0, NULL, NULL); log_assert (n); *r_shadow_info = xtrymalloc (n); if (!*r_shadow_info) err = gpg_error_from_syserror (); else memcpy (*r_shadow_info, s, n); } } break; default: err = gpg_error (GPG_ERR_BAD_SECKEY); break; } if (!err && r_keytype) *r_keytype = keytype; xfree (buf); return err; } /* Delete the key with GRIP from the disk after having asked for * confirmation using DESC_TEXT. If FORCE is set the function won't * require a confirmation via Pinentry or warns if the key is also * used by ssh. If ONLY_STUBS is set only stub keys (references to * smartcards) will be affected. * * Common error codes are: * GPG_ERR_NO_SECKEY * GPG_ERR_KEY_ON_CARD * GPG_ERR_NOT_CONFIRMED * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested. */ gpg_error_t agent_delete_key (ctrl_t ctrl, const char *desc_text, const unsigned char *grip, int force, int only_stubs) { gpg_error_t err; gcry_sexp_t s_skey = NULL; unsigned char *buf = NULL; size_t len; char *desc_text_final = NULL; char *comment = NULL; ssh_control_file_t cf = NULL; char hexgrip[40+4+1]; char *default_desc = NULL; int key_type; err = read_key_file (grip, &s_skey, NULL); if (gpg_err_code (err) == GPG_ERR_ENOENT) err = gpg_error (GPG_ERR_NO_SECKEY); if (err) goto leave; err = make_canon_sexp (s_skey, &buf, &len); if (err) goto leave; key_type = agent_private_key_type (buf); if (only_stubs && key_type != PRIVATE_KEY_SHADOWED) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } switch (key_type) { case PRIVATE_KEY_CLEAR: case PRIVATE_KEY_OPENPGP_NONE: case PRIVATE_KEY_PROTECTED: bin2hex (grip, 20, hexgrip); if (!force) { if (!desc_text) { default_desc = xtryasprintf (L_("Do you really want to delete the key identified by keygrip%%0A" " %s%%0A %%C%%0A?"), hexgrip); desc_text = default_desc; } /* Note, that we will take the comment as a C string for display purposes; i.e. all stuff beyond a Nul character is ignored. */ { gcry_sexp_t comment_sexp; comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0); if (comment_sexp) comment = gcry_sexp_nth_string (comment_sexp, 1); gcry_sexp_release (comment_sexp); } if (desc_text) err = agent_modify_description (desc_text, comment, s_skey, &desc_text_final); if (err) goto leave; err = agent_get_confirmation (ctrl, desc_text_final, L_("Delete key"), L_("No"), 0); if (err) goto leave; cf = ssh_open_control_file (); if (cf) { if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL)) { err = agent_get_confirmation (ctrl, L_("Warning: This key is also listed for use with SSH!\n" "Deleting the key might remove your ability to " "access remote machines."), L_("Delete key"), L_("No"), 0); if (err) goto leave; } } } err = remove_key_file (grip); break; case PRIVATE_KEY_SHADOWED: err = remove_key_file (grip); break; default: log_error ("invalid private key format\n"); err = gpg_error (GPG_ERR_BAD_SECKEY); break; } leave: ssh_close_control_file (cf); gcry_free (comment); xfree (desc_text_final); xfree (default_desc); xfree (buf); gcry_sexp_release (s_skey); return err; } /* Write an S-expression formatted shadow key to our key storage. Shadow key is created by an S-expression public key in PKBUF and card's SERIALNO and the IDSTRING. With FORCE passed as true an existing key with the given GRIP will get overwritten. */ gpg_error_t agent_write_shadow_key (const unsigned char *grip, const char *serialno, const char *keyid, const unsigned char *pkbuf, int force) { gpg_error_t err; unsigned char *shadow_info; unsigned char *shdkey; size_t len; /* Just in case some caller did not parse the stuff correctly, skip * leading spaces. */ while (spacep (serialno)) serialno++; while (spacep (keyid)) keyid++; shadow_info = make_shadow_info (serialno, keyid); if (!shadow_info) return gpg_error_from_syserror (); err = agent_shadow_key (pkbuf, shadow_info, &shdkey); xfree (shadow_info); if (err) { log_error ("shadowing the key failed: %s\n", gpg_strerror (err)); return err; } len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL); err = agent_write_private_key (grip, shdkey, len, force, serialno, keyid, 0); xfree (shdkey); if (err) log_error ("error writing key: %s\n", gpg_strerror (err)); return err; } diff --git a/agent/pkdecrypt.c b/agent/pkdecrypt.c index ba3d90469..82818f863 100644 --- a/agent/pkdecrypt.c +++ b/agent/pkdecrypt.c @@ -1,152 +1,152 @@ /* pkdecrypt.c - public key decryption (well, actually using a secret key) * Copyright (C) 2001, 2003 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 "agent.h" /* DECRYPT the stuff in ciphertext which is expected to be a S-Exp. Try to get the key from CTRL and write the decoded stuff back to OUTFP. The padding information is stored at R_PADDING with -1 for not known. */ gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *desc_text, const unsigned char *ciphertext, size_t ciphertextlen, membuf_t *outbuf, int *r_padding) { gcry_sexp_t s_skey = NULL, s_cipher = NULL, s_plain = NULL; unsigned char *shadow_info = NULL; gpg_error_t err = 0; int no_shadow_info = 0; char *buf = NULL; size_t len; *r_padding = -1; if (!ctrl->have_keygrip) { log_error ("speculative decryption not yet supported\n"); err = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } err = gcry_sexp_sscan (&s_cipher, NULL, (char*)ciphertext, ciphertextlen); if (err) { log_error ("failed to convert ciphertext: %s\n", gpg_strerror (err)); err = gpg_error (GPG_ERR_INV_DATA); goto leave; } if (DBG_CRYPTO) { log_printhex (ctrl->keygrip, 20, "keygrip:"); log_printhex (ciphertext, ciphertextlen, "cipher: "); } err = agent_key_from_file (ctrl, NULL, desc_text, NULL, &shadow_info, CACHE_MODE_NORMAL, NULL, &s_skey, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_NO_SECKEY) no_shadow_info = 1; else if (err) { if (gpg_err_code (err) != GPG_ERR_NO_SECKEY) log_error ("failed to read the secret key\n"); goto leave; } if (shadow_info || no_shadow_info) { /* divert operation to the smartcard */ if (!gcry_sexp_canon_len (ciphertext, ciphertextlen, NULL, NULL)) { err = gpg_error (GPG_ERR_INV_SEXP); goto leave; } if (agent_is_tpm2_key (s_skey)) - err = divert_tpm2_pkdecrypt (ctrl, desc_text, ciphertext, shadow_info, + err = divert_tpm2_pkdecrypt (ctrl, ciphertext, shadow_info, &buf, &len, r_padding); else - err = divert_pkdecrypt (ctrl, desc_text, ctrl->keygrip, ciphertext, - shadow_info, &buf, &len, r_padding); + err = divert_pkdecrypt (ctrl, ctrl->keygrip, ciphertext, + &buf, &len, r_padding); if (err) { log_error ("smartcard decryption failed: %s\n", gpg_strerror (err)); goto leave; } put_membuf_printf (outbuf, "(5:value%u:", (unsigned int)len); put_membuf (outbuf, buf, len); put_membuf (outbuf, ")", 2); } else { /* No smartcard, but a private key */ /* if (DBG_CRYPTO ) */ /* { */ /* log_debug ("skey: "); */ /* gcry_sexp_dump (s_skey); */ /* } */ err = gcry_pk_decrypt (&s_plain, s_cipher, s_skey); if (err) { log_error ("decryption failed: %s\n", gpg_strerror (err)); goto leave; } if (DBG_CRYPTO) { log_debug ("plain: "); gcry_sexp_dump (s_plain); } len = gcry_sexp_sprint (s_plain, GCRYSEXP_FMT_CANON, NULL, 0); log_assert (len); buf = xmalloc (len); len = gcry_sexp_sprint (s_plain, GCRYSEXP_FMT_CANON, buf, len); log_assert (len); if (*buf == '(') put_membuf (outbuf, buf, len); else { /* Old style libgcrypt: This is only an S-expression part. Turn it into a complete S-expression. */ put_membuf (outbuf, "(5:value", 8); put_membuf (outbuf, buf, len); put_membuf (outbuf, ")", 2); } } leave: gcry_sexp_release (s_skey); gcry_sexp_release (s_plain); gcry_sexp_release (s_cipher); xfree (buf); xfree (shadow_info); return err; } diff --git a/agent/pksign.c b/agent/pksign.c index a4aff041b..dfed0e398 100644 --- a/agent/pksign.c +++ b/agent/pksign.c @@ -1,632 +1,626 @@ /* pksign.c - public key signing (well, actually using a secret key) * Copyright (C) 2001-2004, 2010 Free Software Foundation, Inc. * Copyright (C) 2001-2004, 2010, 2013 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 . */ #include #include #include #include #include #include #include #include "agent.h" #include "../common/i18n.h" static int do_encode_md (const byte * md, size_t mdlen, int algo, gcry_sexp_t * r_hash, int raw_value) { gcry_sexp_t hash; int rc; if (!raw_value) { const char *s; char tmp[16+1]; int i; s = gcry_md_algo_name (algo); if (!s || strlen (s) >= 16) { hash = NULL; rc = gpg_error (GPG_ERR_DIGEST_ALGO); } else { for (i=0; s[i]; i++) tmp[i] = ascii_tolower (s[i]); tmp[i] = '\0'; rc = gcry_sexp_build (&hash, NULL, "(data (flags pkcs1) (hash %s %b))", tmp, (int)mdlen, md); } } else { rc = gcry_sexp_build (&hash, NULL, "(data (flags raw) (value %b))", (int)mdlen, md); } *r_hash = hash; return rc; } /* Return the number of bits of the Q parameter from the DSA key KEY. */ static unsigned int get_dsa_qbits (gcry_sexp_t key) { gcry_sexp_t l1, l2; gcry_mpi_t q; unsigned int nbits; l1 = gcry_sexp_find_token (key, "private-key", 0); if (!l1) l1 = gcry_sexp_find_token (key, "protected-private-key", 0); if (!l1) l1 = gcry_sexp_find_token (key, "shadowed-private-key", 0); if (!l1) l1 = gcry_sexp_find_token (key, "public-key", 0); if (!l1) return 0; /* Does not contain a key object. */ l2 = gcry_sexp_cadr (l1); gcry_sexp_release (l1); l1 = gcry_sexp_find_token (l2, "q", 1); gcry_sexp_release (l2); if (!l1) return 0; /* Invalid object. */ q = gcry_sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG); gcry_sexp_release (l1); if (!q) return 0; /* Missing value. */ nbits = gcry_mpi_get_nbits (q); gcry_mpi_release (q); return nbits; } /* Return an appropriate hash algorithm to be used with RFC-6979 for a message digest of length MDLEN. Although a fallback of SHA-256 is used the current implementation in Libgcrypt will reject a hash algorithm which does not match the length of the message. */ static const char * rfc6979_hash_algo_string (size_t mdlen) { switch (mdlen) { case 20: return "sha1"; case 28: return "sha224"; case 32: return "sha256"; case 48: return "sha384"; case 64: return "sha512"; default: return "sha256"; } } /* Encode a message digest for use with the EdDSA algorithm (i.e. curve Ed25519). */ static gpg_error_t do_encode_eddsa (size_t nbits, const byte *md, size_t mdlen, gcry_sexp_t *r_hash) { gpg_error_t err; gcry_sexp_t hash; const char *fmt; if (nbits == 448) fmt = "(data(value %b))"; else fmt = "(data(flags eddsa)(hash-algo sha512)(value %b))"; *r_hash = NULL; err = gcry_sexp_build (&hash, NULL, fmt, (int)mdlen, md); if (!err) *r_hash = hash; return err; } /* Encode a message digest for use with an DSA algorithm. */ static gpg_error_t do_encode_dsa (const byte *md, size_t mdlen, int pkalgo, gcry_sexp_t pkey, gcry_sexp_t *r_hash) { gpg_error_t err; gcry_sexp_t hash; unsigned int qbits; *r_hash = NULL; if (pkalgo == GCRY_PK_ECC) qbits = gcry_pk_get_nbits (pkey); else if (pkalgo == GCRY_PK_DSA) qbits = get_dsa_qbits (pkey); else return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); if (pkalgo == GCRY_PK_DSA && (qbits%8)) { /* FIXME: We check the QBITS but print a message about the hash length. */ log_error (_("DSA requires the hash length to be a" " multiple of 8 bits\n")); return gpg_error (GPG_ERR_INV_LENGTH); } /* Don't allow any Q smaller than 160 bits. We don't want someone to issue signatures from a key with a 16-bit Q or something like that, which would look correct but allow trivial forgeries. Yes, I know this rules out using MD5 with DSA. ;) */ if (qbits < 160) { log_error (_("%s key uses an unsafe (%u bit) hash\n"), gcry_pk_algo_name (pkalgo), qbits); return gpg_error (GPG_ERR_INV_LENGTH); } /* ECDSA 521 is special as it is larger than the largest hash we have (SHA-512). Thus we change the size for further processing to 512. */ if (pkalgo == GCRY_PK_ECC && qbits > 512) qbits = 512; /* Check if we're too short. Too long is safe as we'll automatically left-truncate. */ if (mdlen < qbits/8) { log_error (_("a %zu bit hash is not valid for a %u bit %s key\n"), mdlen*8, gcry_pk_get_nbits (pkey), gcry_pk_algo_name (pkalgo)); return gpg_error (GPG_ERR_INV_LENGTH); } /* Truncate. */ if (mdlen > qbits/8) mdlen = qbits/8; /* Create the S-expression. */ err = gcry_sexp_build (&hash, NULL, "(data (flags rfc6979) (hash %s %b))", rfc6979_hash_algo_string (mdlen), (int)mdlen, md); if (!err) *r_hash = hash; return err; } /* Special version of do_encode_md to take care of pkcs#1 padding. For TLS-MD5SHA1 we need to do the padding ourself as Libgrypt does not know about this special scheme. Fixme: We should have a pkcs1-only-padding flag for Libgcrypt. */ static int do_encode_raw_pkcs1 (const byte *md, size_t mdlen, unsigned int nbits, gcry_sexp_t *r_hash) { int rc; gcry_sexp_t hash; unsigned char *frame; size_t i, n, nframe; nframe = (nbits+7) / 8; if ( !mdlen || mdlen + 8 + 4 > nframe ) { /* Can't encode this hash into a frame of size NFRAME. */ return gpg_error (GPG_ERR_TOO_SHORT); } frame = xtrymalloc (nframe); if (!frame) return gpg_error_from_syserror (); /* Assemble the pkcs#1 block type 1. */ n = 0; frame[n++] = 0; frame[n++] = 1; /* Block type. */ i = nframe - mdlen - 3 ; log_assert (i >= 8); /* At least 8 bytes of padding. */ memset (frame+n, 0xff, i ); n += i; frame[n++] = 0; memcpy (frame+n, md, mdlen ); n += mdlen; log_assert (n == nframe); /* Create the S-expression. */ rc = gcry_sexp_build (&hash, NULL, "(data (flags raw) (value %b))", (int)nframe, frame); xfree (frame); *r_hash = hash; return rc; } /* SIGN whatever information we have accumulated in CTRL and return * the signature S-expression. LOOKUP is an optional function to * provide a way for lower layers to ask for the caching TTL. If a * CACHE_NONCE is given that cache item is first tried to get a * passphrase. If OVERRIDEDATA is not NULL, OVERRIDEDATALEN bytes * from this buffer are used instead of the data in CTRL. The * override feature is required to allow the use of Ed25519 with ssh * because Ed25519 does the hashing itself. */ gpg_error_t agent_pksign_do (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, gcry_sexp_t *signature_sexp, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, const void *overridedata, size_t overridedatalen) { gpg_error_t err = 0; gcry_sexp_t s_skey = NULL; gcry_sexp_t s_sig = NULL; gcry_sexp_t s_hash = NULL; gcry_sexp_t s_pkey = NULL; unsigned char *shadow_info = NULL; int no_shadow_info = 0; const unsigned char *data; int datalen; int check_signature = 0; int algo; if (overridedata) { data = overridedata; datalen = overridedatalen; } else if (ctrl->digest.data) { data = ctrl->digest.data; datalen = ctrl->digest.valuelen; } else { data = ctrl->digest.value; datalen = ctrl->digest.valuelen; } if (!ctrl->have_keygrip) return gpg_error (GPG_ERR_NO_SECKEY); err = agent_key_from_file (ctrl, cache_nonce, desc_text, NULL, &shadow_info, cache_mode, lookup_ttl, &s_skey, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_NO_SECKEY) no_shadow_info = 1; else if (err) { log_error ("failed to read the secret key\n"); goto leave; } else algo = get_pk_algo_from_key (s_skey); if (shadow_info || no_shadow_info) { /* Divert operation to the smartcard. With NO_SHADOW_INFO set * we don't have the keystub but we want to see whether the key * is on the active card. */ size_t len; unsigned char *buf = NULL; if (no_shadow_info) { /* Try to get the public key from the card or fail with the * original NO_SECKEY error. We also write a stub file (we * are here only because no stub exists). */ char *serialno; unsigned char *pkbuf = NULL; size_t pkbuflen; char hexgrip[2*KEYGRIP_LEN+1]; char *keyref; if (agent_card_serialno (ctrl, &serialno, NULL)) { /* No card available or error reading the card. */ err = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } bin2hex (ctrl->keygrip, KEYGRIP_LEN, hexgrip); if (agent_card_readkey (ctrl, hexgrip, &pkbuf, &keyref)) { /* No such key on the card. */ xfree (serialno); err = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL); err = gcry_sexp_sscan (&s_pkey, NULL, (char*)pkbuf, pkbuflen); if (err) { xfree (serialno); xfree (pkbuf); xfree (keyref); log_error ("%s: corrupted key returned by scdaemon\n", __func__); goto leave; } if (keyref) agent_write_shadow_key (ctrl->keygrip, serialno, keyref, pkbuf, 0); algo = get_pk_algo_from_key (s_pkey); xfree (serialno); xfree (pkbuf); xfree (keyref); } else { /* Get the public key from the stub file. */ err = agent_public_key_from_file (ctrl, ctrl->keygrip, &s_pkey); if (err) { log_error ("failed to read the public key\n"); goto leave; } } { - char *desc2 = NULL; - - if (desc_text) - agent_modify_description (desc_text, NULL, s_pkey, &desc2); - if (agent_is_tpm2_key (s_skey)) - err = divert_tpm2_pksign (ctrl, desc2? desc2 : desc_text, + err = divert_tpm2_pksign (ctrl, data, datalen, ctrl->digest.algo, shadow_info, &buf, &len); else - err = divert_pksign (ctrl, desc2? desc2 : desc_text, + err = divert_pksign (ctrl, ctrl->keygrip, data, datalen, ctrl->digest.algo, - shadow_info, &buf, &len); - xfree (desc2); + &buf, &len); } if (err) { log_error ("smartcard signing failed: %s\n", gpg_strerror (err)); goto leave; } if (algo == GCRY_PK_RSA) { unsigned char *p = buf; check_signature = 1; /* * Smartcard returns fixed-size data, which is good for * PKCS1. If variable-size unsigned MPI is needed, remove * zeros. */ if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1 || ctrl->digest.raw_value) { int i; for (i = 0; i < len - 1; i++) if (p[i]) break; p += i; len -= i; } err = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%b)))", (int)len, p); } else if (algo == GCRY_PK_EDDSA) { err = gcry_sexp_build (&s_sig, NULL, "(sig-val(eddsa(r%b)(s%b)))", (int)len/2, buf, (int)len/2, buf + len/2); } else if (algo == GCRY_PK_ECC) { unsigned char *r_buf, *s_buf; int r_buflen, s_buflen; int i; r_buflen = s_buflen = len/2; /* * Smartcard returns fixed-size data. For ECDSA signature, * variable-size unsigned MPI is assumed, thus, remove * zeros. */ r_buf = buf; for (i = 0; i < r_buflen - 1; i++) if (r_buf[i]) break; r_buf += i; r_buflen -= i; s_buf = buf + len/2; for (i = 0; i < s_buflen - 1; i++) if (s_buf[i]) break; s_buf += i; s_buflen -= i; err = gcry_sexp_build (&s_sig, NULL, "(sig-val(ecdsa(r%b)(s%b)))", r_buflen, r_buf, s_buflen, s_buf); } else err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); xfree (buf); if (err) { log_error ("failed to convert sigbuf returned by divert_pksign " "into S-Exp: %s", gpg_strerror (err)); goto leave; } } else { /* No smartcard, but a private key (in S_SKEY). */ /* Put the hash into a sexp */ if (algo == GCRY_PK_EDDSA) err = do_encode_eddsa (gcry_pk_get_nbits (s_skey), data, datalen, &s_hash); else if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1) err = do_encode_raw_pkcs1 (data, datalen, gcry_pk_get_nbits (s_skey), &s_hash); else if (algo == GCRY_PK_DSA || algo == GCRY_PK_ECC) err = do_encode_dsa (data, datalen, algo, s_skey, &s_hash); else if (ctrl->digest.is_pss) { log_info ("signing with rsaPSS is currently only supported" " for (some) smartcards\n"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); } else err = do_encode_md (data, datalen, ctrl->digest.algo, &s_hash, ctrl->digest.raw_value); if (err) goto leave; if (DBG_CRYPTO) { gcry_log_debugsxp ("skey", s_skey); gcry_log_debugsxp ("hash", s_hash); } /* sign */ err = gcry_pk_sign (&s_sig, s_hash, s_skey); if (err) { log_error ("signing failed: %s\n", gpg_strerror (err)); goto leave; } if (DBG_CRYPTO) gcry_log_debugsxp ("rslt", s_sig); } /* Check that the signature verification worked and nothing is * fooling us e.g. by a bug in the signature create code or by * deliberately introduced faults. Because Libgcrypt 1.7 does this * for RSA internally there is no need to do it here again. We do * this always for card based RSA keys, though. */ if (check_signature) { gcry_sexp_t sexp_key = s_pkey? s_pkey: s_skey; if (s_hash == NULL) { if (ctrl->digest.is_pss) { err = gcry_sexp_build (&s_hash, NULL, "(data (flags raw) (value %b))", (int)datalen, data); } else if (algo == GCRY_PK_DSA || algo == GCRY_PK_ECC) err = do_encode_dsa (data, datalen, algo, sexp_key, &s_hash); else if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1) err = do_encode_raw_pkcs1 (data, datalen, gcry_pk_get_nbits (sexp_key), &s_hash); else err = do_encode_md (data, datalen, ctrl->digest.algo, &s_hash, ctrl->digest.raw_value); } if (!err) err = gcry_pk_verify (s_sig, s_hash, sexp_key); if (err) { log_error (_("checking created signature failed: %s\n"), gpg_strerror (err)); if (DBG_CRYPTO) { gcry_log_debugsxp ("verify s_hsh", s_hash); gcry_log_debugsxp ("verify s_sig", s_sig); gcry_log_debugsxp ("verify s_key", sexp_key); } gcry_sexp_release (s_sig); s_sig = NULL; } } leave: *signature_sexp = s_sig; gcry_sexp_release (s_pkey); gcry_sexp_release (s_skey); gcry_sexp_release (s_hash); xfree (shadow_info); return err; } /* SIGN whatever information we have accumulated in CTRL and write it * back to OUTFP. If a CACHE_NONCE is given that cache item is first * tried to get a passphrase. */ gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, membuf_t *outbuf, cache_mode_t cache_mode) { gpg_error_t err; gcry_sexp_t s_sig = NULL; char *buf = NULL; size_t len = 0; err = agent_pksign_do (ctrl, cache_nonce, desc_text, &s_sig, cache_mode, NULL, NULL, 0); if (err) goto leave; len = gcry_sexp_sprint (s_sig, GCRYSEXP_FMT_CANON, NULL, 0); log_assert (len); buf = xtrymalloc (len); if (!buf) { err = gpg_error_from_syserror (); goto leave; } len = gcry_sexp_sprint (s_sig, GCRYSEXP_FMT_CANON, buf, len); log_assert (len); put_membuf (outbuf, buf, len); leave: gcry_sexp_release (s_sig); xfree (buf); return err; }