diff --git a/agent/agent.h b/agent/agent.h index 49cc2fd98..f7e96fcff 100644 --- a/agent/agent.h +++ b/agent/agent.h @@ -1,640 +1,641 @@ /* 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 vave 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; int client_uid; /* The current pinentry mode. */ pinentry_mode_t pinentry_mode; /* The TTL used for the --preset option of certain commands. */ int cache_ttl_opt_preset; /* Information on the currently used digest (for signing commands). */ struct { 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 and data matches. */ CACHE_MODE_NORMAL, /* Normal cache (gpg-agent). */ CACHE_MODE_USER, /* GET_PASSPHRASE related cache. */ CACHE_MODE_SSH, /* SSH related cache. */ CACHE_MODE_NONCE, /* This is a non-predictable nonce. */ CACHE_MODE_PIN, /* PINs stored/retrieved by scdaemon. */ CACHE_MODE_DATA /* Arbitrary data. */ } cache_mode_t; /* The TTL is seconds used for adding a new nonce mode cache item. */ #define CACHE_TTL_NONCE 120 /* The TTL in seconds used by the --preset option of some commands. This is the default value changeable by an OPTION command. */ #define CACHE_TTL_OPT_PRESET 900 /* The type of a function to lookup a TTL by a keygrip. */ typedef int (*lookup_ttl_t)(const char *hexgrip); /* This is a special version of the usual _() gettext macro. It assumes a server connection control variable with the name "ctrl" and uses that to translate a string according to the locale set for the connection. The macro LunderscoreIMPL is used by i18n to actually define the inline function when needed. */ #if defined (ENABLE_NLS) || defined (USE_SIMPLE_GETTEXT) #define L_(a) agent_Lunderscore (ctrl, (a)) #define LunderscorePROTO \ static inline const char *agent_Lunderscore (ctrl_t ctrl, \ const char *string) \ GNUPG_GCC_ATTR_FORMAT_ARG(2); #define LunderscoreIMPL \ static inline const char * \ agent_Lunderscore (ctrl_t ctrl, const char *string) \ { \ return ctrl? i18n_localegettext (ctrl->lc_messages, string) \ /* */: gettext (string); \ } #else #define L_(a) (a) #endif /* Information from scdaemon for card keys. */ struct card_key_info_s { struct card_key_info_s *next; char keygrip[41]; char *serialno; char *idstr; }; /*-- gpg-agent.c --*/ void agent_exit (int rc) GPGRT_ATTR_NORETURN; /* Also implemented in other tools */ void agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total), ctrl_t ctrl); gpg_error_t agent_copy_startup_env (ctrl_t ctrl); const char *get_agent_socket_name (void); const char *get_agent_ssh_socket_name (void); int get_agent_active_connection_count (void); #ifdef HAVE_W32_SYSTEM void *get_agent_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); gpg_error_t pinentry_loopback_confirm (ctrl_t ctrl, const char *desc, int ask_confirmation, const char *ok, const char *notok); #ifdef HAVE_W32_SYSTEM int serve_mmapped_ssh_request (ctrl_t ctrl, unsigned char *request, size_t maxreqlen); #endif /*HAVE_W32_SYSTEM*/ /*-- command-ssh.c --*/ ssh_control_file_t ssh_open_control_file (void); void ssh_close_control_file (ssh_control_file_t cf); gpg_error_t ssh_read_control_file (ssh_control_file_t cf, char *r_hexgrip, int *r_disabled, int *r_ttl, int *r_confirm); gpg_error_t ssh_search_control_file (ssh_control_file_t cf, const char *hexgrip, int *r_disabled, int *r_ttl, int *r_confirm); void start_command_handler_ssh (ctrl_t, gnupg_fd_t); /*-- findkey.c --*/ gpg_error_t agent_modify_description (const char *in, const char *comment, const gcry_sexp_t key, char **result); int agent_write_private_key (const unsigned char *grip, const void *buffer, size_t length, int force, const char *serialno, const char *keyref); 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); int agent_get_confirmation (ctrl_t ctrl, const char *desc, const char *ok, const char *notokay, int with_cancel); int agent_show_message (ctrl_t ctrl, const char *desc, const char *ok_btn); int agent_popup_message_start (ctrl_t ctrl, const char *desc, const char *ok_btn); void agent_popup_message_stop (ctrl_t ctrl); int agent_clear_passphrase (ctrl_t ctrl, const char *keyinfo, cache_mode_t cache_mode); /*-- cache.c --*/ void initialize_module_cache (void); void deinitialize_module_cache (void); void agent_cache_housekeeping (void); void agent_flush_cache (int pincache_only); int agent_put_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode, const char *data, int ttl); char *agent_get_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode); void agent_store_cache_hit (const char *key); /*-- pksign.c --*/ gpg_error_t agent_pksign_do (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, gcry_sexp_t *signature_sexp, cache_mode_t cache_mode, lookup_ttl_t lookup_ttl, const void *overridedata, size_t overridedatalen); gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *desc_text, membuf_t *outbuf, cache_mode_t cache_mode); /*-- pkdecrypt.c --*/ 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, 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, 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 *grip, const unsigned char *digest, size_t digestlen, int algo, 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 *grip, const unsigned char *cipher, const unsigned char *shadow_info, char **r_buf, size_t *r_len, int *r_padding); int divert_generic_cmd (ctrl_t ctrl, const char *cmdline, void *assuan_context); gpg_error_t divert_writekey (ctrl_t ctrl, int force, const char *serialno, const char *keyref, const char *keydata, size_t keydatalen); /*-- call-scd.c --*/ void initialize_module_call_scd (void); void agent_scd_dump_state (void); int agent_scd_check_running (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); gpg_error_t agent_card_writekey (ctrl_t ctrl, int force, const char *serialno, const char *keyref, const char *keydata, size_t keydatalen, int (*getpin_cb)(void *, const char *, const char *, char*, size_t), void *getpin_cb_arg); gpg_error_t agent_card_getattr (ctrl_t ctrl, const char *name, char **result, const char *keygrip); int agent_card_scd (ctrl_t ctrl, const char *cmdline, int (*getpin_cb)(void *, const char *, const char *, char*, size_t), void *getpin_cb_arg, void *assuan_context); void agent_card_free_keyinfo (struct card_key_info_s *l); gpg_error_t agent_card_keyinfo (ctrl_t ctrl, const char *keygrip, int cap, struct card_key_info_s **result); 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/gpg-agent.c b/agent/gpg-agent.c index 6a7213c67..70e9e229f 100644 --- a/agent/gpg-agent.c +++ b/agent/gpg-agent.c @@ -1,3275 +1,3276 @@ /* gpg-agent.c - The GnuPG Agent * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc. * Copyright (C) 2000-2016 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 # ifndef WINVER # define WINVER 0x0500 /* Same as in common/sysutils.c */ # endif # ifdef HAVE_WINSOCK2_H # include # endif # include # include #else /*!HAVE_W32_SYSTEM*/ # include # include #endif /*!HAVE_W32_SYSTEM*/ #include #ifdef HAVE_SIGNAL_H # include #endif #include +#define INCLUDED_BY_MAIN_MODULE 1 #define GNUPG_COMMON_NEED_AFLOCAL #include "agent.h" #include /* Malloc hooks and socket wrappers. */ #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/gc-opt-flags.h" #include "../common/exechelp.h" #include "../common/asshelp.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aGPGConfList, aGPGConfTest, aUseStandardSocketP, oOptions, oDebug, oDebugAll, oDebugLevel, oDebugWait, oDebugQuickRandom, oDebugPinentry, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oGrab, oNoGrab, oLogFile, oServer, oDaemon, oSupervised, oBatch, oPinentryProgram, oPinentryTouchFile, oPinentryInvisibleChar, oPinentryTimeout, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oScdaemonProgram, oDefCacheTTL, oDefCacheTTLSSH, oMaxCacheTTL, oMaxCacheTTLSSH, oEnforcePassphraseConstraints, oMinPassphraseLen, oMinPassphraseNonalpha, oCheckPassphrasePattern, oMaxPassphraseDays, oEnablePassphraseHistory, oDisableExtendedKeyFormat, oEnableExtendedKeyFormat, oUseStandardSocket, oNoUseStandardSocket, oExtraSocket, oBrowserSocket, oFakedSystemTime, oIgnoreCacheForSigning, oAllowMarkTrusted, oNoAllowMarkTrusted, oAllowPresetPassphrase, oAllowLoopbackPinentry, oNoAllowLoopbackPinentry, oNoAllowExternalCache, oAllowEmacsPinentry, oKeepTTY, oKeepDISPLAY, oSSHSupport, oSSHFingerprintDigest, oPuttySupport, oDisableScdaemon, oDisableCheckOwnSocket, oS2KCount, oS2KCalibration, oAutoExpandSecmem, oListenBacklog, oWriteEnvFile, oNoop }; #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif static ARGPARSE_OPTS opts[] = { ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"), ARGPARSE_group (301, N_("@Options:\n ")), ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")), ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")), #ifndef HAVE_W32_SYSTEM ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"), ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_n (oGrab, "grab", "@"), /* FIXME: Add the below string for 2.3 */ /* N_("let PIN-Entry grab keyboard and mouse")), */ ARGPARSE_s_n (oNoGrab, "no-grab", "@"), ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")), ARGPARSE_s_s (oPinentryProgram, "pinentry-program", /* */ N_("|PGM|use PGM as the PIN-Entry program")), ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"), ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"), ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"), ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program", /* */ N_("|PGM|use PGM as the SCdaemon program") ), ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon", /* */ N_("do not use the SCdaemon") ), ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_s (oExtraSocket, "extra-socket", /* */ N_("|NAME|accept some commands via NAME")), ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"), ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"), ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oDisplay, "display", "@"), ARGPARSE_s_s (oTTYname, "ttyname", "@"), ARGPARSE_s_s (oTTYtype, "ttytype", "@"), ARGPARSE_s_s (oLCctype, "lc-ctype", "@"), ARGPARSE_s_s (oLCmessages, "lc-messages", "@"), ARGPARSE_s_s (oXauthority, "xauthority", "@"), ARGPARSE_s_n (oKeepTTY, "keep-tty", /* */ N_("ignore requests to change the TTY")), ARGPARSE_s_n (oKeepDISPLAY, "keep-display", /* */ N_("ignore requests to change the X display")), ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl", N_("|N|expire cached PINs after N seconds")), ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ), ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ), ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ), ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints", /* */ "@"), ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"), ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"), ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"), ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"), ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"), ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing", /* */ N_("do not use the PIN cache when signing")), ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache", /* */ N_("disallow the use of an external password cache")), ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted", /* */ N_("disallow clients to mark keys as \"trusted\"")), ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"), ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase", /* */ N_("allow presetting passphrase")), ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry", N_("disallow caller to override the pinentry")), ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"), ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry", /* */ N_("allow passphrase to be prompted through Emacs")), ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")), ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest", N_("|ALGO|use ALGO to show ssh fingerprints")), ARGPARSE_s_n (oPuttySupport, "enable-putty-support", #ifdef HAVE_W32_SYSTEM /* */ N_("enable putty support") #else /* */ "@" #endif ), ARGPARSE_s_n (oDisableExtendedKeyFormat, "disable-extended-key-format", "@"), ARGPARSE_s_n (oEnableExtendedKeyFormat, "enable-extended-key-format", "@"), ARGPARSE_s_u (oS2KCount, "s2k-count", "@"), ARGPARSE_s_u (oS2KCalibration, "s2k-calibration", "@"), ARGPARSE_op_u (oAutoExpandSecmem, "auto-expand-secmem", "@"), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), /* Dummy options for backward compatibility. */ ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"), ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"), ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"), /* Dummy options. */ ARGPARSE_end () /* End of list */ }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_MPI_VALUE , "mpi" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */ #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */ #define MAX_CACHE_TTL (120*60) /* 2 hours */ #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */ #define MIN_PASSPHRASE_LEN (8) #define MIN_PASSPHRASE_NONALPHA (1) #define MAX_PASSPHRASE_DAYS (0) /* The timer tick used for housekeeping stuff. Note that on Windows * we use a SetWaitableTimer seems to signal earlier than about 2 * seconds. Thus we use 4 seconds on all platforms except for * Windowsce. CHECK_OWN_SOCKET_INTERVAL defines how often we check * our own socket in standard socket mode. If that value is 0 we * don't check at all. All values are in seconds. */ #if defined(HAVE_W32CE_SYSTEM) # define TIMERTICK_INTERVAL (60) # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */ #else # define TIMERTICK_INTERVAL (4) # define CHECK_OWN_SOCKET_INTERVAL (60) #endif /* Flag indicating that the ssh-agent subsystem has been enabled. */ static int ssh_support; #ifdef HAVE_W32_SYSTEM /* Flag indicating that support for Putty has been enabled. */ static int putty_support; /* A magic value used with WM_COPYDATA. */ #define PUTTY_IPC_MAGIC 0x804e50ba /* To avoid surprises we limit the size of the mapped IPC file to this value. Putty currently (0.62) uses 8k, thus 16k should be enough for the foreseeable future. */ #define PUTTY_IPC_MAXLEN 16384 #endif /*HAVE_W32_SYSTEM*/ /* The list of open file descriptors at startup. Note that this list * has been allocated using the standard malloc. */ #ifndef HAVE_W32_SYSTEM static int *startup_fd_list; #endif /* The signal mask at startup and a flag telling whether it is valid. */ #ifdef HAVE_SIGPROCMASK static sigset_t startup_signal_mask; static int startup_signal_mask_valid; #endif /* Flag to indicate that a shutdown was requested. */ static int shutdown_pending; /* Counter for the currently running own socket checks. */ static int check_own_socket_running; /* Flags to indicate that check_own_socket shall not be called. */ static int disable_check_own_socket; /* Flag indicating that we are in supervised mode. */ static int is_supervised; /* Flag to inhibit socket removal in cleanup. */ static int inhibit_socket_removal; /* It is possible that we are currently running under setuid permissions */ static int maybe_setuid = 1; /* Name of the communication socket used for native gpg-agent requests. The second variable is either NULL or a malloced string with the real socket name in case it has been redirected. */ static char *socket_name; static char *redir_socket_name; /* Name of the optional extra socket used for native gpg-agent requests. */ static char *socket_name_extra; static char *redir_socket_name_extra; /* Name of the optional browser socket used for native gpg-agent requests. */ static char *socket_name_browser; static char *redir_socket_name_browser; /* Name of the communication socket used for ssh-agent protocol. */ static char *socket_name_ssh; static char *redir_socket_name_ssh; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; static assuan_sock_nonce_t socket_nonce_extra; static assuan_sock_nonce_t socket_nonce_browser; static assuan_sock_nonce_t socket_nonce_ssh; /* Value for the listen() backlog argument. We use the same value for * all sockets - 64 is on current Linux half of the default maximum. * Let's try this as default. Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Default values for options passed to the pinentry. */ static char *default_display; static char *default_ttyname; static char *default_ttytype; static char *default_lc_ctype; static char *default_lc_messages; static char *default_xauthority; /* Name of a config file, which will be reread on a HUP if it is not NULL. */ static char *config_filename; /* Helper to implement --debug-level */ static const char *debug_level; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* The handle_tick() function may test whether a parent is still * running. We record the PID of the parent here or -1 if it should * be watched. */ static pid_t parent_pid = (pid_t)(-1); /* This flag is true if the inotify mechanism for detecting the * removal of the homedir is active. This flag is used to disable the * alternative but portable stat based check. */ static int have_homedir_inotify; /* Depending on how gpg-agent was started, the homedir inotify watch * may not be reliable. This flag is set if we assume that inotify * works reliable. */ static int reliable_homedir_inotify; /* Number of active connections. */ static int active_connections; /* This object is used to dispatch progress messages from Libgcrypt to * the right thread. Given that we will have at max only a few dozen * connections at a time, using a linked list is the easiest way to * handle this. */ struct progress_dispatch_s { struct progress_dispatch_s *next; /* The control object of the connection. If this is NULL no * connection is associated with this item and it is free for reuse * by new connections. */ ctrl_t ctrl; /* The thread id of (npth_self) of the connection. */ npth_t tid; /* The callback set by the connection. This is similar to the * Libgcrypt callback but with the control object passed as the * first argument. */ void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total); }; struct progress_dispatch_s *progress_dispatch_list; /* Local prototypes. */ static char *create_socket_name (char *standard_name, int with_homedir); static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin, char **r_redir_name, assuan_sock_nonce_t *nonce); static void create_directories (void); static void agent_libgcrypt_progress_cb (void *data, const char *what, int printchar, int current, int total); static void agent_init_default_ctrl (ctrl_t ctrl); static void agent_deinit_default_ctrl (ctrl_t ctrl); static void handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_extra, gnupg_fd_t listen_fd_browser, gnupg_fd_t listen_fd_ssh); static void check_own_socket (void); static int check_for_running_agent (int silent); /* Pth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; /* Functions. */ /* Allocate a string describing a library version by calling a GETFNC. This function is expected to be called only once. GETFNC is expected to have a semantic like gcry_check_version (). */ static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; if (maybe_setuid) { gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ maybe_setuid = 0; } s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } /* Return strings describing this program. The case values are described in common/argparse.c:strusage. The values here override the default values given by strusage. */ static const char * my_strusage (int level) { static char *ver_gcry; const char *p; switch (level) { case 11: p = "@GPG_AGENT@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; case 1: case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)"); break; case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n" "Secret key management for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL only the active debug flags are propagated to the subsystems. With DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. Note that we don't fail here, because it is important to keep gpg-agent running even after re-reading the options due to a SIGHUP. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) opt.verbose = 1; if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_MPI_VALUE) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2); if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is the corresponding real name if the socket has been redirected. */ static void remove_socket (char *name, char *redir_name) { if (name && *name) { if (redir_name) name = redir_name; gnupg_remove (name); *name = 0; } } /* Discover which inherited file descriptors correspond to which * services/sockets offered by gpg-agent, using the LISTEN_FDS and * LISTEN_FDNAMES convention. The understood labels are "ssh", * "extra", and "browser". "std" or other labels will be interpreted * as the standard socket. * * This function is designed to log errors when the expected file * descriptors don't make sense, but to do its best to continue to * work even in the face of minor misconfigurations. * * For more information on the LISTEN_FDS convention, see * sd_listen_fds(3) on certain Linux distributions. */ #ifndef HAVE_W32_SYSTEM static void map_supervised_sockets (gnupg_fd_t *r_fd, gnupg_fd_t *r_fd_extra, gnupg_fd_t *r_fd_browser, gnupg_fd_t *r_fd_ssh) { struct { const char *label; int **fdaddr; char **nameaddr; } tbl[] = { { "ssh", &r_fd_ssh, &socket_name_ssh }, { "browser", &r_fd_browser, &socket_name_browser }, { "extra", &r_fd_extra, &socket_name_extra }, { "std", &r_fd, &socket_name } /* (Must be the last item.) */ }; const char *envvar; char **fdnames; int nfdnames; int fd_count; *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1; /* Print a warning if LISTEN_PID does not match outr pid. */ envvar = getenv ("LISTEN_PID"); if (!envvar) log_error ("no LISTEN_PID environment variable found in " "--supervised mode (ignoring)\n"); else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ()) log_error ("environment variable LISTEN_PID (%lu) does not match" " our pid (%lu) in --supervised mode (ignoring)\n", (unsigned long)strtoul (envvar, NULL, 10), (unsigned long)getpid ()); /* Parse LISTEN_FDNAMES into the array FDNAMES. */ envvar = getenv ("LISTEN_FDNAMES"); if (envvar) { fdnames = strtokenize (envvar, ":"); if (!fdnames) { log_error ("strtokenize failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); agent_exit (1); } for (nfdnames=0; fdnames[nfdnames]; nfdnames++) ; } else { fdnames = NULL; nfdnames = 0; } /* Parse LISTEN_FDS into fd_count or provide a replacement. */ envvar = getenv ("LISTEN_FDS"); if (envvar) fd_count = atoi (envvar); else if (fdnames) { log_error ("no LISTEN_FDS environment variable found in --supervised" " mode (relying on LISTEN_FDNAMES instead)\n"); fd_count = nfdnames; } else { log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables " "found in --supervised mode" " (assuming 1 active descriptor)\n"); fd_count = 1; } if (fd_count < 1) { log_error ("--supervised mode expects at least one file descriptor" " (was told %d, carrying on as though it were 1)\n", fd_count); fd_count = 1; } /* Assign the descriptors to the return values. */ if (!fdnames) { struct stat statbuf; if (fd_count != 1) log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1" " in --supervised mode." " (ignoring all sockets but the first one)\n", fd_count); if (fstat (3, &statbuf) == -1 && errno ==EBADF) log_fatal ("file descriptor 3 must be valid in --supervised mode" " if LISTEN_FDNAMES is not set\n"); *r_fd = 3; socket_name = gnupg_get_socket_name (3); } else if (fd_count != nfdnames) { log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match " "LISTEN_FDS (%d) in --supervised mode\n", nfdnames, fd_count); } else { int i, j, fd; char *name; for (i = 0; i < nfdnames; i++) { for (j = 0; j < DIM (tbl); j++) { if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1) { fd = 3 + i; if (**tbl[j].fdaddr == -1) { name = gnupg_get_socket_name (fd); if (name) { **tbl[j].fdaddr = fd; *tbl[j].nameaddr = name; log_info ("using fd %d for %s socket (%s)\n", fd, tbl[j].label, name); } else { log_error ("cannot listen on fd %d for %s socket\n", fd, tbl[j].label); close (fd); } } else { log_error ("cannot listen on more than one %s socket\n", tbl[j].label); close (fd); } break; } } } } xfree (fdnames); } #endif /*!HAVE_W32_SYSTEM*/ /* Cleanup code for this program. This is either called has an atexit handler or directly. */ static void cleanup (void) { static int done; if (done) return; done = 1; deinitialize_module_cache (); if (!is_supervised && !inhibit_socket_removal) { remove_socket (socket_name, redir_socket_name); if (opt.extra_socket > 1) remove_socket (socket_name_extra, redir_socket_name_extra); if (opt.browser_socket > 1) remove_socket (socket_name_browser, redir_socket_name_browser); remove_socket (socket_name_ssh, redir_socket_name_ssh); } } /* Handle options which are allowed to be reset after program start. Return true when the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread) { int i; if (!pargs) { /* reset mode */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.no_grab = 1; opt.debug_pinentry = 0; opt.pinentry_program = NULL; opt.pinentry_touch_file = NULL; xfree (opt.pinentry_invisible_char); opt.pinentry_invisible_char = NULL; opt.pinentry_timeout = 0; opt.scdaemon_program = NULL; opt.def_cache_ttl = DEFAULT_CACHE_TTL; opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH; opt.max_cache_ttl = MAX_CACHE_TTL; opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH; opt.enforce_passphrase_constraints = 0; opt.min_passphrase_len = MIN_PASSPHRASE_LEN; opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA; opt.check_passphrase_pattern = NULL; opt.max_passphrase_days = MAX_PASSPHRASE_DAYS; opt.enable_passphrase_history = 0; opt.enable_extended_key_format = 1; opt.ignore_cache_for_signing = 0; opt.allow_mark_trusted = 1; opt.allow_external_cache = 1; opt.allow_loopback_pinentry = 1; opt.allow_emacs_pinentry = 0; opt.disable_scdaemon = 0; disable_check_own_socket = 0; /* Note: When changing the next line, change also gpgconf_list. */ opt.ssh_fingerprint_digest = GCRY_MD_MD5; opt.s2k_count = 0; set_s2k_calibration_time (0); /* Set to default. */ return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oDebugPinentry: opt.debug_pinentry = 1; break; case oLogFile: if (!reread) return 0; /* not handled */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oNoGrab: opt.no_grab |= 1; break; case oGrab: opt.no_grab |= 2; break; case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break; case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break; case oPinentryInvisibleChar: xfree (opt.pinentry_invisible_char); opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break; break; case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break; case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break; case oDisableScdaemon: opt.disable_scdaemon = 1; break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break; case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break; case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break; case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break; case oEnforcePassphraseConstraints: opt.enforce_passphrase_constraints=1; break; case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break; case oMinPassphraseNonalpha: opt.min_passphrase_nonalpha = pargs->r.ret_ulong; break; case oCheckPassphrasePattern: opt.check_passphrase_pattern = pargs->r.ret_str; break; case oMaxPassphraseDays: opt.max_passphrase_days = pargs->r.ret_ulong; break; case oEnablePassphraseHistory: opt.enable_passphrase_history = 1; break; case oEnableExtendedKeyFormat: opt.enable_extended_key_format = 2; break; case oDisableExtendedKeyFormat: if (opt.enable_extended_key_format != 2) opt.enable_extended_key_format = 0; break; case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break; case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break; case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break; case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break; case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break; case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break; case oNoAllowExternalCache: opt.allow_external_cache = 0; break; case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1; break; case oSSHFingerprintDigest: i = gcry_md_map_name (pargs->r.ret_str); if (!i) log_error (_("selected digest algorithm is invalid\n")); else opt.ssh_fingerprint_digest = i; break; case oS2KCount: opt.s2k_count = pargs->r.ret_ulong; break; case oS2KCalibration: set_s2k_calibration_time (pargs->r.ret_ulong); break; case oNoop: break; default: return 0; /* not handled */ } return 1; /* handled */ } /* Fixup some options after all have been processed. */ static void finalize_rereadable_options (void) { /* Hack to allow --grab to override --no-grab. */ if ((opt.no_grab & 2)) opt.no_grab = 0; } static void thread_init_once (void) { static int npth_initialized = 0; if (!npth_initialized) { npth_initialized++; npth_init (); } gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now that we have set the syscall clamp we need to tell Libgcrypt * that it should get them from libgpg-error. Note that Libgcrypt * has already been initialized but at that point nPth was not * initialized and thus Libgcrypt could not set its system call * clamp. */ #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */ gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0); #endif } static void initialize_modules (void) { thread_init_once (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); initialize_module_cache (); initialize_module_call_pinentry (); initialize_module_call_scd (); initialize_module_trustlist (); } /* The main entry point. */ int main (int argc, char **argv ) { ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; FILE *configfp = NULL; char *configname = NULL; const char *shell; unsigned configlineno; int parse_debug = 0; int default_config =1; int pipe_server = 0; int is_daemon = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; int debug_wait = 0; int gpgconf_list = 0; gpg_error_t err; struct assuan_malloc_hooks malloc_hooks; early_system_init (); /* Before we do anything else we save the list of currently open file descriptors and the signal mask. This info is required to do the exec call properly. We don't need it on Windows. */ #ifndef HAVE_W32_SYSTEM startup_fd_list = get_all_open_fds (); #endif /*!HAVE_W32_SYSTEM*/ #ifdef HAVE_SIGPROCMASK if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask)) startup_signal_mask_valid = 1; #endif /*HAVE_SIGPROCMASK*/ /* Set program name etc. */ set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); /* Please note that we may running SUID(ROOT), so be very CAREFUL when adding any stuff between here and the call to INIT_SECMEM() somewhere after the option parsing */ log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); assuan_sock_set_system_hooks (ASSUAN_SYSTEM_NPTH); setup_libassuan_logging (&opt.debug, NULL); setup_libgcrypt_logging (); gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL); disable_core_dumps (); /* Set default options. */ parse_rereadable_options (NULL, 0); /* Reset them to default values. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Record some of the original environment strings. */ { const char *s; int idx; static const char *names[] = { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL }; err = 0; opt.startup_env = session_env_new (); if (!opt.startup_env) err = gpg_error_from_syserror (); for (idx=0; !err && names[idx]; idx++) { s = getenv (names[idx]); if (s) err = session_env_setenv (opt.startup_env, names[idx], s); } if (!err) { s = gnupg_ttyname (0); if (s) err = session_env_setenv (opt.startup_env, "GPG_TTY", s); } if (err) log_fatal ("error recording startup environment: %s\n", gpg_strerror (err)); /* Fixme: Better use the locale function here. */ opt.startup_lc_ctype = getenv ("LC_CTYPE"); if (opt.startup_lc_ctype) opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype); opt.startup_lc_messages = getenv ("LC_MESSAGES"); if (opt.startup_lc_messages) opt.startup_lc_messages = xstrdup (opt.startup_lc_messages); } /* Check whether we have a config file on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */ while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; else if (pargs.r_opt == oOptions) { /* yes there is one, so we do not try the default one, but read the option file when it is encountered at the commandline */ default_config = 0; } else if (pargs.r_opt == oNoOptions) default_config = 0; /* --no-options */ else if (pargs.r_opt == oHomedir) gnupg_set_homedir (pargs.r.ret_str); else if (pargs.r_opt == oDebugQuickRandom) { gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); } } /* Initialize the secure memory. */ gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0); maybe_setuid = 0; /* Now we are now working under our real uid */ if (default_config) configname = make_filename (gnupg_homedir (), GPG_AGENT_NAME EXTSEP_S "conf", NULL); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if( parse_debug ) log_info (_("Note: no default option file '%s'\n"), configname ); /* Save the default conf file name so that reread_configuration is able to test whether the config file has been created in the meantime. */ xfree (config_filename); config_filename = configname; configname = NULL; } else { log_error (_("option file '%s': %s\n"), configname, strerror(errno) ); exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname ) log_info (_("reading options from '%s'\n"), configname ); default_config = 0; } while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) ) { if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aGPGConfList: gpgconf_list = 1; break; case aGPGConfTest: gpgconf_list = 2; break; case aUseStandardSocketP: gpgconf_list = 3; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oOptions: /* config files may not be nested (silently ignore them) */ if (!configfp) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoGreeting: /* Dummy option. */ break; case oNoVerbose: opt.verbose = 0; break; case oNoOptions: break; /* no-options */ case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oServer: pipe_server = 1; break; case oDaemon: is_daemon = 1; break; case oSupervised: is_supervised = 1; break; case oDisplay: default_display = xstrdup (pargs.r.ret_str); break; case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break; case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break; case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break; case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str); break; case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str); break; case oUseStandardSocket: case oNoUseStandardSocket: obsolete_option (configname, configlineno, "use-standard-socket"); break; case oFakedSystemTime: { time_t faked_time = isotime2epoch (pargs.r.ret_str); if (faked_time == (time_t)(-1)) faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10); gnupg_set_time (faked_time, 0); } break; case oKeepTTY: opt.keep_tty = 1; break; case oKeepDISPLAY: opt.keep_display = 1; break; case oSSHSupport: ssh_support = 1; break; case oPuttySupport: # ifdef HAVE_W32_SYSTEM putty_support = 1; # endif break; case oExtraSocket: opt.extra_socket = 1; /* (1 = points into argv) */ socket_name_extra = pargs.r.ret_str; break; case oBrowserSocket: opt.browser_socket = 1; /* (1 = points into argv) */ socket_name_browser = pargs.r.ret_str; break; case oAutoExpandSecmem: /* Try to enable this option. It will officially only be * supported by Libgcrypt 1.9 but 1.8.2 already supports it * on the quiet and thus we use the numeric value value. */ gcry_control (78 /*GCRYCTL_AUTO_EXPAND_SECMEM*/, (unsigned int)pargs.r.ret_ulong, 0); break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; case oDebugQuickRandom: /* Only used by the first stage command line parser. */ break; case oWriteEnvFile: obsolete_option (configname, configlineno, "write-env-file"); break; default : pargs.err = configfp? 1:2; break; } } if (configfp) { fclose( configfp ); configfp = NULL; /* Keep a copy of the name so that it can be read on SIGHUP. */ if (config_filename != configname) { xfree (config_filename); config_filename = configname; } configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (log_get_errorcount(0)) exit(2); finalize_rereadable_options (); /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } #ifdef ENABLE_NLS /* gpg-agent usually does not output any messages because it runs in the background. For log files it is acceptable to have messages always encoded in utf-8. We switch here to utf-8, so that commands like --help still give native messages. It is far easier to switch only once instead of for every message and it actually helps when more then one thread is active (avoids an extra copy step). */ bind_textdomain_codeset (PACKAGE_GT, "UTF-8"); #endif if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised) { /* We have been called without any command and thus we merely check whether an agent is already running. We do this right here so that we don't clobber a logfile with this check but print the status directly to stderr. */ opt.debug = 0; set_debug (); check_for_running_agent (0); agent_exit (0); } if (is_supervised) ; else if (!opt.extra_socket) opt.extra_socket = 1; else if (socket_name_extra && (!strcmp (socket_name_extra, "none") || !strcmp (socket_name_extra, "/dev/null"))) { /* User requested not to create this socket. */ opt.extra_socket = 0; socket_name_extra = NULL; } if (is_supervised) ; else if (!opt.browser_socket) opt.browser_socket = 1; else if (socket_name_browser && (!strcmp (socket_name_browser, "none") || !strcmp (socket_name_browser, "/dev/null"))) { /* User requested not to create this socket. */ opt.browser_socket = 0; socket_name_browser = NULL; } set_debug (); if (atexit (cleanup)) { log_error ("atexit failed\n"); cleanup (); exit (1); } /* Try to create missing directories. */ create_directories (); if (debug_wait && pipe_server) { thread_init_once (); log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } if (gpgconf_list == 3) { /* We now use the standard socket always - return true for backward compatibility. */ agent_exit (0); } else if (gpgconf_list == 2) agent_exit (0); else if (gpgconf_list) { char *filename; char *filename_esc; /* List options and default values in the GPG Conf format. */ filename = make_filename (gnupg_homedir (), GPG_AGENT_NAME EXTSEP_S "conf", NULL); filename_esc = percent_escape (filename, NULL); es_printf ("%s-%s.conf:%lu:\"%s\n", GPGCONF_NAME, GPG_AGENT_NAME, GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename); xfree (filename_esc); es_printf ("verbose:%lu:\n" "quiet:%lu:\n" "debug-level:%lu:\"none:\n" "log-file:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME ); es_printf ("default-cache-ttl:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL ); es_printf ("default-cache-ttl-ssh:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH ); es_printf ("max-cache-ttl:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL ); es_printf ("max-cache-ttl-ssh:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH ); es_printf ("enforce-passphrase-constraints:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("min-passphrase-len:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN ); es_printf ("min-passphrase-nonalpha:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_NONALPHA); es_printf ("check-passphrase-pattern:%lu:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME); es_printf ("max-passphrase-days:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_PASSPHRASE_DAYS); es_printf ("enable-passphrase-history:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-grab:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("ignore-cache-for-signing:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-allow-external-cache:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-allow-mark-trusted:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("disable-scdaemon:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, "md5"); #ifdef HAVE_W32_SYSTEM es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE); #endif es_printf ("no-allow-loopback-pinentry:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("allow-emacs-pinentry:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("pinentry-timeout:%lu:0:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME); es_printf ("grab:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); agent_exit (0); } /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } /* Make sure that we have a default ttyname. */ if (!default_ttyname && gnupg_ttyname (1)) default_ttyname = xstrdup (gnupg_ttyname (1)); if (!default_ttytype && getenv ("TERM")) default_ttytype = xstrdup (getenv ("TERM")); if (pipe_server) { /* This is the simple pipe based server */ ctrl_t ctrl; initialize_modules (); ctrl = xtrycalloc (1, sizeof *ctrl); if (!ctrl) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); agent_exit (1); } ctrl->session_env = session_env_new (); if (!ctrl->session_env) { log_error ("error allocating session environment block: %s\n", strerror (errno) ); xfree (ctrl); agent_exit (1); } agent_init_default_ctrl (ctrl); start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD); agent_deinit_default_ctrl (ctrl); xfree (ctrl); } else if (is_supervised) { #ifndef HAVE_W32_SYSTEM gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh; initialize_modules (); /* when supervised and sending logs to stderr, the process supervisor should handle log entry metadata (pid, name, timestamp) */ if (!logfile) log_set_prefix (NULL, 0); log_info ("%s %s starting in supervised mode.\n", strusage(11), strusage(13) ); /* See below in "regular server mode" on why we remove certain * envvars. */ if (!opt.keep_display) gnupg_unsetenv ("DISPLAY"); gnupg_unsetenv ("INSIDE_EMACS"); /* Virtually create the sockets. Note that we use -1 here * because the whole thing works only on Unix. */ map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh); if (fd == -1) log_fatal ("no standard socket provided\n"); #ifdef HAVE_SIGPROCMASK if (startup_signal_mask_valid) { if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL)) log_error ("error restoring signal mask: %s\n", strerror (errno)); } else log_info ("no saved signal mask\n"); #endif /*HAVE_SIGPROCMASK*/ log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n", fd, fd_extra, fd_browser, fd_ssh); handle_connections (fd, fd_extra, fd_browser, fd_ssh); #endif /*!HAVE_W32_SYSTEM*/ } else if (!is_daemon) ; /* NOTREACHED */ else { /* Regular server mode */ gnupg_fd_t fd; gnupg_fd_t fd_extra = GNUPG_INVALID_FD; gnupg_fd_t fd_browser = GNUPG_INVALID_FD; gnupg_fd_t fd_ssh = GNUPG_INVALID_FD; #ifndef HAVE_W32_SYSTEM pid_t pid; #endif /* Remove the DISPLAY variable so that a pinentry does not default to a specific display. There is still a default display when gpg-agent was started using --display or a client requested this using an OPTION command. Note, that we don't do this when running in reverse daemon mode (i.e. when exec the program given as arguments). */ #ifndef HAVE_W32_SYSTEM if (!opt.keep_display && !argc) gnupg_unsetenv ("DISPLAY"); #endif /* Remove the INSIDE_EMACS variable so that a pinentry does not always try to interact with Emacs. The variable is set when a client requested this using an OPTION command. */ gnupg_unsetenv ("INSIDE_EMACS"); /* Create the sockets. */ socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1); fd = create_server_socket (socket_name, 1, 0, &redir_socket_name, &socket_nonce); if (opt.extra_socket) { if (socket_name_extra) socket_name_extra = create_socket_name (socket_name_extra, 0); else socket_name_extra = create_socket_name /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1); opt.extra_socket = 2; /* Indicate that it has been malloced. */ fd_extra = create_server_socket (socket_name_extra, 0, 0, &redir_socket_name_extra, &socket_nonce_extra); } if (opt.browser_socket) { if (socket_name_browser) socket_name_browser = create_socket_name (socket_name_browser, 0); else socket_name_browser= create_socket_name /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1); opt.browser_socket = 2; /* Indicate that it has been malloced. */ fd_browser = create_server_socket (socket_name_browser, 0, 0, &redir_socket_name_browser, &socket_nonce_browser); } socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1); fd_ssh = create_server_socket (socket_name_ssh, 0, 1, &redir_socket_name_ssh, &socket_nonce_ssh); /* If we are going to exec a program in the parent, we record the PID, so that the child may check whether the program is still alive. */ if (argc) parent_pid = getpid (); fflush (NULL); #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; initialize_modules (); #else /*!HAVE_W32_SYSTEM*/ pid = fork (); if (pid == (pid_t)-1) { log_fatal ("fork failed: %s\n", strerror (errno) ); exit (1); } else if (pid) { /* We are the parent */ char *infostr_ssh_sock, *infostr_ssh_valid; /* Close the socket FD. */ close (fd); /* The signal mask might not be correct right now and thus we restore it. That is not strictly necessary but some programs falsely assume a cleared signal mask. */ #ifdef HAVE_SIGPROCMASK if (startup_signal_mask_valid) { if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL)) log_error ("error restoring signal mask: %s\n", strerror (errno)); } else log_info ("no saved signal mask\n"); #endif /*HAVE_SIGPROCMASK*/ /* Create the SSH info string if enabled. */ if (ssh_support) { if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s", socket_name_ssh) < 0) { log_error ("out of core\n"); kill (pid, SIGTERM); exit (1); } if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu", (unsigned long)getpid()) < 0) { log_error ("out of core\n"); kill (pid, SIGTERM); exit (1); } } *socket_name = 0; /* Don't let cleanup() remove the socket - the child should do this from now on */ if (opt.extra_socket) *socket_name_extra = 0; if (opt.browser_socket) *socket_name_browser = 0; *socket_name_ssh = 0; if (argc) { /* Run the program given on the commandline. */ if (ssh_support && (putenv (infostr_ssh_sock) || putenv (infostr_ssh_valid))) { log_error ("failed to set environment: %s\n", strerror (errno) ); kill (pid, SIGTERM ); exit (1); } /* Close all the file descriptors except the standard ones and those open at startup. We explicitly don't close 0,1,2 in case something went wrong collecting them at startup. */ close_all_fds (3, startup_fd_list); /* Run the command. */ execvp (argv[0], argv); log_error ("failed to run the command: %s\n", strerror (errno)); kill (pid, SIGTERM); exit (1); } else { /* Print the environment string, so that the caller can use shell's eval to set it */ if (csh_style) { if (ssh_support) { *strchr (infostr_ssh_sock, '=') = ' '; es_printf ("setenv %s;\n", infostr_ssh_sock); } } else { if (ssh_support) { es_printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock); } } if (ssh_support) { xfree (infostr_ssh_sock); xfree (infostr_ssh_valid); } exit (0); } /*NOTREACHED*/ } /* End parent */ /* This is the child */ initialize_modules (); /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( ! close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); cleanup (); exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; /* Unless we are running with a program given on the command * line we can assume that the inotify things works and thus * we can avoid the regular stat calls. */ if (!argc) reliable_homedir_inotify = 1; } { struct sigaction sa; sa.sa_handler = SIG_IGN; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sigaction (SIGPIPE, &sa, NULL); } #endif /*!HAVE_W32_SYSTEM*/ if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); exit (1); } log_info ("%s %s started\n", strusage(11), strusage(13) ); handle_connections (fd, fd_extra, fd_browser, fd_ssh); assuan_sock_close (fd); } return 0; } /* Exit entry point. This function should be called instead of a plain exit. */ void agent_exit (int rc) { /*FIXME: update_random_seed_file();*/ /* We run our cleanup handler because that may close cipher contexts stored in secure memory and thus this needs to be done before we explicitly terminate secure memory. */ cleanup (); #if 1 /* at this time a bit annoying */ if (opt.debug & DBG_MEMSTAT_VALUE) { gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); } if (opt.debug) gcry_control (GCRYCTL_DUMP_SECMEM_STATS ); #endif gcry_control (GCRYCTL_TERM_SECMEM ); rc = rc? rc : log_get_errorcount(0)? 2 : 0; exit (rc); } /* This is our callback function for gcrypt progress messages. It is set once at startup and dispatches progress messages to the corresponding threads of the agent. */ static void agent_libgcrypt_progress_cb (void *data, const char *what, int printchar, int current, int total) { struct progress_dispatch_s *dispatch; npth_t mytid = npth_self (); (void)data; for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) if (dispatch->ctrl && dispatch->tid == mytid) break; if (dispatch && dispatch->cb) dispatch->cb (dispatch->ctrl, what, printchar, current, total); /* Libgcrypt < 1.8 does not know about nPth and thus when it reads * from /dev/random this will block the process. To mitigate this * problem we yield the thread when Libgcrypt tells us that it needs * more entropy. This way other threads have chance to run. */ #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */ if (what && !strcmp (what, "need_entropy")) { #if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */ /* In older gpg-error versions gpgrt_yield is buggy for use with * nPth and thus we need to resort to a sleep call. */ npth_usleep (1000); /* 1ms */ #else gpgrt_yield (); #endif } #endif } /* If a progress dispatcher callback has been associated with the * current connection unregister it. */ static void unregister_progress_cb (void) { struct progress_dispatch_s *dispatch; npth_t mytid = npth_self (); for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) if (dispatch->ctrl && dispatch->tid == mytid) break; if (dispatch) { dispatch->ctrl = NULL; dispatch->cb = NULL; } } /* Setup a progress callback CB for the current connection. Using a * CB of NULL disables the callback. */ void agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total), ctrl_t ctrl) { struct progress_dispatch_s *dispatch, *firstfree; npth_t mytid = npth_self (); firstfree = NULL; for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) { if (dispatch->ctrl && dispatch->tid == mytid) break; if (!dispatch->ctrl && !firstfree) firstfree = dispatch; } if (!dispatch) /* None allocated: Reuse or allocate a new one. */ { if (firstfree) { dispatch = firstfree; } else if ((dispatch = xtrycalloc (1, sizeof *dispatch))) { dispatch->next = progress_dispatch_list; progress_dispatch_list = dispatch; } else { log_error ("error allocating new progress dispatcher slot: %s\n", gpg_strerror (gpg_error_from_syserror ())); return; } dispatch->ctrl = ctrl; dispatch->tid = mytid; } dispatch->cb = cb; } /* Each thread has its own local variables conveyed by a control structure usually identified by an argument named CTRL. This function is called immediately after allocating the control structure. Its purpose is to setup the default values for that structure. Note that some values may have already been set. */ static void agent_init_default_ctrl (ctrl_t ctrl) { log_assert (ctrl->session_env); /* Note we ignore malloc errors because we can't do much about it and the request will fail anyway shortly after this initialization. */ session_env_setenv (ctrl->session_env, "DISPLAY", default_display); session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname); session_env_setenv (ctrl->session_env, "TERM", default_ttytype); session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority); session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL); if (ctrl->lc_ctype) xfree (ctrl->lc_ctype); ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL; if (ctrl->lc_messages) xfree (ctrl->lc_messages); ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages) /**/ : NULL; ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET; } /* Release all resources allocated by default in the control structure. This is the counterpart to agent_init_default_ctrl. */ static void agent_deinit_default_ctrl (ctrl_t ctrl) { unregister_progress_cb (); session_env_release (ctrl->session_env); if (ctrl->lc_ctype) xfree (ctrl->lc_ctype); if (ctrl->lc_messages) xfree (ctrl->lc_messages); } /* Because the ssh protocol does not send us information about the current TTY setting, we use this function to use those from startup or those explicitly set. This is also used for the restricted mode where we ignore requests to change the environment. */ gpg_error_t agent_copy_startup_env (ctrl_t ctrl) { gpg_error_t err = 0; int iterator = 0; const char *name, *value; while (!err && (name = session_env_list_stdenvnames (&iterator, NULL))) { if ((value = session_env_getenv (opt.startup_env, name))) err = session_env_setenv (ctrl->session_env, name, value); } if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype) if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype))) err = gpg_error_from_syserror (); if (!err && !ctrl->lc_messages && opt.startup_lc_messages) if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages))) err = gpg_error_from_syserror (); if (err) log_error ("error setting default session environment: %s\n", gpg_strerror (err)); return err; } /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the PTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process' original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { ARGPARSE_ARGS pargs; FILE *fp; unsigned int configlineno = 0; int dummy; if (!config_filename) return; /* No config file. */ fp = fopen (config_filename, "r"); if (!fp) { log_info (_("option file '%s': %s\n"), config_filename, strerror(errno) ); return; } parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = 1; /* do not remove the args */ while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) ) { if (pargs.r_opt < -1) pargs.err = 1; /* Print a warning. */ else /* Try to parse this option - ignore unchangeable ones. */ parse_rereadable_options (&pargs, 1); } fclose (fp); finalize_rereadable_options (); set_debug (); } /* Return the file name of the socket we are using for native requests. */ const char * get_agent_socket_name (void) { const char *s = socket_name; return (s && *s)? s : NULL; } /* Return the file name of the socket we are using for SSH requests. */ const char * get_agent_ssh_socket_name (void) { const char *s = socket_name_ssh; return (s && *s)? s : NULL; } /* Return the number of active connections. */ int get_agent_active_connection_count (void) { return active_connections; } /* Under W32, this function returns the handle of the scdaemon notification event. Calling it the first time creates that event. */ #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) void * get_agent_scd_notify_event (void) { static HANDLE the_event = INVALID_HANDLE_VALUE; if (the_event == INVALID_HANDLE_VALUE) { HANDLE h, h2; SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE}; /* We need to use a manual reset event object due to the way our w32-pth wait function works: If we would use an automatic reset event we are not able to figure out which handle has been signaled because at the time we single out the signaled handles using WFSO the event has already been reset due to the WFMO. */ h = CreateEvent (&sa, TRUE, FALSE, NULL); if (!h) log_error ("can't create scd notify event: %s\n", w32_strerror (-1) ); else if (!DuplicateHandle (GetCurrentProcess(), h, GetCurrentProcess(), &h2, EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0)) { log_error ("setting synchronize for scd notify event failed: %s\n", w32_strerror (-1) ); CloseHandle (h); } else { CloseHandle (h); the_event = h2; } } return the_event; } #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/ /* Create a name for the socket in the home directory as using STANDARD_NAME. We also check for valid characters as well as against a maximum allowed length for a unix domain socket is done. The function terminates the process in case of an error. Returns: Pointer to an allocated string with the absolute name of the socket used. */ static char * create_socket_name (char *standard_name, int with_homedir) { char *name; if (with_homedir) name = make_filename (gnupg_socketdir (), standard_name, NULL); else name = make_filename (standard_name, NULL); if (strchr (name, PATHSEP_C)) { log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S); agent_exit (2); } return name; } /* Create a Unix domain socket with NAME. Returns the file descriptor or terminates the process in case of an error. Note that this function needs to be used for the regular socket first (indicated by PRIMARY) and only then for the extra and the ssh sockets. If the socket has been redirected the name of the real socket is stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a Cygwin compatible socket is created (Windows only). */ static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin, char **r_redir_name, assuan_sock_nonce_t *nonce) { struct sockaddr *addr; struct sockaddr_un *unaddr; socklen_t len; gnupg_fd_t fd; int rc; xfree (*r_redir_name); *r_redir_name = NULL; fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); *name = 0; /* Inhibit removal of the socket by cleanup(). */ agent_exit (2); } if (cygwin) assuan_sock_set_flag (fd, "cygwin", 1); unaddr = xmalloc (sizeof *unaddr); addr = (struct sockaddr*)unaddr; { int redirected; if (assuan_sock_set_sockaddr_un (name, addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), name); else log_error ("error preparing socket '%s': %s\n", name, gpg_strerror (gpg_error_from_syserror ())); *name = 0; /* Inhibit removal of the socket by cleanup(). */ xfree (unaddr); agent_exit (2); } if (redirected) { *r_redir_name = xstrdup (unaddr->sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name); } } len = SUN_LEN (unaddr); rc = assuan_sock_bind (fd, addr, len); /* Our error code mapping on W32CE returns EEXIST thus we also test for this. */ if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Check whether a gpg-agent is already running. We do this test only if this is the primary socket. For secondary sockets we assume that a test for gpg-agent has already been done and reuse the requested socket. Testing the ssh-socket is not possible because at this point, though we know the new Assuan socket, the Assuan server and thus the ssh-agent server is not yet operational; this would lead to a hang. */ if (primary && !check_for_running_agent (1)) { log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX); log_set_file (NULL); log_error (_("a gpg-agent is already running - " "not starting a new one\n")); *name = 0; /* Inhibit removal of the socket by cleanup(). */ assuan_sock_close (fd); xfree (unaddr); agent_exit (2); } gnupg_remove (unaddr->sun_path); rc = assuan_sock_bind (fd, addr, len); } if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { /* We use gpg_strerror here because it allows us to get strings for some W32 socket error codes. */ log_error (_("error binding socket to '%s': %s\n"), unaddr->sun_path, gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); *name = 0; /* Inhibit removal of the socket by cleanup(). */ xfree (unaddr); agent_exit (2); } if (gnupg_chmod (unaddr->sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), unaddr->sun_path, strerror (errno)); if (listen (FD2INT(fd), listen_backlog ) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); *name = 0; /* Inhibit removal of the socket by cleanup(). */ assuan_sock_close (fd); xfree (unaddr); agent_exit (2); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), unaddr->sun_path); xfree (unaddr); return fd; } /* Check that the directory for storing the private keys exists and create it if not. This function won't fail as it is only a convenience function and not strictly necessary. */ static void create_private_keys_directory (const char *home) { char *fname; struct stat statbuf; fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL); if (stat (fname, &statbuf) && errno == ENOENT) { if (gnupg_mkdir (fname, "-rwx")) log_error (_("can't create directory '%s': %s\n"), fname, strerror (errno) ); else if (!opt.quiet) log_info (_("directory '%s' created\n"), fname); } if (gnupg_chmod (fname, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), fname, strerror (errno)); xfree (fname); } /* Create the directory only if the supplied directory name is the same as the default one. This way we avoid to create arbitrary directories when a non-default home directory is used. To cope with HOME, we compare only the suffix if we see that the default homedir does start with a tilde. We don't stop here in case of problems because other functions will throw an error anyway.*/ static void create_directories (void) { struct stat statbuf; const char *defhome = standard_homedir (); char *home; home = make_filename (gnupg_homedir (), NULL); if ( stat (home, &statbuf) ) { if (errno == ENOENT) { if ( #ifdef HAVE_W32_SYSTEM ( !compare_filenames (home, defhome) ) #else (*defhome == '~' && (strlen (home) >= strlen (defhome+1) && !strcmp (home + strlen(home) - strlen (defhome+1), defhome+1))) || (*defhome != '~' && !strcmp (home, defhome) ) #endif ) { if (gnupg_mkdir (home, "-rwx")) log_error (_("can't create directory '%s': %s\n"), home, strerror (errno) ); else { if (!opt.quiet) log_info (_("directory '%s' created\n"), home); create_private_keys_directory (home); } } } else log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno)); } else if ( !S_ISDIR(statbuf.st_mode)) { log_error (_("can't use '%s' as home directory\n"), home); } else /* exists and is a directory. */ { create_private_keys_directory (home); } xfree (home); } /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { static time_t last_minute; struct stat statbuf; if (!last_minute) last_minute = time (NULL); /* If we are running as a child of another process, check whether the parent is still alive and shutdown if not. */ #ifndef HAVE_W32_SYSTEM if (parent_pid != (pid_t)(-1)) { if (kill (parent_pid, 0)) { shutdown_pending = 2; log_info ("parent process died - shutting down\n"); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); agent_exit (0); } } #endif /*HAVE_W32_SYSTEM*/ /* Code to be run from time to time. */ #if CHECK_OWN_SOCKET_INTERVAL > 0 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL)) { check_own_socket (); last_minute = time (NULL); } #endif /* Need to check for expired cache entries. */ agent_cache_housekeeping (); /* Check whether the homedir is still available. */ if (!shutdown_pending && (!have_homedir_inotify || !reliable_homedir_inotify) && stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* A global function which allows us to call the reload stuff from other places too. This is only used when build for W32. */ void agent_sighup_action (void) { log_info ("SIGHUP received - " "re-reading configuration and flushing cache\n"); agent_flush_cache (0); reread_configuration (); agent_reload_trustlist (); /* We flush the module name cache so that after installing a "pinentry" binary that one can be used in case the "pinentry-basic" fallback was in use. */ gnupg_module_name_flush_some (); if (opt.disable_scdaemon) agent_card_killscd (); } /* A helper function to handle SIGUSR2. */ static void agent_sigusr2_action (void) { if (opt.verbose) log_info ("SIGUSR2 received - updating card event counter\n"); /* Nothing to check right now. We only increment a counter. */ bump_card_eventcounter (); } #ifndef HAVE_W32_SYSTEM /* The signal handler for this program. It is expected to be run in its own thread and not in the context of a signal handler. */ static void handle_signal (int signo) { switch (signo) { #ifndef HAVE_W32_SYSTEM case SIGHUP: agent_sighup_action (); break; case SIGUSR1: log_info ("SIGUSR1 received - printing internal information:\n"); /* Fixme: We need to see how to integrate pth dumping into our logging system. */ /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */ agent_query_dump_state (); agent_scd_dump_state (); break; case SIGUSR2: agent_sigusr2_action (); break; case SIGTERM: if (!shutdown_pending) log_info ("SIGTERM received - shutting down ...\n"); else log_info ("SIGTERM received - still %i open connections\n", active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info ("shutdown forced\n"); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); agent_exit (0); } break; case SIGINT: log_info ("SIGINT received - immediate shutdown\n"); log_info( "%s %s stopped\n", strusage(11), strusage(13)); cleanup (); agent_exit (0); break; #endif default: log_info ("signal %d received - no action defined\n", signo); } } #endif /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT(ctrl->thread_startup.fd), strerror (errno)); assuan_sock_close (ctrl->thread_startup.fd); xfree (ctrl); return -1; } else return 0; } #ifdef HAVE_W32_SYSTEM /* The window message processing function for Putty. Warning: This code runs as a native Windows thread. Use of our own functions needs to be bracket with pth_leave/pth_enter. */ static LRESULT CALLBACK putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { int ret = 0; int w32rc; COPYDATASTRUCT *cds; const char *mapfile; HANDLE maphd; PSID mysid = NULL; PSID mapsid = NULL; void *data = NULL; PSECURITY_DESCRIPTOR psd = NULL; ctrl_t ctrl = NULL; if (msg != WM_COPYDATA) { return DefWindowProc (hwnd, msg, wparam, lparam); } cds = (COPYDATASTRUCT*)lparam; if (cds->dwData != PUTTY_IPC_MAGIC) return 0; /* Ignore data with the wrong magic. */ mapfile = cds->lpData; if (!cds->cbData || mapfile[cds->cbData - 1]) return 0; /* Ignore empty and non-properly terminated strings. */ if (DBG_IPC) { npth_protect (); log_debug ("ssh map file '%s'", mapfile); npth_unprotect (); } maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile); if (DBG_IPC) { npth_protect (); log_debug ("ssh map handle %p\n", maphd); npth_unprotect (); } if (!maphd || maphd == INVALID_HANDLE_VALUE) return 0; npth_protect (); mysid = w32_get_user_sid (); if (!mysid) { log_error ("error getting my sid\n"); goto leave; } w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, &mapsid, NULL, NULL, NULL, &psd); if (w32rc) { log_error ("error getting sid of ssh map file: rc=%d", w32rc); goto leave; } if (DBG_IPC) { char *sidstr; if (!ConvertSidToStringSid (mysid, &sidstr)) sidstr = NULL; log_debug (" my sid: '%s'", sidstr? sidstr: "[error]"); LocalFree (sidstr); if (!ConvertSidToStringSid (mapsid, &sidstr)) sidstr = NULL; log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]"); LocalFree (sidstr); } if (!EqualSid (mysid, mapsid)) { log_error ("ssh map file has a non-matching sid\n"); goto leave; } data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (DBG_IPC) log_debug ("ssh IPC buffer at %p\n", data); if (!data) goto leave; /* log_printhex ("request:", data, 20); */ ctrl = xtrycalloc (1, sizeof *ctrl); if (!ctrl) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); goto leave; } ctrl->session_env = session_env_new (); if (!ctrl->session_env) { log_error ("error allocating session environment block: %s\n", strerror (errno) ); goto leave; } agent_init_default_ctrl (ctrl); if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN)) ret = 1; /* Valid ssh message has been constructed. */ agent_deinit_default_ctrl (ctrl); /* log_printhex (" reply:", data, 20); */ leave: xfree (ctrl); if (data) UnmapViewOfFile (data); xfree (mapsid); if (psd) LocalFree (psd); xfree (mysid); CloseHandle (maphd); npth_unprotect (); return ret; } #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_W32_SYSTEM /* The thread handling Putty's IPC requests. */ static void * putty_message_thread (void *arg) { WNDCLASS wndwclass = {0, putty_message_proc, 0, 0, NULL, NULL, NULL, NULL, NULL, "Pageant"}; HWND hwnd; MSG msg; (void)arg; if (opt.verbose) log_info ("putty message loop thread started\n"); /* The message loop runs as thread independent from our nPth system. This also means that we need to make sure that we switch back to our system before calling any no-windows function. */ npth_unprotect (); /* First create a window to make sure that a message queue exists for this thread. */ if (!RegisterClass (&wndwclass)) { npth_protect (); log_error ("error registering Pageant window class"); return NULL; } hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0, 0, 0, 0, 0, HWND_MESSAGE, /* hWndParent */ NULL, /* hWndMenu */ NULL, /* hInstance */ NULL); /* lpParm */ if (!hwnd) { npth_protect (); log_error ("error creating Pageant window"); return NULL; } while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* Back to nPth. */ npth_protect (); if (opt.verbose) log_info ("putty message loop thread stopped\n"); return NULL; } #endif /*HAVE_W32_SYSTEM*/ static void * do_start_connection_thread (ctrl_t ctrl) { active_connections++; agent_init_default_ctrl (ctrl); if (opt.verbose && !DBG_IPC) log_info (_("handler 0x%lx for fd %d started\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd); if (opt.verbose && !DBG_IPC) log_info (_("handler 0x%lx for fd %d terminated\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); agent_deinit_default_ctrl (ctrl); xfree (ctrl); active_connections--; return NULL; } /* This is the standard connection thread's main function. */ static void * start_connection_thread_std (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } return do_start_connection_thread (ctrl); } /* This is the extra socket connection thread's main function. */ static void * start_connection_thread_extra (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_extra)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } ctrl->restricted = 1; return do_start_connection_thread (ctrl); } /* This is the browser socket connection thread's main function. */ static void * start_connection_thread_browser (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_browser)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } ctrl->restricted = 2; return do_start_connection_thread (ctrl); } /* This is the ssh connection thread's main function. */ static void * start_connection_thread_ssh (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_ssh)) return NULL; active_connections++; agent_init_default_ctrl (ctrl); if (opt.verbose) log_info (_("ssh handler 0x%lx for fd %d started\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); start_command_handler_ssh (ctrl, ctrl->thread_startup.fd); if (opt.verbose) log_info (_("ssh handler 0x%lx for fd %d terminated\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); agent_deinit_default_ctrl (ctrl); xfree (ctrl); active_connections--; return NULL; } /* Connection handler loop. Wait for connection requests and spawn a thread after accepting a connection. */ static void handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_extra, gnupg_fd_t listen_fd_browser, gnupg_fd_t listen_fd_ssh) { gpg_error_t err; npth_attr_t tattr; struct sockaddr_un paddr; socklen_t plen; fd_set fdset, read_fdset; int ret; gnupg_fd_t fd; int nfd; int saved_errno; struct timespec abstime; struct timespec curtime; struct timespec timeout; #ifdef HAVE_W32_SYSTEM HANDLE events[2]; unsigned int events_set; #endif int sock_inotify_fd = -1; int home_inotify_fd = -1; struct { const char *name; void *(*func) (void *arg); gnupg_fd_t l_fd; } listentbl[] = { { "std", start_connection_thread_std }, { "extra", start_connection_thread_extra }, { "browser", start_connection_thread_browser }, { "ssh", start_connection_thread_ssh } }; ret = npth_attr_init(&tattr); if (ret) log_fatal ("error allocating thread attributes: %s\n", strerror (ret)); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #else # ifdef HAVE_W32CE_SYSTEM /* Use a dummy event. */ sigs = 0; ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo); # else events[0] = get_agent_scd_notify_event (); events[1] = INVALID_HANDLE_VALUE; # endif #endif if (disable_check_own_socket) sock_inotify_fd = -1; else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name))) { if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED) log_info ("error enabling daemon termination by socket removal: %s\n", gpg_strerror (err)); } if (disable_check_own_socket) home_inotify_fd = -1; else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd, gnupg_homedir ()))) { if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED) log_info ("error enabling daemon termination by homedir removal: %s\n", gpg_strerror (err)); } else have_homedir_inotify = 1; /* On Windows we need to fire up a separate thread to listen for requests from Putty (an SSH client), so we can replace Putty's Pageant (its ssh-agent implementation). */ #ifdef HAVE_W32_SYSTEM if (putty_support) { npth_t thread; ret = npth_create (&thread, &tattr, putty_message_thread, NULL); if (ret) { log_error ("error spawning putty message loop: %s\n", strerror (ret)); } } #endif /*HAVE_W32_SYSTEM*/ /* Set a flag to tell call-scd.c that it may enable event notifications. */ opt.sigusr2_enabled = 1; FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (listen_fd_extra != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_extra), &fdset); if (FD2INT (listen_fd_extra) > nfd) nfd = FD2INT (listen_fd_extra); } if (listen_fd_browser != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_browser), &fdset); if (FD2INT (listen_fd_browser) > nfd) nfd = FD2INT (listen_fd_browser); } if (listen_fd_ssh != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_ssh), &fdset); if (FD2INT (listen_fd_ssh) > nfd) nfd = FD2INT (listen_fd_ssh); } if (sock_inotify_fd != -1) { FD_SET (sock_inotify_fd, &fdset); if (sock_inotify_fd > nfd) nfd = sock_inotify_fd; } if (home_inotify_fd != -1) { FD_SET (home_inotify_fd, &fdset); if (home_inotify_fd > nfd) nfd = home_inotify_fd; } listentbl[0].l_fd = listen_fd; listentbl[1].l_fd = listen_fd_extra; listentbl[2].l_fd = listen_fd_browser; listentbl[3].l_fd = listen_fd_ssh; npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (active_connections == 0) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ FD_ZERO (&fdset); nfd = -1; if (sock_inotify_fd != -1) { FD_SET (sock_inotify_fd, &fdset); nfd = sock_inotify_fd; } if (home_inotify_fd != -1) { FD_SET (home_inotify_fd, &fdset); if (home_inotify_fd > nfd) nfd = home_inotify_fd; } } /* POSIX says that fd_set should be implemented as a structure, thus a simple assignment is fine to copy the entire set. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask ()); saved_errno = errno; { int signo; while (npth_sigev_get_pending (&signo)) handle_signal (signo); } #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, events, &events_set); saved_errno = errno; /* This is valid even if npth_eselect returns an error. */ if (events_set & 1) agent_sigusr2_action (); #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; /* The inotify fds are set even when a shutdown is pending (see * above). So we must handle them in any case. To avoid that * they trigger a second time we close them immediately. */ if (sock_inotify_fd != -1 && FD_ISSET (sock_inotify_fd, &read_fdset) && gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME)) { shutdown_pending = 1; close (sock_inotify_fd); sock_inotify_fd = -1; log_info ("socket file has been removed - shutting down\n"); } if (home_inotify_fd != -1 && FD_ISSET (home_inotify_fd, &read_fdset)) { shutdown_pending = 1; close (home_inotify_fd); home_inotify_fd = -1; log_info ("homedir has been removed - shutting down\n"); } if (!shutdown_pending) { int idx; ctrl_t ctrl; npth_t thread; for (idx=0; idx < DIM(listentbl); idx++) { if (listentbl[idx].l_fd == GNUPG_INVALID_FD) continue; if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset)) continue; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed for %s: %s\n", listentbl[idx].name, strerror (errno)); } else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl))) { log_error ("error allocating connection data for %s: %s\n", listentbl[idx].name, strerror (errno) ); assuan_sock_close (fd); } else if ( !(ctrl->session_env = session_env_new ())) { log_error ("error allocating session env block for %s: %s\n", listentbl[idx].name, strerror (errno) ); xfree (ctrl); assuan_sock_close (fd); } else { ctrl->thread_startup.fd = fd; ret = npth_create (&thread, &tattr, listentbl[idx].func, ctrl); if (ret) { log_error ("error spawning connection handler for %s:" " %s\n", listentbl[idx].name, strerror (ret)); assuan_sock_close (fd); xfree (ctrl); } } } } } if (sock_inotify_fd != -1) close (sock_inotify_fd); if (home_inotify_fd != -1) close (home_inotify_fd); cleanup (); log_info (_("%s %s stopped\n"), strusage(11), strusage(13)); npth_attr_destroy (&tattr); } /* Helper for check_own_socket. */ static gpg_error_t check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length) { membuf_t *mb = opaque; put_membuf (mb, buffer, length); return 0; } /* The thread running the actual check. We need to run this in a separate thread so that check_own_thread can be called from the timer tick. */ static void * check_own_socket_thread (void *arg) { int rc; char *sockname = arg; assuan_context_t ctx = NULL; membuf_t mb; char *buffer; check_own_socket_running++; rc = assuan_new (&ctx); if (rc) { log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc)); goto leave; } assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1); rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0); if (rc) { log_error ("can't connect my own socket: %s\n", gpg_strerror (rc)); goto leave; } init_membuf (&mb, 100); rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb, NULL, NULL, NULL, NULL); put_membuf (&mb, "", 1); buffer = get_membuf (&mb, NULL); if (rc || !buffer) { log_error ("sending command \"%s\" to my own socket failed: %s\n", "GETINFO pid", gpg_strerror (rc)); rc = 1; } else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ()) { log_error ("socket is now serviced by another server\n"); rc = 1; } else if (opt.verbose > 1) log_error ("socket is still served by this server\n"); xfree (buffer); leave: xfree (sockname); if (ctx) assuan_release (ctx); if (rc) { /* We may not remove the socket as it is now in use by another server. */ inhibit_socket_removal = 1; shutdown_pending = 2; log_info ("this process is useless - shutting down\n"); } check_own_socket_running--; return NULL; } /* Check whether we are still listening on our own socket. In case another gpg-agent process started after us has taken ownership of our socket, we would linger around without any real task. Thus we better check once in a while whether we are really needed. */ static void check_own_socket (void) { char *sockname; npth_t thread; npth_attr_t tattr; int err; if (disable_check_own_socket) return; if (check_own_socket_running || shutdown_pending) return; /* Still running or already shutting down. */ sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); if (!sockname) return; /* Out of memory. */ err = npth_attr_init (&tattr); if (err) return; npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, check_own_socket_thread, sockname); if (err) log_error ("error spawning check_own_socket_thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } /* Figure out whether an agent is available and running. Prints an error if not. If SILENT is true, no messages are printed. Returns 0 if the agent is running. */ static int check_for_running_agent (int silent) { gpg_error_t err; char *sockname; assuan_context_t ctx = NULL; sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); if (!sockname) return gpg_error_from_syserror (); err = assuan_new (&ctx); if (!err) err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0); xfree (sockname); if (err) { if (!silent) log_error (_("no gpg-agent running in this session\n")); if (ctx) assuan_release (ctx); return -1; } if (!opt.quiet && !silent) log_info ("gpg-agent running and available\n"); assuan_release (ctx); return 0; } diff --git a/agent/preset-passphrase.c b/agent/preset-passphrase.c index e22e9d58d..7b322a0b7 100644 --- a/agent/preset-passphrase.c +++ b/agent/preset-passphrase.c @@ -1,266 +1,267 @@ /* preset-passphrase.c - A tool to preset a passphrase. * Copyright (C) 2004 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 #ifdef HAVE_LOCALE_H #include #endif #ifdef HAVE_LANGINFO_CODESET #include #endif #ifdef HAVE_DOSISH_SYSTEM #include /* for setmode() */ #endif #ifdef HAVE_W32_SYSTEM # ifdef HAVE_WINSOCK2_H # include # endif # include /* To initialize the sockets. fixme */ #endif +#define INCLUDED_BY_MAIN_MODULE 1 #include "agent.h" #include "../common/simple-pwquery.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oVerbose = 'v', oPassphrase = 'P', oPreset = 'c', oForget = 'f', oNoVerbose = 500, oHomedir, aTest }; static const char *opt_passphrase; static ARGPARSE_OPTS opts[] = { { 301, NULL, 0, N_("@Options:\n ") }, { oVerbose, "verbose", 0, "verbose" }, { oPassphrase, "passphrase", 2, "|STRING|use passphrase STRING" }, { oPreset, "preset", 256, "preset passphrase"}, { oForget, "forget", 256, "forget passphrase"}, { oHomedir, "homedir", 2, "@" }, ARGPARSE_end () }; static const char * my_strusage (int level) { const char *p; switch (level) { case 11: p = "gpg-preset-passphrase (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: gpg-preset-passphrase [options] KEYGRIP (-h for help)\n"); break; case 41: p = _("Syntax: gpg-preset-passphrase [options] KEYGRIP\n" "Password cache maintenance\n"); break; default: p = NULL; } return p; } static void preset_passphrase (const char *keygrip) { int rc; char *line; /* FIXME: Use secure memory. */ char passphrase[500]; char *passphrase_esc; if (!opt_passphrase) { rc = read (0, passphrase, sizeof (passphrase) - 1); if (rc < 0) { log_error ("reading passphrase failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); return; } passphrase[rc] = '\0'; line = strchr (passphrase, '\n'); if (line) { if (line > passphrase && line[-1] == '\r') line--; *line = '\0'; } /* FIXME: How to handle empty passwords? */ } { const char *s = opt_passphrase ? opt_passphrase : passphrase; passphrase_esc = bin2hex (s, strlen (s), NULL); } if (!passphrase_esc) { log_error ("can not escape string: %s\n", gpg_strerror (gpg_error_from_syserror ())); return; } rc = asprintf (&line, "PRESET_PASSPHRASE %s -1 %s\n", keygrip, passphrase_esc); wipememory (passphrase_esc, strlen (passphrase_esc)); xfree (passphrase_esc); if (rc < 0) { log_error ("caching passphrase failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); return; } if (!opt_passphrase) wipememory (passphrase, sizeof (passphrase)); rc = simple_query (line); if (rc) { log_error ("caching passphrase failed: %s\n", gpg_strerror (rc)); return; } wipememory (line, strlen (line)); xfree (line); } static void forget_passphrase (const char *keygrip) { int rc; char *line; rc = asprintf (&line, "CLEAR_PASSPHRASE %s\n", keygrip); if (rc < 0) rc = gpg_error_from_syserror (); else rc = simple_query (line); if (rc) { log_error ("clearing passphrase failed: %s\n", gpg_strerror (rc)); return; } xfree (line); } int main (int argc, char **argv) { ARGPARSE_ARGS pargs; int cmd = 0; const char *keygrip = NULL; early_system_init (); set_strusage (my_strusage); log_set_prefix ("gpg-preset-passphrase", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* (do not remove the args) */ while (arg_parse (&pargs, opts) ) { switch (pargs.r_opt) { case oVerbose: opt.verbose++; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oPreset: cmd = oPreset; break; case oForget: cmd = oForget; break; case oPassphrase: opt_passphrase = pargs.r.ret_str; break; default : pargs.err = 2; break; } } if (log_get_errorcount(0)) exit(2); if (argc == 1) keygrip = *argv; else usage (1); /* Tell simple-pwquery about the standard socket name. */ { char *tmp = make_filename (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); simple_pw_set_socket (tmp); xfree (tmp); } if (cmd == oPreset) preset_passphrase (keygrip); else if (cmd == oForget) forget_passphrase (keygrip); else log_error ("one of the options --preset or --forget must be given\n"); agent_exit (0); return 8; /*NOTREACHED*/ } void agent_exit (int rc) { rc = rc? rc : log_get_errorcount(0)? 2 : 0; exit (rc); } diff --git a/agent/protect-tool.c b/agent/protect-tool.c index 059a9bdbd..4a307abc2 100644 --- a/agent/protect-tool.c +++ b/agent/protect-tool.c @@ -1,822 +1,823 @@ /* protect-tool.c - A tool to test the secret key protection * Copyright (C) 2002, 2003, 2004, 2006 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 #ifdef HAVE_LOCALE_H #include #endif #ifdef HAVE_LANGINFO_CODESET #include #endif #ifdef HAVE_DOSISH_SYSTEM #include /* for setmode() */ #endif +#define INCLUDED_BY_MAIN_MODULE 1 #include "agent.h" #include "../common/i18n.h" #include "../common/get-passphrase.h" #include "../common/sysutils.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oVerbose = 'v', oArmor = 'a', oPassphrase = 'P', oProtect = 'p', oUnprotect = 'u', oNoVerbose = 500, oShadow, oShowShadowInfo, oShowKeygrip, oS2Kcalibration, oCanonical, oStore, oForce, oHaveCert, oNoFailOnExist, oHomedir, oPrompt, oStatusMsg, oDebugUseOCB, oAgentProgram }; struct rsa_secret_key_s { gcry_mpi_t n; /* public modulus */ gcry_mpi_t e; /* public exponent */ gcry_mpi_t d; /* exponent */ gcry_mpi_t p; /* prime p. */ gcry_mpi_t q; /* prime q. */ gcry_mpi_t u; /* inverse of p mod q. */ }; static int opt_armor; static int opt_canonical; static int opt_store; static int opt_force; static int opt_no_fail_on_exist; static int opt_have_cert; static const char *opt_passphrase; static char *opt_prompt; static int opt_status_msg; static const char *opt_agent_program; static int opt_debug_use_ocb; static char *get_passphrase (int promptno); static void release_passphrase (char *pw); static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (oProtect, "protect", "protect a private key"), ARGPARSE_c (oUnprotect, "unprotect", "unprotect a private key"), ARGPARSE_c (oShadow, "shadow", "create a shadow entry for a public key"), ARGPARSE_c (oShowShadowInfo, "show-shadow-info", "return the shadow info"), ARGPARSE_c (oShowKeygrip, "show-keygrip", "show the \"keygrip\""), ARGPARSE_c (oS2Kcalibration, "s2k-calibration", "@"), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", "verbose"), ARGPARSE_s_n (oArmor, "armor", "write output in advanced format"), ARGPARSE_s_n (oCanonical, "canonical", "write output in canonical format"), ARGPARSE_s_s (oPassphrase, "passphrase", "|STRING|use passphrase STRING"), ARGPARSE_s_n (oHaveCert, "have-cert", "certificate to export provided on STDIN"), ARGPARSE_s_n (oStore, "store", "store the created key in the appropriate place"), ARGPARSE_s_n (oForce, "force", "force overwriting"), ARGPARSE_s_n (oNoFailOnExist, "no-fail-on-exist", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oPrompt, "prompt", "|ESCSTRING|use ESCSTRING as prompt in pinentry"), ARGPARSE_s_n (oStatusMsg, "enable-status-msg", "@"), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_n (oDebugUseOCB, "debug-use-ocb", "@"), /* For hacking only. */ ARGPARSE_end () }; static const char * my_strusage (int level) { const char *p; switch (level) { case 11: p = "gpg-protect-tool (" GNUPG_NAME ")"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: gpg-protect-tool [options] (-h for help)\n"); break; case 41: p = _("Syntax: gpg-protect-tool [options] [args]\n" "Secret key maintenance tool\n"); break; default: p = NULL; } return p; } /* static void */ /* print_mpi (const char *text, gcry_mpi_t a) */ /* { */ /* char *buf; */ /* void *bufaddr = &buf; */ /* int rc; */ /* rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, bufaddr, NULL, a); */ /* if (rc) */ /* log_info ("%s: [error printing number: %s]\n", text, gpg_strerror (rc)); */ /* else */ /* { */ /* log_info ("%s: %s\n", text, buf); */ /* gcry_free (buf); */ /* } */ /* } */ static unsigned char * make_canonical (const char *fname, const char *buf, size_t buflen) { int rc; size_t erroff, len; gcry_sexp_t sexp; unsigned char *result; rc = gcry_sexp_sscan (&sexp, &erroff, buf, buflen); if (rc) { log_error ("invalid S-Expression in '%s' (off=%u): %s\n", fname, (unsigned int)erroff, gpg_strerror (rc)); return NULL; } len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0); log_assert (len); result = xmalloc (len); len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, result, len); log_assert (len); gcry_sexp_release (sexp); return result; } static char * make_advanced (const unsigned char *buf, size_t buflen) { int rc; size_t erroff, len; gcry_sexp_t sexp; char *result; rc = gcry_sexp_sscan (&sexp, &erroff, (const char*)buf, buflen); if (rc) { log_error ("invalid canonical S-Expression (off=%u): %s\n", (unsigned int)erroff, gpg_strerror (rc)); return NULL; } len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0); log_assert (len); result = xmalloc (len); len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, result, len); log_assert (len); gcry_sexp_release (sexp); return result; } static char * read_file (const char *fname, size_t *r_length) { FILE *fp; char *buf; size_t buflen; if (!strcmp (fname, "-")) { size_t nread, bufsize = 0; fp = stdin; #ifdef HAVE_DOSISH_SYSTEM setmode ( fileno(fp) , O_BINARY ); #endif buf = NULL; buflen = 0; #define NCHUNK 8192 do { bufsize += NCHUNK; if (!buf) buf = xmalloc (bufsize); else buf = xrealloc (buf, bufsize); nread = fread (buf+buflen, 1, NCHUNK, fp); if (nread < NCHUNK && ferror (fp)) { log_error ("error reading '[stdin]': %s\n", strerror (errno)); xfree (buf); return NULL; } buflen += nread; } while (nread == NCHUNK); #undef NCHUNK } else { struct stat st; fp = fopen (fname, "rb"); if (!fp) { log_error ("can't open '%s': %s\n", fname, strerror (errno)); return NULL; } if (fstat (fileno(fp), &st)) { log_error ("can't stat '%s': %s\n", fname, strerror (errno)); fclose (fp); return NULL; } buflen = st.st_size; buf = xmalloc (buflen+1); if (fread (buf, buflen, 1, fp) != 1) { log_error ("error reading '%s': %s\n", fname, strerror (errno)); fclose (fp); xfree (buf); return NULL; } fclose (fp); } *r_length = buflen; return buf; } static unsigned char * read_key (const char *fname) { char *buf; size_t buflen; unsigned char *key; buf = read_file (fname, &buflen); if (!buf) return NULL; key = make_canonical (fname, buf, buflen); xfree (buf); return key; } static void read_and_protect (const char *fname) { int rc; unsigned char *key; unsigned char *result; size_t resultlen; char *pw; key = read_key (fname); if (!key) return; pw = get_passphrase (1); rc = agent_protect (key, pw, &result, &resultlen, 0, opt_debug_use_ocb? 1 : -1); release_passphrase (pw); xfree (key); if (rc) { log_error ("protecting the key failed: %s\n", gpg_strerror (rc)); return; } if (opt_armor) { char *p = make_advanced (result, resultlen); xfree (result); if (!p) return; result = (unsigned char*)p; resultlen = strlen (p); } fwrite (result, resultlen, 1, stdout); xfree (result); } static void read_and_unprotect (ctrl_t ctrl, const char *fname) { int rc; unsigned char *key; unsigned char *result; size_t resultlen; char *pw; gnupg_isotime_t protected_at; key = read_key (fname); if (!key) return; rc = agent_unprotect (ctrl, key, (pw=get_passphrase (1)), protected_at, &result, &resultlen); release_passphrase (pw); xfree (key); if (rc) { if (opt_status_msg) log_info ("[PROTECT-TOOL:] bad-passphrase\n"); log_error ("unprotecting the key failed: %s\n", gpg_strerror (rc)); return; } if (opt.verbose) { if (*protected_at) log_info ("key protection done at %.4s-%.2s-%.2s %.2s:%.2s:%s\n", protected_at, protected_at+4, protected_at+6, protected_at+9, protected_at+11, protected_at+13); else log_info ("key protection done at [unknown]\n"); } if (opt_armor) { char *p = make_advanced (result, resultlen); xfree (result); if (!p) return; result = (unsigned char*)p; resultlen = strlen (p); } fwrite (result, resultlen, 1, stdout); xfree (result); } static void read_and_shadow (const char *fname) { int rc; unsigned char *key; unsigned char *result; size_t resultlen; unsigned char dummy_info[] = "(8:313233342:43)"; key = read_key (fname); if (!key) return; rc = agent_shadow_key (key, dummy_info, &result); xfree (key); if (rc) { log_error ("shadowing the key failed: %s\n", gpg_strerror (rc)); return; } resultlen = gcry_sexp_canon_len (result, 0, NULL,NULL); log_assert (resultlen); if (opt_armor) { char *p = make_advanced (result, resultlen); xfree (result); if (!p) return; result = (unsigned char*)p; resultlen = strlen (p); } fwrite (result, resultlen, 1, stdout); xfree (result); } static void show_shadow_info (const char *fname) { int rc; unsigned char *key; const unsigned char *info; size_t infolen; key = read_key (fname); if (!key) return; rc = agent_get_shadow_info (key, &info); xfree (key); if (rc) { log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc)); return; } infolen = gcry_sexp_canon_len (info, 0, NULL,NULL); log_assert (infolen); if (opt_armor) { char *p = make_advanced (info, infolen); if (!p) return; fwrite (p, strlen (p), 1, stdout); xfree (p); } else fwrite (info, infolen, 1, stdout); } static void show_file (const char *fname) { unsigned char *key; size_t keylen; char *p; key = read_key (fname); if (!key) return; keylen = gcry_sexp_canon_len (key, 0, NULL,NULL); log_assert (keylen); if (opt_canonical) { fwrite (key, keylen, 1, stdout); } else { p = make_advanced (key, keylen); if (p) { fwrite (p, strlen (p), 1, stdout); xfree (p); } } xfree (key); } static void show_keygrip (const char *fname) { unsigned char *key; gcry_sexp_t private; unsigned char grip[20]; int i; key = read_key (fname); if (!key) return; if (gcry_sexp_new (&private, key, 0, 0)) { log_error ("gcry_sexp_new failed\n"); return; } xfree (key); if (!gcry_pk_get_keygrip (private, grip)) { log_error ("can't calculate keygrip\n"); return; } gcry_sexp_release (private); for (i=0; i < 20; i++) printf ("%02X", grip[i]); putchar ('\n'); } int main (int argc, char **argv ) { ARGPARSE_ARGS pargs; int cmd = 0; const char *fname; ctrl_t ctrl; early_system_init (); set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); log_set_prefix ("gpg-protect-tool", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); setup_libgcrypt_logging (); gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* (do not remove the args) */ while (arg_parse (&pargs, opts) ) { switch (pargs.r_opt) { case oVerbose: opt.verbose++; break; case oArmor: opt_armor=1; break; case oCanonical: opt_canonical=1; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oAgentProgram: opt_agent_program = pargs.r.ret_str; break; case oProtect: cmd = oProtect; break; case oUnprotect: cmd = oUnprotect; break; case oShadow: cmd = oShadow; break; case oShowShadowInfo: cmd = oShowShadowInfo; break; case oShowKeygrip: cmd = oShowKeygrip; break; case oS2Kcalibration: cmd = oS2Kcalibration; break; case oPassphrase: opt_passphrase = pargs.r.ret_str; break; case oStore: opt_store = 1; break; case oForce: opt_force = 1; break; case oNoFailOnExist: opt_no_fail_on_exist = 1; break; case oHaveCert: opt_have_cert = 1; break; case oPrompt: opt_prompt = pargs.r.ret_str; break; case oStatusMsg: opt_status_msg = 1; break; case oDebugUseOCB: opt_debug_use_ocb = 1; break; default: pargs.err = ARGPARSE_PRINT_ERROR; break; } } if (log_get_errorcount (0)) exit (2); fname = "-"; if (argc == 1) fname = *argv; else if (argc > 1) usage (1); /* Allocate an CTRL object. An empty object should be sufficient. */ ctrl = xtrycalloc (1, sizeof *ctrl); if (!ctrl) { log_error ("error allocating connection control data: %s\n", strerror (errno)); agent_exit (1); } /* Set the information which can't be taken from envvars. */ gnupg_prepare_get_passphrase (GPG_ERR_SOURCE_DEFAULT, opt.verbose, opt_agent_program, NULL, NULL, NULL); if (opt_prompt) opt_prompt = percent_plus_unescape (opt_prompt, 0); if (cmd == oProtect) read_and_protect (fname); else if (cmd == oUnprotect) read_and_unprotect (ctrl, fname); else if (cmd == oShadow) read_and_shadow (fname); else if (cmd == oShowShadowInfo) show_shadow_info (fname); else if (cmd == oShowKeygrip) show_keygrip (fname); else if (cmd == oS2Kcalibration) { if (!opt.verbose) opt.verbose++; /* We need to see something. */ get_standard_s2k_count (); } else show_file (fname); xfree (ctrl); agent_exit (0); return 8; /*NOTREACHED*/ } void agent_exit (int rc) { rc = rc? rc : log_get_errorcount(0)? 2 : 0; exit (rc); } /* Return the passphrase string and ask the agent if it has not been set from the command line PROMPTNO select the prompt to display: 0 = default 1 = taken from the option --prompt 2 = for unprotecting a pkcs#12 object 3 = for protecting a new pkcs#12 object 4 = for protecting an imported pkcs#12 in our system */ static char * get_passphrase (int promptno) { char *pw; int err; const char *desc; char *orig_codeset; int repeat = 0; if (opt_passphrase) return xstrdup (opt_passphrase); orig_codeset = i18n_switchto_utf8 (); if (promptno == 1 && opt_prompt) { desc = opt_prompt; } else if (promptno == 2) { desc = _("Please enter the passphrase to unprotect the " "PKCS#12 object."); } else if (promptno == 3) { desc = _("Please enter the passphrase to protect the " "new PKCS#12 object."); repeat = 1; } else if (promptno == 4) { desc = _("Please enter the passphrase to protect the " "imported object within the GnuPG system."); repeat = 1; } else desc = _("Please enter the passphrase or the PIN\n" "needed to complete this operation."); i18n_switchback (orig_codeset); err = gnupg_get_passphrase (NULL, NULL, _("Passphrase:"), desc, repeat, repeat, 1, &pw); if (err) { if (gpg_err_code (err) == GPG_ERR_CANCELED || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED) log_info (_("cancelled\n")); else log_error (_("error while asking for the passphrase: %s\n"), gpg_strerror (err)); agent_exit (0); } log_assert (pw); return pw; } static void release_passphrase (char *pw) { if (pw) { wipememory (pw, strlen (pw)); xfree (pw); } } /* Stub function. */ int agent_key_available (const unsigned char *grip) { (void)grip; return -1; /* Not available. */ } char * agent_get_cache (ctrl_t ctrl, const char *key, cache_mode_t cache_mode) { (void)ctrl; (void)key; (void)cache_mode; return NULL; } gpg_error_t agent_askpin (ctrl_t ctrl, const char *desc_text, const char *prompt_text, const char *initial_errtext, struct pin_entry_info_s *pininfo, const char *keyinfo, cache_mode_t cache_mode) { gpg_error_t err; unsigned char *passphrase; size_t size; (void)ctrl; (void)desc_text; (void)prompt_text; (void)initial_errtext; (void)keyinfo; (void)cache_mode; *pininfo->pin = 0; /* Reset the PIN. */ passphrase = get_passphrase (0); size = strlen (passphrase); if (size >= pininfo->max_length) return gpg_error (GPG_ERR_TOO_LARGE); memcpy (&pininfo->pin, passphrase, size); xfree (passphrase); pininfo->pin[size] = 0; if (pininfo->check_cb) { /* More checks by utilizing the optional callback. */ pininfo->cb_errtext = NULL; err = pininfo->check_cb (pininfo); } else err = 0; return err; } /* Replacement for the function in findkey.c. Here we write the key * to stdout. */ int agent_write_private_key (const unsigned char *grip, const void *buffer, size_t length, int force, const char *serialno, const char *keyref) { char hexgrip[40+4+1]; char *p; (void)force; (void)serialno; (void)keyref; bin2hex (grip, 20, hexgrip); strcpy (hexgrip+40, ".key"); p = make_advanced (buffer, length); if (p) { printf ("# Begin dump of %s\n%s%s# End dump of %s\n", hexgrip, p, (*p && p[strlen(p)-1] == '\n')? "":"\n", hexgrip); xfree (p); } return 0; } diff --git a/agent/t-protect.c b/agent/t-protect.c index d17c19325..88b552585 100644 --- a/agent/t-protect.c +++ b/agent/t-protect.c @@ -1,350 +1,351 @@ /* t-protect.c - Module tests for protect.c * Copyright (C) 2005 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 +#define INCLUDED_BY_MAIN_MODULE 1 #include "agent.h" #define pass() do { ; } while(0) #define fail() do { fprintf (stderr, "%s:%d: test failed\n",\ __FILE__,__LINE__); \ exit (1); \ } while(0) static void test_agent_protect (void) { /* Protect the key encoded in canonical format in PLAINKEY. We assume a valid S-Exp here. */ unsigned int i; int ret; struct key_spec { const char *string; }; /* Valid RSA key. */ struct key_spec key_rsa_valid = { "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73" "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xB6\xB5\x09\x59\x6A\x9E\xCA\xBC\x93\x92" "\x12\xF8\x91\xE6\x56\xA6\x26\xBA\x07\xDA\x85\x21\xA9\xCA\xD4\xC0\x8E\x64\x0C\x04" "\x05\x2F\xBB\x87\xF4\x24\xEF\x1A\x02\x75\xA4\x8A\x92\x99\xAC\x9D\xB6\x9A\xBE\x3D" "\x01\x24\xE6\xC7\x56\xB1\xF7\xDF\xB9\xB8\x42\xD6\x25\x1A\xEA\x6E\xE8\x53\x90\x49" "\x5C\xAD\xA7\x3D\x67\x15\x37\xFC\xE5\x85\x0A\x93\x2F\x32\xBA\xB6\x0A\xB1\xAC\x1F" "\x85\x2C\x1F\x83\xC6\x25\xE7\xA7\xD7\x0C\xDA\x9E\xF1\x6D\x5C\x8E\x47\x73\x9D\x77" "\xDF\x59\x26\x1A\xBE\x84\x54\x80\x7F\xF4\x41\xE1\x43\xFB\xD3\x7F\x85\x45\x29\x28" "\x31\x3A\x65\x33\x3A\x01\x00\x01\x29\x28\x31\x3A\x64\x31\x32\x38\x3A\x07\x7A\xD3" "\xDE\x28\x42\x45\xF4\x80\x6A\x1B\x82\xB7\x9E\x61\x6F\xBD\xE8\x21\xC8\x2D\x69\x1A" "\x65\x66\x5E\x57\xB5\xFA\xD3\xF3\x4E\x67\xF4\x01\xE7\xBD\x2E\x28\x69\x9E\x89\xD9" "\xC4\x96\xCF\x82\x19\x45\xAE\x83\xAC\x7A\x12\x31\x17\x6A\x19\x6B\xA6\x02\x7E\x77" "\xD8\x57\x89\x05\x5D\x50\x40\x4A\x7A\x2A\x95\xB1\x51\x2F\x91\xF1\x90\xBB\xAE\xF7" "\x30\xED\x55\x0D\x22\x7D\x51\x2F\x89\xC0\xCD\xB3\x1A\xC0\x6F\xA9\xA1\x95\x03\xDD" "\xF6\xB6\x6D\x0B\x42\xB9\x69\x1B\xFD\x61\x40\xEC\x17\x20\xFF\xC4\x8A\xE0\x0C\x34" "\x79\x6D\xC8\x99\xE5\x29\x28\x31\x3A\x70\x36\x35\x3A\x00\xD5\x86\xC7\x8E\x5F\x1B" "\x4B\xF2\xE7\xCD\x7A\x04\xCA\x09\x19\x11\x70\x6F\x19\x78\x8B\x93\xE4\x4E\xE2\x0A" "\xAF\x46\x2E\x83\x63\xE9\x8A\x72\x25\x3E\xD8\x45\xCC\xBF\x24\x81\xBB\x35\x1E\x85" "\x57\xC8\x5B\xCF\xFF\x0D\xAB\xDB\xFF\x8E\x26\xA7\x9A\x09\x38\x09\x6F\x27\x29\x28" "\x31\x3A\x71\x36\x35\x3A\x00\xDB\x0C\xDF\x60\xF2\x6F\x2A\x29\x6C\x88\xD6\xBF\x9F" "\x8E\x5B\xE4\x5C\x0D\xDD\x71\x3C\x96\xCC\x73\xEB\xCB\x48\xB0\x61\x74\x09\x43\xF2" "\x1D\x2A\x93\xD6\xE4\x2A\x72\x11\xE7\xF0\x2A\x95\xDC\xED\x6C\x39\x0A\x67\xAD\x21" "\xEC\xF7\x39\xAE\x8A\x0C\xA4\x6F\xF2\xEB\xB3\x29\x28\x31\x3A\x75\x36\x34\x3A\x33" "\x14\x91\x95\xF1\x69\x12\xDB\x20\xA4\x8D\x02\x0D\xBC\x3B\x9E\x38\x81\xB3\x9D\x72" "\x2B\xF7\x93\x78\xF6\x34\x0F\x43\x14\x8A\x6E\x9F\xC5\xF5\x3E\x28\x53\xB7\x38\x7B" "\xA4\x44\x3B\xA5\x3A\x52\xFC\xA8\x17\x3D\xE6\xE8\x5B\x42\xF9\x78\x3D\x4A\x78\x17" "\xD0\x68\x0B\x29\x29\x29\x00" }; /* This RSA key is missing the last closing brace. */ struct key_spec key_rsa_bogus_0 = { "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73" "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xB6\xB5\x09\x59\x6A\x9E\xCA\xBC\x93\x92" "\x12\xF8\x91\xE6\x56\xA6\x26\xBA\x07\xDA\x85\x21\xA9\xCA\xD4\xC0\x8E\x64\x0C\x04" "\x05\x2F\xBB\x87\xF4\x24\xEF\x1A\x02\x75\xA4\x8A\x92\x99\xAC\x9D\xB6\x9A\xBE\x3D" "\x01\x24\xE6\xC7\x56\xB1\xF7\xDF\xB9\xB8\x42\xD6\x25\x1A\xEA\x6E\xE8\x53\x90\x49" "\x5C\xAD\xA7\x3D\x67\x15\x37\xFC\xE5\x85\x0A\x93\x2F\x32\xBA\xB6\x0A\xB1\xAC\x1F" "\x85\x2C\x1F\x83\xC6\x25\xE7\xA7\xD7\x0C\xDA\x9E\xF1\x6D\x5C\x8E\x47\x73\x9D\x77" "\xDF\x59\x26\x1A\xBE\x84\x54\x80\x7F\xF4\x41\xE1\x43\xFB\xD3\x7F\x85\x45\x29\x28" "\x31\x3A\x65\x33\x3A\x01\x00\x01\x29\x28\x31\x3A\x64\x31\x32\x38\x3A\x07\x7A\xD3" "\xDE\x28\x42\x45\xF4\x80\x6A\x1B\x82\xB7\x9E\x61\x6F\xBD\xE8\x21\xC8\x2D\x69\x1A" "\x65\x66\x5E\x57\xB5\xFA\xD3\xF3\x4E\x67\xF4\x01\xE7\xBD\x2E\x28\x69\x9E\x89\xD9" "\xC4\x96\xCF\x82\x19\x45\xAE\x83\xAC\x7A\x12\x31\x17\x6A\x19\x6B\xA6\x02\x7E\x77" "\xD8\x57\x89\x05\x5D\x50\x40\x4A\x7A\x2A\x95\xB1\x51\x2F\x91\xF1\x90\xBB\xAE\xF7" "\x30\xED\x55\x0D\x22\x7D\x51\x2F\x89\xC0\xCD\xB3\x1A\xC0\x6F\xA9\xA1\x95\x03\xDD" "\xF6\xB6\x6D\x0B\x42\xB9\x69\x1B\xFD\x61\x40\xEC\x17\x20\xFF\xC4\x8A\xE0\x0C\x34" "\x79\x6D\xC8\x99\xE5\x29\x28\x31\x3A\x70\x36\x35\x3A\x00\xD5\x86\xC7\x8E\x5F\x1B" "\x4B\xF2\xE7\xCD\x7A\x04\xCA\x09\x19\x11\x70\x6F\x19\x78\x8B\x93\xE4\x4E\xE2\x0A" "\xAF\x46\x2E\x83\x63\xE9\x8A\x72\x25\x3E\xD8\x45\xCC\xBF\x24\x81\xBB\x35\x1E\x85" "\x57\xC8\x5B\xCF\xFF\x0D\xAB\xDB\xFF\x8E\x26\xA7\x9A\x09\x38\x09\x6F\x27\x29\x28" "\x31\x3A\x71\x36\x35\x3A\x00\xDB\x0C\xDF\x60\xF2\x6F\x2A\x29\x6C\x88\xD6\xBF\x9F" "\x8E\x5B\xE4\x5C\x0D\xDD\x71\x3C\x96\xCC\x73\xEB\xCB\x48\xB0\x61\x74\x09\x43\xF2" "\x1D\x2A\x93\xD6\xE4\x2A\x72\x11\xE7\xF0\x2A\x95\xDC\xED\x6C\x39\x0A\x67\xAD\x21" "\xEC\xF7\x39\xAE\x8A\x0C\xA4\x6F\xF2\xEB\xB3\x29\x28\x31\x3A\x75\x36\x34\x3A\x33" "\x14\x91\x95\xF1\x69\x12\xDB\x20\xA4\x8D\x02\x0D\xBC\x3B\x9E\x38\x81\xB3\x9D\x72" "\x2B\xF7\x93\x78\xF6\x34\x0F\x43\x14\x8A\x6E\x9F\xC5\xF5\x3E\x28\x53\xB7\x38\x7B" "\xA4\x44\x3B\xA5\x3A\x52\xFC\xA8\x17\x3D\xE6\xE8\x5B\x42\xF9\x78\x3D\x4A\x78\x17" "\xD0\x68\x0B\x29\x29\x00" }; /* This RSA key is the 'e' value. */ struct key_spec key_rsa_bogus_1 = { "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73" "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xA8\x80\xB6\x71\xF4\x95\x9F\x49\x84\xED" "\xC1\x1D\x5F\xFF\xED\x14\x7B\x9C\x6A\x62\x0B\x7B\xE2\x3E\x41\x48\x49\x85\xF5\x64" "\x50\x04\x9D\x30\xFC\x84\x1F\x01\xC3\xC3\x15\x03\x48\x6D\xFE\x59\x0B\xB0\xD0\x3E" "\x68\x8A\x05\x7A\x62\xB0\xB9\x6E\xC5\xD2\xA8\xEE\x0C\x6B\xDE\x5E\x3D\x8E\xE8\x8F" "\xB3\xAE\x86\x99\x7E\xDE\x2B\xC2\x4D\x60\x51\xDB\xB1\x2C\xD0\x38\xEC\x88\x62\x3E" "\xA9\xDD\x11\x53\x04\x17\xE4\xF2\x07\x50\xDC\x44\xED\x14\xF5\x0B\xAB\x9C\xBC\x24" "\xC6\xCB\xAD\x0F\x05\x25\x94\xE2\x73\xEB\x14\xD5\xEE\x5E\x18\xF0\x40\x31\x29\x28" "\x31\x3A\x64\x31\x32\x38\x3A\x40\xD0\x55\x9D\x2A\xA7\xBC\xBF\xE2\x3E\x33\x98\x71" "\x7B\x37\x3D\xB8\x38\x57\xA1\x43\xEA\x90\x81\x42\xCA\x23\xE1\xBF\x9C\xA8\xBC\xC5" "\x9B\xF8\x9D\x77\x71\xCD\xD3\x85\x8B\x20\x3A\x92\xE9\xBC\x79\xF3\xF7\xF5\x6D\x15" "\xA3\x58\x3F\xC2\xEB\xED\x72\xD4\xE0\xCF\xEC\xB3\xEC\xEB\x09\xEA\x1E\x72\x6A\xBA" "\x95\x82\x2C\x7E\x30\x95\x66\x3F\xA8\x2D\x40\x0F\x7A\x12\x4E\xF0\x71\x0F\x97\xDB" "\x81\xE4\x39\x6D\x24\x58\xFA\xAB\x3A\x36\x73\x63\x01\x77\x42\xC7\x9A\xEA\x87\xDA" "\x93\x8F\x6C\x64\xAD\x9E\xF0\xCA\xA2\x89\xA4\x0E\xB3\x25\x73\x29\x28\x31\x3A\x70" "\x36\x35\x3A\x00\xC3\xF7\x37\x3F\x9D\x93\xEC\xC7\x5E\x4C\xB5\x73\x29\x62\x35\x80" "\xC6\x7C\x1B\x1E\x68\x5F\x92\x56\x77\x0A\xE2\x8E\x95\x74\x87\xA5\x2F\x83\x2D\xF7" "\xA1\xC2\x78\x54\x18\x6E\xDE\x35\xF0\x9F\x7A\xCA\x80\x5C\x83\x5C\x44\xAD\x8B\xE7" "\x5B\xE2\x63\x7D\x6A\xC7\x98\x97\x29\x28\x31\x3A\x71\x36\x35\x3A\x00\xDC\x1F\xB1" "\xB3\xD8\x13\xE0\x09\x19\xFD\x1C\x58\xA1\x2B\x02\xB4\xC8\xF2\x1C\xE7\xF9\xC6\x3B" "\x68\xB9\x72\x43\x86\xEF\xA9\x94\x68\x02\xEF\x7D\x77\xE0\x0A\xD1\xD7\x48\xFD\xCD" "\x98\xDA\x13\x8A\x76\x48\xD4\x0F\x63\x28\xFA\x01\x1B\xF3\xC7\x15\xB8\x53\x22\x7E" "\x77\x29\x28\x31\x3A\x75\x36\x35\x3A\x00\xB3\xBB\x4D\xEE\x5A\xAF\xD0\xF2\x56\x8A" "\x10\x2D\x6F\x4B\x2D\x76\x49\x9B\xE9\xA8\x60\x5D\x9E\x7E\x50\x86\xF1\xA1\x0F\x28" "\x9B\x7B\xE8\xDD\x1F\x87\x4E\x79\x7B\x50\x12\xA7\xB4\x8B\x52\x38\xEC\x7C\xBB\xB9" "\x55\x87\x11\x1C\x74\xE7\x7F\xA0\xBA\xE3\x34\x5D\x61\xBF\x29\x29\x29\x00" }; struct key_spec key_ecdsa_valid = { "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28" "\x35\x3A\x65\x63\x64\x73\x61\x28\x35\x3A\x63\x75\x72\x76\x65\x31" "\x30\x3A\x4E\x49\x53\x54\x20\x50\x2D\x32\x35\x36\x29\x28\x31\x3A" "\x71\x36\x35\x3A\x04\x64\x5A\x12\x6F\x86\x7C\x43\x87\x2B\x7C\xAF" "\x77\xFE\xD8\x22\x31\xEA\xE6\x89\x9F\xAA\xEA\x63\x26\xBC\x49\xED" "\x85\xC6\xD2\xC9\x8B\x38\xD2\x78\x75\xE6\x1C\x27\x57\x01\xC5\xA1" "\xE3\xF9\x1F\xBE\xCF\xC1\x72\x73\xFE\xA4\x58\xB6\x6A\x92\x7D\x33" "\x1D\x02\xC9\xCB\x12\x29\x28\x31\x3A\x64\x33\x33\x3A\x00\x81\x2D" "\x69\x9A\x5F\x5B\x6F\x2C\x99\x61\x36\x15\x6B\x44\xD8\x06\xC1\x54" "\xC1\x4C\xFB\x70\x6A\xB6\x64\x81\x78\xF3\x94\x2F\x30\x5D\x29\x29" "\x28\x37\x3A\x63\x6F\x6D\x6D\x65\x6E\x74\x32\x32\x3A\x2F\x68\x6F" "\x6D\x65\x2F\x77\x6B\x2F\x2E\x73\x73\x68\x2F\x69\x64\x5F\x65\x63" "\x64\x73\x61\x29\x29" }; struct { const char *key; const char *passphrase; int no_result_expected; int compare_results; unsigned char *result_expected; size_t resultlen_expected; int ret_expected; unsigned char *result; size_t resultlen; } specs[] = { /* Invalid S-Expressions */ /* - non-NULL */ { "", "passphrase", 1, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 }, /* - NULL; disabled, this segfaults */ //{ NULL, // "passphrase", 1, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 }, /* Valid and invalid keys. */ { key_rsa_valid.string, "passphrase", 0, 0, NULL, 0, 0, NULL, 0 }, { key_rsa_bogus_0.string, "passphrase", 0, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 }, { key_rsa_bogus_1.string, "passphrase", 0, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 }, { key_ecdsa_valid.string, "passphrase", 0, 0, NULL, 0, 0, NULL, 0 }, /* FIXME: add more test data. */ }; for (i = 0; i < DIM (specs); i++) { ret = agent_protect ((const unsigned char*)specs[i].key, specs[i].passphrase, &specs[i].result, &specs[i].resultlen, 0, -1); if (gpg_err_code (ret) != specs[i].ret_expected) { printf ("agent_protect(%d) returned '%i/%s'; expected '%i/%s'\n", i, ret, gpg_strerror (ret), specs[i].ret_expected, gpg_strerror (specs[i].ret_expected)); abort (); } if (specs[i].no_result_expected) { assert (! specs[i].result); assert (! specs[i].resultlen); } else { if (specs[i].compare_results) { assert (specs[i].resultlen == specs[i].resultlen_expected); if (specs[i].result_expected) assert (! memcmp (specs[i].result, specs[i].result_expected, specs[i].resultlen)); else assert (! specs[i].result); } xfree (specs[i].result); } } } static void test_agent_unprotect (void) { /* Unprotect the key encoded in canonical format. We assume a valid S-Exp here. */ /* int */ /* agent_unprotect (const unsigned char *protectedkey, const char *passphrase, */ /* unsigned char **result, size_t *resultlen) */ } static void test_agent_private_key_type (void) { /* 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. */ /* int */ /* agent_private_key_type (const unsigned char *privatekey) */ } static void test_make_shadow_info (void) { #if 0 static struct { const char *snstr; const char *idstr; const char *expected; } data[] = { { "", "", NULL }, }; int i; unsigned char *result; for (i=0; i < DIM(data); i++) { result = make_shadow_info (data[i].snstr, data[i].idstr); if (!result && !data[i].expected) pass (); else if (!result && data[i].expected) fail (); else if (!data[i].expected) fail (); /* fixme: Need to compare the result but also need to check proper S-expression syntax. */ } #endif } static void test_agent_shadow_key (void) { /* 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) */ } static void test_agent_get_shadow_info (void) { /* Parse a canonical encoded shadowed key and return a pointer to the inner list with the shadow_info */ /* int */ /* agent_get_shadow_info (const unsigned char *shadowkey, */ /* unsigned char const **shadow_info) */ } static void test_agent_protect_shared_secret (void) { } int main (int argc, char **argv) { (void)argv; opt.verbose = argc - 1; /* We can do "./t-protect -v -v" */ gcry_control (GCRYCTL_DISABLE_SECMEM); test_agent_protect (); test_agent_unprotect (); test_agent_private_key_type (); test_make_shadow_info (); test_agent_shadow_key (); test_agent_get_shadow_info (); test_agent_protect_shared_secret (); return 0; } /* Stub function. */ gpg_error_t convert_from_openpgp_native (gcry_sexp_t s_pgp, const char *passphrase, unsigned char **r_key) { (void)s_pgp; (void)passphrase; (void)r_key; return gpg_error (GPG_ERR_BUG); } diff --git a/common/iobuf.c b/common/iobuf.c index db5d062cd..43f2e101c 100644 --- a/common/iobuf.c +++ b/common/iobuf.c @@ -1,2820 +1,2821 @@ /* iobuf.c - File Handling for OpenPGP. * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006, 2007, 2008, * 2009, 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # ifdef HAVE_WINSOCK2_H # include # endif # include #endif #ifdef __riscos__ # include # include #endif /* __riscos__ */ #include #include "util.h" #include "sysutils.h" #include "iobuf.h" /*-- Begin configurable part. --*/ /* The standard size of the internal buffers. */ #define DEFAULT_IOBUF_BUFFER_SIZE (64*1024) /* To avoid a potential DoS with compression packets we better limit the number of filters in a chain. */ #define MAX_NESTING_FILTER 64 /*-- End configurable part. --*/ /* The size of the iobuffers. This can be changed using the * iobuf_set_buffer_size function. */ static unsigned int iobuf_buffer_size = DEFAULT_IOBUF_BUFFER_SIZE; #ifdef HAVE_W32_SYSTEM # ifdef HAVE_W32CE_SYSTEM # define FD_FOR_STDIN (es_fileno (es_stdin)) # define FD_FOR_STDOUT (es_fileno (es_stdout)) # else # define FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE)) # define FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE)) # endif #else /*!HAVE_W32_SYSTEM*/ # define FD_FOR_STDIN (0) # define FD_FOR_STDOUT (1) #endif /*!HAVE_W32_SYSTEM*/ /* The context used by the file filter. */ typedef struct { gnupg_fd_t fp; /* Open file pointer or handle. */ int keep_open; int no_cache; int eof_seen; int delayed_rc; int print_only_name; /* Flags indicating that fname is not a real file. */ char fname[1]; /* Name of the file. */ } file_filter_ctx_t; /* The context used by the estream filter. */ typedef struct { estream_t fp; /* Open estream handle. */ int keep_open; int no_cache; int eof_seen; int use_readlimit; /* Take care of the readlimit. */ size_t readlimit; /* Number of bytes left to read. */ int print_only_name; /* Flags indicating that fname is not a real file. */ char fname[1]; /* Name of the file. */ } file_es_filter_ctx_t; /* Object to control the "close cache". */ struct close_cache_s { struct close_cache_s *next; gnupg_fd_t fp; char fname[1]; }; typedef struct close_cache_s *close_cache_t; static close_cache_t close_cache; +int iobuf_debug_mode; #ifdef HAVE_W32_SYSTEM typedef struct { int sock; int keep_open; int no_cache; int eof_seen; int print_only_name; /* Flag indicating that fname is not a real file. */ char fname[1]; /* Name of the file */ } sock_filter_ctx_t; #endif /*HAVE_W32_SYSTEM*/ /* The first partial length header block must be of size 512 to make * it easier (and more efficient) we use a min. block size of 512 for * all chunks (but the last one) */ #define OP_MIN_PARTIAL_CHUNK 512 #define OP_MIN_PARTIAL_CHUNK_2POW 9 /* The context we use for the block filter (used to handle OpenPGP length information header). */ typedef struct { int use; size_t size; size_t count; int partial; /* 1 = partial header, 2 in last partial packet. */ char *buffer; /* Used for partial header. */ size_t buflen; /* Used size of buffer. */ int first_c; /* First character of a partial header (which is > 0). */ int eof; } block_filter_ctx_t; /* Local prototypes. */ static int underflow (iobuf_t a, int clear_pending_eof); static int underflow_target (iobuf_t a, int clear_pending_eof, size_t target); static int translate_file_handle (int fd, int for_write); /* Sends any pending data to the filter's FILTER function. Note: this works on the filter and not on the whole pipeline. That is, iobuf_flush doesn't necessarily cause data to be written to any underlying file; it just causes any data buffered at the filter A to be sent to A's filter function. If A is a IOBUF_OUTPUT_TEMP filter, then this also enlarges the buffer by iobuf_buffer_size. May only be called on an IOBUF_OUTPUT or IOBUF_OUTPUT_TEMP filters. */ static int filter_flush (iobuf_t a); /* This is a replacement for strcmp. Under W32 it does not distinguish between backslash and slash. */ static int fd_cache_strcmp (const char *a, const char *b) { #ifdef HAVE_DOSISH_SYSTEM for (; *a && *b; a++, b++) { if (*a != *b && !((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/')) ) break; } return *(const unsigned char *)a - *(const unsigned char *)b; #else return strcmp (a, b); #endif } /* * Invalidate (i.e. close) a cached iobuf */ static int fd_cache_invalidate (const char *fname) { close_cache_t cc; int rc = 0; assert (fname); if (DBG_IOBUF) log_debug ("fd_cache_invalidate (%s)\n", fname); for (cc = close_cache; cc; cc = cc->next) { if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname)) { if (DBG_IOBUF) log_debug (" did (%s)\n", cc->fname); #ifdef HAVE_W32_SYSTEM if (!CloseHandle (cc->fp)) rc = -1; #else rc = close (cc->fp); #endif cc->fp = GNUPG_INVALID_FD; } } return rc; } /* Try to sync changes to the disk. This is to avoid data loss during a system crash in write/close/rename cycle on some file systems. */ static int fd_cache_synchronize (const char *fname) { int err = 0; #ifdef HAVE_FSYNC close_cache_t cc; if (DBG_IOBUF) log_debug ("fd_cache_synchronize (%s)\n", fname); for (cc=close_cache; cc; cc = cc->next ) { if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname)) { if (DBG_IOBUF) log_debug (" did (%s)\n", cc->fname); err = fsync (cc->fp); } } #else (void)fname; #endif /*HAVE_FSYNC*/ return err; } static gnupg_fd_t direct_open (const char *fname, const char *mode, int mode700) { #ifdef HAVE_W32_SYSTEM unsigned long da, cd, sm; HANDLE hfile; (void)mode700; /* Note, that we do not handle all mode combinations */ /* According to the ReactOS source it seems that open() of the * standard MSW32 crt does open the file in shared mode which is * something new for MS applications ;-) */ if (strchr (mode, '+')) { if (fd_cache_invalidate (fname)) return GNUPG_INVALID_FD; da = GENERIC_READ | GENERIC_WRITE; cd = OPEN_EXISTING; sm = FILE_SHARE_READ | FILE_SHARE_WRITE; } else if (strchr (mode, 'w')) { if (fd_cache_invalidate (fname)) return GNUPG_INVALID_FD; da = GENERIC_WRITE; cd = CREATE_ALWAYS; sm = FILE_SHARE_WRITE; } else { da = GENERIC_READ; cd = OPEN_EXISTING; sm = FILE_SHARE_READ; } #ifdef HAVE_W32CE_SYSTEM { wchar_t *wfname = utf8_to_wchar (fname); if (wfname) { hfile = CreateFile (wfname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL); xfree (wfname); } else hfile = INVALID_HANDLE_VALUE; } #else hfile = CreateFile (fname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL); #endif return hfile; #else /*!HAVE_W32_SYSTEM*/ int oflag; int cflag = S_IRUSR | S_IWUSR; if (!mode700) cflag |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* Note, that we do not handle all mode combinations */ if (strchr (mode, '+')) { if (fd_cache_invalidate (fname)) return GNUPG_INVALID_FD; oflag = O_RDWR; } else if (strchr (mode, 'w')) { if (fd_cache_invalidate (fname)) return GNUPG_INVALID_FD; oflag = O_WRONLY | O_CREAT | O_TRUNC; } else { oflag = O_RDONLY; } #ifdef O_BINARY if (strchr (mode, 'b')) oflag |= O_BINARY; #endif #ifdef __riscos__ { struct stat buf; /* Don't allow iobufs on directories */ if (!stat (fname, &buf) && S_ISDIR (buf.st_mode) && !S_ISREG (buf.st_mode)) return __set_errno (EISDIR); } #endif return open (fname, oflag, cflag); #endif /*!HAVE_W32_SYSTEM*/ } /* * Instead of closing an FD we keep it open and cache it for later reuse * Note that this caching strategy only works if the process does not chdir. */ static void fd_cache_close (const char *fname, gnupg_fd_t fp) { close_cache_t cc; assert (fp); if (!fname || !*fname) { #ifdef HAVE_W32_SYSTEM CloseHandle (fp); #else close (fp); #endif if (DBG_IOBUF) log_debug ("fd_cache_close (%d) real\n", (int)fp); return; } /* try to reuse a slot */ for (cc = close_cache; cc; cc = cc->next) { if (cc->fp == GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname)) { cc->fp = fp; if (DBG_IOBUF) log_debug ("fd_cache_close (%s) used existing slot\n", fname); return; } } /* add a new one */ if (DBG_IOBUF) log_debug ("fd_cache_close (%s) new slot created\n", fname); cc = xcalloc (1, sizeof *cc + strlen (fname)); strcpy (cc->fname, fname); cc->fp = fp; cc->next = close_cache; close_cache = cc; } /* * Do a direct_open on FNAME but first try to reuse one from the fd_cache */ static gnupg_fd_t fd_cache_open (const char *fname, const char *mode) { close_cache_t cc; assert (fname); for (cc = close_cache; cc; cc = cc->next) { if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname)) { gnupg_fd_t fp = cc->fp; cc->fp = GNUPG_INVALID_FD; if (DBG_IOBUF) log_debug ("fd_cache_open (%s) using cached fp\n", fname); #ifdef HAVE_W32_SYSTEM if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff) { log_error ("rewind file failed on handle %p: ec=%d\n", fp, (int) GetLastError ()); fp = GNUPG_INVALID_FD; } #else if (lseek (fp, 0, SEEK_SET) == (off_t) - 1) { log_error ("can't rewind fd %d: %s\n", fp, strerror (errno)); fp = GNUPG_INVALID_FD; } #endif return fp; } } if (DBG_IOBUF) log_debug ("fd_cache_open (%s) not cached\n", fname); return direct_open (fname, mode, 0); } static int file_filter (void *opaque, int control, iobuf_t chain, byte * buf, size_t * ret_len) { file_filter_ctx_t *a = opaque; gnupg_fd_t f = a->fp; size_t size = *ret_len; size_t nbytes = 0; int rc = 0; (void)chain; /* Not used. */ if (control == IOBUFCTRL_UNDERFLOW) { log_assert (size); /* We need a buffer. */ if (a->eof_seen) { rc = -1; *ret_len = 0; } else if (a->delayed_rc) { rc = a->delayed_rc; a->delayed_rc = 0; if (rc == -1) a->eof_seen = -1; *ret_len = 0; } else { #ifdef HAVE_W32_SYSTEM unsigned long nread; nbytes = 0; if (!ReadFile (f, buf, size, &nread, NULL)) { int ec = (int) GetLastError (); if (ec != ERROR_BROKEN_PIPE) { rc = gpg_error_from_errno (ec); log_error ("%s: read error: ec=%d\n", a->fname, ec); } } else if (!nread) { a->eof_seen = 1; rc = -1; } else { nbytes = nread; } #else int n; nbytes = 0; read_more: do { n = read (f, buf + nbytes, size - nbytes); } while (n == -1 && errno == EINTR); if (n > 0) { nbytes += n; if (nbytes < size) goto read_more; } else if (!n) /* eof */ { if (nbytes) a->delayed_rc = -1; else { a->eof_seen = 1; rc = -1; } } else /* error */ { rc = gpg_error_from_syserror (); if (gpg_err_code (rc) != GPG_ERR_EPIPE) log_error ("%s: read error: %s\n", a->fname, gpg_strerror (rc)); if (nbytes) { a->delayed_rc = rc; rc = 0; } } #endif *ret_len = nbytes; } } else if (control == IOBUFCTRL_FLUSH) { if (size) { #ifdef HAVE_W32_SYSTEM byte *p = buf; unsigned long n; nbytes = size; do { if (size && !WriteFile (f, p, nbytes, &n, NULL)) { int ec = (int) GetLastError (); rc = gpg_error_from_errno (ec); log_error ("%s: write error: ec=%d\n", a->fname, ec); break; } p += n; nbytes -= n; } while (nbytes); nbytes = p - buf; #else byte *p = buf; int n; nbytes = size; do { do { n = write (f, p, nbytes); } while (n == -1 && errno == EINTR); if (n > 0) { p += n; nbytes -= n; } } while (n != -1 && nbytes); if (n == -1) { rc = gpg_error_from_syserror (); log_error ("%s: write error: %s\n", a->fname, strerror (errno)); } nbytes = p - buf; #endif } *ret_len = nbytes; } else if (control == IOBUFCTRL_INIT) { a->eof_seen = 0; a->delayed_rc = 0; a->keep_open = 0; a->no_cache = 0; } else if (control == IOBUFCTRL_DESC) { mem2str (buf, "file_filter(fd)", *ret_len); } else if (control == IOBUFCTRL_FREE) { if (f != FD_FOR_STDIN && f != FD_FOR_STDOUT) { if (DBG_IOBUF) log_debug ("%s: close fd/handle %d\n", a->fname, FD2INT (f)); if (!a->keep_open) fd_cache_close (a->no_cache ? NULL : a->fname, f); } xfree (a); /* We can free our context now. */ } return rc; } /* Similar to file_filter but using the estream system. */ static int file_es_filter (void *opaque, int control, iobuf_t chain, byte * buf, size_t * ret_len) { file_es_filter_ctx_t *a = opaque; estream_t f = a->fp; size_t size = *ret_len; size_t nbytes = 0; int rc = 0; (void)chain; /* Not used. */ if (control == IOBUFCTRL_UNDERFLOW) { assert (size); /* We need a buffer. */ if (a->eof_seen) { rc = -1; *ret_len = 0; } else if (a->use_readlimit) { nbytes = 0; if (!a->readlimit) { /* eof */ a->eof_seen = 1; rc = -1; } else { if (size > a->readlimit) size = a->readlimit; rc = es_read (f, buf, size, &nbytes); if (rc == -1) { /* error */ rc = gpg_error_from_syserror (); log_error ("%s: read error: %s\n", a->fname,strerror (errno)); } else if (!nbytes) { /* eof */ a->eof_seen = 1; rc = -1; } else a->readlimit -= nbytes; } *ret_len = nbytes; } else { nbytes = 0; rc = es_read (f, buf, size, &nbytes); if (rc == -1) { /* error */ rc = gpg_error_from_syserror (); log_error ("%s: read error: %s\n", a->fname, strerror (errno)); } else if (!nbytes) { /* eof */ a->eof_seen = 1; rc = -1; } *ret_len = nbytes; } } else if (control == IOBUFCTRL_FLUSH) { if (size) { byte *p = buf; size_t nwritten; nbytes = size; do { nwritten = 0; if (es_write (f, p, nbytes, &nwritten)) { rc = gpg_error_from_syserror (); log_error ("%s: write error: %s\n", a->fname, strerror (errno)); break; } p += nwritten; nbytes -= nwritten; } while (nbytes); nbytes = p - buf; } *ret_len = nbytes; } else if (control == IOBUFCTRL_INIT) { a->eof_seen = 0; a->no_cache = 0; } else if (control == IOBUFCTRL_DESC) { mem2str (buf, "estream_filter", *ret_len); } else if (control == IOBUFCTRL_FREE) { if (f != es_stdin && f != es_stdout) { if (DBG_IOBUF) log_debug ("%s: es_fclose %p\n", a->fname, f); if (!a->keep_open) es_fclose (f); } f = NULL; xfree (a); /* We can free our context now. */ } return rc; } #ifdef HAVE_W32_SYSTEM /* Because network sockets are special objects under Lose32 we have to use a dedicated filter for them. */ static int sock_filter (void *opaque, int control, iobuf_t chain, byte * buf, size_t * ret_len) { sock_filter_ctx_t *a = opaque; size_t size = *ret_len; size_t nbytes = 0; int rc = 0; (void)chain; if (control == IOBUFCTRL_UNDERFLOW) { assert (size); /* need a buffer */ if (a->eof_seen) { rc = -1; *ret_len = 0; } else { int nread; nread = recv (a->sock, buf, size, 0); if (nread == SOCKET_ERROR) { int ec = (int) WSAGetLastError (); rc = gpg_error_from_errno (ec); log_error ("socket read error: ec=%d\n", ec); } else if (!nread) { a->eof_seen = 1; rc = -1; } else { nbytes = nread; } *ret_len = nbytes; } } else if (control == IOBUFCTRL_FLUSH) { if (size) { byte *p = buf; int n; nbytes = size; do { n = send (a->sock, p, nbytes, 0); if (n == SOCKET_ERROR) { int ec = (int) WSAGetLastError (); rc = gpg_error_from_errno (ec); log_error ("socket write error: ec=%d\n", ec); break; } p += n; nbytes -= n; } while (nbytes); nbytes = p - buf; } *ret_len = nbytes; } else if (control == IOBUFCTRL_INIT) { a->eof_seen = 0; a->keep_open = 0; a->no_cache = 0; } else if (control == IOBUFCTRL_DESC) { mem2str (buf, "sock_filter", *ret_len); } else if (control == IOBUFCTRL_FREE) { if (!a->keep_open) closesocket (a->sock); xfree (a); /* we can free our context now */ } return rc; } #endif /*HAVE_W32_SYSTEM*/ /**************** * This is used to implement the block write mode. * Block reading is done on a byte by byte basis in readbyte(), * without a filter */ static int block_filter (void *opaque, int control, iobuf_t chain, byte * buffer, size_t * ret_len) { block_filter_ctx_t *a = opaque; char *buf = (char *)buffer; size_t size = *ret_len; int c, needed, rc = 0; char *p; if (control == IOBUFCTRL_UNDERFLOW) { size_t n = 0; p = buf; assert (size); /* need a buffer */ if (a->eof) /* don't read any further */ rc = -1; while (!rc && size) { if (!a->size) { /* get the length bytes */ if (a->partial == 2) { a->eof = 1; if (!n) rc = -1; break; } else if (a->partial) { /* These OpenPGP introduced huffman like encoded length * bytes are really a mess :-( */ if (a->first_c) { c = a->first_c; a->first_c = 0; } else if ((c = iobuf_get (chain)) == -1) { log_error ("block_filter: 1st length byte missing\n"); rc = GPG_ERR_BAD_DATA; break; } if (c < 192) { a->size = c; a->partial = 2; if (!a->size) { a->eof = 1; if (!n) rc = -1; break; } } else if (c < 224) { a->size = (c - 192) * 256; if ((c = iobuf_get (chain)) == -1) { log_error ("block_filter: 2nd length byte missing\n"); rc = GPG_ERR_BAD_DATA; break; } a->size += c + 192; a->partial = 2; if (!a->size) { a->eof = 1; if (!n) rc = -1; break; } } else if (c == 255) { a->size = iobuf_get_noeof (chain) << 24; a->size |= iobuf_get_noeof (chain) << 16; a->size |= iobuf_get_noeof (chain) << 8; if ((c = iobuf_get (chain)) == -1) { log_error ("block_filter: invalid 4 byte length\n"); rc = GPG_ERR_BAD_DATA; break; } a->size |= c; a->partial = 2; if (!a->size) { a->eof = 1; if (!n) rc = -1; break; } } else { /* Next partial body length. */ a->size = 1 << (c & 0x1f); } /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */ } else BUG (); } while (!rc && size && a->size) { needed = size < a->size ? size : a->size; c = iobuf_read (chain, p, needed); if (c < needed) { if (c == -1) c = 0; log_error ("block_filter %p: read error (size=%lu,a->size=%lu)\n", a, (ulong) size + c, (ulong) a->size + c); rc = GPG_ERR_BAD_DATA; } else { size -= c; a->size -= c; p += c; n += c; } } } *ret_len = n; } else if (control == IOBUFCTRL_FLUSH) { if (a->partial) { /* the complicated openpgp scheme */ size_t blen, n, nbytes = size + a->buflen; assert (a->buflen <= OP_MIN_PARTIAL_CHUNK); if (nbytes < OP_MIN_PARTIAL_CHUNK) { /* not enough to write a partial block out; so we store it */ if (!a->buffer) a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK); memcpy (a->buffer + a->buflen, buf, size); a->buflen += size; } else { /* okay, we can write out something */ /* do this in a loop to use the most efficient block lengths */ p = buf; do { /* find the best matching block length - this is limited * by the size of the internal buffering */ for (blen = OP_MIN_PARTIAL_CHUNK * 2, c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes; blen *= 2, c++) ; blen /= 2; c--; /* write the partial length header */ assert (c <= 0x1f); /*;-) */ c |= 0xe0; iobuf_put (chain, c); if ((n = a->buflen)) { /* write stuff from the buffer */ assert (n == OP_MIN_PARTIAL_CHUNK); if (iobuf_write (chain, a->buffer, n)) rc = gpg_error_from_syserror (); a->buflen = 0; nbytes -= n; } if ((n = nbytes) > blen) n = blen; if (n && iobuf_write (chain, p, n)) rc = gpg_error_from_syserror (); p += n; nbytes -= n; } while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK); /* store the rest in the buffer */ if (!rc && nbytes) { assert (!a->buflen); assert (nbytes < OP_MIN_PARTIAL_CHUNK); if (!a->buffer) a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK); memcpy (a->buffer, p, nbytes); a->buflen = nbytes; } } } else BUG (); } else if (control == IOBUFCTRL_INIT) { if (DBG_IOBUF) log_debug ("init block_filter %p\n", a); if (a->partial) a->count = 0; else if (a->use == IOBUF_INPUT) a->count = a->size = 0; else a->count = a->size; /* force first length bytes */ a->eof = 0; a->buffer = NULL; a->buflen = 0; } else if (control == IOBUFCTRL_DESC) { mem2str (buf, "block_filter", *ret_len); } else if (control == IOBUFCTRL_FREE) { if (a->use == IOBUF_OUTPUT) { /* write the end markers */ if (a->partial) { u32 len; /* write out the remaining bytes without a partial header * the length of this header may be 0 - but if it is * the first block we are not allowed to use a partial header * and frankly we can't do so, because this length must be * a power of 2. This is _really_ complicated because we * have to check the possible length of a packet prior * to it's creation: a chain of filters becomes complicated * and we need a lot of code to handle compressed packets etc. * :-((((((( */ /* construct header */ len = a->buflen; /*log_debug("partial: remaining length=%u\n", len ); */ if (len < 192) rc = iobuf_put (chain, len); else if (len < 8384) { if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192))) rc = iobuf_put (chain, ((len - 192) % 256)); } else { /* use a 4 byte header */ if (!(rc = iobuf_put (chain, 0xff))) if (!(rc = iobuf_put (chain, (len >> 24) & 0xff))) if (!(rc = iobuf_put (chain, (len >> 16) & 0xff))) if (!(rc = iobuf_put (chain, (len >> 8) & 0xff))) rc = iobuf_put (chain, len & 0xff); } if (!rc && len) rc = iobuf_write (chain, a->buffer, len); if (rc) { log_error ("block_filter: write error: %s\n", strerror (errno)); rc = gpg_error_from_syserror (); } xfree (a->buffer); a->buffer = NULL; a->buflen = 0; } else BUG (); } else if (a->size) { log_error ("block_filter: pending bytes!\n"); } if (DBG_IOBUF) log_debug ("free block_filter %p\n", a); xfree (a); /* we can free our context now */ } return rc; } /* Change the default size for all IOBUFs to KILOBYTE. This needs to * be called before any iobufs are used and can only be used once. * Returns the current value. Using 0 has no effect except for * returning the current value. */ unsigned int iobuf_set_buffer_size (unsigned int kilobyte) { static int used; if (!used && kilobyte) { if (kilobyte < 4) kilobyte = 4; else if (kilobyte > 16*1024) kilobyte = 16*1024; iobuf_buffer_size = kilobyte * 1024; used = 1; } return iobuf_buffer_size / 1024; } #define MAX_IOBUF_DESC 32 /* * Fill the buffer by the description of iobuf A. * The buffer size should be MAX_IOBUF_DESC (or larger). * Returns BUF as (const char *). */ static const char * iobuf_desc (iobuf_t a, byte *buf) { size_t len = MAX_IOBUF_DESC; if (! a || ! a->filter) memcpy (buf, "?", 2); else a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL, buf, &len); return buf; } static void print_chain (iobuf_t a) { if (!DBG_IOBUF) return; for (; a; a = a->chain) { byte desc[MAX_IOBUF_DESC]; log_debug ("iobuf chain: %d.%d '%s' filter_eof=%d start=%d len=%d\n", a->no, a->subno, iobuf_desc (a, desc), a->filter_eof, (int) a->d.start, (int) a->d.len); } } int iobuf_print_chain (iobuf_t a) { print_chain (a); return 0; } iobuf_t iobuf_alloc (int use, size_t bufsize) { iobuf_t a; static int number = 0; assert (use == IOBUF_INPUT || use == IOBUF_INPUT_TEMP || use == IOBUF_OUTPUT || use == IOBUF_OUTPUT_TEMP); if (bufsize == 0) { log_bug ("iobuf_alloc() passed a bufsize of 0!\n"); bufsize = iobuf_buffer_size; } a = xcalloc (1, sizeof *a); a->use = use; a->d.buf = xmalloc (bufsize); a->d.size = bufsize; a->no = ++number; a->subno = 0; a->real_fname = NULL; return a; } int iobuf_close (iobuf_t a) { iobuf_t a_chain; size_t dummy_len = 0; int rc = 0; for (; a; a = a_chain) { byte desc[MAX_IOBUF_DESC]; int rc2 = 0; a_chain = a->chain; if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a))) log_error ("filter_flush failed on close: %s\n", gpg_strerror (rc)); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: close '%s'\n", a->no, a->subno, iobuf_desc (a, desc)); if (a->filter && (rc2 = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain, NULL, &dummy_len))) log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc)); if (! rc && rc2) /* Whoops! An error occurred. Save it in RC if we haven't already recorded an error. */ rc = rc2; xfree (a->real_fname); if (a->d.buf) { memset (a->d.buf, 0, a->d.size); /* erase the buffer */ xfree (a->d.buf); } xfree (a); } return rc; } int iobuf_cancel (iobuf_t a) { const char *s; iobuf_t a2; int rc; #if defined(HAVE_W32_SYSTEM) || defined(__riscos__) char *remove_name = NULL; #endif if (a && a->use == IOBUF_OUTPUT) { s = iobuf_get_real_fname (a); if (s && *s) { #if defined(HAVE_W32_SYSTEM) || defined(__riscos__) remove_name = xstrdup (s); #else remove (s); #endif } } /* send a cancel message to all filters */ for (a2 = a; a2; a2 = a2->chain) { size_t dummy; if (a2->filter) a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy); } rc = iobuf_close (a); #if defined(HAVE_W32_SYSTEM) || defined(__riscos__) if (remove_name) { /* Argg, MSDOS does not allow removing open files. So * we have to do it here */ #ifdef HAVE_W32CE_SYSTEM wchar_t *wtmp = utf8_to_wchar (remove_name); if (wtmp) DeleteFile (wtmp); xfree (wtmp); #else remove (remove_name); #endif xfree (remove_name); } #endif return rc; } iobuf_t iobuf_temp (void) { return iobuf_alloc (IOBUF_OUTPUT_TEMP, iobuf_buffer_size); } iobuf_t iobuf_temp_with_content (const char *buffer, size_t length) { iobuf_t a; int i; a = iobuf_alloc (IOBUF_INPUT_TEMP, length); assert (length == a->d.size); /* memcpy (a->d.buf, buffer, length); */ for (i=0; i < length; i++) a->d.buf[i] = buffer[i]; a->d.len = length; return a; } int iobuf_is_pipe_filename (const char *fname) { if (!fname || (*fname=='-' && !fname[1]) ) return 1; return check_special_filename (fname, 0, 1) != -1; } static iobuf_t do_open (const char *fname, int special_filenames, int use, const char *opentype, int mode700) { iobuf_t a; gnupg_fd_t fp; file_filter_ctx_t *fcx; size_t len = 0; int print_only = 0; int fd; byte desc[MAX_IOBUF_DESC]; assert (use == IOBUF_INPUT || use == IOBUF_OUTPUT); if (special_filenames /* NULL or '-'. */ && (!fname || (*fname == '-' && !fname[1]))) { if (use == IOBUF_INPUT) { fp = FD_FOR_STDIN; fname = "[stdin]"; } else { fp = FD_FOR_STDOUT; fname = "[stdout]"; } print_only = 1; } else if (!fname) return NULL; else if (special_filenames && (fd = check_special_filename (fname, 0, 1)) != -1) return iobuf_fdopen (translate_file_handle (fd, use == IOBUF_INPUT ? 0 : 1), opentype); else { if (use == IOBUF_INPUT) fp = fd_cache_open (fname, opentype); else fp = direct_open (fname, opentype, mode700); if (fp == GNUPG_INVALID_FD) return NULL; } a = iobuf_alloc (use, iobuf_buffer_size); fcx = xmalloc (sizeof *fcx + strlen (fname)); fcx->fp = fp; fcx->print_only_name = print_only; strcpy (fcx->fname, fname); if (!print_only) a->real_fname = xstrdup (fname); a->filter = file_filter; a->filter_ov = fcx; file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: open '%s' desc=%s fd=%d\n", a->no, a->subno, fname, iobuf_desc (a, desc), FD2INT (fcx->fp)); return a; } iobuf_t iobuf_open (const char *fname) { return do_open (fname, 1, IOBUF_INPUT, "rb", 0); } iobuf_t iobuf_create (const char *fname, int mode700) { return do_open (fname, 1, IOBUF_OUTPUT, "wb", mode700); } iobuf_t iobuf_openrw (const char *fname) { return do_open (fname, 0, IOBUF_OUTPUT, "r+b", 0); } static iobuf_t do_iobuf_fdopen (int fd, const char *mode, int keep_open) { iobuf_t a; gnupg_fd_t fp; file_filter_ctx_t *fcx; size_t len; fp = INT2FD (fd); a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT, iobuf_buffer_size); fcx = xmalloc (sizeof *fcx + 20); fcx->fp = fp; fcx->print_only_name = 1; fcx->keep_open = keep_open; sprintf (fcx->fname, "[fd %d]", fd); a->filter = file_filter; a->filter_ov = fcx; file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: fdopen%s '%s'\n", a->no, a->subno, keep_open? "_nc":"", fcx->fname); iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL); return a; } iobuf_t iobuf_fdopen (int fd, const char *mode) { return do_iobuf_fdopen (fd, mode, 0); } iobuf_t iobuf_fdopen_nc (int fd, const char *mode) { return do_iobuf_fdopen (fd, mode, 1); } iobuf_t iobuf_esopen (estream_t estream, const char *mode, int keep_open, size_t readlimit) { iobuf_t a; file_es_filter_ctx_t *fcx; size_t len = 0; a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT, iobuf_buffer_size); fcx = xtrymalloc (sizeof *fcx + 30); fcx->fp = estream; fcx->print_only_name = 1; fcx->keep_open = keep_open; fcx->readlimit = readlimit; fcx->use_readlimit = !!readlimit; snprintf (fcx->fname, 30, "[fd %p]", estream); a->filter = file_es_filter; a->filter_ov = fcx; file_es_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: esopen%s '%s'\n", a->no, a->subno, keep_open? "_nc":"", fcx->fname); return a; } iobuf_t iobuf_sockopen (int fd, const char *mode) { iobuf_t a; #ifdef HAVE_W32_SYSTEM sock_filter_ctx_t *scx; size_t len; a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT, iobuf_buffer_size); scx = xmalloc (sizeof *scx + 25); scx->sock = fd; scx->print_only_name = 1; sprintf (scx->fname, "[sock %d]", fd); a->filter = sock_filter; a->filter_ov = scx; sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: sockopen '%s'\n", a->no, a->subno, scx->fname); iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL); #else a = iobuf_fdopen (fd, mode); #endif return a; } int iobuf_ioctl (iobuf_t a, iobuf_ioctl_t cmd, int intval, void *ptrval) { byte desc[MAX_IOBUF_DESC]; if (cmd == IOBUF_IOCTL_KEEP_OPEN) { /* Keep system filepointer/descriptor open. This was used in the past by http.c; this ioctl is not directly used anymore. */ if (DBG_IOBUF) log_debug ("iobuf-%d.%d: ioctl '%s' keep_open=%d\n", a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc), intval); for (; a; a = a->chain) if (!a->chain && a->filter == file_filter) { file_filter_ctx_t *b = a->filter_ov; b->keep_open = intval; return 0; } #ifdef HAVE_W32_SYSTEM else if (!a->chain && a->filter == sock_filter) { sock_filter_ctx_t *b = a->filter_ov; b->keep_open = intval; return 0; } #endif } else if (cmd == IOBUF_IOCTL_INVALIDATE_CACHE) { if (DBG_IOBUF) log_debug ("iobuf-*.*: ioctl '%s' invalidate\n", ptrval ? (char *) ptrval : "?"); if (!a && !intval && ptrval) { if (fd_cache_invalidate (ptrval)) return -1; return 0; } } else if (cmd == IOBUF_IOCTL_NO_CACHE) { if (DBG_IOBUF) log_debug ("iobuf-%d.%d: ioctl '%s' no_cache=%d\n", a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc), intval); for (; a; a = a->chain) if (!a->chain && a->filter == file_filter) { file_filter_ctx_t *b = a->filter_ov; b->no_cache = intval; return 0; } #ifdef HAVE_W32_SYSTEM else if (!a->chain && a->filter == sock_filter) { sock_filter_ctx_t *b = a->filter_ov; b->no_cache = intval; return 0; } #endif } else if (cmd == IOBUF_IOCTL_FSYNC) { /* Do a fsync on the open fd and return any errors to the caller of iobuf_ioctl. Note that we work on a file name here. */ if (DBG_IOBUF) log_debug ("iobuf-*.*: ioctl '%s' fsync\n", ptrval? (const char*)ptrval:""); if (!a && !intval && ptrval) { return fd_cache_synchronize (ptrval); } } return -1; } /**************** * Register an i/o filter. */ int iobuf_push_filter (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov) { return iobuf_push_filter2 (a, f, ov, 0); } int iobuf_push_filter2 (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov, int rel_ov) { iobuf_t b; size_t dummy_len = 0; int rc = 0; if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a))) return rc; if (a->subno >= MAX_NESTING_FILTER) { log_error ("i/o filter too deeply nested - corrupted data?\n"); return GPG_ERR_BAD_DATA; } /* We want to create a new filter and put it in front of A. A simple implementation would do: b = iobuf_alloc (...); b->chain = a; return a; This is a bit problematic: A is the head of the pipeline and there are potentially many pointers to it. Requiring the caller to update all of these pointers is a burden. An alternative implementation would add a level of indirection. For instance, we could use a pipeline object, which contains a pointer to the first filter in the pipeline. This is not what we do either. Instead, we allocate a new buffer (B) and copy the first filter's state into that and use the initial buffer (A) for the new filter. One limitation of this approach is that it is not practical to maintain a pointer to a specific filter's state. Before: A | v 0x100 0x200 +----------+ +----------+ | filter x |--------->| filter y |---->.... +----------+ +----------+ After: B | v 0x300 +----------+ A | filter x | | +----------+ v 0x100 ^ v 0x200 +----------+ +----------+ | filter w | | filter y |---->.... +----------+ +----------+ Note: filter x's address changed from 0x100 to 0x300, but A still points to the head of the pipeline. */ b = xmalloc (sizeof *b); memcpy (b, a, sizeof *b); /* fixme: it is stupid to keep a copy of the name at every level * but we need the name somewhere because the name known by file_filter * may have been released when we need the name of the file */ b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL; /* remove the filter stuff from the new stream */ a->filter = NULL; a->filter_ov = NULL; a->filter_ov_owner = 0; a->filter_eof = 0; if (a->use == IOBUF_OUTPUT_TEMP) /* A TEMP filter buffers any data sent to it; it does not forward any data down the pipeline. If we add a new filter to the pipeline, it shouldn't also buffer data. It should send it downstream to be buffered. Thus, the correct type for a filter added in front of an IOBUF_OUTPUT_TEMP filter is IOBUF_OUPUT, not IOBUF_OUTPUT_TEMP. */ { a->use = IOBUF_OUTPUT; /* When pipeline is written to, the temp buffer's size is increased accordingly. We don't need to allocate a 10 MB buffer for a non-terminal filter. Just use the default size. */ a->d.size = iobuf_buffer_size; } else if (a->use == IOBUF_INPUT_TEMP) /* Same idea as above. */ { a->use = IOBUF_INPUT; a->d.size = iobuf_buffer_size; } /* The new filter (A) gets a new buffer. If the pipeline is an output or temp pipeline, then giving the buffer to the new filter means that data that was written before the filter was pushed gets sent to the filter. That's clearly wrong. If the pipeline is an input pipeline, then giving the buffer to the new filter (A) means that data that has read from (B), but not yet read from the pipeline won't be processed by the new filter (A)! That's certainly not what we want. */ a->d.buf = xmalloc (a->d.size); a->d.len = 0; a->d.start = 0; /* disable nlimit for the new stream */ a->ntotal = b->ntotal + b->nbytes; a->nlimit = a->nbytes = 0; a->nofast = 0; /* make a link from the new stream to the original stream */ a->chain = b; /* setup the function on the new stream */ a->filter = f; a->filter_ov = ov; a->filter_ov_owner = rel_ov; a->subno = b->subno + 1; if (DBG_IOBUF) { byte desc[MAX_IOBUF_DESC]; log_debug ("iobuf-%d.%d: push '%s'\n", a->no, a->subno, iobuf_desc (a, desc)); print_chain (a); } /* now we can initialize the new function if we have one */ if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain, NULL, &dummy_len))) log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc)); return rc; } /**************** * Remove an i/o filter. */ int iobuf_pop_filter (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov) { iobuf_t b; size_t dummy_len = 0; int rc = 0; byte desc[MAX_IOBUF_DESC]; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: pop '%s'\n", a->no, a->subno, iobuf_desc (a, desc)); if (a->use == IOBUF_INPUT_TEMP || a->use == IOBUF_OUTPUT_TEMP) { /* This should be the last filter in the pipeline. */ assert (! a->chain); return 0; } if (!a->filter) { /* this is simple */ b = a->chain; assert (b); xfree (a->d.buf); xfree (a->real_fname); memcpy (a, b, sizeof *a); xfree (b); return 0; } for (b = a; b; b = b->chain) if (b->filter == f && (!ov || b->filter_ov == ov)) break; if (!b) log_bug ("iobuf_pop_filter(): filter function not found\n"); /* flush this stream if it is an output stream */ if (a->use == IOBUF_OUTPUT && (rc = filter_flush (b))) { log_error ("filter_flush failed in iobuf_pop_filter: %s\n", gpg_strerror (rc)); return rc; } /* and tell the filter to free it self */ if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain, NULL, &dummy_len))) { log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc)); return rc; } if (b->filter_ov && b->filter_ov_owner) { xfree (b->filter_ov); b->filter_ov = NULL; } /* and see how to remove it */ if (a == b && !b->chain) log_bug ("can't remove the last filter from the chain\n"); else if (a == b) { /* remove the first iobuf from the chain */ /* everything from b is copied to a. This is save because * a flush has been done on the to be removed entry */ b = a->chain; xfree (a->d.buf); xfree (a->real_fname); memcpy (a, b, sizeof *a); xfree (b); if (DBG_IOBUF) log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno); } else if (!b->chain) { /* remove the last iobuf from the chain */ log_bug ("Ohh jeee, trying to remove a head filter\n"); } else { /* remove an intermediate iobuf from the chain */ log_bug ("Ohh jeee, trying to remove an intermediate filter\n"); } return rc; } /**************** * read underflow: read at least one byte into the buffer and return * the first byte or -1 on EOF. */ static int underflow (iobuf_t a, int clear_pending_eof) { return underflow_target (a, clear_pending_eof, 1); } /**************** * read underflow: read TARGET bytes into the buffer and return * the first byte or -1 on EOF. */ static int underflow_target (iobuf_t a, int clear_pending_eof, size_t target) { size_t len; int rc; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: underflow: buffer size: %d; still buffered: %d => space for %d bytes\n", a->no, a->subno, (int) a->d.size, (int) (a->d.len - a->d.start), (int) (a->d.size - (a->d.len - a->d.start))); if (a->use == IOBUF_INPUT_TEMP) /* By definition, there isn't more data to read into the buffer. */ return -1; assert (a->use == IOBUF_INPUT); /* If there is still some buffered data, then move it to the start of the buffer and try to fill the end of the buffer. (This is useful if we are called from iobuf_peek().) */ assert (a->d.start <= a->d.len); a->d.len -= a->d.start; memmove (a->d.buf, &a->d.buf[a->d.start], a->d.len); a->d.start = 0; if (a->d.len < target && a->filter_eof) /* The last time we tried to read from this filter, we got an EOF. We couldn't return the EOF, because there was buffered data. Since there is no longer any buffered data, return the error. */ { if (DBG_IOBUF) log_debug ("iobuf-%d.%d: underflow: eof (pending eof)\n", a->no, a->subno); if (! clear_pending_eof) return -1; if (a->chain) /* A filter follows this one. Free this filter. */ { iobuf_t b = a->chain; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: filter popped (pending EOF returned)\n", a->no, a->subno); xfree (a->d.buf); xfree (a->real_fname); memcpy (a, b, sizeof *a); xfree (b); print_chain (a); } else a->filter_eof = 0; /* for the top level filter */ return -1; /* return one(!) EOF */ } if (a->d.len == 0 && a->error) /* The last time we tried to read from this filter, we got an error. We couldn't return the error, because there was buffered data. Since there is no longer any buffered data, return the error. */ { if (DBG_IOBUF) log_debug ("iobuf-%d.%d: pending error (%s) returned\n", a->no, a->subno, gpg_strerror (a->error)); return -1; } if (a->filter && ! a->filter_eof && ! a->error) /* We have a filter function and the last time we tried to read we didn't get an EOF or an error. Try to fill the buffer. */ { /* Be careful to account for any buffered data. */ len = a->d.size - a->d.len; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: underflow: A->FILTER (%lu bytes)\n", a->no, a->subno, (ulong) len); if (len == 0) /* There is no space for more data. Don't bother calling A->FILTER. */ rc = 0; else rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain, &a->d.buf[a->d.len], &len); a->d.len += len; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: A->FILTER() returned rc=%d (%s), read %lu bytes\n", a->no, a->subno, rc, rc == 0 ? "ok" : rc == -1 ? "EOF" : gpg_strerror (rc), (ulong) len); /* if( a->no == 1 ) */ /* log_hexdump (" data:", a->d.buf, len); */ if (rc == -1) /* EOF. */ { size_t dummy_len = 0; /* Tell the filter to free itself */ if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain, NULL, &dummy_len))) log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc)); /* Free everything except for the internal buffer. */ if (a->filter_ov && a->filter_ov_owner) xfree (a->filter_ov); a->filter_ov = NULL; a->filter = NULL; a->filter_eof = 1; if (clear_pending_eof && a->d.len == 0 && a->chain) /* We don't need to keep this filter around at all: - we got an EOF - we have no buffered data - a filter follows this one. Unlink this filter. */ { iobuf_t b = a->chain; if (DBG_IOBUF) log_debug ("iobuf-%d.%d: pop in underflow (nothing buffered, got EOF)\n", a->no, a->subno); xfree (a->d.buf); xfree (a->real_fname); memcpy (a, b, sizeof *a); xfree (b); print_chain (a); return -1; } else if (a->d.len == 0) /* We can't unlink this filter (it is the only one in the pipeline), but we can immediately return EOF. */ return -1; } else if (rc) /* Record the error. */ { a->error = rc; if (a->d.len == 0) /* There is no buffered data. Immediately return EOF. */ return -1; } } assert (a->d.start <= a->d.len); if (a->d.start < a->d.len) return a->d.buf[a->d.start++]; /* EOF. */ return -1; } static int filter_flush (iobuf_t a) { size_t len; int rc; if (a->use == IOBUF_OUTPUT_TEMP) { /* increase the temp buffer */ size_t newsize = a->d.size + iobuf_buffer_size; if (DBG_IOBUF) log_debug ("increasing temp iobuf from %lu to %lu\n", (ulong) a->d.size, (ulong) newsize); a->d.buf = xrealloc (a->d.buf, newsize); a->d.size = newsize; return 0; } else if (a->use != IOBUF_OUTPUT) log_bug ("flush on non-output iobuf\n"); else if (!a->filter) log_bug ("filter_flush: no filter\n"); len = a->d.len; rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len); if (!rc && len != a->d.len) { log_info ("filter_flush did not write all!\n"); rc = GPG_ERR_INTERNAL; } else if (rc) a->error = rc; a->d.len = 0; return rc; } int iobuf_readbyte (iobuf_t a) { int c; if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP) { log_bug ("iobuf_readbyte called on a non-INPUT pipeline!\n"); return -1; } assert (a->d.start <= a->d.len); if (a->nlimit && a->nbytes >= a->nlimit) return -1; /* forced EOF */ if (a->d.start < a->d.len) { c = a->d.buf[a->d.start++]; } else if ((c = underflow (a, 1)) == -1) return -1; /* EOF */ assert (a->d.start <= a->d.len); /* Note: if underflow doesn't return EOF, then it returns the first byte that was read and advances a->d.start appropriately. */ a->nbytes++; return c; } int iobuf_read (iobuf_t a, void *buffer, unsigned int buflen) { unsigned char *buf = (unsigned char *)buffer; int c, n; if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP) { log_bug ("iobuf_read called on a non-INPUT pipeline!\n"); return -1; } if (a->nlimit) { /* Handle special cases. */ for (n = 0; n < buflen; n++) { if ((c = iobuf_readbyte (a)) == -1) { if (!n) return -1; /* eof */ break; } if (buf) { *buf = c; buf++; } } return n; } n = 0; do { if (n < buflen && a->d.start < a->d.len) /* Drain the buffer. */ { unsigned size = a->d.len - a->d.start; if (size > buflen - n) size = buflen - n; if (buf) memcpy (buf, a->d.buf + a->d.start, size); n += size; a->d.start += size; if (buf) buf += size; } if (n < buflen) /* Draining the internal buffer didn't fill BUFFER. Call underflow to read more data into the filter's internal buffer. */ { if ((c = underflow (a, 1)) == -1) /* EOF. If we managed to read something, don't return EOF now. */ { a->nbytes += n; return n ? n : -1 /*EOF*/; } if (buf) *buf++ = c; n++; } } while (n < buflen); a->nbytes += n; return n; } int iobuf_peek (iobuf_t a, byte * buf, unsigned buflen) { int n = 0; assert (buflen > 0); assert (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP); if (buflen > a->d.size) /* We can't peek more than we can buffer. */ buflen = a->d.size; /* Try to fill the internal buffer with enough data to satisfy the request. */ while (buflen > a->d.len - a->d.start) { if (underflow_target (a, 0, buflen) == -1) /* EOF. We can't read any more. */ break; /* Underflow consumes the first character (it's the return value). unget() it by resetting the "file position". */ assert (a->d.start == 1); a->d.start = 0; } n = a->d.len - a->d.start; if (n > buflen) n = buflen; if (n == 0) /* EOF. */ return -1; memcpy (buf, &a->d.buf[a->d.start], n); return n; } int iobuf_writebyte (iobuf_t a, unsigned int c) { int rc; if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP) { log_bug ("iobuf_writebyte called on an input pipeline!\n"); return -1; } if (a->d.len == a->d.size) if ((rc=filter_flush (a))) return rc; assert (a->d.len < a->d.size); a->d.buf[a->d.len++] = c; return 0; } int iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen) { const unsigned char *buf = (const unsigned char *)buffer; int rc; if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP) { log_bug ("iobuf_write called on an input pipeline!\n"); return -1; } do { if (buflen && a->d.len < a->d.size) { unsigned size = a->d.size - a->d.len; if (size > buflen) size = buflen; memcpy (a->d.buf + a->d.len, buf, size); buflen -= size; buf += size; a->d.len += size; } if (buflen) { rc = filter_flush (a); if (rc) return rc; } } while (buflen); return 0; } int iobuf_writestr (iobuf_t a, const char *buf) { if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP) { log_bug ("iobuf_writestr called on an input pipeline!\n"); return -1; } return iobuf_write (a, buf, strlen (buf)); } int iobuf_write_temp (iobuf_t dest, iobuf_t source) { assert (source->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP); assert (dest->use == IOBUF_OUTPUT || dest->use == IOBUF_OUTPUT_TEMP); iobuf_flush_temp (source); return iobuf_write (dest, source->d.buf, source->d.len); } size_t iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen) { byte desc[MAX_IOBUF_DESC]; size_t n; while (1) { int rc = filter_flush (a); if (rc) log_bug ("Flushing iobuf %d.%d (%s) from iobuf_temp_to_buffer failed. Ignoring.\n", a->no, a->subno, iobuf_desc (a, desc)); if (! a->chain) break; a = a->chain; } n = a->d.len; if (n > buflen) n = buflen; memcpy (buffer, a->d.buf, n); return n; } /* Copies the data from the input iobuf SOURCE to the output iobuf DEST until either an error is encountered or EOF is reached. Returns the number of bytes copies. */ size_t iobuf_copy (iobuf_t dest, iobuf_t source) { char *temp; /* Use a 32 KB buffer. */ const size_t temp_size = 32 * 1024; size_t nread; size_t nwrote = 0; size_t max_read = 0; int err; assert (source->use == IOBUF_INPUT || source->use == IOBUF_INPUT_TEMP); assert (dest->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP); if (iobuf_error (dest)) return -1; temp = xmalloc (temp_size); while (1) { nread = iobuf_read (source, temp, temp_size); if (nread == -1) /* EOF. */ break; if (nread > max_read) max_read = nread; err = iobuf_write (dest, temp, nread); if (err) break; nwrote += nread; } /* Burn the buffer. */ if (max_read) wipememory (temp, max_read); xfree (temp); return nwrote; } void iobuf_flush_temp (iobuf_t temp) { if (temp->use == IOBUF_INPUT || temp->use == IOBUF_INPUT_TEMP) log_bug ("iobuf_flush_temp called on an input pipeline!\n"); while (temp->chain) iobuf_pop_filter (temp, temp->filter, NULL); } void iobuf_set_limit (iobuf_t a, off_t nlimit) { if (nlimit) a->nofast = 1; else a->nofast = 0; a->nlimit = nlimit; a->ntotal += a->nbytes; a->nbytes = 0; } off_t iobuf_get_filelength (iobuf_t a, int *overflow) { if (overflow) *overflow = 0; /* Hmmm: file_filter may have already been removed */ for ( ; a->chain; a = a->chain ) ; if (a->filter != file_filter) return 0; { file_filter_ctx_t *b = a->filter_ov; gnupg_fd_t fp = b->fp; #if defined(HAVE_W32_SYSTEM) ulong size; static int (* __stdcall get_file_size_ex) (void *handle, LARGE_INTEGER *r_size); static int get_file_size_ex_initialized; if (!get_file_size_ex_initialized) { void *handle; handle = dlopen ("kernel32.dll", RTLD_LAZY); if (handle) { get_file_size_ex = dlsym (handle, "GetFileSizeEx"); if (!get_file_size_ex) dlclose (handle); } get_file_size_ex_initialized = 1; } if (get_file_size_ex) { /* This is a newer system with GetFileSizeEx; we use this then because it seem that GetFileSize won't return a proper error in case a file is larger than 4GB. */ LARGE_INTEGER exsize; if (get_file_size_ex (fp, &exsize)) { if (!exsize.u.HighPart) return exsize.u.LowPart; if (overflow) *overflow = 1; return 0; } } else { if ((size=GetFileSize (fp, NULL)) != 0xffffffff) return size; } log_error ("GetFileSize for handle %p failed: %s\n", fp, w32_strerror (0)); #else /*!HAVE_W32_SYSTEM*/ { struct stat st; if ( !fstat (FD2INT (fp), &st) ) return st.st_size; log_error("fstat() failed: %s\n", strerror(errno) ); } #endif /*!HAVE_W32_SYSTEM*/ } return 0; } int iobuf_get_fd (iobuf_t a) { for (; a->chain; a = a->chain) ; if (a->filter != file_filter) return -1; { file_filter_ctx_t *b = a->filter_ov; gnupg_fd_t fp = b->fp; return FD2INT (fp); } } off_t iobuf_tell (iobuf_t a) { return a->ntotal + a->nbytes; } #if !defined(HAVE_FSEEKO) && !defined(fseeko) #ifdef HAVE_LIMITS_H # include #endif #ifndef LONG_MAX # define LONG_MAX ((long) ((unsigned long) -1 >> 1)) #endif #ifndef LONG_MIN # define LONG_MIN (-1 - LONG_MAX) #endif /**************** * A substitute for fseeko, for hosts that don't have it. */ static int fseeko (FILE * stream, off_t newpos, int whence) { while (newpos != (long) newpos) { long pos = newpos < 0 ? LONG_MIN : LONG_MAX; if (fseek (stream, pos, whence) != 0) return -1; newpos -= pos; whence = SEEK_CUR; } return fseek (stream, (long) newpos, whence); } #endif int iobuf_seek (iobuf_t a, off_t newpos) { file_filter_ctx_t *b = NULL; if (a->use == IOBUF_OUTPUT || a->use == IOBUF_INPUT) { /* Find the last filter in the pipeline. */ for (; a->chain; a = a->chain) ; if (a->filter != file_filter) return -1; b = a->filter_ov; #ifdef HAVE_W32_SYSTEM if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff) { log_error ("SetFilePointer failed on handle %p: ec=%d\n", b->fp, (int) GetLastError ()); return -1; } #else if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1) { log_error ("can't lseek: %s\n", strerror (errno)); return -1; } #endif /* Discard the buffer it is not a temp stream. */ a->d.len = 0; } a->d.start = 0; a->nbytes = 0; a->nlimit = 0; a->nofast = 0; a->ntotal = newpos; a->error = 0; /* It is impossible for A->CHAIN to be non-NULL. If A is an INPUT or OUTPUT buffer, then we find the last filter, which is defined as A->CHAIN being NULL. If A is a TEMP filter, then A must be the only filter in the pipe: when iobuf_push_filter adds a filter to the front of a pipeline, it sets the new filter to be an OUTPUT filter if the pipeline is an OUTPUT or TEMP pipeline and to be an INPUT filter if the pipeline is an INPUT pipeline. Thus, only the last filter in a TEMP pipeline can be a */ /* remove filters, but the last */ if (a->chain) log_debug ("iobuf_pop_filter called in iobuf_seek - please report\n"); while (a->chain) iobuf_pop_filter (a, a->filter, NULL); return 0; } const char * iobuf_get_real_fname (iobuf_t a) { if (a->real_fname) return a->real_fname; /* the old solution */ for (; a; a = a->chain) if (!a->chain && a->filter == file_filter) { file_filter_ctx_t *b = a->filter_ov; return b->print_only_name ? NULL : b->fname; } return NULL; } const char * iobuf_get_fname (iobuf_t a) { for (; a; a = a->chain) if (!a->chain && a->filter == file_filter) { file_filter_ctx_t *b = a->filter_ov; return b->fname; } return NULL; } const char * iobuf_get_fname_nonnull (iobuf_t a) { const char *fname; fname = iobuf_get_fname (a); return fname? fname : "[?]"; } /**************** * Enable or disable partial body length mode (RFC 4880 4.2.2.4). * * If LEN is 0, this disables partial block mode by popping the * partial body length filter, which must be the most recently * added filter. * * If LEN is non-zero, it pushes a partial body length filter. If * this is a read filter, LEN must be the length byte from the first * chunk and A should be position just after this first partial body * length header. */ void iobuf_set_partial_body_length_mode (iobuf_t a, size_t len) { if (!len) /* Disable partial body length mode. */ { if (a->use == IOBUF_INPUT) log_debug ("iobuf_pop_filter called in set_partial_block_mode" " - please report\n"); log_assert (a->filter == block_filter); iobuf_pop_filter (a, block_filter, NULL); } else /* Enabled partial body length mode. */ { block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx); ctx->use = a->use; ctx->partial = 1; ctx->size = 0; ctx->first_c = len; iobuf_push_filter (a, block_filter, ctx); } } unsigned int iobuf_read_line (iobuf_t a, byte ** addr_of_buffer, unsigned *length_of_buffer, unsigned *max_length) { int c; char *buffer = (char *)*addr_of_buffer; unsigned length = *length_of_buffer; unsigned nbytes = 0; unsigned maxlen = *max_length; char *p; /* The code assumes that we have space for at least a newline and a NUL character in the buffer. This requires at least 2 bytes. We don't complicate the code by handling the stupid corner case, but simply assert that it can't happen. */ assert (!buffer || length >= 2 || maxlen >= 2); if (!buffer || length <= 1) /* must allocate a new buffer */ { length = 256 <= maxlen ? 256 : maxlen; buffer = xrealloc (buffer, length); *addr_of_buffer = (unsigned char *)buffer; *length_of_buffer = length; } p = buffer; while (1) { if (!a->nofast && a->d.start < a->d.len && nbytes < length - 1) /* Fast path for finding '\n' by using standard C library's optimized memchr. */ { unsigned size = a->d.len - a->d.start; byte *newline_pos; if (size > length - 1 - nbytes) size = length - 1 - nbytes; newline_pos = memchr (a->d.buf + a->d.start, '\n', size); if (newline_pos) { /* Found newline, copy buffer and return. */ size = (newline_pos - (a->d.buf + a->d.start)) + 1; memcpy (p, a->d.buf + a->d.start, size); p += size; nbytes += size; a->d.start += size; a->nbytes += size; break; } else { /* No newline, copy buffer and continue. */ memcpy (p, a->d.buf + a->d.start, size); p += size; nbytes += size; a->d.start += size; a->nbytes += size; } } else { c = iobuf_readbyte (a); if (c == -1) break; *p++ = c; nbytes++; if (c == '\n') break; } if (nbytes == length - 1) /* We don't have enough space to add a \n and a \0. Increase the buffer size. */ { if (length == maxlen) /* We reached the buffer's size limit! */ { /* Skip the rest of the line. */ while (c != '\n' && (c = iobuf_get (a)) != -1) ; /* p is pointing at the last byte in the buffer. We always terminate the line with "\n\0" so overwrite the previous byte with a \n. */ assert (p > buffer); p[-1] = '\n'; /* Indicate truncation. */ *max_length = 0; break; } length += length < 1024 ? 256 : 1024; if (length > maxlen) length = maxlen; buffer = xrealloc (buffer, length); *addr_of_buffer = (unsigned char *)buffer; *length_of_buffer = length; p = buffer + nbytes; } } /* Add the terminating NUL. */ *p = 0; /* Return the number of characters written to the buffer including the newline, but not including the terminating NUL. */ return nbytes; } static int translate_file_handle (int fd, int for_write) { #if defined(HAVE_W32CE_SYSTEM) /* This is called only with one of the special filenames. Under W32CE the FD here is not a file descriptor but a rendezvous id, thus we need to finish the pipe first. */ fd = _assuan_w32ce_finish_pipe (fd, for_write); #elif defined(HAVE_W32_SYSTEM) { int x; (void)for_write; if (fd == 0) x = (int) GetStdHandle (STD_INPUT_HANDLE); else if (fd == 1) x = (int) GetStdHandle (STD_OUTPUT_HANDLE); else if (fd == 2) x = (int) GetStdHandle (STD_ERROR_HANDLE); else x = fd; if (x == -1) log_debug ("GetStdHandle(%d) failed: ec=%d\n", fd, (int) GetLastError ()); fd = x; } #else (void)for_write; #endif return fd; } void iobuf_skip_rest (iobuf_t a, unsigned long n, int partial) { if ( partial ) { for (;;) { if (a->nofast || a->d.start >= a->d.len) { if (iobuf_readbyte (a) == -1) { break; } } else { unsigned long count = a->d.len - a->d.start; a->nbytes += count; a->d.start = a->d.len; } } } else { unsigned long remaining = n; while (remaining > 0) { if (a->nofast || a->d.start >= a->d.len) { if (iobuf_readbyte (a) == -1) { break; } --remaining; } else { unsigned long count = a->d.len - a->d.start; if (count > remaining) { count = remaining; } a->nbytes += count; a->d.start += count; remaining -= count; } } } } diff --git a/common/iobuf.h b/common/iobuf.h index 9c9650c61..a3d9bd547 100644 --- a/common/iobuf.h +++ b/common/iobuf.h @@ -1,630 +1,623 @@ /* iobuf.h - I/O buffer * Copyright (C) 1998, 1999, 2000, 2001, 2003, * 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_IOBUF_H #define GNUPG_COMMON_IOBUF_H /* An iobuf is basically a filter in a pipeline. Consider the following command, which consists of three filters that are chained together: $ cat file | base64 --decode | gunzip The first filter reads the file from the file system and sends that data to the second filter. The second filter decodes base64-encoded data and sends the data to the third and last filter. The last filter decompresses the data and the result is displayed on the terminal. The iobuf system works in the same way where each iobuf is a filter and the individual iobufs can be chained together. There are number of predefined filters. iobuf_open(), for instance, creates a filter that reads from a specified file. And, iobuf_temp_with_content() creates a filter that returns some specified contents. There are also filters for writing content. iobuf_openrw opens a file for writing. iobuf_temp creates a filter that writes data to a fixed-sized buffer. To chain filters together, you use the iobuf_push_filter() function. The filters are chained together using the chain field in the iobuf_t. A pipeline can only be used for reading (IOBUF_INPUT) or for writing (IOBUF_OUTPUT / IOBUF_OUTPUT_TEMP). When reading, data flows from the last filter towards the first. That is, the user calls iobuf_read(), the module reads from the first filter, which gets its input from the second filter, etc. When writing, data flows from the first filter towards the last. In this case, when the user calls iobuf_write(), the data is written to the first filter, which writes the transformed data to the second filter, etc. An iobuf_t contains some state about the filter. For instance, it indicates if the filter has already returned EOF (filter_eof) and the next filter in the pipeline, if any (chain). It also contains a function pointer, filter. This is a generic function. It is called when input is needed or output is available. In this case it is passed a pointer to some filter-specific persistent state (filter_ov), the actual operation, the next filter in the chain, if any, and a buffer that either contains the contents to write, if the pipeline is setup to write data, or is the place to store data, if the pipeline is setup to read data. Unlike a Unix pipeline, an IOBUF pipeline can return EOF multiple times. This is similar to the following: { cat file1; cat file2; } | grep foo However, instead of grep seeing a single stream, grep would see each byte stream followed by an EOF marker. (When a filter returns EOF, the EOF is returned to the user exactly once and then the filter is removed from the pipeline.) */ /* For estream_t. */ #include #include "../common/types.h" #include "../common/sysutils.h" #define DBG_IOBUF iobuf_debug_mode /* Filter control modes. */ enum { IOBUFCTRL_INIT = 1, IOBUFCTRL_FREE = 2, IOBUFCTRL_UNDERFLOW = 3, IOBUFCTRL_FLUSH = 4, IOBUFCTRL_DESC = 5, IOBUFCTRL_CANCEL = 6, IOBUFCTRL_USER = 16 }; /* Command codes for iobuf_ioctl. */ typedef enum { IOBUF_IOCTL_KEEP_OPEN = 1, /* Uses intval. */ IOBUF_IOCTL_INVALIDATE_CACHE = 2, /* Uses ptrval. */ IOBUF_IOCTL_NO_CACHE = 3, /* Uses intval. */ IOBUF_IOCTL_FSYNC = 4 /* Uses ptrval. */ } iobuf_ioctl_t; enum iobuf_use { /* Pipeline is in input mode. The data flows from the end to the beginning. That is, when reading from the pipeline, the first filter gets its input from the second filter, etc. */ IOBUF_INPUT, /* Pipeline is in input mode. The last filter in the pipeline is a temporary buffer from which the data is "read". */ IOBUF_INPUT_TEMP, /* Pipeline is in output mode. The data flows from the beginning to the end. That is, when writing to the pipeline, the user writes to the first filter, which transforms the data and sends it to the second filter, etc. */ IOBUF_OUTPUT, /* Pipeline is in output mode. The last filter in the pipeline is a temporary buffer that grows as necessary. */ IOBUF_OUTPUT_TEMP }; typedef struct iobuf_struct *iobuf_t; typedef struct iobuf_struct *IOBUF; /* Compatibility with gpg 1.4. */ /* fixme: we should hide most of this stuff */ struct iobuf_struct { /* The type of filter. Either IOBUF_INPUT, IOBUF_OUTPUT or IOBUF_OUTPUT_TEMP. */ enum iobuf_use use; /* nlimit can be changed using iobuf_set_limit. If non-zero, it is the number of additional bytes that can be read from the filter before EOF is forcefully returned. */ off_t nlimit; /* nbytes if the number of bytes that have been read (using iobuf_get / iobuf_readbyte / iobuf_read) since the last call to iobuf_set_limit. */ off_t nbytes; /* The number of bytes read prior to the last call to iobuf_set_limit. Thus, the total bytes read (i.e., the position of stream) is ntotal + nbytes. */ off_t ntotal; /* Whether we need to read from the filter one byte at a time or whether we can do bulk reads. We need to read one byte at a time if a limit (set via iobuf_set_limit) is active. */ int nofast; /* A buffer for unread/unwritten data. For an output pipeline (IOBUF_OUTPUT), this is the data that has not yet been written to the filter. Consider a simple pipeline consisting of a single stage, which writes to a file. When you write to the pipeline (iobuf_writebyte or iobuf_write), the data is first stored in this buffer. Only when the buffer is full or you call iobuf_flush() is FILTER actually called and the data written to the file. For an input pipeline (IOBUF_INPUT), this is the data that has been read from this filter, but not yet been read from the preceding filter (or the user, if this filter is the head of the pipeline). Again, consider a simple pipeline consisting of a single stage. This stage reads from a file. If you read a single byte (iobuf_get) and the buffer is empty, then FILTER is called to fill the buffer. In this case, a single byte is not requested, but the whole buffer is filled (if possible). */ struct { /* Size of the buffer. */ size_t size; /* Number of bytes at the beginning of the buffer that have already been consumed. (In other words: the index of the first byte that hasn't been consumed.) This is only non-zero for input filters. */ size_t start; /* The number of bytes in the buffer including any bytes that have been consumed. */ size_t len; /* The buffer itself. */ byte *buf; } d; /* When FILTER is called to read some data, it may read some data and then return EOF. We can't return the EOF immediately. Instead, we note that we observed the EOF and when the buffer is finally empty, we return the EOF. */ int filter_eof; /* Like filter_eof, when FILTER is called to read some data, it may read some data and then return an error. We can't return the error (in the form of an EOF) immediately. Instead, we note that we observed the error and when the buffer is finally empty, we return the EOF. */ int error; /* The callback function to read data from the filter, etc. See iobuf_filter_push for details. */ int (*filter) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len); /* An opaque pointer that can be used for local filter state. This is passed as the first parameter to FILTER. */ void *filter_ov; /* Whether the iobuf code should free(filter_ov) when destroying the filter. */ int filter_ov_owner; /* When using iobuf_open, iobuf_create, iobuf_openrw to open a file, the file's name is saved here. This is used to delete the file when an output pipeline (IOBUF_OUPUT) is canceled (iobuf_cancel). */ char *real_fname; /* The next filter in the pipeline. */ iobuf_t chain; /* This field is for debugging. Each time a filter is allocated (via iobuf_alloc()), a monotonically increasing counter is incremented and this field is set to the new value. This field should only be accessed via the iobuf_io macro. */ int no; /* The number of filters in the pipeline following (not including) this one. When you call iobuf_push_filter or iobuf_push_filter2, this value is used to check the length of the pipeline if the pipeline already contains 65 stages then these functions fail. This amount of nesting typically indicates corrupted data or an active denial of service attack. */ int subno; }; -#ifndef EXTERN_UNLESS_MAIN_MODULE -#if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE) -#define EXTERN_UNLESS_MAIN_MODULE extern -#else -#define EXTERN_UNLESS_MAIN_MODULE -#endif -#endif -EXTERN_UNLESS_MAIN_MODULE int iobuf_debug_mode; +extern int iobuf_debug_mode; /* Change the default size for all IOBUFs to KILOBYTE. This needs to * be called before any iobufs are used and can only be used once. * Returns the current value. Using 0 has no effect except for * returning the current value. */ unsigned int iobuf_set_buffer_size (unsigned int kilobyte); /* Returns whether the specified filename corresponds to a pipe. In particular, this function checks if FNAME is "-" and, if special filenames are enabled (see check_special_filename), whether FNAME is a special filename. */ int iobuf_is_pipe_filename (const char *fname); /* Allocate a new filter. This filter doesn't have a function assigned to it. Thus you need to manually set IOBUF->FILTER and IOBUF->FILTER_OV, if required. This function is intended to help create a new primary source or primary sink, i.e., the last filter in the pipeline. USE is IOBUF_INPUT, IOBUF_INPUT_TEMP, IOBUF_OUTPUT or IOBUF_OUTPUT_TEMP. BUFSIZE is the desired internal buffer size (that is, the size of the typical read / write request). */ iobuf_t iobuf_alloc (int use, size_t bufsize); /* Create an output filter that simply buffers data written to it. This is useful for collecting data for later processing. The buffer can be written to in the usual way (iobuf_write, etc.). The data can later be extracted using iobuf_write_temp() or iobuf_temp_to_buffer(). */ iobuf_t iobuf_temp (void); /* Create an input filter that contains some data for reading. */ iobuf_t iobuf_temp_with_content (const char *buffer, size_t length); /* Create an input file filter that reads from a file. If FNAME is '-', reads from stdin. If special filenames are enabled (iobuf_enable_special_filenames), then interprets special filenames. */ iobuf_t iobuf_open (const char *fname); /* Create an output file filter that writes to a file. If FNAME is NULL or '-', writes to stdout. If special filenames are enabled (iobuf_enable_special_filenames), then interprets special filenames. If FNAME is not NULL, '-' or a special filename, the file is opened for writing. If the file exists, it is truncated. If MODE700 is TRUE, the file is created with mode 600. Otherwise, mode 666 is used. */ iobuf_t iobuf_create (const char *fname, int mode700); /* Create an output file filter that writes to a specified file. Neither '-' nor special file names are recognized. */ iobuf_t iobuf_openrw (const char *fname); /* Create a file filter using an existing file descriptor. If MODE contains the letter 'w', creates an output filter. Otherwise, creates an input filter. Note: MODE must reflect the file descriptors actual mode! When the filter is destroyed, the file descriptor is closed. */ iobuf_t iobuf_fdopen (int fd, const char *mode); /* Like iobuf_fdopen, but doesn't close the file descriptor when the filter is destroyed. */ iobuf_t iobuf_fdopen_nc (int fd, const char *mode); /* Create a filter using an existing estream. If MODE contains the letter 'w', creates an output filter. Otherwise, creates an input filter. If KEEP_OPEN is TRUE, then the stream is not closed when the filter is destroyed. Otherwise, the stream is closed when the filter is destroyed. If READLIMIT is not 0 this gives a limit on the number of bytes to read from estream. */ iobuf_t iobuf_esopen (estream_t estream, const char *mode, int keep_open, size_t readlimit); /* Create a filter using an existing socket. On Windows creates a special socket filter. On non-Windows systems simply, this simply calls iobuf_fdopen. */ iobuf_t iobuf_sockopen (int fd, const char *mode); /* Set various options / perform different actions on a PIPELINE. See the IOBUF_IOCTL_* macros above. */ int iobuf_ioctl (iobuf_t a, iobuf_ioctl_t cmd, int intval, void *ptrval); /* Close a pipeline. The filters in the pipeline are first flushed using iobuf_flush, if they are output filters, and then IOBUFCTRL_FREE is called on each filter. If any filter returns a non-zero value in response to the IOBUFCTRL_FREE, that first such non-zero value is returned. Note: processing is not aborted in this case. If all filters are freed successfully, 0 is returned. */ int iobuf_close (iobuf_t iobuf); /* Calls IOBUFCTRL_CANCEL on each filter in the pipeline. Then calls io_close() on the pipeline. Finally, if the pipeline is an output pipeline, deletes the file. Returns the result of calling iobuf_close on the pipeline. */ int iobuf_cancel (iobuf_t iobuf); /* Add a new filter to the front of a pipeline. A is the head of the pipeline. F is the filter implementation. OV is an opaque pointer that is passed to F and is normally used to hold any internal state, such as a file pointer. Note: you may only maintain a reference to an iobuf_t as a reference to the head of the pipeline. That is, don't think about setting a pointer in OV to point to the filter's iobuf_t. This is because when we add a new filter to a pipeline, we memcpy the state in A into new buffer. This has the advantage that there is no need to update any references to the pipeline when a filter is added or removed, but it also means that a filter's state moves around in memory. The behavior of the filter function is determined by the value of the control parameter: IOBUFCTRL_INIT: Called this value just before the filter is linked into the pipeline. This can be used to initialize internal data structures. IOBUFCTRL_FREE: Called with this value just before the filter is removed from the pipeline. Normally used to release internal data structures, close a file handle, etc. IOBUFCTRL_UNDERFLOW: Called with this value to fill the passed buffer with more data. *LEN is the size of the buffer. Before returning, it should be set to the number of bytes which were written into the buffer. The function must return 0 to indicate success, -1 on EOF and a GPG_ERR_xxxxx code for any error. Note: this function may both return data and indicate an error or EOF. In this case, it simply writes the data to BUF, sets *LEN and returns the appropriate return code. The implication is that if an error occurs and no data has yet been written, it is essential that *LEN be set to 0! IOBUFCTRL_FLUSH: Called with this value to write out any collected data. *LEN is the number of bytes in BUF that need to be written out. Returns 0 on success and a GPG_ERR_* code otherwise. *LEN must be set to the number of bytes that were written out. IOBUFCTRL_CANCEL: Called with this value when iobuf_cancel() is called on the pipeline. IOBUFCTRL_DESC: Called with this value to get a human-readable description of the filter. *LEN is the size of the buffer. The description is filled into BUF, NUL-terminated. Always returns 0. */ int iobuf_push_filter (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov); /* This variant of iobuf_push_filter allows the called to indicate that OV should be freed when this filter is freed. That is, if REL_OV is TRUE, then when the filter is popped or freed OV will be freed after the filter function is called with control set to IOBUFCTRL_FREE. */ int iobuf_push_filter2 (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov, int rel_ov); /* Pop the top filter. The top filter must have the filter function F and the cookie OV. The cookie check is ignored if OV is NULL. */ int iobuf_pop_filter (iobuf_t a, int (*f) (void *opaque, int control, iobuf_t chain, byte * buf, size_t * len), void *ov); /* Used for debugging. Prints out the chain using log_debug if IOBUF_DEBUG_MODE is not 0. */ int iobuf_print_chain (iobuf_t a); /* Indicate that some error occurred on the specified filter. */ #define iobuf_set_error(a) do { (a)->error = 1; } while(0) /* Return any pending error on filter A. */ #define iobuf_error(a) ((a)->error) /* Limit the amount of additional data that may be read from the filter. That is, if you've already read 100 bytes from A and you set the limit to 50, then you can read up to an additional 50 bytes (i.e., a total of 150 bytes) before EOF is forcefully returned. Setting NLIMIT to 0 removes any active limit. Note: using iobuf_seek removes any currently enforced limit! */ void iobuf_set_limit (iobuf_t a, off_t nlimit); /* Returns the number of bytes that have been read from the pipeline. Note: the result is undefined for IOBUF_OUTPUT and IOBUF_OUTPUT_TEMP pipelines! */ off_t iobuf_tell (iobuf_t a); /* There are two cases: - If A is an INPUT or OUTPUT pipeline, then the last filter in the pipeline is found. If that is not a file filter, -1 is returned. Otherwise, an fseek(..., SEEK_SET) is performed on the file descriptor. - If A is a TEMP pipeline and the *first* (and thus only filter) is a TEMP filter, then the "file position" is effectively unchanged. That is, data is appended to the buffer and the seek does not cause the size of the buffer to grow. If no error occurred, then any limit previous set by iobuf_set_limit() is cleared. Further, any error on the filter (the file filter or the temp filter) is cleared. Returns 0 on success and -1 if an error occurs. */ int iobuf_seek (iobuf_t a, off_t newpos); /* Read a single byte. If a filter has no more data, returns -1 to indicate the EOF. Generally, you don't want to use this function, but instead prefer the iobuf_get macro, which is faster if there is data in the internal buffer. */ int iobuf_readbyte (iobuf_t a); /* Get a byte from the iobuf; must check for eof prior to this function. This function returns values in the range 0 .. 255 or -1 to indicate EOF. iobuf_get_noeof() does not return -1 to indicate EOF, but masks the returned value to be in the range 0 .. 255. */ #define iobuf_get(a) \ ( ((a)->nofast || (a)->d.start >= (a)->d.len )? \ iobuf_readbyte((a)) : ( (a)->nbytes++, (a)->d.buf[(a)->d.start++] ) ) #define iobuf_get_noeof(a) (iobuf_get((a))&0xff) /* Fill BUF with up to BUFLEN bytes. If a filter has no more data, returns -1 to indicate the EOF. Otherwise returns the number of bytes read. */ int iobuf_read (iobuf_t a, void *buf, unsigned buflen); /* Read a line of input (including the '\n') from the pipeline. The semantics are the same as for fgets(), but if the buffer is too short a larger one will be allocated up to *MAX_LENGTH and the end of the line except the trailing '\n' discarded. (Thus, *ADDR_OF_BUFFER must be allocated using malloc().) If the buffer is enlarged, then *LENGTH_OF_BUFFER will be updated to reflect the new size. If the line is truncated, then *MAX_LENGTH will be set to 0. If *ADDR_OF_BUFFER is NULL, a buffer is allocated using malloc(). A line is considered a byte stream ending in a '\n'. Returns the number of characters written to the buffer (i.e., excluding any discarded characters due to truncation). Thus, use this instead of strlen(buffer) to determine the length of the string as this is unreliable if the input contains NUL characters. EOF is indicated by a line of length zero. The last LF may be missing due to an EOF. */ unsigned iobuf_read_line (iobuf_t a, byte ** addr_of_buffer, unsigned *length_of_buffer, unsigned *max_length); /* Read up to BUFLEN bytes from pipeline A. Note: this function can't return more than the pipeline's internal buffer size. The return value is the number of bytes actually written to BUF. If the filter returns EOF, then this function returns -1. This function does not clear any pending EOF. That is, if the pipeline consists of two filters and the first one returns EOF during the peek, then the subsequent iobuf_read* will still return EOF before returning the data from the second filter. */ int iobuf_peek (iobuf_t a, byte * buf, unsigned buflen); /* Write a byte to the pipeline. Returns 0 on success and an error code otherwise. */ int iobuf_writebyte (iobuf_t a, unsigned c); /* Alias for iobuf_writebyte. */ #define iobuf_put(a,c) iobuf_writebyte(a,c) /* Write a sequence of bytes to the pipeline. Returns 0 on success and an error code otherwise. */ int iobuf_write (iobuf_t a, const void *buf, unsigned buflen); /* Write a string (not including the NUL terminator) to the pipeline. Returns 0 on success and an error code otherwise. */ int iobuf_writestr (iobuf_t a, const char *buf); /* Flushes the pipeline removing all filters but the sink (the last filter) in the process. */ void iobuf_flush_temp (iobuf_t temp); /* Flushes the pipeline SOURCE removing all filters but the sink (the last filter) in the process (i.e., it calls iobuf_flush_temp(source)) and then writes the data to the pipeline DEST. Note: this doesn't free (iobuf_close()) SOURCE. Both SOURCE and DEST must be output pipelines. */ int iobuf_write_temp (iobuf_t dest, iobuf_t source); /* Flushes each filter in the pipeline (i.e., sends any buffered data to the filter by calling IOBUFCTRL_FLUSH). Then, copies up to the first BUFLEN bytes from the last filter's internal buffer (which will only be non-empty if it is a temp filter) to the buffer BUFFER. Returns the number of bytes actually copied. */ size_t iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen); /* Copies the data from the input iobuf SOURCE to the output iobuf DEST until either an error is encountered or EOF is reached. Returns the number of bytes successfully written. If an error occurred, then any buffered bytes are not returned to SOURCE and are effectively lost. To check if an error occurred, use iobuf_error. */ size_t iobuf_copy (iobuf_t dest, iobuf_t source); /* Return the size of any underlying file. This only works with file_filter based pipelines. On Win32, it is sometimes not possible to determine the size of files larger than 4GB. In this case, *OVERFLOW (if not NULL) is set to 1. Otherwise, *OVERFLOW is set to 0. */ off_t iobuf_get_filelength (iobuf_t a, int *overflow); #define IOBUF_FILELENGTH_LIMIT 0xffffffff /* Return the file descriptor designating the underlying file. This only works with file_filter based pipelines. */ int iobuf_get_fd (iobuf_t a); /* Return the real filename, if available. This only supports pipelines that end in file filters. Returns NULL if not available. */ const char *iobuf_get_real_fname (iobuf_t a); /* Return the filename or a description thereof. For instance, for iobuf_open("-"), this will return "[stdin]". This only supports pipelines that end in file filters. Returns NULL if not available. */ const char *iobuf_get_fname (iobuf_t a); /* Like iobuf_getfname, but instead of returning NULL if no description is available, return "[?]". */ const char *iobuf_get_fname_nonnull (iobuf_t a); /* Pushes a filter on the pipeline that interprets the datastream as an OpenPGP data block whose length is encoded using partial body length headers (see Section 4.2.2.4 of RFC 4880). Concretely, it just returns / writes the data and finishes the packet with an EOF. */ void iobuf_set_partial_body_length_mode (iobuf_t a, size_t len); /* If PARTIAL is set, then read from the pipeline until the first EOF is returned. If PARTIAL is 0, then read up to N bytes or until the first EOF is returned. Recall: a filter can return EOF. In this case, it and all preceding filters are popped from the pipeline and the next read is from the following filter (which may or may not return EOF). */ void iobuf_skip_rest (iobuf_t a, unsigned long n, int partial); #define iobuf_where(a) "[don't know]" /* Each time a filter is allocated (via iobuf_alloc()), a monotonically increasing counter is incremented and this field is set to the new value. This macro returns that number. */ #define iobuf_id(a) ((a)->no) #define iobuf_get_temp_buffer(a) ( (a)->d.buf ) #define iobuf_get_temp_length(a) ( (a)->d.len ) /* Whether the filter uses an in-memory buffer. */ #define iobuf_is_temp(a) ( (a)->use == IOBUF_OUTPUT_TEMP ) #endif /*GNUPG_COMMON_IOBUF_H*/ diff --git a/common/util.h b/common/util.h index 8ad805832..a6bab2415 100644 --- a/common/util.h +++ b/common/util.h @@ -1,401 +1,409 @@ /* util.h - Utility functions for GnuPG * Copyright (C) 2001, 2002, 2003, 2004, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute and/or modify this * part of GnuPG under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * 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 copies of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, see . */ #ifndef GNUPG_COMMON_UTIL_H #define GNUPG_COMMON_UTIL_H #include /* We need this for the memory function protos. */ #include /* We need errno. */ #include /* We need gpg_error_t and estream. */ /* These error codes are used but not defined in the required * libgpg-error version. Define them here. * Example: (#if GPG_ERROR_VERSION_NUMBER < 0x011500 // 1.21) */ #if GPG_ERROR_VERSION_NUMBER < 0x012400 /* 1.36 */ #define GPG_ERR_NO_AUTH 314 #define GPG_ERR_BAD_AUTH 315 #endif /*GPG_ERROR_VERSION_NUMBER*/ #if GPG_ERROR_VERSION_NUMBER < 0x012500 /* 1.37 */ #define GPG_ERR_NO_KEYBOXD 316 #define GPG_ERR_KEYBOXD 317 #endif /*GPG_ERROR_VERSION_NUMBER*/ +#ifndef EXTERN_UNLESS_MAIN_MODULE +# if !defined (INCLUDED_BY_MAIN_MODULE) +# define EXTERN_UNLESS_MAIN_MODULE extern +# else +# define EXTERN_UNLESS_MAIN_MODULE +# endif +#endif + /* Hash function used with libksba. */ #define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write) /* The length of the keygrip. This is a SHA-1 hash of the key * parameters as generated by gcry_pk_get_keygrip. */ #define KEYGRIP_LEN 20 /* The length of the unique blob identifier as used by the keyboxd. * This is the possible truncated fingerprint of the primary key. */ #define UBID_LEN 20 /* Get all the stuff from jnlib. */ #include "../common/logging.h" #include "../common/argparse.h" #include "../common/stringhelp.h" #include "../common/mischelp.h" #include "../common/strlist.h" #include "../common/dotlock.h" #include "../common/utf8conv.h" #include "../common/dynload.h" #include "../common/fwddecl.h" #include "../common/utilproto.h" #include "gettime.h" /* Redefine asprintf by our estream version which uses our own memory allocator.. */ #define asprintf gpgrt_asprintf #define vasprintf gpgrt_vasprintf /* Due to a bug in mingw32's snprintf related to the 'l' modifier and for increased portability we use our snprintf on all systems. */ #undef snprintf #define snprintf gpgrt_snprintf /* Replacements for macros not available with libgpg-error < 1.20. */ /* We need this type even if we are not using libreadline and or we did not include libreadline in the current file. */ #ifndef GNUPG_LIBREADLINE_H_INCLUDED typedef char **rl_completion_func_t (const char *, int, int); #endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/ /* Handy malloc macros - please use only them. */ #define xtrymalloc(a) gcry_malloc ((a)) #define xtrymalloc_secure(a) gcry_malloc_secure ((a)) #define xtrycalloc(a,b) gcry_calloc ((a),(b)) #define xtrycalloc_secure(a,b) gcry_calloc_secure ((a),(b)) #define xtryrealloc(a,b) gcry_realloc ((a),(b)) #define xtrystrdup(a) gcry_strdup ((a)) #define xfree(a) gcry_free ((a)) #define xfree_fnc gcry_free #define xmalloc(a) gcry_xmalloc ((a)) #define xmalloc_secure(a) gcry_xmalloc_secure ((a)) #define xcalloc(a,b) gcry_xcalloc ((a),(b)) #define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b)) #define xrealloc(a,b) gcry_xrealloc ((a),(b)) #define xstrdup(a) gcry_xstrdup ((a)) /* For compatibility with gpg 1.4 we also define these: */ #define xmalloc_clear(a) gcry_xcalloc (1, (a)) #define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a)) /* The default error source of the application. This is different from GPG_ERR_SOURCE_DEFAULT in that it does not depend on the source file and thus is usable in code shared by applications. Defined by init.c. */ extern gpg_err_source_t default_errsource; /* Convenience function to return a gpg-error code for memory allocation failures. This function makes sure that an error will be returned even if accidentally ERRNO is not set. */ static inline gpg_error_t out_of_core (void) { return gpg_error_from_syserror (); } /*-- yesno.c --*/ int answer_is_yes (const char *s); int answer_is_yes_no_default (const char *s, int def_answer); int answer_is_yes_no_quit (const char *s); int answer_is_okay_cancel (const char *s, int def_answer); /*-- xreadline.c --*/ ssize_t read_line (FILE *fp, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); /*-- b64enc.c and b64dec.c --*/ struct b64state { unsigned int flags; int idx; int quad_count; FILE *fp; estream_t stream; char *title; unsigned char radbuf[4]; u32 crc; int stop_seen:1; int invalid_encoding:1; gpg_error_t lasterr; }; gpg_error_t b64enc_start (struct b64state *state, FILE *fp, const char *title); gpg_error_t b64enc_start_es (struct b64state *state, estream_t fp, const char *title); gpg_error_t b64enc_write (struct b64state *state, const void *buffer, size_t nbytes); gpg_error_t b64enc_finish (struct b64state *state); gpg_error_t b64dec_start (struct b64state *state, const char *title); gpg_error_t b64dec_proc (struct b64state *state, void *buffer, size_t length, size_t *r_nbytes); gpg_error_t b64dec_finish (struct b64state *state); /*-- sexputil.c */ char *canon_sexp_to_string (const unsigned char *canon, size_t canonlen); void log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen); void log_printsexp (const char *text, gcry_sexp_t sexp); gpg_error_t make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen, unsigned char *grip); int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b); unsigned char *make_simple_sexp_from_hexstr (const char *line, size_t *nscanned); int hash_algo_from_sigval (const unsigned char *sigval); unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen, const void *e, size_t elen, size_t *r_len); gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_n, size_t *r_nlen, unsigned char const **r_e, size_t *r_elen); int get_pk_algo_from_key (gcry_sexp_t key); int get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen); char *pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid); /*-- convert.c --*/ int hex2bin (const char *string, void *buffer, size_t length); int hexcolon2bin (const char *string, void *buffer, size_t length); char *bin2hex (const void *buffer, size_t length, char *stringbuf); char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf); const char *hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen); char *hex2str_alloc (const char *hexstring, size_t *r_count); unsigned int hex2fixedbuf (const char *hexstr, void *buffer, size_t bufsize); /*-- percent.c --*/ char *percent_plus_escape (const char *string); char *percent_data_escape (int plus, const char *prefix, const void *data, size_t datalen); char *percent_plus_unescape (const char *string, int nulrepl); char *percent_unescape (const char *string, int nulrepl); size_t percent_plus_unescape_inplace (char *string, int nulrepl); size_t percent_unescape_inplace (char *string, int nulrepl); /*-- openpgp-oid.c --*/ gpg_error_t openpgp_oid_from_str (const char *string, gcry_mpi_t *r_mpi); char *openpgp_oidbuf_to_str (const unsigned char *buf, size_t len); char *openpgp_oid_to_str (gcry_mpi_t a); int openpgp_oidbuf_is_ed25519 (const void *buf, size_t len); int openpgp_oid_is_ed25519 (gcry_mpi_t a); int openpgp_oidbuf_is_cv25519 (const void *buf, size_t len); int openpgp_oid_is_cv25519 (gcry_mpi_t a); const char *openpgp_curve_to_oid (const char *name, unsigned int *r_nbits); const char *openpgp_oid_to_curve (const char *oid, int canon); const char *openpgp_oid_or_name_to_curve (const char *oidname, int canon); const char *openpgp_enum_curves (int *idxp); const char *openpgp_is_curve_supported (const char *name, int *r_algo, unsigned int *r_nbits); const char *get_keyalgo_string (enum gcry_pk_algos algo, unsigned int nbits, const char *curve); /*-- homedir.c --*/ const char *standard_homedir (void); const char *default_homedir (void); void gnupg_set_homedir (const char *newdir); const char *gnupg_homedir (void); int gnupg_default_homedir_p (void); const char *gnupg_daemon_rootdir (void); const char *gnupg_socketdir (void); const char *gnupg_sysconfdir (void); const char *gnupg_bindir (void); const char *gnupg_libexecdir (void); const char *gnupg_libdir (void); const char *gnupg_datadir (void); const char *gnupg_localedir (void); const char *gnupg_cachedir (void); const char *gpg_agent_socket_name (void); const char *dirmngr_socket_name (void); char *_gnupg_socketdir_internal (int skip_checks, unsigned *r_info); /* All module names. We also include gpg and gpgsm for the sake for gpgconf. */ #define GNUPG_MODULE_NAME_AGENT 1 #define GNUPG_MODULE_NAME_PINENTRY 2 #define GNUPG_MODULE_NAME_SCDAEMON 3 #define GNUPG_MODULE_NAME_DIRMNGR 4 #define GNUPG_MODULE_NAME_PROTECT_TOOL 5 #define GNUPG_MODULE_NAME_CHECK_PATTERN 6 #define GNUPG_MODULE_NAME_GPGSM 7 #define GNUPG_MODULE_NAME_GPG 8 #define GNUPG_MODULE_NAME_CONNECT_AGENT 9 #define GNUPG_MODULE_NAME_GPGCONF 10 #define GNUPG_MODULE_NAME_DIRMNGR_LDAP 11 #define GNUPG_MODULE_NAME_GPGV 12 #define GNUPG_MODULE_NAME_KEYBOXD 13 const char *gnupg_module_name (int which); void gnupg_module_name_flush_some (void); void gnupg_set_builddir (const char *newdir); /* A list of constants to identify protocols. This is used by tools * which need to distinguish between the different protocols * implemented by GnuPG. May be used as bit flags. */ #define GNUPG_PROTOCOL_OPENPGP 1 /* The one and only (gpg). */ #define GNUPG_PROTOCOL_CMS 2 /* The core of S/MIME (gpgsm) */ #define GNUPG_PROTOCOL_SSH_AGENT 4 /* Out ssh-agent implementation */ /*-- gpgrlhelp.c --*/ void gnupg_rl_initialize (void); /*-- helpfile.c --*/ char *gnupg_get_help_string (const char *key, int only_current_locale); /*-- localename.c --*/ const char *gnupg_messages_locale_name (void); /*-- miscellaneous.c --*/ /* This function is called at startup to tell libgcrypt to use our own logging subsystem. */ void setup_libgcrypt_logging (void); /* Print an out of core message and die. */ void xoutofcore (void); /* Same as estream_asprintf but die on memory failure. */ char *xasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* This is now an alias to estream_asprintf. */ char *xtryasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* Replacement for gcry_cipher_algo_name. */ const char *gnupg_cipher_algo_name (int algo); void obsolete_option (const char *configname, unsigned int configlineno, const char *name); const char *print_fname_stdout (const char *s); const char *print_fname_stdin (const char *s); void print_utf8_buffer3 (estream_t fp, const void *p, size_t n, const char *delim); void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim); void print_utf8_buffer (estream_t fp, const void *p, size_t n); void print_utf8_string (estream_t stream, const char *p); void print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved); char *try_make_printable_string (const void *p, size_t n, int delim); char *make_printable_string (const void *p, size_t n, int delim); char *decode_c_string (const char *src); int is_file_compressed (const char *s, int *ret_rc); int match_multistr (const char *multistr,const char *match); int gnupg_compare_version (const char *a, const char *b); struct debug_flags_s { unsigned int flag; const char *name; }; int parse_debug_flag (const char *string, unsigned int *debugvar, const struct debug_flags_s *flags); /*-- Simple replacement functions. */ /* We use the gnupg_ttyname macro to be safe not to run into conflicts which an extisting but broken ttyname. */ #if !defined(HAVE_TTYNAME) || defined(HAVE_BROKEN_TTYNAME) # define gnupg_ttyname(n) _gnupg_ttyname ((n)) /* Systems without ttyname (W32) will merely return NULL. */ static inline char * _gnupg_ttyname (int fd) { (void)fd; return NULL; } #else /*HAVE_TTYNAME*/ # define gnupg_ttyname(n) ttyname ((n)) #endif /*HAVE_TTYNAME */ #ifdef HAVE_W32CE_SYSTEM #define getpid() GetCurrentProcessId () char *_gnupg_getenv (const char *name); /* See sysutils.c */ #define getenv(a) _gnupg_getenv ((a)) char *_gnupg_setenv (const char *name); /* See sysutils.c */ #define setenv(a,b,c) _gnupg_setenv ((a),(b),(c)) int _gnupg_isatty (int fd); #define gnupg_isatty(a) _gnupg_isatty ((a)) #else #define gnupg_isatty(a) isatty ((a)) #endif /*-- Macros to replace ctype ones to avoid locale problems. --*/ #define spacep(p) (*(p) == ' ' || *(p) == '\t') #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define alphap(p) ((*(p) >= 'A' && *(p) <= 'Z') \ || (*(p) >= 'a' && *(p) <= 'z')) #define alnump(p) (alphap (p) || digitp (p)) #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* Note this isn't identical to a C locale isspace() without \f and \v, but works for the purposes used here. */ #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t') /* The atoi macros assume that the buffer has only valid digits. */ #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) #define xtoi_4(p) ((xtoi_2(p) * 256) + xtoi_2((p)+2)) #endif /*GNUPG_COMMON_UTIL_H*/ diff --git a/dirmngr/dirmngr.c b/dirmngr/dirmngr.c index 8f28fa43d..88f0aa430 100644 --- a/dirmngr/dirmngr.c +++ b/dirmngr/dirmngr.c @@ -1,2356 +1,2357 @@ /* dirmngr.c - Keyserver and X.509 LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2010, 2011 g10 Code GmbH * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * SPDX-License-Identifier: GPL-3.0+ */ #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #include #endif #include #include #ifdef HAVE_SIGNAL_H # include #endif #ifdef HAVE_INOTIFY_INIT # include #endif /*HAVE_INOTIFY_INIT*/ #include #include "dirmngr-err.h" #if HTTP_USE_NTBTLS # include #elif HTTP_USE_GNUTLS # include #endif /*HTTP_USE_GNUTLS*/ +#define INCLUDED_BY_MAIN_MODULE 1 #define GNUPG_COMMON_NEED_AFLOCAL #include "dirmngr.h" #include #include "certcache.h" #include "crlcache.h" #include "crlfetch.h" #include "misc.h" #if USE_LDAP # include "ldapserver.h" #endif #include "../common/asshelp.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "../common/init.h" #include "../common/gc-opt-flags.h" #include "dns-stuff.h" #include "http-common.h" #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aServer, aDaemon, aSupervised, aListCRLs, aLoadCRL, aFetchCRL, aShutdown, aFlush, aGPGConfList, aGPGConfTest, oOptions, oDebug, oDebugAll, oDebugWait, oDebugLevel, oGnutlsDebug, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oLogFile, oBatch, oDisableHTTP, oDisableLDAP, oDisableIPv4, oDisableIPv6, oIgnoreLDAPDP, oIgnoreHTTPDP, oIgnoreOCSPSvcUrl, oHonorHTTPProxy, oHTTPProxy, oLDAPProxy, oOnlyLDAPProxy, oLDAPFile, oLDAPTimeout, oLDAPAddServers, oOCSPResponder, oOCSPSigner, oOCSPMaxClockSkew, oOCSPMaxPeriod, oOCSPCurrentPeriod, oMaxReplies, oHkpCaCert, oFakedSystemTime, oForce, oAllowOCSP, oAllowVersionCheck, oSocketName, oLDAPWrapperProgram, oHTTPWrapperProgram, oIgnoreCertExtension, oUseTor, oNoUseTor, oKeyServer, oNameServer, oDisableCheckOwnSocket, oStandardResolver, oRecursiveResolver, oResolverTimeout, oConnectTimeout, oConnectQuickTimeout, oListenBacklog, aTest }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ), ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ), #ifndef HAVE_W32_SYSTEM ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")), ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")), ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")), ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")), ARGPARSE_c (aFlush, "flush", N_("flush the cache")), ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write server mode logs to FILE")), ARGPARSE_s_n (oBatch, "batch", N_("run without asking a user")), ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")), ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")), ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check", N_("allow online software version check")), ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")), ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")), ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp", N_("ignore HTTP CRL distribution points")), ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp", N_("ignore LDAP CRL distribution points")), ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url", N_("ignore certificate contained OCSP service URLs")), ARGPARSE_s_s (oHTTPProxy, "http-proxy", N_("|URL|redirect all HTTP requests to URL")), ARGPARSE_s_s (oLDAPProxy, "ldap-proxy", N_("|HOST|use HOST for LDAP queries")), ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy", N_("do not use fallback hosts with --ldap-proxy")), ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file", N_("|FILE|read LDAP server list from FILE")), ARGPARSE_s_n (oLDAPAddServers, "add-servers", N_("add new servers discovered in CRL distribution" " points to serverlist")), ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout", N_("|N|set LDAP timeout to N seconds")), ARGPARSE_s_s (oOCSPResponder, "ocsp-responder", N_("|URL|use OCSP responder at URL")), ARGPARSE_s_s (oOCSPSigner, "ocsp-signer", N_("|FPR|OCSP response signed by FPR")), ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"), ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"), ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"), ARGPARSE_s_i (oMaxReplies, "max-replies", N_("|N|do not return more than N items in one query")), ARGPARSE_s_s (oNameServer, "nameserver", "@"), ARGPARSE_s_s (oKeyServer, "keyserver", "@"), ARGPARSE_s_s (oHkpCaCert, "hkp-cacert", N_("|FILE|use the CA certificates in FILE for HKP over TLS")), ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")), ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"), ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"), ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"), ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */ ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/ ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"), ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"), ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"), ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", "@"), ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"), ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"), ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"), ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"), ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"), ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing " "of all commands and options)\n")), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_X509_VALUE , "x509" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { DBG_DNS_VALUE , "dns" }, { DBG_NETWORK_VALUE, "network" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_MAX_REPLIES 10 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */ #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */ #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */ /* For the cleanup handler we need to keep track of the socket's name. */ static const char *socket_name; /* If the socket has been redirected, this is the name of the redirected socket.. */ static const char *redir_socket_name; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; /* Value for the listen() backlog argument. * Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Only if this flag has been set will we remove the socket file. */ static int cleanup_socket; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* Helper to implement --debug-level. */ static const char *debug_level; /* Helper to set the NTBTLS or GNUTLS log level. */ static int opt_gnutls_debug = -1; /* Flag indicating that a shutdown has been requested. */ static volatile int shutdown_pending; /* Flags to indicate that we shall not watch our own socket. */ static int disable_check_own_socket; /* Flag to control the Tor mode. */ static enum { TOR_MODE_AUTO = 0, /* Switch to NO or YES */ TOR_MODE_NEVER, /* Never use Tor. */ TOR_MODE_NO, /* Do not use Tor */ TOR_MODE_YES, /* Use Tor */ TOR_MODE_FORCE /* Force using Tor */ } tor_mode; /* Counter for the active connections. */ static int active_connections; /* This flag is set by any network access and used by the housekeeping * thread to run background network tasks. */ static int network_activity_seen; /* A list of filenames registered with --hkp-cacert. */ static strlist_t hkp_cacert_filenames; /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */ #define TIMERTICK_INTERVAL (60) #define TIMERTICK_INTERVAL_SHUTDOWN (4) /* How oft to run the housekeeping. */ #define HOUSEKEEPING_INTERVAL (600) /* This union is used to avoid compiler warnings in case a pointer is 64 bit and an int 32 bit. We store an integer in a pointer and get it back later (npth_getspecific et al.). */ union int_and_ptr_u { int aint; assuan_fd_t afd; void *aptr; }; /* The key used to store the current file descriptor in the thread local storage. We use this in conjunction with the log_set_pid_suffix_cb feature. */ #ifndef HAVE_W32_SYSTEM static npth_key_t my_tlskey_current_fd; #endif /* Prototypes. */ static void cleanup (void); #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename); #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string); static void netactivity_action (void); static void handle_connections (assuan_fd_t listen_fd); /* NPth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; static const char * my_strusage( int level ) { const char *p; switch ( level ) { case 11: p = "@DIRMNGR@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 49: p = PACKAGE_BUGREPORT; break; case 1: case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)"); break; case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n" "Keyserver, CRL, and OCSP access for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Callback from libksba to hash a provided buffer. Our current implementation does only allow SHA-1 for hashing. This may be extended by mapping the name, testing for algorithm availability and adjust the length checks accordingly. */ static gpg_error_t my_ksba_hash_buffer (void *arg, const char *oid, const void *buffer, size_t length, size_t resultsize, unsigned char *result, size_t *resultlen) { (void)arg; if (oid && strcmp (oid, "1.3.14.3.2.26")) return gpg_error (GPG_ERR_NOT_SUPPORTED); if (resultsize < 20) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); gcry_md_hash_buffer (2, result, buffer, length); *resultlen = 20; return 0; } /* GNUTLS log function callback. */ #ifdef HTTP_USE_GNUTLS static void my_gnutls_log (int level, const char *text) { int n; n = strlen (text); while (n && text[n-1] == '\n') n--; log_debug ("gnutls:L%d: %.*s\n", level, n, text); } #endif /*HTTP_USE_GNUTLS*/ /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE); else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); log_info (_("valid debug levels are: %s\n"), "none, basic, advanced, expert, guru"); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) { opt.verbose = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); } if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); #if HTTP_USE_NTBTLS if (opt_gnutls_debug >= 0) { ntbtls_set_debug (opt_gnutls_debug, NULL, NULL); } #elif HTTP_USE_GNUTLS if (opt_gnutls_debug >= 0) { gnutls_global_set_log_function (my_gnutls_log); gnutls_global_set_log_level (opt_gnutls_debug); } #endif /*HTTP_USE_GNUTLS*/ if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } static void set_tor_mode (void) { if (dirmngr_use_tor ()) { /* Enable Tor mode and when called again force a new circuit * (e.g. on SIGHUP). */ enable_dns_tormode (1); if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1)) { log_error ("error enabling Tor mode: %s\n", strerror (errno)); log_info ("(is your Libassuan recent enough?)\n"); } } else disable_dns_tormode (); } /* Return true if Tor shall be used. */ int dirmngr_use_tor (void) { if (tor_mode == TOR_MODE_AUTO) { /* Figure out whether Tor is running. */ assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) tor_mode = TOR_MODE_NO; else { tor_mode = TOR_MODE_YES; assuan_sock_close (sock); } } if (tor_mode == TOR_MODE_FORCE) return 2; /* Use Tor (using 2 to indicate force mode) */ else if (tor_mode == TOR_MODE_YES) return 1; /* Use Tor */ else return 0; /* Do not use Tor. */ } static void wrong_args (const char *text) { es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME); es_fputs (text, es_stderr); es_putc ('\n', es_stderr); dirmngr_exit (2); } /* Helper to stop the reaper thread for the ldap wrapper. */ static void shutdown_reaper (void) { #if USE_LDAP ldap_wrapper_wait_connections (); #endif } /* Handle options which are allowed to be reset after program start. Return true if the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread) { if (!pargs) { /* Reset mode. */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.ldap_wrapper_program = NULL; opt.disable_http = 0; opt.disable_ldap = 0; opt.honor_http_proxy = 0; opt.http_proxy = NULL; opt.ldap_proxy = NULL; opt.only_ldap_proxy = 0; opt.ignore_http_dp = 0; opt.ignore_ldap_dp = 0; opt.ignore_ocsp_service_url = 0; opt.allow_ocsp = 0; opt.allow_version_check = 0; opt.ocsp_responder = NULL; opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */ opt.ocsp_max_period = 90 * 86400; /* 90 days. */ opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */ opt.max_replies = DEFAULT_MAX_REPLIES; while (opt.ocsp_signer) { fingerprint_list_t tmp = opt.ocsp_signer->next; xfree (opt.ocsp_signer); opt.ocsp_signer = tmp; } FREE_STRLIST (opt.ignored_cert_extensions); http_register_tls_ca (NULL); FREE_STRLIST (hkp_cacert_filenames); FREE_STRLIST (opt.keyserver); /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */ if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_AUTO; disable_check_own_socket = 0; enable_standard_resolver (0); set_dns_timeout (0); opt.connect_timeout = 0; opt.connect_quick_timeout = 0; return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break; case oLogFile: if (!reread) return 0; /* Not handled. */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oLDAPWrapperProgram: opt.ldap_wrapper_program = pargs->r.ret_str; break; case oHTTPWrapperProgram: opt.http_wrapper_program = pargs->r.ret_str; break; case oDisableHTTP: opt.disable_http = 1; break; case oDisableLDAP: opt.disable_ldap = 1; break; case oDisableIPv4: opt.disable_ipv4 = 1; break; case oDisableIPv6: opt.disable_ipv6 = 1; break; case oHonorHTTPProxy: opt.honor_http_proxy = 1; break; case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break; case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break; case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break; case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break; case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break; case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break; case oAllowOCSP: opt.allow_ocsp = 1; break; case oAllowVersionCheck: opt.allow_version_check = 1; break; case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break; case oOCSPSigner: opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str); break; case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break; case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break; case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break; case oMaxReplies: opt.max_replies = pargs->r.ret_int; break; case oHkpCaCert: { /* We need to register the filenames with gnutls (http.c) and * also for our own cert cache. */ char *tmpname; /* Do tilde expansion and make path absolute. */ tmpname = make_absfilename (pargs->r.ret_str, NULL); http_register_tls_ca (tmpname); add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str); xfree (tmpname); } break; case oIgnoreCertExtension: add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str); break; case oUseTor: tor_mode = TOR_MODE_FORCE; break; case oNoUseTor: if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_NEVER; break; case oStandardResolver: enable_standard_resolver (1); break; case oRecursiveResolver: enable_recursive_resolver (1); break; case oKeyServer: if (*pargs->r.ret_str) add_to_strlist (&opt.keyserver, pargs->r.ret_str); break; case oNameServer: set_dns_nameserver (pargs->r.ret_str); break; case oResolverTimeout: set_dns_timeout (pargs->r.ret_int); break; case oConnectTimeout: opt.connect_timeout = pargs->r.ret_ulong * 1000; break; case oConnectQuickTimeout: opt.connect_quick_timeout = pargs->r.ret_ulong * 1000; break; default: return 0; /* Not handled. */ } set_dns_verbose (opt.verbose, !!DBG_DNS); http_set_verbose (opt.verbose, !!DBG_NETWORK); set_dns_disable_ipv4 (opt.disable_ipv4); set_dns_disable_ipv6 (opt.disable_ipv6); return 1; /* Handled. */ } /* This function is called after option parsing to adjust some values * and call option setup functions. */ static void post_option_parsing (void) { /* It would be too surpirsing if the quick timeout is larger than * the standard value. */ if (opt.connect_quick_timeout > opt.connect_timeout) opt.connect_quick_timeout = opt.connect_timeout; set_debug (); } #ifndef HAVE_W32_SYSTEM static int pid_suffix_callback (unsigned long *r_suffix) { union int_and_ptr_u value; memset (&value, 0, sizeof value); value.aptr = npth_getspecific (my_tlskey_current_fd); *r_suffix = value.aint; return (*r_suffix != -1); /* Use decimal representation. */ } #endif /*!HAVE_W32_SYSTEM*/ #if HTTP_USE_NTBTLS static void my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv) { (void)opaque; if (level == -1) log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv); else { char prefix[10+20]; snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level); log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv); } } #endif static void thread_init (void) { npth_init (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now with NPth running we can set the logging callback. Our windows implementation does not yet feature the NPth TLS functions. */ #ifndef HAVE_W32_SYSTEM if (npth_key_create (&my_tlskey_current_fd, NULL) == 0) if (npth_setspecific (my_tlskey_current_fd, NULL) == 0) log_set_pid_suffix_cb (pid_suffix_callback); #endif /*!HAVE_W32_SYSTEM*/ } int main (int argc, char **argv) { enum cmd_and_opt_values cmd = 0; ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; FILE *configfp = NULL; char *configname = NULL; const char *shell; unsigned configlineno; int parse_debug = 0; int default_config =1; int greeting = 0; int nogreeting = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; #if USE_LDAP char *ldapfile = NULL; #endif /*USE_LDAP*/ int debug_wait = 0; int rc; struct assuan_malloc_hooks malloc_hooks; early_system_init (); set_strusage (my_strusage); log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* Check that the libraries are suitable. Do it here because the option parsing may need services of the libraries. */ if (!ksba_check_version (NEED_KSBA_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba", NEED_KSBA_VERSION, ksba_check_version (NULL) ); ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL); /* Init TLS library. */ #if HTTP_USE_NTBTLS if (!ntbtls_check_version (NEED_NTBTLS_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls", NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) ); #elif HTTP_USE_GNUTLS rc = gnutls_global_init (); if (rc) log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc)); #endif /*HTTP_USE_GNUTLS*/ /* Init Assuan. */ malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_assuan_log_prefix (log_get_prefix (NULL)); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor); setup_libgcrypt_logging (); #if HTTP_USE_NTBTLS ntbtls_set_log_handler (my_ntbtls_log_handler, NULL); #endif /* Setup defaults. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Reset rereadable options to default values. */ parse_rereadable_options (NULL, 0); /* Default TCP timeouts. */ opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT; opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT; /* LDAP defaults. */ opt.add_new_ldapservers = 0; opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT; /* Other defaults. */ /* Check whether we have a config file given on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */ while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; else if (pargs.r_opt == oOptions) { /* Yes there is one, so we do not try the default one, but read the option file when it is encountered at the commandline */ default_config = 0; } else if (pargs.r_opt == oNoOptions) default_config = 0; /* --no-options */ else if (pargs.r_opt == oHomedir) { gnupg_set_homedir (pargs.r.ret_str); } } socket_name = dirmngr_socket_name (); if (default_config) configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL ); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if( parse_debug ) log_info (_("Note: no default option file '%s'\n"), configname ); } else { log_error (_("option file '%s': %s\n"), configname, strerror(errno) ); exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname ) log_info (_("reading options from '%s'\n"), configname ); default_config = 0; } while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) ) { if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aServer: case aDaemon: case aSupervised: case aShutdown: case aFlush: case aListCRLs: case aLoadCRL: case aFetchCRL: case aGPGConfList: case aGPGConfTest: cmd = pargs.r_opt; break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oOptions: /* Config files may not be nested (silently ignore them) */ if (!configfp) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; break; case oNoOptions: break; /* no-options */ case oHomedir: /* Ignore this option here. */; break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oLDAPFile: # if USE_LDAP ldapfile = pargs.r.ret_str; # endif /*USE_LDAP*/ break; case oLDAPAddServers: opt.add_new_ldapservers = 1; break; case oLDAPTimeout: opt.ldaptimeout = pargs.r.ret_int; break; case oFakedSystemTime: gnupg_set_time ((time_t)pargs.r.ret_ulong, 0); break; case oForce: opt.force = 1; break; case oSocketName: socket_name = pargs.r.ret_str; break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; default : pargs.err = configfp? 1:2; break; } } if (configfp) { fclose (configfp); configfp = NULL; /* Keep a copy of the name so that it can be read on SIGHUP. */ opt.config_filename = configname; configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (log_get_errorcount(0)) exit(2); if (nogreeting ) greeting = 0; if (!opt.homedir_cache) opt.homedir_cache = xstrdup (gnupg_homedir ()); if (greeting) { es_fprintf (es_stderr, "%s %s; %s\n", strusage(11), strusage(13), strusage(14) ); es_fprintf (es_stderr, "%s\n", strusage(15) ); } #ifdef IS_DEVELOPMENT_VERSION log_info ("NOTE: this is a development version!\n"); #endif /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } if (!access ("/etc/"DIRMNGR_NAME, F_OK) && !strncmp (gnupg_homedir (), "/etc/", 5)) log_info ("NOTE: DirMngr is now a proper part of %s. The configuration and" " other directory names changed. Please check that no other version" " of dirmngr is still installed. To disable this warning, remove the" " directory '/etc/dirmngr'.\n", GNUPG_NAME); if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } /* Note that we do not run set_tor_mode in --gpgconf-list mode * because it will attempt to connect to the tor client and that can * be time consuming. */ post_option_parsing (); if (cmd != aGPGConfTest && cmd != aGPGConfList) set_tor_mode (); /* Get LDAP server list from file. */ #if USE_LDAP if (!ldapfile) { ldapfile = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); opt.ldapservers = parse_ldapserver_file (ldapfile); xfree (ldapfile); } else opt.ldapservers = parse_ldapserver_file (ldapfile); #endif /*USE_LDAP*/ #ifndef HAVE_W32_SYSTEM /* We need to ignore the PIPE signal because the we might log to a socket and that code handles EPIPE properly. The ldap wrapper also requires us to ignore this silly signal. Assuan would set this signal to ignore anyway.*/ signal (SIGPIPE, SIG_IGN); #endif /* Ready. Now to our duties. */ if (!cmd) cmd = aServer; rc = 0; if (cmd == aServer) { /* Note that this server mode is mainly useful for debugging. */ if (argc) wrong_args ("--server"); if (logfile) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); start_command_handler (ASSUAN_INVALID_FD, 0); shutdown_reaper (); } #ifndef HAVE_W32_SYSTEM else if (cmd == aSupervised) { /* In supervised mode, we expect file descriptor 3 to be an already opened, listening socket. We will also not detach from the controlling process or close stderr; the supervisor should handle all of that. */ struct stat statbuf; if (fstat (3, &statbuf) == -1 && errno == EBADF) { log_error ("file descriptor 3 must be validin --supervised mode\n"); dirmngr_exit (1); } socket_name = gnupg_get_socket_name (3); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } else log_set_prefix (NULL, 0); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (3); shutdown_reaper (); } #endif /*HAVE_W32_SYSTEM*/ else if (cmd == aDaemon) { assuan_fd_t fd; pid_t pid; int len; struct sockaddr_un serv_addr; if (argc) wrong_args ("--daemon"); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } #ifndef HAVE_W32_SYSTEM if (strchr (socket_name, ':')) { log_error (_("colons are not allowed in the socket name\n")); dirmngr_exit (1); } #endif fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); cleanup (); dirmngr_exit (1); } { int redirected; if (assuan_sock_set_sockaddr_un (socket_name, (struct sockaddr*)&serv_addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), socket_name); else log_error ("error preparing socket '%s': %s\n", socket_name, gpg_strerror (gpg_error_from_syserror ())); dirmngr_exit (1); } if (redirected) { redir_socket_name = xstrdup (serv_addr.sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", socket_name, redir_socket_name); } } len = SUN_LEN (&serv_addr); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Fixme: We should test whether a dirmngr is already running. */ gnupg_remove (redir_socket_name? redir_socket_name : socket_name); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); } if (rc != -1 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { log_error (_("error binding socket to '%s': %s\n"), serv_addr.sun_path, gpg_strerror (gpg_error_from_errno (errno))); assuan_sock_close (fd); dirmngr_exit (1); } cleanup_socket = 1; if (gnupg_chmod (serv_addr.sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), serv_addr.sun_path, strerror (errno)); if (listen (FD2INT (fd), listen_backlog) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); assuan_sock_close (fd); dirmngr_exit (1); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), serv_addr.sun_path); es_fflush (NULL); /* Note: We keep the dirmngr_info output only for the sake of existing scripts which might use this to detect a successful start of the dirmngr. */ #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; pid = getpid (); es_printf ("set %s=%s;%lu;1\n", DIRMNGR_INFO_NAME, socket_name, (ulong) pid); #else pid = fork(); if (pid == (pid_t)-1) { log_fatal (_("error forking process: %s\n"), strerror (errno)); dirmngr_exit (1); } if (pid) { /* We are the parent */ char *infostr; /* Don't let cleanup() remove the socket - the child is responsible for doing that. */ cleanup_socket = 0; close (fd); /* Create the info string: :: */ if (asprintf (&infostr, "%s=%s:%lu:1", DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0) { log_error (_("out of core\n")); kill (pid, SIGTERM); dirmngr_exit (1); } /* Print the environment string, so that the caller can use shell's eval to set it. But see above. */ if (csh_style) { *strchr (infostr, '=') = ' '; es_printf ( "setenv %s;\n", infostr); } else { es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME); } free (infostr); exit (0); /*NEVER REACHED*/ } /* end parent */ /* This is the child */ /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( !close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); dirmngr_exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); dirmngr_exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; } #endif if (!nodetach ) { if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); dirmngr_exit (1); } } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (fd); shutdown_reaper (); } else if (cmd == aListCRLs) { /* Just list the CRL cache and exit. */ if (argc) wrong_args ("--list-crls"); crl_cache_init (); crl_cache_list (es_stdout); } else if (cmd == aLoadCRL) { struct server_control_s ctrlbuf; memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); if (!argc) rc = crl_cache_load (&ctrlbuf, NULL); else { for (; !rc && argc; argc--, argv++) rc = crl_cache_load (&ctrlbuf, *argv); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFetchCRL) { ksba_reader_t reader; struct server_control_s ctrlbuf; if (argc != 1) wrong_args ("--fetch-crl URL"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); rc = crl_fetch (&ctrlbuf, argv[0], &reader); if (rc) log_error (_("fetching CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); else { rc = crl_cache_insert (&ctrlbuf, argv[0], reader); if (rc) log_error (_("processing CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); crl_close_reader (reader); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFlush) { /* Delete cache and exit. */ if (argc) wrong_args ("--flush"); rc = crl_cache_flush(); } else if (cmd == aGPGConfTest) dirmngr_exit (0); else if (cmd == aGPGConfList) { unsigned long flags = 0; char *filename; char *filename_esc; /* First the configuration file. This is not an option, but it is vital information for GPG Conf. */ if (!opt.config_filename) opt.config_filename = make_filename (gnupg_homedir (), "dirmngr.conf", NULL ); filename = percent_escape (opt.config_filename, NULL); es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n", GC_OPT_FLAG_DEFAULT, filename); xfree (filename); es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT); es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE); /* --csh and --sh are mutually exclusive, something we can not express in GPG Conf. --options is only usable from the command line, really. --debug-all interacts with --debug, and having both of them is thus problematic. --no-detach is also only usable on the command line. --batch is unused. */ filename = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); filename_esc = percent_escape (filename, NULL); es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); xfree (filename); es_printf ("ldaptimeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT); es_printf ("max-replies:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES); es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE); es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE); /* Note: The next one is to fix a typo in gpgconf - should be removed eventually. */ es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE); filename_esc = percent_escape (get_default_keyserver (0), NULL); es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("resolver-timeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, 0); } cleanup (); return !!rc; } static void cleanup (void) { crl_cache_deinit (); cert_cache_deinit (1); reload_dns_stuff (1); #if USE_LDAP ldapserver_list_free (opt.ldapservers); #endif /*USE_LDAP*/ opt.ldapservers = NULL; if (cleanup_socket) { cleanup_socket = 0; if (redir_socket_name) gnupg_remove (redir_socket_name); else if (socket_name && *socket_name) gnupg_remove (socket_name); } } void dirmngr_exit (int rc) { cleanup (); exit (rc); } void dirmngr_init_default_ctrl (ctrl_t ctrl) { ctrl->magic = SERVER_CONTROL_MAGIC; if (opt.http_proxy) ctrl->http_proxy = xstrdup (opt.http_proxy); ctrl->http_no_crl = 1; ctrl->timeout = opt.connect_timeout; } void dirmngr_deinit_default_ctrl (ctrl_t ctrl) { if (!ctrl) return; ctrl->magic = 0xdeadbeef; xfree (ctrl->http_proxy); ctrl->http_proxy = NULL; } /* Create a list of LDAP servers from the file FILENAME. Returns the list or NULL in case of errors. The format fo such a file is line oriented where empty lines and lines starting with a hash mark are ignored. All other lines are assumed to be colon seprated with these fields: 1. field: Hostname 2. field: Portnumber 3. field: Username 4. field: Password 5. field: Base DN */ #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename) { char buffer[1024]; char *p; ldap_server_t server, serverstart, *serverend; int c; unsigned int lineno = 0; estream_t fp; fp = es_fopen (filename, "r"); if (!fp) { log_info ("failed to open '%s': %s\n", filename, strerror (errno)); return NULL; } serverstart = NULL; serverend = &serverstart; while (es_fgets (buffer, sizeof buffer, fp)) { lineno++; if (!*buffer || buffer[strlen(buffer)-1] != '\n') { if (*buffer && es_feof (fp)) ; /* Last line not terminated - continue. */ else { log_error (_("%s:%u: line too long - skipped\n"), filename, lineno); while ( (c=es_fgetc (fp)) != EOF && c != '\n') ; /* Skip until end of line. */ continue; } } /* Skip empty and comment lines.*/ for (p=buffer; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; /* Parse the colon separated fields. */ server = ldapserver_parse_one (buffer, filename, lineno); if (server) { *serverend = server; serverend = &server->next; } } if (es_ferror (fp)) log_error (_("error reading '%s': %s\n"), filename, strerror (errno)); es_fclose (fp); return serverstart; } #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string) { gpg_error_t err; char *fname; estream_t fp; char line[256]; char *p; fingerprint_list_t list, *list_tail, item; unsigned int lnr = 0; int c, i, j; int errflag = 0; /* Check whether this is not a filename and treat it as a direct fingerprint specification. */ if (!strpbrk (string, "/.~\\")) { item = xcalloc (1, sizeof *item); for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++) if ( string[i] != ':' ) item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (string+i) || !string[i])) { log_error (_("%s:%u: invalid fingerprint detected\n"), "--ocsp-signer", 0); xfree (item); return NULL; } return item; } /* Well, it is a filename. */ if (*string == '/' || (*string == '~' && string[1] == '/')) fname = make_filename (string, NULL); else { if (string[0] == '.' && string[1] == '/' ) string += 2; fname = make_filename (gnupg_homedir (), string, NULL); } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); xfree (fname); return NULL; } list = NULL; list_tail = &list; for (;;) { if (!es_fgets (line, DIM(line)-1, fp) ) { if (!es_feof (fp)) { err = gpg_error_from_syserror (); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; } es_fclose (fp); if (errflag) { while (list) { fingerprint_list_t tmp = list->next; xfree (list); list = tmp; } } xfree (fname); return list; /* Ready. */ } lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ while ( (c=es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG /* */: GPG_ERR_INCOMPLETE_LINE); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; continue; } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; item = xcalloc (1, sizeof *item); *list_tail = item; list_tail = &item->next; for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++) if ( p[i] != ':' ) item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (p+i) || p[i] == '\n')) { log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr); errflag = 1; } i++; while (spacep (p+i)) i++; if (p[i] && p[i] != '\n') log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr); } /*NOTREACHED*/ } /* Stuff used in daemon mode. */ /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the NPTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process' original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { ARGPARSE_ARGS pargs; FILE *fp; unsigned int configlineno = 0; int dummy; if (!opt.config_filename) return; /* No config file. */ fp = fopen (opt.config_filename, "r"); if (!fp) { log_error (_("option file '%s': %s\n"), opt.config_filename, strerror(errno) ); return; } parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = 1; /* do not remove the args */ while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) ) { if (pargs.r_opt < -1) pargs.err = 1; /* Print a warning. */ else /* Try to parse this option - ignore unchangeable ones. */ parse_rereadable_options (&pargs, 1); } fclose (fp); post_option_parsing (); } /* A global function which allows us to trigger the reload stuff from other places. */ void dirmngr_sighup_action (void) { log_info (_("SIGHUP received - " "re-reading configuration and flushing caches\n")); reread_configuration (); set_tor_mode (); cert_cache_deinit (0); crl_cache_deinit (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); reload_dns_stuff (0); ks_hkp_reload (); } /* This function is called if some network activity was done. At this * point we know the we have a network and we can decide whether to * run scheduled background tasks soon. The function should return * quickly and only trigger actions for another thread. */ static void netactivity_action (void) { network_activity_seen = 1; } /* The signal handler. */ #ifndef HAVE_W32_SYSTEM static void handle_signal (int signo) { switch (signo) { case SIGHUP: dirmngr_sighup_action (); break; case SIGUSR1: cert_cache_print_stats (); domaininfo_print_stats (); break; case SIGUSR2: log_info (_("SIGUSR2 received - no action defined\n")); break; case SIGTERM: if (!shutdown_pending) log_info (_("SIGTERM received - shutting down ...\n")); else log_info (_("SIGTERM received - still %d active connections\n"), active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info (_("shutdown forced\n")); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); dirmngr_exit (0); } break; case SIGINT: log_info (_("SIGINT received - immediate shutdown\n")); log_info( "%s %s stopped\n", strusage(11), strusage(13)); cleanup (); dirmngr_exit (0); break; default: log_info (_("signal %d received - no action defined\n"), signo); } } #endif /*!HAVE_W32_SYSTEM*/ /* Thread to do the housekeeping. */ static void * housekeeping_thread (void *arg) { static int sentinel; time_t curtime; struct server_control_s ctrlbuf; (void)arg; curtime = gnupg_get_time (); if (sentinel) { log_info ("housekeeping is already going on\n"); return NULL; } sentinel++; if (opt.verbose > 1) log_info ("starting housekeeping\n"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); dns_stuff_housekeeping (); ks_hkp_housekeeping (curtime); if (network_activity_seen) { network_activity_seen = 0; if (opt.allow_version_check) dirmngr_load_swdb (&ctrlbuf, 0); workqueue_run_global_tasks (&ctrlbuf, 1); } else workqueue_run_global_tasks (&ctrlbuf, 0); dirmngr_deinit_default_ctrl (&ctrlbuf); if (opt.verbose > 1) log_info ("ready with housekeeping\n"); sentinel--; return NULL; } /* We try to enable correct overflow handling for signed int (commonly * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced * and used here as a pragma. Later gcc versions (gcc 6?) removed * this as a pragma and -fwrapv was then suggested as a replacement * for -fno-strict-overflow. */ #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC push_options # pragma GCC optimize ("wrapv") #endif static int time_for_housekeeping_p (time_t curtime) { static time_t last_housekeeping; if (!last_housekeeping) last_housekeeping = curtime; if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime || last_housekeeping > curtime /*(be prepared for y2038)*/) { last_housekeeping = curtime; return 1; } return 0; } #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC pop_options #endif /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { struct stat statbuf; if (time_for_housekeeping_p (gnupg_get_time ())) { npth_t thread; npth_attr_t tattr; int err; err = npth_attr_init (&tattr); if (err) log_error ("error preparing housekeeping thread: %s\n", strerror (err)); else { npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, housekeeping_thread, NULL); if (err) log_error ("error spawning housekeeping thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } } /* Check whether the homedir is still available. */ if (!shutdown_pending && stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT (fd), strerror (errno)); assuan_sock_close (fd); return -1; } else return 0; } /* Helper to call a connection's main function. */ static void * start_connection_thread (void *arg) { static unsigned int last_session_id; unsigned int session_id; union int_and_ptr_u argval; gnupg_fd_t fd; memset (&argval, 0, sizeof argval); argval.aptr = arg; fd = argval.afd; if (check_nonce (fd, &socket_nonce)) { log_error ("handler nonce check FAILED\n"); return NULL; } #ifndef HAVE_W32_SYSTEM npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif active_connections++; if (opt.verbose) log_info (_("handler for fd %d started\n"), FD2INT (fd)); session_id = ++last_session_id; if (!session_id) session_id = ++last_session_id; start_command_handler (fd, session_id); if (opt.verbose) log_info (_("handler for fd %d terminated\n"), FD2INT (fd)); active_connections--; workqueue_run_post_session_tasks (session_id); #ifndef HAVE_W32_SYSTEM argval.afd = ASSUAN_INVALID_FD; npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif return NULL; } #ifdef HAVE_INOTIFY_INIT /* Read an inotify event and return true if it matches NAME. */ static int my_inotify_is_name (int fd, const char *name) { union { struct inotify_event ev; char _buf[sizeof (struct inotify_event) + 100 + 1]; } buf; int n; const char *s; s = strrchr (name, '/'); if (s && s[1]) name = s + 1; n = npth_read (fd, &buf, sizeof buf); if (n < sizeof (struct inotify_event)) return 0; if (buf.ev.len < strlen (name)+1) return 0; if (strcmp (buf.ev.name, name)) return 0; /* Not the desired file. */ return 1; /* Found. */ } #endif /*HAVE_INOTIFY_INIT*/ /* Main loop in daemon mode. Note that LISTEN_FD will be owned by * this function. */ static void handle_connections (assuan_fd_t listen_fd) { npth_attr_t tattr; #ifndef HAVE_W32_SYSTEM int signo; #endif struct sockaddr_un paddr; socklen_t plen = sizeof( paddr ); int nfd, ret; fd_set fdset, read_fdset; struct timespec abstime; struct timespec curtime; struct timespec timeout; int saved_errno; int my_inotify_fd = -1; npth_attr_init (&tattr); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM /* FIXME */ npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #endif #ifdef HAVE_INOTIFY_INIT if (disable_check_own_socket) my_inotify_fd = -1; else if ((my_inotify_fd = inotify_init ()) == -1) log_info ("error enabling fast daemon termination: %s\n", strerror (errno)); else { /* We need to watch the directory for the file because there * won't be an IN_DELETE_SELF for a socket file. */ char *slash = strrchr (socket_name, '/'); log_assert (slash && slash[1]); *slash = 0; if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1) { close (my_inotify_fd); my_inotify_fd = -1; } *slash = '/'; } #endif /*HAVE_INOTIFY_INIT*/ /* Setup the fdset. It has only one member. This is because we use pth_select instead of pth_accept to properly sync timeouts with to full second. */ FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); if (my_inotify_fd > nfd) nfd = my_inotify_fd; } npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; /* Main loop. */ for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (!active_connections) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ /* assuan_sock_close (listen_fd); */ /* listen_fd = -1; */ FD_ZERO (&fdset); nfd = -1; if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); nfd = my_inotify_fd; } } /* Take a copy of the fdset. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. When a shutdown is pending we use a shorter * interval to handle the shutdown more quickly. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += (shutdown_pending ? TIMERTICK_INTERVAL_SHUTDOWN : TIMERTICK_INTERVAL); } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask()); saved_errno = errno; while (npth_sigev_get_pending(&signo)) handle_signal (signo); #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL); saved_errno = errno; #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) { /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; } if (shutdown_pending) { /* Do not anymore accept connections. */ continue; } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset) && my_inotify_is_name (my_inotify_fd, socket_name)) { shutdown_pending = 1; log_info ("socket file has been removed - shutting down\n"); } #endif /*HAVE_INOTIFY_INIT*/ if (FD_ISSET (FD2INT (listen_fd), &read_fdset)) { gnupg_fd_t fd; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listen_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed: %s\n", strerror (errno)); } else { char threadname[50]; union int_and_ptr_u argval; npth_t thread; memset (&argval, 0, sizeof argval); argval.afd = fd; snprintf (threadname, sizeof threadname, "conn fd=%d", FD2INT(fd)); ret = npth_create (&thread, &tattr, start_connection_thread, argval.aptr); if (ret) { log_error ("error spawning connection handler: %s\n", strerror (ret) ); assuan_sock_close (fd); } npth_setname_np (thread, threadname); } } } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1) close (my_inotify_fd); #endif /*HAVE_INOTIFY_INIT*/ npth_attr_destroy (&tattr); if (listen_fd != GNUPG_INVALID_FD) assuan_sock_close (listen_fd); cleanup (); log_info ("%s %s stopped\n", strusage(11), strusage(13)); } const char* dirmngr_get_current_socket_name (void) { if (socket_name) return socket_name; else return dirmngr_socket_name (); } diff --git a/dirmngr/dirmngr.h b/dirmngr/dirmngr.h index b27b8e6fb..92d9d4b6a 100644 --- a/dirmngr/dirmngr.h +++ b/dirmngr/dirmngr.h @@ -1,269 +1,270 @@ /* dirmngr.h - Common definitions for the dirmngr * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2004, 2015 g10 Code GmbH * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * SPDX-License-Identifier: GPL-3.0+ */ #ifndef DIRMNGR_H #define DIRMNGR_H #include "./dirmngr-err.h" #define map_assuan_err(a) \ map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a)) #include #include #include #include "../common/util.h" #include "../common/membuf.h" #include "../common/sysutils.h" /* (gnupg_fd_t) */ #include "../common/asshelp.h" /* (assuan_context_t) */ #include "../common/i18n.h" #include "dirmngr-status.h" #include "http.h" /* (parsed_uri_t) */ /* This objects keeps information about a particular LDAP server and is used as item of a single linked list of servers. */ struct ldap_server_s { struct ldap_server_s* next; char *host; int port; char *user; char *pass; char *base; unsigned int use_ldaps:1; }; typedef struct ldap_server_s *ldap_server_t; /* This objects is used to build a list of URI consisting of the original and the parsed URI. */ struct uri_item_s { struct uri_item_s *next; parsed_uri_t parsed_uri; /* The broken down URI. */ char uri[1]; /* The original URI. */ }; typedef struct uri_item_s *uri_item_t; /* A list of fingerprints. */ struct fingerprint_list_s; typedef struct fingerprint_list_s *fingerprint_list_t; struct fingerprint_list_s { fingerprint_list_t next; char hexfpr[20+20+1]; }; /* A large struct named "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 */ const char *homedir_cache; /* Dir for cache files (/var/cache/dirmngr). */ char *config_filename; /* Name of a config file, which will be reread on a HUP if it is not NULL. */ char *ldap_wrapper_program; /* Override value for the LDAP wrapper program. */ char *http_wrapper_program; /* Override value for the HTTP wrapper program. */ int running_detached; /* We are running in detached mode. */ int allow_version_check; /* --allow-version-check is active. */ int force; /* Force loading outdated CRLs. */ unsigned int connect_timeout; /* Timeout for connect. */ unsigned int connect_quick_timeout; /* Shorter timeout for connect. */ int disable_http; /* Do not use HTTP at all. */ int disable_ldap; /* Do not use LDAP at all. */ int disable_ipv4; /* Do not use legacy IP addresses. */ int disable_ipv6; /* Do not use standard IP addresses. */ int honor_http_proxy; /* Honor the http_proxy env variable. */ const char *http_proxy; /* The default HTTP proxy. */ const char *ldap_proxy; /* Use given LDAP proxy. */ int only_ldap_proxy; /* Only use the LDAP proxy; no fallback. */ int ignore_http_dp; /* Ignore HTTP CRL distribution points. */ int ignore_ldap_dp; /* Ignore LDAP CRL distribution points. */ int ignore_ocsp_service_url; /* Ignore OCSP service URLs as given in the certificate. */ /* A list of certificate extension OIDs which are ignored so that one can claim that a critical extension has been handled. One OID per string. */ strlist_t ignored_cert_extensions; int allow_ocsp; /* Allow using OCSP. */ int max_replies; unsigned int ldaptimeout; ldap_server_t ldapservers; int add_new_ldapservers; const char *ocsp_responder; /* Standard OCSP responder's URL. */ fingerprint_list_t ocsp_signer; /* The list of fingerprints with allowed standard OCSP signer certificates. */ unsigned int ocsp_max_clock_skew; /* Allowed seconds of clocks skew. */ unsigned int ocsp_max_period; /* Seconds a response is at maximum considered valid after thisUpdate. */ unsigned int ocsp_current_period; /* Seconds a response is considered current after nextUpdate. */ strlist_t keyserver; /* List of default keyservers. */ } opt; #define DBG_X509_VALUE 1 /* debug x.509 parsing */ #define DBG_CRYPTO_VALUE 4 /* debug low level crypto */ #define DBG_DNS_VALUE 16 /* debug DNS calls. */ #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 /* debug assuan communication */ #define DBG_NETWORK_VALUE 2048 /* debug network I/O. */ #define DBG_LOOKUP_VALUE 8192 /* debug lookup details */ #define DBG_EXTPROG_VALUE 16384 /* debug external program calls */ #define DBG_X509 (opt.debug & DBG_X509_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_DNS (opt.debug & DBG_DNS_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) #define DBG_NETWORK (opt.debug & DBG_NETWORK_VALUE) #define DBG_LOOKUP (opt.debug & DBG_LOOKUP_VALUE) #define DBG_EXTPROG (opt.debug & DBG_EXTPROG_VALUE) /* A simple list of certificate references. FIXME: Better use certlist_t also for references (Store NULL at .cert) */ struct cert_ref_s { struct cert_ref_s *next; unsigned char fpr[20]; }; typedef struct cert_ref_s *cert_ref_t; /* Forward references; access only through server.c. */ struct server_local_s; #if SIZEOF_UNSIGNED_LONG == 8 # define SERVER_CONTROL_MAGIC 0x6469726d6e677220 #else # define SERVER_CONTROL_MAGIC 0x6469726d #endif /* Connection control structure. */ struct server_control_s { unsigned long magic;/* Always has SERVER_CONTROL_MAGIC. */ int refcount; /* Count additional references to this object. */ int no_server; /* We are not running under server control. */ int status_fd; /* Only for non-server mode. */ struct server_local_s *server_local; int force_crl_refresh; /* Always load a fresh CRL. */ int check_revocations_nest_level; /* Internal to check_revovations. */ cert_ref_t ocsp_certs; /* Certificates from the current OCSP response. */ int audit_events; /* Send audit events to client. */ char *http_proxy; /* The used http_proxy or NULL. */ unsigned int timeout; /* Timeout for connect calls in ms. */ unsigned int http_no_crl:1; /* Do not check CRLs for https. */ }; /*-- dirmngr.c --*/ void dirmngr_exit( int ); /* Wrapper for exit() */ void dirmngr_init_default_ctrl (ctrl_t ctrl); void dirmngr_deinit_default_ctrl (ctrl_t ctrl); void dirmngr_sighup_action (void); const char* dirmngr_get_current_socket_name (void); int dirmngr_use_tor (void); /*-- Various housekeeping functions. --*/ void ks_hkp_housekeeping (time_t curtime); void ks_hkp_reload (void); void ks_hkp_init (void); /*-- server.c --*/ ldap_server_t get_ldapservers_from_ctrl (ctrl_t ctrl); ksba_cert_t get_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_issuing_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid); gpg_error_t get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr); int dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat, const char *msg); void start_command_handler (gnupg_fd_t fd, unsigned int session_id); gpg_error_t dirmngr_tick (ctrl_t ctrl); /*-- http-ntbtls.c --*/ /* Note that we don't use a callback for gnutls. */ gpg_error_t gnupg_http_tls_verify_cb (void *opaque, http_t http, http_session_t session, unsigned int flags, void *tls_context); /*-- loadswdb.c --*/ gpg_error_t dirmngr_load_swdb (ctrl_t ctrl, int force); /*-- domaininfo.c --*/ void domaininfo_print_stats (void); int domaininfo_is_wkd_not_supported (const char *domain); void domaininfo_set_no_name (const char *domain); void domaininfo_set_wkd_supported (const char *domain); void domaininfo_set_wkd_not_supported (const char *domain); void domaininfo_set_wkd_not_found (const char *domain); /*-- workqueue.c --*/ typedef const char *(*wqtask_t)(ctrl_t ctrl, const char *args); void workqueue_dump_queue (ctrl_t ctrl); gpg_error_t workqueue_add_task (wqtask_t func, const char *args, unsigned int session_id, int need_network); void workqueue_run_global_tasks (ctrl_t ctrl, int with_network); void workqueue_run_post_session_tasks (unsigned int session_id); #endif /*DIRMNGR_H*/ diff --git a/g10/gpgcompose.c b/g10/gpgcompose.c index 43cecb90e..0a2b21a4c 100644 --- a/g10/gpgcompose.c +++ b/g10/gpgcompose.c @@ -1,3112 +1,3113 @@ /* gpgcompose.c - Maintainer tool to create OpenPGP messages by hand. * Copyright (C) 2016 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 +#define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include "packet.h" #include "keydb.h" #include "main.h" #include "options.h" #include "call-agent.h" static int do_debug; #define debug(fmt, ...) \ do { if (do_debug) log_debug (fmt, ##__VA_ARGS__); } while (0) /* --encryption, for instance, adds a filter in front of out. There is an operator (--encryption-pop) to end this. We use the following infrastructure to make it easy to pop the state. */ struct filter { void *func; void *context; int pkttype; int partial_block_mode; struct filter *next; }; /* Hack to ass CTRL to some functions. */ static ctrl_t global_ctrl; static struct filter *filters; static void filter_push (iobuf_t out, void *func, void *context, int type, int partial_block_mode) { gpg_error_t err; struct filter *f = xmalloc_clear (sizeof (*f)); f->next = filters; f->func = func; f->context = context; f->pkttype = type; f->partial_block_mode = partial_block_mode; filters = f; err = iobuf_push_filter (out, func, context); if (err) log_fatal ("Adding filter: %s\n", gpg_strerror (err)); } static void filter_pop (iobuf_t out, int expected_type) { gpg_error_t err; struct filter *f = filters; log_assert (f); if (f->pkttype != expected_type) log_fatal ("Attempted to pop a %s container, " "but current container is a %s container.\n", pkttype_str (f->pkttype), pkttype_str (expected_type)); if (f->pkttype == PKT_ENCRYPTED) { err = iobuf_pop_filter (out, f->func, f->context); if (err) log_fatal ("Popping encryption filter: %s\n", gpg_strerror (err)); } else log_fatal ("FILTERS appears to be corrupted.\n"); if (f->partial_block_mode) iobuf_set_partial_body_length_mode (out, 0); filters = f->next; xfree (f); } /* Return if CIPHER_ID is a valid cipher. */ static int valid_cipher (int cipher_id) { return (cipher_id == CIPHER_ALGO_IDEA || cipher_id == CIPHER_ALGO_3DES || cipher_id == CIPHER_ALGO_CAST5 || cipher_id == CIPHER_ALGO_BLOWFISH || cipher_id == CIPHER_ALGO_AES || cipher_id == CIPHER_ALGO_AES192 || cipher_id == CIPHER_ALGO_AES256 || cipher_id == CIPHER_ALGO_TWOFISH || cipher_id == CIPHER_ALGO_CAMELLIA128 || cipher_id == CIPHER_ALGO_CAMELLIA192 || cipher_id == CIPHER_ALGO_CAMELLIA256); } /* Parse a session key encoded as a string of the form x:HEXDIGITS where x is the algorithm id. (This is the format emitted by gpg --show-session-key.) */ struct session_key { int algo; int keylen; char *key; }; static struct session_key parse_session_key (const char *option, char *p, int require_algo) { char *tail; struct session_key sk; memset (&sk, 0, sizeof (sk)); /* Check for the optional "cipher-id:" at the start of the string. */ errno = 0; sk.algo = strtol (p, &tail, 10); if (! errno && tail && *tail == ':') { if (! valid_cipher (sk.algo)) log_info ("%s: %d is not a known cipher (but using anyways)\n", option, sk.algo); p = tail + 1; } else if (require_algo) log_fatal ("%s: Session key must have the form algo:HEXCHARACTERS.\n", option); else sk.algo = 0; /* Ignore a leading 0x. */ if (p[0] == '0' && p[1] == 'x') p += 2; if (strlen (p) % 2 != 0) log_fatal ("%s: session key must consist of an even number of hexadecimal characters.\n", option); sk.keylen = strlen (p) / 2; sk.key = xmalloc (sk.keylen); if (hex2bin (p, sk.key, sk.keylen) == -1) log_fatal ("%s: Session key must only contain hexadecimal characters\n", option); return sk; } /* A callback. OPTION_STR is the option that was matched. ARGC is the number of arguments following the option and ARGV are those arguments. (Thus, argv[0] is the first string following the option and argv[-1] is the option.) COOKIE is the opaque value passed to process_options. */ typedef int (*option_prcessor_t) (const char *option_str, int argc, char *argv[], void *cookie); struct option { /* The option that this matches. This must start with "--" or be the empty string. The empty string matches bare arguments. */ const char *option; /* The function to call to process this option. */ option_prcessor_t func; /* Documentation. */ const char *help; }; /* Merge two lists of options. Note: this makes a shallow copy! The caller must xfree() the result. */ static struct option * merge_options (struct option a[], struct option b[]) { int i, j; struct option *c; for (i = 0; a[i].option; i ++) ; for (j = 0; b[j].option; j ++) ; c = xmalloc ((i + j + 1) * sizeof (struct option)); memcpy (c, a, i * sizeof (struct option)); memcpy (&c[i], b, j * sizeof (struct option)); c[i + j].option = NULL; if (a[i].help && b[j].help) c[i + j].help = xasprintf ("%s\n\n%s", a[i].help, b[j].help); else if (a[i].help) c[i + j].help = a[i].help; else if (b[j].help) c[i + j].help = b[j].help; return c; } /* Returns whether ARG is an option. All options start with --. */ static int is_option (const char *arg) { return arg[0] == '-' && arg[1] == '-'; } /* OPTIONS is a NULL terminated array of struct option:s. Finds the entry that is the same as ARG. Returns -1 if no entry is found. The empty string option matches bare arguments. */ static int match_option (const struct option options[], const char *arg) { int i; int bare_arg = ! is_option (arg); for (i = 0; options[i].option; i ++) if ((! bare_arg && strcmp (options[i].option, arg) == 0) /* Non-options match the empty string. */ || (bare_arg && options[i].option[0] == '\0')) return i; return -1; } static void show_help (struct option options[]) { int i; int max_length = 0; int space; for (i = 0; options[i].option; i ++) { const char *option = options[i].option[0] ? options[i].option : "ARG"; int l = strlen (option); if (l > max_length) max_length = l; } space = 72 - (max_length + 2); if (space < 40) space = 40; for (i = 0; ; i ++) { const char *option = options[i].option; const char *help = options[i].help; int l; int j; char *tmp; char *formatted; char *p; char *newline; if (! option && ! help) break; if (option) { const char *o = option[0] ? option : "ARG"; l = strlen (o); fprintf (stdout, "%s", o); } if (! help) { fputc ('\n', stdout); continue; } if (option) for (j = l; j < max_length + 2; j ++) fputc (' ', stdout); #define BOLD_START "\033[1m" #define NORMAL_RESTORE "\033[0m" #define BOLD(x) BOLD_START x NORMAL_RESTORE if (! option || options[i].func) tmp = (char *) help; else tmp = xasprintf ("%s " BOLD("(Unimplemented.)"), help); if (! option) space = 72; formatted = format_text (tmp, space, space + 4); if (!formatted) abort (); if (tmp != help) xfree (tmp); if (! option) { printf ("\n%s\n", formatted); break; } for (p = formatted; p && *p; p = (*newline == '\0') ? newline : newline + 1) { newline = strchr (p, '\n'); if (! newline) newline = &p[strlen (p)]; l = (size_t) newline - (size_t) p; if (p != formatted) for (j = 0; j < max_length + 2; j ++) fputc (' ', stdout); fwrite (p, l, 1, stdout); fputc ('\n', stdout); } xfree (formatted); } } /* Return value is number of consumed argv elements. */ static int process_options (const char *parent_option, struct option break_options[], struct option local_options[], void *lcookie, struct option global_options[], void *gcookie, int argc, char *argv[]) { int i; for (i = 0; i < argc; i ++) { int j; struct option *option; void *cookie; int bare_arg; option_prcessor_t func; int consumed; if (break_options) { j = match_option (break_options, argv[i]); if (j != -1) /* Match. Break out. */ return i; } j = match_option (local_options, argv[i]); if (j == -1) { if (global_options) j = match_option (global_options, argv[i]); if (j == -1) { if (strcmp (argv[i], "--help") == 0) { if (! global_options) show_help (local_options); else { struct option *combined = merge_options (local_options, global_options); show_help (combined); xfree (combined); } g10_exit (0); } if (parent_option) log_fatal ("%s: Unknown option: %s\n", parent_option, argv[i]); else log_fatal ("Unknown option: %s\n", argv[i]); } option = &global_options[j]; cookie = gcookie; } else { option = &local_options[j]; cookie = lcookie; } bare_arg = strcmp (option->option, "") == 0; func = option->func; if (! func) { if (bare_arg) log_fatal ("Bare arguments unimplemented.\n"); else log_fatal ("Unimplemented option: %s\n", option->option); } consumed = func (bare_arg ? parent_option : argv[i], argc - i - !bare_arg, &argv[i + !bare_arg], cookie); i += consumed; if (bare_arg) i --; } return i; } /* The keys, subkeys, user ids and user attributes in the order that they were added. */ PACKET components[20]; /* The number of components. */ int ncomponents; static int add_component (int pkttype, void *component) { int i = ncomponents ++; log_assert (i < sizeof (components) / sizeof (components[0])); log_assert (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_PUBLIC_SUBKEY || pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY || pkttype == PKT_USER_ID || pkttype == PKT_ATTRIBUTE); components[i].pkttype = pkttype; components[i].pkt.generic = component; return i; } static void dump_component (PACKET *pkt) { struct kbnode_struct kbnode; if (! do_debug) return; memset (&kbnode, 0, sizeof (kbnode)); kbnode.pkt = pkt; dump_kbnode (&kbnode); } /* Returns the first primary key in COMPONENTS or NULL if there is none. */ static PKT_public_key * primary_key (void) { int i; for (i = 0; i < ncomponents; i ++) if (components[i].pkttype == PKT_PUBLIC_KEY) return components[i].pkt.public_key; return NULL; } /* The last session key (updated when adding a SK-ESK, PK-ESK or SED packet. */ static DEK session_key; static int user_id (const char *option, int argc, char *argv[], void *cookie); static int public_key (const char *option, int argc, char *argv[], void *cookie); static int sk_esk (const char *option, int argc, char *argv[], void *cookie); static int pk_esk (const char *option, int argc, char *argv[], void *cookie); static int encrypted (const char *option, int argc, char *argv[], void *cookie); static int encrypted_pop (const char *option, int argc, char *argv[], void *cookie); static int literal (const char *option, int argc, char *argv[], void *cookie); static int signature (const char *option, int argc, char *argv[], void *cookie); static int copy (const char *option, int argc, char *argv[], void *cookie); static struct option major_options[] = { { "--user-id", user_id, "Create a user id packet." }, { "--public-key", public_key, "Create a public key packet." }, { "--private-key", NULL, "Create a private key packet." }, { "--public-subkey", public_key, "Create a subkey packet." }, { "--private-subkey", NULL, "Create a private subkey packet." }, { "--sk-esk", sk_esk, "Create a symmetric-key encrypted session key packet." }, { "--pk-esk", pk_esk, "Create a public-key encrypted session key packet." }, { "--encrypted", encrypted, "Create a symmetrically encrypted data packet." }, { "--encrypted-mdc", encrypted, "Create a symmetrically encrypted and integrity protected data packet." }, { "--encrypted-pop", encrypted_pop, "Pop the most recent encryption container started by either" " --encrypted or --encrypted-mdc." }, { "--compressed", NULL, "Create a compressed data packet." }, { "--literal", literal, "Create a literal (plaintext) data packet." }, { "--signature", signature, "Create a signature packet." }, { "--onepass-sig", NULL, "Create a one-pass signature packet." }, { "--copy", copy, "Copy the specified file." }, { NULL, NULL, "To get more information about a given command, use:\n\n" " $ gpgcompose --command --help to list a command's options."}, }; static struct option global_options[] = { { NULL, NULL, NULL }, }; /* Make our lives easier and use a static limit for the user name. 10k is way more than enough anyways... */ const int user_id_max_len = 10 * 1024; static int user_id_name (const char *option, int argc, char *argv[], void *cookie) { PKT_user_id *uid = cookie; int l; if (argc == 0) log_fatal ("Usage: %s USER_ID\n", option); if (uid->len) log_fatal ("Attempt to set user id multiple times.\n"); l = strlen (argv[0]); if (l > user_id_max_len) log_fatal ("user id too long (max: %d)\n", user_id_max_len); memcpy (uid->name, argv[0], l); uid->name[l] = 0; uid->len = l; return 1; } static struct option user_id_options[] = { { "", user_id_name, "Set the user id. This is usually in the format " "\"Name (comment) \"" }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --user-id \"USERID\" | " GPG_NAME " --list-packets" } }; static int user_id (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; gpg_error_t err; PKT_user_id *uid = xmalloc_clear (sizeof (*uid) + user_id_max_len); int c = add_component (PKT_USER_ID, uid); int processed; processed = process_options (option, major_options, user_id_options, uid, global_options, NULL, argc, argv); if (! uid->len) log_fatal ("%s: user id not given", option); err = build_packet (out, &components[c]); if (err) log_fatal ("Serializing user id packet: %s\n", gpg_strerror (err)); debug ("Wrote user id packet:\n"); dump_component (&components[c]); return processed; } static int pk_search_terms (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; KEYDB_HANDLE hd; KEYDB_SEARCH_DESC desc; kbnode_t kb; PKT_public_key *pk = cookie; PKT_public_key *pk_ref; int i; if (argc == 0) log_fatal ("Usage: %s KEYID\n", option); if (pk->pubkey_algo) log_fatal ("%s: multiple keys provided\n", option); err = classify_user_id (argv[0], &desc, 0); if (err) log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err)); hd = keydb_new (ctrl); err = keydb_search (hd, &desc, 1, NULL); if (err) log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err)); err = keydb_get_keyblock (hd, &kb); if (err) log_fatal ("retrieving keyblock for '%s': %s\n", argv[0], gpg_strerror (err)); keydb_release (hd); pk_ref = kb->pkt->pkt.public_key; /* Copy the timestamp (if not already set), algo and public key parameters. */ if (! pk->timestamp) pk->timestamp = pk_ref->timestamp; pk->pubkey_algo = pk_ref->pubkey_algo; for (i = 0; i < pubkey_get_npkey (pk->pubkey_algo); i ++) pk->pkey[i] = gcry_mpi_copy (pk_ref->pkey[i]); release_kbnode (kb); return 1; } static int pk_timestamp (const char *option, int argc, char *argv[], void *cookie) { PKT_public_key *pk = cookie; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s TIMESTAMP\n", option); errno = 0; pk->timestamp = parse_timestamp (argv[0], &tail); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); return 1; } #define TIMESTAMP_HELP \ "Either as seconds since the epoch or as an ISO 8601 formatted " \ "string (yyyymmddThhmmss, where the T is a literal)." static struct option pk_options[] = { { "--timestamp", pk_timestamp, "The creation time. " TIMESTAMP_HELP }, { "", pk_search_terms, "The key to copy the creation time and public key parameters from." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --public-key $KEYID --user-id \"USERID\" \\\n" " | " GPG_NAME " --list-packets" } }; static int public_key (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; iobuf_t out = cookie; PKT_public_key *pk; int c; int processed; int t = (strcmp (option, "--public-key") == 0 ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY); (void) option; pk = xmalloc_clear (sizeof (*pk)); pk->version = 4; c = add_component (t, pk); processed = process_options (option, major_options, pk_options, pk, global_options, NULL, argc, argv); if (! pk->pubkey_algo) log_fatal ("%s: key to extract public key parameters from not given", option); /* Clear the keyid in case we updated one of the relevant fields after accessing it. */ pk->keyid[0] = pk->keyid[1] = 0; err = build_packet (out, &components[c]); if (err) log_fatal ("serializing %s packet: %s\n", t == PKT_PUBLIC_KEY ? "public key" : "subkey", gpg_strerror (err)); debug ("Wrote %s packet:\n", t == PKT_PUBLIC_KEY ? "public key" : "subkey"); dump_component (&components[c]); return processed; } struct signinfo { /* Key with which to sign. */ kbnode_t issuer_kb; PKT_public_key *issuer_pk; /* Overrides the issuer's key id. */ u32 issuer_keyid[2]; /* Sets the issuer's keyid to the primary key's key id. */ int issuer_keyid_self; /* Key to sign. */ PKT_public_key *pk; /* Subkey to sign. */ PKT_public_key *sk; /* User id to sign. */ PKT_user_id *uid; int class; int digest_algo; u32 timestamp; u32 key_expiration; byte *cipher_algorithms; int cipher_algorithms_len; byte *digest_algorithms; int digest_algorithms_len; byte *compress_algorithms; int compress_algorithms_len; u32 expiration; int exportable_set; int exportable; int revocable_set; int revocable; int trust_level_set; byte trust_args[2]; char *trust_scope; struct revocation_key *revocation_key; int nrevocation_keys; struct notation *notations; byte *key_server_preferences; int key_server_preferences_len; char *key_server; int primary_user_id_set; int primary_user_id; char *policy_uri; byte *key_flags; int key_flags_len; char *signers_user_id; byte reason_for_revocation_code; char *reason_for_revocation; byte *features; int features_len; /* Whether to corrupt the signature. */ int corrupt; }; static int sig_issuer (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; KEYDB_HANDLE hd; KEYDB_SEARCH_DESC desc; struct signinfo *si = cookie; if (argc == 0) log_fatal ("Usage: %s KEYID\n", option); if (si->issuer_pk) log_fatal ("%s: multiple keys provided\n", option); err = classify_user_id (argv[0], &desc, 0); if (err) log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err)); hd = keydb_new (ctrl); err = keydb_search (hd, &desc, 1, NULL); if (err) log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err)); err = keydb_get_keyblock (hd, &si->issuer_kb); if (err) log_fatal ("retrieving keyblock for '%s': %s\n", argv[0], gpg_strerror (err)); keydb_release (hd); si->issuer_pk = si->issuer_kb->pkt->pkt.public_key; return 1; } static int sig_issuer_keyid (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; KEYDB_SEARCH_DESC desc; struct signinfo *si = cookie; if (argc == 0) log_fatal ("Usage: %s KEYID|self\n", option); if (si->issuer_keyid[0] || si->issuer_keyid[1] || si->issuer_keyid_self) log_fatal ("%s given multiple times.\n", option); if (strcasecmp (argv[0], "self") == 0) { si->issuer_keyid_self = 1; return 1; } err = classify_user_id (argv[0], &desc, 0); if (err) log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err)); if (desc.mode != KEYDB_SEARCH_MODE_LONG_KID) log_fatal ("%s is not a valid long key id.\n", argv[0]); keyid_copy (si->issuer_keyid, desc.u.kid); return 1; } static int sig_pk (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int i; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s COMPONENT_INDEX\n", option); errno = 0; i = strtoul (argv[0], &tail, 10); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); if (i >= ncomponents) log_fatal ("%d: No such component (have %d components so far)\n", i, ncomponents); if (! (components[i].pkttype == PKT_PUBLIC_KEY || components[i].pkttype == PKT_PUBLIC_SUBKEY)) log_fatal ("Component %d is not a public key or a subkey.", i); if (strcmp (option, "--pk") == 0) { if (si->pk) log_fatal ("%s already given.\n", option); si->pk = components[i].pkt.public_key; } else if (strcmp (option, "--sk") == 0) { if (si->sk) log_fatal ("%s already given.\n", option); si->sk = components[i].pkt.public_key; } else log_fatal ("Cannot handle %s\n", option); return 1; } static int sig_user_id (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int i; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s COMPONENT_INDEX\n", option); if (si->uid) log_fatal ("%s already given.\n", option); errno = 0; i = strtoul (argv[0], &tail, 10); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); if (i >= ncomponents) log_fatal ("%d: No such component (have %d components so far)\n", i, ncomponents); if (! (components[i].pkttype != PKT_USER_ID || components[i].pkttype == PKT_ATTRIBUTE)) log_fatal ("Component %d is not a public key or a subkey.", i); si->uid = components[i].pkt.user_id; return 1; } static int sig_class (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int i; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s CLASS\n", option); errno = 0; i = strtoul (argv[0], &tail, 0); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); si->class = i; return 1; } static int sig_digest (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int i; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s DIGEST_ALGO\n", option); errno = 0; i = strtoul (argv[0], &tail, 10); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); si->digest_algo = i; return 1; } static int sig_timestamp (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s TIMESTAMP\n", option); errno = 0; si->timestamp = parse_timestamp (argv[0], &tail); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); return 1; } static int sig_expiration (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int is_expiration = strcmp (option, "--expiration") == 0; u32 *i = is_expiration ? &si->expiration : &si->key_expiration; if (! is_expiration) log_assert (strcmp (option, "--key-expiration") == 0); if (argc == 0) log_fatal ("Usage: %s DURATION\n", option); *i = parse_expire_string (argv[0]); if (*i == (u32)-1) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); return 1; } static int sig_int_list (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int nvalues = 1; char *values = xmalloc (nvalues * sizeof (values[0])); char *tail = argv[0]; int i; byte **a; int *n; if (argc == 0) log_fatal ("Usage: %s VALUE[,VALUE...]\n", option); for (i = 0; tail && *tail; i ++) { int v; char *old_tail = tail; errno = 0; v = strtol (tail, &tail, 0); if (errno || old_tail == tail || (tail && !(*tail == ',' || *tail == 0))) log_fatal ("Invalid value passed to %s (%s). " "Expected a list of comma separated numbers\n", option, argv[0]); if (! (0 <= v && v <= 255)) log_fatal ("%s: %d is out of range (Expected: 0-255)\n", option, v); if (i == nvalues) { nvalues *= 2; values = xrealloc (values, nvalues * sizeof (values[0])); } values[i] = v; if (*tail == ',') tail ++; else log_assert (*tail == 0); } if (strcmp ("--cipher-algos", option) == 0) { a = &si->cipher_algorithms; n = &si->cipher_algorithms_len; } else if (strcmp ("--digest-algos", option) == 0) { a = &si->digest_algorithms; n = &si->digest_algorithms_len; } else if (strcmp ("--compress-algos", option) == 0) { a = &si->compress_algorithms; n = &si->compress_algorithms_len; } else log_fatal ("Cannot handle %s\n", option); if (*a) log_fatal ("Option %s given multiple times.\n", option); *a = values; *n = i; return 1; } static int sig_flag (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int range[2] = {0, 255}; char *tail; int v; if (strcmp (option, "--primary-user-id") == 0) range[1] = 1; if (argc <= 1) { if (range[0] == 0 && range[1] == 1) log_fatal ("Usage: %s 0|1\n", option); else log_fatal ("Usage: %s %d-%d\n", option, range[0], range[1]); } errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1])) log_fatal ("Invalid value passed to %s (%s). Expected %d-%d\n", option, argv[0], range[0], range[1]); if (strcmp (option, "--exportable") == 0) { si->exportable_set = 1; si->exportable = v; } else if (strcmp (option, "--revocable") == 0) { si->revocable_set = 1; si->revocable = v; } else if (strcmp (option, "--primary-user-id") == 0) { si->primary_user_id_set = 1; si->primary_user_id = v; } else log_fatal ("Cannot handle %s\n", option); return 1; } static int sig_trust_level (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int i; char *tail; if (argc <= 1) log_fatal ("Usage: %s DEPTH TRUST_AMOUNT\n", option); for (i = 0; i < sizeof (si->trust_args) / sizeof (si->trust_args[0]); i ++) { int v; errno = 0; v = strtol (argv[i], &tail, 0); if (errno || (tail && *tail) || !(0 <= v && v <= 255)) log_fatal ("Invalid value passed to %s (%s). Expected 0-255\n", option, argv[i]); si->trust_args[i] = v; } si->trust_level_set = 1; return 2; } static int sig_string_arg (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; char *p = argv[0]; char **s; if (argc == 0) log_fatal ("Usage: %s STRING\n", option); if (strcmp (option, "--trust-scope") == 0) s = &si->trust_scope; else if (strcmp (option, "--key-server") == 0) s = &si->key_server; else if (strcmp (option, "--signers-user-id") == 0) s = &si->signers_user_id; else if (strcmp (option, "--policy-uri") == 0) s = &si->policy_uri; else log_fatal ("Cannot handle %s\n", option); if (*s) log_fatal ("%s already given.\n", option); *s = xstrdup (p); return 1; } static int sig_revocation_key (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; struct signinfo *si = cookie; int v; char *tail; PKT_public_key pk; struct revocation_key *revkey; if (argc < 2) log_fatal ("Usage: %s CLASS KEYID\n", option); memset (&pk, 0, sizeof (pk)); errno = 0; v = strtol (argv[0], &tail, 16); if (errno || (tail && *tail) || !(0 <= v && v <= 255)) log_fatal ("%s: Invalid class value (%s). Expected 0-255\n", option, argv[0]); pk.req_usage = PUBKEY_USAGE_SIG; err = get_pubkey_byname (NULL, GET_PUBKEY_NO_AKL, NULL, &pk, argv[1], NULL, NULL, 1); if (err) log_fatal ("looking up key %s: %s\n", argv[1], gpg_strerror (err)); si->nrevocation_keys ++; si->revocation_key = xrealloc (si->revocation_key, si->nrevocation_keys * sizeof (*si->revocation_key)); revkey = &si->revocation_key[si->nrevocation_keys - 1]; revkey->class = v; revkey->algid = pk.pubkey_algo; fingerprint_from_pk (&pk, revkey->fpr, NULL); release_public_key_parts (&pk); return 2; } static int sig_notation (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int is_blob = strcmp (option, "--notation") != 0; struct notation *notation; char *p = argv[0]; int p_free = 0; char *data; int data_size; int data_len; if (argc == 0) log_fatal ("Usage: %s [!<]name=value\n", option); if ((p[0] == '!' && p[1] == '<') || p[0] == '<') /* Read from a file. */ { char *filename = NULL; iobuf_t in; int prefix; if (p[0] == '<') p ++; else { /* Remove the '<', which string_to_notation does not understand, and preserve the '!'. */ p = xstrdup (&p[1]); p_free = 1; p[0] = '!'; } filename = strchr (p, '='); if (! filename) log_fatal ("No value specified. Usage: %s [!<]name=value\n", option); filename ++; prefix = (size_t) filename - (size_t) p; errno = 0; in = iobuf_open (filename); if (! in) log_fatal ("Opening '%s': %s\n", filename, errno ? strerror (errno): "unknown error"); /* A notation can be at most about a few dozen bytes short of 64k. Since this is relatively small, we just allocate that much instead of trying to dynamically size a buffer. */ data_size = 64 * 1024; data = xmalloc (data_size); log_assert (prefix <= data_size); memcpy (data, p, prefix); data_len = iobuf_read (in, &data[prefix], data_size - prefix - 1); if (data_len == -1) /* EOF => 0 bytes read. */ data_len = 0; if (data_len == data_size - prefix - 1) /* Technically, we should do another read and check for EOF, but what's one byte more or less? */ log_fatal ("Notation data doesn't fit in the packet.\n"); iobuf_close (in); /* NUL terminate it. */ data[prefix + data_len] = 0; if (p_free) xfree (p); p = data; p_free = 1; data = &p[prefix]; if (is_blob) p[prefix - 1] = 0; } else if (is_blob) { data = strchr (p, '='); if (! data) { data = p; data_len = 0; } else { p = xstrdup (p); p_free = 1; data = strchr (p, '='); log_assert (data); /* NUL terminate the name. */ *data = 0; data ++; data_len = strlen (data); } } if (is_blob) notation = blob_to_notation (p, data, data_len); else notation = string_to_notation (p, 1); if (! notation) log_fatal ("creating notation: an unknown error occurred.\n"); notation->next = si->notations; si->notations = notation; if (p_free) xfree (p); return 1; } static int sig_big_endian_arg (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; char *p = argv[0]; int i; int l; char *bytes; if (argc == 0) log_fatal ("Usage: %s HEXDIGITS\n", option); /* Skip a leading "0x". */ if (p[0] == '0' && p[1] == 'x') p += 2; for (i = 0; i < strlen (p); i ++) if (!hexdigitp (&p[i])) log_fatal ("%s: argument ('%s') must consist of hex digits.\n", option, p); if (strlen (p) % 2 != 0) log_fatal ("%s: argument ('%s') must contain an even number of hex digits.\n", option, p); l = strlen (p) / 2; bytes = xmalloc (l); hex2bin (p, bytes, l); if (strcmp (option, "--key-server-preferences") == 0) { if (si->key_server_preferences) log_fatal ("%s given multiple times.\n", option); si->key_server_preferences = bytes; si->key_server_preferences_len = l; } else if (strcmp (option, "--key-flags") == 0) { if (si->key_flags) log_fatal ("%s given multiple times.\n", option); si->key_flags = bytes; si->key_flags_len = l; } else if (strcmp (option, "--features") == 0) { if (si->features) log_fatal ("%s given multiple times.\n", option); si->features = bytes; si->features_len = l; } else log_fatal ("Cannot handle %s\n", option); return 1; } static int sig_reason_for_revocation (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; int v; char *tail; if (argc < 2) log_fatal ("Usage: %s REASON_CODE REASON_STRING\n", option); errno = 0; v = strtol (argv[0], &tail, 16); if (errno || (tail && *tail) || !(0 <= v && v <= 255)) log_fatal ("%s: Invalid reason code (%s). Expected 0-255\n", option, argv[0]); if (si->reason_for_revocation) log_fatal ("%s given multiple times.\n", option); si->reason_for_revocation_code = v; si->reason_for_revocation = xstrdup (argv[1]); return 2; } static int sig_corrupt (const char *option, int argc, char *argv[], void *cookie) { struct signinfo *si = cookie; (void) option; (void) argc; (void) argv; (void) cookie; si->corrupt = 1; return 0; } static struct option sig_options[] = { { "--issuer", sig_issuer, "The key to use to generate the signature."}, { "--issuer-keyid", sig_issuer_keyid, "Set the issuer's key id. This is useful for creating a " "self-signature. As a special case, the value \"self\" refers " "to the primary key's key id. " "(RFC 4880, Section 5.2.3.5)" }, { "--pk", sig_pk, "The primary keyas an index into the components (keys and uids) " "created so far where the first component has the index 0." }, { "--sk", sig_pk, "The subkey as an index into the components (keys and uids) created " "so far where the first component has the index 0. Only needed for " "0x18, 0x19, and 0x28 signatures." }, { "--user-id", sig_user_id, "The user id as an index into the components (keys and uids) created " "so far where the first component has the index 0. Only needed for " "0x10-0x13 and 0x30 signatures." }, { "--class", sig_class, "The signature's class. Valid values are " "0x10-0x13 (user id and primary-key certification), " "0x18 (subkey binding), " "0x19 (primary key binding), " "0x1f (direct primary key signature), " "0x20 (key revocation), " "0x28 (subkey revocation), and " "0x30 (certification revocation)." }, { "--digest", sig_digest, "The digest algorithm" }, { "--timestamp", sig_timestamp, "The signature's creation time. " TIMESTAMP_HELP " 0 means now. " "(RFC 4880, Section 5.2.3.4)" }, { "--key-expiration", sig_expiration, "The number of days until the associated key expires. To specify " "seconds, prefix the value with \"seconds=\". It is also possible " "to use 'y', 'm' and 'w' as simple multipliers. For instance, 2y " "means 2 years, etc. " "(RFC 4880, Section 5.2.3.6)" }, { "--cipher-algos", sig_int_list, "A comma separated list of the preferred cipher algorithms (identified by " "their number, see RFC 4880, Section 9). " "(RFC 4880, Section 5.2.3.7)" }, { "--digest-algos", sig_int_list, "A comma separated list of the preferred algorithms (identified by " "their number, see RFC 4880, Section 9). " "(RFC 4880, Section 5.2.3.8)" }, { "--compress-algos", sig_int_list, "A comma separated list of the preferred algorithms (identified by " "their number, see RFC 4880, Section 9)." "(RFC 4880, Section 5.2.3.9)" }, { "--expiration", sig_expiration, "The number of days until the signature expires. To specify seconds, " "prefix the value with \"seconds=\". It is also possible to use 'y', " "'m' and 'w' as simple multipliers. For instance, 2y means 2 years, " "etc. " "(RFC 4880, Section 5.2.3.10)" }, { "--exportable", sig_flag, "Mark this signature as exportable (1) or local (0). " "(RFC 4880, Section 5.2.3.11)" }, { "--revocable", sig_flag, "Mark this signature as revocable (1, revocations are ignored) " "or non-revocable (0). " "(RFC 4880, Section 5.2.3.12)" }, { "--trust-level", sig_trust_level, "Set the trust level. This takes two integer arguments (0-255): " "the trusted-introducer level and the degree of trust. " "(RFC 4880, Section 5.2.3.13.)" }, { "--trust-scope", sig_string_arg, "A regular expression that limits the scope of --trust-level. " "(RFC 4880, Section 5.2.3.14.)" }, { "--revocation-key", sig_revocation_key, "Specify a designated revoker. Takes two arguments: the class " "(normally 0x80 or 0xC0 (sensitive)) and the key id of the " "designatured revoker. May be given multiple times. " "(RFC 4880, Section 5.2.3.15)" }, { "--notation", sig_notation, "Add a human-readable notation of the form \"[!<]name=value\" where " "\"!\" means that the critical flag should be set and \"<\" means " "that VALUE is a file to read the data from. " "(RFC 4880, Section 5.2.3.16)" }, { "--notation-binary", sig_notation, "Add a binary notation of the form \"[!<]name=value\" where " "\"!\" means that the critical flag should be set and \"<\" means " "that VALUE is a file to read the data from. " "(RFC 4880, Section 5.2.3.16)" }, { "--key-server-preferences", sig_big_endian_arg, "Big-endian number encoding the keyserver preferences. " "(RFC 4880, Section 5.2.3.17)" }, { "--key-server", sig_string_arg, "The preferred keyserver. (RFC 4880, Section 5.2.3.18)" }, { "--primary-user-id", sig_flag, "Sets the primary user id flag. (RFC 4880, Section 5.2.3.19)" }, { "--policy-uri", sig_string_arg, "URI of a document that describes the issuer's signing policy. " "(RFC 4880, Section 5.2.3.20)" }, { "--key-flags", sig_big_endian_arg, "Big-endian number encoding the key flags. " "(RFC 4880, Section 5.2.3.21)" }, { "--signers-user-id", sig_string_arg, "The user id (as a string) responsible for the signing. " "(RFC 4880, Section 5.2.3.22)" }, { "--reason-for-revocation", sig_reason_for_revocation, "Takes two arguments: a reason for revocation code and a " "user-provided string. " "(RFC 4880, Section 5.2.3.23)" }, { "--features", sig_big_endian_arg, "Big-endian number encoding the feature flags. " "(RFC 4880, Section 5.2.3.24)" }, { "--signature-target", NULL, "Takes three arguments: the target signature's public key algorithm " " (as an integer), the hash algorithm (as an integer) and the hash " " (as a hexadecimal string). " "(RFC 4880, Section 5.2.3.25)" }, { "--embedded-signature", NULL, "An embedded signature. This must be immediately followed by a " "signature packet (created using --signature ...) or a filename " "containing the packet." "(RFC 4880, Section 5.2.3.26)" }, { "--hashed", NULL, "The following attributes will be placed in the hashed area of " "the signature. (This is the default and it reset at the end of" "each signature.)" }, { "--unhashed", NULL, "The following attributes will be placed in the unhashed area of " "the signature (and thus not integrity protected)." }, { "--corrupt", sig_corrupt, "Corrupt the signature." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --public-key $KEYID --user-id USERID \\\n" " --signature --class 0x10 --issuer $KEYID --issuer-keyid self \\\n" " | " GPG_NAME " --list-packets"} }; static int mksubpkt_callback (PKT_signature *sig, void *cookie) { struct signinfo *si = cookie; int i; if (si->key_expiration) { char buf[4]; buf[0] = (si->key_expiration >> 24) & 0xff; buf[1] = (si->key_expiration >> 16) & 0xff; buf[2] = (si->key_expiration >> 8) & 0xff; buf[3] = si->key_expiration & 0xff; build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4); } if (si->cipher_algorithms) build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, si->cipher_algorithms, si->cipher_algorithms_len); if (si->digest_algorithms) build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, si->digest_algorithms, si->digest_algorithms_len); if (si->compress_algorithms) build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, si->compress_algorithms, si->compress_algorithms_len); if (si->exportable_set) { char buf = si->exportable; build_sig_subpkt (sig, SIGSUBPKT_EXPORTABLE, &buf, 1); } if (si->trust_level_set) build_sig_subpkt (sig, SIGSUBPKT_TRUST, si->trust_args, sizeof (si->trust_args)); if (si->trust_scope) build_sig_subpkt (sig, SIGSUBPKT_REGEXP, si->trust_scope, strlen (si->trust_scope)); for (i = 0; i < si->nrevocation_keys; i ++) { struct revocation_key *revkey = &si->revocation_key[i]; gpg_error_t err = keygen_add_revkey (sig, revkey); if (err) { u32 keyid[2]; keyid_from_fingerprint (global_ctrl, revkey->fpr, 20, keyid); log_fatal ("adding revocation key %s: %s\n", keystr (keyid), gpg_strerror (err)); } } /* keygen_add_revkey sets revocable=0 so be sure to do this after adding the rev keys. */ if (si->revocable_set) { char buf = si->revocable; build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, &buf, 1); } keygen_add_notations (sig, si->notations); if (si->key_server_preferences) build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, si->key_server_preferences, si->key_server_preferences_len); if (si->key_server) build_sig_subpkt (sig, SIGSUBPKT_PREF_KS, si->key_server, strlen (si->key_server)); if (si->primary_user_id_set) { char buf = si->primary_user_id; build_sig_subpkt (sig, SIGSUBPKT_PRIMARY_UID, &buf, 1); } if (si->policy_uri) build_sig_subpkt (sig, SIGSUBPKT_POLICY, si->policy_uri, strlen (si->policy_uri)); if (si->key_flags) build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, si->key_flags, si->key_flags_len); if (si->signers_user_id) build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID, si->signers_user_id, strlen (si->signers_user_id)); if (si->reason_for_revocation) { int len = 1 + strlen (si->reason_for_revocation); char *buf; buf = xmalloc (len); buf[0] = si->reason_for_revocation_code; memcpy (&buf[1], si->reason_for_revocation, len - 1); build_sig_subpkt (sig, SIGSUBPKT_REVOC_REASON, buf, len); xfree (buf); } if (si->features) build_sig_subpkt (sig, SIGSUBPKT_FEATURES, si->features, si->features_len); return 0; } static int signature (const char *option, int argc, char *argv[], void *cookie) { gpg_error_t err; iobuf_t out = cookie; struct signinfo si; int processed; PKT_public_key *pk; PKT_signature *sig; PACKET pkt; u32 keyid_orig[2], keyid[2]; (void) option; memset (&si, 0, sizeof (si)); memset (&pkt, 0, sizeof (pkt)); processed = process_options (option, major_options, sig_options, &si, global_options, NULL, argc, argv); if (ncomponents) { int pkttype = components[ncomponents - 1].pkttype; if (pkttype == PKT_PUBLIC_KEY) { if (! si.class) /* Direct key sig. */ si.class = 0x1F; } else if (pkttype == PKT_PUBLIC_SUBKEY) { if (! si.sk) si.sk = components[ncomponents - 1].pkt.public_key; if (! si.class) /* Subkey binding sig. */ si.class = 0x18; } else if (pkttype == PKT_USER_ID) { if (! si.uid) si.uid = components[ncomponents - 1].pkt.user_id; if (! si.class) /* Certification of a user id and public key packet. */ si.class = 0x10; } } pk = NULL; if (! si.pk || ! si.issuer_pk) /* No primary key specified. Default to the first one that we find. */ { int i; for (i = 0; i < ncomponents; i ++) if (components[i].pkttype == PKT_PUBLIC_KEY) { pk = components[i].pkt.public_key; break; } } if (! si.pk) { if (! pk) log_fatal ("%s: no primary key given and no primary key available", "--pk"); si.pk = pk; } if (! si.issuer_pk) { if (! pk) log_fatal ("%s: no issuer key given and no primary key available", "--issuer"); si.issuer_pk = pk; } if (si.class == 0x18 || si.class == 0x19 || si.class == 0x28) /* Requires the primary key and a subkey. */ { if (! si.sk) log_fatal ("sig class 0x%x requires a subkey (--sk)\n", si.class); } else if (si.class == 0x10 || si.class == 0x11 || si.class == 0x12 || si.class == 0x13 || si.class == 0x30) /* Requires the primary key and a user id. */ { if (! si.uid) log_fatal ("sig class 0x%x requires a uid (--uid)\n", si.class); } else if (si.class == 0x1F || si.class == 0x20) /* Just requires the primary key. */ ; else log_fatal ("Unsupported signature class: 0x%x\n", si.class); sig = xmalloc_clear (sizeof (*sig)); /* Save SI.ISSUER_PK->KEYID. */ keyid_copy (keyid_orig, pk_keyid (si.issuer_pk)); if (si.issuer_keyid[0] || si.issuer_keyid[1]) keyid_copy (si.issuer_pk->keyid, si.issuer_keyid); else if (si.issuer_keyid_self) { PKT_public_key *pripk = primary_key(); if (! pripk) log_fatal ("--issuer-keyid self given, but no primary key available.\n"); keyid_copy (si.issuer_pk->keyid, pk_keyid (pripk)); } /* The reuse of core gpg stuff by this tool is questionable when it * requires adding extra code to the actual gpg code. It does not * make sense to pass an extra parameter and in particular not given * that gpg already has opt.cert_digest_algo to override it. */ if (si.digest_algo) log_info ("note: digest algo can't be passed to make_keysig_packet\n"); /* Changing the issuer's key id is fragile. Check to make sure make_keysig_packet didn't recompute the keyid. */ keyid_copy (keyid, si.issuer_pk->keyid); err = make_keysig_packet (global_ctrl, &sig, si.pk, si.uid, si.sk, si.issuer_pk, si.class, si.timestamp, si.expiration, mksubpkt_callback, &si, NULL); log_assert (keyid_cmp (keyid, si.issuer_pk->keyid) == 0); if (err) log_fatal ("Generating signature: %s\n", gpg_strerror (err)); /* Restore SI.PK->KEYID. */ keyid_copy (si.issuer_pk->keyid, keyid_orig); if (si.corrupt) { /* Set the top 32-bits to 0xBAD0DEAD. */ int bits = gcry_mpi_get_nbits (sig->data[0]); gcry_mpi_t x = gcry_mpi_new (0); gcry_mpi_add_ui (x, x, 0xBAD0DEAD); gcry_mpi_lshift (x, x, bits > 32 ? bits - 32 : bits); gcry_mpi_clear_highbit (sig->data[0], bits > 32 ? bits - 32 : 0); gcry_mpi_add (sig->data[0], sig->data[0], x); gcry_mpi_release (x); } pkt.pkttype = PKT_SIGNATURE; pkt.pkt.signature = sig; err = build_packet (out, &pkt); if (err) log_fatal ("serializing public key packet: %s\n", gpg_strerror (err)); debug ("Wrote signature packet:\n"); dump_component (&pkt); free_seckey_enc (sig); release_kbnode (si.issuer_kb); xfree (si.revocation_key); return processed; } struct sk_esk_info { /* The cipher used for encrypting the session key (when a session key is used). */ int cipher; /* The cipher used for encryping the SED packet. */ int sed_cipher; /* S2K related data. */ int hash; int mode; int mode_set; byte salt[8]; int salt_set; int iterations; /* If applying the S2K function to the passphrase is the session key or if it is the decryption key for the session key. */ int s2k_is_session_key; /* Generate a new, random session key. */ int new_session_key; /* The unencrypted session key. */ int session_key_len; char *session_key; char *password; }; static int sk_esk_cipher (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "integer|IDEA|3DES|CAST5|BLOWFISH|AES|AES192|AES256|CAMELLIA128|CAMELLIA192|CAMELLIA256"; int cipher; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (strcasecmp (argv[0], "IDEA") == 0) cipher = CIPHER_ALGO_IDEA; else if (strcasecmp (argv[0], "3DES") == 0) cipher = CIPHER_ALGO_3DES; else if (strcasecmp (argv[0], "CAST5") == 0) cipher = CIPHER_ALGO_CAST5; else if (strcasecmp (argv[0], "BLOWFISH") == 0) cipher = CIPHER_ALGO_BLOWFISH; else if (strcasecmp (argv[0], "AES") == 0) cipher = CIPHER_ALGO_AES; else if (strcasecmp (argv[0], "AES192") == 0) cipher = CIPHER_ALGO_AES192; else if (strcasecmp (argv[0], "TWOFISH") == 0) cipher = CIPHER_ALGO_TWOFISH; else if (strcasecmp (argv[0], "CAMELLIA128") == 0) cipher = CIPHER_ALGO_CAMELLIA128; else if (strcasecmp (argv[0], "CAMELLIA192") == 0) cipher = CIPHER_ALGO_CAMELLIA192; else if (strcasecmp (argv[0], "CAMELLIA256") == 0) cipher = CIPHER_ALGO_CAMELLIA256; else { char *tail; int v; errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || ! valid_cipher (v)) log_fatal ("Invalid or unsupported value. Usage: %s %s\n", option, usage); cipher = v; } if (strcmp (option, "--cipher") == 0) { if (si->cipher) log_fatal ("%s given multiple times.", option); si->cipher = cipher; } else if (strcmp (option, "--sed-cipher") == 0) { if (si->sed_cipher) log_fatal ("%s given multiple times.", option); si->sed_cipher = cipher; } return 1; } static int sk_esk_mode (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "integer|simple|salted|iterated"; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (si->mode) log_fatal ("%s given multiple times.", option); if (strcasecmp (argv[0], "simple") == 0) si->mode = 0; else if (strcasecmp (argv[0], "salted") == 0) si->mode = 1; else if (strcasecmp (argv[0], "iterated") == 0) si->mode = 3; else { char *tail; int v; errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || ! (v == 0 || v == 1 || v == 3)) log_fatal ("Invalid or unsupported value. Usage: %s %s\n", option, usage); si->mode = v; } si->mode_set = 1; return 1; } static int sk_esk_hash_algorithm (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "integer|MD5|SHA1|RMD160|SHA256|SHA384|SHA512|SHA224"; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (si->hash) log_fatal ("%s given multiple times.", option); if (strcasecmp (argv[0], "MD5") == 0) si->hash = DIGEST_ALGO_MD5; else if (strcasecmp (argv[0], "SHA1") == 0) si->hash = DIGEST_ALGO_SHA1; else if (strcasecmp (argv[0], "RMD160") == 0) si->hash = DIGEST_ALGO_RMD160; else if (strcasecmp (argv[0], "SHA256") == 0) si->hash = DIGEST_ALGO_SHA256; else if (strcasecmp (argv[0], "SHA384") == 0) si->hash = DIGEST_ALGO_SHA384; else if (strcasecmp (argv[0], "SHA512") == 0) si->hash = DIGEST_ALGO_SHA512; else if (strcasecmp (argv[0], "SHA224") == 0) si->hash = DIGEST_ALGO_SHA224; else { char *tail; int v; errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || ! (v == DIGEST_ALGO_MD5 || v == DIGEST_ALGO_SHA1 || v == DIGEST_ALGO_RMD160 || v == DIGEST_ALGO_SHA256 || v == DIGEST_ALGO_SHA384 || v == DIGEST_ALGO_SHA512 || v == DIGEST_ALGO_SHA224)) log_fatal ("Invalid or unsupported value. Usage: %s %s\n", option, usage); si->hash = v; } return 1; } static int sk_esk_salt (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "16-HEX-CHARACTERS"; char *p = argv[0]; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (si->salt_set) log_fatal ("%s given multiple times.", option); if (p[0] == '0' && p[1] == 'x') p += 2; if (strlen (p) != 16) log_fatal ("%s: Salt must be exactly 16 hexadecimal characters (have: %zd)\n", option, strlen (p)); if (hex2bin (p, si->salt, sizeof (si->salt)) == -1) log_fatal ("%s: Salt must only contain hexadecimal characters\n", option); si->salt_set = 1; return 1; } static int sk_esk_iterations (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "ITERATION-COUNT"; char *tail; int v; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || v < 0) log_fatal ("%s: Non-negative integer expected.\n", option); si->iterations = v; return 1; } static int sk_esk_session_key (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "HEX-CHARACTERS|auto|none"; char *p = argv[0]; struct session_key sk; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (si->session_key || si->s2k_is_session_key || si->new_session_key) log_fatal ("%s given multiple times.", option); if (strcasecmp (p, "none") == 0) { si->s2k_is_session_key = 1; return 1; } if (strcasecmp (p, "new") == 0) { si->new_session_key = 1; return 1; } if (strcasecmp (p, "auto") == 0) return 1; sk = parse_session_key (option, p, 0); if (si->session_key) log_fatal ("%s given multiple times.", option); if (sk.algo) si->sed_cipher = sk.algo; si->session_key_len = sk.keylen; si->session_key = sk.key; return 1; } static int sk_esk_password (const char *option, int argc, char *argv[], void *cookie) { struct sk_esk_info *si = cookie; char *usage = "PASSWORD"; if (argc == 0) log_fatal ("Usage: --sk-esk %s\n", usage); if (si->password) log_fatal ("%s given multiple times.", option); si->password = xstrdup (argv[0]); return 1; } static struct option sk_esk_options[] = { { "--cipher", sk_esk_cipher, "The encryption algorithm for encrypting the session key. " "One of IDEA, 3DES, CAST5, BLOWFISH, AES (default), AES192, " "AES256, TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." }, { "--sed-cipher", sk_esk_cipher, "The encryption algorithm for encrypting the SED packet. " "One of IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, " "AES256 (default), TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." }, { "--mode", sk_esk_mode, "The S2K mode. Either one of the strings \"simple\", \"salted\" " "or \"iterated\" or an integer." }, { "--hash", sk_esk_hash_algorithm, "The hash algorithm to used to derive the key. One of " "MD5, SHA1 (default), RMD160, SHA256, SHA384, SHA512, or SHA224." }, { "--salt", sk_esk_salt, "The S2K salt encoded as 16 hexadecimal characters. One needed " "if the S2K function is in salted or iterated mode." }, { "--iterations", sk_esk_iterations, "The iteration count. If not provided, a reasonable value is chosen. " "Note: due to the encoding scheme, not every value is valid. For " "convenience, the provided value will be rounded appropriately. " "Only needed if the S2K function is in iterated mode." }, { "--session-key", sk_esk_session_key, "The session key to be encrypted by the S2K function as a hexadecimal " "string. If this is \"new\", then a new session key is generated." "If this is \"auto\", then either the last session key is " "used, if the was none, one is generated. If this is \"none\", then " "the session key is the result of applying the S2K algorithms to the " "password. The session key may be prefaced with an integer and a colon " "to indicate the cipher to use for the SED packet (making --sed-cipher " "unnecessary and allowing the direct use of the result of " "\"" GPG_NAME " --show-session-key\")." }, { "", sk_esk_password, "The password." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --sk-esk foobar --encrypted \\\n" " --literal --value foo | " GPG_NAME " --list-packets" } }; static int sk_esk (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; gpg_error_t err; int processed; struct sk_esk_info si; DEK sesdek; DEK s2kdek; PKT_symkey_enc *ske; PACKET pkt; memset (&si, 0, sizeof (si)); processed = process_options (option, major_options, sk_esk_options, &si, global_options, NULL, argc, argv); if (! si.password) log_fatal ("%s: missing password. Usage: %s PASSWORD", option, option); /* Fill in defaults, if appropriate. */ if (! si.cipher) si.cipher = CIPHER_ALGO_AES; if (! si.sed_cipher) si.sed_cipher = CIPHER_ALGO_AES256; if (! si.hash) si.hash = DIGEST_ALGO_SHA1; if (! si.mode_set) /* Salted and iterated. */ si.mode = 3; if (si.mode != 0 && ! si.salt_set) /* Generate a salt. */ gcry_randomize (si.salt, 8, GCRY_STRONG_RANDOM); if (si.mode == 0) { if (si.iterations) log_info ("%s: --iterations provided, but not used for mode=0\n", option); si.iterations = 0; } else if (! si.iterations) si.iterations = 10000; memset (&sesdek, 0, sizeof (sesdek)); /* The session key is used to encrypt the SED packet. */ sesdek.algo = si.sed_cipher; if (si.session_key) /* Copy the unencrypted session key into SESDEK. */ { sesdek.keylen = openpgp_cipher_get_algo_keylen (sesdek.algo); if (sesdek.keylen != si.session_key_len) log_fatal ("%s: Cipher algorithm requires a %d byte session key, but provided session key is %d bytes.", option, sesdek.keylen, si.session_key_len); log_assert (sesdek.keylen <= sizeof (sesdek.key)); memcpy (sesdek.key, si.session_key, sesdek.keylen); } else if (! si.s2k_is_session_key || si.new_session_key) /* We need a session key, but one wasn't provided. Generate it. */ make_session_key (&sesdek); /* The encrypted session key needs 1 + SESDEK.KEYLEN bytes of space. */ ske = xmalloc_clear (sizeof (*ske) + sesdek.keylen); ske->version = 4; ske->cipher_algo = si.cipher; ske->s2k.mode = si.mode; ske->s2k.hash_algo = si.hash; log_assert (sizeof (si.salt) == sizeof (ske->s2k.salt)); memcpy (ske->s2k.salt, si.salt, sizeof (ske->s2k.salt)); if (! si.s2k_is_session_key) { if (!si.iterations) ske->s2k.count = encode_s2k_iterations (agent_get_s2k_count ()); else ske->s2k.count = encode_s2k_iterations (si.iterations); } /* Derive the symmetric key that is either the session key or the key used to encrypt the session key. */ memset (&s2kdek, 0, sizeof (s2kdek)); s2kdek.algo = si.cipher; s2kdek.keylen = openpgp_cipher_get_algo_keylen (s2kdek.algo); err = gcry_kdf_derive (si.password, strlen (si.password), ske->s2k.mode == 3 ? GCRY_KDF_ITERSALTED_S2K : ske->s2k.mode == 1 ? GCRY_KDF_SALTED_S2K : GCRY_KDF_SIMPLE_S2K, ske->s2k.hash_algo, ske->s2k.salt, 8, S2K_DECODE_COUNT (ske->s2k.count), /* The size of the desired key and its buffer. */ s2kdek.keylen, s2kdek.key); if (err) log_fatal ("gcry_kdf_derive failed: %s", gpg_strerror (err)); if (si.s2k_is_session_key) { ske->seskeylen = 0; session_key = s2kdek; } else /* Encrypt the session key using the s2k specifier. */ { DEK *sesdekp = &sesdek; void *enckey; size_t enckeylen; /* Now encrypt the session key (or rather, the algorithm used to encrypt the SKESK plus the session key) using S2KDEK. */ err = encrypt_seskey (&s2kdek, 0, &sesdekp, &enckey, &enckeylen); if (err) log_fatal ("encrypt_seskey failed: %s\n", gpg_strerror (err)); if (enckeylen - 1 > sesdek.keylen) log_fatal ("key size is too big: %zu\n", enckeylen); else { ske->seskeylen = (byte)enckeylen; memcpy (ske->seskey, enckey, enckeylen); } /* Save the session key for later. */ session_key = sesdek; xfree (enckey); } pkt.pkttype = PKT_SYMKEY_ENC; pkt.pkt.symkey_enc = ske; err = build_packet (out, &pkt); if (err) log_fatal ("Serializing sym-key encrypted packet: %s\n", gpg_strerror (err)); debug ("Wrote sym-key encrypted packet:\n"); dump_component (&pkt); xfree (si.session_key); xfree (si.password); xfree (ske); return processed; } struct pk_esk_info { int session_key_set; int new_session_key; int sed_cipher; int session_key_len; char *session_key; int throw_keyid; char *keyid; }; static int pk_esk_session_key (const char *option, int argc, char *argv[], void *cookie) { struct pk_esk_info *pi = cookie; char *usage = "HEX-CHARACTERS|auto|none"; char *p = argv[0]; struct session_key sk; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (pi->session_key_set) log_fatal ("%s given multiple times.", option); pi->session_key_set = 1; if (strcasecmp (p, "new") == 0) { pi->new_session_key = 1; return 1; } if (strcasecmp (p, "auto") == 0) return 1; sk = parse_session_key (option, p, 0); if (pi->session_key) log_fatal ("%s given multiple times.", option); if (sk.algo) pi->sed_cipher = sk.algo; pi->session_key_len = sk.keylen; pi->session_key = sk.key; return 1; } static int pk_esk_throw_keyid (const char *option, int argc, char *argv[], void *cookie) { struct pk_esk_info *pi = cookie; (void) option; (void) argc; (void) argv; pi->throw_keyid = 1; return 0; } static int pk_esk_keyid (const char *option, int argc, char *argv[], void *cookie) { struct pk_esk_info *pi = cookie; char *usage = "KEYID"; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (pi->keyid) log_fatal ("Multiple key ids given, but only one is allowed."); pi->keyid = xstrdup (argv[0]); return 1; } static struct option pk_esk_options[] = { { "--session-key", pk_esk_session_key, "The session key to be encrypted by the S2K function as a hexadecimal " "string. If this is not given or is \"auto\", then the current " "session key is used. If there is no session key or this is \"new\", " "then a new session key is generated. The session key may be " "prefaced with an integer and a colon to indicate the cipher to use " "for the SED packet (making --sed-cipher unnecessary and allowing the " "direct use of the result of \"" GPG_NAME " --show-session-key\")." }, { "--throw-keyid", pk_esk_throw_keyid, "Throw the keyid." }, { "", pk_esk_keyid, "The key id." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --pk-esk $KEYID --encrypted --literal --value foo \\\n" " | " GPG_NAME " --list-packets"} }; static int pk_esk (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; gpg_error_t err; int processed; struct pk_esk_info pi; PKT_public_key pk; memset (&pi, 0, sizeof (pi)); processed = process_options (option, major_options, pk_esk_options, &pi, global_options, NULL, argc, argv); if (! pi.keyid) log_fatal ("%s: missing keyid. Usage: %s KEYID", option, option); memset (&pk, 0, sizeof (pk)); pk.req_usage = PUBKEY_USAGE_ENC; err = get_pubkey_byname (NULL, GET_PUBKEY_NO_AKL, NULL, &pk, pi.keyid, NULL, NULL, 1); if (err) log_fatal ("%s: looking up key %s: %s\n", option, pi.keyid, gpg_strerror (err)); if (pi.sed_cipher) /* Have a session key. */ { session_key.algo = pi.sed_cipher; session_key.keylen = pi.session_key_len; log_assert (session_key.keylen <= sizeof (session_key.key)); memcpy (session_key.key, pi.session_key, session_key.keylen); } if (pi.new_session_key || ! session_key.algo) { if (! pi.new_session_key) /* Default to AES256. */ session_key.algo = CIPHER_ALGO_AES256; make_session_key (&session_key); } err = write_pubkey_enc (global_ctrl, &pk, pi.throw_keyid, &session_key, out); if (err) log_fatal ("%s: writing pk_esk packet for %s: %s\n", option, pi.keyid, gpg_strerror (err)); debug ("Wrote pk_esk packet for %s\n", pi.keyid); xfree (pi.keyid); xfree (pi.session_key); return processed; } struct encinfo { int saw_session_key; }; static int encrypted_session_key (const char *option, int argc, char *argv[], void *cookie) { struct encinfo *ei = cookie; char *usage = "HEX-CHARACTERS|auto"; char *p = argv[0]; struct session_key sk; if (argc == 0) log_fatal ("Usage: %s %s\n", option, usage); if (ei->saw_session_key) log_fatal ("%s given multiple times.", option); ei->saw_session_key = 1; if (strcasecmp (p, "auto") == 0) return 1; sk = parse_session_key (option, p, 1); session_key.algo = sk.algo; log_assert (sk.keylen <= sizeof (session_key.key)); memcpy (session_key.key, sk.key, sk.keylen); xfree (sk.key); return 1; } static struct option encrypted_options[] = { { "--session-key", encrypted_session_key, "The session key to be encrypted by the S2K function as a hexadecimal " "string. If this is not given or is \"auto\", then the last session key " "is used. If there was none, then an error is raised. The session key " "must be prefaced with an integer and a colon to indicate the cipher " "to use (this is format used by \"" GPG_NAME " --show-session-key\")." }, { NULL, NULL, "After creating the packet, this command clears the current " "session key.\n\n" "Example: nested encryption packets:\n\n" " $ gpgcompose --sk-esk foo --encrypted-mdc \\\n" " --sk-esk bar --encrypted-mdc \\\n" " --literal --value 123 --encrypted-pop --encrypted-pop | " GPG_NAME" -d" } }; static int encrypted (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; int processed; struct encinfo ei; PKT_encrypted e; cipher_filter_context_t *cfx; memset (&ei, 0, sizeof (ei)); processed = process_options (option, major_options, encrypted_options, &ei, global_options, NULL, argc, argv); if (! session_key.algo) log_fatal ("%s: no session key configured\n" " (use e.g. --sk-esk PASSWORD or --pk-esk KEYID).\n", option); memset (&e, 0, sizeof (e)); /* We only need to set E->LEN, E->EXTRALEN (if E->LEN is not 0), and E->NEW_CTB. */ e.len = 0; e.new_ctb = 1; /* Register the cipher filter. */ cfx = xmalloc_clear (sizeof (*cfx)); /* Copy the session key. */ cfx->dek = xmalloc (sizeof (*cfx->dek)); *cfx->dek = session_key; if (do_debug) { char *buf; buf = xmalloc (2 * session_key.keylen + 1); debug ("session key: algo: %d; keylen: %d; key: %s\n", session_key.algo, session_key.keylen, bin2hex (session_key.key, session_key.keylen, buf)); xfree (buf); } if (strcmp (option, "--encrypted-mdc") == 0) cfx->dek->use_mdc = 1; else if (strcmp (option, "--encrypted") == 0) cfx->dek->use_mdc = 0; else log_fatal ("%s: option not handled by this function!\n", option); cfx->datalen = 0; filter_push (out, cipher_filter_cfb, cfx, PKT_ENCRYPTED, cfx->datalen == 0); debug ("Wrote encrypted packet:\n"); /* Clear the current session key. */ memset (&session_key, 0, sizeof (session_key)); return processed; } static struct option encrypted_pop_options[] = { { NULL, NULL, "Example:\n\n" " $ gpgcompose --sk-esk PASSWORD \\\n" " --encrypted-mdc \\\n" " --literal --value foo \\\n" " --encrypted-pop | " GPG_NAME " --list-packets" } }; static int encrypted_pop (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; int processed; processed = process_options (option, major_options, encrypted_pop_options, NULL, global_options, NULL, argc, argv); /* We only support a single option, --help, which causes the program * to exit. */ log_assert (processed == 0); filter_pop (out, PKT_ENCRYPTED); debug ("Popped encryption container.\n"); return processed; } struct data { int file; union { char *data; char *filename; }; struct data *next; }; /* This must be the first member of the struct to be able to use add_value! */ struct datahead { struct data *head; struct data **last_next; }; static int add_value (const char *option, int argc, char *argv[], void *cookie) { struct datahead *dh = cookie; struct data *d = xmalloc_clear (sizeof (struct data)); d->file = strcmp ("--file", option) == 0; if (! d->file) log_assert (strcmp ("--value", option) == 0); if (argc == 0) { if (d->file) log_fatal ("Usage: %s FILENAME\n", option); else log_fatal ("Usage: %s STRING\n", option); } if (! dh->last_next) /* First time through. Initialize DH->LAST_NEXT. */ { log_assert (! dh->head); dh->last_next = &dh->head; } if (d->file) d->filename = argv[0]; else d->data = argv[0]; /* Append it. */ *dh->last_next = d; dh->last_next = &d->next; return 1; } struct litinfo { /* This must be the first element for add_value to work! */ struct datahead data; int timestamp_set; u32 timestamp; char mode; int partial_body_length_encoding; char *name; }; static int literal_timestamp (const char *option, int argc, char *argv[], void *cookie) { struct litinfo *li = cookie; char *tail = NULL; if (argc == 0) log_fatal ("Usage: %s TIMESTAMP\n", option); errno = 0; li->timestamp = parse_timestamp (argv[0], &tail); if (errno || (tail && *tail)) log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]); li->timestamp_set = 1; return 1; } static int literal_mode (const char *option, int argc, char *argv[], void *cookie) { struct litinfo *li = cookie; if (argc == 0 || ! (strcmp (argv[0], "b") == 0 || strcmp (argv[0], "t") == 0 || strcmp (argv[0], "u") == 0)) log_fatal ("Usage: %s [btu]\n", option); li->mode = argv[0][0]; return 1; } static int literal_partial_body_length (const char *option, int argc, char *argv[], void *cookie) { struct litinfo *li = cookie; char *tail; int v; int range[2] = {0, 1}; if (argc <= 1) log_fatal ("Usage: %s [0|1]\n", option); errno = 0; v = strtol (argv[0], &tail, 0); if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1])) log_fatal ("Invalid value passed to %s (%s). Expected %d-%d\n", option, argv[0], range[0], range[1]); li->partial_body_length_encoding = v; return 1; } static int literal_name (const char *option, int argc, char *argv[], void *cookie) { struct litinfo *li = cookie; if (argc <= 0) log_fatal ("Usage: %s NAME\n", option); if (strlen (argv[0]) > 255) log_fatal ("%s: name is too long (%zd > 255 characters).\n", option, strlen (argv[0])); li->name = argv[0]; return 1; } static struct option literal_options[] = { { "--value", add_value, "A string to store in the literal packet." }, { "--file", add_value, "A file to copy into the literal packet." }, { "--timestamp", literal_timestamp, "The literal packet's time stamp. This defaults to the current time." }, { "--mode", literal_mode, "The content's mode (normally 'b' (default), 't' or 'u')." }, { "--partial-body-length", literal_partial_body_length, "Force partial body length encoding." }, { "--name", literal_name, "The literal's name." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --literal --value foobar | " GPG_NAME " -d"} }; static int literal (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; gpg_error_t err; int processed; struct litinfo li; PKT_plaintext *pt; PACKET pkt; struct data *data; memset (&li, 0, sizeof (li)); processed = process_options (option, major_options, literal_options, &li, global_options, NULL, argc, argv); if (! li.data.head) log_fatal ("%s: no data provided (use --value or --file)", option); pt = xmalloc_clear (sizeof (*pt) + (li.name ? strlen (li.name) : 0)); pt->new_ctb = 1; if (li.timestamp_set) pt->timestamp = li.timestamp; else /* Default to the current time. */ pt->timestamp = make_timestamp (); pt->mode = li.mode; if (! pt->mode) /* Default to binary. */ pt->mode = 'b'; if (li.name) { strcpy (pt->name, li.name); pt->namelen = strlen (pt->name); } pkt.pkttype = PKT_PLAINTEXT; pkt.pkt.plaintext = pt; if (! li.partial_body_length_encoding) /* Compute the amount of data. */ { pt->len = 0; for (data = li.data.head; data; data = data->next) { if (data->file) { iobuf_t in; int overflow; off_t off; in = iobuf_open (data->filename); if (! in) /* An error opening the file. We do error handling below so just break here. */ { pt->len = 0; break; } off = iobuf_get_filelength (in, &overflow); iobuf_close (in); if (overflow || off == 0) /* Length is unknown or there was an error (unfortunately, iobuf_get_filelength doesn't distinguish between 0 length files and an error!). Fall back to partial body mode. */ { pt->len = 0; break; } pt->len += off; } else pt->len += strlen (data->data); } } err = build_packet (out, &pkt); if (err) log_fatal ("Serializing literal packet: %s\n", gpg_strerror (err)); /* Write out the data. */ for (data = li.data.head; data; data = data->next) { if (data->file) { iobuf_t in; errno = 0; in = iobuf_open (data->filename); if (! in) log_fatal ("Opening '%s': %s\n", data->filename, errno ? strerror (errno): "unknown error"); iobuf_copy (out, in); if (iobuf_error (in)) log_fatal ("Reading from %s: %s\n", data->filename, gpg_strerror (iobuf_error (in))); if (iobuf_error (out)) log_fatal ("Writing literal data from %s: %s\n", data->filename, gpg_strerror (iobuf_error (out))); iobuf_close (in); } else { err = iobuf_write (out, data->data, strlen (data->data)); if (err) log_fatal ("Writing literal data: %s\n", gpg_strerror (err)); } } if (! pt->len) { /* Disable partial body length mode. */ log_assert (pt->new_ctb == 1); iobuf_set_partial_body_length_mode (out, 0); } debug ("Wrote literal packet:\n"); dump_component (&pkt); while (li.data.head) { data = li.data.head->next; xfree (li.data.head); li.data.head = data; } xfree (pt); return processed; } static int copy_file (const char *option, int argc, char *argv[], void *cookie) { char **filep = cookie; if (argc == 0) log_fatal ("Usage: %s FILENAME\n", option); *filep = argv[0]; return 1; } static struct option copy_options[] = { { "", copy_file, "Copy the specified file to stdout." }, { NULL, NULL, "Example:\n\n" " $ gpgcompose --copy /etc/hostname\n\n" "This is particularly useful when combined with gpgsplit." } }; static int copy (const char *option, int argc, char *argv[], void *cookie) { iobuf_t out = cookie; char *file = NULL; iobuf_t in; int processed; processed = process_options (option, major_options, copy_options, &file, global_options, NULL, argc, argv); if (! file) log_fatal ("Usage: %s FILE\n", option); errno = 0; in = iobuf_open (file); if (! in) log_fatal ("Error opening %s: %s.\n", file, errno ? strerror (errno): "unknown error"); iobuf_copy (out, in); if (iobuf_error (out)) log_fatal ("Copying data to destination: %s\n", gpg_strerror (iobuf_error (out))); if (iobuf_error (in)) log_fatal ("Reading data from %s: %s\n", argv[0], gpg_strerror (iobuf_error (in))); iobuf_close (in); return processed; } int main (int argc, char *argv[]) { const char *filename = "-"; iobuf_t out; int preprocessed = 1; int processed; ctrl_t ctrl; opt.ignore_time_conflict = 1; /* Allow notations in the IETF space, for instance. */ opt.expert = 1; global_ctrl = ctrl = xcalloc (1, sizeof *ctrl); keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG, KEYDB_RESOURCE_FLAG_DEFAULT); if (argc == 1) /* Nothing to do. */ return 0; if (strcmp (argv[1], "--output") == 0 || strcmp (argv[1], "-o") == 0) { filename = argv[2]; log_info ("Writing to %s\n", filename); preprocessed += 2; } out = iobuf_create (filename, 0); if (! out) log_fatal ("Failed to open stdout for writing\n"); processed = process_options (NULL, NULL, major_options, out, global_options, NULL, argc - preprocessed, &argv[preprocessed]); if (processed != argc - preprocessed) log_fatal ("Didn't process %d options.\n", argc - preprocessed - processed); iobuf_close (out); return 0; } /* Stubs duplicated from gpg.c. */ int g10_errors_seen = 0; /* Note: This function is used by signal handlers!. */ static void emergency_cleanup (void) { gcry_control (GCRYCTL_TERM_SECMEM ); } void g10_exit( int rc ) { gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE); emergency_cleanup (); rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit (rc); } void keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr, strlist_t commands, int quiet, int seckey_check) { (void) ctrl; (void) username; (void) locusr; (void) commands; (void) quiet; (void) seckey_check; } void show_basic_key_info (ctrl_t ctrl, KBNODE keyblock, int made_from_sec) { (void)ctrl; (void)keyblock; (void)made_from_sec; } int keyedit_print_one_sig (ctrl_t ctrl, estream_t fp, int rc, kbnode_t keyblock, kbnode_t node, int *inv_sigs, int *no_key, int *oth_err, int is_selfsig, int print_without_key, int extended) { (void) ctrl; (void) fp; (void) rc; (void) keyblock; (void) node; (void) inv_sigs; (void) no_key; (void) oth_err; (void) is_selfsig; (void) print_without_key; (void) extended; return 0; } diff --git a/g10/main.h b/g10/main.h index ec58795b0..704eb339f 100644 --- a/g10/main.h +++ b/g10/main.h @@ -1,519 +1,519 @@ /* main.h * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef G10_MAIN_H #define G10_MAIN_H #include "../common/types.h" #include "../common/iobuf.h" +#include "../common/util.h" #include "keydb.h" #include "keyedit.h" -#include "../common/util.h" /* It could be argued that the default cipher should be 3DES rather than AES128, and the default compression should be 0 (i.e. uncompressed) rather than 1 (zip). However, the real world issues of speed and size come into play here. */ #if GPG_USE_AES256 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_AES256 #elif GPG_USE_AES128 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_AES #elif GPG_USE_CAST5 # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_CAST5 #else # define DEFAULT_CIPHER_ALGO CIPHER_ALGO_3DES #endif /* We will start using OCB mode by default only if the yet to be * released libgcrypt 1.9 is used. */ #if GCRYPT_VERSION_NUMBER < 0x010900 # define DEFAULT_AEAD_ALGO AEAD_ALGO_OCB #else # define DEFAULT_AEAD_ALGO AEAD_ALGO_EAX #endif #define DEFAULT_DIGEST_ALGO ((GNUPG)? DIGEST_ALGO_SHA256:DIGEST_ALGO_SHA1) #define DEFAULT_S2K_DIGEST_ALGO DIGEST_ALGO_SHA1 #ifdef HAVE_ZIP # define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_ZIP #else # define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_NONE #endif #define S2K_DIGEST_ALGO (opt.s2k_digest_algo?opt.s2k_digest_algo:DEFAULT_S2K_DIGEST_ALGO) /* Various data objects. */ typedef struct { ctrl_t ctrl; int header_okay; PK_LIST pk_list; DEK *symkey_dek; STRING2KEY *symkey_s2k; cipher_filter_context_t cfx; } encrypt_filter_context_t; struct groupitem { char *name; strlist_t values; struct groupitem *next; }; struct weakhash { enum gcry_md_algos algo; int rejection_shown; struct weakhash *next; }; /*-- gpg.c --*/ extern int g10_errors_seen; #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) void g10_exit(int rc) __attribute__ ((noreturn)); #else void g10_exit(int rc); #endif void print_pubkey_algo_note (pubkey_algo_t algo); void print_cipher_algo_note (cipher_algo_t algo); void print_digest_algo_note (digest_algo_t algo); void print_digest_rejected_note (enum gcry_md_algos algo); void print_sha1_keysig_rejected_note (void); void print_reported_error (gpg_error_t err, gpg_err_code_t skip_if_ec); void print_further_info (const char *format, ...) GPGRT_ATTR_PRINTF(1,2); void additional_weak_digest (const char* digestname); /*-- armor.c --*/ char *make_radix64_string( const byte *data, size_t len ); /*-- misc.c --*/ void trap_unaligned(void); void register_secured_file (const char *fname); void unregister_secured_file (const char *fname); int is_secured_file (int fd); int is_secured_filename (const char *fname); u16 checksum_u16( unsigned n ); u16 checksum( byte *p, unsigned n ); u16 checksum_mpi( gcry_mpi_t a ); u32 buffer_to_u32( const byte *buffer ); const byte *get_session_marker( size_t *rlen ); enum gcry_cipher_algos map_cipher_openpgp_to_gcry (cipher_algo_t algo); #define openpgp_cipher_open(_a,_b,_c,_d) \ gcry_cipher_open((_a),map_cipher_openpgp_to_gcry((_b)),(_c),(_d)) #define openpgp_cipher_get_algo_keylen(_a) \ gcry_cipher_get_algo_keylen(map_cipher_openpgp_to_gcry((_a))) #define openpgp_cipher_get_algo_blklen(_a) \ gcry_cipher_get_algo_blklen(map_cipher_openpgp_to_gcry((_a))) int openpgp_cipher_blocklen (cipher_algo_t algo); int openpgp_cipher_test_algo(cipher_algo_t algo); const char *openpgp_cipher_algo_name (cipher_algo_t algo); gpg_error_t openpgp_aead_test_algo (aead_algo_t algo); const char *openpgp_aead_algo_name (aead_algo_t algo); gpg_error_t openpgp_aead_algo_info (aead_algo_t algo, enum gcry_cipher_modes *r_mode, unsigned int *r_noncelen); int openpgp_pk_test_algo (pubkey_algo_t algo); int openpgp_pk_test_algo2 (pubkey_algo_t algo, unsigned int use); int openpgp_pk_algo_usage ( int algo ); const char *openpgp_pk_algo_name (pubkey_algo_t algo); enum gcry_md_algos map_md_openpgp_to_gcry (digest_algo_t algo); int openpgp_md_test_algo (digest_algo_t algo); const char *openpgp_md_algo_name (int algo); struct expando_args { PKT_public_key *pk; PKT_public_key *pksk; byte imagetype; int validity_info; const char *validity_string; const byte *namehash; }; char *pct_expando (ctrl_t ctrl, const char *string,struct expando_args *args); void deprecated_warning(const char *configname,unsigned int configlineno, const char *option,const char *repl1,const char *repl2); void deprecated_command (const char *name); void obsolete_scdaemon_option (const char *configname, unsigned int configlineno, const char *name); int string_to_cipher_algo (const char *string); aead_algo_t string_to_aead_algo (const char *string); int string_to_digest_algo (const char *string); const char *compress_algo_to_string(int algo); int string_to_compress_algo(const char *string); int check_compress_algo(int algo); int default_cipher_algo(void); aead_algo_t default_aead_algo(void); int default_compress_algo(void); void compliance_failure(void); struct parse_options { char *name; unsigned int bit; char **value; char *help; }; char *optsep(char **stringp); char *argsplit(char *string); int parse_options(char *str,unsigned int *options, struct parse_options *opts,int noisy); const char *get_libexecdir (void); int path_access(const char *file,int mode); int pubkey_get_npkey (pubkey_algo_t algo); int pubkey_get_nskey (pubkey_algo_t algo); int pubkey_get_nsig (pubkey_algo_t algo); int pubkey_get_nenc (pubkey_algo_t algo); /* Temporary helpers. */ unsigned int pubkey_nbits( int algo, gcry_mpi_t *pkey ); int mpi_print (estream_t stream, gcry_mpi_t a, int mode); unsigned int ecdsa_qbits_from_Q (unsigned int qbits); /*-- cpr.c --*/ void set_status_fd ( int fd ); int is_status_enabled ( void ); void write_status ( int no ); void write_status_error (const char *where, gpg_error_t err); void write_status_errcode (const char *where, int errcode); void write_status_failure (const char *where, gpg_error_t err); void write_status_text ( int no, const char *text ); void write_status_printf (int no, const char *format, ...) GPGRT_ATTR_PRINTF(2,3); void write_status_strings (int no, const char *text, ...) GPGRT_ATTR_SENTINEL(0); void write_status_buffer ( int no, const char *buffer, size_t len, int wrap ); void write_status_text_and_buffer ( int no, const char *text, const char *buffer, size_t len, int wrap ); void write_status_begin_signing (gcry_md_hd_t md); int cpr_enabled(void); char *cpr_get( const char *keyword, const char *prompt ); char *cpr_get_no_help( const char *keyword, const char *prompt ); char *cpr_get_utf8( const char *keyword, const char *prompt ); char *cpr_get_hidden( const char *keyword, const char *prompt ); void cpr_kill_prompt(void); int cpr_get_answer_is_yes_def (const char *keyword, const char *prompt, int def_yes); int cpr_get_answer_is_yes( const char *keyword, const char *prompt ); int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt ); int cpr_get_answer_okay_cancel (const char *keyword, const char *prompt, int def_answer); /*-- helptext.c --*/ void display_online_help( const char *keyword ); /*-- encode.c --*/ int setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek); gpg_error_t encrypt_seskey (DEK *dek, aead_algo_t aead_algo, DEK **r_seskey, void **r_enckey, size_t *r_enckeylen); aead_algo_t use_aead (pk_list_t pk_list, int algo); int use_mdc (pk_list_t pk_list,int algo); int encrypt_symmetric (const char *filename ); int encrypt_store (const char *filename ); int encrypt_crypt (ctrl_t ctrl, int filefd, const char *filename, strlist_t remusr, int use_symkey, pk_list_t provided_keys, int outputfd); void encrypt_crypt_files (ctrl_t ctrl, int nfiles, char **files, strlist_t remusr); int encrypt_filter (void *opaque, int control, iobuf_t a, byte *buf, size_t *ret_len); int write_pubkey_enc (ctrl_t ctrl, PKT_public_key *pk, int throw_keyid, DEK *dek, iobuf_t out); /*-- sign.c --*/ int sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr, int do_encrypt, strlist_t remusr, const char *outfile ); int clearsign_file (ctrl_t ctrl, const char *fname, strlist_t locusr, const char *outfile); int sign_symencrypt_file (ctrl_t ctrl, const char *fname, strlist_t locusr); /*-- sig-check.c --*/ void sig_check_dump_stats (void); /* SIG is a revocation signature. Check if any of PK's designated revokers generated it. If so, return 0. Note: this function (correctly) doesn't care if the designated revoker is revoked. */ int check_revocation_keys (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig); /* Check that the backsig BACKSIG from the subkey SUB_PK to its primary key MAIN_PK is valid. */ int check_backsig(PKT_public_key *main_pk,PKT_public_key *sub_pk, PKT_signature *backsig); /* Check that the signature SIG over a key (e.g., a key binding or a key revocation) is valid. (To check signatures over data, use check_signature.) */ int check_key_signature (ctrl_t ctrl, kbnode_t root, kbnode_t sig, int *is_selfsig ); /* Like check_key_signature, but with the ability to specify some additional parameters and get back additional information. See the documentation for the implementation for details. */ int check_key_signature2 (ctrl_t ctrl, kbnode_t root, kbnode_t node, PKT_public_key *check_pk, PKT_public_key *ret_pk, int *is_selfsig, u32 *r_expiredate, int *r_expired); /* Returns whether SIGNER generated the signature SIG over the packet PACKET, which is a key, subkey or uid, and comes from the key block KB. If SIGNER is NULL, it is looked up based on the information in SIG. If not NULL, sets *IS_SELFSIG to indicate whether the signature is a self-signature and *RET_PK to a copy of the signer's key. */ gpg_error_t check_signature_over_key_or_uid (ctrl_t ctrl, PKT_public_key *signer, PKT_signature *sig, KBNODE kb, PACKET *packet, int *is_selfsig, PKT_public_key *ret_pk); /*-- delkey.c --*/ gpg_error_t delete_keys (ctrl_t ctrl, strlist_t names, int secret, int allow_both); /*-- keygen.c --*/ const char *get_default_pubkey_algo (void); u32 parse_expire_string(const char *string); u32 ask_expire_interval(int object,const char *def_expire); u32 ask_expiredate(void); unsigned int ask_key_flags (int algo, int subkey, unsigned int current); const char *ask_curve (int *algo, int *subkey_algo, const char *current); void quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr, const char *usagestr, const char *expirestr); void generate_keypair (ctrl_t ctrl, int full, const char *fname, const char *card_serialno, int card_backup_key); int keygen_set_std_prefs (const char *string,int personal); PKT_user_id *keygen_get_std_prefs (void); int keygen_add_key_expire( PKT_signature *sig, void *opaque ); int keygen_add_key_flags (PKT_signature *sig, void *opaque); int keygen_add_std_prefs( PKT_signature *sig, void *opaque ); int keygen_upd_std_prefs( PKT_signature *sig, void *opaque ); int keygen_add_keyserver_url(PKT_signature *sig, void *opaque); int keygen_add_notations(PKT_signature *sig,void *opaque); int keygen_add_revkey(PKT_signature *sig, void *opaque); gpg_error_t make_backsig (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pk, PKT_public_key *sub_pk, PKT_public_key *sub_psk, u32 timestamp, const char *cache_nonce); gpg_error_t generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr, const char *usagestr, const char *expirestr); #ifdef ENABLE_CARD_SUPPORT gpg_error_t generate_card_subkeypair (ctrl_t ctrl, kbnode_t pub_keyblock, int keyno, const char *serialno); #endif /*-- openfile.c --*/ int overwrite_filep( const char *fname ); char *make_outfile_name( const char *iname ); char *ask_outfile_name( const char *name, size_t namelen ); int open_outfile (int out_fd, const char *iname, int mode, int restrictedperm, iobuf_t *a); char *get_matching_datafile (const char *sigfilename); iobuf_t open_sigfile (const char *sigfilename, progress_filter_context_t *pfx); void try_make_homedir( const char *fname ); char *get_openpgp_revocdir (const char *home); /*-- seskey.c --*/ void make_session_key( DEK *dek ); gcry_mpi_t encode_session_key( int openpgp_pk_algo, DEK *dek, unsigned nbits ); gcry_mpi_t encode_md_value (PKT_public_key *pk, gcry_md_hd_t md, int hash_algo ); /*-- import.c --*/ struct import_stats_s; typedef struct import_stats_s *import_stats_t; struct import_filter_s; typedef struct import_filter_s *import_filter_t; typedef gpg_error_t (*import_screener_t)(kbnode_t keyblock, void *arg); int parse_import_options(char *str,unsigned int *options,int noisy); gpg_error_t parse_and_set_import_filter (const char *string); import_filter_t save_and_clear_import_filter (void); void restore_import_filter (import_filter_t filt); gpg_error_t read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock); void import_keys (ctrl_t ctrl, char **fnames, int nnames, import_stats_t stats_hd, unsigned int options, int origin, const char *url); gpg_error_t import_keys_es_stream (ctrl_t ctrl, estream_t fp, import_stats_t stats_handle, unsigned char **fpr, size_t *fpr_len, unsigned int options, import_screener_t screener, void *screener_arg, int origin, const char *url); gpg_error_t import_old_secring (ctrl_t ctrl, const char *fname); import_stats_t import_new_stats_handle (void); void import_release_stats_handle (import_stats_t hd); void import_print_stats (import_stats_t hd); /* Communication for impex_filter_getval */ struct impex_filter_parm_s { ctrl_t ctrl; kbnode_t node; }; const char *impex_filter_getval (void *cookie, const char *propname); gpg_error_t transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats, kbnode_t sec_keyblock, int batch, int force, int only_marked); int collapse_uids( KBNODE *keyblock ); int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen); /*-- export.c --*/ struct export_stats_s; typedef struct export_stats_s *export_stats_t; export_stats_t export_new_stats (void); void export_release_stats (export_stats_t stats); void export_print_stats (export_stats_t stats); int parse_export_options(char *str,unsigned int *options,int noisy); gpg_error_t parse_and_set_export_filter (const char *string); int exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, kbnode_t node); int export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); int export_seckeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); int export_secsubkeys (ctrl_t ctrl, strlist_t users, unsigned int options, export_stats_t stats); gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen); gpg_error_t receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd, int cleartext, char **cache_nonce_addr, const char *hexgrip, PKT_public_key *pk); gpg_error_t write_keyblock_to_output (kbnode_t keyblock, int with_armor, unsigned int options); gpg_error_t export_ssh_key (ctrl_t ctrl, const char *userid); /*-- dearmor.c --*/ int dearmor_file( const char *fname ); int enarmor_file( const char *fname ); /*-- revoke.c --*/ struct revocation_reason_info; int gen_standard_revoke (ctrl_t ctrl, PKT_public_key *psk, const char *cache_nonce); int gen_revoke (ctrl_t ctrl, const char *uname); int gen_desig_revoke (ctrl_t ctrl, const char *uname, strlist_t locusr); int revocation_reason_build_cb( PKT_signature *sig, void *opaque ); struct revocation_reason_info * ask_revocation_reason( int key_rev, int cert_rev, int hint ); struct revocation_reason_info * get_default_uid_revocation_reason(void); void release_revocation_reason_info( struct revocation_reason_info *reason ); /*-- keylist.c --*/ void public_key_list (ctrl_t ctrl, strlist_t list, int locate_mode, int no_local); void secret_key_list (ctrl_t ctrl, strlist_t list ); void print_subpackets_colon(PKT_signature *sig); void reorder_keyblock (KBNODE keyblock); void list_keyblock_direct (ctrl_t ctrl, kbnode_t keyblock, int secret, int has_secret, int fpr, int no_validity); void print_fingerprint (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int mode); void print_revokers (estream_t fp, PKT_public_key *pk); void show_policy_url(PKT_signature *sig,int indent,int mode); void show_keyserver_url(PKT_signature *sig,int indent,int mode); void show_notation(PKT_signature *sig,int indent,int mode,int which); void dump_attribs (const PKT_user_id *uid, PKT_public_key *pk); void set_attrib_fd(int fd); void print_key_info (ctrl_t ctrl, estream_t fp, int indent, PKT_public_key *pk, int secret); void print_key_info_log (ctrl_t ctrl, int loglevel, int indent, PKT_public_key *pk, int secret); void print_card_key_info (estream_t fp, KBNODE keyblock); void print_key_line (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int secret); /*-- verify.c --*/ void print_file_status( int status, const char *name, int what ); int verify_signatures (ctrl_t ctrl, int nfiles, char **files ); int verify_files (ctrl_t ctrl, int nfiles, char **files ); int gpg_verify (ctrl_t ctrl, int sig_fd, int data_fd, estream_t out_fp); /*-- decrypt.c --*/ int decrypt_message (ctrl_t ctrl, const char *filename ); gpg_error_t decrypt_message_fd (ctrl_t ctrl, int input_fd, int output_fd); void decrypt_messages (ctrl_t ctrl, int nfiles, char *files[]); /*-- plaintext.c --*/ int hash_datafiles( gcry_md_hd_t md, gcry_md_hd_t md2, strlist_t files, const char *sigfilename, int textmode); int hash_datafile_by_fd ( gcry_md_hd_t md, gcry_md_hd_t md2, int data_fd, int textmode ); PKT_plaintext *setup_plaintext_name(const char *filename,IOBUF iobuf); /*-- server.c --*/ int gpg_server (ctrl_t); gpg_error_t gpg_proxy_pinentry_notify (ctrl_t ctrl, const unsigned char *line); #ifdef ENABLE_CARD_SUPPORT /*-- card-util.c --*/ void change_pin (int no, int allow_admin); void card_status (ctrl_t ctrl, estream_t fp, const char *serialno); void card_edit (ctrl_t ctrl, strlist_t commands); gpg_error_t card_generate_subkey (ctrl_t ctrl, kbnode_t pub_keyblock); int card_store_subkey (KBNODE node, int use); #endif /*-- migrate.c --*/ void migrate_secring (ctrl_t ctrl); #endif /*G10_MAIN_H*/ diff --git a/g10/options.h b/g10/options.h index 339804f59..e80d3ead0 100644 --- a/g10/options.h +++ b/g10/options.h @@ -1,424 +1,416 @@ /* options.h * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2010, 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 G10_OPTIONS_H #define G10_OPTIONS_H #include #include "../common/types.h" #include #include "main.h" #include "packet.h" #include "tofu.h" #include "../common/session-env.h" #include "../common/compliance.h" -#ifndef EXTERN_UNLESS_MAIN_MODULE -/* Norcraft can't cope with common symbols */ -#if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE) -#define EXTERN_UNLESS_MAIN_MODULE extern -#else -#define EXTERN_UNLESS_MAIN_MODULE -#endif -#endif /* Declaration of a keyserver spec type. The definition is found in ../common/keyserver.h. */ struct keyserver_spec; typedef struct keyserver_spec *keyserver_spec_t; /* Global options for GPG. */ EXTERN_UNLESS_MAIN_MODULE struct { int verbose; int quiet; unsigned debug; int armor; char *outfile; estream_t outfp; /* Hack, sometimes used in place of outfile. */ off_t max_output; /* If > 0 a hint with the expected number of input data bytes. This * is not necessary an exact number but intended to be used for * progress info and to decide on how to allocate buffers. */ uint64_t input_size_hint; /* The AEAD chunk size expressed as a power of 2. */ int chunk_size; int dry_run; int autostart; int list_only; int mimemode; int textmode; int expert; const char *def_sig_expire; int ask_sig_expire; const char *def_cert_expire; int ask_cert_expire; int batch; /* run in batch mode */ int answer_yes; /* answer yes on most questions */ int answer_no; /* answer no on most questions */ int check_sigs; /* check key signatures */ int with_colons; int with_key_data; int with_icao_spelling; /* Print ICAO spelling with fingerprints. */ int with_fingerprint; /* Option --with-fingerprint active. */ int with_subkey_fingerprint; /* Option --with-subkey-fingerprint active. */ int with_keygrip; /* Option --with-keygrip active. */ int with_key_screening;/* Option --with-key-screening active. */ int with_tofu_info; /* Option --with-tofu_info active. */ int with_secret; /* Option --with-secret active. */ int with_wkd_hash; /* Option --with-wkd-hash. */ int with_key_origin; /* Option --with-key-origin. */ int fingerprint; /* list fingerprints */ int list_sigs; /* list signatures */ int no_armor; int list_packets; /* Option --list-packets active. */ int def_cipher_algo; int def_aead_algo; int force_mdc; int disable_mdc; int force_aead; int def_digest_algo; int cert_digest_algo; int compress_algo; int compress_level; int bz2_compress_level; int bz2_decompress_lowmem; strlist_t def_secret_key; char *def_recipient; int def_recipient_self; strlist_t secret_keys_to_try; /* A list of mail addresses (addr-spec) provided by the user with * the option --sender. */ strlist_t sender_list; int def_cert_level; int min_cert_level; int ask_cert_level; int emit_version; /* 0 = none, 1 = major only, 2 = major and minor, 3 = full version, 4 = full version plus OS string. */ int marginals_needed; int completes_needed; int max_cert_depth; const char *agent_program; const char *keyboxd_program; const char *dirmngr_program; int disable_dirmngr; const char *def_new_key_algo; /* Options to be passed to the gpg-agent */ session_env_t session_env; char *lc_ctype; char *lc_messages; int skip_verify; int skip_hidden_recipients; /* TM_CLASSIC must be zero to accommodate trustdbsg generated before we started storing the trust model inside the trustdb. */ enum { TM_CLASSIC=0, TM_PGP=1, TM_EXTERNAL=2, TM_ALWAYS, TM_DIRECT, TM_AUTO, TM_TOFU, TM_TOFU_PGP } trust_model; enum tofu_policy tofu_default_policy; int force_ownertrust; enum gnupg_compliance_mode compliance; enum { KF_DEFAULT, KF_NONE, KF_SHORT, KF_LONG, KF_0xSHORT, KF_0xLONG } keyid_format; const char *set_filename; strlist_t comments; int throw_keyids; const char *photo_viewer; int s2k_mode; int s2k_digest_algo; int s2k_cipher_algo; unsigned char s2k_count; /* This is the encoded form, not the raw count */ int not_dash_escaped; int escape_from; int lock_once; keyserver_spec_t keyserver; /* The list of configured keyservers. */ struct { unsigned int options; unsigned int import_options; unsigned int export_options; char *http_proxy; } keyserver_options; int exec_disable; int exec_path_set; unsigned int import_options; unsigned int export_options; unsigned int list_options; unsigned int verify_options; const char *def_preference_list; const char *def_keyserver_url; prefitem_t *personal_cipher_prefs; prefitem_t *personal_aead_prefs; prefitem_t *personal_digest_prefs; prefitem_t *personal_compress_prefs; struct weakhash *weak_digests; int no_perm_warn; char *temp_dir; int no_encrypt_to; int encrypt_to_default_key; int interactive; struct notation *sig_notations; struct notation *cert_notations; strlist_t sig_policy_url; strlist_t cert_policy_url; strlist_t sig_keyserver_url; strlist_t cert_subpackets; strlist_t sig_subpackets; int allow_non_selfsigned_uid; int allow_freeform_uid; int no_literal; ulong set_filesize; int fast_list_mode; int legacy_list_mode; int ignore_time_conflict; int ignore_valid_from; int ignore_crc_error; int ignore_mdc_error; int command_fd; const char *override_session_key; int show_session_key; const char *gpg_agent_info; int try_all_secrets; int no_expensive_trust_checks; int no_sig_cache; int no_auto_check_trustdb; int preserve_permissions; int no_homedir_creation; struct groupitem *grouplist; int mangle_dos_filenames; int enable_progress_filter; unsigned int screen_columns; unsigned int screen_lines; byte *show_subpackets; int rfc2440_text; /* If true, let write failures on the status-fd exit the process. */ int exit_on_status_write_error; /* If > 0, limit the number of card insertion prompts to this value. */ int limit_card_insert_tries; struct { /* If set, require an 0x19 backsig to be present on signatures made by signing subkeys. If not set, a missing backsig is not an error (but an invalid backsig still is). */ unsigned int require_cross_cert:1; unsigned int use_embedded_filename:1; unsigned int utf8_filename:1; unsigned int dsa2:1; unsigned int allow_weak_digest_algos:1; unsigned int allow_weak_key_signatures:1; unsigned int large_rsa:1; unsigned int disable_signer_uid:1; /* Flag to enable experimental features from RFC4880bis. */ unsigned int rfc4880bis:1; /* Hack: --output is not given but OUTFILE was temporary set to "-". */ unsigned int dummy_outfile:1; /* Force the use of the OpenPGP card and do not allow the use of * another card. */ unsigned int use_only_openpgp_card:1; } flags; /* Linked list of ways to find a key if the key isn't on the local keyring. */ struct akl { enum { AKL_NODEFAULT, AKL_LOCAL, AKL_CERT, AKL_PKA, AKL_DANE, AKL_WKD, AKL_LDAP, AKL_KEYSERVER, AKL_SPEC } type; keyserver_spec_t spec; struct akl *next; } *auto_key_locate; /* The value of --key-origin. See parse_key_origin(). */ int key_origin; char *key_origin_url; int passphrase_repeat; int pinentry_mode; int request_origin; int unwrap_encryption; int only_sign_text_ids; int no_symkey_cache; /* Disable the cache used for --symmetric. */ int use_keyboxd; /* Use the external keyboxd as storage backend. */ } opt; /* CTRL is used to keep some global variables we currently can't avoid. Future concurrent versions of gpg will put it into a per request structure CTRL. */ EXTERN_UNLESS_MAIN_MODULE struct { int in_auto_key_retrieve; /* True if we are doing an auto_key_retrieve. */ /* Hack to store the last error. We currently need it because the proc_packet machinery is not able to reliabale return error codes. Thus for the --server purposes we store some of the error codes here. FIXME! */ gpg_error_t lasterr; /* Kludge to silence some warnings using --secret-key-list. */ int silence_parse_warnings; } glo_ctrl; #define DBG_PACKET_VALUE 1 /* debug packet reading/writing */ #define DBG_MPI_VALUE 2 /* debug mpi details */ #define DBG_CRYPTO_VALUE 4 /* debug crypto handling */ /* (may reveal sensitive data) */ #define DBG_FILTER_VALUE 8 /* debug internal filter handling */ #define DBG_IOBUF_VALUE 16 /* debug iobuf stuff */ #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_TRUST_VALUE 256 /* debug the trustdb */ #define DBG_HASHING_VALUE 512 /* debug hashing operations */ #define DBG_IPC_VALUE 1024 /* debug assuan communication */ #define DBG_CLOCK_VALUE 4096 #define DBG_LOOKUP_VALUE 8192 /* debug the key lookup */ #define DBG_EXTPROG_VALUE 16384 /* debug external program calls */ /* Tests for the debugging flags. */ #define DBG_PACKET (opt.debug & DBG_PACKET_VALUE) #define DBG_MPI (opt.debug & DBG_MPI_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_FILTER (opt.debug & DBG_FILTER_VALUE) #define DBG_CACHE (opt.debug & DBG_CACHE_VALUE) #define DBG_TRUST (opt.debug & DBG_TRUST_VALUE) #define DBG_HASHING (opt.debug & DBG_HASHING_VALUE) #define DBG_IPC (opt.debug & DBG_IPC_VALUE) #define DBG_CLOCK (opt.debug & DBG_CLOCK_VALUE) #define DBG_LOOKUP (opt.debug & DBG_LOOKUP_VALUE) #define DBG_EXTPROG (opt.debug & DBG_EXTPROG_VALUE) /* FIXME: We need to check why we did not put this into opt. */ #define DBG_MEMORY memory_debug_mode #define DBG_MEMSTAT memory_stat_debug_mode EXTERN_UNLESS_MAIN_MODULE int memory_debug_mode; EXTERN_UNLESS_MAIN_MODULE int memory_stat_debug_mode; /* Compatibility flags. */ #define GNUPG (opt.compliance==CO_GNUPG || opt.compliance==CO_DE_VS) #define RFC2440 (opt.compliance==CO_RFC2440) #define RFC4880 (opt.compliance==CO_RFC4880) #define PGP7 (opt.compliance==CO_PGP7) #define PGP8 (opt.compliance==CO_PGP8) #define PGPX (PGP7 || PGP8) /* Various option flags. Note that there should be no common string names between the IMPORT_ and EXPORT_ flags as they can be mixed in the keyserver-options option. */ #define IMPORT_LOCAL_SIGS (1<<0) #define IMPORT_REPAIR_PKS_SUBKEY_BUG (1<<1) #define IMPORT_FAST (1<<2) #define IMPORT_SHOW (1<<3) #define IMPORT_MERGE_ONLY (1<<4) #define IMPORT_MINIMAL (1<<5) #define IMPORT_CLEAN (1<<6) #define IMPORT_NO_SECKEY (1<<7) #define IMPORT_KEEP_OWNERTTRUST (1<<8) #define IMPORT_EXPORT (1<<9) #define IMPORT_RESTORE (1<<10) #define IMPORT_REPAIR_KEYS (1<<11) #define IMPORT_DRY_RUN (1<<12) #define IMPORT_DROP_UIDS (1<<13) #define IMPORT_SELF_SIGS_ONLY (1<<14) #define EXPORT_LOCAL_SIGS (1<<0) #define EXPORT_ATTRIBUTES (1<<1) #define EXPORT_SENSITIVE_REVKEYS (1<<2) #define EXPORT_RESET_SUBKEY_PASSWD (1<<3) #define EXPORT_MINIMAL (1<<4) #define EXPORT_CLEAN (1<<5) #define EXPORT_PKA_FORMAT (1<<6) #define EXPORT_DANE_FORMAT (1<<7) #define EXPORT_BACKUP (1<<10) #define EXPORT_DROP_UIDS (1<<13) #define LIST_SHOW_PHOTOS (1<<0) #define LIST_SHOW_POLICY_URLS (1<<1) #define LIST_SHOW_STD_NOTATIONS (1<<2) #define LIST_SHOW_USER_NOTATIONS (1<<3) #define LIST_SHOW_NOTATIONS (LIST_SHOW_STD_NOTATIONS|LIST_SHOW_USER_NOTATIONS) #define LIST_SHOW_KEYSERVER_URLS (1<<4) #define LIST_SHOW_UID_VALIDITY (1<<5) #define LIST_SHOW_UNUSABLE_UIDS (1<<6) #define LIST_SHOW_UNUSABLE_SUBKEYS (1<<7) #define LIST_SHOW_KEYRING (1<<8) #define LIST_SHOW_SIG_EXPIRE (1<<9) #define LIST_SHOW_SIG_SUBPACKETS (1<<10) #define LIST_SHOW_USAGE (1<<11) #define LIST_SHOW_ONLY_FPR_MBOX (1<<12) #define VERIFY_SHOW_PHOTOS (1<<0) #define VERIFY_SHOW_POLICY_URLS (1<<1) #define VERIFY_SHOW_STD_NOTATIONS (1<<2) #define VERIFY_SHOW_USER_NOTATIONS (1<<3) #define VERIFY_SHOW_NOTATIONS (VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_USER_NOTATIONS) #define VERIFY_SHOW_KEYSERVER_URLS (1<<4) #define VERIFY_SHOW_UID_VALIDITY (1<<5) #define VERIFY_SHOW_UNUSABLE_UIDS (1<<6) #define VERIFY_PKA_LOOKUPS (1<<7) #define VERIFY_PKA_TRUST_INCREASE (1<<8) #define VERIFY_SHOW_PRIMARY_UID_ONLY (1<<9) #define KEYSERVER_HTTP_PROXY (1<<0) #define KEYSERVER_TIMEOUT (1<<1) #define KEYSERVER_ADD_FAKE_V3 (1<<2) #define KEYSERVER_AUTO_KEY_RETRIEVE (1<<3) #define KEYSERVER_HONOR_KEYSERVER_URL (1<<4) #define KEYSERVER_HONOR_PKA_RECORD (1<<5) #endif /*G10_OPTIONS_H*/ diff --git a/g10/test.c b/g10/test.c index 375f361a7..648148a10 100644 --- a/g10/test.c +++ b/g10/test.c @@ -1,191 +1,192 @@ /* test.c - Infrastructure for unit tests. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include +#define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" /* A unit test consists of one or more tests. Tests can be broken into groups and each group can consist of one or more tests. */ /* The number of test groups. */ static int test_groups; /* The current test group. */ static char *test_group; /* Whether there was already a failure in the current test group. */ static int current_test_group_failed; /* The number of test groups with a failure. */ static int test_groups_failed; /* The total number of tests. */ static int tests; /* The total number of tests that failed. */ static int tests_failed; /* Flag to request verbose diagnostics. This is set if the envvar "verbose" exists and is not the empty string. */ static int verbose; #define TEST_GROUP(description) \ do { \ test_group = (description); \ test_groups ++; \ current_test_group_failed = 0; \ } while (0) #define STRINGIFY2(x) #x #define STRINGIFY(x) STRINGIFY2(x) /* Execute a test. */ #define TEST(description, test, expected) \ do { \ int test_result; \ int expected_result; \ \ tests ++; \ if (verbose) \ { \ printf ("%d. Checking %s...", \ tests, (description) ?: ""); \ fflush (stdout); \ } \ test_result = (test); \ expected_result = (expected); \ \ if (test_result == expected_result) \ { \ if (verbose) printf (" ok.\n"); \ } \ else \ { \ if (!verbose) \ printf ("%d. Checking %s...", \ tests, (description) ?: ""); \ printf (" failed.\n"); \ printf (" %s == %s failed.\n", \ STRINGIFY(test), \ STRINGIFY(expected)); \ tests_failed ++; \ if (! current_test_group_failed) \ { \ current_test_group_failed = 1; \ test_groups_failed ++; \ } \ } \ } while (0) /* Test that a condition evaluates to true. */ #define TEST_P(description, test) \ TEST(description, !!(test), 1) /* Like CHECK, but if the test fails, abort the program. */ #define ASSERT(description, test, expected) \ do { \ int tests_failed_pre = tests_failed; \ CHECK(description, test, expected); \ if (tests_failed_pre != tests_failed) \ exit_tests (1); \ } while (0) /* Call this if something went wrong. */ #define ABORT(message) \ do { \ printf ("aborting..."); \ if (message) \ printf (" %s\n", (message)); \ \ exit_tests (1); \ } while (0) /* You need to fill this function in. */ static void do_test (int argc, char *argv[]); /* Print stats and call the real exit. If FORCE is set use EXIT_FAILURE even if no test has failed. */ static void exit_tests (int force) { if (tests_failed == 0) { if (verbose) printf ("All %d tests passed.\n", tests); exit (!!force); } else { printf ("%d of %d tests failed", tests_failed, tests); if (test_groups > 1) printf (" (%d of %d groups)", test_groups_failed, test_groups); printf ("\n"); exit (1); } } /* Prepend FNAME with the srcdir environment variable's value and return a malloced filename. Caller must release the returned string using test_free. */ char * prepend_srcdir (const char *fname) { static const char *srcdir; char *result; if (!srcdir && !(srcdir = getenv ("abs_top_srcdir"))) srcdir = "."; result = malloc (strlen (srcdir) + strlen ("/g10/") + strlen (fname) + 1); strcpy (result, srcdir); strcat (result, "/g10/"); strcat (result, fname); return result; } void test_free (void *a) { if (a) free (a); } int main (int argc, char *argv[]) { const char *s; (void) test_group; s = getenv ("verbose"); if (s && *s) verbose = 1; do_test (argc, argv); exit_tests (0); return !!tests_failed; } diff --git a/g13/g13-common.h b/g13/g13-common.h index acf25b843..42b8deebd 100644 --- a/g13/g13-common.h +++ b/g13/g13-common.h @@ -1,96 +1,96 @@ /* g13.h - Global definitions for G13. * Copyright (C) 2009 Free Software Foundation, Inc. * Copyright (C) 2009, 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 . */ #ifndef G13_COMMON_H #define G13_COMMON_H #ifdef GPG_ERR_SOURCE_DEFAULT #error GPG_ERR_SOURCE_DEFAULT already defined #endif #define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_G13 #include #include "../common/util.h" #include "../common/status.h" #include "../common/session-env.h" #include "../common/strlist.h" - /* Debug values and macros. */ #define DBG_MOUNT_VALUE 1 /* Debug mount or device stuff. */ #define DBG_CRYPTO_VALUE 4 /* Debug low level crypto. */ #define DBG_MEMORY_VALUE 32 /* Debug memory allocation stuff. */ #define DBG_MEMSTAT_VALUE 128 /* Show memory statistics. */ #define DBG_IPC_VALUE 1024 /* Debug assuan communication. */ #define DBG_MOUNT (opt.debug & DBG_MOUNT_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE) #define DBG_IPC (opt.debug & DBG_IPC_VALUE) /* A large struct named "opt" to keep global flags. Note that this struct is used by g13 and g13-syshelp and thus some fields may only make sense for one of them. */ +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. */ const char *config_filename; /* Name of the used config file. */ /* Filename of the AGENT program. */ const char *agent_program; /* Filename of the GPG program. Unless set via an program option it is initialized at the first engine startup to the standard gpg filename. */ const char *gpg_program; /* GPG arguments. XXX: Currently it is not possible to set them. */ strlist_t gpg_arguments; /* Environment variables passed along to the engine. */ char *display; char *ttyname; char *ttytype; char *lc_ctype; char *lc_messages; char *xauthority; char *pinentry_user_data; session_env_t session_env; /* Name of the output file - FIXME: what is this? */ const char *outfile; } opt; /*-- g13-common.c --*/ void g13_init_signals (void); void g13_install_emergency_cleanup (void); void g13_exit (int rc); /*-- server.c and g13-sh-cmd.c --*/ gpg_error_t g13_status (ctrl_t ctrl, int no, ...) GPGRT_ATTR_SENTINEL(0); #endif /*G13_COMMON_H*/ diff --git a/g13/g13-syshelp.c b/g13/g13-syshelp.c index bf71ac20f..4ce74ee4c 100644 --- a/g13/g13-syshelp.c +++ b/g13/g13-syshelp.c @@ -1,748 +1,749 @@ /* g13-syshelp.c - Helper for disk key management with GnuPG * Copyright (C) 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 #ifdef HAVE_PWD_H # include #endif #include +#define INCLUDED_BY_MAIN_MODULE 1 #include "g13-syshelp.h" #include #include #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/asshelp.h" #include "../common/init.h" #include "keyblob.h" enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oRecipient = 'r', aGPGConfList = 500, oDebug, oDebugLevel, oDebugAll, oDebugNone, oDebugWait, oDebugAllowCoreDump, oLogFile, oNoLogFile, oAuditLog, oOutput, oAgentProgram, oGpgProgram, oType, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oStatusFD, oLoggerFD, oNoVerbose, oNoSecmemWarn, oHomedir, oDryRun, oNoDetach, oNoRandomSeedFile, oFakedSystemTime }; static ARGPARSE_OPTS opts[] = { ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_n (oDebugNone, "debug-none", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_MOUNT_VALUE , "mount" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_IPC_VALUE , "ipc" }, { 0, NULL } }; /* The timer tick interval used by the idle task. */ #define TIMERTICK_INTERVAL_SEC (1) /* It is possible that we are currently running under setuid permissions. */ static int maybe_setuid = 1; /* Helper to implement --debug-level and --debug. */ static const char *debug_level; static unsigned int debug_value; /* Local prototypes. */ static void g13_syshelp_deinit_default_ctrl (ctrl_t ctrl); static void release_tab_items (tab_item_t tab); static tab_item_t parse_g13tab (const char *username); static const char * my_strusage( int level ) { const char *p; switch (level) { case 11: p = "@G13@-syshelp (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n"); break; case 1: case 40: p = _("Usage: @G13@-syshelp [options] [files] (-h for help)"); break; case 41: p = _("Syntax: @G13@-syshelp [options] [files]\n" "Helper to perform root-only tasks for g13\n"); break; case 31: p = "\nHome: "; break; case 32: p = gnupg_homedir (); break; default: p = NULL; break; } return p; } /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active debug flags are propagated to the subsystems. With DEBUG_LEVEL set, a specific set of debug flags is set; and individual debugging flags will be added on top. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE|DBG_MOUNT_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_IPC_VALUE|DBG_MOUNT_VALUE; else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_MOUNT_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* if (numok) */ /* opt.debug &= ~(DBG_HASHING_VALUE); */ } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); g13_exit(2); } opt.debug |= debug_value; if (opt.debug && !opt.verbose) opt.verbose = 1; if (opt.debug) opt.quiet = 0; if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } int main ( int argc, char **argv) { ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; gpg_error_t err = 0; /* const char *fname; */ int may_coredump; FILE *configfp = NULL; char *configname = NULL; unsigned configlineno; int parse_debug = 0; int no_more_options = 0; int default_config =1; char *logfile = NULL; /* int debug_wait = 0; */ int use_random_seed = 1; /* int nodetach = 0; */ /* int nokeysetup = 0; */ struct server_control_s ctrl; /*mtrace();*/ early_system_init (); gnupg_reopen_std (G13_NAME "-syshelp"); set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); log_set_prefix (G13_NAME "-syshelp", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); /* Take extra care of the random pool. */ gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); may_coredump = disable_core_dumps (); g13_init_signals (); dotlock_create (NULL, 0); /* Register locking cleanup. */ opt.session_env = session_env_new (); if (!opt.session_env) log_fatal ("error allocating session environment block: %s\n", strerror (errno)); /* Fixme: We enable verbose mode here because there is currently no way to do this when starting g13-syshelp. To fix that we should add a g13-syshelp.conf file in /etc/gnupg. */ opt.verbose = 1; /* First check whether we have a debug option on the commandline. */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; } /* Initialize the secure memory. */ gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); maybe_setuid = 0; /* Now we are now working under our real uid */ /* Setup malloc hooks. */ { struct assuan_malloc_hooks malloc_hooks; malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); } /* Prepare libassuan. */ assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); /*assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);*/ setup_libassuan_logging (&opt.debug, NULL); /* Setup a default control structure for command line mode. */ memset (&ctrl, 0, sizeof ctrl); g13_syshelp_init_default_ctrl (&ctrl); ctrl.no_server = 1; ctrl.status_fd = -1; /* No status output. */ if (default_config ) configname = make_filename (gnupg_sysconfdir (), G13_NAME"-syshelp.conf", NULL); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags = 1; /* Do not remove the args. */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if (parse_debug) log_info (_("NOTE: no default option file '%s'\n"), configname); } else { log_error (_("option file '%s': %s\n"), configname, strerror(errno)); g13_exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname) log_info (_("reading options from '%s'\n"), configname); default_config = 0; } while (!no_more_options && optfile_parse (configfp, configname, &configlineno, &pargs, opts)) { switch (pargs.r_opt) { case oQuiet: opt.quiet = 1; break; case oDryRun: opt.dry_run = 1; break; case oVerbose: opt.verbose++; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); break; case oNoVerbose: opt.verbose = 0; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); break; case oLogFile: logfile = pargs.r.ret_str; break; case oNoLogFile: logfile = NULL; break; case oNoDetach: /*nodetach = 1; */break; case oDebug: if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags)) { pargs.r_opt = ARGPARSE_INVALID_ARG; pargs.err = ARGPARSE_PRINT_ERROR; } break; case oDebugAll: debug_value = ~0; break; case oDebugNone: debug_value = 0; break; case oDebugLevel: debug_level = pargs.r.ret_str; break; case oDebugWait: /*debug_wait = pargs.r.ret_int; */break; case oDebugAllowCoreDump: may_coredump = enable_core_dumps (); break; case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break; case oLoggerFD: log_set_fd (pargs.r.ret_int ); break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oFakedSystemTime: { time_t faked_time = isotime2epoch (pargs.r.ret_str); if (faked_time == (time_t)(-1)) faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10); gnupg_set_time (faked_time, 0); } break; case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break; case oNoRandomSeedFile: use_random_seed = 0; break; default: pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR; break; } } if (configfp) { fclose (configfp); configfp = NULL; /* Keep a copy of the config filename. */ opt.config_filename = configname; configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (!opt.config_filename) opt.config_filename = make_filename (gnupg_homedir (), G13_NAME".conf", NULL); if (log_get_errorcount(0)) g13_exit(2); /* Now that we have the options parsed we need to update the default control structure. */ g13_syshelp_init_default_ctrl (&ctrl); if (may_coredump && !opt.quiet) log_info (_("WARNING: program may create a core file!\n")); if (logfile) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } /* Print any pending secure memory warnings. */ gcry_control (GCRYCTL_RESUME_SECMEM_WARN); /* Setup the debug flags for all subsystems. */ set_debug (); /* Install a regular exit handler to make real sure that the secure memory gets wiped out. */ g13_install_emergency_cleanup (); /* Terminate if we found any error until now. */ if (log_get_errorcount(0)) g13_exit (2); /* Set the standard GnuPG random seed file. */ if (use_random_seed) { char *p = make_filename (gnupg_homedir (), "random_seed", NULL); gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p); xfree(p); } /* Get the UID of the caller. */ #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID) { const char *uidstr; struct passwd *pwd = NULL; uidstr = getenv ("USERV_UID"); /* Print a quick note if we are not started via userv. */ if (!uidstr) { if (getuid ()) { log_info ("WARNING: Not started via userv\n"); ctrl.fail_all_cmds = 1; } ctrl.client.uid = getuid (); } else { unsigned long myuid; errno = 0; myuid = strtoul (uidstr, NULL, 10); if (myuid == ULONG_MAX && errno) { log_info ("WARNING: Started via broken userv: %s\n", strerror (errno)); ctrl.fail_all_cmds = 1; ctrl.client.uid = getuid (); } else ctrl.client.uid = (uid_t)myuid; } pwd = getpwuid (ctrl.client.uid); if (!pwd || !*pwd->pw_name) { log_info ("WARNING: Name for UID not found: %s\n", strerror (errno)); ctrl.fail_all_cmds = 1; ctrl.client.uname = xstrdup ("?"); } else ctrl.client.uname = xstrdup (pwd->pw_name); /* Check that the user name does not contain a directory separator. */ if (strchr (ctrl.client.uname, '/')) { log_info ("WARNING: Invalid user name passed\n"); ctrl.fail_all_cmds = 1; } } #else /*!HAVE_PWD_H || !HAVE_GETPWUID*/ log_info ("WARNING: System does not support required syscalls\n"); ctrl.fail_all_cmds = 1; ctrl.client.uid = getuid (); ctrl.client.uname = xstrdup ("?"); #endif /*!HAVE_PWD_H || !HAVE_GETPWUID*/ /* Read the table entries for this user. */ if (!ctrl.fail_all_cmds && !(ctrl.client.tab = parse_g13tab (ctrl.client.uname))) ctrl.fail_all_cmds = 1; /* Start the server. */ err = syshelp_server (&ctrl); if (err) log_error ("server exited with error: %s <%s>\n", gpg_strerror (err), gpg_strsource (err)); /* Cleanup. */ g13_syshelp_deinit_default_ctrl (&ctrl); g13_exit (0); return 8; /*NOTREACHED*/ } /* Store defaults into the per-connection CTRL object. */ void g13_syshelp_init_default_ctrl (ctrl_t ctrl) { ctrl->conttype = CONTTYPE_DM_CRYPT; } /* Release all resources allocated by default in the CTRl object. */ static void g13_syshelp_deinit_default_ctrl (ctrl_t ctrl) { xfree (ctrl->client.uname); release_tab_items (ctrl->client.tab); } /* Release the list of g13tab itejms at TAB. */ static void release_tab_items (tab_item_t tab) { while (tab) { tab_item_t next = tab->next; xfree (tab->mountpoint); xfree (tab); tab = next; } } void g13_syshelp_i_know_what_i_am_doing (void) { const char * const yesfile = "Yes-g13-I-know-what-I-am-doing"; char *fname; fname = make_filename (gnupg_sysconfdir (), yesfile, NULL); if (access (fname, F_OK)) { log_info ("*******************************************************\n"); log_info ("* The G13 support for DM-Crypt is new and not matured.\n"); log_info ("* Bugs or improper use may delete all your disks!\n"); log_info ("* To confirm that you are ware of this risk, create\n"); log_info ("* the file '%s'.\n", fname); log_info ("*******************************************************\n"); exit (1); } xfree (fname); } /* Parse the /etc/gnupg/g13tab for user USERNAME. Return a table for the user on success. Return NULL on error and print diagnostics. */ static tab_item_t parse_g13tab (const char *username) { gpg_error_t err; int c, n; char line[512]; char *p; char *fname; estream_t fp; int lnr; char **words = NULL; tab_item_t table = NULL; tab_item_t *tabletail, ti; fname = make_filename (gnupg_sysconfdir (), G13_NAME"tab", NULL); fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } tabletail = &table; err = 0; lnr = 0; while (es_fgets (line, DIM(line)-1, fp)) { lnr++; n = strlen (line); if (!n || line[n-1] != '\n') { /* Eat until end of line. */ while ((c=es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); log_error (_("file '%s', line %d: %s\n"), fname, lnr, gpg_strerror (err)); continue; } line[--n] = 0; /* Chop the LF. */ if (n && line[n-1] == '\r') line[--n] = 0; /* Chop an optional CR. */ /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; if (!*p || *p == '#') continue; /* Parse the line. The format is * [