diff --git a/doc/scute.texi b/doc/scute.texi index ec03da2..eb0e6f3 100644 --- a/doc/scute.texi +++ b/doc/scute.texi @@ -1,1006 +1,1012 @@ \input texinfo @c -*- Texinfo -*- @c %**start of header @setfilename scute.info @include version.texi @settitle The Scute Manual @c Unify some of the indices. @syncodeindex tp fn @syncodeindex pg fn @c %**end of header @copying This is @cite{The Scute Manual} for Scute version @value{VERSION} and was last updated @value{UPDATED}. Scute is a PKCS#11 provider on top of GnuPG. @noindent Copyright @copyright{} 2006, 2007, 2008, 2009, 2010, 2017, 2019, 2020 g10 Code GmbH. @quotation The Scute Manual is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the license can be found in the section entitled ``Library Copying''. The Scute Manual 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 Lesser General Public License for more details. @end quotation @end copying @dircategory GnuPG @direntry * Scute: (scute). PKCS#11 module for GnuPG supported tokens. @end direntry @c A couple of macros with no effect on texinfo @c but used by the yat2m processor. @macro manpage {a} @end macro @macro mansect {a} @end macro @macro manpause @end macro @macro mancont @end macro @c @c Printing stuff taken from gcc. @c @macro gnupgtabopt{body} @code{\body\} @end macro @c @c Titlepage @c @setchapternewpage odd @titlepage @title The Scute Manual @subtitle Version @value{VERSION} @subtitle @value{UPDATED} @author g10 Code GmbH @page @vskip 0pt plus 1filll @insertcopying @end titlepage @ifnothtml @c @summarycontents @contents @page @end ifnothtml @ifnottex @node Top @top The Scute Manual @insertcopying @sp 1 @end ifnottex @menu * Introduction:: How to use this manual. * Preparation:: What you should do before using Scute. * Client Authentication:: How to use Scute for client authentication. * Email Signing:: How to use Scute for S/MIME email signing. * Document Signing:: How to use Scute with LibreOffice. * Troubleshooting:: What to do when things go wrong. * Internals:: Technical details about Scute. * Library Copying:: The GNU General Public License says how you can copy and share Scute. @c Indices @c @c * Concept Index:: Index of concepts and programs. @ifnothtml @detailmenu --- The Detailed Node Listing --- Introduction * Getting Started:: Purpose of the manual, and how to use it. * Features:: Reasons to install and use Scute. * Overview:: Basic architecture of the Scute module. Preparation * Prerequisites:: Dependencies of Scute. * Building the Source:: How to build Scute. * Certificate Preparation:: Preparing certificates for use with Scute. Client Authentication * Application Configuration:: Preparing the application for use with Scute. * Authentication With Service:: Using Scute for client authentication. Email Signing Document Signing Troubleshooting Internals * Features and Limitations:: Details about the interfaces implemented. * Developing Scute:: How to understand or improve Scute. * Mozilla Compatibility:: Interoperability notes for Mozilla NSS. @end detailmenu @end ifnothtml @end menu @c @ifhtml @c @page @c @summarycontents @c @contents @c @end ifhtml @c ************************************ @c **** BEGIN man page ************** @c ************************************ @ifset isman @manpage scute.7 @mansect 7 @ifset manverb .B scute \- The GnuPG PKCS#11 provider @end ifset @mansect synopsis @ifset manverb .B scute.so @end ifset @mansect description Scute is a PKCS#11 implementation for the GnuPG Agent using the GnuPG Smart Card Daemon. Currently, OpenPGP and PIV cards are supported. Scute enables the use of the OpenPGP smart card or a PIV smart card in applications supporting PKCS#11 compliant security tokens. The main application at this time is client authentication in Mozilla-based web browsers. In the future, other applications will be supported. To prepare your application for use with Scute, you have to load the Scute module as a PKCS#11 module into the application. See below for notes on how to do that with Firefox. @mansect options @noindent As a shared library, @command{scute} has no command line options but its behaviour can be modified by the use of a global configuration file or with an environment variable (see below). The global configuration file is expected as @file{/etc/gnupg/scute.conf}. It consists of keywords and values and some meta commands. There is currently only one useful option for general use, the other options are used for debugging. @command{Scute} uses the same parser as GnuPG does; thus for the meta commands please consult the GnuPG description. @noindent Here is the short list of supported keywords: @table @gnupgtabopt @item only-marked @opindex only-marked Scute consideres only keys having the @code{Use-for-p11} as part of their meta data. @item user @var{name} @opindex user If Scute is running with root permission and this option is used it runs the GnuPG components in the context of the user @var{name}. @var{name} may either be a name or a numerical UID. This allows to use the GnuPG setup of a certain user instead of running it under the root account. This is needed to make Scute work smoothly as a PKCS#11 provider for OpenVPN. If the current user is not root, this option has no effect. @item debug @var{flag} @opindex debug Useful values for @var{flag} are 1 and 3. @item log-file @var{file} @opindex log-file This has currently no effect but will in a future version write the log to @var{file}. Writing to a socket will be possible by prefixing the @var{file} with the string @code{socket://}. @item assume-single-threaded @opindex assume-single-threaded This is a hack to ignore a request to use native threads instead of user provided callbacks. Should only be used with caution if there is no easy way to fix the caller or until we have fixed Scute. - @end table +In addition to the above configuration file, Scute also reads GnuPG´s +@file{common.conf} in the same way GnuPG does. This way the +@option{no-autostart} option is detected and Scute will not try to +launch gpg-agent, which it usually does. The important use-case here +is running Scute on a server with the gpg-agent on a desktop box. + + @mansect notes (Firefox) To use Scute with Firefox or Thunderbird, follow these instructions: From the menu choose @code{Edit->Preferences}. In the preferences configuration dialog, you then select the @code{Advanced} configuration section, then the @code{Security} tab, and then select @code{Security Devices} in the category @code{Certificates}. In the devices manager dialog, you can select @code{Load} to load a new PKCS#11 device. In the pop-up dialog that follows, you can give a module name (e.g. ``@code{Scute}'') and a module filename. The latter should correspond to the full file name of the installed Scute module file @file{scute.so}. The default installation path is @file{/usr/local/lib}, which would mean that you have to provide the file name @file{/usr/local/lib/scute.so}. If you or your system administrator installed Scute in a different location, you have to adjust the file name correspondingly. After confirming installation of the security device, a pop-up window should confirm that the module was successfully loaded, and an entry for the security device should appear in the device manager list of @mansect environment The environment variable @code{SCUTE_DEBUG} gives the same debug flags as described above. This numerically value may be followed by a colon and the name for the log file. The global options will override these values once they have been parsed. @mansect see also @command{scdaemon}(1) @command{gpgsm}(1) @manpause @end ifset @c ************************************ @c **** END man page **************** @c ************************************ @node Introduction @chapter Introduction Scute is a PKCS#11 implementation for the GnuPG Agent using the GnuPG Smart Card Daemon. Currently, OpenPGP and PIV cards are supported. Scute enables the use of the OpenPGP smart card or a PIV smart card in applications supporting PKCS#11 compliant security tokens. The main application at this time is client authentication in Mozilla-based web browsers. In the future, other applications will be supported. @menu * Getting Started:: Purpose of the manual, and how to use it. * Features:: Reasons to install and use Scute. * Overview:: Basic architecture of the Scute module. @end menu @node Getting Started @section Getting Started This manual documents the Scute module, how it can be used for common applications supported by it, and how it can be extended and improved by programmers. It is thus a user manual as well as a developer manual. The reader is assumed to possess basic knowledge about cryptography in general, and public key cryptography in particular. The underlying cryptographic engines that are used by the library are not explained, but where necessary, special features or requirements are provided. This manual can be used in several ways. If read from the beginning to the end, it gives a good introduction into the module and how it can be used in an application. Forward references are included where necessary. Later on, the manual can be used as a reference manual to get just the information needed about any particular application of the module. @node Features @section Features Scute is currently the only implementation of PKCS#11 for the OpenPGP smart card. Apart from that, it offers a couple of other benefits: @table @asis @item it's free software Anybody can use, modify, and redistribute it under the terms of the GNU General Public License (@pxref{Library Copying}). @item it's built to grow Although Scute initially provided a single function, client authentication using OpenPGP smart cards in Mozilla-based web browsers, it was built with the intention of supporting other applications as well in the future. @item it's easy Building and installing Scute is easy, and preparing smart cards for use with Scute is a snatch using the GnuPG 2 framework. The integration of Scute into the application is seamless. @end table @node Overview @section Overview Scute is a security device that implements the PKCS#11 interface for security tokens. Applications which know how to use the PKCS#11 interface to access security tokens for cryptographic operations can use Scute to access the OpenPGP smart card. An important example of such an application is the Firefox web browser by the Mozilla project, which uses the Mozilla Network Security Services library (NSS). Scute itself does not include a driver for the smart card itself. Instead, it uses the GnuPG 2 framework to access the smart cards and associated data like certificates. Scute acts as the glue between the application and GnuPG 2. Currently supported usages are client authentication over HTTPS with Firefox (allowing users to authenticate themselves to a remote web service without entering their log-in information), email signing with Thunderbird, and document signing with LibreOffice. @node Preparation @chapter Preparation To use Scute, you first have to install the software. You also have to prepare each card you want to use with Scute before it can be used. Furthermore, you need to configure the application to make use of Scute for cryptographic operations. This chapter explains each of these steps in detail. @menu * Prerequisites:: Dependencies of Scute. * Building the Source:: How to build Scute. * Certificate Preparation:: Preparing certificates for use with Scute. @end menu @node Prerequisites @section Prerequisites There are two types of dependencies for Scute: compile-time dependencies and run-time dependencies. The compile-time dependencies only need to be fulfilled when Scute is compiled and installed. The run-time dependencies need to be fulfilled when Scute is used in an application. Scute depends, in addition to the essential build utilities, on the following packages at build time: @table @code @item libgpg-error Scute uses the GnuPG 2 framework for error handling, so it depends on the GPG error library. The minimum version required is 1.38. @item libassuan Scute uses the GnuPG framework for communication with the GPG Agent, so it also depends on the Assuan library. The minimum version required is 2.5.0. @end table At run-time, in addition to the run-time versions of the above libraries, you also need the following packages installed and configured: @table @asis @item GnuPG Scute uses the GnuPG 2 framework to access the OpenPGP card and for certificate management. The minimum version required is 2.2.0. For full functionality, in particular for use with the OpenVPN software, GnuPG version 2.3 is required. @item Pinentry Pinentry is a dependency of GnuPG 2, so it also needs to be installed with it. @item Firefox et al. Firefox is the first application supported by Scute. In the future, other applications may be supported. The applications are not dependencies of Scute, but Scute can not be used stand-alone, so you can not experience it without an application. @end table @node Building the Source @section Building the Source Scute does comply to the GNU coding standards and thus can be compiled and installed according to the generic installation instructions found in the source package in the file @code{INSTALL}. There are no Scute specific options to the configure script. After installation, the @code{scute.so} module file can be found in the library directory of the installation path. @node Certificate Preparation @section Certificate Preparation To use an OpenPGP card with Scute, it first has to be initialized by generating or loading a key on the card, see @uref{http://www.gnupg.org/(en)/howtos/card-howto/en/smartcard-howto.html, the OpenPGP Card How-To}. Then a certificate has to be created and imported into GPGSM. This task involves three steps: First, a certificate signing request (@acronym{CSR}) has to be created that matches the key on the card. This certificate signing request then has to be submitted to a certificate authority (@acronym{CA}), which will create the certificate and send it back to you. At last, the certificate has to be imported into GPGSM. This section will explain all of these steps in detail. @menu * Creating a CSR:: How to create a card-based CSR. * Signing the CSR:: Obtain a certificate from the CSR. * Importing the Certificate:: How to import the certificate into GPGSM. * On-card Certificate:: How to store the certificate on the card. @end menu @node Creating a CSR @subsection Creating a CSR Before you start, make sure that the GPG Agent is running, see @ref{Prerequisites} and that your card is in the reader. There is no need to configure GPGSM, so you can create a CSR with the command: @example $ gpgsm --gen-key > floppy-head.csr Please select what kind of key you want: (1) RSA (2) Existing key (3) Existing key from card Your selection? 3 @end example As we create a certificate for the OpenPGP Card, the option ``@code{[3] Direct from card}'' should be selected. @example Serial number of the card: 355F9746499F0D4B4ECEE4928B007D16 Available keys: (1) D53137B94C38D9BF6A199706EA6D5253 OPENPGP.1 (2) B0CD1A9DFC3539A1D6A8B851A11C8665 OPENPGP.2 (3) 53DB41052CC590A40B403F3E6350E5DC OPENPGP.3 Your selection? 3 Possible actions for a RSA key: (1) sign, encrypt (2) sign (3) encrypt Your selection? 2 @end example The only operation currently supported is client authentication. For this, the authentication key has to be selected. This is the third key on the card, so the options ``@code{[3] OPENPGP.3}'' and ``@code{[2] sign}'' should be chosen. Note that the key usage is only advisory, and the CA may assign different capabilities. @example Enter the X.509 subject name: CN=Floppy Head,OU="Webserver Team",O="Snake Oil, Ltd",L="Snake Town",ST="Snake Desert",C=XY Enter email addresses (end with an empty line): > floppy.head@@example.org > Enter DNS names (optional; end with an empty line): > Enter URIs (optional; end with an empty line): > Create self-signed certificate? (y/N) n @end example As a last step, the common name and e-mail address of the key owner need to be specified by you. The above are only an example for a fictious person working at a fictious company. DNS names are only meaningful for server certificates and thus should be left empty. We have now entered all required information and gpgsm will display what it has gathered and ask whether to create the certificate request: @example These parameters are used: Key-Type: card:OPENPGP.3 Key-Length: 1024 Key-Usage: sign Name-DN: CN=Floppy Head,OU="Webserver Team",O="Snake Oil, Ltd",L="Snake Town",ST="Snake Desert",C=XY Name-Email: floppy.head@@example.org Proceed with creation? (y/N) y Now creating certificate request. This may take a while ... gpgsm: about to sign the CSR for key: &53DB41052CC590A40B403F3E6350E5DC @end example GPGSM will now start working on creating the request. During this time you will be asked once for a passphrase to unprotect the authentication key on the card. A pop up window will appear to ask for it. When it is ready, you should see the final notice: @example gpgsm: certificate request created Ready. You should now send this request to your CA. @end example Now, you may look at the created request: @example $ cat floppy-head.csr -----BEGIN CERTIFICATE REQUEST----- MIICCDCCAXECAQAwgYExCzAJBgNVBAYTAlhZMRUwEwYDVQQIEwxTbmFrZSBEZXNl cnQxEzARBgNVBAcTClNuYWtlIFRvd24xFzAVBgNVBAoTDlNuYWtlIE9pbCwgTHRk MRcwFQYDVQQLEw5XZWJzZXJ2ZXIgVGVhbTEUMBIGA1UEAxMLRmxvcHB5IEhlYWQw gaAwDQYJKoZIhvcNAQEBBQADgY4AMIGKAoGBANWaM9YS89AOx3GX1Rua+4DUHwbL wt0rBYdBddlabMMteVjUcOOhbFMirLpLAi1S8fUXNiy84ysOmFStmvSIXDsAgXq5 1ESOU4SNg2zEkPDF1WYJ5BFIXdYq9i2k5W7+ctV8PkKv3e5IeYXTa5qppIPD31de gM8Qj7tK0hL/eNCfAgQAAQABoEUwQwYJKoZIhvcNAQkOMTYwNDAiBgNVHREEGzAZ gRdmbG9wcHkuaGVhZEBleGFtcGxlLmNvbTAOBgNVHQ8BAf8EBAMCBsAwDQYJKoZI hvcNAQEFBQADgYEAFC9q6+ib9YGCLB/2AlZR+/dvb+pEeXR1EbpV/dw/gjP1yPY6 29n8ZIDLUvQvNCtfCcXFxFimVSSB/KmFXXsJbM+NXQyT6Ocn34iHmkf9IVRMWQWg ZBYfQVeXAd7XlxI6d1wXDLwD/26lTU/rH2JU6H1+zSfZxqwVC4Iu+kiN4Y8= -----END CERTIFICATE REQUEST----- $ @end example @node Signing the CSR @subsection Signing the CSR The next step is to submit this certificate request to the CA, which can then create a certificate and send it back to you. If, for example, you use the CA @uref{http://www.cacert.org, CAcert}, then you can log into your account at the CAcert website, choose ``Client Certificates -> New'', check ``Show advanced options'', paste the above request block into the text field and click on ``Submit''. If everything works correctly, a certificate will be shown, which you can cut and paste into a new file @file{floppy-head.crt}. Alternatively if, for example, you set up your own CA with OpenSSL, then you can create your own certificate by issueing a command similar @code{openssl ca -in floppy-head.csr -cert snakeoil-ca-rsa.crt -keyfile snakeoil-ca-rsa.key -out floppy-head.crt}. Please see the OpenSSL documentation for more details on how to set up and administrate a certificate authority infrastructure. @node Importing the Certificate @subsection Importing the Certificate into GPGSM Once the CSR has been signed, you should end up with a certificate file @file{floppy-head.crt}, which you then have to import into GPGSM. It is also recommended that you import the root certificate of the CA first in the same fashion. @example $ gpgsm --import floppy-head.crt gpgsm: certificate imported gpgsm: total number processed: 1 gpgsm: imported: 1 @end example gpgsm tells you that it has imported the certificate. It is now associated with the key you used when creating the request. To see the content of your certificate, you may now enter: @example $ gpgsm -K Floppy /home/foo/.gnupg/pubring.kbx --------------------------- Serial number: 10 Issuer: /CN=Snake Oil CA/OU=Certificate Authority/O=Snake Oil, Ltd/L=Snake Town/ST=Snake Desert/C=XY/EMail=ca@@snakeoil.dom Subject: /CN=Floppy Head/OU=Webserver Team/O=Snake Oil, Ltd/ST=Snake Desert/C=XY validity: 2006-11-11 14:09:12 through 2007-11-11 14:09:12 key type: 1024 bit RSA fingerprint: EC:93:A2:55:C6:58:7F:C9:9E:96:DB:12:6E:64:99:54:BB:E1:94:68 @end example The option ``@code{-K}'' is used above because this will only list certificates for which a private key is available. To see more details, you may use ``@code{--dump-secret-keys}'' instead of ``@code{-K}''. @node On-card Certificate @subsection Loading the Certificate onto the Card This step is optional. You may choose to store the certificate directly into your OpenPGP card. The benefit of doing so is that Scute will then be able to fetch the certificate from the card without having to look into the GPGSM store. You need your certificate in the DER format. Export it from the GPGSM store with the following command: @example $ gpgsm -o floppy-head.crt --export Floppy @end example Then, fire up the GnuPG card editor to transfer the certificate to the card (note that the @code{writecert} command is not listed in the editor's online help): @example $ gpg2 --card-edit Application ID ...: D27600012301020000005000012340000 [...] gpg/card> admin Admin commands are allowed gpg/card> writecert 3 < floppy-head.crt gpg/card> quit @end example @node Client Authentication @chapter Client Authentication @menu * Application Configuration:: Preparing the application for use with Scute. * Authentication With Service:: Using Scute for client authentication. @end menu Scute allows you to authenticate yourself to a website securely without entering a username or password by simply using your OpenPGP card. Currently, only Mozilla-based browsers like Firefox are supported, although other applications using Mozilla NSS or supporting PKCS#11 modules may work. @node Application Configuration @section Application Configuration To prepare your application for use with Scute, you have to load the Scute module as a PKCS#11 module into the application. With Firefox, this can be done by choosing @code{Edit->Preferences} in the menu. In the preferences configuration dialog, you should select the @code{Advanced} configuration section, then the @code{Security} tab, and then select @code{Security Devices} in the category @code{Certificates}. @center @image{firefox-pref,13cm} In the devices manager dialog, you can select @code{Load} to load a new PKCS #11 device. @center @image{firefox-dm-load-before,13cm} In the pop-up dialog that follows, you can give a module name (e.g. ``@code{Scute}'') and a module filename. The latter should correspond to the full file name of the installed Scute module file @file{scute.so}. The default installation path is @file{/usr/local/lib}, which would mean that you have to provide the file name @file{/usr/local/lib/scute.so}. If you or your system administrator installed Scute in a different location, you have to adjust the file name correspondingly. @center @image{firefox-dm-load,8cm} After confirming installation of the security device, a pop-up window should confirm that the module was successfully loaded, and an entry for the security device should appear in the device manager list of @code{Security Modules and Devices}. @center @image{firefox-dm-load-after,15cm} When you insert the OpenPGP card for which you generated and imported a certificate earlier (see @ref{Certificate Preparation}), the device manager should detect this security token and display some information about it in the @code{Details} list when you select it from the module list. @center @image{firefox-dm-token-present,15cm} The client certificate will show up in the @code{Certificate Manager} under @code{Your Certificates}: @center @image{firefox-cm,13cm} @node Authentication With Service @section Authentication With Service Before you access a web service which requires client authentication, for instance a fictious web service @ifnottex @indicateurl{https://example.com}, @end ifnottex @iftex @code{https://example.com}, @end iftex the OpenPGP card should be present. In this case, a pop-up window will appear that requests you to enter the PIN number protecting the authentication key on the OpenPGP card. After entering the PIN number, your browser will be authenticated to the server. If the server accepts your request and certificate, this is all which is required. You should leave the card in the reader as long as the connection persists. Depending on how aggressively GPG Agent caches your PIN number, you may have to enter the PIN number again later to keep up the connection to the server. If the card is not present, or you enter the wrong PIN, or the server does not admit your certificate, you will get an error message. This error message is generated by the application and Scute can not influence it. Unfortunately, in Firefox (at least up to version 38.5.0), this error message is not very user friendly. For example, entering a bad PIN results in the following generic error message, and the @code{Try Again} button does not work as expected: @center @image{firefox-bad-pin,11cm} @comment FIXME: Document possible error codes. @node Email Signing @chapter Email Signing Scute also allows you to use your card-based X.509 certificate to sign your emails with the S/MIME signature format. This has been tested with Mozilla Thunderbird only, but should work with any mail client with support for PKCS #11 (notably GNOME Evolution). You must first load the Scute module into your mail client. With Mozilla Thunderbird, the procedure is the same as the one described above for Mozilla Firefox. Then, open your account configuration dialog (@code{Edit->Account Settings}), and in the @code{Security} tab, under the section @code{Digital Signing}, use the @code{Select...} button to associate your card-based certificate with your account. @center @image{thunderbird-account-settings,13cm} When writing a new message, you may then use the @code{S/MIME} button and select @code{Digitally sign this message} in the popup menu. You will be prompted for your User PIN before the message is sent. @center @image{thunderbird-smime-button,13cm} @node Document Signing @chapter Document Signing Scute can also be used with LibreOffice to sign OpenDocument files. First, you must load the Scute module into Mozilla Firefox according to the above procedure. Then, configure LibreOffice to use Firefox's certificate store by defining the @code{MOZILLA_CERTIFICATE_FOLDER} environment variable to your Firefox profile directory. Then, to sign the document you are editing, select the @code{File->Digital Signatures...} menu option to open the @code{Digital Signatures} dialog. @center @image{libreoffice-digital-signatures,13cm} Click the @code{Sign Document} button to open the certificate selection dialog. Select your card-based certificate, then validate. Enter your User PIN when prompted by GPG Agent. @center @image{libreoffice-certificate-selection,13cm} You may also sign a PDF export of your document. Select the @code{File->Export as PDF...} menu option to open the @code{PDF Options} dialog. In the @code{Digital Signatures} tab, use the @code{Select} button to open the certificate selection dialog as above. You will be prompted for your User PIN when you will click the @code{Export} button. @center @image{libreoffice-pdf-signature,13cm} @node Troubleshooting @chapter Troubleshooting @strong{Symptom:} Loading the Scute security device in the security device manager of Firefox fails with "Unable to load module". @strong{Solution:} Make sure that Scute is correctly installed, and that all libraries and executables are available. If you are using GnuPG 2.0 (instead of 2.1), you may need to make sure that the GPG Agent is running and can be found via the environment variable @code{GPG_AGENT_INFO}. @xref{Invoking GPG-AGENT, , , gnupg, Using the GNU Privacy Guard}, for details on how to run the GPG Agent. @strong{Symptom:} Client authentication fails with " has received an incorrect or unexpected message. Error code: -12227". @strong{Solution:} Make sure that the correct OpenPGP card is inserted and the certificate available in GPGSM. Check that the OpenPGP card is detected correctly in the security device manager and the corresponding certificate is displayed in the certificate manager of Firefox. @xref{Authentication With Service}. @strong{Symptom:} The OpenPGP card is detected and displayed in the security device manager in Firefox, but no corresponding certificate is displayed in the certificate manager of Firefox. @strong{Solution:} Make sure that the corresponding certificate is imported in GPGSM. @comment FIXME: Can this really happen??? @node Internals @chapter Internals The following notes are intended for people interested in more technical details about Scute and its implementation. They give an overview about its scope and potential compatibility issues with applications. @menu * Features and Limitations:: Details about the interfaces implemented. * Developing Scute:: How to understand or improve Scute. * Mozilla Compatibility:: Interoperability notes for Mozilla NSS. @end menu @node Features and Limitations @section Features and Limitations Scute implements version 2.20 of the @uref{https://www.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-11-cryptographic-token-interface-standard.htm, PKCS #11} specification. The @uref{http://www.g10code.com/p-card.html,OpenPGP smart card} application is supported in read-only mode. The following functions are not supported: @table @code @item C_Initialize No support for native thread package. Locking callbacks must be provided if multi-threaded operation is desired. @item C_WaitForSlotEvent Not implemented. The interface as specified by PKCS #11 is broken anyway, as the function can not safely be canceled. Thus, we require polling. @item C_GetOperationState @itemx C_SetOperationState Not supported. @item C_InitToken @itemx C_InitPIN @itemx C_SetPIN Not supported. No write operations are allowed. To configure the token, please use the tools accompanying the GnuPG software suite. @item C_Login @itemx C_Logout Not supported. No login into the token by the software is required. Passphrase queries are implemented by the use of GPG Agent and Pinentry. @item C_EncryptInit @itemx C_Encrypt @itemx C_EncryptUpdate @itemx C_EncryptFinal @itemx C_DigestInit @itemx C_Digest @itemx C_DigestUpdate @itemx C_DigestKey @itemx C_DigestFinal @itemx C_VerifyInit @itemx C_Verify @itemx C_VerifyUpdate @itemx C_VerifyFinal @itemx C_VerifyRecoverInit @itemx C_VerifyRec Not supported. Only secret key operations are supported. @item C_DecryptInit @itemx C_Decrypt Not yet supported, but will be in the future. @item C_SignUpdate @itemx C_SignFinal @itemx C_DecryptUpdate @itemx C_DecryptFinal No progressive crypto-operations are supported. @item C_SignRecoverInit @itemx C_SignRecover Not supported. @item C_DigestEncryptUpdate @itemx C_DecryptDigestUpdate @itemx C_SignEncryptUpdate @itemx C_DecryptVerifyUpdate Dual-purpose cryptographic functions are not supported. @item C_GenerateKey @itemx C_GenerateKeyPair @itemx C_WrapKey @itemx C_UnwrapKey @itemx C_DeriveKey Key management functions are not supported. Please use the tools accompanying the GnuPG software suite to generate and import keys for use with the token. @item C_SeedRandom Not supported. @item C_CreateObject @itemx C_CopyObject @itemx C_DestroyObject @itemx C_SetAttributeValue: Only read-only operations are supported on objects. @item C_GetObjectSize Not supported. @item CKO_CERTIFICATE The label specifies the key on the card used (e.g. @code{OPENPGP.3}). The ID is the fingerprint. @item CKO_PRIVATE_KEY: The @code{CKA_LOCAL} attribute can not be supported by the OpenPGP card. It is always set to false (as the key on the card may be copied to the card from an external source). @end table @node Developing Scute @section Developing Scute Scute is single-threaded. There is a global lock that is taken in all entry points of Scute, except for @code{C_Initialize}, @code{C_Finalize}, @code{C_GetFunctionList}, and stubs. Here are a couple of hints on how to develop PKCS #11 modules for Mozilla: @code{libopensc2} ships with a @code{pkcs11-spy} library that can be loaded as a wrapper around the PKCS #11 library you want to use to log all functions invoked by Mozilla. Here is how to use it: Set the @code{PKCS11SPY_OUTPUT} environment variable to a filename. @code{pkcs11-spy} appends its log messages at the end of this file. Set the @code{PKCS11SPY} environment variable to the filename of the PKCS #11 module you actually want to use. Start Mozilla within this environment. There is a different, probably more powerful way to debug Mozilla PKCS #11 libraries. However, to be able to use it, you need to configure and compile the Mozilla NSS sources with @code{--enable-debug}. Instructions can be found at: @uref{https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/nss_tech_notes} Here are a couple of links to more information about implementing a PKCS #11 module for Mozilla: @table @uref @item https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11_Implement Guidelines for implementors of PKCS #11 modules targeting Mozilla @item http://www-archive.mozilla.org/projects/security/pki/pkcs11/ PKCS #11 Conformance Testing @item https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS The Mozilla NSS web page @end table @node Mozilla Compatibility @section Mozilla Compatibility Mozilla has a bug that causes the wrong security device to be unloaded when unloading a security device. Also, the displayed list becomes corrupt. When closing and reopening the security device manager, the list displayed is correct, but in anyway the wrong security module is unloaded. @include lesser.texi @c An index with just one item does not make any sense. @c @node Concept Index @c @unnumbered Concept Index @c @c @printindex cp @bye diff --git a/src/agent.c b/src/agent.c index 68d48ff..bfad3f8 100644 --- a/src/agent.c +++ b/src/agent.c @@ -1,1220 +1,1236 @@ /* agent.c - Talking to gpg-agent. * Copyright (C) 2006, 2007, 2008, 2015, 2019 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # define PATHSEP_C ';' # define WINVER 0x0500 /* Required for AllowSetForegroundWindow. */ # include # include #else # define PATHSEP_C ':' #endif #include #include #include "debug.h" #include "support.h" #include "sexp-parse.h" #include "cert.h" #include "agent.h" /* The global agent context. */ static assuan_context_t agent_ctx; /* Hack required for Windows. */ void gnupg_allow_set_foregound_window (pid_t pid) { if (!pid || pid == (pid_t)(-1)) return; #ifdef HAVE_W32_SYSTEM else if (!AllowSetForegroundWindow (pid)) DEBUG (DBG_CRIT, "AllowSetForegroundWindow(%lu) failed: %u\n", (unsigned long)pid, (unsigned int)GetLastError ()); #endif } /* Establish a connection to a running GPG agent. */ static gpg_error_t agent_connect (assuan_context_t *ctx_r) { gpg_error_t err = 0; assuan_context_t ctx = NULL; char buffer[512]; #ifndef HAVE_W32_SYSTEM DEBUG (DBG_INFO, "agent_connect: uid=%lu euid=%lu", (unsigned long)getuid (), (unsigned long)geteuid ()); #endif /* Use gpgconf to make sure that gpg-agent is started and to obtain * the socket name. For older version of gnupg we will fallback to - * using two gpgconf commands with the same effect. */ - /* FIXME: We should make sure that USER has no spaces. */ - snprintf (buffer, sizeof buffer, "%s %s%s --show-socket --launch gpg-agent", - get_gpgconf_path (), - _scute_opt.user? "--chuid=":"", - _scute_opt.user? _scute_opt.user:""); - err = read_first_line (buffer, buffer, sizeof buffer); - if (gpg_err_code (err) == GPG_ERR_NO_AGENT && is_gnupg_older_than (2, 2, 14)) + * using two gpgconf commands with the same effect. If GnuPG has + * been configured not to autostart the agent by using the + * common.conf mechanism we don't do this either. This is so that + * Scute won't start an gpg-agent on a server with the agent running + * on the desktop. */ + if (_scute_opt.no_autostart && !is_gnupg_older_than (2, 3, 8)) { - snprintf (buffer, sizeof buffer, "%s --launch gpg-agent", + DEBUG (DBG_INFO, "agent_connect: note: no-autostart option found"); + snprintf (buffer, sizeof buffer, "%s --list-dirs agent-socket", get_gpgconf_path ()); - err = read_first_line (buffer, NULL, 0); - if (!err) + err = read_first_line (buffer, buffer, sizeof buffer); + } + else + { + /* FIXME: We should make sure that USER has no spaces. */ + snprintf (buffer, sizeof buffer, + "%s %s%s --show-socket --launch gpg-agent", + get_gpgconf_path (), + _scute_opt.user? "--chuid=":"", + _scute_opt.user? _scute_opt.user:""); + err = read_first_line (buffer, buffer, sizeof buffer); + if (gpg_err_code (err) == GPG_ERR_NO_AGENT + && is_gnupg_older_than (2, 2, 14)) { - snprintf (buffer, sizeof buffer, "%s --list-dirs agent-socket", + snprintf (buffer, sizeof buffer, "%s --launch gpg-agent", get_gpgconf_path ()); - err = read_first_line (buffer, buffer, sizeof buffer); + err = read_first_line (buffer, NULL, 0); + if (!err) + { + snprintf (buffer, sizeof buffer, "%s --list-dirs agent-socket", + get_gpgconf_path ()); + err = read_first_line (buffer, buffer, sizeof buffer); + } } } DEBUG (DBG_INFO, "agent_connect: agent socket is '%s'", buffer); /* Then connect to the socket we got. */ if (!err) { err = assuan_new (&ctx); if (!err) { err = assuan_socket_connect (ctx, buffer, 0, 0); if (!err) { *ctx_r = ctx; if (_scute_opt.debug_flags & DBG_ASSUAN) assuan_set_log_stream (*ctx_r, _scute_debug_stream); } else assuan_release (ctx); } } /* We do not try any harder. If gpg-connect-agent somehow failed * to give us a suitable socket, we probably cannot do better. */ if (err) DEBUG (DBG_CRIT, "cannot connect to GPG agent: %s", gpg_strerror (err)); return err; } /* * Check whether STRING starts with KEYWORD. The keyword is * delimited by end of string, a space or a tab. Returns NULL if not * found or a pointer into STRING to the next non-space character * after the KEYWORD (which may be end of string). */ static char * has_leading_keyword (const char *string, const char *keyword) { size_t n = strlen (keyword); if (!strncmp (string, keyword, n) && (!string[n] || string[n] == ' ' || string[n] == '\t')) { string += n; while (*string == ' ' || *string == '\t') string++; return (char*)string; } return NULL; } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { const char *s; (void)opaque; if ((s = has_leading_keyword (line, "PINENTRY_LAUNCHED"))) { gnupg_allow_set_foregound_window ((pid_t)strtoul (s, NULL, 10)); /* We do not pass errors to avoid breaking other code. */ } else DEBUG (DBG_CRIT, "ignoring gpg-agent inquiry `%s'\n", line); return 0; } /* Send a simple command to the agent. */ static gpg_error_t agent_simple_cmd (assuan_context_t ctx, const char *fmt, ...) { gpg_error_t err; char *optstr; va_list arg; int res; va_start (arg, fmt); res = vasprintf (&optstr, fmt, arg); va_end (arg); if (res < 0) return gpg_error_from_errno (errno); err = assuan_transact (ctx, optstr, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err) DEBUG (DBG_CRIT, "gpg-agent command '%s' failed: %s", optstr, gpg_strerror (err)); free (optstr); return err; } /* Configure the GPG agent at connection CTX. */ static gpg_error_t agent_configure (assuan_context_t ctx) { gpg_error_t err = 0; char *dft_display = NULL; char *dft_ttyname = NULL; char *dft_ttytype = NULL; #if defined(HAVE_SETLOCALE) && (defined(LC_CTYPE) || defined(LC_MESSAGES)) char *old_lc = NULL; char *dft_lc = NULL; #endif char *dft_xauthority = NULL; char *dft_pinentry_user_data = NULL; err = agent_simple_cmd (ctx, "RESET"); if (err) return err; /* Set up display, terminal and locale options. */ dft_display = getenv ("DISPLAY"); if (dft_display) err = agent_simple_cmd (ctx, "OPTION display=%s", dft_display); if (err) return err; dft_ttyname = getenv ("GPG_TTY"); if ((!dft_ttyname || !*dft_ttyname) && ttyname (0)) dft_ttyname = ttyname (0); if (dft_ttyname) { err = agent_simple_cmd (ctx, "OPTION ttyname=%s", dft_ttyname); if (err) return err; } dft_ttytype = getenv ("TERM"); if (dft_ttytype) err = agent_simple_cmd (ctx, "OPTION ttytype=%s", dft_ttytype); if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) old_lc = setlocale (LC_CTYPE, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) return gpg_error_from_errno (errno); } dft_lc = setlocale (LC_CTYPE, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-ctype=%s", dft_lc); if (old_lc) { setlocale (LC_CTYPE, old_lc); free (old_lc); } #endif if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) old_lc = setlocale (LC_MESSAGES, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) err = gpg_error_from_errno (errno); } dft_lc = setlocale (LC_MESSAGES, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-messages=%s", dft_lc); if (old_lc) { setlocale (LC_MESSAGES, old_lc); free (old_lc); } #endif dft_xauthority = getenv ("XAUTHORITY"); if (dft_xauthority) err = agent_simple_cmd (ctx, "OPTION xauthority=%s", dft_xauthority); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; else if (err) return err; dft_pinentry_user_data = getenv ("PINENTRY_USER_DATA"); if (dft_pinentry_user_data) err = agent_simple_cmd (ctx, "OPTION pinentry_user_data=%s", dft_pinentry_user_data); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; err = agent_simple_cmd (ctx, "OPTION allow-pinentry-notify"); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; return err; } /* Check for a broken pipe, that is a lost connection to the agent. * Update the gloabls so that a re-connect is done the next time. * Returns ERR or the modified code GPG_ERR_NO_AGENT. */ static gpg_error_t check_broken_pipe (gpg_error_t err) { /* Note that Scute _currently_ uses GPG_ERR_SOURCE_ANY. */ if (gpg_err_code (err) == GPG_ERR_EPIPE && gpg_err_source (err) == GPG_ERR_SOURCE_ANY) { DEBUG (DBG_INFO, "Broken connection to the gpg-agent"); scute_agent_finalize (); err = gpg_error (GPG_ERR_NO_AGENT); } return err; } /* If the connection to the agent was lost earlier and detected by * check_broken_pipe we try to reconnect. */ static gpg_error_t ensure_agent_connection (void) { gpg_error_t err; if (agent_ctx) return 0; /* Connection still known. */ DEBUG (DBG_INFO, "Re-connecting to gpg-agent"); err = agent_connect (&agent_ctx); if (err) return err; err = agent_configure (agent_ctx); return check_broken_pipe (err); } /* Try to connect to the agent via socket. Handle the server's initial greeting. This is used only once when SCute is loaded. Re-connection is done using ensure_agent_connection. */ gpg_error_t scute_agent_initialize (void) { gpg_error_t err = 0; if (agent_ctx) { DEBUG (DBG_CRIT, "GPG Agent connection already established"); return 0; } DEBUG (DBG_INFO, "Establishing connection to gpg-agent"); err = agent_connect (&agent_ctx); if (err) return err; err = agent_configure (agent_ctx); if (err) scute_agent_finalize (); return err; } /* Call the agent to get the list of devices. */ gpg_error_t scute_agent_serialno (void) { gpg_error_t err = 0; err = ensure_agent_connection (); if (err) return err; err = assuan_transact (agent_ctx, "SCD SERIALNO --all", NULL, NULL, NULL, NULL, NULL, NULL); return err; } struct keyinfo_parm { int require_card; gpg_error_t error; struct keyinfo *list; }; /* Callback function for agent_keyinfo_list. */ static gpg_error_t keyinfo_list_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct keyinfo_parm *parm = opaque; const char *keyword = line; int keywordlen; struct keyinfo *keyinfo = NULL; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 7 && !memcmp (keyword, "KEYINFO", keywordlen)) { const char *s; int n; struct keyinfo **l_p = &parm->list; /* It's going to append the information at the end. */ while ((*l_p)) l_p = &(*l_p)->next; keyinfo = calloc (1, sizeof *keyinfo); if (!keyinfo) goto alloc_error; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (n != 40) goto parm_error; memcpy (keyinfo->grip, line, 40); keyinfo->grip[40] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (*line++ != 'T') { if (!parm->require_card) { /* It's not on card, skip the status line. */ free (keyinfo); return 0; } else goto parm_error; } if (!*line) goto parm_error; while (spacep (line)) line++; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n) goto skip; keyinfo->serialno = malloc (n+1); if (!keyinfo->serialno) goto alloc_error; memcpy (keyinfo->serialno, line, n); keyinfo->serialno[n] = 0; line = s; skip: *l_p = keyinfo; } return err; alloc_error: free (keyinfo->serialno); free (keyinfo); if (!parm->error) parm->error = gpg_error_from_syserror (); return 0; parm_error: free (keyinfo); if (!parm->error) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); return 0; } void scute_agent_free_keyinfo (struct keyinfo *l) { struct keyinfo *l_next; for (; l; l = l_next) { l_next = l->next; free (l->serialno); free (l); } } gpg_error_t scute_agent_keyinfo_list (struct keyinfo **keyinfo_p) { gpg_error_t err; err = ensure_agent_connection (); if (!err) { struct keyinfo_parm parm; parm.require_card = 1; parm.error = 0; parm.list = NULL; err = assuan_transact (agent_ctx, (_scute_opt.only_marked? "KEYINFO --list --need-attr=Use-for-p11": "KEYINFO --list"), NULL, NULL, /* No data call back */ NULL, NULL, /* No inquiry call back */ keyinfo_list_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *keyinfo_p = parm.list; else scute_agent_free_keyinfo (parm.list); } return err; } /* Return a new malloced string by unescaping the string S. Escaping is percent escaping and '+'/space mapping. A binary nul will silently be replaced by a 0xFF. Function returns NULL to indicate an out of memory status. */ static char * unescape_status_string (const unsigned char *src) { char *buffer; char *dst; buffer = malloc (strlen (src) + 1); if (!buffer) return NULL; dst = buffer; while (*src) { if (*src == '%' && src[1] && src[2]) { src++; *dst = xtoi_2 (src); if (*dst == '\0') *dst = '\xff'; dst++; src += 2; } else if (*src == '+') { *(dst++) = ' '; src++; } else *(dst++) = *(src++); } *dst = 0; return buffer; } /* We only support RSA signatures up to 4096 bits. */ #define MAX_SIGNATURE_BITS 4096 /* Enough space to hold a 4096 bit RSA signature in an S-expression. */ #define MAX_SIGNATURE_LEN 640 /* FIXME: magic value */ struct signature { unsigned char data[MAX_SIGNATURE_LEN]; int len; }; static gpg_error_t pksign_cb (void *opaque, const void *buffer, size_t length) { struct signature *sig = opaque; if (sig->len + length > MAX_SIGNATURE_LEN) { DEBUG (DBG_INFO, "maximum signature length exceeded"); return gpg_error (GPG_ERR_BAD_DATA); } memcpy (&sig->data[sig->len], buffer, length); sig->len += length; return 0; } /* Parse the result of an pksign operation which is a s-expression in canonical form that looks like: RSA (7:sig-val(3:rsa(1:s:))) ECDSA (7:sig-val(5:ecdsa(1:r:)(1:s:))) EDDSA (7:sig-val(5:eddsa(1:r:)(1:s:))) The raw result is stored in RESULT of size *LEN. For RSA, *LEN is adjusted to the actual size. */ static gpg_error_t pksign_parse_result (const struct signature *sig, unsigned char *result, unsigned int *len) { gpg_error_t err; const unsigned char *s = sig->data; size_t n; int depth; int is_ecc; if (*s++ != '(') gpg_error (GPG_ERR_INV_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "sig-val")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (smatch (&s, n, "rsa")) is_ecc = 0; else if (smatch (&s, n, "ecdsa")) is_ecc = 1; else if (smatch (&s, n, "eddsa")) is_ecc = 1; else return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (is_ecc) { if (! smatch (&s, n, "r")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if ((*len)/2 < (unsigned int) n) return gpg_error (GPG_ERR_INV_LENGTH); /* Fixup for EdDSA, removing the prefix. */ if (n == (*len)/2 + 1) s++; /* Add possibly removed zero bytes by gpg-agent, to be fixed-size. */ memset (result, 0, *len); memcpy (result + (*len)/2 - n, s, n); s += n; depth = 1; err = sskip (&s, &depth); if (err) return err; if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "s")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if ((*len)/2 < (unsigned int) n) return gpg_error (GPG_ERR_INV_LENGTH); /* Add possibly removed zero byte, to be fixed-size. */ memcpy (result + (*len) - n, s, n); s += n; } else { /* RSA */ if (! smatch (&s, n, "s")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); /* Remove a possible prepended zero byte. */ if (!*s && n > 1) { n -= 1; s += 1; } if (*len < (unsigned int) n) return gpg_error (GPG_ERR_INV_LENGTH); *len = (unsigned int) n; memcpy (result, s, n); s += n; } depth = 3; err = sskip (&s, &depth); if (err) return err; if (s - sig->data != sig->len || depth != 0) return gpg_error (GPG_ERR_INV_SEXP); return 0; } /* Decodes the hash DATA of size LEN (if necessary). Returns a pointer to the raw hash data in R_DATA, the size in R_LEN, and the name of the hash function in R_HASH. Prior to TLSv1.2, the hash function was the concatenation of MD5 and SHA1 applied to the data respectively, and no encoding was applied. From TLSv1.2 on, the hash value is prefixed with an hash identifier and encoded using ASN1. FIXME: Reference. */ static gpg_error_t decode_hash (const unsigned char *data, int len, const unsigned char **r_data, size_t *r_len, const char **r_hash) { static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */ { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C }; static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */ { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 }; static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */ { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 }; static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */ { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 }; #define HANDLE(hash,hashlen) \ if (len == sizeof hash ## _prefix + (hashlen) \ && !memcmp (data, hash ## _prefix, sizeof hash ## _prefix)) \ { \ *r_data = data + sizeof hash ## _prefix; \ *r_len = hashlen; \ *r_hash = #hash; \ } if (len == 36) { /* Prior to TLSv1.2, a combination of MD5 and SHA1 was used. */ *r_data = data; *r_len = 36; *r_hash = "tls-md5sha1"; } /* TLSv1.2 encodes the hash value using ASN1. */ else HANDLE (sha1, 20) else HANDLE (rmd160, 20) else HANDLE (sha224, 28) else HANDLE (sha256, 32) else HANDLE (sha384, 48) else HANDLE (sha512, 64) else return gpg_error (GPG_ERR_INV_ARG); #undef HANDLE return 0; } struct sethash_inq_parm_s { assuan_context_t ctx; const void *data; size_t datalen; }; /* This is the inquiry callback required by the SETHASH command. */ static gpg_error_t sethash_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct sethash_inq_parm_s *parm = opaque; if (has_leading_keyword (line, "TBSDATA")) { err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else err = default_inq_cb (opaque, line); return err; } /* Call the agent to sign (DATA,LEN) using the key described by * HEXGRIP. Stores the signature in SIG_RESULT and its length at * SIG_LEN; SIGLEN must initially point to the allocated size of * SIG_RESULT. */ gpg_error_t scute_agent_sign (const char *hexgrip, CK_MECHANISM_TYPE mechtype, unsigned char *data, int len, unsigned char *sig_result, unsigned int *sig_len) { char cmd[150]; gpg_error_t err; const char *hash; const unsigned char *raw_data; size_t raw_len; #define MAX_DATA_LEN 64 /* Size of an SHA512 sum. */ unsigned char pretty_data[2 * MAX_DATA_LEN + 1]; int i; struct signature sig; int nopadding = (mechtype != CKM_RSA_PKCS); sig.len = 0; if (sig_len == NULL) return gpg_error (GPG_ERR_INV_ARG); if (nopadding) { raw_data = data; raw_len = len; hash = NULL; } else { err = decode_hash (data, len, &raw_data, &raw_len, &hash); if (err) return err; } if (!hexgrip || !sig_result) return gpg_error (GPG_ERR_INV_ARG); snprintf (cmd, sizeof (cmd), "SIGKEY %s", hexgrip); err = ensure_agent_connection (); if (err) return err; err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; if (nopadding) { struct sethash_inq_parm_s parm; const char *more_option = ""; parm.ctx = agent_ctx; parm.data = raw_data; parm.datalen = raw_len; if (mechtype == CKM_RSA_X_509) { if (raw_len && raw_data[raw_len -1] == 0xBC) more_option = "--pss"; } else if (mechtype == CKM_ECDSA) { /* Determine the hash by the length of input data. */ if (len == 20) hash = "sha1"; else if (len == 32) hash = "sha256"; else if (len == 48) hash = "sha384"; else if (len == 64) hash = "sha512"; } else if (mechtype == CKM_ECDSA_SHA1) hash = "sha1"; else if (mechtype == CKM_ECDSA_SHA256) hash = "sha256"; else if (mechtype == CKM_ECDSA_SHA384) hash = "sha384"; else if (mechtype == CKM_ECDSA_SHA512) hash = "sha512"; if (hash) goto with_hash; snprintf (cmd, sizeof (cmd), "SETHASH %s --inquire", more_option); err = assuan_transact (agent_ctx, cmd, NULL, NULL, sethash_inq_cb, &parm, NULL, NULL); } else { with_hash: for (i = 0; i < raw_len; i++) snprintf (&pretty_data[2 * i], 3, "%02X", raw_data[i]); pretty_data[2 * raw_len] = '\0'; snprintf (cmd, sizeof (cmd), "SETHASH --hash=%s %s", hash, pretty_data); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); } err = check_broken_pipe (err); if (err) return err; err = assuan_transact (agent_ctx, "PKSIGN", pksign_cb, &sig, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; err = pksign_parse_result (&sig, sig_result, sig_len); return err; } struct pkdecrypt_parm_s { unsigned int len; unsigned char data[512]; assuan_context_t ctx; const unsigned char *ciphertext; size_t ciphertextlen; }; static gpg_error_t pkdecrypt_data_cb (void *opaque, const void *buffer, size_t length) { struct pkdecrypt_parm_s *parm = opaque; if (parm->len + length > sizeof parm->data) { DEBUG (DBG_INFO, "maximum decryption result length exceeded"); return gpg_error (GPG_ERR_BAD_DATA); } memcpy (parm->data + parm->len, buffer, length); parm->len += length; return 0; } /* Handle the inquiries from pkdecrypt. Note, we only send the data, * assuan_transact takes care of flushing and writing the "END". */ static gpg_error_t pkdecrypt_inq_cb (void *opaque, const char *line) { struct pkdecrypt_parm_s *parm = opaque; gpg_error_t err; const char *keyword = line; int keywordlen; for (keywordlen = 0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 10 && !memcmp (keyword, "CIPHERTEXT", 10)) err = assuan_send_data (parm->ctx, parm->ciphertext, parm->ciphertextlen); else err = default_inq_cb (NULL, line); return err; } /* Parse the result of a pkdecrypt operation which is an s-expression * in canonical form that looks like * (5:value:). * * The raw result is stored in RESULT which has a size of *R_LEN, and * *R_LEN is adjusted to the actual size. */ static gpg_error_t pkdecrypt_parse_result (struct pkdecrypt_parm_s *ctx, unsigned char *result, unsigned int *r_len) { char *buf = ctx->data; size_t len = ctx->len; char *endp, *raw; size_t n, rawlen; if (len < 13 || memcmp (buf, "(5:value", 8) ) return gpg_error (GPG_ERR_INV_SEXP); len -= 8; buf += 8; n = strtoul (buf, &endp, 10); if (!n || *endp != ':') return gpg_error (GPG_ERR_INV_SEXP); endp++; if ((endp-buf)+n > len) return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */ /* Let (RAW,RAWLEN) describe the pkcs#1 block and remove that padding. */ raw = endp; rawlen = n; if (rawlen < 10) /* 0x00 + 0x02 + <1_random> + 0x00 + <16-session> */ return gpg_error (GPG_ERR_INV_SESSION_KEY); if (raw[0] || raw[1] != 2 ) /* Wrong block type version. */ return gpg_error (GPG_ERR_INV_SESSION_KEY); for (n=2; n < rawlen && raw[n]; n++) /* Skip the random bytes. */ ; if (n+1 >= rawlen || raw[n] ) return gpg_error (GPG_ERR_INV_SESSION_KEY); n++; /* Skip the zero byte */ if (*r_len < (rawlen - n)) return gpg_error (GPG_ERR_TOO_LARGE); memcpy (result, raw + n, rawlen - n); *r_len = rawlen - n; return 0; } /* Call the agent to decrypt (ENCDATA,ENCDATALEN) using the key * described by HEXGRIP. Stores the plaintext at R_PLAINDATA and its * length at R_PLAINDATALEN; R_PLAINDATALEN must initially point to * the allocated size of R_PLAINDATA and is updated to the actual used * size on return. */ gpg_error_t scute_agent_decrypt (const char *hexgrip, unsigned char *encdata, int encdatalen, unsigned char *r_plaindata, unsigned int *r_plaindatalen) { char cmd[150]; gpg_error_t err; struct pkdecrypt_parm_s pkdecrypt; char *s_data; size_t s_datalen; if (!hexgrip || !encdata || !encdatalen || !r_plaindatalen) return gpg_error (GPG_ERR_INV_ARG); if (!r_plaindata) { /* Fixme: We do not return the minimal required length but our * internal buffer size. */ pkdecrypt.len = *r_plaindatalen; *r_plaindatalen = sizeof pkdecrypt.data - 1; if (pkdecrypt.len > sizeof pkdecrypt.data - 1) return gpg_error (GPG_ERR_INV_LENGTH); return 0; } err = ensure_agent_connection (); if (err) return err; snprintf (cmd, sizeof (cmd), "SETKEY %s", hexgrip); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; /* Convert the input into an appropriate s-expression as expected by * gpg-agent which is: * * (enc-val * (flags pkcs1) * (rsa * (a VALUE))) * * Out of convenience we append a non-counted extra nul to the * created canonical s-expression. */ s_data = malloc (100 + encdatalen); if (!s_data) return gpg_error_from_syserror (); snprintf (s_data, 50, "(7:enc-val(5:flags5:pkcs1)(3:rsa(1:a%d:", encdatalen); s_datalen = strlen (s_data); memcpy (s_data + s_datalen, encdata, encdatalen); s_datalen += encdatalen; memcpy (s_data + s_datalen, ")))", 4); s_datalen += 3; pkdecrypt.len = 0; pkdecrypt.ctx = agent_ctx; pkdecrypt.ciphertext = s_data; pkdecrypt.ciphertextlen = s_datalen; err = assuan_transact (agent_ctx, "PKDECRYPT", pkdecrypt_data_cb, &pkdecrypt, pkdecrypt_inq_cb, &pkdecrypt, NULL, NULL); err = check_broken_pipe (err); if (!err) err = pkdecrypt_parse_result (&pkdecrypt, r_plaindata, r_plaindatalen); free (s_data); return err; } /* Determine if FPR is trusted. */ gpg_error_t scute_agent_is_trusted (const char *fpr, bool *is_trusted) { gpg_error_t err; bool trusted = false; char cmd[150]; err = ensure_agent_connection (); if (err) return err; snprintf (cmd, sizeof (cmd), "ISTRUSTED %s", fpr); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err && gpg_err_code (err) != GPG_ERR_NOT_TRUSTED) return err; else if (!err) trusted = true; *is_trusted = trusted; return 0; } #define GET_CERT_INIT_SIZE 2048 struct get_cert_s { unsigned char *cert_der; int cert_der_len; int cert_der_size; }; struct random_request { unsigned char *buffer; size_t len; }; gpg_error_t get_challenge_data_cb (void *opaque, const void *line, size_t len) { struct random_request *request = opaque; if (len != request->len) return gpg_error (GPG_ERR_INV_LENGTH); memcpy (request->buffer, line, len); return 0; } gpg_error_t scute_agent_get_random (unsigned char *data, size_t len) { char command[16]; gpg_error_t err; struct random_request request; err = ensure_agent_connection (); if (err) return err; snprintf (command, sizeof(command), "SCD RANDOM %zu", len); request.buffer = data; request.len = len; err = assuan_transact (agent_ctx, command, get_challenge_data_cb, &request, NULL, NULL, NULL, NULL); err = check_broken_pipe (err); return err; } void scute_agent_finalize (void) { if (!agent_ctx) { DEBUG (DBG_CRIT, "no GPG Agent connection established"); return; } DEBUG (DBG_INFO, "releasing agent context"); assuan_release (agent_ctx); agent_ctx = NULL; } diff --git a/src/options.h b/src/options.h index e9533f0..0ed034a 100644 --- a/src/options.h +++ b/src/options.h @@ -1,39 +1,40 @@ /* options.h - Global options. * Copyright (C) 2020 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #ifndef OPTIONS_H #define OPTIONS_H 1 /* Global options. */ typedef struct { char *user; int debug_flags; int only_marked; int assume_single_threaded; + int no_autostart; /* Do not autostart gpg-agent. */ } _scute_opt_t; extern _scute_opt_t _scute_opt; /*-- readconf.c --*/ void _scute_read_conf (void); #endif /*OPTIONS_H*/ diff --git a/src/readconf.c b/src/readconf.c index bc7d424..cfede1b 100644 --- a/src/readconf.c +++ b/src/readconf.c @@ -1,95 +1,114 @@ /* readconf.c - Read configuration file * Copyright (C) 2020 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #define GPGRT_ENABLE_ARGPARSE_MACROS 1 #include #include "options.h" _scute_opt_t _scute_opt; static const char * my_strusage (int level) { const char *p; switch (level) { case 9: p = "LGPL-2.1-or-later"; break; case 11: p = "scute"; break; default: p = NULL; } return p; } /* Read the global configuration file. This functon needs to be * called early. */ void _scute_read_conf (void) { enum { oNull = 500, oUser, oDebug, oLogfile, oOnlyMarked, - oAssumeSingleThreaded }; + oAssumeSingleThreaded, oNoAutostart }; gpgrt_opt_t opts[] = { ARGPARSE_s_s(oUser, "user", NULL ), ARGPARSE_s_s(oDebug, "debug", NULL), ARGPARSE_s_s(oLogfile, "log-file", NULL), ARGPARSE_s_n(oOnlyMarked, "only-marked", NULL), ARGPARSE_s_n(oAssumeSingleThreaded, "assume-single-threaded", NULL), ARGPARSE_end() }; + gpgrt_opt_t commonopts[] = + { + ARGPARSE_s_s(oNoAutostart, "no-autostart", NULL ), + ARGPARSE_end() + }; int dummy_argc = 0; char **dummy_argv = NULL; gpgrt_argparse_t pargs = { &dummy_argc, &dummy_argv, ARGPARSE_FLAG_SYS }; gpgrt_set_strusage (my_strusage); gpgrt_set_confdir (GPGRT_CONFDIR_SYS, "/etc/gnupg"); while (gpgrt_argparser (&pargs, opts, "scute.conf")) { switch (pargs.r_opt) { case oUser: free (_scute_opt.user); _scute_opt.user = strdup (pargs.r.ret_str); break; case oDebug: _scute_opt.debug_flags = 1; break; case oLogfile: break; case oAssumeSingleThreaded: _scute_opt.assume_single_threaded = 1; break; case oOnlyMarked: _scute_opt.only_marked = 1; break; case ARGPARSE_CONFFILE: break; default : pargs.err = ARGPARSE_PRINT_WARNING; break; } } gpgrt_argparse (NULL, &pargs, NULL); + pargs.flags = (ARGPARSE_FLAG_NOVERSION + | ARGPARSE_FLAG_SYS + | ARGPARSE_FLAG_USER + ); + while (gpgrt_argparser (&pargs, commonopts, "common.conf")) + { + if (pargs.r_opt == oNoAutostart) + _scute_opt.no_autostart = 1; + } + + gpgrt_argparse (NULL, &pargs, NULL); + + + }