diff --git a/doc/gpg.texi b/doc/gpg.texi index 9b6303540..0c53bc1d4 100644 --- a/doc/gpg.texi +++ b/doc/gpg.texi @@ -1,4371 +1,4382 @@ @c Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, @c 2008, 2009, 2010 Free Software Foundation, Inc. @c This is part of the GnuPG manual. @c For copying conditions, see the file gnupg.texi. @include defs.inc @node Invoking GPG @chapter Invoking GPG @cindex GPG command options @cindex command options @cindex options, GPG command @c Begin standard stuff @ifclear gpgtwohack @manpage gpg.1 @ifset manverb .B gpg \- OpenPGP encryption and signing tool @end ifset @mansect synopsis @ifset manverb .B gpg .RB [ \-\-homedir .IR dir ] .RB [ \-\-options .IR file ] .RI [ options ] .I command .RI [ args ] @end ifset @end ifclear @c End standard stuff @c Begin gpg2 hack stuff @ifset gpgtwohack @manpage gpg2.1 @ifset manverb .B gpg2 \- OpenPGP encryption and signing tool @end ifset @mansect synopsis @ifset manverb .B gpg2 .RB [ \-\-homedir .IR dir ] .RB [ \-\-options .IR file ] .RI [ options ] .I command .RI [ args ] @end ifset @end ifset @c End gpg2 hack stuff @mansect description @command{@gpgname} is the OpenPGP part of the GNU Privacy Guard (GnuPG). It is a tool to provide digital encryption and signing services using the OpenPGP standard. @command{@gpgname} features complete key management and all the bells and whistles you would expect from a full OpenPGP implementation. There are two main versions of GnuPG: GnuPG 1.x and GnuPG 2.x. GnuPG 2.x supports modern encryption algorithms and thus should be preferred over GnuPG 1.x. You only need to use GnuPG 1.x if your platform doesn't support GnuPG 2.x, or you need support for some features that GnuPG 2.x has deprecated, e.g., decrypting data created with PGP-2 keys. @ifclear gpgtwohack If you are looking for version 1 of GnuPG, you may find that version installed under the name @command{gpg1}. @end ifclear @ifset gpgtwohack In contrast to the standalone command @command{gpg} from GnuPG 1.x, the 2.x version is commonly installed under the name @command{@gpgname}. @end ifset @manpause @xref{Option Index}, for an index to @command{@gpgname}'s commands and options. @mancont @menu * GPG Commands:: List of all commands. * GPG Options:: List of all options. * GPG Configuration:: Configuration files. * GPG Examples:: Some usage examples. Developer information: * Unattended Usage of GPG:: Using @command{gpg} from other programs. @end menu @c * GPG Protocol:: The protocol the server mode uses. @c ******************************************* @c *************** **************** @c *************** COMMANDS **************** @c *************** **************** @c ******************************************* @mansect commands @node GPG Commands @section Commands Commands are not distinguished from options except for the fact that only one command is allowed. Generally speaking, irrelevant options are silently ignored, and may not be checked for correctness. @command{@gpgname} may be run with no commands. In this case it will print a warning perform a reasonable action depending on the type of file it is given as input (an encrypted message is decrypted, a signature is verified, a file containing keys is listed, etc.). If you run into any problems, please add the option @option{--verbose} to the invocation to see more diagnostics. @menu * General GPG Commands:: Commands not specific to the functionality. * Operational GPG Commands:: Commands to select the type of operation. * OpenPGP Key Management:: How to manage your keys. @end menu @c ******************************************* @c ********** GENERAL COMMANDS ************* @c ******************************************* @node General GPG Commands @subsection Commands not specific to the function @table @gnupgtabopt @item --version @opindex version Print the program version and licensing information. Note that you cannot abbreviate this command. @item --help @itemx -h @opindex help Print a usage message summarizing the most useful command-line options. Note that you cannot arbitrarily abbreviate this command (though you can use its short form @option{-h}). @item --warranty @opindex warranty Print warranty information. @item --dump-options @opindex dump-options Print a list of all available options and commands. Note that you cannot abbreviate this command. @end table @c ******************************************* @c ******** OPERATIONAL COMMANDS *********** @c ******************************************* @node Operational GPG Commands @subsection Commands to select the type of operation @table @gnupgtabopt @item --sign @itemx -s @opindex sign Sign a message. This command may be combined with @option{--encrypt} (to sign and encrypt a message), @option{--symmetric} (to sign and symmetrically encrypt a message), or both @option{--encrypt} and @option{--symmetric} (to sign and encrypt a message that can be decrypted using a secret key or a passphrase). The signing key is chosen by default or can be set explicitly using the @option{--local-user} and @option{--default-key} options. @item --clear-sign @opindex clear-sign @itemx --clearsign @opindex clearsign Make a cleartext signature. The content in a cleartext signature is readable without any special software. OpenPGP software is only needed to verify the signature. cleartext signatures may modify end-of-line whitespace for platform independence and are not intended to be reversible. The signing key is chosen by default or can be set explicitly using the @option{--local-user} and @option{--default-key} options. @item --detach-sign @itemx -b @opindex detach-sign Make a detached signature. @item --encrypt @itemx -e @opindex encrypt Encrypt data to one or more public keys. This command may be combined with @option{--sign} (to sign and encrypt a message), @option{--symmetric} (to encrypt a message that can be decrypted using a secret key or a passphrase), or @option{--sign} and @option{--symmetric} together (for a signed message that can be decrypted using a secret key or a passphrase). @option{--recipient} and related options specify which public keys to use for encryption. @item --symmetric @itemx -c @opindex symmetric Encrypt with a symmetric cipher using a passphrase. The default symmetric cipher used is @value{GPGSYMENCALGO}, but may be chosen with the @option{--cipher-algo} option. This command may be combined with @option{--sign} (for a signed and symmetrically encrypted message), @option{--encrypt} (for a message that may be decrypted via a secret key or a passphrase), or @option{--sign} and @option{--encrypt} together (for a signed message that may be decrypted via a secret key or a passphrase). @command{@gpgname} caches the passphrase used for symmetric encryption so that a decrypt operation may not require that the user needs to enter the passphrase. The option @option{--no-symkey-cache} can be used to disable this feature. @item --store @opindex store Store only (make a simple literal data packet). @item --decrypt @itemx -d @opindex decrypt Decrypt the file given on the command line (or STDIN if no file is specified) and write it to STDOUT (or the file specified with @option{--output}). If the decrypted file is signed, the signature is also verified. This command differs from the default operation, as it never writes to the filename which is included in the file and it rejects files that don't begin with an encrypted message. @item --verify @opindex verify Assume that the first argument is a signed file and verify it without generating any output. With no arguments, the signature packet is read from STDIN. If only one argument is given, the specified file is expected to include a complete signature. With more than one argument, the first argument should specify a file with a detached signature and the remaining files should contain the signed data. To read the signed data from STDIN, use @samp{-} as the second filename. For security reasons, a detached signature will not read the signed material from STDIN if not explicitly specified. Note: If the option @option{--batch} is not used, @command{@gpgname} may assume that a single argument is a file with a detached signature, and it will try to find a matching data file by stripping certain suffixes. Using this historical feature to verify a detached signature is strongly discouraged; you should always specify the data file explicitly. Note: When verifying a cleartext signature, @command{@gpgname} verifies only what makes up the cleartext signed data and not any extra data outside of the cleartext signature or the header lines directly following the dash marker line. The option @code{--output} may be used to write out the actual signed data, but there are other pitfalls with this format as well. It is suggested to avoid cleartext signatures in favor of detached signatures. Note: Sometimes the use of the @command{gpgv} tool is easier than using the full-fledged @command{gpg} with this option. @command{gpgv} is designed to compare signed data against a list of trusted keys and returns with success only for a good signature. It has its own manual page. @item --multifile @opindex multifile This modifies certain other commands to accept multiple files for processing on the command line or read from STDIN with each filename on a separate line. This allows for many files to be processed at once. @option{--multifile} may currently be used along with @option{--verify}, @option{--encrypt}, and @option{--decrypt}. Note that @option{--multifile --verify} may not be used with detached signatures. @item --verify-files @opindex verify-files Identical to @option{--multifile --verify}. @item --encrypt-files @opindex encrypt-files Identical to @option{--multifile --encrypt}. @item --decrypt-files @opindex decrypt-files Identical to @option{--multifile --decrypt}. @item --list-keys @itemx -k @itemx --list-public-keys @opindex list-keys List the specified keys. If no keys are specified, then all keys from the configured public keyrings are listed. Never use the output of this command in scripts or other programs. The output is intended only for humans and its format is likely to change. The @option{--with-colons} option emits the output in a stable, machine-parseable format, which is intended for use by scripts and other programs. @item --list-secret-keys @itemx -K @opindex list-secret-keys List the specified secret keys. If no keys are specified, then all known secret keys are listed. A @code{#} after the initial tags @code{sec} or @code{ssb} means that the secret key or subkey is currently not usable. We also say that this key has been taken offline (for example, a primary key can be taken offline by exporting the key using the command @option{--export-secret-subkeys}). A @code{>} after these tags indicate that the key is stored on a smartcard. See also @option{--list-keys}. @item --check-signatures @opindex check-signatures @itemx --check-sigs @opindex check-sigs Same as @option{--list-keys}, but the key signatures are verified and listed too. Note that for performance reasons the revocation status of a signing key is not shown. This command has the same effect as using @option{--list-keys} with @option{--with-sig-check}. The status of the verification is indicated by a flag directly following the "sig" tag (and thus before the flags described below. A "!" indicates that the signature has been successfully verified, a "-" denotes a bad signature and a "%" is used if an error occurred while checking the signature (e.g. a non supported algorithm). Signatures where the public key is not available are not listed; to see their keyids the command @option{--list-sigs} can be used. For each signature listed, there are several flags in between the signature status flag and keyid. These flags give additional information about each key signature. From left to right, they are the numbers 1-3 for certificate check level (see @option{--ask-cert-level}), "L" for a local or non-exportable signature (see @option{--lsign-key}), "R" for a nonRevocable signature (see the @option{--edit-key} command "nrsign"), "P" for a signature that contains a policy URL (see @option{--cert-policy-url}), "N" for a signature that contains a notation (see @option{--cert-notation}), "X" for an eXpired signature (see @option{--ask-cert-expire}), and the numbers 1-9 or "T" for 10 and above to indicate trust signature levels (see the @option{--edit-key} command "tsign"). @item --locate-keys @itemx --locate-external-keys @opindex locate-keys @opindex locate-external-keys Locate the keys given as arguments. This command basically uses the -same algorithm as used when locating keys for encryption or signing -and may thus be used to see what keys @command{@gpgname} might use. -In particular external methods as defined by -@option{--auto-key-locate} may be used to locate a key. Only public -keys are listed. The variant @option{--locate-external-keys} does not -consider a locally existing key and can thus be used to force the -refresh of a key via the defined external methods. +same algorithm as used when locating keys for encryption and may thus +be used to see what keys @command{@gpgname} might use. In particular +external methods as defined by @option{--auto-key-locate} are used to +locate a key if the arguments comain valid mail addresses. Only +public keys are listed. + +The variant @option{--locate-external-keys} does not consider a +locally existing key and can thus be used to force the refresh of a +key via the defined external methods. If a fingerprint is given and +and the methods defined by --auto-key-locate define LDAP servers, the +key is fetched from these resources; defined non-LDAP keyservers are +skipped. @item --show-keys @opindex show-keys This commands takes OpenPGP keys as input and prints information about them in the same way the command @option{--list-keys} does for locally stored key. In addition the list options @code{show-unusable-uids}, @code{show-unusable-subkeys}, @code{show-notations} and @code{show-policy-urls} are also enabled. As usual for automated processing, this command should be combined with the option @option{--with-colons}. @item --fingerprint @opindex fingerprint List all keys (or the specified ones) along with their fingerprints. This is the same output as @option{--list-keys} but with the additional output of a line with the fingerprint. May also be combined with @option{--check-signatures}. If this command is given twice, the fingerprints of all secondary keys are listed too. This command also forces pretty printing of fingerprints if the keyid format has been set to "none". @item --list-packets @opindex list-packets List only the sequence of packets. This command is only useful for debugging. When used with option @option{--verbose} the actual MPI values are dumped and not only their lengths. Note that the output of this command may change with new releases. @item --edit-card @opindex edit-card @itemx --card-edit @opindex card-edit Present a menu to work with a smartcard. The subcommand "help" provides an overview on available commands. For a detailed description, please see the Card HOWTO at https://gnupg.org/documentation/howtos.html#GnuPG-cardHOWTO . @item --card-status @opindex card-status Show the content of the smart card. @item --change-pin @opindex change-pin Present a menu to allow changing the PIN of a smartcard. This functionality is also available as the subcommand "passwd" with the @option{--edit-card} command. @item --delete-keys @var{name} @opindex delete-keys Remove key from the public keyring. In batch mode either @option{--yes} is required or the key must be specified by fingerprint. This is a safeguard against accidental deletion of multiple keys. If the exclamation mark syntax is used with the fingerprint of a subkey only that subkey is deleted; if the exclamation mark is used with the fingerprint of the primary key the entire public key is deleted. @item --delete-secret-keys @var{name} @opindex delete-secret-keys Remove key from the secret keyring. In batch mode the key must be specified by fingerprint. The option @option{--yes} can be used to advise gpg-agent not to request a confirmation. This extra pre-caution is done because @command{@gpgname} can't be sure that the secret key (as controlled by gpg-agent) is only used for the given OpenPGP public key. If the exclamation mark syntax is used with the fingerprint of a subkey only the secret part of that subkey is deleted; if the exclamation mark is used with the fingerprint of the primary key only the secret part of the primary key is deleted. @item --delete-secret-and-public-key @var{name} @opindex delete-secret-and-public-key Same as @option{--delete-key}, but if a secret key exists, it will be removed first. In batch mode the key must be specified by fingerprint. The option @option{--yes} can be used to advise gpg-agent not to request a confirmation. @item --export @opindex export Either export all keys from all keyrings (default keyrings and those registered via option @option{--keyring}), or if at least one name is given, those of the given name. The exported keys are written to STDOUT or to the file given with option @option{--output}. Use together with @option{--armor} to mail those keys. @item --send-keys @var{keyIDs} @opindex send-keys Similar to @option{--export} but sends the keys to a keyserver. Fingerprints may be used instead of key IDs. Don't send your complete keyring to a keyserver --- select only those keys which are new or changed by you. If no @var{keyIDs} are given, @command{@gpgname} does nothing. Take care: Keyservers are by design write only systems and thus it is not possible to ever delete keys once they have been send to a keyserver. @item --export-secret-keys @itemx --export-secret-subkeys @opindex export-secret-keys @opindex export-secret-subkeys Same as @option{--export}, but exports the secret keys instead. The exported keys are written to STDOUT or to the file given with option @option{--output}. This command is often used along with the option @option{--armor} to allow for easy printing of the key for paper backup; however the external tool @command{paperkey} does a better job of creating backups on paper. Note that exporting a secret key can be a security risk if the exported keys are sent over an insecure channel. The second form of the command has the special property to render the secret part of the primary key useless; this is a GNU extension to OpenPGP and other implementations can not be expected to successfully import such a key. Its intended use is in generating a full key with an additional signing subkey on a dedicated machine. This command then exports the key without the primary key to the main machine. GnuPG may ask you to enter the passphrase for the key. This is required, because the internal protection method of the secret key is different from the one specified by the OpenPGP protocol. @item --export-ssh-key @opindex export-ssh-key This command is used to export a key in the OpenSSH public key format. It requires the specification of one key by the usual means and exports the latest valid subkey which has an authentication capability to STDOUT or to the file given with option @option{--output}. That output can directly be added to ssh's @file{authorized_key} file. By specifying the key to export using a key ID or a fingerprint suffixed with an exclamation mark (!), a specific subkey or the primary key can be exported. This does not even require that the key has the authentication capability flag set. @item --import @itemx --fast-import @opindex import Import/merge keys. This adds the given keys to the keyring. The fast version is currently just a synonym. There are a few other options which control how this command works. Most notable here is the @option{--import-options merge-only} option which does not insert new keys but does only the merging of new signatures, user-IDs and subkeys. @item --receive-keys @var{keyIDs} @opindex receive-keys @itemx --recv-keys @var{keyIDs} @opindex recv-keys Import the keys with the given @var{keyIDs} from a keyserver. @item --refresh-keys @opindex refresh-keys Request updates from a keyserver for keys that already exist on the local keyring. This is useful for updating a key with the latest signatures, user IDs, etc. Calling this with no arguments will refresh the entire keyring. @item --search-keys @var{names} @opindex search-keys Search the keyserver for the given @var{names}. Multiple names given here will be joined together to create the search string for the keyserver. Note that keyservers search for @var{names} in a different and simpler way than gpg does. The best choice is to use a mail address. Due to data privacy reasons keyservers may even not even allow searching by user id or mail address and thus may only return results when being used with the @option{--recv-key} command to search by key fingerprint or keyid. @item --fetch-keys @var{URIs} @opindex fetch-keys Retrieve keys located at the specified @var{URIs}. Note that different installations of GnuPG may support different protocols (HTTP, FTP, LDAP, etc.). When using HTTPS the system provided root certificates are used by this command. @item --update-trustdb @opindex update-trustdb Do trust database maintenance. This command iterates over all keys and builds the Web of Trust. This is an interactive command because it may have to ask for the "ownertrust" values for keys. The user has to give an estimation of how far she trusts the owner of the displayed key to correctly certify (sign) other keys. GnuPG only asks for the ownertrust value if it has not yet been assigned to a key. Using the @option{--edit-key} menu, the assigned value can be changed at any time. @item --check-trustdb @opindex check-trustdb Do trust database maintenance without user interaction. From time to time the trust database must be updated so that expired keys or signatures and the resulting changes in the Web of Trust can be tracked. Normally, GnuPG will calculate when this is required and do it automatically unless @option{--no-auto-check-trustdb} is set. This command can be used to force a trust database check at any time. The processing is identical to that of @option{--update-trustdb} but it skips keys with a not yet defined "ownertrust". For use with cron jobs, this command can be used together with @option{--batch} in which case the trust database check is done only if a check is needed. To force a run even in batch mode add the option @option{--yes}. @anchor{option --export-ownertrust} @item --export-ownertrust @opindex export-ownertrust Send the ownertrust values to STDOUT. This is useful for backup purposes as these values are the only ones which can't be re-created from a corrupted trustdb. Example: @c man:.RS @example @gpgname{} --export-ownertrust > otrust.txt @end example @c man:.RE @item --import-ownertrust @opindex import-ownertrust Update the trustdb with the ownertrust values stored in @code{files} (or STDIN if not given); existing values will be overwritten. In case of a severely damaged trustdb and if you have a recent backup of the ownertrust values (e.g. in the file @file{otrust.txt}), you may re-create the trustdb using these commands: @c man:.RS @example cd ~/.gnupg rm trustdb.gpg @gpgname{} --import-ownertrust < otrust.txt @end example @c man:.RE @item --rebuild-keydb-caches @opindex rebuild-keydb-caches When updating from version 1.0.6 to 1.0.7 this command should be used to create signature caches in the keyring. It might be handy in other situations too. @item --print-md @var{algo} @itemx --print-mds @opindex print-md Print message digest of algorithm @var{algo} for all given files or STDIN. With the second form (or a deprecated "*" for @var{algo}) digests for all available algorithms are printed. @item --gen-random @var{0|1|2} @var{count} @opindex gen-random Emit @var{count} random bytes of the given quality level 0, 1 or 2. If @var{count} is not given or zero, an endless sequence of random bytes will be emitted. If used with @option{--armor} the output will be base64 encoded. PLEASE, don't use this command unless you know what you are doing; it may remove precious entropy from the system! @item --gen-prime @var{mode} @var{bits} @opindex gen-prime Use the source, Luke :-). The output format is subject to change with ant release. @item --enarmor @itemx --dearmor @opindex enarmor @opindex dearmor Pack or unpack an arbitrary input into/from an OpenPGP ASCII armor. This is a GnuPG extension to OpenPGP and in general not very useful. @item --tofu-policy @{auto|good|unknown|bad|ask@} @var{keys} @opindex tofu-policy Set the TOFU policy for all the bindings associated with the specified @var{keys}. For more information about the meaning of the policies, @pxref{trust-model-tofu}. The @var{keys} may be specified either by their fingerprint (preferred) or their keyid. @c @item --server @c @opindex server @c Run gpg in server mode. This feature is not yet ready for use and @c thus not documented. @end table @c ******************************************* @c ******* KEY MANGEMENT COMMANDS ********** @c ******************************************* @node OpenPGP Key Management @subsection How to manage your keys This section explains the main commands for key management. @table @gnupgtabopt @item --quick-generate-key @var{user-id} [@var{algo} [@var{usage} [@var{expire}]]] @itemx --quick-gen-key @opindex quick-generate-key @opindex quick-gen-key This is a simple command to generate a standard key with one user id. In contrast to @option{--generate-key} the key is generated directly without the need to answer a bunch of prompts. Unless the option @option{--yes} is given, the key creation will be canceled if the given user id already exists in the keyring. If invoked directly on the console without any special options an answer to a ``Continue?'' style confirmation prompt is required. In case the user id already exists in the keyring a second prompt to force the creation of the key will show up. If @var{algo} or @var{usage} are given, only the primary key is created and no prompts are shown. To specify an expiration date but still create a primary and subkey use ``default'' or ``future-default'' for @var{algo} and ``default'' for @var{usage}. For a description of these optional arguments see the command @code{--quick-add-key}. The @var{usage} accepts also the value ``cert'' which can be used to create a certification only primary key; the default is to a create certification and signing key. The @var{expire} argument can be used to specify an expiration date for the key. Several formats are supported; commonly the ISO formats ``YYYY-MM-DD'' or ``YYYYMMDDThhmmss'' are used. To make the key expire in N seconds, N days, N weeks, N months, or N years use ``seconds=N'', ``Nd'', ``Nw'', ``Nm'', or ``Ny'' respectively. Not specifying a value, or using ``-'' results in a key expiring in a reasonable default interval. The values ``never'', ``none'' can be used for no expiration date. If this command is used with @option{--batch}, @option{--pinentry-mode} has been set to @code{loopback}, and one of the passphrase options (@option{--passphrase}, @option{--passphrase-fd}, or @option{--passphrase-file}) is used, the supplied passphrase is used for the new key and the agent does not ask for it. To create a key without any protection @code{--passphrase ''} may be used. To create an OpenPGP key from the keys available on the currently inserted smartcard, the special string ``card'' can be used for @var{algo}. If the card features an encryption and a signing key, gpg will figure them out and creates an OpenPGP key consisting of the usual primary key and one subkey. This works only with certain smartcards. Note that the interactive @option{--full-gen-key} command allows to do the same but with greater flexibility in the selection of the smartcard keys. Note that it is possible to create a primary key and a subkey using non-default algorithms by using ``default'' and changing the default parameters using the option @option{--default-new-key-algo}. @item --quick-set-expire @var{fpr} @var{expire} [*|@var{subfprs}] @opindex quick-set-expire With two arguments given, directly set the expiration time of the primary key identified by @var{fpr} to @var{expire}. To remove the expiration time @code{0} can be used. With three arguments and the third given as an asterisk, the expiration time of all non-revoked and not yet expired subkeys are set to @var{expire}. With more than two arguments and a list of fingerprints given for @var{subfprs}, all non-revoked subkeys matching these fingerprints are set to @var{expire}. @item --quick-add-key @var{fpr} [@var{algo} [@var{usage} [@var{expire}]]] @opindex quick-add-key Directly add a subkey to the key identified by the fingerprint @var{fpr}. Without the optional arguments an encryption subkey is added. If any of the arguments are given a more specific subkey is added. @var{algo} may be any of the supported algorithms or curve names given in the format as used by key listings. To use the default algorithm the string ``default'' or ``-'' can be used. Supported algorithms are ``rsa'', ``dsa'', ``elg'', ``ed25519'', ``cv25519'', and other ECC curves. For example the string ``rsa'' adds an RSA key with the default key length; a string ``rsa4096'' requests that the key length is 4096 bits. The string ``future-default'' is an alias for the algorithm which will likely be used as default algorithm in future versions of gpg. To list the supported ECC curves the command @code{gpg --with-colons --list-config curve} can be used. Depending on the given @var{algo} the subkey may either be an encryption subkey or a signing subkey. If an algorithm is capable of signing and encryption and such a subkey is desired, a @var{usage} string must be given. This string is either ``default'' or ``-'' to keep the default or a comma delimited list (or space delimited list) of keywords: ``sign'' for a signing subkey, ``auth'' for an authentication subkey, and ``encr'' for an encryption subkey (``encrypt'' can be used as alias for ``encr''). The valid combinations depend on the algorithm. The @var{expire} argument can be used to specify an expiration date for the key. Several formats are supported; commonly the ISO formats ``YYYY-MM-DD'' or ``YYYYMMDDThhmmss'' are used. To make the key expire in N seconds, N days, N weeks, N months, or N years use ``seconds=N'', ``Nd'', ``Nw'', ``Nm'', or ``Ny'' respectively. Not specifying a value, or using ``-'' results in a key expiring in a reasonable default interval. The values ``never'', ``none'' can be used for no expiration date. @item --generate-key @opindex generate-key @itemx --gen-key @opindex gen-key Generate a new key pair using the current default parameters. This is the standard command to create a new key. In addition to the key a revocation certificate is created and stored in the @file{openpgp-revocs.d} directory below the GnuPG home directory. @item --full-generate-key @opindex full-generate-key @itemx --full-gen-key @opindex full-gen-key Generate a new key pair with dialogs for all options. This is an extended version of @option{--generate-key}. There is also a feature which allows you to create keys in batch mode. See the manual section ``Unattended key generation'' on how to use this. @item --generate-revocation @var{name} @opindex generate-revocation @itemx --gen-revoke @var{name} @opindex gen-revoke Generate a revocation certificate for the complete key. To only revoke a subkey or a key signature, use the @option{--edit} command. This command merely creates the revocation certificate so that it can be used to revoke the key if that is ever needed. To actually revoke a key the created revocation certificate needs to be merged with the key to revoke. This is done by importing the revocation certificate using the @option{--import} command. Then the revoked key needs to be published, which is best done by sending the key to a keyserver (command @option{--send-key}) and by exporting (@option{--export}) it to a file which is then send to frequent communication partners. @item --generate-designated-revocation @var{name} @opindex generate-designated-revocation @itemx --desig-revoke @var{name} @opindex desig-revoke Generate a designated revocation certificate for a key. This allows a user (with the permission of the keyholder) to revoke someone else's key. @item --edit-key @opindex edit-key Present a menu which enables you to do most of the key management related tasks. It expects the specification of a key on the command line. @c ******** Begin Edit-key Options ********** @table @asis @item uid @var{n} @opindex keyedit:uid Toggle selection of user ID or photographic user ID with index @var{n}. Use @code{*} to select all and @code{0} to deselect all. @item key @var{n} @opindex keyedit:key Toggle selection of subkey with index @var{n} or key ID @var{n}. Use @code{*} to select all and @code{0} to deselect all. @item sign @opindex keyedit:sign Make a signature on key of user @code{name}. If the key is not yet signed by the default user (or the users given with @option{-u}), the program displays the information of the key again, together with its fingerprint and asks whether it should be signed. This question is repeated for all users specified with @option{-u}. @item lsign @opindex keyedit:lsign Same as "sign" but the signature is marked as non-exportable and will therefore never be used by others. This may be used to make keys valid only in the local environment. @item nrsign @opindex keyedit:nrsign Same as "sign" but the signature is marked as non-revocable and can therefore never be revoked. @item tsign @opindex keyedit:tsign Make a trust signature. This is a signature that combines the notions of certification (like a regular signature), and trust (like the "trust" command). It is generally only useful in distinct communities or groups. For more information please read the sections ``Trust Signature'' and ``Regular Expression'' in RFC-4880. @end table @c man:.RS Note that "l" (for local / non-exportable), "nr" (for non-revocable, and "t" (for trust) may be freely mixed and prefixed to "sign" to create a signature of any type desired. @c man:.RE If the option @option{--only-sign-text-ids} is specified, then any non-text based user ids (e.g., photo IDs) will not be selected for signing. @table @asis @item delsig @opindex keyedit:delsig Delete a signature. Note that it is not possible to retract a signature, once it has been send to the public (i.e. to a keyserver). In that case you better use @code{revsig}. @item revsig @opindex keyedit:revsig Revoke a signature. For every signature which has been generated by one of the secret keys, GnuPG asks whether a revocation certificate should be generated. @item check @opindex keyedit:check Check the signatures on all selected user IDs. With the extra option @code{selfsig} only self-signatures are shown. @item adduid @opindex keyedit:adduid Create an additional user ID. @item addphoto @opindex keyedit:addphoto Create a photographic user ID. This will prompt for a JPEG file that will be embedded into the user ID. Note that a very large JPEG will make for a very large key. Also note that some programs will display your JPEG unchanged (GnuPG), and some programs will scale it to fit in a dialog box (PGP). @item showphoto @opindex keyedit:showphoto Display the selected photographic user ID. @item deluid @opindex keyedit:deluid Delete a user ID or photographic user ID. Note that it is not possible to retract a user id, once it has been send to the public (i.e. to a keyserver). In that case you better use @code{revuid}. @item revuid @opindex keyedit:revuid Revoke a user ID or photographic user ID. @item primary @opindex keyedit:primary Flag the current user id as the primary one, removes the primary user id flag from all other user ids and sets the timestamp of all affected self-signatures one second ahead. Note that setting a photo user ID as primary makes it primary over other photo user IDs, and setting a regular user ID as primary makes it primary over other regular user IDs. @item keyserver @opindex keyedit:keyserver Set a preferred keyserver for the specified user ID(s). This allows other users to know where you prefer they get your key from. See @option{--keyserver-options honor-keyserver-url} for more on how this works. Setting a value of "none" removes an existing preferred keyserver. @item notation @opindex keyedit:notation Set a name=value notation for the specified user ID(s). See @option{--cert-notation} for more on how this works. Setting a value of "none" removes all notations, setting a notation prefixed with a minus sign (-) removes that notation, and setting a notation name (without the =value) prefixed with a minus sign removes all notations with that name. @item pref @opindex keyedit:pref List preferences from the selected user ID. This shows the actual preferences, without including any implied preferences. @item showpref @opindex keyedit:showpref More verbose preferences listing for the selected user ID. This shows the preferences in effect by including the implied preferences of 3DES (cipher), SHA-1 (digest), and Uncompressed (compression) if they are not already included in the preference list. In addition, the preferred keyserver and signature notations (if any) are shown. @item setpref @var{string} @opindex keyedit:setpref Set the list of user ID preferences to @var{string} for all (or just the selected) user IDs. Calling setpref with no arguments sets the preference list to the default (either built-in or set via @option{--default-preference-list}), and calling setpref with "none" as the argument sets an empty preference list. Use @command{@gpgname --version} to get a list of available algorithms. Note that while you can change the preferences on an attribute user ID (aka "photo ID"), GnuPG does not select keys via attribute user IDs so these preferences will not be used by GnuPG. When setting preferences, you should list the algorithms in the order which you'd like to see them used by someone else when encrypting a message to your key. If you don't include 3DES, it will be automatically added at the end. Note that there are many factors that go into choosing an algorithm (for example, your key may not be the only recipient), and so the remote OpenPGP application being used to send to you may or may not follow your exact chosen order for a given message. It will, however, only choose an algorithm that is present on the preference list of every recipient key. See also the INTEROPERABILITY WITH OTHER OPENPGP PROGRAMS section below. @item addkey @opindex keyedit:addkey Add a subkey to this key. @item addcardkey @opindex keyedit:addcardkey Generate a subkey on a card and add it to this key. @item keytocard @opindex keyedit:keytocard Transfer the selected secret subkey (or the primary key if no subkey has been selected) to a smartcard. The secret key in the keyring will be replaced by a stub if the key could be stored successfully on the card and you use the save command later. Only certain key types may be transferred to the card. A sub menu allows you to select on what card to store the key. Note that it is not possible to get that key back from the card - if the card gets broken your secret key will be lost unless you have a backup somewhere. @item bkuptocard @var{file} @opindex keyedit:bkuptocard Restore the given @var{file} to a card. This command may be used to restore a backup key (as generated during card initialization) to a new card. In almost all cases this will be the encryption key. You should use this command only with the corresponding public key and make sure that the file given as argument is indeed the backup to restore. You should then select 2 to restore as encryption key. You will first be asked to enter the passphrase of the backup key and then for the Admin PIN of the card. @item delkey @opindex keyedit:delkey Remove a subkey (secondary key). Note that it is not possible to retract a subkey, once it has been send to the public (i.e. to a keyserver). In that case you better use @code{revkey}. Also note that this only deletes the public part of a key. @item revkey @opindex keyedit:revkey Revoke a subkey. @item expire @opindex keyedit:expire Change the key or subkey expiration time. If a subkey is selected, the expiration time of this subkey will be changed. With no selection, the key expiration of the primary key is changed. @item trust @opindex keyedit:trust Change the owner trust value for the key. This updates the trust-db immediately and no save is required. @item disable @itemx enable @opindex keyedit:disable @opindex keyedit:enable Disable or enable an entire key. A disabled key can not normally be used for encryption. @item addrevoker @opindex keyedit:addrevoker Add a designated revoker to the key. This takes one optional argument: "sensitive". If a designated revoker is marked as sensitive, it will not be exported by default (see export-options). @item passwd @opindex keyedit:passwd Change the passphrase of the secret key. @item toggle @opindex keyedit:toggle This is dummy command which exists only for backward compatibility. @item clean @opindex keyedit:clean Compact (by removing all signatures except the selfsig) any user ID that is no longer usable (e.g. revoked, or expired). Then, remove any signatures that are not usable by the trust calculations. Specifically, this removes any signature that does not validate, any signature that is superseded by a later signature, revoked signatures, and signatures issued by keys that are not present on the keyring. @item minimize @opindex keyedit:minimize Make the key as small as possible. This removes all signatures from each user ID except for the most recent self-signature. @item change-usage @opindex keyedit:change-usage Change the usage flags (capabilities) of the primary key or of subkeys. These usage flags (e.g. Certify, Sign, Authenticate, Encrypt) are set during key creation. Sometimes it is useful to have the opportunity to change them (for example to add Authenticate) after they have been created. Please take care when doing this; the allowed usage flags depend on the key algorithm. @item cross-certify @opindex keyedit:cross-certify Add cross-certification signatures to signing subkeys that may not currently have them. Cross-certification signatures protect against a subtle attack against signing subkeys. See @option{--require-cross-certification}. All new keys generated have this signature by default, so this command is only useful to bring older keys up to date. @item save @opindex keyedit:save Save all changes to the keyrings and quit. @item quit @opindex keyedit:quit Quit the program without updating the keyrings. @end table @c man:.RS The listing shows you the key with its secondary keys and all user IDs. The primary user ID is indicated by a dot, and selected keys or user IDs are indicated by an asterisk. The trust value is displayed with the primary key: "trust" is the assigned owner trust and "validity" is the calculated validity of the key. Validity values are also displayed for all user IDs. For possible values of trust, @pxref{trust-values}. @c man:.RE @c ******** End Edit-key Options ********** @item --sign-key @var{name} @opindex sign-key Signs a public key with your secret key. This is a shortcut version of the subcommand "sign" from @option{--edit}. @item --lsign-key @var{name} @opindex lsign-key Signs a public key with your secret key but marks it as non-exportable. This is a shortcut version of the subcommand "lsign" from @option{--edit-key}. @item --quick-sign-key @var{fpr} [@var{names}] @itemx --quick-lsign-key @var{fpr} [@var{names}] @opindex quick-sign-key @opindex quick-lsign-key Directly sign a key from the passphrase without any further user interaction. The @var{fpr} must be the verified primary fingerprint of a key in the local keyring. If no @var{names} are given, all useful user ids are signed; with given [@var{names}] only useful user ids matching one of theses names are signed. By default, or if a name is prefixed with a '*', a case insensitive substring match is used. If a name is prefixed with a '=' a case sensitive exact match is done. The command @option{--quick-lsign-key} marks the signatures as non-exportable. If such a non-exportable signature already exists the @option{--quick-sign-key} turns it into a exportable signature. If you need to update an existing signature, for example to add or change notation data, you need to use the option @option{--force-sign-key}. This command uses reasonable defaults and thus does not provide the full flexibility of the "sign" subcommand from @option{--edit-key}. Its intended use is to help unattended key signing by utilizing a list of verified fingerprints. @item --quick-add-uid @var{user-id} @var{new-user-id} @opindex quick-add-uid This command adds a new user id to an existing key. In contrast to the interactive sub-command @code{adduid} of @option{--edit-key} the @var{new-user-id} is added verbatim with only leading and trailing white space removed, it is expected to be UTF-8 encoded, and no checks on its form are applied. @item --quick-revoke-uid @var{user-id} @var{user-id-to-revoke} @opindex quick-revoke-uid This command revokes a user ID on an existing key. It cannot be used to revoke the last user ID on key (some non-revoked user ID must remain), with revocation reason ``User ID is no longer valid''. If you want to specify a different revocation reason, or to supply supplementary revocation text, you should use the interactive sub-command @code{revuid} of @option{--edit-key}. @item --quick-revoke-sig @var{fpr} @var{signing-fpr} [@var{names}] @opindex quick-revoke-sig This command revokes the key signatures made by @var{signing-fpr} from the key specified by the fingerprint @var{fpr}. With @var{names} given only the signatures on user ids of the key matching any of the given names are affected (see @option{--quick-sign-key}). If a revocation already exists a notice is printed instead of creating a new revocation; no error is returned in this case. Note that key signature revocations may be superseded by a newer key signature and in turn again revoked. @item --quick-set-primary-uid @var{user-id} @var{primary-user-id} @opindex quick-set-primary-uid This command sets or updates the primary user ID flag on an existing key. @var{user-id} specifies the key and @var{primary-user-id} the user ID which shall be flagged as the primary user ID. The primary user ID flag is removed from all other user ids and the timestamp of all affected self-signatures is set one second ahead. @item --change-passphrase @var{user-id} @opindex change-passphrase @itemx --passwd @var{user-id} @opindex passwd Change the passphrase of the secret key belonging to the certificate specified as @var{user-id}. This is a shortcut for the sub-command @code{passwd} of the edit key menu. When using together with the option @option{--dry-run} this will not actually change the passphrase but check that the current passphrase is correct. @end table @c ******************************************* @c *************** **************** @c *************** OPTIONS **************** @c *************** **************** @c ******************************************* @mansect options @node GPG Options @section Option Summary @command{@gpgname} features a bunch of options to control the exact behaviour and to change the default configuration. @menu * GPG Configuration Options:: How to change the configuration. * GPG Key related Options:: Key related options. * GPG Input and Output:: Input and Output. * OpenPGP Options:: OpenPGP protocol specific options. * Compliance Options:: Compliance options. * GPG Esoteric Options:: Doing things one usually doesn't want to do. * Deprecated Options:: Deprecated options. @end menu Long options can be put in an options file (default "~/.gnupg/gpg.conf"). Short option names will not work - for example, "armor" is a valid option for the options file, while "a" is not. Do not write the 2 dashes, but simply the name of the option and any required arguments. Lines with a hash ('#') as the first non-white-space character are ignored. Commands may be put in this file too, but that is not generally useful as the command will execute automatically with every execution of gpg. Please remember that option parsing stops as soon as a non-option is encountered, you can explicitly stop parsing by using the special option @option{--}. @c ******************************************* @c ******** CONFIGURATION OPTIONS ********** @c ******************************************* @node GPG Configuration Options @subsection How to change the configuration These options are used to change the configuration and most of them are usually found in the option file. @table @gnupgtabopt @item --default-key @var{name} @opindex default-key Use @var{name} as the default key to sign with. If this option is not used, the default key is the first key found in the secret keyring. Note that @option{-u} or @option{--local-user} overrides this option. This option may be given multiple times. In this case, the last key for which a secret key is available is used. If there is no secret key available for any of the specified values, GnuPG will not emit an error message but continue as if this option wasn't given. @item --default-recipient @var{name} @opindex default-recipient Use @var{name} as default recipient if option @option{--recipient} is not used and don't ask if this is a valid one. @var{name} must be non-empty. @item --default-recipient-self @opindex default-recipient-self Use the default key as default recipient if option @option{--recipient} is not used and don't ask if this is a valid one. The default key is the first one from the secret keyring or the one set with @option{--default-key}. @item --no-default-recipient @opindex no-default-recipient Reset @option{--default-recipient} and @option{--default-recipient-self}. Should not be used in an option file. @item -v, --verbose @opindex verbose Give more information during processing. If used twice, the input data is listed in detail. @item --no-verbose @opindex no-verbose Reset verbose level to 0. Should not be used in an option file. @item -q, --quiet @opindex quiet Try to be as quiet as possible. Should not be used in an option file. @item --batch @itemx --no-batch @opindex batch @opindex no-batch Use batch mode. Never ask, do not allow interactive commands. @option{--no-batch} disables this option. Note that even with a filename given on the command line, gpg might still need to read from STDIN (in particular if gpg figures that the input is a detached signature and no data file has been specified). Thus if you do not want to feed data via STDIN, you should connect STDIN to @file{/dev/null}. It is highly recommended to use this option along with the options @option{--status-fd} and @option{--with-colons} for any unattended use of @command{gpg}. Should not be used in an option file. @item --no-tty @opindex no-tty Make sure that the TTY (terminal) is never used for any output. This option is needed in some cases because GnuPG sometimes prints warnings to the TTY even if @option{--batch} is used. @item --yes @opindex yes Assume "yes" on most questions. Should not be used in an option file. @item --no @opindex no Assume "no" on most questions. Should not be used in an option file. @item --list-options @var{parameters} @opindex list-options This is a space or comma delimited string that gives options used when listing keys and signatures (that is, @option{--list-keys}, @option{--check-signatures}, @option{--list-public-keys}, @option{--list-secret-keys}, and the @option{--edit-key} functions). Options can be prepended with a @option{no-} (after the two dashes) to give the opposite meaning. The options are: @table @asis @item show-photos @opindex list-options:show-photos Causes @option{--list-keys}, @option{--check-signatures}, @option{--list-public-keys}, and @option{--list-secret-keys} to display any photo IDs attached to the key. Defaults to no. See also @option{--photo-viewer}. Does not work with @option{--with-colons}: see @option{--attribute-fd} for the appropriate way to get photo data for scripts and other frontends. @item show-usage @opindex list-options:show-usage Show usage information for keys and subkeys in the standard key listing. This is a list of letters indicating the allowed usage for a key (@code{E}=encryption, @code{S}=signing, @code{C}=certification, @code{A}=authentication). Defaults to yes. @item show-policy-urls @opindex list-options:show-policy-urls Show policy URLs in the @option{--check-signatures} listings. Defaults to no. @item show-notations @itemx show-std-notations @itemx show-user-notations @opindex list-options:show-notations @opindex list-options:show-std-notations @opindex list-options:show-user-notations Show all, IETF standard, or user-defined signature notations in the @option{--check-signatures} listings. Defaults to no. @item show-keyserver-urls @opindex list-options:show-keyserver-urls Show any preferred keyserver URL in the @option{--check-signatures} listings. Defaults to no. @item show-uid-validity @opindex list-options:show-uid-validity Display the calculated validity of user IDs during key listings. Defaults to yes. @item show-unusable-uids @opindex list-options:show-unusable-uids Show revoked and expired user IDs in key listings. Defaults to no. @item show-unusable-subkeys @opindex list-options:show-unusable-subkeys Show revoked and expired subkeys in key listings. Defaults to no. @item show-keyring @opindex list-options:show-keyring Display the keyring name at the head of key listings to show which keyring a given key resides on. Defaults to no. @item show-sig-expire @opindex list-options:show-sig-expire Show signature expiration dates (if any) during @option{--check-signatures} listings. Defaults to no. @item show-sig-subpackets @opindex list-options:show-sig-subpackets Include signature subpackets in the key listing. This option can take an optional argument list of the subpackets to list. If no argument is passed, list all subpackets. Defaults to no. This option is only meaningful when using @option{--with-colons} along with @option{--check-signatures}. @item show-only-fpr-mbox @opindex list-options:show-only-fpr-mbox For each user-id which has a valid mail address print only the fingerprint followed by the mail address. @end table @item --verify-options @var{parameters} @opindex verify-options This is a space or comma delimited string that gives options used when verifying signatures. Options can be prepended with a `no-' to give the opposite meaning. The options are: @table @asis @item show-photos @opindex verify-options:show-photos Display any photo IDs present on the key that issued the signature. Defaults to no. See also @option{--photo-viewer}. @item show-policy-urls @opindex verify-options:show-policy-urls Show policy URLs in the signature being verified. Defaults to yes. @item show-notations @itemx show-std-notations @itemx show-user-notations @opindex verify-options:show-notations @opindex verify-options:show-std-notations @opindex verify-options:show-user-notations Show all, IETF standard, or user-defined signature notations in the signature being verified. Defaults to IETF standard. @item show-keyserver-urls @opindex verify-options:show-keyserver-urls Show any preferred keyserver URL in the signature being verified. Defaults to yes. @item show-uid-validity @opindex verify-options:show-uid-validity Display the calculated validity of the user IDs on the key that issued the signature. Defaults to yes. @item show-unusable-uids @opindex verify-options:show-unusable-uids Show revoked and expired user IDs during signature verification. Defaults to no. @item show-primary-uid-only @opindex verify-options:show-primary-uid-only Show only the primary user ID during signature verification. That is all the AKA lines as well as photo Ids are not shown with the signature verification status. @item pka-lookups @opindex verify-options:pka-lookups Enable PKA lookups to verify sender addresses. Note that PKA is based on DNS, and so enabling this option may disclose information on when and what signatures are verified or to whom data is encrypted. This is similar to the "web bug" described for the @option{--auto-key-retrieve} option. @item pka-trust-increase @opindex verify-options:pka-trust-increase Raise the trust in a signature to full if the signature passes PKA validation. This option is only meaningful if pka-lookups is set. @end table @item --enable-large-rsa @itemx --disable-large-rsa @opindex enable-large-rsa @opindex disable-large-rsa With --generate-key and --batch, enable the creation of RSA secret keys as large as 8192 bit. Note: 8192 bit is more than is generally recommended. These large keys don't significantly improve security, but they are more expensive to use, and their signatures and certifications are larger. This option is only available if the binary was build with large-secmem support. @item --enable-dsa2 @itemx --disable-dsa2 @opindex enable-dsa2 @opindex disable-dsa2 Enable hash truncation for all DSA keys even for old DSA Keys up to 1024 bit. This is also the default with @option{--openpgp}. Note that older versions of GnuPG also required this flag to allow the generation of DSA larger than 1024 bit. @item --photo-viewer @var{string} @opindex photo-viewer This is the command line that should be run to view a photo ID. "%i" will be expanded to a filename containing the photo. "%I" does the same, except the file will not be deleted once the viewer exits. Other flags are "%k" for the key ID, "%K" for the long key ID, "%f" for the key fingerprint, "%t" for the extension of the image type (e.g. "jpg"), "%T" for the MIME type of the image (e.g. "image/jpeg"), "%v" for the single-character calculated validity of the image being viewed (e.g. "f"), "%V" for the calculated validity as a string (e.g. "full"), "%U" for a base32 encoded hash of the user ID, and "%%" for an actual percent sign. If neither %i or %I are present, then the photo will be supplied to the viewer on standard input. On Unix the default viewer is @code{xloadimage -fork -quiet -title 'KeyID 0x%k' STDIN} with a fallback to @code{display -title 'KeyID 0x%k' %i} and finally to @code{xdg-open %i}. On Windows @code{!ShellExecute 400 %i} is used; here the command is a meta command to use that API call followed by a wait time in milliseconds which is used to give the viewer time to read the temporary image file before gpg deletes it again. Note that if your image viewer program is not secure, then executing it from gpg does not make it secure. @item --exec-path @var{string} @opindex exec-path @efindex PATH Sets a list of directories to search for photo viewers If not provided photo viewers use the @code{PATH} environment variable. @item --keyring @var{file} @opindex keyring Add @var{file} to the current list of keyrings. If @var{file} begins with a tilde and a slash, these are replaced by the $HOME directory. If the filename does not contain a slash, it is assumed to be in the GnuPG home directory ("~/.gnupg" if @option{--homedir} or $GNUPGHOME is not used). Note that this adds a keyring to the current list. If the intent is to use the specified keyring alone, use @option{--keyring} along with @option{--no-default-keyring}. If the option @option{--no-keyring} has been used no keyrings will be used at all. @item --secret-keyring @var{file} @opindex secret-keyring This is an obsolete option and ignored. All secret keys are stored in the @file{private-keys-v1.d} directory below the GnuPG home directory. @item --primary-keyring @var{file} @opindex primary-keyring Designate @var{file} as the primary public keyring. This means that newly imported keys (via @option{--import} or keyserver @option{--recv-from}) will go to this keyring. @item --trustdb-name @var{file} @opindex trustdb-name Use @var{file} instead of the default trustdb. If @var{file} begins with a tilde and a slash, these are replaced by the $HOME directory. If the filename does not contain a slash, it is assumed to be in the GnuPG home directory (@file{~/.gnupg} if @option{--homedir} or $GNUPGHOME is not used). @include opt-homedir.texi @item --display-charset @var{name} @opindex display-charset Set the name of the native character set. This is used to convert some informational strings like user IDs to the proper UTF-8 encoding. Note that this has nothing to do with the character set of data to be encrypted or signed; GnuPG does not recode user-supplied data. If this option is not used, the default character set is determined from the current locale. A verbosity level of 3 shows the chosen set. Valid values for @var{name} are: @table @asis @item iso-8859-1 @opindex display-charset:iso-8859-1 This is the Latin 1 set. @item iso-8859-2 @opindex display-charset:iso-8859-2 The Latin 2 set. @item iso-8859-15 @opindex display-charset:iso-8859-15 This is currently an alias for the Latin 1 set. @item koi8-r @opindex display-charset:koi8-r The usual Russian set (RFC-1489). @item utf-8 @opindex display-charset:utf-8 Bypass all translations and assume that the OS uses native UTF-8 encoding. @end table @item --utf8-strings @itemx --no-utf8-strings @opindex utf8-strings Assume that command line arguments are given as UTF-8 strings. The default (@option{--no-utf8-strings}) is to assume that arguments are encoded in the character set as specified by @option{--display-charset}. These options affect all following arguments. Both options may be used multiple times. This option should not be used in an option file. @anchor{gpg-option --options} @item --options @var{file} @opindex options Read options from @var{file} and do not try to read them from the default options file in the homedir (see @option{--homedir}). This option is ignored if used in an options file. @item --no-options @opindex no-options Shortcut for @option{--options /dev/null}. This option is detected before an attempt to open an option file. Using this option will also prevent the creation of a @file{~/.gnupg} homedir. @item -z @var{n} @itemx --compress-level @var{n} @itemx --bzip2-compress-level @var{n} @opindex compress-level @opindex bzip2-compress-level Set compression level to @var{n} for the ZIP and ZLIB compression algorithms. The default is to use the default compression level of zlib (normally 6). @option{--bzip2-compress-level} sets the compression level for the BZIP2 compression algorithm (defaulting to 6 as well). This is a different option from @option{--compress-level} since BZIP2 uses a significant amount of memory for each additional compression level. @option{-z} sets both. A value of 0 for @var{n} disables compression. @item --bzip2-decompress-lowmem @opindex bzip2-decompress-lowmem Use a different decompression method for BZIP2 compressed files. This alternate method uses a bit more than half the memory, but also runs at half the speed. This is useful under extreme low memory circumstances when the file was originally compressed at a high @option{--bzip2-compress-level}. @item --mangle-dos-filenames @itemx --no-mangle-dos-filenames @opindex mangle-dos-filenames @opindex no-mangle-dos-filenames Older version of Windows cannot handle filenames with more than one dot. @option{--mangle-dos-filenames} causes GnuPG to replace (rather than add to) the extension of an output filename to avoid this problem. This option is off by default and has no effect on non-Windows platforms. @item --ask-cert-level @itemx --no-ask-cert-level @opindex ask-cert-level When making a key signature, prompt for a certification level. If this option is not specified, the certification level used is set via @option{--default-cert-level}. See @option{--default-cert-level} for information on the specific levels and how they are used. @option{--no-ask-cert-level} disables this option. This option defaults to no. @item --default-cert-level @var{n} @opindex default-cert-level The default to use for the check level when signing a key. 0 means you make no particular claim as to how carefully you verified the key. 1 means you believe the key is owned by the person who claims to own it but you could not, or did not verify the key at all. This is useful for a "persona" verification, where you sign the key of a pseudonymous user. 2 means you did casual verification of the key. For example, this could mean that you verified the key fingerprint and checked the user ID on the key against a photo ID. 3 means you did extensive verification of the key. For example, this could mean that you verified the key fingerprint with the owner of the key in person, and that you checked, by means of a hard to forge document with a photo ID (such as a passport) that the name of the key owner matches the name in the user ID on the key, and finally that you verified (by exchange of email) that the email address on the key belongs to the key owner. Note that the examples given above for levels 2 and 3 are just that: examples. In the end, it is up to you to decide just what "casual" and "extensive" mean to you. This option defaults to 0 (no particular claim). @item --min-cert-level @opindex min-cert-level When building the trust database, treat any signatures with a certification level below this as invalid. Defaults to 2, which disregards level 1 signatures. Note that level 0 "no particular claim" signatures are always accepted. @item --trusted-key @var{long key ID or fingerprint} @opindex trusted-key Assume that the specified key (which must be given as a full 8 byte key ID or 20 byte fingerprint) is as trustworthy as one of your own secret keys. This option is useful if you don't want to keep your secret keys (or one of them) online but still want to be able to check the validity of a given recipient's or signator's key. @item --trust-model @{pgp|classic|tofu|tofu+pgp|direct|always|auto@} @opindex trust-model Set what trust model GnuPG should follow. The models are: @table @asis @item pgp @opindex trust-model:pgp This is the Web of Trust combined with trust signatures as used in PGP 5.x and later. This is the default trust model when creating a new trust database. @item classic @opindex trust-model:classic This is the standard Web of Trust as introduced by PGP 2. @item tofu @opindex trust-model:tofu @anchor{trust-model-tofu} TOFU stands for Trust On First Use. In this trust model, the first time a key is seen, it is memorized. If later another key with a user id with the same email address is seen, both keys are marked as suspect. In that case, the next time either is used, a warning is displayed describing the conflict, why it might have occurred (either the user generated a new key and failed to cross sign the old and new keys, the key is forgery, or a man-in-the-middle attack is being attempted), and the user is prompted to manually confirm the validity of the key in question. Because a potential attacker is able to control the email address and thereby circumvent the conflict detection algorithm by using an email address that is similar in appearance to a trusted email address, whenever a message is verified, statistics about the number of messages signed with the key are shown. In this way, a user can easily identify attacks using fake keys for regular correspondents. When compared with the Web of Trust, TOFU offers significantly weaker security guarantees. In particular, TOFU only helps ensure consistency (that is, that the binding between a key and email address doesn't change). A major advantage of TOFU is that it requires little maintenance to use correctly. To use the web of trust properly, you need to actively sign keys and mark users as trusted introducers. This is a time-consuming process and anecdotal evidence suggests that even security-conscious users rarely take the time to do this thoroughly and instead rely on an ad-hoc TOFU process. In the TOFU model, policies are associated with bindings between keys and email addresses (which are extracted from user ids and normalized). There are five policies, which can be set manually using the @option{--tofu-policy} option. The default policy can be set using the @option{--tofu-default-policy} option. The TOFU policies are: @code{auto}, @code{good}, @code{unknown}, @code{bad} and @code{ask}. The @code{auto} policy is used by default (unless overridden by @option{--tofu-default-policy}) and marks a binding as marginally trusted. The @code{good}, @code{unknown} and @code{bad} policies mark a binding as fully trusted, as having unknown trust or as having trust never, respectively. The @code{unknown} policy is useful for just using TOFU to detect conflicts, but to never assign positive trust to a binding. The final policy, @code{ask} prompts the user to indicate the binding's trust. If batch mode is enabled (or input is inappropriate in the context), then the user is not prompted and the @code{undefined} trust level is returned. @item tofu+pgp @opindex trust-model:tofu+pgp This trust model combines TOFU with the Web of Trust. This is done by computing the trust level for each model and then taking the maximum trust level where the trust levels are ordered as follows: @code{unknown < undefined < marginal < fully < ultimate < expired < never}. By setting @option{--tofu-default-policy=unknown}, this model can be used to implement the web of trust with TOFU's conflict detection algorithm, but without its assignment of positive trust values, which some security-conscious users don't like. @item direct @opindex trust-model:direct Key validity is set directly by the user and not calculated via the Web of Trust. This model is solely based on the key and does not distinguish user IDs. Note that when changing to another trust model the trust values assigned to a key are transformed into ownertrust values, which also indicate how you trust the owner of the key to sign other keys. @item always @opindex trust-model:always Skip key validation and assume that used keys are always fully valid. You generally won't use this unless you are using some external validation scheme. This option also suppresses the "[uncertain]" tag printed with signature checks when there is no evidence that the user ID is bound to the key. Note that this trust model still does not allow the use of expired, revoked, or disabled keys. @item auto @opindex trust-model:auto Select the trust model depending on whatever the internal trust database says. This is the default model if such a database already exists. Note that a tofu trust model is not considered here and must be enabled explicitly. @end table @item --auto-key-locate @var{mechanisms} @itemx --no-auto-key-locate @opindex auto-key-locate GnuPG can automatically locate and retrieve keys as needed using this option. This happens when encrypting to an email address (in the "user@@example.com" form), and there are no "user@@example.com" keys on the local keyring. This option takes any number of the mechanisms listed below, in the order they are to be tried. Instead of listing the mechanisms as comma delimited arguments, the option may also be given several times to add more mechanism. The option @option{--no-auto-key-locate} or the mechanism "clear" resets the list. The default is "local,wkd". @table @asis @item cert Locate a key using DNS CERT, as specified in RFC-4398. @item pka Locate a key using DNS PKA. @item dane Locate a key using DANE, as specified in draft-ietf-dane-openpgpkey-05.txt. @item wkd Locate a key using the Web Key Directory protocol. @item ldap Using DNS Service Discovery, check the domain in question for any LDAP keyservers to use. If this fails, attempt to locate the key using the PGP Universal method of checking @samp{ldap://keys.(thedomain)}. @item ntds - Locate the key using the Active Directory (Windows only). + Locate the key using the Active Directory (Windows only). This + method also allows to search by fingerprint using the command + @option{--locate-external-key}. @item keyserver - Locate a key using a keyserver. + Locate a key using a keyserver. This method also allows to search + by fingerprint using the command @option{--locate-external-key} if + any of the configured keyservers is an LDAP server. @item keyserver-URL In addition, a keyserver URL as used in the @command{dirmngr} configuration may be used here to query that particular keyserver. + This method also allows to search by fingerprint using the command + @option{--locate-external-key} if the URL specifies an LDAP server. @item local Locate the key using the local keyrings. This mechanism allows the user to select the order a local key lookup is done. Thus using @samp{--auto-key-locate local} is identical to @option{--no-auto-key-locate}. @item nodefault This flag disables the standard local key lookup, done before any of the mechanisms defined by the @option{--auto-key-locate} are tried. The position of this mechanism in the list does not matter. It is not required if @code{local} is also used. @item clear Clear all defined mechanisms. This is useful to override mechanisms given in a config file. Note that a @code{nodefault} in @var{mechanisms} will also be cleared unless it is given after the @code{clear}. @end table @item --auto-key-import @itemx --no-auto-key-import @opindex auto-key-import @opindex no-auto-key-import This is an offline mechanism to get a missing key for signature verification and for later encryption to this key. If this option is enabled and a signature includes an embedded key, that key is used to verify the signature and on verification success that key is imported. The default is @option{--no-auto-key-import}. On the sender (signing) site the option @option{--include-key-block} needs to be used to put the public part of the signing key as “Key Block subpacket” into the signature. @item --auto-key-retrieve @itemx --no-auto-key-retrieve @opindex auto-key-retrieve @opindex no-auto-key-retrieve These options enable or disable the automatic retrieving of keys from a keyserver when verifying signatures made by keys that are not on the local keyring. The default is @option{--no-auto-key-retrieve}. The order of methods tried to lookup the key is: 1. If the option @option{--auto-key-import} is set and the signatures includes an embedded key, that key is used to verify the signature and on verification success that key is imported. 2. If a preferred keyserver is specified in the signature and the option @option{honor-keyserver-url} is active (which is not the default), that keyserver is tried. Note that the creator of the signature uses the option @option{--sig-keyserver-url} to specify the preferred keyserver for data signatures. 3. If the signature has the Signer's UID set (e.g. using @option{--sender} while creating the signature) a Web Key Directory (WKD) lookup is done. This is the default configuration but can be disabled by removing WKD from the auto-key-locate list or by using the option @option{--disable-signer-uid}. 4. If the option @option{honor-pka-record} is active, the legacy PKA method is used. 5. If any keyserver is configured and the Issuer Fingerprint is part of the signature (since GnuPG 2.1.16), the configured keyservers are tried. Note that this option makes a "web bug" like behavior possible. Keyserver or Web Key Directory operators can see which keys you request, so by sending you a message signed by a brand new key (which you naturally will not have on your local keyring), the operator can tell both your IP address and the time when you verified the signature. @item --keyid-format @{none|short|0xshort|long|0xlong@} @opindex keyid-format Select how to display key IDs. "none" does not show the key ID at all but shows the fingerprint in a separate line. "short" is the traditional 8-character key ID. "long" is the more accurate (but less convenient) 16-character key ID. Add an "0x" to either to include an "0x" at the beginning of the key ID, as in 0x99242560. Note that this option is ignored if the option @option{--with-colons} is used. @item --keyserver @var{name} @opindex keyserver This option is deprecated - please use the @option{--keyserver} in @file{dirmngr.conf} instead. Use @var{name} as your keyserver. This is the server that @option{--receive-keys}, @option{--send-keys}, and @option{--search-keys} will communicate with to receive keys from, send keys to, and search for keys on. The format of the @var{name} is a URI: `scheme:[//]keyservername[:port]' The scheme is the type of keyserver: "hkp"/"hkps" for the HTTP (or compatible) keyservers or "ldap"/"ldaps" for the LDAP keyservers. Note that your particular installation of GnuPG may have other keyserver types available as well. Keyserver schemes are case-insensitive. After the keyserver name, optional keyserver configuration options may be provided. These are the same as the global @option{--keyserver-options} from below, but apply only to this particular keyserver. Most keyservers synchronize with each other, so there is generally no need to send keys to more than one server. The keyserver @code{hkp://keys.gnupg.net} uses round robin DNS to give a different keyserver each time you use it. @item --keyserver-options @{@var{name}=@var{value}@} @opindex keyserver-options This is a space or comma delimited string that gives options for the keyserver. Options can be prefixed with a `no-' to give the opposite meaning. Valid import-options or export-options may be used here as well to apply to importing (@option{--recv-key}) or exporting (@option{--send-key}) a key from a keyserver. While not all options are available for all keyserver types, some common options are: @table @asis @item include-revoked When searching for a key with @option{--search-keys}, include keys that are marked on the keyserver as revoked. Note that not all keyservers differentiate between revoked and unrevoked keys, and for such keyservers this option is meaningless. Note also that most keyservers do not have cryptographic verification of key revocations, and so turning this option off may result in skipping keys that are incorrectly marked as revoked. @item include-disabled When searching for a key with @option{--search-keys}, include keys that are marked on the keyserver as disabled. Note that this option is not used with HKP keyservers. @item auto-key-retrieve This is an obsolete alias for the option @option{auto-key-retrieve}. Please do not use it; it will be removed in future versions.. @item honor-keyserver-url When using @option{--refresh-keys}, if the key in question has a preferred keyserver URL, then use that preferred keyserver to refresh the key from. In addition, if auto-key-retrieve is set, and the signature being verified has a preferred keyserver URL, then use that preferred keyserver to fetch the key from. Note that this option introduces a "web bug": The creator of the key can see when the keys is refreshed. Thus this option is not enabled by default. @item honor-pka-record If @option{--auto-key-retrieve} is used, and the signature being verified has a PKA record, then use the PKA information to fetch the key. Defaults to "yes". @item include-subkeys When receiving a key, include subkeys as potential targets. Note that this option is not used with HKP keyservers, as they do not support retrieving keys by subkey id. @item timeout @itemx http-proxy=@var{value} @itemx verbose @itemx debug @itemx check-cert @item ca-cert-file These options have no more function since GnuPG 2.1. Use the @code{dirmngr} configuration options instead. @end table The default list of options is: "self-sigs-only, import-clean, repair-keys, repair-pks-subkey-bug, export-attributes, honor-pka-record". However, if the actual used source is an LDAP server "no-self-sigs-only" is assumed unless "self-sigs-only" has been explictly configured. @item --completes-needed @var{n} @opindex compliant-needed Number of completely trusted users to introduce a new key signer (defaults to 1). @item --marginals-needed @var{n} @opindex marginals-needed Number of marginally trusted users to introduce a new key signer (defaults to 3) @item --tofu-default-policy @{auto|good|unknown|bad|ask@} @opindex tofu-default-policy The default TOFU policy (defaults to @code{auto}). For more information about the meaning of this option, @pxref{trust-model-tofu}. @item --max-cert-depth @var{n} @opindex max-cert-depth Maximum depth of a certification chain (default is 5). @item --no-sig-cache @opindex no-sig-cache Do not cache the verification status of key signatures. Caching gives a much better performance in key listings. However, if you suspect that your public keyring is not safe against write modifications, you can use this option to disable the caching. It probably does not make sense to disable it because all kind of damage can be done if someone else has write access to your public keyring. @item --auto-check-trustdb @itemx --no-auto-check-trustdb @opindex auto-check-trustdb If GnuPG feels that its information about the Web of Trust has to be updated, it automatically runs the @option{--check-trustdb} command internally. This may be a time consuming process. @option{--no-auto-check-trustdb} disables this option. @item --use-agent @itemx --no-use-agent @opindex use-agent This is dummy option. @command{@gpgname} always requires the agent. @item --gpg-agent-info @opindex gpg-agent-info This is dummy option. It has no effect when used with @command{@gpgname}. @item --agent-program @var{file} @opindex agent-program Specify an agent program to be used for secret key operations. The default value is determined by running @command{gpgconf} with the option @option{--list-dirs}. Note that the pipe symbol (@code{|}) is used for a regression test suite hack and may thus not be used in the file name. @item --dirmngr-program @var{file} @opindex dirmngr-program Specify a dirmngr program to be used for keyserver access. The default value is @file{@value{BINDIR}/dirmngr}. @item --disable-dirmngr Entirely disable the use of the Dirmngr. @item --no-autostart @opindex no-autostart Do not start the gpg-agent or the dirmngr if it has not yet been started and its service is required. This option is mostly useful on machines where the connection to gpg-agent has been redirected to another machines. If dirmngr is required on the remote machine, it may be started manually using @command{gpgconf --launch dirmngr}. @item --lock-once @opindex lock-once Lock the databases the first time a lock is requested and do not release the lock until the process terminates. @item --lock-multiple @opindex lock-multiple Release the locks every time a lock is no longer needed. Use this to override a previous @option{--lock-once} from a config file. @item --lock-never @opindex lock-never Disable locking entirely. This option should be used only in very special environments, where it can be assured that only one process is accessing those files. A bootable floppy with a stand-alone encryption system will probably use this. Improper usage of this option may lead to data and key corruption. @item --exit-on-status-write-error @opindex exit-on-status-write-error This option will cause write errors on the status FD to immediately terminate the process. That should in fact be the default but it never worked this way and thus we need an option to enable this, so that the change won't break applications which close their end of a status fd connected pipe too early. Using this option along with @option{--enable-progress-filter} may be used to cleanly cancel long running gpg operations. @item --limit-card-insert-tries @var{n} @opindex limit-card-insert-tries With @var{n} greater than 0 the number of prompts asking to insert a smartcard gets limited to N-1. Thus with a value of 1 gpg won't at all ask to insert a card if none has been inserted at startup. This option is useful in the configuration file in case an application does not know about the smartcard support and waits ad infinitum for an inserted card. @item --no-random-seed-file @opindex no-random-seed-file GnuPG uses a file to store its internal random pool over invocations. This makes random generation faster; however sometimes write operations are not desired. This option can be used to achieve that with the cost of slower random generation. @item --no-greeting @opindex no-greeting Suppress the initial copyright message. @item --no-secmem-warning @opindex no-secmem-warning Suppress the warning about "using insecure memory". @item --no-permission-warning @opindex permission-warning Suppress the warning about unsafe file and home directory (@option{--homedir}) permissions. Note that the permission checks that GnuPG performs are not intended to be authoritative, but rather they simply warn about certain common permission problems. Do not assume that the lack of a warning means that your system is secure. Note that the warning for unsafe @option{--homedir} permissions cannot be suppressed in the gpg.conf file, as this would allow an attacker to place an unsafe gpg.conf file in place, and use this file to suppress warnings about itself. The @option{--homedir} permissions warning may only be suppressed on the command line. @item --require-secmem @itemx --no-require-secmem @opindex require-secmem Refuse to run if GnuPG cannot get secure memory. Defaults to no (i.e. run, but give a warning). @item --require-cross-certification @itemx --no-require-cross-certification @opindex require-cross-certification When verifying a signature made from a subkey, ensure that the cross certification "back signature" on the subkey is present and valid. This protects against a subtle attack against subkeys that can sign. Defaults to @option{--require-cross-certification} for @command{@gpgname}. @item --expert @itemx --no-expert @opindex expert Allow the user to do certain nonsensical or "silly" things like signing an expired or revoked key, or certain potentially incompatible things like generating unusual key types. This also disables certain warning messages about potentially incompatible actions. As the name implies, this option is for experts only. If you don't fully understand the implications of what it allows you to do, leave this off. @option{--no-expert} disables this option. @end table @c ******************************************* @c ******** KEY RELATED OPTIONS ************ @c ******************************************* @node GPG Key related Options @subsection Key related options @table @gnupgtabopt @item --recipient @var{name} @itemx -r @opindex recipient Encrypt for user id @var{name}. If this option or @option{--hidden-recipient} is not specified, GnuPG asks for the user-id unless @option{--default-recipient} is given. @item --hidden-recipient @var{name} @itemx -R @opindex hidden-recipient Encrypt for user ID @var{name}, but hide the key ID of this user's key. This option helps to hide the receiver of the message and is a limited countermeasure against traffic analysis. If this option or @option{--recipient} is not specified, GnuPG asks for the user ID unless @option{--default-recipient} is given. @item --recipient-file @var{file} @itemx -f @opindex recipient-file This option is similar to @option{--recipient} except that it encrypts to a key stored in the given file. @var{file} must be the name of a file containing exactly one key. @command{@gpgname} assumes that the key in this file is fully valid. @item --hidden-recipient-file @var{file} @itemx -F @opindex hidden-recipient-file This option is similar to @option{--hidden-recipient} except that it encrypts to a key stored in the given file. @var{file} must be the name of a file containing exactly one key. @command{@gpgname} assumes that the key in this file is fully valid. @item --encrypt-to @var{name} @opindex encrypt-to Same as @option{--recipient} but this one is intended for use in the options file and may be used with your own user-id as an "encrypt-to-self". These keys are only used when there are other recipients given either by use of @option{--recipient} or by the asked user id. No trust checking is performed for these user ids and even disabled keys can be used. @item --hidden-encrypt-to @var{name} @opindex hidden-encrypt-to Same as @option{--hidden-recipient} but this one is intended for use in the options file and may be used with your own user-id as a hidden "encrypt-to-self". These keys are only used when there are other recipients given either by use of @option{--recipient} or by the asked user id. No trust checking is performed for these user ids and even disabled keys can be used. @item --no-encrypt-to @opindex no-encrypt-to Disable the use of all @option{--encrypt-to} and @option{--hidden-encrypt-to} keys. @item --group @{@var{name}=@var{value}@} @opindex group Sets up a named group, which is similar to aliases in email programs. Any time the group name is a recipient (@option{-r} or @option{--recipient}), it will be expanded to the values specified. Multiple groups with the same name are automatically merged into a single group. The values are @code{key IDs} or fingerprints, but any key description is accepted. Note that a value with spaces in it will be treated as two different values. Note also there is only one level of expansion --- you cannot make an group that points to another group. When used from the command line, it may be necessary to quote the argument to this option to prevent the shell from treating it as multiple arguments. @item --ungroup @var{name} @opindex ungroup Remove a given entry from the @option{--group} list. @item --no-groups @opindex no-groups Remove all entries from the @option{--group} list. @item --local-user @var{name} @itemx -u @opindex local-user Use @var{name} as the key to sign with. Note that this option overrides @option{--default-key}. @item --sender @var{mbox} @opindex sender This option has two purposes. @var{mbox} must either be a complete user id with a proper mail address or just a mail address. When creating a signature this option tells gpg the user id of a key used to make a signature if the key was not directly specified by a user id. When verifying a signature the @var{mbox} is used to restrict the information printed by the TOFU code to matching user ids. @item --try-secret-key @var{name} @opindex try-secret-key For hidden recipients GPG needs to know the keys to use for trial decryption. The key set with @option{--default-key} is always tried first, but this is often not sufficient. This option allows setting more keys to be used for trial decryption. Although any valid user-id specification may be used for @var{name} it makes sense to use at least the long keyid to avoid ambiguities. Note that gpg-agent might pop up a pinentry for a lot keys to do the trial decryption. If you want to stop all further trial decryption you may use close-window button instead of the cancel button. @item --try-all-secrets @opindex try-all-secrets Don't look at the key ID as stored in the message but try all secret keys in turn to find the right decryption key. This option forces the behaviour as used by anonymous recipients (created by using @option{--throw-keyids} or @option{--hidden-recipient}) and might come handy in case where an encrypted message contains a bogus key ID. @item --skip-hidden-recipients @itemx --no-skip-hidden-recipients @opindex skip-hidden-recipients @opindex no-skip-hidden-recipients During decryption skip all anonymous recipients. This option helps in the case that people use the hidden recipients feature to hide their own encrypt-to key from others. If one has many secret keys this may lead to a major annoyance because all keys are tried in turn to decrypt something which was not really intended for it. The drawback of this option is that it is currently not possible to decrypt a message which includes real anonymous recipients. @end table @c ******************************************* @c ******** INPUT AND OUTPUT *************** @c ******************************************* @node GPG Input and Output @subsection Input and Output @table @gnupgtabopt @item --armor @itemx -a @opindex armor Create ASCII armored output. The default is to create the binary OpenPGP format. @item --no-armor @opindex no-armor Assume the input data is not in ASCII armored format. @item --output @var{file} @itemx -o @var{file} @opindex output Write output to @var{file}. To write to stdout use @code{-} as the filename. @item --max-output @var{n} @opindex max-output This option sets a limit on the number of bytes that will be generated when processing a file. Since OpenPGP supports various levels of compression, it is possible that the plaintext of a given message may be significantly larger than the original OpenPGP message. While GnuPG works properly with such messages, there is often a desire to set a maximum file size that will be generated before processing is forced to stop by the OS limits. Defaults to 0, which means "no limit". @item --input-size-hint @var{n} @opindex input-size-hint This option can be used to tell GPG the size of the input data in bytes. @var{n} must be a positive base-10 number. This option is only useful if the input is not taken from a file. GPG may use this hint to optimize its buffer allocation strategy. It is also used by the @option{--status-fd} line ``PROGRESS'' to provide a value for ``total'' if that is not available by other means. @item --key-origin @var{string}[,@var{url}] @opindex key-origin gpg can track the origin of a key. Certain origins are implicitly known (e.g. keyserver, web key directory) and set. For a standard import the origin of the keys imported can be set with this option. To list the possible values use "help" for @var{string}. Some origins can store an optional @var{url} argument. That URL can appended to @var{string} after a comma. @item --import-options @var{parameters} @opindex import-options This is a space or comma delimited string that gives options for importing keys. Options can be prepended with a `no-' to give the opposite meaning. The options are: @table @asis @item import-local-sigs Allow importing key signatures marked as "local". This is not generally useful unless a shared keyring scheme is being used. Defaults to no. @item keep-ownertrust Normally possible still existing ownertrust values of a key are cleared if a key is imported. This is in general desirable so that a formerly deleted key does not automatically gain an ownertrust values merely due to import. On the other hand it is sometimes necessary to re-import a trusted set of keys again but keeping already assigned ownertrust values. This can be achieved by using this option. @item repair-pks-subkey-bug During import, attempt to repair the damage caused by the PKS keyserver bug (pre version 0.9.6) that mangles keys with multiple subkeys. 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. Defaults to no for regular @option{--import} and to yes for keyserver @option{--receive-keys}. @item import-show @itemx show-only Show a listing of the key as imported right before it is stored. This can be combined with the option @option{--dry-run} to only look at keys; the option @option{show-only} is a shortcut for this combination. The command @option{--show-keys} is another shortcut for this. Note that suffixes like '#' for "sec" and "sbb" lines may or may not be printed. @item import-export Run the entire import code but instead of storing the key to the local keyring write it to the output. The export options @option{export-pka} and @option{export-dane} affect the output. This option can be used to remove all invalid parts from a key without the need to store it. @item merge-only During import, allow key updates to existing keys, but do not allow any new keys to be imported. Defaults to no. @item import-clean After import, compact (remove all signatures except the self-signature) any user IDs from the new key that are not usable. Then, remove any signatures from the new key that are not usable. This includes signatures that were issued by keys that are not present on the keyring. This option is the same as running the @option{--edit-key} command "clean" after import. Defaults to no. @item self-sigs-only Accept only self-signatures while importing a key. All other key signatures are skipped at an early import stage. This option can be used with @code{keyserver-options} to mitigate attempts to flood a key with bogus signatures from a keyserver. The drawback is that all other valid key signatures, as required by the Web of Trust are also not imported. Note that when using this option along with import-clean it suppresses the final clean step after merging the imported key into the existing key. @item repair-keys After import, fix various problems with the keys. For example, this reorders signatures, and strips duplicate signatures. Defaults to yes. @item import-minimal Import the smallest key possible. This removes all signatures except the most recent self-signature on each user ID. This option is the same as running the @option{--edit-key} command "minimize" after import. Defaults to no. @item restore @itemx import-restore Import in key restore mode. This imports all data which is usually skipped during import; including all GnuPG specific data. All other contradicting options are overridden. @end table @item --import-filter @{@var{name}=@var{expr}@} @itemx --export-filter @{@var{name}=@var{expr}@} @opindex import-filter @opindex export-filter These options define an import/export filter which are applied to the imported/exported keyblock right before it will be stored/written. @var{name} defines the type of filter to use, @var{expr} the expression to evaluate. The option can be used several times which then appends more expression to the same @var{name}. @noindent The available filter types are: @table @asis @item keep-uid This filter will keep a user id packet and its dependent packets in the keyblock if the expression evaluates to true. @item drop-subkey This filter drops the selected subkeys. Currently only implemented for --export-filter. @item drop-sig This filter drops the selected key signatures on user ids. Self-signatures are not considered. Currently only implemented for --import-filter. @end table For the syntax of the expression see the chapter "FILTER EXPRESSIONS". The property names for the expressions depend on the actual filter type and are indicated in the following table. The available properties are: @table @asis @item uid A string with the user id. (keep-uid) @item mbox The addr-spec part of a user id with mailbox or the empty string. (keep-uid) @item key_algo A number with the public key algorithm of a key or subkey packet. (drop-subkey) @item key_created @itemx key_created_d The first is the timestamp a public key or subkey packet was created. The second is the same but given as an ISO string, e.g. "2016-08-17". (drop-subkey) @item fpr The hexified fingerprint of the current subkey or primary key. (drop-subkey) @item primary Boolean indicating whether the user id is the primary one. (keep-uid) @item expired Boolean indicating whether a user id (keep-uid), a key (drop-subkey), or a signature (drop-sig) expired. @item revoked Boolean indicating whether a user id (keep-uid) or a key (drop-subkey) has been revoked. @item disabled Boolean indicating whether a primary key is disabled. (not used) @item secret Boolean indicating whether a key or subkey is a secret one. (drop-subkey) @item usage A string indicating the usage flags for the subkey, from the sequence ``ecsa?''. For example, a subkey capable of just signing and authentication would be an exact match for ``sa''. (drop-subkey) @item sig_created @itemx sig_created_d The first is the timestamp a signature packet was created. The second is the same but given as an ISO date string, e.g. "2016-08-17". (drop-sig) @item sig_algo A number with the public key algorithm of a signature packet. (drop-sig) @item sig_digest_algo A number with the digest algorithm of a signature packet. (drop-sig) @end table @item --export-options @var{parameters} @opindex export-options This is a space or comma delimited string that gives options for exporting keys. Options can be prepended with a `no-' to give the opposite meaning. The options are: @table @asis @item export-local-sigs Allow exporting key signatures marked as "local". This is not generally useful unless a shared keyring scheme is being used. Defaults to no. @item export-attributes Include attribute user IDs (photo IDs) while exporting. Not including attribute user IDs is useful to export keys that are going to be used by an OpenPGP program that does not accept attribute user IDs. Defaults to yes. @item export-sensitive-revkeys Include designated revoker information that was marked as "sensitive". Defaults to no. @c Since GnuPG 2.1 gpg-agent manages the secret key and thus the @c export-reset-subkey-passwd hack is not anymore justified. Such use @c cases may be implemented using a specialized secret key export @c tool. @c @item export-reset-subkey-passwd @c When using the @option{--export-secret-subkeys} command, this option resets @c the passphrases for all exported subkeys to empty. This is useful @c when the exported subkey is to be used on an unattended machine where @c a passphrase doesn't necessarily make sense. Defaults to no. @item backup @itemx export-backup Export for use as a backup. The exported data includes all data which is needed to restore the key or keys later with GnuPG. The format is basically the OpenPGP format but enhanced with GnuPG specific data. All other contradicting options are overridden. @item export-clean Compact (remove all signatures from) user IDs on the key being exported if the user IDs are not usable. Also, do not export any signatures that are not usable. This includes signatures that were issued by keys that are not present on the keyring. This option is the same as running the @option{--edit-key} command "clean" before export except that the local copy of the key is not modified. Defaults to no. @item export-minimal Export the smallest key possible. This removes all signatures except the most recent self-signature on each user ID. This option is the same as running the @option{--edit-key} command "minimize" before export except that the local copy of the key is not modified. Defaults to no. @item export-pka Instead of outputting the key material output PKA records suitable to put into DNS zone files. An ORIGIN line is printed before each record to allow diverting the records to the corresponding zone file. @item export-dane Instead of outputting the key material output OpenPGP DANE records suitable to put into DNS zone files. An ORIGIN line is printed before each record to allow diverting the records to the corresponding zone file. @end table @item --with-colons @opindex with-colons Print key listings delimited by colons. Note that the output will be encoded in UTF-8 regardless of any @option{--display-charset} setting. This format is useful when GnuPG is called from scripts and other programs as it is easily machine parsed. The details of this format are documented in the file @file{doc/DETAILS}, which is included in the GnuPG source distribution. @item --fixed-list-mode @opindex fixed-list-mode Do not merge primary user ID and primary key in @option{--with-colon} listing mode and print all timestamps as seconds since 1970-01-01. Since GnuPG 2.0.10, this mode is always used and thus this option is obsolete; it does not harm to use it though. @item --legacy-list-mode @opindex legacy-list-mode Revert to the pre-2.1 public key list mode. This only affects the human readable output and not the machine interface (i.e. @code{--with-colons}). Note that the legacy format does not convey suitable information for elliptic curves. @item --with-fingerprint @opindex with-fingerprint Same as the command @option{--fingerprint} but changes only the format of the output and may be used together with another command. @item --with-subkey-fingerprint @opindex with-subkey-fingerprint If a fingerprint is printed for the primary key, this option forces printing of the fingerprint for all subkeys. This could also be achieved by using the @option{--with-fingerprint} twice but by using this option along with keyid-format "none" a compact fingerprint is printed. @item --with-icao-spelling @opindex with-icao-spelling Print the ICAO spelling of the fingerprint in addition to the hex digits. @item --with-keygrip @opindex with-keygrip Include the keygrip in the key listings. In @code{--with-colons} mode this is implicitly enable for secret keys. @item --with-key-origin @opindex with-key-origin Include the locally held information on the origin and last update of a key in a key listing. In @code{--with-colons} mode this is always printed. This data is currently experimental and shall not be considered part of the stable API. @item --with-wkd-hash @opindex with-wkd-hash Print a Web Key Directory identifier along with each user ID in key listings. This is an experimental feature and semantics may change. @item --with-secret @opindex with-secret Include info about the presence of a secret key in public key listings done with @code{--with-colons}. @end table @c ******************************************* @c ******** OPENPGP OPTIONS **************** @c ******************************************* @node OpenPGP Options @subsection OpenPGP protocol specific options @table @gnupgtabopt @item -t, --textmode @itemx --no-textmode @opindex textmode Treat input files as text and store them in the OpenPGP canonical text form with standard "CRLF" line endings. This also sets the necessary flags to inform the recipient that the encrypted or signed data is text and may need its line endings converted back to whatever the local system uses. This option is useful when communicating between two platforms that have different line ending conventions (UNIX-like to Mac, Mac to Windows, etc). @option{--no-textmode} disables this option, and is the default. @item --force-v3-sigs @itemx --no-force-v3-sigs @item --force-v4-certs @itemx --no-force-v4-certs These options are obsolete and have no effect since GnuPG 2.1. @item --force-mdc @itemx --disable-mdc @opindex force-mdc @opindex disable-mdc These options are obsolete and have no effect since GnuPG 2.2.8. The MDC is always used. But note: If the creation of a legacy non-MDC message is exceptionally required, the option @option{--rfc2440} allows for this. @item --disable-signer-uid @opindex disable-signer-uid By default the user ID of the signing key is embedded in the data signature. As of now this is only done if the signing key has been specified with @option{local-user} using a mail address, or with @option{sender}. This information can be helpful for verifier to locate the key; see option @option{--auto-key-retrieve}. @item --include-key-block @opindex include-key-block This option is used to embed the actual signing key into a data signature. The embedded key is stripped down to a single user id and includes only the signing subkey used to create the signature as well as as valid encryption subkeys. All other info is removed from the key to keep it and thus the signature small. This option is the OpenPGP counterpart to the @command{gpgsm} option @option{--include-certs}. @item --personal-cipher-preferences @var{string} @opindex personal-cipher-preferences Set the list of personal cipher preferences to @var{string}. Use @command{@gpgname --version} to get a list of available algorithms, and use @code{none} to set no preference at all. This allows the user to safely override the algorithm chosen by the recipient key preferences, as GPG will only select an algorithm that is usable by all recipients. The most highly ranked cipher in this list is also used for the @option{--symmetric} encryption command. @item --personal-digest-preferences @var{string} @opindex personal-digest-preferences Set the list of personal digest preferences to @var{string}. Use @command{@gpgname --version} to get a list of available algorithms, and use @code{none} to set no preference at all. This allows the user to safely override the algorithm chosen by the recipient key preferences, as GPG will only select an algorithm that is usable by all recipients. The most highly ranked digest algorithm in this list is also used when signing without encryption (e.g. @option{--clear-sign} or @option{--sign}). @item --personal-compress-preferences @var{string} @opindex personal-compress-preferences Set the list of personal compression preferences to @var{string}. Use @command{@gpgname --version} to get a list of available algorithms, and use @code{none} to set no preference at all. This allows the user to safely override the algorithm chosen by the recipient key preferences, as GPG will only select an algorithm that is usable by all recipients. The most highly ranked compression algorithm in this list is also used when there are no recipient keys to consider (e.g. @option{--symmetric}). @item --s2k-cipher-algo @var{name} @opindex s2k-cipher-algo Use @var{name} as the cipher algorithm for symmetric encryption with a passphrase if @option{--personal-cipher-preferences} and @option{--cipher-algo} are not given. The default is @value{GPGSYMENCALGO}. @item --s2k-digest-algo @var{name} @opindex s2k-digest-algo Use @var{name} as the digest algorithm used to mangle the passphrases for symmetric encryption. The default is SHA-1. @item --s2k-mode @var{n} @opindex s2k-mode Selects how passphrases for symmetric encryption are mangled. If @var{n} is 0 a plain passphrase (which is in general not recommended) will be used, a 1 adds a salt (which should not be used) to the passphrase and a 3 (the default) iterates the whole process a number of times (see @option{--s2k-count}). @item --s2k-count @var{n} @opindex s2k-count Specify how many times the passphrases mangling for symmetric encryption is repeated. This value may range between 1024 and 65011712 inclusive. The default is inquired from gpg-agent. Note that not all values in the 1024-65011712 range are legal and if an illegal value is selected, GnuPG will round up to the nearest legal value. This option is only meaningful if @option{--s2k-mode} is set to the default of 3. @end table @c *************************** @c ******* Compliance ******** @c *************************** @node Compliance Options @subsection Compliance options These options control what GnuPG is compliant to. Only one of these options may be active at a time. Note that the default setting of this is nearly always the correct one. See the INTEROPERABILITY WITH OTHER OPENPGP PROGRAMS section below before using one of these options. @table @gnupgtabopt @item --gnupg @opindex gnupg Use standard GnuPG behavior. This is essentially OpenPGP behavior (see @option{--openpgp}), but with some additional workarounds for common compatibility problems in different versions of PGP. This is the default option, so it is not generally needed, but it may be useful to override a different compliance option in the gpg.conf file. @item --openpgp @opindex openpgp Reset all packet, cipher and digest options to strict OpenPGP behavior. Use this option to reset all previous options like @option{--s2k-*}, @option{--cipher-algo}, @option{--digest-algo} and @option{--compress-algo} to OpenPGP compliant values. All PGP workarounds are disabled. @item --rfc4880 @opindex rfc4880 Reset all packet, cipher and digest options to strict RFC-4880 behavior. Note that this is currently the same thing as @option{--openpgp}. @item --rfc4880bis @opindex rfc4880bis Enable experimental features from proposed updates to RFC-4880. This option can be used in addition to the other compliance options. Warning: The behavior may change with any GnuPG release and created keys or data may not be usable with future GnuPG versions. @item --rfc2440 @opindex rfc2440 Reset all packet, cipher and digest options to strict RFC-2440 behavior. Note that by using this option encryption packets are created in a legacy mode without MDC protection. This is dangerous and should thus only be used for experiments. See also option @option{--ignore-mdc-error}. @item --pgp6 @opindex pgp6 Set up all options to be as PGP 6 compliant as possible. This restricts you to the ciphers IDEA (if the IDEA plugin is installed), 3DES, and CAST5, the hashes MD5, SHA1 and RIPEMD160, and the compression algorithms none and ZIP. This also disables @option{--throw-keyids}, and making signatures with signing subkeys as PGP 6 does not understand signatures made by signing subkeys. This option implies @option{--escape-from-lines}. @item --pgp7 @opindex pgp7 Set up all options to be as PGP 7 compliant as possible. This is identical to @option{--pgp6} except that MDCs are not disabled, and the list of allowable ciphers is expanded to add AES128, AES192, AES256, and TWOFISH. @item --pgp8 @opindex pgp8 Set up all options to be as PGP 8 compliant as possible. PGP 8 is a lot closer to the OpenPGP standard than previous versions of PGP, so all this does is disable @option{--throw-keyids} and set @option{--escape-from-lines}. All algorithms are allowed except for the SHA224, SHA384, and SHA512 digests. @item --compliance @var{string} @opindex compliance This option can be used instead of one of the options above. Valid values for @var{string} are the above option names (without the double dash) and possibly others as shown when using "help" for @var{value}. @end table @c ******************************************* @c ******** ESOTERIC OPTIONS *************** @c ******************************************* @node GPG Esoteric Options @subsection Doing things one usually doesn't want to do @table @gnupgtabopt @item -n @itemx --dry-run @opindex dry-run Don't make any changes (this is not completely implemented). @item --list-only @opindex list-only Changes the behaviour of some commands. This is like @option{--dry-run} but different in some cases. The semantic of this option may be extended in the future. Currently it only skips the actual decryption pass and therefore enables a fast listing of the encryption keys. @item -i @itemx --interactive @opindex interactive Prompt before overwriting any files. @item --debug-level @var{level} @opindex debug-level Select the debug level for investigating problems. @var{level} may be a numeric value or by a keyword: @table @code @item none No debugging at all. A value of less than 1 may be used instead of the keyword. @item basic Some basic debug messages. A value between 1 and 2 may be used instead of the keyword. @item advanced More verbose debug messages. A value between 3 and 5 may be used instead of the keyword. @item expert Even more detailed messages. A value between 6 and 8 may be used instead of the keyword. @item guru All of the debug messages you can get. A value greater than 8 may be used instead of the keyword. The creation of hash tracing files is only enabled if the keyword is used. @end table How these messages are mapped to the actual debugging flags is not specified and may change with newer releases of this program. They are however carefully selected to best aid in debugging. @item --debug @var{flags} @opindex debug Set debugging flags. All flags are or-ed and @var{flags} may be given in C syntax (e.g. 0x0042) or as a comma separated list of flag names. To get a list of all supported flags the single word "help" can be used. @item --debug-all @opindex debug-all Set all useful debugging flags. @item --debug-iolbf @opindex debug-iolbf Set stdout into line buffered mode. This option is only honored when given on the command line. @item --faked-system-time @var{epoch} @opindex faked-system-time This option is only useful for testing; it sets the system time back or forth to @var{epoch} which is the number of seconds elapsed since the year 1970. Alternatively @var{epoch} may be given as a full ISO time string (e.g. "20070924T154812"). If you suffix @var{epoch} with an exclamation mark (!), the system time will appear to be frozen at the specified time. @item --enable-progress-filter @opindex enable-progress-filter Enable certain PROGRESS status outputs. This option allows frontends to display a progress indicator while gpg is processing larger files. There is a slight performance overhead using it. @item --status-fd @var{n} @opindex status-fd Write special status strings to the file descriptor @var{n}. See the file DETAILS in the documentation for a listing of them. @item --status-file @var{file} @opindex status-file Same as @option{--status-fd}, except the status data is written to file @var{file}. @item --logger-fd @var{n} @opindex logger-fd Write log output to file descriptor @var{n} and not to STDERR. @item --log-file @var{file} @itemx --logger-file @var{file} @opindex log-file Same as @option{--logger-fd}, except the logger data is written to file @var{file}. Use @file{socket://} to log to a socket. Note that in this version of gpg the option has only an effect if @option{--batch} is also used. @item --attribute-fd @var{n} @opindex attribute-fd Write attribute subpackets to the file descriptor @var{n}. This is most useful for use with @option{--status-fd}, since the status messages are needed to separate out the various subpackets from the stream delivered to the file descriptor. @item --attribute-file @var{file} @opindex attribute-file Same as @option{--attribute-fd}, except the attribute data is written to file @var{file}. @item --comment @var{string} @itemx --no-comments @opindex comment Use @var{string} as a comment string in cleartext signatures and ASCII armored messages or keys (see @option{--armor}). The default behavior is not to use a comment string. @option{--comment} may be repeated multiple times to get multiple comment strings. @option{--no-comments} removes all comments. It is a good idea to keep the length of a single comment below 60 characters to avoid problems with mail programs wrapping such lines. Note that comment lines, like all other header lines, are not protected by the signature. @item --emit-version @itemx --no-emit-version @opindex emit-version Force inclusion of the version string in ASCII armored output. If given once only the name of the program and the major number is emitted, given twice the minor is also emitted, given thrice the micro is added, and given four times an operating system identification is also emitted. @option{--no-emit-version} (default) disables the version line. @item --sig-notation @{@var{name}=@var{value}@} @itemx --cert-notation @{@var{name}=@var{value}@} @itemx -N, --set-notation @{@var{name}=@var{value}@} @opindex sig-notation @opindex cert-notation @opindex set-notation Put the name value pair into the signature as notation data. @var{name} must consist only of printable characters or spaces, and must contain a '@@' character in the form keyname@@domain.example.com (substituting the appropriate keyname and domain name, of course). This is to help prevent pollution of the IETF reserved notation namespace. The @option{--expert} flag overrides the '@@' check. @var{value} may be any printable string; it will be encoded in UTF-8, so you should check that your @option{--display-charset} is set correctly. If you prefix @var{name} with an exclamation mark (!), the notation data will be flagged as critical (rfc4880:5.2.3.16). @option{--sig-notation} sets a notation for data signatures. @option{--cert-notation} sets a notation for key signatures (certifications). @option{--set-notation} sets both. There are special codes that may be used in notation names. "%k" will be expanded into the key ID of the key being signed, "%K" into the long key ID of the key being signed, "%f" into the fingerprint of the key being signed, "%s" into the key ID of the key making the signature, "%S" into the long key ID of the key making the signature, "%g" into the fingerprint of the key making the signature (which might be a subkey), "%p" into the fingerprint of the primary key of the key making the signature, "%c" into the signature count from the OpenPGP smartcard, and "%%" results in a single "%". %k, %K, and %f are only meaningful when making a key signature (certification), and %c is only meaningful when using the OpenPGP smartcard. @item --known-notation @var{name} @opindex known-notation Adds @var{name} to a list of known critical signature notations. The effect of this is that gpg will not mark a signature with a critical signature notation of that name as bad. Note that gpg already knows by default about a few critical signatures notation names. @item --sig-policy-url @var{string} @itemx --cert-policy-url @var{string} @itemx --set-policy-url @var{string} @opindex sig-policy-url @opindex cert-policy-url @opindex set-policy-url Use @var{string} as a Policy URL for signatures (rfc4880:5.2.3.20). If you prefix it with an exclamation mark (!), the policy URL packet will be flagged as critical. @option{--sig-policy-url} sets a policy url for data signatures. @option{--cert-policy-url} sets a policy url for key signatures (certifications). @option{--set-policy-url} sets both. The same %-expandos used for notation data are available here as well. @item --sig-keyserver-url @var{string} @opindex sig-keyserver-url Use @var{string} as a preferred keyserver URL for data signatures. If you prefix it with an exclamation mark (!), the keyserver URL packet will be flagged as critical. The same %-expandos used for notation data are available here as well. @item --set-filename @var{string} @opindex set-filename Use @var{string} as the filename which is stored inside messages. This overrides the default, which is to use the actual filename of the file being encrypted. Using the empty string for @var{string} effectively removes the filename from the output. @item --for-your-eyes-only @itemx --no-for-your-eyes-only @opindex for-your-eyes-only Set the `for your eyes only' flag in the message. This causes GnuPG to refuse to save the file unless the @option{--output} option is given, and PGP to use a "secure viewer" with a claimed Tempest-resistant font to display the message. This option overrides @option{--set-filename}. @option{--no-for-your-eyes-only} disables this option. @item --use-embedded-filename @itemx --no-use-embedded-filename @opindex use-embedded-filename Try to create a file with a name as embedded in the data. This can be a dangerous option as it enables overwriting files. Defaults to no. Note that the option @option{--output} overrides this option. @item --cipher-algo @var{name} @opindex cipher-algo Use @var{name} as cipher algorithm. Running the program with the command @option{--version} yields a list of supported algorithms. If this is not used the cipher algorithm is selected from the preferences stored with the key. In general, you do not want to use this option as it allows you to violate the OpenPGP standard. @option{--personal-cipher-preferences} is the safe way to accomplish the same thing. @item --digest-algo @var{name} @opindex digest-algo Use @var{name} as the message digest algorithm. Running the program with the command @option{--version} yields a list of supported algorithms. In general, you do not want to use this option as it allows you to violate the OpenPGP standard. @option{--personal-digest-preferences} is the safe way to accomplish the same thing. @item --compress-algo @var{name} @opindex compress-algo Use compression algorithm @var{name}. "zlib" is RFC-1950 ZLIB compression. "zip" is RFC-1951 ZIP compression which is used by PGP. "bzip2" is a more modern compression scheme that can compress some things better than zip or zlib, but at the cost of more memory used during compression and decompression. "uncompressed" or "none" disables compression. If this option is not used, the default behavior is to examine the recipient key preferences to see which algorithms the recipient supports. If all else fails, ZIP is used for maximum compatibility. ZLIB may give better compression results than ZIP, as the compression window size is not limited to 8k. BZIP2 may give even better compression results than that, but will use a significantly larger amount of memory while compressing and decompressing. This may be significant in low memory situations. Note, however, that PGP (all versions) only supports ZIP compression. Using any algorithm other than ZIP or "none" will make the message unreadable with PGP. In general, you do not want to use this option as it allows you to violate the OpenPGP standard. @option{--personal-compress-preferences} is the safe way to accomplish the same thing. @item --cert-digest-algo @var{name} @opindex cert-digest-algo Use @var{name} as the message digest algorithm used when signing a key. Running the program with the command @option{--version} yields a list of supported algorithms. Be aware that if you choose an algorithm that GnuPG supports but other OpenPGP implementations do not, then some users will not be able to use the key signatures you make, or quite possibly your entire key. @item --disable-cipher-algo @var{name} @opindex disable-cipher-algo Never allow the use of @var{name} as cipher algorithm. The given name will not be checked so that a later loaded algorithm will still get disabled. @item --disable-pubkey-algo @var{name} @opindex disable-pubkey-algo Never allow the use of @var{name} as public key algorithm. The given name will not be checked so that a later loaded algorithm will still get disabled. @item --throw-keyids @itemx --no-throw-keyids @opindex throw-keyids Do not put the recipient key IDs into encrypted messages. This helps to hide the receivers of the message and is a limited countermeasure against traffic analysis.@footnote{Using a little social engineering anyone who is able to decrypt the message can check whether one of the other recipients is the one he suspects.} On the receiving side, it may slow down the decryption process because all available secret keys must be tried. @option{--no-throw-keyids} disables this option. This option is essentially the same as using @option{--hidden-recipient} for all recipients. @item --not-dash-escaped @opindex not-dash-escaped This option changes the behavior of cleartext signatures so that they can be used for patch files. You should not send such an armored file via email because all spaces and line endings are hashed too. You can not use this option for data which has 5 dashes at the beginning of a line, patch files don't have this. A special armor header line tells GnuPG about this cleartext signature option. @item --escape-from-lines @itemx --no-escape-from-lines @opindex escape-from-lines Because some mailers change lines starting with "From " to ">From " it is good to handle such lines in a special way when creating cleartext signatures to prevent the mail system from breaking the signature. Note that all other PGP versions do it this way too. Enabled by default. @option{--no-escape-from-lines} disables this option. @item --passphrase-repeat @var{n} @opindex passphrase-repeat Specify how many times @command{@gpgname} will request a new passphrase be repeated. This is useful for helping memorize a passphrase. Defaults to 1 repetition; can be set to 0 to disable any passphrase repetition. Note that a @var{n} greater than 1 will pop up the pinentry window @var{n}+1 times even if a modern pinentry with two entry fields is used. @item --passphrase-fd @var{n} @opindex passphrase-fd Read the passphrase from file descriptor @var{n}. Only the first line will be read from file descriptor @var{n}. If you use 0 for @var{n}, the passphrase will be read from STDIN. This can only be used if only one passphrase is supplied. Note that since Version 2.0 this passphrase is only used if the option @option{--batch} has also been given. Since Version 2.1 the @option{--pinentry-mode} also needs to be set to @code{loopback}. @item --passphrase-file @var{file} @opindex passphrase-file Read the passphrase from file @var{file}. Only the first line will be read from file @var{file}. This can only be used if only one passphrase is supplied. Obviously, a passphrase stored in a file is of questionable security if other users can read this file. Don't use this option if you can avoid it. Note that since Version 2.0 this passphrase is only used if the option @option{--batch} has also been given. Since Version 2.1 the @option{--pinentry-mode} also needs to be set to @code{loopback}. @item --passphrase @var{string} @opindex passphrase Use @var{string} as the passphrase. This can only be used if only one passphrase is supplied. Obviously, this is of very questionable security on a multi-user system. Don't use this option if you can avoid it. Note that since Version 2.0 this passphrase is only used if the option @option{--batch} has also been given. Since Version 2.1 the @option{--pinentry-mode} also needs to be set to @code{loopback}. @item --pinentry-mode @var{mode} @opindex pinentry-mode Set the pinentry mode to @var{mode}. Allowed values for @var{mode} are: @table @asis @item default Use the default of the agent, which is @code{ask}. @item ask Force the use of the Pinentry. @item cancel Emulate use of Pinentry's cancel button. @item error Return a Pinentry error (``No Pinentry''). @item loopback Redirect Pinentry queries to the caller. Note that in contrast to Pinentry the user is not prompted again if he enters a bad password. @end table @item --no-symkey-cache @opindex no-symkey-cache Disable the passphrase cache used for symmetrical en- and decryption. This cache is based on the message specific salt value (cf. @option{--s2k-mode}). @item --request-origin @var{origin} @opindex request-origin Tell gpg to assume that the operation ultimately originated at @var{origin}. Depending on the origin certain restrictions are applied and the Pinentry may include an extra note on the origin. Supported values for @var{origin} are: @code{local} which is the default, @code{remote} to indicate a remote origin or @code{browser} for an operation requested by a web browser. @item --command-fd @var{n} @opindex command-fd This is a replacement for the deprecated shared-memory IPC mode. If this option is enabled, user input on questions is not expected from the TTY but from the given file descriptor. It should be used together with @option{--status-fd}. See the file doc/DETAILS in the source distribution for details on how to use it. @item --command-file @var{file} @opindex command-file Same as @option{--command-fd}, except the commands are read out of file @var{file} @item --allow-non-selfsigned-uid @itemx --no-allow-non-selfsigned-uid @opindex allow-non-selfsigned-uid Allow the import and use of keys with user IDs which are not self-signed. This is not recommended, as a non self-signed user ID is trivial to forge. @option{--no-allow-non-selfsigned-uid} disables. @item --allow-freeform-uid @opindex allow-freeform-uid Disable all checks on the form of the user ID while generating a new one. This option should only be used in very special environments as it does not ensure the de-facto standard format of user IDs. @item --ignore-time-conflict @opindex ignore-time-conflict GnuPG normally checks that the timestamps associated with keys and signatures have plausible values. However, sometimes a signature seems to be older than the key due to clock problems. This option makes these checks just a warning. See also @option{--ignore-valid-from} for timestamp issues on subkeys. @item --ignore-valid-from @opindex ignore-valid-from GnuPG normally does not select and use subkeys created in the future. This option allows the use of such keys and thus exhibits the pre-1.0.7 behaviour. You should not use this option unless there is some clock problem. See also @option{--ignore-time-conflict} for timestamp issues with signatures. @item --ignore-crc-error @opindex ignore-crc-error The ASCII armor used by OpenPGP is protected by a CRC checksum against transmission errors. Occasionally the CRC gets mangled somewhere on the transmission channel but the actual content (which is protected by the OpenPGP protocol anyway) is still okay. This option allows GnuPG to ignore CRC errors. @item --ignore-mdc-error @opindex ignore-mdc-error This option changes a MDC integrity protection failure into a warning. It is required to decrypt old messages which did not use an MDC. It may also be useful if a message is partially garbled, but it is necessary to get as much data as possible out of that garbled message. Be aware that a missing or failed MDC can be an indication of an attack. Use with great caution; see also option @option{--rfc2440}. @item --allow-weak-digest-algos @opindex allow-weak-digest-algos Signatures made with known-weak digest algorithms are normally rejected with an ``invalid digest algorithm'' message. This option allows the verification of signatures made with such weak algorithms. MD5 is the only digest algorithm considered weak by default. See also @option{--weak-digest} to reject other digest algorithms. @item --weak-digest @var{name} @opindex weak-digest Treat the specified digest algorithm as weak. Signatures made over weak digests algorithms are normally rejected. This option can be supplied multiple times if multiple algorithms should be considered weak. See also @option{--allow-weak-digest-algos} to disable rejection of weak digests. MD5 is always considered weak, and does not need to be listed explicitly. @item --allow-weak-key-signatures @opindex allow-weak-key-signatures To avoid a minor risk of collision attacks on third-party key signatures made using SHA-1, those key signatures are considered invalid. This options allows to override this restriction. @item --no-default-keyring @opindex no-default-keyring Do not add the default keyrings to the list of keyrings. Note that GnuPG will not operate without any keyrings, so if you use this option and do not provide alternate keyrings via @option{--keyring} or @option{--secret-keyring}, then GnuPG will still use the default public or secret keyrings. @item --no-keyring @opindex no-keyring Do not use any keyring at all. This overrides the default and all options which specify keyrings. @item --skip-verify @opindex skip-verify Skip the signature verification step. This may be used to make the decryption faster if the signature verification is not needed. @item --with-key-data @opindex with-key-data Print key listings delimited by colons (like @option{--with-colons}) and print the public key data. @item --list-signatures @opindex list-signatures @itemx --list-sigs @opindex list-sigs Same as @option{--list-keys}, but the signatures are listed too. This command has the same effect as using @option{--list-keys} with @option{--with-sig-list}. Note that in contrast to @option{--check-signatures} the key signatures are not verified. This command can be used to create a list of signing keys missing in the local keyring; for example: @example gpg --list-sigs --with-colons USERID | \ awk -F: '$1=="sig" && $2=="?" @{if($13)@{print $13@}else@{print $5@}@}' @end example @item --fast-list-mode @opindex fast-list-mode Changes the output of the list commands to work faster; this is achieved by leaving some parts empty. Some applications don't need the user ID and the trust information given in the listings. By using this options they can get a faster listing. The exact behaviour of this option may change in future versions. If you are missing some information, don't use this option. @item --no-literal @opindex no-literal This is not for normal use. Use the source to see for what it might be useful. @item --set-filesize @opindex set-filesize This is not for normal use. Use the source to see for what it might be useful. @item --show-session-key @opindex show-session-key Display the session key used for one message. See @option{--override-session-key} for the counterpart of this option. We think that Key Escrow is a Bad Thing; however the user should have the freedom to decide whether to go to prison or to reveal the content of one specific message without compromising all messages ever encrypted for one secret key. You can also use this option if you receive an encrypted message which is abusive or offensive, to prove to the administrators of the messaging system that the ciphertext transmitted corresponds to an inappropriate plaintext so they can take action against the offending user. @item --override-session-key @var{string} @itemx --override-session-key-fd @var{fd} @opindex override-session-key Don't use the public key but the session key @var{string} respective the session key taken from the first line read from file descriptor @var{fd}. The format of this string is the same as the one printed by @option{--show-session-key}. This option is normally not used but comes handy in case someone forces you to reveal the content of an encrypted message; using this option you can do this without handing out the secret key. Note that using @option{--override-session-key} may reveal the session key to all local users via the global process table. Often it is useful to combine this option with @option{--no-keyring}. @item --ask-sig-expire @itemx --no-ask-sig-expire @opindex ask-sig-expire When making a data signature, prompt for an expiration time. If this option is not specified, the expiration time set via @option{--default-sig-expire} is used. @option{--no-ask-sig-expire} disables this option. @item --default-sig-expire @opindex default-sig-expire The default expiration time to use for signature expiration. Valid values are "0" for no expiration, a number followed by the letter d (for days), w (for weeks), m (for months), or y (for years) (for example "2m" for two months, or "5y" for five years), or an absolute date in the form YYYY-MM-DD. Defaults to "0". @item --ask-cert-expire @itemx --no-ask-cert-expire @opindex ask-cert-expire When making a key signature, prompt for an expiration time. If this option is not specified, the expiration time set via @option{--default-cert-expire} is used. @option{--no-ask-cert-expire} disables this option. @item --default-cert-expire @opindex default-cert-expire The default expiration time to use for key signature expiration. Valid values are "0" for no expiration, a number followed by the letter d (for days), w (for weeks), m (for months), or y (for years) (for example "2m" for two months, or "5y" for five years), or an absolute date in the form YYYY-MM-DD. Defaults to "0". @item --default-new-key-algo @var{string} @opindex default-new-key-algo @var{string} This option can be used to change the default algorithms for key generation. The @var{string} is similar to the arguments required for the command @option{--quick-add-key} but slightly different. For example the current default of @code{"rsa2048/cert,sign+rsa2048/encr"} (or @code{"rsa3072"}) can be changed to the value of what we currently call future default, which is @code{"ed25519/cert,sign+cv25519/encr"}. You need to consult the source code to learn the details. Note that the advanced key generation commands can always be used to specify a key algorithm directly. @item --force-sign-key @opindex force-sign-key This option modifies the behaviour of the commands @option{--quick-sign-key}, @option{--quick-lsign-key}, and the "sign" sub-commands of @option{--edit-key} by forcing the creation of a key signature, even if one already exists. @item --allow-secret-key-import @opindex allow-secret-key-import This is an obsolete option and is not used anywhere. @item --allow-multiple-messages @item --no-allow-multiple-messages @opindex allow-multiple-messages Allow processing of multiple OpenPGP messages contained in a single file or stream. Some programs that call GPG are not prepared to deal with multiple messages being processed together, so this option defaults to no. Note that versions of GPG prior to 1.4.7 always allowed multiple messages. Future versions of GnUPG will remove this option. Warning: Do not use this option unless you need it as a temporary workaround! @item --enable-special-filenames @opindex enable-special-filenames This option enables a mode in which filenames of the form @file{-&n}, where n is a non-negative decimal number, refer to the file descriptor n and not to a file with that name. @item --no-expensive-trust-checks @opindex no-expensive-trust-checks Experimental use only. @item --preserve-permissions @opindex preserve-permissions Don't change the permissions of a secret keyring back to user read/write only. Use this option only if you really know what you are doing. @item --default-preference-list @var{string} @opindex default-preference-list Set the list of default preferences to @var{string}. This preference list is used for new keys and becomes the default for "setpref" in the edit menu. @item --default-keyserver-url @var{name} @opindex default-keyserver-url Set the default keyserver URL to @var{name}. This keyserver will be used as the keyserver URL when writing a new self-signature on a key, which includes key generation and changing preferences. @item --list-config @opindex list-config Display various internal configuration parameters of GnuPG. This option is intended for external programs that call GnuPG to perform tasks, and is thus not generally useful. See the file @file{doc/DETAILS} in the source distribution for the details of which configuration items may be listed. @option{--list-config} is only usable with @option{--with-colons} set. @item --list-gcrypt-config @opindex list-gcrypt-config Display various internal configuration parameters of Libgcrypt. @item --gpgconf-list @opindex gpgconf-list This command is similar to @option{--list-config} but in general only internally used by the @command{gpgconf} tool. @item --gpgconf-test @opindex gpgconf-test This is more or less dummy action. However it parses the configuration file and returns with failure if the configuration file would prevent @command{@gpgname} from startup. Thus it may be used to run a syntax check on the configuration file. @end table @c ******************************* @c ******* Deprecated ************ @c ******************************* @node Deprecated Options @subsection Deprecated options @table @gnupgtabopt @item --show-photos @itemx --no-show-photos @opindex show-photos Causes @option{--list-keys}, @option{--list-signatures}, @option{--list-public-keys}, @option{--list-secret-keys}, and verifying a signature to also display the photo ID attached to the key, if any. See also @option{--photo-viewer}. These options are deprecated. Use @option{--list-options [no-]show-photos} and/or @option{--verify-options [no-]show-photos} instead. @item --show-keyring @opindex show-keyring Display the keyring name at the head of key listings to show which keyring a given key resides on. This option is deprecated: use @option{--list-options [no-]show-keyring} instead. @item --always-trust @opindex always-trust Identical to @option{--trust-model always}. This option is deprecated. @item --show-notation @itemx --no-show-notation @opindex show-notation Show signature notations in the @option{--list-signatures} or @option{--check-signatures} listings as well as when verifying a signature with a notation in it. These options are deprecated. Use @option{--list-options [no-]show-notation} and/or @option{--verify-options [no-]show-notation} instead. @item --show-policy-url @itemx --no-show-policy-url @opindex show-policy-url Show policy URLs in the @option{--list-signatures} or @option{--check-signatures} listings as well as when verifying a signature with a policy URL in it. These options are deprecated. Use @option{--list-options [no-]show-policy-url} and/or @option{--verify-options [no-]show-policy-url} instead. @end table @c ******************************************* @c *************** **************** @c *************** FILES **************** @c *************** **************** @c ******************************************* @mansect files @node GPG Configuration @section Configuration files There are a few configuration files to control certain aspects of @command{@gpgname}'s operation. Unless noted, they are expected in the current home directory (@pxref{option --homedir}). @table @file @item gpg.conf @efindex gpg.conf This is the standard configuration file read by @command{@gpgname} on startup. It may contain any valid long option; the leading two dashes may not be entered and the option may not be abbreviated. This default name may be changed on the command line (@pxref{gpg-option --options}). You should backup this file. @end table Note that on larger installations, it is useful to put predefined files into the directory @file{@value{SYSCONFSKELDIR}} so that newly created users start up with a working configuration. For existing users a small helper script is provided to create these files (@pxref{addgnupghome}). For internal purposes @command{@gpgname} creates and maintains a few other files; They all live in the current home directory (@pxref{option --homedir}). Only the @command{@gpgname} program may modify these files. @table @file @item ~/.gnupg @efindex ~/.gnupg This is the default home directory which is used if neither the environment variable @code{GNUPGHOME} nor the option @option{--homedir} is given. @item ~/.gnupg/pubring.gpg @efindex pubring.gpg The public keyring using a legacy format. You should backup this file. If this file is not available, @command{gpg} defaults to the new keybox format and creates a file @file{pubring.kbx} unless that file already exists in which case that file will also be used for OpenPGP keys. Note that in the case that both files, @file{pubring.gpg} and @file{pubring.kbx} exists but the latter has no OpenPGP keys, the legacy file @file{pubring.gpg} will be used. Take care: GnuPG versions before 2.1 will always use the file @file{pubring.gpg} because they do not know about the new keybox format. In the case that you have to use GnuPG 1.4 to decrypt archived data you should keep this file. @item ~/.gnupg/pubring.gpg.lock The lock file for the public keyring. @item ~/.gnupg/pubring.kbx @efindex pubring.kbx The public keyring using the new keybox format. This file is shared with @command{gpgsm}. You should backup this file. See above for the relation between this file and it predecessor. To convert an existing @file{pubring.gpg} file to the keybox format, you first backup the ownertrust values, then rename @file{pubring.gpg} to @file{publickeys.backup}, so it won’t be recognized by any GnuPG version, run import, and finally restore the ownertrust values: @example $ cd ~/.gnupg $ gpg --export-ownertrust >otrust.lst $ mv pubring.gpg publickeys.backup $ gpg --import-options restore --import publickeys.backups $ gpg --import-ownertrust otrust.lst @end example @item ~/.gnupg/pubring.kbx.lock The lock file for @file{pubring.kbx}. @item ~/.gnupg/secring.gpg @efindex secring.gpg The legacy secret keyring as used by GnuPG versions before 2.1. It is not used by GnuPG 2.1 and later. You may want to keep it in case you have to use GnuPG 1.4 to decrypt archived data. @item ~/.gnupg/secring.gpg.lock The lock file for the legacy secret keyring. @item ~/.gnupg/.gpg-v21-migrated @efindex .gpg-v21-migrated File indicating that a migration to GnuPG 2.1 has been done. @item ~/.gnupg/trustdb.gpg @efindex trustdb.gpg The trust database. There is no need to backup this file; it is better to backup the ownertrust values (@pxref{option --export-ownertrust}). @item ~/.gnupg/trustdb.gpg.lock The lock file for the trust database. @item ~/.gnupg/random_seed @efindex random_seed A file used to preserve the state of the internal random pool. @item ~/.gnupg/openpgp-revocs.d/ @efindex openpgp-revocs.d This is the directory where gpg stores pre-generated revocation certificates. The file name corresponds to the OpenPGP fingerprint of the respective key. It is suggested to backup those certificates and if the primary private key is not stored on the disk to move them to an external storage device. Anyone who can access theses files is able to revoke the corresponding key. You may want to print them out. You should backup all files in this directory and take care to keep this backup closed away. @end table Operation is further controlled by a few environment variables: @table @asis @item HOME @efindex HOME Used to locate the default home directory. @item GNUPGHOME @efindex GNUPGHOME If set directory used instead of "~/.gnupg". @item GPG_AGENT_INFO This variable is obsolete; it was used by GnuPG versions before 2.1. @item PINENTRY_USER_DATA @efindex PINENTRY_USER_DATA This value is passed via gpg-agent to pinentry. It is useful to convey extra information to a custom pinentry. @item COLUMNS @itemx LINES @efindex COLUMNS @efindex LINES Used to size some displays to the full size of the screen. @item LANGUAGE @efindex LANGUAGE Apart from its use by GNU, it is used in the W32 version to override the language selection done through the Registry. If used and set to a valid and available language name (@var{langid}), the file with the translation is loaded from @code{@var{gpgdir}/gnupg.nls/@var{langid}.mo}. Here @var{gpgdir} is the directory out of which the gpg binary has been loaded. If it can't be loaded the Registry is tried and as last resort the native Windows locale system is used. @end table When calling the gpg-agent component @command{@gpgname} sends a set of environment variables to gpg-agent. The names of these variables can be listed using the command: @example gpg-connect-agent 'getinfo std_env_names' /bye | awk '$1=="D" @{print $2@}' @end example @c ******************************************* @c *************** **************** @c *************** EXAMPLES **************** @c *************** **************** @c ******************************************* @mansect examples @node GPG Examples @section Examples @table @asis @item gpg -se -r @code{Bob} @code{file} sign and encrypt for user Bob @item gpg --clear-sign @code{file} make a cleartext signature @item gpg -sb @code{file} make a detached signature @item gpg -u 0x12345678 -sb @code{file} make a detached signature with the key 0x12345678 @item gpg --list-keys @code{user_ID} show keys @item gpg --fingerprint @code{user_ID} show fingerprint @item gpg --verify @code{pgpfile} @itemx gpg --verify @code{sigfile} [@code{datafile}] Verify the signature of the file but do not output the data unless requested. The second form is used for detached signatures, where @code{sigfile} is the detached signature (either ASCII armored or binary) and @code{datafile} are the signed data; if this is not given, the name of the file holding the signed data is constructed by cutting off the extension (".asc" or ".sig") of @code{sigfile} or by asking the user for the filename. If the option @option{--output} is also used the signed data is written to the file specified by that option; use @code{-} to write the signed data to stdout. @end table @c ******************************************* @c *************** **************** @c *************** USER ID **************** @c *************** **************** @c ******************************************* @mansect how to specify a user id @ifset isman @include specify-user-id.texi @end ifset @mansect filter expressions @chapheading FILTER EXPRESSIONS The options @option{--import-filter} and @option{--export-filter} use expressions with this syntax (square brackets indicate an optional part and curly braces a repetition, white space between the elements are allowed): @c man:.RS @example [lc] @{[@{flag@}] PROPNAME op VALUE [lc]@} @end example @c man:.RE The name of a property (@var{PROPNAME}) may only consist of letters, digits and underscores. The description for the filter type describes which properties are defined. If an undefined property is used it evaluates to the empty string. Unless otherwise noted, the @var{VALUE} must always be given and may not be the empty string. No quoting is defined for the value, thus the value may not contain the strings @code{&&} or @code{||}, which are used as logical connection operators. The flag @code{--} can be used to remove this restriction. Numerical values are computed as long int; standard C notation applies. @var{lc} is the logical connection operator; either @code{&&} for a conjunction or @code{||} for a disjunction. A conjunction is assumed at the begin of an expression. Conjunctions have higher precedence than disjunctions. If @var{VALUE} starts with one of the characters used in any @var{op} a space after the @var{op} is required. @noindent The supported operators (@var{op}) are: @table @asis @item =~ Substring must match. @item !~ Substring must not match. @item = The full string must match. @item <> The full string must not match. @item == The numerical value must match. @item != The numerical value must not match. @item <= The numerical value of the field must be LE than the value. @item < The numerical value of the field must be LT than the value. @item > The numerical value of the field must be GT than the value. @item >= The numerical value of the field must be GE than the value. @item -le The string value of the field must be less or equal than the value. @item -lt The string value of the field must be less than the value. @item -gt The string value of the field must be greater than the value. @item -ge The string value of the field must be greater or equal than the value. @item -n True if value is not empty (no value allowed). @item -z True if value is empty (no value allowed). @item -t Alias for "PROPNAME != 0" (no value allowed). @item -f Alias for "PROPNAME == 0" (no value allowed). @end table @noindent Values for @var{flag} must be space separated. The supported flags are: @table @asis @item -- @var{VALUE} spans to the end of the expression. @item -c The string match in this part is done case-sensitive. @end table The filter options concatenate several specifications for a filter of the same type. For example the four options in this example: @c man:.RS @example --import-filter keep-uid="uid =~ Alfa" --import-filter keep-uid="&& uid !~ Test" --import-filter keep-uid="|| uid =~ Alpha" --import-filter keep-uid="uid !~ Test" @end example @c man:.RE @noindent which is equivalent to @c man:.RS @example --import-filter \ keep-uid="uid =~ Alfa" && uid !~ Test" || uid =~ Alpha" && "uid !~ Test" @end example @c man:.RE imports only the user ids of a key containing the strings "Alfa" or "Alpha" but not the string "test". @mansect trust values @ifset isman @include trust-values.texi @end ifset @mansect return value @chapheading RETURN VALUE The program returns 0 if there are no severe errors, 1 if at least a signature was bad, and other error codes for fatal errors. Note that signature verification requires exact knowledge of what has been signed and by whom it has beensigned. Using only the return code is thus not an appropriate way to verify a signature by a script. Either make proper use or the status codes or use the @command{gpgv} tool which has been designed to make signature verification easy for scripts. @mansect warnings @chapheading WARNINGS Use a good password for your user account and make sure that all security issues are always fixed on your machine. Also employ diligent physical protection to your machine. Consider to use a good passphrase as a last resort protection to your secret key in the case your machine gets stolen. It is important that your secret key is never leaked. Using an easy to carry around token or smartcard with the secret key is often a advisable. If you are going to verify detached signatures, make sure that the program knows about it; either give both filenames on the command line or use @samp{-} to specify STDIN. For scripted or other unattended use of @command{gpg} make sure to use the machine-parseable interface and not the default interface which is intended for direct use by humans. The machine-parseable interface provides a stable and well documented API independent of the locale or future changes of @command{gpg}. To enable this interface use the options @option{--with-colons} and @option{--status-fd}. For certain operations the option @option{--command-fd} may come handy too. See this man page and the file @file{DETAILS} for the specification of the interface. Note that the GnuPG ``info'' pages as well as the PDF version of the GnuPG manual features a chapter on unattended use of GnuPG. As an alternative the library @command{GPGME} can be used as a high-level abstraction on top of that interface. @mansect interoperability @chapheading INTEROPERABILITY WITH OTHER OPENPGP PROGRAMS GnuPG tries to be a very flexible implementation of the OpenPGP standard. In particular, GnuPG implements many of the optional parts of the standard, such as the SHA-512 hash, and the ZLIB and BZIP2 compression algorithms. It is important to be aware that not all OpenPGP programs implement these optional algorithms and that by forcing their use via the @option{--cipher-algo}, @option{--digest-algo}, @option{--cert-digest-algo}, or @option{--compress-algo} options in GnuPG, it is possible to create a perfectly valid OpenPGP message, but one that cannot be read by the intended recipient. There are dozens of variations of OpenPGP programs available, and each supports a slightly different subset of these optional algorithms. For example, until recently, no (unhacked) version of PGP supported the BLOWFISH cipher algorithm. A message using BLOWFISH simply could not be read by a PGP user. By default, GnuPG uses the standard OpenPGP preferences system that will always do the right thing and create messages that are usable by all recipients, regardless of which OpenPGP program they use. Only override this safe default if you really know what you are doing. If you absolutely must override the safe default, or if the preferences on a given key are invalid for some reason, you are far better off using the @option{--pgp6}, @option{--pgp7}, or @option{--pgp8} options. These options are safe as they do not force any particular algorithms in violation of OpenPGP, but rather reduce the available algorithms to a "PGP-safe" list. @mansect bugs @chapheading BUGS On older systems this program should be installed as setuid(root). This is necessary to lock memory pages. Locking memory pages prevents the operating system from writing memory pages (which may contain passphrases or other sensitive material) to disk. If you get no warning message about insecure memory your operating system supports locking without being root. The program drops root privileges as soon as locked memory is allocated. Note also that some systems (especially laptops) have the ability to ``suspend to disk'' (also known as ``safe sleep'' or ``hibernate''). This writes all memory to disk before going into a low power or even powered off mode. Unless measures are taken in the operating system to protect the saved memory, passphrases or other sensitive material may be recoverable from it later. Before you report a bug you should first search the mailing list archives for similar problems and second check whether such a bug has already been reported to our bug tracker at @url{https://bugs.gnupg.org}. @c ******************************************* @c *************** ************** @c *************** UNATTENDED ************** @c *************** ************** @c ******************************************* @manpause @node Unattended Usage of GPG @section Unattended Usage @command{@gpgname} is often used as a backend engine by other software. To help with this a machine interface has been defined to have an unambiguous way to do this. The options @option{--status-fd} and @option{--batch} are almost always required for this. @menu * Programmatic use of GnuPG:: Programmatic use of GnuPG * Ephemeral home directories:: Ephemeral home directories * The quick key manipulation interface:: The quick key manipulation interface * Unattended GPG key generation:: Unattended key generation @end menu @node Programmatic use of GnuPG @subsection Programmatic use of GnuPG Please consider using GPGME instead of calling @command{@gpgname} directly. GPGME offers a stable, backend-independent interface for many cryptographic operations. It supports OpenPGP and S/MIME, and also allows interaction with various GnuPG components. GPGME provides a C-API, and comes with bindings for C++, Qt, and Python. Bindings for other languages are available. @node Ephemeral home directories @subsection Ephemeral home directories Sometimes you want to contain effects of some operation, for example you want to import a key to inspect it, but you do not want this key to be added to your keyring. In earlier versions of GnuPG, it was possible to specify alternate keyring files for both public and secret keys. In modern GnuPG versions, however, we changed how secret keys are stored in order to better protect secret key material, and it was not possible to preserve this interface. The preferred way to do this is to use ephemeral home directories. This technique works across all versions of GnuPG. Create a temporary directory, create (or copy) a configuration that meets your needs, make @command{@gpgname} use this directory either using the environment variable @var{GNUPGHOME}, or the option @option{--homedir}. GPGME supports this too on a per-context basis, by modifying the engine info of contexts. Now execute whatever operation you like, import and export key material as necessary. Once finished, you can delete the directory. All GnuPG backend services that were started will detect this and shut down. @node The quick key manipulation interface @subsection The quick key manipulation interface Recent versions of GnuPG have an interface to manipulate keys without using the interactive command @option{--edit-key}. This interface was added mainly for the benefit of GPGME (please consider using GPGME, see the manual subsection ``Programmatic use of GnuPG''). This interface is described in the subsection ``How to manage your keys''. @node Unattended GPG key generation @subsection Unattended key generation The command @option{--generate-key} may be used along with the option @option{--batch} for unattended key generation. This is the most flexible way of generating keys, but it is also the most complex one. Consider using the quick key manipulation interface described in the previous subsection ``The quick key manipulation interface''. The parameters for the key are either read from stdin or given as a file on the command line. The format of the parameter file is as follows: @itemize @bullet @item Text only, line length is limited to about 1000 characters. @item UTF-8 encoding must be used to specify non-ASCII characters. @item Empty lines are ignored. @item Leading and trailing white space is ignored. @item A hash sign as the first non white space character indicates a comment line. @item Control statements are indicated by a leading percent sign, the arguments are separated by white space from the keyword. @item Parameters are specified by a keyword, followed by a colon. Arguments are separated by white space. @item The first parameter must be @samp{Key-Type}; control statements may be placed anywhere. @item The order of the parameters does not matter except for @samp{Key-Type} which must be the first parameter. The parameters are only used for the generated keyblock (primary and subkeys); parameters from previous sets are not used. Some syntactically checks may be performed. @item Key generation takes place when either the end of the parameter file is reached, the next @samp{Key-Type} parameter is encountered or at the control statement @samp{%commit} is encountered. @end itemize @noindent Control statements: @table @asis @item %echo @var{text} Print @var{text} as diagnostic. @item %dry-run Suppress actual key generation (useful for syntax checking). @item %commit Perform the key generation. Note that an implicit commit is done at the next @asis{Key-Type} parameter. @item %pubring @var{filename} Do not write the key to the default or commandline given keyring but to @var{filename}. This must be given before the first commit to take place, duplicate specification of the same filename is ignored, the last filename before a commit is used. The filename is used until a new filename is used (at commit points) and all keys are written to that file. If a new filename is given, this file is created (and overwrites an existing one). See the previous subsection ``Ephemeral home directories'' for a more robust way to contain side-effects. @item %secring @var{filename} This option is a no-op for GnuPG 2.1 and later. See the previous subsection ``Ephemeral home directories''. @item %ask-passphrase @itemx %no-ask-passphrase This option is a no-op for GnuPG 2.1 and later. @item %no-protection Using this option allows the creation of keys without any passphrase protection. This option is mainly intended for regression tests. @item %transient-key If given the keys are created using a faster and a somewhat less secure random number generator. This option may be used for keys which are only used for a short time and do not require full cryptographic strength. It takes only effect if used together with the control statement @samp{%no-protection}. @end table @noindent General Parameters: @table @asis @item Key-Type: @var{algo} Starts a new parameter block by giving the type of the primary key. The algorithm must be capable of signing. This is a required parameter. @var{algo} may either be an OpenPGP algorithm number or a string with the algorithm name. The special value @samp{default} may be used for @var{algo} to create the default key type; in this case a @samp{Key-Usage} shall not be given and @samp{default} also be used for @samp{Subkey-Type}. @item Key-Length: @var{nbits} The requested length of the generated key in bits. The default is returned by running the command @samp{@gpgname --gpgconf-list}. For ECC keys this parameter is ignored. @item Key-Curve: @var{curve} The requested elliptic curve of the generated key. This is a required parameter for ECC keys. It is ignored for non-ECC keys. @item Key-Grip: @var{hexstring} This is optional and used to generate a CSR or certificate for an already existing key. Key-Length will be ignored when given. @item Key-Usage: @var{usage-list} Space or comma delimited list of key usages. Allowed values are @samp{encrypt}, @samp{sign}, and @samp{auth}. This is used to generate the key flags. Please make sure that the algorithm is capable of this usage. Note that OpenPGP requires that all primary keys are capable of certification, so no matter what usage is given here, the @samp{cert} flag will be on. If no @samp{Key-Usage} is specified and the @samp{Key-Type} is not @samp{default}, all allowed usages for that particular algorithm are used; if it is not given but @samp{default} is used the usage will be @samp{sign}. @item Subkey-Type: @var{algo} This generates a secondary key (subkey). Currently only one subkey can be handled. See also @samp{Key-Type} above. @item Subkey-Length: @var{nbits} Length of the secondary key (subkey) in bits. The default is returned by running the command @samp{@gpgname --gpgconf-list}. @item Subkey-Curve: @var{curve} Key curve for a subkey; similar to @samp{Key-Curve}. @item Subkey-Usage: @var{usage-list} Key usage lists for a subkey; similar to @samp{Key-Usage}. @item Passphrase: @var{string} If you want to specify a passphrase for the secret key, enter it here. Default is to use the Pinentry dialog to ask for a passphrase. @item Name-Real: @var{name} @itemx Name-Comment: @var{comment} @itemx Name-Email: @var{email} The three parts of a user name. Remember to use UTF-8 encoding here. If you don't give any of them, no user ID is created. @item Expire-Date: @var{iso-date}|(@var{number}[d|w|m|y]) Set the expiration date for the key (and the subkey). It may either be entered in ISO date format (e.g. "20000815T145012") or as number of days, weeks, month or years after the creation date. The special notation "seconds=N" is also allowed to specify a number of seconds since creation. Without a letter days are assumed. Note that there is no check done on the overflow of the type used by OpenPGP for timestamps. Thus you better make sure that the given value make sense. Although OpenPGP works with time intervals, GnuPG uses an absolute value internally and thus the last year we can represent is 2105. @item Creation-Date: @var{iso-date} Set the creation date of the key as stored in the key information and which is also part of the fingerprint calculation. Either a date like "1986-04-26" or a full timestamp like "19860426T042640" may be used. The time is considered to be UTC. The special notation "seconds=N" may be used to directly specify a the number of seconds since Epoch (Unix time). If it is not given the current time is used. @item Preferences: @var{string} Set the cipher, hash, and compression preference values for this key. This expects the same type of string as the sub-command @samp{setpref} in the @option{--edit-key} menu. @item Revoker: @var{algo}:@var{fpr} [sensitive] Add a designated revoker to the generated key. Algo is the public key algorithm of the designated revoker (i.e. RSA=1, DSA=17, etc.) @var{fpr} is the fingerprint of the designated revoker. The optional @samp{sensitive} flag marks the designated revoker as sensitive information. Only v4 keys may be designated revokers. @item Keyserver: @var{string} This is an optional parameter that specifies the preferred keyserver URL for the key. @item Handle: @var{string} This is an optional parameter only used with the status lines KEY_CREATED and KEY_NOT_CREATED. @var{string} may be up to 100 characters and should not contain spaces. It is useful for batch key generation to associate a key parameter block with a status line. @end table @noindent Here is an example on how to create a key in an ephemeral home directory: @smallexample $ export GNUPGHOME="$(mktemp -d)" $ cat >foo < ssb elg1024 2016-12-16 [E] @end smallexample @noindent If you want to create a key with the default algorithms you would use these parameters: @smallexample %echo Generating a default key Key-Type: default Subkey-Type: default Name-Real: Joe Tester Name-Comment: with stupid passphrase Name-Email: joe@@foo.bar Expire-Date: 0 Passphrase: abc # Do a commit here, so that we can later print "done" :-) %commit %echo done @end smallexample @mansect see also @ifset isman @command{gpgv}(1), @command{gpgsm}(1), @command{gpg-agent}(1) @end ifset @include see-also-note.texi diff --git a/g10/call-dirmngr.c b/g10/call-dirmngr.c index 72afad8bc..f5fc8fcde 100644 --- a/g10/call-dirmngr.c +++ b/g10/call-dirmngr.c @@ -1,1431 +1,1431 @@ /* call-dirmngr.c - GPG operations to the Dirmngr. * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/keyserver.h" #include "../common/status.h" #include "keyserver-internal.h" #include "call-dirmngr.h" /* Keys retrieved from the web key directory should be small. There * is only one UID and we can expect that the number of subkeys is * reasonable. So we set a generous limit of 256 KiB. */ #define MAX_WKD_RESULT_LENGTH (256 * 1024) /* Parameter structure used to gather status info. Note that it is * also used for WKD requests. */ struct ks_status_parm_s { const char *keyword; /* Look for this keyword or NULL for "SOURCE". */ char *source; }; /* Parameter structure used with the KS_SEARCH command. */ struct ks_search_parm_s { gpg_error_t lasterr; /* Last error code. */ membuf_t saveddata; /* Buffer to build complete lines. */ char *helpbuf; /* NULL or malloced buffer. */ size_t helpbufsize; /* Allocated size of HELPBUF. */ gpg_error_t (*data_cb)(void*, int, char*); /* Callback. */ void *data_cb_value; /* First argument for DATA_CB. */ struct ks_status_parm_s *stparm; /* Link to the status parameter. */ }; /* Parameter structure used with the KS_GET command. */ struct ks_get_parm_s { estream_t memfp; }; /* Parameter structure used with the KS_PUT command. */ struct ks_put_parm_s { assuan_context_t ctx; kbnode_t keyblock; /* The optional keyblock. */ const void *data; /* The key in OpenPGP binary format. */ size_t datalen; /* The length of DATA. */ }; /* Parameter structure used with the DNS_CERT command. */ struct dns_cert_parm_s { estream_t memfp; unsigned char *fpr; size_t fprlen; char *url; }; /* Data used to associate an session with dirmngr contexts. We can't use a simple one to one mapping because we sometimes need two connections to the dirmngr; for example while doing a listing and being in a data callback we may want to retrieve a key. The local dirmngr data takes care of this. At the end of the session the function dirmngr_deinit_session_data is called by gpg.c to cleanup these resources. Note that gpg.h defines a typedef dirmngr_local_t for this structure. */ struct dirmngr_local_s { /* Link to other contexts which are used simultaneously. */ struct dirmngr_local_s *next; /* The active Assuan context. */ assuan_context_t ctx; /* Flag set when the keyserver names have been send. */ int set_keyservers_done; /* Flag set to true while an operation is running on CTX. */ int is_active; }; /* Deinitialize all session data of dirmngr pertaining to CTRL. */ void gpg_dirmngr_deinit_session_data (ctrl_t ctrl) { dirmngr_local_t dml; while ((dml = ctrl->dirmngr_local)) { ctrl->dirmngr_local = dml->next; if (dml->is_active) log_error ("oops: trying to cleanup an active dirmngr context\n"); else assuan_release (dml->ctx); xfree (dml); } } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (assuan_context_t ctx, const char *servername) { gpg_error_t err; char *serverversion; const char *myversion = strusage (13); err = get_assuan_server_version (ctx, 0, &serverversion); if (err) log_error (_("error getting version from '%s': %s\n"), servername, gpg_strerror (err)); else if (compare_version_strings (serverversion, myversion) < 0) { char *warn; warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"), servername, serverversion, myversion); if (!warn) err = gpg_error_from_syserror (); else { log_info (_("WARNING: %s\n"), warn); if (!opt.quiet) { log_info (_("Note: Outdated servers may lack important" " security fixes.\n")); log_info (_("Note: Use the command \"%s\" to restart them.\n"), "gpgconf --kill all"); } write_status_strings (STATUS_WARNING, "server_version_mismatch 0", " ", warn, NULL); xfree (warn); } } xfree (serverversion); return err; } /* Try to connect to the Dirmngr via a socket or spawn it if possible. Handle the server's initial greeting and set global options. */ static gpg_error_t create_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; assuan_context_t ctx; *r_ctx = NULL; if (opt.disable_dirmngr) return gpg_error (GPG_ERR_NO_DIRMNGR); err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, opt.verbose, DBG_IPC, NULL /*gpg_status2*/, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR) { static int shown; if (!shown) { shown = 1; log_info (_("no dirmngr running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (ctx, DIRMNGR_NAME))) { char *line; /* Tell the dirmngr that we want to collect audit event. */ /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */ /* NULL, NULL, NULL, NULL, NULL, NULL); */ if (opt.keyserver_options.http_proxy) { line = xtryasprintf ("OPTION http-proxy=%s", opt.keyserver_options.http_proxy); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } } if (err) ; else if ((opt.keyserver_options.options & KEYSERVER_HONOR_KEYSERVER_URL)) { /* Tell the dirmngr that this possibly privacy invading option is in use. If Dirmngr is running in Tor mode, it will return an error. */ err = assuan_transact (ctx, "OPTION honor-keyserver-url-used", NULL, NULL, NULL, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_FORBIDDEN) log_error (_("keyserver option \"%s\"" " may not be used in %s mode\n"), "honor-keyserver-url", "Tor"); else if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Old dirmngr versions do not support this option. */ } } if (err) assuan_release (ctx); else { /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */ *r_ctx = ctx; } return err; } /* Get a context for accessing dirmngr. If no context is available a new one is created and - if required - dirmngr started. On success an assuan context is stored at R_CTX. This context may only be released by means of close_context. Note that NULL is stored at R_CTX on error. */ static gpg_error_t open_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; dirmngr_local_t dml; *r_ctx = NULL; for (;;) { for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next) ; if (dml) { /* Found an inactive local session - return that. */ log_assert (!dml->is_active); /* But first do the per session init if not yet done. */ if (!dml->set_keyservers_done) { keyserver_spec_t ksi; /* Set all configured keyservers. We clear existing keyservers so that any keyserver configured in GPG overrides keyservers possibly still configured in Dirmngr for the session (Note that the keyserver list of a session in Dirmngr survives a RESET. */ for (ksi = opt.keyserver; ksi; ksi = ksi->next) { char *line; line = xtryasprintf ("KEYSERVER%s %s", ksi == opt.keyserver? " --clear":"", ksi->uri); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (dml->ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } if (err) return err; } dml->set_keyservers_done = 1; } dml->is_active = 1; *r_ctx = dml->ctx; return 0; } dml = xtrycalloc (1, sizeof *dml); if (!dml) return gpg_error_from_syserror (); err = create_context (ctrl, &dml->ctx); if (err) { xfree (dml); return err; } /* To be on the nPth thread safe site we need to add it to a list; this is far easier than to have a lock for this function. It should not happen anyway but the code is free because we need it for the is_active check above. */ dml->next = ctrl->dirmngr_local; ctrl->dirmngr_local = dml; } } /* Close the assuan context CTX or return it to a pool of unused contexts. If CTX is NULL, the function does nothing. */ static void close_context (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("closing inactive dirmngr context %p\n", ctx); dml->is_active = 0; return; } } log_fatal ("closing unknown dirmngr ctx %p\n", ctx); } /* Clear the set_keyservers_done flag on context CTX. */ static void clear_context_flags (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("clear_context_flags on inactive dirmngr ctx %p\n", ctx); dml->set_keyservers_done = 0; return; } } log_fatal ("clear_context_flags on unknown dirmngr ctx %p\n", ctx); } /* Status callback for ks_list, ks_get, ks_search, and wkd_get */ static gpg_error_t ks_status_cb (void *opaque, const char *line) { struct ks_status_parm_s *parm = opaque; gpg_error_t err = 0; const char *s, *s2; const char *warn = NULL; int is_note = 0; if ((s = has_leading_keyword (line, parm->keyword? parm->keyword : "SOURCE"))) { /* Note that the arg for "S SOURCE" is the URL of a keyserver. */ if (!parm->source) { parm->source = xtrystrdup (s); if (!parm->source) err = gpg_error_from_syserror (); } } else if ((s = has_leading_keyword (line, "WARNING")) || (is_note = !!(s = has_leading_keyword (line, "NOTE")))) { if ((s2 = has_leading_keyword (s, "wkd_cached_result"))) { if (opt.verbose) warn = _("WKD uses a cached result"); } else if ((s2 = has_leading_keyword (s, "tor_not_running"))) warn = _("Tor is not running"); else if ((s2 = has_leading_keyword (s, "tor_config_problem"))) warn = _("Tor is not properly configured"); else if ((s2 = has_leading_keyword (s, "dns_config_problem"))) warn = _("DNS is not properly configured"); else if ((s2 = has_leading_keyword (s, "http_redirect"))) warn = _("unacceptable HTTP redirect from server"); else if ((s2 = has_leading_keyword (s, "http_redirect_cleanup"))) warn = _("unacceptable HTTP redirect from server was cleaned up"); else if ((s2 = has_leading_keyword (s, "tls_cert_error"))) warn = _("server uses an invalid certificate"); else warn = NULL; if (warn) { if (is_note) log_info (_("Note: %s\n"), warn); else log_info (_("WARNING: %s\n"), warn); if (s2) { while (*s2 && !spacep (s2)) s2++; while (*s2 && spacep (s2)) s2++; if (*s2) print_further_info ("%s", s2); } } } return err; } /* Run the "KEYSERVER" command to return the name of the used keyserver at R_KEYSERVER. */ gpg_error_t gpg_dirmngr_ks_list (ctrl_t ctrl, char **r_keyserver) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; memset (&stparm, 0, sizeof stparm); stparm.keyword = "KEYSERVER"; if (r_keyserver) *r_keyserver = NULL; err = open_context (ctrl, &ctx); if (err) return err; err = assuan_transact (ctx, "KEYSERVER", NULL, NULL, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; if (!stparm.source) { err = gpg_error (GPG_ERR_NO_KEYSERVER); goto leave; } if (r_keyserver) *r_keyserver = stparm.source; else xfree (stparm.source); stparm.source = NULL; leave: xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_SEARCH command. */ static gpg_error_t ks_search_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_search_parm_s *parm = opaque; const char *line, *s; size_t rawlen, linelen; char fixedbuf[256]; if (parm->lasterr) return 0; if (parm->stparm->source) { err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source); if (err) { parm->lasterr = err; return err; } /* Clear it so that we won't get back here unless the server accidentally sends a second source status line. Note that will not see all accidentally sent source lines because it depends on whether data lines have been send in between. */ xfree (parm->stparm->source); parm->stparm->source = NULL; } if (!data) return 0; /* Ignore END commands. */ put_membuf (&parm->saveddata, data, datalen); again: line = peek_membuf (&parm->saveddata, &rawlen); if (!line) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; /* Tell the server about our problem. */ } if ((s = memchr (line, '\n', rawlen))) { linelen = s - line; /* That is the length excluding the LF. */ if (linelen + 1 < sizeof fixedbuf) { /* We can use the static buffer. */ memcpy (fixedbuf, line, linelen); fixedbuf[linelen] = 0; if (linelen && fixedbuf[linelen-1] == '\r') fixedbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, fixedbuf); } else { if (linelen + 1 >= parm->helpbufsize) { xfree (parm->helpbuf); parm->helpbufsize = linelen + 1 + 1024; parm->helpbuf = xtrymalloc (parm->helpbufsize); if (!parm->helpbuf) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; } } memcpy (parm->helpbuf, line, linelen); parm->helpbuf[linelen] = 0; if (linelen && parm->helpbuf[linelen-1] == '\r') parm->helpbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf); } if (err) parm->lasterr = err; else { clear_membuf (&parm->saveddata, linelen+1); goto again; /* There might be another complete line. */ } } return err; } /* Run the KS_SEARCH command using the search string SEARCHSTR. All data lines are passed to the CB function. That function is called with CB_VALUE as its first argument, a 0 as second argument, and the decoded data line as third argument. The callback function may modify the data line and it is guaranteed that this data line is a complete line with a terminating 0 character but without the linefeed. NULL is passed to the callback to indicate EOF. */ gpg_error_t gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr, gpg_error_t (*cb)(void*, int, char *), void *cb_value) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_search_parm_s parm; char line[ASSUAN_LINELENGTH]; err = open_context (ctrl, &ctx); if (err) return err; { char *escsearchstr = percent_plus_escape (searchstr); if (!escsearchstr) { err = gpg_error_from_syserror (); close_context (ctrl, ctx); return err; } snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr); xfree (escsearchstr); } memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); init_membuf (&parm.saveddata, 1024); parm.data_cb = cb; parm.data_cb_value = cb_value; parm.stparm = &stparm; err = assuan_transact (ctx, line, ks_search_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (!err) err = cb (cb_value, 0, NULL); /* Send EOF. */ else if (parm.stparm->source) { /* Error but we received a SOURCE status. Tell via callback but * ignore errors. */ parm.data_cb (parm.data_cb_value, 1, parm.stparm->source); } xfree (get_membuf (&parm.saveddata, NULL)); xfree (parm.helpbuf); xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_GET and KS_FETCH commands. */ static gpg_error_t ks_get_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_get_parm_s *parm = opaque; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Run the KS_GET command using the patterns in the array PATTERN. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The pattern may only use search specification which a keyserver can use to retrieve keys. Because we know the format of the pattern we don't need to escape the patterns before sending them to the server. Bit values for FLAGS are: - KEYSERVER_IMPORT_FLAG_QUICK :: dirmngr shall use a shorter timeout. - KEYSERVER_IMPORT_FLAG_LDAP :: dirmngr shall only use LDAP or NTDS. If R_SOURCE is not NULL the source of the data is stored as a malloced string there. If a source is not known NULL is stored. Note that this may even be returned after an error. If there are too many patterns the function returns an error. That could be fixed by issuing several search commands or by implementing a different interface. However with long keyids we are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once. */ gpg_error_t gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern, keyserver_spec_t override_keyserver, unsigned int flags, estream_t *r_fp, char **r_source) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_get_parm_s parm; char *line = NULL; size_t linelen; membuf_t mb; int idx; memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); *r_fp = NULL; if (r_source) *r_source = NULL; err = open_context (ctrl, &ctx); if (err) return err; /* If we have an override keyserver we first indicate that the next user of the context needs to again setup the global keyservers and - them we send the override keyserver. */ + then we send the override keyserver. */ if (override_keyserver) { clear_context_flags (ctrl, ctx); line = xtryasprintf ("KEYSERVER --clear %s", override_keyserver->uri); if (!line) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) goto leave; xfree (line); line = NULL; } /* Lump all patterns into one string. */ init_membuf (&mb, 1024); put_membuf_str (&mb, "KS_GET"); if ((flags & KEYSERVER_IMPORT_FLAG_QUICK)) put_membuf_str (&mb, " --quick"); if ((flags & KEYSERVER_IMPORT_FLAG_LDAP)) put_membuf_str (&mb, " --ldap"); put_membuf_str (&mb, " --"); for (idx=0; pattern[idx]; idx++) { put_membuf (&mb, " ", 1); /* Append Delimiter. */ put_membuf_str (&mb, pattern[idx]); } put_membuf (&mb, "", 1); /* Append Nul. */ line = get_membuf (&mb, &linelen); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (linelen + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_MANY); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: if (r_source && stparm.source) { *r_source = stparm.source; stparm.source = NULL; } es_fclose (parm.memfp); xfree (stparm.source); xfree (line); close_context (ctrl, ctx); return err; } /* Run the KS_FETCH and pass URL as argument. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The url is expected to point to a small set of keys; in many cases only to one key. However, schemes like finger may return several keys. Note that the configured keyservers are ignored by the KS_FETCH command. */ gpg_error_t gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp) { gpg_error_t err; assuan_context_t ctx; struct ks_get_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); *r_fp = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = strconcat ("KS_FETCH -- ", url, NULL); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, NULL, NULL); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } static void record_output (estream_t output, pkttype_t type, const char *validity, /* The public key length or -1. */ int pub_key_length, /* The public key algo or -1. */ int pub_key_algo, /* 2 ulongs or NULL. */ const u32 *keyid, /* The creation / expiration date or 0. */ u32 creation_date, u32 expiration_date, const char *userid) { const char *type_str = NULL; char *pub_key_length_str = NULL; char *pub_key_algo_str = NULL; char *keyid_str = NULL; char *creation_date_str = NULL; char *expiration_date_str = NULL; char *userid_escaped = NULL; switch (type) { case PKT_PUBLIC_KEY: type_str = "pub"; break; case PKT_PUBLIC_SUBKEY: type_str = "sub"; break; case PKT_USER_ID: type_str = "uid"; break; case PKT_SIGNATURE: type_str = "sig"; break; default: log_assert (! "Unhandled type."); } if (pub_key_length > 0) pub_key_length_str = xasprintf ("%d", pub_key_length); if (pub_key_algo != -1) pub_key_algo_str = xasprintf ("%d", pub_key_algo); if (keyid) keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]); if (creation_date) creation_date_str = xstrdup (colon_strtime (creation_date)); if (expiration_date) expiration_date_str = xstrdup (colon_strtime (expiration_date)); /* Quote ':', '%', and any 8-bit characters. */ if (userid) { int r; int w = 0; int len = strlen (userid); /* A 100k character limit on the uid should be way more than enough. */ if (len > 100 * 1024) len = 100 * 1024; /* The minimum amount of space that we need. */ userid_escaped = xmalloc (len * 3 + 1); for (r = 0; r < len; r++) { if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80)) { sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]); w += 3; } else userid_escaped[w ++] = userid[r]; } userid_escaped[w] = '\0'; } es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", type_str, validity ?: "", pub_key_length_str ?: "", pub_key_algo_str ?: "", keyid_str ?: "", creation_date_str ?: "", expiration_date_str ?: "", "" /* Certificate S/N */, "" /* Ownertrust. */, userid_escaped ?: "", "" /* Signature class. */, "" /* Key capabilities. */, "" /* Issuer certificate fingerprint. */, "" /* Flag field. */, "" /* S/N of a token. */, "" /* Hash algo. */, "" /* Curve name. */); xfree (userid_escaped); xfree (expiration_date_str); xfree (creation_date_str); xfree (keyid_str); xfree (pub_key_algo_str); xfree (pub_key_length_str); } /* Handle the KS_PUT inquiries. */ static gpg_error_t ks_put_inq_cb (void *opaque, const char *line) { struct ks_put_parm_s *parm = opaque; gpg_error_t err = 0; if (has_leading_keyword (line, "KEYBLOCK")) { if (parm->data) err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else if (has_leading_keyword (line, "KEYBLOCK_INFO")) { kbnode_t node; estream_t fp; char hexfpr[2*MAX_FINGERPRINT_LEN+1]; /* Parse the keyblock and send info lines back to the server. */ fp = es_fopenmem (0, "rw,samethread"); if (!fp) err = gpg_error_from_syserror (); /* Note: the output format for the INFO block follows the colon format as described in doc/DETAILS. We don't actually reuse the functionality from g10/keylist.c to produce the output, because we don't need all of it and some of it is quite expensive to generate. The fields are (the starred fields are the ones we need): * Field 1 - Type of record * Field 2 - Validity * Field 3 - Key length * Field 4 - Public key algorithm * Field 5 - KeyID * Field 6 - Creation date * Field 7 - Expiration date Field 8 - Certificate S/N, UID hash, trust signature info Field 9 - Ownertrust * Field 10 - User-ID Field 11 - Signature class Field 12 - Key capabilities Field 13 - Issuer certificate fingerprint or other info Field 14 - Flag field Field 15 - S/N of a token Field 16 - Hash algorithm Field 17 - Curve name */ for (node = parm->keyblock; !err && node; node=node->next) { switch (node->pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: { PKT_public_key *pk = node->pkt->pkt.public_key; char validity[3]; int i; i = 0; if (pk->flags.revoked) validity[i ++] = 'r'; if (pk->has_expired) validity[i ++] = 'e'; validity[i] = '\0'; keyid_from_pk (pk, NULL); record_output (fp, node->pkt->pkttype, validity, nbits_from_pk (pk), pk->pubkey_algo, pk->keyid, pk->timestamp, pk->expiredate, NULL); es_fprintf (fp, "fpr:::::::::%s:\n", hexfingerprint (pk, hexfpr, sizeof hexfpr)); } break; case PKT_USER_ID: { PKT_user_id *uid = node->pkt->pkt.user_id; if (!uid->attrib_data) { char validity[3]; int i; i = 0; if (uid->flags.revoked) validity[i ++] = 'r'; if (uid->flags.expired) validity[i ++] = 'e'; validity[i] = '\0'; record_output (fp, node->pkt->pkttype, validity, -1, -1, NULL, uid->created, uid->expiredate, uid->name); } } break; default: continue; } /* Given that the last operation was an es_fprintf we should get the correct ERRNO if ferror indicates an error. */ if (es_ferror (fp)) err = gpg_error_from_syserror (); } /* Without an error and if we have an keyblock at all, send the data back. */ if (!err && parm->keyblock) { int rc; char buffer[512]; size_t nread; es_rewind (fp); while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread) { err = assuan_send_data (parm->ctx, buffer, nread); if (err) break; } if (!err && rc) err = gpg_error_from_syserror (); } es_fclose (fp); } else return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); return err; } /* Send a key to the configured server. {DATA,DATLEN} contains the key in OpenPGP binary transport format. If KEYBLOCK is not NULL it has the internal representaion of that key; this is for example used to convey meta data to LDAP keyservers. */ gpg_error_t gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock) { gpg_error_t err; assuan_context_t ctx; struct ks_put_parm_s parm; memset (&parm, 0, sizeof parm); /* We are going to parse the keyblock, thus we better make sure the all information is readily available. */ if (keyblock) merge_keys_and_selfsig (ctrl, keyblock); err = open_context (ctrl, &ctx); if (err) return err; parm.ctx = ctx; parm.keyblock = keyblock; parm.data = data; parm.datalen = datalen; err = assuan_transact (ctx, "KS_PUT", NULL, NULL, ks_put_inq_cb, &parm, NULL, NULL); close_context (ctrl, ctx); return err; } /* Data callback for the DNS_CERT and WKD_GET commands. */ static gpg_error_t dns_cert_data_cb (void *opaque, const void *data, size_t datalen) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (!parm->memfp) return 0; /* Data is not required. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Status callback for the DNS_CERT command. */ static gpg_error_t dns_cert_status_cb (void *opaque, const char *line) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; const char *s; size_t nbytes; if ((s = has_leading_keyword (line, "FPR"))) { char *buf; if (!(buf = xtrystrdup (s))) err = gpg_error_from_syserror (); else if (parm->fpr) err = gpg_error (GPG_ERR_DUP_KEY); else if (!hex2str (buf, buf, strlen (buf)+1, &nbytes)) err = gpg_error_from_syserror (); else if (nbytes < 20) err = gpg_error (GPG_ERR_TOO_SHORT); else { parm->fpr = xtrymalloc (nbytes); if (!parm->fpr) err = gpg_error_from_syserror (); else memcpy (parm->fpr, buf, (parm->fprlen = nbytes)); } xfree (buf); } else if ((s = has_leading_keyword (line, "URL")) && *s) { if (parm->url) err = gpg_error (GPG_ERR_DUP_KEY); else if (!(parm->url = xtrystrdup (s))) err = gpg_error_from_syserror (); } return err; } /* Ask the dirmngr for a DNS CERT record. Depending on the found subtypes different return values are set: - For a PGP subtype a new estream with that key will be returned at R_KEY and the other return parameters are set to NULL/0. - For an IPGP subtype the fingerprint is stored as a malloced block at (R_FPR,R_FPRLEN). If an URL is available it is stored as a malloced string at R_URL; NULL is stored if there is no URL. If CERTTYPE is DNS_CERTTYPE_ANY this function returns the first CERT record found with a supported type; it is expected that only one CERT record is used. If CERTTYPE is one of the supported certtypes, only records with this certtype are considered and the first one found is returned. All R_* args are optional. If CERTTYPE is NULL the DANE method is used to fetch the key. */ gpg_error_t gpg_dirmngr_dns_cert (ctrl_t ctrl, const char *name, const char *certtype, estream_t *r_key, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct dns_cert_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); if (r_key) *r_key = NULL; if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("DNS_CERT %s %s", certtype? certtype : "--dane", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, dns_cert_status_cb, &parm); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_fpr && parm.fpr) { *r_fpr = parm.fpr; parm.fpr = NULL; } if (r_fprlen) *r_fprlen = parm.fprlen; if (r_url && parm.url) { *r_url = parm.url; parm.url = NULL; } leave: xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } /* Ask the dirmngr for PKA info. On success the retrieved fingerprint is returned in a malloced buffer at R_FPR and its length is stored at R_FPRLEN. If an URL is available it is stored as a malloced string at R_URL. On error all return values are set to NULL/0. */ gpg_error_t gpg_dirmngr_get_pka (ctrl_t ctrl, const char *userid, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct dns_cert_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("DNS_CERT --pka -- %s", userid); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, dns_cert_status_cb, &parm); if (err) goto leave; if (r_fpr && parm.fpr) { *r_fpr = parm.fpr; parm.fpr = NULL; } if (r_fprlen) *r_fprlen = parm.fprlen; if (r_url && parm.url) { *r_url = parm.url; parm.url = NULL; } leave: xfree (parm.fpr); xfree (parm.url); xfree (line); close_context (ctrl, ctx); return err; } /* Ask the dirmngr to retrieve a key via the Web Key Directory * protocol. If QUICK is set the dirmngr is advised to use a shorter * timeout. On success a new estream with the key stored at R_KEY and the * url of the lookup (if any) stored at R_URL. Note that */ gpg_error_t gpg_dirmngr_wkd_get (ctrl_t ctrl, const char *name, int quick, estream_t *r_key, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm = { NULL }; struct dns_cert_parm_s parm = { NULL }; char *line = NULL; if (r_key) *r_key = NULL; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("WKD_GET%s -- %s", quick?" --quick":"", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (MAX_WKD_RESULT_LENGTH, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (gpg_err_code (err) == GPG_ERR_ENOSPC) err = gpg_error (GPG_ERR_TOO_LARGE); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_url) { *r_url = stparm.source; stparm.source = NULL; } leave: xfree (stparm.source); xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } diff --git a/g10/getkey.c b/g10/getkey.c index 27ad007c9..8dd585ea9 100644 --- a/g10/getkey.c +++ b/g10/getkey.c @@ -1,4400 +1,4508 @@ /* 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, 2016 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "keydb.h" #include "options.h" #include "main.h" #include "trustdb.h" #include "../common/i18n.h" #include "keyserver-internal.h" #include "call-agent.h" #include "../common/host2net.h" #include "../common/mbox-util.h" #include "../common/status.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 /* Flags values returned by the lookup code. Note that the values are * directly used by the KEY_CONSIDERED status line. */ #define LOOKUP_NOT_SELECTED (1<<0) #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1) /* or revoked */ /* A context object used by the lookup functions. */ 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; /* Hack to return the mechanism (AKL_foo) used to find the key. */ int found_via_akl; /* 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 (ctrl_t ctrl, kbnode_t keyblock); static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret, kbnode_t *ret_keyblock, kbnode_t *ret_found_key); static kbnode_t finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact, int want_secret, unsigned int *r_flags); static void print_status_key_considered (kbnode_t keyblock, unsigned int flags); #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 /* 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) { #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 && 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--; } } log_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->flags.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; 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++; } /* Disable and drop the public key cache (which is filled by cache_public_key and get_pubkey). Note: there is currently no way to re-enable this cache. */ 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 ? */ } /* Free a list of pubkey_t objects. */ void pubkeys_free (pubkey_t keys) { while (keys) { pubkey_t next = keys->next; xfree (keys->pk); release_kbnode (keys->keyblock); xfree (keys); keys = next; } } static void pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key) { kbnode_t a = found_key ? found_key : keyblock; log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY || a->pkt->pkttype == PKT_PUBLIC_SUBKEY); copy_public_key (pk, a->pkt->pkt.public_key); } /* Specialized version of get_pubkey which retrieves the key based on * information in SIG. In contrast to get_pubkey PK is required. IF * FORCED_PK is not NULL, this public key is used and copied to PK. */ gpg_error_t get_pubkey_for_sig (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig, PKT_public_key *forced_pk) { const byte *fpr; size_t fprlen; if (forced_pk) { copy_public_key (pk, forced_pk); return 0; } /* First try the new ISSUER_FPR info. */ fpr = issuer_fpr_raw (sig, &fprlen); if (fpr && !get_pubkey_byfprint (ctrl, pk, NULL, fpr, fprlen)) return 0; /* Fallback to use the ISSUER_KEYID. */ return get_pubkey (ctrl, pk, sig->keyid); } /* Return the public key with the key id KEYID and store it at 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 (ctrl_t ctrl, 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) { internal++; pk = xtrycalloc (1, sizeof *pk); if (!pk) { rc = gpg_error_from_syserror (); goto leave; } } /* Do a lookup. */ { struct getkey_ctx_s ctx; kbnode_t kb = 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; if (ctrl && ctrl->cached_getkey_kdb) { ctx.kr_handle = ctrl->cached_getkey_kdb; ctrl->cached_getkey_kdb = NULL; keydb_search_reset (ctx.kr_handle); } else { 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 (ctrl, &ctx, 0, &kb, &found_key); if (!rc) { pk_from_block (pk, kb, found_key); } getkey_end (ctrl, &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; } /* 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) { int rc = 0; KEYDB_HANDLE hd; KBNODE keyblock; u32 pkid[2]; log_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; } log_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; } /* Return the entire keyblock used to create SIG. This is a * specialized version of get_pubkeyblock. * * FIXME: This is a hack because get_pubkey_for_sig was already called * and it could have used a cache to hold the key. */ kbnode_t get_pubkeyblock_for_sig (ctrl_t ctrl, PKT_signature *sig) { const byte *fpr; size_t fprlen; kbnode_t keyblock; /* First try the new ISSUER_FPR info. */ fpr = issuer_fpr_raw (sig, &fprlen); if (fpr && !get_pubkey_byfprint (ctrl, NULL, &keyblock, fpr, fprlen)) return keyblock; /* Fallback to use the ISSUER_KEYID. */ return get_pubkeyblock (ctrl, sig->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_t get_pubkeyblock (ctrl_t ctrl, 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 (ctrl, &ctx, 0, &keyblock, NULL); getkey_end (ctrl, &ctx); return rc ? NULL : keyblock; } /* Return the public key with the key id KEYID iff the secret key is * available and store it at 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 (ctrl_t ctrl, 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 (ctrl, &ctx, 1, &keyblock, &found_key); if (!err) { pk_from_block (pk, keyblock, found_key); } getkey_end (ctrl, &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 *opaque, u32 * keyid, int uid_no) { ctrl_t ctrl = opaque; int unusable = 0; KBNODE keyblock; PKT_public_key *pk; keyblock = get_pubkeyblock (ctrl, 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->flags.revoked || user_id->flags.expired) unusable = 1; break; } } /* If UID_NO is non-zero, then the keyblock better have at least that many UIDs. */ log_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 (ctrl_t ctrl, 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. */ log_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; ctx->items[0].skipfncvalue = ctrl; } } 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->items[n].skipfncvalue = ctrl; } } } ctx->want_secret = want_secret; ctx->kr_handle = keydb_new (); if (!ctx->kr_handle) { rc = gpg_error_from_syserror (); getkey_end (ctrl, ctx); return rc; } if (!ret_kb) ret_kb = &help_kb; if (pk) { ctx->req_usage = pk->req_usage; } rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key); if (!rc && pk) { pk_from_block (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 (ctrl, ctx); } return rc; } /* Find a public key identified by NAME. * * If name appears to be a valid RFC822 mailbox (i.e., email address) * and auto key lookup is enabled (mode != GET_PUBKEY_NO_AKL), 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. * * MODE can be one of: * GET_PUBKEY_NORMAL - The standard mode * GET_PUBKEY_NO_AKL - 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! * GET_PUBKEY_NO_LOCAL - Only the auto key locate functionaly is * used and no local search is done. * * 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. * * 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, enum get_pubkey_modes mode, GETKEY_CTX * retctx, PKT_public_key * pk, const char *name, KBNODE * ret_keyblock, KEYDB_HANDLE * ret_kdbhd, int include_unusable) { int rc; strlist_t namelist = NULL; struct akl *akl; - int is_mbox; + int is_mbox, is_fpr; + KEYDB_SEARCH_DESC fprbuf; int nodefault = 0; int anylocalfirst = 0; int mechanism_type = AKL_NODEFAULT; + size_t fprbuf_fprlen = 0; /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */ log_assert (retctx == NULL || ret_kdbhd == NULL); if (retctx) *retctx = NULL; /* Does NAME appear to be a mailbox (mail address)? */ is_mbox = is_valid_mailbox (name); if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>' && name[1] != '>' && is_valid_mailbox_mem (name+1, strlen (name)-2)) { /* The mailbox is in the form "" which is not * detected by is_valid_mailbox. Set the flag but keep name as * it is because the bracketed name is actual the better * specification for a local search and the other methods * extract the mail address anyway. */ is_mbox = 1; } + /* If we are called due to --locate-external-key Check whether NAME + * is a fingerprint and then try to lookup that key by configured + * method which support lookup by fingerprint. FPRBUF carries the + * parsed fingerpint iff IS_FPR is true. */ + is_fpr = 0; + if (!is_mbox && mode == GET_PUBKEY_NO_LOCAL) + { + if (!classify_user_id (name, &fprbuf, 1) + && (fprbuf.mode == KEYDB_SEARCH_MODE_FPR16 + || fprbuf.mode == KEYDB_SEARCH_MODE_FPR20 + || fprbuf.mode == KEYDB_SEARCH_MODE_FPR)) + { + /* Note: We should get rid of the FPR16 because we don't + * support v3 keys anymore. However, in 2.3 the fingerprint + * code has already been reworked and thus it is + * questionable whether we should really tackle this here. */ + if (fprbuf.mode == KEYDB_SEARCH_MODE_FPR16) + fprbuf_fprlen = 16; + else + fprbuf_fprlen = 20; + is_fpr = 1; + } + } + /* 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 (mode == GET_PUBKEY_NO_LOCAL) nodefault = 1; /* Auto-key-locate but ignore "local". */ else if (mode != GET_PUBKEY_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 (mode == GET_PUBKEY_NO_LOCAL) { /* Force using the AKL. If IS_MBOX is not set this is the final * error code. */ rc = GPG_ERR_NO_PUBKEY; } else 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 (ctrl, 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 && mode != GET_PUBKEY_NO_AKL - && is_mbox) + && (is_mbox || is_fpr)) { /* 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_akl_local = 0; int no_fingerprint = 0; const char *mechanism_string = "?"; mechanism_type = akl->type; switch (mechanism_type) { case AKL_NODEFAULT: /* This is a dummy mechanism. */ mechanism_string = ""; rc = GPG_ERR_NO_PUBKEY; break; case AKL_LOCAL: if (mode == GET_PUBKEY_NO_LOCAL) { + /* Note that we get here in is_fpr more, so there is + * no extra check for it required. */ mechanism_string = ""; rc = GPG_ERR_NO_PUBKEY; } else { mechanism_string = "Local"; did_akl_local = 1; if (retctx) { getkey_end (ctrl, *retctx); *retctx = NULL; } add_to_strlist (&namelist, name); rc = key_byname (ctrl, anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } break; case AKL_CERT: - mechanism_string = "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; + if (is_fpr) + { + mechanism_string = ""; + rc = GPG_ERR_NO_PUBKEY; + } + else + { + mechanism_string = "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_string = "PKA"; - glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len); - glo_ctrl.in_auto_key_retrieve--; - break; + if (is_fpr) + { + mechanism_string = ""; + rc = GPG_ERR_NO_PUBKEY; + } + else + { + mechanism_string = "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_string = "DANE"; - glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len); - glo_ctrl.in_auto_key_retrieve--; + if (is_fpr) + { + mechanism_string = ""; + rc = GPG_ERR_NO_PUBKEY; + } + else + { + mechanism_string = "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_WKD: - mechanism_string = "WKD"; - glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len); - glo_ctrl.in_auto_key_retrieve--; + if (is_fpr) + { + mechanism_string = ""; + rc = GPG_ERR_NO_PUBKEY; + } + else + { + mechanism_string = "WKD"; + glo_ctrl.in_auto_key_retrieve++; + rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len); + glo_ctrl.in_auto_key_retrieve--; + } break; case AKL_LDAP: - mechanism_string = "LDAP"; - glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len); - glo_ctrl.in_auto_key_retrieve--; - break; + if (is_fpr) + { + mechanism_string = ""; + rc = GPG_ERR_NO_PUBKEY; + } + else + { + mechanism_string = "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_NTDS: mechanism_string = "NTDS"; glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_ntds (ctrl, name, &fpr, &fpr_len); + if (is_fpr) + rc = keyserver_import_fprint_ntds (ctrl, + fprbuf.u.fpr, fprbuf_fprlen); + else + rc = keyserver_import_ntds (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 (keyserver_any_configured (ctrl)) { mechanism_string = "keyserver"; glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, - opt.keyserver); + if (is_fpr) + { + rc = keyserver_import_fprint (ctrl, + fprbuf.u.fpr, fprbuf_fprlen, + opt.keyserver, + KEYSERVER_IMPORT_FLAG_LDAP); + /* Map error codes because Dirmngr returns NO + * DATA if the keyserver does not have the + * requested key. It returns NO KEYSERVER if no + * LDAP keyservers are configured. */ + if (gpg_err_code (rc) == GPG_ERR_NO_DATA + || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER) + rc = gpg_error (GPG_ERR_NO_PUBKEY); + } + else + { + rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, + opt.keyserver); + } glo_ctrl.in_auto_key_retrieve--; } else { mechanism_string = "Unconfigured keyserver"; rc = GPG_ERR_NO_PUBKEY; } break; case AKL_SPEC: { struct keyserver_spec *keyserver; mechanism_string = akl->spec->uri; keyserver = keyserver_match (akl->spec); glo_ctrl.in_auto_key_retrieve++; - rc = keyserver_import_name (ctrl, - name, &fpr, &fpr_len, keyserver); + if (is_fpr) + { + rc = keyserver_import_fprint (ctrl, + fprbuf.u.fpr, fprbuf_fprlen, + opt.keyserver, + KEYSERVER_IMPORT_FLAG_LDAP); + if (gpg_err_code (rc) == GPG_ERR_NO_DATA + || gpg_err_code (rc) == GPG_ERR_NO_KEYSERVER) + rc = gpg_error (GPG_ERR_NO_PUBKEY); + } + else + { + 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) + if (!rc && (fpr || is_fpr)) { char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1]; - log_assert (fpr_len <= MAX_FINGERPRINT_LEN); - - free_strlist (namelist); - namelist = NULL; - - bin2hex (fpr, fpr_len, fpr_string); + if (is_fpr) + { + log_assert (fprbuf_fprlen <= MAX_FINGERPRINT_LEN); + bin2hex (fprbuf.u.fpr, fprbuf_fprlen, fpr_string); + } + else + { + log_assert (fpr_len <= MAX_FINGERPRINT_LEN); + bin2hex (fpr, fpr_len, fpr_string); + } if (opt.verbose) log_info ("auto-key-locate found fingerprint %s\n", fpr_string); + free_strlist (namelist); + namelist = NULL; add_to_strlist (&namelist, fpr_string); } else if (!rc && !fpr && !did_akl_local) { /* 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_akl_local) { /* 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 (ctrl, *retctx); *retctx = NULL; } rc = key_byname (ctrl, anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } if (!rc) { /* Key found. */ if (opt.verbose) log_info (_("automatically retrieved '%s' via %s\n"), name, mechanism_string); break; } if ((gpg_err_code (rc) != GPG_ERR_NO_PUBKEY || opt.verbose || no_fingerprint) && *mechanism_string) log_info (_("error retrieving '%s' via %s: %s\n"), name, mechanism_string, no_fingerprint ? _("No fingerprint") : gpg_strerror (rc)); } } if (rc && retctx) { getkey_end (ctrl, *retctx); *retctx = NULL; } if (retctx && *retctx) { log_assert (!(*retctx)->extra_list); (*retctx)->extra_list = namelist; (*retctx)->found_via_akl = mechanism_type; } else free_strlist (namelist); return rc; } /* Comparison machinery for get_best_pubkey_byname. */ /* First we have a struct to cache computed information about the key * in question. */ struct pubkey_cmp_cookie { int valid; /* Is this cookie valid? */ PKT_public_key key; /* The key. */ PKT_user_id *uid; /* The matching UID packet. */ unsigned int validity; /* Computed validity of (KEY, UID). */ u32 creation_time; /* Creation time of the newest subkey capable of encryption. */ }; /* Then we have a series of helper functions. */ static int key_is_ok (const PKT_public_key *key) { return (! key->has_expired && ! key->flags.revoked && key->flags.valid && ! key->flags.disabled); } static int uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid) { return key_is_ok (key) && ! uid->flags.revoked; } static int subkey_is_ok (const PKT_public_key *sub) { return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled; } /* Return true if KEYBLOCK has only expired encryption subkyes. Note * that the function returns false if the key has no encryption * subkeys at all or the subkeys are revoked. */ static int only_expired_enc_subkeys (kbnode_t keyblock) { kbnode_t node; PKT_public_key *sub; int any = 0; for (node = find_next_kbnode (keyblock, PKT_PUBLIC_SUBKEY); node; node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)) { sub = node->pkt->pkt.public_key; if (!(sub->pubkey_usage & PUBKEY_USAGE_ENC)) continue; if (!subkey_is_ok (sub)) continue; any = 1; if (!sub->has_expired) return 0; } return any? 1 : 0; } /* Finally this function compares a NEW key to the former candidate * OLD. Returns < 0 if the old key is worse, > 0 if the old key is * better, == 0 if it is a tie. */ static int pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old, struct pubkey_cmp_cookie *new, KBNODE new_keyblock) { kbnode_t n; new->creation_time = 0; for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY); n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY)) { PKT_public_key *sub = n->pkt->pkt.public_key; if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0) continue; if (! subkey_is_ok (sub)) continue; if (sub->timestamp > new->creation_time) new->creation_time = sub->timestamp; } for (n = find_next_kbnode (new_keyblock, PKT_USER_ID); n; n = find_next_kbnode (n, PKT_USER_ID)) { PKT_user_id *uid = n->pkt->pkt.user_id; char *mbox = mailbox_from_userid (uid->name); int match = mbox ? strcasecmp (name, mbox) == 0 : 0; xfree (mbox); if (! match) continue; new->uid = scopy_user_id (uid); new->validity = get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK; new->valid = 1; if (! old->valid) return -1; /* No OLD key. */ if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid)) return -1; /* Validity of the NEW key is better. */ if (old->validity < new->validity) return -1; /* Validity of the NEW key is better. */ if (old->validity == new->validity && uid_is_ok (&new->key, uid) && old->creation_time < new->creation_time) return -1; /* Both keys are of the same validity, but the NEW key is newer. */ } /* Stick with the OLD key. */ return 1; } /* This function works like get_pubkey_byname, but if the name * resembles a mail address, the results are ranked and only the best * result is returned. */ gpg_error_t get_best_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode, GETKEY_CTX *retctx, PKT_public_key *pk, const char *name, KBNODE *ret_keyblock, int include_unusable) { gpg_error_t err; struct getkey_ctx_s *ctx = NULL; int is_mbox; int wkd_tried = 0; if (retctx) *retctx = NULL; is_mbox = is_valid_mailbox (name); if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>' && name[1] != '>' && is_valid_mailbox_mem (name+1, strlen (name)-2)) { /* The mailbox is in the form "" which is not * detected by is_valid_mailbox. Set the flag but keep name as * it is because get_pubkey_byname does an is_valid_mailbox_mem * itself. */ is_mbox = 1; } start_over: if (ctx) /* Clear in case of a start over. */ { if (ret_keyblock) { release_kbnode (*ret_keyblock); *ret_keyblock = NULL; } getkey_end (ctrl, ctx); ctx = NULL; } err = get_pubkey_byname (ctrl, mode, &ctx, pk, name, ret_keyblock, NULL, include_unusable); if (err) { goto leave; } /* If the keyblock was retrieved from the local database and the key * has expired, do further checks. However, we can do this only if * the caller requested a keyblock. */ if (is_mbox && ctx && ctx->found_via_akl == AKL_LOCAL && ret_keyblock) { u32 now = make_timestamp (); PKT_public_key *pk2 = (*ret_keyblock)->pkt->pkt.public_key; int found; /* If the key has expired and its origin was the WKD then try to * get a fresh key from the WKD. We also try this if the key * has any only expired encryption subkeys. In case we checked * for a fresh copy in the last 3 hours we won't do that again. * Unfortunately that does not yet work because KEYUPDATE is * only updated during import iff the key has actually changed * (see import.c:import_one). */ if (!wkd_tried && pk2->keyorg == KEYORG_WKD && (pk2->keyupdate + 3*3600) < now && (pk2->has_expired || only_expired_enc_subkeys (*ret_keyblock))) { if (opt.verbose) log_info (_("checking for a fresh copy of an expired key via %s\n"), "WKD"); wkd_tried = 1; glo_ctrl.in_auto_key_retrieve++; found = !keyserver_import_wkd (ctrl, name, 0, NULL, NULL); glo_ctrl.in_auto_key_retrieve--; if (found) goto start_over; } } if (is_mbox && ctx) { /* Rank results and return only the most relevant key. */ struct pubkey_cmp_cookie best = { 0 }; struct pubkey_cmp_cookie new = { 0 }; kbnode_t new_keyblock; while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0) { int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock); release_kbnode (new_keyblock); if (diff < 0) { /* New key is better. */ release_public_key_parts (&best.key); free_user_id (best.uid); best = new; } else if (diff > 0) { /* Old key is better. */ release_public_key_parts (&new.key); free_user_id (new.uid); } else { /* A tie. Keep the old key. */ release_public_key_parts (&new.key); free_user_id (new.uid); } new.uid = NULL; } getkey_end (ctrl, ctx); ctx = NULL; free_user_id (best.uid); best.uid = NULL; if (best.valid) { if (retctx || ret_keyblock) { ctx = xtrycalloc (1, sizeof **retctx); if (! ctx) err = gpg_error_from_syserror (); else { ctx->kr_handle = keydb_new (); if (! ctx->kr_handle) { err = gpg_error_from_syserror (); xfree (ctx); ctx = NULL; if (retctx) *retctx = NULL; } else { u32 *keyid = pk_keyid (&best.key); ctx->exact = 1; 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]; if (ret_keyblock) { release_kbnode (*ret_keyblock); *ret_keyblock = NULL; err = getkey_next (ctrl, ctx, NULL, ret_keyblock); } } } } if (pk) { release_public_key_parts (pk); *pk = best.key; } else release_public_key_parts (&best.key); } } if (err && ctx) { getkey_end (ctrl, ctx); ctx = NULL; } if (retctx && ctx) { *retctx = ctx; ctx = NULL; } leave: getkey_end (ctrl, ctx); return err; } /* Get a public key from a file. * * PK is the buffer to store the key. The caller needs to make sure * that PK->REQ_USAGE is 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. * * FNAME is the file name. That file should contain exactly one * keyblock. * * This function returns 0 on success. Otherwise, an error code is * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key * is not found. * * The self-signed data has already been merged into the public key * using merge_selfsigs. The caller must release the content of PK by * calling release_public_key_parts (or, if PK was malloced, using * free_public_key). */ gpg_error_t get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname) { gpg_error_t err; kbnode_t keyblock; kbnode_t found_key; unsigned int infoflags; err = read_key_from_file_or_buffer (ctrl, fname, NULL, 0, &keyblock); if (!err) { /* Warning: node flag bits 0 and 1 should be preserved by * merge_selfsigs. FIXME: Check whether this still holds. */ merge_selfsigs (ctrl, keyblock); found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags); print_status_key_considered (keyblock, infoflags); if (found_key) pk_from_block (pk, keyblock, found_key); else err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY); } release_kbnode (keyblock); return err; } /* Return a public key from the buffer (BUFFER, BUFLEN). The key is * onlyretruned if it matches the keyid given in WANT_KEYID. On * success the key is stored at the caller provided PKBUF structure. * The caller must release the content of PK by calling * release_public_key_parts (or, if PKBUF was malloced, using * free_public_key). If R_KEYBLOCK is not NULL the full keyblock is * also stored there. */ gpg_error_t get_pubkey_from_buffer (ctrl_t ctrl, PKT_public_key *pkbuf, const void *buffer, size_t buflen, u32 *want_keyid, kbnode_t *r_keyblock) { gpg_error_t err; kbnode_t keyblock; kbnode_t node; PKT_public_key *pk; if (r_keyblock) *r_keyblock = NULL; err = read_key_from_file_or_buffer (ctrl, NULL, buffer, buflen, &keyblock); if (!err) { merge_selfsigs (ctrl, keyblock); for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { pk = node->pkt->pkt.public_key; keyid_from_pk (pk, NULL); if (pk->keyid[0] == want_keyid[0] && pk->keyid[1] == want_keyid[1]) break; } } if (node) copy_public_key (pkbuf, pk); else err = gpg_error (GPG_ERR_NO_PUBKEY); } if (!err && r_keyblock) *r_keyblock = keyblock; else release_kbnode (keyblock); return err; } /* 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. * * 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 (ctrl_t ctrl, 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; /* FIXME: We should get the handle from the cache like we do in * get_pubkey. */ 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); if (pk) ctx.req_usage = pk->req_usage; rc = lookup (ctrl, &ctx, 0, &kb, &found_key); if (!rc && pk) pk_from_block (pk, kb, found_key); if (!rc && r_keyblock) { *r_keyblock = kb; kb = NULL; } release_kbnode (kb); getkey_end (ctrl, &ctx); } else rc = GPG_ERR_GENERAL; /* Oops */ return rc; } /* 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. */ gpg_error_t get_pubkey_byfprint_fast (PKT_public_key * pk, const byte * fprint, size_t fprint_len) { gpg_error_t err; KBNODE keyblock; err = get_keyblock_byfprint_fast (&keyblock, NULL, fprint, fprint_len, 0); if (!err) { if (pk) copy_public_key (pk, keyblock->pkt->pkt.public_key); release_kbnode (keyblock); } return err; } /* This function is similar to get_pubkey_byfprint_fast but returns a * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or * R_HD may be NULL. If LOCK is set the handle has been opend in * locked mode and keydb_disable_caching () has been called. On error * R_KEYBLOCK is set to NULL but R_HD must be released by the caller; * it may have a value of NULL, though. This allows to do an insert * operation on a locked keydb handle. */ gpg_error_t get_keyblock_byfprint_fast (kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd, const byte *fprint, size_t fprint_len, int lock) { gpg_error_t err; KEYDB_HANDLE hd; kbnode_t keyblock; byte fprbuf[MAX_FINGERPRINT_LEN]; int i; if (r_keyblock) *r_keyblock = NULL; if (r_hd) *r_hd = NULL; 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 (); if (lock) { err = keydb_lock (hd); if (err) { /* If locking did not work, we better don't return a handle * at all - there was a reason that locking has been * requested. */ keydb_release (hd); return err; } keydb_disable_caching (hd); } /* Fo all other errors we return the handle. */ if (r_hd) *r_hd = hd; err = keydb_search_fpr (hd, fprbuf); if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) { if (!r_hd) keydb_release (hd); return gpg_error (GPG_ERR_NO_PUBKEY); } err = keydb_get_keyblock (hd, &keyblock); if (err) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err)); if (!r_hd) keydb_release (hd); return gpg_error (GPG_ERR_NO_PUBKEY); } log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY); /* Not caching key here since it won't have all of the fields properly set. */ if (r_keyblock) *r_keyblock = keyblock; else release_kbnode (keyblock); if (!r_hd) keydb_release (hd); 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 (ctrl, kb); err = gpg_error (GPG_ERR_NO_SECKEY); node = kb; do { PKT_public_key *pk = node->pkt->pkt.public_key; /* 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 && ! opt.quiet) 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; } /* 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) { 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 (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL); free_strlist (namelist); return err; } /* 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 (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk, strlist_t names, int want_secret, kbnode_t *ret_keyblock) { return key_byname (ctrl, retctx, names, pk, want_secret, 1, ret_keyblock, NULL); } /* Search for one key 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) { 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 (ctrl, 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; } /* 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 xmalloc, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire * found keyblock is returned which must be released with * release_kbnode. If the function returns an error NULL is stored at * RET_KEYBLOCK. * * The self-signed data has already been merged into the public key * using merge_selfsigs. */ gpg_error_t getkey_next (ctrl_t ctrl, getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock) { int rc; /* Fixme: Make sure this is proper gpg_error */ KBNODE keyblock = NULL; 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); /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the * caller wants PK, but not RET_KEYBLOCK, we need hand in our own * keyblock. */ if (pk && ret_keyblock == NULL) ret_keyblock = &keyblock; rc = lookup (ctrl, ctx, ctx->want_secret, ret_keyblock, pk ? &found_key : NULL); if (!rc && pk) { log_assert (found_key); pk_from_block (pk, NULL, found_key); release_kbnode (keyblock); } return rc; } /* Release any resources used by a key listing context. This must be * called on the context returned by, e.g., getkey_byname. */ void getkey_end (ctrl_t ctrl, getkey_ctx_t ctx) { if (ctx) { #ifdef HAVE_W32_SYSTEM /* FIXME: This creates a big regression for Windows because the * keyring is only released after the global ctrl is released. * So if an operation does a getkey and then tries to modify the * keyring it will fail on Windows with a sharing violation. We * need to modify all keyring write operations to also take the * ctrl and close the cached_getkey_kdb handle to make writing * work. See: GnuPG-bug-id: 3097 */ (void)ctrl; keydb_release (ctx->kr_handle); #else /*!HAVE_W32_SYSTEM*/ if (ctrl && !ctrl->cached_getkey_kdb) ctrl->cached_getkey_kdb = ctx->kr_handle; else keydb_release (ctx->kr_handle); #endif /*!HAVE_W32_SYSTEM*/ free_strlist (ctx->extra_list); if (!ctx->not_allocated) xfree (ctx); } } /************************************************ ************* Merging stuff ******************** ************************************************/ /* 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) { 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]; } } } /* 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 (ctrl_t ctrl, kbnode_t keyblock) { if (!keyblock) ; else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY) merge_selfsigs (ctrl, 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: * - wether 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, *aead, *hash, *zip; size_t n, nsym, naead, nhash, nzip; sig->flags.chosen_selfsig = 1;/* We chose this one. */ uid->created = 0; /* Not created == invalid. */ if (IS_UID_REV (sig)) { uid->flags.revoked = 1; return; /* Has been revoked. */ } else uid->flags.revoked = 0; uid->expiredate = sig->expiredate; if (sig->flags.expired) { uid->flags.expired = 1; return; /* Has expired. */ } else uid->flags.expired = 0; uid->created = sig->timestamp; /* This one is okay. */ uid->selfsigversion = sig->version; /* If we got this far, it's not expired :) */ uid->flags.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->flags.primary = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL); if (p && *p) uid->flags.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_AEAD, &n); aead = p; naead = 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 + naead + 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 (; naead; naead--, n++) { uid->prefs[n].type = PREFTYPE_AEAD; uid->prefs[n].value = *aead++; } 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; /* See whether we have the AEAD feature. */ uid->flags.aead = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n); if (p && n && (p[0] & 0x02)) uid->flags.aead = 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 (ctrl_t ctrl, kbnode_t 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; /* Creation time of the key. */ 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. Note that parse_keyblock_image ensures that the first packet is the public key. */ if (keyblock->pkt->pkttype != PKT_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. We do not support v3 keys anymore but * we keep the code in case a future key versions introduces a * hadr expire time again. */ 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 (ctrl, 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)); } /* SIGNODE is the direct key signature packet (sigclass 0x1f) with * the latest creation time. Extract some information from it. */ if (signode) { /* 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 (ctrl, 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. */ /* Fixme: 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. */ /* Apply the data from the most recent self-signed packet to * the preceding user id packet. */ if (uidnode && signode) { 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 (ctrl, keyblock, k, NULL)) ; /* signature did not verify */ else if ((IS_UID_SIG (sig) || IS_UID_REV (sig)) && sig->timestamp >= sigdate) { /* Note: we allow invalidation of 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 (ctrl, keyblock, k, ultimate_pk, NULL, NULL, NULL, NULL) == 0 && get_ownertrust (ctrl, 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 || (!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. * This may be a different one than from usage computation 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 || (!uid->created && !uiddate))) { key_expire = uid->help_key_expire; uiddate = uid->created; } } } } /* Currently only the not anymore supported v3 keys have a maximum * expiration date, but future key versions may 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->flags.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->flags.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->flags.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->flags.primary = 1; continue; } else { if (cmp_user_ids (k->pkt->pkt.user_id, uidnode->pkt->pkt.user_id) > 0) { uidnode->pkt->pkt.user_id->flags.primary = 0; uidnode = k; uidnode->pkt->pkt.user_id->flags.primary = 1; } else { /* just to be safe: */ k->pkt->pkt.user_id->flags.primary = 0; } } } } } } /* 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) { free_seckey_enc (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 (ctrl_t ctrl, kbnode_t keyblock, kbnode_t 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->flags.exact = 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 (ctrl, 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 (ctrl_t ctrl, kbnode_t keyblock) { KBNODE k; int revoked; struct revoke_info rinfo; PKT_public_key *main_pk; prefitem_t *prefs; unsigned int mdc_feature; unsigned int aead_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 (ctrl, 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 (ctrl, 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 = aead_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->flags.primary) { prefs = k->pkt->pkt.user_id->prefs; mdc_feature = k->pkt->pkt.user_id->flags.mdc; aead_feature = k->pkt->pkt.user_id->flags.aead; 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; pk->flags.aead = aead_feature; } } } /* See whether the key satisfies any additional requirements specified * in CTX. If so, return the node of an appropriate key or subkey. * Otherwise, return NULL if there was no appropriate key. * * Note that we do not return a reference, i.e. the result must not be * freed using 'release_kbnode'. * * In case the primary key is not required, select a suitable subkey. * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or * we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in * REQ_USAGE. * * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT * are set in 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 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. * * If R_FLAGS is not NULL set certain flags for more detailed error * reporting. Used flags are: * * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have * been revoked. * - LOOKUP_NOT_SELECTED :: No suitable key found * * 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 * FIXME * 4. Usage but no primary key requested * FIXME * */ static kbnode_t finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact, int want_secret, unsigned int *r_flags) { kbnode_t k; /* If WANT_EXACT is set, the key or subkey that actually matched the low-level search criteria. */ kbnode_t foundk = NULL; /* The user id (if any) that matched the low-level search criteria. */ PKT_user_id *foundu = NULL; u32 latest_date; kbnode_t latest_key; PKT_public_key *pk; int req_prim; u32 curtime = make_timestamp (); if (r_flags) *r_flags = 0; #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT) 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. */ req_prim = ((req_usage & PUBKEY_USAGE_CERT) || ((PGP6 || PGP7) && (req_usage & PUBKEY_USAGE_SIG))); log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY); /* For an exact match mark the primary or subkey that matched the low-level search criteria. */ if (want_exact) { for (k = keyblock; k; k = k->next) { if ((k->flag & 1)) { log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY); foundk = k; pk = k->pkt->pkt.public_key; pk->flags.exact = 1; break; } } } /* Get the user id that matched that low-level search criteria. */ for (k = keyblock; k; k = k->next) { if ((k->flag & 2)) { log_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_t nextk; int n_subkeys = 0; int n_revoked_or_expired = 0; /* Either start a loop or check just this one subkey. */ for (k = foundk ? foundk : keyblock; k; k = nextk) { 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->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; } n_subkeys++; if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("\tsubkey has been revoked\n"); n_revoked_or_expired++; continue; } if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("\tsubkey has expired\n"); n_revoked_or_expired++; continue; } if (pk->timestamp > curtime && !opt.ignore_valid_from) { if (DBG_LOOKUP) log_debug ("\tsubkey not yet valid\n"); continue; } if (want_secret && agent_probe_secret_key (NULL, pk)) { if (DBG_LOOKUP) log_debug ("\tno secret key\n"); 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; } } if (n_subkeys == n_revoked_or_expired && r_flags) *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED; } /* 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 && !want_exact) || foundk == keyblock || req_prim) { 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->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 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 /* Okay. */ { if (DBG_LOOKUP) log_debug ("\tprimary key may be used\n"); latest_key = keyblock; } } if (!latest_key) { if (DBG_LOOKUP) log_debug ("\tno suitable key found - giving up\n"); if (r_flags) *r_flags |= LOOKUP_NOT_SELECTED; 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) { pk = latest_key->pkt->pkt.public_key; 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. */ } /* Print a KEY_CONSIDERED status line. */ static void print_status_key_considered (kbnode_t keyblock, unsigned int flags) { char hexfpr[2*MAX_FINGERPRINT_LEN + 1]; kbnode_t node; char flagbuf[20]; if (!is_status_enabled ()) return; for (node=keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_SECRET_KEY) break; if (!node) { log_error ("%s: keyblock w/o primary key\n", __func__); return; } hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr); snprintf (flagbuf, sizeof flagbuf, " %u", flags); write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL); } /* 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, and the * specific subkey is stored at *RET_FOUND_KEY. Note that we do not * return a reference in *RET_FOUND_KEY, i.e. the result must not be * freed using 'release_kbnode', and it is only valid until * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not * NULL, then RET_KEYBLOCK must not be NULL. */ static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret, kbnode_t *ret_keyblock, kbnode_t *ret_found_key) { int rc; int no_suitable_key = 0; KBNODE keyblock = NULL; KBNODE found_key = NULL; unsigned int infoflags; log_assert (ret_found_key == NULL || ret_keyblock != NULL); if (ret_keyblock) *ret_keyblock = 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)); goto skip; } if (want_secret) { rc = agent_probe_any_secret_key (NULL, keyblock); if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY) goto skip; /* No secret key available. */ if (rc) goto found; /* Unexpected error. */ } /* Warning: node flag bits 0 and 1 should be preserved by * merge_selfsigs. */ merge_selfsigs (ctrl, keyblock); found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact, want_secret, &infoflags); print_status_key_considered (keyblock, infoflags); 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) { if (ret_keyblock) { *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; } /* If a default key has been specified, return that key. If a card * based key is also available as indicated by FPR_CARD not being * NULL, return that key if suitable. */ gpg_error_t get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk, const byte *fpr_card, size_t fpr_len) { gpg_error_t err; strlist_t namelist = NULL; const char *def_secret_key; def_secret_key = parse_def_secret_key (ctrl); if (def_secret_key) add_to_strlist (&namelist, def_secret_key); else if (fpr_card) { err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len); if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY) { if (opt.debug) log_debug ("using LDAP to find public key for current card\n"); err = keyserver_import_fprint (ctrl, fpr_card, fpr_len, opt.keyserver, KEYSERVER_IMPORT_FLAG_LDAP); if (!err) err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len); else if (gpg_err_code (err) == GPG_ERR_NO_DATA || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER) { /* Dirmngr returns NO DATA is the selected keyserver * does not have the requested key. It returns NO * KEYSERVER if no LDAP keyservers are configured. */ err = gpg_error (GPG_ERR_NO_PUBKEY); } } /* The key on card can be not suitable for requested usage. */ if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY) fpr_card = NULL; /* Fallthrough as no card. */ else return err; /* Success or other error. */ } if (!fpr_card || (def_secret_key && *def_secret_key && def_secret_key[strlen (def_secret_key)-1] == '!')) { err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL); } else { /* Default key is specified and card key is also available. */ kbnode_t k, keyblock = NULL; err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL); if (err) goto leave; for (k = keyblock; k; k = k->next) { PKT_public_key *pk_candidate; char fpr[MAX_FINGERPRINT_LEN]; if (k->pkt->pkttype != PKT_PUBLIC_KEY &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk_candidate = k->pkt->pkt.public_key; if (!pk_candidate->flags.valid) continue; if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage)) continue; fingerprint_from_pk (pk_candidate, fpr, NULL); if (!memcmp (fpr_card, fpr, fpr_len)) { release_public_key_parts (pk); copy_public_key (pk, pk_candidate); break; } } release_kbnode (keyblock); } leave: free_strlist (namelist); return err; } /********************************************* *********** User ID printing helpers ******* *********************************************/ /* Return a string with a printable representation of the user_id. * this string must be freed by xfree. If R_NOUID is not NULL it is * set to true if a user id was not found; otherwise to false. */ static char * get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode, size_t *r_len, int *r_nouid) { user_id_db_t r; keyid_list_t a; int pass = 0; char *p; if (r_nouid) *r_nouid = 0; /* 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 (ctrl, 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_nouid) *r_nouid = 1; if (r_len) *r_len = strlen (p); return p; } char * get_user_id_string_native (ctrl_t ctrl, u32 * keyid) { char *p = get_user_id_string (ctrl, keyid, 0, NULL, NULL); char *p2 = utf8_to_native (p, strlen (p), 0); xfree (p); return p2; } char * get_long_user_id_string (ctrl_t ctrl, u32 * keyid) { return get_user_id_string (ctrl, keyid, 1, NULL, NULL); } /* Please try to use get_user_byfpr instead of this one. */ char * get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid) { return get_user_id_string (ctrl, keyid, 2, rn, r_nouid); } /* Please try to use get_user_id_byfpr_native instead of this one. */ char * get_user_id_native (ctrl_t ctrl, u32 *keyid) { size_t rn; char *p = get_user_id (ctrl, keyid, &rn, NULL); 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 (ctrl_t ctrl, 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 (ctrl, 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 (ctrl_t ctrl, const byte *fpr) { size_t rn; char *p = get_user_id_byfpr (ctrl, fpr, &rn); char *p2 = utf8_to_native (p, rn, 0); xfree (p); return p2; } /* Return the database handle used by this context. The context still owns the handle. */ 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 true if the AKL is empty or has only the local method * active. */ int akl_empty_or_only_local (void) { struct akl *akl; int any = 0; for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL) { any = 1; break; } return !any; } /* Returns false on error. */ int parse_auto_key_locate (const char *options_arg) { char *tok; char *options, *options_buf; options = options_buf = xstrdup (options_arg); 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; else if (ascii_strcasecmp (tok, "cert") == 0) akl->type = AKL_CERT; else if (ascii_strcasecmp (tok, "pka") == 0) akl->type = AKL_PKA; else if (ascii_strcasecmp (tok, "dane") == 0) akl->type = AKL_DANE; else if (ascii_strcasecmp (tok, "wkd") == 0) akl->type = AKL_WKD; else if (ascii_strcasecmp (tok, "ntds") == 0) akl->type = AKL_NTDS; else if ((akl->spec = parse_keyserver_uri (tok, 1))) akl->type = AKL_SPEC; else { free_akl (akl); xfree (options_buf); 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; } } xfree (options_buf); return 1; } /* The list of key origins. */ static struct { const char *name; int origin; } key_origin_list[] = { { "self", KEYORG_SELF }, { "file", KEYORG_FILE }, { "url", KEYORG_URL }, { "wkd", KEYORG_WKD }, { "dane", KEYORG_DANE }, { "ks-pref", KEYORG_KS_PREF }, { "ks", KEYORG_KS }, { "unknown", KEYORG_UNKNOWN } }; /* Parse the argument for --key-origin. Return false on error. */ int parse_key_origin (char *string) { int i; char *comma; comma = strchr (string, ','); if (comma) *comma = 0; if (!ascii_strcasecmp (string, "help")) { log_info (_("valid values for option '%s':\n"), "--key-origin"); for (i=0; i < DIM (key_origin_list); i++) log_info (" %s\n", key_origin_list[i].name); g10_exit (1); } for (i=0; i < DIM (key_origin_list); i++) if (!ascii_strcasecmp (string, key_origin_list[i].name)) { opt.key_origin = key_origin_list[i].origin; xfree (opt.key_origin_url); opt.key_origin_url = NULL; if (comma && comma[1]) { opt.key_origin_url = xstrdup (comma+1); trim_spaces (opt.key_origin_url); } return 1; } if (comma) *comma = ','; return 0; } /* Return a string or "?" for the key ORIGIN. */ const char * key_origin_string (int origin) { int i; for (i=0; i < DIM (key_origin_list); i++) if (key_origin_list[i].origin == origin) return key_origin_list[i].name; return "?"; } /* 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)) { log_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/gpgv.c b/g10/gpgv.c index a788c67c4..3131ba904 100644 --- a/g10/gpgv.c +++ b/g10/gpgv.c @@ -1,822 +1,832 @@ /* gpgv.c - The GnuPG signature verify utility * Copyright (C) 1998-2020 Free Software Foundation, Inc. * Copyright (C) 1998-2019 Werner Koch * Copyright (C) 2015-2020 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #ifdef HAVE_DOSISH_SYSTEM #include /* for setmode() */ #endif #ifdef HAVE_LIBREADLINE #define GNUPG_LIBREADLINE_H_INCLUDED #include #endif #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "filter.h" #include "../common/ttyio.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/status.h" #include "call-agent.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oOutput = 'o', oBatch = 500, oKeyring, oIgnoreTimeConflict, oStatusFD, oLoggerFD, oLoggerFile, oHomedir, oWeakDigest, oEnableSpecialFilenames, oDebug, aTest }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_s (oKeyring, "keyring", N_("|FILE|take the keys from the keyring FILE")), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")), ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", N_("make timestamp conflicts only a warning")), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"), ARGPARSE_s_s (oLoggerFile, "log-file", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oWeakDigest, "weak-digest", N_("|ALGO|reject signatures made with ALGO")), ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"), ARGPARSE_s_s (oDebug, "debug", "@"), 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_IPC_VALUE , "ipc" }, { DBG_CLOCK_VALUE , "clock" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 0, NULL } }; int g10_errors_seen = 0; static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } static const char * my_strusage( int level ) { static char *ver_gcry; const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPG@v (GnuPG)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: gpgv [options] [files] (-h for help)"); break; case 41: p = _("Syntax: gpgv [options] [files]\n" "Check signatures against known trusted keys\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; default: p = NULL; } return p; } int main( int argc, char **argv ) { ARGPARSE_ARGS pargs; int rc=0; strlist_t sl; strlist_t nrings = NULL; ctrl_t ctrl; early_system_init (); set_strusage (my_strusage); log_set_prefix ("gpgv", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); gnupg_init_signals (0, NULL); opt.command_fd = -1; /* no command fd */ opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE; opt.trust_model = TM_ALWAYS; opt.no_sig_cache = 1; opt.flags.require_cross_cert = 1; opt.batch = 1; opt.answer_yes = 1; opt.weak_digests = NULL; tty_no_terminal(1); tty_batchmode(1); dotlock_disable (); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); additional_weak_digest("MD5"); gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG); pargs.argc = &argc; pargs.argv = &argv; pargs.flags= ARGPARSE_FLAG_KEEP; while (gnupg_argparser (&pargs, opts, NULL)) { switch (pargs.r_opt) { case ARGPARSE_CONFFILE: break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; opt.list_sigs=1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); 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 oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break; case oOutput: opt.outfile = pargs.r.ret_str; break; case oStatusFD: set_status_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFD: log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFile: log_set_file (pargs.r.ret_str); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID) ); break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oWeakDigest: additional_weak_digest(pargs.r.ret_str); break; case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break; case oEnableSpecialFilenames: enable_special_filenames (); break; default : pargs.err = ARGPARSE_PRINT_ERROR; break; } } gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount (0)) g10_exit(2); if (opt.verbose > 1) set_packet_list_mode(1); /* Note: We open all keyrings in read-only mode. */ if (!nrings) /* No keyring given: use default one. */ keydb_add_resource ("trustedkeys" EXTSEP_S "kbx", (KEYDB_RESOURCE_FLAG_READONLY |KEYDB_RESOURCE_FLAG_GPGVDEF)); for (sl = nrings; sl; sl = sl->next) keydb_add_resource (sl->d, KEYDB_RESOURCE_FLAG_READONLY); FREE_STRLIST (nrings); ctrl = xcalloc (1, sizeof *ctrl); if ((rc = verify_signatures (ctrl, argc, argv))) log_error("verify signatures failed: %s\n", gpg_strerror (rc) ); keydb_release (ctrl->cached_getkey_kdb); xfree (ctrl); /* cleanup */ g10_exit (0); return 8; /*NOTREACHED*/ } void g10_exit( int rc ) { rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit(rc ); } /* Stub: * We have to override the trustcheck from pkclist.c because * this utility assumes that all keys in the keyring are trustworthy */ int check_signatures_trust (ctrl_t ctrl, PKT_signature *sig) { (void)ctrl; (void)sig; return 0; } void read_trust_options (ctrl_t ctrl, byte *trust_model, ulong *created, ulong *nextcheck, byte *marginals, byte *completes, byte *cert_depth, byte *min_cert_level) { (void)ctrl; (void)trust_model; (void)created; (void)nextcheck; (void)marginals; (void)completes; (void)cert_depth; (void)min_cert_level; } /* Stub: * We don't have the trustdb , so we have to provide some stub functions * instead */ int cache_disabled_value (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } void check_trustdb_stale (ctrl_t ctrl) { (void)ctrl; } int get_validity_info (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid) { (void)ctrl; (void)kb; (void)pk; (void)uid; return '?'; } unsigned int get_validity (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid, PKT_signature *sig, int may_ask) { (void)ctrl; (void)kb; (void)pk; (void)uid; (void)sig; (void)may_ask; return 0; } const char * trust_value_to_string (unsigned int value) { (void)value; return "err"; } const char * uid_trust_string_fixed (ctrl_t ctrl, PKT_public_key *key, PKT_user_id *uid) { (void)ctrl; (void)key; (void)uid; return "err"; } int get_ownertrust_info (ctrl_t ctrl, PKT_public_key *pk, int no_create) { (void)ctrl; (void)pk; (void)no_create; return '?'; } unsigned int get_ownertrust (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return TRUST_UNKNOWN; } /* Stubs: * Because we only work with trusted keys, it does not make sense to * get them from a keyserver */ struct keyserver_spec * keyserver_match (struct keyserver_spec *spec) { (void)spec; return NULL; } int keyserver_any_configured (ctrl_t ctrl) { (void)ctrl; return 0; } int keyserver_import_keyid (u32 *keyid, void *dummy, unsigned int flags) { (void)keyid; (void)dummy; (void)flags; return -1; } int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, struct keyserver_spec *keyserver, unsigned int flags) { (void)ctrl; (void)fprint; (void)fprint_len; (void)keyserver; (void)flags; return -1; } +int +keyserver_import_fprint_ntds (ctrl_t ctrl, + const byte *fprint, size_t fprint_len) +{ + (void)ctrl; + (void)fprint; + (void)fprint_len; + return -1; +} + int keyserver_import_cert (const char *name) { (void)name; return -1; } int keyserver_import_pka (const char *name,unsigned char *fpr) { (void)name; (void)fpr; return -1; } gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { (void)ctrl; (void)name; (void)flags; (void)fpr; (void)fpr_len; return GPG_ERR_BUG; } int keyserver_import_name (const char *name,struct keyserver_spec *spec) { (void)name; (void)spec; return -1; } int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)mbox; (void)fpr; (void)fprlen; return -1; } int keyserver_import_ldap (const char *name) { (void)name; return -1; } gpg_error_t read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname, const void *buffer, size_t buflen, kbnode_t *r_keyblock) { (void)ctrl; (void)fname; (void)buffer; (void)buflen; (void)r_keyblock; return -1; } gpg_error_t import_included_key_block (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return -1; } /* Stub: * No encryption here but mainproc links to these functions. */ gpg_error_t get_session_key (ctrl_t ctrl, PKT_pubkey_enc *k, DEK *dek) { (void)ctrl; (void)k; (void)dek; return GPG_ERR_GENERAL; } /* Stub: */ gpg_error_t get_override_session_key (DEK *dek, const char *string) { (void)dek; (void)string; return GPG_ERR_GENERAL; } /* Stub: */ int decrypt_data (ctrl_t ctrl, void *procctx, PKT_encrypted *ed, DEK *dek) { (void)ctrl; (void)procctx; (void)ed; (void)dek; return GPG_ERR_GENERAL; } /* Stub: * No interactive commands, so we don't need the helptexts */ void display_online_help (const char *keyword) { (void)keyword; } /* Stub: * We don't use secret keys, but getkey.c links to this */ int check_secret_key (PKT_public_key *pk, int n) { (void)pk; (void)n; return GPG_ERR_GENERAL; } /* Stub: * No secret key, so no passphrase needed */ DEK * passphrase_to_dek (int cipher_algo, STRING2KEY *s2k, int create, int nocache, const char *tmp, int *canceled) { (void)cipher_algo; (void)s2k; (void)create; (void)nocache; (void)tmp; if (canceled) *canceled = 0; return NULL; } void passphrase_clear_cache (const char *cacheid) { (void)cacheid; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { (void)sig; return NULL; } struct keyserver_spec * parse_keyserver_uri (const char *uri, int require_scheme, const char *configname, unsigned int configlineno) { (void)uri; (void)require_scheme; (void)configname; (void)configlineno; return NULL; } void free_keyserver_spec (struct keyserver_spec *keyserver) { (void)keyserver; } /* Stubs to avoid linking to photoid.c */ void show_photos (const struct user_attribute *attrs, int count, PKT_public_key *pk) { (void)attrs; (void)count; (void)pk; } int parse_image_header (const struct user_attribute *attr, byte *type, u32 *len) { (void)attr; (void)type; (void)len; return 0; } char * image_type_to_string (byte type, int string) { (void)type; (void)string; return NULL; } #ifdef ENABLE_CARD_SUPPORT int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { (void)name; (void)info; return 0; } #endif /* ENABLE_CARD_SUPPORT */ /* We do not do any locking, so use these stubs here */ void dotlock_disable (void) { } dotlock_t dotlock_create (const char *file_to_lock, unsigned int flags) { (void)file_to_lock; (void)flags; return NULL; } void dotlock_destroy (dotlock_t h) { (void)h; } int dotlock_take (dotlock_t h, long timeout) { (void)h; (void)timeout; return 0; } int dotlock_release (dotlock_t h) { (void)h; return 0; } void dotlock_remove_lockfiles (void) { } gpg_error_t agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { (void)ctrl; (void)hexkeygrip; (void)r_cleartext; *r_serialno = NULL; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t gpg_dirmngr_get_pka (ctrl_t ctrl, const char *userid, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { (void)ctrl; (void)userid; if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; return gpg_error (GPG_ERR_NOT_FOUND); } gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, const void *prefix, size_t prefixlen, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen) { (void)ctrl; (void)keyspec; (void)options; (void)prefix; (void)prefixlen; (void)stats; *r_keyblock = NULL; *r_data = NULL; *r_datalen = 0; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } gpg_error_t tofu_write_tfs_record (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, const char *user_id) { (void)ctrl; (void)fp; (void)pk; (void)user_id; return gpg_error (GPG_ERR_GENERAL); } gpg_error_t tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id, enum tofu_policy *policy) { (void)ctrl; (void)pk; (void)user_id; (void)policy; return gpg_error (GPG_ERR_GENERAL); } const char * tofu_policy_str (enum tofu_policy policy) { (void)policy; return "unknown"; } void tofu_begin_batch_update (ctrl_t ctrl) { (void)ctrl; } void tofu_end_batch_update (ctrl_t ctrl) { (void)ctrl; } gpg_error_t tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb) { (void) ctrl; (void) kb; return 0; } int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen) { (void)sig; (void)r_commentlen; if (r_reason) *r_reason = NULL; if (r_comment) *r_comment = NULL; return 0; } diff --git a/g10/keyserver-internal.h b/g10/keyserver-internal.h index 4439468c0..d1fb682a2 100644 --- a/g10/keyserver-internal.h +++ b/g10/keyserver-internal.h @@ -1,65 +1,67 @@ /* keyserver-internal.h - Keyserver internals * Copyright (C) 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef _KEYSERVER_INTERNAL_H_ #define _KEYSERVER_INTERNAL_H_ #include #include "../common/keyserver.h" #include "../common/iobuf.h" #include "../common/types.h" /* Flags for the keyserver import functions. */ #define KEYSERVER_IMPORT_FLAG_QUICK 1 #define KEYSERVER_IMPORT_FLAG_LDAP 2 int parse_keyserver_options(char *options); void free_keyserver_spec(struct keyserver_spec *keyserver); struct keyserver_spec *keyserver_match(struct keyserver_spec *spec); struct keyserver_spec *parse_keyserver_uri (const char *string, int require_scheme); struct keyserver_spec *parse_preferred_keyserver(PKT_signature *sig); int keyserver_any_configured (ctrl_t ctrl); int keyserver_export (ctrl_t ctrl, strlist_t users); int keyserver_import (ctrl_t ctrl, strlist_t users); int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, struct keyserver_spec *keyserver, unsigned int flags); +int keyserver_import_fprint_ntds (ctrl_t ctrl, + const byte *fprint, size_t fprint_len); int keyserver_import_keyid (ctrl_t ctrl, u32 *keyid, struct keyserver_spec *keyserver, unsigned int flags); gpg_error_t keyserver_refresh (ctrl_t ctrl, strlist_t users); gpg_error_t keyserver_search (ctrl_t ctrl, strlist_t tokens); int keyserver_fetch (ctrl_t ctrl, strlist_t urilist, int origin); int keyserver_import_cert (ctrl_t ctrl, const char *name, int dane_mode, unsigned char **fpr,size_t *fpr_len); gpg_error_t keyserver_import_pka (ctrl_t ctrl, const char *name, unsigned char **fpr,size_t *fpr_len); gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len); int keyserver_import_ntds (ctrl_t ctrl, const char *name, unsigned char **fpr,size_t *fpr_len); int keyserver_import_name (ctrl_t ctrl, const char *name,unsigned char **fpr,size_t *fpr_len, struct keyserver_spec *keyserver); int keyserver_import_ldap (ctrl_t ctrl, const char *name, unsigned char **fpr,size_t *fpr_len); #endif /* !_KEYSERVER_INTERNAL_H_ */ diff --git a/g10/keyserver.c b/g10/keyserver.c index 7bbfe97ec..c5e70601d 100644 --- a/g10/keyserver.c +++ b/g10/keyserver.c @@ -1,2232 +1,2242 @@ /* keyserver.c - generic keyserver code * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, * 2009, 2011, 2012 Free Software Foundation, Inc. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "../common/iobuf.h" #include "filter.h" #include "keydb.h" #include "../common/status.h" #include "exec.h" #include "main.h" #include "../common/i18n.h" #include "../common/ttyio.h" #include "options.h" #include "packet.h" #include "trustdb.h" #include "keyserver-internal.h" #include "../common/util.h" #include "../common/membuf.h" #include "../common/mbox-util.h" #include "call-dirmngr.h" #ifdef HAVE_W32_SYSTEM /* It seems Vista doesn't grok X_OK and so fails access() tests. Previous versions interpreted X_OK as F_OK anyway, so we'll just use F_OK directly. */ #undef X_OK #define X_OK F_OK #endif /* HAVE_W32_SYSTEM */ struct keyrec { KEYDB_SEARCH_DESC desc; u32 createtime,expiretime; int size,flags; byte type; IOBUF uidbuf; unsigned int lines; }; /* Parameters for the search line handler. */ struct search_line_handler_parm_s { ctrl_t ctrl; /* The session control structure. */ char *searchstr_disp; /* Native encoded search string or NULL. */ KEYDB_SEARCH_DESC *desc; /* Array with search descriptions. */ int count; /* Number of keys we are currently prepared to handle. This is the size of the DESC array. If it is too small, it will grow safely. */ int validcount; /* Enable the "Key x-y of z" messages. */ int nkeys; /* Number of processed records. */ int any_lines; /* At least one line has been processed. */ unsigned int numlines; /* Counter for displayed lines. */ int eof_seen; /* EOF encountered. */ int not_found; /* Set if no keys have been found. */ }; enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH}; static struct parse_options keyserver_opts[]= { /* some of these options are not real - just for the help message */ {"max-cert-size",0,NULL,NULL}, /* MUST be the first in this array! */ {"http-proxy", KEYSERVER_HTTP_PROXY, NULL, /* MUST be the second! */ N_("override proxy options set for dirmngr")}, {"include-revoked",0,NULL,N_("include revoked keys in search results")}, {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")}, {"timeout", KEYSERVER_TIMEOUT, NULL, N_("override timeout options set for dirmngr")}, {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL, NULL}, {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL, N_("automatically retrieve keys when verifying signatures")}, {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL, N_("honor the preferred keyserver URL set on the key")}, {"honor-pka-record",KEYSERVER_HONOR_PKA_RECORD,NULL, N_("honor the PKA record set on a key when retrieving keys")}, {NULL,0,NULL,NULL} }; static gpg_error_t keyserver_get (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, struct keyserver_spec *override_keyserver, unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen); static gpg_error_t keyserver_put (ctrl_t ctrl, strlist_t keyspecs); /* Reasonable guess. The commonly used test key simon.josefsson.org is larger than 32k, thus we need at least this value. */ #define DEFAULT_MAX_CERT_SIZE 65536 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE; static void warn_kshelper_option(char *option, int noisy) { char *p; if ((p=strchr (option, '='))) *p = 0; if (!strcmp (option, "ca-cert-file")) log_info ("keyserver option '%s' is obsolete; please use " "'%s' in dirmngr.conf\n", "ca-cert-file", "hkp-cacert"); else if (!strcmp (option, "check-cert") || !strcmp (option, "broken-http-proxy")) log_info ("keyserver option '%s' is obsolete\n", option); else if (noisy || opt.verbose) log_info ("keyserver option '%s' is unknown\n", option); } /* Called from main to parse the args for --keyserver-options. */ int parse_keyserver_options(char *options) { int ret=1; char *tok; char *max_cert=NULL; keyserver_opts[0].value=&max_cert; keyserver_opts[1].value=&opt.keyserver_options.http_proxy; while((tok=optsep(&options))) { if(tok[0]=='\0') continue; /* We accept quite a few possible options here - some options to handle specially, the keyserver_options list, and import and export options that pertain to keyserver operations. */ if (!parse_options (tok,&opt.keyserver_options.options, keyserver_opts,0) && !parse_import_options(tok,&opt.keyserver_options.import_options,0) && !parse_export_options(tok,&opt.keyserver_options.export_options,0)) { /* All of the standard options have failed, so the option was destined for a keyserver plugin as used by GnuPG < 2.1 */ warn_kshelper_option (tok, 1); } } if(max_cert) { max_cert_size=strtoul(max_cert,(char **)NULL,10); if(max_cert_size==0) max_cert_size=DEFAULT_MAX_CERT_SIZE; } return ret; } void free_keyserver_spec(struct keyserver_spec *keyserver) { xfree(keyserver->uri); xfree(keyserver->scheme); xfree(keyserver->auth); xfree(keyserver->host); xfree(keyserver->port); xfree(keyserver->path); xfree(keyserver->opaque); free_strlist(keyserver->options); xfree(keyserver); } /* Return 0 for match */ static int cmp_keyserver_spec(struct keyserver_spec *one,struct keyserver_spec *two) { if(ascii_strcasecmp(one->scheme,two->scheme)==0) { if(one->host && two->host && ascii_strcasecmp(one->host,two->host)==0) { if((one->port && two->port && ascii_strcasecmp(one->port,two->port)==0) || (!one->port && !two->port)) return 0; } else if(one->opaque && two->opaque && ascii_strcasecmp(one->opaque,two->opaque)==0) return 0; } return 1; } /* Try and match one of our keyservers. If we can, return that. If we can't, return our input. */ struct keyserver_spec * keyserver_match(struct keyserver_spec *spec) { struct keyserver_spec *ks; for(ks=opt.keyserver;ks;ks=ks->next) if(cmp_keyserver_spec(spec,ks)==0) return ks; return spec; } /* TODO: once we cut over to an all-curl world, we don't need this parser any longer so it can be removed, or at least moved to keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */ keyserver_spec_t parse_keyserver_uri (const char *string,int require_scheme) { int assume_hkp=0; struct keyserver_spec *keyserver; const char *idx; int count; char *uri, *duped_uri, *options; log_assert (string); keyserver=xmalloc_clear(sizeof(struct keyserver_spec)); duped_uri = uri = xstrdup (string); options=strchr(uri,' '); if(options) { char *tok; *options='\0'; options++; while((tok=optsep(&options))) warn_kshelper_option (tok, 0); } /* Get the scheme */ for(idx=uri,count=0;*idx && *idx!=':';idx++) { count++; /* Do we see the start of an RFC-2732 ipv6 address here? If so, there clearly isn't a scheme so get out early. */ if(*idx=='[') { /* Was the '[' the first thing in the string? If not, we have a mangled scheme with a [ in it so fail. */ if(count==1) break; else goto fail; } } if(count==0) goto fail; if(*idx=='\0' || *idx=='[') { if(require_scheme) return NULL; /* Assume HKP if there is no scheme */ assume_hkp=1; keyserver->scheme=xstrdup("hkp"); keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1); strcpy(keyserver->uri,keyserver->scheme); strcat(keyserver->uri,"://"); strcat(keyserver->uri,uri); } else { int i; keyserver->uri=xstrdup(uri); keyserver->scheme=xmalloc(count+1); /* Force to lowercase */ for(i=0;ischeme[i]=ascii_tolower(uri[i]); keyserver->scheme[i]='\0'; /* Skip past the scheme and colon */ uri+=count+1; } if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0) { log_info ("keyserver option '%s' is obsolete\n", "x-broken-hkp"); } else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0) { /* Canonicalize this to "hkp" so it works with both the internal and external keyserver interface. */ xfree(keyserver->scheme); keyserver->scheme=xstrdup("hkp"); } if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/') { /* Three slashes means network path with a default host name. This is a hack because it does not crok all possible combinations. We should better replace all code by the parser from http.c. */ keyserver->path = xstrdup (uri+2); } else if(assume_hkp || (uri[0]=='/' && uri[1]=='/')) { /* Two slashes means network path. */ /* Skip over the "//", if any */ if(!assume_hkp) uri+=2; /* Do we have userinfo auth data present? */ for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++) count++; /* We found a @ before the slash, so that means everything before the @ is auth data. */ if(*idx=='@') { if(count==0) goto fail; keyserver->auth=xmalloc(count+1); strncpy(keyserver->auth,uri,count); keyserver->auth[count]='\0'; uri+=count+1; } /* Is it an RFC-2732 ipv6 [literal address] ? */ if(*uri=='[') { for(idx=uri+1,count=1;*idx && ((isascii (*idx) && isxdigit(*idx)) || *idx==':' || *idx=='.');idx++) count++; /* Is the ipv6 literal address terminated? */ if(*idx==']') count++; else goto fail; } else for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++) count++; if(count==0) goto fail; keyserver->host=xmalloc(count+1); strncpy(keyserver->host,uri,count); keyserver->host[count]='\0'; /* Skip past the host */ uri+=count; if(*uri==':') { /* It would seem to be reasonable to limit the range of the ports to values between 1-65535, but RFC 1738 and 1808 imply there is no limit. Of course, the real world has limits. */ for(idx=uri+1,count=0;*idx && *idx!='/';idx++) { count++; /* Ports are digits only */ if(!digitp(idx)) goto fail; } keyserver->port=xmalloc(count+1); strncpy(keyserver->port,uri+1,count); keyserver->port[count]='\0'; /* Skip past the colon and port number */ uri+=1+count; } /* Everything else is the path */ if(*uri) keyserver->path=xstrdup(uri); else keyserver->path=xstrdup("/"); if(keyserver->path[1]) keyserver->flags.direct_uri=1; } else if(uri[0]!='/') { /* No slash means opaque. Just record the opaque blob and get out. */ keyserver->opaque=xstrdup(uri); } else { /* One slash means absolute path. We don't need to support that yet. */ goto fail; } xfree (duped_uri); return keyserver; fail: free_keyserver_spec(keyserver); xfree (duped_uri); return NULL; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { struct keyserver_spec *spec=NULL; const byte *p; size_t plen; p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen); if(p && plen) { byte *dupe=xmalloc(plen+1); memcpy(dupe,p,plen); dupe[plen]='\0'; spec = parse_keyserver_uri (dupe, 1); xfree(dupe); } return spec; } static void print_keyrec (ctrl_t ctrl, int number,struct keyrec *keyrec) { int i; iobuf_writebyte(keyrec->uidbuf,0); iobuf_flush_temp(keyrec->uidbuf); es_printf ("(%d)\t%s ", number, iobuf_get_temp_buffer (keyrec->uidbuf)); if (keyrec->size>0) es_printf ("%d bit ", keyrec->size); if(keyrec->type) { const char *str; str = openpgp_pk_algo_name (keyrec->type); if (str && strcmp (str, "?")) es_printf ("%s ",str); else es_printf ("unknown "); } switch(keyrec->desc.mode) { /* If the keyserver helper gave us a short keyid, we have no choice but to use it. Do check --keyid-format to add a 0x if needed. */ case KEYDB_SEARCH_MODE_SHORT_KID: es_printf ("key %s%08lX", (opt.keyid_format==KF_0xSHORT || opt.keyid_format==KF_0xLONG)?"0x":"", (ulong)keyrec->desc.u.kid[1]); break; /* However, if it gave us a long keyid, we can honor --keyid-format via keystr(). */ case KEYDB_SEARCH_MODE_LONG_KID: es_printf ("key %s",keystr(keyrec->desc.u.kid)); break; /* If it gave us a PGP 2.x fingerprint, not much we can do beyond displaying it. */ case KEYDB_SEARCH_MODE_FPR16: es_printf ("key "); for(i=0;i<16;i++) es_printf ("%02X",keyrec->desc.u.fpr[i]); break; /* If we get a modern fingerprint, we have the most flexibility. */ case KEYDB_SEARCH_MODE_FPR20: { u32 kid[2]; keyid_from_fingerprint (ctrl, keyrec->desc.u.fpr,20,kid); es_printf("key %s",keystr(kid)); } break; default: BUG(); break; } if(keyrec->createtime>0) { es_printf (", "); es_printf (_("created: %s"), strtimestamp(keyrec->createtime)); } if(keyrec->expiretime>0) { es_printf (", "); es_printf (_("expires: %s"), strtimestamp(keyrec->expiretime)); } if (keyrec->flags&1) es_printf (" (%s)", _("revoked")); if(keyrec->flags&2) es_printf (" (%s)", _("disabled")); if(keyrec->flags&4) es_printf (" (%s)", _("expired")); es_printf ("\n"); } /* Returns a keyrec (which must be freed) once a key is complete, and NULL otherwise. Call with a NULL keystring once key parsing is complete to return any unfinished keys. */ static struct keyrec * parse_keyrec(char *keystring) { /* FIXME: Remove the static and put the data into the parms we use for the caller anyway. */ static struct keyrec *work=NULL; struct keyrec *ret=NULL; char *record; int i; if(keystring==NULL) { if(work==NULL) return NULL; else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE) { xfree(work); return NULL; } else { ret=work; work=NULL; return ret; } } if(work==NULL) { work=xmalloc_clear(sizeof(struct keyrec)); work->uidbuf=iobuf_temp(); } trim_trailing_ws (keystring, strlen (keystring)); if((record=strsep(&keystring,":"))==NULL) return ret; if(ascii_strcasecmp("pub",record)==0) { char *tok; gpg_error_t err; if(work->desc.mode) { ret=work; work=xmalloc_clear(sizeof(struct keyrec)); work->uidbuf=iobuf_temp(); } if((tok=strsep(&keystring,":"))==NULL) return ret; err = classify_user_id (tok, &work->desc, 1); if (err || (work->desc.mode != KEYDB_SEARCH_MODE_SHORT_KID && work->desc.mode != KEYDB_SEARCH_MODE_LONG_KID && work->desc.mode != KEYDB_SEARCH_MODE_FPR16 && work->desc.mode != KEYDB_SEARCH_MODE_FPR20)) { work->desc.mode=KEYDB_SEARCH_MODE_NONE; return ret; } /* Note all items after this are optional. This allows us to have a pub line as simple as pub:keyid and nothing else. */ work->lines++; if((tok=strsep(&keystring,":"))==NULL) return ret; work->type=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; work->size=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; if(atoi(tok)<=0) work->createtime=0; else work->createtime=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; if(atoi(tok)<=0) work->expiretime=0; else { work->expiretime=atoi(tok); /* Force the 'e' flag on if this key is expired. */ if(work->expiretime<=make_timestamp()) work->flags|=4; } if((tok=strsep(&keystring,":"))==NULL) return ret; while(*tok) switch(*tok++) { case 'r': case 'R': work->flags|=1; break; case 'd': case 'D': work->flags|=2; break; case 'e': case 'E': work->flags|=4; break; } } else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode) { char *userid,*tok,*decoded; if((tok=strsep(&keystring,":"))==NULL) return ret; if(strlen(tok)==0) return ret; userid=tok; /* By definition, de-%-encoding is always smaller than the original string so we can decode in place. */ i=0; while(*tok) if(tok[0]=='%' && tok[1] && tok[2]) { int c; userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c; i++; tok+=3; } else userid[i++]=*tok++; /* We don't care about the other info provided in the uid: line since no keyserver supports marking userids with timestamps or revoked/expired/disabled yet. */ /* No need to check for control characters, as utf8_to_native does this for us. */ decoded=utf8_to_native(userid,i,0); if(strlen(decoded)>opt.screen_columns-10) decoded[opt.screen_columns-10]='\0'; iobuf_writestr(work->uidbuf,decoded); xfree(decoded); iobuf_writestr(work->uidbuf,"\n\t"); work->lines++; } /* Ignore any records other than "pri" and "uid" for easy future growth. */ return ret; } /* Show a prompt and allow the user to select keys for retrieval. */ static gpg_error_t show_prompt (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int numdesc, int count, const char *search) { gpg_error_t err; char *answer = NULL; es_fflush (es_stdout); if (count && opt.command_fd == -1) { static int from = 1; tty_printf ("Keys %d-%d of %d for \"%s\". ", from, numdesc, count, search); from = numdesc + 1; } again: err = 0; xfree (answer); answer = cpr_get_no_help ("keysearch.prompt", _("Enter number(s), N)ext, or Q)uit > ")); /* control-d */ if (answer[0]=='\x04') { tty_printf ("Q\n"); answer[0] = 'q'; } if (answer[0]=='q' || answer[0]=='Q') err = gpg_error (GPG_ERR_CANCELED); else if (atoi (answer) >= 1 && atoi (answer) <= numdesc) { char *split = answer; char *num; int numarray[50]; int numidx = 0; int idx; while ((num = strsep (&split, " ,"))) if (atoi (num) >= 1 && atoi (num) <= numdesc) { if (numidx >= DIM (numarray)) { tty_printf ("Too many keys selected\n"); goto again; } numarray[numidx++] = atoi (num); } if (!numidx) goto again; { KEYDB_SEARCH_DESC *selarray; selarray = xtrymalloc (numidx * sizeof *selarray); if (!selarray) { err = gpg_error_from_syserror (); goto leave; } for (idx = 0; idx < numidx; idx++) selarray[idx] = desc[numarray[idx]-1]; err = keyserver_get (ctrl, selarray, numidx, NULL, 0, NULL, NULL); xfree (selarray); } } leave: xfree (answer); return err; } /* This is a callback used by call-dirmngr.c to process the result of KS_SEARCH command. If SPECIAL is 0, LINE is the actual data line received with all escaping removed and guaranteed to be exactly one line with stripped LF; an EOF is indicated by LINE passed as NULL. If special is 1, the line contains the source of the information (usually an URL). LINE may be modified after return. */ static gpg_error_t search_line_handler (void *opaque, int special, char *line) { struct search_line_handler_parm_s *parm = opaque; gpg_error_t err = 0; struct keyrec *keyrec; if (special == 1) { log_info ("data source: %s\n", line); return 0; } else if (special) { log_debug ("unknown value %d for special search callback", special); return 0; } if (parm->eof_seen && line) { log_debug ("ooops: unexpected data after EOF\n"); line = NULL; } /* Print the received line. */ if (opt.with_colons && line) { es_printf ("%s\n", line); } /* Look for an info: line. The only current info: values defined are the version and key count. */ if (line && !parm->any_lines && !ascii_strncasecmp ("info:", line, 5)) { char *str = line + 5; char *tok; if ((tok = strsep (&str, ":"))) { int version; if (sscanf (tok, "%d", &version) !=1 ) version = 1; if (version !=1 ) { log_error (_("invalid keyserver protocol " "(us %d!=handler %d)\n"), 1, version); return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL); } } if ((tok = strsep (&str, ":")) && sscanf (tok, "%d", &parm->count) == 1) { if (!parm->count) parm->not_found = 1;/* Server indicated that no items follow. */ else if (parm->count < 0) parm->count = 10; /* Bad value - assume something reasonable. */ else parm->validcount = 1; /* COUNT seems to be okay. */ } parm->any_lines = 1; return 0; /* Line processing finished. */ } again: if (line) keyrec = parse_keyrec (line); else { /* Received EOF - flush data */ parm->eof_seen = 1; keyrec = parse_keyrec (NULL); if (!keyrec) { if (!parm->nkeys) parm->not_found = 1; /* No keys at all. */ else { if (parm->nkeys != parm->count) parm->validcount = 0; if (!(opt.with_colons && opt.batch)) { err = show_prompt (parm->ctrl, parm->desc, parm->nkeys, parm->validcount? parm->count : 0, parm->searchstr_disp); return err; } } } } /* Save the key in the key array. */ if (keyrec) { /* Allocate or enlarge the key array if needed. */ if (!parm->desc) { if (parm->count < 1) { parm->count = 10; parm->validcount = 0; } parm->desc = xtrymalloc (parm->count * sizeof *parm->desc); if (!parm->desc) { err = gpg_error_from_syserror (); iobuf_close (keyrec->uidbuf); xfree (keyrec); return err; } } else if (parm->nkeys == parm->count) { /* Keyserver sent more keys than claimed in the info: line. */ KEYDB_SEARCH_DESC *tmp; int newcount = parm->count + 10; tmp = xtryrealloc (parm->desc, newcount * sizeof *parm->desc); if (!tmp) { err = gpg_error_from_syserror (); iobuf_close (keyrec->uidbuf); xfree (keyrec); return err; } parm->count = newcount; parm->desc = tmp; parm->validcount = 0; } parm->desc[parm->nkeys] = keyrec->desc; if (!opt.with_colons) { /* SCREEN_LINES - 1 for the prompt. */ if (parm->numlines + keyrec->lines > opt.screen_lines - 1) { err = show_prompt (parm->ctrl, parm->desc, parm->nkeys, parm->validcount ? parm->count:0, parm->searchstr_disp); if (err) return err; parm->numlines = 0; } print_keyrec (parm->ctrl, parm->nkeys+1, keyrec); } parm->numlines += keyrec->lines; iobuf_close (keyrec->uidbuf); xfree (keyrec); parm->any_lines = 1; parm->nkeys++; /* If we are here due to a flush after the EOF, run again for the last prompt. Fixme: Make this code better readable. */ if (parm->eof_seen) goto again; } return 0; } int keyserver_export (ctrl_t ctrl, strlist_t users) { gpg_error_t err; strlist_t sl=NULL; KEYDB_SEARCH_DESC desc; int rc=0; /* Weed out descriptors that we don't support sending */ for(;users;users=users->next) { err = classify_user_id (users->d, &desc, 1); if (err || (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)) { log_error(_("\"%s\" not a key ID: skipping\n"),users->d); continue; } else append_to_strlist(&sl,users->d); } if(sl) { rc = keyserver_put (ctrl, sl); free_strlist(sl); } return rc; } /* Structure to convey the arg to keyserver_retrieval_screener. */ struct ks_retrieval_screener_arg_s { KEYDB_SEARCH_DESC *desc; int ndesc; }; /* Check whether a key matches the search description. The function returns 0 if the key shall be imported. */ static gpg_error_t keyserver_retrieval_screener (kbnode_t keyblock, void *opaque) { struct ks_retrieval_screener_arg_s *arg = opaque; KEYDB_SEARCH_DESC *desc = arg->desc; int ndesc = arg->ndesc; kbnode_t node; PKT_public_key *pk; int n; u32 keyid[2]; byte fpr[MAX_FINGERPRINT_LEN]; size_t fpr_len = 0; /* Secret keys are not expected from a keyserver. We do not care about secret subkeys because the import code takes care of skipping them. Not allowing an import of a public key with a secret subkey would make it too easy to inhibit the downloading of a public key. Recall that keyservers do only limited checks. */ node = find_kbnode (keyblock, PKT_SECRET_KEY); if (node) return gpg_error (GPG_ERR_GENERAL); /* Do not import. */ if (!ndesc) return 0; /* Okay if no description given. */ /* Loop over all key packets. */ for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype != PKT_PUBLIC_KEY && node->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk = node->pkt->pkt.public_key; fingerprint_from_pk (pk, fpr, &fpr_len); keyid_from_pk (pk, keyid); /* Compare requested and returned fingerprints if available. */ for (n = 0; n < ndesc; n++) { if (desc[n].mode == KEYDB_SEARCH_MODE_FPR20) { if (fpr_len == 20 && !memcmp (fpr, desc[n].u.fpr, 20)) return 0; } else if (desc[n].mode == KEYDB_SEARCH_MODE_FPR16) { if (fpr_len == 16 && !memcmp (fpr, desc[n].u.fpr, 16)) return 0; } else if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID) { if (keyid[0] == desc[n].u.kid[0] && keyid[1] == desc[n].u.kid[1]) return 0; } else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID) { if (keyid[1] == desc[n].u.kid[1]) return 0; } else /* No keyid or fingerprint - can't check. */ return 0; /* allow import. */ } } return gpg_error (GPG_ERR_GENERAL); } int keyserver_import (ctrl_t ctrl, strlist_t users) { gpg_error_t err; KEYDB_SEARCH_DESC *desc; int num=100,count=0; int rc=0; /* Build a list of key ids */ desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num); for(;users;users=users->next) { err = classify_user_id (users->d, &desc[count], 1); if (err || (desc[count].mode != KEYDB_SEARCH_MODE_SHORT_KID && desc[count].mode != KEYDB_SEARCH_MODE_LONG_KID && desc[count].mode != KEYDB_SEARCH_MODE_FPR16 && desc[count].mode != KEYDB_SEARCH_MODE_FPR20)) { log_error (_("\"%s\" not a key ID: skipping\n"), users->d); continue; } count++; if(count==num) { num+=100; desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num); } } if(count>0) rc = keyserver_get (ctrl, desc, count, NULL, 0, NULL, NULL); xfree(desc); return rc; } /* Return true if any keyserver has been configured. */ int keyserver_any_configured (ctrl_t ctrl) { return !gpg_dirmngr_ks_list (ctrl, NULL); } /* Import all keys that exactly match NAME */ int keyserver_import_name (ctrl_t ctrl, const char *name, unsigned char **fpr, size_t *fprlen, struct keyserver_spec *keyserver) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_EXACT; desc.u.name = name; return keyserver_get (ctrl, &desc, 1, keyserver, 0, fpr, fprlen); } /* Import the keys that match exactly MBOX */ int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { KEYDB_SEARCH_DESC desc = { 0 }; struct keyserver_spec keyserver = { NULL, "ldap:///" }; desc.mode = KEYDB_SEARCH_MODE_MAIL; desc.u.name = mbox; return keyserver_get (ctrl, &desc, 1, &keyserver, 0, fpr, fprlen); } int -keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, +keyserver_import_fprint (ctrl_t ctrl, const byte *fprint, size_t fprint_len, struct keyserver_spec *keyserver, unsigned int flags) { KEYDB_SEARCH_DESC desc; - memset(&desc,0,sizeof(desc)); + memset (&desc, 0, sizeof(desc)); if(fprint_len==16) desc.mode=KEYDB_SEARCH_MODE_FPR16; else if(fprint_len==20) desc.mode=KEYDB_SEARCH_MODE_FPR20; else - return -1; + return gpg_error (GPG_ERR_INV_ARG); - memcpy(desc.u.fpr,fprint,fprint_len); + memcpy (desc.u.fpr, fprint, fprint_len); - /* TODO: Warn here if the fingerprint we got doesn't match the one - we asked for? */ return keyserver_get (ctrl, &desc, 1, keyserver, flags, NULL, NULL); } + +int +keyserver_import_fprint_ntds (ctrl_t ctrl, + const byte *fprint, size_t fprint_len) +{ + struct keyserver_spec keyserver = { NULL, "ldap:///" }; + + return keyserver_import_fprint (ctrl, fprint, fprint_len, + &keyserver, KEYSERVER_IMPORT_FLAG_LDAP); +} + + int keyserver_import_keyid (ctrl_t ctrl, u32 *keyid,struct keyserver_spec *keyserver, unsigned int flags) { KEYDB_SEARCH_DESC desc; memset(&desc,0,sizeof(desc)); desc.mode=KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0]=keyid[0]; desc.u.kid[1]=keyid[1]; return keyserver_get (ctrl, &desc, 1, keyserver, flags, NULL, NULL); } /* code mostly stolen from do_export_stream */ static int keyidlist (ctrl_t ctrl, strlist_t users, KEYDB_SEARCH_DESC **klist, int *count, int fakev3) { int rc = 0; int num = 100; kbnode_t keyblock = NULL; kbnode_t node; KEYDB_HANDLE kdbhd; int ndesc; KEYDB_SEARCH_DESC *desc = NULL; strlist_t sl; *count=0; *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num); kdbhd = keydb_new (); if (!kdbhd) { rc = gpg_error_from_syserror (); goto leave; } keydb_disable_caching (kdbhd); /* We are looping the search. */ if(!users) { ndesc = 1; desc = xmalloc_clear ( ndesc * sizeof *desc); desc[0].mode = KEYDB_SEARCH_MODE_FIRST; } else { for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) ; desc = xmalloc ( ndesc * sizeof *desc); for (ndesc=0, sl=users; sl; sl = sl->next) { gpg_error_t err; if (!(err = classify_user_id (sl->d, desc+ndesc, 1))) ndesc++; else log_error (_("key \"%s\" not found: %s\n"), sl->d, gpg_strerror (err)); } } for (;;) { rc = keydb_search (kdbhd, desc, ndesc, NULL); if (rc) break; /* ready. */ if (!users) desc[0].mode = KEYDB_SEARCH_MODE_NEXT; /* read the keyblock */ rc = keydb_get_keyblock (kdbhd, &keyblock ); if( rc ) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (rc) ); goto leave; } if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY))) { /* This is to work around a bug in some keyservers (pksd and OKS) that calculate v4 RSA keyids as if they were v3 RSA. The answer is to refresh both the correct v4 keyid (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7). This only happens for key refresh using the HKP scheme and if the refresh-add-fake-v3-keyids keyserver option is set. */ if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) && node->pkt->pkt.public_key->version>=4) { (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID; v3_keyid (node->pkt->pkt.public_key->pkey[0], (*klist)[*count].u.kid); (*count)++; if(*count==num) { num+=100; *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num); } } /* v4 keys get full fingerprints. v3 keys get long keyids. This is because it's easy to calculate any sort of keyid from a v4 fingerprint, but not a v3 fingerprint. */ if(node->pkt->pkt.public_key->version<4) { (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID; keyid_from_pk(node->pkt->pkt.public_key, (*klist)[*count].u.kid); } else { size_t dummy; (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20; fingerprint_from_pk(node->pkt->pkt.public_key, (*klist)[*count].u.fpr,&dummy); } /* This is a little hackish, using the skipfncvalue as a void* pointer to the keyserver spec, but we don't need the skipfnc here, and it saves having an additional field for this (which would be wasted space most of the time). */ (*klist)[*count].skipfncvalue=NULL; /* Are we honoring preferred keyservers? */ if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL) { PKT_user_id *uid=NULL; PKT_signature *sig=NULL; merge_keys_and_selfsig (ctrl, keyblock); for(node=node->next;node;node=node->next) { if(node->pkt->pkttype==PKT_USER_ID && node->pkt->pkt.user_id->flags.primary) uid=node->pkt->pkt.user_id; else if(node->pkt->pkttype==PKT_SIGNATURE && node->pkt->pkt.signature-> flags.chosen_selfsig && uid) { sig=node->pkt->pkt.signature; break; } } /* Try and parse the keyserver URL. If it doesn't work, then we end up writing NULL which indicates we are the same as any other key. */ if(sig) (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig); } (*count)++; if(*count==num) { num+=100; *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num); } } } if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) rc = 0; leave: if(rc) { xfree(*klist); *klist = NULL; } xfree(desc); keydb_release(kdbhd); release_kbnode(keyblock); return rc; } /* Note this is different than the original HKP refresh. It allows usernames to refresh only part of the keyring. */ gpg_error_t keyserver_refresh (ctrl_t ctrl, strlist_t users) { gpg_error_t err; int count, numdesc; int fakev3 = 0; KEYDB_SEARCH_DESC *desc; unsigned int options=opt.keyserver_options.import_options; /* We switch merge-only on during a refresh, as 'refresh' should never import new keys, even if their keyids match. */ opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY; /* Similarly, we switch on fast-import, since refresh may make multiple import sets (due to preferred keyserver URLs). We don't want each set to rebuild the trustdb. Instead we do it once at the end here. */ opt.keyserver_options.import_options|=IMPORT_FAST; /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO scheme, then enable fake v3 keyid generation. Note that this works only with a keyserver configured. gpg.conf (i.e. opt.keyserver); however that method of configuring a keyserver is deprecated and in any case it is questionable whether we should keep on supporting these ancient and broken keyservers. */ if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 || ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0)) fakev3=1; err = keyidlist (ctrl, users, &desc, &numdesc, fakev3); if (err) return err; count=numdesc; if(count>0) { int i; /* Try to handle preferred keyserver keys first */ for(i=0;iuri); /* We use the keyserver structure we parsed out before. Note that a preferred keyserver without a scheme:// will be interpreted as hkp:// */ err = keyserver_get (ctrl, &desc[i], 1, keyserver, 0, NULL, NULL); if (err) log_info(_("WARNING: unable to refresh key %s" " via %s: %s\n"),keystr_from_desc(&desc[i]), keyserver->uri,gpg_strerror (err)); else { /* We got it, so mark it as NONE so we don't try and get it again from the regular keyserver. */ desc[i].mode=KEYDB_SEARCH_MODE_NONE; count--; } free_keyserver_spec(keyserver); } } } if(count>0) { char *tmpuri; err = gpg_dirmngr_ks_list (ctrl, &tmpuri); if (!err) { if (!opt.quiet) { log_info (ngettext("refreshing %d key from %s\n", "refreshing %d keys from %s\n", count), count, tmpuri); } xfree (tmpuri); err = keyserver_get (ctrl, desc, numdesc, NULL, 0, NULL, NULL); } } xfree(desc); opt.keyserver_options.import_options=options; /* If the original options didn't have fast import, and the trustdb is dirty, rebuild. */ if(!(opt.keyserver_options.import_options&IMPORT_FAST)) check_or_update_trustdb (ctrl); return err; } /* Search for keys on the keyservers. The patterns are given in the string list TOKENS. */ gpg_error_t keyserver_search (ctrl_t ctrl, strlist_t tokens) { gpg_error_t err; char *searchstr; struct search_line_handler_parm_s parm; memset (&parm, 0, sizeof parm); if (!tokens) return 0; /* Return success if no patterns are given. */ /* Write global options */ /* for(temp=opt.keyserver_options.other;temp;temp=temp->next) */ /* es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */ /* Write per-keyserver options */ /* for(temp=keyserver->options;temp;temp=temp->next) */ /* es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */ { membuf_t mb; strlist_t item; init_membuf (&mb, 1024); for (item = tokens; item; item = item->next) { if (item != tokens) put_membuf (&mb, " ", 1); put_membuf_str (&mb, item->d); } put_membuf (&mb, "", 1); /* Append Nul. */ searchstr = get_membuf (&mb, NULL); if (!searchstr) { err = gpg_error_from_syserror (); goto leave; } } /* FIXME: Enable the next line */ /* log_info (_("searching for \"%s\" from %s\n"), searchstr, keyserver->uri); */ parm.ctrl = ctrl; if (searchstr) parm.searchstr_disp = utf8_to_native (searchstr, strlen (searchstr), 0); err = gpg_dirmngr_ks_search (ctrl, searchstr, search_line_handler, &parm); if (parm.not_found || gpg_err_code (err) == GPG_ERR_NO_DATA) { if (parm.searchstr_disp) log_info (_("key \"%s\" not found on keyserver\n"), parm.searchstr_disp); else log_info (_("key not found on keyserver\n")); } if (gpg_err_code (err) == GPG_ERR_NO_DATA) err = gpg_error (GPG_ERR_NOT_FOUND); else if (err) log_error ("error searching keyserver: %s\n", gpg_strerror (err)); /* switch(ret) */ /* { */ /* case KEYSERVER_SCHEME_NOT_FOUND: */ /* log_error(_("no handler for keyserver scheme '%s'\n"), */ /* opt.keyserver->scheme); */ /* break; */ /* case KEYSERVER_NOT_SUPPORTED: */ /* log_error(_("action '%s' not supported with keyserver " */ /* "scheme '%s'\n"), "search", opt.keyserver->scheme); */ /* break; */ /* case KEYSERVER_TIMEOUT: */ /* log_error(_("keyserver timed out\n")); */ /* break; */ /* case KEYSERVER_INTERNAL_ERROR: */ /* default: */ /* log_error(_("keyserver internal error\n")); */ /* break; */ /* } */ /* return gpg_error (GPG_ERR_KEYSERVER); */ leave: xfree (parm.desc); xfree (parm.searchstr_disp); xfree(searchstr); return err; } /* Helper for keyserver_get. Here we only receive a chunk of the description to be processed in one batch. This is required due to the limited number of patterns the dirmngr interface (KS_GET) can grok and to limit the amount of temporary required memory. */ static gpg_error_t keyserver_get_chunk (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, int *r_ndesc_used, import_stats_t stats_handle, struct keyserver_spec *override_keyserver, unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen) { gpg_error_t err = 0; char **pattern; int idx, npat, npat_fpr; estream_t datastream; char *source = NULL; size_t linelen; /* Estimated linelen for KS_GET. */ size_t n; int only_fprs; #define MAX_KS_GET_LINELEN 950 /* Somewhat lower than the real limit. */ *r_ndesc_used = 0; /* Create an array filled with a search pattern for each key. The array is delimited by a NULL entry. */ pattern = xtrycalloc (ndesc+1, sizeof *pattern); if (!pattern) return gpg_error_from_syserror (); /* Note that we break the loop as soon as our estimation of the to be used line length reaches the limit. But we do this only if we have processed at least one search requests so that an overlong single request will be rejected only later by gpg_dirmngr_ks_get but we are sure that R_NDESC_USED has been updated. This avoids a possible indefinite loop. */ linelen = 24; /* "KS_GET --quick --ldap --" */ for (npat=npat_fpr=0, idx=0; idx < ndesc; idx++) { int quiet = 0; if (desc[idx].mode == KEYDB_SEARCH_MODE_FPR20 || desc[idx].mode == KEYDB_SEARCH_MODE_FPR16) { n = 1+2+2*20; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtrymalloc (n); if (!pattern[npat]) err = gpg_error_from_syserror (); else { strcpy (pattern[npat], "0x"); bin2hex (desc[idx].u.fpr, desc[idx].mode == KEYDB_SEARCH_MODE_FPR20? 20 : 16, pattern[npat]+2); npat++; if (desc[idx].mode == KEYDB_SEARCH_MODE_FPR20) npat_fpr++; } } else if(desc[idx].mode == KEYDB_SEARCH_MODE_LONG_KID) { n = 1+2+16; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtryasprintf ("0x%08lX%08lX", (ulong)desc[idx].u.kid[0], (ulong)desc[idx].u.kid[1]); if (!pattern[npat]) err = gpg_error_from_syserror (); else npat++; } else if(desc[idx].mode == KEYDB_SEARCH_MODE_SHORT_KID) { n = 1+2+8; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtryasprintf ("0x%08lX", (ulong)desc[idx].u.kid[1]); if (!pattern[npat]) err = gpg_error_from_syserror (); else npat++; } else if(desc[idx].mode == KEYDB_SEARCH_MODE_EXACT) { /* The Dirmngr also uses classify_user_id to detect the type of the search string. By adding the '=' prefix we force Dirmngr's KS_GET to consider this an exact search string. (In gpg 1.4 and gpg 2.0 the keyserver helpers used the KS_GETNAME command to indicate this.) */ n = 1+1+strlen (desc[idx].u.name); if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = strconcat ("=", desc[idx].u.name, NULL); if (!pattern[npat]) err = gpg_error_from_syserror (); else { npat++; quiet = 1; } } else if(desc[idx].mode == KEYDB_SEARCH_MODE_MAIL) { n = 1 + strlen (desc[idx].u.name) + 1 + 1; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; if (desc[idx].u.name[0] == '<') pattern[npat] = xtrystrdup (desc[idx].u.name); else pattern[npat] = strconcat ("<", desc[idx].u.name, ">", NULL); if (!pattern[npat]) err = gpg_error_from_syserror (); else { npat++; quiet = 1; } } else if (desc[idx].mode == KEYDB_SEARCH_MODE_NONE) continue; else BUG(); if (err) { for (idx=0; idx < npat; idx++) xfree (pattern[idx]); xfree (pattern); return err; } if (!quiet && override_keyserver) { if (override_keyserver->host) log_info (_("requesting key %s from %s server %s\n"), keystr_from_desc (&desc[idx]), override_keyserver->scheme, override_keyserver->host); else log_info (_("requesting key %s from %s\n"), keystr_from_desc (&desc[idx]), override_keyserver->uri); } } /* Remember now many of search items were considered. Note that this is different from NPAT. */ *r_ndesc_used = idx; only_fprs = (npat && npat == npat_fpr); err = gpg_dirmngr_ks_get (ctrl, pattern, override_keyserver, flags, &datastream, &source); for (idx=0; idx < npat; idx++) xfree (pattern[idx]); xfree (pattern); if (opt.verbose && source) log_info ("data source: %s\n", source); if (!err) { struct ks_retrieval_screener_arg_s screenerarg; unsigned int options; /* FIXME: Check whether this comment should be moved to dirmngr. Slurp up all the key data. In the future, it might be nice to look for KEY foo OUTOFBAND and FAILED indicators. It's harmless to ignore them, but ignoring them does make gpg complain about "no valid OpenPGP data found". One way to do this could be to continue parsing this line-by-line and make a temp iobuf for each key. Note that we don't allow the import of secret keys from a keyserver. Keyservers should never accept or send them but we better protect against rogue keyservers. */ /* For LDAP servers we reset IMPORT_SELF_SIGS_ONLY unless it has * been set explicitly. */ options = (opt.keyserver_options.import_options | IMPORT_NO_SECKEY); if (source && (!strncmp (source, "ldap:", 5) || !strncmp (source, "ldaps:", 6)) && !opt.flags.expl_import_self_sigs_only) options &= ~IMPORT_SELF_SIGS_ONLY; screenerarg.desc = desc; screenerarg.ndesc = *r_ndesc_used; import_keys_es_stream (ctrl, datastream, stats_handle, r_fpr, r_fprlen, options, keyserver_retrieval_screener, &screenerarg, only_fprs? KEYORG_KS : 0, source); } es_fclose (datastream); xfree (source); return err; } /* Retrieve a key from a keyserver. The search pattern are in (DESC,NDESC). Allowed search modes are keyid, fingerprint, and exact searches. OVERRIDE_KEYSERVER gives an optional override keyserver. If (R_FPR,R_FPRLEN) are not NULL, they may return the fingerprint of a single imported key. If the FLAG bit KEYSERVER_IMPORT_FLAG_QUICK is set, dirmngr is advised to use a shorter timeout. */ static gpg_error_t keyserver_get (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, struct keyserver_spec *override_keyserver, unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen) { gpg_error_t err; import_stats_t stats_handle; int ndesc_used; int any_good = 0; stats_handle = import_new_stats_handle(); for (;;) { err = keyserver_get_chunk (ctrl, desc, ndesc, &ndesc_used, stats_handle, override_keyserver, flags, r_fpr, r_fprlen); if (!err) any_good = 1; if (err || ndesc_used >= ndesc) break; /* Error or all processed. */ /* Prepare for the next chunk. */ desc += ndesc_used; ndesc -= ndesc_used; } if (any_good) import_print_stats (stats_handle); import_release_stats_handle (stats_handle); return err; } /* Send all keys specified by KEYSPECS to the configured keyserver. */ static gpg_error_t keyserver_put (ctrl_t ctrl, strlist_t keyspecs) { gpg_error_t err; strlist_t kspec; char *ksurl; if (!keyspecs) return 0; /* Return success if the list is empty. */ if (gpg_dirmngr_ks_list (ctrl, &ksurl)) { log_error (_("no keyserver known\n")); return gpg_error (GPG_ERR_NO_KEYSERVER); } for (kspec = keyspecs; kspec; kspec = kspec->next) { void *data; size_t datalen; kbnode_t keyblock; err = export_pubkey_buffer (ctrl, kspec->d, opt.keyserver_options.export_options, NULL, 0, NULL, &keyblock, &data, &datalen); if (err) log_error (_("skipped \"%s\": %s\n"), kspec->d, gpg_strerror (err)); else { if (!opt.quiet) log_info (_("sending key %s to %s\n"), keystr (keyblock->pkt->pkt.public_key->keyid), ksurl?ksurl:"[?]"); err = gpg_dirmngr_ks_put (ctrl, data, datalen, keyblock); release_kbnode (keyblock); xfree (data); if (err) { write_status_error ("keyserver_send", err); log_error (_("keyserver send failed: %s\n"), gpg_strerror (err)); } } } xfree (ksurl); return err; } /* Loop over all URLs in STRLIST and fetch the key at that URL. Note that the fetch operation ignores the configured keyservers and instead directly retrieves the keys. */ int keyserver_fetch (ctrl_t ctrl, strlist_t urilist, int origin) { gpg_error_t err; strlist_t sl; estream_t datastream; unsigned int save_options = opt.keyserver_options.import_options; /* Switch on fast-import, since fetch can handle more than one import and we don't want each set to rebuild the trustdb. Instead we do it once at the end. */ opt.keyserver_options.import_options |= IMPORT_FAST; for (sl=urilist; sl; sl=sl->next) { if (!opt.quiet) log_info (_("requesting key from '%s'\n"), sl->d); err = gpg_dirmngr_ks_fetch (ctrl, sl->d, &datastream); if (!err) { import_stats_t stats_handle; stats_handle = import_new_stats_handle(); import_keys_es_stream (ctrl, datastream, stats_handle, NULL, NULL, opt.keyserver_options.import_options, NULL, NULL, origin, sl->d); import_print_stats (stats_handle); import_release_stats_handle (stats_handle); } else log_info (_("WARNING: unable to fetch URI %s: %s\n"), sl->d, gpg_strerror (err)); es_fclose (datastream); } opt.keyserver_options.import_options = save_options; /* If the original options didn't have fast import, and the trustdb is dirty, rebuild. */ if (!(opt.keyserver_options.import_options&IMPORT_FAST)) check_or_update_trustdb (ctrl); return 0; } /* Import key in a CERT or pointed to by a CERT. In DANE_MODE fetch the certificate using the DANE method. */ int keyserver_import_cert (ctrl_t ctrl, const char *name, int dane_mode, unsigned char **fpr,size_t *fpr_len) { gpg_error_t err; char *look,*url; estream_t key; look = xstrdup(name); if (!dane_mode) { char *domain = strrchr (look,'@'); if (domain) *domain='.'; } err = gpg_dirmngr_dns_cert (ctrl, look, dane_mode? NULL : "*", &key, fpr, fpr_len, &url); if (err) ; else if (key) { int armor_status=opt.no_armor; import_filter_t save_filt; /* CERTs and DANE records are always in binary format */ opt.no_armor=1; if (dane_mode) { save_filt = save_and_clear_import_filter (); if (!save_filt) err = gpg_error_from_syserror (); else { char *filtstr = es_bsprintf ("keep-uid=mbox = %s", look); err = filtstr? 0 : gpg_error_from_syserror (); if (!err) err = parse_and_set_import_filter (filtstr); xfree (filtstr); if (!err) err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, IMPORT_NO_SECKEY, NULL, NULL, KEYORG_DANE, NULL); restore_import_filter (save_filt); } } else { err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, (opt.keyserver_options.import_options | IMPORT_NO_SECKEY), NULL, NULL, 0, NULL); } opt.no_armor=armor_status; es_fclose (key); key = NULL; } else if (*fpr) { /* We only consider the IPGP type if a fingerprint was provided. This lets us select the right key regardless of what a URL points to, or get the key from a keyserver. */ if(url) { struct keyserver_spec *spec; spec = parse_keyserver_uri (url, 1); if(spec) { err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, spec, 0); free_keyserver_spec(spec); } } else if (keyserver_any_configured (ctrl)) { /* If only a fingerprint is provided, try and fetch it from the configured keyserver. */ err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, opt.keyserver, 0); } else log_info(_("no keyserver known\n")); /* Give a better string here? "CERT fingerprint for \"%s\" found, but no keyserver" " known (use option --keyserver)\n" ? */ } xfree(url); xfree(look); return err; } /* Import key pointed to by a PKA record. Return the requested fingerprint in fpr. */ gpg_error_t keyserver_import_pka (ctrl_t ctrl, const char *name, unsigned char **fpr, size_t *fpr_len) { gpg_error_t err; char *url; err = gpg_dirmngr_get_pka (ctrl, name, fpr, fpr_len, &url); if (url && *url && fpr && fpr_len) { /* An URL is available. Lookup the key. */ struct keyserver_spec *spec; spec = parse_keyserver_uri (url, 1); if (spec) { err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, spec, 0); free_keyserver_spec (spec); } } xfree (url); if (err) { xfree(*fpr); *fpr = NULL; *fpr_len = 0; } return err; } /* Import a key using the Web Key Directory protocol. */ gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { gpg_error_t err; char *mbox; estream_t key; char *url = NULL; /* We want to work on the mbox. That is what dirmngr will do anyway * and we need the mbox for the import filter anyway. */ mbox = mailbox_from_userid (name); if (!mbox) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_EINVAL) err = gpg_error (GPG_ERR_INV_USER_ID); return err; } err = gpg_dirmngr_wkd_get (ctrl, mbox, flags, &key, &url); if (err) ; else if (key) { int armor_status = opt.no_armor; import_filter_t save_filt; /* Keys returned via WKD are in binary format. However, we * relax that requirement and allow also for armored data. */ opt.no_armor = 0; save_filt = save_and_clear_import_filter (); if (!save_filt) err = gpg_error_from_syserror (); else { char *filtstr = es_bsprintf ("keep-uid=mbox = %s", mbox); err = filtstr? 0 : gpg_error_from_syserror (); if (!err) err = parse_and_set_import_filter (filtstr); xfree (filtstr); if (!err) err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, IMPORT_NO_SECKEY, NULL, NULL, KEYORG_WKD, url); } restore_import_filter (save_filt); opt.no_armor = armor_status; es_fclose (key); key = NULL; } xfree (url); xfree (mbox); return err; } /* Import a key by name using LDAP */ int keyserver_import_ldap (ctrl_t ctrl, const char *name, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)name; (void)fpr; (void)fprlen; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/ #if 0 char *domain; struct keyserver_spec *keyserver; strlist_t list=NULL; int rc,hostlen=1; struct srventry *srvlist=NULL; int srvcount,i; char srvname[MAXDNAME]; /* Parse out the domain */ domain=strrchr(name,'@'); if(!domain) return GPG_ERR_GENERAL; domain++; keyserver=xmalloc_clear(sizeof(struct keyserver_spec)); keyserver->scheme=xstrdup("ldap"); keyserver->host=xmalloc(1); keyserver->host[0]='\0'; snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain); FIXME("network related - move to dirmngr or drop the code"); srvcount=getsrv(srvname,&srvlist); for(i=0;ihost=xrealloc(keyserver->host,hostlen); strcat(keyserver->host,srvlist[i].target); if(srvlist[i].port!=389) { char port[7]; hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */ keyserver->host=xrealloc(keyserver->host,hostlen); snprintf(port,7,":%u",srvlist[i].port); strcat(keyserver->host,port); } strcat(keyserver->host," "); } free(srvlist); /* If all else fails, do the PGP Universal trick of ldap://keys.(domain) */ hostlen+=5+strlen(domain); keyserver->host=xrealloc(keyserver->host,hostlen); strcat(keyserver->host,"keys."); strcat(keyserver->host,domain); append_to_strlist(&list,name); rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/ /* keyserver_work (ctrl, KS_GETNAME, list, NULL, */ /* 0, fpr, fpr_len, keyserver); */ free_strlist(list); free_keyserver_spec(keyserver); return rc; #endif } diff --git a/g10/test-stubs.c b/g10/test-stubs.c index 9125d6a64..c6fa9c024 100644 --- a/g10/test-stubs.c +++ b/g10/test-stubs.c @@ -1,578 +1,588 @@ /* test-stubs.c - The GnuPG signature verify utility * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2005, 2006, * 2008, 2009, 2012 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "filter.h" #include "../common/ttyio.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/status.h" #include "call-agent.h" int g10_errors_seen; void g10_exit( int rc ) { rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit(rc ); } /* Stub: * We have to override the trustcheck from pkclist.c because * this utility assumes that all keys in the keyring are trustworthy */ int check_signatures_trust (ctrl_t ctrl, PKT_signature *sig) { (void)ctrl; (void)sig; return 0; } void read_trust_options (ctrl_t ctrl, byte *trust_model, ulong *created, ulong *nextcheck, byte *marginals, byte *completes, byte *cert_depth, byte *min_cert_level) { (void)ctrl; (void)trust_model; (void)created; (void)nextcheck; (void)marginals; (void)completes; (void)cert_depth; (void)min_cert_level; } /* Stub: * We don't have the trustdb , so we have to provide some stub functions * instead */ int cache_disabled_value (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } void check_trustdb_stale (ctrl_t ctrl) { (void)ctrl; } int get_validity_info (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid) { (void)ctrl; (void)kb; (void)pk; (void)uid; return '?'; } unsigned int get_validity (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid, PKT_signature *sig, int may_ask) { (void)ctrl; (void)kb; (void)pk; (void)uid; (void)sig; (void)may_ask; return 0; } const char * trust_value_to_string (unsigned int value) { (void)value; return "err"; } const char * uid_trust_string_fixed (ctrl_t ctrl, PKT_public_key *key, PKT_user_id *uid) { (void)ctrl; (void)key; (void)uid; return "err"; } int get_ownertrust_info (ctrl_t ctrl, PKT_public_key *pk, int no_create) { (void)ctrl; (void)pk; (void)no_create; return '?'; } unsigned int get_ownertrust (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return TRUST_UNKNOWN; } /* Stubs: * Because we only work with trusted keys, it does not make sense to * get them from a keyserver */ struct keyserver_spec * keyserver_match (struct keyserver_spec *spec) { (void)spec; return NULL; } int keyserver_any_configured (ctrl_t ctrl) { (void)ctrl; return 0; } int keyserver_import_keyid (u32 *keyid, void *dummy, unsigned int flags) { (void)keyid; (void)dummy; (void)flags; return -1; } int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, struct keyserver_spec *keyserver, unsigned int flags) { (void)ctrl; (void)fprint; (void)fprint_len; (void)keyserver; (void)flags; return -1; } +int +keyserver_import_fprint_ntds (ctrl_t ctrl, + const byte *fprint, size_t fprint_len) +{ + (void)ctrl; + (void)fprint; + (void)fprint_len; + return -1; +} + int keyserver_import_cert (const char *name) { (void)name; return -1; } int keyserver_import_pka (const char *name,unsigned char *fpr) { (void)name; (void)fpr; return -1; } gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { (void)ctrl; (void)name; (void)flags; (void)fpr; (void)fpr_len; return GPG_ERR_BUG; } int keyserver_import_name (const char *name,struct keyserver_spec *spec) { (void)name; (void)spec; return -1; } int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)mbox; (void)fpr; (void)fprlen; return -1; } int keyserver_import_ldap (const char *name) { (void)name; return -1; } gpg_error_t read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname, const void *buffer, size_t buflen, kbnode_t *r_keyblock) { (void)ctrl; (void)fname; (void)buffer; (void)buflen; (void)r_keyblock; return -1; } gpg_error_t import_included_key_block (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return -1; } /* Stub: * No encryption here but mainproc links to these functions. */ gpg_error_t get_session_key (ctrl_t ctrl, PKT_pubkey_enc *k, DEK *dek) { (void)ctrl; (void)k; (void)dek; return GPG_ERR_GENERAL; } /* Stub: */ gpg_error_t get_override_session_key (DEK *dek, const char *string) { (void)dek; (void)string; return GPG_ERR_GENERAL; } /* Stub: */ int decrypt_data (ctrl_t ctrl, void *procctx, PKT_encrypted *ed, DEK *dek) { (void)ctrl; (void)procctx; (void)ed; (void)dek; return GPG_ERR_GENERAL; } /* Stub: * No interactive commands, so we don't need the helptexts */ void display_online_help (const char *keyword) { (void)keyword; } /* Stub: * We don't use secret keys, but getkey.c links to this */ int check_secret_key (PKT_public_key *pk, int n) { (void)pk; (void)n; return GPG_ERR_GENERAL; } /* Stub: * No secret key, so no passphrase needed */ DEK * passphrase_to_dek (int cipher_algo, STRING2KEY *s2k, int create, int nocache, const char *tmp, int *canceled) { (void)cipher_algo; (void)s2k; (void)create; (void)nocache; (void)tmp; if (canceled) *canceled = 0; return NULL; } void passphrase_clear_cache (const char *cacheid) { (void)cacheid; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { (void)sig; return NULL; } struct keyserver_spec * parse_keyserver_uri (const char *uri, int require_scheme, const char *configname, unsigned int configlineno) { (void)uri; (void)require_scheme; (void)configname; (void)configlineno; return NULL; } void free_keyserver_spec (struct keyserver_spec *keyserver) { (void)keyserver; } /* Stubs to avoid linking to photoid.c */ void show_photos (const struct user_attribute *attrs, int count, PKT_public_key *pk) { (void)attrs; (void)count; (void)pk; } int parse_image_header (const struct user_attribute *attr, byte *type, u32 *len) { (void)attr; (void)type; (void)len; return 0; } char * image_type_to_string (byte type, int string) { (void)type; (void)string; return NULL; } #ifdef ENABLE_CARD_SUPPORT int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { (void)name; (void)info; return 0; } #endif /* ENABLE_CARD_SUPPORT */ /* We do not do any locking, so use these stubs here */ void dotlock_disable (void) { } dotlock_t dotlock_create (const char *file_to_lock, unsigned int flags) { (void)file_to_lock; (void)flags; return NULL; } void dotlock_destroy (dotlock_t h) { (void)h; } int dotlock_take (dotlock_t h, long timeout) { (void)h; (void)timeout; return 0; } int dotlock_release (dotlock_t h) { (void)h; return 0; } void dotlock_remove_lockfiles (void) { } gpg_error_t agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { (void)ctrl; (void)hexkeygrip; (void)r_cleartext; *r_serialno = NULL; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t gpg_dirmngr_get_pka (ctrl_t ctrl, const char *userid, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { (void)ctrl; (void)userid; if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; return gpg_error (GPG_ERR_NOT_FOUND); } gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, const void *prefix, size_t prefixlen, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen) { (void)ctrl; (void)keyspec; (void)options; (void)prefix; (void)prefixlen; (void)stats; *r_keyblock = NULL; *r_data = NULL; *r_datalen = 0; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } gpg_error_t tofu_write_tfs_record (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, const char *user_id) { (void)ctrl; (void)fp; (void)pk; (void)user_id; return gpg_error (GPG_ERR_GENERAL); } gpg_error_t tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id, enum tofu_policy *policy) { (void)ctrl; (void)pk; (void)user_id; (void)policy; return gpg_error (GPG_ERR_GENERAL); } const char * tofu_policy_str (enum tofu_policy policy) { (void)policy; return "unknown"; } void tofu_begin_batch_update (ctrl_t ctrl) { (void)ctrl; } void tofu_end_batch_update (ctrl_t ctrl) { (void)ctrl; } gpg_error_t tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb) { (void) ctrl; (void) kb; return 0; } int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen) { (void)sig; (void)r_commentlen; if (r_reason) *r_reason = NULL; if (r_comment) *r_comment = NULL; return 0; }