Invoking GPG-AGENT
******************

gpg-agent is a daemon to manage secret (private) keys independelty from any protocol.  It is used as a backend for gpg and gpgsm as well as for a couple of other utilities.

The usual way to run the agent is from the ~/.xsession file:

     eval `gpg-agent --daemon`

If you don't use an X server, you can also put this into your regular startup file ~/.profile or .bash_profile.  It is best not to run multiple instance of the gpg-agent, so you should make sure that only is running:  gpg-agent uses an environment variable to inform clients about the communication parameters. You can write the content of this environment variable to a file so that you can test for a running agent.  This short script may do the job:

     if test -f $HOME/.gpg-agent-info && \
        kill -0 `cut -d: -f 2 $HOME/.gpg-agent-info` 2>/dev/null; then
          GPG_AGENT_INFO=`cat $HOME/.gpg-agent-info`
          export GPG_AGENT_INFO
     else
          eval `gpg-agent --daemon`
          echo $GPG_AGENT_INFO >$HOME/.gpg-agent-info
     fi

If you want to use a curses based pinentry (which is usually also the fallback mode for a GUI based pinentry), you should add these lines to your .bashrc or whatever initialization file is used for all shell invocations:

     GPG_TTY=`tty`
     export GPG_TTY

It is important that this environment variable always reflects the output of the tty command.

Please make sure that a proper pinentry program has been installed under the default filename (which is system dependant) or use the option pinentry-pgm to specify the full name of that program. It is often useful to install a symbolic link from the actual used pinentry (e.g. /usr/bin/pinentry-gtk) to the expected one (e.g. /usr/bin/pinentry).

See Option Index, for an index to GPG-AGENT's commands and options.

Commands
========

Commands are not distinguished from options execpt for the fact that only one one command is allowed.

--version
     Print the program version and licensing information.  Not that you can abbreviate this command.

--help, -h
     Print a usage message summarizing the most usefule command-line options. Not that you can abbreviate this command.

--dump-options
     Print a list of all available options and commands.  Not that you can abbreviate this command.

--server
     Run in server mode and wait for commands on the stdin.  The default mode is to create a socket and listen for commands there.

--daemon
     Run the program in the background.  This option is required to prevent it from being accidently running in the background.  A common way to do this is:

     $ eval `gpg-agent --daemon`

Option Summary
==============

--options FILE
     Reads configuration from FILE instead of from the default per-user configuration file.  The default configuration file is named gpg-agent.conf and expected in the .gnupg directory directly below the home directory of the user.

-v

--verbose
     Outputs additional information while running. You can increase the verbosity by giving several verbose commands to GPGSM, such as -vv.

-q

--quiet
     Try to be as quiet as possible.

--batch
     Don't invoke a pinentry or do any other thing requiring human interaction.

--faked-system-time EPOCH
     This option is only useful for testing; it sets the system time back or forth to EPOCH which is the number of seconds elapsed since the year 1970.

--debug-level LEVEL
     Select the debug level for investigating problems. LEVEL may be one of:

     none
          no debugging at all.

     basic
          some basic debug messages

     advanced
          more verbose debug messages

     expert
          even more detailed messages

     guru
          all of the debug messages you can get

     How these messages are mapped to the actual debugging flags is not specified and may change with newer releaes of this program. They are however carefully selected to best aid in debugging.

--debug FLAGS
     This option is only useful for debugging and the behaviour may change at any time without notice.  FLAGS are bit encoded and may be given in usual C-Syntax. The currently defined bits are:

     0  (1)
          X.509 or OpenPGP protocol related data

     1  (2)
          values of big number integers

     2  (4)
          low level crypto operations

     5  (32)
          memory allocation

     6  (64)
          caching

     7  (128)
          show memory statistics.

     9  (512)
          write hashed data to files named dbgmd-000*

     10 (1024)
          trace Assuan protocol

     12 (4096)
          bypass all certificate validation

--debug-all
     Same as --debug=0xffffffff

--debug-wait N
     When running in server mode, wait N seconds before entering the actual processing loop and print the pid.  This gives time to attach a debugger.

--no-detach
     Don't detach the process from the console.  This is manly usefule for debugging.

-s
--sh
-c
--csh
     Format the info output in daemon mode for use with the standard Bourne shell respective the C-shell . The default ist to guess it based on the environment variable SHELL which is in almost all cases sufficient.

--no-grab
     Tell the pinentryo not to grab the keyboard and mouse.  This option should in general not be used to avaoid X-sniffing attacks.

--log-file FILE
     Append all logging output to FILE.  This is very helpful in seeing what the agent actually does.

--disable-pth
     Don't allow multiple connections.  This option is in general not very useful.

--allow-mark-trusted
     Allow clients to mark keys as trusted, i.e. put them into the trustlist.txt file.  This is by default not allowed to make it harder for users to inadvertly accept Root-CA keys.

--ignore-cache-for-signing
     This option will let gpg-agent bypass the passphrase cache for all signing operation.  Note that there is also a per-session option to control this behaviour but this command line option takes precedence.

--default-cache-ttl N
     Set the time a cache entry is valid to N seconds.  The default are 600 seconds.

--max-cache-ttl N
     Set the maximum time a cache entry is valid to N seconds.  After this time a cache entry will get expired even if it has been accessed recently.  The default are 2 hours (7200 seconds).

--pinentry-program FILENAME
     Use program FILENAME as the PIN entry.  The default is installation dependend and can be shown with the --version command.

--scdaemon-program FILENAME
     Use program FILENAME as the Smartcard daemon.  The default is installation dependend and can be shown with the --version command.

--display STRING
--ttyname STRING
--ttytype STRING
--lc-type STRING
--lc-messages STRING
     These options are used with the server mode to pass localization information.

--keep-tty
--keep-display
     Ignore requests to change change the current TTY respective the X window system's DISPLAY variable.  This is useful to lock the pinentry to pop up at the TTY or display you started the agent.

All the long options may also be given in the configuration file after stripping off the two leading dashes.

Use of some signals.
====================

A running gpg-agent may be controlled by signals, i.e. using the kill command to send a signal to the process.

Here is a list of supported signals:

SIGHUP
     This signals flushes all chached passphrases and when the program was started with a configuration file, the configuration file is read again. Only certain options are honored: quiet, verbose, debug, debug-all, no-grab, pinentry-program, default-cache-ttl and ignore-cache-for-signing. scdaemon-program is also supported but due to the current implementation, which calls the scdaemon only once, it is not of much use.

SIGTERM
     Shuts down the process but waits until all current requests are fulfilled.  If the process has received 3 of these signals and requests are still pending, a shutdown is forced.

SIGINT
     Shuts down the process immediately.

SIGUSR1
SIGUSR2
     These signals are used for internal purposes.

Examples
========

     $ eval `gpg-agent --daemon`

Agent's Assuan Protocol
=======================

The gpg-agent should be started by the login shell and set an environment variable to tell clients about the socket to be used. Clients should deny to access an agent with a socket name which does not match its own configuration.  An application may choose to start an instance of the gpgagent if it does not figure that any has been started; it should not do this if a gpgagent is running but not usable.  Because gpg-agent can only be used in background mode, no special command line option is required to activate the use of the protocol.

To identify a key we use a thing called keygrip which is the SHA-1 hash of an canoncical encoded S-Expression of the the public key as used in Libgcrypt.  For the purpose of this interface the keygrip is given as a hex string.  The advantage of using this and not the hash of a certificate is that it will be possible to use the same keypair for different protocols, thereby saving space on the token used to keep the secret keys.

Decrypting a session key
------------------------

The client asks the server to decrypt a session key.  The encrypted session key should have all information needed to select the appropriate secret key or to delegate it to a smartcard.

       SETKEY <keyGrip>

Tell the server about the key to be used for decryption.  If this is not used, gpg-agent may try to figure out the key by trying to decrypt the message with each key available.

       PKDECRYPT

The agent checks whether this command is allowed and then does an INQUIRY to get the ciphertext the client should then send the cipher text.

         S: INQUIRE CIPHERTEXT
         C: D (xxxxxx
         C: D xxxx)
         C: END

Please note that the server may send status info lines while reading the data lines from the client.  The data send is a SPKI like S-Exp with this structure:

          (enc-val
            (<algo>
              (<param_name1> <mpi>)
      	   ...
              (<param_namen> <mpi>)))

Where algo is a string with the name of the algorithm; see the libgcrypt documentation for a list of valid algorithms.  The number and names of the parameters depend on the algorithm.  The agent does return an error if there is an inconsistency.

If the decryption was successful the decrypted data is returned by means of "D" lines.

Here is an example session:

        C: PKDECRYPT
        S: INQUIRE CIPHERTEXT
        C: D (enc-val elg (a 349324324)
        C: D    (b 3F444677CA)))
        C: END
        S: # session key follows
        S: D 1234567890ABCDEF0
        S: OK descryption successful

Signing a Hash
--------------

The client ask the agent to sign a given hash value.  A default key will be chosen if no key has been set.  To set a key a client first uses:

        SIGKEY <keyGrip>

This can be used multiple times to create multiple signature, the list of keys is reset with the next PKSIGN command or a RESET.  The server test whether the key is a valid key to sign something and responds with okay.

        SETHASH <hexstring>

The client can use this command to tell the server about the data (which usually is a hash) to be signed.

The actual signing is done using

        PKSIGN <options>

Options are not yet defined, but my later be used to choosen among different algorithms (e.g. pkcs 1.5)

The agent does then some checks, asks for the passphrase and if SETHASH has not been used asks the client for the data to sign:

        S: INQUIRE HASHVAL
        C: D ABCDEF012345678901234
        C: END

As a result the server returns the signature as an SPKI like S-Exp in "D" lines:

          (sig-val
            (<algo>
              (<param_name1> <mpi>)
      	   ...
              (<param_namen> <mpi>)))

The operation is affected by the option

        OPTION use-cache-for-signing=0|1

The default of 1 uses the cache.  Setting this option to 0 will lead gpg-agent to ignore the passphrase cache.  Note, that there is also a global command line option for gpg-agent to globally disable the caching.

Here is an example session:

        C: SIGKEY <keyGrip>
        S: OK key available
        C: SIGKEY <keyGrip>
        S: OK key available
        C: PKSIGN
        S: # I did ask the user whether he really wants to sign
        S: # I did ask the user for the passphrase
        S: INQUIRE HASHVAL
        C: D ABCDEF012345678901234
        C: END
        S: # signature follows
        S: D (sig-val rsa (s 45435453654612121212))
        S: OK

Generating a Key
----------------

This is used to create a new keypair and store the secret key inside the active PSE -w which is in most cases a Soft-PSE.  An not yet defined option allows to choose the storage location.  To get the secret key out of the PSE, a special export tool has to be used.

        GENKEY

Invokes the key generation process and the server will then inquire on the generation parameters, like:

        S: INQUIRE KEYPARM
        C: D (genkey (rsa (nbits  1024)))
        C: END

The format of the key parameters which depends on the algorithm is of the form:

         (genkey
           (algo
             (parameter_name_1 ....)
               ....
             (parameter_name_n ....)))

If everything succeeds, the server returns the *public key* in a SPKI like S-Expression like this:

          (public-key
            (rsa
      	 (n <mpi>)
      	 (e <mpi>)))

Here is an example session:

        C: GENKEY
        S: INQUIRE KEYPARM
        C: D (genkey (rsa (nbits  1024)))
        C: END
        S: D (public-key
        S: D   (rsa (n 326487324683264) (e 10001)))
        S  OK key created

Importing a Secret Key
----------------------

This operation is not yet supportted by GpgAgent.  Specialized tools are to be used for this.

There is no actual need because we can expect that secret keys created by a 3rd party are stored on a smartcard.  If we have generated the key ourself, we do not need to import it.

Export a Secret Key
-------------------

Not implemented.

Should be done by an extra tool.

Importing a Root Certificate
----------------------------

Actually we do not import a Root Cert but provide a way to validate any piece of data by storing its Hash along with a description and an identifier in the PSE.  Here is the interface desription:

         ISTRUSTED <fingerprint>

Check whether the OpenPGP primary key or the X.509 certificate with the given fingerprint is an ultimately trusted key or a trusted Root CA certificate.  The fingerprint should be given as a hexstring (without any blanks or colons or whatever in between) and may be left padded with 00 in case of an MD5 fingerprint.  GPGAgent will answer with:

         OK

The key is in the table of trusted keys.

         ERR 304 (Not Trusted)

The key is not in this table.

Gpg needs the entire list of trusted keys to maintain the web of trust; the following command is therefore quite helpful:

         LISTTRUSTED

GpgAgent returns a list of trusted keys line by line:

         S: D 000000001234454556565656677878AF2F1ECCFF P
         S: D 340387563485634856435645634856438576457A P
         S: D FEDC6532453745367FD83474357495743757435D S
         S: OK

The first item on a line is the hexified fingerprint where MD5 ingerprints are 00 padded to the left and the second item is a flag to indicate the type of key (so that gpg is able to only take care of PGP keys).  P = OpenPGP, S = S/MIME.  A client should ignore the rest of the line, so that we can extend the format in the future.

Finally a client should be able to mark a key as trusted:

        MARKTRUSTED FINGERPRINT "P"|"S"

The server will then pop up a window to ask the user whether she really trusts this key. For this it will probably ask for a text to be displayed like this:

        S: INQUIRE TRUSTDESC
        C: D Do you trust the key with the fingerprint @FPR@
        C: D bla fasel blurb.
        C: END
        S: OK

Known sequences with the pattern @foo@ are replaced according to this table:

@FPR16@
     Format the fingerprint according to gpg rules for a v3 keys.

@FPR20@
     Format the fingerprint according to gpg rules for a v4 keys.

@FPR@
     Choose an appropriate format to format the fingerprint.

@@
     Replaced by a single @

Ask for a passphrase
--------------------

This function is usually used to ask for a passphrase to be used for conventional encryption, but may also be used by programs which need special handling of passphrases.  This command uses a syntax which helps clients to use the agent with minimum effort.

       GET_PASSPHRASE CACHE_ID [ERROR_MESSAGE PROMPT DESCRIPTION]

CACHE_ID is expected to be a hex string used for caching a passphrase.  Use a X to bypass the cache.  With no other arguments the agent returns a cached passphrase or an error.

ERROR_MESSAGE is either a single X for no error message or a string to be shown as an error message like (e.g. "invalid passphrase").  Blanks must be percent escaped or replaced by +'.

PROMPT is either a single X for a default prompt or the text to be shown as the prompt.  Blanks must be percent escaped or replaced by +.

DESCRIPTION is a text shown above the entry field.  Blanks must be percent escaped or replaced by +.

The agent either returns with an error or with a OK followed by the hex encoded passphrase.  Note that the length of the strings is implicitly limited by the maximum length of a command.

       CLEAR_PASSPHRASE CACHE_ID

may be used to invalidate the cache entry for a passphrase.  The function returns with OK even when there is no cached passphrase.

Ask for confirmation
--------------------

This command may be used to ask for a simple confirmation by presenting a text and 2 bottonts: Okay and Cancel.

       GET_CONFIRMATION DESCRIPTION

DESCRIPTIONis displayed along with a Okay and Cancel button. Blanks must be percent escaped or replaced by +.  A X may be used to display confirmation dialog with a default text.

The agent either returns with an error or with a OK.  Note, that the length of DESCRIPTION is implicitly limited by the maximum length of a command.

Check whether a key is available
--------------------------------

This can be used to see whether a secret key is available.  It does not return any information on whether the key is somehow protected.

       HAVEKEY KEYGRIP

The Agent answers either with OK or No_Secret_Key (208).  The caller may want to check for other error codes as well.

Register a smartcard
--------------------

       LEARN [--send]

This command is used to register a smartcard.  With the --send option given the certificates are send back.

Change a Passphrase
-------------------

       PASSWD KEYGRIP

This command is used to interactively change the passphrase of the key indentified by the hex string KEYGRIP.