diff --git a/NEWS b/NEWS index c19c1cd12..2ee35e6c8 100644 --- a/NEWS +++ b/NEWS @@ -1,2874 +1,2877 @@ Noteworthy changes in version 2.1.11 (unreleased) ------------------------------------------------- + * gpg: Don't check for ambigious or non-matching key specification in + the config file or given to --encrypt-to. This feature will return + in 2.3.x. Noteworthy changes in version 2.1.10 (2015-12-04) ------------------------------------------------- * gpg: New trust models "tofu" and "tofu+pgp". * gpg: New command --tofu-policy. New options --tofu-default-policy and --tofu-db-format. * gpg: New option --weak-digest to specify hash algorithms which should be considered weak. * gpg: Allow the use of multiple --default-key options; take the last available key. * gpg: New option --encrypt-to-default-key. * gpg: New option --unwrap to only strip the encryption layer. * gpg: New option --only-sign-text-ids to exclude photo IDs from key signing. * gpg: Check for ambigious or non-matching key specification in the config file or given to --encrypt-to. * gpg: Show the used card reader with --card-status. * gpg: Print export statistics and an EXPORTED status line. * gpg: Allow selecting subkeys by keyid in --edit-key. * gpg: Allow updating the expiration time of multiple subkeys at once. * dirmngr: New option --use-tor. For full support this requires libassuan version 2.4.2 and a patched version of libadns (e.g. adns-1.4-g10-7 as used by the standard Windows installer). * dirmngr: New option --nameserver to specify the nameserver used in Tor mode. * dirmngr: Keyservers may again be specified by IP address. * dirmngr: Fixed problems in resolving keyserver pools. * dirmngr: Fixed handling of premature termination of TLS streams so that large numbers of keys can be refreshed via hkps. * gpg: Fixed a regression in --locate-key [since 2.1.9]. * gpg: Fixed another bug for keyrings with legacy keys. * gpgsm: Allow combinations of usage flags in --gen-key. * Make tilde expansion work with most options. * Many other cleanups and bug fixes. Noteworthy changes in version 2.1.9 (2015-10-09) ------------------------------------------------ * gpg: Allow fetching keys via OpenPGP DANE (--auto-key-locate). New option --print-dane-records. * gpg: Fix for a problem with PGP-2 keys in a keyring. * gpg: Fail with an error instead of a warning if a modern cipher algorithm is used without a MDC. * agent: New option --pinentry-invisible-char. * agent: Always do a RSA signature verification after creation. * agent: Fix a regression in ssh-add-ing Ed25519 keys. * agent: Fix ssh fingerprint computation for nistp384 and EdDSA. * agent: Fix crash during passprase entry on some platforms. * scd: Change timeout to fix problems with some 2.1 cards. * dirmngr: Displayed name is now Key Acquirer. * dirmngr: Add option --keyserver. Deprecate that option for gpg. Install a dirmngr.conf file from a skeleton for new installations. Noteworthy changes in version 2.1.8 (2015-09-10) ------------------------------------------------ * gpg: Sending very large keys to the keyservers works again. * gpg: Validity strings in key listings are now again translatable. * gpg: Emit FAILURE status lines to help GPGME. * gpg: Does not anymore link to Libksba to reduce dependencies. * gpgsm: Export of secret keys via Assuan is now possible. * agent: Raise the maximum passphrase length from 100 to 255 bytes. * agent: Fix regression using EdDSA keys with ssh. * Does not anymore use a build timestamp by default. * The fallback encoding for broken locale settings changed from Latin-1 to UTF-8. * Many code cleanups and improved internal documentation. * Various minor bug fixes. Noteworthy changes in version 2.1.7 (2015-08-11) ------------------------------------------------ * gpg: Support encryption with Curve25519 if Libgcrypt 1.7 is used. * gpg: In the --edit-key menu: Removed the need for "toggle", changed how secret keys are indicated, new commands "fpr *" and "grip". * gpg: More fixes related to legacy keys in a keyring. * gpgv: Does now also work with a "trustedkeys.kbx" file. * scd: Support some feature from the OpenPGP card 3.0 specs. * scd: Improved ECC support * agent: New option --force for the DELETE_KEY command. * w32: Look for the Pinentry at more places. * Dropped deprecated gpgsm-gencert.sh * Various other bug fixes. Noteworthy changes in version 2.1.6 (2015-07-01) ------------------------------------------------ * agent: New option --verify for the PASSWD command. * gpgsm: Add command option "offline" as an alternative to --disable-dirmngr. * gpg: Do not prompt multiple times for a password in pinentry loopback mode. * Allow the use of debug category names with --debug. * Using gpg-agent and gpg/gpgsm with different locales will now show the correct translations in Pinentry. * gpg: Improve speed of --list-sigs and --check-sigs. * gpg: Make --list-options show-sig-subpackets work again. * gpg: Fix an export problem for old keyrings with PGP-2 keys. * scd: Support PIN-pads on more readers. * dirmngr: Properly cleanup zombie LDAP helper processes and avoid hangs on dirmngr shutdown. * Various other bug fixes. Noteworthy changes in version 2.1.5 (2015-06-11) ------------------------------------------------ * Support for an external passphrase cache. * Support for the forthcoming version 3 OpenPGP smartcard. * Manuals now show the actual used file names. * Prepared for improved integration with Emacs. * Code cleanups and minor bug fixes. Noteworthy changes in version 2.1.4 (2015-05-12) ------------------------------------------------ * gpg: Add command --quick-adduid to non-interactively add a new user id to an existing key. * gpg: Do no enable honor-keyserver-url by default. Make it work if enabled. * gpg: Display the serial number in the --card-status output again. * agent: Support for external password managers. Add option --no-allow-external-cache. * scdaemon: Improved handling of extended APDUs. * Make HTTP proxies work again. * All network access including DNS as been moved to Dirmngr. * Allow building without LDAP support. * Fixed lots of smaller bugs. Noteworthy changes in version 2.1.3 (2015-04-11) ------------------------------------------------ * gpg: LDAP keyservers are now supported by 2.1. * gpg: New option --with-icao-spelling. * gpg: New option --print-pka-records. Changed the PKA method to use CERT records and hashed names. * gpg: New command --list-gcrypt-config. New parameter "curve" for --list-config. * gpg: Print a NEWSIG status line like gpgsm always did. * gpg: Print MPI values with --list-packets and --verbose. * gpg: Write correct MPI lengths with ECC keys. * gpg: Skip legacy PGP-2 keys while searching. * gpg: Improved searching for mail addresses when using a keybox. * gpgsm: Changed default algos to AES-128 and SHA-256. * gpgtar: Fixed extracting files with sizes of a multiple of 512. * dirmngr: Fixed SNI handling for hkps pools. * dirmngr: extra-certs and trusted-certs are now always loaded from the sysconfig dir instead of the homedir. * Fixed possible problems due to compiler optimization, two minor regressions, and other bugs. Noteworthy changes in version 2.1.2 (2015-02-11) ------------------------------------------------ * gpg: The parameter 'Passphrase' for batch key generation works again. * gpg: Using a passphrase option in batch mode now has the expected effect on --quick-gen-key. * gpg: Improved reporting of unsupported PGP-2 keys. * gpg: Added support for algo names when generating keys using --command-fd. * gpg: Fixed DoS based on bogus and overlong key packets. * agent: When setting --default-cache-ttl the value for --max-cache-ttl is adjusted to be not lower than the former. * agent: Fixed problems with the new --extra-socket. * agent: Made --allow-loopback-pinentry changeable with gpgconf. * agent: Fixed importing of unprotected openpgp keys. * agent: Now tries to use a fallback pinentry if the standard pinentry is not installed. * scd: Added support for ECDH. * Fixed several bugs related to bogus keyrings and improved some other code. Noteworthy changes in version 2.1.1 (2014-12-16) ------------------------------------------------ * gpg: Detect faulty use of --verify on detached signatures. * gpg: New import option "keep-ownertrust". * gpg: New sub-command "factory-reset" for --card-edit. * gpg: A stub key for smartcards is now created by --card-status. * gpg: Fixed regression in --refresh-keys. * gpg: Fixed regresion in %g and %p codes for --sig-notation. * gpg: Fixed best matching hash algo detection for ECDSA and EdDSA. * gpg: Improved perceived speed of secret key listisngs. * gpg: Print number of skipped PGP-2 keys on import. * gpg: Removed the option aliases --throw-keyid and --notation-data; use --throw-keyids and --set-notation instead. * gpg: New import option "keep-ownertrust". * gpg: Skip too large keys during import. * gpg,gpgsm: New option --no-autostart to avoid starting gpg-agent or dirmngr. * gpg-agent: New option --extra-socket to provide a restricted command set for use with remote clients. * gpgconf --kill does not anymore start a service only to kill it. * gpg-pconnect-agent: Add convenience option --uiserver. * Fixed keyserver access for Windows. * Fixed build problems on Mac OS X * The Windows installer does now install development files * More translations (but most of them are not complete). * To support remotely mounted home directories, the IPC sockets may now be redirected. This feature requires Libassuan 2.2.0. * Improved portability and the usual bunch of bug fixes. Noteworthy changes in version 2.1.0 (2014-11-06) ------------------------------------------------ This release introduces a lot of changes. Most of them are internal and thus not user visible. However, some long standing behavior has slightly changed and it is strongly suggested that an existing "~/.gnupg" directory is backed up before this version is used. A verbose description of the major new features and changes can be found in the file doc/whats-new-in-2.1.txt. * gpg: All support for v3 (PGP 2) keys has been dropped. All signatures are now created as v4 signatures. v3 keys will be removed from the keyring. * gpg: With pinentry-0.9.0 the passphrase "enter again" prompt shows up in the same window as the "new passphrase" prompt. * gpg: Allow importing keys with duplicated long key ids. * dirmngr: May now be build without support for LDAP. * For a complete list of changes see the lists of changes for the 2.1.0 beta versions below. Note that all relevant fixes from versions 2.0.14 to 2.0.26 are also applied to this version. [Noteworthy changes in version 2.1.0-beta864 (2014-10-03)] * gpg: Removed the GPG_AGENT_INFO related code. GnuPG does now always use a fixed socket name in its home directory. * gpg: Renamed --gen-key to --full-gen-key and re-added a --gen-key command with less choices. * gpg: Use SHA-256 for all signature types also on RSA keys. * gpg: Default keyring is now created with a .kbx suffix. * gpg: Add a shortcut to the key capabilies menu (e.g. "=e" sets the encryption capabilities). * gpg: Fixed obsolete options parsing. * Further improvements for the alternative speedo build system. [Noteworthy changes in version 2.1.0-beta834 (2014-09-18)] * gpg: Improved passphrase caching. * gpg: Switched to algorithm number 22 for EdDSA. * gpg: Removed CAST5 from the default preferences. * gpg: Order SHA-1 last in the hash preferences. * gpg: Changed default cipher for --symmetric to AES-128. * gpg: Fixed export of ECC keys and import of EdDSA keys. * dirmngr: Fixed the KS_FETCH command. * The speedo build system now downloads related packages and works for non-Windows platforms. [Noteworthy changes in version 2.1.0-beta783 (2014-08-14)] * gpg: Add command --quick-gen-key. * gpg: Make --quick-sign-key promote local key signatures. * gpg: Added "show-usage" sub-option to --list-options. * gpg: Screen keyserver responses to avoid importing unwanted keys from rogue servers. * gpg: Removed the option --pgp2 and --rfc1991 and the ability to create PGP-2 compatible messages. * gpg: Removed options --compress-keys and --compress-sigs. * gpg: Cap attribute packets at 16MB. * gpg: Improved output of --list-packets. * gpg: Make with-colons output of --search-keys work again. * gpgsm: Auto-create the ".gnupg" directory like gpg does. * agent: Fold new passphrase warning prompts into one. * scdaemon: Add support for the Smartcard-HSM card. * scdaemon: Remove the use of the pcsc-wrapper. [Noteworthy changes in version 2.1.0-beta751 (2014-07-03)] * gpg: Create revocation certificates during key generation. * gpg: Create exported secret keys and revocation certifciates with mode 0700 * gpg: The validity of user ids is now shown by default. To revert this add "list-options no-show-uid-validity" to gpg.conf. * gpg: Make export of secret keys work again. * gpg: The output of --list-packets does now print the offset of the packet and information about the packet header. * gpg: Avoid DoS due to garbled compressed data packets. [CVE-2014-4617] * gpg: Print more specific reason codes with the INV_RECP status. * gpg: Cap RSA and Elgamal keysize at 4096 bit also for unattended key generation. * scdaemon: Support reader Gemalto IDBridge CT30 and pinpad of SCT cyberJack go. * The speedo build system has been improved. It is now also possible to build a partly working installer for Windows. [Noteworthy changes in version 2.1.0-beta442 (2014-06-05)] * gpg: Changed the format of key listings. To revert to the old format the option --legacy-list-mode is available. * gpg: Add experimental signature support using curve Ed25519 and with a patched Libgcrypt also encryption support with Curve25519. [Update: this encryption support has been removed from 2.1.0 until we have agreed on a suitable format.] * gpg: Allow use of Brainpool curves. * gpg: Accepts a space separated fingerprint as user ID. This allows to copy and paste the fingerprint from the key listing. * gpg: The hash algorithm is now printed for signature records in key listings. * gpg: Reject signatures made using the MD5 hash algorithm unless the new option --allow-weak-digest-algos or --pgp2 are given. * gpg: Print a warning if the Gnome-Keyring-Daemon intercepts the communication with the gpg-agent. * gpg: New option --pinentry-mode. * gpg: Fixed decryption using an OpenPGP card. * gpg: Fixed bug with deeply nested compressed packets. * gpg: Only the major version number is by default included in the armored output. * gpg: Do not create a trustdb file if --trust-model=always is used. * gpg: Protect against rogue keyservers sending secret keys. * gpg: The format of the fallback key listing ("gpg KEYFILE") is now more aligned to the regular key listing ("gpg -k"). * gpg: The option--show-session-key prints its output now before the decryption of the bulk message starts. * gpg: New %U expando for the photo viewer. * gpg,gpgsm: New option --with-secret. * gpgsm: By default the users are now asked via the Pinentry whether they trust an X.509 root key. To prohibit interactive marking of such keys, the new option --no-allow-mark-trusted may be used. * gpgsm: New commands to export a secret RSA key in PKCS#1 or PKCS#8 format. * gpgsm: Improved handling of re-issued CA certificates. * agent: The included ssh agent does now support ECDSA keys. * agent: New option --enable-putty-support to allow gpg-agent on Windows to act as a Pageant replacement with full smartcard support. * scdaemon: New option --enable-pinpad-varlen. * scdaemon: Various fixes for pinpad equipped card readers. * scdaemon: Rename option --disable-pinpad (was --disable-keypad). * scdaemon: Better support fo CCID readers. Now, internal CCID driver supports readers with no auto configuration feature. * dirmngr: Removed support for the original HKP keyserver which is not anymore used by any site. * dirmngr: Improved support for keyserver pools. * tools: New option --dirmngr for gpg-connect-agent. * The GNU Pth library has been replaced by the new nPth library. * Support installation as portable application under Windows. * All kind of other improvements - see the git log. [Noteworthy changes in version 2.1.0beta3 (2011-12-20)] * gpg: Fixed regression in the secret key export function. * gpg: Allow generation of card keys up to 4096 bit. * gpgsm: Preliminary support for the validation model "steed". * gpgsm: Improved certificate creation. * agent: Support the SSH confirm flag. * agent: New option to select a passphrase mode. The loopback mode may be used to bypass Pinentry. * agent: The Assuan commands KILLAGENT and KILLSCD are working again. * scdaemon: Does not anymore block after changing a card (regression fix). * tools: gpg-connect-agent does now proberly display the help output for "SCD HELP" commands. [Noteworthy changes in version 2.1.0beta2 (2011-03-08)] * gpg: ECC support as described by draft-jivsov-openpgp-ecc-06.txt [Update: now known as RFC-6637]. * gpg: Print "AES128" instead of "AES". This change introduces a little incompatibility for tools using "gpg --list-config". We hope that these tools are written robust enough to accept this new algorithm name as well. * gpgsm: New feature to create certificates from a parameter file. Add prompt to the --gen-key UI to create self-signed certificates. * agent: TMPDIR is now also honored when creating a socket using the --no-standard-socket option and with symcryptrun's temp files. * scdaemon: Fixed a bug where scdaemon sends a signal to gpg-agent running in non-daemon mode. * dirmngr: Fixed CRL loading under W32 (bug#1010). * Dirmngr has taken over the function of the keyserver helpers. Thus we now have a specified direct interface to keyservers via Dirmngr. LDAP, DNS and mail backends are not yet implemented. * Fixed TTY management for pinentries and session variable update problem. [Noteworthy changes in version 2.1.0beta1 (2010-10-26)] * gpg: secring.gpg is not anymore used but all secret key operations are delegated to gpg-agent. The import command moves secret keys to the agent. * gpg: The OpenPGP import command is now able to merge secret keys. * gpg: Encrypted OpenPGP messages with trailing data (e.g. other OpenPGP packets) are now correctly parsed. * gpg: Given sufficient permissions Dirmngr is started automagically. * gpg: Fixed output of "gpgconf --check-options". * gpg: Removed options --export-options(export-secret-subkey-passwd) and --simple-sk-checksum. * gpg: New options --try-secret-key. * gpg: Support DNS lookups for SRV, PKA and CERT on W32. * gpgsm: The --audit-log feature is now more complete. * gpgsm: The default for --include-cert is now to include all certificates in the chain except for the root certificate. * gpgsm: New option --ignore-cert-extension. * g13: The G13 tool for disk encryption key management has been added. * agent: If the agent's --use-standard-socket option is active, all tools try to start and daemonize the agent on the fly. In the past this was only supported on W32; on non-W32 systems the new configure option --disable-standard-socket may now be used to disable this new default. * agent: New and changed passphrases are now created with an iteration count requiring about 100ms of CPU work. * dirmngr: Dirmngr is now a part of this package. It is now also expected to run as a system service and the configuration directories are changed to the GnuPG name space. [Update: 2.1.0 starts dirmngr on demand as user daemon.] * Support for Windows CE. [Update: This has not been tested for the 2.1.0 release] * Numerical values may now be used as an alternative to the debug-level keywords. Version 2.0.28 (2015-06-02) Version 2.0.27 (2015-02-18) Version 2.0.26 (2014-08-12) Version 2.0.25 (2014-06-30) Version 2.0.24 (2014-06-24) Version 2.0.23 (2014-06-03) Version 2.0.22 (2013-10-04) Version 2.0.21 (2013-08-19) Version 2.0.20 (2013-05-10) Version 2.0.19 (2012-03-27) Version 2.0.18 (2011-08-04) Version 2.0.17 (2011-01-13) Version 2.0.16 (2010-07-19) Version 2.0.15 (2010-03-09) Version 2.0.14 (2009-12-21) Noteworthy changes in version 2.0.13 (2009-09-04) ------------------------------------------------- * GPG now generates 2048 bit RSA keys by default. The default hash algorithm preferences has changed to prefer SHA-256 over SHA-1. 2048 bit DSA keys are now generated to use a 256 bit hash algorithm * The envvars XMODIFIERS, GTK_IM_MODULE and QT_IM_MODULE are now passed to the Pinentry to make SCIM work. * The GPGSM command --gen-key features a --batch mode and implements all features of gpgsm-gencert.sh in standard mode. * New option --re-import for GPGSM's IMPORT server command. * Enhanced writing of existing keys to OpenPGP v2 cards. * Add hack to the internal CCID driver to allow the use of some Omnikey based card readers with 2048 bit keys. * GPG now repeatly asks the user to insert the requested OpenPGP card. This can be disabled with --limit-card-insert-tries=1. * Minor bug fixes. Noteworthy changes in version 2.0.12 (2009-06-17) ------------------------------------------------- * GPGSM now always lists ephemeral certificates if specified by fingerprint or keygrip. * New command "KEYINFO" for GPG_AGENT. GPGSM now also returns information about smartcards. * Made sure not to leak file descriptors if running gpg-agent with a command. Restore the signal mask to solve a problem in Mono. * Changed order of the confirmation questions for root certificates and store negative answers in trustlist.txt. * Better synchronization of concurrent smartcard sessions. * Support 2048 bit OpenPGP cards. * Support Telesec Netkey 3 cards. * The gpg-protect-tool now uses gpg-agent via libassuan. Under Windows the Pinentry will now be put into the foreground. * Changed code to avoid a possible Mac OS X system freeze. Noteworthy changes in version 2.0.11 (2009-03-03) ------------------------------------------------- * Fixed a problem in SCDAEMON which caused unexpected card resets. * SCDAEMON is now aware of the Geldkarte. * The SCDAEMON option --allow-admin is now used by default. * GPGCONF now restarts SCdaemon if necessary. * The default cipher algorithm in GPGSM is now again 3DES. This is due to interoperability problems with Outlook 2003 which still can't cope with AES. Noteworthy changes in version 2.0.10 (2009-01-12) ------------------------------------------------- * [gpg] New keyserver helper gpg2keys_kdns as generic DNS CERT lookup. Run with --help for a short description. Requires the ADNS library. * [gpg] New mechanisms "local" and "nodefault" for --auto-key-locate. Fixed a few problems with this option. * [gpg] New command --locate-keys. * [gpg] New options --with-sig-list and --with-sig-check. * [gpg] The option "-sat" is no longer an alias for --clearsign. * [gpg] The option --fixed-list-mode is now implicitly used and obsolete. * [gpg] New control statement %ask-passphrase for the unattended key generation. * [gpg] The algorithm to compute the SIG_ID status has been changed. * [gpgsm] Now uses AES by default. * [gpgsm] Made --output option work with --export-secret-key-p12. * [gpg-agent] Terminate process if the own listening socket is not anymore served by ourself. * [scdaemon] Made it more robust on W32. * [gpg-connect-agent] Accept commands given as command line arguments. * [w32] Initialized the socket subsystem for all keyserver helpers. * [w32] The sysconf directory has been moved from a subdirectory of the installation directory to %CSIDL_COMMON_APPDATA%/GNU/etc/gnupg. * [w32] The gnupg2.nls directory is not anymore used. The standard locale directory is now used. * [w32] Fixed a race condition between gpg and gpgsm in the use of temporary file names. * The gpg-preset-passphrase mechanism works again. An arbitrary string may now be used for a custom cache ID. * Admin PINs are cached again (bug in 2.0.9). * Support for version 2 OpenPGP cards. * Libgcrypt 1.4 is now required. Noteworthy changes in version 2.0.9 (2008-03-26) ------------------------------------------------ * Gpgsm always tries to locate missing certificates from a running Dirmngr's cache. * Tweaks for Windows. * The Admin PIN for OpenPGP cards may now be entered with the pinpad. * Improved certificate chain construction. * Extended the PKITS framework. * Fixed a bug in the ambigious name detection. * Fixed possible memory corruption while importing OpenPGP keys (bug introduced with 2.0.8). [CVE-2008-1530] * Minor bug fixes. Noteworthy changes in version 2.0.8 (2007-12-20) ------------------------------------------------ * Enhanced gpg-connect-agent with a small scripting language. * New option --list-config for gpgconf. * Fixed a crash in gpgconf. * Gpg-agent now supports the passphrase quality bar of the latest Pinentry. * The envvars XAUTHORITY and PINENTRY_USER_DATA are now passed to the Pinentry. * Fixed the auto creation of the key stub for smartcards. * Fixed a rare bug in decryption using the OpenPGP card. * Creating DSA2 keys is now possible. * New option --extra-digest-algo for gpgsm to allow verification of broken signatures. * Allow encryption with legacy Elgamal sign+encrypt keys with option --rfc2440. * Windows is now a supported platform. * Made sure that under Windows the file permissions of the socket are taken into account. This required a change of our socket emulation code and changed the IPC protocol under Windows. Noteworthy changes in version 2.0.7 (2007-09-10) ------------------------------------------------ * Fixed encryption problem if duplicate certificates are in the keybox. * Made it work on Windows Vista. Note that the entire Windows port is still considered Beta. * Add new options min-passphrase-nonalpha, check-passphrase-pattern, enforce-passphrase-constraints and max-passphrase-days to gpg-agent. * Add command --check-components to gpgconf. Gpgconf now uses the installed versions of the programs and does not anymore search via PATH for them. Noteworthy changes in version 2.0.6 (2007-08-16) ------------------------------------------------ * GPGSM does now grok --default-key. * GPGCONF is now aware of --default-key and --encrypt-to. * GPGSM does again correctly print the serial number as well the the various keyids. This was broken since 2.0.4. * New option --validation-model and support for the chain-model. * Improved Windows support. Noteworthy changes in version 2.0.5 (2007-07-05) ------------------------------------------------ * Switched license to GPLv3. * Basic support for Windows. Run "./autogen.sh --build-w32" to build it. As usual the mingw cross compiling toolchain is required. * Fixed bug when using the --p12-charset without --armor. * The command --gen-key may now be used instead of the gpgsm-gencert.sh script. * Changed key generation to reveal less information about the machine. Bug fixes for gpg2's card key generation. Noteworthy changes in version 2.0.4 (2007-05-09) ------------------------------------------------ * The server mode key listing commands are now also working for systems without the funopen/fopencookie API. * PKCS#12 import now tries several encodings in case the passphrase was not utf-8 encoded. New option --p12-charset for gpgsm. * Improved the libgcrypt logging support in all modules. Noteworthy changes in version 2.0.3 (2007-03-08) ------------------------------------------------ * By default, do not allow processing multiple plaintexts in a single stream. Many programs that called GnuPG were assuming that GnuPG did not permit this, and were thus not using the plaintext boundary status tags that GnuPG provides. This change makes GnuPG reject such messages by default which makes those programs safe again. --allow-multiple-messages returns to the old behavior. [CVE-2007-1263]. * New --verify-option show-primary-uid-only. * gpgconf may now reads a global configuration file to select which options are changeable by a frontend. The new applygnupgdefaults tool may be used by an admin to set default options for all users. * The PIN pad of the Cherry XX44 keyboard is now supported. The DINSIG and the NKS applications are now also aware of PIN pads. Noteworthy changes in version 2.0.2 (2007-01-31) ------------------------------------------------ * Fixed a serious and exploitable bug in processing encrypted packages. [CVE-2006-6235]. * Added --passphrase-repeat to set the number of times GPG will prompt for a new passphrase to be repeated. This is useful to help memorize a new passphrase. The default is 1 repetition. * Using a PIN pad does now also work for the signing key. * A warning is displayed by gpg-agent if a new passphrase is too short. New option --min-passphrase-len defaults to 8. * The status code BEGIN_SIGNING now shows the used hash algorithms. Noteworthy changes in version 2.0.1 (2006-11-28) ------------------------------------------------ * Experimental support for the PIN pads of the SPR 532 and the Kaan Advanced card readers. Add "disable-keypad" scdaemon.conf if you don't want it. Does currently only work for the OpenPGP card and its authentication and decrypt keys. * Fixed build problems on some some platforms and crashes on amd64. * Fixed a buffer overflow in gpg2. [bug#728,CVE-2006-6169] Noteworthy changes in version 2.0.0 (2006-11-11) ------------------------------------------------ * First stable version of a GnuPG integrating OpenPGP and S/MIME. Noteworthy changes in version 1.9.95 (2006-11-06) ------------------------------------------------- * Minor bug fixes. Noteworthy changes in version 1.9.94 (2006-10-24) ------------------------------------------------- * Keys for gpgsm may now be specified using a keygrip. A keygrip is indicated by a prefixing it with an ampersand. * gpgconf now supports switching the CMS cipher algo (e.g. to AES). * New command --gpgconf-test for all major tools. This may be used to check whether the configuration file is sane. Noteworthy changes in version 1.9.93 (2006-10-18) ------------------------------------------------- * In --with-validation mode gpgsm will now also ask whether a root certificate should be trusted. * Link to Pth only if really necessary. * Fixed a pubring corruption bug in gpg2 occurring when importing signatures or keys with insane lengths. * Fixed v3 keyID calculation bug in gpg2. * More tweaks for certificates without extensions. Noteworthy changes in version 1.9.92 (2006-10-11) ------------------------------------------------- * Bug fixes. Noteworthy changes in version 1.9.91 (2006-10-04) ------------------------------------------------- * New "relax" flag for trustlist.txt to allow root CA certificates without BasicContraints. * [gpg2] Removed the -k PGP 2 compatibility hack. -k is now an alias for --list-keys. * [gpg2] Print a warning if "-sat" is used instead of "--clearsign". Noteworthy changes in version 1.9.90 (2006-09-25) ------------------------------------------------- * Made readline work for gpg. * Cleanups und minor bug fixes. * Included translations from gnupg 1.4.5. Noteworthy changes in version 1.9.23 (2006-09-18) ------------------------------------------------- * Regular man pages for most tools are now build directly from the Texinfo source. * The gpg code from 1.4.5 has been fully merged into this release. The configure option --enable-gpg is still required to build this gpg part. For production use of OpenPGP the gpg version 1.4.5 is still recommended. Note, that gpg will be installed under the name gpg2 to allow coexisting with an 1.4.x gpg. * API change in gpg-agent's pkdecrypt command. Thus an older gpgsm may not be used with the current gpg-agent. * The scdaemon will now call a script on reader status changes. * gpgsm now allows file descriptor passing for "INPUT", "OUTPUT" and "MESSAGE". * The gpgsm server may now output a key listing to the output file handle. This needs to be enabled using "OPTION list-to-output=1". * The --output option of gpgsm has now an effect on list-keys. * New gpgsm commands --dump-chain and list-chain. * gpg-connect-agent has new options to utilize descriptor passing. * A global trustlist may now be used. See doc/examples/trustlist.txt. * When creating a new pubring.kbx keybox common certificates are imported. Noteworthy changes in version 1.9.22 (2006-07-27) ------------------------------------------------- * Enhanced pkcs#12 support to allow import from simple keyBags. * Exporting to pkcs#12 now create bag attributes so that Mozilla is able to import the files. * Fixed uploading of certain keys to the smart card. Noteworthy changes in version 1.9.21 (2006-06-20) ------------------------------------------------- * New command APDU for scdaemon to allow using it for general card access. Might be used through gpg-connect-agent by using the SCD prefix command. * Support for the CardMan 4040 PCMCIA reader (Linux 2.6.15 required). * Scdaemon does not anymore reset cards at the end of a connection. * Kludge to allow use of Bundesnetzagentur issued X.509 certificates. * Added --hash=xxx option to scdaemon's PKSIGN command. * Pkcs#12 files are now created with a MAC. This is for better interoperability. * Collected bug fixes and minor other changes. Noteworthy changes in version 1.9.20 (2005-12-20) ------------------------------------------------- * Importing pkcs#12 files created be recent versions of Mozilla works again. * Basic support for qualified signatures. * New debug tool gpgparsemail. Noteworthy changes in version 1.9.19 (2005-09-12) ------------------------------------------------- * The Belgian eID card is now supported for signatures and ssh. Other pkcs#15 cards should work as well. * Fixed bug in --export-secret-key-p12 so that certificates are again included. Noteworthy changes in version 1.9.18 (2005-08-01) ------------------------------------------------- * [gpgsm] Now allows for more than one email address as well as URIs and dnsNames in certificate request generation. A keygrip may be given to create a request from an existing key. * A couple of minor bug fixes. Noteworthy changes in version 1.9.17 (2005-06-20) ------------------------------------------------- * gpg-connect-agent has now features to handle Assuan INQUIRE commands. * Internal changes for OpenPGP cards. New Assuan command WRITEKEY. * GNU Pth is now a hard requirement. * [scdaemon] Support for OpenSC has been removed. Instead a new and straightforward pkcs#15 modules has been written. As of now it does allows only signing using TCOS cards but we are going to enhance it to match all the old capabilities. * [gpg-agent] New option --write-env-file and Assuan command UPDATESTARTUPTTY. * [gpg-agent] New option --default-cache-ttl-ssh to set the TTL for SSH passphrase caching independent from the other passphrases. Noteworthy changes in version 1.9.16 (2005-04-21) ------------------------------------------------- * gpg-agent does now support the ssh-agent protocol and thus allows to use the pinentry as well as the OpenPGP smartcard with ssh. * New tool gpg-connect-agent as a general client for the gpg-agent. * New tool symcryptrun as a wrapper for certain encryption tools. * The gpg tool is not anymore build by default because those gpg versions available in the gnupg 1.4 series are far more matured. Noteworthy changes in version 1.9.15 (2005-01-13) ------------------------------------------------- * Fixed passphrase caching bug. * Better support for CCID readers; the reader from Cherry RS 6700 USB does now work. Noteworthy changes in version 1.9.14 (2004-12-22) ------------------------------------------------- * [gpg-agent] New option --use-standard-socket to allow the use of a fixed socket. gpgsm falls back to this socket if GPG_AGENT_INFO has not been set. * Ported to MS Windows with some functional limitations. * New tool gpg-preset-passphrase. Noteworthy changes in version 1.9.13 (2004-12-03) ------------------------------------------------- * [gpgsm] New option --prefer-system-dirmngr. * Minor cleanups and debugging aids. Noteworthy changes in version 1.9.12 (2004-10-22) ------------------------------------------------- * [scdaemon] Partly rewrote the PC/SC code. * Removed the sc-investigate tool. It is now in a separate package available at ftp://ftp.g10code.com/g10code/gscutils/ . * [gpg-agent] Fixed logging problem. Noteworthy changes in version 1.9.11 (2004-10-01) ------------------------------------------------- * When using --import along with --with-validation, the imported certificates are validated and only imported if they are fully valid. * [gpg-agent] New option --max-cache-ttl. * [gpg-agent] When used without --daemon or --server, gpg-agent now check whether a agent is already running and usable. * Fixed some i18n problems. Noteworthy changes in version 1.9.10 (2004-07-22) ------------------------------------------------- * Fixed a serious bug in the checking of trusted root certificates. * New configure option --enable-agent-pnly allows to build and install just the agent. * Fixed a problem with the log file handling. Noteworthy changes in version 1.9.9 (2004-06-08) ------------------------------------------------ * [gpg-agent] The new option --allow-mark-trusted is now required to allow gpg-agent to add a key to the trustlist.txt after user confirmation. * Creating PKCS#10 requests does now honor the key usage. Noteworthy changes in version 1.9.8 (2004-04-29) ------------------------------------------------ * [scdaemon] Overhauled the internal CCID driver. * [scdaemon] Status files named ~/.gnupg/reader_.status are now written when using the internal CCID driver. * [gpgsm] New commands --dump-{,secret,external}-keys to show a very detailed view of the certificates. * The keybox gets now compressed after 3 hours and ephemeral stored certificates are deleted after about a day. * [gpg] Usability fixes for --card-edit. Note, that this has already been ported back to gnupg-1.3 Noteworthy changes in version 1.9.7 (2004-04-06) ------------------------------------------------ * Instrumented the modules for gpgconf. * Added support for DINSIG card applications. * Include the smimeCapabilities attribute with signed messages. * Now uses the gettext domain "gnupg2" to avoid conflicts with gnupg versions < 1.9. Noteworthy changes in version 1.9.6 (2004-03-06) ------------------------------------------------ * Code cleanups and bug fixes. Noteworthy changes in version 1.9.5 (2004-02-21) ------------------------------------------------ * gpg-protect-tool gets now installed into libexec as it ought to be. Cleaned up the build system to better comply with the coding standards. * [gpgsm] The --import command is now able to autodetect pkcs#12 files and import secret and private keys from this file format. A new command --export-secret-key-p12 is provided to allow exporting of secret keys in PKCS\#12 format. * [gpgsm] The pinentry will now present a description of the key for whom the passphrase is requested. * [gpgsm] New option --with-validation to check the validity of key while listing it. * New option --debug-level={none,basic,advanced,expert,guru} to map the debug flags to sensitive levels on a per program base. Noteworthy changes in version 1.9.4 (2004-01-30) ------------------------------------------------ * Added support for the Telesec NKS 2.0 card application. * Added simple tool addgnupghome to create .gnupg directories from /etc/skel/.gnupg. * Various minor bug fixes and cleanups; mainly gpgsm and gpg-agent related. Noteworthy changes in version 1.9.3 (2003-12-23) ------------------------------------------------ * New gpgsm options --{enable,disable}-ocsp to validate keys using OCSP. This option requires a not yet released DirMngr version. Default is disabled. * The --log-file option may now be used to print logs to a socket. Prefix the socket name with "socket://" to enable this. This does not work on all systems and falls back to stderr if there is a problem with the socket. * The options --encrypt-to and --no-encrypt-to now work the same in gpgsm as in gpg. Note, they are also used in server mode. * Duplicated recipients are now silently removed in gpgsm. Noteworthy changes in version 1.9.2 (2003-11-17) ------------------------------------------------ * On card key generation is no longer done using the --gen-key command but from the menu provided by the new --card-edit command. * PINs are now properly cached and there are only 2 PINs visible. The 3rd PIN (CHV2) is internally syncronized with the regular PIN. * All kind of other internal stuff. Noteworthy changes in version 1.9.1 (2003-09-06) ------------------------------------------------ * Support for OpenSC is back. scdaemon supports a --disable-opensc to disable OpenSC use at runtime, so that PC/SC or ct-API can still be used directly. * Rudimentary support for the SCR335 smartcard reader using an internal driver. Requires current libusb from CVS. * Bug fixes. Noteworthy changes in version 1.9.0 (2003-08-05) ------------------------------------------------ ====== PLEASE SEE README-alpha ======= * gpg has been renamed to gpg2 and gpgv to gpgv2. This is a temporary change to allow co-existing with stable gpg versions. * ~/.gnupg/gpg.conf-1.9.0 is fist tried as config file before the usual gpg.conf. * Removed the -k, -kv and -kvv commands. -k is now an alias to --list-keys. New command -K as alias for --list-secret-keys. * Removed --run-as-shm-coprocess feature. * gpg does now also use libgcrypt, libgpg-error is required. * New gpgsm commands --call-dirmngr and --call-protect-tool. * Changing a passphrase is now possible using "gpgsm --passwd" * The content-type attribute is now recognized and created. * The agent does now reread certain options on receiving a HUP. * The pinentry is now forked for each request so that clients with different environments are supported. When running in daemon mode and --keep-display is not used the DISPLAY variable is ignored. * Merged stuff from the newpg branch and started this new development branch. Version 1.4.19 (2015-02-27) Version 1.4.18 (2014-06-30) Version 1.4.17 (2014-06-23) Version 1.4.16 (2013-12-18) Version 1.4.15 (2013-10-04) Version 1.4.14 (2013-07-25) Version 1.4.13 (2012-12-20) Version 1.4.12 (2012-01-30) Version 1.4.11 (2010-10-18) Version 1.4.10 (2009-09-02) Version 1.4.9 (2008-03-26) Version 1.4.8 (2007-12-20) Version 1.4.7 (2007-03-05) Version 1.4.6 (2006-12-06) Version 1.4.5 (2006-08-01) Version 1.4.4 (2006-06-25) Version 1.4.3 (2006-04-03) Version 1.4.2 (2005-07-26) Version 1.4.1 (2005-03-15) Version 1.4.0 (2004-12-16) Noteworthy changes in version 1.3.2 (2003-05-27) ------------------------------------------------ * New "--gnupg" option (set by default) that disables --openpgp, and the various --pgpX emulation options. This replaces --no-openpgp, and --no-pgpX, and also means that GnuPG has finally grown a --gnupg option to make GnuPG act like GnuPG. * A bug in key validation has been fixed. This bug only affects keys with more than one user ID (photo IDs do not count here), and results in all user IDs on a given key being treated with the validity of the most-valid user ID on that key. * Notation names that do not contain a '@' are no longer allowed unless --expert is set. This is to help prevent pollution of the (as yet unused) IETF notation namespace. * Multiple trust models are now supported via the --trust-model option. The options are "pgp" (web-of-trust plus trust signatures), "classic" (web-of-trust only), and "always" (identical to the --always-trust option). * The --personal-{cipher|digest|compression}-preferences are now consulted to get default algorithms before resorting to the last-ditch defaults of --s2k-cipher-algo, SHA1, and ZIP respectively. This allows a user to set algorithms to use in a safe manner so they are used when legal to do so, without forcing them on for all messages. * New --primary-keyring option to designate the keyring that the user wants new keys imported into. * --s2k-digest-algo is now used for all password mangling. Earlier versions used both --s2k-digest-algo and --digest-algo for passphrase mangling. * Handling of --hidden-recipient or --throw-keyid messages is now easier - the user only needs to give their passphrase once, and GnuPG will try it against all of the available secret keys. * Care is taken to prevent compiler optimization from removing memory wiping code. * New option --no-mangle-dos-filenames so that filenames are not truncated in the W32 version. * A "convert-from-106" script has been added. This is a simple script that automates the conversion from a 1.0.6 or earlier version of GnuPG to a 1.0.7 or later version. * Disabled keys are now skipped when selecting keys for encryption. If you are using the --with-colons key listings to detect disabled keys, please see doc/DETAILS for a minor format change in this release. * Minor trustdb changes to make the trust calculations match common usage. * New command "revuid" in the --edit-key menu to revoke a user ID. This is a simpler interface to the old method (which still works) of revoking the user ID self-signature. * Status VALIDSIG does now also print the primary key's fingerprint, as well as the signature version, pubkey algorithm, hash algorithm, and signature class. * Add read-only support for the SHA-256 hash, and optional read-only support for the SHA-384 and SHA-512 hashes. * New option --enable-progress-filter for use with frontends. * DNS SRV records are used in HKP keyserver lookups to allow administrators to load balance and select keyserver ports automatically. This is as specified in draft-shaw-openpgp-hkp-00.txt. * When using the "keyid!" syntax during a key export, only that specified key is exported. If the key in question is a subkey, the primary key plus only that subkey is exported. * configure --disable-xxx options to disable individual algorithms at build time. This can be used to build a smaller gpg binary for embedded uses where space is tight. See the README file for the algorithms that can be used with this option, or use --enable-minimal to build the smallest gpg possible (disables all optional algorithms, disables keyserver access, and disables photo IDs). * The keyserver no-modify flag on a key can now be displayed and modified. * Note that the TIGER/192 digest algorithm is in the process of being dropped from the OpenPGP standard. While this release of GnuPG still contains it, it is disabled by default. To ensure you will still be able to use your messages with future versions of GnuPG and other OpenPGP programs, please do not use this algorithm. Noteworthy changes in version 1.3.1 (2002-11-12) ------------------------------------------------ * Trust signature support. This is based on the Maurer trust model where a user can specify the trust level along with the signature with multiple levels so users can delegate certification ability to other users, possibly restricted by a regular expression on the user ID. Note that full trust signature support requires a regular expression parsing library. The regexp code from glibc 2.3.1 is included for those platforms that don't have working regexp functions available. The configure option --disable-regex may be used to disable any regular expression code, which will make GnuPG ignore any trust signature with a regular expression included. * Two new commands --hidden-recipient (-R) and --hidden-encrypt-to encrypt to a user, but hide the identity of that user. This is the same functionality as --throw-keyid, but can be used on a per-user basis. * Full algorithm names (e.g. "3DES", "SHA1", "ZIP") can now be used interchangeably with the short algorithm names (e.g. "S2", "H2", "Z1") anywhere algorithm names are used in GnuPG. Noteworthy changes in version 1.3.0 (2002-10-18) ------------------------------------------------ * The last piece of internal keyserver support has been removed, and now all keyserver access is done via the keyserver plugins. There is also a newer keyserver protocol used between GnuPG and the plugins, so plugins from earlier versions of GnuPG may not work properly. * The HKP keyserver plugin supports the new machine-readable key listing format for those keyservers that provide it. * When using a HKP keyserver with multiple DNS records (such as wwwkeys.pgp.net which has the addresses of multiple servers around the world), try all records until one succeeds. Note that it depends on the LDAP library used whether the LDAP keyserver plugin does this as well. * The library dependencies for OpenLDAP seem to change fairly frequently, and GnuPG's configure script cannot guess all the combinations. Use ./configure LDAPLIBS="-L libdir -l libs" to override the script and use the libraries selected. * Secret keys generated with --export-secret-subkeys are now indicated in key listings with a '#' after the "sec", and in --with-colons listings by showing no capabilities (no lowercase characters). * --trusted-key has been un-obsoleted, as it is useful for adding ultimately trusted keys from the config file. It is identical to using --edit and "trust" to change a key to ultimately trusted. * Translations other than de are no longer distributed with the development branch. This is due to the frequent text changes during development, which cause the translations to rapidly go out of date. Version 1.2.8 (2006-12-07) Version 1.2.7 (2004-12-27) Version 1.2.6 (2004-08-25) Version 1.2.5 (2004-07-26) Version 1.2.4 (2003-12-23) Version 1.2.3 (2003-08-21) Version 1.2.2 (2003-05-01) Version 1.2.1 (2002-10-25) Version 1.2.0 (2002-09-21) Noteworthy changes in version 1.1.92 (2002-09-11) ------------------------------------------------- * [IMPORTANT] The default configuration file is now ~/.gnupg/gpg.conf. If an old ~/.gnupg/options is found it will still be used. This change is required to have a more consistent naming scheme with forthcoming tools. * The use of MDCs have increased. A MDC will be used if the recipients directly request it, if the recipients have AES, AES192, AES256, or TWOFISH in their cipher preferences, or if the chosen cipher has a blocksize not equal to 64 bits (currently this is also AES, AES192, AES256, and TWOFISH). * GnuPG will no longer automatically disable compression when processing an already-compressed file unless a MDC is being used. This is to give the message a certain amount of resistance to the chosen-ciphertext attack while communicating with other programs (most commonly PGP earlier than version 7.x) that do not support MDCs. * The option --interactive now has the desired effect when importing keys. * The file permission and ownership checks on files have been clarified. Specifically, the homedir (usually ~/.gnupg) is checked to protect everything within it. If the user specifies keyrings outside this homedir, they are presumed to be shared keyrings and therefore *not* checked. Configuration files specified with the --options option and the IDEA cipher extension specified with --load-extension are checked, along with their enclosing directories. * The configure option --with-static-rnd=auto allows to build gpg with all available entropy gathering modules included. At runtime the best usable one will be selected from the list linux, egd, unix. This is also the default for systems lacking a /dev/random device. * The default character set is now taken from the current locale; it can still be overridden by the --charset option. Using the option -vvv shows the used character set. * [REMOVED] --emulate-checksum-bug and --emulate-3des-s2k-bug have been removed. Noteworthy changes in version 1.1.91 (2002-08-04) ------------------------------------------------- * All modules are now linked statically; the --load-extension option is in general not useful anymore. The only exception is to specify the deprecated idea cipher. * The IDEA plugin has changed. Previous versions of the IDEA plugin will no longer work with GnuPG. However, the current version of the plugin will work with earlier GnuPG versions. * When using --batch with one of the --delete-key commands, the key must be specified by fingerprint. See the man page for details. * There are now various ways to restrict the ability GnuPG has to exec external programs (for the keyserver helpers or photo ID viewers). Read the README file for the complete list. * New export option to leave off attribute packets (photo IDs) during export. This is useful when exporting to HKP keyservers which do not understand attribute packets. * New import option to repair during import the HKP keyserver mangling multiple subkeys bug. Note that this cannot completely repair the damaged key as some crucial data is removed by the keyserver, but it does at least give you back one subkey. This is on by default for keyserver --recv-keys, and off by default for regular --import. * The keyserver helper programs now live in /usr/[local/]libexec/gnupg by default. If you are upgrading from 1.0.7, you might want to delete your old copies in /usr/[local/]bin. If you use an OS that does not use libexec for whatever reason, use configure --libexecdir=/usr/local/lib to place the keyserver helpers there. * The LDAP keyserver handler now works properly with very old (version 1) LDAP keyservers. Noteworthy changes in version 1.1.90 (2002-07-01) ------------------------------------------------- * New commands: --personal-cipher-preferences, --personal-digest-preferences, and --personal-compress-preferences allow the user to specify which algorithms are to be preferred. Note that this does not permit using an algorithm that is not present in the recipient's preferences (which would violate the OpenPGP standard). This just allows sorting the preferences differently. * New "group" command to refer to several keys with one name. * A warning is issued if the user forces the use of an algorithm that is not listed in the recipient's preferences. * Full revocation key (aka "designated revoker") support. * The preferred hash algorithms on a key are consulted when encrypting a signed message to that key. Note that this is disabled by default by a SHA1 preference in --personal-digest-preferences. * --cert-digest-algo allows the user to specify the hash algorithm to use when signing a key rather than the default SHA1 (or MD5 for PGP2 keys). Do not use this feature unless you fully understand the implications of this. * --pgp7 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 7.x. * New --attribute-fd command for frontends and scripts to get the contents of attribute packets (i.e. photos) * In expert mode, the user can now re-sign a v3 key with a v4 self-signature. This does not change the v3 key into a v4 key, but it does allow the user to use preferences, primary ID flags, etc. * Significantly improved photo ID support on non-unixlike platforms. * The version number has jumped ahead to 1.1.90 to skip over the old version 1.1 and to get ready for the upcoming 1.2. * ElGamal sign and encrypt is not anymore allowed in the key generation dialog unless in expert mode. RSA sign and encrypt has been added with the same restrictions. * [W32] Keyserver access does work with Windows NT. Noteworthy changes in version 1.0.7 (2002-04-29) ------------------------------------------------ * Secret keys are now stored and exported in a new format which uses SHA-1 for integrity checks. This format renders the Rosa/Klima attack useless. Other OpenPGP implementations might not yet support this, so the option --simple-sk-checksum creates the old vulnerable format. * The default cipher algorithm for encryption is now CAST5, default hash algorithm is SHA-1. This will give us better interoperability with other OpenPGP implementations. * Symmetric encrypted messages now use a fixed file size if possible. This is a tradeoff: it breaks PGP 5, but fixes PGP 2, 6, and 7. Note this was only an issue with RFC-1991 style symmetric messages. * Photographic user ID support. This uses an external program to view the images. * Enhanced keyserver support via keyserver "plugins". GnuPG comes with plugins for the NAI LDAP keyserver as well as the HKP email keyserver. It retains internal support for the HKP HTTP keyserver. * Nonrevocable signatures are now supported. If a user signs a key nonrevocably, this signature cannot be taken back so be careful! * Multiple signature classes are usable when signing a key to specify how carefully the key information (fingerprint, photo ID, etc) was checked. * --pgp2 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 2.x. * --pgp6 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 6.x. * Signatures may now be given an expiration date. When signing a key with an expiration date, the user is prompted whether they want their signature to expire at the same time. * Revocation keys (designated revokers) are now supported if present. There is currently no way to designate new keys as designated revokers. * Permissions on the .gnupg directory and its files are checked for safety. * --expert mode enables certain silly things such as signing a revoked user id, expired key, or revoked key. * Some fixes to build cleanly under Cygwin32. * New tool gpgsplit to split OpenPGP data formats into packets. * New option --preserve-permissions. * Subkeys created in the future are not used for encryption or signing unless the new option --ignore-valid-from is used. * Revoked user-IDs are not listed unless signatures are listed too or we are in verbose mode. * There is no default comment string with ascii armors anymore except for revocation certificates and --enarmor mode. * The command "primary" in the edit menu can be used to change the primary UID, "setpref" and "updpref" can be used to change the preferences. * Fixed the preference handling; since 1.0.5 they were erroneously matched against against the latest user ID and not the given one. * RSA key generation. * Merged Stefan's patches for RISC OS in. See comments in scripts/build-riscos. * It is now possible to sign and conventional encrypt a message (-cs). * The MDC feature flag is supported and can be set by using the "updpref" edit command. * The status messages GOODSIG and BADSIG are now returning the primary UID, encoded using %XX escaping (but with spaces left as spaces, so that it should not break too much) * Support for GDBM based keyrings has been removed. * The entire keyring management has been revamped. * The way signature stati are store has changed so that v3 signatures can be supported. To increase the speed of many operations for existing keyrings you can use the new --rebuild-keydb-caches command. * The entire key validation process (trustdb) has been revamped. See the man page entries for --update-trustdb, --check-trustdb and --no-auto-check-trustdb. * --trusted-keys is again obsolete, --edit can be used to set the ownertrust of any key to ultimately trusted. * A subkey is never used to sign keys. * Read only keyrings are now handled as expected. Noteworthy changes in version 1.0.6 (2001-05-29) ------------------------------------------------ * Security fix for a format string bug in the tty code. * Fixed format string bugs in all PO files. * Removed Russian translation due to too many bugs. The FTP server has an unofficial but better translation in the contrib directory. * Fixed expire time calculation and keyserver access. * The usual set of minor bug fixes and enhancements. * non-writable keyrings are now correctly handled. Noteworthy changes in version 1.0.5 (2001-04-29) ------------------------------------------------ * WARNING: The semantics of --verify have changed to address a problem with detached signature detection. --verify now ignores signed material given on stdin unless this is requested by using a "-" as the name for the file with the signed material. Please check all your detached signature handling applications and make sure that they don't pipe the signed material to stdin without using a filename together with "-" on the the command line. * WARNING: Corrected hash calculation for input data larger than 512M - it was just wrong, so you might notice bad signature in some very big files. It may be wise to keep an old copy of GnuPG around. * Secret keys are no longer imported unless you use the new option --allow-secret-key-import. This is a kludge and future versions will handle it in another way. * New command "showpref" in the --edit-key menu to show an easier to understand preference listing. * There is now the notation of a primary user ID. For example, it is printed with a signature verification as the first user ID; revoked user IDs are not printed there anymore. In general the primary user ID is the one with the latest self-signature. * New --charset=utf-8 to bypass all internal conversions. * Large File Support (LFS) is now working. * New options: --ignore-crc-error, --no-sig-create-check, --no-sig-cache, --fixed-list-mode, --no-expensive-trust-checks, --enable-special-filenames and --use-agent. See man page. * New command --pipemode, which can be used to run gpg as a co-process. Currently only the verification of detached signatures are working. See doc/DETAILS. * Keyserver support for the W32 version. * Rewritten key selection code so that GnuPG can better cope with multiple subkeys, expire dates and so. The drawback is that it is slower. * A whole lot of bug fixes. * The verification status of self-signatures are now cached. To increase the speed of key list operations for existing keys you can do the following in your GnuPG homedir (~/.gnupg): cp pubring.gpg pubring.gpg.save && gpg --export-all >x && \ rm pubring.gpg && gpg --import x Only v4 keys (i.e not the old RSA keys) benefit from this caching. * New translations: Estonian, Turkish. Noteworthy changes in version 1.0.4 (2000-10-17) ------------------------------------------------ * Fixed a serious bug which could lead to false signature verification results when more than one signature is fed to gpg. This is the primary reason for releasing this version. * New utility gpgv which is a stripped down version of gpg to be used to verify signatures against a list of trusted keys. * Rijndael (AES) is now supported and listed with top preference. * --with-colons now works with --print-md[s]. Noteworthy changes in version 1.0.3 (2000-09-18) ------------------------------------------------ * Fixed problems with piping to/from other MS-Windows software * Expiration time of the primary key can be changed again. * Revoked user IDs are now marked in the output of --list-key * New options --show-session-key and --override-session-key to help the British folks to somewhat minimize the danger of this Orwellian RIP bill. * New options --merge-only and --try-all-secrets. * New configuration option --with-egd-socket. * The --trusted-key option is back after it left us with 0.9.5 * RSA is supported. Key generation does not yet work but will come soon. * CAST5 and SHA-1 are now the default algorithms to protect the key and for symmetric-only encryption. This should solve a couple of compatibility problems because the old algorithms are optional according to RFC2440 * Twofish and MDC enhanced encryption is now used. PGP 7 supports this. Older versions of GnuPG don't support it, so they should be upgraded to at least 1.0.2 Noteworthy changes in version 1.0.2 (2000-07-12) ---------------------------------------------- * Fixed expiration handling of encryption keys. * Add an experimental feature to do unattended key generation. * The user is now asked for the reason of revocation as required by the new OpenPGP draft. * There is a ~/.gnupg/random_seed file now which saves the state of the internal RNG and increases system performance somewhat. This way the full entropy source is only used in cases were it is really required. Use the option --no-random-seed-file to disable this feature. * New options --ignore-time-conflict and --lock-never. * Some fixes for the W32 version. * The entropy.dll is not anymore used by the W32 version but replaced by code derived from Cryptlib. * Encryption is now much faster: About 2 times for 1k bit keys and 8 times for 4k keys. * New encryption keys are generated in a way which allows a much faster decryption. * New command --export-secret-subkeys which outputs the the _primary_ key with it's secret parts deleted. This is useful for automated decryption/signature creation as it allows to keep the real secret primary key offline and thereby protecting the key certificates and allowing to create revocations for the subkeys. See the FAQ for a procedure to install such secret keys. * Keygeneration now writes to the first writeable keyring or as default to the one in the homedirectory. Prior versions ignored all --keyring options. * New option --command-fd to take user input from a file descriptor; to be used with --status-fd by software which uses GnuPG as a backend. * There is a new status PROGRESS which is used to show progress during key generation. * Support for the new MDC encryption packets. To create them either --force-mdc must be use or cipher algorithm with a blocksize other than 64 bits is to be used. --openpgp currently disables MDC packets entirely. This option should not yet be used. * New option --no-auto-key-retrieve to disable retrieving of a missing public key from a keyserver, when a keyserver has been set. * Danish translation Noteworthy changes in version 1.0.1 (1999-12-16) ----------------------------------- * New command --verify-files. New option --fast-list-mode. * $http_proxy is now used when --honor-http-proxy is set. * Fixed some minor bugs and the problem with conventional encrypted packets which did use the gpg v3 partial length headers. * Add Indonesian and Portugese translations. * Fixed a bug with symmetric-only encryption using the non-default 3DES. The option --emulate-3des-s2k-bug may be used to decrypt documents which have been encrypted this way; this should be done immediately as this workaround will be remove in 1.1 * Can now handle (but not display) PGP's photo IDs. I don't know the format of that packet but after stripping a few bytes from the start it looks like a JPEG (at least my test data). Handling of this package is required because otherwise it would mix up the self signatures and you can't import those keys. * Passing non-ascii user IDs on the commandline should now work in all cases. * New keys are now generated with an additional preference to Blowfish. * Removed the GNU Privacy Handbook from the distribution as it will go into a separate one. Noteworthy changes in version 1.0.0 (1999-09-07) ----------------------------------- * Add a very preliminary version of the GNU Privacy Handbook to the distribution (lynx doc/gph/index.html). * Changed the version number to GnuPG 2001 ;-) Noteworthy changes in version 0.9.11 (1999-09-03) ------------------------------------ * UTF-8 strings are now correctly printed (if --charset is set correctly). Output of --with-colons remains C-style escaped UTF-8. * Workaround for a problem with PGP 5 detached signature in textmode. * Fixed a problem when importing new subkeys (duplicated signatures). Noteworthy changes in version 0.9.10 (1999-07-23) ------------------------------------ * Some strange new options to help pgpgpg * Cleaned up the dox a bit. Noteworthy changes in version 0.9.9 ----------------------------------- * New options --[no-]utf8-strings. * New edit-menu commands "enable" and "disable" for entire keys. * You will be asked for a filename if gpg cannot deduce one. * Changes to support libtool which is needed for the development of libgcrypt. * New script tools/lspgpot to help transferring assigned trustvalues from PGP to GnuPG. * New commands --lsign-key and made --sign-key a shortcut for --edit and sign. * New options (#122--126 ;-) --[no-]default-recipient[-self], --disable-{cipher,pubkey}-algo. See the man page. * Enhanced info output in case of multiple recipients and fixed exit code. * New option --allow-non-selfsigned-uid to work around a problem with the German IN way of separating signing and encryption keys. Noteworthy changes in version 0.9.8 (1999-06-26) ----------------------------------- * New subcommand "delsig" in the edit menu. * The name of the output file is not anymore the one which is embedded in the processed message, but the used filename with the extension stripped. To revert to the old behaviour you can use the option --use-embedded-filename. * Another hack to cope with pgp2 generated detached signatures. * latin-2 character set works (--charset=iso-8859-2). * New option --with-key-data to list the public key parameters. New option -N to insert notations and a --set-policy-url. A couple of other options to allow reseting of options. * Better support for HPUX. Noteworthy changes in version 0.9.7 (1999-05-23) ----------------------------------- * Add some work arounds for a bugs in pgp 2 which led to bad signatures when used with canonical texts in some cases. * Enhanced some status outputs. Noteworthy changes in version 0.9.6 (1999-05-06) ----------------------------------- * Twofish is now statically linked by default. The experimental 128 bit version is now disabled. Full support will be available as soon as the OpenPGP WG has decided on an interpretation of rfc2440. * Dropped support for the ancient Blowfish160 which is not OpenPGP. * Merged gpgm and gpg into one binary. * Add "revsig" and "revkey" commands to the edit menu. It is now possible to revoke signature and subkeys. Noteworthy changes in version 0.9.5 (1999-03-20) ----------------------------------- * New command "lsign" in the keyedit menu to create non-exportable signatures. Removed --trusted-keys option. * A bunch of changes to the key validation code. * --list-trust-path now has an optional --with-colons format. * New command --recv-keys to import keys from an keyserver. Noteworthy changes in version 0.9.4 (1999-03-08) ----------------------------------- * New configure option --enable-static-rnd=[egd|linux|unix|none] to select a random gathering module for static linking. * The original text is now verbatim copied to a cleartext signed message. * Bugfixes but there are still a couple of bugs. Noteworthy changes in version 0.9.3 (1999-02-19) ----------------------------------- * Changed the internal design of getkey which now allows a efficient lookup of multiple keys and add a word match mode. * New options --[no-]encrypt-to. * Some changes to the configure stuff. Switched to automake 1.4. Removed intl/ from CVS, autogen.sh now uses gettextize. * Preferences now include Twofish. Removed preference to Blowfish with a special hack to suppress the "not listed in preferences" warning; this is to allow us to switch completely to Twofish in the near future. * Changed the locking stuff. * Print all user ids of a good signature. Noteworthy changes in version 0.9.2 (1999-01-01) ----------------------------------- * add some additional time warp checks. * Option --keyserver and command --send-keys to utilize HKP servers. * Upgraded to zlib 1.1.3 and fixed an inflate bug * More cleanup on the cleartext signatures. Noteworthy changes in version 0.9.1 (1999-01-01) ----------------------------------- * Polish language support. * When querying the passphrase, the key ID of the primary key is displayed along with the one of the used secondary key. * Fixed a bug occurring when decrypting pgp 5 encrypted messages, fixed an infinite loop bug in the 3DES code and in the code which looks for trusted signatures. * Fixed a bug in the mpi library which caused signatures not to compare okay. * Rewrote the handling of cleartext signatures; the code is now better maintainable (I hope so). * New status output VALIDSIG only for valid signatures together with the fingerprint of the signer's key. Noteworthy changes in version 0.9.0 (1998-12-23) ----------------------------------- * --export does now only exports rfc2440 compatible keys; the old behaviour is available with --export-all. Generation of v3 ElGamal (sign and encrypt) keys is not longer supported. * Fixed the uncompress bug. * Rewrote the rndunix module. There are two environment variables used for debugging now: GNUPG_RNDUNIX_DBG give the file to write debugging information (use "-" for stdout) and if GNUPG_RNDUNIX_DBGALL is set, all programs which are only tried are also printed. * New option --escape-from-lines to "dash-escape" "From " lines to prevent mailers to change them to ">From ". This is not enabled by default because it is not in compliance with rfc2440 - however, you should turn it on. Noteworthy changes in version 0.4.5 (1998-12-08) ----------------------------------- * The keyrings and the trustdb is now locked, so that other GnuPG processes won't damage these files. You may want to put the option --lock-once into your options file. * The latest self-signatures are now used; this enables --import to see updated preferences etc. * Import of subkeys should now work. * Random gathering modules may now be loaded as extensions. Add such a module for most Unices but it is very experimental! * Brazilian language support. Noteworthy changes in version 0.4.4 (1998-11-20) ----------------------------------- * Fixed the way the key expiration time is stored. If you have an expiration time on your key you should fix it with --edit-key and the command "expire". I apologize for this inconvenience. * Add option --charset to support "koi8-r" encoding of user ids. (Not yet tested). * Preferences should now work again. You should run "gpgm --check-trustdb \*" to rebuild all preferences. * Checking of certificates should now work but this needs a lot of testing. Key validation values are now cached in the trustdb; they should be recalculated as needed, but you may use --check-trustdb or --update-trustdb to do this. * Spanish translation by Urko Lusa. * Patch files are from now on signed. See the man page for the new option --not-dash-escaped. * New syntax: --edit-key [] If you run it without --batch the commands are executed and then you are put into normal mode unless you use "quit" or "save" as one of the commands. When in batch mode, the program quits after the last command, so you have to use "save" if you did some changes. It does not yet work completely, but may be used to list so the keys etc. Noteworthy changes in version 0.4.3 (1998-11-08) ----------------------------------- * Fixed the gettext configure bug. * Kludge for RSA keys: keyid and length of a RSA key are correctly reported, but you get an error if you try to use this key (If you do not have the non-US version). * Experimental support for keyrings stored in a GDBM database. This is *much* faster than a standard keyring. You will notice that the import gets slower with time; the reason is that all new keys are used to verify signatures of previous inserted keys. Use "--keyring gnupg-gdbm:". This is not (yet) supported for secret keys. * A Russian language file in the distribution (alternatives are in the contrib directory of the FTP servers) * commandline option processing now works as expected for GNU programs with the exception that you can't mix options and normal arguments. * Now --list-key lists all matching keys. This is needed in some other places too. Noteworthy changes in version 0.4.2 (1998-10-18) ----------------------------------- * This is only a snapshot: There are still a few bugs. * Fixed this huge memory leak. * Redesigned the trust database: You should run "gpgm --check-trustdb". New command --update-trustdb, which adds new key from the public keyring into your trustdb * Fixed a bug in the armor code, leading to invalid packet errors. (a workaround for this was to use --no-armor). The shorten line length (64 instead of 72) fixes a problem with pgp5 and keyservers. * comment packets are not anymore generated. "--export" filters them out. One Exception: The comment packets in a secret keyring are still used because they carry the factorization of the public prime product. * --import now only looks for KEYBLOCK headers, so you can now simply remove the "- " in front of such a header if someone accidently signed such a message or the keyblock is part of a cleartext signed message. * --with-colons now lists the key expiration time and not anymore the valid period. * Some keyblocks created with old releases have a wrong sequence of packets, so that the keyservers don't accept these keys. Simply using "--edit-key" fixes the problem. * New option --force-v3-sigs to generate signed messages which are compatible to PGP 5. * Add some code to support DLD (for non ELF systems) - but this is not tested because my BSD box is currently broken. * New command "expire" in the edit-key menu. Noteworthy changes in version 0.4.1 (1998-10-07) ----------------------------------- * A secondary key is used when the primary key is specified but cannot be used for the operation (if it is a sign-only key). * GNUPG can now handle concatenated armored messages: There is still a bug if different kinds of messages are mixed. * Iterated+Salted passphrases now work. If want to be sure that PGP5 is able to handle them you may want to use the options "--s2k-mode 3 --s2k-cipher-algo cast5 --s2k-digest-algo sha1" when changing a passphrase. * doc/OpenPGP talks about OpenPGP compliance, doc/HACKING gives a few hints about the internal structure. * Checked gnupg against the August 1998 draft (07) and I believe it is in compliance with this document (except for one point). * Fixed some bugs in the import merging code and rewrote some code for the trustdb. Noteworthy changes in version 0.4.0 (1998-09-18) ----------------------------------- * Triple DES is now supported. Michael Roth did this piece of needed work. We have now all the coded needed to be OpenPGP compliant. * Added a simple rpm spec file (see INSTALL). * detached and armored signatures are now using "PGP SIGNATURE", except when --rfc1991 is used. * All times which are not in the yyyy-mm-dd format are now printed in local time. Noteworthy changes in version 0.3.5 (1998-09-14) ----------------------------------- * New option --throw-keyid to create anonymous enciphered messages. If gpg detects such a message it tires all available secret keys in turn so decode it. This is a gnupg extension and not in OpenPGP but it has been discussed there and afaik some products use this scheme too (Suggested by Nimrod Zimmerman). * Fixed a bug with 5 byte length headers. * --delete-[secret-]key is now also available in gpgm. * cleartext signatures are not anymore converted to LF only. * Fixed a trustdb problem. Run "gpgm --check-trustdb" to fix old trust dbs. * Building in another directory should now work. * Weak key detection mechanism (Niklas Hernaeus). Noteworthy changes in version 0.3.4 (1998-08-11) ----------------------------------- * New options --comment and --set-filename; see g10/OPTIONS * yes/no, y/n localized. * Fixed some bugs. Noteworthy changes in version 0.3.3 (1998-08-08) ----------------------------------- * IMPORTANT: I found yet another bug in the way the secret keys are encrypted - I did it the way pgp 2.x did it, but OpenPGP and pgp 5.x specify another (in some aspects simpler) method. To convert your secret keys you have to do this: 1. Build the new release but don't install it and keep a copy of the old program. 2. Disable the network, make sure that you are the only user, be sure that there are no Trojan horses etc .... 3. Use your old gpg (version 0.3.[12]) and set the passphrases of ALL your secret keys to empty! (gpg --change-passphrase your-user-id). 4. Save your ownertrusts (see the next point) 5. rm ~/.gnupg/trustdb.gpg 6. install the new version of gpg (0.3.3) 7. For every secret key call "gpg --edit-key your-user-id", enter "passwd" at the prompt, follow the instructions and change your password back, enter "save" to store it. 8. Restore the ownertrust (see next point). * The format of the trust database has changed; you must delete the old one, so gnupg can create a new one. IMPORTANT: Use version 0.3.[12] to save your assigned ownertrusts ("gpgm --list-ownertrust >saved-trust"); then build this new version and restore the ownertrust with this new version ("gpgm --import-ownertrust saved-trust"). Please note that --list-ownertrust has been renamed to --export-ownertrust in this release and it does now only export defined ownertrusts. * The command --edit-key now provides a commandline driven menu which can be used for various tasks. --sign-key is only an an alias to --edit-key and maybe removed in future: use the command "sign" of this new menu - you can select which user ids you want to sign. * Alternate user ids can now be created an signed. * Owner trust values can now be changed with --edit-key (trust) * GNUPG can now run as a coprocess; this enables sophisticated frontends. tools/shmtest.c is a simple sample implementation. This needs some more work: all tty_xxx() are to be replaced by cpr_xxx() and some changes in the display logics is needed. * Removed options --gen-prime and --gen-random. * Removed option --add-key; use --edit-key instead. * Removed option --change-passphrase; use --edit-key instead. * Signatures are now checked even if the output file could not be created. Command "--verify" tries to find the detached data. * gpg now disables core dumps. * compress and symmetric cipher preferences are now used. Because there is no 3DES yet, this is replaced by Blowfish. * We have added the Twofish as an experimental cipher algorithm. Many thanks to Matthew Skala for doing this work. Twofish is the AES submission from Schneier et al.; see "www.counterpane.com/twofish.html" for more information. * Started with a help system: If you enter a question mark at some prompt; you should get a specific help for this prompt. * There is no more backup copy of the secret keyring. * A lot of new bugs. I think this release is not as stable as the previous one. Noteworthy changes in version 0.3.2 (1998-07-09) ----------------------------------- * Fixed some bugs when using --textmode (-seat) * Now displays the trust status of a positive verified message. * Keyrings are now scanned in the sequence they are added with --[secret-]keyring. Note that the default keyring is implicitly added as the very first one unless --no-default-keyring is used. * Fixed setuid and dlopen bug. Noteworthy changes in version 0.3.1 (1998-07-06) ----------------------------------- * Partial headers are now written in the OpenPGP format if a key in a v4 packet is used. * Removed some unused options, removed the gnupg.sig stuff. * Key lookup by name now returns a key which can be used for the desired action. * New options --list-ownertrust (gpgm) to make a backup copy of the ownertrust values you assigned. * clear signature headers are now in compliance with OpenPGP. Noteworthy changes in version 0.3.0 (1998-06-25) ----------------------------------- * New option --emulate-checksum-bug. If your passphrase does not work anymore, use this option and --change-passphrase to rewrite your passphrase. * More complete v4 key support: Preferences and expiration time is set into the self signature. * Key generation defaults to DSA/ElGamal keys, so that new keys are interoperable with pgp5 * DSA key generation is faster and key generation does not anymore remove entropy from the random generator (the primes are public parameters, so there is really no need for a cryptographic secure prime number generator which we had used). * A complete new structure for representing the key parameters. * Removed most public key knowledge into the cipher library. * Support for dynamic loading of new algorithms. * Moved tiger to an extension module. Noteworthy changes in version 0.2.19 (1998-05-29) ------------------------------------ * Replaced /dev/urandom in checks with new tool mk-tdata. * Some assembler file cleanups; some more functions for the Alpha. * Tiger has now the OpenPGP assigned number 6. Because the OID has changed, old signatures using this algorithm can't be verified. * gnupg now encrypts the compressed packed and not any longer in the reverse order; anyway it can decrypt both versions. Thanks to Tom for telling me this (not security related) bug. * --add-key works and you are now able to generate subkeys. * It is now possible to generate ElGamal keys in v4 packets to create valid OpenPGP keys. * Some new features for better integration into MUAs. Noteworthy changes in version 0.2.18 (1998-05-15) ------------------------------------ * Splitted cipher/random.c, add new option "--disable-dev-random" to configure to support the development of a random source for other systems. Prepared sourcefiles rand-unix.c, rand-w32.c and rand-dummy.c (which is used to allow compilation on systems without a random source). * Fixed a small bug in the key generation (it was possible that 48 bits of a key were not taken from the random pool) * Add key generation for DSA and v4 signatures. * Add a function trap_unaligned(), so that a SIGBUS is issued on Alphas and not the slow emulation code is used. And success: rmd160 raised a SIGBUS. * Enhanced the formatting facility of argparse and changed the use of \r,\v to @ because gettext does not like it. * New option "--compress-algo 1" to allow the creation of compressed messages which are readable by PGP and "--print-md" (gpgm) to make speed measurement easier. Noteworthy changes in version 0.2.17 (1998-05-04) ------------------------------------ * Comment packets are now of private type 61. * Passphrase code still used a 160 bit blowfish key, added a silly workaround. Please change your passphrase again - sorry. * Conventional encryption now uses a type 3 packet to describe the used algorithms. * The new algorithm number for Blowfish is 20, 16 is still used for encryption only; for signing it is only used when it is in a v3 packet, so that GNUPG keys are still valid. Noteworthy changes in version 0.2.16 (1998-04-28) ------------------------------------ * Add experimental support for the TIGER/192 message digest algorithm. (But there is only a dummy ASN OID). * Standard cipher is now Blowfish with 128 bit key in OpenPGP's CFB mode. I renamed the old cipher to Blowfish160. Because the OpenPGP group refused to assign me a number for Blowfish160, I have to drop support for this in the future. You should use "--change-passphrase" to recode your current passphrase with 128 bit Blowfish. Noteworthy changes in version 0.2.15 (1998-04-09) ------------------------------------ * Fixed a bug with the old checksum calculation for secret keys. If you run the program without --batch, a warning does inform you if your secret key needs to be converted; simply use --change-passphrase to recalculate the checksum. Please do this soon, as the compatible mode will be removed sometime in the future. * CAST5 works (using the PGP's special CFB mode). * Again somewhat more PGP 5 compatible. * Some new test cases Noteworthy changes in version 0.2.14 (1998-04-02) ------------------------------------ * Changed the internal handling of keyrings. * Add support to list PGP 5 keyrings with subkeys * Timestamps of signatures are now verified. * A expiration time can now be specified during key generation. * Some speedups for Blowfish and SHA-1, rewrote SHA-1 transform. Reduced the amount of random bytes needed for key generation in some cases. Noteworthy changes in version 0.2.13 (1998-03-10) ------------------------------------ * Verify of DSA signatures works. * Re-implemented the slower random number generator. Noteworthy changes in version 0.2.12 (1998-03-07) ------------------------------------ * --delete-key checks that there is no secret key. The new option --delete-secret-key maybe used to delete a secret key. * "-kv" now works as expected. Options "--list-{keys,sigs]" and "--check-sigs" are now working. * New options "--verify" and "--decrypt" to better support integration into MUAs (partly done for Mutt). * New option "--with-colons" to make parsing of key lists easier. Noteworthy changes in version 0.2.11 (1998-03-02) ------------------------------------ * GPG now asks for a recipient's name if option "-r" is not used. * If there is no good trust path, the program asks whether to use the public keys anyway. * "--delete-key" works for public keys. What semantics shall I use when there is a secret key too? Delete the secret key or leave him and auto-regenerate the public key, next time the secret key is used? Noteworthy changes in version 0.2.10 (1998-02-27) ------------------------------------ * Code for the alpha is much faster (about 20 times); the data was misaligned and the kernel traps this, so nearly all time was used by system to trap the misalignments and to write syslog messages. Shame on me and thanks to Ralph for pointing me at this while drinking some beer yesterday. * Changed some configure options and add an option --disable-m-guard to remove the memory checking code and to compile everything with optimization on. * New environment variable GNUPGHOME, which can be used to set another homedir than ~/.gnupg. Changed default homedir for Windoze version to c:/gnupg. * Fixed detached signatures; detached PGP signatures caused a SEGV. * The Windoze version works (as usual w/o a strong RNG). Noteworthy changes in version 0.2.9 (1998-02-26) ----------------------------------- * Fixed FreeBSD bug. * Added a simple man page. * Switched to automake1.2f and a newer gettext. Noteworthy changes in version 0.2.8 (1998-02-24) ----------------------------------- * Changed the name to GNUPG, the binaries are called gpg and gpgm. You must rename rename the directory "~/.g10" to ~/.gnupg/, rename {pub,sec}ring.g10 to {pub,sec}ring.gpg, trustdb.g10 to trustdb.gpg and g10.sig to gnupg.sig. * New or changed passphrases are now salted. Noteworthy changes in version 0.2.7 (1998-02-18) ----------------------------------- * New command "gen-revoke" to create a key revocation certificate. * New option "homedir" to set the homedir (which defaults to "~/.g10"). This directory is created if it does not exists (only the last part of the name and not the complete hierarchy) * Command "import" works. (Try: "finger gcrypt@ftp.guug.de|g10 --import") * New commands "dearmor/enarmor" for g10maint. These are mainly used for internal test purposes. * Option --version now conforming to the GNU standards and lists the available ciphers, message digests and public key algorithms. * Assembler code for m68k (not tested). * "make check" works. Noteworthy changes in version 0.2.6 (1998-02-13) ----------------------------------- * Option "--export" works. Noteworthy changes in version 0.2.5 (1998-02-12) ----------------------------------- * Added zlib for systems which don't have it. Use "./configure --with-zlib" to link with the static version. * Generalized some more functions and rewrote the encoding of message digests into MPIs. * Enhanced the checkit script Noteworthy changes in version 0.2.4 (1998-02-11) ----------------------------------- * nearly doubled the speed of the ElGamal signature verification. * backup copies of keyrings are created. * assembler stuff for Pentium; gives about 15% better performance. * fixed a lot of bugs. Noteworthy changes in version 0.2.3 (1998-02-09) ----------------------------------- * Found a bug in the calculation of ELG fingerprints. This is now fixed, but all existing fingerprints and keyids for ELG keys are not any more valid. * armor should now work; including clear signed text. * moved some options to the new program g10maint * It's now 64 bit clean and runs fine on an alpha--linux. * Key generation is much faster now. I fixed this by using not so strong random number for the primes (this was a bug because the ElGamal primes are public parameters and it does not make sense to generate them from strong random). The real secret is the x value which is still generated from strong (okay: /dev/random) random bits. * added option "--status-fd": see g10/OPTIONS * We have secure memory on systems which support mlock(). It is not complete yet, because we do not have signal handler which does a cleanup in very case. We should also check the ulimit for the user in the case that the admin does not have set a limit on locked pages. * started with internationalization support. * The logic to handle the web of trust is now implemented. It is has some bugs; but I'm going to change the algorithm anyway. It works by calculating the trustlevel on the fly. It may ask you to provide trust parameters if the calculated trust probability is too low. I will write a paper which discusses this new approach. * a couple of changes to the configure script. * New option "--quick-random" which uses a much quicker random number generator. Keys generated while this option is in effect are flags with "INSECURE!" in the user-id. This is a development only option. * Read support for new version packets (OpenPGP). * Comment packets are now of correct OpenPGP type 16. Old comment packets written by G10 are detected because they always start with a hash which is an invalid version byte. * The string "(INSECURE!)" is appended to a new user-id if this is generated on a system without a good random number generator. Version 0.2.2 (1998-02-09) Version 0.2.1 (1998-01-28) Version 0.2.0 (1998-01-25) Version 0.1.3 (1998-01-12) Version 0.1.2 (1998-01-07) Version 0.1.1 (1998-01-07) Version 0.1.0 (1998-01-05) Version 0.0.0 (1997-12-20) Copyright (C) 1998-2015 Free Software Foundation, Inc. Copyright (C) 1997-2015 Werner Koch This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/g10/getkey.c b/g10/getkey.c index ad0c207bf..45c3f512b 100644 --- a/g10/getkey.c +++ b/g10/getkey.c @@ -1,3294 +1,3570 @@ /* getkey.c - Get a key from the database * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2008, 2010 Free Software Foundation, Inc. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "util.h" #include "packet.h" #include "iobuf.h" #include "keydb.h" #include "options.h" #include "main.h" #include "trustdb.h" #include "i18n.h" #include "keyserver-internal.h" #include "call-agent.h" #include "host2net.h" #include "mbox-util.h" #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE #if MAX_PK_CACHE_ENTRIES < 2 #error We need the cache for key creation #endif struct getkey_ctx_s { /* Part of the search criteria: whether the search is an exact search or not. A search that is exact requires that a key or subkey meet all of the specified criteria. A search that is not exact allows selecting a different key or subkey from the keyblock that matched the critera. Further, an exact search returns the key or subkey that matched whereas a non-exact search typically returns the primary key. See finish_lookup for details. */ int exact; /* Part of the search criteria: Whether the caller only wants keys with an available secret key. This is used by getkey_next to get the next result with the same initial criteria. */ int want_secret; /* Part of the search criteria: The type of the requested key. A mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If non-zero, then for a key to match, it must implement one of the required uses. */ int req_usage; /* The database handle. */ KEYDB_HANDLE kr_handle; /* Whether we should call xfree() on the context when the context is released using getkey_end()). */ int not_allocated; /* This variable is used as backing store for strings which have their address used in ITEMS. */ strlist_t extra_list; /* Part of the search criteria: The low-level search specification as passed to keydb_search. */ int nitems; /* This must be the last element in the structure. When we allocate the structure, we allocate it so that ITEMS can hold NITEMS. */ KEYDB_SEARCH_DESC items[1]; }; #if 0 static struct { int any; int okay_count; int nokey_count; int error_count; } lkup_stats[21]; #endif typedef struct keyid_list { struct keyid_list *next; char fpr[MAX_FINGERPRINT_LEN]; u32 keyid[2]; } *keyid_list_t; #if MAX_PK_CACHE_ENTRIES typedef struct pk_cache_entry { struct pk_cache_entry *next; u32 keyid[2]; PKT_public_key *pk; } *pk_cache_entry_t; static pk_cache_entry_t pk_cache; static int pk_cache_entries; /* Number of entries in pk cache. */ static int pk_cache_disabled; #endif #if MAX_UID_CACHE_ENTRIES < 5 #error we really need the userid cache #endif typedef struct user_id_db { struct user_id_db *next; keyid_list_t keyids; int len; char name[1]; } *user_id_db_t; static user_id_db_t user_id_db; static int uid_cache_entries; /* Number of entries in uid cache. */ static void merge_selfsigs (kbnode_t keyblock); static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key, int want_secret); #if 0 static void print_stats () { int i; for (i = 0; i < DIM (lkup_stats); i++) { if (lkup_stats[i].any) es_fprintf (es_stderr, "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n", i, lkup_stats[i].okay_count, lkup_stats[i].nokey_count, lkup_stats[i].error_count); } } #endif /* For documentation see keydb.h. */ void cache_public_key (PKT_public_key * pk) { #if MAX_PK_CACHE_ENTRIES pk_cache_entry_t ce, ce2; u32 keyid[2]; if (pk_cache_disabled) return; if (pk->flags.dont_cache) return; if (is_ELGAMAL (pk->pubkey_algo) || pk->pubkey_algo == PUBKEY_ALGO_DSA || pk->pubkey_algo == PUBKEY_ALGO_ECDSA || pk->pubkey_algo == PUBKEY_ALGO_EDDSA || pk->pubkey_algo == PUBKEY_ALGO_ECDH || is_RSA (pk->pubkey_algo)) { keyid_from_pk (pk, keyid); } else return; /* Don't know how to get the keyid. */ for (ce = pk_cache; ce; ce = ce->next) if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]) { if (DBG_CACHE) log_debug ("cache_public_key: already in cache\n"); return; } if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES) { int n; /* Remove the last 50% of the entries. */ for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++) ce = ce->next; if (ce != pk_cache && ce->next) { ce2 = ce->next; ce->next = NULL; ce = ce2; for (; ce; ce = ce2) { ce2 = ce->next; free_public_key (ce->pk); xfree (ce); pk_cache_entries--; } } assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES); } pk_cache_entries++; ce = xmalloc (sizeof *ce); ce->next = pk_cache; pk_cache = ce; ce->pk = copy_public_key (NULL, pk); ce->keyid[0] = keyid[0]; ce->keyid[1] = keyid[1]; #endif } /* Return a const utf-8 string with the text "[User ID not found]". This function is required so that we don't need to switch gettext's encoding temporary. */ static const char * user_id_not_found_utf8 (void) { static char *text; if (!text) text = native_to_utf8 (_("[User ID not found]")); return text; } /* Return the user ID from the given keyblock. * We use the primary uid flag which has been set by the merge_selfsigs * function. The returned value is only valid as long as the given * keyblock is not changed. */ static const char * get_primary_uid (KBNODE keyblock, size_t * uidlen) { KBNODE k; const char *s; for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data && k->pkt->pkt.user_id->is_primary) { *uidlen = k->pkt->pkt.user_id->len; return k->pkt->pkt.user_id->name; } } s = user_id_not_found_utf8 (); *uidlen = strlen (s); return s; } static void release_keyid_list (keyid_list_t k) { while (k) { keyid_list_t k2 = k->next; xfree (k); k = k2; } } /**************** * Store the association of keyid and userid * Feed only public keys to this function. */ static void cache_user_id (KBNODE keyblock) { user_id_db_t r; const char *uid; size_t uidlen; keyid_list_t keyids = NULL; KBNODE k; for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { keyid_list_t a = xmalloc_clear (sizeof *a); /* Hmmm: For a long list of keyids it might be an advantage * to append the keys. */ fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL); keyid_from_pk (k->pkt->pkt.public_key, a->keyid); /* First check for duplicates. */ for (r = user_id_db; r; r = r->next) { keyid_list_t b = r->keyids; for (b = r->keyids; b; b = b->next) { if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN)) { if (DBG_CACHE) log_debug ("cache_user_id: already in cache\n"); release_keyid_list (keyids); xfree (a); return; } } } /* Now put it into the cache. */ a->next = keyids; keyids = a; } } if (!keyids) BUG (); /* No key no fun. */ uid = get_primary_uid (keyblock, &uidlen); if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES) { /* fixme: use another algorithm to free some cache slots */ r = user_id_db; user_id_db = r->next; release_keyid_list (r->keyids); xfree (r); uid_cache_entries--; } r = xmalloc (sizeof *r + uidlen - 1); r->keyids = keyids; r->len = uidlen; memcpy (r->name, uid, r->len); r->next = user_id_db; user_id_db = r; uid_cache_entries++; } /* For documentation see keydb.h. */ void getkey_disable_caches () { #if MAX_PK_CACHE_ENTRIES { pk_cache_entry_t ce, ce2; for (ce = pk_cache; ce; ce = ce2) { ce2 = ce->next; free_public_key (ce->pk); xfree (ce); } pk_cache_disabled = 1; pk_cache_entries = 0; pk_cache = NULL; } #endif /* fixme: disable user id cache ? */ } +void +pubkey_free (struct pubkey *key) +{ + xfree (key->pk); + release_kbnode (key->keyblock); + xfree (key); +} + +void +pubkeys_free (struct pubkey *keys) +{ + while (keys) + { + struct pubkey *next = keys->next; + pubkey_free (keys); + keys = next; + } +} + +/* Returns all keys that match the search specfication SEARCH_TERMS. + + This function also checks for and warns about duplicate entries in + the keydb, which can occur if the user has configured multiple + keyrings or keyboxes or if a keyring or keybox was corrupted. + + Note: SEARCH_TERMS will not be expanded (i.e., it may not be a + group). + + USE is the operation for which the key is required. It must be + either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or + PUBKEY_USAGE_AUTH. + + XXX: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are + implemented. + + INCLUDE_UNUSABLE indicates whether disabled keys are allowed. + (Recipients specified with --encrypt-to and --hidden-encrypt-to may + be disabled. It is possible to edit disabled keys.) + + SOURCE is the context in which SEARCH_TERMS was specified, e.g., + "--encrypt-to", etc. If this function is called interactively, + then this should be NULL. + + If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user + does not specify a long key id or a fingerprint. + + The results are placed in *KEYS. *KEYS must be NULL! */ +gpg_error_t +get_pubkeys (ctrl_t ctrl, + char *search_terms, int use, int include_unusable, char *source, + int warn_possibly_ambiguous, + struct pubkey **keys) +{ + /* We show a warning when a key appears multiple times in the DB. + This can happen for two reasons: + + - The user has configured multiple keyrings or keyboxes. + + - The keyring or keybox has been corrupted in some way, e.g., a + bug or a random process changing them. + + For each duplicate, we only want to show the key once. Hence, + this list. */ + static strlist_t key_dups; + + /* USE transformed to a string. */ + char *use_str; + + gpg_error_t err; + + KEYDB_SEARCH_DESC desc; + + GETKEY_CTX ctx; + struct pubkey *results = NULL; + struct pubkey *r; + + int count; + + char fingerprint[2 * MAX_FINGERPRINT_LEN + 1]; + + if (DBG_LOOKUP) + { + log_debug ("\n"); + log_debug ("%s: Checking %s=%s\n", + __func__, source ? source : "user input", search_terms); + } + + if (*keys) + log_bug ("%s: KEYS should be NULL!\n", __func__); + + switch (use) + { + case PUBKEY_USAGE_ENC: use_str = "encrypt"; break; + case PUBKEY_USAGE_SIG: use_str = "sign"; break; + case PUBKEY_USAGE_CERT: use_str = "cetify"; break; + case PUBKEY_USAGE_AUTH: use_str = "authentication"; break; + default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use); + } + + if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH) + log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str); + + err = classify_user_id (search_terms, &desc, 1); + if (err) + { + log_info (_("key \"%s\" not found: %s\n"), + search_terms, gpg_strerror (err)); + if (!opt.quiet && source) + log_info (_("(check argument of option '%s')\n"), source); + goto out; + } + + if (warn_possibly_ambiguous + && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID + || desc.mode == KEYDB_SEARCH_MODE_FPR16 + || desc.mode == KEYDB_SEARCH_MODE_FPR20 + || desc.mode == KEYDB_SEARCH_MODE_FPR)) + { + log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"), + search_terms); + if (!opt.quiet && source) + log_info (_("(check argument of option '%s')\n"), source); + } + + /* Gather all of the results. */ + ctx = NULL; + count = 0; + do + { + PKT_public_key *pk = xmalloc_clear (sizeof *pk); + KBNODE kb; + pk->req_usage = use; + + if (! ctx) + err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL, + include_unusable, 1); + else + err = getkey_next (ctx, pk, &kb); + + if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) + /* No more results. */ + { + xfree (pk); + break; + } + else if (err) + /* An error (other than "not found"). */ + { + log_error (_("error looking up: %s\n"), + gpg_strerror (err)); + xfree (pk); + break; + } + + /* Another result! */ + count ++; + + r = xmalloc_clear (sizeof (*r)); + r->pk = pk; + r->keyblock = kb; + r->next = results; + results = r; + } + while (ctx); + getkey_end (ctx); + + if (DBG_LOOKUP) + { + log_debug ("%s resulted in %d matches.\n", search_terms, count); + for (r = results; r; r = r->next) + log_debug (" %s\n", + hexfingerprint (r->keyblock->pkt->pkt.public_key, + fingerprint, sizeof (fingerprint))); + } + + if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND) + /* No match. */ + { + if (DBG_LOOKUP) + log_debug ("%s: '%s' not found.\n", __func__, search_terms); + + log_info (_("key \"%s\" not found\n"), search_terms); + if (!opt.quiet && source) + log_info (_("(check argument of option '%s')\n"), source); + + goto out; + } + else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) + /* No more matches. */ + ; + else if (err) + /* Some other error. An error message was already printed + out. Free RESULTS and continue. */ + goto out; + + /* Check for duplicates. */ + if (DBG_LOOKUP) + log_debug ("%s: Checking results of %s='%s' for dups\n", + __func__, source ? source : "user input", search_terms); + count = 0; + for (r = results; r; r = r->next) + { + struct pubkey **prevp; + struct pubkey *next; + struct pubkey *r2; + int dups = 0; + + prevp = &r->next; + next = r->next; + while ((r2 = next)) + { + if (cmp_public_keys (r->keyblock->pkt->pkt.public_key, + r2->keyblock->pkt->pkt.public_key) != 0) + /* Not a dup. */ + { + prevp = &r2->next; + next = r2->next; + continue; + } + + dups ++; + count ++; + + /* Remove R2 from the list. */ + *prevp = r2->next; + release_kbnode (r2->keyblock); + next = r2->next; + xfree (r2); + } + + if (dups) + { + hexfingerprint (r->keyblock->pkt->pkt.public_key, + fingerprint, sizeof fingerprint); + if (! strlist_find (key_dups, fingerprint)) + { + char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1]; + + log_info (_("Warning: %s appears in the keyring %d times.\n"), + format_hexfingerprint (fingerprint, + fingerprint_formatted, + sizeof fingerprint_formatted), + 1 + dups); + add_to_strlist (&key_dups, fingerprint); + } + } + } + + if (DBG_LOOKUP && count) + { + log_debug ("After removing %d dups:\n", count); + for (r = results, count = 0; r; r = r->next) + log_debug (" %d: %s\n", + count, + hexfingerprint (r->keyblock->pkt->pkt.public_key, + fingerprint, sizeof fingerprint)); + } + + out: + if (err) + { + while ((r = results)) + { + results = results->next; + pubkey_free (r); + release_kbnode (r->keyblock); + xfree (r); + } + } + else + *keys = results; + + return err; +} + + static void pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock, KBNODE found_key) { KBNODE a = found_key ? found_key : keyblock; (void) ctx; assert (a->pkt->pkttype == PKT_PUBLIC_KEY || a->pkt->pkttype == PKT_PUBLIC_SUBKEY); copy_public_key (pk, a->pkt->pkt.public_key); } /* For documentation see keydb.h. */ int get_pubkey (PKT_public_key * pk, u32 * keyid) { int internal = 0; int rc = 0; #if MAX_PK_CACHE_ENTRIES if (pk) { /* Try to get it from the cache. We don't do this when pk is NULL as it does not guarantee that the user IDs are cached. */ pk_cache_entry_t ce; for (ce = pk_cache; ce; ce = ce->next) { if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]) /* XXX: We don't check PK->REQ_USAGE here, but if we don't read from the cache, we do check it! */ { copy_public_key (pk, ce->pk); return 0; } } } #endif /* More init stuff. */ if (!pk) { pk = xmalloc_clear (sizeof *pk); internal++; } /* Do a lookup. */ { struct getkey_ctx_s ctx; KBNODE kb = NULL; KBNODE found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; /* Use the key ID exactly as given. */ ctx.not_allocated = 1; ctx.kr_handle = keydb_new (); if (!ctx.kr_handle) { rc = gpg_error_from_syserror (); goto leave; } ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; ctx.req_usage = pk->req_usage; rc = lookup (&ctx, &kb, &found_key, 0); if (!rc) { pk_from_block (&ctx, pk, kb, found_key); } getkey_end (&ctx); release_kbnode (kb); } if (!rc) goto leave; rc = GPG_ERR_NO_PUBKEY; leave: if (!rc) cache_public_key (pk); if (internal) free_public_key (pk); return rc; } /* For documentation see keydb.h. */ int get_pubkey_fast (PKT_public_key * pk, u32 * keyid) { int rc = 0; KEYDB_HANDLE hd; KBNODE keyblock; u32 pkid[2]; assert (pk); #if MAX_PK_CACHE_ENTRIES { /* Try to get it from the cache */ pk_cache_entry_t ce; for (ce = pk_cache; ce; ce = ce->next) { if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] /* Only consider primary keys. */ && ce->pk->keyid[0] == ce->pk->main_keyid[0] && ce->pk->keyid[1] == ce->pk->main_keyid[1]) { if (pk) copy_public_key (pk, ce->pk); return 0; } } } #endif hd = keydb_new (); if (!hd) return gpg_error_from_syserror (); rc = keydb_search_kid (hd, keyid); if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) { keydb_release (hd); return GPG_ERR_NO_PUBKEY; } rc = keydb_get_keyblock (hd, &keyblock); keydb_release (hd); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc)); return GPG_ERR_NO_PUBKEY; } assert (keyblock && keyblock->pkt && keyblock->pkt->pkttype == PKT_PUBLIC_KEY); /* We return the primary key. If KEYID matched a subkey, then we return an error. */ keyid_from_pk (keyblock->pkt->pkt.public_key, pkid); if (keyid[0] == pkid[0] && keyid[1] == pkid[1]) copy_public_key (pk, keyblock->pkt->pkt.public_key); else rc = GPG_ERR_NO_PUBKEY; release_kbnode (keyblock); /* Not caching key here since it won't have all of the fields properly set. */ return rc; } /* For documentation see keydb.h. */ KBNODE get_pubkeyblock (u32 * keyid) { struct getkey_ctx_s ctx; int rc = 0; KBNODE keyblock = NULL; memset (&ctx, 0, sizeof ctx); /* No need to set exact here because we want the entire block. */ ctx.not_allocated = 1; ctx.kr_handle = keydb_new (); if (!ctx.kr_handle) return NULL; ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; rc = lookup (&ctx, &keyblock, NULL, 0); getkey_end (&ctx); return rc ? NULL : keyblock; } /* For documentation see keydb.h. */ gpg_error_t get_seckey (PKT_public_key *pk, u32 *keyid) { gpg_error_t err; struct getkey_ctx_s ctx; kbnode_t keyblock = NULL; kbnode_t found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; /* Use the key ID exactly as given. */ ctx.not_allocated = 1; ctx.kr_handle = keydb_new (); if (!ctx.kr_handle) return gpg_error_from_syserror (); ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; ctx.req_usage = pk->req_usage; err = lookup (&ctx, &keyblock, &found_key, 1); if (!err) { pk_from_block (&ctx, pk, keyblock, found_key); } getkey_end (&ctx); release_kbnode (keyblock); if (!err) { err = agent_probe_secret_key (/*ctrl*/NULL, pk); if (err) release_public_key_parts (pk); } return err; } /* Skip unusable keys. A key is unusable if it is revoked, expired or disabled or if the selected user id is revoked or expired. */ static int skip_unusable (void *dummy, u32 * keyid, int uid_no) { int unusable = 0; KBNODE keyblock; PKT_public_key *pk; (void) dummy; keyblock = get_pubkeyblock (keyid); if (!keyblock) { log_error ("error checking usability status of %s\n", keystr (keyid)); goto leave; } pk = keyblock->pkt->pkt.public_key; /* Is the key revoked or expired? */ if (pk->flags.revoked || pk->has_expired) unusable = 1; /* Is the user ID in question revoked or expired? */ if (!unusable && uid_no) { KBNODE node; int uids_seen = 0; for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { PKT_user_id *user_id = node->pkt->pkt.user_id; uids_seen ++; if (uids_seen != uid_no) continue; if (user_id->is_revoked || user_id->is_expired) unusable = 1; break; } } /* If UID_NO is non-zero, then the keyblock better have at least that many UIDs. */ assert (uids_seen == uid_no); } if (!unusable) unusable = pk_is_disabled (pk); leave: release_kbnode (keyblock); return unusable; } /* Search for keys matching some criteria. If RETCTX is not NULL, then the constructed context is returned in *RETCTX so that getpubkey_next can be used to get subsequent results. In this case, getkey_end() must be used to free the search context. If RETCTX is not NULL, then RET_KDBHD must be NULL. If NAMELIST is not NULL, then a search query is constructed using classify_user_id on each of the strings in the list. (Recall: the database does an OR of the terms, not an AND.) If NAMELIST is NULL, then all results are returned. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is set, it is used to filter the search results. See the documentation for finish_lookup to understand exactly how this is used. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If WANT_SECRET is set, then only keys with an available secret key (either locally or via key registered on a smartcard) are returned. If INCLUDE_UNUSABLE is set, then unusable keys (see the documentation for skip_unusable for an exact definition) are skipped unless they are looked up by key id or by fingerprint. If RET_KB is not NULL, the keyblock is returned in *RET_KB. This should be freed using release_kbnode(). If RET_KDBHD is not NULL, then the new database handle used to conduct the search is returned in *RET_KDBHD. This can be used to get subsequent results using keydb_search_next. Note: in this case, no advanced filtering is done for subsequent results (e.g., WANT_SECRET and PK->REQ_USAGE are not respected). This function returns 0 on success. Otherwise, an error code is returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY (if want_secret is set) is returned if the key is not found. */ static int key_byname (GETKEY_CTX *retctx, strlist_t namelist, PKT_public_key *pk, int want_secret, int include_unusable, KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd) { int rc = 0; int n; strlist_t r; GETKEY_CTX ctx; KBNODE help_kb = NULL; KBNODE found_key = NULL; if (retctx) { /* Reset the returned context in case of error. */ assert (!ret_kdbhd); /* Not allowed because the handle is stored in the context. */ *retctx = NULL; } if (ret_kdbhd) *ret_kdbhd = NULL; if (!namelist) /* No search terms: iterate over the whole DB. */ { ctx = xmalloc_clear (sizeof *ctx); ctx->nitems = 1; ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST; if (!include_unusable) ctx->items[0].skipfnc = skip_unusable; } else { /* Build the search context. */ for (n = 0, r = namelist; r; r = r->next) n++; /* CTX has space for a single search term at the end. Thus, we need to allocate sizeof *CTX plus (n - 1) sizeof CTX->ITEMS. */ ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items); ctx->nitems = n; for (n = 0, r = namelist; r; r = r->next, n++) { gpg_error_t err; err = classify_user_id (r->d, &ctx->items[n], 1); if (ctx->items[n].exact) ctx->exact = 1; if (err) { xfree (ctx); return gpg_err_code (err); /* FIXME: remove gpg_err_code. */ } if (!include_unusable && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20 && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR) ctx->items[n].skipfnc = skip_unusable; } } ctx->want_secret = want_secret; ctx->kr_handle = keydb_new (); if (!ctx->kr_handle) { rc = gpg_error_from_syserror (); getkey_end (ctx); return rc; } if (!ret_kb) ret_kb = &help_kb; if (pk) { ctx->req_usage = pk->req_usage; } rc = lookup (ctx, ret_kb, &found_key, want_secret); if (!rc && pk) { pk_from_block (ctx, pk, *ret_kb, found_key); } release_kbnode (help_kb); if (retctx) /* Caller wants the context. */ *retctx = ctx; else { if (ret_kdbhd) { *ret_kdbhd = ctx->kr_handle; ctx->kr_handle = NULL; } getkey_end (ctx); } return rc; } /* For documentation see keydb.h. */ int get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk, const char *name, KBNODE * ret_keyblock, KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl) { int rc; strlist_t namelist = NULL; struct akl *akl; int is_mbox; int nodefault = 0; int anylocalfirst = 0; if (retctx) *retctx = NULL; /* Does NAME appear to be a mailbox (mail address)? */ is_mbox = is_valid_mailbox (name); /* The auto-key-locate feature works as follows: there are a number of methods to look up keys. By default, the local keyring is tried first. Then, each method listed in the --auto-key-locate is tried in the order it appears. This can be changed as follows: - if nodefault appears anywhere in the list of options, then the local keyring is not tried first, or, - if local appears anywhere in the list of options, then the local keyring is not tried first, but in the order in which it was listed in the --auto-key-locate option. Note: we only save the search context in RETCTX if the local method is the first method tried (either explicitly or implicitly). */ if (!no_akl) /* auto-key-locate is enabled. */ { /* nodefault is true if "nodefault" or "local" appear. */ for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL) { nodefault = 1; break; } /* anylocalfirst is true if "local" appears before any other search methods (except "nodefault"). */ for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type != AKL_NODEFAULT) { if (akl->type == AKL_LOCAL) anylocalfirst = 1; break; } } if (!nodefault) /* "nodefault" didn't occur. Thus, "local" is implicitly the first method to try. */ anylocalfirst = 1; if (nodefault && is_mbox) /* Either "nodefault" or "local" (explicitly) appeared in the auto key locate list and NAME appears to be an email address. Don't try the local keyring. */ { rc = GPG_ERR_NO_PUBKEY; } else /* Either "nodefault" and "local" don't appear in the auto key locate list (in which case we try the local keyring first) or NAME does not appear to be an email address (in which case we only try the local keyring). In this case, lookup NAME in the local keyring. */ { add_to_strlist (&namelist, name); rc = key_byname (retctx, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } /* If the requested name resembles a valid mailbox and automatic retrieval has been enabled, we try to import the key. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox) /* NAME wasn't present in the local keyring (or we didn't try the local keyring). Since the auto key locate feature is enabled and NAME appears to be an email address, try the auto locate feature. */ { for (akl = opt.auto_key_locate; akl; akl = akl->next) { unsigned char *fpr = NULL; size_t fpr_len; int did_key_byname = 0; int no_fingerprint = 0; const char *mechanism = "?"; switch (akl->type) { case AKL_NODEFAULT: /* This is a dummy mechanism. */ mechanism = "None"; rc = GPG_ERR_NO_PUBKEY; break; case AKL_LOCAL: mechanism = "Local"; did_key_byname = 1; if (retctx) { getkey_end (*retctx); *retctx = NULL; } add_to_strlist (&namelist, name); rc = key_byname (anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); break; case AKL_CERT: mechanism = "DNS CERT"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_PKA: mechanism = "PKA"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_DANE: mechanism = "DANE"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_LDAP: mechanism = "LDAP"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_KEYSERVER: /* Strictly speaking, we don't need to only use a valid mailbox for the getname search, but it helps cut down on the problem of searching for something like "john" and getting a whole lot of keys back. */ if (opt.keyserver) { mechanism = opt.keyserver->uri; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, opt.keyserver); glo_ctrl.in_auto_key_retrieve--; } else { mechanism = "Unconfigured keyserver"; rc = GPG_ERR_NO_PUBKEY; } break; case AKL_SPEC: { struct keyserver_spec *keyserver; mechanism = akl->spec->uri; keyserver = keyserver_match (akl->spec); glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, keyserver); glo_ctrl.in_auto_key_retrieve--; } break; } /* Use the fingerprint of the key that we actually fetched. This helps prevent problems where the key that we fetched doesn't have the same name that we used to fetch it. In the case of CERT and PKA, this is an actual security requirement as the URL might point to a key put in by an attacker. By forcing the use of the fingerprint, we won't use the attacker's key here. */ if (!rc && fpr) { char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1]; assert (fpr_len <= MAX_FINGERPRINT_LEN); free_strlist (namelist); namelist = NULL; bin2hex (fpr, fpr_len, fpr_string); if (opt.verbose) log_info ("auto-key-locate found fingerprint %s\n", fpr_string); add_to_strlist (&namelist, fpr_string); } else if (!rc && !fpr && !did_key_byname) /* The acquisition method said no failure occurred, but it didn't return a fingerprint. That's a failure. */ { no_fingerprint = 1; rc = GPG_ERR_NO_PUBKEY; } xfree (fpr); fpr = NULL; if (!rc && !did_key_byname) /* There was no error and we didn't do a local lookup. This means that we imported a key into the local keyring. Try to read the imported key from the keyring. */ { if (retctx) { getkey_end (*retctx); *retctx = NULL; } rc = key_byname (anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } if (!rc) { /* Key found. */ log_info (_("automatically retrieved '%s' via %s\n"), name, mechanism); break; } if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY || opt.verbose || no_fingerprint) log_info (_("error retrieving '%s' via %s: %s\n"), name, mechanism, no_fingerprint ? _("No fingerprint") : gpg_strerror (rc)); } } if (rc && retctx) { getkey_end (*retctx); *retctx = NULL; } if (retctx && *retctx) { assert (!(*retctx)->extra_list); (*retctx)->extra_list = namelist; } else free_strlist (namelist); return rc; } /* For documentation see keydb.h. FIXME: We should replace this with the _byname function. This can be done by creating a userID conforming to the unified fingerprint style. */ int get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock, const byte * fprint, size_t fprint_len) { int rc; if (r_keyblock) *r_keyblock = NULL; if (fprint_len == 20 || fprint_len == 16) { struct getkey_ctx_s ctx; KBNODE kb = NULL; KBNODE found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; ctx.not_allocated = 1; ctx.kr_handle = keydb_new (); if (!ctx.kr_handle) return gpg_error_from_syserror (); ctx.nitems = 1; ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20; memcpy (ctx.items[0].u.fpr, fprint, fprint_len); rc = lookup (&ctx, &kb, &found_key, 0); if (!rc && pk) pk_from_block (&ctx, pk, kb, found_key); if (!rc && r_keyblock) { *r_keyblock = kb; kb = NULL; } release_kbnode (kb); getkey_end (&ctx); } else rc = GPG_ERR_GENERAL; /* Oops */ return rc; } /* For documentation see keydb.h. */ int get_pubkey_byfprint_fast (PKT_public_key * pk, const byte * fprint, size_t fprint_len) { int rc = 0; KEYDB_HANDLE hd; KBNODE keyblock; byte fprbuf[MAX_FINGERPRINT_LEN]; int i; for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++) fprbuf[i] = fprint[i]; while (i < MAX_FINGERPRINT_LEN) fprbuf[i++] = 0; hd = keydb_new (); if (!hd) return gpg_error_from_syserror (); rc = keydb_search_fpr (hd, fprbuf); if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) { keydb_release (hd); return GPG_ERR_NO_PUBKEY; } rc = keydb_get_keyblock (hd, &keyblock); keydb_release (hd); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc)); return GPG_ERR_NO_PUBKEY; } assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY); if (pk) copy_public_key (pk, keyblock->pkt->pkt.public_key); release_kbnode (keyblock); /* Not caching key here since it won't have all of the fields properly set. */ return 0; } const char * parse_def_secret_key (ctrl_t ctrl) { KEYDB_HANDLE hd = NULL; strlist_t t; static int warned; for (t = opt.def_secret_key; t; t = t->next) { gpg_error_t err; KEYDB_SEARCH_DESC desc; KBNODE kb; KBNODE node; err = classify_user_id (t->d, &desc, 1); if (err) { log_error (_("secret key \"%s\" not found: %s\n"), t->d, gpg_strerror (err)); if (!opt.quiet) log_info (_("(check argument of option '%s')\n"), "--default-key"); continue; } if (! hd) { hd = keydb_new (); if (!hd) return NULL; } else keydb_search_reset (hd); err = keydb_search (hd, &desc, 1, NULL); if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) continue; if (err) { log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err)); t = NULL; break; } err = keydb_get_keyblock (hd, &kb); if (err) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (err)); continue; } merge_selfsigs (kb); err = gpg_error (GPG_ERR_NO_SECKEY); node = kb; do { PKT_public_key *pk = node->pkt->pkt.public_key; /* Check that the key has the signing capability. */ if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG)) continue; /* Check if the key is valid. */ if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug (_("not using %s as default key, %s"), keystr_from_pk (pk), "revoked"); continue; } if (pk->has_expired) { if (DBG_LOOKUP) log_debug (_("not using %s as default key, %s"), keystr_from_pk (pk), "expired"); continue; } if (pk_is_disabled (pk)) { if (DBG_LOOKUP) log_debug (_("not using %s as default key, %s"), keystr_from_pk (pk), "disabled"); continue; } err = agent_probe_secret_key (ctrl, pk); if (! err) /* This is a valid key. */ break; } while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY))); release_kbnode (kb); if (err) { if (! warned && ! opt.quiet) { log_info (_("Warning: not using '%s' as default key: %s\n"), t->d, gpg_strerror (GPG_ERR_NO_SECKEY)); print_reported_error (err, GPG_ERR_NO_SECKEY); } } else { if (! warned) log_info (_("using \"%s\" as default secret key for signing\n"), t->d); break; } } if (! warned && opt.def_secret_key && ! t) log_info (_("all values passed to '%s' ignored\n"), "--default-key"); warned = 1; if (hd) keydb_release (hd); if (t) return t->d; return NULL; } /* For documentation see keydb.h. */ gpg_error_t get_seckey_default (ctrl_t ctrl, PKT_public_key *pk) { gpg_error_t err; strlist_t namelist = NULL; int include_unusable = 1; const char *def_secret_key = parse_def_secret_key (ctrl); if (def_secret_key) add_to_strlist (&namelist, def_secret_key); else include_unusable = 0; err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL); free_strlist (namelist); return err; } /* For documentation see keydb.h. */ gpg_error_t getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk, strlist_t names, int want_secret, kbnode_t *ret_keyblock) { return key_byname (retctx, names, pk, want_secret, 1, ret_keyblock, NULL); } /* For documentation see keydb.h. */ gpg_error_t getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk, const char *name, int want_secret, kbnode_t *ret_keyblock) { gpg_error_t err; strlist_t namelist = NULL; int with_unusable = 1; const char *def_secret_key = NULL; if (want_secret && !name) def_secret_key = parse_def_secret_key (ctrl); if (want_secret && !name && def_secret_key) add_to_strlist (&namelist, def_secret_key); else if (name) add_to_strlist (&namelist, name); else with_unusable = 0; err = key_byname (retctx, namelist, pk, want_secret, with_unusable, ret_keyblock, NULL); /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if WANT_SECRET has been used. */ free_strlist (namelist); return err; } /* For documentation see keydb.h. */ gpg_error_t getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock) { int rc; /* Fixme: Make sure this is proper gpg_error */ KBNODE found_key = NULL; /* We need to disable the caching so that for an exact key search we won't get the result back from the cache and thus end up in an endless loop. The endless loop can occur, because the cache is used without respecting the current file pointer! */ keydb_disable_caching (ctx->kr_handle); rc = lookup (ctx, ret_keyblock, &found_key, ctx->want_secret); if (!rc && pk && ret_keyblock) pk_from_block (ctx, pk, *ret_keyblock, found_key); return rc; } /* For documentation see keydb.h. */ void getkey_end (getkey_ctx_t ctx) { if (ctx) { keydb_release (ctx->kr_handle); free_strlist (ctx->extra_list); if (!ctx->not_allocated) xfree (ctx); } } /************************************************ ************* Merging stuff ******************** ************************************************/ /* For documentation see keydb.h. */ void setup_main_keyids (kbnode_t keyblock) { u32 kid[2], mainkid[2]; kbnode_t kbctx, node; PKT_public_key *pk; if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) BUG (); pk = keyblock->pkt->pkt.public_key; keyid_from_pk (pk, mainkid); for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); ) { if (!(node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)) continue; pk = node->pkt->pkt.public_key; keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */ if (!pk->main_keyid[0] && !pk->main_keyid[1]) { pk->main_keyid[0] = mainkid[0]; pk->main_keyid[1] = mainkid[1]; } } } /* For documentation see keydb.h. */ void merge_keys_and_selfsig (KBNODE keyblock) { if (!keyblock) ; else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY) merge_selfsigs (keyblock); else log_debug ("FIXME: merging secret key blocks is not anymore available\n"); } static int parse_key_usage (PKT_signature * sig) { int key_usage = 0; const byte *p; size_t n; byte flags; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n); if (p && n) { /* First octet of the keyflags. */ flags = *p; if (flags & 1) { key_usage |= PUBKEY_USAGE_CERT; flags &= ~1; } if (flags & 2) { key_usage |= PUBKEY_USAGE_SIG; flags &= ~2; } /* We do not distinguish between encrypting communications and encrypting storage. */ if (flags & (0x04 | 0x08)) { key_usage |= PUBKEY_USAGE_ENC; flags &= ~(0x04 | 0x08); } if (flags & 0x20) { key_usage |= PUBKEY_USAGE_AUTH; flags &= ~0x20; } if (flags) key_usage |= PUBKEY_USAGE_UNKNOWN; if (!key_usage) key_usage |= PUBKEY_USAGE_NONE; } else if (p) /* Key flags of length zero. */ key_usage |= PUBKEY_USAGE_NONE; /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a capability that we do not handle. This serves to distinguish between a zero key usage which we handle as the default capabilities for that algorithm, and a usage that we do not handle. Likewise we use PUBKEY_USAGE_NONE to indicate that key_flags have been given but they do not specify any usage. */ return key_usage; } /* Apply information from SIGNODE (which is the valid self-signature * associated with that UID) to the UIDNODE: * - weather the UID has been revoked * - assumed creation date of the UID * - temporary store the keyflags here * - temporary store the key expiration time here * - mark whether the primary user ID flag hat been set. * - store the preferences */ static void fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated) { PKT_user_id *uid = uidnode->pkt->pkt.user_id; PKT_signature *sig = signode->pkt->pkt.signature; const byte *p, *sym, *hash, *zip; size_t n, nsym, nhash, nzip; sig->flags.chosen_selfsig = 1;/* We chose this one. */ uid->created = 0; /* Not created == invalid. */ if (IS_UID_REV (sig)) { uid->is_revoked = 1; return; /* Has been revoked. */ } else uid->is_revoked = 0; uid->expiredate = sig->expiredate; if (sig->flags.expired) { uid->is_expired = 1; return; /* Has expired. */ } else uid->is_expired = 0; uid->created = sig->timestamp; /* This one is okay. */ uid->selfsigversion = sig->version; /* If we got this far, it's not expired :) */ uid->is_expired = 0; /* Store the key flags in the helper variable for later processing. */ uid->help_key_usage = parse_key_usage (sig); /* Ditto for the key expiration. */ p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) uid->help_key_expire = keycreated + buf32_to_u32 (p); else uid->help_key_expire = 0; /* Set the primary user ID flag - we will later wipe out some * of them to only have one in our keyblock. */ uid->is_primary = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL); if (p && *p) uid->is_primary = 2; /* We could also query this from the unhashed area if it is not in * the hased area and then later try to decide which is the better * there should be no security problem with this. * For now we only look at the hashed one. */ /* Now build the preferences list. These must come from the hashed section so nobody can modify the ciphers a key is willing to accept. */ p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n); sym = p; nsym = p ? n : 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n); hash = p; nhash = p ? n : 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n); zip = p; nzip = p ? n : 0; if (uid->prefs) xfree (uid->prefs); n = nsym + nhash + nzip; if (!n) uid->prefs = NULL; else { uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1)); n = 0; for (; nsym; nsym--, n++) { uid->prefs[n].type = PREFTYPE_SYM; uid->prefs[n].value = *sym++; } for (; nhash; nhash--, n++) { uid->prefs[n].type = PREFTYPE_HASH; uid->prefs[n].value = *hash++; } for (; nzip; nzip--, n++) { uid->prefs[n].type = PREFTYPE_ZIP; uid->prefs[n].value = *zip++; } uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */ uid->prefs[n].value = 0; } /* See whether we have the MDC feature. */ uid->flags.mdc = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n); if (p && n && (p[0] & 0x01)) uid->flags.mdc = 1; /* And the keyserver modify flag. */ uid->flags.ks_modify = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n); if (p && n && (p[0] & 0x80)) uid->flags.ks_modify = 0; } static void sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo) { rinfo->date = sig->timestamp; rinfo->algo = sig->pubkey_algo; rinfo->keyid[0] = sig->keyid[0]; rinfo->keyid[1] = sig->keyid[1]; } /* Given a keyblock, parse the key block and extract various pieces of information and save them with the primary key packet and the user id packets. For instance, some information is stored in signature packets. We find the latest such valid packet (since the user can change that information) and copy its contents into the PKT_public_key. Note that R_REVOKED may be set to 0, 1 or 2. This function fills in the following fields in the primary key's keyblock: main_keyid (computed) revkey / numrevkeys (derived from self signed key data) flags.valid (whether we have at least 1 self-sig) flags.maybe_revoked (whether a designed revoked the key, but we are missing the key to check the sig) selfsigversion (highest version of any valid self-sig) pubkey_usage (derived from most recent self-sig or most recent user id) has_expired (various sources) expiredate (various sources) See the documentation for fixup_uidnode for how the user id packets are modified. In addition to that the primary user id's is_primary field is set to 1 and the other user id's is_primary are set to 0. */ static void merge_selfsigs_main (KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo) { PKT_public_key *pk = NULL; KBNODE k; u32 kid[2]; u32 sigdate, uiddate, uiddate2; KBNODE signode, uidnode, uidnode2; u32 curtime = make_timestamp (); unsigned int key_usage = 0; u32 keytimestamp = 0; u32 key_expire = 0; int key_expire_seen = 0; byte sigversion = 0; *r_revoked = 0; memset (rinfo, 0, sizeof (*rinfo)); /* Section 11.1 of RFC 4880 determines the order of packets within a message. There are three sections, which must occur in the following order: the public key, the user ids and user attributes and the subkeys. Within each section, each primary packet (e.g., a user id packet) is followed by one or more signature packets, which modify that packet. */ /* According to Section 11.1 of RFC 4880, the public key must be the first packet. */ if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) /* parse_keyblock_image ensures that the first packet is the public key. */ BUG (); pk = keyblock->pkt->pkt.public_key; keytimestamp = pk->timestamp; keyid_from_pk (pk, kid); pk->main_keyid[0] = kid[0]; pk->main_keyid[1] = kid[1]; if (pk->version < 4) { /* Before v4 the key packet itself contains the expiration date * and there was no way to change it, so we start with the one * from the key packet. */ key_expire = pk->max_expiredate; key_expire_seen = 1; } /* First pass: - Find the latest direct key self-signature. We assume that the newest one overrides all others. - Determine whether the key has been revoked. - Gather all revocation keys (unlike other data, we don't just take them from the latest self-signed packet). - Determine max (sig[...]->version). */ /* Reset this in case this key was already merged. */ xfree (pk->revkey); pk->revkey = NULL; pk->numrevkeys = 0; signode = NULL; sigdate = 0; /* Helper variable to find the latest signature. */ /* According to Section 11.1 of RFC 4880, the public key comes first and is immediately followed by any signature packets that modify it. */ for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID && k->pkt->pkttype != PKT_ATTRIBUTE && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1]) /* Self sig. */ { if (check_key_signature (keyblock, k, NULL)) ; /* Signature did not verify. */ else if (IS_KEY_REV (sig)) { /* Key has been revoked - there is no way to * override such a revocation, so we theoretically * can stop now. We should not cope with expiration * times for revocations here because we have to * assume that an attacker can generate all kinds of * signatures. However due to the fact that the key * has been revoked it does not harm either and by * continuing we gather some more info on that * key. */ *r_revoked = 1; sig_to_revoke_info (sig, rinfo); } else if (IS_KEY_SIG (sig)) { /* Add the indicated revocations keys from all signatures not just the latest. We do this because you need multiple 1F sigs to properly handle revocation keys (PGP does it this way, and a revocation key could be sensitive and hence in a different signature). */ if (sig->revkey) { int i; pk->revkey = xrealloc (pk->revkey, sizeof (struct revocation_key) * (pk->numrevkeys + sig->numrevkeys)); for (i = 0; i < sig->numrevkeys; i++) memcpy (&pk->revkey[pk->numrevkeys++], &sig->revkey[i], sizeof (struct revocation_key)); } if (sig->timestamp >= sigdate) /* This is the latest signature so far. */ { if (sig->flags.expired) ; /* Signature has expired - ignore it. */ else { sigdate = sig->timestamp; signode = k; if (sig->version > sigversion) sigversion = sig->version; } } } } } } /* Remove dupes from the revocation keys. */ if (pk->revkey) { int i, j, x, changed = 0; for (i = 0; i < pk->numrevkeys; i++) { for (j = i + 1; j < pk->numrevkeys; j++) { if (memcmp (&pk->revkey[i], &pk->revkey[j], sizeof (struct revocation_key)) == 0) { /* remove j */ for (x = j; x < pk->numrevkeys - 1; x++) pk->revkey[x] = pk->revkey[x + 1]; pk->numrevkeys--; j--; changed = 1; } } } if (changed) pk->revkey = xrealloc (pk->revkey, pk->numrevkeys * sizeof (struct revocation_key)); } if (signode) /* SIGNODE is the 1F signature packet with the latest creation time. Extract some information from it. */ { /* Some information from a direct key signature take precedence * over the same information given in UID sigs. */ PKT_signature *sig = signode->pkt->pkt.signature; const byte *p; key_usage = parse_key_usage (sig); p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) { key_expire = keytimestamp + buf32_to_u32 (p); key_expire_seen = 1; } /* Mark that key as valid: One direct key signature should * render a key as valid. */ pk->flags.valid = 1; } /* Pass 1.5: Look for key revocation signatures that were not made by the key (i.e. did a revocation key issue a revocation for us?). Only bother to do this if there is a revocation key in the first place and we're not revoked already. */ if (!*r_revoked && pk->revkey) for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = k->pkt->pkt.signature; if (IS_KEY_REV (sig) && (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])) { int rc = check_revocation_keys (pk, sig); if (rc == 0) { *r_revoked = 2; sig_to_revoke_info (sig, rinfo); /* Don't continue checking since we can't be any more revoked than this. */ break; } else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY) pk->flags.maybe_revoked = 1; /* A failure here means the sig did not verify, was not issued by a revocation key, or a revocation key loop was broken. If a revocation key isn't findable, however, the key might be revoked and we don't know it. */ /* TODO: In the future handle subkey and cert revocations? PGP doesn't, but it's in 2440. */ } } } /* Second pass: Look at the self-signature of all user IDs. */ /* According to RFC 4880 section 11.1, user id and attribute packets are in the second section, after the public key packet and before the subkey packets. */ signode = uidnode = NULL; sigdate = 0; /* Helper variable to find the latest signature in one UID. */ for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE) /* New user id packet. */ { if (uidnode && signode) /* Apply the data from the most recent self-signed packet to the preceding user id packet. */ { fixup_uidnode (uidnode, signode, keytimestamp); pk->flags.valid = 1; } /* Clear SIGNODE. The only relevant self-signed data for UIDNODE follows it. */ if (k->pkt->pkttype == PKT_USER_ID) uidnode = k; else uidnode = NULL; signode = NULL; sigdate = 0; } else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1]) { if (check_key_signature (keyblock, k, NULL)) ; /* signature did not verify */ else if ((IS_UID_SIG (sig) || IS_UID_REV (sig)) && sig->timestamp >= sigdate) { /* Note: we allow to invalidate cert revocations * by a newer signature. An attacker can't use this * because a key should be revoked with a key revocation. * The reason why we have to allow for that is that at * one time an email address may become invalid but later * the same email address may become valid again (hired, * fired, hired again). */ sigdate = sig->timestamp; signode = k; signode->pkt->pkt.signature->flags.chosen_selfsig = 0; if (sig->version > sigversion) sigversion = sig->version; } } } } if (uidnode && signode) { fixup_uidnode (uidnode, signode, keytimestamp); pk->flags.valid = 1; } /* If the key isn't valid yet, and we have --allow-non-selfsigned-uid set, then force it valid. */ if (!pk->flags.valid && opt.allow_non_selfsigned_uid) { if (opt.verbose) log_info (_("Invalid key %s made valid by" " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk)); pk->flags.valid = 1; } /* The key STILL isn't valid, so try and find an ultimately trusted signature. */ if (!pk->flags.valid) { uidnode = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) uidnode = k; else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]) { PKT_public_key *ultimate_pk; ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk)); /* We don't want to use the full get_pubkey to avoid infinite recursion in certain cases. There is no reason to check that an ultimately trusted key is still valid - if it has been revoked the user should also remove the ultimate trust flag. */ if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0 && check_key_signature2 (keyblock, k, ultimate_pk, NULL, NULL, NULL, NULL) == 0 && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE) { free_public_key (ultimate_pk); pk->flags.valid = 1; break; } free_public_key (ultimate_pk); } } } } /* Record the highest selfsig version so we know if this is a v3 key through and through, or a v3 key with a v4 selfsig somewhere. This is useful in a few places to know if the key must be treated as PGP2-style or OpenPGP-style. Note that a selfsig revocation with a higher version number will also raise this value. This is okay since such a revocation must be issued by the user (i.e. it cannot be issued by someone else to modify the key behavior.) */ pk->selfsigversion = sigversion; /* Now that we had a look at all user IDs we can now get some information * from those user IDs. */ if (!key_usage) { /* Find the latest user ID with key flags set. */ uiddate = 0; /* Helper to find the latest user ID. */ for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->help_key_usage && uid->created > uiddate) { key_usage = uid->help_key_usage; uiddate = uid->created; } } } } if (!key_usage) { /* No key flags at all: get it from the algo. */ key_usage = openpgp_pk_algo_usage (pk->pubkey_algo); } else { /* Check that the usage matches the usage as given by the algo. */ int x = openpgp_pk_algo_usage (pk->pubkey_algo); if (x) /* Mask it down to the actual allowed usage. */ key_usage &= x; } /* Whatever happens, it's a primary key, so it can certify. */ pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT; if (!key_expire_seen) { /* Find the latest valid user ID with a key expiration set * Note, that this may be a different one from the above because * some user IDs may have no expiration date set. */ uiddate = 0; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->help_key_expire && uid->created > uiddate) { key_expire = uid->help_key_expire; uiddate = uid->created; } } } } /* Currently only v3 keys have a maximum expiration date, but I'll bet v5 keys get this feature again. */ if (key_expire == 0 || (pk->max_expiredate && key_expire > pk->max_expiredate)) key_expire = pk->max_expiredate; pk->has_expired = key_expire >= curtime ? 0 : key_expire; pk->expiredate = key_expire; /* Fixme: we should see how to get rid of the expiretime fields but * this needs changes at other places too. */ /* And now find the real primary user ID and delete all others. */ uiddate = uiddate2 = 0; uidnode = uidnode2 = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->is_primary) { if (uid->created > uiddate) { uiddate = uid->created; uidnode = k; } else if (uid->created == uiddate && uidnode) { /* The dates are equal, so we need to do a different (and arbitrary) comparison. This should rarely, if ever, happen. It's good to try and guarantee that two different GnuPG users with two different keyrings at least pick the same primary. */ if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0) uidnode = k; } } else { if (uid->created > uiddate2) { uiddate2 = uid->created; uidnode2 = k; } else if (uid->created == uiddate2 && uidnode2) { if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0) uidnode2 = k; } } } } if (uidnode) { for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { PKT_user_id *uid = k->pkt->pkt.user_id; if (k != uidnode) uid->is_primary = 0; } } } else if (uidnode2) { /* None is flagged primary - use the latest user ID we have, and disambiguate with the arbitrary packet comparison. */ uidnode2->pkt->pkt.user_id->is_primary = 1; } else { /* None of our uids were self-signed, so pick the one that sorts first to be the primary. This is the best we can do here since there are no self sigs to date the uids. */ uidnode = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { if (!uidnode) { uidnode = k; uidnode->pkt->pkt.user_id->is_primary = 1; continue; } else { if (cmp_user_ids (k->pkt->pkt.user_id, uidnode->pkt->pkt.user_id) > 0) { uidnode->pkt->pkt.user_id->is_primary = 0; uidnode = k; uidnode->pkt->pkt.user_id->is_primary = 1; } else k->pkt->pkt.user_id->is_primary = 0; /* just to be safe */ } } } } } /* Convert a buffer to a signature. Useful for 0x19 embedded sigs. Caller must free the signature when they are done. */ static PKT_signature * buf_to_sig (const byte * buf, size_t len) { PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature)); IOBUF iobuf = iobuf_temp_with_content (buf, len); int save_mode = set_packet_list_mode (0); if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0) { xfree (sig); sig = NULL; } set_packet_list_mode (save_mode); iobuf_close (iobuf); return sig; } /* Use the self-signed data to fill in various fields in subkeys. KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in. Sets the following fields on the subkey: main_keyid flags.valid if the subkey has a valid self-sig binding flags.revoked flags.backsig pubkey_usage has_expired expired_date On this subkey's most revent valid self-signed packet, the following field is set: flags.chosen_selfsig */ static void merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode) { PKT_public_key *mainpk = NULL, *subpk = NULL; PKT_signature *sig; KBNODE k; u32 mainkid[2]; u32 sigdate = 0; KBNODE signode; u32 curtime = make_timestamp (); unsigned int key_usage = 0; u32 keytimestamp = 0; u32 key_expire = 0; const byte *p; if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY) BUG (); mainpk = keyblock->pkt->pkt.public_key; if (mainpk->version < 4) return;/* (actually this should never happen) */ keyid_from_pk (mainpk, mainkid); subpk = subnode->pkt->pkt.public_key; keytimestamp = subpk->timestamp; subpk->flags.valid = 0; subpk->main_keyid[0] = mainpk->main_keyid[0]; subpk->main_keyid[1] = mainpk->main_keyid[1]; /* Find the latest key binding self-signature. */ signode = NULL; sigdate = 0; /* Helper to find the latest signature. */ for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { sig = k->pkt->pkt.signature; if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1]) { if (check_key_signature (keyblock, k, NULL)) ; /* Signature did not verify. */ else if (IS_SUBKEY_REV (sig)) { /* Note that this means that the date on a revocation sig does not matter - even if the binding sig is dated after the revocation sig, the subkey is still marked as revoked. This seems ok, as it is just as easy to make new subkeys rather than re-sign old ones as the problem is in the distribution. Plus, PGP (7) does this the same way. */ subpk->flags.revoked = 1; sig_to_revoke_info (sig, &subpk->revoked); /* Although we could stop now, we continue to * figure out other information like the old expiration * time. */ } else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate) { if (sig->flags.expired) ; /* Signature has expired - ignore it. */ else { sigdate = sig->timestamp; signode = k; signode->pkt->pkt.signature->flags.chosen_selfsig = 0; } } } } } /* No valid key binding. */ if (!signode) return; sig = signode->pkt->pkt.signature; sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */ key_usage = parse_key_usage (sig); if (!key_usage) { /* No key flags at all: get it from the algo. */ key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo); } else { /* Check that the usage matches the usage as given by the algo. */ int x = openpgp_pk_algo_usage (subpk->pubkey_algo); if (x) /* Mask it down to the actual allowed usage. */ key_usage &= x; } subpk->pubkey_usage = key_usage; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) key_expire = keytimestamp + buf32_to_u32 (p); else key_expire = 0; subpk->has_expired = key_expire >= curtime ? 0 : key_expire; subpk->expiredate = key_expire; /* Algo doesn't exist. */ if (openpgp_pk_test_algo (subpk->pubkey_algo)) return; subpk->flags.valid = 1; /* Find the most recent 0x19 embedded signature on our self-sig. */ if (!subpk->flags.backsig) { int seq = 0; size_t n; PKT_signature *backsig = NULL; sigdate = 0; /* We do this while() since there may be other embedded signatures in the future. We only want 0x19 here. */ while ((p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_SIGNATURE, &n, &seq, NULL))) if (n > 3 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19))) { PKT_signature *tempsig = buf_to_sig (p, n); if (tempsig) { if (tempsig->timestamp > sigdate) { if (backsig) free_seckey_enc (backsig); backsig = tempsig; sigdate = backsig->timestamp; } else free_seckey_enc (tempsig); } } seq = 0; /* It is safe to have this in the unhashed area since the 0x19 is located on the selfsig for convenience, not security. */ while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE, &n, &seq, NULL))) if (n > 3 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19))) { PKT_signature *tempsig = buf_to_sig (p, n); if (tempsig) { if (tempsig->timestamp > sigdate) { if (backsig) free_seckey_enc (backsig); backsig = tempsig; sigdate = backsig->timestamp; } else free_seckey_enc (tempsig); } } if (backsig) { /* At this point, backsig contains the most recent 0x19 sig. Let's see if it is good. */ /* 2==valid, 1==invalid, 0==didn't check */ if (check_backsig (mainpk, subpk, backsig) == 0) subpk->flags.backsig = 2; else subpk->flags.backsig = 1; free_seckey_enc (backsig); } } } /* Merge information from the self-signatures with the public key, subkeys and user ids to make using them more easy. See documentation for merge_selfsigs_main, merge_selfsigs_subkey and fixup_uidnode for exactly which fields are updated. */ static void merge_selfsigs (KBNODE keyblock) { KBNODE k; int revoked; struct revoke_info rinfo; PKT_public_key *main_pk; prefitem_t *prefs; unsigned int mdc_feature; if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) { if (keyblock->pkt->pkttype == PKT_SECRET_KEY) { log_error ("expected public key but found secret key " "- must stop\n"); /* We better exit here because a public key is expected at other places too. FIXME: Figure this out earlier and don't get to here at all */ g10_exit (1); } BUG (); } merge_selfsigs_main (keyblock, &revoked, &rinfo); /* Now merge in the data from each of the subkeys. */ for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { merge_selfsigs_subkey (keyblock, k); } } main_pk = keyblock->pkt->pkt.public_key; if (revoked || main_pk->has_expired || !main_pk->flags.valid) { /* If the primary key is revoked, expired, or invalid we * better set the appropriate flags on that key and all * subkeys. */ for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = k->pkt->pkt.public_key; if (!main_pk->flags.valid) pk->flags.valid = 0; if (revoked && !pk->flags.revoked) { pk->flags.revoked = revoked; memcpy (&pk->revoked, &rinfo, sizeof (rinfo)); } if (main_pk->has_expired) pk->has_expired = main_pk->has_expired; } } return; } /* Set the preference list of all keys to those of the primary real * user ID. Note: we use these preferences when we don't know by * which user ID the key has been selected. * fixme: we should keep atoms of commonly used preferences or * use reference counting to optimize the preference lists storage. * FIXME: it might be better to use the intersection of * all preferences. * Do a similar thing for the MDC feature flag. */ prefs = NULL; mdc_feature = 0; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data && k->pkt->pkt.user_id->is_primary) { prefs = k->pkt->pkt.user_id->prefs; mdc_feature = k->pkt->pkt.user_id->flags.mdc; break; } } for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = k->pkt->pkt.public_key; if (pk->prefs) xfree (pk->prefs); pk->prefs = copy_prefs (prefs); pk->flags.mdc = mdc_feature; } } } /* See whether the key satisfies any additional requirements specified in CTX. If so, return 1 and set CTX->FOUND_KEY to an appropriate key or subkey. Otherwise, return 0 if there was no appropriate key. In case the primary key is not required, select a suitable subkey. We need the primary key if PUBKEY_USAGE_CERT is set in CTX->REQ_USAGE or we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in CTX->REQ_USAGE. If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT are set in CTX->REQ_USAGE, we filter by the key's function. Concretely, if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only return a key if it is (at least) either a signing or a certification key. If CTX->REQ_USAGE is set, then we reject any keys that are not good (i.e., valid, not revoked, not expired, etc.). This allows the getkey functions to be used for plain key listings. Sets the matched key's user id field (pk->user_id) to the user id that matched the low-level search criteria or NULL. This function needs to handle several different cases: 1. No requested usage and no primary key requested Examples for this case are that we have a keyID to be used for decrytion or verification. 2. No usage but primary key requested This is the case for all functions which work on an entire keyblock, e.g. for editing or listing 3. Usage and primary key requested FXME 4. Usage but no primary key requested FIXME */ static KBNODE finish_lookup (GETKEY_CTX ctx, KBNODE keyblock) { KBNODE k; /* If CTX->EXACT is set, the key or subkey that actually matched the low-level search criteria. */ KBNODE foundk = NULL; /* The user id (if any) that matched the low-level search criteria. */ PKT_user_id *foundu = NULL; #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT) unsigned int req_usage = (ctx->req_usage & USAGE_MASK); /* Request the primary if we're certifying another key, and also if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7 do not understand signatures made by a signing subkey. PGP 8 does. */ int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) || ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG)); u32 curtime = make_timestamp (); u32 latest_date; KBNODE latest_key; assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY); if (ctx->exact) /* Get the key or subkey that matched the low-level search criteria. */ { for (k = keyblock; k; k = k->next) { if ((k->flag & 1)) { assert (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY); foundk = k; break; } } } /* Get the user id that matched that low-level search criteria. */ for (k = keyblock; k; k = k->next) { if ((k->flag & 2)) { assert (k->pkt->pkttype == PKT_USER_ID); foundu = k->pkt->pkt.user_id; break; } } if (DBG_LOOKUP) log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n", (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL), foundk ? "one" : "all", req_usage); if (!req_usage) { latest_key = foundk ? foundk : keyblock; goto found; } latest_date = 0; latest_key = NULL; /* Set latest_key to the latest (the one with the most recent timestamp) good (valid, not revoked, not expired, etc.) subkey. Don't bother if we are only looking for a primary key or we need an exact match and the exact match is not a subkey. */ if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY)) ; else { KBNODE nextk; /* Either start a loop or check just this one subkey. */ for (k = foundk ? foundk : keyblock; k; k = nextk) { PKT_public_key *pk; if (foundk) /* If FOUNDK is not NULL, then only consider that exact key, i.e., don't iterate. */ nextk = NULL; else nextk = k->next; if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk = k->pkt->pkt.public_key; if (DBG_LOOKUP) log_debug ("\tchecking subkey %08lX\n", (ulong) keyid_from_pk (pk, NULL)); if (!pk->flags.valid) { if (DBG_LOOKUP) log_debug ("\tsubkey not valid\n"); continue; } if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("\tsubkey has been revoked\n"); continue; } if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("\tsubkey has expired\n"); continue; } if (pk->timestamp > curtime && !opt.ignore_valid_from) { if (DBG_LOOKUP) log_debug ("\tsubkey not yet valid\n"); continue; } if (!((pk->pubkey_usage & USAGE_MASK) & req_usage)) { if (DBG_LOOKUP) log_debug ("\tusage does not match: want=%x have=%x\n", req_usage, pk->pubkey_usage); continue; } if (DBG_LOOKUP) log_debug ("\tsubkey might be fine\n"); /* In case a key has a timestamp of 0 set, we make sure that it is used. A better change would be to compare ">=" but that might also change the selected keys and is as such a more intrusive change. */ if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date)) { latest_date = pk->timestamp; latest_key = k; } } } /* Check if the primary key is ok (valid, not revoke, not expire, matches requested usage) if: - we didn't find an appropriate subkey and we're not doing an exact search, - we're doing an exact match and the exact match was the primary key, or, - we're just considering the primary key. */ if ((!latest_key && !ctx->exact) || foundk == keyblock || req_prim) { PKT_public_key *pk; if (DBG_LOOKUP && !foundk && !req_prim) log_debug ("\tno suitable subkeys found - trying primary\n"); pk = keyblock->pkt->pkt.public_key; if (!pk->flags.valid) { if (DBG_LOOKUP) log_debug ("\tprimary key not valid\n"); } else if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("\tprimary key has been revoked\n"); } else if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("\tprimary key has expired\n"); } else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage)) { if (DBG_LOOKUP) log_debug ("\tprimary key usage does not match: " "want=%x have=%x\n", req_usage, pk->pubkey_usage); } else /* Okay. */ { if (DBG_LOOKUP) log_debug ("\tprimary key may be used\n"); latest_key = keyblock; latest_date = pk->timestamp; } } if (!latest_key) { if (DBG_LOOKUP) log_debug ("\tno suitable key found - giving up\n"); return NULL; /* Not found. */ } found: if (DBG_LOOKUP) log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL)); if (latest_key) { PKT_public_key *pk = latest_key->pkt->pkt.public_key; if (pk->user_id) free_user_id (pk->user_id); pk->user_id = scopy_user_id (foundu); } if (latest_key != keyblock && opt.verbose) { char *tempkeystr = xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key)); log_info (_("using subkey %s instead of primary key %s\n"), tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key)); xfree (tempkeystr); } cache_user_id (keyblock); return latest_key ? latest_key : keyblock; /* Found. */ } /* A high-level function to lookup keys. This function builds on top of the low-level keydb API. It first searches the database using the description stored in CTX->ITEMS, then it filters the results using CTX and, finally, if WANT_SECRET is set, it ignores any keys for which no secret key is available. Unlike the low-level search functions, this function also merges all of the self-signed data into the keys, subkeys and user id packets (see the merge_selfsigs for details). On success the key's keyblock is stored at *RET_KEYBLOCK. */ static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key, int want_secret) { int rc; int no_suitable_key = 0; KBNODE keyblock = NULL; KBNODE found_key = NULL; for (;;) { rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL); if (rc) break; /* If we are iterating over the entire database, then we need to change from KEYDB_SEARCH_MODE_FIRST, which does an implicit reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */ if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST) ctx->items->mode = KEYDB_SEARCH_MODE_NEXT; rc = keydb_get_keyblock (ctx->kr_handle, &keyblock); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc)); rc = 0; goto skip; } if (want_secret && agent_probe_any_secret_key (NULL, keyblock)) goto skip; /* No secret key available. */ /* Warning: node flag bits 0 and 1 should be preserved by * merge_selfsigs. For secret keys, premerge transferred the * keys to the keyblock. */ merge_selfsigs (keyblock); found_key = finish_lookup (ctx, keyblock); if (found_key) { no_suitable_key = 0; goto found; } else no_suitable_key = 1; skip: /* Release resources and continue search. */ release_kbnode (keyblock); keyblock = NULL; /* The keyblock cache ignores the current "file position". Thus, if we request the next result and the cache matches (and it will since it is what we just looked for), we'll get the same entry back! We can avoid this infinite loop by disabling the cache. */ keydb_disable_caching (ctx->kr_handle); } found: if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND) log_error ("keydb_search failed: %s\n", gpg_strerror (rc)); if (!rc) { *ret_keyblock = keyblock; /* Return the keyblock. */ keyblock = NULL; } else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key) rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY; else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY; release_kbnode (keyblock); if (ret_found_key) { if (! rc) *ret_found_key = found_key; else *ret_found_key = NULL; } return rc; } /* For documentation see keydb.h. */ gpg_error_t enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk) { gpg_error_t err = 0; const char *name; struct { int eof; int state; strlist_t sl; kbnode_t keyblock; kbnode_t node; } *c = *context; if (!c) { /* Make a new context. */ c = xtrycalloc (1, sizeof *c); if (!c) return gpg_error_from_syserror (); *context = c; } if (!sk) { /* Free the context. */ release_kbnode (c->keyblock); xfree (c); *context = NULL; return 0; } if (c->eof) return gpg_error (GPG_ERR_EOF); for (;;) { /* Loop until we have a keyblock. */ while (!c->keyblock) { /* Loop over the list of secret keys. */ do { name = NULL; switch (c->state) { case 0: /* First try to use the --default-key. */ name = parse_def_secret_key (ctrl); c->state = 1; break; case 1: /* Init list of keys to try. */ c->sl = opt.secret_keys_to_try; c->state++; break; case 2: /* Get next item from list. */ if (c->sl) { name = c->sl->d; c->sl = c->sl->next; } else c->state++; break; default: /* No more names to check - stop. */ c->eof = 1; return gpg_error (GPG_ERR_EOF); } } while (!name || !*name); err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock); if (err) { /* getkey_byname might return a keyblock even in the error case - I have not checked. Thus better release it. */ release_kbnode (c->keyblock); c->keyblock = NULL; } else c->node = c->keyblock; } /* Get the next key from the current keyblock. */ for (; c->node; c->node = c->node->next) { if (c->node->pkt->pkttype == PKT_PUBLIC_KEY || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { copy_public_key (sk, c->node->pkt->pkt.public_key); c->node = c->node->next; return 0; /* Found. */ } } /* Dispose the keyblock and continue. */ release_kbnode (c->keyblock); c->keyblock = NULL; } } /********************************************* *********** User ID printing helpers ******* *********************************************/ /* Return a string with a printable representation of the user_id. * this string must be freed by xfree. */ static char * get_user_id_string (u32 * keyid, int mode, size_t *r_len) { user_id_db_t r; keyid_list_t a; int pass = 0; char *p; /* Try it two times; second pass reads from the database. */ do { for (r = user_id_db; r; r = r->next) { for (a = r->keyids; a; a = a->next) { if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1]) { if (mode == 2) { /* An empty string as user id is possible. Make sure that the malloc allocates one byte and does not bail out. */ p = xmalloc (r->len? r->len : 1); memcpy (p, r->name, r->len); if (r_len) *r_len = r->len; } else { if (mode) p = xasprintf ("%08lX%08lX %.*s", (ulong) keyid[0], (ulong) keyid[1], r->len, r->name); else p = xasprintf ("%s %.*s", keystr (keyid), r->len, r->name); if (r_len) *r_len = strlen (p); } return p; } } } } while (++pass < 2 && !get_pubkey (NULL, keyid)); if (mode == 2) p = xstrdup (user_id_not_found_utf8 ()); else if (mode) p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]); else p = xasprintf ("%s [?]", keystr (keyid)); if (r_len) *r_len = strlen (p); return p; } char * get_user_id_string_native (u32 * keyid) { char *p = get_user_id_string (keyid, 0, NULL); char *p2 = utf8_to_native (p, strlen (p), 0); xfree (p); return p2; } char * get_long_user_id_string (u32 * keyid) { return get_user_id_string (keyid, 1, NULL); } /* Please try to use get_user_byfpr instead of this one. */ char * get_user_id (u32 * keyid, size_t * rn) { return get_user_id_string (keyid, 2, rn); } /* Please try to use get_user_id_byfpr_native instead of this one. */ char * get_user_id_native (u32 * keyid) { size_t rn; char *p = get_user_id (keyid, &rn); char *p2 = utf8_to_native (p, rn, 0); xfree (p); return p2; } /* Return the user id for a key designated by its fingerprint, FPR, which must be MAX_FINGERPRINT_LEN bytes in size. Note: the returned string, which must be freed using xfree, may not be NUL terminated. To determine the length of the string, you must use *RN. */ char * get_user_id_byfpr (const byte *fpr, size_t *rn) { user_id_db_t r; char *p; int pass = 0; /* Try it two times; second pass reads from the database. */ do { for (r = user_id_db; r; r = r->next) { keyid_list_t a; for (a = r->keyids; a; a = a->next) { if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN)) { /* An empty string as user id is possible. Make sure that the malloc allocates one byte and does not bail out. */ p = xmalloc (r->len? r->len : 1); memcpy (p, r->name, r->len); *rn = r->len; return p; } } } } while (++pass < 2 && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN)); p = xstrdup (user_id_not_found_utf8 ()); *rn = strlen (p); return p; } /* Like get_user_id_byfpr, but convert the string to the native encoding. The returned string needs to be freed. Unlike get_user_id_byfpr, the returned string is NUL terminated. */ char * get_user_id_byfpr_native (const byte *fpr) { size_t rn; char *p = get_user_id_byfpr (fpr, &rn); char *p2 = utf8_to_native (p, rn, 0); xfree (p); return p2; } /* For documentation see keydb.h. */ KEYDB_HANDLE get_ctx_handle (GETKEY_CTX ctx) { return ctx->kr_handle; } static void free_akl (struct akl *akl) { if (! akl) return; if (akl->spec) free_keyserver_spec (akl->spec); xfree (akl); } void release_akl (void) { while (opt.auto_key_locate) { struct akl *akl2 = opt.auto_key_locate; opt.auto_key_locate = opt.auto_key_locate->next; free_akl (akl2); } } /* Returns false on error. */ int parse_auto_key_locate (char *options) { char *tok; while ((tok = optsep (&options))) { struct akl *akl, *check, *last = NULL; int dupe = 0; if (tok[0] == '\0') continue; akl = xmalloc_clear (sizeof (*akl)); if (ascii_strcasecmp (tok, "clear") == 0) { xfree (akl); free_akl (opt.auto_key_locate); opt.auto_key_locate = NULL; continue; } else if (ascii_strcasecmp (tok, "nodefault") == 0) akl->type = AKL_NODEFAULT; else if (ascii_strcasecmp (tok, "local") == 0) akl->type = AKL_LOCAL; else if (ascii_strcasecmp (tok, "ldap") == 0) akl->type = AKL_LDAP; else if (ascii_strcasecmp (tok, "keyserver") == 0) akl->type = AKL_KEYSERVER; #ifdef USE_DNS_CERT else if (ascii_strcasecmp (tok, "cert") == 0) akl->type = AKL_CERT; #endif else if (ascii_strcasecmp (tok, "pka") == 0) akl->type = AKL_PKA; else if (ascii_strcasecmp (tok, "dane") == 0) akl->type = AKL_DANE; else if ((akl->spec = parse_keyserver_uri (tok, 1))) akl->type = AKL_SPEC; else { free_akl (akl); return 0; } /* We must maintain the order the user gave us */ for (check = opt.auto_key_locate; check; last = check, check = check->next) { /* Check for duplicates */ if (check->type == akl->type && (akl->type != AKL_SPEC || (akl->type == AKL_SPEC && strcmp (check->spec->uri, akl->spec->uri) == 0))) { dupe = 1; free_akl (akl); break; } } if (!dupe) { if (last) last->next = akl; else opt.auto_key_locate = akl; } } return 1; } /* Returns true if a secret key is available for the public key with key id KEYID; returns false if not. This function ignores legacy keys. Note: this is just a fast check and does not tell us whether the secret key is valid; this check merely indicates whether there is some secret key with the specified key id. */ int have_secret_key_with_kid (u32 *keyid) { gpg_error_t err; KEYDB_HANDLE kdbhd; KEYDB_SEARCH_DESC desc; kbnode_t keyblock; kbnode_t node; int result = 0; kdbhd = keydb_new (); if (!kdbhd) return 0; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0] = keyid[0]; desc.u.kid[1] = keyid[1]; while (!result) { err = keydb_search (kdbhd, &desc, 1, NULL); if (err) break; err = keydb_get_keyblock (kdbhd, &keyblock); if (err) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (err)); break; } for (node = keyblock; node; node = node->next) { /* Bit 0 of the flags is set if the search found the key using that key or subkey. Note: a search will only ever match a single key or subkey. */ if ((node->flag & 1)) { assert (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY); if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key)) result = 1; /* Secret key available. */ else result = 0; break; } } release_kbnode (keyblock); } keydb_release (kdbhd); return result; } diff --git a/g10/gpg.c b/g10/gpg.c index 71f44eddf..0e61238a3 100644 --- a/g10/gpg.c +++ b/g10/gpg.c @@ -1,5483 +1,4971 @@ /* gpg.c - The GnuPG utility (main for gpg) * Copyright (C) 1998-2011 Free Software Foundation, Inc. * Copyright (C) 1997-2014 Werner Koch * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #ifdef HAVE_STAT #include /* for stat() */ #endif #include #ifdef HAVE_W32_SYSTEM # ifdef HAVE_WINSOCK2_H # include # endif # include #endif #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include #include "../common/iobuf.h" #include "util.h" #include "packet.h" #include "membuf.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "filter.h" #include "ttyio.h" #include "i18n.h" #include "sysutils.h" #include "status.h" #include "keyserver-internal.h" #include "exec.h" #include "gc-opt-flags.h" #include "asshelp.h" #include "call-dirmngr.h" #include "tofu.h" #include "../common/init.h" #include "../common/shareddefs.h" #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__) #define MY_O_BINARY O_BINARY #ifndef S_IRGRP # define S_IRGRP 0 # define S_IWGRP 0 #endif #else #define MY_O_BINARY 0 #endif enum cmd_and_opt_values { aNull = 0, oArmor = 'a', aDetachedSign = 'b', aSym = 'c', aDecrypt = 'd', aEncr = 'e', oInteractive = 'i', aListKeys = 'k', oDryRun = 'n', oOutput = 'o', oQuiet = 'q', oRecipient = 'r', oHiddenRecipient = 'R', aSign = 's', oTextmodeShort= 't', oLocalUser = 'u', oVerbose = 'v', oCompress = 'z', oSetNotation = 'N', aListSecretKeys = 'K', oBatch = 500, oMaxOutput, oSigNotation, oCertNotation, oShowNotation, oNoShowNotation, aEncrFiles, aEncrSym, aDecryptFiles, aClearsign, aStore, aQuickKeygen, aFullKeygen, aKeygen, aSignEncr, aSignEncrSym, aSignSym, aSignKey, aLSignKey, aQuickSignKey, aQuickLSignKey, aQuickAddUid, aListConfig, aListGcryptConfig, aGPGConfList, aGPGConfTest, aListPackets, aEditKey, aDeleteKeys, aDeleteSecretKeys, aDeleteSecretAndPublicKeys, aImport, aFastImport, aVerify, aVerifyFiles, aListSigs, aSendKeys, aRecvKeys, aLocateKeys, aSearchKeys, aRefreshKeys, aFetchKeys, aExport, aExportSecret, aExportSecretSub, aCheckKeys, aGenRevoke, aDesigRevoke, aPrimegen, aPrintMD, aPrintMDs, aCheckTrustDB, aUpdateTrustDB, aFixTrustDB, aListTrustDB, aListTrustPath, aExportOwnerTrust, aImportOwnerTrust, aDeArmor, aEnArmor, aGenRandom, aRebuildKeydbCaches, aCardStatus, aCardEdit, aChangePIN, aPasswd, aServer, aTOFUPolicy, oTextmode, oNoTextmode, oExpert, oNoExpert, oDefSigExpire, oAskSigExpire, oNoAskSigExpire, oDefCertExpire, oAskCertExpire, oNoAskCertExpire, oDefCertLevel, oMinCertLevel, oAskCertLevel, oNoAskCertLevel, oFingerprint, oWithFingerprint, oWithICAOSpelling, oWithKeygrip, oWithSecret, oAnswerYes, oAnswerNo, oKeyring, oPrimaryKeyring, oSecretKeyring, oShowKeyring, oDefaultKey, oDefRecipient, oDefRecipientSelf, oNoDefRecipient, oTrySecretKey, oOptions, oDebug, oDebugLevel, oDebugAll, oDebugIOLBF, oStatusFD, oStatusFile, oAttributeFD, oAttributeFile, oEmitVersion, oNoEmitVersion, oCompletesNeeded, oMarginalsNeeded, oMaxCertDepth, oLoadExtension, oGnuPG, oRFC2440, oRFC4880, oOpenPGP, oPGP6, oPGP7, oPGP8, oRFC2440Text, oNoRFC2440Text, oCipherAlgo, oDigestAlgo, oCertDigestAlgo, oCompressAlgo, oCompressLevel, oBZ2CompressLevel, oBZ2DecompressLowmem, oPassphrase, oPassphraseFD, oPassphraseFile, oPassphraseRepeat, oPinentryMode, oCommandFD, oCommandFile, oQuickRandom, oNoVerbose, oTrustDBName, oNoSecmemWarn, oRequireSecmem, oNoRequireSecmem, oNoPermissionWarn, oNoMDCWarn, oNoArmor, oNoDefKeyring, oNoGreeting, oNoTTY, oNoOptions, oNoBatch, oHomedir, oWithColons, oWithKeyData, oWithSigList, oWithSigCheck, oSkipVerify, oSkipHiddenRecipients, oNoSkipHiddenRecipients, oAlwaysTrust, oTrustModel, oForceOwnertrust, oSetFilename, oForYourEyesOnly, oNoForYourEyesOnly, oSetPolicyURL, oSigPolicyURL, oCertPolicyURL, oShowPolicyURL, oNoShowPolicyURL, oSigKeyserverURL, oUseEmbeddedFilename, oNoUseEmbeddedFilename, oComment, oDefaultComment, oNoComments, oThrowKeyids, oNoThrowKeyids, oShowPhotos, oNoShowPhotos, oPhotoViewer, oForceMDC, oNoForceMDC, oDisableMDC, oNoDisableMDC, oS2KMode, oS2KDigest, oS2KCipher, oS2KCount, oDisplayCharset, oNotDashEscaped, oEscapeFrom, oNoEscapeFrom, oLockOnce, oLockMultiple, oLockNever, oKeyServer, oKeyServerOptions, oImportOptions, oExportOptions, oListOptions, oVerifyOptions, oTempDir, oExecPath, oEncryptTo, oHiddenEncryptTo, oNoEncryptTo, oEncryptToDefaultKey, oLoggerFD, oLoggerFile, oUtf8Strings, oNoUtf8Strings, oDisableCipherAlgo, oDisablePubkeyAlgo, oAllowNonSelfsignedUID, oNoAllowNonSelfsignedUID, oAllowFreeformUID, oNoAllowFreeformUID, oAllowSecretKeyImport, oEnableSpecialFilenames, oNoLiteral, oSetFilesize, oHonorHttpProxy, oFastListMode, oListOnly, oIgnoreTimeConflict, oIgnoreValidFrom, oIgnoreCrcError, oIgnoreMDCError, oShowSessionKey, oOverrideSessionKey, oNoRandomSeedFile, oAutoKeyRetrieve, oNoAutoKeyRetrieve, oUseAgent, oNoUseAgent, oGpgAgentInfo, oMergeOnly, oTryAllSecrets, oTrustedKey, oNoExpensiveTrustChecks, oFixedListMode, oLegacyListMode, oNoSigCache, oAutoCheckTrustDB, oNoAutoCheckTrustDB, oPreservePermissions, oDefaultPreferenceList, oDefaultKeyserverURL, oPersonalCipherPreferences, oPersonalDigestPreferences, oPersonalCompressPreferences, oAgentProgram, oDirmngrProgram, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oGroup, oUnGroup, oNoGroups, oStrict, oNoStrict, oMangleDosFilenames, oNoMangleDosFilenames, oEnableProgressFilter, oMultifile, oKeyidFormat, oExitOnStatusWriteError, oLimitCardInsertTries, oReaderPort, octapiDriver, opcscDriver, oDisableCCID, oRequireCrossCert, oNoRequireCrossCert, oAutoKeyLocate, oNoAutoKeyLocate, oAllowMultisigVerification, oEnableLargeRSA, oDisableLargeRSA, oEnableDSA2, oDisableDSA2, oAllowMultipleMessages, oNoAllowMultipleMessages, oAllowWeakDigestAlgos, oFakedSystemTime, oNoAutostart, oPrintPKARecords, oPrintDANERecords, oTOFUDefaultPolicy, oTOFUDBFormat, oWeakDigest, oUnwrap, oOnlySignTextIDs, oNoop }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aSign, "sign", N_("make a signature")), ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")), ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")), ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")), ARGPARSE_c (aEncrFiles, "encrypt-files", "@"), ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")), ARGPARSE_c (aStore, "store", "@"), ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")), ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"), ARGPARSE_c (aVerify, "verify" , N_("verify a signature")), ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ), ARGPARSE_c (aListKeys, "list-keys", N_("list keys")), ARGPARSE_c (aListKeys, "list-public-keys", "@" ), ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")), ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")), ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")), ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")), ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")), ARGPARSE_c (aQuickKeygen, "quick-gen-key" , N_("quickly generate a new key pair")), ARGPARSE_c (aQuickAddUid, "quick-adduid", N_("quickly add a new user-id")), ARGPARSE_c (aFullKeygen, "full-gen-key" , N_("full featured key pair generation")), ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")), ARGPARSE_c (aDeleteKeys,"delete-keys", N_("remove keys from the public keyring")), ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys", N_("remove keys from the secret keyring")), ARGPARSE_c (aQuickSignKey, "quick-sign-key" , N_("quickly sign a key")), ARGPARSE_c (aQuickLSignKey, "quick-lsign-key", N_("quickly sign a key locally")), ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")), ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")), ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")), ARGPARSE_c (aEditKey, "key-edit" ,"@"), ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")), ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ), ARGPARSE_c (aExport, "export" , N_("export keys") ), ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ), ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ), ARGPARSE_c (aSearchKeys, "search-keys" , N_("search for keys on a key server") ), ARGPARSE_c (aRefreshKeys, "refresh-keys", N_("update all keys from a keyserver")), ARGPARSE_c (aLocateKeys, "locate-keys", "@"), ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ), ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ), ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ), ARGPARSE_c (aImport, "import", N_("import/merge keys")), ARGPARSE_c (aFastImport, "fast-import", "@"), #ifdef ENABLE_CARD_SUPPORT ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")), ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")), ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")), #endif ARGPARSE_c (aListConfig, "list-config", "@"), ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"), ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ), ARGPARSE_c (aListPackets, "list-packets","@"), #ifndef NO_TRUST_MODELS ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"), ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"), ARGPARSE_c (aUpdateTrustDB,"update-trustdb", N_("update the trust database")), ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"), ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"), #endif ARGPARSE_c (aDeArmor, "dearmor", "@"), ARGPARSE_c (aDeArmor, "dearmour", "@"), ARGPARSE_c (aEnArmor, "enarmor", "@"), ARGPARSE_c (aEnArmor, "enarmour", "@"), ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")), ARGPARSE_c (aPrimegen, "gen-prime", "@" ), ARGPARSE_c (aGenRandom,"gen-random", "@" ), ARGPARSE_c (aServer, "server", N_("run in server mode")), ARGPARSE_c (aTOFUPolicy, "tofu-policy", N_("|VALUE|set the TOFU policy for a key (good, unknown, bad, ask, auto)")), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")), ARGPARSE_s_n (oArmor, "armour", "@"), ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")), ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"), ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */ ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"), ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"), ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), ARGPARSE_s_s (oTempDir, "temp-directory", "@"), ARGPARSE_s_s (oExecPath, "exec-path", "@"), ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"), ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"), ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"), ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"), ARGPARSE_s_s (oLocalUser, "local-user", N_("|USER-ID|use USER-ID to sign or decrypt")), ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"), ARGPARSE_s_i (oCompress, NULL, N_("|N|set compress level to N (0 disables)")), ARGPARSE_s_i (oCompressLevel, "compress-level", "@"), ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"), ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"), ARGPARSE_s_n (oTextmodeShort, NULL, "@"), ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")), ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"), ARGPARSE_s_n (oExpert, "expert", "@"), ARGPARSE_s_n (oNoExpert, "no-expert", "@"), ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"), ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"), ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"), ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"), ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"), ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"), ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"), ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"), ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"), ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")), ARGPARSE_p_u (oMaxOutput, "max-output", "@"), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", "@"), ARGPARSE_s_n (oNoTTY, "no-tty", "@"), ARGPARSE_s_n (oForceMDC, "force-mdc", "@"), ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"), ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"), ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"), ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")), ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")), ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_n (oAnswerYes, "yes", "@"), ARGPARSE_s_n (oAnswerNo, "no", "@"), ARGPARSE_s_s (oKeyring, "keyring", "@"), ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"), ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"), ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"), ARGPARSE_s_s (oDefaultKey, "default-key", "@"), ARGPARSE_s_s (oKeyServer, "keyserver", "@"), ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"), ARGPARSE_s_s (oImportOptions, "import-options", "@"), ARGPARSE_s_s (oExportOptions, "export-options", "@"), ARGPARSE_s_s (oListOptions, "list-options", "@"), ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"), ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"), ARGPARSE_s_s (oDisplayCharset, "charset", "@"), ARGPARSE_s_s (oOptions, "options", "@"), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"), ARGPARSE_s_i (oStatusFD, "status-fd", "@"), ARGPARSE_s_s (oStatusFile, "status-file", "@"), ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"), ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"), ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"), ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"), ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ), ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"), ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */ ARGPARSE_s_n (oGnuPG, "gnupg", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"), ARGPARSE_s_n (oRFC2440, "rfc2440", "@"), ARGPARSE_s_n (oRFC4880, "rfc4880", "@"), ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")), ARGPARSE_s_n (oPGP6, "pgp6", "@"), ARGPARSE_s_n (oPGP7, "pgp7", "@"), ARGPARSE_s_n (oPGP8, "pgp8", "@"), ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"), ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"), ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"), ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"), ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"), ARGPARSE_s_i (oS2KCount, "s2k-count", "@"), ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"), ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"), ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"), ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"), ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */ ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"), ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"), ARGPARSE_s_n (oShowPhotos, "show-photos", "@"), ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"), ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"), ARGPARSE_s_s (oSetNotation, "set-notation", "@"), ARGPARSE_s_s (oSigNotation, "sig-notation", "@"), ARGPARSE_s_s (oCertNotation, "cert-notation", "@"), ARGPARSE_group (302, N_( "@\n(See the man page for a complete listing of all commands and options)\n" )), ARGPARSE_group (303, N_("@\nExamples:\n\n" " -se -r Bob [file] sign and encrypt for user Bob\n" " --clearsign [file] make a clear text signature\n" " --detach-sign [file] make a detached signature\n" " --list-keys [names] show keys\n" " --fingerprint [names] show fingerprints\n")), /* More hidden commands and options. */ ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */ #ifndef NO_TRUST_MODELS ARGPARSE_c (aListTrustDB, "list-trustdb", "@"), #endif /* Not yet used: ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */ ARGPARSE_c (aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys", "@"), ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"), ARGPARSE_s_s (oPassphrase, "passphrase", "@"), ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"), ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"), ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"), ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"), ARGPARSE_s_i (oCommandFD, "command-fd", "@"), ARGPARSE_s_s (oCommandFile, "command-file", "@"), ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), #ifndef NO_TRUST_MODELS ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"), ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"), ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"), ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"), #endif ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"), ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"), ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"), ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"), ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"), ARGPARSE_s_n (oNoArmor, "no-armor", "@"), ARGPARSE_s_n (oNoArmor, "no-armour", "@"), ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_n (oNoOptions, "no-options", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_n (oNoBatch, "no-batch", "@"), ARGPARSE_s_n (oWithColons, "with-colons", "@"), ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"), ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"), ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"), ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */ ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */ ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */ ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"), ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"), ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"), ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */ ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"), ARGPARSE_s_s (oTrustModel, "trust-model", "@"), ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"), ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"), ARGPARSE_s_s (oSetFilename, "set-filename", "@"), ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"), ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"), ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"), ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"), ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"), ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"), ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"), ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"), ARGPARSE_s_n (oShowNotation, "show-notation", "@"), ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"), ARGPARSE_s_s (oComment, "comment", "@"), ARGPARSE_s_n (oDefaultComment, "default-comment", "@"), ARGPARSE_s_n (oNoComments, "no-comments", "@"), ARGPARSE_s_n (oEmitVersion, "emit-version", "@"), ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"), ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */ ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"), ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"), ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"), ARGPARSE_s_n (oLockOnce, "lock-once", "@"), ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"), ARGPARSE_s_n (oLockNever, "lock-never", "@"), ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"), ARGPARSE_s_s (oLoggerFile, "log-file", "@"), ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */ ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"), ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"), ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"), ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"), ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"), ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"), ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"), ARGPARSE_s_n (oWithSecret, "with-secret", "@"), ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"), ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"), ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"), ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"), ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"), ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"), ARGPARSE_s_n (oNoLiteral, "no-literal", "@"), ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"), ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"), ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"), ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"), ARGPARSE_s_n (oListOnly, "list-only", "@"), ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"), ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"), ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"), ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"), ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"), ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"), ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"), ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"), ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"), ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"), ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"), ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"), ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ), ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"), ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"), ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"), ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"), ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"), ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"), ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"), ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"), ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"), ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-preferences", "@"), ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"), ARGPARSE_s_s (oWeakDigest, "weak-digest","@"), ARGPARSE_s_n (oUnwrap, "unwrap", "@"), ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"), /* Aliases. I constantly mistype these, and assume other people do as well. */ ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"), ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"), ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"), 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_s (oGroup, "group", "@"), ARGPARSE_s_s (oUnGroup, "ungroup", "@"), ARGPARSE_s_n (oNoGroups, "no-groups", "@"), ARGPARSE_s_n (oStrict, "strict", "@"), ARGPARSE_s_n (oNoStrict, "no-strict", "@"), ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"), ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"), ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"), ARGPARSE_s_n (oMultifile, "multifile", "@"), ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"), ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"), ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"), ARGPARSE_s_n (oAllowMultisigVerification, "allow-multisig-verification", "@"), ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"), ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"), ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"), ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"), ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"), ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"), ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"), /* These two are aliases to help users of the PGP command line product use gpg with minimal pain. Many commands are common already as they seem to have borrowed commands from us. Now I'm returning the favor. */ ARGPARSE_s_s (oLocalUser, "sign-with", "@"), ARGPARSE_s_s (oRecipient, "user", "@"), ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"), ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"), ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"), ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"), /* New options. Fixme: Should go more to the top. */ ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"), ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), /* Dummy options with warnings. */ ARGPARSE_s_n (oUseAgent, "use-agent", "@"), ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"), ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"), ARGPARSE_s_s (oReaderPort, "reader-port", "@"), ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"), ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"), ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"), ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"), /* Dummy options. */ ARGPARSE_s_n (oNoop, "sk-comments", "@"), ARGPARSE_s_n (oNoop, "no-sk-comments", "@"), ARGPARSE_s_n (oNoop, "compress-keys", "@"), ARGPARSE_s_n (oNoop, "compress-sigs", "@"), ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"), ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"), ARGPARSE_s_n (oNoop, "force-v4-certs", "@"), ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_PACKET_VALUE , "packet" }, { DBG_MPI_VALUE , "mpi" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_FILTER_VALUE , "filter" }, { DBG_IOBUF_VALUE , "iobuf" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_TRUST_VALUE , "trust" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_CARD_IO_VALUE, "cardio" }, { DBG_IPC_VALUE , "ipc" }, { DBG_CLOCK_VALUE , "clock" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 0, NULL } }; #ifdef ENABLE_SELINUX_HACKS #define ALWAYS_ADD_KEYRINGS 1 #else #define ALWAYS_ADD_KEYRINGS 0 #endif int g10_errors_seen = 0; static int utf8_strings = 0; static int maybe_setuid = 1; static char *build_list( const char *text, char letter, const char *(*mapf)(int), int (*chkf)(int) ); static void set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd ); static void print_mds( const char *fname, int algo ); static void add_notation_data( const char *string, int which ); static void add_policy_url( const char *string, int which ); static void add_keyserver_url( const char *string, int which ); static void emergency_cleanup (void); 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; } static int build_list_pk_test_algo (int algo) { /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA is also available. */ if (algo == PUBKEY_ALGO_RSA_E || algo == PUBKEY_ALGO_RSA_S) return GPG_ERR_DIGEST_ALGO; return openpgp_pk_test_algo (algo); } static const char * build_list_pk_algo_name (int algo) { return openpgp_pk_algo_name (algo); } static int build_list_cipher_test_algo (int algo) { return openpgp_cipher_test_algo (algo); } static const char * build_list_cipher_algo_name (int algo) { return openpgp_cipher_algo_name (algo); } static int build_list_md_test_algo (int algo) { /* By default we do not accept MD5 based signatures. To avoid confusion we do not announce support for it either. */ if (algo == DIGEST_ALGO_MD5) return GPG_ERR_DIGEST_ALGO; return openpgp_md_test_algo (algo); } static const char * build_list_md_algo_name (int algo) { return openpgp_md_algo_name (algo); } static const char * my_strusage( int level ) { static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry; const char *p; switch( level ) { case 11: p = "@GPG@ (@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 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; #ifdef IS_DEVELOPMENT_VERSION case 25: p="NOTE: THIS IS A DEVELOPMENT VERSION!"; break; case 26: p="It is only intended for test purposes and should NOT be"; break; case 27: p="used in a production environment or with production keys!"; break; #endif case 1: case 40: p = _("Usage: @GPG@ [options] [files] (-h for help)"); break; case 41: p = _("Syntax: @GPG@ [options] [files]\n" "Sign, check, encrypt or decrypt\n" "Default operation depends on the input data\n"); break; case 31: p = "\nHome: "; break; #ifndef __riscos__ case 32: p = opt.homedir; break; #else /* __riscos__ */ case 32: p = make_filename(opt.homedir, NULL); break; #endif /* __riscos__ */ case 33: p = _("\nSupported algorithms:\n"); break; case 34: if (!pubkeys) pubkeys = build_list (_("Pubkey: "), 1, build_list_pk_algo_name, build_list_pk_test_algo ); p = pubkeys; break; case 35: if( !ciphers ) ciphers = build_list(_("Cipher: "), 'S', build_list_cipher_algo_name, build_list_cipher_test_algo ); p = ciphers; break; case 36: if( !digests ) digests = build_list(_("Hash: "), 'H', build_list_md_algo_name, build_list_md_test_algo ); p = digests; break; case 37: if( !zips ) zips = build_list(_("Compression: "),'Z', compress_algo_to_string, check_compress_algo); p = zips; break; default: p = NULL; } return p; } static char * build_list (const char *text, char letter, const char * (*mapf)(int), int (*chkf)(int)) { membuf_t mb; int indent; int i, j, len; const char *s; char *string; if (maybe_setuid) gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ indent = utf8_charcount (text, -1); len = 0; init_membuf (&mb, 512); for (i=0; i <= 110; i++ ) { if (!chkf (i) && (s = mapf (i))) { if (mb.len - len > 60) { put_membuf_str (&mb, ",\n"); len = mb.len; for (j=0; j < indent; j++) put_membuf_str (&mb, " "); } else if (mb.len) put_membuf_str (&mb, ", "); else put_membuf_str (&mb, text); put_membuf_str (&mb, s); if (opt.verbose && letter) { char num[20]; if (letter == 1) snprintf (num, sizeof num, " (%d)", i); else snprintf (num, sizeof num, " (%c%d)", letter, i); put_membuf_str (&mb, num); } } } if (mb.len) put_membuf_str (&mb, "\n"); put_membuf (&mb, "", 1); string = get_membuf (&mb, NULL); return xrealloc (string, strlen (string)+1); } static void wrong_args( const char *text) { es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text); g10_exit(2); } static char * make_username( const char *string ) { char *p; if( utf8_strings ) p = xstrdup(string); else p = native_to_utf8( string ); return p; } static void set_opt_session_env (const char *name, const char *value) { gpg_error_t err; err = session_env_setenv (opt.session_env, name, value); if (err) log_fatal ("error setting session environment: %s\n", gpg_strerror (err)); } /* 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 (const char *level) { int numok = (level && digitp (level)); int numlvl = numok? atoi (level) : 0; if (!level) ; else if (!strcmp (level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_MEMSTAT_VALUE; else if (!strcmp (level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE; else if (!strcmp (level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE); else if (!strcmp (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"), level); g10_exit (2); } if (opt.debug & DBG_MEMORY_VALUE ) memory_debug_mode = 1; if (opt.debug & DBG_MEMSTAT_VALUE ) memory_stat_debug_mode = 1; 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); if (opt.debug & DBG_IOBUF_VALUE ) iobuf_debug_mode = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } /* We need the home directory also in some other directories, so make sure that both variables are always in sync. */ static void set_homedir (const char *dir) { if (!dir) dir = ""; opt.homedir = dir; } /* We set the screen dimensions for UI purposes. Do not allow screens smaller than 80x24 for the sake of simplicity. */ static void set_screen_dimensions(void) { #ifndef HAVE_W32_SYSTEM char *str; str=getenv("COLUMNS"); if(str) opt.screen_columns=atoi(str); str=getenv("LINES"); if(str) opt.screen_lines=atoi(str); #endif if(opt.screen_columns<80 || opt.screen_columns>255) opt.screen_columns=80; if(opt.screen_lines<24 || opt.screen_lines>255) opt.screen_lines=24; } /* Helper to open a file FNAME either for reading or writing to be used with --status-file etc functions. Not generally useful but it avoids the riscos specific functions and well some Windows people might like it too. Prints an error message and returns -1 on error. On success the file descriptor is returned. */ static int open_info_file (const char *fname, int for_write, int binary) { #ifdef __riscos__ return riscos_fdopenfile (fname, for_write); #elif defined (ENABLE_SELINUX_HACKS) /* We can't allow these even when testing for a secured filename because files to be secured might not yet been secured. This is similar to the option file but in that case it is unlikely that sensitive information may be retrieved by means of error messages. */ (void)fname; (void)for_write; (void)binary; return -1; #else int fd; if (binary) binary = MY_O_BINARY; /* if (is_secured_filename (fname)) */ /* { */ /* fd = -1; */ /* gpg_err_set_errno (EPERM); */ /* } */ /* else */ /* { */ do { if (for_write) fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); else fd = open (fname, O_RDONLY | binary); } while (fd == -1 && errno == EINTR); /* } */ if ( fd == -1) log_error ( for_write? _("can't create '%s': %s\n") : _("can't open '%s': %s\n"), fname, strerror(errno)); return fd; #endif } static void set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd ) { enum cmd_and_opt_values cmd = *ret_cmd; if( !cmd || cmd == new_cmd ) cmd = new_cmd; else if( cmd == aSign && new_cmd == aEncr ) cmd = aSignEncr; else if( cmd == aEncr && new_cmd == aSign ) cmd = aSignEncr; else if( cmd == aSign && new_cmd == aSym ) cmd = aSignSym; else if( cmd == aSym && new_cmd == aSign ) cmd = aSignSym; else if( cmd == aSym && new_cmd == aEncr ) cmd = aEncrSym; else if( cmd == aEncr && new_cmd == aSym ) cmd = aEncrSym; else if (cmd == aSignEncr && new_cmd == aSym) cmd = aSignEncrSym; else if (cmd == aSignSym && new_cmd == aEncr) cmd = aSignEncrSym; else if (cmd == aEncrSym && new_cmd == aSign) cmd = aSignEncrSym; else if( ( cmd == aSign && new_cmd == aClearsign ) || ( cmd == aClearsign && new_cmd == aSign ) ) cmd = aClearsign; else { log_error(_("conflicting commands\n")); g10_exit(2); } *ret_cmd = cmd; } static void add_group(char *string) { char *name,*value; struct groupitem *item; /* Break off the group name */ name=strsep(&string,"="); if(string==NULL) { log_error(_("no = sign found in group definition '%s'\n"),name); return; } trim_trailing_ws(name,strlen(name)); /* Does this group already exist? */ for(item=opt.grouplist;item;item=item->next) if(strcasecmp(item->name,name)==0) break; if(!item) { item=xmalloc(sizeof(struct groupitem)); item->name=name; item->next=opt.grouplist; item->values=NULL; opt.grouplist=item; } /* Break apart the values */ while ((value= strsep(&string," \t"))) { if (*value) add_to_strlist2(&item->values,value,utf8_strings); } } static void rm_group(char *name) { struct groupitem *item,*last=NULL; trim_trailing_ws(name,strlen(name)); for(item=opt.grouplist;item;last=item,item=item->next) { if(strcasecmp(item->name,name)==0) { if(last) last->next=item->next; else opt.grouplist=item->next; free_strlist(item->values); xfree(item); break; } } } /* We need to check three things. 0) The homedir. It must be x00, a directory, and owned by the user. 1) The options/gpg.conf file. Okay unless it or its containing directory is group or other writable or not owned by us. Disable exec in this case. 2) Extensions. Same as #1. Returns true if the item is unsafe. */ static int check_permissions (const char *path, int item) { #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM) static int homedir_cache=-1; char *tmppath,*dir; struct stat statbuf,dirbuf; int homedir=0,ret=0,checkonly=0; int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0; if(opt.no_perm_warn) return 0; assert(item==0 || item==1 || item==2); /* extensions may attach a path */ if(item==2 && path[0]!=DIRSEP_C) { if(strchr(path,DIRSEP_C)) tmppath=make_filename(path,NULL); else tmppath=make_filename(gnupg_libdir (),path,NULL); } else tmppath=xstrdup(path); /* If the item is located in the homedir, but isn't the homedir, don't continue if we already checked the homedir itself. This is to avoid user confusion with an extra options file warning which could be rectified if the homedir itself had proper permissions. */ if(item!=0 && homedir_cache>-1 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0) { ret=homedir_cache; goto end; } /* It's okay if the file or directory doesn't exist */ if(stat(tmppath,&statbuf)!=0) { ret=0; goto end; } /* Now check the enclosing directory. Theoretically, we could walk this test up to the root directory /, but for the sake of sanity, I'm stopping at one level down. */ dir=make_dirname(tmppath); if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode)) { /* Weird error */ ret=1; goto end; } xfree(dir); /* Assume failure */ ret=1; if(item==0) { /* The homedir must be x00, a directory, and owned by the user. */ if(S_ISDIR(statbuf.st_mode)) { if(statbuf.st_uid==getuid()) { if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0) ret=0; else perm=1; } else own=1; homedir_cache=ret; } } else if(item==1 || item==2) { /* The options or extension file. Okay unless it or its containing directory is group or other writable or not owned by us or root. */ if(S_ISREG(statbuf.st_mode)) { if(statbuf.st_uid==getuid() || statbuf.st_uid==0) { if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0) { /* it's not writable, so make sure the enclosing directory is also not writable */ if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0) { if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0) ret=0; else enc_dir_perm=1; } else enc_dir_own=1; } else { /* it's writable, so the enclosing directory had better not let people get to it. */ if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0) { if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0) ret=0; else perm=enc_dir_perm=1; /* unclear which one to fix! */ } else enc_dir_own=1; } } else own=1; } } else BUG(); if(!checkonly) { if(own) { if(item==0) log_info(_("WARNING: unsafe ownership on" " homedir '%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe ownership on" " configuration file '%s'\n"),tmppath); else log_info(_("WARNING: unsafe ownership on" " extension '%s'\n"),tmppath); } if(perm) { if(item==0) log_info(_("WARNING: unsafe permissions on" " homedir '%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe permissions on" " configuration file '%s'\n"),tmppath); else log_info(_("WARNING: unsafe permissions on" " extension '%s'\n"),tmppath); } if(enc_dir_own) { if(item==0) log_info(_("WARNING: unsafe enclosing directory ownership on" " homedir '%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe enclosing directory ownership on" " configuration file '%s'\n"),tmppath); else log_info(_("WARNING: unsafe enclosing directory ownership on" " extension '%s'\n"),tmppath); } if(enc_dir_perm) { if(item==0) log_info(_("WARNING: unsafe enclosing directory permissions on" " homedir '%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe enclosing directory permissions on" " configuration file '%s'\n"),tmppath); else log_info(_("WARNING: unsafe enclosing directory permissions on" " extension '%s'\n"),tmppath); } } end: xfree(tmppath); if(homedir) homedir_cache=ret; return ret; #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/ (void)path; (void)item; return 0; #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/ } /* Print the OpenPGP defined algo numbers. */ static void print_algo_numbers(int (*checker)(int)) { int i,first=1; for(i=0;i<=110;i++) { if(!checker(i)) { if(first) first=0; else es_printf (";"); es_printf ("%d",i); } } } static void print_algo_names(int (*checker)(int),const char *(*mapper)(int)) { int i,first=1; for(i=0;i<=110;i++) { if(!checker(i)) { if(first) first=0; else es_printf (";"); es_printf ("%s",mapper(i)); } } } /* In the future, we can do all sorts of interesting configuration output here. For now, just give "group" as the Enigmail folks need it, and pubkey, cipher, hash, and compress as they may be useful for frontends. */ static void list_config(char *items) { int show_all = !items; char *name = NULL; const char *s; struct groupitem *giter; int first, iter; if(!opt.with_colons) return; while(show_all || (name=strsep(&items," "))) { int any=0; if(show_all || ascii_strcasecmp(name,"group")==0) { for (giter = opt.grouplist; giter; giter = giter->next) { strlist_t sl; es_fprintf (es_stdout, "cfg:group:"); es_write_sanitized (es_stdout, giter->name, strlen(giter->name), ":", NULL); es_putc (':', es_stdout); for(sl=giter->values; sl; sl=sl->next) { es_write_sanitized (es_stdout, sl->d, strlen (sl->d), ":;", NULL); if(sl->next) es_printf(";"); } es_printf("\n"); } any=1; } if(show_all || ascii_strcasecmp(name,"version")==0) { es_printf("cfg:version:"); es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL); es_printf ("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"pubkey")==0) { es_printf ("cfg:pubkey:"); print_algo_numbers (build_list_pk_test_algo); es_printf ("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"pubkeyname")==0) { es_printf ("cfg:pubkeyname:"); print_algo_names (build_list_pk_test_algo, build_list_pk_algo_name); es_printf ("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"cipher")==0) { es_printf ("cfg:cipher:"); print_algo_numbers (build_list_cipher_test_algo); es_printf ("\n"); any=1; } if (show_all || !ascii_strcasecmp (name,"ciphername")) { es_printf ("cfg:ciphername:"); print_algo_names (build_list_cipher_test_algo, build_list_cipher_algo_name); es_printf ("\n"); any = 1; } if(show_all || ascii_strcasecmp(name,"digest")==0 || ascii_strcasecmp(name,"hash")==0) { es_printf ("cfg:digest:"); print_algo_numbers (build_list_md_test_algo); es_printf ("\n"); any=1; } if (show_all || !ascii_strcasecmp(name,"digestname") || !ascii_strcasecmp(name,"hashname")) { es_printf ("cfg:digestname:"); print_algo_names (build_list_md_test_algo, build_list_md_algo_name); es_printf ("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"compress")==0) { es_printf ("cfg:compress:"); print_algo_numbers(check_compress_algo); es_printf ("\n"); any=1; } if (show_all || !ascii_strcasecmp(name,"ccid-reader-id")) { /* We ignore this for GnuPG 1.4 backward compatibility. */ any=1; } if (show_all || !ascii_strcasecmp (name,"curve")) { es_printf ("cfg:curve:"); for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0) es_printf ("%s%s", first?"":";", s); es_printf ("\n"); any=1; } /* Curve OIDs are rarely useful and thus only printed if requested. */ if (name && !ascii_strcasecmp (name,"curveoid")) { es_printf ("cfg:curveoid:"); for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0) { s = openpgp_curve_to_oid (s, NULL); es_printf ("%s%s", first?"":";", s? s:"[?]"); } es_printf ("\n"); any=1; } if(show_all) break; if(!any) log_error(_("unknown configuration item '%s'\n"),name); } } /* List options and default values in the GPG Conf format. This is a new tool distributed with gnupg 1.9.x but we also want some limited support in older gpg versions. The output is the name of the configuration file and a list of options available for editing by gpgconf. */ static void gpgconf_list (const char *configfile) { char *configfile_esc = percent_escape (configfile, NULL); es_printf ("%s-%s.conf:%lu:\"%s\n", GPGCONF_NAME, GPG_NAME, GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null"); es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT); es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE); /* The next one is an info only item and should match the macros at the top of keygen.c */ es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "RSA-2048"); xfree (configfile_esc); } static int parse_subpacket_list(char *list) { char *tok; byte subpackets[128],i; int count=0; if(!list) { /* No arguments means all subpackets */ memset(subpackets+1,1,sizeof(subpackets)-1); count=127; } else { memset(subpackets,0,sizeof(subpackets)); /* Merge with earlier copy */ if(opt.show_subpackets) { byte *in; for(in=opt.show_subpackets;*in;in++) { if(*in>127 || *in<1) BUG(); if(!subpackets[*in]) count++; subpackets[*in]=1; } } while((tok=strsep(&list," ,"))) { if(!*tok) continue; i=atoi(tok); if(i>127 || i<1) return 0; if(!subpackets[i]) count++; subpackets[i]=1; } } xfree(opt.show_subpackets); opt.show_subpackets=xmalloc(count+1); opt.show_subpackets[count--]=0; for(i=1;i<128 && count>=0;i++) if(subpackets[i]) opt.show_subpackets[count--]=i; return 1; } static int parse_list_options(char *str) { char *subpackets=""; /* something that isn't NULL */ struct parse_options lopts[]= { {"show-photos",LIST_SHOW_PHOTOS,NULL, N_("display photo IDs during key listings")}, {"show-usage",LIST_SHOW_USAGE,NULL, N_("show key usage information during key listings")}, {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL, N_("show policy URLs during signature listings")}, {"show-notations",LIST_SHOW_NOTATIONS,NULL, N_("show all notations during signature listings")}, {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL, N_("show IETF standard notations during signature listings")}, {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL, NULL}, {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL, N_("show user-supplied notations during signature listings")}, {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL, N_("show preferred keyserver URLs during signature listings")}, {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL, N_("show user ID validity during key listings")}, {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL, N_("show revoked and expired user IDs in key listings")}, {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL, N_("show revoked and expired subkeys in key listings")}, {"show-keyring",LIST_SHOW_KEYRING,NULL, N_("show the keyring name in key listings")}, {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL, N_("show expiration dates during signature listings")}, {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL, NULL}, {NULL,0,NULL,NULL} }; /* C99 allows for non-constant initializers, but we'd like to compile everywhere, so fill in the show-sig-subpackets argument here. Note that if the parse_options array changes, we'll have to change the subscript here. */ lopts[13].value=&subpackets; if(parse_options(str,&opt.list_options,lopts,1)) { if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS) { /* Unset so users can pass multiple lists in. */ opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS; if(!parse_subpacket_list(subpackets)) return 0; } else if(subpackets==NULL && opt.show_subpackets) { /* User did 'no-show-subpackets' */ xfree(opt.show_subpackets); opt.show_subpackets=NULL; } return 1; } else return 0; } /* Collapses argc/argv into a single string that must be freed */ static char * collapse_args(int argc,char *argv[]) { char *str=NULL; int i,first=1,len=0; for(i=0;iflags & PK_LIST_CONFIG) - && !(t->flags & PK_LIST_ENCRYPT_TO)); t = t->next) - ; - if (!t) - return 0; - - for (t = s; t; t = t->next) - { - const char *option_str; - int option; - - KEYDB_SEARCH_DESC desc; - struct result *results = NULL; - struct result *r; - - int count; - - /* We also potentially need a ! at the end. */ - char fingerprint[2 * MAX_FINGERPRINT_LEN + 1 + 1]; - char fingerprint2[2 * MAX_FINGERPRINT_LEN + 1]; - - KBNODE best_kb; - PKT_public_key *best_pk; - - /* Whether the key is for encryption or signing. */ - int encrypt = 1; - - /* If the key has been given on the command line and it has not - been given by one of the encrypt-to options, we skip the - checks. The reason is that the actual key selection code - does its own checks and provides proper status message to the - caller to detect the wrong keys. */ - if (!(t->flags & PK_LIST_CONFIG) && !(t->flags & PK_LIST_ENCRYPT_TO)) - { - add_to_strlist (&s2, t->d); - s2->flags = t->flags; - continue; - } - - option = t->flags >> PK_LIST_SHIFT; - switch (option) - { - case oDefaultKey: - option_str = "--default-key"; - encrypt = 0; - break; - case oLocalUser: - option_str = "--local-user"; - encrypt = 0; - break; - - case oEncryptTo: option_str = "--encrypt-to"; break; - case oHiddenEncryptTo: option_str = "--hidden-encrypt-to"; break; - case oEncryptToDefaultKey: option_str = "--encrypt-to-default-key"; break; - case oRecipient: option_str = "--recipient"; break; - case oHiddenRecipient: option_str = "--hidden-recipient"; break; - default: - log_bug ("Unsupport option: %d\n", (t->flags >> PK_LIST_SHIFT)); - } - - if (DBG_LOOKUP) - { - log_debug ("\n"); - log_debug ("%s: Checking %s=%s\n", __func__, option_str, t->d); - } - - err = classify_user_id (t->d, &desc, 1); - if (err) - { - if (! rc) - rc = err; - - log_error (_("key \"%s\" not found: %s\n"), - t->d, gpg_strerror (err)); - if (!opt.quiet) - log_info (_("(check argument of option '%s')\n"), option_str); - continue; - } - - if (warn_possibly_ambiguous - && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID - || desc.mode == KEYDB_SEARCH_MODE_FPR16 - || desc.mode == KEYDB_SEARCH_MODE_FPR20 - || desc.mode == KEYDB_SEARCH_MODE_FPR)) - log_info (_("Warning: value '%s' for option '%s'" - " should be a long key ID or a fingerprint\n"), - t->d, option_str); - - if (! hd) - { - hd = keydb_new (); - if (!hd) - { - rc = gpg_error_from_syserror (); - break; - } - } - else - keydb_search_reset (hd); - - /* Gather all of the results. */ - count = 0; - while (1) - { - KBNODE kb; - - err = keydb_search (hd, &desc, 1, NULL); - if (gpg_err_code (err) == GPG_ERR_NOT_FOUND - || gpg_err_code (err) == GPG_ERR_EOF) - /* No more results. */ - break; - else if (err) - /* An error (other than "not found"). */ - { - log_error (_("error searching the keyring: %s\n"), - gpg_strerror (err)); - break; - } - - err = keydb_get_keyblock (hd, &kb); - if (err) - { - log_error (_("error reading keyblock: %s\n"), gpg_strerror (err)); - break; - } - - /* Another result! */ - count ++; - - r = xmalloc_clear (sizeof (*r)); - r->keyblock = kb; - r->next = results; - results = r; - } - - if (DBG_LOOKUP) - { - log_debug ("%s resulted in %d matches.\n", t->d, count); - for (r = results; r; r = r->next) - log_debug (" %s\n", - hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof (fingerprint))); - } - - if (! results && (gpg_err_code (err) == GPG_ERR_NOT_FOUND - || gpg_err_code (err) == GPG_ERR_EOF)) - /* No match. */ - { - if (DBG_LOOKUP) - log_debug ("%s: '%s' not found.\n", __func__, t->d); - - if (error_if_not_found) - { - if (! rc) - rc = err; - - log_error (_("key \"%s\" not found\n"), t->d); - if (!opt.quiet) - log_info (_("(check argument of option '%s')\n"), option_str); - } - continue; - } - else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND - || gpg_err_code (err) == GPG_ERR_EOF) - /* No more matches. */ - ; - else if (err) - /* Some other error. An error message was already printed - out. Free RESULTS and continue. */ - { - if (! rc) - rc = err; - - while ((r = results)) - { - results = results->next; - release_kbnode (r->keyblock); - xfree (r); - } - - continue; - } - - /* Check for duplicates. */ - - if (DBG_LOOKUP) - log_debug ("%s: Checking results of %s='%s' for dups\n", - __func__, option_str, t->d); - while (1) - { - struct result **prevp; - struct result *next; - struct result *r2; - int dups = 0; - - /* After checking a result, we set R->PROCESSED. Find the - next unprocessed result. */ - for (r = results; r; r = r->next) - if (! r->processed) - break; - - if (! r) - /* There is nothing left to check. */ - break; - - hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof fingerprint); - r->processed = 1; - - prevp = &results; - next = results; - while ((r2 = next)) - { - if (r2->processed) - { - prevp = &r2->next; - next = r2->next; - continue; - } - - hexfingerprint (r2->keyblock->pkt->pkt.public_key, - fingerprint2, sizeof fingerprint2); - - if (strcmp (fingerprint, fingerprint2) != 0) - /* Not a dup. */ - { - prevp = &r2->next; - next = r2->next; - continue; - } - - dups ++; - - /* Remove R2 from the list. */ - *prevp = r2->next; - release_kbnode (r2->keyblock); - next = r2->next; - xfree (r2); - } - - if (dups && ! strlist_find (key_dups, fingerprint)) - { - log_info (_("Warning: %s appears in the keyring %d times.\n"), - format_hexfingerprint (fingerprint, - fingerprint_formatted, - sizeof fingerprint_formatted), - 1 + dups); - add_to_strlist (&key_dups, fingerprint); - } - } - - if (DBG_LOOKUP) - { - log_debug ("After removing dups:\n"); - for (r = results, count = 0; r; r = r->next) - { - count ++; - log_debug (" %d: %s\n", - count, - hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof fingerprint)); - } - } - - /* Now we find the best key. */ - assert (results); - /* Prune invalid keys. */ - { - int ambiguous = 0; - - if (DBG_LOOKUP) - log_debug ("Pruning bad keys.\n"); - - best_pk = NULL; - for (r = results; r; r = r->next) - { - KBNODE kb = r->keyblock; - PKT_public_key *pk = kb->pkt->pkt.public_key; - KBNODE n; - - /* Merge in the data from the self sigs so that things - like the revoked status are available. */ - merge_keys_and_selfsig (kb); - - if (/* Using disabled keys with --encrypt-to is allowed. */ - ! (option == oEncryptTo || option == oHiddenEncryptTo) - && pk_is_disabled (pk)) - { - if (DBG_LOOKUP) - log_debug (" Skipping disabled key: %s\n", - hexfingerprint (pk, fingerprint, - sizeof fingerprint)); - continue; - } - if (pk->flags.revoked) - { - if (DBG_LOOKUP) - log_debug (" Skipping revoked key: %s\n", - hexfingerprint (pk, fingerprint, - sizeof fingerprint)); - continue; - } - if (pk->has_expired) - { - if (DBG_LOOKUP) - log_debug (" Skipping expired key: %s\n", - hexfingerprint (pk, fingerprint, - sizeof fingerprint)); - continue; - } - - /* Check for the required encryption or signing - capability. */ - n = kb; - do - { - PKT_public_key *key = n->pkt->pkt.public_key; - - if ((/* Using disabled keys with --encrypt-to is allowed. */ - pk_is_disabled (key) - && ! (option == oEncryptTo - || option == oHiddenEncryptTo)) - || key->flags.revoked - || key->has_expired) - /* Invalid. */ - continue; - - if (encrypt && ! (key->pubkey_usage & PUBKEY_USAGE_ENC)) - continue; - if (! encrypt && ! (key->pubkey_usage & PUBKEY_USAGE_SIG)) - continue; - - /* Key passes basic tests. */ - break; - } - while ((n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))); - - if (! n) - { - if (DBG_LOOKUP) - log_debug (" Skipping %s, which does not have %s capability.\n", - hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof fingerprint), - encrypt ? "encrypt" : "sign"); - continue; - } - else if (DBG_LOOKUP) - log_debug (" %s is valid and has %s capability.\n", - hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof fingerprint), - encrypt ? "encrypt" : "sign"); - - - if (! best_pk) - { - best_pk = pk; - best_kb = kb; - continue; - } - - /* We have multiple candidates. Prefer the newer key. - - XXX: we should also consider key capabilities (if we - are encrypting to the key, does it have an encryption - capability?). - - XXX: if we are signing, then we should consider the - key that is actually available (e.g., if one is on a - smart card). */ - ambiguous = 1; - if (best_pk->timestamp < pk->timestamp) - best_pk = pk; - } - - if (! results) - { - if (encrypt) - log_error (_("%s: no matching keys are valid encryption keys"), - t->d); - else - log_error (_("%s: no matching keys are valid signing keys"), - t->d); - if (!opt.quiet) - log_info (_("(check argument of option '%s')\n"), option_str); - continue; - } - - if (ambiguous) - { - /* TRANSLATORS: The %s prints a key specification which - for example has been given at the command line. - Lines with fingerprints are printed after this - message. */ - log_error (_("key specification '%s' is ambiguous\n"), - t->d); - if (!opt.quiet) - log_info (_("(check argument of option '%s')\n"), - option_str); - - log_info (_("'%s' matches at least:\n"), t->d); - - for (r = results; r; r = r->next) - log_info (" %s\n", - format_hexfingerprint - (hexfingerprint (r->keyblock->pkt->pkt.public_key, - fingerprint, sizeof fingerprint), - fingerprint_formatted, - sizeof fingerprint_formatted)); - - if (! rc) - rc = GPG_ERR_AMBIGUOUS_NAME; - } - } - - if ((desc.mode == KEYDB_SEARCH_MODE_SHORT_KID - || desc.mode == KEYDB_SEARCH_MODE_LONG_KID - || desc.mode == KEYDB_SEARCH_MODE_FPR16 - || desc.mode == KEYDB_SEARCH_MODE_FPR20) - && strchr (t->d, '!')) - /* Exact search. In this case we want to set FINGERPRINT not - to the primary key, but the key (primary or sub) that - matched the search criteria. Note: there will always be - exactly one match. */ - { - kbnode_t n = best_kb; - PKT_public_key *match = NULL; - int i; - - do - { - if ((n->flag & 1)) - /* The matched node. */ - { - assert (! match); - match = n->pkt->pkt.public_key; - } - } - while ((n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))); - assert (match); - - hexfingerprint (match, fingerprint, sizeof fingerprint); - i = strlen (fingerprint); - fingerprint[i] = '!'; - fingerprint[i + 1] = '\0'; - } - else - hexfingerprint (best_pk, fingerprint, sizeof fingerprint); - - add_to_strlist (&s2, fingerprint); - s2->flags = s->flags; - - { - struct result *next = results; - while ((r = next)) - { - next = r->next; - release_kbnode (r->keyblock); - xfree (r); - } - } - } - - strlist_rev (&s2); - - keydb_release (hd); - - free_strlist (s); - *sp = s2; - return rc; -} - - int main (int argc, char **argv) { ARGPARSE_ARGS pargs; IOBUF a; int rc=0; int orig_argc; char **orig_argv; const char *fname; char *username; int may_coredump; strlist_t sl; strlist_t remusr = NULL; strlist_t locusr = NULL; strlist_t nrings = NULL; armor_filter_context_t *afx = NULL; int detached_sig = 0; FILE *configfp = NULL; char *configname = NULL; char *save_configname = NULL; char *default_configname = NULL; unsigned configlineno; int parse_debug = 0; int default_config = 1; int default_keyring = 1; int greeting = 0; int nogreeting = 0; char *logfile = NULL; int use_random_seed = 1; enum cmd_and_opt_values cmd = 0; const char *debug_level = NULL; #ifndef NO_TRUST_MODELS const char *trustdb_name = NULL; #endif /*!NO_TRUST_MODELS*/ char *def_cipher_string = NULL; char *def_digest_string = NULL; char *compress_algo_string = NULL; char *cert_digest_string = NULL; char *s2k_cipher_string = NULL; char *s2k_digest_string = NULL; char *pers_cipher_list = NULL; char *pers_digest_list = NULL; char *pers_compress_list = NULL; int eyes_only=0; int multifile=0; int pwfd = -1; int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */ int any_explicit_recipient = 0; int require_secmem=0,got_secmem=0; struct assuan_malloc_hooks malloc_hooks; ctrl_t ctrl; #ifdef __riscos__ opt.lock_once = 1; #endif /* __riscos__ */ /* Please note that we may running SUID(ROOT), so be very CAREFUL when adding any stuff between here and the call to secmem_init() somewhere after the option parsing. */ early_system_init (); gnupg_reopen_std (GPG_NAME); trap_unaligned (); gnupg_rl_initialize (); set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); log_set_prefix (GPG_NAME, 1); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); /* Check that the libraries are suitable. Do it right here because the option parsing may need services of the library. */ if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) ) { log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"), NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) ); } /* Use our own logging handler for Libcgrypt. */ setup_libgcrypt_logging (); /* Put random number into secure memory */ gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); may_coredump = disable_core_dumps(); gnupg_init_signals (0, emergency_cleanup); dotlock_create (NULL, 0); /* Register lock file cleanup. */ opt.autostart = 1; opt.session_env = session_env_new (); if (!opt.session_env) log_fatal ("error allocating session environment block: %s\n", strerror (errno)); opt.command_fd = -1; /* no command fd */ opt.compress_level = -1; /* defaults to standard compress level */ opt.bz2_compress_level = -1; /* defaults to standard compress level */ /* note: if you change these lines, look at oOpenPGP */ opt.def_cipher_algo = 0; opt.def_digest_algo = 0; opt.cert_digest_algo = 0; opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */ opt.s2k_mode = 3; /* iterated+salted */ opt.s2k_count = 0; /* Auto-calibrate when needed. */ opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO; opt.completes_needed = 1; opt.marginals_needed = 3; opt.max_cert_depth = 5; opt.escape_from = 1; opt.flags.require_cross_cert = 1; opt.import_options = 0; opt.export_options = EXPORT_ATTRIBUTES; opt.keyserver_options.import_options = IMPORT_REPAIR_PKS_SUBKEY_BUG; opt.keyserver_options.export_options = EXPORT_ATTRIBUTES; opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD; opt.verify_options = (LIST_SHOW_UID_VALIDITY | VERIFY_SHOW_POLICY_URLS | VERIFY_SHOW_STD_NOTATIONS | VERIFY_SHOW_KEYSERVER_URLS); opt.list_options = LIST_SHOW_UID_VALIDITY; #ifdef NO_TRUST_MODELS opt.trust_model = TM_ALWAYS; #else opt.trust_model = TM_AUTO; #endif opt.tofu_default_policy = TOFU_POLICY_AUTO; opt.tofu_db_format = TOFU_DB_AUTO; opt.mangle_dos_filenames = 0; opt.min_cert_level = 2; set_screen_dimensions (); opt.keyid_format = KF_SHORT; opt.def_sig_expire = "0"; opt.def_cert_expire = "0"; set_homedir (default_homedir ()); opt.passphrase_repeat = 1; opt.emit_version = 1; /* Limit to the major number. */ opt.weak_digests = NULL; additional_weak_digest("MD5"); /* Check whether we have a config file on the command line. */ 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++; else if (pargs.r_opt == oDebugIOLBF) es_setvbuf (es_stdout, NULL, _IOLBF, 0); 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 */ opt.no_homedir_creation = 1; } else if( pargs.r_opt == oHomedir ) set_homedir ( pargs.r.ret_str ); else if( pargs.r_opt == oNoPermissionWarn ) opt.no_perm_warn=1; else if (pargs.r_opt == oStrict ) { /* Not used */ } else if (pargs.r_opt == oNoStrict ) { /* Not used */ } } #ifdef HAVE_DOSISH_SYSTEM if ( strchr (opt.homedir,'\\') ) { char *d, *buf = xmalloc (strlen (opt.homedir)+1); const char *s = opt.homedir; for (d=buf,s=opt.homedir; *s; s++) { *d++ = *s == '\\'? '/': *s; #ifdef HAVE_W32_SYSTEM if (s[1] && IsDBCSLeadByte (*s)) *d++ = *++s; #endif } *d = 0; set_homedir (buf); } #endif /* Initialize the secure memory. */ if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0)) got_secmem = 1; #if defined(HAVE_GETUID) && defined(HAVE_GETEUID) /* There should be no way to get to this spot while still carrying setuid privs. Just in case, bomb out if we are. */ if ( getuid () != geteuid () ) BUG (); #endif maybe_setuid = 0; /* Okay, we are now working under our real uid */ /* malloc hooks go here ... */ 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); setup_libassuan_logging (&opt.debug); /* Try for a version specific config file first */ default_configname = get_default_configname (); if (default_config) configname = xstrdup (default_configname); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= ARGPARSE_FLAG_KEEP; /* By this point we have a homedir, and cannot change it. */ check_permissions(opt.homedir,0); next_pass: if( configname ) { if(check_permissions(configname,1)) { /* If any options file is unsafe, then disable any external programs for keyserver calls or photo IDs. Since the external program to call is set in the options file, a unsafe options file can lead to an arbitrary program being run. */ opt.exec_disable=1; } configlineno = 0; configfp = fopen( configname, "r" ); if (configfp && is_secured_file (fileno (configfp))) { fclose (configfp); configfp = NULL; gpg_err_set_errno (EPERM); } 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) ); g10_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) ) { switch( pargs.r_opt ) { case aCheckKeys: case aListConfig: case aListGcryptConfig: case aGPGConfList: case aGPGConfTest: case aListPackets: case aImport: case aFastImport: case aSendKeys: case aRecvKeys: case aSearchKeys: case aRefreshKeys: case aFetchKeys: case aExport: #ifdef ENABLE_CARD_SUPPORT case aCardStatus: case aCardEdit: case aChangePIN: #endif /* ENABLE_CARD_SUPPORT*/ case aListKeys: case aLocateKeys: case aListSigs: case aExportSecret: case aExportSecretSub: case aSym: case aClearsign: case aGenRevoke: case aDesigRevoke: case aPrimegen: case aGenRandom: case aPrintMD: case aPrintMDs: case aListTrustDB: case aCheckTrustDB: case aUpdateTrustDB: case aFixTrustDB: case aListTrustPath: case aDeArmor: case aEnArmor: case aSign: case aQuickSignKey: case aQuickLSignKey: case aSignKey: case aLSignKey: case aStore: case aQuickKeygen: case aQuickAddUid: case aExportOwnerTrust: case aImportOwnerTrust: case aRebuildKeydbCaches: set_cmd (&cmd, pargs.r_opt); break; case aKeygen: case aFullKeygen: case aEditKey: case aDeleteSecretKeys: case aDeleteSecretAndPublicKeys: case aDeleteKeys: case aPasswd: set_cmd (&cmd, pargs.r_opt); greeting=1; break; case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break; case aDecryptFiles: multifile=1; /* fall through */ case aDecrypt: set_cmd( &cmd, aDecrypt); break; case aEncrFiles: multifile=1; /* fall through */ case aEncr: set_cmd( &cmd, aEncr); break; case aVerifyFiles: multifile=1; /* fall through */ case aVerify: set_cmd( &cmd, aVerify); break; case aServer: set_cmd (&cmd, pargs.r_opt); opt.batch = 1; break; case aTOFUPolicy: set_cmd (&cmd, pargs.r_opt); break; case oArmor: opt.armor = 1; opt.no_armor=0; break; case oOutput: opt.outfile = pargs.r.ret_str; break; case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break; case oQuiet: opt.quiet = 1; break; case oNoTTY: tty_no_terminal(1); break; case oDryRun: opt.dry_run = 1; break; case oInteractive: opt.interactive = 1; break; case oVerbose: opt.verbose++; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); opt.list_options|=LIST_SHOW_UNUSABLE_UIDS; opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS; break; case oBatch: opt.batch = 1; nogreeting = 1; break; case oUseAgent: /* Dummy. */ break; case oNoUseAgent: obsolete_option (configname, configlineno, "no-use-agent"); break; case oGpgAgentInfo: obsolete_option (configname, configlineno, "gpg-agent-info"); break; case oReaderPort: obsolete_scdaemon_option (configname, configlineno, "reader-port"); break; case octapiDriver: obsolete_scdaemon_option (configname, configlineno, "ctapi-driver"); break; case opcscDriver: obsolete_scdaemon_option (configname, configlineno, "pcsc-driver"); break; case oDisableCCID: obsolete_scdaemon_option (configname, configlineno, "disable-ccid"); break; case oHonorHttpProxy: obsolete_option (configname, configlineno, "honor-http-proxy"); break; case oAnswerYes: opt.answer_yes = 1; break; case oAnswerNo: opt.answer_no = 1; break; case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break; case oPrimaryKeyring: sl = append_to_strlist (&nrings, pargs.r.ret_str); sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY; break; case oShowKeyring: deprecated_warning(configname,configlineno,"--show-keyring", "--list-options ","show-keyring"); opt.list_options|=LIST_SHOW_KEYRING; 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: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs.r.ret_str; break; case oDebugIOLBF: break; /* Already set in pre-parse step. */ case oStatusFD: set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) ); break; case oStatusFile: set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) ); break; case oAttributeFD: set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) ); break; case oAttributeFile: set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) ); break; case oLoggerFD: log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFile: logfile = pargs.r.ret_str; break; case oWithFingerprint: opt.with_fingerprint = 1; opt.fingerprint++; break; case oWithICAOSpelling: opt.with_icao_spelling = 1; break; case oFingerprint: opt.fingerprint++; fpr_maybe_cmd = 1; break; case oWithKeygrip: opt.with_keygrip = 1; break; case oWithSecret: opt.with_secret = 1; break; case oSecretKeyring: /* Ignore this old option. */ 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 oNoArmor: opt.no_armor=1; opt.armor=0; break; case oNoDefKeyring: default_keyring = 0; break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); opt.list_sigs=0; break; case oQuickRandom: gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); break; case oEmitVersion: opt.emit_version++; break; case oNoEmitVersion: opt.emit_version=0; break; case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break; case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break; case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break; #ifndef NO_TRUST_MODELS case oTrustDBName: trustdb_name = pargs.r.ret_str; break; #endif /*!NO_TRUST_MODELS*/ case oDefaultKey: sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str); sl->flags = (pargs.r_opt << PK_LIST_SHIFT); if (configfp) sl->flags |= PK_LIST_CONFIG; break; case oDefRecipient: if( *pargs.r.ret_str ) { xfree (opt.def_recipient); opt.def_recipient = make_username(pargs.r.ret_str); } break; case oDefRecipientSelf: xfree(opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 1; break; case oNoDefRecipient: xfree(opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 0; break; case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */ case oHomedir: break; case oNoBatch: opt.batch = 0; break; case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/ case oWithColons: opt.with_colons=':'; break; case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/ case oWithSigList: opt.list_sigs = 1; break; case oSkipVerify: opt.skip_verify=1; break; case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break; case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break; case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break; #ifndef NO_TRUST_MODELS /* There are many programs (like mutt) that call gpg with --always-trust so keep this option around for a long time. */ case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break; case oTrustModel: parse_trust_model(pargs.r.ret_str); break; #endif /*!NO_TRUST_MODELS*/ case oTOFUDefaultPolicy: opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str); break; case oTOFUDBFormat: opt.tofu_db_format = parse_tofu_db_format (pargs.r.ret_str); break; case oForceOwnertrust: log_info(_("Note: %s is not for normal use!\n"), "--force-ownertrust"); opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str); if(opt.force_ownertrust==-1) { log_error("invalid ownertrust '%s'\n",pargs.r.ret_str); opt.force_ownertrust=0; } break; case oLoadExtension: /* Dummy so that gpg 1.4 conf files can work. Should eventually be removed. */ break; case oOpenPGP: case oRFC4880: /* This is effectively the same as RFC2440, but with "--enable-dsa2 --no-rfc2440-text --escape-from-lines --require-cross-certification". */ opt.compliance = CO_RFC4880; opt.flags.dsa2 = 1; opt.flags.require_cross_cert = 1; opt.rfc2440_text = 0; opt.allow_non_selfsigned_uid = 1; opt.allow_freeform_uid = 1; opt.escape_from = 1; opt.not_dash_escaped = 0; opt.def_cipher_algo = 0; opt.def_digest_algo = 0; opt.cert_digest_algo = 0; opt.compress_algo = -1; opt.s2k_mode = 3; /* iterated+salted */ opt.s2k_digest_algo = DIGEST_ALGO_SHA1; opt.s2k_cipher_algo = CIPHER_ALGO_3DES; break; case oRFC2440: opt.compliance = CO_RFC2440; opt.flags.dsa2 = 0; opt.rfc2440_text = 1; opt.allow_non_selfsigned_uid = 1; opt.allow_freeform_uid = 1; opt.escape_from = 0; opt.not_dash_escaped = 0; opt.def_cipher_algo = 0; opt.def_digest_algo = 0; opt.cert_digest_algo = 0; opt.compress_algo = -1; opt.s2k_mode = 3; /* iterated+salted */ opt.s2k_digest_algo = DIGEST_ALGO_SHA1; opt.s2k_cipher_algo = CIPHER_ALGO_3DES; break; case oPGP6: opt.compliance = CO_PGP6; break; case oPGP7: opt.compliance = CO_PGP7; break; case oPGP8: opt.compliance = CO_PGP8; break; case oGnuPG: opt.compliance = CO_GNUPG; break; case oRFC2440Text: opt.rfc2440_text=1; break; case oNoRFC2440Text: opt.rfc2440_text=0; break; case oSetFilename: if(utf8_strings) opt.set_filename = pargs.r.ret_str; else opt.set_filename = native_to_utf8(pargs.r.ret_str); break; case oForYourEyesOnly: eyes_only = 1; break; case oNoForYourEyesOnly: eyes_only = 0; break; case oSetPolicyURL: add_policy_url(pargs.r.ret_str,0); add_policy_url(pargs.r.ret_str,1); break; case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break; case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break; case oShowPolicyURL: deprecated_warning(configname,configlineno,"--show-policy-url", "--list-options ","show-policy-urls"); deprecated_warning(configname,configlineno,"--show-policy-url", "--verify-options ","show-policy-urls"); opt.list_options|=LIST_SHOW_POLICY_URLS; opt.verify_options|=VERIFY_SHOW_POLICY_URLS; break; case oNoShowPolicyURL: deprecated_warning(configname,configlineno,"--no-show-policy-url", "--list-options ","no-show-policy-urls"); deprecated_warning(configname,configlineno,"--no-show-policy-url", "--verify-options ","no-show-policy-urls"); opt.list_options&=~LIST_SHOW_POLICY_URLS; opt.verify_options&=~VERIFY_SHOW_POLICY_URLS; break; case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break; case oUseEmbeddedFilename: opt.flags.use_embedded_filename=1; break; case oNoUseEmbeddedFilename: opt.flags.use_embedded_filename=0; break; case oComment: if(pargs.r.ret_str[0]) append_to_strlist(&opt.comments,pargs.r.ret_str); break; case oDefaultComment: deprecated_warning(configname,configlineno, "--default-comment","--no-comments",""); /* fall through */ case oNoComments: free_strlist(opt.comments); opt.comments=NULL; break; case oThrowKeyids: opt.throw_keyids = 1; break; case oNoThrowKeyids: opt.throw_keyids = 0; break; case oShowPhotos: deprecated_warning(configname,configlineno,"--show-photos", "--list-options ","show-photos"); deprecated_warning(configname,configlineno,"--show-photos", "--verify-options ","show-photos"); opt.list_options|=LIST_SHOW_PHOTOS; opt.verify_options|=VERIFY_SHOW_PHOTOS; break; case oNoShowPhotos: deprecated_warning(configname,configlineno,"--no-show-photos", "--list-options ","no-show-photos"); deprecated_warning(configname,configlineno,"--no-show-photos", "--verify-options ","no-show-photos"); opt.list_options&=~LIST_SHOW_PHOTOS; opt.verify_options&=~VERIFY_SHOW_PHOTOS; break; case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break; case oForceMDC: opt.force_mdc = 1; break; case oNoForceMDC: opt.force_mdc = 0; break; case oDisableMDC: opt.disable_mdc = 1; break; case oNoDisableMDC: opt.disable_mdc = 0; break; case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break; case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break; case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break; case oS2KCount: if (pargs.r.ret_int) opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int); else opt.s2k_count = 0; /* Auto-calibrate when needed. */ break; case oNoEncryptTo: opt.no_encrypt_to = 1; break; case oEncryptTo: /* store the recipient in the second list */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO); if (configfp) sl->flags |= PK_LIST_CONFIG; break; case oHiddenEncryptTo: /* store the recipient in the second list */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO|PK_LIST_HIDDEN); if (configfp) sl->flags |= PK_LIST_CONFIG; break; case oEncryptToDefaultKey: opt.encrypt_to_default_key = configfp ? 2 : 1; break; case oRecipient: /* store the recipient */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = (pargs.r_opt << PK_LIST_SHIFT); if (configfp) sl->flags |= PK_LIST_CONFIG; any_explicit_recipient = 1; break; case oHiddenRecipient: /* store the recipient with a flag */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_HIDDEN); if (configfp) sl->flags |= PK_LIST_CONFIG; any_explicit_recipient = 1; break; case oTrySecretKey: add_to_strlist2 (&opt.secret_keys_to_try, pargs.r.ret_str, utf8_strings); break; case oTextmodeShort: opt.textmode = 2; break; case oTextmode: opt.textmode=1; break; case oNoTextmode: opt.textmode=0; break; case oExpert: opt.expert = 1; break; case oNoExpert: opt.expert = 0; break; case oDefSigExpire: if(*pargs.r.ret_str!='\0') { if(parse_expire_string(pargs.r.ret_str)==(u32)-1) log_error(_("'%s' is not a valid signature expiration\n"), pargs.r.ret_str); else opt.def_sig_expire=pargs.r.ret_str; } break; case oAskSigExpire: opt.ask_sig_expire = 1; break; case oNoAskSigExpire: opt.ask_sig_expire = 0; break; case oDefCertExpire: if(*pargs.r.ret_str!='\0') { if(parse_expire_string(pargs.r.ret_str)==(u32)-1) log_error(_("'%s' is not a valid signature expiration\n"), pargs.r.ret_str); else opt.def_cert_expire=pargs.r.ret_str; } break; case oAskCertExpire: opt.ask_cert_expire = 1; break; case oNoAskCertExpire: opt.ask_cert_expire = 0; break; case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break; case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break; case oAskCertLevel: opt.ask_cert_level = 1; break; case oNoAskCertLevel: opt.ask_cert_level = 0; break; case oLocalUser: /* store the local users */ sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings ); sl->flags = (pargs.r_opt << PK_LIST_SHIFT); if (configfp) sl->flags |= PK_LIST_CONFIG; break; case oCompress: /* this is the -z command line option */ opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int; break; case oCompressLevel: opt.compress_level = pargs.r.ret_int; break; case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break; case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break; case oPassphrase: set_passphrase_from_string(pargs.r.ret_str); break; case oPassphraseFD: pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0); break; case oPassphraseFile: pwfd = open_info_file (pargs.r.ret_str, 0, 1); break; case oPassphraseRepeat: opt.passphrase_repeat = pargs.r.ret_int; break; case oPinentryMode: opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str); if (opt.pinentry_mode == -1) log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str); break; case oCommandFD: opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0); break; case oCommandFile: opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1); break; case oCipherAlgo: def_cipher_string = xstrdup(pargs.r.ret_str); break; case oDigestAlgo: def_digest_string = xstrdup(pargs.r.ret_str); break; case oCompressAlgo: /* If it is all digits, stick a Z in front of it for later. This is for backwards compatibility with versions that took the compress algorithm number. */ { char *pt=pargs.r.ret_str; while(*pt) { if (!isascii (*pt) || !isdigit (*pt)) break; pt++; } if(*pt=='\0') { compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2); strcpy(compress_algo_string,"Z"); strcat(compress_algo_string,pargs.r.ret_str); } else compress_algo_string = xstrdup(pargs.r.ret_str); } break; case oCertDigestAlgo: cert_digest_string = xstrdup(pargs.r.ret_str); break; case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break; case oRequireSecmem: require_secmem=1; break; case oNoRequireSecmem: require_secmem=0; break; case oNoPermissionWarn: opt.no_perm_warn=1; break; case oNoMDCWarn: opt.no_mdc_warn=1; break; case oDisplayCharset: if( set_native_charset( pargs.r.ret_str ) ) log_error(_("'%s' is not a valid character set\n"), pargs.r.ret_str); break; case oNotDashEscaped: opt.not_dash_escaped = 1; break; case oEscapeFrom: opt.escape_from = 1; break; case oNoEscapeFrom: opt.escape_from = 0; break; case oLockOnce: opt.lock_once = 1; break; case oLockNever: dotlock_disable (); break; case oLockMultiple: #ifndef __riscos__ opt.lock_once = 0; #else /* __riscos__ */ riscos_not_implemented("lock-multiple"); #endif /* __riscos__ */ break; case oKeyServer: { keyserver_spec_t keyserver; keyserver = parse_keyserver_uri (pargs.r.ret_str, 0); if (!keyserver) log_error (_("could not parse keyserver URL\n")); else { /* We only support a single keyserver. Later ones override earlier ones. (Since we parse the config file first and then the command line arguments, the command line takes precedence.) */ if (opt.keyserver) free_keyserver_spec (opt.keyserver); opt.keyserver = keyserver; } } break; case oKeyServerOptions: if(!parse_keyserver_options(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid keyserver options\n"), configname,configlineno); else log_error(_("invalid keyserver options\n")); } break; case oImportOptions: if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1)) { if(configname) log_error(_("%s:%d: invalid import options\n"), configname,configlineno); else log_error(_("invalid import options\n")); } break; case oExportOptions: if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1)) { if(configname) log_error(_("%s:%d: invalid export options\n"), configname,configlineno); else log_error(_("invalid export options\n")); } break; case oListOptions: if(!parse_list_options(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid list options\n"), configname,configlineno); else log_error(_("invalid list options\n")); } break; case oVerifyOptions: { struct parse_options vopts[]= { {"show-photos",VERIFY_SHOW_PHOTOS,NULL, N_("display photo IDs during signature verification")}, {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL, N_("show policy URLs during signature verification")}, {"show-notations",VERIFY_SHOW_NOTATIONS,NULL, N_("show all notations during signature verification")}, {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL, N_("show IETF standard notations during signature verification")}, {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL, NULL}, {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL, N_("show user-supplied notations during signature verification")}, {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL, N_("show preferred keyserver URLs during signature verification")}, {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL, N_("show user ID validity during signature verification")}, {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL, N_("show revoked and expired user IDs in signature verification")}, {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL, N_("show only the primary user ID in signature verification")}, {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL, N_("validate signatures with PKA data")}, {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL, N_("elevate the trust of signatures with valid PKA data")}, {NULL,0,NULL,NULL} }; if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1)) { if(configname) log_error(_("%s:%d: invalid verify options\n"), configname,configlineno); else log_error(_("invalid verify options\n")); } } break; case oTempDir: opt.temp_dir=pargs.r.ret_str; break; case oExecPath: if(set_exec_path(pargs.r.ret_str)) log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str); else opt.exec_path_set=1; break; case oSetNotation: add_notation_data( pargs.r.ret_str, 0 ); add_notation_data( pargs.r.ret_str, 1 ); break; case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break; case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break; case oShowNotation: deprecated_warning(configname,configlineno,"--show-notation", "--list-options ","show-notations"); deprecated_warning(configname,configlineno,"--show-notation", "--verify-options ","show-notations"); opt.list_options|=LIST_SHOW_NOTATIONS; opt.verify_options|=VERIFY_SHOW_NOTATIONS; break; case oNoShowNotation: deprecated_warning(configname,configlineno,"--no-show-notation", "--list-options ","no-show-notations"); deprecated_warning(configname,configlineno,"--no-show-notation", "--verify-options ","no-show-notations"); opt.list_options&=~LIST_SHOW_NOTATIONS; opt.verify_options&=~VERIFY_SHOW_NOTATIONS; break; case oUtf8Strings: utf8_strings = 1; break; case oNoUtf8Strings: utf8_strings = 0; break; case oDisableCipherAlgo: { int algo = string_to_cipher_algo (pargs.r.ret_str); gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo); } break; case oDisablePubkeyAlgo: { int algo = gcry_pk_map_name (pargs.r.ret_str); gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo); } break; case oNoSigCache: opt.no_sig_cache = 1; break; case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break; case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break; case oAllowFreeformUID: opt.allow_freeform_uid = 1; break; case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break; case oNoLiteral: opt.no_literal = 1; break; case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break; case oFastListMode: opt.fast_list_mode = 1; break; case oFixedListMode: /* Dummy */ break; case oLegacyListMode: opt.legacy_list_mode = 1; break; case oPrintPKARecords: opt.print_pka_records = 1; break; case oPrintDANERecords: opt.print_dane_records = 1; break; case oListOnly: opt.list_only=1; break; case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break; case oIgnoreValidFrom: opt.ignore_valid_from = 1; break; case oIgnoreCrcError: opt.ignore_crc_error = 1; break; case oIgnoreMDCError: opt.ignore_mdc_error = 1; break; case oNoRandomSeedFile: use_random_seed = 0; break; case oAutoKeyRetrieve: case oNoAutoKeyRetrieve: if(pargs.r_opt==oAutoKeyRetrieve) opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE; else opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE; deprecated_warning(configname,configlineno, pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve": "--no-auto-key-retrieve","--keyserver-options ", pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve": "no-auto-key-retrieve"); break; case oShowSessionKey: opt.show_session_key = 1; break; case oOverrideSessionKey: opt.override_session_key = pargs.r.ret_str; break; case oMergeOnly: deprecated_warning(configname,configlineno,"--merge-only", "--import-options ","merge-only"); opt.import_options|=IMPORT_MERGE_ONLY; break; case oAllowSecretKeyImport: /* obsolete */ break; case oTryAllSecrets: opt.try_all_secrets = 1; break; case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break; case oEnableSpecialFilenames: iobuf_enable_special_filenames (1); break; case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break; case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break; case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break; case oPreservePermissions: opt.preserve_permissions=1; break; case oDefaultPreferenceList: opt.def_preference_list = pargs.r.ret_str; break; case oDefaultKeyserverURL: { keyserver_spec_t keyserver; keyserver = parse_keyserver_uri (pargs.r.ret_str,1 ); if (!keyserver) log_error (_("could not parse keyserver URL\n")); else free_keyserver_spec (keyserver); opt.def_keyserver_url = pargs.r.ret_str; } break; case oPersonalCipherPreferences: pers_cipher_list=pargs.r.ret_str; break; case oPersonalDigestPreferences: pers_digest_list=pargs.r.ret_str; break; case oPersonalCompressPreferences: pers_compress_list=pargs.r.ret_str; break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break; case oWeakDigest: additional_weak_digest(pargs.r.ret_str); break; case oUnwrap: opt.unwrap_encryption = 1; break; case oOnlySignTextIDs: opt.only_sign_text_ids = 1; break; case oDisplay: set_opt_session_env ("DISPLAY", pargs.r.ret_str); break; case oTTYname: set_opt_session_env ("GPG_TTY", pargs.r.ret_str); break; case oTTYtype: set_opt_session_env ("TERM", pargs.r.ret_str); break; case oXauthority: set_opt_session_env ("XAUTHORITY", pargs.r.ret_str); break; case oLCctype: opt.lc_ctype = pargs.r.ret_str; break; case oLCmessages: opt.lc_messages = pargs.r.ret_str; break; case oGroup: add_group(pargs.r.ret_str); break; case oUnGroup: rm_group(pargs.r.ret_str); break; case oNoGroups: while(opt.grouplist) { struct groupitem *iter=opt.grouplist; free_strlist(iter->values); opt.grouplist=opt.grouplist->next; xfree(iter); } break; case oStrict: case oNoStrict: /* Not used */ break; case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break; case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break; case oEnableProgressFilter: opt.enable_progress_filter = 1; break; case oMultifile: multifile=1; break; case oKeyidFormat: if(ascii_strcasecmp(pargs.r.ret_str,"short")==0) opt.keyid_format=KF_SHORT; else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0) opt.keyid_format=KF_LONG; else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0) opt.keyid_format=KF_0xSHORT; else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0) opt.keyid_format=KF_0xLONG; else log_error("unknown keyid-format '%s'\n",pargs.r.ret_str); break; case oExitOnStatusWriteError: opt.exit_on_status_write_error = 1; break; case oLimitCardInsertTries: opt.limit_card_insert_tries = pargs.r.ret_int; break; case oRequireCrossCert: opt.flags.require_cross_cert=1; break; case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break; case oAutoKeyLocate: if(!parse_auto_key_locate(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid auto-key-locate list\n"), configname,configlineno); else log_error(_("invalid auto-key-locate list\n")); } break; case oNoAutoKeyLocate: release_akl(); break; case oEnableLargeRSA: #if SECMEM_BUFFER_SIZE >= 65536 opt.flags.large_rsa=1; #else if (configname) log_info("%s:%d: WARNING: gpg not built with large secure " "memory buffer. Ignoring enable-large-rsa\n", configname,configlineno); else log_info("WARNING: gpg not built with large secure " "memory buffer. Ignoring --enable-large-rsa\n"); #endif /* SECMEM_BUFFER_SIZE >= 65536 */ break; case oDisableLargeRSA: opt.flags.large_rsa=0; break; case oEnableDSA2: opt.flags.dsa2=1; break; case oDisableDSA2: opt.flags.dsa2=0; break; case oAllowMultisigVerification: case oAllowMultipleMessages: opt.flags.allow_multiple_messages=1; break; case oNoAllowMultipleMessages: opt.flags.allow_multiple_messages=0; break; case oAllowWeakDigestAlgos: opt.flags.allow_weak_digest_algos = 1; 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 oNoAutostart: opt.autostart = 0; break; case oNoop: break; default: pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR; break; } } if (configfp) { fclose( configfp ); configfp = NULL; /* Remember the first config file name. */ if (!save_configname) save_configname = configname; else xfree(configname); configname = NULL; goto next_pass; } xfree(configname); configname = NULL; if (log_get_errorcount (0)) g10_exit(2); /* The command --gpgconf-list is pretty simple and may be called directly after the option parsing. */ if (cmd == aGPGConfList) { gpgconf_list (save_configname ? save_configname : default_configname); g10_exit (0); } xfree (save_configname); xfree (default_configname); if( nogreeting ) greeting = 0; 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 if (!opt.batch) { const char *s; if((s=strusage(25))) log_info("%s\n",s); if((s=strusage(26))) log_info("%s\n",s); if((s=strusage(27))) log_info("%s\n",s); } #endif /* FIXME: We should use logging to a file only in server mode; however we have not yet implemetyed that. Thus we try to get away with --batch as indication for logging to file required. */ if (logfile && opt.batch) { log_set_file (logfile); log_set_prefix (NULL, 1|2|4); } if (opt.verbose > 2) log_info ("using character set '%s'\n", get_native_charset ()); if( may_coredump && !opt.quiet ) log_info(_("WARNING: program may create a core file!\n")); if (eyes_only) { if (opt.set_filename) log_info(_("WARNING: %s overrides %s\n"), "--for-your-eyes-only","--set-filename"); opt.set_filename="_CONSOLE"; } if (opt.no_literal) { log_info(_("Note: %s is not for normal use!\n"), "--no-literal"); if (opt.textmode) log_error(_("%s not allowed with %s!\n"), "--textmode", "--no-literal" ); if (opt.set_filename) log_error(_("%s makes no sense with %s!\n"), eyes_only?"--for-your-eyes-only":"--set-filename", "--no-literal" ); } if (opt.set_filesize) log_info(_("Note: %s is not for normal use!\n"), "--set-filesize"); if( opt.batch ) tty_batchmode( 1 ); 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 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]); } gcry_control (GCRYCTL_RESUME_SECMEM_WARN); if(require_secmem && !got_secmem) { log_info(_("will not run with insecure memory due to %s\n"), "--require-secmem"); g10_exit(2); } set_debug (debug_level); if (DBG_CLOCK) log_clock ("start"); /* Do these after the switch(), so they can override settings. */ if(PGP6) { /* That does not anymore work because we have no more support for v3 signatures. */ opt.disable_mdc=1; opt.escape_from=1; opt.ask_sig_expire=0; } else if(PGP7) { /* That does not anymore work because we have no more support for v3 signatures. */ opt.escape_from=1; opt.ask_sig_expire=0; } else if(PGP8) { opt.escape_from=1; } if( def_cipher_string ) { opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string); xfree(def_cipher_string); def_cipher_string = NULL; if ( openpgp_cipher_test_algo (opt.def_cipher_algo) ) log_error(_("selected cipher algorithm is invalid\n")); } if( def_digest_string ) { opt.def_digest_algo = string_to_digest_algo (def_digest_string); xfree(def_digest_string); def_digest_string = NULL; if ( openpgp_md_test_algo (opt.def_digest_algo) ) log_error(_("selected digest algorithm is invalid\n")); } if( compress_algo_string ) { opt.compress_algo = string_to_compress_algo(compress_algo_string); xfree(compress_algo_string); compress_algo_string = NULL; if( check_compress_algo(opt.compress_algo) ) log_error(_("selected compression algorithm is invalid\n")); } if( cert_digest_string ) { opt.cert_digest_algo = string_to_digest_algo (cert_digest_string); xfree(cert_digest_string); cert_digest_string = NULL; if (openpgp_md_test_algo(opt.cert_digest_algo)) log_error(_("selected certification digest algorithm is invalid\n")); } if( s2k_cipher_string ) { opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string); xfree(s2k_cipher_string); s2k_cipher_string = NULL; if (openpgp_cipher_test_algo (opt.s2k_cipher_algo)) log_error(_("selected cipher algorithm is invalid\n")); } if( s2k_digest_string ) { opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string); xfree(s2k_digest_string); s2k_digest_string = NULL; if (openpgp_md_test_algo(opt.s2k_digest_algo)) log_error(_("selected digest algorithm is invalid\n")); } if( opt.completes_needed < 1 ) log_error(_("completes-needed must be greater than 0\n")); if( opt.marginals_needed < 2 ) log_error(_("marginals-needed must be greater than 1\n")); if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 ) log_error(_("max-cert-depth must be in the range from 1 to 255\n")); if(opt.def_cert_level<0 || opt.def_cert_level>3) log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n")); if( opt.min_cert_level < 1 || opt.min_cert_level > 3 ) log_error(_("invalid min-cert-level; must be 1, 2, or 3\n")); switch( opt.s2k_mode ) { case 0: log_info(_("Note: simple S2K mode (0) is strongly discouraged\n")); break; case 1: case 3: break; default: log_error(_("invalid S2K mode; must be 0, 1 or 3\n")); } /* This isn't actually needed, but does serve to error out if the string is invalid. */ if(opt.def_preference_list && keygen_set_std_prefs(opt.def_preference_list,0)) log_error(_("invalid default preferences\n")); if(pers_cipher_list && keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM)) log_error(_("invalid personal cipher preferences\n")); if(pers_digest_list && keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH)) log_error(_("invalid personal digest preferences\n")); if(pers_compress_list && keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP)) log_error(_("invalid personal compress preferences\n")); /* We don't support all possible commands with multifile yet */ if(multifile) { char *cmdname; switch(cmd) { case aSign: cmdname="--sign"; break; case aSignEncr: cmdname="--sign --encrypt"; break; case aClearsign: cmdname="--clearsign"; break; case aDetachedSign: cmdname="--detach-sign"; break; case aSym: cmdname="--symmetric"; break; case aEncrSym: cmdname="--symmetric --encrypt"; break; case aStore: cmdname="--store"; break; default: cmdname=NULL; break; } if(cmdname) log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile"); } if( log_get_errorcount(0) ) g10_exit(2); if(opt.compress_level==0) opt.compress_algo=COMPRESS_ALGO_NONE; /* Check our chosen algorithms against the list of legal algorithms. */ if(!GNUPG) { const char *badalg=NULL; preftype_t badtype=PREFTYPE_NONE; if(opt.def_cipher_algo && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL)) { badalg = openpgp_cipher_algo_name (opt.def_cipher_algo); badtype = PREFTYPE_SYM; } else if(opt.def_digest_algo && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL)) { badalg = gcry_md_algo_name (opt.def_digest_algo); badtype = PREFTYPE_HASH; } else if(opt.cert_digest_algo && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL)) { badalg = gcry_md_algo_name (opt.cert_digest_algo); badtype = PREFTYPE_HASH; } else if(opt.compress_algo!=-1 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL)) { badalg = compress_algo_to_string(opt.compress_algo); badtype = PREFTYPE_ZIP; } if(badalg) { switch(badtype) { case PREFTYPE_SYM: log_info(_("you may not use cipher algorithm '%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; case PREFTYPE_HASH: log_info(_("you may not use digest algorithm '%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; case PREFTYPE_ZIP: log_info(_("you may not use compression algorithm '%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; default: BUG(); } compliance_failure(); } } /* Set the random seed file. */ if( use_random_seed ) { char *p = make_filename(opt.homedir, "random_seed", NULL ); gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p); if (!access (p, F_OK)) register_secured_file (p); xfree(p); } /* If there is no command but the --fingerprint is given, default to the --list-keys command. */ if (!cmd && fpr_maybe_cmd) { set_cmd (&cmd, aListKeys); } if( opt.verbose > 1 ) set_packet_list_mode(1); /* Add the keyrings, but not for some special commands. We always need to add the keyrings if we are running under SELinux, this is so that the rings are added to the list of secured files. */ if( ALWAYS_ADD_KEYRINGS || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) ) { if (!nrings || default_keyring) /* Add default ring. */ keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG, KEYDB_RESOURCE_FLAG_DEFAULT); for (sl = nrings; sl; sl = sl->next ) keydb_add_resource (sl->d, sl->flags); } FREE_STRLIST(nrings); if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK) /* In loopback mode, never ask for the password multiple times. */ { opt.passphrase_repeat = 0; } if (cmd == aGPGConfTest) g10_exit(0); if( pwfd != -1 ) /* Read the passphrase now. */ read_passphrase_from_fd( pwfd ); fname = argc? *argv : NULL; if(fname && utf8_strings) opt.flags.utf8_filename=1; ctrl = xcalloc (1, sizeof *ctrl); gpg_init_default_ctrl (ctrl); #ifndef NO_TRUST_MODELS switch (cmd) { case aPrimegen: case aPrintMD: case aPrintMDs: case aGenRandom: case aDeArmor: case aEnArmor: break; case aFixTrustDB: case aExportOwnerTrust: rc = setup_trustdb (0, trustdb_name); break; case aListTrustDB: rc = setup_trustdb (argc? 1:0, trustdb_name); break; default: /* If we are using TM_ALWAYS, we do not need to create the trustdb. */ rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name); break; } if (rc) log_error (_("failed to initialize the TrustDB: %s\n"), gpg_strerror (rc)); #endif /*!NO_TRUST_MODELS*/ switch (cmd) { case aStore: case aSym: case aSign: case aSignSym: case aClearsign: if (!opt.quiet && any_explicit_recipient) log_info (_("WARNING: recipients (-r) given " "without using public key encryption\n")); break; default: break; } /* Check for certain command whether we need to migrate a secring.gpg to the gpg-agent. */ switch (cmd) { case aListSecretKeys: case aSign: case aSignEncr: case aSignEncrSym: case aSignSym: case aClearsign: case aDecrypt: case aSignKey: case aLSignKey: case aEditKey: case aPasswd: case aDeleteSecretKeys: case aDeleteSecretAndPublicKeys: case aQuickKeygen: case aQuickAddUid: case aFullKeygen: case aKeygen: case aImport: case aExportSecret: case aExportSecretSub: case aGenRevoke: case aDesigRevoke: case aCardEdit: case aChangePIN: migrate_secring (ctrl); break; case aListKeys: if (opt.with_secret) migrate_secring (ctrl); break; default: break; } - { - rc = check_user_ids (&locusr, 1, 1); - if (rc) - g10_exit (1); - rc = check_user_ids (&remusr, 0, 1); - if (rc) - g10_exit (1); - rc = check_user_ids (&opt.def_secret_key, 1, 0); - if (rc) - g10_exit (1); - } - /* The command dispatcher. */ switch( cmd ) { case aServer: gpg_server (ctrl); break; case aStore: /* only store the file */ if( argc > 1 ) wrong_args(_("--store [filename]")); if( (rc = encrypt_store(fname)) ) { write_status_failure ("store", rc); log_error ("storing '%s' failed: %s\n", print_fname_stdin(fname),gpg_strerror (rc) ); } break; case aSym: /* encrypt the given file only with the symmetric cipher */ if( argc > 1 ) wrong_args(_("--symmetric [filename]")); if( (rc = encrypt_symmetric(fname)) ) { write_status_failure ("symencrypt", rc); log_error (_("symmetric encryption of '%s' failed: %s\n"), print_fname_stdin(fname),gpg_strerror (rc) ); } break; case aEncr: /* encrypt the given file */ if(multifile) encrypt_crypt_files (ctrl, argc, argv, remusr); else { if( argc > 1 ) wrong_args(_("--encrypt [filename]")); if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) ) { write_status_failure ("encrypt", rc); log_error("%s: encryption failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } } break; case aEncrSym: /* This works with PGP 8 in the sense that it acts just like a symmetric message. It doesn't work at all with 2 or 6. It might work with 7, but alas, I don't have a copy to test with right now. */ if( argc > 1 ) wrong_args(_("--symmetric --encrypt [filename]")); else if(opt.s2k_mode==0) log_error(_("you cannot use --symmetric --encrypt" " with --s2k-mode 0\n")); else if(PGP6 || PGP7) log_error(_("you cannot use --symmetric --encrypt" " while in %s mode\n"),compliance_option_string()); else { if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) ) { write_status_failure ("encrypt", rc); log_error ("%s: encryption failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } } break; case aSign: /* sign the given file */ sl = NULL; if( detached_sig ) { /* sign all files */ for( ; argc; argc--, argv++ ) add_to_strlist( &sl, *argv ); } else { if( argc > 1 ) wrong_args(_("--sign [filename]")); if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } } if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL))) { write_status_failure ("sign", rc); log_error ("signing failed: %s\n", gpg_strerror (rc) ); } free_strlist(sl); break; case aSignEncr: /* sign and encrypt the given file */ if( argc > 1 ) wrong_args(_("--sign --encrypt [filename]")); if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } else sl = NULL; if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL))) { write_status_failure ("sign-encrypt", rc); log_error("%s: sign+encrypt failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } free_strlist(sl); break; case aSignEncrSym: /* sign and encrypt the given file */ if( argc > 1 ) wrong_args(_("--symmetric --sign --encrypt [filename]")); else if(opt.s2k_mode==0) log_error(_("you cannot use --symmetric --sign --encrypt" " with --s2k-mode 0\n")); else if(PGP6 || PGP7) log_error(_("you cannot use --symmetric --sign --encrypt" " while in %s mode\n"),compliance_option_string()); else { if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } else sl = NULL; if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 2, remusr, NULL))) { write_status_failure ("sign-encrypt", rc); log_error("%s: symmetric+sign+encrypt failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } free_strlist(sl); } break; case aSignSym: /* sign and conventionally encrypt the given file */ if (argc > 1) wrong_args(_("--sign --symmetric [filename]")); rc = sign_symencrypt_file (ctrl, fname, locusr); if (rc) { write_status_failure ("sign-symencrypt", rc); log_error("%s: sign+symmetric failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } break; case aClearsign: /* make a clearsig */ if( argc > 1 ) wrong_args(_("--clearsign [filename]")); if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) ) { write_status_failure ("sign", rc); log_error("%s: clearsign failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) ); } break; case aVerify: rc = 0; if (multifile) { if ((rc = verify_files (ctrl, argc, argv))) log_error("verify files failed: %s\n", gpg_strerror (rc) ); } else { if ((rc = verify_signatures (ctrl, argc, argv))) log_error("verify signatures failed: %s\n", gpg_strerror (rc) ); } if (rc) write_status_failure ("verify", rc); break; case aDecrypt: if (multifile) decrypt_messages (ctrl, argc, argv); else { if( argc > 1 ) wrong_args(_("--decrypt [filename]")); if( (rc = decrypt_message (ctrl, fname) )) { write_status_failure ("decrypt", rc); log_error("decrypt_message failed: %s\n", gpg_strerror (rc) ); } } break; case aQuickSignKey: case aQuickLSignKey: { const char *fpr; if (argc < 1) wrong_args ("--quick-[l]sign-key fingerprint [userids]"); fpr = *argv++; argc--; sl = NULL; for( ; argc; argc--, argv++) append_to_strlist2 (&sl, *argv, utf8_strings); keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey)); free_strlist (sl); } break; case aSignKey: if( argc != 1 ) wrong_args(_("--sign-key user-id")); /* fall through */ case aLSignKey: if( argc != 1 ) wrong_args(_("--lsign-key user-id")); /* fall through */ sl=NULL; if(cmd==aSignKey) append_to_strlist(&sl,"sign"); else if(cmd==aLSignKey) append_to_strlist(&sl,"lsign"); else BUG(); append_to_strlist( &sl, "save" ); username = make_username( fname ); keyedit_menu (ctrl, username, locusr, sl, 0, 0 ); xfree(username); free_strlist(sl); break; case aEditKey: /* Edit a key signature */ if( !argc ) wrong_args(_("--edit-key user-id [commands]")); username = make_username( fname ); if( argc > 1 ) { sl = NULL; for( argc--, argv++ ; argc; argc--, argv++ ) append_to_strlist( &sl, *argv ); keyedit_menu (ctrl, username, locusr, sl, 0, 1 ); free_strlist(sl); } else keyedit_menu (ctrl, username, locusr, NULL, 0, 1 ); xfree(username); break; case aPasswd: if (argc != 1) wrong_args (_("--passwd ")); else { username = make_username (fname); keyedit_passwd (ctrl, username); xfree (username); } break; case aDeleteKeys: case aDeleteSecretKeys: case aDeleteSecretAndPublicKeys: sl = NULL; /* I'm adding these in reverse order as add_to_strlist2 reverses them again, and it's easier to understand in the proper order :) */ for( ; argc; argc-- ) add_to_strlist2( &sl, argv[argc-1], utf8_strings ); delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys); free_strlist(sl); break; case aCheckKeys: opt.check_sigs = 1; case aListSigs: opt.list_sigs = 1; case aListKeys: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); public_key_list (ctrl, sl, 0); free_strlist(sl); break; case aListSecretKeys: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); secret_key_list (ctrl, sl); free_strlist(sl); break; case aLocateKeys: sl = NULL; for (; argc; argc--, argv++) add_to_strlist2( &sl, *argv, utf8_strings ); public_key_list (ctrl, sl, 1); free_strlist (sl); break; case aQuickKeygen: if (argc != 1 ) wrong_args("--gen-key user-id"); username = make_username (fname); quick_generate_keypair (ctrl, username); xfree (username); break; case aKeygen: /* generate a key */ if( opt.batch ) { if( argc > 1 ) wrong_args("--gen-key [parameterfile]"); generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0); } else { if (opt.command_fd != -1 && argc) { if( argc > 1 ) wrong_args("--gen-key [parameterfile]"); opt.batch = 1; generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0); } else if (argc) wrong_args ("--gen-key"); else generate_keypair (ctrl, 0, NULL, NULL, 0); } break; case aFullKeygen: /* Generate a key with all options. */ if (opt.batch) { if (argc > 1) wrong_args ("--full-gen-key [parameterfile]"); generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0); } else { if (argc) wrong_args("--full-gen-key"); generate_keypair (ctrl, 1, NULL, NULL, 0); } break; case aQuickAddUid: { const char *uid, *newuid; if (argc != 2) wrong_args ("--quick-adduid USER-ID NEW-USER-ID"); uid = *argv++; argc--; newuid = *argv++; argc--; keyedit_quick_adduid (ctrl, uid, newuid); } break; case aFastImport: opt.import_options |= IMPORT_FAST; case aImport: import_keys (ctrl, argc? argv:NULL, argc, NULL, opt.import_options); break; /* TODO: There are a number of command that use this same "make strlist, call function, report error, free strlist" pattern. Join them together here and avoid all that duplicated code. */ case aExport: case aSendKeys: case aRecvKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); if( cmd == aSendKeys ) rc = keyserver_export (ctrl, sl ); else if( cmd == aRecvKeys ) rc = keyserver_import (ctrl, sl ); else { export_stats_t stats = export_new_stats (); rc = export_pubkeys (ctrl, sl, opt.export_options, stats); export_print_stats (stats); export_release_stats (stats); } if(rc) { if(cmd==aSendKeys) { write_status_failure ("send-keys", rc); log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc)); } else if(cmd==aRecvKeys) { write_status_failure ("recv-keys", rc); log_error (_("keyserver receive failed: %s\n"), gpg_strerror (rc)); } else { write_status_failure ("export", rc); log_error (_("key export failed: %s\n"), gpg_strerror (rc)); } } free_strlist(sl); break; case aSearchKeys: sl = NULL; for (; argc; argc--, argv++) append_to_strlist2 (&sl, *argv, utf8_strings); rc = keyserver_search (ctrl, sl); if (rc) { write_status_failure ("search-keys", rc); log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc)); } free_strlist (sl); break; case aRefreshKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); rc = keyserver_refresh (ctrl, sl); if(rc) { write_status_failure ("refresh-keys", rc); log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc)); } free_strlist(sl); break; case aFetchKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); rc = keyserver_fetch (ctrl, sl); if(rc) { write_status_failure ("fetch-keys", rc); log_error ("key fetch failed: %s\n",gpg_strerror (rc)); } free_strlist(sl); break; case aExportSecret: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); { export_stats_t stats = export_new_stats (); export_seckeys (ctrl, sl, stats); export_print_stats (stats); export_release_stats (stats); } free_strlist(sl); break; case aExportSecretSub: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); { export_stats_t stats = export_new_stats (); export_secsubkeys (ctrl, sl, stats); export_print_stats (stats); export_release_stats (stats); } free_strlist(sl); break; case aGenRevoke: if( argc != 1 ) wrong_args("--gen-revoke user-id"); username = make_username(*argv); gen_revoke( username ); xfree( username ); break; case aDesigRevoke: if (argc != 1) wrong_args ("--desig-revoke user-id"); username = make_username (*argv); gen_desig_revoke (ctrl, username, locusr); xfree (username); break; case aDeArmor: if( argc > 1 ) wrong_args("--dearmor [file]"); rc = dearmor_file( argc? *argv: NULL ); if( rc ) { write_status_failure ("dearmor", rc); log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc)); } break; case aEnArmor: if( argc > 1 ) wrong_args("--enarmor [file]"); rc = enarmor_file( argc? *argv: NULL ); if( rc ) { write_status_failure ("enarmor", rc); log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc)); } break; case aPrimegen: #if 0 /*FIXME*/ { int mode = argc < 2 ? 0 : atoi(*argv); if( mode == 1 && argc == 2 ) { mpi_print (es_stdout, generate_public_prime( atoi(argv[1]) ), 1); } else if( mode == 2 && argc == 3 ) { mpi_print (es_stdout, generate_elg_prime( 0, atoi(argv[1]), atoi(argv[2]), NULL,NULL ), 1); } else if( mode == 3 && argc == 3 ) { MPI *factors; mpi_print (es_stdout, generate_elg_prime( 1, atoi(argv[1]), atoi(argv[2]), NULL,&factors ), 1); es_putc ('\n', es_stdout); mpi_print (es_stdout, factors[0], 1 ); /* print q */ } else if( mode == 4 && argc == 3 ) { MPI g = mpi_alloc(1); mpi_print (es_stdout, generate_elg_prime( 0, atoi(argv[1]), atoi(argv[2]), g, NULL ), 1); es_putc ('\n', es_stdout); mpi_print (es_stdout, g, 1 ); mpi_free (g); } else wrong_args("--gen-prime mode bits [qbits] "); es_putc ('\n', es_stdout); } #endif wrong_args("--gen-prime not yet supported "); break; case aGenRandom: { int level = argc ? atoi(*argv):0; int count = argc > 1 ? atoi(argv[1]): 0; int endless = !count; if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 ) wrong_args("--gen-random 0|1|2 [count]"); while( endless || count ) { byte *p; /* Wee need a multiple of 3, so that in case of armored output we get a correct string. No linefolding is done, as it is best to levae this to other tools */ size_t n = !endless && count < 99? count : 99; p = gcry_random_bytes (n, level); #ifdef HAVE_DOSISH_SYSTEM setmode ( fileno(stdout), O_BINARY ); #endif if (opt.armor) { char *tmp = make_radix64_string (p, n); es_fputs (tmp, es_stdout); xfree (tmp); if (n%3 == 1) es_putc ('=', es_stdout); if (n%3) es_putc ('=', es_stdout); } else { es_fwrite( p, n, 1, es_stdout ); } xfree(p); if( !endless ) count -= n; } if (opt.armor) es_putc ('\n', es_stdout); } break; case aPrintMD: if( argc < 1) wrong_args("--print-md algo [files]"); { int all_algos = (**argv=='*' && !(*argv)[1]); int algo = all_algos? 0 : gcry_md_map_name (*argv); if( !algo && !all_algos ) log_error(_("invalid hash algorithm '%s'\n"), *argv ); else { argc--; argv++; if( !argc ) print_mds(NULL, algo); else { for(; argc; argc--, argv++ ) print_mds(*argv, algo); } } } break; case aPrintMDs: /* old option */ if( !argc ) print_mds(NULL,0); else { for(; argc; argc--, argv++ ) print_mds(*argv,0); } break; #ifndef NO_TRUST_MODELS case aListTrustDB: if( !argc ) list_trustdb (es_stdout, NULL); else { for( ; argc; argc--, argv++ ) list_trustdb (es_stdout, *argv ); } break; case aUpdateTrustDB: if( argc ) wrong_args("--update-trustdb"); update_trustdb(); break; case aCheckTrustDB: /* Old versions allowed for arguments - ignore them */ check_trustdb(); break; case aFixTrustDB: how_to_fix_the_trustdb (); break; case aListTrustPath: if( !argc ) wrong_args("--list-trust-path "); for( ; argc; argc--, argv++ ) { username = make_username( *argv ); list_trust_path( username ); xfree(username); } break; case aExportOwnerTrust: if( argc ) wrong_args("--export-ownertrust"); export_ownertrust(); break; case aImportOwnerTrust: if( argc > 1 ) wrong_args("--import-ownertrust [file]"); import_ownertrust( argc? *argv:NULL ); break; #endif /*!NO_TRUST_MODELS*/ case aRebuildKeydbCaches: if (argc) wrong_args ("--rebuild-keydb-caches"); keydb_rebuild_caches (1); break; #ifdef ENABLE_CARD_SUPPORT case aCardStatus: if (argc) wrong_args ("--card-status"); card_status (es_stdout, NULL, 0); break; case aCardEdit: if (argc) { sl = NULL; for (argc--, argv++ ; argc; argc--, argv++) append_to_strlist (&sl, *argv); card_edit (ctrl, sl); free_strlist (sl); } else card_edit (ctrl, NULL); break; case aChangePIN: if (!argc) change_pin (0,1); else if (argc == 1) change_pin (atoi (*argv),1); else wrong_args ("--change-pin [no]"); break; #endif /* ENABLE_CARD_SUPPORT*/ case aListConfig: { char *str=collapse_args(argc,argv); list_config(str); xfree(str); } break; case aListGcryptConfig: /* Fixme: It would be nice to integrate that with --list-config but unfortunately there is no way yet to have libgcrypt print it to an estream for further parsing. */ gcry_control (GCRYCTL_PRINT_CONFIG, stdout); break; case aTOFUPolicy: #ifdef USE_TOFU { int policy; int i; KEYDB_HANDLE hd; if (argc < 2) wrong_args ("--tofu-policy POLICY KEYID [KEYID...]"); policy = parse_tofu_policy (argv[0]); hd = keydb_new (); if (! hd) g10_exit (1); for (i = 1; i < argc; i ++) { KEYDB_SEARCH_DESC desc; kbnode_t kb; rc = classify_user_id (argv[i], &desc, 0); if (rc) { log_error (_("error parsing key specification '%s': %s\n"), argv[i], gpg_strerror (rc)); g10_exit (1); } if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID || desc.mode == KEYDB_SEARCH_MODE_LONG_KID || desc.mode == KEYDB_SEARCH_MODE_FPR16 || desc.mode == KEYDB_SEARCH_MODE_FPR20 || desc.mode == KEYDB_SEARCH_MODE_FPR || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP)) { log_error (_("'%s' does not appear to be a valid" " key ID, fingerprint or keygrip\n"), argv[i]); g10_exit (1); } rc = keydb_search_reset (hd); if (rc) { /* This should not happen, thus no need to tranalate the string. */ log_error ("keydb_search_reset failed: %s\n", gpg_strerror (rc)); g10_exit (1); } rc = keydb_search (hd, &desc, 1, NULL); if (rc) { log_error (_("key \"%s\" not found: %s\n"), argv[i], gpg_strerror (rc)); g10_exit (1); } rc = keydb_get_keyblock (hd, &kb); if (rc) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (rc)); g10_exit (1); } merge_keys_and_selfsig (kb); if (tofu_set_policy (kb, policy)) g10_exit (1); } keydb_release (hd); } #endif /*USE_TOFU*/ break; case aListPackets: opt.list_packets=2; default: if( argc > 1 ) wrong_args(_("[filename]")); /* Issue some output for the unix newbie */ if (!fname && !opt.outfile && gnupg_isatty (fileno (stdin)) && gnupg_isatty (fileno (stdout)) && gnupg_isatty (fileno (stderr))) log_info(_("Go ahead and type your message ...\n")); a = iobuf_open(fname); if (a && is_secured_file (iobuf_get_fd (a))) { iobuf_close (a); a = NULL; gpg_err_set_errno (EPERM); } if( !a ) log_error(_("can't open '%s'\n"), print_fname_stdin(fname)); else { if( !opt.no_armor ) { if( use_armor_filter( a ) ) { afx = new_armor_context (); push_armor_filter (afx, a); } } if( cmd == aListPackets ) { set_packet_list_mode(1); opt.list_packets=1; } rc = proc_packets (ctrl, NULL, a ); if( rc ) { write_status_failure ("-", rc); log_error ("processing message failed: %s\n", gpg_strerror (rc)); } iobuf_close(a); } break; } /* cleanup */ gpg_deinit_default_ctrl (ctrl); xfree (ctrl); release_armor_context (afx); FREE_STRLIST(remusr); FREE_STRLIST(locusr); g10_exit(0); return 8; /*NEVER REACHED*/ } /* 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); if (DBG_CLOCK) log_clock ("stop"); if ( (opt.debug & DBG_MEMSTAT_VALUE) ) { keydb_dump_stats (); gcry_control (GCRYCTL_DUMP_MEMORY_STATS); gcry_control (GCRYCTL_DUMP_RANDOM_STATS); } if (opt.debug) gcry_control (GCRYCTL_DUMP_SECMEM_STATS ); emergency_cleanup (); rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit (rc); } /* Pretty-print hex hashes. This assumes at least an 80-character display, but there are a few other similar assumptions in the display code. */ static void print_hex (gcry_md_hd_t md, int algo, const char *fname) { int i,n,count,indent=0; const byte *p; if (fname) indent = es_printf("%s: ",fname); if (indent>40) { es_printf ("\n"); indent=0; } if (algo==DIGEST_ALGO_RMD160) indent += es_printf("RMD160 = "); else if (algo>0) indent += es_printf("%6s = ", gcry_md_algo_name (algo)); else algo = abs(algo); count = indent; p = gcry_md_read (md, algo); n = gcry_md_get_algo_dlen (algo); count += es_printf ("%02X",*p++); for(i=1;i79) { es_printf ("\n%*s",indent," "); count = indent; } else count += es_printf(" "); if (!(i%8)) count += es_printf(" "); } else if (n==20) { if(!(i%2)) { if(count+4>79) { es_printf ("\n%*s",indent," "); count=indent; } else count += es_printf(" "); } if (!(i%10)) count += es_printf(" "); } else { if(!(i%4)) { if (count+8>79) { es_printf ("\n%*s",indent," "); count=indent; } else count += es_printf(" "); } } count += es_printf("%02X",*p); } es_printf ("\n"); } static void print_hashline( gcry_md_hd_t md, int algo, const char *fname ) { int i, n; const byte *p; if ( fname ) { for (p = fname; *p; p++ ) { if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' ) es_printf ("%%%02X", *p ); else es_putc (*p, es_stdout); } } es_putc (':', es_stdout); es_printf ("%d:", algo); p = gcry_md_read (md, algo); n = gcry_md_get_algo_dlen (algo); for(i=0; i < n ; i++, p++ ) es_printf ("%02X", *p); es_fputs (":\n", es_stdout); } static void print_mds( const char *fname, int algo ) { estream_t fp; char buf[1024]; size_t n; gcry_md_hd_t md; if (!fname) { fp = es_stdin; es_set_binary (fp); } else { fp = es_fopen (fname, "rb" ); if (fp && is_secured_file (es_fileno (fp))) { es_fclose (fp); fp = NULL; gpg_err_set_errno (EPERM); } } if (!fp) { log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) ); return; } gcry_md_open (&md, 0, 0); if (algo) gcry_md_enable (md, algo); else { if (!gcry_md_test_algo (GCRY_MD_MD5)) gcry_md_enable (md, GCRY_MD_MD5); gcry_md_enable (md, GCRY_MD_SHA1); if (!gcry_md_test_algo (GCRY_MD_RMD160)) gcry_md_enable (md, GCRY_MD_RMD160); if (!gcry_md_test_algo (GCRY_MD_SHA224)) gcry_md_enable (md, GCRY_MD_SHA224); if (!gcry_md_test_algo (GCRY_MD_SHA256)) gcry_md_enable (md, GCRY_MD_SHA256); if (!gcry_md_test_algo (GCRY_MD_SHA384)) gcry_md_enable (md, GCRY_MD_SHA384); if (!gcry_md_test_algo (GCRY_MD_SHA512)) gcry_md_enable (md, GCRY_MD_SHA512); } while ((n=es_fread (buf, 1, DIM(buf), fp))) gcry_md_write (md, buf, n); if (es_ferror(fp)) log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno)); else { gcry_md_final (md); if (opt.with_colons) { if ( algo ) print_hashline (md, algo, fname); else { if (!gcry_md_test_algo (GCRY_MD_MD5)) print_hashline( md, GCRY_MD_MD5, fname ); print_hashline( md, GCRY_MD_SHA1, fname ); if (!gcry_md_test_algo (GCRY_MD_RMD160)) print_hashline( md, GCRY_MD_RMD160, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA224)) print_hashline (md, GCRY_MD_SHA224, fname); if (!gcry_md_test_algo (GCRY_MD_SHA256)) print_hashline( md, GCRY_MD_SHA256, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA384)) print_hashline ( md, GCRY_MD_SHA384, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA512)) print_hashline ( md, GCRY_MD_SHA512, fname ); } } else { if (algo) print_hex (md, -algo, fname); else { if (!gcry_md_test_algo (GCRY_MD_MD5)) print_hex (md, GCRY_MD_MD5, fname); print_hex (md, GCRY_MD_SHA1, fname ); if (!gcry_md_test_algo (GCRY_MD_RMD160)) print_hex (md, GCRY_MD_RMD160, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA224)) print_hex (md, GCRY_MD_SHA224, fname); if (!gcry_md_test_algo (GCRY_MD_SHA256)) print_hex (md, GCRY_MD_SHA256, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA384)) print_hex (md, GCRY_MD_SHA384, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA512)) print_hex (md, GCRY_MD_SHA512, fname ); } } } gcry_md_close (md); if (fp != es_stdin) es_fclose (fp); } /**************** * Check the supplied name,value string and add it to the notation * data to be used for signatures. which==0 for sig notations, and 1 * for cert notations. */ static void add_notation_data( const char *string, int which ) { struct notation *notation; notation=string_to_notation(string,utf8_strings); if(notation) { if(which) { notation->next=opt.cert_notations; opt.cert_notations=notation; } else { notation->next=opt.sig_notations; opt.sig_notations=notation; } } } static void add_policy_url( const char *string, int which ) { unsigned int i,critical=0; strlist_t sl; if(*string=='!') { string++; critical=1; } for(i=0;iflags |= 1; } static void add_keyserver_url( const char *string, int which ) { unsigned int i,critical=0; strlist_t sl; if(*string=='!') { string++; critical=1; } for(i=0;iflags |= 1; } diff --git a/g10/keydb.h b/g10/keydb.h index 556b53726..66bfa57c0 100644 --- a/g10/keydb.h +++ b/g10/keydb.h @@ -1,859 +1,882 @@ /* keydb.h - Key database * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, * 2006, 2010 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_KEYDB_H #define G10_KEYDB_H #include #include "types.h" #include "util.h" #include "packet.h" /* What qualifies as a certification (rather than a signature?) */ #define IS_CERT(s) (IS_KEY_SIG(s) || IS_UID_SIG(s) || IS_SUBKEY_SIG(s) \ || IS_KEY_REV(s) || IS_UID_REV(s) || IS_SUBKEY_REV(s)) #define IS_SIG(s) (!IS_CERT(s)) #define IS_KEY_SIG(s) ((s)->sig_class == 0x1f) #define IS_UID_SIG(s) (((s)->sig_class & ~3) == 0x10) #define IS_SUBKEY_SIG(s) ((s)->sig_class == 0x18) #define IS_KEY_REV(s) ((s)->sig_class == 0x20) #define IS_UID_REV(s) ((s)->sig_class == 0x30) #define IS_SUBKEY_REV(s) ((s)->sig_class == 0x28) struct getkey_ctx_s; typedef struct getkey_ctx_s *GETKEY_CTX; typedef struct getkey_ctx_s *getkey_ctx_t; /**************** * A Keyblock is all packets which form an entire certificate; * i.e. the public key, certificate, trust packets, user ids, * signatures, and subkey. * * This structure is also used to bind arbitrary packets together. */ struct kbnode_struct { KBNODE next; PACKET *pkt; int flag; int private_flag; ulong recno; /* used while updating the trustdb */ }; #define is_deleted_kbnode(a) ((a)->private_flag & 1) #define is_cloned_kbnode(a) ((a)->private_flag & 2) enum resource_type { rt_UNKNOWN = 0, rt_RING = 1 }; /* Bit flags used with build_pk_list. */ enum { PK_LIST_ENCRYPT_TO=1, /* This is an encrypt-to recipient. */ PK_LIST_HIDDEN=2, /* This is a hidden recipient. */ PK_LIST_CONFIG=4 /* Specified via config file. */ }; /* To store private data in the flags they must be left shifted by this value. */ enum { PK_LIST_SHIFT=3 }; /**************** * A data structure to hold information about the external position * of a keyblock. */ struct keyblock_pos_struct { int resno; /* resource number */ enum resource_type rt; off_t offset; /* position information */ unsigned count; /* length of the keyblock in packets */ iobuf_t fp; /* Used by enum_keyblocks. */ int secret; /* working on a secret keyring */ PACKET *pkt; /* ditto */ int valid; }; typedef struct keyblock_pos_struct KBPOS; /* Structure to hold a couple of public key certificates. */ typedef struct pk_list *PK_LIST; /* Deprecated. */ typedef struct pk_list *pk_list_t; struct pk_list { PK_LIST next; PKT_public_key *pk; int flags; /* flag bit 1==throw_keyid */ }; /* Structure to hold a list of secret key certificates. */ typedef struct sk_list *SK_LIST; struct sk_list { SK_LIST next; PKT_public_key *pk; int mark; /* not used */ }; /* structure to collect all information which can be used to * identify a public key */ typedef struct pubkey_find_info *PUBKEY_FIND_INFO; struct pubkey_find_info { u32 keyid[2]; unsigned nbits; byte pubkey_algo; byte fingerprint[MAX_FINGERPRINT_LEN]; char userid[1]; }; typedef struct keydb_handle *KEYDB_HANDLE; /* Helper type for preference fucntions. */ union pref_hint { int digest_length; }; /*-- keydb.c --*/ #define KEYDB_RESOURCE_FLAG_PRIMARY 2 /* The primary resource. */ #define KEYDB_RESOURCE_FLAG_DEFAULT 4 /* The default one. */ #define KEYDB_RESOURCE_FLAG_READONLY 8 /* Open in read only mode. */ #define KEYDB_RESOURCE_FLAG_GPGVDEF 16 /* Default file for gpgv. */ /* Format a search term for debugging output. The caller must free the result. */ char *keydb_search_desc_dump (struct keydb_search_desc *desc); /* Register a resource (keyring or keybox). The first keyring or keybox that is added using this function is created if it does not already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set. FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants. URL must have the following form: gnupg-ring:filename = plain keyring gnupg-kbx:filename = keybox file filename = check file's type (create as a plain keyring) Note: on systems with drive letters (Windows) invalid URLs (i.e., those with an unrecognized part before the ':' such as "c:\...") will silently be treated as bare filenames. On other systems, such URLs will cause this function to return GPG_ERR_GENERAL. If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring and the file ends in ".gpg", then this function also checks if a file with the same name, but the extension ".kbx" exists, is a keybox and the OpenPGP flag is set. If so, this function opens that resource instead. If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and the URL ends in ".kbx", then this function will try opening the same URL, but with the extension ".gpg". If that file is a keybox with the OpenPGP flag set or it is a keyring, then we use that instead. If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the file should be created and the file's extension is ".gpg" then we replace the extension with ".kbx". If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a keyring (not a keybox), then this resource is considered the primary resource. This is used by keydb_locate_writable(). If another primary keyring is set, then that keyring is considered the primary. If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a keyring (not a keybox), then the keyring is marked as read only and operations just as keyring_insert_keyblock will return GPG_ERR_ACCESS. */ gpg_error_t keydb_add_resource (const char *url, unsigned int flags); /* Dump some statistics to the log. */ void keydb_dump_stats (void); /* Create a new database handle. Returns NULL on error, sets ERRNO, and prints an error diagnostic. */ KEYDB_HANDLE keydb_new (void); /* Free all resources owned by the database handle. */ void keydb_release (KEYDB_HANDLE hd); /* Set a flag on the handle to suppress use of cached results. This is required for updating a keyring and for key listings. Fixme: Using a new parameter for keydb_new might be a better solution. */ void keydb_disable_caching (KEYDB_HANDLE hd); /* Save the last found state and invalidate the current selection (i.e., the entry selected by keydb_search() is invalidated and something like keydb_get_keyblock() will return an error). This does not change the file position. This makes it possible to do something like: keydb_search (hd, ...); // Result 1. keydb_push_found_state (hd); keydb_search_reset (hd); keydb_search (hd, ...); // Result 2. keydb_pop_found_state (hd); keydb_get_keyblock (hd, ...); // -> Result 1. Note: it is only possible to save a single save state at a time. In other words, the the save stack only has room for a single instance of the state. */ void keydb_push_found_state (KEYDB_HANDLE hd); /* Restore the previous save state. If the saved state is invalid, this is equivalent to */ void keydb_pop_found_state (KEYDB_HANDLE hd); /* Return the file name of the resource in which the current search result was found or, if there is no search result, the filename of the current resource (i.e., the resource that the file position points to). Note: the filename is not necessarily the URL used to open it! This function only returns NULL if no handle is specified, in all other error cases an empty string is returned. */ const char *keydb_get_resource_name (KEYDB_HANDLE hd); /* Return the keyblock last found by keydb_search() in *RET_KB. On success, the function returns 0 and the caller must free *RET_KB using release_kbnode(). Otherwise, the function returns an error code. The returned keyblock has the kbnode flag bit 0 set for the node with the public key used to locate the keyblock or flag bit 1 set for the user ID node. */ gpg_error_t keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb); /* Update the keyblock KB (i.e., extract the fingerprint and find the corresponding keyblock in the keyring). This doesn't do anything if --dry-run was specified. Returns 0 on success. Otherwise, it returns an error code. Note: if there isn't a keyblock in the keyring corresponding to KB, then this function returns GPG_ERR_VALUE_NOT_FOUND. This function selects the matching record and modifies the current file position to point to the record just after the selected entry. Thus, if you do a subsequent search using HD, you should first do a keydb_search_reset. Further, if the selected record is important, you should use keydb_push_found_state and keydb_pop_found_state to save and restore it. */ gpg_error_t keydb_update_keyblock (KEYDB_HANDLE hd, kbnode_t kb); /* Insert a keyblock into one of the underlying keyrings or keyboxes. Be default, the keyring / keybox from which the last search result came is used. If there was no previous search result (or keydb_search_reset was called), then the keyring / keybox where the next search would start is used (i.e., the current file position). Note: this doesn't do anything if --dry-run was specified. Returns 0 on success. Otherwise, it returns an error code. */ gpg_error_t keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb); /* Delete the currently selected keyblock. If you haven't done a search yet on this database handle (or called keydb_search_reset), then this will return an error. Returns 0 on success or an error code, if an error occurs. */ gpg_error_t keydb_delete_keyblock (KEYDB_HANDLE hd); /* A database may consists of multiple keyrings / key boxes. This sets the "file position" to the start of the first keyring / key box that is writable (i.e., doesn't have the read-only flag set). This first tries the primary keyring (the last keyring (not keybox!) added using keydb_add_resource() and with KEYDB_RESOURCE_FLAG_PRIMARY set). If that is not writable, then it tries the keyrings / keyboxes in the order in which they were added. */ gpg_error_t keydb_locate_writable (KEYDB_HANDLE hd); /* Rebuild the on-disk caches of all key resources. */ void keydb_rebuild_caches (int noisy); /* Return the number of skipped blocks (because they were to large to read from a keybox) since the last search reset. */ unsigned long keydb_get_skipped_counter (KEYDB_HANDLE hd); /* Clears the current search result and resets the handle's position so that the next search starts at the beginning of the database (the start of the first resource). Returns 0 on success and an error code if an error occurred. (Currently, this function always returns 0 if HD is valid.) */ gpg_error_t keydb_search_reset (KEYDB_HANDLE hd); /* Search the database for keys matching the search description. If the DB contains any legacy keys, these are silently ignored. DESC is an array of search terms with NDESC entries. The search terms are or'd together. That is, the next entry in the DB that matches any of the descriptions will be returned. Note: this function resumes searching where the last search left off (i.e., at the current file position). If you want to search from the start of the database, then you need to first call keydb_search_reset(). If no key matches the search description, returns GPG_ERR_NOT_FOUND. If there was a match, returns 0. If an error occurred, returns an error code. The returned key is considered to be selected and the raw data can, for instance, be returned by calling keydb_get_keyblock(). */ gpg_error_t keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc, size_t *descindex); /* Return the first non-legacy key in the database. If you want the very first key in the database, you can directly call keydb_search with the search description KEYDB_SEARCH_MODE_FIRST. */ gpg_error_t keydb_search_first (KEYDB_HANDLE hd); /* Return the next key (not the next matching key!). Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this function silently skips legacy keys. */ gpg_error_t keydb_search_next (KEYDB_HANDLE hd); /* This is a convenience function for searching for keys with a long key id. Note: this function resumes searching where the last search left off. If you want to search the whole database, then you need to first call keydb_search_reset(). */ gpg_error_t keydb_search_kid (KEYDB_HANDLE hd, u32 *kid); /* This is a convenience function for searching for keys with a long (20 byte) fingerprint. Note: this function resumes searching where the last search left off. If you want to search the whole database, then you need to first call keydb_search_reset(). */ gpg_error_t keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr); /*-- pkclist.c --*/ void show_revocation_reason( PKT_public_key *pk, int mode ); int check_signatures_trust( PKT_signature *sig ); void release_pk_list (PK_LIST pk_list); int build_pk_list (ctrl_t ctrl, strlist_t rcpts, PK_LIST *ret_pk_list); gpg_error_t find_and_check_key (ctrl_t ctrl, const char *name, unsigned int use, int mark_hidden, pk_list_t *pk_list_addr); int algo_available( preftype_t preftype, int algo, const union pref_hint *hint ); int select_algo_from_prefs( PK_LIST pk_list, int preftype, int request, const union pref_hint *hint); int select_mdc_from_pklist (PK_LIST pk_list); void warn_missing_mdc_from_pklist (PK_LIST pk_list); void warn_missing_aes_from_pklist (PK_LIST pk_list); /*-- skclist.c --*/ int random_is_faked (void); void release_sk_list( SK_LIST sk_list ); gpg_error_t build_sk_list (ctrl_t ctrl, strlist_t locusr, SK_LIST *ret_sk_list, unsigned use); /*-- passphrase.h --*/ unsigned char encode_s2k_iterations (int iterations); assuan_context_t agent_open (int try, const char *orig_codeset); void agent_close (assuan_context_t ctx); int have_static_passphrase(void); const char *get_static_passphrase (void); void set_passphrase_from_string(const char *pass); void read_passphrase_from_fd( int fd ); void passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo ); DEK *passphrase_to_dek_ext(u32 *keyid, int pubkey_algo, int cipher_algo, STRING2KEY *s2k, int mode, const char *tryagain_text, const char *custdesc, const char *custprompt, int *canceled); DEK *passphrase_to_dek( u32 *keyid, int pubkey_algo, int cipher_algo, STRING2KEY *s2k, int mode, const char *tryagain_text, int *canceled); void set_next_passphrase( const char *s ); char *get_last_passphrase(void); void next_to_last_passphrase(void); void emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo); #define FORMAT_KEYDESC_NORMAL 0 #define FORMAT_KEYDESC_IMPORT 1 #define FORMAT_KEYDESC_EXPORT 2 #define FORMAT_KEYDESC_DELKEY 3 char *gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped); /*-- getkey.c --*/ /* Cache a copy of a public key in the public key cache. PK is not cached if caching is disabled (via getkey_disable_caches), if PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id from the public key (e.g., unsupported algorithm), or a key with the key id is already in the cache. The public key packet is copied into the cache using copy_public_key. Thus, any secret parts are not copied, for instance. This cache is filled by get_pubkey and is read by get_pubkey and get_pubkey_fast. */ void cache_public_key( PKT_public_key *pk ); /* Disable and drop the public key cache (which is filled by cache_public_key and get_pubkey). Note: there is currently no way to reenable this cache. */ void getkey_disable_caches(void); /* Return the public key with the key id KEYID and store it in *PK. The resources in *PK should be released using release_public_key_parts(). This function also stores a copy of the public key in the user id cache (see cache_public_key). If PK is NULL, this function just stores the public key in the cache and returns the usual return code. PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the lookup function. If this is non-zero, only keys with the specified usage will be returned. As such, it is essential that PK->REQ_USAGE be correctly initialized! Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key with the specified key id, or another error code if an error occurs. If the data was not read from the cache, then the self-signed data has definitely been merged into the public key using merge_selfsigs. */ int get_pubkey( PKT_public_key *pk, u32 *keyid ); /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into account nor does it merge in the self-signed data. This function also only considers primary keys. It is intended to be used as a quick check of the key to avoid recursion. It should only be used in very certain cases. Like get_pubkey and unlike any of the other lookup functions, this function also consults the user id cache (see cache_public_key). Return the public key in *PK. The resources in *PK should be released using release_public_key_parts(). */ int get_pubkey_fast ( PKT_public_key *pk, u32 *keyid ); /* Return the key block for the key with key id KEYID or NULL, if an error occurs. Use release_kbnode() to release the key block. The self-signed data has already been merged into the public key using merge_selfsigs. */ KBNODE get_pubkeyblock( u32 *keyid ); +/* A list used by get_pubkeys to gather all of the matches. */ +struct pubkey +{ + struct pubkey *next; + /* The key to use (either the public key or the subkey). */ + PKT_public_key *pk; + kbnode_t keyblock; +}; + +/* Free a single key. This does not remove key from any list! */ +void pubkey_free (struct pubkey *key); + +/* Free a list of public keys. */ +void pubkeys_free (struct pubkey *keys); + +/* Returns all keys that match the search specfication SEARCH_TERMS. + The returned keys should be freed using pubkeys_free. */ +gpg_error_t +get_pubkeys (ctrl_t ctrl, + char *search_terms, int use, int include_unusable, char *source, + int warn_possibly_ambiguous, + struct pubkey **keys); + /* Find a public key identified by the name NAME. If name appears to be a valid valid RFC822 mailbox (i.e., email address) and auto key lookup is enabled (no_akl == 0), then the specified auto key lookup methods (--auto-key-lookup) are used to import the key into the local keyring. Otherwise, just the local keyring is consulted. If RETCTX is not NULL, then the constructed context is returned in *RETCTX so that getpubkey_next can be used to get subsequent results. In this case, getkey_end() must be used to free the search context. If RETCTX is not NULL, then RET_KDBHD must be NULL. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is passed through to the lookup function and is a mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only keys with the specified usage will be returned. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). NAME is a string, which is turned into a search query using classify_user_id. If RET_KEYBLOCK is not NULL, the keyblock is returned in *RET_KEYBLOCK. This should be freed using release_kbnode(). If RET_KDBHD is not NULL, then the new database handle used to conduct the search is returned in *RET_KDBHD. This can be used to get subsequent results using keydb_search_next or to modify the returned record. Note: in this case, no advanced filtering is done for subsequent results (e.g., PK->REQ_USAGE is not respected). Unlike RETCTX, this is always returned. If INCLUDE_UNUSABLE is set, then unusable keys (see the documentation for skip_unusable for an exact definition) are skipped unless they are looked up by key id or by fingerprint. If NO_AKL is set, then the auto key locate functionality is disabled and only the local key ring is considered. Note: the local key ring is consulted even if local is not in the --auto-key-locate option list! This function returns 0 on success. Otherwise, an error code is returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY (if want_secret is set) is returned if the key is not found. */ int get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX *retctx, PKT_public_key *pk, const char *name, KBNODE *ret_keyblock, KEYDB_HANDLE *ret_kdbhd, int include_unusable, int no_akl ); /* Return the public key with the key id KEYID and store it in *PK. The resources should be released using release_public_key_parts(). Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE is passed through to the lookup function and is a mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it must be valid! If this is non-zero, only keys with the specified usage will be returned. Returns 0 on success. If a public key with the specified key id is not found or a secret key is not available for that public key, an error code is returned. Note: this function ignores legacy keys. An error code is also return if an error occurs. The self-signed data has already been merged into the public key using merge_selfsigs. */ gpg_error_t get_seckey (PKT_public_key *pk, u32 *keyid); /* Lookup a key with the specified fingerprint. If PK is not NULL, the public key of the first result is returned in *PK. Note: this function does an exact search and thus the returned public key may be a subkey rather than the primary key. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If PK->REQ_USAGE is set, it is used to filter the search results. (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the documentation for finish_lookup to understand exactly how this is used. If R_KEYBLOCK is not NULL, then the first result's keyblock is returned in *R_KEYBLOCK. This should be freed using release_kbnode(). FPRINT is a byte array whose contents is the fingerprint to use as the search term. FPRINT_LEN specifies the length of the fingerprint (in bytes). Currently, only 16 and 20-byte fingerprints are supported. */ int get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock, const byte *fprint, size_t fprint_len); /* This function is similar to get_pubkey_byfprint, but it doesn't merge the self-signed data into the public key and subkeys or into the user ids. It also doesn't add the key to the user id cache. Further, this function ignores PK->REQ_USAGE. This function is intended to avoid recursion and, as such, should only be used in very specific situations. Like get_pubkey_byfprint, PK may be NULL. In that case, this function effectively just checks for the existence of the key. */ int get_pubkey_byfprint_fast (PKT_public_key *pk, const byte *fprint, size_t fprint_len); /* Returns true if a secret key is available for the public key with key id KEYID. */ int have_secret_key_with_kid (u32 *keyid); /* Parse the --default-key parameter. Returns the last key (in terms of when the option is given) that is available. */ const char *parse_def_secret_key (ctrl_t ctrl); /* Look up a secret key. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is set, it is used to filter the search results. See the documentation for finish_lookup to understand exactly how this is used. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If --default-key was set, then the specified key is looked up. (In this case, the default key is returned even if it is considered unusable. See the documentation for skip_unusable for exactly what this means.) Otherwise, this initiates a DB scan that returns all keys that are usable (see previous paragraph for exactly what usable means) and for which a secret key is available. This function returns the first match. Additional results can be returned using getkey_next. */ gpg_error_t get_seckey_default (ctrl_t ctrl, PKT_public_key *pk); /* Search for keys matching some criteria. If RETCTX is not NULL, then the constructed context is returned in *RETCTX so that getpubkey_next can be used to get subsequent results. In this case, getkey_end() must be used to free the search context. If RETCTX is not NULL, then RET_KDBHD must be NULL. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is set, it is used to filter the search results. See the documentation for finish_lookup to understand exactly how this is used. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If NAMES is not NULL, then a search query is constructed using classify_user_id on each of the strings in the list. (Recall: the database does an OR of the terms, not an AND.) If NAMES is NULL, then all results are returned. If WANT_SECRET is set, then only keys with an available secret key (either locally or via key registered on a smartcard) are returned. This function does not skip unusable keys (see the documentation for skip_unusable for an exact definition). If RET_KEYBLOCK is not NULL, the keyblock is returned in *RET_KEYBLOCK. This should be freed using release_kbnode(). This function returns 0 on success. Otherwise, an error code is returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY (if want_secret is set) is returned if the key is not found. */ gpg_error_t getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk, strlist_t names, int want_secret, kbnode_t *ret_keyblock); /* Search for keys matching some criteria. If RETCTX is not NULL, then the constructed context is returned in *RETCTX so that getpubkey_next can be used to get subsequent results. In this case, getkey_end() must be used to free the search context. If RETCTX is not NULL, then RET_KDBHD must be NULL. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is set, it is used to filter the search results. See the documentation for finish_lookup to understand exactly how this is used. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If NAME is not NULL, then a search query is constructed using classify_user_id on the string. In this case, even unusable keys (see the documentation for skip_unusable for an exact definition of unusable) are returned. Otherwise, if --default-key was set, then that key is returned (even if it is unusable). If neither of these conditions holds, then the first usable key is returned. If WANT_SECRET is set, then only keys with an available secret key (either locally or via key registered on a smartcard) are returned. This function does not skip unusable keys (see the documentation for skip_unusable for an exact definition). If RET_KEYBLOCK is not NULL, the keyblock is returned in *RET_KEYBLOCK. This should be freed using release_kbnode(). This function returns 0 on success. Otherwise, an error code is returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY (if want_secret is set) is returned if the key is not found. FIXME: We also have the get_pubkey_byname function which has a different semantic. Should be merged with this one. */ gpg_error_t getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk, const char *name, int want_secret, kbnode_t *ret_keyblock); /* Return the next search result. If PK is not NULL, the public key of the next result is returned in *PK. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). The self-signed data has already been merged into the public key using merge_selfsigs. */ gpg_error_t getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock); /* Release any resources used by a key listing content. This must be called on the context returned by, e.g., getkey_byname. */ void getkey_end (getkey_ctx_t ctx); /* Return the database handle used by this context. The context still owns the handle. */ KEYDB_HANDLE get_ctx_handle(GETKEY_CTX ctx); /* Enumerate some secret keys (specifically, those specified with --default-key and --try-secret-key). Use the following procedure: 1) Initialize a void pointer to NULL 2) Pass a reference to this pointer to this function (content) and provide space for the secret key (sk) 3) Call this function as long as it does not return an error (or until you are done). The error code GPG_ERR_EOF indicates the end of the listing. 4) Call this function a last time with SK set to NULL, so that can free it's context. In pseudo-code: void *ctx = NULL; PKT_public_key *sk = xmalloc_clear (sizeof (*sk)); gpg_error_t err; while ((err = enum_secret_keys (&ctx, sk))) { // Process SK. if (done) break; free_public_key (sk); sk = xmalloc_clear (sizeof (*sk)); } // Release any resources used by CTX. enum_secret_keys (&ctx, NULL); free_public_key (sk); if (gpg_err_code (err) != GPG_ERR_EOF) ; // An error occurred. */ gpg_error_t enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *pk); /* Set the mainkey_id fields for all keys in KEYBLOCK. This is usually done by merge_selfsigs but at some places we only need the main_kid not a full merge. The function also guarantees that all pk->keyids are computed. */ void setup_main_keyids (kbnode_t keyblock); /* KEYBLOCK corresponds to a public key block. This function merges much of the information from the self-signed data into the public key, public subkey and user id data structures. If you use the high-level search API (e.g., get_pubkey) for looking up key blocks, then you don't need to call this function. This function is useful, however, if you change the keyblock, e.g., by adding or removing a self-signed data packet. */ void merge_keys_and_selfsig( KBNODE keyblock ); char*get_user_id_string_native( u32 *keyid ); char*get_long_user_id_string( u32 *keyid ); char*get_user_id( u32 *keyid, size_t *rn ); char*get_user_id_native( u32 *keyid ); char *get_user_id_byfpr (const byte *fpr, size_t *rn); char *get_user_id_byfpr_native (const byte *fpr); void release_akl(void); int parse_auto_key_locate(char *options); /*-- keyid.c --*/ int pubkey_letter( int algo ); char *pubkey_string (PKT_public_key *pk, char *buffer, size_t bufsize); #define PUBKEY_STRING_SIZE 32 u32 v3_keyid (gcry_mpi_t a, u32 *ki); void hash_public_key( gcry_md_hd_t md, PKT_public_key *pk ); const char *format_keyid (u32 *keyid, int format, char *buffer, int len); size_t keystrlen(void); const char *keystr(u32 *keyid); const char *keystr_with_sub (u32 *main_kid, u32 *sub_kid); const char *keystr_from_pk(PKT_public_key *pk); const char *keystr_from_pk_with_sub (PKT_public_key *main_pk, PKT_public_key *sub_pk); const char *keystr_from_desc(KEYDB_SEARCH_DESC *desc); u32 keyid_from_pk( PKT_public_key *pk, u32 *keyid ); u32 keyid_from_sig( PKT_signature *sig, u32 *keyid ); u32 keyid_from_fingerprint(const byte *fprint, size_t fprint_len, u32 *keyid); byte *namehash_from_uid(PKT_user_id *uid); unsigned nbits_from_pk( PKT_public_key *pk ); const char *datestr_from_pk( PKT_public_key *pk ); const char *datestr_from_sig( PKT_signature *sig ); const char *expirestr_from_pk( PKT_public_key *pk ); const char *expirestr_from_sig( PKT_signature *sig ); const char *revokestr_from_pk( PKT_public_key *pk ); const char *usagestr_from_pk (PKT_public_key *pk, int fill); const char *colon_strtime (u32 t); const char *colon_datestr_from_pk (PKT_public_key *pk); const char *colon_datestr_from_sig (PKT_signature *sig); const char *colon_expirestr_from_sig (PKT_signature *sig); byte *fingerprint_from_pk( PKT_public_key *pk, byte *buf, size_t *ret_len ); char *hexfingerprint (PKT_public_key *pk, char *buffer, size_t buflen); char *format_hexfingerprint (const char *fingerprint, char *buffer, size_t buflen); gpg_error_t keygrip_from_pk (PKT_public_key *pk, unsigned char *array); gpg_error_t hexkeygrip_from_pk (PKT_public_key *pk, char **r_grip); /*-- kbnode.c --*/ KBNODE new_kbnode( PACKET *pkt ); KBNODE clone_kbnode( KBNODE node ); void release_kbnode( KBNODE n ); void delete_kbnode( KBNODE node ); void add_kbnode( KBNODE root, KBNODE node ); void insert_kbnode( KBNODE root, KBNODE node, int pkttype ); void move_kbnode( KBNODE *root, KBNODE node, KBNODE where ); void remove_kbnode( KBNODE *root, KBNODE node ); KBNODE find_prev_kbnode( KBNODE root, KBNODE node, int pkttype ); KBNODE find_next_kbnode( KBNODE node, int pkttype ); KBNODE find_kbnode( KBNODE node, int pkttype ); KBNODE walk_kbnode( KBNODE root, KBNODE *context, int all ); void clear_kbnode_flags( KBNODE n ); int commit_kbnode( KBNODE *root ); void dump_kbnode( KBNODE node ); #endif /*G10_KEYDB_H*/ diff --git a/g10/pkclist.c b/g10/pkclist.c index b6a213fe2..d7e78cb7c 100644 --- a/g10/pkclist.c +++ b/g10/pkclist.c @@ -1,1618 +1,1625 @@ /* pkclist.c - create a list of public keys * 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 . */ #include #include #include #include #include #include #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "keydb.h" #include "util.h" #include "main.h" #include "trustdb.h" #include "ttyio.h" #include "status.h" #include "photoid.h" #include "i18n.h" #include "tofu.h" #define CONTROL_D ('D' - 'A' + 1) static void send_status_inv_recp (int reason, const char *name) { char buf[40]; snprintf (buf, sizeof buf, "%d ", reason); write_status_text_and_buffer (STATUS_INV_RECP, buf, name, strlen (name), -1); } /**************** * Show the revocation reason as it is stored with the given signature */ static void do_show_revocation_reason( PKT_signature *sig ) { size_t n, nn; const byte *p, *pp; int seq = 0; const char *text; while( (p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON, &n, &seq, NULL )) ) { if( !n ) continue; /* invalid - just skip it */ if( *p == 0 ) text = _("No reason specified"); else if( *p == 0x01 ) text = _("Key is superseded"); else if( *p == 0x02 ) text = _("Key has been compromised"); else if( *p == 0x03 ) text = _("Key is no longer used"); else if( *p == 0x20 ) text = _("User ID is no longer valid"); else text = NULL; log_info ( _("reason for revocation: ")); if (text) log_printf ("%s\n", text); else log_printf ("code=%02x\n", *p ); n--; p++; pp = NULL; do { /* We don't want any empty lines, so skip them */ while( n && *p == '\n' ) { p++; n--; } if( n ) { pp = memchr( p, '\n', n ); nn = pp? pp - p : n; log_info ( _("revocation comment: ") ); es_write_sanitized (log_get_stream(), p, nn, NULL, NULL); log_printf ("\n"); p += nn; n -= nn; } } while( pp ); } } /* Mode 0: try and find the revocation based on the pk (i.e. check subkeys, etc.) Mode 1: use only the revocation on the main pk */ void show_revocation_reason( PKT_public_key *pk, int mode ) { /* Hmmm, this is not so easy because we have to duplicate the code * used in the trustbd to calculate the keyflags. We need to find * a clean way to check revocation certificates on keys and * signatures. And there should be no duplicate code. Because we * enter this function only when the trustdb told us that we have * a revoked key, we could simply look for a revocation cert and * display this one, when there is only one. Let's try to do this * until we have a better solution. */ KBNODE node, keyblock = NULL; byte fingerprint[MAX_FINGERPRINT_LEN]; size_t fingerlen; int rc; /* get the keyblock */ fingerprint_from_pk( pk, fingerprint, &fingerlen ); rc = get_pubkey_byfprint(NULL, &keyblock, fingerprint, fingerlen); if( rc ) { /* that should never happen */ log_debug( "failed to get the keyblock\n"); return; } for( node=keyblock; node; node = node->next ) { if( (mode && node->pkt->pkttype == PKT_PUBLIC_KEY) || ( ( node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) && !cmp_public_keys( node->pkt->pkt.public_key, pk ) ) ) break; } if( !node ) { log_debug("Oops, PK not in keyblock\n"); release_kbnode( keyblock ); return; } /* now find the revocation certificate */ for( node = node->next; node ; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; if( node->pkt->pkttype == PKT_SIGNATURE && (node->pkt->pkt.signature->sig_class == 0x20 || node->pkt->pkt.signature->sig_class == 0x28 ) ) { /* FIXME: we should check the signature here */ do_show_revocation_reason ( node->pkt->pkt.signature ); break; } } /* We didn't find it, so check if the whole key is revoked */ if(!node && !mode) show_revocation_reason(pk,1); release_kbnode( keyblock ); } /**************** * mode: 0 = standard * 1 = Without key info and additional menu option 'm' * this does also add an option to set the key to ultimately trusted. * Returns: * -2 = nothing changed - caller should show some additional info * -1 = quit operation * 0 = nothing changed * 1 = new ownertrust now in new_trust */ #ifndef NO_TRUST_MODELS static int do_edit_ownertrust (PKT_public_key *pk, int mode, unsigned *new_trust, int defer_help ) { char *p; u32 keyid[2]; int changed=0; int quit=0; int show=0; int min_num; int did_help=defer_help; unsigned int minimum = tdb_get_min_ownertrust (pk); char pkstrbuf[PUBKEY_STRING_SIZE]; switch(minimum) { default: case TRUST_UNDEFINED: min_num=1; break; case TRUST_NEVER: min_num=2; break; case TRUST_MARGINAL: min_num=3; break; case TRUST_FULLY: min_num=4; break; } keyid_from_pk (pk, keyid); for(;;) { /* A string with valid answers. TRANSLATORS: These are the allowed answers in lower and uppercase. Below you will find the matching strings which should be translated accordingly and the letter changed to match the one in the answer string. i = please show me more information m = back to the main menu s = skip this key q = quit */ const char *ans = _("iImMqQsS"); if( !did_help ) { if( !mode ) { KBNODE keyblock, un; tty_printf(_("No trust value assigned to:\n")); tty_printf("%s/%s %s\n", pubkey_string (pk, pkstrbuf, sizeof pkstrbuf), keystr(keyid), datestr_from_pk( pk ) ); p=get_user_id_native(keyid); tty_printf(_(" \"%s\"\n"),p); xfree(p); keyblock = get_pubkeyblock (keyid); if (!keyblock) BUG (); for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype != PKT_USER_ID ) continue; if (un->pkt->pkt.user_id->is_revoked ) continue; if (un->pkt->pkt.user_id->is_expired ) continue; /* Only skip textual primaries */ if (un->pkt->pkt.user_id->is_primary && !un->pkt->pkt.user_id->attrib_data ) continue; if((opt.verify_options&VERIFY_SHOW_PHOTOS) && un->pkt->pkt.user_id->attrib_data) show_photos (un->pkt->pkt.user_id->attribs, un->pkt->pkt.user_id->numattribs, pk, un->pkt->pkt.user_id); p=utf8_to_native(un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len,0); tty_printf(_(" aka \"%s\"\n"),p); } print_fingerprint (NULL, pk, 2); tty_printf("\n"); release_kbnode (keyblock); } if(opt.trust_model==TM_DIRECT) { tty_printf(_("How much do you trust that this key actually " "belongs to the named user?\n")); tty_printf("\n"); } else { /* This string also used in keyedit.c:trustsig_prompt */ tty_printf(_("Please decide how far you trust this user to" " correctly verify other users' keys\n" "(by looking at passports, checking fingerprints from" " different sources, etc.)\n")); tty_printf("\n"); } if(min_num<=1) tty_printf (_(" %d = I don't know or won't say\n"), 1); if(min_num<=2) tty_printf (_(" %d = I do NOT trust\n"), 2); if(min_num<=3) tty_printf (_(" %d = I trust marginally\n"), 3); if(min_num<=4) tty_printf (_(" %d = I trust fully\n"), 4); if (mode) tty_printf (_(" %d = I trust ultimately\n"), 5); #if 0 /* not yet implemented */ tty_printf (" i = please show me more information\n"); #endif if( mode ) tty_printf(_(" m = back to the main menu\n")); else { tty_printf(_(" s = skip this key\n")); tty_printf(_(" q = quit\n")); } tty_printf("\n"); if(minimum) tty_printf(_("The minimum trust level for this key is: %s\n\n"), trust_value_to_string(minimum)); did_help = 1; } if( strlen(ans) != 8 ) BUG(); p = cpr_get("edit_ownertrust.value",_("Your decision? ")); trim_spaces(p); cpr_kill_prompt(); if( !*p ) did_help = 0; else if( *p && p[1] ) ; else if( !p[1] && ((*p >= '0'+min_num) && *p <= (mode?'5':'4')) ) { unsigned int trust; switch( *p ) { case '1': trust = TRUST_UNDEFINED; break; case '2': trust = TRUST_NEVER ; break; case '3': trust = TRUST_MARGINAL ; break; case '4': trust = TRUST_FULLY ; break; case '5': trust = TRUST_ULTIMATE ; break; default: BUG(); } if (trust == TRUST_ULTIMATE && !cpr_get_answer_is_yes ("edit_ownertrust.set_ultimate.okay", _("Do you really want to set this key" " to ultimate trust? (y/N) "))) ; /* no */ else { *new_trust = trust; changed = 1; break; } } #if 0 /* not yet implemented */ else if( *p == ans[0] || *p == ans[1] ) { tty_printf(_("Certificates leading to an ultimately trusted key:\n")); show = 1; break; } #endif else if( mode && (*p == ans[2] || *p == ans[3] || *p == CONTROL_D ) ) { break ; /* back to the menu */ } else if( !mode && (*p == ans[6] || *p == ans[7] ) ) { break; /* skip */ } else if( !mode && (*p == ans[4] || *p == ans[5] ) ) { quit = 1; break ; /* back to the menu */ } xfree(p); p = NULL; } xfree(p); return show? -2: quit? -1 : changed; } #endif /*!NO_TRUST_MODELS*/ /* * Display a menu to change the ownertrust of the key PK (which should * be a primary key). * For mode values see do_edit_ownertrust () */ #ifndef NO_TRUST_MODELS int edit_ownertrust (PKT_public_key *pk, int mode ) { unsigned int trust = 0; int no_help = 0; for(;;) { switch ( do_edit_ownertrust (pk, mode, &trust, no_help ) ) { case -1: /* quit */ return -1; case -2: /* show info */ no_help = 1; break; case 1: /* trust value set */ trust &= ~TRUST_FLAG_DISABLED; trust |= get_ownertrust (pk) & TRUST_FLAG_DISABLED; update_ownertrust (pk, trust ); return 1; default: return 0; } } } #endif /*!NO_TRUST_MODELS*/ /**************** * Check whether we can trust this pk which has a trustlevel of TRUSTLEVEL * Returns: true if we trust. */ static int do_we_trust( PKT_public_key *pk, unsigned int trustlevel ) { /* We should not be able to get here with a revoked or expired key */ if(trustlevel & TRUST_FLAG_REVOKED || trustlevel & TRUST_FLAG_SUB_REVOKED || (trustlevel & TRUST_MASK) == TRUST_EXPIRED) BUG(); if( opt.trust_model==TM_ALWAYS ) { if( opt.verbose ) log_info("No trust check due to '--trust-model always' option\n"); return 1; } switch(trustlevel & TRUST_MASK) { default: log_error ("invalid trustlevel %u returned from validation layer\n", trustlevel); /* fall thru */ case TRUST_UNKNOWN: case TRUST_UNDEFINED: log_info(_("%s: There is no assurance this key belongs" " to the named user\n"),keystr_from_pk(pk)); return 0; /* no */ case TRUST_MARGINAL: log_info(_("%s: There is limited assurance this key belongs" " to the named user\n"),keystr_from_pk(pk)); return 1; /* yes */ case TRUST_FULLY: if( opt.verbose ) log_info(_("This key probably belongs to the named user\n")); return 1; /* yes */ case TRUST_ULTIMATE: if( opt.verbose ) log_info(_("This key belongs to us\n")); return 1; /* yes */ } return 1; /*NOTREACHED*/ } /**************** * wrapper around do_we_trust, so we can ask whether to use the * key anyway. */ static int do_we_trust_pre( PKT_public_key *pk, unsigned int trustlevel ) { int rc; rc = do_we_trust( pk, trustlevel ); if( !opt.batch && !rc ) { print_pubkey_info(NULL,pk); print_fingerprint (NULL, pk, 2); tty_printf("\n"); tty_printf( _("It is NOT certain that the key belongs to the person named\n" "in the user ID. If you *really* know what you are doing,\n" "you may answer the next question with yes.\n")); tty_printf("\n"); if (is_status_enabled ()) { u32 kid[2]; char *hint_str; keyid_from_pk (pk, kid); hint_str = get_long_user_id_string ( kid ); write_status_text ( STATUS_USERID_HINT, hint_str ); xfree (hint_str); } if( cpr_get_answer_is_yes("untrusted_key.override", _("Use this key anyway? (y/N) ")) ) rc = 1; /* Hmmm: Should we set a flag to tell the user about * his decision the next time he encrypts for this recipient? */ } return rc; } /**************** * Check whether we can trust this signature. * Returns an error code if we should not trust this signature. */ int check_signatures_trust( PKT_signature *sig ) { PKT_public_key *pk = xmalloc_clear( sizeof *pk ); unsigned int trustlevel = TRUST_UNKNOWN; int rc=0; rc = get_pubkey( pk, sig->keyid ); if (rc) { /* this should not happen */ log_error("Ooops; the key vanished - can't check the trust\n"); rc = GPG_ERR_NO_PUBKEY; goto leave; } if ( opt.trust_model==TM_ALWAYS ) { if( !opt.quiet ) log_info(_("WARNING: Using untrusted key!\n")); if (opt.with_fingerprint) print_fingerprint (NULL, pk, 1); goto leave; } if(pk->flags.maybe_revoked && !pk->flags.revoked) log_info(_("WARNING: this key might be revoked (revocation key" " not present)\n")); trustlevel = get_validity (pk, NULL, sig, 1); if ( (trustlevel & TRUST_FLAG_REVOKED) ) { write_status( STATUS_KEYREVOKED ); if(pk->flags.revoked == 2) log_info(_("WARNING: This key has been revoked by its" " designated revoker!\n")); else log_info(_("WARNING: This key has been revoked by its owner!\n")); log_info(_(" This could mean that the signature is forged.\n")); show_revocation_reason( pk, 0 ); } else if ((trustlevel & TRUST_FLAG_SUB_REVOKED) ) { write_status( STATUS_KEYREVOKED ); log_info(_("WARNING: This subkey has been revoked by its owner!\n")); show_revocation_reason( pk, 0 ); } if ((trustlevel & TRUST_FLAG_DISABLED)) log_info (_("Note: This key has been disabled.\n")); /* If we have PKA information adjust the trustlevel. */ if (sig->pka_info && sig->pka_info->valid) { unsigned char fpr[MAX_FINGERPRINT_LEN]; PKT_public_key *primary_pk; size_t fprlen; int okay; primary_pk = xmalloc_clear (sizeof *primary_pk); get_pubkey (primary_pk, pk->main_keyid); fingerprint_from_pk (primary_pk, fpr, &fprlen); free_public_key (primary_pk); if ( fprlen == 20 && !memcmp (sig->pka_info->fpr, fpr, 20) ) { okay = 1; write_status_text (STATUS_PKA_TRUST_GOOD, sig->pka_info->email); log_info (_("Note: Verified signer's address is '%s'\n"), sig->pka_info->email); } else { okay = 0; write_status_text (STATUS_PKA_TRUST_BAD, sig->pka_info->email); log_info (_("Note: Signer's address '%s' " "does not match DNS entry\n"), sig->pka_info->email); } switch ( (trustlevel & TRUST_MASK) ) { case TRUST_UNKNOWN: case TRUST_UNDEFINED: case TRUST_MARGINAL: if (okay && opt.verify_options&VERIFY_PKA_TRUST_INCREASE) { trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_FULLY); log_info (_("trustlevel adjusted to FULL" " due to valid PKA info\n")); } /* (fall through) */ case TRUST_FULLY: if (!okay) { trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_NEVER); log_info (_("trustlevel adjusted to NEVER" " due to bad PKA info\n")); } break; } } /* Now let the user know what up with the trustlevel. */ switch ( (trustlevel & TRUST_MASK) ) { case TRUST_EXPIRED: log_info(_("Note: This key has expired!\n")); print_fingerprint (NULL, pk, 1); break; default: log_error ("invalid trustlevel %u returned from validation layer\n", trustlevel); /* fall thru */ case TRUST_UNKNOWN: case TRUST_UNDEFINED: write_status( STATUS_TRUST_UNDEFINED ); log_info(_("WARNING: This key is not certified with" " a trusted signature!\n")); log_info(_(" There is no indication that the " "signature belongs to the owner.\n" )); print_fingerprint (NULL, pk, 1); break; case TRUST_NEVER: /* currently we won't get that status */ write_status( STATUS_TRUST_NEVER ); log_info(_("WARNING: We do NOT trust this key!\n")); log_info(_(" The signature is probably a FORGERY.\n")); if (opt.with_fingerprint) print_fingerprint (NULL, pk, 1); rc = gpg_error (GPG_ERR_BAD_SIGNATURE); break; case TRUST_MARGINAL: write_status( STATUS_TRUST_MARGINAL ); log_info(_("WARNING: This key is not certified with" " sufficiently trusted signatures!\n")); log_info(_(" It is not certain that the" " signature belongs to the owner.\n" )); print_fingerprint (NULL, pk, 1); break; case TRUST_FULLY: write_status( STATUS_TRUST_FULLY ); if (opt.with_fingerprint) print_fingerprint (NULL, pk, 1); break; case TRUST_ULTIMATE: write_status( STATUS_TRUST_ULTIMATE ); if (opt.with_fingerprint) print_fingerprint (NULL, pk, 1); break; } leave: free_public_key( pk ); return rc; } void release_pk_list (pk_list_t pk_list) { PK_LIST pk_rover; for ( ; pk_list; pk_list = pk_rover) { pk_rover = pk_list->next; free_public_key ( pk_list->pk ); xfree ( pk_list ); } } static int key_present_in_pk_list(PK_LIST pk_list, PKT_public_key *pk) { for( ; pk_list; pk_list = pk_list->next) if (cmp_public_keys(pk_list->pk, pk) == 0) return 0; return -1; } /**************** * Return a malloced string with a default recipient if there is any */ static char * default_recipient(ctrl_t ctrl) { PKT_public_key *pk; byte fpr[MAX_FINGERPRINT_LEN+1]; size_t n; char *p; int i; if( opt.def_recipient ) return xstrdup( opt.def_recipient ); if( !opt.def_recipient_self ) return NULL; pk = xmalloc_clear( sizeof *pk ); i = get_seckey_default (ctrl, pk); if( i ) { free_public_key( pk ); return NULL; } n = MAX_FINGERPRINT_LEN; fingerprint_from_pk( pk, fpr, &n ); free_public_key( pk ); p = xmalloc( 2*n+3 ); *p++ = '0'; *p++ = 'x'; for(i=0; i < n; i++ ) sprintf( p+2*i, "%02X", fpr[i] ); p -= 2; return p; } static int expand_id(const char *id,strlist_t *into,unsigned int flags) { struct groupitem *groups; int count=0; for(groups=opt.grouplist;groups;groups=groups->next) { /* need strcasecmp() here, as this should be localized */ if(strcasecmp(groups->name,id)==0) { strlist_t each,sl; /* this maintains the current utf8-ness */ for(each=groups->values;each;each=each->next) { sl=add_to_strlist(into,each->d); sl->flags=flags; count++; } break; } } return count; } /* For simplicity, and to avoid potential loops, we only expand once - you can't make an alias that points to an alias. */ static strlist_t expand_group(strlist_t input) { strlist_t sl,output=NULL,rover; for(rover=input;rover;rover=rover->next) if(expand_id(rover->d,&output,rover->flags)==0) { /* Didn't find any groups, so use the existing string */ sl=add_to_strlist(&output,rover->d); sl->flags=rover->flags; } return output; } /* Helper for build_pk_list to find and check one key. This helper is also used directly in server mode by the RECIPIENTS command. On success the new key is added to PK_LIST_ADDR. NAME is the user id of the key. USE the requested usage and a set MARK_HIDDEN will mark the key in the updated list as a hidden recipient. */ gpg_error_t find_and_check_key (ctrl_t ctrl, const char *name, unsigned int use, int mark_hidden, pk_list_t *pk_list_addr) { int rc; PKT_public_key *pk; int trustlevel; if (!name || !*name) return gpg_error (GPG_ERR_INV_USER_ID); pk = xtrycalloc (1, sizeof *pk); if (!pk) return gpg_error_from_syserror (); pk->req_usage = use; rc = get_pubkey_byname (ctrl, NULL, pk, name, NULL, NULL, 0, 0); if (rc) { int code; /* Key not found or other error. */ log_error (_("%s: skipped: %s\n"), name, gpg_strerror (rc) ); switch (gpg_err_code (rc)) { case GPG_ERR_NO_SECKEY: case GPG_ERR_NO_PUBKEY: code = 1; break; case GPG_ERR_INV_USER_ID: code = 14; break; default: code = 0; break; } send_status_inv_recp (code, name); free_public_key (pk); return rc; } rc = openpgp_pk_test_algo2 (pk->pubkey_algo, use); if (rc) { /* Key found but not usable for us (e.g. sign-only key). */ send_status_inv_recp (3, name); /* Wrong key usage */ log_error (_("%s: skipped: %s\n"), name, gpg_strerror (rc) ); free_public_key (pk); return rc; } /* Key found and usable. Check validity. */ trustlevel = get_validity (pk, pk->user_id, NULL, 1); if ( (trustlevel & TRUST_FLAG_DISABLED) ) { /* Key has been disabled. */ send_status_inv_recp (13, name); log_info (_("%s: skipped: public key is disabled\n"), name); free_public_key (pk); return GPG_ERR_UNUSABLE_PUBKEY; } if ( !do_we_trust_pre (pk, trustlevel) ) { /* We don't trust this key. */ send_status_inv_recp (10, name); free_public_key (pk); return GPG_ERR_UNUSABLE_PUBKEY; } /* Note: do_we_trust may have changed the trustlevel. */ /* Skip the actual key if the key is already present in the list. */ if (!key_present_in_pk_list (*pk_list_addr, pk)) { if (!opt.quiet) log_info (_("%s: skipped: public key already present\n"), name); free_public_key (pk); } else { pk_list_t r; r = xtrymalloc (sizeof *r); if (!r) { rc = gpg_error_from_syserror (); free_public_key (pk); return rc; } r->pk = pk; r->next = *pk_list_addr; r->flags = mark_hidden? 1:0; *pk_list_addr = r; } return 0; } /* This is the central function to collect the keys for recipients. It is thus used to prepare a public key encryption. encrypt-to keys, default keys and the keys for the actual recipients are all collected here. When not in batch mode and no recipient has been passed on the commandline, the function will also ask for recipients. RCPTS is a string list with the recipients; NULL is an allowed value but not very useful. Group expansion is done on these names; they may be in any of the user Id formats we can handle. The flags bits for each string in the string list are used for: Bit 0 (PK_LIST_ENCRYPT_TO): This is an encrypt-to recipient. Bit 1 (PK_LIST_HIDDEN) : This is a hidden recipient. On success a list of keys is stored at the address RET_PK_LIST; the caller must free this list. On error the value at this address is not changed. */ int build_pk_list (ctrl_t ctrl, strlist_t rcpts, PK_LIST *ret_pk_list) { PK_LIST pk_list = NULL; PKT_public_key *pk=NULL; int rc=0; int any_recipients=0; strlist_t rov,remusr; char *def_rec = NULL; char pkstrbuf[PUBKEY_STRING_SIZE]; /* Try to expand groups if any have been defined. */ if (opt.grouplist) remusr = expand_group (rcpts); else remusr = rcpts; + /* XXX: Change this function to use get_pubkeys instead of + get_pubkey_byname to detect ambiguous key specifications and warn + about duplicate keyblocks. For ambiguous key specifications on + the command line or provided interactively, prompt the user to + select the best key. If a key specification is ambiguous and we + are in batch mode, die. */ + if (opt.encrypt_to_default_key) { static int warned; const char *default_key = parse_def_secret_key (ctrl); if (default_key) { PK_LIST r = xmalloc_clear (sizeof *r); r->pk = xmalloc_clear (sizeof *r->pk); r->pk->req_usage = PUBKEY_USAGE_ENC; rc = get_pubkey_byname (ctrl, NULL, r->pk, default_key, NULL, NULL, 0, 1); if (rc) { xfree (r->pk); xfree (r); log_error (_("Can't encrypt to '%s'.\n"), default_key); if (!opt.quiet) log_info (_("(check argument of option '%s')\n"), "--default-key"); } else { r->next = pk_list; r->flags = 0; pk_list = r; } } else if (opt.def_secret_key) { if (! warned) log_info (_("option '%s' given, but no valid default keys given\n"), "--encrypt-to-default-key"); warned = 1; } else { if (! warned) log_info (_("option '%s' given, but option '%s' not given\n"), "--encrypt-to-default-key", "--default-key"); warned = 1; } } /* Check whether there are any recipients in the list and build the * list of the encrypt-to ones (we always trust them). */ for ( rov = remusr; rov; rov = rov->next ) { if ( !(rov->flags & PK_LIST_ENCRYPT_TO) ) { /* This is a regular recipient; i.e. not an encrypt-to one. */ any_recipients = 1; /* Hidden recipients are not allowed while in PGP mode, issue a warning and switch into GnuPG mode. */ if ((rov->flags & PK_LIST_HIDDEN) && (PGP6 || PGP7 || PGP8)) { log_info(_("you may not use %s while in %s mode\n"), "--hidden-recipient", compliance_option_string()); compliance_failure(); } } else if (!opt.no_encrypt_to) { /* --encrypt-to has not been disabled. Check this encrypt-to key. */ pk = xmalloc_clear( sizeof *pk ); pk->req_usage = PUBKEY_USAGE_ENC; /* We explicitly allow encrypt-to to an disabled key; thus we pass 1 for the second last argument and 1 as the last argument to disable AKL. */ if ( (rc = get_pubkey_byname (ctrl, NULL, pk, rov->d, NULL, NULL, 1, 1)) ) { free_public_key ( pk ); pk = NULL; log_error (_("%s: skipped: %s\n"), rov->d, gpg_strerror (rc) ); send_status_inv_recp (0, rov->d); goto fail; } else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, PUBKEY_USAGE_ENC)) ) { /* Skip the actual key if the key is already present * in the list. Add it to our list if not. */ if (key_present_in_pk_list(pk_list, pk) == 0) { free_public_key (pk); pk = NULL; if (!opt.quiet) log_info (_("%s: skipped: public key already present\n"), rov->d); } else { PK_LIST r; r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = (rov->flags&PK_LIST_HIDDEN)?1:0; pk_list = r; /* Hidden encrypt-to recipients are not allowed while in PGP mode, issue a warning and switch into GnuPG mode. */ if ((r->flags&PK_LIST_ENCRYPT_TO) && (PGP6 || PGP7 || PGP8)) { log_info(_("you may not use %s while in %s mode\n"), "--hidden-encrypt-to", compliance_option_string()); compliance_failure(); } } } else { /* The public key is not usable for encryption. */ free_public_key( pk ); pk = NULL; log_error(_("%s: skipped: %s\n"), rov->d, gpg_strerror (rc) ); send_status_inv_recp (3, rov->d); /* Wrong key usage */ goto fail; } } } /* If we don't have any recipients yet and we are not in batch mode drop into interactive selection mode. */ if ( !any_recipients && !opt.batch ) { int have_def_rec; char *answer = NULL; strlist_t backlog = NULL; if (pk_list) any_recipients = 1; def_rec = default_recipient(ctrl); have_def_rec = !!def_rec; if ( !have_def_rec ) tty_printf(_("You did not specify a user ID. (you may use \"-r\")\n")); for (;;) { rc = 0; xfree(answer); if ( have_def_rec ) { /* A default recipient is taken as the first entry. */ answer = def_rec; def_rec = NULL; } else if (backlog) { /* This is part of our trick to expand and display groups. */ answer = strlist_pop (&backlog); } else { /* Show the list of already collected recipients and ask for more. */ PK_LIST iter; tty_printf("\n"); tty_printf(_("Current recipients:\n")); for (iter=pk_list;iter;iter=iter->next) { u32 keyid[2]; keyid_from_pk(iter->pk,keyid); tty_printf ("%s/%s %s \"", pubkey_string (iter->pk, pkstrbuf, sizeof pkstrbuf), keystr(keyid), datestr_from_pk (iter->pk)); if (iter->pk->user_id) tty_print_utf8_string(iter->pk->user_id->name, iter->pk->user_id->len); else { size_t n; char *p = get_user_id( keyid, &n ); tty_print_utf8_string( p, n ); xfree(p); } tty_printf("\"\n"); } answer = cpr_get_utf8("pklist.user_id.enter", _("\nEnter the user ID. " "End with an empty line: ")); trim_spaces(answer); cpr_kill_prompt(); } if ( !answer || !*answer ) { xfree(answer); break; /* No more recipients entered - get out of loop. */ } /* Do group expand here too. The trick here is to continue the loop if any expansion occurred. The code above will then list all expanded keys. */ if (expand_id(answer,&backlog,0)) continue; /* Get and check key for the current name. */ free_public_key (pk); pk = xmalloc_clear( sizeof *pk ); pk->req_usage = PUBKEY_USAGE_ENC; rc = get_pubkey_byname (ctrl, NULL, pk, answer, NULL, NULL, 0, 0 ); if (rc) tty_printf(_("No such user ID.\n")); else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, PUBKEY_USAGE_ENC)) ) { if ( have_def_rec ) { /* No validation for a default recipient. */ if (!key_present_in_pk_list(pk_list, pk)) { free_public_key (pk); pk = NULL; log_info (_("skipped: public key " "already set as default recipient\n") ); } else { PK_LIST r = xmalloc (sizeof *r); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing default ids. */ pk_list = r; } any_recipients = 1; continue; } else { /* Check validity of this key. */ int trustlevel; trustlevel = get_validity (pk, pk->user_id, NULL, 1); if ( (trustlevel & TRUST_FLAG_DISABLED) ) { tty_printf (_("Public key is disabled.\n") ); } else if ( do_we_trust_pre (pk, trustlevel) ) { /* Skip the actual key if the key is already * present in the list */ if (!key_present_in_pk_list(pk_list, pk)) { free_public_key (pk); pk = NULL; log_info(_("skipped: public key already set\n") ); } else { PK_LIST r; r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing interactive ids. */ pk_list = r; } any_recipients = 1; continue; } } } xfree(def_rec); def_rec = NULL; have_def_rec = 0; } if ( pk ) { free_public_key( pk ); pk = NULL; } } else if ( !any_recipients && (def_rec = default_recipient(ctrl)) ) { /* We are in batch mode and have only a default recipient. */ pk = xmalloc_clear( sizeof *pk ); pk->req_usage = PUBKEY_USAGE_ENC; /* The default recipient is allowed to be disabled; thus pass 1 as second last argument. We also don't want an AKL. */ rc = get_pubkey_byname (ctrl, NULL, pk, def_rec, NULL, NULL, 1, 1); if (rc) log_error(_("unknown default recipient \"%s\"\n"), def_rec ); else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo, PUBKEY_USAGE_ENC)) ) { /* Mark any_recipients here since the default recipient would have been used if it wasn't already there. It doesn't really matter if we got this key from the default recipient or an encrypt-to. */ any_recipients = 1; if (!key_present_in_pk_list(pk_list, pk)) log_info (_("skipped: public key already set " "as default recipient\n")); else { PK_LIST r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing default ids. */ pk_list = r; } } if ( pk ) { free_public_key( pk ); pk = NULL; } xfree(def_rec); def_rec = NULL; } else { /* General case: Check all keys. */ any_recipients = 0; for (; remusr; remusr = remusr->next ) { if ( (remusr->flags & PK_LIST_ENCRYPT_TO) ) continue; /* encrypt-to keys are already handled. */ rc = find_and_check_key (ctrl, remusr->d, PUBKEY_USAGE_ENC, !!(remusr->flags&PK_LIST_HIDDEN), &pk_list); if (rc) goto fail; any_recipients = 1; } } if ( !rc && !any_recipients ) { log_error(_("no valid addressees\n")); write_status_text (STATUS_NO_RECP, "0"); rc = GPG_ERR_NO_USER_ID; } fail: if ( rc ) release_pk_list( pk_list ); else *ret_pk_list = pk_list; if (opt.grouplist) free_strlist(remusr); return rc; } /* In pgp6 mode, disallow all ciphers except IDEA (1), 3DES (2), and CAST5 (3), all hashes except MD5 (1), SHA1 (2), and RIPEMD160 (3), and all compressions except none (0) and ZIP (1). pgp7 and pgp8 mode expands the cipher list to include AES128 (7), AES192 (8), AES256 (9), and TWOFISH (10). pgp8 adds the SHA-256 hash (8). For a true PGP key all of this is unneeded as they are the only items present in the preferences subpacket, but checking here covers the weird case of encrypting to a key that had preferences from a different implementation which was then used with PGP. I am not completely comfortable with this as the right thing to do, as it slightly alters the list of what the user is supposedly requesting. It is not against the RFC however, as the preference chosen will never be one that the user didn't specify somewhere ("The implementation may use any mechanism to pick an algorithm in the intersection"), and PGP has no mechanism to fix such a broken preference list, so I'm including it. -dms */ int algo_available( preftype_t preftype, int algo, const union pref_hint *hint) { if( preftype == PREFTYPE_SYM ) { if(PGP6 && (algo != CIPHER_ALGO_IDEA && algo != CIPHER_ALGO_3DES && algo != CIPHER_ALGO_CAST5)) return 0; if(PGP7 && (algo != CIPHER_ALGO_IDEA && algo != CIPHER_ALGO_3DES && algo != CIPHER_ALGO_CAST5 && algo != CIPHER_ALGO_AES && algo != CIPHER_ALGO_AES192 && algo != CIPHER_ALGO_AES256 && algo != CIPHER_ALGO_TWOFISH)) return 0; /* PGP8 supports all the ciphers we do.. */ return algo && !openpgp_cipher_test_algo ( algo ); } else if( preftype == PREFTYPE_HASH ) { if (hint && hint->digest_length) { if (hint->digest_length!=20 || opt.flags.dsa2) { /* If --enable-dsa2 is set or the hash isn't 160 bits (which implies DSA2), then we'll accept a hash that is larger than we need. Otherwise we won't accept any hash that isn't exactly the right size. */ if (hint->digest_length > gcry_md_get_algo_dlen (algo)) return 0; } else if (hint->digest_length != gcry_md_get_algo_dlen (algo)) return 0; } if((PGP6 || PGP7) && (algo != DIGEST_ALGO_MD5 && algo != DIGEST_ALGO_SHA1 && algo != DIGEST_ALGO_RMD160)) return 0; if(PGP8 && (algo != DIGEST_ALGO_MD5 && algo != DIGEST_ALGO_SHA1 && algo != DIGEST_ALGO_RMD160 && algo != DIGEST_ALGO_SHA256)) return 0; return algo && !openpgp_md_test_algo (algo); } else if( preftype == PREFTYPE_ZIP ) { if((PGP6 || PGP7) && (algo != COMPRESS_ALGO_NONE && algo != COMPRESS_ALGO_ZIP)) return 0; /* PGP8 supports all the compression algos we do */ return !check_compress_algo( algo ); } else return 0; } /**************** * Return -1 if we could not find an algorithm. */ int select_algo_from_prefs(PK_LIST pk_list, int preftype, int request, const union pref_hint *hint) { PK_LIST pkr; u32 bits[8]; const prefitem_t *prefs; int result=-1,i; u16 scores[256]; if( !pk_list ) return -1; memset(bits,0xFF,sizeof(bits)); memset(scores,0,sizeof(scores)); for( pkr = pk_list; pkr; pkr = pkr->next ) { u32 mask[8]; int rank=1,implicit=-1; memset(mask,0,sizeof(mask)); switch(preftype) { case PREFTYPE_SYM: /* IDEA is implicitly there for v3 keys with v3 selfsigs if --pgp2 mode is on. This was a 2440 thing that was dropped from 4880 but is still relevant to GPG's 1991 support. All this doesn't mean IDEA is actually available, of course. */ implicit=CIPHER_ALGO_3DES; break; case PREFTYPE_HASH: /* While I am including this code for completeness, note that currently --pgp2 mode locks the hash at MD5, so this code will never even be called. Even if the hash wasn't locked at MD5, we don't support sign+encrypt in --pgp2 mode, and that's the only time PREFTYPE_HASH is used anyway. -dms */ implicit=DIGEST_ALGO_SHA1; break; case PREFTYPE_ZIP: /* Uncompressed is always an option. */ implicit=COMPRESS_ALGO_NONE; } if (pkr->pk->user_id) /* selected by user ID */ prefs = pkr->pk->user_id->prefs; else prefs = pkr->pk->prefs; if( prefs ) { for (i=0; prefs[i].type; i++ ) { if( prefs[i].type == preftype ) { /* Make sure all scores don't add up past 0xFFFF (and roll around) */ if(rank+scores[prefs[i].value]<=0xFFFF) scores[prefs[i].value]+=rank; else scores[prefs[i].value]=0xFFFF; mask[prefs[i].value/32] |= 1<<(prefs[i].value%32); rank++; /* We saw the implicit algorithm, so we don't need tack it on the end ourselves. */ if(implicit==prefs[i].value) implicit=-1; } } } if(rank==1 && preftype==PREFTYPE_ZIP) { /* If the compression preferences are not present, they are assumed to be ZIP, Uncompressed (RFC4880:13.3.1) */ scores[1]=1; /* ZIP is first choice */ scores[0]=2; /* Uncompressed is second choice */ mask[0]|=3; } /* If the key didn't have the implicit algorithm listed explicitly, add it here at the tail of the list. */ if(implicit>-1) { scores[implicit]+=rank; mask[implicit/32] |= 1<<(implicit%32); } for(i=0;i<8;i++) bits[i]&=mask[i]; } /* We've now scored all of the algorithms, and the usable ones have bits set. Let's pick the winner. */ /* The caller passed us a request. Can we use it? */ if(request>-1 && (bits[request/32] & (1<<(request%32))) && algo_available(preftype,request,hint)) result=request; if(result==-1) { /* If we have personal prefs set, use them. */ prefs=NULL; if(preftype==PREFTYPE_SYM && opt.personal_cipher_prefs) prefs=opt.personal_cipher_prefs; else if(preftype==PREFTYPE_HASH && opt.personal_digest_prefs) prefs=opt.personal_digest_prefs; else if(preftype==PREFTYPE_ZIP && opt.personal_compress_prefs) prefs=opt.personal_compress_prefs; if( prefs ) for(i=0; prefs[i].type; i++ ) { if(bits[prefs[i].value/32] & (1<<(prefs[i].value%32)) && algo_available( preftype, prefs[i].value, hint)) { result = prefs[i].value; break; } } } if(result==-1) { unsigned int best=-1; /* At this point, we have not selected an algorithm due to a special request or via personal prefs. Pick the highest ranked algorithm (i.e. the one with the lowest score). */ if(preftype==PREFTYPE_HASH && scores[DIGEST_ALGO_MD5]) { /* "If you are building an authentication system, the recipient may specify a preferred signing algorithm. However, the signer would be foolish to use a weak algorithm simply because the recipient requests it." (RFC4880:14). If any other hash algorithm is available, pretend that MD5 isn't. Note that if the user intentionally chose MD5 by putting it in their personal prefs, then we do what the user said (as we never reach this code). */ for(i=DIGEST_ALGO_MD5+1;i<256;i++) if(scores[i]) { scores[DIGEST_ALGO_MD5]=0; break; } } for(i=0;i<256;i++) { /* Note the '<' here. This means in case of a tie, we will favor the lower algorithm number. We have a choice between the lower number (probably an older algorithm with more time in use), or the higher number (probably a newer algorithm with less time in use). Older is probably safer here, even though the newer algorithms tend to be "stronger". */ if(scores[i] && scores[i]next) { int mdc; if (pkr->pk->user_id) /* selected by user ID */ mdc = pkr->pk->user_id->flags.mdc; else mdc = pkr->pk->flags.mdc; if (!mdc) return 0; /* At least one recipient does not support it. */ } return 1; /* Can be used. */ } /* Print a warning for all keys in PK_LIST missing the MDC feature. */ void warn_missing_mdc_from_pklist (PK_LIST pk_list) { PK_LIST pkr; for (pkr = pk_list; pkr; pkr = pkr->next) { int mdc; if (pkr->pk->user_id) /* selected by user ID */ mdc = pkr->pk->user_id->flags.mdc; else mdc = pkr->pk->flags.mdc; if (!mdc) log_info (_("Note: key %s has no %s feature\n"), keystr_from_pk (pkr->pk), "MDC"); } } void warn_missing_aes_from_pklist (PK_LIST pk_list) { PK_LIST pkr; for (pkr = pk_list; pkr; pkr = pkr->next) { const prefitem_t *prefs; int i; int gotit = 0; prefs = pkr->pk->user_id? pkr->pk->user_id->prefs : pkr->pk->prefs; if (prefs) { for (i=0; !gotit && prefs[i].type; i++ ) if (prefs[i].type == PREFTYPE_SYM && prefs[i].value == CIPHER_ALGO_AES) gotit++; } if (!gotit) log_info (_("Note: key %s has no preference for %s\n"), keystr_from_pk (pkr->pk), "AES"); } } diff --git a/g10/skclist.c b/g10/skclist.c index 3d137b261..1eb0633fd 100644 --- a/g10/skclist.c +++ b/g10/skclist.c @@ -1,264 +1,271 @@ /* skclist.c - Build a list of secret keys * Copyright (C) 1998, 1999, 2000, 2001, 2006, * 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "keydb.h" #include "util.h" #include "i18n.h" /* Return true if Libgcrypt's RNG is in faked mode. */ int random_is_faked (void) { return !!gcry_control (GCRYCTL_FAKED_RANDOM_P, 0); } void release_sk_list (SK_LIST sk_list) { SK_LIST sk_rover; for (; sk_list; sk_list = sk_rover) { sk_rover = sk_list->next; free_public_key (sk_list->pk); xfree (sk_list); } } /* Check that we are only using keys which don't have * the string "(insecure!)" or "not secure" or "do not use" * in one of the user ids. */ static int is_insecure (PKT_public_key *pk) { u32 keyid[2]; KBNODE node = NULL, u; int insecure = 0; keyid_from_pk (pk, keyid); node = get_pubkeyblock (keyid); for (u = node; u; u = u->next) { if (u->pkt->pkttype == PKT_USER_ID) { PKT_user_id *id = u->pkt->pkt.user_id; if (id->attrib_data) continue; /* skip attribute packets */ if (strstr (id->name, "(insecure!)") || strstr (id->name, "not secure") || strstr (id->name, "do not use") || strstr (id->name, "(INSECURE!)")) { insecure = 1; break; } } } release_kbnode (node); return insecure; } static int key_present_in_sk_list (SK_LIST sk_list, PKT_public_key *pk) { for (; sk_list; sk_list = sk_list->next) { if (!cmp_public_keys (sk_list->pk, pk)) return 0; } return -1; } static int is_duplicated_entry (strlist_t list, strlist_t item) { for (; list && list != item; list = list->next) { if (!strcmp (list->d, item->d)) return 1; } return 0; } gpg_error_t build_sk_list (ctrl_t ctrl, strlist_t locusr, SK_LIST *ret_sk_list, unsigned int use) { gpg_error_t err; SK_LIST sk_list = NULL; + /* XXX: Change this function to use get_pubkeys instead of + getkey_byname to detect ambiguous key specifications and warn + about duplicate keyblocks. For ambiguous key specifications on + the command line or provided interactively, prompt the user to + select the best key. If a key specification is ambiguous and we + are in batch mode, die. */ + if (!locusr) /* No user ids given - use the default key. */ { PKT_public_key *pk; pk = xmalloc_clear (sizeof *pk); pk->req_usage = use; if ((err = getkey_byname (ctrl, NULL, pk, NULL, 1, NULL))) { free_public_key (pk); pk = NULL; log_error ("no default secret key: %s\n", gpg_strerror (err)); write_status_text (STATUS_INV_SGNR, get_inv_recpsgnr_code (err)); } else if ((err = openpgp_pk_test_algo2 (pk->pubkey_algo, use))) { free_public_key (pk); pk = NULL; log_error ("invalid default secret key: %s\n", gpg_strerror (err)); write_status_text (STATUS_INV_SGNR, get_inv_recpsgnr_code (err)); } else { SK_LIST r; if (random_is_faked () && !is_insecure (pk)) { log_info (_("key is not flagged as insecure - " "can't use it with the faked RNG!\n")); free_public_key (pk); pk = NULL; write_status_text (STATUS_INV_SGNR, get_inv_recpsgnr_code (GPG_ERR_NOT_TRUSTED)); } else { r = xmalloc (sizeof *r); r->pk = pk; pk = NULL; r->next = sk_list; r->mark = 0; sk_list = r; } } } else /* Check the given user ids. */ { strlist_t locusr_orig = locusr; for (; locusr; locusr = locusr->next) { PKT_public_key *pk; err = 0; /* Do an early check against duplicated entries. However * this won't catch all duplicates because the user IDs may * be specified in different ways. */ if (is_duplicated_entry (locusr_orig, locusr)) { log_info (_("skipped \"%s\": duplicated\n"), locusr->d); continue; } pk = xmalloc_clear (sizeof *pk); pk->req_usage = use; if ((err = getkey_byname (ctrl, NULL, pk, locusr->d, 1, NULL))) { free_public_key (pk); pk = NULL; log_error (_("skipped \"%s\": %s\n"), locusr->d, gpg_strerror (err)); write_status_text_and_buffer (STATUS_INV_SGNR, get_inv_recpsgnr_code (err), locusr->d, strlen (locusr->d), -1); } else if (!key_present_in_sk_list (sk_list, pk)) { free_public_key (pk); pk = NULL; log_info (_("skipped: secret key already present\n")); } else if ((err = openpgp_pk_test_algo2 (pk->pubkey_algo, use))) { free_public_key (pk); pk = NULL; log_error ("skipped \"%s\": %s\n", locusr->d, gpg_strerror (err)); write_status_text_and_buffer (STATUS_INV_SGNR, get_inv_recpsgnr_code (err), locusr->d, strlen (locusr->d), -1); } else { SK_LIST r; if (pk->version == 4 && (use & PUBKEY_USAGE_SIG) && pk->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E) { log_info (_("skipped \"%s\": %s\n"), locusr->d, _("this is a PGP generated Elgamal key which" " is not secure for signatures!")); free_public_key (pk); pk = NULL; write_status_text_and_buffer (STATUS_INV_SGNR, get_inv_recpsgnr_code (GPG_ERR_WRONG_KEY_USAGE), locusr->d, strlen (locusr->d), -1); } else if (random_is_faked () && !is_insecure (pk)) { log_info (_("key is not flagged as insecure - " "can't use it with the faked RNG!\n")); free_public_key (pk); pk = NULL; write_status_text_and_buffer (STATUS_INV_SGNR, get_inv_recpsgnr_code (GPG_ERR_NOT_TRUSTED), locusr->d, strlen (locusr->d), -1); } else { r = xmalloc (sizeof *r); r->pk = pk; pk = NULL; r->next = sk_list; r->mark = 0; sk_list = r; } } } } if (!err && !sk_list) { log_error ("no valid signators\n"); write_status_text (STATUS_NO_SGNR, "0"); err = gpg_error (GPG_ERR_NO_USER_ID); } if (err) release_sk_list (sk_list); else *ret_sk_list = sk_list; return err; }