diff --git a/agent/agent.h b/agent/agent.h index 4d981adcf..fb4641259 100644 --- a/agent/agent.h +++ b/agent/agent.h @@ -1,622 +1,624 @@ /* 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 "../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 contrained 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 /* 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 smartcard tasks. */ const char *scdaemon_program; int disable_scdaemon; /* Never use the SCdaemon. */ 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; /* 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. */ const char *check_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 scd_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 SCdaemon (call-scd.c). */ struct scd_local_s *scd_local; /* Environment settings for the connection. */ session_env_t session_env; char *lc_ctype; char *lc_messages; unsigned long client_pid; /* 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 { int algo; unsigned char value[MAX_DIGEST_LEN]; int valuelen; int raw_value: 1; } 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 }; /* 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. */ 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 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_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 /*-- 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_scd_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); #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, 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); 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_is_dsa_key (gcry_sexp_t s_key); int agent_is_eddsa_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); 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 (void); 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 --*/ int agent_pkdecrypt (ctrl_t ctrl, const char *desc_text, const unsigned char *ciphertext, size_t ciphertextlen, membuf_t *outbuf, int *r_padding); /*-- genkey.c --*/ int check_passphrase_constraints (ctrl_t ctrl, const char *pw, int no_empty, 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); gpg_error_t agent_get_shadow_info (const unsigned char *shadowkey, unsigned char const **shadow_info); 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-scd.c --*/ int divert_pksign (ctrl_t ctrl, const char *desc_text, const unsigned char *digest, size_t digestlen, int algo, + const unsigned char *grip, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen); int divert_pkdecrypt (ctrl_t ctrl, const char *desc_text, const unsigned char *cipher, + const unsigned char *grip, 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); int divert_writekey (ctrl_t ctrl, int force, const char *serialno, const char *id, const char *keydata, size_t keydatalen); /*-- call-scd.c --*/ void initialize_module_call_scd (void); void agent_scd_dump_state (void); int agent_scd_check_running (void); void agent_scd_check_aliveness (void); int agent_reset_scd (ctrl_t ctrl); 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); int agent_card_writekey (ctrl_t ctrl, int force, const char *serialno, const char *id, 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); gpg_error_t agent_card_cardlist (ctrl_t ctrl, strlist_t *result); 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_killscd (void); /*-- 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); #endif /*AGENT_H*/ diff --git a/agent/divert-scd.c b/agent/divert-scd.c index b79f7a880..70a71e991 100644 --- a/agent/divert-scd.c +++ b/agent/divert-scd.c @@ -1,612 +1,645 @@ /* 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 int ask_for_card (ctrl_t ctrl, const unsigned char *shadow_info, char **r_kid) { int rc, i; char *serialno; int no_card = 0; char *desc; char *want_sn, *want_kid, *want_sn_disp; int len; *r_kid = NULL; rc = parse_shadow_info (shadow_info, &want_sn, &want_kid, NULL); if (rc) return rc; want_sn_disp = xtrystrdup (want_sn); if (!want_sn_disp) { rc = gpg_error_from_syserror (); xfree (want_sn); xfree (want_kid); return rc; } len = strlen (want_sn_disp); if (len == 32 && !strncmp (want_sn_disp, "D27600012401", 12)) { /* This is an OpenPGP card - reformat */ memmove (want_sn_disp, want_sn_disp+16, 4); want_sn_disp[4] = ' '; memmove (want_sn_disp+5, want_sn_disp+20, 8); want_sn_disp[13] = 0; } else if (len == 20 && want_sn_disp[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_disp[19] = 0; } for (;;) { rc = agent_card_serialno (ctrl, &serialno, want_sn); if (!rc) { - log_debug ("detected card with S/N %s\n", serialno); + log_info ("detected card with S/N %s\n", serialno); i = strcmp (serialno, want_sn); xfree (serialno); serialno = NULL; if (!i) { xfree (want_sn_disp); xfree (want_sn); *r_kid = want_kid; return 0; /* yes, we have the correct card */ } } else if (gpg_err_code (rc) == GPG_ERR_ENODEV) { - log_debug ("no device present\n"); + log_info ("no device present\n"); rc = 0; no_card = 1; } else if (gpg_err_code (rc) == GPG_ERR_CARD_NOT_PRESENT) { - log_debug ("no card present\n"); + log_info ("no card present\n"); rc = 0; no_card = 2; } else { log_error ("error accessing card: %s\n", gpg_strerror (rc)); } if (!rc) { if (asprintf (&desc, "%s:%%0A%%0A" " %s", no_card ? L_("Please insert the card with serial number") : L_("Please remove the current card and " "insert the one with serial number"), want_sn_disp) < 0) { rc = out_of_core (); } else { rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0); if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK && gpg_err_code (rc) == GPG_ERR_NO_PIN_ENTRY) rc = gpg_error (GPG_ERR_CARD_NOT_PRESENT); xfree (desc); } } if (rc) { xfree (want_sn_disp); xfree (want_sn); xfree (want_kid); return rc; } } } /* 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 informtion 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. * * FIXME: Explain the other args. */ int divert_pksign (ctrl_t ctrl, const char *desc_text, const unsigned char *digest, size_t digestlen, int algo, + const unsigned char *grip, const unsigned char *shadow_info, unsigned char **r_sig, size_t *r_siglen) { int rc; char *kid; size_t siglen; unsigned char *sigval = NULL; (void)desc_text; rc = ask_for_card (ctrl, shadow_info, &kid); if (rc) return rc; + /* For OpenPGP cards we better use the keygrip as key reference. + * This has the advantage that app-openpgp can check that the stored + * key matches our expectation. This is important in case new keys + * have been created on the same card but the sub file has not been + * updated. In that case we would get a error from our final + * signature checking code or, if the pubkey algo is different, + * weird errors from the card (Conditions of use not satisfied). */ + if (kid && grip && !strncmp (kid, "OPENPGP.", 8)) + { + xfree (kid); + kid = bin2hex (grip, KEYGRIP_LEN, NULL); + if (!kid) + return gpg_error_from_syserror (); + } + + 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, 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, 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, const unsigned char *cipher, + const unsigned char *grip, const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding) { int rc; char *kid; const unsigned char *s; size_t n; int depth; const unsigned char *ciphertext; size_t ciphertextlen; char *plaintext; size_t plaintextlen; (void)desc_text; *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, &kid); if (rc) return rc; + /* For OpenPGP cards we better use the keygrip as key reference. + * This has the advantage that app-openpgp can check that the stored + * key matches our expectation. This is important in case new keys + * have been created on the same card but the sub file has not been + * updated. In that case we would get a error from our final + * signature checking code or, if the pubkey algo is different, + * weird errors from the card (Conditions of use not satisfied). */ + if (kid && grip && !strncmp (kid, "OPENPGP.", 8)) + { + xfree (kid); + kid = bin2hex (grip, KEYGRIP_LEN, NULL); + if (!kid) + return gpg_error_from_syserror (); + } + rc = agent_card_pkdecrypt (ctrl, kid, getpin_cb, ctrl, NULL, ciphertext, ciphertextlen, &plaintext, &plaintextlen, r_padding); if (!rc) { *r_buf = plaintext; *r_len = plaintextlen; } xfree (kid); return rc; } int divert_writekey (ctrl_t ctrl, int force, const char *serialno, const char *id, const char *keydata, size_t keydatalen) { return agent_card_writekey (ctrl, force, serialno, id, 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/pkdecrypt.c b/agent/pkdecrypt.c index 06a8e0b6f..6aed96b4f 100644 --- a/agent/pkdecrypt.c +++ b/agent/pkdecrypt.c @@ -1,146 +1,147 @@ /* 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 #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. */ int 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; int rc; char *buf = NULL; size_t len; *r_padding = -1; if (!ctrl->have_keygrip) { log_error ("speculative decryption not yet supported\n"); rc = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } rc = gcry_sexp_sscan (&s_cipher, NULL, (char*)ciphertext, ciphertextlen); if (rc) { log_error ("failed to convert ciphertext: %s\n", gpg_strerror (rc)); rc = gpg_error (GPG_ERR_INV_DATA); goto leave; } if (DBG_CRYPTO) { log_printhex (ctrl->keygrip, 20, "keygrip:"); log_printhex (ciphertext, ciphertextlen, "cipher: "); } rc = agent_key_from_file (ctrl, NULL, desc_text, ctrl->keygrip, &shadow_info, CACHE_MODE_NORMAL, NULL, &s_skey, NULL); if (rc) { if (gpg_err_code (rc) != GPG_ERR_NO_SECKEY) log_error ("failed to read the secret key\n"); goto leave; } if (shadow_info) { /* divert operation to the smartcard */ if (!gcry_sexp_canon_len (ciphertext, ciphertextlen, NULL, NULL)) { rc = gpg_error (GPG_ERR_INV_SEXP); goto leave; } - rc = divert_pkdecrypt (ctrl, desc_text, ciphertext, shadow_info, + rc = divert_pkdecrypt (ctrl, desc_text, ciphertext, + ctrl->keygrip, shadow_info, &buf, &len, r_padding); if (rc) { log_error ("smartcard decryption failed: %s\n", gpg_strerror (rc)); 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); */ /* } */ rc = gcry_pk_decrypt (&s_plain, s_cipher, s_skey); if (rc) { log_error ("decryption failed: %s\n", gpg_strerror (rc)); goto leave; } if (DBG_CRYPTO) { log_debug ("plain: "); gcry_sexp_dump (s_plain); } len = gcry_sexp_sprint (s_plain, GCRYSEXP_FMT_CANON, NULL, 0); assert (len); buf = xmalloc (len); len = gcry_sexp_sprint (s_plain, GCRYSEXP_FMT_CANON, buf, len); 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 rc; } diff --git a/agent/pksign.c b/agent/pksign.c index ed2f133a0..09d61b8c7 100644 --- a/agent/pksign.c +++ b/agent/pksign.c @@ -1,571 +1,572 @@ /* 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 #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) { for (i=0; i < strlen (s); i++) tmp[i] = tolower (s[i]); tmp[i] = '\0'; } rc = gcry_sexp_build (&hash, NULL, "(data (flags pkcs1) (hash %s %b))", tmp, (int)mdlen, md); } else { gcry_mpi_t mpi; rc = gcry_mpi_scan (&mpi, GCRYMPI_FMT_USG, md, mdlen, NULL); if (!rc) { rc = gcry_sexp_build (&hash, NULL, "(data (flags raw) (value %m))", mpi); gcry_mpi_release (mpi); } else hash = NULL; } *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 (const byte *md, size_t mdlen, gcry_sexp_t *r_hash) { gpg_error_t err; gcry_sexp_t hash; *r_hash = NULL; err = gcry_sexp_build (&hash, NULL, "(data(flags eddsa)(hash-algo sha512)(value %b))", (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_ECDSA) 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 has 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_ECDSA && 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 ; 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; 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; const unsigned char *data; int datalen; int check_signature = 0; if (overridedata) { data = overridedata; datalen = overridedatalen; } 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, ctrl->keygrip, &shadow_info, cache_mode, lookup_ttl, &s_skey, NULL); 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) { /* Divert operation to the smartcard */ size_t len; unsigned char *buf = NULL; int key_type; int is_RSA = 0; int is_ECDSA = 0; int is_EdDSA = 0; err = agent_public_key_from_file (ctrl, ctrl->keygrip, &s_pkey); if (err) { log_error ("failed to read the public key\n"); goto leave; } if (agent_is_eddsa_key (s_skey)) is_EdDSA = 1; else { key_type = agent_is_dsa_key (s_skey); if (key_type == 0) is_RSA = 1; else if (key_type == GCRY_PK_ECDSA) is_ECDSA = 1; } { char *desc2 = NULL; if (desc_text) agent_modify_description (desc_text, NULL, s_skey, &desc2); err = divert_pksign (ctrl, desc2? desc2 : desc_text, data, datalen, ctrl->digest.algo, + ctrl->keygrip, shadow_info, &buf, &len); xfree (desc2); } if (err) { log_error ("smartcard signing failed: %s\n", gpg_strerror (err)); goto leave; } if (is_RSA) { check_signature = 1; if (*buf & 0x80) { len++; buf = xtryrealloc (buf, len); if (!buf) goto leave; memmove (buf + 1, buf, len - 1); *buf = 0; } err = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%b)))", (int)len, buf); } else if (is_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 (is_ECDSA) { unsigned char *r_buf_allocated = NULL; unsigned char *s_buf_allocated = NULL; unsigned char *r_buf, *s_buf; int r_buflen, s_buflen; r_buflen = s_buflen = len/2; if (*buf & 0x80) { r_buflen++; r_buf_allocated = xtrymalloc (r_buflen); if (!r_buf_allocated) { err = gpg_error_from_syserror (); goto leave; } r_buf = r_buf_allocated; memcpy (r_buf + 1, buf, len/2); *r_buf = 0; } else r_buf = buf; if (*(buf + len/2) & 0x80) { s_buflen++; s_buf_allocated = xtrymalloc (s_buflen); if (!s_buf_allocated) { err = gpg_error_from_syserror (); xfree (r_buf_allocated); goto leave; } s_buf = s_buf_allocated; memcpy (s_buf + 1, buf + len/2, len/2); *s_buf = 0; } else s_buf = buf + len/2; err = gcry_sexp_build (&s_sig, NULL, "(sig-val(ecdsa(r%b)(s%b)))", r_buflen, r_buf, s_buflen, s_buf); xfree (r_buf_allocated); xfree (s_buf_allocated); } 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 */ int dsaalgo = 0; /* Put the hash into a sexp */ if (agent_is_eddsa_key (s_skey)) err = do_encode_eddsa (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 ( (dsaalgo = agent_is_dsa_key (s_skey)) ) err = do_encode_dsa (data, datalen, dsaalgo, s_skey, &s_hash); 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. */ if (check_signature) { gcry_sexp_t sexp_key = s_pkey? s_pkey: s_skey; if (s_hash == NULL) { 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)); 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; } diff --git a/agent/protect.c b/agent/protect.c index 1766909f9..87df685e5 100644 --- a/agent/protect.c +++ b/agent/protect.c @@ -1,1760 +1,1761 @@ /* protect.c - Un/Protect a secret key * Copyright (C) 1998-2003, 2007, 2009, 2011 Free Software Foundation, Inc. * Copyright (C) 1998-2003, 2007, 2009, 2011, 2013-2015 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # ifdef HAVE_WINSOCK2_H # include # endif # include #else # include #endif #include "agent.h" #include "cvt-openpgp.h" #include "../common/sexp-parse.h" /* The protection mode for encryption. The supported modes for decryption are listed in agent_unprotect(). */ #define PROT_CIPHER GCRY_CIPHER_AES128 #define PROT_CIPHER_STRING "aes" #define PROT_CIPHER_KEYLEN (128/8) /* Decode an rfc4880 encoded S2K count. */ #define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6)) /* A table containing the information needed to create a protected private key. */ static const struct { const char *algo; const char *parmlist; int prot_from, prot_to; int ecc_hack; } protect_info[] = { { "rsa", "nedpqu", 2, 5 }, { "dsa", "pqgyx", 4, 4 }, { "elg", "pgyx", 3, 3 }, { "ecdsa","pabgnqd", 6, 6, 1 }, { "ecdh", "pabgnqd", 6, 6, 1 }, { "ecc", "pabgnqd", 6, 6, 1 }, { NULL } }; /* The number of milliseconds we use in the S2K function and the * calibrated count value. A count value of zero indicates that the * calibration has not yet been done or needs to be done again. */ static unsigned int s2k_calibration_time = AGENT_S2K_CALIBRATION; static unsigned long s2k_calibrated_count; /* A helper object for time measurement. */ struct calibrate_time_s { #ifdef HAVE_W32_SYSTEM FILETIME creation_time, exit_time, kernel_time, user_time; #else clock_t ticks; #endif }; static int hash_passphrase (const char *passphrase, int hashalgo, int s2kmode, const unsigned char *s2ksalt, unsigned long s2kcount, unsigned char *key, size_t keylen); /* Get the process time and store it in DATA. */ static void calibrate_get_time (struct calibrate_time_s *data) { #ifdef HAVE_W32_SYSTEM # ifdef HAVE_W32CE_SYSTEM GetThreadTimes (GetCurrentThread (), &data->creation_time, &data->exit_time, &data->kernel_time, &data->user_time); # else GetProcessTimes (GetCurrentProcess (), &data->creation_time, &data->exit_time, &data->kernel_time, &data->user_time); # endif #elif defined (CLOCK_THREAD_CPUTIME_ID) struct timespec tmp; clock_gettime (CLOCK_THREAD_CPUTIME_ID, &tmp); data->ticks = (clock_t)(((unsigned long long)tmp.tv_sec * 1000000000 + tmp.tv_nsec) * CLOCKS_PER_SEC / 1000000000); #else data->ticks = clock (); #endif } static unsigned long calibrate_elapsed_time (struct calibrate_time_s *starttime) { struct calibrate_time_s stoptime; calibrate_get_time (&stoptime); #ifdef HAVE_W32_SYSTEM { unsigned long long t1, t2; t1 = (((unsigned long long)starttime->kernel_time.dwHighDateTime << 32) + starttime->kernel_time.dwLowDateTime); t1 += (((unsigned long long)starttime->user_time.dwHighDateTime << 32) + starttime->user_time.dwLowDateTime); t2 = (((unsigned long long)stoptime.kernel_time.dwHighDateTime << 32) + stoptime.kernel_time.dwLowDateTime); t2 += (((unsigned long long)stoptime.user_time.dwHighDateTime << 32) + stoptime.user_time.dwLowDateTime); return (unsigned long)((t2 - t1)/10000); } #else return (unsigned long)((((double) (stoptime.ticks - starttime->ticks)) /CLOCKS_PER_SEC)*1000); #endif } /* Run a test hashing for COUNT and return the time required in milliseconds. */ static unsigned long calibrate_s2k_count_one (unsigned long count) { int rc; char keybuf[PROT_CIPHER_KEYLEN]; struct calibrate_time_s starttime; calibrate_get_time (&starttime); rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1, 3, "saltsalt", count, keybuf, sizeof keybuf); if (rc) BUG (); return calibrate_elapsed_time (&starttime); } /* Measure the time we need to do the hash operations and deduce an S2K count which requires roughly some targeted amount of time. */ static unsigned long calibrate_s2k_count (void) { unsigned long count; unsigned long ms; for (count = 65536; count; count *= 2) { ms = calibrate_s2k_count_one (count); if (opt.verbose > 1) log_info ("S2K calibration: %lu -> %lums\n", count, ms); if (ms > s2k_calibration_time) break; } count = (unsigned long)(((double)count / ms) * s2k_calibration_time); count /= 1024; count *= 1024; if (count < 65536) count = 65536; if (opt.verbose) { ms = calibrate_s2k_count_one (count); log_info ("S2K calibration: %lu -> %lums\n", count, ms); } return count; } /* Set the calibration time. This may be called early at startup or * at any time. Thus it should one set variables. */ void set_s2k_calibration_time (unsigned int milliseconds) { if (!milliseconds) milliseconds = AGENT_S2K_CALIBRATION; else if (milliseconds > 60 * 1000) milliseconds = 60 * 1000; /* Cap at 60 seconds. */ s2k_calibration_time = milliseconds; s2k_calibrated_count = 0; /* Force re-calibration. */ } /* Return the calibrated S2K count. This is only public for the use * of the Assuan getinfo s2k_count_cal command. */ unsigned long get_calibrated_s2k_count (void) { if (!s2k_calibrated_count) s2k_calibrated_count = calibrate_s2k_count (); /* Enforce a lower limit. */ return s2k_calibrated_count < 65536 ? 65536 : s2k_calibrated_count; } /* Return the standard S2K count. */ unsigned long get_standard_s2k_count (void) { if (opt.s2k_count) return opt.s2k_count < 65536 ? 65536 : opt.s2k_count; return get_calibrated_s2k_count (); } /* Return the milliseconds required for the standard S2K * operation. */ unsigned long get_standard_s2k_time (void) { return calibrate_s2k_count_one (get_standard_s2k_count ()); } /* Same as get_standard_s2k_count but return the count in the encoding as described by rfc4880. */ unsigned char get_standard_s2k_count_rfc4880 (void) { unsigned long iterations; unsigned int count; unsigned char result; unsigned char c=0; iterations = get_standard_s2k_count (); if (iterations >= 65011712) return 255; /* Need count to be in the range 16-31 */ for (count=iterations>>6; count>=32; count>>=1) c++; result = (c<<4)|(count-16); if (S2K_DECODE_COUNT(result) < iterations) result++; return result; } /* Calculate the MIC for a private key or shared secret S-expression. SHA1HASH should point to a 20 byte buffer. This function is suitable for all algorithms. */ static gpg_error_t calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash) { const unsigned char *hash_begin, *hash_end; const unsigned char *s; size_t n; int is_shared_secret; s = plainkey; 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, "private-key")) is_shared_secret = 0; else if (smatch (&s, n, "shared-secret")) is_shared_secret = 1; else return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); hash_begin = s; if (!is_shared_secret) { s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; /* Skip the algorithm name. */ } while (*s == '(') { s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; if ( *s != ')' ) return gpg_error (GPG_ERR_INV_SEXP); s++; } if (*s != ')') return gpg_error (GPG_ERR_INV_SEXP); s++; hash_end = s; gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash, hash_begin, hash_end - hash_begin); return 0; } /* Encrypt the parameter block starting at PROTBEGIN with length PROTLEN using the utf8 encoded key PASSPHRASE and return the entire encrypted block in RESULT or return with an error code. SHA1HASH is the 20 byte SHA-1 hash required for the integrity code. The parameter block is expected to be an incomplete canonical encoded S-Expression of the form (example in advanced format): (d #046129F..[some bytes not shown]..81#) (p #00e861b..[some bytes not shown]..f1#) (q #00f7a7c..[some bytes not shown]..61#) (u #304559a..[some bytes not shown]..9b#) the returned block is the S-Expression: (protected mode (parms) encrypted_octet_string) */ static int do_encryption (const unsigned char *hashbegin, size_t hashlen, const unsigned char *protbegin, size_t protlen, const char *passphrase, const char *timestamp_exp, size_t timestamp_exp_len, unsigned char **result, size_t *resultlen, unsigned long s2k_count, int use_ocb) { gcry_cipher_hd_t hd; const char *modestr; unsigned char hashvalue[20]; int blklen, enclen, outlen; unsigned char *iv = NULL; unsigned int ivsize; /* Size of the buffer allocated for IV. */ const unsigned char *s2ksalt; /* Points into IV. */ int rc; char *outbuf = NULL; char *p; int saltpos, ivpos, encpos; s2ksalt = iv; /* Silence compiler warning. */ *resultlen = 0; *result = NULL; modestr = (use_ocb? "openpgp-s2k3-ocb-aes" /* */: "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc"); rc = gcry_cipher_open (&hd, PROT_CIPHER, use_ocb? GCRY_CIPHER_MODE_OCB : GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_SECURE); if (rc) return rc; /* We need to work on a copy of the data because this makes it * easier to add the trailer and the padding and more important we * have to prefix the text with 2 parenthesis. In CBC mode we * have to allocate enough space for: * * (()(4:hash4:sha120:)) + padding * * we always append a full block of random bytes as padding but * encrypt only what is needed for a full blocksize. In OCB mode we * have to allocate enough space for just: * * (()) */ blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER); if (use_ocb) { /* (( )) */ outlen = 2 + protlen + 2 ; enclen = outlen + 16 /* taglen */; outbuf = gcry_malloc_secure (enclen); } else { /* (( )( 4:hash 4:sha1 20: )) */ outlen = 2 + protlen + 2 + 6 + 6 + 23 + 2 + blklen; enclen = outlen/blklen * blklen; outbuf = gcry_malloc_secure (outlen); } if (!outbuf) { rc = out_of_core (); goto leave; } /* Allocate a buffer for the nonce and the salt. */ if (!rc) { /* Allocate random bytes to be used as IV, padding and s2k salt * or in OCB mode for a nonce and the s2k salt. The IV/nonce is * set later because for OCB we need to set the key first. */ ivsize = (use_ocb? 12 : (blklen*2)) + 8; iv = xtrymalloc (ivsize); if (!iv) rc = gpg_error_from_syserror (); else { gcry_create_nonce (iv, ivsize); s2ksalt = iv + ivsize - 8; } } /* Hash the passphrase and set the key. */ if (!rc) { unsigned char *key; size_t keylen = PROT_CIPHER_KEYLEN; key = gcry_malloc_secure (keylen); if (!key) rc = out_of_core (); else { rc = hash_passphrase (passphrase, GCRY_MD_SHA1, 3, s2ksalt, s2k_count? s2k_count:get_standard_s2k_count(), key, keylen); if (!rc) rc = gcry_cipher_setkey (hd, key, keylen); xfree (key); } } if (rc) goto leave; /* Set the IV/nonce. */ rc = gcry_cipher_setiv (hd, iv, use_ocb? 12 : blklen); if (rc) goto leave; if (use_ocb) { /* In OCB Mode we use only the public key parameters as AAD. */ rc = gcry_cipher_authenticate (hd, hashbegin, protbegin - hashbegin); if (!rc) rc = gcry_cipher_authenticate (hd, timestamp_exp, timestamp_exp_len); if (!rc) rc = gcry_cipher_authenticate (hd, protbegin+protlen, hashlen - (protbegin+protlen - hashbegin)); } else { /* Hash the entire expression for CBC mode. Because * TIMESTAMP_EXP won't get protected, we can't simply hash a * continuous buffer but need to call md_write several times. */ gcry_md_hd_t md; rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 ); if (!rc) { gcry_md_write (md, hashbegin, protbegin - hashbegin); gcry_md_write (md, protbegin, protlen); gcry_md_write (md, timestamp_exp, timestamp_exp_len); gcry_md_write (md, protbegin+protlen, hashlen - (protbegin+protlen - hashbegin)); memcpy (hashvalue, gcry_md_read (md, GCRY_MD_SHA1), 20); gcry_md_close (md); } } /* Encrypt. */ if (!rc) { p = outbuf; *p++ = '('; *p++ = '('; memcpy (p, protbegin, protlen); p += protlen; if (use_ocb) { *p++ = ')'; *p++ = ')'; } else { memcpy (p, ")(4:hash4:sha120:", 17); p += 17; memcpy (p, hashvalue, 20); p += 20; *p++ = ')'; *p++ = ')'; memcpy (p, iv+blklen, blklen); /* Add padding. */ p += blklen; } assert ( p - outbuf == outlen); if (use_ocb) { gcry_cipher_final (hd); rc = gcry_cipher_encrypt (hd, outbuf, outlen, NULL, 0); if (!rc) { log_assert (outlen + 16 == enclen); rc = gcry_cipher_gettag (hd, outbuf + outlen, 16); } } else { rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0); } } if (rc) goto leave; /* Release cipher handle and check for errors. */ gcry_cipher_close (hd); /* Now allocate the buffer we want to return. This is (protected openpgp-s2k3-sha1-aes-cbc ((sha1 salt no_of_iterations) 16byte_iv) encrypted_octet_string) in canoncical format of course. We use asprintf and %n modifier and dummy values as placeholders. */ { char countbuf[35]; snprintf (countbuf, sizeof countbuf, "%lu", s2k_count ? s2k_count : get_standard_s2k_count ()); p = xtryasprintf ("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)", (int)strlen (modestr), modestr, &saltpos, (unsigned int)strlen (countbuf), countbuf, use_ocb? 12 : blklen, &ivpos, use_ocb? 12 : blklen, "", enclen, &encpos, enclen, ""); if (!p) { gpg_error_t tmperr = out_of_core (); xfree (iv); xfree (outbuf); return tmperr; } } *resultlen = strlen (p); *result = (unsigned char*)p; memcpy (p+saltpos, s2ksalt, 8); memcpy (p+ivpos, iv, use_ocb? 12 : blklen); memcpy (p+encpos, outbuf, enclen); xfree (iv); xfree (outbuf); return 0; leave: gcry_cipher_close (hd); xfree (iv); xfree (outbuf); return rc; } /* Protect the key encoded in canonical format in PLAINKEY. We assume a valid S-Exp here. With USE_UCB set to -1 the default scheme is used (ie. either CBC or OCB), set to 0 the old CBC mode is used, and set to 1 OCB is used. */ int agent_protect (const unsigned char *plainkey, const char *passphrase, unsigned char **result, size_t *resultlen, unsigned long s2k_count, int use_ocb) { int rc; const char *parmlist; int prot_from_idx, prot_to_idx; const unsigned char *s; const unsigned char *hash_begin, *hash_end; const unsigned char *prot_begin, *prot_end, *real_end; size_t n; int c, infidx, i; char timestamp_exp[35]; unsigned char *protected; size_t protectedlen; int depth = 0; unsigned char *p; int have_curve = 0; if (use_ocb == -1) use_ocb = !!opt.enable_extended_key_format; /* Create an S-expression with the protected-at timestamp. */ memcpy (timestamp_exp, "(12:protected-at15:", 19); gnupg_get_isotime (timestamp_exp+19); timestamp_exp[19+15] = ')'; /* Parse original key. */ s = plainkey; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "private-key")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); depth++; hash_begin = s; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); for (infidx=0; protect_info[infidx].algo && !smatch (&s, n, protect_info[infidx].algo); infidx++) ; if (!protect_info[infidx].algo) return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); /* The parser below is a complete mess: To make it robust for ECC use we should reorder the s-expression to include only what we really need and thus guarantee the right order for saving stuff. This should be done before calling this function and maybe with the help of the new gcry_sexp_extract_param. */ parmlist = protect_info[infidx].parmlist; prot_from_idx = protect_info[infidx].prot_from; prot_to_idx = protect_info[infidx].prot_to; prot_begin = prot_end = NULL; for (i=0; (c=parmlist[i]); i++) { if (i == prot_from_idx) prot_begin = s; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (n != 1 || c != *s) { if (n == 5 && !memcmp (s, "curve", 5) && !i && protect_info[infidx].ecc_hack) { /* This is a private ECC key but the first parameter is the name of the curve. We change the parameter list here to the one we expect in this case. */ have_curve = 1; parmlist = "?qd"; prot_from_idx = 2; prot_to_idx = 2; } else if (n == 5 && !memcmp (s, "flags", 5) && i == 1 && have_curve) { /* "curve" followed by "flags": Change again. */ parmlist = "??qd"; prot_from_idx = 3; prot_to_idx = 3; } else return gpg_error (GPG_ERR_INV_SEXP); } s += n; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s +=n; /* skip value */ if (*s != ')') return gpg_error (GPG_ERR_INV_SEXP); depth--; if (i == prot_to_idx) prot_end = s; s++; } if (*s != ')' || !prot_begin || !prot_end ) return gpg_error (GPG_ERR_INV_SEXP); depth--; hash_end = s; s++; /* Skip to the end of the S-expression. */ assert (depth == 1); rc = sskip (&s, &depth); if (rc) return rc; assert (!depth); real_end = s-1; rc = do_encryption (hash_begin, hash_end - hash_begin + 1, prot_begin, prot_end - prot_begin + 1, passphrase, timestamp_exp, sizeof (timestamp_exp), &protected, &protectedlen, s2k_count, use_ocb); if (rc) return rc; /* Now create the protected version of the key. Note that the 10 extra bytes are for the inserted "protected-" string (the beginning of the plaintext reads: "((11:private-key(" ). The 35 term is the space for (12:protected-at15:). */ *resultlen = (10 + (prot_begin-plainkey) + protectedlen + 35 + (real_end-prot_end)); *result = p = xtrymalloc (*resultlen); if (!p) { gpg_error_t tmperr = out_of_core (); xfree (protected); return tmperr; } memcpy (p, "(21:protected-", 14); p += 14; memcpy (p, plainkey+4, prot_begin - plainkey - 4); p += prot_begin - plainkey - 4; memcpy (p, protected, protectedlen); p += protectedlen; memcpy (p, timestamp_exp, 35); p += 35; memcpy (p, prot_end+1, real_end - prot_end); p += real_end - prot_end; assert ( p - *result == *resultlen); xfree (protected); return 0; } /* Do the actual decryption and check the return list for consistency. */ static gpg_error_t do_decryption (const unsigned char *aad_begin, size_t aad_len, const unsigned char *aadhole_begin, size_t aadhole_len, const unsigned char *protected, size_t protectedlen, const char *passphrase, const unsigned char *s2ksalt, unsigned long s2kcount, const unsigned char *iv, size_t ivlen, int prot_cipher, int prot_cipher_keylen, int is_ocb, unsigned char **result) { int rc; int blklen; gcry_cipher_hd_t hd; unsigned char *outbuf; size_t reallen; blklen = gcry_cipher_get_algo_blklen (prot_cipher); if (is_ocb) { /* OCB does not require a multiple of the block length but we * check that it is long enough for the 128 bit tag and that we * have the 96 bit nonce. */ if (protectedlen < (4 + 16) || ivlen != 12) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); } else { if (protectedlen < 4 || (protectedlen%blklen)) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); } rc = gcry_cipher_open (&hd, prot_cipher, is_ocb? GCRY_CIPHER_MODE_OCB : GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_SECURE); if (rc) return rc; outbuf = gcry_malloc_secure (protectedlen); if (!outbuf) rc = out_of_core (); /* Hash the passphrase and set the key. */ if (!rc) { unsigned char *key; key = gcry_malloc_secure (prot_cipher_keylen); if (!key) rc = out_of_core (); else { rc = hash_passphrase (passphrase, GCRY_MD_SHA1, 3, s2ksalt, s2kcount, key, prot_cipher_keylen); if (!rc) rc = gcry_cipher_setkey (hd, key, prot_cipher_keylen); xfree (key); } } /* Set the IV/nonce. */ if (!rc) { rc = gcry_cipher_setiv (hd, iv, ivlen); } /* Decrypt. */ if (!rc) { if (is_ocb) { rc = gcry_cipher_authenticate (hd, aad_begin, aadhole_begin - aad_begin); if (!rc) rc = gcry_cipher_authenticate (hd, aadhole_begin + aadhole_len, aad_len - (aadhole_begin+aadhole_len - aad_begin)); if (!rc) { gcry_cipher_final (hd); rc = gcry_cipher_decrypt (hd, outbuf, protectedlen - 16, protected, protectedlen - 16); } if (!rc) { rc = gcry_cipher_checktag (hd, protected + protectedlen - 16, 16); if (gpg_err_code (rc) == GPG_ERR_CHECKSUM) { /* Return Bad Passphrase instead of checksum error */ rc = gpg_error (GPG_ERR_BAD_PASSPHRASE); } } } else { rc = gcry_cipher_decrypt (hd, outbuf, protectedlen, protected, protectedlen); } } /* Release cipher handle and check for errors. */ gcry_cipher_close (hd); if (rc) { xfree (outbuf); return rc; } /* Do a quick check on the data structure. */ if (*outbuf != '(' && outbuf[1] != '(') { xfree (outbuf); return gpg_error (GPG_ERR_BAD_PASSPHRASE); } /* Check that we have a consistent S-Exp. */ reallen = gcry_sexp_canon_len (outbuf, protectedlen, NULL, NULL); if (!reallen || (reallen + blklen < protectedlen) ) { xfree (outbuf); return gpg_error (GPG_ERR_BAD_PASSPHRASE); } *result = outbuf; return 0; } /* Merge the parameter list contained in CLEARTEXT with the original * protect lists PROTECTEDKEY by replacing the list at REPLACEPOS. * Return the new list in RESULT and the MIC value in the 20 byte * buffer SHA1HASH; if SHA1HASH is NULL no MIC will be computed. * CUTOFF and CUTLEN will receive the offset and the length of the * resulting list which should go into the MIC calculation but then be * removed. */ static gpg_error_t merge_lists (const unsigned char *protectedkey, size_t replacepos, const unsigned char *cleartext, unsigned char *sha1hash, unsigned char **result, size_t *resultlen, size_t *cutoff, size_t *cutlen) { size_t n, newlistlen; unsigned char *newlist, *p; const unsigned char *s; const unsigned char *startpos, *endpos; int i, rc; *result = NULL; *resultlen = 0; *cutoff = 0; *cutlen = 0; if (replacepos < 26) return gpg_error (GPG_ERR_BUG); /* Estimate the required size of the resulting list. We have a large safety margin of >20 bytes (FIXME: MIC hash from CLEARTEXT and the removed "protected-" */ newlistlen = gcry_sexp_canon_len (protectedkey, 0, NULL, NULL); if (!newlistlen) return gpg_error (GPG_ERR_BUG); n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL); if (!n) return gpg_error (GPG_ERR_BUG); newlistlen += n; newlist = gcry_malloc_secure (newlistlen); if (!newlist) return out_of_core (); /* Copy the initial segment */ strcpy ((char*)newlist, "(11:private-key"); p = newlist + 15; memcpy (p, protectedkey+15+10, replacepos-15-10); p += replacepos-15-10; /* Copy the cleartext. */ s = cleartext; if (*s != '(' && s[1] != '(') return gpg_error (GPG_ERR_BUG); /*we already checked this */ s += 2; startpos = s; while ( *s == '(' ) { s++; n = snext (&s); if (!n) goto invalid_sexp; s += n; n = snext (&s); if (!n) goto invalid_sexp; s += n; if ( *s != ')' ) goto invalid_sexp; s++; } if ( *s != ')' ) goto invalid_sexp; endpos = s; s++; /* Intermezzo: Get the MIC if requested. */ if (sha1hash) { if (*s != '(') goto invalid_sexp; s++; n = snext (&s); if (!smatch (&s, n, "hash")) goto invalid_sexp; n = snext (&s); if (!smatch (&s, n, "sha1")) goto invalid_sexp; n = snext (&s); if (n != 20) goto invalid_sexp; memcpy (sha1hash, s, 20); s += n; if (*s != ')') goto invalid_sexp; } /* Append the parameter list. */ memcpy (p, startpos, endpos - startpos); p += endpos - startpos; /* Skip over the protected list element in the original list. */ s = protectedkey + replacepos; assert (*s == '('); s++; i = 1; rc = sskip (&s, &i); if (rc) goto failure; /* Record the position of the optional protected-at expression. */ if (*s == '(') { const unsigned char *save_s = s; s++; n = snext (&s); if (smatch (&s, n, "protected-at")) { i = 1; rc = sskip (&s, &i); if (rc) goto failure; *cutlen = s - save_s; } s = save_s; } startpos = s; i = 2; /* we are inside this level */ rc = sskip (&s, &i); if (rc) goto failure; assert (s[-1] == ')'); endpos = s; /* one behind the end of the list */ /* Append the rest. */ if (*cutlen) *cutoff = p - newlist; memcpy (p, startpos, endpos - startpos); p += endpos - startpos; /* ready */ *result = newlist; *resultlen = newlistlen; return 0; failure: wipememory (newlist, newlistlen); xfree (newlist); return rc; invalid_sexp: wipememory (newlist, newlistlen); xfree (newlist); return gpg_error (GPG_ERR_INV_SEXP); } /* Unprotect the key encoded in canonical format. We assume a valid S-Exp here. If a protected-at item is available, its value will be stored at protected_at unless this is NULL. */ 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) { static const struct { const char *name; /* Name of the protection method. */ int algo; /* (A zero indicates the "openpgp-native" hack.) */ int keylen; /* Used key length in bytes. */ unsigned int is_ocb:1; } algotable[] = { { "openpgp-s2k3-sha1-aes-cbc", GCRY_CIPHER_AES128, (128/8)}, { "openpgp-s2k3-sha1-aes256-cbc", GCRY_CIPHER_AES256, (256/8)}, { "openpgp-s2k3-ocb-aes", GCRY_CIPHER_AES128, (128/8), 1}, { "openpgp-native", 0, 0 } }; int rc; const unsigned char *s; const unsigned char *protect_list; size_t n; int infidx, i; unsigned char sha1hash[20], sha1hash2[20]; const unsigned char *s2ksalt; unsigned long s2kcount; const unsigned char *iv; int prot_cipher, prot_cipher_keylen; int is_ocb; const unsigned char *aad_begin, *aad_end, *aadhole_begin, *aadhole_end; const unsigned char *prot_begin; unsigned char *cleartext; unsigned char *final; size_t finallen; size_t cutoff, cutlen; if (protected_at) *protected_at = 0; s = protectedkey; 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, "protected-private-key")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); { aad_begin = aad_end = s; aad_end++; i = 1; rc = sskip (&aad_end, &i); if (rc) return rc; } s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); for (infidx=0; protect_info[infidx].algo && !smatch (&s, n, protect_info[infidx].algo); infidx++) ; if (!protect_info[infidx].algo) return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); /* See wether we have a protected-at timestamp. */ protect_list = s; /* Save for later. */ if (protected_at) { while (*s == '(') { prot_begin = s; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "protected-at")) { n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (n != 15) return gpg_error (GPG_ERR_UNKNOWN_SEXP); memcpy (protected_at, s, 15); protected_at[15] = 0; break; } s += n; i = 1; rc = sskip (&s, &i); if (rc) return rc; } } /* Now find the list with the protected information. Here is an example for such a list: (protected openpgp-s2k3-sha1-aes-cbc ((sha1 ) ) ) */ s = protect_list; for (;;) { if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); prot_begin = s; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "protected")) break; s += n; i = 1; rc = sskip (&s, &i); if (rc) return rc; } /* found */ { aadhole_begin = aadhole_end = prot_begin; aadhole_end++; i = 1; rc = sskip (&aadhole_end, &i); if (rc) return rc; } n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); /* Lookup the protection algo. */ prot_cipher = 0; /* (avoid gcc warning) */ prot_cipher_keylen = 0; /* (avoid gcc warning) */ is_ocb = 0; for (i=0; i < DIM (algotable); i++) if (smatch (&s, n, algotable[i].name)) { prot_cipher = algotable[i].algo; prot_cipher_keylen = algotable[i].keylen; is_ocb = algotable[i].is_ocb; break; } if (i == DIM (algotable)) return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION); if (!prot_cipher) /* This is "openpgp-native". */ { gcry_sexp_t s_prot_begin; rc = gcry_sexp_sscan (&s_prot_begin, NULL, prot_begin, gcry_sexp_canon_len (prot_begin, 0,NULL,NULL)); if (rc) return rc; rc = convert_from_openpgp_native (ctrl, s_prot_begin, passphrase, &final); gcry_sexp_release (s_prot_begin); if (!rc) { *result = final; *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL); } return rc; } if (*s != '(' || s[1] != '(') return gpg_error (GPG_ERR_INV_SEXP); s += 2; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "sha1")) return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION); n = snext (&s); if (n != 8) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); s2ksalt = s; s += n; n = snext (&s); if (!n) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); /* We expect a list close as next, so we can simply use strtoul() here. We might want to check that we only have digits - but this is nothing we should worry about */ if (s[n] != ')' ) return gpg_error (GPG_ERR_INV_SEXP); /* Old versions of gpg-agent used the funny floating point number in a byte encoding as specified by OpenPGP. However this is not needed and thus we now store it as a plain unsigned integer. We can easily distinguish the old format by looking at its value: Less than 256 is an old-style encoded number; other values are plain integers. In any case we check that they are at least 65536 because we never used a lower value in the past and we should have a lower limit. */ s2kcount = strtoul ((const char*)s, NULL, 10); if (!s2kcount) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); if (s2kcount < 256) s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6); if (s2kcount < 65536) return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); s += n; s++; /* skip list end */ n = snext (&s); if (is_ocb) { if (n != 12) /* Wrong size of the nonce. */ return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); } else { if (n != 16) /* Wrong blocksize for IV (we support only 128 bit). */ return gpg_error (GPG_ERR_CORRUPTED_PROTECTION); } iv = s; s += n; if (*s != ')' ) return gpg_error (GPG_ERR_INV_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); cleartext = NULL; /* Avoid cc warning. */ rc = do_decryption (aad_begin, aad_end - aad_begin, aadhole_begin, aadhole_end - aadhole_begin, s, n, passphrase, s2ksalt, s2kcount, iv, is_ocb? 12:16, prot_cipher, prot_cipher_keylen, is_ocb, &cleartext); if (rc) return rc; rc = merge_lists (protectedkey, prot_begin-protectedkey, cleartext, is_ocb? NULL : sha1hash, &final, &finallen, &cutoff, &cutlen); /* Albeit cleartext has been allocated in secure memory and thus xfree will wipe it out, we do an extra wipe just in case somethings goes badly wrong. */ wipememory (cleartext, n); xfree (cleartext); if (rc) return rc; if (!is_ocb) { rc = calculate_mic (final, sha1hash2); if (!rc && memcmp (sha1hash, sha1hash2, 20)) rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION); if (rc) { wipememory (final, finallen); xfree (final); return rc; } } /* Now remove the part which is included in the MIC but should not go into the final thing. */ if (cutlen) { memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen); finallen -= cutlen; } *result = final; *resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL); return 0; } /* Check the type of the private key, this is one of the constants: PRIVATE_KEY_UNKNOWN if we can't figure out the type (this is the value 0), PRIVATE_KEY_CLEAR for an unprotected private key. PRIVATE_KEY_PROTECTED for an protected private key or PRIVATE_KEY_SHADOWED for a sub key where the secret parts are stored elsewhere. Finally PRIVATE_KEY_OPENPGP_NONE may be returned is the key is still in the openpgp-native format but without protection. */ int agent_private_key_type (const unsigned char *privatekey) { const unsigned char *s; size_t n; int i; s = privatekey; if (*s != '(') return PRIVATE_KEY_UNKNOWN; s++; n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; if (smatch (&s, n, "protected-private-key")) { /* We need to check whether this is openpgp-native protected with the protection method "none". In that case we return a different key type so that the caller knows that there is no need to ask for a passphrase. */ if (*s != '(') return PRIVATE_KEY_PROTECTED; /* Unknown sexp - assume protected. */ s++; n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ s += n; /* Skip over the algo */ /* Find the (protected ...) list. */ for (;;) { if (*s != '(') return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ s++; n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ if (smatch (&s, n, "protected")) break; s += n; i = 1; if (sskip (&s, &i)) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ } /* Found - Is this openpgp-native? */ n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ if (smatch (&s, n, "openpgp-native")) /* Yes. */ { if (*s != '(') return PRIVATE_KEY_UNKNOWN; /* Unknown sexp. */ s++; n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ s += n; /* Skip over "openpgp-private-key". */ /* Find the (protection ...) list. */ for (;;) { if (*s != '(') return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ s++; n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ if (smatch (&s, n, "protection")) break; s += n; i = 1; if (sskip (&s, &i)) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ } /* Found - Is the mode "none"? */ n = snext (&s); if (!n) return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */ if (smatch (&s, n, "none")) return PRIVATE_KEY_OPENPGP_NONE; /* Yes. */ } return PRIVATE_KEY_PROTECTED; } if (smatch (&s, n, "shadowed-private-key")) return PRIVATE_KEY_SHADOWED; if (smatch (&s, n, "private-key")) return PRIVATE_KEY_CLEAR; return PRIVATE_KEY_UNKNOWN; } /* Transform a passphrase into a suitable key of length KEYLEN and store this key in the caller provided buffer KEY. The caller must provide an HASHALGO, a valid S2KMODE (see rfc-2440) and depending on that mode an S2KSALT of 8 random bytes and an S2KCOUNT. Returns an error code on failure. */ static int hash_passphrase (const char *passphrase, int hashalgo, int s2kmode, const unsigned char *s2ksalt, unsigned long s2kcount, unsigned char *key, size_t keylen) { /* The key derive function does not support a zero length string for the passphrase in the S2K modes. Return a better suited error code than GPG_ERR_INV_DATA. */ if (!passphrase || !*passphrase) return gpg_error (GPG_ERR_NO_PASSPHRASE); return gcry_kdf_derive (passphrase, strlen (passphrase), s2kmode == 3? GCRY_KDF_ITERSALTED_S2K : s2kmode == 1? GCRY_KDF_SALTED_S2K : s2kmode == 0? GCRY_KDF_SIMPLE_S2K : GCRY_KDF_NONE, hashalgo, s2ksalt, 8, s2kcount, keylen, key); } 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) { return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt, S2K_DECODE_COUNT (s2kcount), key, keylen); } /* Create an canonical encoded S-expression with the shadow info from a card's SERIALNO and the IDSTRING. */ unsigned char * make_shadow_info (const char *serialno, const char *idstring) { const char *s; char *info, *p; char numbuf[20]; size_t n; for (s=serialno, n=0; *s && s[1]; s += 2) n++; info = p = xtrymalloc (1 + sizeof numbuf + n + sizeof numbuf + strlen (idstring) + 1 + 1); if (!info) return NULL; *p++ = '('; p = stpcpy (p, smklen (numbuf, sizeof numbuf, n, NULL)); for (s=serialno; *s && s[1]; s += 2) *(unsigned char *)p++ = xtoi_2 (s); p = stpcpy (p, smklen (numbuf, sizeof numbuf, strlen (idstring), NULL)); p = stpcpy (p, idstring); *p++ = ')'; *p = 0; return (unsigned char *)info; } /* Create a shadow key from a public key. We use the shadow protocol "t1-v1" and insert the S-expressionn SHADOW_INFO. The resulting S-expression is returned in an allocated buffer RESULT will point to. The input parameters are expected to be valid canonicalized S-expressions */ int agent_shadow_key (const unsigned char *pubkey, const unsigned char *shadow_info, unsigned char **result) { const unsigned char *s; const unsigned char *point; size_t n; int depth = 0; char *p; size_t pubkey_len = gcry_sexp_canon_len (pubkey, 0, NULL,NULL); size_t shadow_info_len = gcry_sexp_canon_len (shadow_info, 0, NULL,NULL); if (!pubkey_len || !shadow_info_len) return gpg_error (GPG_ERR_INV_VALUE); s = pubkey; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "public-key")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; /* skip over the algorithm name */ while (*s != ')') { if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s +=n; /* skip value */ if (*s != ')') return gpg_error (GPG_ERR_INV_SEXP); depth--; s++; } point = s; /* insert right before the point */ depth--; s++; assert (depth == 1); /* Calculate required length by taking in account: the "shadowed-" prefix, the "shadowed", "t1-v1" as well as some parenthesis */ n = 12 + pubkey_len + 1 + 3+8 + 2+5 + shadow_info_len + 1; *result = xtrymalloc (n); p = (char*)*result; if (!p) return out_of_core (); p = stpcpy (p, "(20:shadowed-private-key"); /* (10:public-key ...)*/ memcpy (p, pubkey+14, point - (pubkey+14)); p += point - (pubkey+14); p = stpcpy (p, "(8:shadowed5:t1-v1"); memcpy (p, shadow_info, shadow_info_len); p += shadow_info_len; *p++ = ')'; memcpy (p, point, pubkey_len - (point - pubkey)); p += pubkey_len - (point - pubkey); return 0; } /* Parse a canonical encoded shadowed key and return a pointer to the inner list with the shadow_info */ gpg_error_t agent_get_shadow_info (const unsigned char *shadowkey, unsigned char const **shadow_info) { const unsigned char *s; size_t n; int depth = 0; s = shadowkey; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (!smatch (&s, n, "shadowed-private-key")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_UNKNOWN_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s += n; /* skip over the algorithm name */ for (;;) { if (*s == ')') return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); depth++; s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "shadowed")) break; s += n; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); s +=n; /* skip value */ if (*s != ')') return gpg_error (GPG_ERR_INV_SEXP); depth--; s++; } /* Found the shadowed list, S points to the protocol */ n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "t1-v1")) { if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); *shadow_info = s; } else return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL); return 0; } /* Parse the canonical encoded SHADOW_INFO S-expression. On success the hex encoded serial number is returned as a malloced strings at R_HEXSN and the Id string as a malloced string at R_IDSTR. On error an error code is returned and NULL is stored at the result parameters addresses. If the serial number or the ID string is not required, NULL may be passed for them. */ gpg_error_t parse_shadow_info (const unsigned char *shadow_info, char **r_hexsn, char **r_idstr, int *r_pinlen) { const unsigned char *s; size_t n; if (r_hexsn) *r_hexsn = NULL; if (r_idstr) *r_idstr = NULL; if (r_pinlen) *r_pinlen = 0; s = shadow_info; if (*s != '(') return gpg_error (GPG_ERR_INV_SEXP); s++; n = snext (&s); if (!n) return gpg_error (GPG_ERR_INV_SEXP); if (r_hexsn) { *r_hexsn = bin2hex (s, n, NULL); if (!*r_hexsn) return gpg_error_from_syserror (); } s += n; n = snext (&s); if (!n) { if (r_hexsn) { xfree (*r_hexsn); *r_hexsn = NULL; } return gpg_error (GPG_ERR_INV_SEXP); } if (r_idstr) { *r_idstr = xtrymalloc (n+1); if (!*r_idstr) { if (r_hexsn) { xfree (*r_hexsn); *r_hexsn = NULL; } return gpg_error_from_syserror (); } memcpy (*r_idstr, s, n); (*r_idstr)[n] = 0; + trim_spaces (*r_idstr); } /* Parse the optional PINLEN. */ n = snext (&s); if (!n) return 0; if (r_pinlen) { char *tmpstr = xtrymalloc (n+1); if (!tmpstr) { if (r_hexsn) { xfree (*r_hexsn); *r_hexsn = NULL; } if (r_idstr) { xfree (*r_idstr); *r_idstr = NULL; } return gpg_error_from_syserror (); } memcpy (tmpstr, s, n); tmpstr[n] = 0; *r_pinlen = (int)strtol (tmpstr, NULL, 10); xfree (tmpstr); } return 0; } diff --git a/g10/mainproc.c b/g10/mainproc.c index 79ff21198..762fc79c8 100644 --- a/g10/mainproc.c +++ b/g10/mainproc.c @@ -1,2805 +1,2808 @@ /* mainproc.c - handle packets * Copyright (C) 1998-2009 Free Software Foundation, Inc. * Copyright (C) 2013-2014 Werner Koch * Copyright (C) 2020 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "options.h" #include "keydb.h" #include "filter.h" #include "main.h" #include "../common/status.h" #include "../common/i18n.h" #include "trustdb.h" #include "keyserver-internal.h" #include "photoid.h" #include "../common/mbox-util.h" #include "call-dirmngr.h" #include "../common/compliance.h" /* Put an upper limit on nested packets. The 32 is an arbitrary value, a much lower should actually be sufficient. */ #define MAX_NESTING_DEPTH 32 /* An object to build a list of keyid related info. */ struct kidlist_item { struct kidlist_item *next; u32 kid[2]; int pubkey_algo; int reason; }; /* * Object to hold the processing context. */ typedef struct mainproc_context *CTX; struct mainproc_context { ctrl_t ctrl; struct mainproc_context *anchor; /* May be useful in the future. */ PKT_public_key *last_pubkey; PKT_user_id *last_user_id; md_filter_context_t mfx; int sigs_only; /* Process only signatures and reject all other stuff. */ int encrypt_only; /* Process only encryption messages. */ /* Name of the file with the complete signature or the file with the detached signature. This is currently only used to deduce the file name of the data file if that has not been given. */ const char *sigfilename; /* A structure to describe the signed data in case of a detached signature. */ struct { /* A file descriptor of the signed data. Only used if not -1. */ int data_fd; /* A list of filenames with the data files or NULL. This is only used if DATA_FD is -1. */ strlist_t data_names; /* Flag to indicated that either one of the next previous fields is used. This is only needed for better readability. */ int used; } signed_data; DEK *dek; int last_was_session_key; kbnode_t list; /* The current list of packets. */ iobuf_t iobuf; /* Used to get the filename etc. */ int trustletter; /* Temporary usage in list_node. */ ulong symkeys; /* Number of symmetrically encrypted session keys. */ struct kidlist_item *pkenc_list; /* List of encryption packets. */ int seen_pkt_encrypted_aead; /* PKT_ENCRYPTED_AEAD packet seen. */ struct { unsigned int sig_seen:1; /* Set to true if a signature packet has been seen. */ unsigned int data:1; /* Any data packet seen */ unsigned int uncompress_failed:1; } any; }; /* Counter with the number of literal data packets seen. Note that * this is also bumped at the end of an encryption. This counter is * used for a basic consistency check of a received PGP message. */ static int literals_seen; /*** Local prototypes. ***/ static int do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a); static void list_node (CTX c, kbnode_t node); static void proc_tree (CTX c, kbnode_t node); /*** Functions. ***/ /* Reset the literal data counter. This is required to setup a new * decryption or verification context. */ void reset_literals_seen(void) { literals_seen = 0; } static void release_list( CTX c ) { proc_tree (c, c->list); release_kbnode (c->list); while (c->pkenc_list) { struct kidlist_item *tmp = c->pkenc_list->next; xfree (c->pkenc_list); c->pkenc_list = tmp; } c->pkenc_list = NULL; c->list = NULL; c->any.data = 0; c->any.uncompress_failed = 0; c->last_was_session_key = 0; c->seen_pkt_encrypted_aead = 0; xfree (c->dek); c->dek = NULL; } static int add_onepass_sig (CTX c, PACKET *pkt) { kbnode_t node; if (c->list) /* Add another packet. */ add_kbnode (c->list, new_kbnode (pkt)); else /* Insert the first one. */ c->list = node = new_kbnode (pkt); return 1; } static int add_gpg_control (CTX c, PACKET *pkt) { if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* New clear text signature. * Process the last one and reset everything */ release_list(c); } if (c->list) /* Add another packet. */ add_kbnode (c->list, new_kbnode (pkt)); else /* Insert the first one. */ c->list = new_kbnode (pkt); return 1; } static int add_user_id (CTX c, PACKET *pkt) { if (!c->list) { log_error ("orphaned user ID\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_subkey (CTX c, PACKET *pkt) { if (!c->list) { log_error ("subkey w/o mainkey\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_ring_trust (CTX c, PACKET *pkt) { if (!c->list) { log_error ("ring trust w/o key\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_signature (CTX c, PACKET *pkt) { kbnode_t node; c->any.sig_seen = 1; if (pkt->pkttype == PKT_SIGNATURE && !c->list) { /* This is the first signature for the following datafile. * GPG does not write such packets; instead it always uses * onepass-sig packets. The drawback of PGP's method * of prepending the signature to the data is * that it is not possible to make a signature from data read * from stdin. (GPG is able to read PGP stuff anyway.) */ node = new_kbnode (pkt); c->list = node; return 1; } else if (!c->list) return 0; /* oops (invalid packet sequence)*/ else if (!c->list->pkt) BUG(); /* so nicht */ /* Add a new signature node item at the end. */ node = new_kbnode (pkt); add_kbnode (c->list, node); return 1; } static gpg_error_t symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen) { gpg_error_t err; gcry_cipher_hd_t hd; enum gcry_cipher_modes ciphermode; unsigned int noncelen, keylen; if (dek->use_aead) { err = openpgp_aead_algo_info (dek->use_aead, &ciphermode, &noncelen); if (err) return err; } else { ciphermode = GCRY_CIPHER_MODE_CFB; noncelen = 0; } /* Check that the session key has a size of 16 to 32 bytes. */ if ((dek->use_aead && (slen < (noncelen + 16 + 16) || slen > (noncelen + 32 + 16))) || (!dek->use_aead && (slen < 17 || slen > 33))) { log_error ( _("weird size for an encrypted session key (%d)\n"), (int)slen); return gpg_error (GPG_ERR_BAD_KEY); } err = openpgp_cipher_open (&hd, dek->algo, ciphermode, 1); if (!err) err = gcry_cipher_setkey (hd, dek->key, dek->keylen); if (!err) err = gcry_cipher_setiv (hd, noncelen? seskey : NULL, noncelen); if (err) goto leave; if (dek->use_aead) { byte ad[4]; ad[0] = (0xc0 | PKT_SYMKEY_ENC); ad[1] = 5; ad[2] = dek->algo; ad[3] = dek->use_aead; err = gcry_cipher_authenticate (hd, ad, 4); if (err) goto leave; gcry_cipher_final (hd); keylen = slen - noncelen - 16; err = gcry_cipher_decrypt (hd, seskey+noncelen, keylen, NULL, 0); if (err) goto leave; err = gcry_cipher_checktag (hd, seskey+noncelen+keylen, 16); if (err) goto leave; /* Now we replace the dek components with the real session key to * decrypt the contents of the sequencing packet. */ if (keylen > DIM(dek->key)) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } dek->keylen = keylen; memcpy (dek->key, seskey + noncelen, dek->keylen); } else { gcry_cipher_decrypt (hd, seskey, slen, NULL, 0); /* Here we can only test whether the algo given in decrypted * session key is a valid OpenPGP algo. With 11 defined * symmetric algorithms we will miss 4.3% of wrong passphrases * here. The actual checking is done later during bulk * decryption; we can't bring this check forward easily. We * need to use the GPG_ERR_CHECKSUM so that we won't run into * the gnupg < 2.2 bug compatible case which would terminate the * process on GPG_ERR_CIPHER_ALGO. Note that with AEAD (above) * we will have a reliable test here. */ if (openpgp_cipher_test_algo (seskey[0]) || openpgp_cipher_get_algo_keylen (seskey[0]) != slen - 1) { err = gpg_error (GPG_ERR_CHECKSUM); goto leave; } /* Now we replace the dek components with the real session key to * decrypt the contents of the sequencing packet. */ keylen = slen-1; if (keylen > DIM(dek->key)) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } dek->algo = seskey[0]; dek->keylen = slen-1; memcpy (dek->key, seskey + 1, dek->keylen); } /*log_hexdump( "thekey", dek->key, dek->keylen );*/ leave: gcry_cipher_close (hd); return 0; } static void proc_symkey_enc (CTX c, PACKET *pkt) { gpg_error_t err; PKT_symkey_enc *enc; enc = pkt->pkt.symkey_enc; if (!enc) log_error ("invalid symkey encrypted packet\n"); else if(!c->dek) { int algo = enc->cipher_algo; const char *s = openpgp_cipher_algo_name (algo); const char *a = (enc->aead_algo ? openpgp_aead_algo_name (enc->aead_algo) /**/ : "CFB"); if (!openpgp_cipher_test_algo (algo)) { if (!opt.quiet) { /* Note: TMPSTR is only used to avoid i18n changes. */ char *tmpstr = xstrconcat (s, ".", a, NULL); if (enc->seskeylen) log_info (_("%s encrypted session key\n"), tmpstr); else log_info (_("%s encrypted data\n"), tmpstr); xfree (tmpstr); } } else log_error (_("encrypted with unknown algorithm %d\n"), algo); if (openpgp_md_test_algo (enc->s2k.hash_algo)) { log_error(_("passphrase generated with unknown digest" " algorithm %d\n"),enc->s2k.hash_algo); s = NULL; } c->last_was_session_key = 2; if (!s || opt.list_only) goto leave; if (opt.override_session_key) { c->dek = xmalloc_clear (sizeof *c->dek); if (get_override_session_key (c->dek, opt.override_session_key)) { xfree (c->dek); c->dek = NULL; } } else { c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL, NULL); if (c->dek) { c->dek->symmetric = 1; c->dek->use_aead = enc->aead_algo; /* FIXME: This doesn't work perfectly if a symmetric key comes before a public key in the message - if the user doesn't know the passphrase, then there is a chance that the "decrypted" algorithm will happen to be a valid one, which will make the returned dek appear valid, so we won't try any public keys that come later. */ if (enc->seskeylen) { err = symkey_decrypt_seskey (c->dek, enc->seskey, enc->seskeylen); if (err) { log_info ("decryption of the symmetrically encrypted" " session key failed: %s\n", gpg_strerror (err)); if (gpg_err_code (err) != GPG_ERR_BAD_KEY && gpg_err_code (err) != GPG_ERR_CHECKSUM) log_fatal ("process terminated to be bug compatible\n"); if (c->dek->s2k_cacheid[0]) { if (opt.debug) log_debug ("cleared passphrase cached with ID:" " %s\n", c->dek->s2k_cacheid); passphrase_clear_cache (c->dek->s2k_cacheid); } xfree (c->dek); c->dek = NULL; } } else c->dek->algo_info_printed = 1; } } } leave: c->symkeys++; free_packet (pkt, NULL); } static void proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt) { PKT_pubkey_enc *enc; int result = 0; /* Check whether the secret key is available and store in this case. */ c->last_was_session_key = 1; enc = pkt->pkt.pubkey_enc; /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/ /* Hmmm: why do I have this algo check here - anyway there is * function to check it. */ if (opt.verbose) log_info (_("public key is %s\n"), keystr (enc->keyid)); if (is_status_enabled()) { char buf[50]; /* FIXME: For ECC support we need to map the OpenPGP algo number to the Libgcrypt defined one. This is due a chicken-egg problem: We need to have code in Libgcrypt for a new algorithm so to implement a proposed new algorithm before the IANA will finally assign an OpenPGP identifier. */ snprintf (buf, sizeof buf, "%08lX%08lX %d 0", (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo); write_status_text (STATUS_ENC_TO, buf); } if (!opt.list_only && opt.override_session_key) { /* It does not make much sense to store the session key in * secure memory because it has already been passed on the * command line and the GCHQ knows about it. */ c->dek = xmalloc_clear (sizeof *c->dek); result = get_override_session_key (c->dek, opt.override_session_key); if (result) { xfree (c->dek); c->dek = NULL; } } else if (enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E || enc->pubkey_algo == PUBKEY_ALGO_ECDH || enc->pubkey_algo == PUBKEY_ALGO_RSA || enc->pubkey_algo == PUBKEY_ALGO_RSA_E || enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL) { /* Note that we also allow type 20 Elgamal keys for decryption. There are still a couple of those keys in active use as a subkey. */ /* FIXME: Store this all in a list and process it later so that we can prioritize what key to use. This gives a better user experience if wildcard keyids are used. */ if (!c->dek && ((!enc->keyid[0] && !enc->keyid[1]) || opt.try_all_secrets || have_secret_key_with_kid (enc->keyid))) { if(opt.list_only) result = GPG_ERR_MISSING_ACTION; /* fixme: Use better error code. */ else { c->dek = xmalloc_secure_clear (sizeof *c->dek); if ((result = get_session_key (ctrl, enc, c->dek))) { /* Error: Delete the DEK. */ xfree (c->dek); c->dek = NULL; } } } else result = GPG_ERR_NO_SECKEY; } else result = GPG_ERR_PUBKEY_ALGO; if (1) { /* Store it for later display. */ struct kidlist_item *x = xmalloc (sizeof *x); x->kid[0] = enc->keyid[0]; x->kid[1] = enc->keyid[1]; x->pubkey_algo = enc->pubkey_algo; x->reason = result; x->next = c->pkenc_list; c->pkenc_list = x; if (!result && opt.verbose > 1) log_info (_("public key encrypted data: good DEK\n")); } free_packet(pkt, NULL); } /* * Print the list of public key encrypted packets which we could * not decrypt. */ static void print_pkenc_list (ctrl_t ctrl, struct kidlist_item *list, int failed) { for (; list; list = list->next) { PKT_public_key *pk; const char *algstr; if (failed && !list->reason) continue; if (!failed && list->reason) continue; algstr = openpgp_pk_algo_name (list->pubkey_algo); pk = xmalloc_clear (sizeof *pk); if (!algstr) algstr = "[?]"; pk->pubkey_algo = list->pubkey_algo; if (!get_pubkey (ctrl, pk, list->kid)) { char *p; log_info (_("encrypted with %u-bit %s key, ID %s, created %s\n"), nbits_from_pk (pk), algstr, keystr_from_pk(pk), strtimestamp (pk->timestamp)); p = get_user_id_native (ctrl, list->kid); log_printf (_(" \"%s\"\n"), p); xfree (p); } else log_info (_("encrypted with %s key, ID %s\n"), algstr, keystr(list->kid)); free_public_key (pk); if (gpg_err_code (list->reason) == GPG_ERR_NO_SECKEY) { if (is_status_enabled()) { char buf[20]; snprintf (buf, sizeof buf, "%08lX%08lX", (ulong)list->kid[0], (ulong)list->kid[1]); write_status_text (STATUS_NO_SECKEY, buf); } } else if (gpg_err_code (list->reason) == GPG_ERR_MISSING_ACTION) { /* Not tested for secret key due to --list-only mode. */ } else if (list->reason) { log_info (_("public key decryption failed: %s\n"), gpg_strerror (list->reason)); + if (gpg_err_source (list->reason) == GPG_ERR_SOURCE_SCD + && gpg_err_code (list->reason) == GPG_ERR_INV_ID) + print_further_info ("a reason might be a card with replaced keys"); write_status_error ("pkdecrypt_failed", list->reason); } } } static void proc_encrypted (CTX c, PACKET *pkt) { int result = 0; int early_plaintext = literals_seen; if (pkt->pkttype == PKT_ENCRYPTED_AEAD) c->seen_pkt_encrypted_aead = 1; if (early_plaintext) { log_info (_("WARNING: multiple plaintexts seen\n")); write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA); /* We fail only later so that we can print some more info first. */ } if (!opt.quiet) { if (c->symkeys>1) log_info (_("encrypted with %lu passphrases\n"), c->symkeys); else if (c->symkeys == 1) log_info (_("encrypted with 1 passphrase\n")); print_pkenc_list (c->ctrl, c->pkenc_list, 1 ); print_pkenc_list (c->ctrl, c->pkenc_list, 0 ); } /* FIXME: Figure out the session key by looking at all pkenc packets. */ write_status (STATUS_BEGIN_DECRYPTION); /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/ if (opt.list_only) result = -1; else if (!c->dek && !c->last_was_session_key) { int algo; STRING2KEY s2kbuf; STRING2KEY *s2k = NULL; int canceled; if (opt.override_session_key) { c->dek = xmalloc_clear (sizeof *c->dek); result = get_override_session_key (c->dek, opt.override_session_key); if (result) { xfree (c->dek); c->dek = NULL; } } else { /* Assume this is old style conventional encrypted data. */ algo = opt.def_cipher_algo; if (algo) log_info (_("assuming %s encrypted data\n"), openpgp_cipher_algo_name (algo)); else if (openpgp_cipher_test_algo (CIPHER_ALGO_IDEA)) { algo = opt.def_cipher_algo; if (!algo) algo = opt.s2k_cipher_algo; log_info (_("IDEA cipher unavailable, " "optimistically attempting to use %s instead\n"), openpgp_cipher_algo_name (algo)); } else { algo = CIPHER_ALGO_IDEA; if (!opt.s2k_digest_algo) { /* If no digest is given we assume SHA-1. */ s2kbuf.mode = 0; s2kbuf.hash_algo = DIGEST_ALGO_SHA1; s2k = &s2kbuf; } log_info (_("assuming %s encrypted data\n"), "IDEA"); } c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL, &canceled); if (c->dek) c->dek->algo_info_printed = 1; else if (canceled) result = gpg_error (GPG_ERR_CANCELED); else result = gpg_error (GPG_ERR_INV_PASSPHRASE); } } else if (!c->dek) result = GPG_ERR_NO_SECKEY; /* Compute compliance with CO_DE_VS. */ if (!result && is_status_enabled () /* Symmetric encryption and asymmetric encryption voids compliance. */ && (c->symkeys != !!c->pkenc_list ) /* Overriding session key voids compliance. */ && !opt.override_session_key /* Check symmetric cipher. */ && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo, GCRY_CIPHER_MODE_CFB)) { struct kidlist_item *i; int compliant = 1; PKT_public_key *pk = xmalloc (sizeof *pk); if ( !(c->pkenc_list || c->symkeys) ) log_debug ("%s: where else did the session key come from?\n", __func__); /* Now check that every key used to encrypt the session key is * compliant. */ for (i = c->pkenc_list; i && compliant; i = i->next) { memset (pk, 0, sizeof *pk); pk->pubkey_algo = i->pubkey_algo; if (get_pubkey (c->ctrl, pk, i->kid) != 0 || ! gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL)) compliant = 0; release_public_key_parts (pk); } xfree (pk); if (compliant) write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS), NULL); } if (!result) result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek ); /* Trigger the deferred error. */ if (!result && early_plaintext) result = gpg_error (GPG_ERR_BAD_DATA); if (result == -1) ; else if (!result && !opt.ignore_mdc_error && !pkt->pkt.encrypted->mdc_method && !pkt->pkt.encrypted->aead_algo) { /* The message has been decrypted but does not carry an MDC. * The option --ignore-mdc-error has also not been used. To * avoid attacks changing an MDC message to a non-MDC message, * we fail here. */ log_error (_("WARNING: message was not integrity protected\n")); if (!pkt->pkt.encrypted->mdc_method && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8 || c->dek->algo == CIPHER_ALGO_TWOFISH)) { /* Before 2.2.8 we did not fail hard for a missing MDC if * one of the old ciphers where used. Although these cases * are rare in practice we print a hint on how to decrypt * such messages. */ log_string (GPGRT_LOG_INFO, _("Hint: If this message was created before the year 2003 it is\n" "likely that this message is legitimate. This is because back\n" "then integrity protection was not widely used.\n")); log_info (_("Use the option '%s' to decrypt anyway.\n"), "--ignore-mdc-error"); write_status_errcode ("nomdc_with_legacy_cipher", GPG_ERR_DECRYPT_FAILED); } log_info (_("decryption forced to fail!\n")); write_status (STATUS_DECRYPTION_FAILED); } else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE && !pkt->pkt.encrypted->aead_algo && opt.ignore_mdc_error)) { /* All is fine or for an MDC message the MDC failed but the * --ignore-mdc-error option is active. For compatibility * reasons we issue GOODMDC also for AEAD messages. */ write_status (STATUS_DECRYPTION_OKAY); if (opt.verbose > 1) log_info(_("decryption okay\n")); if (pkt->pkt.encrypted->aead_algo) write_status (STATUS_GOODMDC); else if (pkt->pkt.encrypted->mdc_method && !result) write_status (STATUS_GOODMDC); else log_info (_("WARNING: message was not integrity protected\n")); } else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE || gpg_err_code (result) == GPG_ERR_TRUNCATED) { glo_ctrl.lasterr = result; log_error (_("WARNING: encrypted message has been manipulated!\n")); write_status (STATUS_BADMDC); write_status (STATUS_DECRYPTION_FAILED); } else { if ((gpg_err_code (result) == GPG_ERR_BAD_KEY || gpg_err_code (result) == GPG_ERR_CHECKSUM || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO) && *c->dek->s2k_cacheid != '\0') { if (opt.debug) log_debug ("cleared passphrase cached with ID: %s\n", c->dek->s2k_cacheid); passphrase_clear_cache (c->dek->s2k_cacheid); } glo_ctrl.lasterr = result; write_status (STATUS_DECRYPTION_FAILED); log_error (_("decryption failed: %s\n"), gpg_strerror (result)); /* Hmmm: does this work when we have encrypted using multiple * ways to specify the session key (symmmetric and PK). */ } xfree (c->dek); c->dek = NULL; free_packet (pkt, NULL); c->last_was_session_key = 0; write_status (STATUS_END_DECRYPTION); /* Bump the counter even if we have not seen a literal data packet * inside an encryption container. This acts as a sentinel in case * a misplace extra literal data packets follows after this * encrypted packet. */ literals_seen++; } static int have_seen_pkt_encrypted_aead( CTX c ) { CTX cc; for (cc = c; cc; cc = cc->anchor) { if (cc->seen_pkt_encrypted_aead) return 1; } return 0; } static void proc_plaintext( CTX c, PACKET *pkt ) { PKT_plaintext *pt = pkt->pkt.plaintext; int any, clearsig, rc; kbnode_t n; /* This is a literal data packet. Bumb a counter for later checks. */ literals_seen++; if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8)) log_info (_("Note: sender requested \"for-your-eyes-only\"\n")); else if (opt.verbose) { /* We don't use print_utf8_buffer because that would require a * string change which we don't want in 2.2. It is also not * clear whether the filename is always utf-8 encoded. */ char *tmp = make_printable_string (pt->name, pt->namelen, 0); log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp); xfree (tmp); } free_md_filter_context (&c->mfx); if (gcry_md_open (&c->mfx.md, 0, 0)) BUG (); /* fixme: we may need to push the textfilter if we have sigclass 1 * and no armoring - Not yet tested * Hmmm, why don't we need it at all if we have sigclass 1 * Should we assume that plaintext in mode 't' has always sigclass 1?? * See: Russ Allbery's mail 1999-02-09 */ any = clearsig = 0; for (n=c->list; n; n = n->next ) { if (n->pkt->pkttype == PKT_ONEPASS_SIG) { /* The onepass signature case. */ if (n->pkt->pkt.onepass_sig->digest_algo) { if (!opt.skip_verify) gcry_md_enable (c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo); any = 1; } } else if (n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START) { /* The clearsigned message case. */ size_t datalen = n->pkt->pkt.gpg_control->datalen; const byte *data = n->pkt->pkt.gpg_control->data; /* Check that we have at least the sigclass and one hash. */ if (datalen < 2) log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n"); /* Note that we don't set the clearsig flag for not-dash-escaped * documents. */ clearsig = (*data == 0x01); for (data++, datalen--; datalen; datalen--, data++) if (!opt.skip_verify) gcry_md_enable (c->mfx.md, *data); any = 1; break; /* Stop here as one-pass signature packets are not expected. */ } else if (n->pkt->pkttype == PKT_SIGNATURE) { /* The SIG+LITERAL case that PGP used to use. */ if (!opt.skip_verify) gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo); any = 1; } } if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead(c)) { /* This is for the old GPG LITERAL+SIG case. It's not legal according to 2440, so hopefully it won't come up that often. There is no good way to specify what algorithms to use in that case, so these there are the historical answer. */ gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160); gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1); } if (DBG_HASHING) { gcry_md_debug (c->mfx.md, "verify"); if (c->mfx.md2) gcry_md_debug (c->mfx.md2, "verify2"); } rc=0; if (literals_seen > 1) { log_info (_("WARNING: multiple plaintexts seen\n")); if (!opt.flags.allow_multiple_messages) { write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA"); log_inc_errorcount (); rc = gpg_error (GPG_ERR_UNEXPECTED); } } if (!rc) { /* It we are in --verify mode, we do not want to output the * signed text. However, if --output is also used we do what * has been requested and write out the signed data. */ rc = handle_plaintext (pt, &c->mfx, (opt.outfp || opt.outfile)? 0 : c->sigs_only, clearsig); if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only) { /* Can't write output but we hash it anyway to check the signature. */ rc = handle_plaintext( pt, &c->mfx, 1, clearsig ); } } if (rc) log_error ("handle plaintext failed: %s\n", gpg_strerror (rc)); free_packet (pkt, NULL); c->last_was_session_key = 0; /* We add a marker control packet instead of the plaintext packet. * This is so that we can later detect invalid packet sequences. */ n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0)); if (c->list) add_kbnode (c->list, n); else c->list = n; } static int proc_compressed_cb (iobuf_t a, void *info) { if ( ((CTX)info)->signed_data.used && ((CTX)info)->signed_data.data_fd != -1) return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a, ((CTX)info)->signed_data.data_fd); else return proc_signature_packets (((CTX)info)->ctrl, info, a, ((CTX)info)->signed_data.data_names, ((CTX)info)->sigfilename ); } static int proc_encrypt_cb (iobuf_t a, void *info ) { CTX c = info; return proc_encryption_packets (c->ctrl, info, a ); } static int proc_compressed (CTX c, PACKET *pkt) { PKT_compressed *zd = pkt->pkt.compressed; int rc; /*printf("zip: compressed data packet\n");*/ if (c->sigs_only) rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c); else if( c->encrypt_only ) rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c); else rc = handle_compressed (c->ctrl, c, zd, NULL, NULL); if (gpg_err_code (rc) == GPG_ERR_BAD_DATA) { if (!c->any.uncompress_failed) { CTX cc; for (cc=c; cc; cc = cc->anchor) cc->any.uncompress_failed = 1; log_error ("uncompressing failed: %s\n", gpg_strerror (rc)); } } else if (rc) log_error ("uncompressing failed: %s\n", gpg_strerror (rc)); free_packet (pkt, NULL); c->last_was_session_key = 0; return rc; } /* * Check the signature. If R_PK is not NULL a copy of the public key * used to verify the signature will be stored there, or NULL if not * found. If FORCED_PK is not NULL, this public key is used to verify * _data signatures_ and no key lookup is done. Returns: 0 = valid * signature or an error code */ static int do_check_sig (CTX c, kbnode_t node, PKT_public_key *forced_pk, int *is_selfsig, int *is_expkey, int *is_revkey, PKT_public_key **r_pk) { PKT_signature *sig; gcry_md_hd_t md = NULL; gcry_md_hd_t md2 = NULL; gcry_md_hd_t md_good = NULL; int algo, rc; if (r_pk) *r_pk = NULL; log_assert (node->pkt->pkttype == PKT_SIGNATURE); if (is_selfsig) *is_selfsig = 0; sig = node->pkt->pkt.signature; algo = sig->digest_algo; rc = openpgp_md_test_algo (algo); if (rc) return rc; if (sig->sig_class == 0x00) { if (c->mfx.md) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); } else /* detached signature */ { /* check_signature() will enable the md. */ if (gcry_md_open (&md, 0, 0 )) BUG (); } } else if (sig->sig_class == 0x01) { /* How do we know that we have to hash the (already hashed) text in canonical mode ??? (calculating both modes???) */ if (c->mfx.md) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2)) BUG (); } else /* detached signature */ { log_debug ("Do we really need this here?"); /* check_signature() will enable the md*/ if (gcry_md_open (&md, 0, 0 )) BUG (); if (gcry_md_open (&md2, 0, 0 )) BUG (); } } else if ((sig->sig_class&~3) == 0x10 || sig->sig_class == 0x18 || sig->sig_class == 0x1f || sig->sig_class == 0x20 || sig->sig_class == 0x28 || sig->sig_class == 0x30) { if (c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY) { return check_key_signature (c->ctrl, c->list, node, is_selfsig); } else if (sig->sig_class == 0x20) { log_error (_("standalone revocation - " "use \"gpg --import\" to apply\n")); return GPG_ERR_NOT_PROCESSED; } else { log_error ("invalid root packet for sigclass %02x\n", sig->sig_class); return GPG_ERR_SIG_CLASS; } } else return GPG_ERR_SIG_CLASS; /* We only get here if we are checking the signature of a binary (0x00) or text document (0x01). */ rc = check_signature2 (c->ctrl, sig, md, forced_pk, NULL, is_expkey, is_revkey, r_pk); if (! rc) md_good = md; else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2) { PKT_public_key *pk2; rc = check_signature2 (c->ctrl, sig, md2, forced_pk, NULL, is_expkey, is_revkey, r_pk? &pk2 : NULL); if (!rc) { md_good = md2; if (r_pk) { free_public_key (*r_pk); *r_pk = pk2; } } } if (md_good) { unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo); sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo)); memcpy (sig->digest, buffer, sig->digest_len); } gcry_md_close (md); gcry_md_close (md2); return rc; } static void print_userid (PACKET *pkt) { if (!pkt) BUG(); if (pkt->pkttype != PKT_USER_ID) { es_printf ("ERROR: unexpected packet type %d", pkt->pkttype ); return; } if (opt.with_colons) { if (pkt->pkt.user_id->attrib_data) es_printf("%u %lu", pkt->pkt.user_id->numattribs, pkt->pkt.user_id->attrib_len); else es_write_sanitized (es_stdout, pkt->pkt.user_id->name, pkt->pkt.user_id->len, ":", NULL); } else print_utf8_buffer (es_stdout, pkt->pkt.user_id->name, pkt->pkt.user_id->len ); } /* * List the keyblock in a user friendly way */ static void list_node (CTX c, kbnode_t node) { if (!node) ; else if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = node->pkt->pkt.public_key; if (opt.with_colons) { u32 keyid[2]; keyid_from_pk( pk, keyid ); if (pk->flags.primary) c->trustletter = (opt.fast_list_mode ? 0 : get_validity_info (c->ctrl, node->pkt->pkttype == PKT_PUBLIC_KEY ? node : NULL, pk, NULL)); es_printf ("%s:", pk->flags.primary? "pub":"sub" ); if (c->trustletter) es_putc (c->trustletter, es_stdout); es_printf (":%u:%d:%08lX%08lX:%s:%s::", nbits_from_pk( pk ), pk->pubkey_algo, (ulong)keyid[0],(ulong)keyid[1], colon_datestr_from_pk( pk ), colon_strtime (pk->expiredate) ); if (pk->flags.primary && !opt.fast_list_mode) es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout); es_putc (':', es_stdout); es_putc ('\n', es_stdout); } else { print_key_line (c->ctrl, es_stdout, pk, 0); } if (opt.keyid_format == KF_NONE && !opt.with_colons) ; /* Already printed. */ else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1) print_fingerprint (c->ctrl, NULL, pk, 0); if (pk->flags.primary) { int kl = opt.keyid_format == KF_NONE? 0 : keystrlen (); /* Now list all userids with their signatures. */ for (node = node->next; node; node = node->next) { if (node->pkt->pkttype == PKT_SIGNATURE) { list_node (c, node ); } else if (node->pkt->pkttype == PKT_USER_ID) { if (opt.with_colons) es_printf ("%s:::::::::", node->pkt->pkt.user_id->attrib_data?"uat":"uid"); else es_printf ("uid%*s", kl + (opt.legacy_list_mode? 9:11), "" ); print_userid (node->pkt); if (opt.with_colons) es_putc (':', es_stdout); es_putc ('\n', es_stdout); } else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { list_node(c, node ); } } } } else if (node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { log_debug ("FIXME: No way to print secret key packets here\n"); /* fixme: We may use a function to turn a secret key packet into a public key one and use that here. */ } else if (node->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = node->pkt->pkt.signature; int is_selfsig = 0; int rc2 = 0; size_t n; char *p; int sigrc = ' '; if (!opt.verbose) return; if (sig->sig_class == 0x20 || sig->sig_class == 0x30) es_fputs ("rev", es_stdout); else es_fputs ("sig", es_stdout); if (opt.check_sigs) { fflush (stdout); rc2 = do_check_sig (c, node, NULL, &is_selfsig, NULL, NULL, NULL); switch (gpg_err_code (rc2)) { case 0: sigrc = '!'; break; case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break; case GPG_ERR_NO_PUBKEY: case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break; default: sigrc = '%'; break; } } else /* Check whether this is a self signature. */ { u32 keyid[2]; if (c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_SECRET_KEY ) { keyid_from_pk (c->list->pkt->pkt.public_key, keyid); if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]) is_selfsig = 1; } } if (opt.with_colons) { es_putc (':', es_stdout); if (sigrc != ' ') es_putc (sigrc, es_stdout); es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo, (ulong)sig->keyid[0], (ulong)sig->keyid[1], colon_datestr_from_sig (sig), colon_expirestr_from_sig (sig)); if (sig->trust_depth || sig->trust_value) es_printf ("%d %d",sig->trust_depth,sig->trust_value); es_putc (':', es_stdout); if (sig->trust_regexp) es_write_sanitized (es_stdout, sig->trust_regexp, strlen (sig->trust_regexp), ":", NULL); es_putc (':', es_stdout); } else es_printf ("%c %s %s ", sigrc, keystr (sig->keyid), datestr_from_sig(sig)); if (sigrc == '%') es_printf ("[%s] ", gpg_strerror (rc2) ); else if (sigrc == '?') ; else if (is_selfsig) { if (opt.with_colons) es_putc (':', es_stdout); es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout); if (opt.with_colons) es_putc (':', es_stdout); } else if (!opt.fast_list_mode) { p = get_user_id (c->ctrl, sig->keyid, &n, NULL); es_write_sanitized (es_stdout, p, n, opt.with_colons?":":NULL, NULL ); xfree (p); } if (opt.with_colons) es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l'); es_putc ('\n', es_stdout); } else log_error ("invalid node with packet of type %d\n", node->pkt->pkttype); } int proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a ) { int rc; CTX c = xmalloc_clear (sizeof *c); c->ctrl = ctrl; c->anchor = anchor; rc = do_proc_packets (ctrl, c, a); xfree (c); return rc; } int proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a, strlist_t signedfiles, const char *sigfilename ) { CTX c = xmalloc_clear (sizeof *c); int rc; c->ctrl = ctrl; c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = -1; c->signed_data.data_names = signedfiles; c->signed_data.used = !!signedfiles; c->sigfilename = sigfilename; rc = do_proc_packets (ctrl, c, a); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any.sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = GPG_ERR_NO_DATA; } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any.sig_seen) c->anchor->any.sig_seen = 1; xfree (c); return rc; } int proc_signature_packets_by_fd (ctrl_t ctrl, void *anchor, iobuf_t a, int signed_data_fd ) { int rc; CTX c; c = xtrycalloc (1, sizeof *c); if (!c) return gpg_error_from_syserror (); c->ctrl = ctrl; c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = signed_data_fd; c->signed_data.data_names = NULL; c->signed_data.used = (signed_data_fd != -1); rc = do_proc_packets (ctrl, c, a); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any.sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = gpg_error (GPG_ERR_NO_DATA); } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any.sig_seen) c->anchor->any.sig_seen = 1; xfree ( c ); return rc; } int proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a ) { CTX c = xmalloc_clear (sizeof *c); int rc; c->ctrl = ctrl; c->anchor = anchor; c->encrypt_only = 1; rc = do_proc_packets (ctrl, c, a); xfree (c); return rc; } static int check_nesting (CTX c) { int level; for (level=0; c; c = c->anchor) level++; if (level > MAX_NESTING_DEPTH) { log_error ("input data with too deeply nested packets\n"); write_status_text (STATUS_UNEXPECTED, "1"); return GPG_ERR_BAD_DATA; } return 0; } static int do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a) { PACKET *pkt; struct parse_packet_ctx_s parsectx; int rc = 0; int any_data = 0; int newpkt; rc = check_nesting (c); if (rc) return rc; pkt = xmalloc( sizeof *pkt ); c->iobuf = a; init_packet(pkt); init_parse_packet (&parsectx, a); while ((rc=parse_packet (&parsectx, pkt)) != -1) { any_data = 1; if (rc) { free_packet (pkt, &parsectx); /* Stop processing when an invalid packet has been encountered * but don't do so when we are doing a --list-packets. */ if (gpg_err_code (rc) == GPG_ERR_INV_PACKET && opt.list_packets == 0) break; continue; } newpkt = -1; if (opt.list_packets) { switch (pkt->pkttype) { case PKT_PUBKEY_ENC: proc_pubkey_enc (ctrl, c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; default: newpkt = 0; break; } } else if (c->sigs_only) { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: case PKT_SYMKEY_ENC: case PKT_PUBKEY_ENC: case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: write_status_text( STATUS_UNEXPECTED, "0" ); rc = GPG_ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break; default: newpkt = 0; break; } } else if (c->encrypt_only) { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: write_status_text (STATUS_UNEXPECTED, "0"); rc = GPG_ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_PUBKEY_ENC: proc_pubkey_enc (ctrl, c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break; default: newpkt = 0; break; } } else { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: release_list (c); c->list = new_kbnode (pkt); newpkt = 1; break; case PKT_PUBLIC_SUBKEY: case PKT_SECRET_SUBKEY: newpkt = add_subkey (c, pkt); break; case PKT_USER_ID: newpkt = add_user_id (c, pkt); break; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_PUBKEY_ENC: proc_pubkey_enc (ctrl, c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break; case PKT_RING_TRUST: newpkt = add_ring_trust (c, pkt); break; default: newpkt = 0; break; } } if (rc) goto leave; /* This is a very ugly construct and frankly, I don't remember why * I used it. Adding the MDC check here is a hack. * The right solution is to initiate another context for encrypted * packet and not to reuse the current one ... It works right * when there is a compression packet between which adds just * an extra layer. * Hmmm: Rewrite this whole module here?? */ if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC) c->any.data = (pkt->pkttype == PKT_PLAINTEXT); if (newpkt == -1) ; else if (newpkt) { pkt = xmalloc (sizeof *pkt); init_packet (pkt); } else free_packet (pkt, &parsectx); } if (rc == GPG_ERR_INV_PACKET) write_status_text (STATUS_NODATA, "3"); if (any_data) rc = 0; else if (rc == -1) write_status_text (STATUS_NODATA, "2"); leave: release_list (c); xfree(c->dek); free_packet (pkt, &parsectx); deinit_parse_packet (&parsectx); xfree (pkt); free_md_filter_context (&c->mfx); return rc; } /* Helper for pka_uri_from_sig to parse the to-be-verified address out of the notation data. */ static pka_info_t * get_pka_address (PKT_signature *sig) { pka_info_t *pka = NULL; struct notation *nd,*notation; notation=sig_to_notation(sig); for(nd=notation;nd;nd=nd->next) { if(strcmp(nd->name,"pka-address@gnupg.org")!=0) continue; /* Not the notation we want. */ /* For now we only use the first valid PKA notation. In future we might want to keep additional PKA notations in a linked list. */ if (is_valid_mailbox (nd->value)) { pka = xmalloc (sizeof *pka + strlen(nd->value)); pka->valid = 0; pka->checked = 0; pka->uri = NULL; strcpy (pka->email, nd->value); break; } } free_notation(notation); return pka; } /* Return the URI from a DNS PKA record. If this record has already be retrieved for the signature we merely return it; if not we go out and try to get that DNS record. */ static const char * pka_uri_from_sig (CTX c, PKT_signature *sig) { if (!sig->flags.pka_tried) { log_assert (!sig->pka_info); sig->flags.pka_tried = 1; sig->pka_info = get_pka_address (sig); if (sig->pka_info) { char *url; unsigned char *fpr; size_t fprlen; if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email, &fpr, &fprlen, &url)) { if (fpr && fprlen == sizeof sig->pka_info->fpr) { memcpy (sig->pka_info->fpr, fpr, fprlen); if (url) { sig->pka_info->valid = 1; if (!*url) xfree (url); else sig->pka_info->uri = url; url = NULL; } } xfree (fpr); xfree (url); } } } return sig->pka_info? sig->pka_info->uri : NULL; } /* Return true if the AKL has the WKD method specified. */ static int akl_has_wkd_method (void) { struct akl *akl; for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type == AKL_WKD) return 1; return 0; } /* Return the ISSUER fingerprint buffer and its lenbgth at R_LEN. * Returns NULL if not available. The returned buffer is valid as * long as SIG is not modified. */ const byte * issuer_fpr_raw (PKT_signature *sig, size_t *r_len) { const byte *p; size_t n; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n); if (p && n == 21 && p[0] == 4) { *r_len = n - 1; return p+1; } *r_len = 0; return NULL; } /* Return the ISSUER fingerprint string in human readable format if * available. Caller must release the string. */ /* FIXME: Move to another file. */ char * issuer_fpr_string (PKT_signature *sig) { const byte *p; size_t n; p = issuer_fpr_raw (sig, &n); return p? bin2hex (p, n, NULL) : NULL; } static void print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un, PKT_signature *sig, int rc) { char *p; write_status_text_and_buffer (statno, keyid_str, un? un->pkt->pkt.user_id->name:"[?]", un? un->pkt->pkt.user_id->len:3, -1); if (un) p = utf8_to_native (un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len, 0); else p = xstrdup ("[?]"); if (rc) log_info (_("BAD signature from \"%s\""), p); else if (sig->flags.expired) log_info (_("Expired signature from \"%s\""), p); else log_info (_("Good signature from \"%s\""), p); xfree (p); } static int check_sig_and_print (CTX c, kbnode_t node) { PKT_signature *sig = node->pkt->pkt.signature; const char *astr; int rc; int is_expkey = 0; int is_revkey = 0; char *issuer_fpr = NULL; PKT_public_key *pk = NULL; /* The public key for the signature or NULL. */ kbnode_t included_keyblock = NULL; if (opt.skip_verify) { log_info(_("signature verification suppressed\n")); return 0; } /* Check that the message composition is valid. * * Per RFC-2440bis (-15) allowed: * * S{1,n} -- detached signature. * S{1,n} P -- old style PGP2 signature * O{1,n} P S{1,n} -- standard OpenPGP signature. * C P S{1,n} -- cleartext signature. * * * O = One-Pass Signature packet. * S = Signature packet. * P = OpenPGP Message packet (Encrypted | Compressed | Literal) * (Note that the current rfc2440bis draft also allows * for a signed message but that does not work as it * introduces ambiguities.) * We keep track of these packages using the marker packet * CTRLPKT_PLAINTEXT_MARK. * C = Marker packet for cleartext signatures. * * We reject all other messages. * * Actually we are calling this too often, i.e. for verification of * each message but better have some duplicate work than to silently * introduce a bug here. */ { kbnode_t n; int n_onepass, n_sig; /* log_debug ("checking signature packet composition\n"); */ /* dump_kbnode (c->list); */ n = c->list; log_assert (n); if ( n->pkt->pkttype == PKT_SIGNATURE ) { /* This is either "S{1,n}" case (detached signature) or "S{1,n} P" (old style PGP2 signature). */ for (n = n->next; n; n = n->next) if (n->pkt->pkttype != PKT_SIGNATURE) break; if (!n) ; /* Okay, this is a detached signature. */ else if (n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK) ) { if (n->next) goto ambiguous; /* We only allow one P packet. */ } else goto ambiguous; } else if (n->pkt->pkttype == PKT_ONEPASS_SIG) { /* This is the "O{1,n} P S{1,n}" case (standard signature). */ for (n_onepass=1, n = n->next; n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next) n_onepass++; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (!n_sig) goto ambiguous; /* If we wanted to disallow multiple sig verification, we'd do something like this: if (n && !opt.allow_multisig_verification) goto ambiguous; However, now that we have --allow-multiple-messages, this can stay allowable as we can't get here unless multiple messages (i.e. multiple literals) are allowed. */ if (n_onepass != n_sig) { log_info ("number of one-pass packets does not match " "number of signature packets\n"); goto ambiguous; } } else if (n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* This is the "C P S{1,n}" case (clear text signature). */ n = n->next; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (n || !n_sig) goto ambiguous; } else { ambiguous: log_error(_("can't handle this ambiguous signature data\n")); return 0; } } if (sig->signers_uid) write_status_buffer (STATUS_NEWSIG, sig->signers_uid, strlen (sig->signers_uid), 0); else write_status_text (STATUS_NEWSIG, NULL); astr = openpgp_pk_algo_name ( sig->pubkey_algo ); issuer_fpr = issuer_fpr_string (sig); if (issuer_fpr) { log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp)); log_info (_(" using %s key %s\n"), astr? astr: "?", issuer_fpr); } else if (!keystrlen () || keystrlen () > 8) { log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp)); log_info (_(" using %s key %s\n"), astr? astr: "?", keystr(sig->keyid)); } else /* Legacy format. */ log_info (_("Signature made %s using %s key ID %s\n"), asctimestamp(sig->timestamp), astr? astr: "?", keystr(sig->keyid)); /* In verbose mode print the signers UID. */ if (sig->signers_uid) log_info (_(" issuer \"%s\"\n"), sig->signers_uid); rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk); /* If the key is not found but the signature includes a key block we * use that key block for verification and on success import it. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.key_block && opt.flags.auto_key_import) { PKT_public_key *included_pk; const byte *kblock; size_t kblock_len; included_pk = xcalloc (1, sizeof *included_pk); kblock = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_BLOCK, &kblock_len); if (kblock && kblock_len > 1 && !get_pubkey_from_buffer (c->ctrl, included_pk, kblock+1, kblock_len-1, sig->keyid, &included_keyblock)) { rc = do_check_sig (c, node, included_pk, NULL, &is_expkey, &is_revkey, &pk); if (!rc) { /* The keyblock has been verified, we now import it. */ rc = import_included_key_block (c->ctrl, included_keyblock); } } free_public_key (included_pk); } /* If the key isn't found, check for a preferred keyserver. Note * that this is only done if honor-keyserver-url has been set. We * test for this in the loop so that we can show info about the * preferred keyservers. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks) { const byte *p; int seq = 0; size_t n; int any_pref_ks = 0; while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL))) { /* According to my favorite copy editor, in English grammar, you say "at" if the key is located on a web page, but "from" if it is located on a keyserver. I'm not going to even try to make two strings here :) */ log_info(_("Key available at: ") ); print_utf8_buffer (log_get_stream(), p, n); log_printf ("\n"); any_pref_ks = 1; if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)) { struct keyserver_spec *spec; spec = parse_preferred_keyserver (sig); if (spec) { int res; if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "Pref-KS"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; res = keyserver_import_keyid (c->ctrl, sig->keyid,spec, 1); glo_ctrl.in_auto_key_retrieve--; if (!res) rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "Pref-KS", gpg_strerror (res)); free_keyserver_spec (spec); if (!rc) break; } } } if (any_pref_ks && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)) log_info (_("Note: Use '%s' to make use of this info\n"), "--keyserver-option honor-keyserver-url"); } /* If the above methods didn't work, our next try is to retrieve the * key from the WKD. This requires that WKD is in the AKL and the * Signer's UID is in the signature. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE) && !opt.flags.disable_signer_uid && akl_has_wkd_method () && sig->signers_uid) { int res; if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "WKD"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; res = keyserver_import_wkd (c->ctrl, sig->signers_uid, 1, NULL, NULL); glo_ctrl.in_auto_key_retrieve--; /* Fixme: If the fingerprint is embedded in the signature, * compare it to the fingerprint of the returned key. */ if (!res) rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res)); } /* If the avove methods didn't work, our next try is to use the URI * from a DNS PKA record. This is a legacy method which will * eventually be removed. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE) && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD)) { const char *uri = pka_uri_from_sig (c, sig); if (uri) { /* FIXME: We might want to locate the key using the fingerprint instead of the keyid. */ int res; struct keyserver_spec *spec; spec = parse_keyserver_uri (uri, 1); if (spec) { if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "PKA"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; res = keyserver_import_keyid (c->ctrl, sig->keyid, spec, 1); glo_ctrl.in_auto_key_retrieve--; free_keyserver_spec (spec); if (!res) rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "PKA", gpg_strerror (res)); } } } /* If the above methods didn't work, our next try is to locate * the key via its fingerprint from a keyserver. This requires * that the signers fingerprint is encoded in the signature. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && keyserver_any_configured (c->ctrl)) { int res; const byte *p; size_t n; p = issuer_fpr_raw (sig, &n); if (p) { /* v4 packet with a SHA-1 fingerprint. */ if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "KS"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver, 1); glo_ctrl.in_auto_key_retrieve--; if (!res) rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res)); } } if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE) { kbnode_t un, keyblock; int count = 0; int statno; char keyid_str[50]; PKT_public_key *mainpk = NULL; if (rc) statno = STATUS_BADSIG; else if (sig->flags.expired) statno = STATUS_EXPSIG; else if (is_expkey) statno = STATUS_EXPKEYSIG; else if(is_revkey) statno = STATUS_REVKEYSIG; else statno = STATUS_GOODSIG; /* FIXME: We should have the public key in PK and thus the * keyblock has already been fetched. Thus we could use the * fingerprint or PK itself to lookup the entire keyblock. That * would best be done with a cache. */ if (included_keyblock) { keyblock = included_keyblock; included_keyblock = NULL; } else keyblock = get_pubkeyblock_for_sig (c->ctrl, sig); snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ", (ulong)sig->keyid[0], (ulong)sig->keyid[1]); /* Find and print the primary user ID along with the "Good|Expired|Bad signature" line. */ for (un=keyblock; un; un = un->next) { int valid; if (un->pkt->pkttype==PKT_PUBLIC_KEY) { mainpk = un->pkt->pkt.public_key; continue; } if (un->pkt->pkttype != PKT_USER_ID) continue; if (!un->pkt->pkt.user_id->created) continue; if (un->pkt->pkt.user_id->flags.revoked) continue; if (un->pkt->pkt.user_id->flags.expired) continue; if (!un->pkt->pkt.user_id->flags.primary) continue; /* We want the textual primary user ID here */ if (un->pkt->pkt.user_id->attrib_data) continue; log_assert (mainpk); /* Since this is just informational, don't actually ask the user to update any trust information. (Note: we register the signature later.) Because print_good_bad_signature does not print a LF we need to compute the validity before calling that function. */ if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) valid = get_validity (c->ctrl, keyblock, mainpk, un->pkt->pkt.user_id, NULL, 0); else valid = 0; /* Not used. */ keyid_str[17] = 0; /* cut off the "[uncertain]" part */ print_good_bad_signature (statno, keyid_str, un, sig, rc); if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) log_printf (" [%s]\n",trust_value_to_string(valid)); else log_printf ("\n"); count++; } log_assert (mainpk); /* In case we did not found a valid textual userid above we print the first user id packet or a "[?]" instead along with the "Good|Expired|Bad signature" line. */ if (!count) { /* Try for an invalid textual userid */ for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype == PKT_USER_ID && !un->pkt->pkt.user_id->attrib_data) break; } /* Try for any userid at all */ if (!un) { for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype == PKT_USER_ID) break; } } if (opt.trust_model==TM_ALWAYS || !un) keyid_str[17] = 0; /* cut off the "[uncertain]" part */ print_good_bad_signature (statno, keyid_str, un, sig, rc); if (opt.trust_model != TM_ALWAYS && un) log_printf (" %s",_("[uncertain]") ); log_printf ("\n"); } /* If we have a good signature and already printed * the primary user ID, print all the other user IDs */ if (count && !rc && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY)) { char *p; for( un=keyblock; un; un = un->next) { if (un->pkt->pkttype != PKT_USER_ID) continue; if ((un->pkt->pkt.user_id->flags.revoked || un->pkt->pkt.user_id->flags.expired) && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS)) continue; /* Skip textual primary user ids which we printed above. */ if (un->pkt->pkt.user_id->flags.primary && !un->pkt->pkt.user_id->attrib_data ) continue; /* If this user id has attribute data, print that. */ if (un->pkt->pkt.user_id->attrib_data) { dump_attribs (un->pkt->pkt.user_id, mainpk); if (opt.verify_options&VERIFY_SHOW_PHOTOS) show_photos (c->ctrl, un->pkt->pkt.user_id->attribs, un->pkt->pkt.user_id->numattribs, mainpk ,un->pkt->pkt.user_id); } p = utf8_to_native (un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len, 0); log_info (_(" aka \"%s\""), p); xfree (p); if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) { const char *valid; if (un->pkt->pkt.user_id->flags.revoked) valid = _("revoked"); else if (un->pkt->pkt.user_id->flags.expired) valid = _("expired"); else /* Since this is just informational, don't actually ask the user to update any trust information. */ valid = (trust_value_to_string (get_validity (c->ctrl, keyblock, mainpk, un->pkt->pkt.user_id, NULL, 0))); log_printf (" [%s]\n",valid); } else log_printf ("\n"); } } /* For good signatures print notation data. */ if (!rc) { if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS)) show_policy_url (sig, 0, 1); else show_policy_url (sig, 0, 2); if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS)) show_keyserver_url (sig, 0, 1); else show_keyserver_url (sig, 0, 2); if ((opt.verify_options & VERIFY_SHOW_NOTATIONS)) show_notation (sig, 0, 1, (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0) + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0))); else show_notation (sig, 0, 2, 0); } /* For good signatures print the VALIDSIG status line. */ if (!rc && is_status_enabled () && pk) { char pkhex[MAX_FINGERPRINT_LEN*2+1]; char mainpkhex[MAX_FINGERPRINT_LEN*2+1]; hexfingerprint (pk, pkhex, sizeof pkhex); hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex); /* TODO: Replace the reserved '0' in the field below with bits for status flags (policy url, notation, etc.). */ write_status_printf (STATUS_VALIDSIG, "%s %s %lu %lu %d 0 %d %d %02X %s", pkhex, strtimestamp (sig->timestamp), (ulong)sig->timestamp, (ulong)sig->expiredate, sig->version, sig->pubkey_algo, sig->digest_algo, sig->sig_class, mainpkhex); } /* Print compliance warning for Good signatures. */ if (!rc && pk && !opt.quiet && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL)) { log_info (_("WARNING: This key is not suitable for signing" " in %s mode\n"), gnupg_compliance_option_string (opt.compliance)); } /* For good signatures compute and print the trust information. Note that in the Tofu trust model this may ask the user on how to resolve a conflict. */ if (!rc) { if ((opt.verify_options & VERIFY_PKA_LOOKUPS)) pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */ rc = check_signatures_trust (c->ctrl, sig); } /* Print extra information about the signature. */ if (sig->flags.expired) { log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate)); rc = GPG_ERR_GENERAL; /* Need a better error here? */ } else if (sig->expiredate) log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate)); if (opt.verbose) { char pkstrbuf[PUBKEY_STRING_SIZE]; if (pk) pubkey_string (pk, pkstrbuf, sizeof pkstrbuf); else *pkstrbuf = 0; log_info (_("%s signature, digest algorithm %s%s%s\n"), sig->sig_class==0x00?_("binary"): sig->sig_class==0x01?_("textmode"):_("unknown"), gcry_md_algo_name (sig->digest_algo), *pkstrbuf?_(", key algorithm "):"", pkstrbuf); } /* Print final warnings. */ if (!rc && !c->signed_data.used) { /* Signature is basically good but we test whether the deprecated command gpg --verify FILE.sig was used instead of gpg --verify FILE.sig FILE to verify a detached signature. If we figure out that a data file with a matching name exists, we print a warning. The problem is that the first form would also verify a standard signature. This behavior could be used to create a made up .sig file for a tarball by creating a standard signature from a valid detached signature packet (for example from a signed git tag). Then replace the sig file on the FTP server along with a changed tarball. Using the first form the verify command would correctly verify the signature but don't even consider the tarball. */ kbnode_t n; char *dfile; dfile = get_matching_datafile (c->sigfilename); if (dfile) { for (n = c->list; n; n = n->next) if (n->pkt->pkttype != PKT_SIGNATURE) break; if (n) { /* Not only signature packets in the tree thus this is not a detached signature. */ log_info (_("WARNING: not a detached signature; " "file '%s' was NOT verified!\n"), dfile); } xfree (dfile); } } /* Compute compliance with CO_DE_VS. */ if (pk && is_status_enabled () && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL) && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo)) write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS), NULL); free_public_key (pk); pk = NULL; release_kbnode( keyblock ); if (rc) g10_errors_seen = 1; if (opt.batch && rc) g10_exit (1); } else { write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s", (ulong)sig->keyid[0], (ulong)sig->keyid[1], sig->pubkey_algo, sig->digest_algo, sig->sig_class, (ulong)sig->timestamp, gpg_err_code (rc), issuer_fpr? issuer_fpr:"-"); if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY) { write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX", (ulong)sig->keyid[0], (ulong)sig->keyid[1]); } if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED) log_error (_("Can't check signature: %s\n"), gpg_strerror (rc)); } free_public_key (pk); release_kbnode (included_keyblock); xfree (issuer_fpr); return rc; } /* * Process the tree which starts at node */ static void proc_tree (CTX c, kbnode_t node) { kbnode_t n1; int rc; if (opt.list_packets || opt.list_only) return; /* We must skip our special plaintext marker packets here because they may be the root packet. These packets are only used in additional checks and skipping them here doesn't matter. */ while (node && node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK) { node = node->next; } if (!node) return; c->trustletter = ' '; if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { merge_keys_and_selfsig (c->ctrl, node); list_node (c, node); } else if (node->pkt->pkttype == PKT_SECRET_KEY) { merge_keys_and_selfsig (c->ctrl, node); list_node (c, node); } else if (node->pkt->pkttype == PKT_ONEPASS_SIG) { /* Check all signatures. */ if (!c->any.data) { int use_textmode = 0; free_md_filter_context (&c->mfx); /* Prepare to create all requested message digests. */ rc = gcry_md_open (&c->mfx.md, 0, 0); if (rc) goto hash_err; /* Fixme: why looking for the signature packet and not the one-pass packet? */ for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo); if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01) use_textmode = 1; /* Ask for file and hash it. */ if (c->sigs_only) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, NULL, c->signed_data.data_fd, use_textmode); else rc = hash_datafiles (c->mfx.md, NULL, c->signed_data.data_names, c->sigfilename, use_textmode); } else { rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2, iobuf_get_real_fname (c->iobuf), use_textmode); } hash_err: if (rc) { log_error ("can't hash datafile: %s\n", gpg_strerror (rc)); return; } } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) check_sig_and_print (c, n1); } else if (node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START) { /* Clear text signed message. */ if (!c->any.data) { log_error ("cleartext signature without data\n"); return; } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) check_sig_and_print (c, n1); } else if (node->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = node->pkt->pkt.signature; int multiple_ok = 1; n1 = find_next_kbnode (node, PKT_SIGNATURE); if (n1) { byte class = sig->sig_class; byte hash = sig->digest_algo; for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE))) { /* We can't currently handle multiple signatures of * different classes (we'd pretty much have to run a * different hash context for each), but if they are all * the same and it is detached signature, we make an * exception. Note that the old code also disallowed * multiple signatures if the digest algorithms are * different. We softened this restriction only for * detached signatures, to be on the safe side. */ if (n1->pkt->pkt.signature->sig_class != class || (c->any.data && n1->pkt->pkt.signature->digest_algo != hash)) { multiple_ok = 0; log_info (_("WARNING: multiple signatures detected. " "Only the first will be checked.\n")); break; } } } if (sig->sig_class != 0x00 && sig->sig_class != 0x01) { log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class); } else if (!c->any.data) { /* Detached signature */ free_md_filter_context (&c->mfx); rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0); if (rc) goto detached_hash_err; if (multiple_ok) { /* If we have and want to handle multiple signatures we * need to enable all hash algorithms for the context. */ for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); ) if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo)) gcry_md_enable (c->mfx.md, map_md_openpgp_to_gcry (n1->pkt->pkt.signature->digest_algo)); } if (RFC2440 || RFC4880) ; /* Strict RFC mode. */ else if (sig->digest_algo == DIGEST_ALGO_SHA1 && sig->pubkey_algo == PUBKEY_ALGO_DSA && sig->sig_class == 0x01) { /* Enable a workaround for a pgp5 bug when the detached * signature has been created in textmode. Note that we * do not implement this for multiple signatures with * different hash algorithms. */ rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0); if (rc) goto detached_hash_err; } /* Here we used to have another hack to work around a pgp * 2 bug: It worked by not using the textmode for detached * signatures; this would let the first signature check * (on md) fail but the second one (on md2), which adds an * extra CR would then have produced the "correct" hash. * This is very, very ugly hack but it may haved help in * some cases (and break others). * c->mfx.md2? 0 :(sig->sig_class == 0x01) */ if (DBG_HASHING) { gcry_md_debug (c->mfx.md, "verify"); if (c->mfx.md2) gcry_md_debug (c->mfx.md2, "verify2"); } if (c->sigs_only) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2, c->signed_data.data_fd, (sig->sig_class == 0x01)); else rc = hash_datafiles (c->mfx.md, c->mfx.md2, c->signed_data.data_names, c->sigfilename, (sig->sig_class == 0x01)); } else { rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2, iobuf_get_real_fname(c->iobuf), (sig->sig_class == 0x01)); } detached_hash_err: if (rc) { log_error ("can't hash datafile: %s\n", gpg_strerror (rc)); return; } } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } else if (!opt.quiet) log_info (_("old style (PGP 2.x) signature\n")); if (multiple_ok) { for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE))) check_sig_and_print (c, n1); } else check_sig_and_print (c, node); } else { dump_kbnode (c->list); log_error ("invalid root packet detected in proc_tree()\n"); dump_kbnode (node); } } diff --git a/g10/sign.c b/g10/sign.c index 6a90fe16e..18f6d20ea 100644 --- a/g10/sign.c +++ b/g10/sign.c @@ -1,1813 +1,1818 @@ /* sign.c - sign data * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2010, 2012 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 "gpg.h" #include "options.h" #include "packet.h" #include "../common/status.h" #include "../common/iobuf.h" #include "keydb.h" #include "../common/util.h" #include "main.h" #include "filter.h" #include "../common/ttyio.h" #include "trustdb.h" #include "../common/status.h" #include "../common/i18n.h" #include "pkglue.h" #include "../common/sysutils.h" #include "call-agent.h" #include "../common/mbox-util.h" #include "../common/compliance.h" #ifdef HAVE_DOSISH_SYSTEM #define LF "\r\n" #else #define LF "\n" #endif /* Bitflags to convey hints on what kind of signayire is created. */ #define SIGNHINT_KEYSIG 1 #define SIGNHINT_SELFSIG 2 /* Hack */ static int recipient_digest_algo=0; /**************** * Create notations and other stuff. It is assumed that the stings in * STRLIST are already checked to contain only printable data and have * a valid NAME=VALUE format. */ static void mk_notation_policy_etc (PKT_signature *sig, PKT_public_key *pk, PKT_public_key *pksk) { const char *string; char *p = NULL; strlist_t pu = NULL; struct notation *nd = NULL; struct expando_args args; log_assert (sig->version >= 4); memset (&args, 0, sizeof(args)); args.pk = pk; args.pksk = pksk; /* Notation data. */ if (IS_SIG(sig) && opt.sig_notations) nd = opt.sig_notations; else if (IS_CERT(sig) && opt.cert_notations) nd = opt.cert_notations; if (nd) { struct notation *item; for (item = nd; item; item = item->next) { item->altvalue = pct_expando (item->value,&args); if (!item->altvalue) log_error (_("WARNING: unable to %%-expand notation " "(too large). Using unexpanded.\n")); } keygen_add_notations (sig, nd); for (item = nd; item; item = item->next) { xfree (item->altvalue); item->altvalue = NULL; } } /* Set policy URL. */ if (IS_SIG(sig) && opt.sig_policy_url) pu = opt.sig_policy_url; else if (IS_CERT(sig) && opt.cert_policy_url) pu = opt.cert_policy_url; for (; pu; pu = pu->next) { string = pu->d; p = pct_expando (string, &args); if (!p) { log_error(_("WARNING: unable to %%-expand policy URL " "(too large). Using unexpanded.\n")); p = xstrdup(string); } build_sig_subpkt (sig, (SIGSUBPKT_POLICY | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)), p, strlen (p)); xfree (p); } /* Preferred keyserver URL. */ if (IS_SIG(sig) && opt.sig_keyserver_url) pu = opt.sig_keyserver_url; for (; pu; pu = pu->next) { string = pu->d; p = pct_expando (string, &args); if (!p) { log_error (_("WARNING: unable to %%-expand preferred keyserver URL" " (too large). Using unexpanded.\n")); p = xstrdup (string); } build_sig_subpkt (sig, (SIGSUBPKT_PREF_KS | ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0)), p, strlen (p)); xfree (p); } /* Set signer's user id. */ if (IS_SIG (sig) && !opt.flags.disable_signer_uid) { char *mbox; /* For now we use the uid which was used to locate the key. */ if (pksk->user_id && (mbox = mailbox_from_userid (pksk->user_id->name))) { if (DBG_LOOKUP) log_debug ("setting Signer's UID to '%s'\n", mbox); build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, mbox, strlen (mbox)); xfree (mbox); } else if (opt.sender_list) { /* If a list of --sender was given we scan that list and use * the first one matching a user id of the current key. */ /* FIXME: We need to get the list of user ids for the PKSK * packet. That requires either a function to look it up * again or we need to extend the key packet struct to link * to the primary key which in turn could link to the user * ids. Too much of a change right now. Let's take just * one from the supplied list and hope that the caller * passed a matching one. */ build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, opt.sender_list->d, strlen (opt.sender_list->d)); } } } /* * Put the Key Block subpakcet into SIG for key PKSK. Returns an * error code on failure. */ static gpg_error_t mk_sig_subpkt_key_block (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pksk) { gpg_error_t err; char *mbox; char *filterexp = NULL; int save_opt_armor = opt.armor; int save_opt_verbose = opt.verbose; char hexfpr[2*MAX_FINGERPRINT_LEN + 1]; void *data = NULL; size_t datalen; kbnode_t keyblock = NULL; push_export_filters (); opt.armor = 0; hexfingerprint (pksk, hexfpr, sizeof hexfpr); /* Get the user id so that we know which one to insert into the * key. */ if (pksk->user_id && (mbox = mailbox_from_userid (pksk->user_id->name))) { if (DBG_LOOKUP) log_debug ("including key with UID '%s' (specified)\n", mbox); filterexp = xasprintf ("keep-uid= -- mbox = %s", mbox); xfree (mbox); } else if (opt.sender_list) { /* If --sender was given we use the first one from that list. */ if (DBG_LOOKUP) log_debug ("including key with UID '%s' (--sender)\n", opt.sender_list->d); filterexp = xasprintf ("keep-uid= -- mbox = %s", opt.sender_list->d); } else /* Use the primary user id. */ { if (DBG_LOOKUP) log_debug ("including key with primary UID\n"); filterexp = xstrdup ("keep-uid= primary -t"); } if (DBG_LOOKUP) log_debug ("export filter expression: %s\n", filterexp); err = parse_and_set_export_filter (filterexp); if (err) goto leave; xfree (filterexp); filterexp = xasprintf ("drop-subkey= fpr <> %s && usage !~ e", hexfpr); if (DBG_LOOKUP) log_debug ("export filter expression: %s\n", filterexp); err = parse_and_set_export_filter (filterexp); if (err) goto leave; opt.verbose = 0; err = export_pubkey_buffer (ctrl, hexfpr, EXPORT_MINIMAL|EXPORT_CLEAN, "", 1, /* Prefix with the reserved byte. */ NULL, &keyblock, &data, &datalen); opt.verbose = save_opt_verbose; if (err) { log_error ("failed to get to be included key: %s\n", gpg_strerror (err)); goto leave; } build_sig_subpkt (sig, SIGSUBPKT_KEY_BLOCK, data, datalen); leave: xfree (data); release_kbnode (keyblock); xfree (filterexp); opt.armor = save_opt_armor; pop_export_filters (); return err; } /* * Helper to hash a user ID packet. */ static void hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid) { byte buf[5]; (void)sigversion; if (uid->attrib_data) { buf[0] = 0xd1; /* Indicates an attribute packet. */ buf[1] = uid->attrib_len >> 24; /* Always use 4 length bytes. */ buf[2] = uid->attrib_len >> 16; buf[3] = uid->attrib_len >> 8; buf[4] = uid->attrib_len; } else { buf[0] = 0xb4; /* Indicates a userid packet. */ buf[1] = uid->len >> 24; /* Always use 4 length bytes. */ buf[2] = uid->len >> 16; buf[3] = uid->len >> 8; buf[4] = uid->len; } gcry_md_write( md, buf, 5 ); if (uid->attrib_data) gcry_md_write (md, uid->attrib_data, uid->attrib_len ); else gcry_md_write (md, uid->name, uid->len ); } /* * Helper to hash some parts from the signature */ static void hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig) { byte buf[6]; size_t n; gcry_md_putc (md, sig->version); gcry_md_putc (md, sig->sig_class); gcry_md_putc (md, sig->pubkey_algo); gcry_md_putc (md, sig->digest_algo); if (sig->hashed) { n = sig->hashed->len; gcry_md_putc (md, (n >> 8) ); gcry_md_putc (md, n ); gcry_md_write (md, sig->hashed->data, n ); n += 6; } else { gcry_md_putc (md, 0); /* Always hash the length of the subpacket. */ gcry_md_putc (md, 0); n = 6; } /* Add some magic. */ buf[0] = sig->version; buf[1] = 0xff; buf[2] = n >> 24; /* (n is only 16 bit, so this is always 0) */ buf[3] = n >> 16; buf[4] = n >> 8; buf[5] = n; gcry_md_write (md, buf, 6); } /* Perform the sign operation. If CACHE_NONCE is given the agent is * advised to use that cached passphrase for the key. SIGNHINTS has * hints so that we can do some additional checks. */ static int do_sign (ctrl_t ctrl, PKT_public_key *pksk, PKT_signature *sig, gcry_md_hd_t md, int mdalgo, const char *cache_nonce, unsigned int signhints) { gpg_error_t err; byte *dp; char *hexgrip; if (pksk->timestamp > sig->timestamp ) { ulong d = pksk->timestamp - sig->timestamp; log_info (ngettext("key %s was created %lu second" " in the future (time warp or clock problem)\n", "key %s was created %lu seconds" " in the future (time warp or clock problem)\n", d), keystr_from_pk (pksk), d); if (!opt.ignore_time_conflict) return gpg_error (GPG_ERR_TIME_CONFLICT); } print_pubkey_algo_note (pksk->pubkey_algo); if (!mdalgo) mdalgo = gcry_md_get_algo (md); if ((signhints & SIGNHINT_KEYSIG) && !(signhints & SIGNHINT_SELFSIG) && mdalgo == GCRY_MD_SHA1 && !opt.flags.allow_weak_key_signatures) { /* We do not allow the creation of third-party key signatures * using SHA-1 because we also reject them when verifying. Note * that this will render dsa1024 keys unsuitable for such * keysigs and in turn the WoT. */ print_sha1_keysig_rejected_note (); err = gpg_error (GPG_ERR_DIGEST_ALGO); goto leave; } /* Check compliance. */ if (! gnupg_digest_is_allowed (opt.compliance, 1, mdalgo)) { log_error (_("digest algorithm '%s' may not be used in %s mode\n"), gcry_md_algo_name (mdalgo), gnupg_compliance_option_string (opt.compliance)); err = gpg_error (GPG_ERR_DIGEST_ALGO); goto leave; } if (! gnupg_pk_is_allowed (opt.compliance, PK_USE_SIGNING, pksk->pubkey_algo, 0, pksk->pkey, nbits_from_pk (pksk), NULL)) { log_error (_("key %s may not be used for signing in %s mode\n"), keystr_from_pk (pksk), gnupg_compliance_option_string (opt.compliance)); err = gpg_error (GPG_ERR_PUBKEY_ALGO); goto leave; } if (!gnupg_rng_is_compliant (opt.compliance)) { err = gpg_error (GPG_ERR_FORBIDDEN); log_error (_("%s is not compliant with %s mode\n"), "RNG", gnupg_compliance_option_string (opt.compliance)); write_status_error ("random-compliance", err); goto leave; } print_digest_algo_note (mdalgo); dp = gcry_md_read (md, mdalgo); sig->digest_algo = mdalgo; sig->digest_start[0] = dp[0]; sig->digest_start[1] = dp[1]; mpi_release (sig->data[0]); sig->data[0] = NULL; mpi_release (sig->data[1]); sig->data[1] = NULL; err = hexkeygrip_from_pk (pksk, &hexgrip); if (!err) { char *desc; gcry_sexp_t s_sigval; desc = gpg_format_keydesc (ctrl, pksk, FORMAT_KEYDESC_NORMAL, 1); err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc, pksk->keyid, pksk->main_keyid, pksk->pubkey_algo, dp, gcry_md_get_algo_dlen (mdalgo), mdalgo, &s_sigval); xfree (desc); if (err) ; else if (pksk->pubkey_algo == GCRY_PK_RSA || pksk->pubkey_algo == GCRY_PK_RSA_S) sig->data[0] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG); else if (openpgp_oid_is_ed25519 (pksk->pkey[0])) { sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_OPAQUE); sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_OPAQUE); } else { sig->data[0] = get_mpi_from_sexp (s_sigval, "r", GCRYMPI_FMT_USG); sig->data[1] = get_mpi_from_sexp (s_sigval, "s", GCRYMPI_FMT_USG); } gcry_sexp_release (s_sigval); } xfree (hexgrip); leave: if (err) - log_error (_("signing failed: %s\n"), gpg_strerror (err)); + { + log_error (_("signing failed: %s\n"), gpg_strerror (err)); + if (gpg_err_source (err) == GPG_ERR_SOURCE_SCD + && gpg_err_code (err) == GPG_ERR_INV_ID) + print_further_info ("a reason might be a card with replaced keys"); + } else { if (opt.verbose) { char *ustr = get_user_id_string_native (ctrl, sig->keyid); log_info (_("%s/%s signature from: \"%s\"\n"), openpgp_pk_algo_name (pksk->pubkey_algo), openpgp_md_algo_name (sig->digest_algo), ustr); xfree (ustr); } } return err; } static int complete_sig (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md, const char *cache_nonce, unsigned int signhints) { int rc; /* if (!(rc = check_secret_key (pksk, 0))) */ rc = do_sign (ctrl, pksk, sig, md, 0, cache_nonce, signhints); return rc; } /* Return true if the key seems to be on a version 1 OpenPGP card. This works by asking the agent and may fail if the card has not yet been used with the agent. */ static int openpgp_card_v1_p (PKT_public_key *pk) { gpg_error_t err; int result; /* Shortcut if we are not using RSA: The v1 cards only support RSA thus there is no point in looking any further. */ if (!is_RSA (pk->pubkey_algo)) return 0; if (!pk->flags.serialno_valid) { char *hexgrip; err = hexkeygrip_from_pk (pk, &hexgrip); if (err) { log_error ("error computing a keygrip: %s\n", gpg_strerror (err)); return 0; /* Ooops. */ } xfree (pk->serialno); agent_get_keyinfo (NULL, hexgrip, &pk->serialno, NULL); xfree (hexgrip); pk->flags.serialno_valid = 1; } if (!pk->serialno) result = 0; /* Error from a past agent_get_keyinfo or no card. */ else { /* The version number of the card is included in the serialno. */ result = !strncmp (pk->serialno, "D2760001240101", 14); } return result; } /* Get a matching hash algorithm for DSA and ECDSA. */ static int match_dsa_hash (unsigned int qbytes) { if (qbytes <= 20) return DIGEST_ALGO_SHA1; if (qbytes <= 28) return DIGEST_ALGO_SHA224; if (qbytes <= 32) return DIGEST_ALGO_SHA256; if (qbytes <= 48) return DIGEST_ALGO_SHA384; if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */ return DIGEST_ALGO_SHA512; return DEFAULT_DIGEST_ALGO; /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong answer we have if a digest larger than 512 bits is requested. */ } /* First try --digest-algo. If that isn't set, see if the recipient has a preferred algorithm (which is also filtered through --personal-digest-prefs). If we're making a signature without a particular recipient (i.e. signing, rather than signing+encrypting) then take the first algorithm in --personal-digest-prefs that is usable for the pubkey algorithm. If --personal-digest-prefs isn't set, then take the OpenPGP default (i.e. SHA-1). Note that Ed25519+EdDSA takes an input of arbitrary length and thus we don't enforce any particular algorithm like we do for standard ECDSA. However, we use SHA256 as the default algorithm. Possible improvement: Use the highest-ranked usable algorithm from the signing key prefs either before or after using the personal list? */ static int hash_for (PKT_public_key *pk) { if (opt.def_digest_algo) { return opt.def_digest_algo; } else if (recipient_digest_algo && !is_weak_digest (recipient_digest_algo)) { return recipient_digest_algo; } else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA && openpgp_oid_is_ed25519 (pk->pkey[0])) { if (opt.personal_digest_prefs) return opt.personal_digest_prefs[0].value; else return DIGEST_ALGO_SHA256; } else if (pk->pubkey_algo == PUBKEY_ALGO_DSA || pk->pubkey_algo == PUBKEY_ALGO_ECDSA) { unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]); if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA) qbytes = ecdsa_qbits_from_Q (qbytes); qbytes = qbytes/8; /* It's a DSA key, so find a hash that is the same size as q or larger. If q is 160, assume it is an old DSA key and use a 160-bit hash unless --enable-dsa2 is set, in which case act like a new DSA key that just happens to have a 160-bit q (i.e. allow truncation). If q is not 160, by definition it must be a new DSA key. We ignore the personal_digest_prefs for ECDSA because they should always macth the curve and truncated hashes are not useful either. Even worse, smartcards may reject non matching hash lengths for curves (e.g. using SHA-512 with brainpooolP385r1 on a Yubikey). */ if (pk->pubkey_algo == PUBKEY_ALGO_DSA && opt.personal_digest_prefs) { prefitem_t *prefs; if (qbytes != 20 || opt.flags.dsa2) { for (prefs=opt.personal_digest_prefs; prefs->type; prefs++) if (gcry_md_get_algo_dlen (prefs->value) >= qbytes) return prefs->value; } else { for (prefs=opt.personal_digest_prefs; prefs->type; prefs++) if (gcry_md_get_algo_dlen (prefs->value) == qbytes) return prefs->value; } } return match_dsa_hash(qbytes); } else if (openpgp_card_v1_p (pk)) { /* The sk lives on a smartcard, and old smartcards only handle SHA-1 and RIPEMD/160. Newer smartcards (v2.0) don't have this restriction anymore. Fortunately the serial number encodes the version of the card and thus we know that this key is on a v1 card. */ if(opt.personal_digest_prefs) { prefitem_t *prefs; for (prefs=opt.personal_digest_prefs;prefs->type;prefs++) if (prefs->value==DIGEST_ALGO_SHA1 || prefs->value==DIGEST_ALGO_RMD160) return prefs->value; } return DIGEST_ALGO_SHA1; } else if (opt.personal_digest_prefs) { /* It's not DSA, so we can use whatever the first hash algorithm is in the pref list */ return opt.personal_digest_prefs[0].value; } else return DEFAULT_DIGEST_ALGO; } static void print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what) { byte array[MAX_FINGERPRINT_LEN]; char buf[100+MAX_FINGERPRINT_LEN*2]; size_t n; snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ", what, sig->pubkey_algo, sig->digest_algo, sig->sig_class, (ulong)sig->timestamp ); fingerprint_from_pk (pk, array, &n); bin2hex (array, n, buf + strlen (buf)); write_status_text( STATUS_SIG_CREATED, buf ); } /* * Loop over the secret certificates in SK_LIST and build the one pass * signature packets. OpenPGP says that the data should be bracket by * the onepass-sig and signature-packet; so we build these onepass * packet here in reverse order */ static int write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass ) { int skcount; SK_LIST sk_rover; for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next) skcount++; for (; skcount; skcount--) { PKT_public_key *pk; PKT_onepass_sig *ops; PACKET pkt; int i, rc; for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { if (++i == skcount) break; } pk = sk_rover->pk; ops = xmalloc_clear (sizeof *ops); ops->sig_class = sigclass; ops->digest_algo = hash_for (pk); ops->pubkey_algo = pk->pubkey_algo; keyid_from_pk (pk, ops->keyid); ops->last = (skcount == 1); init_packet(&pkt); pkt.pkttype = PKT_ONEPASS_SIG; pkt.pkt.onepass_sig = ops; rc = build_packet (out, &pkt); free_packet (&pkt, NULL); if (rc) { log_error ("build onepass_sig packet failed: %s\n", gpg_strerror (rc)); return rc; } } return 0; } /* * Helper to write the plaintext (literal data) packet */ static int write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode) { PKT_plaintext *pt = NULL; u32 filesize; int rc = 0; if (!opt.no_literal) pt=setup_plaintext_name(fname,inp); /* try to calculate the length of the data */ if ( !iobuf_is_pipe_filename (fname) && *fname ) { off_t tmpsize; int overflow; if( !(tmpsize = iobuf_get_filelength(inp, &overflow)) && !overflow && opt.verbose) log_info (_("WARNING: '%s' is an empty file\n"), fname); /* We can't encode the length of very large files because OpenPGP uses only 32 bit for file sizes. So if the size of a file is larger than 2^32 minus some bytes for packet headers, we switch to partial length encoding. */ if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) ) filesize = tmpsize; else filesize = 0; /* Because the text_filter modifies the length of the * data, it is not possible to know the used length * without a double read of the file - to avoid that * we simple use partial length packets. */ if ( ptmode == 't' || ptmode == 'u' || ptmode == 'm') filesize = 0; } else filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */ if (!opt.no_literal) { PACKET pkt; /* Note that PT has been initialized above in no_literal mode. */ pt->timestamp = make_timestamp (); pt->mode = ptmode; pt->len = filesize; pt->new_ctb = !pt->len; pt->buf = inp; init_packet(&pkt); pkt.pkttype = PKT_PLAINTEXT; pkt.pkt.plaintext = pt; /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/ if( (rc = build_packet (out, &pkt)) ) log_error ("build_packet(PLAINTEXT) failed: %s\n", gpg_strerror (rc) ); pt->buf = NULL; free_packet (&pkt, NULL); } else { byte copy_buffer[4096]; int bytes_copied; while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1) if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) { log_error ("copying input to output failed: %s\n", gpg_strerror (rc)); break; } wipememory(copy_buffer,4096); /* burn buffer */ } /* fixme: it seems that we never freed pt/pkt */ return rc; } /* * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized * hash which will not be changes here. */ static int write_signature_packets (ctrl_t ctrl, SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash, int sigclass, u32 timestamp, u32 duration, int status_letter, const char *cache_nonce) { SK_LIST sk_rover; /* Loop over the certificates with secret keys. */ for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) { PKT_public_key *pk; PKT_signature *sig; gcry_md_hd_t md; gpg_error_t err; pk = sk_rover->pk; /* Build the signature packet. */ sig = xtrycalloc (1, sizeof *sig); if (!sig) return gpg_error_from_syserror (); if (duration || opt.sig_policy_url || opt.sig_notations || opt.sig_keyserver_url) sig->version = 4; else sig->version = pk->version; keyid_from_pk (pk, sig->keyid); sig->digest_algo = hash_for (pk); sig->pubkey_algo = pk->pubkey_algo; if (timestamp) sig->timestamp = timestamp; else sig->timestamp = make_timestamp(); if (duration) sig->expiredate = sig->timestamp + duration; sig->sig_class = sigclass; if (gcry_md_copy (&md, hash)) BUG (); if (sig->version >= 4) { build_sig_subpkt_from_sig (sig, pk); mk_notation_policy_etc (sig, NULL, pk); if (opt.flags.include_key_block && IS_SIG (sig)) err = mk_sig_subpkt_key_block (ctrl, sig, pk); else err = 0; } hash_sigversion_to_magic (md, sig); gcry_md_final (md); if (!err) err = do_sign (ctrl, pk, sig, md, hash_for (pk), cache_nonce, 0); gcry_md_close (md); if (!err) { /* Write the packet. */ PACKET pkt; init_packet (&pkt); pkt.pkttype = PKT_SIGNATURE; pkt.pkt.signature = sig; err = build_packet (out, &pkt); if (!err && is_status_enabled()) print_status_sig_created (pk, sig, status_letter); free_packet (&pkt, NULL); if (err) log_error ("build signature packet failed: %s\n", gpg_strerror (err)); } else free_seckey_enc (sig); if (err) return err; } return 0; } /**************** * Sign the files whose names are in FILENAME. * If DETACHED has the value true, * make a detached signature. If FILENAMES->d is NULL read from stdin * and ignore the detached mode. Sign the file with all secret keys * which can be taken from LOCUSR, if this is NULL, use the default one * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the * signed data for these users. If ENCRYPTFLAG is 2 symmetric encryption * is also used. * If OUTFILE is not NULL; this file is used for output and the function * does not ask for overwrite permission; output is then always * uncompressed, non-armored and in binary mode. */ int sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr, int encryptflag, strlist_t remusr, const char *outfile ) { const char *fname; armor_filter_context_t *afx; compress_filter_context_t zfx; md_filter_context_t mfx; text_filter_context_t tfx; progress_filter_context_t *pfx; encrypt_filter_context_t efx; IOBUF inp = NULL, out = NULL; PACKET pkt; int rc = 0; PK_LIST pk_list = NULL; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; int multifile = 0; u32 duration=0; pfx = new_progress_context (); afx = new_armor_context (); memset( &zfx, 0, sizeof zfx); memset( &mfx, 0, sizeof mfx); memset( &efx, 0, sizeof efx); efx.ctrl = ctrl; init_packet( &pkt ); if( filenames ) { fname = filenames->d; multifile = !!filenames->next; } else fname = NULL; if( fname && filenames->next && (!detached || encryptflag) ) log_bug("multiple files can only be detached signed"); if(encryptflag==2 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek))) goto leave; if (opt.ask_sig_expire && !opt.batch) duration = ask_expire_interval(1,opt.def_sig_expire); else duration = parse_expire_string(opt.def_sig_expire); /* Note: In the old non-agent version the following call used to unprotect the secret key. This is now done on demand by the agent. */ if( (rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) ) goto leave; if (encryptflag && (rc=build_pk_list (ctrl, remusr, &pk_list))) goto leave; /* prepare iobufs */ if( multifile ) /* have list of filenames */ inp = NULL; /* we do it later */ else { inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; gpg_err_set_errno (EPERM); } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); } if( outfile ) { if (is_secured_filename ( outfile )) { out = NULL; gpg_err_set_errno (EPERM); } else out = iobuf_create (outfile, 0); if( !out ) { rc = gpg_error_from_syserror (); log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) ); goto leave; } else if( opt.verbose ) log_info(_("writing to '%s'\n"), outfile ); } else if( (rc = open_outfile (-1, fname, opt.armor? 1: detached? 2:0, 0, &out))) goto leave; /* prepare to calculate the MD over the input */ if( opt.textmode && !outfile && !multifile ) { memset( &tfx, 0, sizeof tfx); iobuf_push_filter( inp, text_filter, &tfx ); } if ( gcry_md_open (&mfx.md, 0, 0) ) BUG (); if (DBG_HASHING) gcry_md_debug (mfx.md, "sign"); /* If we're encrypting and signing, it is reasonable to pick the hash algorithm to use out of the recipient key prefs. This is best effort only, as in a DSA2 and smartcard world there are cases where we cannot please everyone with a single hash (DSA2 wants >160 and smartcards want =160). In the future this could be more complex with different hashes for each sk, but the current design requires a single hash for all SKs. */ if(pk_list) { if(opt.def_digest_algo) { if(!opt.expert && select_algo_from_prefs(pk_list,PREFTYPE_HASH, opt.def_digest_algo, NULL)!=opt.def_digest_algo) log_info(_("WARNING: forcing digest algorithm %s (%d)" " violates recipient preferences\n"), gcry_md_algo_name (opt.def_digest_algo), opt.def_digest_algo ); } else { int algo; int conflict = 0; struct pref_hint hint = { 0 }; /* Of course, if the recipient asks for something unreasonable (like the wrong hash for a DSA key) then don't do it. Check all sk's - if any are DSA or live on a smartcard, then the hash has restrictions and we may not be able to give the recipient what they want. For DSA, pass a hint for the largest q we have. Note that this means that a q>160 key will override a q=160 key and force the use of truncation for the q=160 key. The alternative would be to ignore the recipient prefs completely and get a different hash for each DSA key in hash_for(). The override behavior here is more or less reasonable as it is under the control of the user which keys they sign with for a given message and the fact that the message with multiple signatures won't be usable on an implementation that doesn't understand DSA2 anyway. */ for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA) { int temp_hashlen = (gcry_mpi_get_nbits (sk_rover->pk->pkey[1])); if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA) { temp_hashlen = ecdsa_qbits_from_Q (temp_hashlen); if (!temp_hashlen) conflict = 1; /* Better don't use the prefs. */ temp_hashlen = (temp_hashlen+7)/8; /* Fixup for that funny nistp521 (yes, 521) * were we need to use a 512 bit hash algo. */ if (temp_hashlen == 66) temp_hashlen = 64; } else temp_hashlen = (temp_hashlen+7)/8; /* Pick a hash that is large enough for our largest q or matches our Q but if tehreare several of them we run into a conflict and don't use the preferences. */ if (hint.digest_length < temp_hashlen) { if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA) { if (hint.exact) conflict = 1; hint.exact = 1; } hint.digest_length = temp_hashlen; } } } if (!conflict && (algo = select_algo_from_prefs (pk_list,PREFTYPE_HASH, -1,&hint)) > 0) { /* Note that we later check that the algo is not weak. */ recipient_digest_algo = algo; } } } for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) gcry_md_enable (mfx.md, hash_for (sk_rover->pk)); if( !multifile ) iobuf_push_filter( inp, md_filter, &mfx ); if( detached && !encryptflag) afx->what = 2; if( opt.armor && !outfile ) push_armor_filter (afx, out); if( encryptflag ) { efx.pk_list = pk_list; /* fixme: set efx.cfx.datalen if known */ iobuf_push_filter( out, encrypt_filter, &efx ); } if (opt.compress_algo && !outfile && !detached) { int compr_algo=opt.compress_algo; /* If not forced by user */ if(compr_algo==-1) { /* If we're not encrypting, then select_algo_from_prefs will fail and we'll end up with the default. If we are encrypting, select_algo_from_prefs cannot fail since there is an assumed preference for uncompressed data. Still, if it did fail, we'll also end up with the default. */ if((compr_algo= select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1) compr_algo=default_compress_algo(); } else if(!opt.expert && pk_list && select_algo_from_prefs(pk_list,PREFTYPE_ZIP, compr_algo,NULL)!=compr_algo) log_info(_("WARNING: forcing compression algorithm %s (%d)" " violates recipient preferences\n"), compress_algo_to_string(compr_algo),compr_algo); /* algo 0 means no compression */ if( compr_algo ) push_compress_filter(out,&zfx,compr_algo); } /* Write the one-pass signature packets if needed */ if (!detached) { rc = write_onepass_sig_packets (sk_list, out, opt.textmode && !outfile ? 0x01:0x00); if (rc) goto leave; } write_status_begin_signing (mfx.md); /* Setup the inner packet. */ if( detached ) { if( multifile ) { strlist_t sl; if( opt.verbose ) log_info(_("signing:") ); /* must walk reverse trough this list */ for( sl = strlist_last(filenames); sl; sl = strlist_prev( filenames, sl ) ) { inp = iobuf_open(sl->d); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; gpg_err_set_errno (EPERM); } if( !inp ) { rc = gpg_error_from_syserror (); log_error(_("can't open '%s': %s\n"), sl->d,strerror(errno)); goto leave; } handle_progress (pfx, inp, sl->d); if( opt.verbose ) log_printf (" '%s'", sl->d ); if(opt.textmode) { memset( &tfx, 0, sizeof tfx); iobuf_push_filter( inp, text_filter, &tfx ); } iobuf_push_filter( inp, md_filter, &mfx ); while( iobuf_get(inp) != -1 ) ; iobuf_close(inp); inp = NULL; } if( opt.verbose ) log_printf ("\n"); } else { /* read, so that the filter can calculate the digest */ while( iobuf_get(inp) != -1 ) ; } } else { rc = write_plaintext_packet (out, inp, fname, opt.textmode && !outfile ? (opt.mimemode? 'm':'t'):'b'); } /* catch errors from above */ if (rc) goto leave; /* write the signatures */ rc = write_signature_packets (ctrl, sk_list, out, mfx.md, opt.textmode && !outfile? 0x01 : 0x00, 0, duration, detached ? 'D':'S', NULL); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else { iobuf_close(out); if (encryptflag) write_status( STATUS_END_ENCRYPTION ); } iobuf_close(inp); gcry_md_close ( mfx.md ); release_sk_list( sk_list ); release_pk_list( pk_list ); recipient_digest_algo=0; release_progress_context (pfx); release_armor_context (afx); return rc; } /**************** * make a clear signature. note that opt.armor is not needed */ int clearsign_file (ctrl_t ctrl, const char *fname, strlist_t locusr, const char *outfile ) { armor_filter_context_t *afx; progress_filter_context_t *pfx; gcry_md_hd_t textmd = NULL; IOBUF inp = NULL, out = NULL; PACKET pkt; int rc = 0; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; u32 duration=0; pfx = new_progress_context (); afx = new_armor_context (); init_packet( &pkt ); if (opt.ask_sig_expire && !opt.batch) duration = ask_expire_interval (1,opt.def_sig_expire); else duration = parse_expire_string (opt.def_sig_expire); /* Note: In the old non-agent version the following call used to unprotect the secret key. This is now done on demand by the agent. */ if( (rc=build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG )) ) goto leave; /* prepare iobufs */ inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; gpg_err_set_errno (EPERM); } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); if( outfile ) { if (is_secured_filename (outfile) ) { outfile = NULL; gpg_err_set_errno (EPERM); } else out = iobuf_create (outfile, 0); if( !out ) { rc = gpg_error_from_syserror (); log_error(_("can't create '%s': %s\n"), outfile, strerror(errno) ); goto leave; } else if( opt.verbose ) log_info(_("writing to '%s'\n"), outfile ); } else if ((rc = open_outfile (-1, fname, 1, 0, &out))) goto leave; iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF ); { const char *s; int any = 0; byte hashs_seen[256]; memset( hashs_seen, 0, sizeof hashs_seen ); iobuf_writestr(out, "Hash: " ); for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { int i = hash_for (sk_rover->pk); if( !hashs_seen[ i & 0xff ] ) { s = gcry_md_algo_name ( i ); if( s ) { hashs_seen[ i & 0xff ] = 1; if( any ) iobuf_put(out, ',' ); iobuf_writestr(out, s ); any = 1; } } } log_assert(any); iobuf_writestr(out, LF ); } if( opt.not_dash_escaped ) iobuf_writestr( out, "NotDashEscaped: You need "GPG_NAME " to verify this message" LF ); iobuf_writestr(out, LF ); if ( gcry_md_open (&textmd, 0, 0) ) BUG (); for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) gcry_md_enable (textmd, hash_for(sk_rover->pk)); if ( DBG_HASHING ) gcry_md_debug ( textmd, "clearsign" ); copy_clearsig_text (out, inp, textmd, !opt.not_dash_escaped, opt.escape_from); /* fixme: check for read errors */ /* now write the armor */ afx->what = 2; push_armor_filter (afx, out); /* Write the signatures. */ rc = write_signature_packets (ctrl, sk_list, out, textmd, 0x01, 0, duration, 'C', NULL); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else iobuf_close(out); iobuf_close(inp); gcry_md_close ( textmd ); release_sk_list( sk_list ); release_progress_context (pfx); release_armor_context (afx); return rc; } /* * Sign and conventionally encrypt the given file. * FIXME: Far too much code is duplicated - revamp the whole file. */ int sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr) { armor_filter_context_t *afx; progress_filter_context_t *pfx; compress_filter_context_t zfx; md_filter_context_t mfx; text_filter_context_t tfx; cipher_filter_context_t cfx; IOBUF inp = NULL, out = NULL; PACKET pkt; STRING2KEY *s2k = NULL; int rc = 0; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; int algo; u32 duration=0; int canceled; pfx = new_progress_context (); afx = new_armor_context (); memset( &zfx, 0, sizeof zfx); memset( &mfx, 0, sizeof mfx); memset( &tfx, 0, sizeof tfx); memset( &cfx, 0, sizeof cfx); init_packet( &pkt ); if (opt.ask_sig_expire && !opt.batch) duration = ask_expire_interval (1, opt.def_sig_expire); else duration = parse_expire_string (opt.def_sig_expire); /* Note: In the old non-agent version the following call used to unprotect the secret key. This is now done on demand by the agent. */ rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_SIG); if (rc) goto leave; /* prepare iobufs */ inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; gpg_err_set_errno (EPERM); } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); /* prepare key */ s2k = xmalloc_clear( sizeof *s2k ); s2k->mode = opt.s2k_mode; s2k->hash_algo = S2K_DIGEST_ALGO; algo = default_cipher_algo(); if (!opt.quiet || !opt.batch) log_info (_("%s encryption will be used\n"), openpgp_cipher_algo_name (algo) ); cfx.dek = passphrase_to_dek (algo, s2k, 1, 1, NULL, &canceled); if (!cfx.dek || !cfx.dek->keylen) { rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE); log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) ); goto leave; } cfx.dek->use_mdc = use_mdc (NULL, cfx.dek->algo); /* now create the outfile */ rc = open_outfile (-1, fname, opt.armor? 1:0, 0, &out); if (rc) goto leave; /* prepare to calculate the MD over the input */ if (opt.textmode) iobuf_push_filter (inp, text_filter, &tfx); if ( gcry_md_open (&mfx.md, 0, 0) ) BUG (); if ( DBG_HASHING ) gcry_md_debug (mfx.md, "symc-sign"); for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) gcry_md_enable (mfx.md, hash_for (sk_rover->pk)); iobuf_push_filter (inp, md_filter, &mfx); /* Push armor output filter */ if (opt.armor) push_armor_filter (afx, out); /* Write the symmetric key packet */ /*(current filters: armor)*/ { PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc ); enc->version = 4; enc->cipher_algo = cfx.dek->algo; enc->s2k = *s2k; pkt.pkttype = PKT_SYMKEY_ENC; pkt.pkt.symkey_enc = enc; if( (rc = build_packet( out, &pkt )) ) log_error("build symkey packet failed: %s\n", gpg_strerror (rc) ); xfree(enc); } /* Push the encryption filter */ iobuf_push_filter( out, cipher_filter, &cfx ); /* Push the compress filter */ if (default_compress_algo()) { if (cfx.dek && cfx.dek->use_mdc) zfx.new_ctb = 1; push_compress_filter (out, &zfx,default_compress_algo() ); } /* Write the one-pass signature packets */ /*(current filters: zip - encrypt - armor)*/ rc = write_onepass_sig_packets (sk_list, out, opt.textmode? 0x01:0x00); if (rc) goto leave; write_status_begin_signing (mfx.md); /* Pipe data through all filters; i.e. write the signed stuff */ /*(current filters: zip - encrypt - armor)*/ rc = write_plaintext_packet (out, inp, fname, opt.textmode ? (opt.mimemode?'m':'t'):'b'); if (rc) goto leave; /* Write the signatures */ /*(current filters: zip - encrypt - armor)*/ rc = write_signature_packets (ctrl, sk_list, out, mfx.md, opt.textmode? 0x01 : 0x00, 0, duration, 'S', NULL); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else { iobuf_close(out); write_status( STATUS_END_ENCRYPTION ); } iobuf_close(inp); release_sk_list( sk_list ); gcry_md_close( mfx.md ); xfree(cfx.dek); xfree(s2k); release_progress_context (pfx); release_armor_context (afx); return rc; } /**************** * Create a v4 signature in *RET_SIG. * * PK is the primary key to sign (required for all sigs) * UID is the user id to sign (required for 0x10..0x13, 0x30) * SUBPK is subkey to sign (required for 0x18, 0x19, 0x28) * * PKSK is the signing key * * SIGCLASS is the type of signature to create. * * DIGEST_ALGO is the digest algorithm. If it is 0 the function * selects an appropriate one. * * TIMESTAMP is the timestamp to use for the signature. 0 means "now" * * DURATION is the amount of time (in seconds) until the signature * expires. * * This function creates the following subpackets: issuer, created, * and expire (if duration is not 0). Additional subpackets can be * added using MKSUBPKT, which is called after these subpackets are * added and before the signature is generated. OPAQUE is passed to * MKSUBPKT. */ int make_keysig_packet (ctrl_t ctrl, PKT_signature **ret_sig, PKT_public_key *pk, PKT_user_id *uid, PKT_public_key *subpk, PKT_public_key *pksk, int sigclass, int digest_algo, u32 timestamp, u32 duration, int (*mksubpkt)(PKT_signature *, void *), void *opaque, const char *cache_nonce) { PKT_signature *sig; int rc=0; int sigversion; gcry_md_hd_t md; u32 pk_keyid[2], pksk_keyid[2]; unsigned int signhints; log_assert ((sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x30 || sigclass == 0x28 ); sigversion = 4; if (sigversion < pksk->version) sigversion = pksk->version; if( !digest_algo ) { /* Basically, this means use SHA1 always unless the user specified something (use whatever they said), or it's DSA (use the best match). They still can't pick an inappropriate hash for DSA or the signature will fail. Note that this still allows the caller of make_keysig_packet to override the user setting if it must. */ if(opt.cert_digest_algo) digest_algo=opt.cert_digest_algo; else if(pksk->pubkey_algo == PUBKEY_ALGO_DSA) digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8); else if (pksk->pubkey_algo == PUBKEY_ALGO_ECDSA || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA) { if (openpgp_oid_is_ed25519 (pksk->pkey[0])) digest_algo = DIGEST_ALGO_SHA256; else digest_algo = match_dsa_hash (ecdsa_qbits_from_Q (gcry_mpi_get_nbits (pksk->pkey[1]))/8); } else digest_algo = DEFAULT_DIGEST_ALGO; } signhints = SIGNHINT_KEYSIG; keyid_from_pk (pk, pk_keyid); keyid_from_pk (pksk, pksk_keyid); if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1]) signhints |= SIGNHINT_SELFSIG; if ( gcry_md_open (&md, digest_algo, 0 ) ) BUG (); /* Hash the public key certificate. */ hash_public_key( md, pk ); if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 ) { /* hash the subkey binding/backsig/revocation */ hash_public_key( md, subpk ); } else if( sigclass != 0x1F && sigclass != 0x20 ) { /* hash the user id */ hash_uid (md, sigversion, uid); } /* and make the signature packet */ sig = xmalloc_clear( sizeof *sig ); sig->version = sigversion; sig->flags.exportable=1; sig->flags.revocable=1; keyid_from_pk (pksk, sig->keyid); sig->pubkey_algo = pksk->pubkey_algo; sig->digest_algo = digest_algo; if(timestamp) sig->timestamp=timestamp; else sig->timestamp=make_timestamp(); if(duration) sig->expiredate=sig->timestamp+duration; sig->sig_class = sigclass; build_sig_subpkt_from_sig (sig, pksk); mk_notation_policy_etc (sig, pk, pksk); /* Crucial that the call to mksubpkt comes LAST before the calls to finalize the sig as that makes it possible for the mksubpkt function to get a reliable pointer to the subpacket area. */ if (mksubpkt) rc = (*mksubpkt)( sig, opaque ); if( !rc ) { hash_sigversion_to_magic (md, sig); gcry_md_final (md); rc = complete_sig (ctrl, sig, pksk, md, cache_nonce, signhints); } gcry_md_close (md); if( rc ) free_seckey_enc( sig ); else *ret_sig = sig; return rc; } /**************** * Create a new signature packet based on an existing one. * Only user ID signatures are supported for now. * PK is the public key to work on. * PKSK is the key used to make the signature. * * TODO: Merge this with make_keysig_packet. */ gpg_error_t update_keysig_packet (ctrl_t ctrl, PKT_signature **ret_sig, PKT_signature *orig_sig, PKT_public_key *pk, PKT_user_id *uid, PKT_public_key *subpk, PKT_public_key *pksk, int (*mksubpkt)(PKT_signature *, void *), void *opaque) { PKT_signature *sig; gpg_error_t rc = 0; int digest_algo; gcry_md_hd_t md; u32 pk_keyid[2], pksk_keyid[2]; unsigned int signhints; if ((!orig_sig || !pk || !pksk) || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid) || (orig_sig->sig_class == 0x18 && !subpk)) return GPG_ERR_GENERAL; if ( opt.cert_digest_algo ) digest_algo = opt.cert_digest_algo; else if (pksk->pubkey_algo == PUBKEY_ALGO_DSA || pksk->pubkey_algo == PUBKEY_ALGO_ECDSA || pksk->pubkey_algo == PUBKEY_ALGO_EDDSA) digest_algo = orig_sig->digest_algo; else if (orig_sig->digest_algo == DIGEST_ALGO_SHA1 || orig_sig->digest_algo == DIGEST_ALGO_RMD160) digest_algo = DEFAULT_DIGEST_ALGO; else digest_algo = orig_sig->digest_algo; signhints = SIGNHINT_KEYSIG; keyid_from_pk (pk, pk_keyid); keyid_from_pk (pksk, pksk_keyid); if (pk_keyid[0] == pksk_keyid[0] && pk_keyid[1] == pksk_keyid[1]) signhints |= SIGNHINT_SELFSIG; if ( gcry_md_open (&md, digest_algo, 0 ) ) BUG (); /* Hash the public key certificate and the user id. */ hash_public_key( md, pk ); if( orig_sig->sig_class == 0x18 ) hash_public_key( md, subpk ); else hash_uid (md, orig_sig->version, uid); /* create a new signature packet */ sig = copy_signature (NULL, orig_sig); sig->digest_algo=digest_algo; /* We need to create a new timestamp so that new sig expiration calculations are done correctly... */ sig->timestamp=make_timestamp(); /* ... but we won't make a timestamp earlier than the existing one. */ { int tmout = 0; while(sig->timestamp<=orig_sig->timestamp) { if (++tmout > 5 && !opt.ignore_time_conflict) { rc = gpg_error (GPG_ERR_TIME_CONFLICT); goto leave; } gnupg_sleep (1); sig->timestamp=make_timestamp(); } } /* Note that already expired sigs will remain expired (with a duration of 1) since build-packet.c:build_sig_subpkt_from_sig detects this case. */ /* Put the updated timestamp into the sig. Note that this will automagically lower any sig expiration dates to correctly correspond to the differences in the timestamps (i.e. the duration will shrink). */ build_sig_subpkt_from_sig (sig, pksk); if (mksubpkt) rc = (*mksubpkt)(sig, opaque); if (!rc) { hash_sigversion_to_magic (md, sig); gcry_md_final (md); rc = complete_sig (ctrl, sig, pksk, md, NULL, signhints); } leave: gcry_md_close (md); if( rc ) free_seckey_enc (sig); else *ret_sig = sig; return rc; }