diff --git a/NEWS b/NEWS index 1efb6e98e..7a69e256b 100644 --- a/NEWS +++ b/NEWS @@ -1,4214 +1,4214 @@ Noteworthy changes in version 2.2.17 (unreleased) ------------------------------------------------- Noteworthy changes in version 2.2.16 (2019-05-28) ------------------------------------------------- * gpg,gpgsm: Fix deadlock on Windows due to a keybox sharing violation. [#4505] * gpg: Allow deletion of subkeys with --delete-key. This finally makes the bang-suffix work as expected for that command. [#4457] * gpg: Replace SHA-1 by SHA-256 in self-signatures when updating them with --quick-set-expire or --quick-set-primary-uid. [#4508] * gpg: Improve the photo image viewer selection. [#4334] * gpg: Fix decryption with --use-embedded-filename. [#4500] * gpg: Remove hints on using the --keyserver option. [#4512] * gpg: Fix export of certain secret keys with comments. [#4490] * gpg: Reject too long user-ids in --quick-gen-key. [#4532] * gpg: Fix a double free in the best key selection code. [#4462] * gpg: Fix the key generation dialog for switching back from EdDSA to ECDSA. * gpg: Use AES-192 with SHA-384 to comply with RFC-6637. * gpg: Use only the addrspec from the Signer's UID subpacket to mitigate a problem with another implementation. * gpg: Skip invalid packets during a keyring listing and sync diagnostics with the output. * gpgsm: Avoid confusing diagnostic when signing with the default key. [#4535] * agent: Do not delete any secret key in --dry-run mode. * agent: Fix failures on 64 bit big-endian boxes related to URIs in a keyfile. [#4501] * agent: Stop scdaemon after a reload with disable-scdaemon newly configured. [#4326] * dirmngr: Improve caching algorithm for WKD domains. * dirmngr: Support other hash algorithms than SHA-1 for OCSP. [#3966] * gpgconf: Make --homedir work for --launch. [#4496] * gpgconf: Before --launch check for a valid config file. [#4497] * wkd: Do not import more than 5 keys from one WKD address. * wkd: Accept keys which are stored in armored format in the directory. * The installer for Windows now comes with signed binaries. Release-info: https://dev.gnupg.org/T4509 See-also: gnupg-announce/2019q2/000438.html Noteworthy changes in version 2.2.15 (2019-03-26) ------------------------------------------------- * sm: Fix --logger-fd and --status-fd on Windows for non-standard file descriptors. * sm: Allow decryption even if expired keys are configured. [#4431] * agent: Change command KEYINFO to print ssh fingerprints with other hash algos. * dirmngr: Fix build problems on Solaris due to the use of reserved symbol names. [#4420] * wkd: New commands --print-wkd-hash and --print-wkd-url for gpg-wks-client. Release-info: https://dev.gnupg.org/T4434 See-also: gnupg-announce/2019q1/000436.html Noteworthy changes in version 2.2.14 (2019-03-19) ------------------------------------------------- * gpg: Allow import of PGP desktop exported secret keys. Also avoid importing secret keys if the secret keyblock is not valid. [#4392] * gpg: Do not error out on version 5 keys in the local keyring. * gpg: Make invalid primary key algo obvious in key listings. * sm: Do not mark a certificate in a key listing as de-vs compliant if its use for a signature will not be possible. * sm: Fix certificate creation with key on card. * sm: Create rsa3072 bit certificates by default. * sm: Print Yubikey attestation extensions with --dump-cert. * agent: Fix cancellation handling for scdaemon. * agent: Support --mode=ssh option for CLEAR_PASSPHRASE. [#4340] * scd: Fix flushing of the CA-FPR DOs in app-openpgp. * scd: Avoid a conflict error with the "undefined" app. * dirmngr: Add CSRF protection exception for protonmail. * dirmngr: Fix build problems with gcc 9 in libdns. * gpgconf: New option --show-socket for use with --launch. * gpgtar: Make option -C work for archive creation. Release-info: https://dev.gnupg.org/T4412 See-also: gnupg-announce/2019q1/000435.html Noteworthy changes in version 2.2.13 (2019-02-12) ------------------------------------------------- * gpg: Implement key lookup via keygrip (using the & prefix). * gpg: Allow generating Ed25519 key from existing key. * gpg: Emit an ERROR status line if no key was found with -k. * gpg: Stop early when trying to create a primary Elgamal key. [#4329] * gpgsm: Print the card's key algorithms along with their keygrips in interactive key generation. * agent: Clear bogus pinentry cache in the error case. [#4348] * scd: Support "acknowledge button" feature. * scd: Fix for USB INTERRUPT transfer. [#4308] * wks: Do no use compression for the the encrypted challenge and response. Release-info: https://dev.gnupg.org/T4290 See-also: gnupg-announce/2019q1/000434.html Noteworthy changes in version 2.2.12 (2018-12-14) ------------------------------------------------- * tools: New commands --install-key and --remove-key for gpg-wks-client. This allows to prepare a Web Key Directory on a local file system for later upload to a web server. * gpg: New --list-option "show-only-fpr-mbox". This makes the use of the new gpg-wks-client --install-key command easier on Windows. * gpg: Improve processing speed when --skip-verify is used. * gpg: Fix a bug where a LF was accidentally written to the console. * gpg: --card-status now shwos whether a card has the new KDF feature enabled. * agent: New runtime option --s2k-calibration=MSEC. New configure option --with-agent-s2k-calibration=MSEC. [#3399] * dirmngr: Try another keyserver from the pool on receiving a 502, 503, or 504 error. [#4175] * dirmngr: Avoid possible CSRF attacks via http redirects. A HTTP query will not anymore follow a 3xx redirect unless the Location header gives the same host. If the host is different only the host and port is taken from the Location header and the original path and query parts are kept. * dirmngr: New command FLUSHCRL to flush all CRLS from disk and memory. [#3967] * New simplified Chinese translation (zh_CN). Release-info: https://dev.gnupg.org/T4289 See-also: gnupg-announce/2018q4/000433.html Noteworthy changes in version 2.2.11 (2018-11-06) ------------------------------------------------- * gpgsm: Fix CRL loading when intermediate certicates are not yet trusted. * gpgsm: Fix an error message about the digest algo. [#4219] * gpg: Fix a wrong warning due to new sign usage check introduced with 2.2.9. [#4014] * gpg: Print the "data source" even for an unsuccessful keyserver query. * gpg: Do not store the TOFU trust model in the trustdb. This allows to enable or disable a TOFO model without triggering a trustdb rebuild. [#4134] * scd: Fix cases of "Bad PIN" after using "forcesig". [#4177] * agent: Fix possible hang in the ssh handler. [#4221] * dirmngr: Tack the unmodified mail address to a WKD request. See commit a2bd4a64e5b057f291a60a9499f881dd47745e2f for details. * dirmngr: Tweak diagnostic about missing LDAP server file. * dirmngr: In verbose mode print the OCSP responder id. * dirmngr: Fix parsing of the LDAP port. [#4230] * wks: Add option --directory/-C to the server. Always build the server on Unix systems. * wks: Add option --with-colons to the client. Support sites which use the policy file instead of the submission-address file. * Fix EBADF when gpg et al. are called by broken CGI scripts. * Fix some minor memory leaks and bugs. Release-info: https://dev.gnupg.org/T4233 See-also: gnupg-announce/2018q4/000432.html Noteworthy changes in version 2.2.10 (2018-08-30) ------------------------------------------------- * gpg: Refresh expired keys originating from the WKD. [#2917] * gpg: Use a 256 KiB limit for a WKD imported key. * gpg: New option --known-notation. [#4060] * scd: Add support for the Trustica Cryptoucan reader. * agent: Speed up starting during on-demand launching. [#3490] * dirmngr: Validate SRV records in WKD queries. Release-info: https://dev.gnupg.org/T4112 See-also: gnupg-announce/2018q3/000428.html Noteworthy changes in version 2.2.9 (2018-07-12) ------------------------------------------------ * dirmngr: Fix recursive resolver mode and other bugs in the libdns code. [#3374,#3803,#3610] * dirmngr: When using libgpg-error 1.32 or later a GnuPG build with NTBTLS support (e.g. the standard Windows installer) does not anymore block for dozens of seconds before returning data. * gpg: Fix bug in --show-keys which actually imported revocation certificates. [#4017] * gpg: Ignore too long user-ID and comment packets. [#4022] * gpg: Fix crash due to bad German translation. Improved printf format compile time check. * gpg: Handle missing ISSUER sub packet gracefully in the presence of the new ISSUER_FPR. [#4046] * gpg: Allow decryption using several passphrases in most cases. [#3795,#4050] * gpg: Command --show-keys now enables the list options show-unusable-uids, show-unusable-subkeys, show-notations and show-policy-urls by default. * gpg: Command --show-keys now prints revocation certificates. [#4018] * gpg: Add revocation reason to the "rev" and "rvs" records of the option --with-colons. [#1173] * gpg: Export option export-clean does now remove certain expired subkeys; export-minimal removes all expired subkeys. [#3622] * gpg: New "usage" property for the drop-subkey filters. [#4019] Release-info: https://dev.gnupg.org/T4036 See-also: gnupg-announce/2018q3/000427.html Noteworthy changes in version 2.2.8 (2018-06-08) ------------------------------------------------ * gpg: Decryption of messages not using the MDC mode will now lead to a hard failure even if a legacy cipher algorithm was used. The option --ignore-mdc-error can be used to turn this failure into a warning. Take care: Never use that option unconditionally or without a prior warning. * gpg: The MDC encryption mode is now always used regardless of the cipher algorithm or any preferences. For testing --rfc2440 can be used to create a message without an MDC. * gpg: Sanitize the diagnostic output of the original file name in verbose mode. [#4012,CVE-2018-12020] * gpg: Detect suspicious multiple plaintext packets in a more reliable way. [#4000] * gpg: Fix the duplicate key signature detection code. [#3994] * gpg: The options --no-mdc-warn, --force-mdc, --no-force-mdc, --disable-mdc and --no-disable-mdc have no more effect. * gpg: New command --show-keys. * agent: Add DBUS_SESSION_BUS_ADDRESS and a few other envvars to the list of startup environment variables. [#3947] See-also: gnupg-announce/2018q2/000425.html Noteworthy changes in version 2.2.7 (2018-05-02) ------------------------------------------------ * gpg: New option --no-symkey-cache to disable the passphrase cache for symmetrical en- and decryption. * gpg: The ERRSIG status now prints the fingerprint if that is part of the signature. * gpg: Relax emitting of FAILURE status lines * gpg: Add a status flag to "sig" lines printed with --list-sigs. * gpg: Fix "Too many open files" when using --multifile. [#3951] * ssh: Return an error for unknown ssh-agent flags. [#3880] * dirmngr: Fix a regression since 2.1.16 which caused corrupted CRL caches under Windows. [#2448,#3923] * dirmngr: Fix a CNAME problem with pools and TLS. Also use a fixed mapping of keys.gnupg.net to sks-keyservers.net. [#3755] * dirmngr: Try resurrecting dead hosts earlier (from 3 to 1.5 hours). * dirmngr: Fallback to CRL if no default OCSP responder is configured. * dirmngr: Implement CRL fetching via https. Here a redirection to http is explictly allowed. * dirmngr: Make LDAP searching and CRL fetching work under Windows. This stopped working with 2.1. [#3937] * agent,dirmngr: New sub-command "getenv" for "getinfo" to ease debugging. See-also: gnupg-announce/2018q2/000424.html Noteworthy changes in version 2.2.6 (2018-04-09) ------------------------------------------------ * gpg,gpgsm: New option --request-origin to pretend requests coming from a browser or a remote site. * gpg: Fix race condition on trustdb.gpg updates due to too early released lock. [#3839] * gpg: Emit FAILURE status lines in almost all cases. [#3872] * gpg: Implement --dry-run for --passwd to make checking a key's passphrase straightforward. * gpg: Make sure to only accept a certification capable key for key signatures. [#3844] * gpg: Better user interaction in --card-edit for the factory-reset sub-command. * gpg: Improve changing key attributes in --card-edit by adding an explicit "key-attr" sub-command. [#3781] * gpg: Print the keygrips in the --card-status. * scd: Support KDF DO setup. [#3823] * scd: Fix some issues with PC/SC on Windows. [#3825] * scd: Fix suspend/resume handling in the CCID driver. * agent: Evict cached passphrases also via a timer. [#3829] * agent: Use separate passphrase caches depending on the request origin. [#3858] * ssh: Support signature flags. [#3880] * dirmngr: Handle failures related to missing IPv6 support gracefully. [#3331] * Fix corner cases related to specified home directory with drive letter on Windows. [#3720] * Allow the use of UNC directory names as homedir. [#3818] See-also: gnupg-announce/2018q2/000421.html Noteworthy changes in version 2.2.5 (2018-02-22) ------------------------------------------------ * gpg: Allow the use of the "cv25519" and "ed25519" short names in addition to the canonical curve names in --batch --gen-key. * gpg: Make sure to print all secret keys with option --list-only and --decrypt. [#3718] * gpg: Fix the use of future-default with --quick-add-key for signing keys. [#3747] * gpg: Select a secret key by checking availability under gpg-agent. [#1967] * gpg: Fix reversed prompt texts for --only-sign-text-ids. [#3787] * gpg,gpgsm: Fix detection of bogus keybox blobs on 32 bit systems. [#3770] * gpgsm: Fix regression since 2.1 in --export-secret-key-raw which got $d mod (q-1)$ wrong. Note that most tools automatically fixup that parameter anyway. * ssh: Fix a regression in getting the client'd PID on *BSD and macOS. * scd: Support the KDF Data Object of the OpenPGP card 3.3. [#3152] * scd: Fix a regression in the internal CCID driver for certain card readers. [#3508] * scd: Fix a problem on NetBSD killing scdaemon on gpg-agent shutdown. [#3778] * dirmngr: Improve returned error description on failure of DNS resolving. [#3756] * wks: Implement command --install-key for gpg-wks-server. * Add option STATIC=1 to the Speedo build system to allow a build with statically linked versions of the core GnuPG libraries. Also use --enable-wks-tools by default by Speedo builds for Unix. See-also: gnupg-announce/2018q1/000420.html Noteworthy changes in version 2.2.4 (2017-12-20) ------------------------------------------------ * gpg: Change default preferences to prefer SHA512. * gpg: Print a warning when more than 150 MiB are encrypted using a cipher with 64 bit block size. * gpg: Print a warning if the MDC feature has not been used for a message. * gpg: Fix regular expression of domain addresses in trust signatures. [#2923] * agent: New option --auto-expand-secmem to help with high numbers of concurrent connections. Requires libgcrypt 1.8.2 for having an effect. [#3530] * dirmngr: Cache responses of WKD queries. * gpgconf: Add option --status-fd. * wks: Add commands --check and --remove-key to gpg-wks-server. * Increase the backlog parameter of the daemons to 64 and add option --listen-backlog. * New configure option --enable-run-gnupg-user-socket to first try a socket directory which is not removed by systemd at session end. See-also: gnupg-announce/2017q4/000419.html Noteworthy changes in version 2.2.3 (2017-11-20) ------------------------------------------------ * gpgsm: Fix initial keybox creation on Windows. [#3507] * dirmngr: Fix crash in case of a CRL loading error. [#3510] * Fix the name of the Windows registry key. [Git#4f5afaf1fd] * gpgtar: Fix wrong behaviour of --set-filename. [#3500] * gpg: Silence AKL retrieval messages. [#3504] * agent: Use clock or clock_gettime for calibration. [#3056] * agent: Improve robustness of the shutdown pending state. [Git#7ffedfab89] See-also: gnupg-announce/2017q4/000417.html Noteworthy changes in version 2.2.2 (2017-11-07) ------------------------------------------------ * gpg: Avoid duplicate key imports by concurrently running gpg processes. [#3446] * gpg: Fix creating on-disk subkey with on-card primary key. [#3280] * gpg: Fix validity retrieval for multiple keyrings. [Debian#878812] * gpg: Fix --dry-run and import option show-only for secret keys. * gpg: Print "sec" or "sbb" for secret keys with import option import-show. [#3431] * gpg: Make import less verbose. [#3397] * gpg: Add alias "Key-Grip" for parameter "Keygrip" and new parameter "Subkey-Grip" to unattended key generation. [#3478] * gpg: Improve "factory-reset" command for OpenPGP cards. [#3286] * gpg: Ease switching Gnuk tokens into ECC mode by using the magic keysize value 25519. * gpgsm: Fix --with-colon listing in crt records for fields > 12. * gpgsm: Do not expect X.509 keyids to be unique. [#1644] * agent: Fix stucked Pinentry when using --max-passphrase-days. [#3190] * agent: New option --s2k-count. [#3276 (workaround)] * dirmngr: Do not follow https-to-http redirects. [#3436] * dirmngr: Reduce default LDAP timeout from 100 to 15 seconds. [#3487] * gpgconf: Ignore non-installed components for commands --apply-profile and --apply-defaults. [#3313] * Add configure option --enable-werror. [#2423] See-also: gnupg-announce/2017q4/000416.html Noteworthy changes in version 2.2.1 (2017-09-19) ------------------------------------------------ * gpg: Fix formatting of the user id in batch mode key generation if only "name-email" is given. * gpgv: Fix annoying "not suitable for" warnings. * wks: Convey only the newest user id to the provider. This is the case if different names are used with the same addr-spec. * wks: Create a complying user id for provider policy mailbox-only. * wks: Add workaround for posteo.de. * scd: Fix the use of large ECC keys with an OpenPGP card. * dirmngr: Use system provided root certificates if no specific HKP certificates are configured. If build with GNUTLS, this was already the case. See-also: gnupg-announce/2017q3/000415.html Noteworthy changes in version 2.2.0 (2017-08-28) ------------------------------------------------ This is the new long term stable branch. This branch will only see bug fixes and no new features. * gpg: Reverted change in 2.1.23 so that --no-auto-key-retrieve is again the default. * Fixed a few minor bugs. See-also: gnupg-announce/2017q3/000413.html Noteworthy changes in version 2.1.23 (2017-08-09) ------------------------------------------------- * gpg: "gpg" is now installed as "gpg" and not anymore as "gpg2". If needed, the new configure option --enable-gpg-is-gpg2 can be used to revert this. * gpg: Options --auto-key-retrieve and --auto-key-locate "local,wkd" are now used by default. Note: this enables keyserver and Web Key Directory operators to notice when a signature from a locally non-available key is being verified for the first time or when you intend to encrypt to a mail address without having the key locally. This new behaviour will eventually make key discovery much easier and mostly automatic. Disable this by adding no-auto-key-retrieve auto-key-locate local to your gpg.conf. * agent: Option --no-grab is now the default. The new option --grab allows to revert this. * gpg: New import option "show-only". * gpg: New option --disable-dirmngr to entirely disable network access for gpg. * gpg,gpgsm: Tweaked DE-VS compliance behaviour. * New configure flag --enable-all-tests to run more extensive tests during "make check". * gpgsm: The keygrip is now always printed in colon mode as documented in the man page. * Fixed connection timeout problem under Windows. See-also: gnupg-announce/2017q3/000412.html Noteworthy changes in version 2.1.22 (2017-07-28) ------------------------------------------------- * gpg: Extend command --quick-set-expire to allow for setting the expiration time of subkeys. * gpg: By default try to repair keys during import. New sub-option no-repair-keys for --import-options. * gpg,gpgsm: Improved checking and reporting of DE-VS compliance. * gpg: New options --key-origin and --with-key-origin. Store the time of the last key update from keyservers, WKD, or DANE. * agent: New option --ssh-fingerprint-digest. * dimngr: Lower timeouts on keyserver connection attempts and made it configurable. * dirmngr: Tor will now automatically be detected and used. The option --no-use-tor disables Tor detection. * dirmngr: Now detects a changed /etc/resolv.conf. * agent,dirmngr: Initiate shutdown on removal of the GnuPG home directory. * gpg: Avoid caching passphrase for failed symmetric encryption. * agent: Support for unprotected ssh keys. * dirmngr: Fixed name resolving on systems using only v6 nameservers. * dirmngr: Allow the use of TLS over http proxies. * w32: Change directory of the daemons after startup. * wks: New man pages for client and server. * Many other bug fixes. See-also: gnupg-announce/2017q3/000411.html Noteworthy changes in version 2.1.21 (2017-05-15) ------------------------------------------------- * gpg,gpgsm: Fix corruption of old style keyring.gpg files. This bug was introduced with version 2.1.20. Note that the default pubring.kbx format was not affected. * gpg,dirmngr: Removed the skeleton config file support. The system's standard methods for providing default configuration files should be used instead. * w32: The Windows installer now allows installation of GnuPG without Administrator permissions. * gpg: Fixed import filter property match bug. * scd: Removed Linux support for Cardman 4040 PCMCIA reader. * scd: Fixed some corner case bugs in resume/suspend handling. * Many minor bug fixes and code cleanup. See-also: gnupg-announce/2017q2/000405.html Noteworthy changes in version 2.1.20 (2017-04-03) ------------------------------------------------- * gpg: New properties 'expired', 'revoked', and 'disabled' for the import and export filters. * gpg: New command --quick-set-primary-uid. * gpg: New compliance field for the --with-colon key listing. * gpg: Changed the key parser to generalize the processing of local meta data packets. * gpg: Fixed assertion failure in the TOFU trust model. * gpg: Fixed exporting of zero length user ID packets. * scd: Improved support for multiple readers. * scd: Fixed timeout handling for key generation. * agent: New option --enable-extended-key-format. * dirmngr: Do not add a keyserver to a new dirmngr.conf. Dirmngr uses a default keyserver. * dimngr: Do not treat TLS warning alerts as severe error when building with GNUTLS. * dirmngr: Actually take /etc/hosts in account. * wks: Fixed client problems on Windows. Published keys are now set to world-readable. * tests: Fixed creation of temporary directories. * A socket directory for a non standard GNUGHOME is now created on the fly under /run/user. Thus "gpgconf --create-socketdir" is now optional. The use of "gpgconf --remove-socketdir" to clean up obsolete socket directories is however recommended to avoid cluttering /run/user with useless directories. * Fixed build problems on some platforms. See-also: gnupg-announce/2017q2/000404.html Noteworthy changes in version 2.1.19 (2017-03-01) ------------------------------------------------- * gpg: Print a warning if Tor mode is requested but the Tor daemon is not running. * gpg: New status code DECRYPTION_KEY to print the actual private key used for decryption. * gpgv: New options --log-file and --debug. * gpg-agent: Revamp the prompts to ask for card PINs. * scd: Support for multiple card readers. * scd: Removed option --debug-disable-ticker. Ticker is used only when it is required to watch removal of device/card. * scd: Improved detection of card inserting and removal. * dirmngr: New option --disable-ipv4. * dirmngr: New option --no-use-tor to explicitly disable the use of Tor. * dirmngr: The option --allow-version-check is now required even if the option --use-tor is also used. * dirmngr: Handle a missing nsswitch.conf gracefully. * dirmngr: Avoid PTR lookups for keyserver pools. The are only done for the debug command "keyserver --hosttable". * dirmngr: Rework the internal certificate cache to support classes of certificates. Load system provided certificates on startup. Add options --tls, --no-crl, and --systrust to the "VALIDATE" command. * dirmngr: Add support for the ntbtls library. * wks: Create mails with a "WKS-Phase" header. Fix detection of Draft-2 mode. * The Windows installer is now build with limited TLS support. * Many other bug fixes and new regression tests. See-also: gnupg-announce/2017q1/000402.html Noteworthy changes in version 2.1.18 (2017-01-23) ------------------------------------------------- * gpg: Remove bogus subkey signature while cleaning a key (with export-clean, import-clean, or --edit-key's sub-command clean) * gpg: Allow freezing the clock with --faked-system-time. * gpg: New --export-option flag "backup", new --import-option flag "restore". * gpg-agent: Fixed long delay due to a regression in the progress callback code. * scd: Lots of code cleanup and internal changes. * scd: Improved the internal CCID driver. * dirmngr: Fixed problem with the DNS glue code (removal of the trailing dot in domain names). * dirmngr: Make sure that Tor is actually enabled after changing the conf file and sending SIGHUP or "gpgconf --reload dirmngr". * dirmngr: Fixed Tor access to IPv6 addresses. Note that current versions of Tor may require that the flag "IPv6Traffic" is used with the option "SocksPort" in torrc to actually allow IPv6 traffic. * dirmngr: Fixed HKP for literally given IPv6 addresses. * dirmngr: Enabled reverse DNS lookups via Tor. * dirmngr: Added experimental SRV record lookup for WKD. See commit 88dc3af3d4ae1afe1d5e136bc4c38bc4e7d4cd10 for details. * dirmngr: For HKP use "pgpkey-hkps" and "pgpkey-hkp" in SRV record lookups. Avoid SRV record lookup when a port is explicitly specified. This fixes a regression from the 1.4 and 2.0 behavior. * dirmngr: Gracefully handle a missing /etc/nsswitch.conf. Ignore negation terms (e.g. "[!UNAVAIL=return]" instead of bailing out. * dirmngr: Better debug output for flags "dns" and "network". * dirmngr: On reload mark all known HKP servers alive. * gpgconf: Allow keyword "all" for --launch, --kill, and --reload. * tools: gpg-wks-client now ignores a missing policy file on the server. * Avoid unnecessary ambiguity error message in the option parsing. * Further improvements of the regression test suite. * Fixed building with --disable-libdns configure option. * Fixed a crash running the tests on 32 bit architectures. * Fixed spurious failures on BSD system in the spawn functions. This affected for example gpg-wks-client and gpgconf. See-also: gnupg-announce/2017q1/000401.html Noteworthy changes in version 2.1.17 (2016-12-20) ------------------------------------------------- * gpg: By default new keys expire after 2 years. * gpg: New command --quick-set-expire to conveniently change the expiration date of keys. * gpg: Option and command names have been changed for easier comprehension. The old names are still available as aliases. * gpg: Improved the TOFU trust model. * gpg: New option --default-new-key-algo. * scd: Support OpenPGP card V3 for RSA. * dirmngr: Support for the ADNS library has been removed. Instead William Ahern's Libdns is now source included and used on all platforms. This enables Tor support on all platforms. The new option --standard-resolver can be used to disable this code at runtime. In case of build problems the new configure option --disable-libdns can be used to build without Libdns. * dirmngr: Lazily launch ldap reaper thread. * tools: New options --check and --status-fd for gpg-wks-client. * The UTF-8 byte order mark is now skipped when reading conf files. * Fixed many bugs and regressions. * Major improvements to the test suite. For example it is possible to run the external test suite of GPGME. See-also: gnupg-announce/2016q4/000400.html Noteworthy changes in version 2.1.16 (2016-11-18) ------------------------------------------------- * gpg: New algorithm for selecting the best ranked public key when using a mail address with -r, -R, or --locate-key. * gpg: New option --with-tofu-info to print a new "tfs" record in colon formatted key listings. * gpg: New option --compliance as an alternative way to specify options like --rfc2440, --rfc4880, et al. * gpg: Many changes to the TOFU implementation. * gpg: Improve usability of --quick-gen-key. * gpg: In --verbose mode print a diagnostic when a pinentry is launched. * gpg: Remove code which warns for old versions of gnome-keyring. * gpg: New option --override-session-key-fd. * gpg: Option --output does now work with --verify. * gpgv: New option --output to allow saving the verified data. * gpgv: New option --enable-special-filenames. * agent, dirmngr: New --supervised mode for use by systemd and alike. * agent: By default listen on all available sockets using standard names. * agent: Invoke scdaemon with --homedir. * dirmngr: On Linux now detects the removal of its own socket and terminates. * scd: Support ECC key generation. * scd: Support more card readers. * dirmngr: New option --allow-version-check to download a software version database in the background. * dirmngr: Use system provided CAs if no --hkp-cacert is given. * dirmngr: Use a default keyserver if none is explicitly set * gpgconf: New command --query-swdb to check software versions against an copy of an online database. * gpgconf: Print the socket directory with --list-dirs. * tools: The WKS tools now support draft version -02. * tools: Always build gpg-wks-client and install under libexec. * tools: New option --supported for gpg-wks-client. * The log-file option now accepts a value "socket://" to log to the socket named "S.log" in the standard socket directory. * Provide fake pinentries for use by tests cases of downstream developers. * Fixed many bugs and regressions. * Many changes and improvements for the test suite. See-also: gnupg-announce/2016q4/000398.html Noteworthy changes in version 2.1.15 (2016-08-18) ------------------------------------------------- * gpg: Remove the --tofu-db-format option and support for the split TOFU database. * gpg: Add option --sender to prepare for coming features. * gpg: Add option --input-size-hint to help progress indicators. * gpg: Extend the PROGRESS status line with the counted unit. * gpg: Avoid publishing the GnuPG version by default with --armor. * gpg: Properly ignore legacy keys in the keyring cache. * gpg: Always print fingerprint records in --with-colons mode. * gpg: Make sure that keygrips are printed for each subkey in --with-colons mode. * gpg: New import filter "drop-sig". * gpgsm: Fix a bug in the machine-readable key listing. * gpg,gpgsm: Block signals during keyring updates to limits the effects of a Ctrl-C at the wrong time. * g13: Add command --umount and other fixes for dm-crypt. * agent: Fix regression in SIGTERM handling. * agent: Cleanup of the ssh-agent code. * agent: Allow import of overly long keys. * scd: Fix problems with card removal. * dirmngr: Remove all code for running as a system service. * tools: Make gpg-wks-client conforming to the specs. * tests: Improve the output of the new regression test tool. * tests: Distribute the standalone test runner. * tests: Run each test in a clean environment. * Spelling and grammar fixes. See-also: gnupg-announce/2016q3/000396.html Noteworthy changes in version 2.1.14 (2016-07-14) ------------------------------------------------- * gpg: Removed options --print-dane-records and --print-pka-records. The new export options "export-pka" and "export-dane" can instead be used with the export command. * gpg: New options --import-filter and --export-filter. * gpg: New import options "import-show" and "import-export". * gpg: New option --no-keyring. * gpg: New command --quick-revuid. * gpg: New options -f/--recipient-file and -F/--hidden-recipient-file to directly specify encryption keys. * gpg: New option --mimemode to indicate that the content is a MIME part. Does only enable --textmode right now. * gpg: New option --rfc4880bis to allow experiments with proposed changes to the current OpenPGP specs. * gpg: Fix regression in the "fetch" sub-command of --card-edit. * gpg: Fix regression since 2.1 in option --try-all-secrets. * gpgv: Change default options for extra security. * gpgsm: No more root certificates are installed by default. * agent: "updatestartuptty" does now affect more environment variables. * scd: The option --homedir does now work with scdaemon. * scd: Support some more GEMPlus card readers. * gpgtar: Fix handling of '-' as file name. * gpgtar: New commands --create and --extract. * gpgconf: Tweak for --list-dirs to better support shell scripts. * tools: Add programs gpg-wks-client and gpg-wks-server to implement a Web Key Service. The configure option --enable-wks-tools is required to build them; they should be considered Beta software. * tests: Complete rework of the openpgp part of the test suite. The test scripts have been changed from Bourne shell scripts to Scheme programs. A customized scheme interpreter (gpgscm) is included. This change was triggered by the need to run the test suite on non-Unix platforms. * The rendering of the man pages has been improved. See-also: gnupg-announce/2016q3/000393.html Noteworthy changes in version 2.1.13 (2016-06-16) ------------------------------------------------- * gpg: New command --quick-addkey. Extend the --quick-gen-key command. * gpg: New --keyid-format "none" which is now also the default. * gpg: New option --with-subkey-fingerprint. * gpg: Include Signer's UID subpacket in signatures if the secret key has been specified using a mail address and the new option --disable-signer-uid is not used. * gpg: Allow unattended deletion of a secret key. * gpg: Allow export of non-passphrase protected secret keys. * gpg: New status lines KEY_CONSIDERED and NOTATION_FLAGS. * gpg: Change status line TOFU_STATS_LONG to use '~' as a non-breaking-space character. * gpg: Speedup key listings in Tofu mode. * gpg: Make sure that the current and total values of a PROGRESS status line are small enough. * gpgsm: Allow the use of AES192 and SERPENT ciphers. * dirmngr: Adjust WKD lookup to current specs. * dirmngr: Fallback to LDAP v3 if v2 is is not supported. * gpgconf: New commands --create-socketdir and --remove-socketdir, new option --homedir. * If a /run/user/$UID directory exists, that directory is now used for IPC sockets instead of the GNUPGHOME directory. This fixes problems with NFS and too long socket names and thus avoids the need for redirection files. * The Speedo build systems now uses the new versions.gnupg.org server to retrieve the default package versions. * Fix detection of libusb on FreeBSD. * Speedup fd closing after a fork. See-also: gnupg-announce/2016q2/000390.html Noteworthy changes in version 2.1.12 (2016-05-04) ------------------------------------------------- * gpg: New --edit-key sub-command "change-usage" for testing purposes. * gpg: Out of order key-signatures are now systematically detected and fixed by --edit-key. * gpg: Improved detection of non-armored messages. * gpg: Removed the extra prompt needed to create Curve25519 keys. * gpg: Improved user ID selection for --quick-sign-key. * gpg: Use the root CAs provided by the system with --fetch-key. * gpg: Add support for the experimental Web Key Directory key location service. * gpg: Improve formatting of Tofu messages and emit new Tofu specific status lines. * gpgsm: Add option --pinentry-mode to support a loopback pinentry. * gpgsm: A new pubring.kbx is now created with the header blob so that gpg can detect that the keybox format needs to be used. * agent: Add read support for the new private key protection format openpgp-s2k-ocb-aes. * agent: Add read support for the new extended private key format. * agent: Default to --allow-loopback-pinentry and add option --no-allow-loopback-pinentry. * scd: Changed to use the new libusb 1.0 API for the internal CCID driver. * dirmngr: The dirmngr-client does now auto-detect the PEM format. * g13: Add experimental support for dm-crypt. * w32: Tofu support is now available with the Speedo build method. * w32: Removed the need for libiconv.dll. * The man pages for gpg and gpgv are now installed under the correct name (gpg2 or gpg - depending on a configure option). * Lots of internal cleanups and bug fixes. See-also: gnupg-announce/2016q2/000387.html Noteworthy changes in version 2.1.11 (2016-01-26) ------------------------------------------------- * gpg: New command --export-ssh-key to replace the gpgkey2ssh tool. * gpg: Allow to generate mail address only keys with --gen-key. * gpg: "--list-options show-usage" is now the default. * gpg: Make lookup of DNS CERT records holding an URL work. * gpg: Emit PROGRESS status lines during key generation. * gpg: Don't check for ambigious or non-matching key specification in the config file or given to --encrypt-to. This feature will return in 2.3.x. * gpg: Lock keybox files while updating them. * gpg: Solve rare error on Windows during keyring and Keybox updates. * gpg: Fix possible keyring corruption. (bug#2193) * gpg: Fix regression of "bkuptocard" sub-command in --edit-key and remove "checkbkupkey" sub-command introduced with 2.1. (bug#2169) * gpg: Fix internal error in gpgv when using default keyid-format. * gpg: Fix --auto-key-retrieve to work with dirmngr.conf configured keyservers. (bug#2147). * agent: New option --pinentry-timeout. * scd: Improve unplugging of USB readers under Windows. * scd: Fix regression for generating RSA keys on card. * dirmmgr: All configured keyservers are now searched. * dirmngr: Install CA certificate for hkps.pool.sks-keyservers.net. Use this certiticate even if --hkp-cacert is not used. * gpgtar: Add actual encryption code. gpgtar does now fully replace gpg-zip. * gpgtar: Fix filename encoding problem on Windows. * Print a warning if a GnuPG component is using an older version of gpg-agent, dirmngr, or scdaemon. See-also: gnupg-announce/2016q1/000383.html Noteworthy changes in version 2.1.10 (2015-12-04) ------------------------------------------------- * gpg: New trust models "tofu" and "tofu+pgp". * gpg: New command --tofu-policy. New options --tofu-default-policy and --tofu-db-format. * gpg: New option --weak-digest to specify hash algorithms which should be considered weak. * gpg: Allow the use of multiple --default-key options; take the last available key. * gpg: New option --encrypt-to-default-key. * gpg: New option --unwrap to only strip the encryption layer. * gpg: New option --only-sign-text-ids to exclude photo IDs from key signing. * gpg: Check for ambigious or non-matching key specification in the config file or given to --encrypt-to. * gpg: Show the used card reader with --card-status. * gpg: Print export statistics and an EXPORTED status line. * gpg: Allow selecting subkeys by keyid in --edit-key. * gpg: Allow updating the expiration time of multiple subkeys at once. * dirmngr: New option --use-tor. For full support this requires libassuan version 2.4.2 and a patched version of libadns (e.g. adns-1.4-g10-7 as used by the standard Windows installer). * dirmngr: New option --nameserver to specify the nameserver used in Tor mode. * dirmngr: Keyservers may again be specified by IP address. * dirmngr: Fixed problems in resolving keyserver pools. * dirmngr: Fixed handling of premature termination of TLS streams so that large numbers of keys can be refreshed via hkps. * gpg: Fixed a regression in --locate-key [since 2.1.9]. * gpg: Fixed another bug for keyrings with legacy keys. * gpgsm: Allow combinations of usage flags in --gen-key. * Make tilde expansion work with most options. * Many other cleanups and bug fixes. See-also: gnupg-announce/2015q4/000381.html Noteworthy changes in version 2.1.9 (2015-10-09) ------------------------------------------------ * gpg: Allow fetching keys via OpenPGP DANE (--auto-key-locate). New option --print-dane-records. [Update: --print-dane-records replaced in 2.1.4.] * gpg: Fix for a problem with PGP-2 keys in a keyring. * gpg: Fail with an error instead of a warning if a modern cipher algorithm is used without a MDC. * agent: New option --pinentry-invisible-char. * agent: Always do a RSA signature verification after creation. * agent: Fix a regression in ssh-add-ing Ed25519 keys. * agent: Fix ssh fingerprint computation for nistp384 and EdDSA. * agent: Fix crash during passphrase entry on some platforms. * scd: Change timeout to fix problems with some 2.1 cards. * dirmngr: Displayed name is now Key Acquirer. * dirmngr: Add option --keyserver. Deprecate that option for gpg. Install a dirmngr.conf file from a skeleton for new installations. See-also: gnupg-announce/2015q4/000380.html Noteworthy changes in version 2.1.8 (2015-09-10) ------------------------------------------------ * gpg: Sending very large keys to the keyservers works again. * gpg: Validity strings in key listings are now again translatable. * gpg: Emit FAILURE status lines to help GPGME. * gpg: Does not anymore link to Libksba to reduce dependencies. * gpgsm: Export of secret keys via Assuan is now possible. * agent: Raise the maximum passphrase length from 100 to 255 bytes. * agent: Fix regression using EdDSA keys with ssh. * Does not anymore use a build timestamp by default. * The fallback encoding for broken locale settings changed from Latin-1 to UTF-8. * Many code cleanups and improved internal documentation. * Various minor bug fixes. See-also: gnupg-announce/2015q3/000379.html Noteworthy changes in version 2.1.7 (2015-08-11) ------------------------------------------------ * gpg: Support encryption with Curve25519 if Libgcrypt 1.7 is used. * gpg: In the --edit-key menu: Removed the need for "toggle", changed how secret keys are indicated, new commands "fpr *" and "grip". * gpg: More fixes related to legacy keys in a keyring. * gpgv: Does now also work with a "trustedkeys.kbx" file. * scd: Support some feature from the OpenPGP card 3.0 specs. * scd: Improved ECC support * agent: New option --force for the DELETE_KEY command. * w32: Look for the Pinentry at more places. * Dropped deprecated gpgsm-gencert.sh * Various other bug fixes. See-also: gnupg-announce/2015q3/000371.html Noteworthy changes in version 2.1.6 (2015-07-01) ------------------------------------------------ * agent: New option --verify for the PASSWD command. * gpgsm: Add command option "offline" as an alternative to --disable-dirmngr. * gpg: Do not prompt multiple times for a password in pinentry loopback mode. * Allow the use of debug category names with --debug. * Using gpg-agent and gpg/gpgsm with different locales will now show the correct translations in Pinentry. * gpg: Improve speed of --list-sigs and --check-sigs. * gpg: Make --list-options show-sig-subpackets work again. * gpg: Fix an export problem for old keyrings with PGP-2 keys. * scd: Support PIN-pads on more readers. * dirmngr: Properly cleanup zombie LDAP helper processes and avoid hangs on dirmngr shutdown. * Various other bug fixes. See-also: gnupg-announce/2015q3/000370.html Noteworthy changes in version 2.1.5 (2015-06-11) ------------------------------------------------ * Support for an external passphrase cache. * Support for the forthcoming version 3 OpenPGP smartcard. * Manuals now show the actual used file names. * Prepared for improved integration with Emacs. * Code cleanups and minor bug fixes. See-also: gnupg-announce/2015q2/000369.html Noteworthy changes in version 2.1.4 (2015-05-12) ------------------------------------------------ * gpg: Add command --quick-adduid to non-interactively add a new user id to an existing key. * gpg: Do no enable honor-keyserver-url by default. Make it work if enabled. * gpg: Display the serial number in the --card-status output again. * agent: Support for external password managers. Add option --no-allow-external-cache. * scdaemon: Improved handling of extended APDUs. * Make HTTP proxies work again. * All network access including DNS as been moved to Dirmngr. * Allow building without LDAP support. * Fixed lots of smaller bugs. See-also: gnupg-announce/2015q2/000366.html Noteworthy changes in version 2.1.3 (2015-04-11) ------------------------------------------------ * gpg: LDAP keyservers are now supported by 2.1. * gpg: New option --with-icao-spelling. * gpg: New option --print-pka-records. Changed the PKA method to use CERT records and hashed names. [Update: --print-pka-records replaced in 2.1.14.] * gpg: New command --list-gcrypt-config. New parameter "curve" for --list-config. * gpg: Print a NEWSIG status line like gpgsm always did. * gpg: Print MPI values with --list-packets and --verbose. * gpg: Write correct MPI lengths with ECC keys. * gpg: Skip legacy PGP-2 keys while searching. * gpg: Improved searching for mail addresses when using a keybox. * gpgsm: Changed default algos to AES-128 and SHA-256. * gpgtar: Fixed extracting files with sizes of a multiple of 512. * dirmngr: Fixed SNI handling for hkps pools. * dirmngr: extra-certs and trusted-certs are now always loaded from the sysconfig dir instead of the homedir. * Fixed possible problems due to compiler optimization, two minor regressions, and other bugs. See-also: gnupg-announce/2015q2/000365.html Noteworthy changes in version 2.1.2 (2015-02-11) ------------------------------------------------ * gpg: The parameter 'Passphrase' for batch key generation works again. * gpg: Using a passphrase option in batch mode now has the expected effect on --quick-gen-key. * gpg: Improved reporting of unsupported PGP-2 keys. * gpg: Added support for algo names when generating keys using --command-fd. * gpg: Fixed DoS based on bogus and overlong key packets. * agent: When setting --default-cache-ttl the value for --max-cache-ttl is adjusted to be not lower than the former. * agent: Fixed problems with the new --extra-socket. * agent: Made --allow-loopback-pinentry changeable with gpgconf. * agent: Fixed importing of unprotected openpgp keys. * agent: Now tries to use a fallback pinentry if the standard pinentry is not installed. * scd: Added support for ECDH. * Fixed several bugs related to bogus keyrings and improved some other code. See-also: gnupg-announce/2015q1/000361.html Noteworthy changes in version 2.1.1 (2014-12-16) ------------------------------------------------ * gpg: Detect faulty use of --verify on detached signatures. * gpg: New import option "keep-ownertrust". * gpg: New sub-command "factory-reset" for --card-edit. * gpg: A stub key for smartcards is now created by --card-status. * gpg: Fixed regression in --refresh-keys. * gpg: Fixed regresion in %g and %p codes for --sig-notation. * gpg: Fixed best matching hash algo detection for ECDSA and EdDSA. * gpg: Improved perceived speed of secret key listisngs. * gpg: Print number of skipped PGP-2 keys on import. * gpg: Removed the option aliases --throw-keyid and --notation-data; use --throw-keyids and --set-notation instead. * gpg: New import option "keep-ownertrust". * gpg: Skip too large keys during import. * gpg,gpgsm: New option --no-autostart to avoid starting gpg-agent or dirmngr. * gpg-agent: New option --extra-socket to provide a restricted command set for use with remote clients. * gpgconf --kill does not anymore start a service only to kill it. * gpg-pconnect-agent: Add convenience option --uiserver. * Fixed keyserver access for Windows. * Fixed build problems on Mac OS X * The Windows installer does now install development files * More translations (but most of them are not complete). * To support remotely mounted home directories, the IPC sockets may now be redirected. This feature requires Libassuan 2.2.0. * Improved portability and the usual bunch of bug fixes. See-also: gnupg-announce/2014q4/000360.html Noteworthy changes in version 2.1.0 (2014-11-06) ------------------------------------------------ This release introduces a lot of changes. Most of them are internal and thus not user visible. However, some long standing behavior has slightly changed and it is strongly suggested that an existing "~/.gnupg" directory is backed up before this version is used. A verbose description of the major new features and changes can be found in the file doc/whats-new-in-2.1.txt. * gpg: All support for v3 (PGP 2) keys has been dropped. All signatures are now created as v4 signatures. v3 keys will be removed from the keyring. * gpg: With pinentry-0.9.0 the passphrase "enter again" prompt shows up in the same window as the "new passphrase" prompt. * gpg: Allow importing keys with duplicated long key ids. * dirmngr: May now be build without support for LDAP. * For a complete list of changes see the lists of changes for the 2.1.0 beta versions below. Note that all relevant fixes from versions 2.0.14 to 2.0.26 are also applied to this version. [Noteworthy changes in version 2.1.0-beta864 (2014-10-03)] * gpg: Removed the GPG_AGENT_INFO related code. GnuPG does now always use a fixed socket name in its home directory. * gpg: Renamed --gen-key to --full-gen-key and re-added a --gen-key command with less choices. * gpg: Use SHA-256 for all signature types also on RSA keys. * gpg: Default keyring is now created with a .kbx suffix. * gpg: Add a shortcut to the key capabilies menu (e.g. "=e" sets the encryption capabilities). * gpg: Fixed obsolete options parsing. * Further improvements for the alternative speedo build system. [Noteworthy changes in version 2.1.0-beta834 (2014-09-18)] * gpg: Improved passphrase caching. * gpg: Switched to algorithm number 22 for EdDSA. * gpg: Removed CAST5 from the default preferences. * gpg: Order SHA-1 last in the hash preferences. * gpg: Changed default cipher for --symmetric to AES-128. * gpg: Fixed export of ECC keys and import of EdDSA keys. * dirmngr: Fixed the KS_FETCH command. * The speedo build system now downloads related packages and works for non-Windows platforms. [Noteworthy changes in version 2.1.0-beta783 (2014-08-14)] * gpg: Add command --quick-gen-key. * gpg: Make --quick-sign-key promote local key signatures. * gpg: Added "show-usage" sub-option to --list-options. * gpg: Screen keyserver responses to avoid importing unwanted keys from rogue servers. * gpg: Removed the option --pgp2 and --rfc1991 and the ability to create PGP-2 compatible messages. * gpg: Removed options --compress-keys and --compress-sigs. * gpg: Cap attribute packets at 16MB. * gpg: Improved output of --list-packets. * gpg: Make with-colons output of --search-keys work again. * gpgsm: Auto-create the ".gnupg" directory like gpg does. * agent: Fold new passphrase warning prompts into one. * scdaemon: Add support for the Smartcard-HSM card. * scdaemon: Remove the use of the pcsc-wrapper. [Noteworthy changes in version 2.1.0-beta751 (2014-07-03)] * gpg: Create revocation certificates during key generation. * gpg: Create exported secret keys and revocation certifciates with mode 0700 * gpg: The validity of user ids is now shown by default. To revert this add "list-options no-show-uid-validity" to gpg.conf. * gpg: Make export of secret keys work again. * gpg: The output of --list-packets does now print the offset of the packet and information about the packet header. * gpg: Avoid DoS due to garbled compressed data packets. [CVE-2014-4617] * gpg: Print more specific reason codes with the INV_RECP status. * gpg: Cap RSA and Elgamal keysize at 4096 bit also for unattended key generation. * scdaemon: Support reader Gemalto IDBridge CT30 and pinpad of SCT cyberJack go. * The speedo build system has been improved. It is now also possible to build a partly working installer for Windows. [Noteworthy changes in version 2.1.0-beta442 (2014-06-05)] * gpg: Changed the format of key listings. To revert to the old format the option --legacy-list-mode is available. * gpg: Add experimental signature support using curve Ed25519 and with a patched Libgcrypt also encryption support with Curve25519. [Update: this encryption support has been removed from 2.1.0 until we have agreed on a suitable format.] * gpg: Allow use of Brainpool curves. * gpg: Accepts a space separated fingerprint as user ID. This allows to copy and paste the fingerprint from the key listing. * gpg: The hash algorithm is now printed for signature records in key listings. * gpg: Reject signatures made using the MD5 hash algorithm unless the new option --allow-weak-digest-algos or --pgp2 are given. * gpg: Print a warning if the Gnome-Keyring-Daemon intercepts the communication with the gpg-agent. * gpg: New option --pinentry-mode. * gpg: Fixed decryption using an OpenPGP card. * gpg: Fixed bug with deeply nested compressed packets. * gpg: Only the major version number is by default included in the armored output. * gpg: Do not create a trustdb file if --trust-model=always is used. * gpg: Protect against rogue keyservers sending secret keys. * gpg: The format of the fallback key listing ("gpg KEYFILE") is now more aligned to the regular key listing ("gpg -k"). * gpg: The option--show-session-key prints its output now before the decryption of the bulk message starts. * gpg: New %U expando for the photo viewer. * gpg,gpgsm: New option --with-secret. * gpgsm: By default the users are now asked via the Pinentry whether they trust an X.509 root key. To prohibit interactive marking of such keys, the new option --no-allow-mark-trusted may be used. * gpgsm: New commands to export a secret RSA key in PKCS#1 or PKCS#8 format. * gpgsm: Improved handling of re-issued CA certificates. * agent: The included ssh agent does now support ECDSA keys. * agent: New option --enable-putty-support to allow gpg-agent on Windows to act as a Pageant replacement with full smartcard support. * scdaemon: New option --enable-pinpad-varlen. * scdaemon: Various fixes for pinpad equipped card readers. * scdaemon: Rename option --disable-pinpad (was --disable-keypad). * scdaemon: Better support fo CCID readers. Now, internal CCID driver supports readers with no auto configuration feature. * dirmngr: Removed support for the original HKP keyserver which is not anymore used by any site. * dirmngr: Improved support for keyserver pools. * tools: New option --dirmngr for gpg-connect-agent. * The GNU Pth library has been replaced by the new nPth library. * Support installation as portable application under Windows. * All kind of other improvements - see the git log. [Noteworthy changes in version 2.1.0beta3 (2011-12-20)] * gpg: Fixed regression in the secret key export function. * gpg: Allow generation of card keys up to 4096 bit. * gpgsm: Preliminary support for the validation model "steed". * gpgsm: Improved certificate creation. * agent: Support the SSH confirm flag. * agent: New option to select a passphrase mode. The loopback mode may be used to bypass Pinentry. * agent: The Assuan commands KILLAGENT and KILLSCD are working again. * scdaemon: Does not anymore block after changing a card (regression fix). * tools: gpg-connect-agent does now proberly display the help output for "SCD HELP" commands. [Noteworthy changes in version 2.1.0beta2 (2011-03-08)] * gpg: ECC support as described by draft-jivsov-openpgp-ecc-06.txt [Update: now known as RFC-6637]. * gpg: Print "AES128" instead of "AES". This change introduces a little incompatibility for tools using "gpg --list-config". We hope that these tools are written robust enough to accept this new algorithm name as well. * gpgsm: New feature to create certificates from a parameter file. Add prompt to the --gen-key UI to create self-signed certificates. * agent: TMPDIR is now also honored when creating a socket using the --no-standard-socket option and with symcryptrun's temp files. * scdaemon: Fixed a bug where scdaemon sends a signal to gpg-agent running in non-daemon mode. * dirmngr: Fixed CRL loading under W32 (bug#1010). * Dirmngr has taken over the function of the keyserver helpers. Thus we now have a specified direct interface to keyservers via Dirmngr. LDAP, DNS and mail backends are not yet implemented. * Fixed TTY management for pinentries and session variable update problem. [Noteworthy changes in version 2.1.0beta1 (2010-10-26)] * gpg: secring.gpg is not anymore used but all secret key operations are delegated to gpg-agent. The import command moves secret keys to the agent. * gpg: The OpenPGP import command is now able to merge secret keys. * gpg: Encrypted OpenPGP messages with trailing data (e.g. other OpenPGP packets) are now correctly parsed. * gpg: Given sufficient permissions Dirmngr is started automagically. * gpg: Fixed output of "gpgconf --check-options". * gpg: Removed options --export-options(export-secret-subkey-passwd) and --simple-sk-checksum. * gpg: New options --try-secret-key. * gpg: Support DNS lookups for SRV, PKA and CERT on W32. * gpgsm: The --audit-log feature is now more complete. * gpgsm: The default for --include-cert is now to include all certificates in the chain except for the root certificate. * gpgsm: New option --ignore-cert-extension. * g13: The G13 tool for disk encryption key management has been added. * agent: If the agent's --use-standard-socket option is active, all tools try to start and daemonize the agent on the fly. In the past this was only supported on W32; on non-W32 systems the new configure option --disable-standard-socket may now be used to disable this new default. * agent: New and changed passphrases are now created with an iteration count requiring about 100ms of CPU work. * dirmngr: Dirmngr is now a part of this package. It is now also expected to run as a system service and the configuration directories are changed to the GnuPG name space. [Update: 2.1.0 starts dirmngr on demand as user daemon.] * Support for Windows CE. [Update: This has not been tested for the 2.1.0 release] * Numerical values may now be used as an alternative to the debug-level keywords. See-also: gnupg-announce/2014q4/000358.html Version 2.0.28 (2015-06-02) Version 2.0.27 (2015-02-18) Version 2.0.26 (2014-08-12) Version 2.0.25 (2014-06-30) Version 2.0.24 (2014-06-24) Version 2.0.23 (2014-06-03) Version 2.0.22 (2013-10-04) Version 2.0.21 (2013-08-19) Version 2.0.20 (2013-05-10) Version 2.0.19 (2012-03-27) Version 2.0.18 (2011-08-04) Version 2.0.17 (2011-01-13) Version 2.0.16 (2010-07-19) Version 2.0.15 (2010-03-09) Version 2.0.14 (2009-12-21) Noteworthy changes in version 2.0.13 (2009-09-04) ------------------------------------------------- * GPG now generates 2048 bit RSA keys by default. The default hash algorithm preferences has changed to prefer SHA-256 over SHA-1. 2048 bit DSA keys are now generated to use a 256 bit hash algorithm * The envvars XMODIFIERS, GTK_IM_MODULE and QT_IM_MODULE are now passed to the Pinentry to make SCIM work. * The GPGSM command --gen-key features a --batch mode and implements all features of gpgsm-gencert.sh in standard mode. * New option --re-import for GPGSM's IMPORT server command. * Enhanced writing of existing keys to OpenPGP v2 cards. * Add hack to the internal CCID driver to allow the use of some Omnikey based card readers with 2048 bit keys. * GPG now repeatly asks the user to insert the requested OpenPGP card. This can be disabled with --limit-card-insert-tries=1. * Minor bug fixes. See-also: gnupg-announce/2009q3/000294.html Noteworthy changes in version 2.0.12 (2009-06-17) ------------------------------------------------- * GPGSM now always lists ephemeral certificates if specified by fingerprint or keygrip. * New command "KEYINFO" for GPG_AGENT. GPGSM now also returns information about smartcards. * Made sure not to leak file descriptors if running gpg-agent with a command. Restore the signal mask to solve a problem in Mono. * Changed order of the confirmation questions for root certificates and store negative answers in trustlist.txt. * Better synchronization of concurrent smartcard sessions. * Support 2048 bit OpenPGP cards. * Support Telesec Netkey 3 cards. * The gpg-protect-tool now uses gpg-agent via libassuan. Under Windows the Pinentry will now be put into the foreground. * Changed code to avoid a possible Mac OS X system freeze. See-also: gnupg-announce/2009q2/000288.html Noteworthy changes in version 2.0.11 (2009-03-03) ------------------------------------------------- * Fixed a problem in SCDAEMON which caused unexpected card resets. * SCDAEMON is now aware of the Geldkarte. * The SCDAEMON option --allow-admin is now used by default. * GPGCONF now restarts SCdaemon if necessary. * The default cipher algorithm in GPGSM is now again 3DES. This is due to interoperability problems with Outlook 2003 which still can't cope with AES. See-also: gnupg-announce/2009q1/000287.html Noteworthy changes in version 2.0.10 (2009-01-12) ------------------------------------------------- * [gpg] New keyserver helper gpg2keys_kdns as generic DNS CERT lookup. Run with --help for a short description. Requires the ADNS library. * [gpg] New mechanisms "local" and "nodefault" for --auto-key-locate. Fixed a few problems with this option. * [gpg] New command --locate-keys. * [gpg] New options --with-sig-list and --with-sig-check. * [gpg] The option "-sat" is no longer an alias for --clearsign. * [gpg] The option --fixed-list-mode is now implicitly used and obsolete. * [gpg] New control statement %ask-passphrase for the unattended key generation. * [gpg] The algorithm to compute the SIG_ID status has been changed. * [gpgsm] Now uses AES by default. * [gpgsm] Made --output option work with --export-secret-key-p12. * [gpg-agent] Terminate process if the own listening socket is not anymore served by ourself. * [scdaemon] Made it more robust on W32. * [gpg-connect-agent] Accept commands given as command line arguments. * [w32] Initialized the socket subsystem for all keyserver helpers. * [w32] The sysconf directory has been moved from a subdirectory of the installation directory to %CSIDL_COMMON_APPDATA%/GNU/etc/gnupg. * [w32] The gnupg2.nls directory is not anymore used. The standard locale directory is now used. * [w32] Fixed a race condition between gpg and gpgsm in the use of temporary file names. * The gpg-preset-passphrase mechanism works again. An arbitrary string may now be used for a custom cache ID. * Admin PINs are cached again (bug in 2.0.9). * Support for version 2 OpenPGP cards. * Libgcrypt 1.4 is now required. See-also: gnupg-announce/2009q1/000284.html Noteworthy changes in version 2.0.9 (2008-03-26) ------------------------------------------------ * Gpgsm always tries to locate missing certificates from a running Dirmngr's cache. * Tweaks for Windows. * The Admin PIN for OpenPGP cards may now be entered with the pinpad. * Improved certificate chain construction. * Extended the PKITS framework. * Fixed a bug in the ambigious name detection. * Fixed possible memory corruption while importing OpenPGP keys (bug introduced with 2.0.8). [CVE-2008-1530] * Minor bug fixes. Noteworthy changes in version 2.0.8 (2007-12-20) ------------------------------------------------ * Enhanced gpg-connect-agent with a small scripting language. * New option --list-config for gpgconf. * Fixed a crash in gpgconf. * Gpg-agent now supports the passphrase quality bar of the latest Pinentry. * The envvars XAUTHORITY and PINENTRY_USER_DATA are now passed to the Pinentry. * Fixed the auto creation of the key stub for smartcards. * Fixed a rare bug in decryption using the OpenPGP card. * Creating DSA2 keys is now possible. * New option --extra-digest-algo for gpgsm to allow verification of broken signatures. * Allow encryption with legacy Elgamal sign+encrypt keys with option --rfc2440. * Windows is now a supported platform. * Made sure that under Windows the file permissions of the socket are taken into account. This required a change of our socket emulation code and changed the IPC protocol under Windows. See-also: gnupg-announce/2007q4/000267.html Noteworthy changes in version 2.0.7 (2007-09-10) ------------------------------------------------ * Fixed encryption problem if duplicate certificates are in the keybox. * Made it work on Windows Vista. Note that the entire Windows port is still considered Beta. * Add new options min-passphrase-nonalpha, check-passphrase-pattern, enforce-passphrase-constraints and max-passphrase-days to gpg-agent. * Add command --check-components to gpgconf. Gpgconf now uses the installed versions of the programs and does not anymore search via PATH for them. See-also: gnupg-announce/2007q3/000259.html Noteworthy changes in version 2.0.6 (2007-08-16) ------------------------------------------------ * GPGSM does now grok --default-key. * GPGCONF is now aware of --default-key and --encrypt-to. * GPGSM does again correctly print the serial number as well the the various keyids. This was broken since 2.0.4. * New option --validation-model and support for the chain-model. * Improved Windows support. See-also: gnupg-announce/2007q3/000258.html Noteworthy changes in version 2.0.5 (2007-07-05) ------------------------------------------------ * Switched license to GPLv3. * Basic support for Windows. Run "./autogen.sh --build-w32" to build it. As usual the mingw cross compiling toolchain is required. * Fixed bug when using the --p12-charset without --armor. * The command --gen-key may now be used instead of the gpgsm-gencert.sh script. * Changed key generation to reveal less information about the machine. Bug fixes for gpg2's card key generation. See-also: gnupg-announce/2007q3/000255.html Noteworthy changes in version 2.0.4 (2007-05-09) ------------------------------------------------ * The server mode key listing commands are now also working for systems without the funopen/fopencookie API. * PKCS#12 import now tries several encodings in case the passphrase was not utf-8 encoded. New option --p12-charset for gpgsm. * Improved the libgcrypt logging support in all modules. See-also: gnupg-announce/2007q2/000254.html Noteworthy changes in version 2.0.3 (2007-03-08) ------------------------------------------------ * By default, do not allow processing multiple plaintexts in a single stream. Many programs that called GnuPG were assuming that GnuPG did not permit this, and were thus not using the plaintext boundary status tags that GnuPG provides. This change makes GnuPG reject such messages by default which makes those programs safe again. --allow-multiple-messages returns to the old behavior. [CVE-2007-1263]. * New --verify-option show-primary-uid-only. * gpgconf may now reads a global configuration file to select which options are changeable by a frontend. The new applygnupgdefaults tool may be used by an admin to set default options for all users. * The PIN pad of the Cherry XX44 keyboard is now supported. The DINSIG and the NKS applications are now also aware of PIN pads. See-also: gnupg-announce/2007q1/000252.html Noteworthy changes in version 2.0.2 (2007-01-31) ------------------------------------------------ * Fixed a serious and exploitable bug in processing encrypted packages. [CVE-2006-6235]. * Added --passphrase-repeat to set the number of times GPG will prompt for a new passphrase to be repeated. This is useful to help memorize a new passphrase. The default is 1 repetition. * Using a PIN pad does now also work for the signing key. * A warning is displayed by gpg-agent if a new passphrase is too short. New option --min-passphrase-len defaults to 8. * The status code BEGIN_SIGNING now shows the used hash algorithms. See-also: gnupg-announce/2007q1/000249.html Noteworthy changes in version 2.0.1 (2006-11-28) ------------------------------------------------ * Experimental support for the PIN pads of the SPR 532 and the Kaan Advanced card readers. Add "disable-keypad" scdaemon.conf if you don't want it. Does currently only work for the OpenPGP card and its authentication and decrypt keys. * Fixed build problems on some some platforms and crashes on amd64. * Fixed a buffer overflow in gpg2. [bug#728,CVE-2006-6169] See-also: gnupg-announce/2006q4/000242.html Noteworthy changes in version 2.0.0 (2006-11-11) ------------------------------------------------ * First stable version of a GnuPG integrating OpenPGP and S/MIME. See-also: gnupg-announce/2006q4/000239.html Noteworthy changes in version 1.9.95 (2006-11-06) ------------------------------------------------- * Minor bug fixes. Noteworthy changes in version 1.9.94 (2006-10-24) ------------------------------------------------- * Keys for gpgsm may now be specified using a keygrip. A keygrip is indicated by a prefixing it with an ampersand. * gpgconf now supports switching the CMS cipher algo (e.g. to AES). * New command --gpgconf-test for all major tools. This may be used to check whether the configuration file is sane. Noteworthy changes in version 1.9.93 (2006-10-18) ------------------------------------------------- * In --with-validation mode gpgsm will now also ask whether a root certificate should be trusted. * Link to Pth only if really necessary. * Fixed a pubring corruption bug in gpg2 occurring when importing signatures or keys with insane lengths. * Fixed v3 keyID calculation bug in gpg2. * More tweaks for certificates without extensions. Noteworthy changes in version 1.9.92 (2006-10-11) ------------------------------------------------- * Bug fixes. See-also: gnupg-announce/2006q4/000236.html Noteworthy changes in version 1.9.91 (2006-10-04) ------------------------------------------------- * New "relax" flag for trustlist.txt to allow root CA certificates without BasicContraints. * [gpg2] Removed the -k PGP 2 compatibility hack. -k is now an alias for --list-keys. * [gpg2] Print a warning if "-sat" is used instead of "--clearsign". Noteworthy changes in version 1.9.90 (2006-09-25) ------------------------------------------------- * Made readline work for gpg. * Cleanups und minor bug fixes. * Included translations from gnupg 1.4.5. Noteworthy changes in version 1.9.23 (2006-09-18) ------------------------------------------------- * Regular man pages for most tools are now build directly from the Texinfo source. * The gpg code from 1.4.5 has been fully merged into this release. The configure option --enable-gpg is still required to build this gpg part. For production use of OpenPGP the gpg version 1.4.5 is still recommended. Note, that gpg will be installed under the name gpg2 to allow coexisting with an 1.4.x gpg. * API change in gpg-agent's pkdecrypt command. Thus an older gpgsm may not be used with the current gpg-agent. * The scdaemon will now call a script on reader status changes. * gpgsm now allows file descriptor passing for "INPUT", "OUTPUT" and "MESSAGE". * The gpgsm server may now output a key listing to the output file handle. This needs to be enabled using "OPTION list-to-output=1". * The --output option of gpgsm has now an effect on list-keys. * New gpgsm commands --dump-chain and list-chain. * gpg-connect-agent has new options to utilize descriptor passing. * A global trustlist may now be used. See doc/examples/trustlist.txt. * When creating a new pubring.kbx keybox common certificates are imported. Noteworthy changes in version 1.9.22 (2006-07-27) ------------------------------------------------- * Enhanced pkcs#12 support to allow import from simple keyBags. * Exporting to pkcs#12 now create bag attributes so that Mozilla is able to import the files. * Fixed uploading of certain keys to the smart card. Noteworthy changes in version 1.9.21 (2006-06-20) ------------------------------------------------- * New command APDU for scdaemon to allow using it for general card access. Might be used through gpg-connect-agent by using the SCD prefix command. * Support for the CardMan 4040 PCMCIA reader (Linux 2.6.15 required). * Scdaemon does not anymore reset cards at the end of a connection. * Kludge to allow use of Bundesnetzagentur issued X.509 certificates. * Added --hash=xxx option to scdaemon's PKSIGN command. * Pkcs#12 files are now created with a MAC. This is for better interoperability. * Collected bug fixes and minor other changes. Noteworthy changes in version 1.9.20 (2005-12-20) ------------------------------------------------- * Importing pkcs#12 files created be recent versions of Mozilla works again. * Basic support for qualified signatures. * New debug tool gpgparsemail. Noteworthy changes in version 1.9.19 (2005-09-12) ------------------------------------------------- * The Belgian eID card is now supported for signatures and ssh. Other pkcs#15 cards should work as well. * Fixed bug in --export-secret-key-p12 so that certificates are again included. Noteworthy changes in version 1.9.18 (2005-08-01) ------------------------------------------------- * [gpgsm] Now allows for more than one email address as well as URIs and dnsNames in certificate request generation. A keygrip may be given to create a request from an existing key. * A couple of minor bug fixes. Noteworthy changes in version 1.9.17 (2005-06-20) ------------------------------------------------- * gpg-connect-agent has now features to handle Assuan INQUIRE commands. * Internal changes for OpenPGP cards. New Assuan command WRITEKEY. * GNU Pth is now a hard requirement. * [scdaemon] Support for OpenSC has been removed. Instead a new and straightforward pkcs#15 modules has been written. As of now it does allows only signing using TCOS cards but we are going to enhance it to match all the old capabilities. * [gpg-agent] New option --write-env-file and Assuan command UPDATESTARTUPTTY. * [gpg-agent] New option --default-cache-ttl-ssh to set the TTL for SSH passphrase caching independent from the other passphrases. Noteworthy changes in version 1.9.16 (2005-04-21) ------------------------------------------------- * gpg-agent does now support the ssh-agent protocol and thus allows to use the pinentry as well as the OpenPGP smartcard with ssh. * New tool gpg-connect-agent as a general client for the gpg-agent. * New tool symcryptrun as a wrapper for certain encryption tools. * The gpg tool is not anymore build by default because those gpg versions available in the gnupg 1.4 series are far more matured. Noteworthy changes in version 1.9.15 (2005-01-13) ------------------------------------------------- * Fixed passphrase caching bug. * Better support for CCID readers; the reader from Cherry RS 6700 USB does now work. Noteworthy changes in version 1.9.14 (2004-12-22) ------------------------------------------------- * [gpg-agent] New option --use-standard-socket to allow the use of a fixed socket. gpgsm falls back to this socket if GPG_AGENT_INFO has not been set. * Ported to MS Windows with some functional limitations. * New tool gpg-preset-passphrase. Noteworthy changes in version 1.9.13 (2004-12-03) ------------------------------------------------- * [gpgsm] New option --prefer-system-dirmngr. * Minor cleanups and debugging aids. Noteworthy changes in version 1.9.12 (2004-10-22) ------------------------------------------------- * [scdaemon] Partly rewrote the PC/SC code. * Removed the sc-investigate tool. It is now in a separate package available at ftp://ftp.g10code.com/g10code/gscutils/ . * [gpg-agent] Fixed logging problem. Noteworthy changes in version 1.9.11 (2004-10-01) ------------------------------------------------- * When using --import along with --with-validation, the imported certificates are validated and only imported if they are fully valid. * [gpg-agent] New option --max-cache-ttl. * [gpg-agent] When used without --daemon or --server, gpg-agent now check whether a agent is already running and usable. * Fixed some i18n problems. Noteworthy changes in version 1.9.10 (2004-07-22) ------------------------------------------------- * Fixed a serious bug in the checking of trusted root certificates. * New configure option --enable-agent-pnly allows to build and install just the agent. * Fixed a problem with the log file handling. Noteworthy changes in version 1.9.9 (2004-06-08) ------------------------------------------------ * [gpg-agent] The new option --allow-mark-trusted is now required to allow gpg-agent to add a key to the trustlist.txt after user confirmation. * Creating PKCS#10 requests does now honor the key usage. Noteworthy changes in version 1.9.8 (2004-04-29) ------------------------------------------------ * [scdaemon] Overhauled the internal CCID driver. * [scdaemon] Status files named ~/.gnupg/reader_.status are now written when using the internal CCID driver. * [gpgsm] New commands --dump-{,secret,external}-keys to show a very detailed view of the certificates. * The keybox gets now compressed after 3 hours and ephemeral stored certificates are deleted after about a day. * [gpg] Usability fixes for --card-edit. Note, that this has already been ported back to gnupg-1.3 Noteworthy changes in version 1.9.7 (2004-04-06) ------------------------------------------------ * Instrumented the modules for gpgconf. * Added support for DINSIG card applications. * Include the smimeCapabilities attribute with signed messages. * Now uses the gettext domain "gnupg2" to avoid conflicts with gnupg versions < 1.9. Noteworthy changes in version 1.9.6 (2004-03-06) ------------------------------------------------ * Code cleanups and bug fixes. Noteworthy changes in version 1.9.5 (2004-02-21) ------------------------------------------------ * gpg-protect-tool gets now installed into libexec as it ought to be. Cleaned up the build system to better comply with the coding standards. * [gpgsm] The --import command is now able to autodetect pkcs#12 files and import secret and private keys from this file format. A new command --export-secret-key-p12 is provided to allow exporting of secret keys in PKCS\#12 format. * [gpgsm] The pinentry will now present a description of the key for whom the passphrase is requested. * [gpgsm] New option --with-validation to check the validity of key while listing it. * New option --debug-level={none,basic,advanced,expert,guru} to map the debug flags to sensitive levels on a per program base. Noteworthy changes in version 1.9.4 (2004-01-30) ------------------------------------------------ * Added support for the Telesec NKS 2.0 card application. * Added simple tool addgnupghome to create .gnupg directories from /etc/skel/.gnupg. * Various minor bug fixes and cleanups; mainly gpgsm and gpg-agent related. Noteworthy changes in version 1.9.3 (2003-12-23) ------------------------------------------------ * New gpgsm options --{enable,disable}-ocsp to validate keys using OCSP. This option requires a not yet released DirMngr version. Default is disabled. * The --log-file option may now be used to print logs to a socket. Prefix the socket name with "socket://" to enable this. This does not work on all systems and falls back to stderr if there is a problem with the socket. * The options --encrypt-to and --no-encrypt-to now work the same in gpgsm as in gpg. Note, they are also used in server mode. * Duplicated recipients are now silently removed in gpgsm. Noteworthy changes in version 1.9.2 (2003-11-17) ------------------------------------------------ * On card key generation is no longer done using the --gen-key command but from the menu provided by the new --card-edit command. * PINs are now properly cached and there are only 2 PINs visible. - The 3rd PIN (CHV2) is internally syncronized with the regular PIN. + The 3rd PIN (CHV2) is internally synchronized with the regular PIN. * All kind of other internal stuff. Noteworthy changes in version 1.9.1 (2003-09-06) ------------------------------------------------ * Support for OpenSC is back. scdaemon supports a --disable-opensc to disable OpenSC use at runtime, so that PC/SC or ct-API can still be used directly. * Rudimentary support for the SCR335 smartcard reader using an internal driver. Requires current libusb from CVS. * Bug fixes. Noteworthy changes in version 1.9.0 (2003-08-05) ------------------------------------------------ ====== PLEASE SEE README-alpha ======= * gpg has been renamed to gpg2 and gpgv to gpgv2. This is a temporary change to allow co-existing with stable gpg versions. * ~/.gnupg/gpg.conf-1.9.0 is fist tried as config file before the usual gpg.conf. * Removed the -k, -kv and -kvv commands. -k is now an alias to --list-keys. New command -K as alias for --list-secret-keys. * Removed --run-as-shm-coprocess feature. * gpg does now also use libgcrypt, libgpg-error is required. * New gpgsm commands --call-dirmngr and --call-protect-tool. * Changing a passphrase is now possible using "gpgsm --passwd" * The content-type attribute is now recognized and created. * The agent does now reread certain options on receiving a HUP. * The pinentry is now forked for each request so that clients with different environments are supported. When running in daemon mode and --keep-display is not used the DISPLAY variable is ignored. * Merged stuff from the newpg branch and started this new development branch. Version 1.4.19 (2015-02-27) Version 1.4.18 (2014-06-30) Version 1.4.17 (2014-06-23) Version 1.4.16 (2013-12-18) Version 1.4.15 (2013-10-04) Version 1.4.14 (2013-07-25) Version 1.4.13 (2012-12-20) Version 1.4.12 (2012-01-30) Version 1.4.11 (2010-10-18) Version 1.4.10 (2009-09-02) Version 1.4.9 (2008-03-26) Version 1.4.8 (2007-12-20) Version 1.4.7 (2007-03-05) Version 1.4.6 (2006-12-06) Version 1.4.5 (2006-08-01) Version 1.4.4 (2006-06-25) Version 1.4.3 (2006-04-03) Version 1.4.2 (2005-07-26) Version 1.4.1 (2005-03-15) Version 1.4.0 (2004-12-16) Noteworthy changes in version 1.3.2 (2003-05-27) ------------------------------------------------ * New "--gnupg" option (set by default) that disables --openpgp, and the various --pgpX emulation options. This replaces --no-openpgp, and --no-pgpX, and also means that GnuPG has finally grown a --gnupg option to make GnuPG act like GnuPG. * A bug in key validation has been fixed. This bug only affects keys with more than one user ID (photo IDs do not count here), and results in all user IDs on a given key being treated with the validity of the most-valid user ID on that key. * Notation names that do not contain a '@' are no longer allowed unless --expert is set. This is to help prevent pollution of the (as yet unused) IETF notation namespace. * Multiple trust models are now supported via the --trust-model option. The options are "pgp" (web-of-trust plus trust signatures), "classic" (web-of-trust only), and "always" (identical to the --always-trust option). * The --personal-{cipher|digest|compression}-preferences are now consulted to get default algorithms before resorting to the last-ditch defaults of --s2k-cipher-algo, SHA1, and ZIP respectively. This allows a user to set algorithms to use in a safe manner so they are used when legal to do so, without forcing them on for all messages. * New --primary-keyring option to designate the keyring that the user wants new keys imported into. * --s2k-digest-algo is now used for all password mangling. Earlier versions used both --s2k-digest-algo and --digest-algo for passphrase mangling. * Handling of --hidden-recipient or --throw-keyid messages is now easier - the user only needs to give their passphrase once, and GnuPG will try it against all of the available secret keys. * Care is taken to prevent compiler optimization from removing memory wiping code. * New option --no-mangle-dos-filenames so that filenames are not truncated in the W32 version. * A "convert-from-106" script has been added. This is a simple script that automates the conversion from a 1.0.6 or earlier version of GnuPG to a 1.0.7 or later version. * Disabled keys are now skipped when selecting keys for encryption. If you are using the --with-colons key listings to detect disabled keys, please see doc/DETAILS for a minor format change in this release. * Minor trustdb changes to make the trust calculations match common usage. * New command "revuid" in the --edit-key menu to revoke a user ID. This is a simpler interface to the old method (which still works) of revoking the user ID self-signature. * Status VALIDSIG does now also print the primary key's fingerprint, as well as the signature version, pubkey algorithm, hash algorithm, and signature class. * Add read-only support for the SHA-256 hash, and optional read-only support for the SHA-384 and SHA-512 hashes. * New option --enable-progress-filter for use with frontends. * DNS SRV records are used in HKP keyserver lookups to allow administrators to load balance and select keyserver ports automatically. This is as specified in draft-shaw-openpgp-hkp-00.txt. * When using the "keyid!" syntax during a key export, only that specified key is exported. If the key in question is a subkey, the primary key plus only that subkey is exported. * configure --disable-xxx options to disable individual algorithms at build time. This can be used to build a smaller gpg binary for embedded uses where space is tight. See the README file for the algorithms that can be used with this option, or use --enable-minimal to build the smallest gpg possible (disables all optional algorithms, disables keyserver access, and disables photo IDs). * The keyserver no-modify flag on a key can now be displayed and modified. * Note that the TIGER/192 digest algorithm is in the process of being dropped from the OpenPGP standard. While this release of GnuPG still contains it, it is disabled by default. To ensure you will still be able to use your messages with future versions of GnuPG and other OpenPGP programs, please do not use this algorithm. See-also: gnupg-announce/2003q2/000153.html Noteworthy changes in version 1.3.1 (2002-11-12) ------------------------------------------------ * Trust signature support. This is based on the Maurer trust model where a user can specify the trust level along with the signature with multiple levels so users can delegate certification ability to other users, possibly restricted by a regular expression on the user ID. Note that full trust signature support requires a regular expression parsing library. The regexp code from glibc 2.3.1 is included for those platforms that don't have working regexp functions available. The configure option --disable-regex may be used to disable any regular expression code, which will make GnuPG ignore any trust signature with a regular expression included. * Two new commands --hidden-recipient (-R) and --hidden-encrypt-to encrypt to a user, but hide the identity of that user. This is the same functionality as --throw-keyid, but can be used on a per-user basis. * Full algorithm names (e.g. "3DES", "SHA1", "ZIP") can now be used interchangeably with the short algorithm names (e.g. "S2", "H2", "Z1") anywhere algorithm names are used in GnuPG. Noteworthy changes in version 1.3.0 (2002-10-18) ------------------------------------------------ * The last piece of internal keyserver support has been removed, and now all keyserver access is done via the keyserver plugins. There is also a newer keyserver protocol used between GnuPG and the plugins, so plugins from earlier versions of GnuPG may not work properly. * The HKP keyserver plugin supports the new machine-readable key listing format for those keyservers that provide it. * When using a HKP keyserver with multiple DNS records (such as wwwkeys.pgp.net which has the addresses of multiple servers around the world), try all records until one succeeds. Note that it depends on the LDAP library used whether the LDAP keyserver plugin does this as well. * The library dependencies for OpenLDAP seem to change fairly frequently, and GnuPG's configure script cannot guess all the combinations. Use ./configure LDAPLIBS="-L libdir -l libs" to override the script and use the libraries selected. * Secret keys generated with --export-secret-subkeys are now indicated in key listings with a '#' after the "sec", and in --with-colons listings by showing no capabilities (no lowercase characters). * --trusted-key has been un-obsoleted, as it is useful for adding ultimately trusted keys from the config file. It is identical to using --edit and "trust" to change a key to ultimately trusted. * Translations other than de are no longer distributed with the development branch. This is due to the frequent text changes during development, which cause the translations to rapidly go out of date. Version 1.2.8 (2006-12-07) Version 1.2.7 (2004-12-27) Version 1.2.6 (2004-08-25) Version 1.2.5 (2004-07-26) Version 1.2.4 (2003-12-23) Version 1.2.3 (2003-08-21) Version 1.2.2 (2003-05-01) Version 1.2.1 (2002-10-25) Version 1.2.0 (2002-09-21) Noteworthy changes in version 1.1.92 (2002-09-11) ------------------------------------------------- * [IMPORTANT] The default configuration file is now ~/.gnupg/gpg.conf. If an old ~/.gnupg/options is found it will still be used. This change is required to have a more consistent naming scheme with forthcoming tools. * The use of MDCs have increased. A MDC will be used if the recipients directly request it, if the recipients have AES, AES192, AES256, or TWOFISH in their cipher preferences, or if the chosen cipher has a blocksize not equal to 64 bits (currently this is also AES, AES192, AES256, and TWOFISH). * GnuPG will no longer automatically disable compression when processing an already-compressed file unless a MDC is being used. This is to give the message a certain amount of resistance to the chosen-ciphertext attack while communicating with other programs (most commonly PGP earlier than version 7.x) that do not support MDCs. * The option --interactive now has the desired effect when importing keys. * The file permission and ownership checks on files have been clarified. Specifically, the homedir (usually ~/.gnupg) is checked to protect everything within it. If the user specifies keyrings outside this homedir, they are presumed to be shared keyrings and therefore *not* checked. Configuration files specified with the --options option and the IDEA cipher extension specified with --load-extension are checked, along with their enclosing directories. * The configure option --with-static-rnd=auto allows to build gpg with all available entropy gathering modules included. At runtime the best usable one will be selected from the list linux, egd, unix. This is also the default for systems lacking a /dev/random device. * The default character set is now taken from the current locale; it can still be overridden by the --charset option. Using the option -vvv shows the used character set. * [REMOVED] --emulate-checksum-bug and --emulate-3des-s2k-bug have been removed. Noteworthy changes in version 1.1.91 (2002-08-04) ------------------------------------------------- * All modules are now linked statically; the --load-extension option is in general not useful anymore. The only exception is to specify the deprecated idea cipher. * The IDEA plugin has changed. Previous versions of the IDEA plugin will no longer work with GnuPG. However, the current version of the plugin will work with earlier GnuPG versions. * When using --batch with one of the --delete-key commands, the key must be specified by fingerprint. See the man page for details. * There are now various ways to restrict the ability GnuPG has to exec external programs (for the keyserver helpers or photo ID viewers). Read the README file for the complete list. * New export option to leave off attribute packets (photo IDs) during export. This is useful when exporting to HKP keyservers which do not understand attribute packets. * New import option to repair during import the HKP keyserver mangling multiple subkeys bug. Note that this cannot completely repair the damaged key as some crucial data is removed by the keyserver, but it does at least give you back one subkey. This is on by default for keyserver --recv-keys, and off by default for regular --import. * The keyserver helper programs now live in /usr/[local/]libexec/gnupg by default. If you are upgrading from 1.0.7, you might want to delete your old copies in /usr/[local/]bin. If you use an OS that does not use libexec for whatever reason, use configure --libexecdir=/usr/local/lib to place the keyserver helpers there. * The LDAP keyserver handler now works properly with very old (version 1) LDAP keyservers. Noteworthy changes in version 1.1.90 (2002-07-01) ------------------------------------------------- * New commands: --personal-cipher-preferences, --personal-digest-preferences, and --personal-compress-preferences allow the user to specify which algorithms are to be preferred. Note that this does not permit using an algorithm that is not present in the recipient's preferences (which would violate the OpenPGP standard). This just allows sorting the preferences differently. * New "group" command to refer to several keys with one name. * A warning is issued if the user forces the use of an algorithm that is not listed in the recipient's preferences. * Full revocation key (aka "designated revoker") support. * The preferred hash algorithms on a key are consulted when encrypting a signed message to that key. Note that this is disabled by default by a SHA1 preference in --personal-digest-preferences. * --cert-digest-algo allows the user to specify the hash algorithm to use when signing a key rather than the default SHA1 (or MD5 for PGP2 keys). Do not use this feature unless you fully understand the implications of this. * --pgp7 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 7.x. * New --attribute-fd command for frontends and scripts to get the contents of attribute packets (i.e. photos) * In expert mode, the user can now re-sign a v3 key with a v4 self-signature. This does not change the v3 key into a v4 key, but it does allow the user to use preferences, primary ID flags, etc. * Significantly improved photo ID support on non-unixlike platforms. * The version number has jumped ahead to 1.1.90 to skip over the old version 1.1 and to get ready for the upcoming 1.2. * ElGamal sign and encrypt is not anymore allowed in the key generation dialog unless in expert mode. RSA sign and encrypt has been added with the same restrictions. * [W32] Keyserver access does work with Windows NT. Noteworthy changes in version 1.0.7 (2002-04-29) ------------------------------------------------ * Secret keys are now stored and exported in a new format which uses SHA-1 for integrity checks. This format renders the Rosa/Klima attack useless. Other OpenPGP implementations might not yet support this, so the option --simple-sk-checksum creates the old vulnerable format. * The default cipher algorithm for encryption is now CAST5, default hash algorithm is SHA-1. This will give us better interoperability with other OpenPGP implementations. * Symmetric encrypted messages now use a fixed file size if possible. This is a tradeoff: it breaks PGP 5, but fixes PGP 2, 6, and 7. Note this was only an issue with RFC-1991 style symmetric messages. * Photographic user ID support. This uses an external program to view the images. * Enhanced keyserver support via keyserver "plugins". GnuPG comes with plugins for the NAI LDAP keyserver as well as the HKP email keyserver. It retains internal support for the HKP HTTP keyserver. * Nonrevocable signatures are now supported. If a user signs a key nonrevocably, this signature cannot be taken back so be careful! * Multiple signature classes are usable when signing a key to specify how carefully the key information (fingerprint, photo ID, etc) was checked. * --pgp2 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 2.x. * --pgp6 mode automatically sets all necessary options to ensure that the resulting message will be usable by a user of PGP 6.x. * Signatures may now be given an expiration date. When signing a key with an expiration date, the user is prompted whether they want their signature to expire at the same time. * Revocation keys (designated revokers) are now supported if present. There is currently no way to designate new keys as designated revokers. * Permissions on the .gnupg directory and its files are checked for safety. * --expert mode enables certain silly things such as signing a revoked user id, expired key, or revoked key. * Some fixes to build cleanly under Cygwin32. * New tool gpgsplit to split OpenPGP data formats into packets. * New option --preserve-permissions. * Subkeys created in the future are not used for encryption or signing unless the new option --ignore-valid-from is used. * Revoked user-IDs are not listed unless signatures are listed too or we are in verbose mode. * There is no default comment string with ascii armors anymore except for revocation certificates and --enarmor mode. * The command "primary" in the edit menu can be used to change the primary UID, "setpref" and "updpref" can be used to change the preferences. * Fixed the preference handling; since 1.0.5 they were erroneously matched against against the latest user ID and not the given one. * RSA key generation. * Merged Stefan's patches for RISC OS in. See comments in scripts/build-riscos. * It is now possible to sign and conventional encrypt a message (-cs). * The MDC feature flag is supported and can be set by using the "updpref" edit command. * The status messages GOODSIG and BADSIG are now returning the primary UID, encoded using %XX escaping (but with spaces left as spaces, so that it should not break too much) * Support for GDBM based keyrings has been removed. * The entire keyring management has been revamped. * The way signature stati are store has changed so that v3 signatures can be supported. To increase the speed of many operations for existing keyrings you can use the new --rebuild-keydb-caches command. * The entire key validation process (trustdb) has been revamped. See the man page entries for --update-trustdb, --check-trustdb and --no-auto-check-trustdb. * --trusted-keys is again obsolete, --edit can be used to set the ownertrust of any key to ultimately trusted. * A subkey is never used to sign keys. * Read only keyrings are now handled as expected. See-also: gnupg-announce/2002q2/000135.html Noteworthy changes in version 1.0.6 (2001-05-29) ------------------------------------------------ * Security fix for a format string bug in the tty code. * Fixed format string bugs in all PO files. * Removed Russian translation due to too many bugs. The FTP server has an unofficial but better translation in the contrib directory. * Fixed expire time calculation and keyserver access. * The usual set of minor bug fixes and enhancements. * non-writable keyrings are now correctly handled. See-also: gnupg-announce/2001q2/000123.html Noteworthy changes in version 1.0.5 (2001-04-29) ------------------------------------------------ * WARNING: The semantics of --verify have changed to address a problem with detached signature detection. --verify now ignores signed material given on stdin unless this is requested by using a "-" as the name for the file with the signed material. Please check all your detached signature handling applications and make sure that they don't pipe the signed material to stdin without using a filename together with "-" on the the command line. * WARNING: Corrected hash calculation for input data larger than 512M - it was just wrong, so you might notice bad signature in some very big files. It may be wise to keep an old copy of GnuPG around. * Secret keys are no longer imported unless you use the new option --allow-secret-key-import. This is a kludge and future versions will handle it in another way. * New command "showpref" in the --edit-key menu to show an easier to understand preference listing. * There is now the notation of a primary user ID. For example, it is printed with a signature verification as the first user ID; revoked user IDs are not printed there anymore. In general the primary user ID is the one with the latest self-signature. * New --charset=utf-8 to bypass all internal conversions. * Large File Support (LFS) is now working. * New options: --ignore-crc-error, --no-sig-create-check, --no-sig-cache, --fixed-list-mode, --no-expensive-trust-checks, --enable-special-filenames and --use-agent. See man page. * New command --pipemode, which can be used to run gpg as a co-process. Currently only the verification of detached signatures are working. See doc/DETAILS. * Keyserver support for the W32 version. * Rewritten key selection code so that GnuPG can better cope with multiple subkeys, expire dates and so. The drawback is that it is slower. * A whole lot of bug fixes. * The verification status of self-signatures are now cached. To increase the speed of key list operations for existing keys you can do the following in your GnuPG homedir (~/.gnupg): cp pubring.gpg pubring.gpg.save && gpg --export-all >x && \ rm pubring.gpg && gpg --import x Only v4 keys (i.e not the old RSA keys) benefit from this caching. * New translations: Estonian, Turkish. See-also: gnupg-announce/2001q2/000122.html Noteworthy changes in version 1.0.4 (2000-10-17) ------------------------------------------------ * Fixed a serious bug which could lead to false signature verification results when more than one signature is fed to gpg. This is the primary reason for releasing this version. * New utility gpgv which is a stripped down version of gpg to be used to verify signatures against a list of trusted keys. * Rijndael (AES) is now supported and listed with top preference. * --with-colons now works with --print-md[s]. See-also: gnupg-announce/2000q4/000082.html Noteworthy changes in version 1.0.3 (2000-09-18) ------------------------------------------------ * Fixed problems with piping to/from other MS-Windows software * Expiration time of the primary key can be changed again. * Revoked user IDs are now marked in the output of --list-key * New options --show-session-key and --override-session-key to help the British folks to somewhat minimize the danger of this Orwellian RIP bill. * New options --merge-only and --try-all-secrets. * New configuration option --with-egd-socket. * The --trusted-key option is back after it left us with 0.9.5 * RSA is supported. Key generation does not yet work but will come soon. * CAST5 and SHA-1 are now the default algorithms to protect the key and for symmetric-only encryption. This should solve a couple of compatibility problems because the old algorithms are optional according to RFC2440 * Twofish and MDC enhanced encryption is now used. PGP 7 supports this. Older versions of GnuPG don't support it, so they should be upgraded to at least 1.0.2 See-also: gnupg-announce/2000q3/000075.html Noteworthy changes in version 1.0.2 (2000-07-12) ---------------------------------------------- * Fixed expiration handling of encryption keys. * Add an experimental feature to do unattended key generation. * The user is now asked for the reason of revocation as required by the new OpenPGP draft. * There is a ~/.gnupg/random_seed file now which saves the state of the internal RNG and increases system performance somewhat. This way the full entropy source is only used in cases were it is really required. Use the option --no-random-seed-file to disable this feature. * New options --ignore-time-conflict and --lock-never. * Some fixes for the W32 version. * The entropy.dll is not anymore used by the W32 version but replaced by code derived from Cryptlib. * Encryption is now much faster: About 2 times for 1k bit keys and 8 times for 4k keys. * New encryption keys are generated in a way which allows a much faster decryption. * New command --export-secret-subkeys which outputs the the _primary_ key with it's secret parts deleted. This is useful for automated decryption/signature creation as it allows to keep the real secret primary key offline and thereby protecting the key certificates and allowing to create revocations for the subkeys. See the FAQ for a procedure to install such secret keys. * Keygeneration now writes to the first writeable keyring or as default to the one in the homedirectory. Prior versions ignored all --keyring options. * New option --command-fd to take user input from a file descriptor; to be used with --status-fd by software which uses GnuPG as a backend. * There is a new status PROGRESS which is used to show progress during key generation. * Support for the new MDC encryption packets. To create them either --force-mdc must be use or cipher algorithm with a blocksize other than 64 bits is to be used. --openpgp currently disables MDC packets entirely. This option should not yet be used. * New option --no-auto-key-retrieve to disable retrieving of a missing public key from a keyserver, when a keyserver has been set. * Danish translation See-also: gnupg-announce/2000q3/000069.html Noteworthy changes in version 1.0.1 (1999-12-16) ----------------------------------- * New command --verify-files. New option --fast-list-mode. * $http_proxy is now used when --honor-http-proxy is set. * Fixed some minor bugs and the problem with conventional encrypted packets which did use the gpg v3 partial length headers. * Add Indonesian and Portugese translations. * Fixed a bug with symmetric-only encryption using the non-default 3DES. The option --emulate-3des-s2k-bug may be used to decrypt documents which have been encrypted this way; this should be done immediately as this workaround will be remove in 1.1 * Can now handle (but not display) PGP's photo IDs. I don't know the format of that packet but after stripping a few bytes from the start it looks like a JPEG (at least my test data). Handling of this package is required because otherwise it would mix up the self signatures and you can't import those keys. * Passing non-ascii user IDs on the commandline should now work in all cases. * New keys are now generated with an additional preference to Blowfish. * Removed the GNU Privacy Handbook from the distribution as it will go into a separate one. See-also: gnupg-announce/1999q4/000050.html Noteworthy changes in version 1.0.0 (1999-09-07) ----------------------------------- * Add a very preliminary version of the GNU Privacy Handbook to the distribution (lynx doc/gph/index.html). * Changed the version number to GnuPG 2001 ;-) See-also: gnupg-announce/1999q3/000037.html Noteworthy changes in version 0.9.11 (1999-09-03) ------------------------------------ * UTF-8 strings are now correctly printed (if --charset is set correctly). Output of --with-colons remains C-style escaped UTF-8. * Workaround for a problem with PGP 5 detached signature in textmode. * Fixed a problem when importing new subkeys (duplicated signatures). See-also: gnupg-announce/1999q3/000036.html Noteworthy changes in version 0.9.10 (1999-07-23) ------------------------------------ * Some strange new options to help pgpgpg * Cleaned up the dox a bit. See-also: gnupg-announce/1999q3/000034.html Noteworthy changes in version 0.9.9 ----------------------------------- * New options --[no-]utf8-strings. * New edit-menu commands "enable" and "disable" for entire keys. * You will be asked for a filename if gpg cannot deduce one. * Changes to support libtool which is needed for the development of libgcrypt. * New script tools/lspgpot to help transferring assigned trustvalues from PGP to GnuPG. * New commands --lsign-key and made --sign-key a shortcut for --edit and sign. * New options (#122--126 ;-) --[no-]default-recipient[-self], --disable-{cipher,pubkey}-algo. See the man page. * Enhanced info output in case of multiple recipients and fixed exit code. * New option --allow-non-selfsigned-uid to work around a problem with the German IN way of separating signing and encryption keys. See-also: gnupg-announce/1999q3/000028.html Noteworthy changes in version 0.9.8 (1999-06-26) ----------------------------------- * New subcommand "delsig" in the edit menu. * The name of the output file is not anymore the one which is embedded in the processed message, but the used filename with the extension stripped. To revert to the old behaviour you can use the option --use-embedded-filename. * Another hack to cope with pgp2 generated detached signatures. * latin-2 character set works (--charset=iso-8859-2). * New option --with-key-data to list the public key parameters. New option -N to insert notations and a --set-policy-url. A couple of other options to allow reseting of options. * Better support for HPUX. See-also: gnupg-announce/1999q2/000016.html Noteworthy changes in version 0.9.7 (1999-05-23) ----------------------------------- * Add some work arounds for a bugs in pgp 2 which led to bad signatures when used with canonical texts in some cases. * Enhanced some status outputs. See-also: gnupg-announce/1999q2/000000.html Noteworthy changes in version 0.9.6 (1999-05-06) ----------------------------------- * Twofish is now statically linked by default. The experimental 128 bit version is now disabled. Full support will be available as soon as the OpenPGP WG has decided on an interpretation of rfc2440. * Dropped support for the ancient Blowfish160 which is not OpenPGP. * Merged gpgm and gpg into one binary. * Add "revsig" and "revkey" commands to the edit menu. It is now possible to revoke signature and subkeys. Noteworthy changes in version 0.9.5 (1999-03-20) ----------------------------------- * New command "lsign" in the keyedit menu to create non-exportable signatures. Removed --trusted-keys option. * A bunch of changes to the key validation code. * --list-trust-path now has an optional --with-colons format. * New command --recv-keys to import keys from an keyserver. Noteworthy changes in version 0.9.4 (1999-03-08) ----------------------------------- * New configure option --enable-static-rnd=[egd|linux|unix|none] to select a random gathering module for static linking. * The original text is now verbatim copied to a cleartext signed message. * Bugfixes but there are still a couple of bugs. Noteworthy changes in version 0.9.3 (1999-02-19) ----------------------------------- * Changed the internal design of getkey which now allows a efficient lookup of multiple keys and add a word match mode. * New options --[no-]encrypt-to. * Some changes to the configure stuff. Switched to automake 1.4. Removed intl/ from CVS, autogen.sh now uses gettextize. * Preferences now include Twofish. Removed preference to Blowfish with a special hack to suppress the "not listed in preferences" warning; this is to allow us to switch completely to Twofish in the near future. * Changed the locking stuff. * Print all user ids of a good signature. Noteworthy changes in version 0.9.2 (1999-01-01) ----------------------------------- * add some additional time warp checks. * Option --keyserver and command --send-keys to utilize HKP servers. * Upgraded to zlib 1.1.3 and fixed an inflate bug * More cleanup on the cleartext signatures. Noteworthy changes in version 0.9.1 (1999-01-01) ----------------------------------- * Polish language support. * When querying the passphrase, the key ID of the primary key is displayed along with the one of the used secondary key. * Fixed a bug occurring when decrypting pgp 5 encrypted messages, fixed an infinite loop bug in the 3DES code and in the code which looks for trusted signatures. * Fixed a bug in the mpi library which caused signatures not to compare okay. * Rewrote the handling of cleartext signatures; the code is now better maintainable (I hope so). * New status output VALIDSIG only for valid signatures together with the fingerprint of the signer's key. Noteworthy changes in version 0.9.0 (1998-12-23) ----------------------------------- * --export does now only exports rfc2440 compatible keys; the old behaviour is available with --export-all. Generation of v3 ElGamal (sign and encrypt) keys is not longer supported. * Fixed the uncompress bug. * Rewrote the rndunix module. There are two environment variables used for debugging now: GNUPG_RNDUNIX_DBG give the file to write debugging information (use "-" for stdout) and if GNUPG_RNDUNIX_DBGALL is set, all programs which are only tried are also printed. * New option --escape-from-lines to "dash-escape" "From " lines to prevent mailers to change them to ">From ". This is not enabled by default because it is not in compliance with rfc2440 - however, you should turn it on. Noteworthy changes in version 0.4.5 (1998-12-08) ----------------------------------- * The keyrings and the trustdb is now locked, so that other GnuPG processes won't damage these files. You may want to put the option --lock-once into your options file. * The latest self-signatures are now used; this enables --import to see updated preferences etc. * Import of subkeys should now work. * Random gathering modules may now be loaded as extensions. Add such a module for most Unices but it is very experimental! * Brazilian language support. Noteworthy changes in version 0.4.4 (1998-11-20) ----------------------------------- * Fixed the way the key expiration time is stored. If you have an expiration time on your key you should fix it with --edit-key and the command "expire". I apologize for this inconvenience. * Add option --charset to support "koi8-r" encoding of user ids. (Not yet tested). * Preferences should now work again. You should run "gpgm --check-trustdb \*" to rebuild all preferences. * Checking of certificates should now work but this needs a lot of testing. Key validation values are now cached in the trustdb; they should be recalculated as needed, but you may use --check-trustdb or --update-trustdb to do this. * Spanish translation by Urko Lusa. * Patch files are from now on signed. See the man page for the new option --not-dash-escaped. * New syntax: --edit-key [] If you run it without --batch the commands are executed and then you are put into normal mode unless you use "quit" or "save" as one of the commands. When in batch mode, the program quits after the last command, so you have to use "save" if you did some changes. It does not yet work completely, but may be used to list so the keys etc. Noteworthy changes in version 0.4.3 (1998-11-08) ----------------------------------- * Fixed the gettext configure bug. * Kludge for RSA keys: keyid and length of a RSA key are correctly reported, but you get an error if you try to use this key (If you do not have the non-US version). * Experimental support for keyrings stored in a GDBM database. This is *much* faster than a standard keyring. You will notice that the import gets slower with time; the reason is that all new keys are used to verify signatures of previous inserted keys. Use "--keyring gnupg-gdbm:". This is not (yet) supported for secret keys. * A Russian language file in the distribution (alternatives are in the contrib directory of the FTP servers) * commandline option processing now works as expected for GNU programs with the exception that you can't mix options and normal arguments. * Now --list-key lists all matching keys. This is needed in some other places too. Noteworthy changes in version 0.4.2 (1998-10-18) ----------------------------------- * This is only a snapshot: There are still a few bugs. * Fixed this huge memory leak. * Redesigned the trust database: You should run "gpgm --check-trustdb". New command --update-trustdb, which adds new key from the public keyring into your trustdb * Fixed a bug in the armor code, leading to invalid packet errors. (a workaround for this was to use --no-armor). The shorten line length (64 instead of 72) fixes a problem with pgp5 and keyservers. * comment packets are not anymore generated. "--export" filters them out. One Exception: The comment packets in a secret keyring are still used because they carry the factorization of the public prime product. * --import now only looks for KEYBLOCK headers, so you can now simply remove the "- " in front of such a header if someone accidentally signed such a message or the keyblock is part of a cleartext signed message. * --with-colons now lists the key expiration time and not anymore the valid period. * Some keyblocks created with old releases have a wrong sequence of packets, so that the keyservers don't accept these keys. Simply using "--edit-key" fixes the problem. * New option --force-v3-sigs to generate signed messages which are compatible to PGP 5. * Add some code to support DLD (for non ELF systems) - but this is not tested because my BSD box is currently broken. * New command "expire" in the edit-key menu. Noteworthy changes in version 0.4.1 (1998-10-07) ----------------------------------- * A secondary key is used when the primary key is specified but cannot be used for the operation (if it is a sign-only key). * GNUPG can now handle concatenated armored messages: There is still a bug if different kinds of messages are mixed. * Iterated+Salted passphrases now work. If want to be sure that PGP5 is able to handle them you may want to use the options "--s2k-mode 3 --s2k-cipher-algo cast5 --s2k-digest-algo sha1" when changing a passphrase. * doc/OpenPGP talks about OpenPGP compliance, doc/HACKING gives a few hints about the internal structure. * Checked gnupg against the August 1998 draft (07) and I believe it is in compliance with this document (except for one point). * Fixed some bugs in the import merging code and rewrote some code for the trustdb. Noteworthy changes in version 0.4.0 (1998-09-18) ----------------------------------- * Triple DES is now supported. Michael Roth did this piece of needed work. We have now all the coded needed to be OpenPGP compliant. * Added a simple rpm spec file (see INSTALL). * detached and armored signatures are now using "PGP SIGNATURE", except when --rfc1991 is used. * All times which are not in the yyyy-mm-dd format are now printed in local time. Noteworthy changes in version 0.3.5 (1998-09-14) ----------------------------------- * New option --throw-keyid to create anonymous enciphered messages. If gpg detects such a message it tires all available secret keys in turn so decode it. This is a gnupg extension and not in OpenPGP but it has been discussed there and afaik some products use this scheme too (Suggested by Nimrod Zimmerman). * Fixed a bug with 5 byte length headers. * --delete-[secret-]key is now also available in gpgm. * cleartext signatures are not anymore converted to LF only. * Fixed a trustdb problem. Run "gpgm --check-trustdb" to fix old trust dbs. * Building in another directory should now work. * Weak key detection mechanism (Niklas Hernaeus). Noteworthy changes in version 0.3.4 (1998-08-11) ----------------------------------- * New options --comment and --set-filename; see g10/OPTIONS * yes/no, y/n localized. * Fixed some bugs. Noteworthy changes in version 0.3.3 (1998-08-08) ----------------------------------- * IMPORTANT: I found yet another bug in the way the secret keys are encrypted - I did it the way pgp 2.x did it, but OpenPGP and pgp 5.x specify another (in some aspects simpler) method. To convert your secret keys you have to do this: 1. Build the new release but don't install it and keep a copy of the old program. 2. Disable the network, make sure that you are the only user, be sure that there are no Trojan horses etc .... 3. Use your old gpg (version 0.3.1 or 0.3.2) and set the passphrases of ALL your secret keys to empty! (gpg --change-passphrase your-user-id). 4. Save your ownertrusts (see the next point) 5. rm ~/.gnupg/trustdb.gpg 6. install the new version of gpg (0.3.3) 7. For every secret key call "gpg --edit-key your-user-id", enter "passwd" at the prompt, follow the instructions and change your password back, enter "save" to store it. 8. Restore the ownertrust (see next point). * The format of the trust database has changed; you must delete the old one, so gnupg can create a new one. IMPORTANT: Use version 0.3.1 or .2 to save your assigned ownertrusts ("gpgm --list-ownertrust >saved-trust"); then build this new version and restore the ownertrust with this new version ("gpgm --import-ownertrust saved-trust"). Please note that --list-ownertrust has been renamed to --export-ownertrust in this release and it does now only export defined ownertrusts. * The command --edit-key now provides a commandline driven menu which can be used for various tasks. --sign-key is only an an alias to --edit-key and maybe removed in future: use the command "sign" of this new menu - you can select which user ids you want to sign. * Alternate user ids can now be created an signed. * Owner trust values can now be changed with --edit-key (trust) * GNUPG can now run as a coprocess; this enables sophisticated frontends. tools/shmtest.c is a simple sample implementation. This needs some more work: all tty_xxx() are to be replaced by cpr_xxx() and some changes in the display logics is needed. * Removed options --gen-prime and --gen-random. * Removed option --add-key; use --edit-key instead. * Removed option --change-passphrase; use --edit-key instead. * Signatures are now checked even if the output file could not be created. Command "--verify" tries to find the detached data. * gpg now disables core dumps. * compress and symmetric cipher preferences are now used. Because there is no 3DES yet, this is replaced by Blowfish. * We have added the Twofish as an experimental cipher algorithm. Many thanks to Matthew Skala for doing this work. Twofish is the AES submission from Schneier et al.; see "www.counterpane.com/twofish.html" for more information. * Started with a help system: If you enter a question mark at some prompt; you should get a specific help for this prompt. * There is no more backup copy of the secret keyring. * A lot of new bugs. I think this release is not as stable as the previous one. Noteworthy changes in version 0.3.2 (1998-07-09) ----------------------------------- * Fixed some bugs when using --textmode (-seat) * Now displays the trust status of a positive verified message. * Keyrings are now scanned in the sequence they are added with --[secret-]keyring. Note that the default keyring is implicitly added as the very first one unless --no-default-keyring is used. * Fixed setuid and dlopen bug. Noteworthy changes in version 0.3.1 (1998-07-06) ----------------------------------- * Partial headers are now written in the OpenPGP format if a key in a v4 packet is used. * Removed some unused options, removed the gnupg.sig stuff. * Key lookup by name now returns a key which can be used for the desired action. * New options --list-ownertrust (gpgm) to make a backup copy of the ownertrust values you assigned. * clear signature headers are now in compliance with OpenPGP. Noteworthy changes in version 0.3.0 (1998-06-25) ----------------------------------- * New option --emulate-checksum-bug. If your passphrase does not work anymore, use this option and --change-passphrase to rewrite your passphrase. * More complete v4 key support: Preferences and expiration time is set into the self signature. * Key generation defaults to DSA/ElGamal keys, so that new keys are interoperable with pgp5 * DSA key generation is faster and key generation does not anymore remove entropy from the random generator (the primes are public parameters, so there is really no need for a cryptographic secure prime number generator which we had used). * A complete new structure for representing the key parameters. * Removed most public key knowledge into the cipher library. * Support for dynamic loading of new algorithms. * Moved tiger to an extension module. Noteworthy changes in version 0.2.19 (1998-05-29) ------------------------------------ * Replaced /dev/urandom in checks with new tool mk-tdata. * Some assembler file cleanups; some more functions for the Alpha. * Tiger has now the OpenPGP assigned number 6. Because the OID has changed, old signatures using this algorithm can't be verified. * gnupg now encrypts the compressed packed and not any longer in the reverse order; anyway it can decrypt both versions. Thanks to Tom for telling me this (not security related) bug. * --add-key works and you are now able to generate subkeys. * It is now possible to generate ElGamal keys in v4 packets to create valid OpenPGP keys. * Some new features for better integration into MUAs. Noteworthy changes in version 0.2.18 (1998-05-15) ------------------------------------ * Splitted cipher/random.c, add new option "--disable-dev-random" to configure to support the development of a random source for other systems. Prepared sourcefiles rand-unix.c, rand-w32.c and rand-dummy.c (which is used to allow compilation on systems without a random source). * Fixed a small bug in the key generation (it was possible that 48 bits of a key were not taken from the random pool) * Add key generation for DSA and v4 signatures. * Add a function trap_unaligned(), so that a SIGBUS is issued on Alphas and not the slow emulation code is used. And success: rmd160 raised a SIGBUS. * Enhanced the formatting facility of argparse and changed the use of \r,\v to @ because gettext does not like it. * New option "--compress-algo 1" to allow the creation of compressed messages which are readable by PGP and "--print-md" (gpgm) to make speed measurement easier. Noteworthy changes in version 0.2.17 (1998-05-04) ------------------------------------ * Comment packets are now of private type 61. * Passphrase code still used a 160 bit blowfish key, added a silly workaround. Please change your passphrase again - sorry. * Conventional encryption now uses a type 3 packet to describe the used algorithms. * The new algorithm number for Blowfish is 20, 16 is still used for encryption only; for signing it is only used when it is in a v3 packet, so that GNUPG keys are still valid. Noteworthy changes in version 0.2.16 (1998-04-28) ------------------------------------ * Add experimental support for the TIGER/192 message digest algorithm. (But there is only a dummy ASN OID). * Standard cipher is now Blowfish with 128 bit key in OpenPGP's CFB mode. I renamed the old cipher to Blowfish160. Because the OpenPGP group refused to assign me a number for Blowfish160, I have to drop support for this in the future. You should use "--change-passphrase" to recode your current passphrase with 128 bit Blowfish. Noteworthy changes in version 0.2.15 (1998-04-09) ------------------------------------ * Fixed a bug with the old checksum calculation for secret keys. If you run the program without --batch, a warning does inform you if your secret key needs to be converted; simply use --change-passphrase to recalculate the checksum. Please do this soon, as the compatible mode will be removed sometime in the future. * CAST5 works (using the PGP's special CFB mode). * Again somewhat more PGP 5 compatible. * Some new test cases Noteworthy changes in version 0.2.14 (1998-04-02) ------------------------------------ * Changed the internal handling of keyrings. * Add support to list PGP 5 keyrings with subkeys * Timestamps of signatures are now verified. * A expiration time can now be specified during key generation. * Some speedups for Blowfish and SHA-1, rewrote SHA-1 transform. Reduced the amount of random bytes needed for key generation in some cases. Noteworthy changes in version 0.2.13 (1998-03-10) ------------------------------------ * Verify of DSA signatures works. * Re-implemented the slower random number generator. Noteworthy changes in version 0.2.12 (1998-03-07) ------------------------------------ * --delete-key checks that there is no secret key. The new option --delete-secret-key maybe used to delete a secret key. * "-kv" now works as expected. Options "--list-{keys,sigs]" and "--check-sigs" are now working. * New options "--verify" and "--decrypt" to better support integration into MUAs (partly done for Mutt). * New option "--with-colons" to make parsing of key lists easier. Noteworthy changes in version 0.2.11 (1998-03-02) ------------------------------------ * GPG now asks for a recipient's name if option "-r" is not used. * If there is no good trust path, the program asks whether to use the public keys anyway. * "--delete-key" works for public keys. What semantics shall I use when there is a secret key too? Delete the secret key or leave him and auto-regenerate the public key, next time the secret key is used? Noteworthy changes in version 0.2.10 (1998-02-27) ------------------------------------ * Code for the alpha is much faster (about 20 times); the data was misaligned and the kernel traps this, so nearly all time was used by system to trap the misalignments and to write syslog messages. Shame on me and thanks to Ralph for pointing me at this while drinking some beer yesterday. * Changed some configure options and add an option --disable-m-guard to remove the memory checking code and to compile everything with optimization on. * New environment variable GNUPGHOME, which can be used to set another homedir than ~/.gnupg. Changed default homedir for Windoze version to c:/gnupg. * Fixed detached signatures; detached PGP signatures caused a SEGV. * The Windoze version works (as usual w/o a strong RNG). Noteworthy changes in version 0.2.9 (1998-02-26) ----------------------------------- * Fixed FreeBSD bug. * Added a simple man page. * Switched to automake1.2f and a newer gettext. Noteworthy changes in version 0.2.8 (1998-02-24) ----------------------------------- * Changed the name to GNUPG, the binaries are called gpg and gpgm. You must rename rename the directory "~/.g10" to ~/.gnupg/, rename {pub,sec}ring.g10 to {pub,sec}ring.gpg, trustdb.g10 to trustdb.gpg and g10.sig to gnupg.sig. * New or changed passphrases are now salted. Noteworthy changes in version 0.2.7 (1998-02-18) ----------------------------------- * New command "gen-revoke" to create a key revocation certificate. * New option "homedir" to set the homedir (which defaults to "~/.g10"). This directory is created if it does not exists (only the last part of the name and not the complete hierarchy) * Command "import" works. (Try: "finger gcrypt@ftp.guug.de|g10 --import") * New commands "dearmor/enarmor" for g10maint. These are mainly used for internal test purposes. * Option --version now conforming to the GNU standards and lists the available ciphers, message digests and public key algorithms. * Assembler code for m68k (not tested). * "make check" works. Noteworthy changes in version 0.2.6 (1998-02-13) ----------------------------------- * Option "--export" works. Noteworthy changes in version 0.2.5 (1998-02-12) ----------------------------------- * Added zlib for systems which don't have it. Use "./configure --with-zlib" to link with the static version. * Generalized some more functions and rewrote the encoding of message digests into MPIs. * Enhanced the checkit script Noteworthy changes in version 0.2.4 (1998-02-11) ----------------------------------- * nearly doubled the speed of the ElGamal signature verification. * backup copies of keyrings are created. * assembler stuff for Pentium; gives about 15% better performance. * fixed a lot of bugs. Noteworthy changes in version 0.2.3 (1998-02-09) ----------------------------------- * Found a bug in the calculation of ELG fingerprints. This is now fixed, but all existing fingerprints and keyids for ELG keys are not any more valid. * armor should now work; including clear signed text. * moved some options to the new program g10maint * It's now 64 bit clean and runs fine on an alpha--linux. * Key generation is much faster now. I fixed this by using not so strong random number for the primes (this was a bug because the ElGamal primes are public parameters and it does not make sense to generate them from strong random). The real secret is the x value which is still generated from strong (okay: /dev/random) random bits. * added option "--status-fd": see g10/OPTIONS * We have secure memory on systems which support mlock(). It is not complete yet, because we do not have signal handler which does a cleanup in very case. We should also check the ulimit for the user in the case that the admin does not have set a limit on locked pages. * started with internationalization support. * The logic to handle the web of trust is now implemented. It is has some bugs; but I'm going to change the algorithm anyway. It works by calculating the trustlevel on the fly. It may ask you to provide trust parameters if the calculated trust probability is too low. I will write a paper which discusses this new approach. * a couple of changes to the configure script. * New option "--quick-random" which uses a much quicker random number generator. Keys generated while this option is in effect are flags with "INSECURE!" in the user-id. This is a development only option. * Read support for new version packets (OpenPGP). * Comment packets are now of correct OpenPGP type 16. Old comment packets written by G10 are detected because they always start with a hash which is an invalid version byte. * The string "(INSECURE!)" is appended to a new user-id if this is generated on a system without a good random number generator. Version 0.2.2 (1998-02-09) Version 0.2.1 (1998-01-28) Version 0.2.0 (1998-01-25) Version 0.1.3 (1998-01-12) Version 0.1.2 (1998-01-07) Version 0.1.1 (1998-01-07) Version 0.1.0 (1998-01-05) Version 0.0.0 (1997-12-20) Copyright (C) 1998-2017 Free Software Foundation, Inc. Copyright (C) 1997-2017 Werner Koch This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/agent/gpg-agent.c b/agent/gpg-agent.c index 87656a1f3..793fc44eb 100644 --- a/agent/gpg-agent.c +++ b/agent/gpg-agent.c @@ -1,3268 +1,3268 @@ /* gpg-agent.c - The GnuPG Agent * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc. * Copyright (C) 2000-2016 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # ifndef WINVER # define WINVER 0x0500 /* Same as in common/sysutils.c */ # endif # ifdef HAVE_WINSOCK2_H # include # endif # include # include #else /*!HAVE_W32_SYSTEM*/ # include # include #endif /*!HAVE_W32_SYSTEM*/ #include #ifdef HAVE_SIGNAL_H # include #endif #include #define GNUPG_COMMON_NEED_AFLOCAL #include "agent.h" #include /* Malloc hooks and socket wrappers. */ #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/gc-opt-flags.h" #include "../common/exechelp.h" #include "../common/asshelp.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aGPGConfList, aGPGConfTest, aUseStandardSocketP, oOptions, oDebug, oDebugAll, oDebugLevel, oDebugWait, oDebugQuickRandom, oDebugPinentry, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oGrab, oNoGrab, oLogFile, oServer, oDaemon, oSupervised, oBatch, oPinentryProgram, oPinentryTouchFile, oPinentryInvisibleChar, oPinentryTimeout, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oScdaemonProgram, oDefCacheTTL, oDefCacheTTLSSH, oMaxCacheTTL, oMaxCacheTTLSSH, oEnforcePassphraseConstraints, oMinPassphraseLen, oMinPassphraseNonalpha, oCheckPassphrasePattern, oMaxPassphraseDays, oEnablePassphraseHistory, oEnableExtendedKeyFormat, oUseStandardSocket, oNoUseStandardSocket, oExtraSocket, oBrowserSocket, oFakedSystemTime, oIgnoreCacheForSigning, oAllowMarkTrusted, oNoAllowMarkTrusted, oAllowPresetPassphrase, oAllowLoopbackPinentry, oNoAllowLoopbackPinentry, oNoAllowExternalCache, oAllowEmacsPinentry, oKeepTTY, oKeepDISPLAY, oSSHSupport, oSSHFingerprintDigest, oPuttySupport, oDisableScdaemon, oDisableCheckOwnSocket, oS2KCount, oS2KCalibration, oAutoExpandSecmem, oListenBacklog, oWriteEnvFile }; #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif static ARGPARSE_OPTS opts[] = { ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"), ARGPARSE_group (301, N_("@Options:\n ")), ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")), ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")), #ifndef HAVE_W32_SYSTEM ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"), ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_n (oGrab, "grab", "@"), /* FIXME: Add the below string for 2.3 */ /* N_("let PIN-Entry grab keyboard and mouse")), */ ARGPARSE_s_n (oNoGrab, "no-grab", "@"), ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")), ARGPARSE_s_s (oPinentryProgram, "pinentry-program", /* */ N_("|PGM|use PGM as the PIN-Entry program")), ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"), ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"), ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"), ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program", /* */ N_("|PGM|use PGM as the SCdaemon program") ), ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon", /* */ N_("do not use the SCdaemon") ), ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_s (oExtraSocket, "extra-socket", /* */ N_("|NAME|accept some commands via NAME")), ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"), ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"), ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oDisplay, "display", "@"), ARGPARSE_s_s (oTTYname, "ttyname", "@"), ARGPARSE_s_s (oTTYtype, "ttytype", "@"), ARGPARSE_s_s (oLCctype, "lc-ctype", "@"), ARGPARSE_s_s (oLCmessages, "lc-messages", "@"), ARGPARSE_s_s (oXauthority, "xauthority", "@"), ARGPARSE_s_n (oKeepTTY, "keep-tty", /* */ N_("ignore requests to change the TTY")), ARGPARSE_s_n (oKeepDISPLAY, "keep-display", /* */ N_("ignore requests to change the X display")), ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl", N_("|N|expire cached PINs after N seconds")), ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ), ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ), ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ), ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints", /* */ "@"), ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"), ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"), ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"), ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"), ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"), ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing", /* */ N_("do not use the PIN cache when signing")), ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache", /* */ N_("disallow the use of an external password cache")), ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted", /* */ N_("disallow clients to mark keys as \"trusted\"")), ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"), ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase", /* */ N_("allow presetting passphrase")), ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry", N_("disallow caller to override the pinentry")), ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"), ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry", /* */ N_("allow passphrase to be prompted through Emacs")), ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")), ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest", N_("|ALGO|use ALGO to show ssh fingerprints")), ARGPARSE_s_n (oPuttySupport, "enable-putty-support", #ifdef HAVE_W32_SYSTEM /* */ N_("enable putty support") #else /* */ "@" #endif ), ARGPARSE_s_n (oEnableExtendedKeyFormat, "enable-extended-key-format", "@"), ARGPARSE_s_u (oS2KCount, "s2k-count", "@"), ARGPARSE_s_u (oS2KCalibration, "s2k-calibration", "@"), ARGPARSE_op_u (oAutoExpandSecmem, "auto-expand-secmem", "@"), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), /* Dummy options for backward compatibility. */ ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"), ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"), ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"), ARGPARSE_end () /* End of list */ }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_MPI_VALUE , "mpi" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */ #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */ #define MAX_CACHE_TTL (120*60) /* 2 hours */ #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */ #define MIN_PASSPHRASE_LEN (8) #define MIN_PASSPHRASE_NONALPHA (1) #define MAX_PASSPHRASE_DAYS (0) /* The timer tick used for housekeeping stuff. Note that on Windows * we use a SetWaitableTimer seems to signal earlier than about 2 * seconds. Thus we use 4 seconds on all platforms except for * Windowsce. CHECK_OWN_SOCKET_INTERVAL defines how often we check * our own socket in standard socket mode. If that value is 0 we * don't check at all. All values are in seconds. */ #if defined(HAVE_W32CE_SYSTEM) # define TIMERTICK_INTERVAL (60) # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */ #else # define TIMERTICK_INTERVAL (4) # define CHECK_OWN_SOCKET_INTERVAL (60) #endif /* Flag indicating that the ssh-agent subsystem has been enabled. */ static int ssh_support; #ifdef HAVE_W32_SYSTEM /* Flag indicating that support for Putty has been enabled. */ static int putty_support; /* A magic value used with WM_COPYDATA. */ #define PUTTY_IPC_MAGIC 0x804e50ba /* To avoid surprises we limit the size of the mapped IPC file to this value. Putty currently (0.62) uses 8k, thus 16k should be enough for the foreseeable future. */ #define PUTTY_IPC_MAXLEN 16384 #endif /*HAVE_W32_SYSTEM*/ /* The list of open file descriptors at startup. Note that this list * has been allocated using the standard malloc. */ #ifndef HAVE_W32_SYSTEM static int *startup_fd_list; #endif /* The signal mask at startup and a flag telling whether it is valid. */ #ifdef HAVE_SIGPROCMASK static sigset_t startup_signal_mask; static int startup_signal_mask_valid; #endif /* Flag to indicate that a shutdown was requested. */ static int shutdown_pending; /* Counter for the currently running own socket checks. */ static int check_own_socket_running; /* Flags to indicate that check_own_socket shall not be called. */ static int disable_check_own_socket; /* Flag indicating that we are in supervised mode. */ static int is_supervised; /* Flag to inhibit socket removal in cleanup. */ static int inhibit_socket_removal; /* It is possible that we are currently running under setuid permissions */ static int maybe_setuid = 1; /* Name of the communication socket used for native gpg-agent requests. The second variable is either NULL or a malloced string with the real socket name in case it has been redirected. */ static char *socket_name; static char *redir_socket_name; /* Name of the optional extra socket used for native gpg-agent requests. */ static char *socket_name_extra; static char *redir_socket_name_extra; /* Name of the optional browser socket used for native gpg-agent requests. */ static char *socket_name_browser; static char *redir_socket_name_browser; /* Name of the communication socket used for ssh-agent protocol. */ static char *socket_name_ssh; static char *redir_socket_name_ssh; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; static assuan_sock_nonce_t socket_nonce_extra; static assuan_sock_nonce_t socket_nonce_browser; static assuan_sock_nonce_t socket_nonce_ssh; /* Value for the listen() backlog argument. We use the same value for * all sockets - 64 is on current Linux half of the default maximum. * Let's try this as default. Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Default values for options passed to the pinentry. */ static char *default_display; static char *default_ttyname; static char *default_ttytype; static char *default_lc_ctype; static char *default_lc_messages; static char *default_xauthority; /* Name of a config file, which will be reread on a HUP if it is not NULL. */ static char *config_filename; /* Helper to implement --debug-level */ static const char *debug_level; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* The handle_tick() function may test whether a parent is still * running. We record the PID of the parent here or -1 if it should * be watched. */ static pid_t parent_pid = (pid_t)(-1); /* This flag is true if the inotify mechanism for detecting the * removal of the homedir is active. This flag is used to disable the * alternative but portable stat based check. */ static int have_homedir_inotify; /* Depending on how gpg-agent was started, the homedir inotify watch * may not be reliable. This flag is set if we assume that inotify * works reliable. */ static int reliable_homedir_inotify; /* Number of active connections. */ static int active_connections; /* This object is used to dispatch progress messages from Libgcrypt to * the right thread. Given that we will have at max only a few dozen * connections at a time, using a linked list is the easiest way to * handle this. */ struct progress_dispatch_s { struct progress_dispatch_s *next; /* The control object of the connection. If this is NULL no * connection is associated with this item and it is free for reuse * by new connections. */ ctrl_t ctrl; /* The thread id of (npth_self) of the connection. */ npth_t tid; /* The callback set by the connection. This is similar to the * Libgcrypt callback but with the control object passed as the * first argument. */ void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total); }; struct progress_dispatch_s *progress_dispatch_list; /* Local prototypes. */ static char *create_socket_name (char *standard_name, int with_homedir); static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin, char **r_redir_name, assuan_sock_nonce_t *nonce); static void create_directories (void); static void agent_libgcrypt_progress_cb (void *data, const char *what, int printchar, int current, int total); static void agent_init_default_ctrl (ctrl_t ctrl); static void agent_deinit_default_ctrl (ctrl_t ctrl); static void handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_extra, gnupg_fd_t listen_fd_browser, gnupg_fd_t listen_fd_ssh); static void check_own_socket (void); static int check_for_running_agent (int silent); /* Pth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; /* Functions. */ /* Allocate a string describing a library version by calling a GETFNC. This function is expected to be called only once. GETFNC is expected to have a semantic like gcry_check_version (). */ static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; if (maybe_setuid) { gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ maybe_setuid = 0; } s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } /* Return strings describing this program. The case values are described in common/argparse.c:strusage. The values here override the default values given by strusage. */ static const char * my_strusage (int level) { static char *ver_gcry; const char *p; switch (level) { case 11: p = "@GPG_AGENT@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; case 1: case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)"); break; case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n" "Secret key management for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL only the active debug flags are propagated to the subsystems. With DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. Note that we don't fail here, because it is important to keep gpg-agent running even after re-reading the options due to a SIGHUP. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) opt.verbose = 1; if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_MPI_VALUE) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2); if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is the corresponding real name if the socket has been redirected. */ static void remove_socket (char *name, char *redir_name) { if (name && *name) { if (redir_name) name = redir_name; gnupg_remove (name); *name = 0; } } /* Discover which inherited file descriptors correspond to which * services/sockets offered by gpg-agent, using the LISTEN_FDS and * LISTEN_FDNAMES convention. The understood labels are "ssh", * "extra", and "browser". "std" or other labels will be interpreted * as the standard socket. * * This function is designed to log errors when the expected file * descriptors don't make sense, but to do its best to continue to * work even in the face of minor misconfigurations. * * For more information on the LISTEN_FDS convention, see * sd_listen_fds(3) on certain Linux distributions. */ #ifndef HAVE_W32_SYSTEM static void map_supervised_sockets (gnupg_fd_t *r_fd, gnupg_fd_t *r_fd_extra, gnupg_fd_t *r_fd_browser, gnupg_fd_t *r_fd_ssh) { struct { const char *label; int **fdaddr; char **nameaddr; } tbl[] = { { "ssh", &r_fd_ssh, &socket_name_ssh }, { "browser", &r_fd_browser, &socket_name_browser }, { "extra", &r_fd_extra, &socket_name_extra }, { "std", &r_fd, &socket_name } /* (Must be the last item.) */ }; const char *envvar; char **fdnames; int nfdnames; int fd_count; *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1; /* Print a warning if LISTEN_PID does not match outr pid. */ envvar = getenv ("LISTEN_PID"); if (!envvar) log_error ("no LISTEN_PID environment variable found in " "--supervised mode (ignoring)\n"); else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ()) log_error ("environment variable LISTEN_PID (%lu) does not match" " our pid (%lu) in --supervised mode (ignoring)\n", (unsigned long)strtoul (envvar, NULL, 10), (unsigned long)getpid ()); /* Parse LISTEN_FDNAMES into the array FDNAMES. */ envvar = getenv ("LISTEN_FDNAMES"); if (envvar) { fdnames = strtokenize (envvar, ":"); if (!fdnames) { log_error ("strtokenize failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); agent_exit (1); } for (nfdnames=0; fdnames[nfdnames]; nfdnames++) ; } else { fdnames = NULL; nfdnames = 0; } /* Parse LISTEN_FDS into fd_count or provide a replacement. */ envvar = getenv ("LISTEN_FDS"); if (envvar) fd_count = atoi (envvar); else if (fdnames) { log_error ("no LISTEN_FDS environment variable found in --supervised" " mode (relying on LISTEN_FDNAMES instead)\n"); fd_count = nfdnames; } else { log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables " "found in --supervised mode" " (assuming 1 active descriptor)\n"); fd_count = 1; } if (fd_count < 1) { log_error ("--supervised mode expects at least one file descriptor" " (was told %d, carrying on as though it were 1)\n", fd_count); fd_count = 1; } /* Assign the descriptors to the return values. */ if (!fdnames) { struct stat statbuf; if (fd_count != 1) log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1" " in --supervised mode." " (ignoring all sockets but the first one)\n", fd_count); if (fstat (3, &statbuf) == -1 && errno ==EBADF) log_fatal ("file descriptor 3 must be valid in --supervised mode" " if LISTEN_FDNAMES is not set\n"); *r_fd = 3; socket_name = gnupg_get_socket_name (3); } else if (fd_count != nfdnames) { log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match " "LISTEN_FDS (%d) in --supervised mode\n", nfdnames, fd_count); } else { int i, j, fd; char *name; for (i = 0; i < nfdnames; i++) { for (j = 0; j < DIM (tbl); j++) { if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1) { fd = 3 + i; if (**tbl[j].fdaddr == -1) { name = gnupg_get_socket_name (fd); if (name) { **tbl[j].fdaddr = fd; *tbl[j].nameaddr = name; log_info ("using fd %d for %s socket (%s)\n", fd, tbl[j].label, name); } else { log_error ("cannot listen on fd %d for %s socket\n", fd, tbl[j].label); close (fd); } } else { log_error ("cannot listen on more than one %s socket\n", tbl[j].label); close (fd); } break; } } } } xfree (fdnames); } #endif /*!HAVE_W32_SYSTEM*/ /* Cleanup code for this program. This is either called has an atexit handler or directly. */ static void cleanup (void) { static int done; if (done) return; done = 1; deinitialize_module_cache (); if (!is_supervised && !inhibit_socket_removal) { remove_socket (socket_name, redir_socket_name); if (opt.extra_socket > 1) remove_socket (socket_name_extra, redir_socket_name_extra); if (opt.browser_socket > 1) remove_socket (socket_name_browser, redir_socket_name_browser); remove_socket (socket_name_ssh, redir_socket_name_ssh); } } /* Handle options which are allowed to be reset after program start. Return true when the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread) { int i; if (!pargs) { /* reset mode */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.no_grab = 1; opt.debug_pinentry = 0; opt.pinentry_program = NULL; opt.pinentry_touch_file = NULL; xfree (opt.pinentry_invisible_char); opt.pinentry_invisible_char = NULL; opt.pinentry_timeout = 0; opt.scdaemon_program = NULL; opt.def_cache_ttl = DEFAULT_CACHE_TTL; opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH; opt.max_cache_ttl = MAX_CACHE_TTL; opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH; opt.enforce_passphrase_constraints = 0; opt.min_passphrase_len = MIN_PASSPHRASE_LEN; opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA; opt.check_passphrase_pattern = NULL; opt.max_passphrase_days = MAX_PASSPHRASE_DAYS; opt.enable_passphrase_history = 0; opt.enable_extended_key_format = 0; opt.ignore_cache_for_signing = 0; opt.allow_mark_trusted = 1; opt.allow_external_cache = 1; opt.allow_loopback_pinentry = 1; opt.allow_emacs_pinentry = 0; opt.disable_scdaemon = 0; disable_check_own_socket = 0; /* Note: When changing the next line, change also gpgconf_list. */ opt.ssh_fingerprint_digest = GCRY_MD_MD5; opt.s2k_count = 0; set_s2k_calibration_time (0); /* Set to default. */ return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oDebugPinentry: opt.debug_pinentry = 1; break; case oLogFile: if (!reread) return 0; /* not handeld */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oNoGrab: opt.no_grab |= 1; break; case oGrab: opt.no_grab |= 2; break; case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break; case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break; case oPinentryInvisibleChar: xfree (opt.pinentry_invisible_char); opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break; break; case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break; case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break; case oDisableScdaemon: opt.disable_scdaemon = 1; break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break; case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break; case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break; case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break; case oEnforcePassphraseConstraints: opt.enforce_passphrase_constraints=1; break; case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break; case oMinPassphraseNonalpha: opt.min_passphrase_nonalpha = pargs->r.ret_ulong; break; case oCheckPassphrasePattern: opt.check_passphrase_pattern = pargs->r.ret_str; break; case oMaxPassphraseDays: opt.max_passphrase_days = pargs->r.ret_ulong; break; case oEnablePassphraseHistory: opt.enable_passphrase_history = 1; break; case oEnableExtendedKeyFormat: opt.enable_extended_key_format = 1; break; case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break; case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break; case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break; case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break; case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break; case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break; case oNoAllowExternalCache: opt.allow_external_cache = 0; break; case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1; break; case oSSHFingerprintDigest: i = gcry_md_map_name (pargs->r.ret_str); if (!i) log_error (_("selected digest algorithm is invalid\n")); else opt.ssh_fingerprint_digest = i; break; case oS2KCount: opt.s2k_count = pargs->r.ret_ulong; break; case oS2KCalibration: set_s2k_calibration_time (pargs->r.ret_ulong); break; default: return 0; /* not handled */ } return 1; /* handled */ } /* Fixup some options after all have been processed. */ static void finalize_rereadable_options (void) { /* Hack to allow --grab to override --no-grab. */ if ((opt.no_grab & 2)) opt.no_grab = 0; } static void thread_init_once (void) { static int npth_initialized = 0; if (!npth_initialized) { npth_initialized++; npth_init (); } gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now that we have set the syscall clamp we need to tell Libgcrypt * that it should get them from libgpg-error. Note that Libgcrypt * has already been initialized but at that point nPth was not * initialized and thus Libgcrypt could not set its system call * clamp. */ #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */ gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0); #endif } static void initialize_modules (void) { thread_init_once (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); initialize_module_cache (); initialize_module_call_pinentry (); initialize_module_call_scd (); initialize_module_trustlist (); } /* The main entry point. */ int main (int argc, char **argv ) { ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; FILE *configfp = NULL; char *configname = NULL; const char *shell; unsigned configlineno; int parse_debug = 0; int default_config =1; int pipe_server = 0; int is_daemon = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; int debug_wait = 0; int gpgconf_list = 0; gpg_error_t err; struct assuan_malloc_hooks malloc_hooks; early_system_init (); /* Before we do anything else we save the list of currently open file descriptors and the signal mask. This info is required to do the exec call properly. We don't need it on Windows. */ #ifndef HAVE_W32_SYSTEM startup_fd_list = get_all_open_fds (); #endif /*!HAVE_W32_SYSTEM*/ #ifdef HAVE_SIGPROCMASK if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask)) startup_signal_mask_valid = 1; #endif /*HAVE_SIGPROCMASK*/ /* Set program name etc. */ set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); /* Please note that we may running SUID(ROOT), so be very CAREFUL when adding any stuff between here and the call to INIT_SECMEM() somewhere after the option parsing */ log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); assuan_sock_set_system_hooks (ASSUAN_SYSTEM_NPTH); setup_libassuan_logging (&opt.debug, NULL); setup_libgcrypt_logging (); gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL); disable_core_dumps (); /* Set default options. */ parse_rereadable_options (NULL, 0); /* Reset them to default values. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Record some of the original environment strings. */ { const char *s; int idx; static const char *names[] = { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL }; err = 0; opt.startup_env = session_env_new (); if (!opt.startup_env) err = gpg_error_from_syserror (); for (idx=0; !err && names[idx]; idx++) { s = getenv (names[idx]); if (s) err = session_env_setenv (opt.startup_env, names[idx], s); } if (!err) { s = gnupg_ttyname (0); if (s) err = session_env_setenv (opt.startup_env, "GPG_TTY", s); } if (err) log_fatal ("error recording startup environment: %s\n", gpg_strerror (err)); /* Fixme: Better use the locale function here. */ opt.startup_lc_ctype = getenv ("LC_CTYPE"); if (opt.startup_lc_ctype) opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype); opt.startup_lc_messages = getenv ("LC_MESSAGES"); if (opt.startup_lc_messages) opt.startup_lc_messages = xstrdup (opt.startup_lc_messages); } /* Check whether we have a config file on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */ while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; else if (pargs.r_opt == oOptions) { /* yes there is one, so we do not try the default one, but read the option file when it is encountered at the commandline */ default_config = 0; } else if (pargs.r_opt == oNoOptions) default_config = 0; /* --no-options */ else if (pargs.r_opt == oHomedir) gnupg_set_homedir (pargs.r.ret_str); else if (pargs.r_opt == oDebugQuickRandom) { gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); } } /* Initialize the secure memory. */ gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0); maybe_setuid = 0; /* Now we are now working under our real uid */ if (default_config) configname = make_filename (gnupg_homedir (), GPG_AGENT_NAME EXTSEP_S "conf", NULL); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if( parse_debug ) log_info (_("Note: no default option file '%s'\n"), configname ); /* Save the default conf file name so that reread_configuration is able to test whether the config file has been created in the meantime. */ xfree (config_filename); config_filename = configname; configname = NULL; } else { log_error (_("option file '%s': %s\n"), configname, strerror(errno) ); exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname ) log_info (_("reading options from '%s'\n"), configname ); default_config = 0; } while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) ) { if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aGPGConfList: gpgconf_list = 1; break; case aGPGConfTest: gpgconf_list = 2; break; case aUseStandardSocketP: gpgconf_list = 3; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oOptions: /* config files may not be nested (silently ignore them) */ if (!configfp) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoGreeting: /* Dummy option. */ break; case oNoVerbose: opt.verbose = 0; break; case oNoOptions: break; /* no-options */ case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oServer: pipe_server = 1; break; case oDaemon: is_daemon = 1; break; case oSupervised: is_supervised = 1; break; case oDisplay: default_display = xstrdup (pargs.r.ret_str); break; case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break; case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break; case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break; case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str); break; case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str); break; case oUseStandardSocket: case oNoUseStandardSocket: obsolete_option (configname, configlineno, "use-standard-socket"); break; case oFakedSystemTime: { time_t faked_time = isotime2epoch (pargs.r.ret_str); if (faked_time == (time_t)(-1)) faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10); gnupg_set_time (faked_time, 0); } break; case oKeepTTY: opt.keep_tty = 1; break; case oKeepDISPLAY: opt.keep_display = 1; break; case oSSHSupport: ssh_support = 1; break; case oPuttySupport: # ifdef HAVE_W32_SYSTEM putty_support = 1; # endif break; case oExtraSocket: opt.extra_socket = 1; /* (1 = points into argv) */ socket_name_extra = pargs.r.ret_str; break; case oBrowserSocket: opt.browser_socket = 1; /* (1 = points into argv) */ socket_name_browser = pargs.r.ret_str; break; case oAutoExpandSecmem: /* Try to enable this option. It will officially only be * supported by Libgcrypt 1.9 but 1.8.2 already supports it * on the quiet and thus we use the numeric value value. */ gcry_control (78 /*GCRYCTL_AUTO_EXPAND_SECMEM*/, (unsigned int)pargs.r.ret_ulong, 0); break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; case oDebugQuickRandom: /* Only used by the first stage command line parser. */ break; case oWriteEnvFile: obsolete_option (configname, configlineno, "write-env-file"); break; default : pargs.err = configfp? 1:2; break; } } if (configfp) { fclose( configfp ); configfp = NULL; /* Keep a copy of the name so that it can be read on SIGHUP. */ if (config_filename != configname) { xfree (config_filename); config_filename = configname; } configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (log_get_errorcount(0)) exit(2); finalize_rereadable_options (); /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } #ifdef ENABLE_NLS /* gpg-agent usually does not output any messages because it runs in the background. For log files it is acceptable to have messages always encoded in utf-8. We switch here to utf-8, so that commands like --help still give native messages. It is far easier to switch only once instead of for every message and it actually helps when more then one thread is active (avoids an extra copy step). */ bind_textdomain_codeset (PACKAGE_GT, "UTF-8"); #endif if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised) { /* We have been called without any command and thus we merely check whether an agent is already running. We do this right here so that we don't clobber a logfile with this check but print the status directly to stderr. */ opt.debug = 0; set_debug (); check_for_running_agent (0); agent_exit (0); } if (is_supervised) ; else if (!opt.extra_socket) opt.extra_socket = 1; else if (socket_name_extra && (!strcmp (socket_name_extra, "none") || !strcmp (socket_name_extra, "/dev/null"))) { /* User requested not to create this socket. */ opt.extra_socket = 0; socket_name_extra = NULL; } if (is_supervised) ; else if (!opt.browser_socket) opt.browser_socket = 1; else if (socket_name_browser && (!strcmp (socket_name_browser, "none") || !strcmp (socket_name_browser, "/dev/null"))) { /* User requested not to create this socket. */ opt.browser_socket = 0; socket_name_browser = NULL; } set_debug (); if (atexit (cleanup)) { log_error ("atexit failed\n"); cleanup (); exit (1); } /* Try to create missing directories. */ create_directories (); if (debug_wait && pipe_server) { thread_init_once (); log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } if (gpgconf_list == 3) { /* We now use the standard socket always - return true for backward compatibility. */ agent_exit (0); } else if (gpgconf_list == 2) agent_exit (0); else if (gpgconf_list) { char *filename; char *filename_esc; /* List options and default values in the GPG Conf format. */ filename = make_filename (gnupg_homedir (), GPG_AGENT_NAME EXTSEP_S "conf", NULL); filename_esc = percent_escape (filename, NULL); es_printf ("%s-%s.conf:%lu:\"%s\n", GPGCONF_NAME, GPG_AGENT_NAME, GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename); xfree (filename_esc); es_printf ("verbose:%lu:\n" "quiet:%lu:\n" "debug-level:%lu:\"none:\n" "log-file:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME ); es_printf ("default-cache-ttl:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL ); es_printf ("default-cache-ttl-ssh:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH ); es_printf ("max-cache-ttl:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL ); es_printf ("max-cache-ttl-ssh:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH ); es_printf ("enforce-passphrase-constraints:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("min-passphrase-len:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN ); es_printf ("min-passphrase-nonalpha:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_NONALPHA); es_printf ("check-passphrase-pattern:%lu:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME); es_printf ("max-passphrase-days:%lu:%d:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_PASSPHRASE_DAYS); es_printf ("enable-passphrase-history:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-grab:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("ignore-cache-for-signing:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-allow-external-cache:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("no-allow-mark-trusted:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("disable-scdaemon:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE); es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, "md5"); #ifdef HAVE_W32_SYSTEM es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE); #endif es_printf ("no-allow-loopback-pinentry:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("allow-emacs-pinentry:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("pinentry-timeout:%lu:0:\n", GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME); es_printf ("enable-extended-key-format:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); es_printf ("grab:%lu:\n", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME); agent_exit (0); } /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } /* Make sure that we have a default ttyname. */ if (!default_ttyname && gnupg_ttyname (1)) default_ttyname = xstrdup (gnupg_ttyname (1)); if (!default_ttytype && getenv ("TERM")) default_ttytype = xstrdup (getenv ("TERM")); if (pipe_server) { /* This is the simple pipe based server */ ctrl_t ctrl; initialize_modules (); ctrl = xtrycalloc (1, sizeof *ctrl); if (!ctrl) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); agent_exit (1); } ctrl->session_env = session_env_new (); if (!ctrl->session_env) { log_error ("error allocating session environment block: %s\n", strerror (errno) ); xfree (ctrl); agent_exit (1); } agent_init_default_ctrl (ctrl); start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD); agent_deinit_default_ctrl (ctrl); xfree (ctrl); } else if (is_supervised) { #ifndef HAVE_W32_SYSTEM gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh; initialize_modules (); /* when supervised and sending logs to stderr, the process supervisor should handle log entry metadata (pid, name, timestamp) */ if (!logfile) log_set_prefix (NULL, 0); log_info ("%s %s starting in supervised mode.\n", strusage(11), strusage(13) ); /* See below in "regular server mode" on why we remove certain * envvars. */ if (!opt.keep_display) gnupg_unsetenv ("DISPLAY"); gnupg_unsetenv ("INSIDE_EMACS"); /* Virtually create the sockets. Note that we use -1 here * because the whole thing works only on Unix. */ map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh); if (fd == -1) log_fatal ("no standard socket provided\n"); #ifdef HAVE_SIGPROCMASK if (startup_signal_mask_valid) { if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL)) log_error ("error restoring signal mask: %s\n", strerror (errno)); } else log_info ("no saved signal mask\n"); #endif /*HAVE_SIGPROCMASK*/ log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n", fd, fd_extra, fd_browser, fd_ssh); handle_connections (fd, fd_extra, fd_browser, fd_ssh); #endif /*!HAVE_W32_SYSTEM*/ } else if (!is_daemon) ; /* NOTREACHED */ else { /* Regular server mode */ gnupg_fd_t fd; gnupg_fd_t fd_extra = GNUPG_INVALID_FD; gnupg_fd_t fd_browser = GNUPG_INVALID_FD; gnupg_fd_t fd_ssh = GNUPG_INVALID_FD; #ifndef HAVE_W32_SYSTEM pid_t pid; #endif /* Remove the DISPLAY variable so that a pinentry does not default to a specific display. There is still a default display when gpg-agent was started using --display or a client requested this using an OPTION command. Note, that we don't do this when running in reverse daemon mode (i.e. when exec the program given as arguments). */ #ifndef HAVE_W32_SYSTEM if (!opt.keep_display && !argc) gnupg_unsetenv ("DISPLAY"); #endif /* Remove the INSIDE_EMACS variable so that a pinentry does not always try to interact with Emacs. The variable is set when a client requested this using an OPTION command. */ gnupg_unsetenv ("INSIDE_EMACS"); /* Create the sockets. */ socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1); fd = create_server_socket (socket_name, 1, 0, &redir_socket_name, &socket_nonce); if (opt.extra_socket) { if (socket_name_extra) socket_name_extra = create_socket_name (socket_name_extra, 0); else socket_name_extra = create_socket_name /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1); opt.extra_socket = 2; /* Indicate that it has been malloced. */ fd_extra = create_server_socket (socket_name_extra, 0, 0, &redir_socket_name_extra, &socket_nonce_extra); } if (opt.browser_socket) { if (socket_name_browser) socket_name_browser = create_socket_name (socket_name_browser, 0); else socket_name_browser= create_socket_name /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1); opt.browser_socket = 2; /* Indicate that it has been malloced. */ fd_browser = create_server_socket (socket_name_browser, 0, 0, &redir_socket_name_browser, &socket_nonce_browser); } socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1); fd_ssh = create_server_socket (socket_name_ssh, 0, 1, &redir_socket_name_ssh, &socket_nonce_ssh); /* If we are going to exec a program in the parent, we record the PID, so that the child may check whether the program is still alive. */ if (argc) parent_pid = getpid (); fflush (NULL); #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; initialize_modules (); #else /*!HAVE_W32_SYSTEM*/ pid = fork (); if (pid == (pid_t)-1) { log_fatal ("fork failed: %s\n", strerror (errno) ); exit (1); } else if (pid) { /* We are the parent */ char *infostr_ssh_sock, *infostr_ssh_valid; /* Close the socket FD. */ close (fd); /* The signal mask might not be correct right now and thus we restore it. That is not strictly necessary but some programs falsely assume a cleared signal mask. */ #ifdef HAVE_SIGPROCMASK if (startup_signal_mask_valid) { if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL)) log_error ("error restoring signal mask: %s\n", strerror (errno)); } else log_info ("no saved signal mask\n"); #endif /*HAVE_SIGPROCMASK*/ /* Create the SSH info string if enabled. */ if (ssh_support) { if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s", socket_name_ssh) < 0) { log_error ("out of core\n"); kill (pid, SIGTERM); exit (1); } if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu", (unsigned long)getpid()) < 0) { log_error ("out of core\n"); kill (pid, SIGTERM); exit (1); } } *socket_name = 0; /* Don't let cleanup() remove the socket - the child should do this from now on */ if (opt.extra_socket) *socket_name_extra = 0; if (opt.browser_socket) *socket_name_browser = 0; *socket_name_ssh = 0; if (argc) { /* Run the program given on the commandline. */ if (ssh_support && (putenv (infostr_ssh_sock) || putenv (infostr_ssh_valid))) { log_error ("failed to set environment: %s\n", strerror (errno) ); kill (pid, SIGTERM ); exit (1); } /* Close all the file descriptors except the standard ones and those open at startup. We explicitly don't close 0,1,2 in case something went wrong collecting them at startup. */ close_all_fds (3, startup_fd_list); /* Run the command. */ execvp (argv[0], argv); log_error ("failed to run the command: %s\n", strerror (errno)); kill (pid, SIGTERM); exit (1); } else { /* Print the environment string, so that the caller can use shell's eval to set it */ if (csh_style) { if (ssh_support) { *strchr (infostr_ssh_sock, '=') = ' '; es_printf ("setenv %s;\n", infostr_ssh_sock); } } else { if (ssh_support) { es_printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock); } } if (ssh_support) { xfree (infostr_ssh_sock); xfree (infostr_ssh_valid); } exit (0); } /*NOTREACHED*/ } /* End parent */ /* This is the child */ initialize_modules (); /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( ! close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); cleanup (); exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; /* Unless we are running with a program given on the command * line we can assume that the inotify things works and thus * we can avoid tye regular stat calls. */ if (!argc) reliable_homedir_inotify = 1; } { struct sigaction sa; sa.sa_handler = SIG_IGN; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sigaction (SIGPIPE, &sa, NULL); } #endif /*!HAVE_W32_SYSTEM*/ if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); exit (1); } log_info ("%s %s started\n", strusage(11), strusage(13) ); handle_connections (fd, fd_extra, fd_browser, fd_ssh); assuan_sock_close (fd); } return 0; } /* Exit entry point. This function should be called instead of a plain exit. */ void agent_exit (int rc) { /*FIXME: update_random_seed_file();*/ /* We run our cleanup handler because that may close cipher contexts stored in secure memory and thus this needs to be done before we explicitly terminate secure memory. */ cleanup (); #if 1 /* at this time a bit annoying */ if (opt.debug & DBG_MEMSTAT_VALUE) { gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); } if (opt.debug) gcry_control (GCRYCTL_DUMP_SECMEM_STATS ); #endif gcry_control (GCRYCTL_TERM_SECMEM ); rc = rc? rc : log_get_errorcount(0)? 2 : 0; exit (rc); } /* This is our callback function for gcrypt progress messages. It is set once at startup and dispatches progress messages to the corresponding threads of the agent. */ static void agent_libgcrypt_progress_cb (void *data, const char *what, int printchar, int current, int total) { struct progress_dispatch_s *dispatch; npth_t mytid = npth_self (); (void)data; for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) if (dispatch->ctrl && dispatch->tid == mytid) break; if (dispatch && dispatch->cb) dispatch->cb (dispatch->ctrl, what, printchar, current, total); /* Libgcrypt < 1.8 does not know about nPth and thus when it reads * from /dev/random this will block the process. To mitigate this * problem we yield the thread when Libgcrypt tells us that it needs * more entropy. This way other threads have chance to run. */ #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */ if (what && !strcmp (what, "need_entropy")) { #if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */ /* In older gpg-error versions gpgrt_yield is buggy for use with * nPth and thus we need to resort to a sleep call. */ npth_usleep (1000); /* 1ms */ #else gpgrt_yield (); #endif } #endif } /* If a progress dispatcher callback has been associated with the * current connection unregister it. */ static void unregister_progress_cb (void) { struct progress_dispatch_s *dispatch; npth_t mytid = npth_self (); for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) if (dispatch->ctrl && dispatch->tid == mytid) break; if (dispatch) { dispatch->ctrl = NULL; dispatch->cb = NULL; } } /* Setup a progress callback CB for the current connection. Using a * CB of NULL disables the callback. */ void agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what, int printchar, int current, int total), ctrl_t ctrl) { struct progress_dispatch_s *dispatch, *firstfree; npth_t mytid = npth_self (); firstfree = NULL; for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next) { if (dispatch->ctrl && dispatch->tid == mytid) break; if (!dispatch->ctrl && !firstfree) firstfree = dispatch; } if (!dispatch) /* None allocated: Reuse or allocate a new one. */ { if (firstfree) { dispatch = firstfree; } else if ((dispatch = xtrycalloc (1, sizeof *dispatch))) { dispatch->next = progress_dispatch_list; progress_dispatch_list = dispatch; } else { log_error ("error allocating new progress dispatcher slot: %s\n", gpg_strerror (gpg_error_from_syserror ())); return; } dispatch->ctrl = ctrl; dispatch->tid = mytid; } dispatch->cb = cb; } /* Each thread has its own local variables conveyed by a control structure usually identified by an argument named CTRL. This function is called immediately after allocating the control structure. Its purpose is to setup the default values for that structure. Note that some values may have already been set. */ static void agent_init_default_ctrl (ctrl_t ctrl) { assert (ctrl->session_env); /* Note we ignore malloc errors because we can't do much about it and the request will fail anyway shortly after this initialization. */ session_env_setenv (ctrl->session_env, "DISPLAY", default_display); session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname); session_env_setenv (ctrl->session_env, "TERM", default_ttytype); session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority); session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL); if (ctrl->lc_ctype) xfree (ctrl->lc_ctype); ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL; if (ctrl->lc_messages) xfree (ctrl->lc_messages); ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages) /**/ : NULL; ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET; } /* Release all resources allocated by default in the control structure. This is the counterpart to agent_init_default_ctrl. */ static void agent_deinit_default_ctrl (ctrl_t ctrl) { unregister_progress_cb (); session_env_release (ctrl->session_env); if (ctrl->lc_ctype) xfree (ctrl->lc_ctype); if (ctrl->lc_messages) xfree (ctrl->lc_messages); } /* Because the ssh protocol does not send us information about the current TTY setting, we use this function to use those from startup or those explicitly set. This is also used for the restricted mode where we ignore requests to change the environment. */ gpg_error_t agent_copy_startup_env (ctrl_t ctrl) { gpg_error_t err = 0; int iterator = 0; const char *name, *value; while (!err && (name = session_env_list_stdenvnames (&iterator, NULL))) { if ((value = session_env_getenv (opt.startup_env, name))) err = session_env_setenv (ctrl->session_env, name, value); } if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype) if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype))) err = gpg_error_from_syserror (); if (!err && !ctrl->lc_messages && opt.startup_lc_messages) if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages))) err = gpg_error_from_syserror (); if (err) log_error ("error setting default session environment: %s\n", gpg_strerror (err)); return err; } /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the PTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process' original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { ARGPARSE_ARGS pargs; FILE *fp; unsigned int configlineno = 0; int dummy; if (!config_filename) return; /* No config file. */ fp = fopen (config_filename, "r"); if (!fp) { log_info (_("option file '%s': %s\n"), config_filename, strerror(errno) ); return; } parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = 1; /* do not remove the args */ while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) ) { if (pargs.r_opt < -1) pargs.err = 1; /* Print a warning. */ else /* Try to parse this option - ignore unchangeable ones. */ parse_rereadable_options (&pargs, 1); } fclose (fp); finalize_rereadable_options (); set_debug (); } /* Return the file name of the socket we are using for native requests. */ const char * get_agent_socket_name (void) { const char *s = socket_name; return (s && *s)? s : NULL; } /* Return the file name of the socket we are using for SSH requests. */ const char * get_agent_ssh_socket_name (void) { const char *s = socket_name_ssh; return (s && *s)? s : NULL; } /* Return the number of active connections. */ int get_agent_active_connection_count (void) { return active_connections; } /* Under W32, this function returns the handle of the scdaemon notification event. Calling it the first time creates that event. */ #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) void * get_agent_scd_notify_event (void) { static HANDLE the_event = INVALID_HANDLE_VALUE; if (the_event == INVALID_HANDLE_VALUE) { HANDLE h, h2; SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE}; /* We need to use a manual reset event object due to the way our w32-pth wait function works: If we would use an automatic reset event we are not able to figure out which handle has been signaled because at the time we single out the signaled handles using WFSO the event has already been reset due to the WFMO. */ h = CreateEvent (&sa, TRUE, FALSE, NULL); if (!h) log_error ("can't create scd notify event: %s\n", w32_strerror (-1) ); else if (!DuplicateHandle (GetCurrentProcess(), h, GetCurrentProcess(), &h2, EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0)) { - log_error ("setting syncronize for scd notify event failed: %s\n", + log_error ("setting synchronize for scd notify event failed: %s\n", w32_strerror (-1) ); CloseHandle (h); } else { CloseHandle (h); the_event = h2; } } return the_event; } #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/ /* Create a name for the socket in the home directory as using STANDARD_NAME. We also check for valid characters as well as against a maximum allowed length for a unix domain socket is done. The function terminates the process in case of an error. Returns: Pointer to an allocated string with the absolute name of the socket used. */ static char * create_socket_name (char *standard_name, int with_homedir) { char *name; if (with_homedir) name = make_filename (gnupg_socketdir (), standard_name, NULL); else name = make_filename (standard_name, NULL); if (strchr (name, PATHSEP_C)) { log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S); agent_exit (2); } return name; } /* Create a Unix domain socket with NAME. Returns the file descriptor or terminates the process in case of an error. Note that this function needs to be used for the regular socket first (indicated by PRIMARY) and only then for the extra and the ssh sockets. If the socket has been redirected the name of the real socket is stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a Cygwin compatible socket is created (Windows only). */ static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin, char **r_redir_name, assuan_sock_nonce_t *nonce) { struct sockaddr *addr; struct sockaddr_un *unaddr; socklen_t len; gnupg_fd_t fd; int rc; xfree (*r_redir_name); *r_redir_name = NULL; fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); *name = 0; /* Inhibit removal of the socket by cleanup(). */ agent_exit (2); } if (cygwin) assuan_sock_set_flag (fd, "cygwin", 1); unaddr = xmalloc (sizeof *unaddr); addr = (struct sockaddr*)unaddr; { int redirected; if (assuan_sock_set_sockaddr_un (name, addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), name); else log_error ("error preparing socket '%s': %s\n", name, gpg_strerror (gpg_error_from_syserror ())); *name = 0; /* Inhibit removal of the socket by cleanup(). */ xfree (unaddr); agent_exit (2); } if (redirected) { *r_redir_name = xstrdup (unaddr->sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name); } } len = SUN_LEN (unaddr); rc = assuan_sock_bind (fd, addr, len); /* Our error code mapping on W32CE returns EEXIST thus we also test for this. */ if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Check whether a gpg-agent is already running. We do this test only if this is the primary socket. For secondary sockets we assume that a test for gpg-agent has already been done and reuse the requested socket. Testing the ssh-socket is not possible because at this point, though we know the new Assuan socket, the Assuan server and thus the ssh-agent server is not yet operational; this would lead to a hang. */ if (primary && !check_for_running_agent (1)) { log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX); log_set_file (NULL); log_error (_("a gpg-agent is already running - " "not starting a new one\n")); *name = 0; /* Inhibit removal of the socket by cleanup(). */ assuan_sock_close (fd); xfree (unaddr); agent_exit (2); } gnupg_remove (unaddr->sun_path); rc = assuan_sock_bind (fd, addr, len); } if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { /* We use gpg_strerror here because it allows us to get strings for some W32 socket error codes. */ log_error (_("error binding socket to '%s': %s\n"), unaddr->sun_path, gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); *name = 0; /* Inhibit removal of the socket by cleanup(). */ xfree (unaddr); agent_exit (2); } if (gnupg_chmod (unaddr->sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), unaddr->sun_path, strerror (errno)); if (listen (FD2INT(fd), listen_backlog ) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); *name = 0; /* Inhibit removal of the socket by cleanup(). */ assuan_sock_close (fd); xfree (unaddr); agent_exit (2); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), unaddr->sun_path); xfree (unaddr); return fd; } /* Check that the directory for storing the private keys exists and create it if not. This function won't fail as it is only a convenience function and not strictly necessary. */ static void create_private_keys_directory (const char *home) { char *fname; struct stat statbuf; fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL); if (stat (fname, &statbuf) && errno == ENOENT) { if (gnupg_mkdir (fname, "-rwx")) log_error (_("can't create directory '%s': %s\n"), fname, strerror (errno) ); else if (!opt.quiet) log_info (_("directory '%s' created\n"), fname); } if (gnupg_chmod (fname, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), fname, strerror (errno)); xfree (fname); } /* Create the directory only if the supplied directory name is the same as the default one. This way we avoid to create arbitrary directories when a non-default home directory is used. To cope with HOME, we compare only the suffix if we see that the default homedir does start with a tilde. We don't stop here in case of problems because other functions will throw an error anyway.*/ static void create_directories (void) { struct stat statbuf; const char *defhome = standard_homedir (); char *home; home = make_filename (gnupg_homedir (), NULL); if ( stat (home, &statbuf) ) { if (errno == ENOENT) { if ( #ifdef HAVE_W32_SYSTEM ( !compare_filenames (home, defhome) ) #else (*defhome == '~' && (strlen (home) >= strlen (defhome+1) && !strcmp (home + strlen(home) - strlen (defhome+1), defhome+1))) || (*defhome != '~' && !strcmp (home, defhome) ) #endif ) { if (gnupg_mkdir (home, "-rwx")) log_error (_("can't create directory '%s': %s\n"), home, strerror (errno) ); else { if (!opt.quiet) log_info (_("directory '%s' created\n"), home); create_private_keys_directory (home); } } } else log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno)); } else if ( !S_ISDIR(statbuf.st_mode)) { log_error (_("can't use '%s' as home directory\n"), home); } else /* exists and is a directory. */ { create_private_keys_directory (home); } xfree (home); } /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { static time_t last_minute; struct stat statbuf; if (!last_minute) last_minute = time (NULL); /* Check whether the scdaemon has died and cleanup in this case. */ agent_scd_check_aliveness (); /* If we are running as a child of another process, check whether the parent is still alive and shutdown if not. */ #ifndef HAVE_W32_SYSTEM if (parent_pid != (pid_t)(-1)) { if (kill (parent_pid, 0)) { shutdown_pending = 2; log_info ("parent process died - shutting down\n"); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); agent_exit (0); } } #endif /*HAVE_W32_SYSTEM*/ /* Code to be run from time to time. */ #if CHECK_OWN_SOCKET_INTERVAL > 0 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL)) { check_own_socket (); last_minute = time (NULL); } #endif /* Need to check for expired cache entries. */ agent_cache_housekeeping (); /* Check whether the homedir is still available. */ if (!shutdown_pending && (!have_homedir_inotify || !reliable_homedir_inotify) && stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* A global function which allows us to call the reload stuff from other places too. This is only used when build for W32. */ void agent_sighup_action (void) { log_info ("SIGHUP received - " "re-reading configuration and flushing cache\n"); agent_flush_cache (); reread_configuration (); agent_reload_trustlist (); /* We flush the module name cache so that after installing a "pinentry" binary that one can be used in case the "pinentry-basic" fallback was in use. */ gnupg_module_name_flush_some (); if (opt.disable_scdaemon) agent_card_killscd (); } /* A helper function to handle SIGUSR2. */ static void agent_sigusr2_action (void) { if (opt.verbose) log_info ("SIGUSR2 received - updating card event counter\n"); /* Nothing to check right now. We only increment a counter. */ bump_card_eventcounter (); } #ifndef HAVE_W32_SYSTEM /* The signal handler for this program. It is expected to be run in its own thread and not in the context of a signal handler. */ static void handle_signal (int signo) { switch (signo) { #ifndef HAVE_W32_SYSTEM case SIGHUP: agent_sighup_action (); break; case SIGUSR1: log_info ("SIGUSR1 received - printing internal information:\n"); /* Fixme: We need to see how to integrate pth dumping into our logging system. */ /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */ agent_query_dump_state (); agent_scd_dump_state (); break; case SIGUSR2: agent_sigusr2_action (); break; case SIGTERM: if (!shutdown_pending) log_info ("SIGTERM received - shutting down ...\n"); else log_info ("SIGTERM received - still %i open connections\n", active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info ("shutdown forced\n"); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); agent_exit (0); } break; case SIGINT: log_info ("SIGINT received - immediate shutdown\n"); log_info( "%s %s stopped\n", strusage(11), strusage(13)); cleanup (); agent_exit (0); break; #endif default: log_info ("signal %d received - no action defined\n", signo); } } #endif /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT(ctrl->thread_startup.fd), strerror (errno)); assuan_sock_close (ctrl->thread_startup.fd); xfree (ctrl); return -1; } else return 0; } #ifdef HAVE_W32_SYSTEM /* The window message processing function for Putty. Warning: This code runs as a native Windows thread. Use of our own functions needs to be bracket with pth_leave/pth_enter. */ static LRESULT CALLBACK putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { int ret = 0; int w32rc; COPYDATASTRUCT *cds; const char *mapfile; HANDLE maphd; PSID mysid = NULL; PSID mapsid = NULL; void *data = NULL; PSECURITY_DESCRIPTOR psd = NULL; ctrl_t ctrl = NULL; if (msg != WM_COPYDATA) { return DefWindowProc (hwnd, msg, wparam, lparam); } cds = (COPYDATASTRUCT*)lparam; if (cds->dwData != PUTTY_IPC_MAGIC) return 0; /* Ignore data with the wrong magic. */ mapfile = cds->lpData; if (!cds->cbData || mapfile[cds->cbData - 1]) return 0; /* Ignore empty and non-properly terminated strings. */ if (DBG_IPC) { npth_protect (); log_debug ("ssh map file '%s'", mapfile); npth_unprotect (); } maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile); if (DBG_IPC) { npth_protect (); log_debug ("ssh map handle %p\n", maphd); npth_unprotect (); } if (!maphd || maphd == INVALID_HANDLE_VALUE) return 0; npth_protect (); mysid = w32_get_user_sid (); if (!mysid) { log_error ("error getting my sid\n"); goto leave; } w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, &mapsid, NULL, NULL, NULL, &psd); if (w32rc) { log_error ("error getting sid of ssh map file: rc=%d", w32rc); goto leave; } if (DBG_IPC) { char *sidstr; if (!ConvertSidToStringSid (mysid, &sidstr)) sidstr = NULL; log_debug (" my sid: '%s'", sidstr? sidstr: "[error]"); LocalFree (sidstr); if (!ConvertSidToStringSid (mapsid, &sidstr)) sidstr = NULL; log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]"); LocalFree (sidstr); } if (!EqualSid (mysid, mapsid)) { log_error ("ssh map file has a non-matching sid\n"); goto leave; } data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (DBG_IPC) log_debug ("ssh IPC buffer at %p\n", data); if (!data) goto leave; /* log_printhex ("request:", data, 20); */ ctrl = xtrycalloc (1, sizeof *ctrl); if (!ctrl) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); goto leave; } ctrl->session_env = session_env_new (); if (!ctrl->session_env) { log_error ("error allocating session environment block: %s\n", strerror (errno) ); goto leave; } agent_init_default_ctrl (ctrl); if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN)) ret = 1; /* Valid ssh message has been constructed. */ agent_deinit_default_ctrl (ctrl); /* log_printhex (" reply:", data, 20); */ leave: xfree (ctrl); if (data) UnmapViewOfFile (data); xfree (mapsid); if (psd) LocalFree (psd); xfree (mysid); CloseHandle (maphd); npth_unprotect (); return ret; } #endif /*HAVE_W32_SYSTEM*/ #ifdef HAVE_W32_SYSTEM /* The thread handling Putty's IPC requests. */ static void * putty_message_thread (void *arg) { WNDCLASS wndwclass = {0, putty_message_proc, 0, 0, NULL, NULL, NULL, NULL, NULL, "Pageant"}; HWND hwnd; MSG msg; (void)arg; if (opt.verbose) log_info ("putty message loop thread started\n"); /* The message loop runs as thread independent from our nPth system. This also means that we need to make sure that we switch back to our system before calling any no-windows function. */ npth_unprotect (); /* First create a window to make sure that a message queue exists for this thread. */ if (!RegisterClass (&wndwclass)) { npth_protect (); log_error ("error registering Pageant window class"); return NULL; } hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0, 0, 0, 0, 0, HWND_MESSAGE, /* hWndParent */ NULL, /* hWndMenu */ NULL, /* hInstance */ NULL); /* lpParm */ if (!hwnd) { npth_protect (); log_error ("error creating Pageant window"); return NULL; } while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* Back to nPth. */ npth_protect (); if (opt.verbose) log_info ("putty message loop thread stopped\n"); return NULL; } #endif /*HAVE_W32_SYSTEM*/ static void * do_start_connection_thread (ctrl_t ctrl) { active_connections++; agent_init_default_ctrl (ctrl); if (opt.verbose && !DBG_IPC) log_info (_("handler 0x%lx for fd %d started\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd); if (opt.verbose && !DBG_IPC) log_info (_("handler 0x%lx for fd %d terminated\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); agent_deinit_default_ctrl (ctrl); xfree (ctrl); active_connections--; return NULL; } /* This is the standard connection thread's main function. */ static void * start_connection_thread_std (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } return do_start_connection_thread (ctrl); } /* This is the extra socket connection thread's main function. */ static void * start_connection_thread_extra (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_extra)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } ctrl->restricted = 1; return do_start_connection_thread (ctrl); } /* This is the browser socket connection thread's main function. */ static void * start_connection_thread_browser (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_browser)) { log_error ("handler 0x%lx nonce check FAILED\n", (unsigned long) npth_self()); return NULL; } ctrl->restricted = 2; return do_start_connection_thread (ctrl); } /* This is the ssh connection thread's main function. */ static void * start_connection_thread_ssh (void *arg) { ctrl_t ctrl = arg; if (check_nonce (ctrl, &socket_nonce_ssh)) return NULL; active_connections++; agent_init_default_ctrl (ctrl); if (opt.verbose) log_info (_("ssh handler 0x%lx for fd %d started\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); start_command_handler_ssh (ctrl, ctrl->thread_startup.fd); if (opt.verbose) log_info (_("ssh handler 0x%lx for fd %d terminated\n"), (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd)); agent_deinit_default_ctrl (ctrl); xfree (ctrl); active_connections--; return NULL; } /* Connection handler loop. Wait for connection requests and spawn a thread after accepting a connection. */ static void handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_extra, gnupg_fd_t listen_fd_browser, gnupg_fd_t listen_fd_ssh) { gpg_error_t err; npth_attr_t tattr; struct sockaddr_un paddr; socklen_t plen; fd_set fdset, read_fdset; int ret; gnupg_fd_t fd; int nfd; int saved_errno; struct timespec abstime; struct timespec curtime; struct timespec timeout; #ifdef HAVE_W32_SYSTEM HANDLE events[2]; unsigned int events_set; #endif int sock_inotify_fd = -1; int home_inotify_fd = -1; struct { const char *name; void *(*func) (void *arg); gnupg_fd_t l_fd; } listentbl[] = { { "std", start_connection_thread_std }, { "extra", start_connection_thread_extra }, { "browser", start_connection_thread_browser }, { "ssh", start_connection_thread_ssh } }; ret = npth_attr_init(&tattr); if (ret) log_fatal ("error allocating thread attributes: %s\n", strerror (ret)); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #else # ifdef HAVE_W32CE_SYSTEM /* Use a dummy event. */ sigs = 0; ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo); # else events[0] = get_agent_scd_notify_event (); events[1] = INVALID_HANDLE_VALUE; # endif #endif if (disable_check_own_socket) sock_inotify_fd = -1; else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name))) { if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED) log_info ("error enabling daemon termination by socket removal: %s\n", gpg_strerror (err)); } if (disable_check_own_socket) home_inotify_fd = -1; else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd, gnupg_homedir ()))) { if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED) log_info ("error enabling daemon termination by homedir removal: %s\n", gpg_strerror (err)); } else have_homedir_inotify = 1; /* On Windows we need to fire up a separate thread to listen for requests from Putty (an SSH client), so we can replace Putty's Pageant (its ssh-agent implementation). */ #ifdef HAVE_W32_SYSTEM if (putty_support) { npth_t thread; ret = npth_create (&thread, &tattr, putty_message_thread, NULL); if (ret) { log_error ("error spawning putty message loop: %s\n", strerror (ret)); } } #endif /*HAVE_W32_SYSTEM*/ /* Set a flag to tell call-scd.c that it may enable event notifications. */ opt.sigusr2_enabled = 1; FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (listen_fd_extra != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_extra), &fdset); if (FD2INT (listen_fd_extra) > nfd) nfd = FD2INT (listen_fd_extra); } if (listen_fd_browser != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_browser), &fdset); if (FD2INT (listen_fd_browser) > nfd) nfd = FD2INT (listen_fd_browser); } if (listen_fd_ssh != GNUPG_INVALID_FD) { FD_SET ( FD2INT(listen_fd_ssh), &fdset); if (FD2INT (listen_fd_ssh) > nfd) nfd = FD2INT (listen_fd_ssh); } if (sock_inotify_fd != -1) { FD_SET (sock_inotify_fd, &fdset); if (sock_inotify_fd > nfd) nfd = sock_inotify_fd; } if (home_inotify_fd != -1) { FD_SET (home_inotify_fd, &fdset); if (home_inotify_fd > nfd) nfd = home_inotify_fd; } listentbl[0].l_fd = listen_fd; listentbl[1].l_fd = listen_fd_extra; listentbl[2].l_fd = listen_fd_browser; listentbl[3].l_fd = listen_fd_ssh; npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (active_connections == 0) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ FD_ZERO (&fdset); nfd = -1; if (sock_inotify_fd != -1) { FD_SET (sock_inotify_fd, &fdset); nfd = sock_inotify_fd; } if (home_inotify_fd != -1) { FD_SET (home_inotify_fd, &fdset); if (home_inotify_fd > nfd) nfd = home_inotify_fd; } } /* POSIX says that fd_set should be implemented as a structure, thus a simple assignment is fine to copy the entire set. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask ()); saved_errno = errno; { int signo; while (npth_sigev_get_pending (&signo)) handle_signal (signo); } #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, events, &events_set); saved_errno = errno; /* This is valid even if npth_eselect returns an error. */ if (events_set & 1) agent_sigusr2_action (); #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; /* The inotify fds are set even when a shutdown is pending (see * above). So we must handle them in any case. To avoid that * they trigger a second time we close them immediately. */ if (sock_inotify_fd != -1 && FD_ISSET (sock_inotify_fd, &read_fdset) && gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME)) { shutdown_pending = 1; close (sock_inotify_fd); sock_inotify_fd = -1; log_info ("socket file has been removed - shutting down\n"); } if (home_inotify_fd != -1 && FD_ISSET (home_inotify_fd, &read_fdset)) { shutdown_pending = 1; close (home_inotify_fd); home_inotify_fd = -1; log_info ("homedir has been removed - shutting down\n"); } if (!shutdown_pending) { int idx; ctrl_t ctrl; npth_t thread; for (idx=0; idx < DIM(listentbl); idx++) { if (listentbl[idx].l_fd == GNUPG_INVALID_FD) continue; if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset)) continue; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed for %s: %s\n", listentbl[idx].name, strerror (errno)); } else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl))) { log_error ("error allocating connection data for %s: %s\n", listentbl[idx].name, strerror (errno) ); assuan_sock_close (fd); } else if ( !(ctrl->session_env = session_env_new ())) { log_error ("error allocating session env block for %s: %s\n", listentbl[idx].name, strerror (errno) ); xfree (ctrl); assuan_sock_close (fd); } else { ctrl->thread_startup.fd = fd; ret = npth_create (&thread, &tattr, listentbl[idx].func, ctrl); if (ret) { log_error ("error spawning connection handler for %s:" " %s\n", listentbl[idx].name, strerror (ret)); assuan_sock_close (fd); xfree (ctrl); } } } } } if (sock_inotify_fd != -1) close (sock_inotify_fd); if (home_inotify_fd != -1) close (home_inotify_fd); cleanup (); log_info (_("%s %s stopped\n"), strusage(11), strusage(13)); npth_attr_destroy (&tattr); } /* Helper for check_own_socket. */ static gpg_error_t check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length) { membuf_t *mb = opaque; put_membuf (mb, buffer, length); return 0; } /* The thread running the actual check. We need to run this in a separate thread so that check_own_thread can be called from the timer tick. */ static void * check_own_socket_thread (void *arg) { int rc; char *sockname = arg; assuan_context_t ctx = NULL; membuf_t mb; char *buffer; check_own_socket_running++; rc = assuan_new (&ctx); if (rc) { log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc)); goto leave; } assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1); rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0); if (rc) { log_error ("can't connect my own socket: %s\n", gpg_strerror (rc)); goto leave; } init_membuf (&mb, 100); rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb, NULL, NULL, NULL, NULL); put_membuf (&mb, "", 1); buffer = get_membuf (&mb, NULL); if (rc || !buffer) { log_error ("sending command \"%s\" to my own socket failed: %s\n", "GETINFO pid", gpg_strerror (rc)); rc = 1; } else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ()) { log_error ("socket is now serviced by another server\n"); rc = 1; } else if (opt.verbose > 1) log_error ("socket is still served by this server\n"); xfree (buffer); leave: xfree (sockname); if (ctx) assuan_release (ctx); if (rc) { /* We may not remove the socket as it is now in use by another server. */ inhibit_socket_removal = 1; shutdown_pending = 2; log_info ("this process is useless - shutting down\n"); } check_own_socket_running--; return NULL; } /* Check whether we are still listening on our own socket. In case another gpg-agent process started after us has taken ownership of our socket, we would linger around without any real task. Thus we better check once in a while whether we are really needed. */ static void check_own_socket (void) { char *sockname; npth_t thread; npth_attr_t tattr; int err; if (disable_check_own_socket) return; if (check_own_socket_running || shutdown_pending) return; /* Still running or already shutting down. */ sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); if (!sockname) return; /* Out of memory. */ err = npth_attr_init (&tattr); if (err) return; npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, check_own_socket_thread, sockname); if (err) log_error ("error spawning check_own_socket_thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } /* Figure out whether an agent is available and running. Prints an error if not. If SILENT is true, no messages are printed. Returns 0 if the agent is running. */ static int check_for_running_agent (int silent) { gpg_error_t err; char *sockname; assuan_context_t ctx = NULL; sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL); if (!sockname) return gpg_error_from_syserror (); err = assuan_new (&ctx); if (!err) err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0); xfree (sockname); if (err) { if (!silent) log_error (_("no gpg-agent running in this session\n")); if (ctx) assuan_release (ctx); return -1; } if (!opt.quiet && !silent) log_info ("gpg-agent running and available\n"); assuan_release (ctx); return 0; } diff --git a/g10/cpr.c b/g10/cpr.c index 3d39d6bda..d502e8b52 100644 --- a/g10/cpr.c +++ b/g10/cpr.c @@ -1,664 +1,664 @@ /* status.c - Status message and command-fd interface * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, * 2004, 2005, 2006, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #ifdef HAVE_SIGNAL_H # include #endif #include "gpg.h" #include "../common/util.h" #include "../common/status.h" #include "../common/ttyio.h" #include "options.h" #include "main.h" #include "../common/i18n.h" #define CONTROL_D ('D' - 'A' + 1) /* The stream to output the status information. Output is disabled if this is NULL. */ static estream_t statusfp; static void progress_cb (void *ctx, const char *what, int printchar, int current, int total) { char buf[50]; (void)ctx; if ( printchar == '\n' && !strcmp (what, "primegen") ) snprintf (buf, sizeof buf, "%.20s X 100 100", what ); else snprintf (buf, sizeof buf, "%.20s %c %d %d", what, printchar=='\n'?'X':printchar, current, total ); write_status_text (STATUS_PROGRESS, buf); } /* Return true if the status message NO may currently be issued. We - need this to avoid syncronisation problem while auto retrieving a + need this to avoid synchronization problem while auto retrieving a key. There it may happen that a status NODATA is issued for a non available key and the user may falsely interpret this has a missing signature. */ static int status_currently_allowed (int no) { if (!glo_ctrl.in_auto_key_retrieve) return 1; /* Yes. */ /* We allow some statis anyway, so that import statistics are correct and to avoid problems if the retrieval subsystem will prompt the user. */ switch (no) { case STATUS_GET_BOOL: case STATUS_GET_LINE: case STATUS_GET_HIDDEN: case STATUS_GOT_IT: case STATUS_IMPORTED: case STATUS_IMPORT_OK: case STATUS_IMPORT_CHECK: case STATUS_IMPORT_RES: return 1; /* Yes. */ default: break; } return 0; /* No. */ } void set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (statusfp && statusfp != es_stdout && statusfp != es_stderr ) es_fclose (statusfp); statusfp = NULL; if (fd == -1) return; if (! gnupg_fd_valid (fd)) log_fatal ("status-fd is invalid: %s\n", strerror (errno)); if (fd == 1) statusfp = es_stdout; else if (fd == 2) statusfp = es_stderr; else statusfp = es_fdopen (fd, "w"); if (!statusfp) { log_fatal ("can't open fd %d for status output: %s\n", fd, strerror (errno)); } last_fd = fd; gcry_set_progress_handler (progress_cb, NULL); } int is_status_enabled () { return !!statusfp; } void write_status ( int no ) { write_status_text( no, NULL ); } /* Write a status line with code NO followed by the string TEXT and * directly followed by the remaining strings up to a NULL. Embedded * CR and LFs in the strings (but not in TEXT) are C-style escaped.*/ void write_status_strings (int no, const char *text, ...) { va_list arg_ptr; const char *s; if (!statusfp || !status_currently_allowed (no) ) return; /* Not enabled or allowed. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if ( text ) { es_putc ( ' ', statusfp); va_start (arg_ptr, text); s = text; do { for (; *s; s++) { if (*s == '\n') es_fputs ("\\n", statusfp); else if (*s == '\r') es_fputs ("\\r", statusfp); else es_fputc (*(const byte *)s, statusfp); } } while ((s = va_arg (arg_ptr, const char*))); va_end (arg_ptr); } es_putc ('\n', statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } void write_status_text (int no, const char *text) { write_status_strings (no, text, NULL); } /* Write a status line with code NO followed by the output of the * printf style FORMAT. Embedded CR and LFs are C-style escaped. */ void write_status_printf (int no, const char *format, ...) { va_list arg_ptr; char *buf; if (!statusfp || !status_currently_allowed (no) ) return; /* Not enabled or allowed. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if (format) { es_putc ( ' ', statusfp); va_start (arg_ptr, format); buf = gpgrt_vbsprintf (format, arg_ptr); if (!buf) log_error ("error printing status line: %s\n", gpg_strerror (gpg_err_code_from_syserror ())); else { if (strpbrk (buf, "\r\n")) { const byte *s; for (s=buf; *s; s++) { if (*s == '\n') es_fputs ("\\n", statusfp); else if (*s == '\r') es_fputs ("\\r", statusfp); else es_fputc (*s, statusfp); } } else es_fputs (buf, statusfp); gpgrt_free (buf); } va_end (arg_ptr); } es_putc ('\n', statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Write an ERROR status line using a full gpg-error error value. */ void write_status_error (const char *where, gpg_error_t err) { if (!statusfp || !status_currently_allowed (STATUS_ERROR)) return; /* Not enabled or allowed. */ es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_ERROR), where, err); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Same as above but outputs the error code only. */ void write_status_errcode (const char *where, int errcode) { if (!statusfp || !status_currently_allowed (STATUS_ERROR)) return; /* Not enabled or allowed. */ es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_ERROR), where, gpg_err_code (errcode)); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* Write a FAILURE status line. */ void write_status_failure (const char *where, gpg_error_t err) { static int any_failure_printed; if (!statusfp || !status_currently_allowed (STATUS_FAILURE)) return; /* Not enabled or allowed. */ if (any_failure_printed) return; any_failure_printed = 1; es_fprintf (statusfp, "[GNUPG:] %s %s %u\n", get_status_string (STATUS_FAILURE), where, err); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } /* * Write a status line with a buffer using %XX escapes. If WRAP is > * 0 wrap the line after this length. If STRING is not NULL it will * be prepended to the buffer, no escaping is done for string. * A wrap of -1 forces spaces not to be encoded as %20. */ void write_status_text_and_buffer (int no, const char *string, const char *buffer, size_t len, int wrap) { const char *s, *text; int esc, first; int lower_limit = ' '; size_t n, count, dowrap; if (!statusfp || !status_currently_allowed (no)) return; /* Not enabled or allowed. */ if (wrap == -1) { lower_limit--; wrap = 0; } text = get_status_string (no); count = dowrap = first = 1; do { if (dowrap) { es_fprintf (statusfp, "[GNUPG:] %s ", text); count = dowrap = 0; if (first && string) { es_fputs (string, statusfp); count += strlen (string); /* Make sure that there is a space after the string. */ if (*string && string[strlen (string)-1] != ' ') { es_putc (' ', statusfp); count++; } } first = 0; } for (esc=0, s=buffer, n=len; n && !esc; s++, n--) { if (*s == '%' || *(const byte*)s <= lower_limit || *(const byte*)s == 127 ) esc = 1; if (wrap && ++count > wrap) { dowrap=1; break; } } if (esc) { s--; n++; } if (s != buffer) es_fwrite (buffer, s-buffer, 1, statusfp); if ( esc ) { es_fprintf (statusfp, "%%%02X", *(const byte*)s ); s++; n--; } buffer = s; len = n; if (dowrap && len) es_putc ('\n', statusfp); } while (len); es_putc ('\n',statusfp); if (es_fflush (statusfp) && opt.exit_on_status_write_error) g10_exit (0); } void write_status_buffer (int no, const char *buffer, size_t len, int wrap) { write_status_text_and_buffer (no, NULL, buffer, len, wrap); } /* Print the BEGIN_SIGNING status message. If MD is not NULL it is used to retrieve the hash algorithms used for the message. */ void write_status_begin_signing (gcry_md_hd_t md) { if (md) { char buf[100]; size_t buflen; int i, ga; buflen = 0; for (i=1; i <= 110; i++) { ga = map_md_openpgp_to_gcry (i); if (ga && gcry_md_is_enabled (md, ga) && buflen+10 < DIM(buf)) { snprintf (buf+buflen, DIM(buf) - buflen, "%sH%d", buflen? " ":"",i); buflen += strlen (buf+buflen); } } write_status_text (STATUS_BEGIN_SIGNING, buf); } else write_status ( STATUS_BEGIN_SIGNING ); } static int myread(int fd, void *buf, size_t count) { int rc; do { rc = read( fd, buf, count ); } while (rc == -1 && errno == EINTR); if (!rc && count) { static int eof_emmited=0; if ( eof_emmited < 3 ) { *(char*)buf = CONTROL_D; rc = 1; eof_emmited++; } else /* Ctrl-D not caught - do something reasonable */ { #ifdef HAVE_DOSISH_SYSTEM #ifndef HAVE_W32CE_SYSTEM raise (SIGINT); /* Nothing to hangup under DOS. */ #endif #else raise (SIGHUP); /* No more input data. */ #endif } } return rc; } /* Request a string from the client over the command-fd. If GETBOOL is set the function returns a static string (do not free) if the entered value was true or NULL if the entered value was false. */ static char * do_get_from_fd ( const char *keyword, int hidden, int getbool ) { int i, len; char *string; if (statusfp != es_stdout) es_fflush (es_stdout); write_status_text (getbool? STATUS_GET_BOOL : hidden? STATUS_GET_HIDDEN : STATUS_GET_LINE, keyword); for (string = NULL, i = len = 200; ; i++ ) { if (i >= len-1 ) { /* On the first iteration allocate a new buffer. If that * buffer is too short at further iterations do a poor man's * realloc. */ char *save = string; len += 100; string = hidden? xmalloc_secure ( len ) : xmalloc ( len ); if (save) { memcpy (string, save, i); xfree (save); } else i = 0; } /* Fixme: why not use our read_line function here? */ if ( myread( opt.command_fd, string+i, 1) != 1 || string[i] == '\n' ) break; else if ( string[i] == CONTROL_D ) { /* Found ETX - Cancel the line and return a sole ETX. */ string[0] = CONTROL_D; i = 1; break; } } string[i] = 0; write_status (STATUS_GOT_IT); if (getbool) /* Fixme: is this correct??? */ return (string[0] == 'Y' || string[0] == 'y') ? "" : NULL; return string; } int cpr_enabled() { if( opt.command_fd != -1 ) return 1; return 0; } char * cpr_get_no_help( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 0, 0 ); for(;;) { p = tty_get( prompt ); return p; } } char * cpr_get( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 0, 0 ); for(;;) { p = tty_get( prompt ); if( *p=='?' && !p[1] && !(keyword && !*keyword)) { xfree(p); display_online_help( keyword ); } else return p; } } char * cpr_get_utf8( const char *keyword, const char *prompt ) { char *p; p = cpr_get( keyword, prompt ); if( p ) { char *utf8 = native_to_utf8( p ); xfree( p ); p = utf8; } return p; } char * cpr_get_hidden( const char *keyword, const char *prompt ) { char *p; if( opt.command_fd != -1 ) return do_get_from_fd ( keyword, 1, 0 ); for(;;) { p = tty_get_hidden( prompt ); if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else return p; } } void cpr_kill_prompt(void) { if( opt.command_fd != -1 ) return; tty_kill_prompt(); return; } int cpr_get_answer_is_yes_def (const char *keyword, const char *prompt, int def_yes) { int yes; char *p; if( opt.command_fd != -1 ) return !!do_get_from_fd ( keyword, 0, 1 ); for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else { tty_kill_prompt(); yes = answer_is_yes_no_default (p, def_yes); xfree(p); return yes; } } } int cpr_get_answer_is_yes (const char *keyword, const char *prompt) { return cpr_get_answer_is_yes_def (keyword, prompt, 0); } int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt ) { int yes; char *p; if( opt.command_fd != -1 ) return !!do_get_from_fd ( keyword, 0, 1 ); for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if( *p == '?' && !p[1] ) { xfree(p); display_online_help( keyword ); } else { tty_kill_prompt(); yes = answer_is_yes_no_quit(p); xfree(p); return yes; } } } int cpr_get_answer_okay_cancel (const char *keyword, const char *prompt, int def_answer) { int yes; char *answer = NULL; char *p; if( opt.command_fd != -1 ) answer = do_get_from_fd ( keyword, 0, 0 ); if (answer) { yes = answer_is_okay_cancel (answer, def_answer); xfree (answer); return yes; } for(;;) { p = tty_get( prompt ); trim_spaces(p); /* it is okay to do this here */ if (*p == '?' && !p[1]) { xfree(p); display_online_help (keyword); } else { tty_kill_prompt(); yes = answer_is_okay_cancel (p, def_answer); xfree(p); return yes; } } } diff --git a/kbx/keybox-blob.c b/kbx/keybox-blob.c index 687421219..ac259eabe 100644 --- a/kbx/keybox-blob.c +++ b/kbx/keybox-blob.c @@ -1,1057 +1,1057 @@ /* keybox-blob.c - KBX Blob handling * Copyright (C) 2000, 2001, 2002, 2003, 2008 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 . */ /* * The keybox data format The KeyBox uses an augmented OpenPGP/X.509 key format. This makes random access to a keyblock/certificate easier and also gives the opportunity to store additional information (e.g. the fingerprint) along with the key. All integers are stored in network byte order, offsets are counted from the beginning of the Blob. ** Overview of blob types | Byte 4 | Blob type | |--------+--------------| | 0 | Empty blob | | 1 | First blob | | 2 | OpenPGP blob | | 3 | X.509 blob | ** The First blob The first blob of a plain KBX file has a special format: - u32 Length of this blob - byte Blob type (1) - byte Version number (1) - u16 Header flags bit 0 - RFU bit 1 - Is being or has been used for OpenPGP blobs - b4 Magic 'KBXf' - u32 RFU - u32 file_created_at - u32 last_maintenance_run - u32 RFU - u32 RFU ** The OpenPGP and X.509 blobs The OpenPGP and X.509 blobs are very similar, things which are X.509 specific are noted like [X.509: xxx] - u32 Length of this blob (including these 4 bytes) - byte Blob type 2 = OpenPGP 3 = X509 - byte Version number of this blob type 1 = The only defined value - u16 Blob flags bit 0 = contains secret key material (not used) bit 1 = ephemeral blob (e.g. used while querying external resources) - u32 Offset to the OpenPGP keyblock or the X.509 DER encoded certificate - u32 The length of the keyblock or certificate - u16 [NKEYS] Number of keys (at least 1!) [X509: always 1] - u16 Size of the key information structure (at least 28). - NKEYS times: - b20 The fingerprint of the key. Fingerprints are always 20 bytes, MD5 left padded with zeroes. - u32 Offset to the n-th key's keyID (a keyID is always 8 byte) or 0 if not known which is the case only for X.509. - u16 Key flags bit 0 = qualified signature (not yet implemented} - u16 RFU - bN Optional filler up to the specified length of this structure. - u16 Size of the serial number (may be zero) - bN The serial number. N as giiven above. - u16 Number of user IDs - u16 [NUIDS] Size of user ID information structure - NUIDS times: For X509, the first user ID is the Issuer, the second the Subject and the others are subjectAltNames. For OpenPGP we only store the information from UserID packets here. - u32 Blob offset to the n-th user ID - u32 Length of this user ID. - u16 User ID flags. (not yet used) - byte Validity - byte RFU - u16 [NSIGS] Number of signatures - u16 Size of signature information (4) - NSIGS times: - u32 Expiration time of signature with some special values. Since version 2.1.20 these special valuesare not anymore used for OpenPGP: - 0x00000000 = not checked - 0x00000001 = missing key - 0x00000002 = bad signature - 0x10000000 = valid and expires at some date in 1978. - 0xffffffff = valid and does not expire - u8 Assigned ownertrust [X509: not used] - u8 All_Validity OpenPGP: See ../g10/trustdb/TRUST_* [not yet used] X509: Bit 4 set := key has been revoked. Note that this value matches TRUST_FLAG_REVOKED - u16 RFU - u32 Recheck_after - - u32 Latest timestamp in the keyblock (useful for KS syncronsiation?) + - u32 Latest timestamp in the keyblock (useful for KS synchronization?) - u32 Blob created at - u32 [NRES] Size of reserved space (not including this field) - bN Reserved space of size NRES for future use. - bN Arbitrary space for example used to store data which is not part of the keyblock or certificate. For example the v3 key IDs go here. - bN Space for the keyblock or certificate. - bN RFU. This is the remaining space after keyblock and before the checksum. It is not covered by the checksum. - - b20 SHA-1 checksum (useful for KS syncronisation?) + - b20 SHA-1 checksum (useful for KS synchronization?) Note, that KBX versions before GnuPG 2.1 used an MD5 checksum. However it was only created but never checked. Thus we do not expect problems if we switch to SHA-1. If the checksum fails and the first 4 bytes are zero, we can try again with MD5. SHA-1 has the advantage that it is faster on CPUs with dedicated SHA-1 support. */ #include #include #include #include #include #include #include #include "keybox-defs.h" #include #ifdef KEYBOX_WITH_X509 #include #endif #include "../common/gettime.h" /* special values of the signature status */ #define SF_NONE(a) ( !(a) ) #define SF_NOKEY(a) ((a) & (1<<0)) #define SF_BAD(a) ((a) & (1<<1)) #define SF_VALID(a) ((a) & (1<<29)) struct membuf { size_t len; size_t size; char *buf; int out_of_core; }; /* #if MAX_FINGERPRINT_LEN < 20 */ /* #error fingerprints are 20 bytes */ /* #endif */ struct keyboxblob_key { char fpr[20]; u32 off_kid; ulong off_kid_addr; u16 flags; }; struct keyboxblob_uid { u32 off; ulong off_addr; char *name; /* used only with x509 */ u32 len; u16 flags; byte validity; }; struct keyid_list { struct keyid_list *next; int seqno; byte kid[8]; }; struct fixup_list { struct fixup_list *next; u32 off; u32 val; }; struct keyboxblob { byte *blob; size_t bloblen; off_t fileoffset; /* stuff used only by keybox_create_blob */ unsigned char *serialbuf; const unsigned char *serial; size_t seriallen; int nkeys; struct keyboxblob_key *keys; int nuids; struct keyboxblob_uid *uids; int nsigs; u32 *sigs; struct fixup_list *fixups; int fixup_out_of_core; struct keyid_list *temp_kids; struct membuf bufbuf; /* temporary store for the blob */ struct membuf *buf; }; /* A simple implementation of a dynamic buffer. Use init_membuf() to create a buffer, put_membuf to append bytes and get_membuf to release and return the buffer. Allocation errors are detected but only returned at the final get_membuf(), this helps not to clutter the code with out of core checks. */ static void init_membuf (struct membuf *mb, int initiallen) { mb->len = 0; mb->size = initiallen; mb->out_of_core = 0; mb->buf = xtrymalloc (initiallen); if (!mb->buf) mb->out_of_core = 1; } static void put_membuf (struct membuf *mb, const void *buf, size_t len) { if (mb->out_of_core) return; if (mb->len + len >= mb->size) { char *p; mb->size += len + 1024; p = xtryrealloc (mb->buf, mb->size); if (!p) { mb->out_of_core = 1; return; } mb->buf = p; } if (buf) memcpy (mb->buf + mb->len, buf, len); else memset (mb->buf + mb->len, 0, len); mb->len += len; } static void * get_membuf (struct membuf *mb, size_t *len) { char *p; if (mb->out_of_core) { xfree (mb->buf); mb->buf = NULL; return NULL; } p = mb->buf; *len = mb->len; mb->buf = NULL; mb->out_of_core = 1; /* don't allow a reuse */ return p; } static void put8 (struct membuf *mb, byte a ) { put_membuf (mb, &a, 1); } static void put16 (struct membuf *mb, u16 a ) { unsigned char tmp[2]; tmp[0] = a>>8; tmp[1] = a; put_membuf (mb, tmp, 2); } static void put32 (struct membuf *mb, u32 a ) { unsigned char tmp[4]; tmp[0] = a>>24; tmp[1] = a>>16; tmp[2] = a>>8; tmp[3] = a; put_membuf (mb, tmp, 4); } /* Store a value in the fixup list */ static void add_fixup (KEYBOXBLOB blob, u32 off, u32 val) { struct fixup_list *fl; if (blob->fixup_out_of_core) return; fl = xtrycalloc(1, sizeof *fl); if (!fl) blob->fixup_out_of_core = 1; else { fl->off = off; fl->val = val; fl->next = blob->fixups; blob->fixups = fl; } } /* OpenPGP specific stuff */ /* We must store the keyid at some place because we can't calculate the offset yet. This is only used for v3 keyIDs. Function returns an index value for later fixup or -1 for out of core. The value must be a non-zero value. */ static int pgp_temp_store_kid (KEYBOXBLOB blob, struct _keybox_openpgp_key_info *kinfo) { struct keyid_list *k, *r; k = xtrymalloc (sizeof *k); if (!k) return -1; memcpy (k->kid, kinfo->keyid, 8); k->seqno = 0; k->next = blob->temp_kids; blob->temp_kids = k; for (r=k; r; r = r->next) k->seqno++; return k->seqno; } /* Helper for pgp_create_key_part. */ static gpg_error_t pgp_create_key_part_single (KEYBOXBLOB blob, int n, struct _keybox_openpgp_key_info *kinfo) { size_t fprlen; int off; fprlen = kinfo->fprlen; if (fprlen > 20) fprlen = 20; memcpy (blob->keys[n].fpr, kinfo->fpr, fprlen); if (fprlen != 20) /* v3 fpr - shift right and fill with zeroes. */ { memmove (blob->keys[n].fpr + 20 - fprlen, blob->keys[n].fpr, fprlen); memset (blob->keys[n].fpr, 0, 20 - fprlen); off = pgp_temp_store_kid (blob, kinfo); if (off == -1) return gpg_error_from_syserror (); blob->keys[n].off_kid = off; } else blob->keys[n].off_kid = 0; /* Will be fixed up later */ blob->keys[n].flags = 0; return 0; } static gpg_error_t pgp_create_key_part (KEYBOXBLOB blob, keybox_openpgp_info_t info) { gpg_error_t err; int n = 0; struct _keybox_openpgp_key_info *kinfo; err = pgp_create_key_part_single (blob, n++, &info->primary); if (err) return err; if (info->nsubkeys) for (kinfo = &info->subkeys; kinfo; kinfo = kinfo->next) if ((err=pgp_create_key_part_single (blob, n++, kinfo))) return err; assert (n == blob->nkeys); return 0; } static void pgp_create_uid_part (KEYBOXBLOB blob, keybox_openpgp_info_t info) { int n = 0; struct _keybox_openpgp_uid_info *u; if (info->nuids) { for (u = &info->uids; u; u = u->next) { blob->uids[n].off = u->off; blob->uids[n].len = u->len; blob->uids[n].flags = 0; blob->uids[n].validity = 0; n++; } } assert (n == blob->nuids); } static void pgp_create_sig_part (KEYBOXBLOB blob, u32 *sigstatus) { int n; for (n=0; n < blob->nsigs; n++) { blob->sigs[n] = sigstatus? sigstatus[n+1] : 0; } } static int pgp_create_blob_keyblock (KEYBOXBLOB blob, const unsigned char *image, size_t imagelen) { struct membuf *a = blob->buf; int n; u32 kbstart = a->len; add_fixup (blob, 8, kbstart); for (n = 0; n < blob->nuids; n++) add_fixup (blob, blob->uids[n].off_addr, kbstart + blob->uids[n].off); put_membuf (a, image, imagelen); add_fixup (blob, 12, a->len - kbstart); return 0; } #ifdef KEYBOX_WITH_X509 /* X.509 specific stuff */ /* Write the raw certificate out */ static int x509_create_blob_cert (KEYBOXBLOB blob, ksba_cert_t cert) { struct membuf *a = blob->buf; const unsigned char *image; size_t length; u32 kbstart = a->len; /* Store our offset for later fixup */ add_fixup (blob, 8, kbstart); image = ksba_cert_get_image (cert, &length); if (!image) return gpg_error (GPG_ERR_GENERAL); put_membuf (a, image, length); add_fixup (blob, 12, a->len - kbstart); return 0; } #endif /*KEYBOX_WITH_X509*/ /* Write a stored keyID out to the buffer */ static void write_stored_kid (KEYBOXBLOB blob, int seqno) { struct keyid_list *r; for ( r = blob->temp_kids; r; r = r->next ) { if (r->seqno == seqno ) { put_membuf (blob->buf, r->kid, 8); return; } } never_reached (); } /* Release a list of key IDs */ static void release_kid_list (struct keyid_list *kl) { struct keyid_list *r, *r2; for ( r = kl; r; r = r2 ) { r2 = r->next; xfree (r); } } static int create_blob_header (KEYBOXBLOB blob, int blobtype, int as_ephemeral) { struct membuf *a = blob->buf; int i; put32 ( a, 0 ); /* blob length, needs fixup */ put8 ( a, blobtype); put8 ( a, 1 ); /* blob type version */ put16 ( a, as_ephemeral? 2:0 ); /* blob flags */ put32 ( a, 0 ); /* offset to the raw data, needs fixup */ put32 ( a, 0 ); /* length of the raw data, needs fixup */ put16 ( a, blob->nkeys ); put16 ( a, 20 + 4 + 2 + 2 ); /* size of key info */ for ( i=0; i < blob->nkeys; i++ ) { put_membuf (a, blob->keys[i].fpr, 20); blob->keys[i].off_kid_addr = a->len; put32 ( a, 0 ); /* offset to keyid, fixed up later */ put16 ( a, blob->keys[i].flags ); put16 ( a, 0 ); /* reserved */ } put16 (a, blob->seriallen); /*fixme: check that it fits into 16 bits*/ if (blob->serial) put_membuf (a, blob->serial, blob->seriallen); put16 ( a, blob->nuids ); put16 ( a, 4 + 4 + 2 + 1 + 1 ); /* size of uid info */ for (i=0; i < blob->nuids; i++) { blob->uids[i].off_addr = a->len; put32 ( a, 0 ); /* offset to userid, fixed up later */ put32 ( a, blob->uids[i].len ); put16 ( a, blob->uids[i].flags ); put8 ( a, 0 ); /* validity */ put8 ( a, 0 ); /* reserved */ } put16 ( a, blob->nsigs ); put16 ( a, 4 ); /* size of sig info */ for (i=0; i < blob->nsigs; i++) { put32 ( a, blob->sigs[i]); } put8 ( a, 0 ); /* assigned ownertrust */ put8 ( a, 0 ); /* validity of all user IDs */ put16 ( a, 0 ); /* reserved */ put32 ( a, 0 ); /* time of next recheck */ put32 ( a, 0 ); /* newest timestamp (none) */ put32 ( a, make_timestamp() ); /* creation time */ put32 ( a, 0 ); /* size of reserved space */ /* reserved space (which is currently of size 0) */ /* space where we write keyIDs and other stuff so that the pointers can actually point to somewhere */ if (blobtype == KEYBOX_BLOBTYPE_PGP) { /* We need to store the keyids for all pgp v3 keys because those key IDs are not part of the fingerprint. While we are doing that, we fixup all the keyID offsets */ for (i=0; i < blob->nkeys; i++ ) { if (blob->keys[i].off_kid) { /* this is a v3 one */ add_fixup (blob, blob->keys[i].off_kid_addr, a->len); write_stored_kid (blob, blob->keys[i].off_kid); } else { /* the better v4 key IDs - just store an offset 8 bytes back */ add_fixup (blob, blob->keys[i].off_kid_addr, blob->keys[i].off_kid_addr - 8); } } } if (blobtype == KEYBOX_BLOBTYPE_X509) { /* We don't want to point to ASN.1 encoded UserIDs (DNs) but to the utf-8 string represenation of them */ for (i=0; i < blob->nuids; i++ ) { if (blob->uids[i].name) { /* this is a v3 one */ add_fixup (blob, blob->uids[i].off_addr, a->len); put_membuf (blob->buf, blob->uids[i].name, blob->uids[i].len); } } } return 0; } static int create_blob_trailer (KEYBOXBLOB blob) { (void)blob; return 0; } static int create_blob_finish (KEYBOXBLOB blob) { struct membuf *a = blob->buf; unsigned char *p; unsigned char *pp; size_t n; /* Write a placeholder for the checksum */ put_membuf (a, NULL, 20); /* get the memory area */ n = 0; /* (Just to avoid compiler warning.) */ p = get_membuf (a, &n); if (!p) return gpg_error (GPG_ERR_ENOMEM); assert (n >= 20); /* fixup the length */ add_fixup (blob, 0, n); /* do the fixups */ if (blob->fixup_out_of_core) { xfree (p); return gpg_error (GPG_ERR_ENOMEM); } { struct fixup_list *fl, *next; for (fl = blob->fixups; fl; fl = next) { assert (fl->off+4 <= n); p[fl->off+0] = fl->val >> 24; p[fl->off+1] = fl->val >> 16; p[fl->off+2] = fl->val >> 8; p[fl->off+3] = fl->val; next = fl->next; xfree (fl); } blob->fixups = NULL; } /* Compute and store the SHA-1 checksum. */ gcry_md_hash_buffer (GCRY_MD_SHA1, p + n - 20, p, n - 20); pp = xtrymalloc (n); if ( !pp ) { xfree (p); return gpg_error_from_syserror (); } memcpy (pp , p, n); xfree (p); blob->blob = pp; blob->bloblen = n; return 0; } gpg_error_t _keybox_create_openpgp_blob (KEYBOXBLOB *r_blob, keybox_openpgp_info_t info, const unsigned char *image, size_t imagelen, int as_ephemeral) { gpg_error_t err; KEYBOXBLOB blob; *r_blob = NULL; blob = xtrycalloc (1, sizeof *blob); if (!blob) return gpg_error_from_syserror (); blob->nkeys = 1 + info->nsubkeys; blob->keys = xtrycalloc (blob->nkeys, sizeof *blob->keys ); if (!blob->keys) { err = gpg_error_from_syserror (); goto leave; } blob->nuids = info->nuids; if (blob->nuids) { blob->uids = xtrycalloc (blob->nuids, sizeof *blob->uids ); if (!blob->uids) { err = gpg_error_from_syserror (); goto leave; } } blob->nsigs = info->nsigs; if (blob->nsigs) { blob->sigs = xtrycalloc (blob->nsigs, sizeof *blob->sigs ); if (!blob->sigs) { err = gpg_error_from_syserror (); goto leave; } } err = pgp_create_key_part (blob, info); if (err) goto leave; pgp_create_uid_part (blob, info); pgp_create_sig_part (blob, NULL); init_membuf (&blob->bufbuf, 1024); blob->buf = &blob->bufbuf; err = create_blob_header (blob, KEYBOX_BLOBTYPE_PGP, as_ephemeral); if (err) goto leave; err = pgp_create_blob_keyblock (blob, image, imagelen); if (err) goto leave; err = create_blob_trailer (blob); if (err) goto leave; err = create_blob_finish (blob); if (err) goto leave; leave: release_kid_list (blob->temp_kids); blob->temp_kids = NULL; if (err) _keybox_release_blob (blob); else *r_blob = blob; return err; } #ifdef KEYBOX_WITH_X509 /* Return an allocated string with the email address extracted from a DN. Note hat we use this code also in ../sm/keylist.c. */ static char * x509_email_kludge (const char *name) { const char *p, *string; unsigned char *buf; int n; string = name; for (;;) { p = strstr (string, "1.2.840.113549.1.9.1=#"); if (!p) return NULL; if (p == name || (p > string+1 && p[-1] == ',' && p[-2] != '\\')) { name = p + 22; break; } string = p + 22; } /* This looks pretty much like an email address in the subject's DN we use this to add an additional user ID entry. This way, OpenSSL generated keys get a nicer and usable listing. */ for (n=0, p=name; hexdigitp (p) && hexdigitp (p+1); p +=2, n++) ; if (!n) return NULL; buf = xtrymalloc (n+3); if (!buf) return NULL; /* oops, out of core */ *buf = '<'; for (n=1, p=name; hexdigitp (p); p +=2, n++) buf[n] = xtoi_2 (p); buf[n++] = '>'; buf[n] = 0; return (char*)buf; } /* Note: We should move calculation of the digest into libksba and remove that parameter */ int _keybox_create_x509_blob (KEYBOXBLOB *r_blob, ksba_cert_t cert, unsigned char *sha1_digest, int as_ephemeral) { int i, rc = 0; KEYBOXBLOB blob; unsigned char *sn; char *p; char **names = NULL; size_t max_names; *r_blob = NULL; blob = xtrycalloc (1, sizeof *blob); if( !blob ) return gpg_error_from_syserror (); sn = ksba_cert_get_serial (cert); if (sn) { size_t n, len; n = gcry_sexp_canon_len (sn, 0, NULL, NULL); if (n < 2) { xfree (sn); return gpg_error (GPG_ERR_GENERAL); } blob->serialbuf = sn; sn++; n--; /* skip '(' */ for (len=0; n && *sn && *sn != ':' && digitp (sn); n--, sn++) len = len*10 + atoi_1 (sn); if (*sn != ':') { xfree (blob->serialbuf); blob->serialbuf = NULL; return gpg_error (GPG_ERR_GENERAL); } sn++; blob->serial = sn; blob->seriallen = len; } blob->nkeys = 1; /* create list of names */ blob->nuids = 0; max_names = 100; names = xtrymalloc (max_names * sizeof *names); if (!names) { rc = gpg_error_from_syserror (); goto leave; } p = ksba_cert_get_issuer (cert, 0); if (!p) { rc = gpg_error (GPG_ERR_MISSING_VALUE); goto leave; } names[blob->nuids++] = p; for (i=0; (p = ksba_cert_get_subject (cert, i)); i++) { if (blob->nuids >= max_names) { char **tmp; max_names += 100; tmp = xtryrealloc (names, max_names * sizeof *names); if (!tmp) { rc = gpg_error_from_syserror (); goto leave; } names = tmp; } names[blob->nuids++] = p; if (!i && (p=x509_email_kludge (p))) names[blob->nuids++] = p; /* due to !i we don't need to check bounds*/ } /* space for signature information */ blob->nsigs = 1; blob->keys = xtrycalloc (blob->nkeys, sizeof *blob->keys ); blob->uids = xtrycalloc (blob->nuids, sizeof *blob->uids ); blob->sigs = xtrycalloc (blob->nsigs, sizeof *blob->sigs ); if (!blob->keys || !blob->uids || !blob->sigs) { rc = gpg_error (GPG_ERR_ENOMEM); goto leave; } memcpy (blob->keys[0].fpr, sha1_digest, 20); blob->keys[0].off_kid = 0; /* We don't have keyids */ blob->keys[0].flags = 0; /* issuer and subject names */ for (i=0; i < blob->nuids; i++) { blob->uids[i].name = names[i]; blob->uids[i].len = strlen(names[i]); names[i] = NULL; blob->uids[i].flags = 0; blob->uids[i].validity = 0; } xfree (names); names = NULL; /* signatures */ blob->sigs[0] = 0; /* not yet checked */ /* Create a temporary buffer for further processing */ init_membuf (&blob->bufbuf, 1024); blob->buf = &blob->bufbuf; /* write out what we already have */ rc = create_blob_header (blob, KEYBOX_BLOBTYPE_X509, as_ephemeral); if (rc) goto leave; rc = x509_create_blob_cert (blob, cert); if (rc) goto leave; rc = create_blob_trailer (blob); if (rc) goto leave; rc = create_blob_finish ( blob ); if (rc) goto leave; leave: release_kid_list (blob->temp_kids); blob->temp_kids = NULL; if (names) { for (i=0; i < blob->nuids; i++) xfree (names[i]); xfree (names); } if (rc) { _keybox_release_blob (blob); *r_blob = NULL; } else { *r_blob = blob; } return rc; } #endif /*KEYBOX_WITH_X509*/ int _keybox_new_blob (KEYBOXBLOB *r_blob, unsigned char *image, size_t imagelen, off_t off) { KEYBOXBLOB blob; *r_blob = NULL; blob = xtrycalloc (1, sizeof *blob); if (!blob) return gpg_error_from_syserror (); blob->blob = image; blob->bloblen = imagelen; blob->fileoffset = off; *r_blob = blob; return 0; } void _keybox_release_blob (KEYBOXBLOB blob) { int i; if (!blob) return; if (blob->buf) { size_t len; xfree (get_membuf (blob->buf, &len)); } xfree (blob->keys ); xfree (blob->serialbuf); for (i=0; i < blob->nuids; i++) xfree (blob->uids[i].name); xfree (blob->uids ); xfree (blob->sigs ); xfree (blob->blob ); xfree (blob ); } const unsigned char * _keybox_get_blob_image ( KEYBOXBLOB blob, size_t *n ) { *n = blob->bloblen; return blob->blob; } off_t _keybox_get_blob_fileoffset (KEYBOXBLOB blob) { return blob->fileoffset; } void _keybox_update_header_blob (KEYBOXBLOB blob, int for_openpgp) { if (blob->bloblen >= 32 && blob->blob[4] == KEYBOX_BLOBTYPE_HEADER) { u32 val = make_timestamp (); /* Update the last maintenance run times tamp. */ blob->blob[20] = (val >> 24); blob->blob[20+1] = (val >> 16); blob->blob[20+2] = (val >> 8); blob->blob[20+3] = (val ); if (for_openpgp) blob->blob[7] |= 0x02; /* OpenPGP data may be available. */ } } diff --git a/scd/app-openpgp.c b/scd/app-openpgp.c index 6c01f3a0d..66b7bd1ee 100644 --- a/scd/app-openpgp.c +++ b/scd/app-openpgp.c @@ -1,5301 +1,5301 @@ /* app-openpgp.c - The OpenPGP card application. * Copyright (C) 2003, 2004, 2005, 2007, 2008, * 2009, 2013, 2014, 2015 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 . */ /* Some notes: CHV means Card Holder Verification and is nothing else than a PIN or password. That term seems to have been used originally with GSM cards. Version v2 of the specs changes the term to the clearer term PW for password. We use the terms here interchangeable because we do not want to change existing strings i18n wise. Version 2 of the specs also drops the separate PW2 which was required in v1 due to ISO requirements. It is now possible to have one physical PW but two reference to it so that they can be individually be verified (e.g. to implement a forced verification for one key). Thus you will noticed the use of PW2 with the verify command but not with change_reference_data because the latter operates directly on the physical PW. The Reset Code (RC) as implemented by v2 cards uses the same error counter as the PW2 of v1 cards. By default no RC is set and thus that error counter is set to 0. After setting the RC the error counter will be initialized to 3. */ #include #include #include #include #include #include #include #include #if GNUPG_MAJOR_VERSION == 1 /* This is used with GnuPG version < 1.9. The code has been source copied from the current GnuPG >= 1.9 and is maintained over there. */ #include "options.h" #include "errors.h" #include "memory.h" #include "cardglue.h" #else /* GNUPG_MAJOR_VERSION != 1 */ #include "scdaemon.h" #endif /* GNUPG_MAJOR_VERSION != 1 */ #include "../common/util.h" #include "../common/i18n.h" #include "iso7816.h" #include "app-common.h" #include "../common/tlv.h" #include "../common/host2net.h" #include "../common/openpgpdefs.h" /* A table describing the DOs of the card. */ static struct { int tag; int constructed; int get_from; /* Constructed DO with this DO or 0 for direct access. */ unsigned int binary:1; unsigned int dont_cache:1; unsigned int flush_on_error:1; unsigned int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of this data object if it is used in 1.1 and later versions of the card. This does not work with composite DO and is currently only useful for the CHV status bytes. */ unsigned int try_extlen:2; /* Large object; try to use an extended length APDU when !=0. The size is determined by extcap.max_certlen_3 when == 1, and by extcap.max_special_do when == 2. */ char *desc; } data_objects[] = { { 0x005E, 0, 0, 1, 0, 0, 0, 2, "Login Data" }, { 0x5F50, 0, 0, 0, 0, 0, 0, 2, "URL" }, { 0x5F52, 0, 0, 1, 0, 0, 0, 0, "Historical Bytes" }, { 0x0065, 1, 0, 1, 0, 0, 0, 0, "Cardholder Related Data"}, { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" }, { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" }, { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" }, { 0x006E, 1, 0, 1, 0, 0, 0, 0, "Application Related Data" }, { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" }, { 0x0073, 1, 0, 1, 0, 0, 0, 0, "Discretionary Data Objects" }, { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" }, { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" }, { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" }, { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" }, { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" }, { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" }, { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" }, { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" }, { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" }, { 0x007A, 1, 0, 1, 0, 0, 0, 0, "Security Support Template" }, { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" }, { 0x0101, 0, 0, 0, 0, 0, 0, 2, "Private DO 1"}, { 0x0102, 0, 0, 0, 0, 0, 0, 2, "Private DO 2"}, { 0x0103, 0, 0, 0, 0, 0, 0, 2, "Private DO 3"}, { 0x0104, 0, 0, 0, 0, 0, 0, 2, "Private DO 4"}, { 0x7F21, 1, 0, 1, 0, 0, 0, 1, "Cardholder certificate"}, /* V3.0 */ { 0x7F74, 0, 0, 1, 0, 0, 0, 0, "General Feature Management"}, { 0x00D5, 0, 0, 1, 0, 0, 0, 0, "AES key data"}, { 0x00F9, 0, 0, 1, 0, 0, 0, 0, "KDF data object"}, { 0 } }; /* Type of keys. */ typedef enum { KEY_TYPE_ECC, KEY_TYPE_RSA, } key_type_t; /* The format of RSA private keys. */ typedef enum { RSA_UNKNOWN_FMT, RSA_STD, RSA_STD_N, RSA_CRT, RSA_CRT_N } rsa_key_format_t; /* One cache item for DOs. */ struct cache_s { struct cache_s *next; int tag; size_t length; unsigned char data[1]; }; /* Object with application (i.e. OpenPGP card) specific data. */ struct app_local_s { /* A linked list with cached DOs. */ struct cache_s *cache; /* Keep track of the public keys. */ struct { int read_done; /* True if we have at least tried to read them. */ unsigned char *key; /* This is a malloced buffer with a canonical encoded S-expression encoding a public key. Might be NULL if key is not available. */ size_t keylen; /* The length of the above S-expression. This is usually only required for cross checks because the length of an S-expression is implicitly available. */ } pk[3]; unsigned char status_indicator; /* The card status indicator. */ unsigned int manufacturer:16; /* Manufacturer ID from the s/n. */ /* Keep track of the ISO card capabilities. */ struct { unsigned int cmd_chaining:1; /* Command chaining is supported. */ unsigned int ext_lc_le:1; /* Extended Lc and Le are supported. */ } cardcap; /* Keep track of extended card capabilities. */ struct { unsigned int is_v2:1; /* Compatible to v2 or later. */ unsigned int extcap_v3:1; /* Extcap is in v3 format. */ unsigned int has_button:1; /* Has confirmation button or not. */ unsigned int sm_supported:1; /* Secure Messaging is supported. */ unsigned int get_challenge:1; unsigned int key_import:1; unsigned int change_force_chv:1; unsigned int private_dos:1; unsigned int algo_attr_change:1; /* Algorithm attributes changeable. */ unsigned int has_decrypt:1; /* Support symmetric decryption. */ unsigned int kdf_do:1; /* Support KDF DO. */ unsigned int sm_algo:2; /* Symmetric crypto algo for SM. */ unsigned int pin_blk2:1; /* PIN block 2 format supported. */ unsigned int mse:1; /* MSE command supported. */ unsigned int max_certlen_3:16; unsigned int max_get_challenge:16; /* Maximum size for get_challenge. */ unsigned int max_special_do:16; /* Maximum size for special DOs. */ } extcap; /* Flags used to control the application. */ struct { unsigned int no_sync:1; /* Do not sync CHV1 and CHV2 */ unsigned int def_chv2:1; /* Use 123456 for CHV2. */ } flags; /* Pinpad request specified on card. */ struct { unsigned int specified:1; int fixedlen_user; int fixedlen_admin; } pinpad; struct { key_type_t key_type; union { struct { unsigned int n_bits; /* Size of the modulus in bits. The rest of this strucuire is only valid if this is not 0. */ unsigned int e_bits; /* Size of the public exponent in bits. */ rsa_key_format_t format; } rsa; struct { const char *curve; int flags; } ecc; }; } keyattr[3]; }; #define ECC_FLAG_DJB_TWEAK (1 << 0) #define ECC_FLAG_PUBKEY (1 << 1) /***** Local prototypes *****/ static unsigned long convert_sig_counter_value (const unsigned char *value, size_t valuelen); static unsigned long get_sig_counter (app_t app); static gpg_error_t do_auth (app_t app, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen); static void parse_algorithm_attribute (app_t app, int keyno); static gpg_error_t change_keyattr_from_string (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *value, size_t valuelen); /* Deconstructor. */ static void do_deinit (app_t app) { if (app && app->app_local) { struct cache_s *c, *c2; int i; for (c = app->app_local->cache; c; c = c2) { c2 = c->next; xfree (c); } for (i=0; i < DIM (app->app_local->pk); i++) { xfree (app->app_local->pk[i].key); app->app_local->pk[i].read_done = 0; } xfree (app->app_local); app->app_local = NULL; } } /* Wrapper around iso7816_get_data which first tries to get the data from the cache. With GET_IMMEDIATE passed as true, the cache is bypassed. With TRY_EXTLEN extended lengths APDUs are use if supported by the card. */ static gpg_error_t get_cached_data (app_t app, int tag, unsigned char **result, size_t *resultlen, int get_immediate, int try_extlen) { gpg_error_t err; int i; unsigned char *p; size_t len; struct cache_s *c; int exmode; *result = NULL; *resultlen = 0; if (!get_immediate) { for (c=app->app_local->cache; c; c = c->next) if (c->tag == tag) { if(c->length) { p = xtrymalloc (c->length); if (!p) return gpg_error (gpg_err_code_from_errno (errno)); memcpy (p, c->data, c->length); *result = p; } *resultlen = c->length; return 0; } } if (try_extlen && app->app_local->cardcap.ext_lc_le) { if (try_extlen == 1) exmode = app->app_local->extcap.max_certlen_3; else if (try_extlen == 2 && app->app_local->extcap.extcap_v3) exmode = app->app_local->extcap.max_special_do; else exmode = 0; } else exmode = 0; err = iso7816_get_data (app->slot, exmode, tag, &p, &len); if (err) return err; if (len) *result = p; *resultlen = len; /* Check whether we should cache this object. */ if (get_immediate) return 0; for (i=0; data_objects[i].tag; i++) if (data_objects[i].tag == tag) { if (data_objects[i].dont_cache) return 0; break; } /* Okay, cache it. */ for (c=app->app_local->cache; c; c = c->next) assert (c->tag != tag); c = xtrymalloc (sizeof *c + len); if (c) { if (len) memcpy (c->data, p, len); else xfree (p); c->length = len; c->tag = tag; c->next = app->app_local->cache; app->app_local->cache = c; } return 0; } /* Remove DO at TAG from the cache. */ static void flush_cache_item (app_t app, int tag) { struct cache_s *c, *cprev; int i; if (!app->app_local) return; for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next) if (c->tag == tag) { if (cprev) cprev->next = c->next; else app->app_local->cache = c->next; xfree (c); for (c=app->app_local->cache; c ; c = c->next) { assert (c->tag != tag); /* Oops: duplicated entry. */ } return; } /* Try again if we have an outer tag. */ for (i=0; data_objects[i].tag; i++) if (data_objects[i].tag == tag && data_objects[i].get_from && data_objects[i].get_from != tag) flush_cache_item (app, data_objects[i].get_from); } /* Flush all entries from the cache which might be out of sync after an error. */ static void flush_cache_after_error (app_t app) { int i; for (i=0; data_objects[i].tag; i++) if (data_objects[i].flush_on_error) flush_cache_item (app, data_objects[i].tag); } /* Flush the entire cache. */ static void flush_cache (app_t app) { if (app && app->app_local) { struct cache_s *c, *c2; for (c = app->app_local->cache; c; c = c2) { c2 = c->next; xfree (c); } app->app_local->cache = NULL; } } /* Get the DO identified by TAG from the card in SLOT and return a buffer with its content in RESULT and NBYTES. The return value is NULL if not found or a pointer which must be used to release the buffer holding value. */ static void * get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes, int *r_rc) { int rc, i; unsigned char *buffer; size_t buflen; unsigned char *value; size_t valuelen; int dummyrc; int exmode; if (!r_rc) r_rc = &dummyrc; *result = NULL; *nbytes = 0; *r_rc = 0; for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++) ; if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11) { exmode = 0; rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen); if (rc) { *r_rc = rc; return NULL; } *result = buffer; *nbytes = buflen; return buffer; } value = NULL; rc = -1; if (data_objects[i].tag && data_objects[i].get_from) { rc = get_cached_data (app, data_objects[i].get_from, &buffer, &buflen, (data_objects[i].dont_cache || data_objects[i].get_immediate_in_v11), data_objects[i].try_extlen); if (!rc) { const unsigned char *s; s = find_tlv_unchecked (buffer, buflen, tag, &valuelen); if (!s) value = NULL; /* not found */ else if (valuelen > buflen - (s - buffer)) { log_error ("warning: constructed DO too short\n"); value = NULL; xfree (buffer); buffer = NULL; } else value = buffer + (s - buffer); } } if (!value) /* Not in a constructed DO, try simple. */ { rc = get_cached_data (app, tag, &buffer, &buflen, (data_objects[i].dont_cache || data_objects[i].get_immediate_in_v11), data_objects[i].try_extlen); if (!rc) { value = buffer; valuelen = buflen; } } if (!rc) { *nbytes = valuelen; *result = value; return buffer; } *r_rc = rc; return NULL; } static void dump_all_do (int slot) { int rc, i, j; unsigned char *buffer; size_t buflen; for (i=0; data_objects[i].tag; i++) { if (data_objects[i].get_from) continue; /* We don't try extended length APDU because such large DO would be pretty useless in a log file. */ rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen); if (gpg_err_code (rc) == GPG_ERR_NO_OBJ) ; else if (rc) log_info ("DO '%s' not available: %s\n", data_objects[i].desc, gpg_strerror (rc)); else { if (data_objects[i].binary) { log_info ("DO '%s': ", data_objects[i].desc); log_printhex ("", buffer, buflen); } else log_info ("DO '%s': '%.*s'\n", data_objects[i].desc, (int)buflen, buffer); /* FIXME: sanitize */ if (data_objects[i].constructed) { for (j=0; data_objects[j].tag; j++) { const unsigned char *value; size_t valuelen; if (j==i || data_objects[i].tag != data_objects[j].get_from) continue; value = find_tlv_unchecked (buffer, buflen, data_objects[j].tag, &valuelen); if (!value) ; /* not found */ else if (valuelen > buflen - (value - buffer)) log_error ("warning: constructed DO too short\n"); else { if (data_objects[j].binary) { log_info ("DO '%s': ", data_objects[j].desc); if (valuelen > 200) log_info ("[%u]\n", (unsigned int)valuelen); else log_printhex ("", value, valuelen); } else log_info ("DO '%s': '%.*s'\n", data_objects[j].desc, (int)valuelen, value); /* FIXME: sanitize */ } } } } xfree (buffer); buffer = NULL; } } /* Count the number of bits, assuming the A represents an unsigned big integer of length LEN bytes. */ static unsigned int count_bits (const unsigned char *a, size_t len) { unsigned int n = len * 8; int i; for (; len && !*a; len--, a++, n -=8) ; if (len) { for (i=7; i && !(*a & (1< Where FLAGS is a plain hexadecimal number representing flag values. The lsb is here the rightmost bit. Defined flags bits are: - Bit 0 = CHV1 and CHV2 are not syncronized + Bit 0 = CHV1 and CHV2 are not synchronized Bit 1 = CHV2 has been set to the default PIN of "123456" (this implies that bit 0 is also set). P= Where PINPAD_REQUEST is in the format of: or ,. N for user PIN, M for admin PIN. If M is missing it means M=N. 0 means to force not to use pinpad. */ static void parse_login_data (app_t app) { unsigned char *buffer, *p; size_t buflen, len; void *relptr; /* Set defaults. */ app->app_local->flags.no_sync = 0; app->app_local->flags.def_chv2 = 0; app->app_local->pinpad.specified = 0; app->app_local->pinpad.fixedlen_user = -1; app->app_local->pinpad.fixedlen_admin = -1; /* Read the DO. */ relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL); if (!relptr) return; /* Ooops. */ for (; buflen; buflen--, buffer++) if (*buffer == '\n') break; if (buflen < 2 || buffer[1] != '\x14') { xfree (relptr); return; /* No control sequences. */ } buflen--; buffer++; do { buflen--; buffer++; if (buflen > 1 && *buffer == 'F' && buffer[1] == '=') { /* Flags control sequence found. */ int lastdig = 0; /* For now we are only interested in the last digit, so skip any leading digits but bail out on invalid characters. */ for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--) lastdig = xtoi_1 (p); buffer = p; buflen = len; if (len && !(*p == '\n' || *p == '\x18')) goto next; /* Invalid characters in field. */ app->app_local->flags.no_sync = !!(lastdig & 1); app->app_local->flags.def_chv2 = (lastdig & 3) == 3; } else if (buflen > 1 && *buffer == 'P' && buffer[1] == '=') { /* Pinpad request control sequence found. */ buffer += 2; buflen -= 2; if (buflen) { if (digitp (buffer)) { char *q; int n, m; n = strtol (buffer, &q, 10); if (q >= (char *)buffer + buflen || *q == '\x18' || *q == '\n') m = n; else { if (*q++ != ',' || !digitp (q)) goto next; m = strtol (q, &q, 10); } if (buflen < ((unsigned char *)q - buffer)) break; buflen -= ((unsigned char *)q - buffer); buffer = q; if (buflen && !(*buffer == '\n' || *buffer == '\x18')) goto next; app->app_local->pinpad.specified = 1; app->app_local->pinpad.fixedlen_user = n; app->app_local->pinpad.fixedlen_admin = m; } } } next: /* Skip to FS (0x18) or LF (\n). */ for (; buflen && *buffer != '\x18' && *buffer != '\n'; buflen--) buffer++; } while (buflen && *buffer != '\n'); xfree (relptr); } #define MAX_ARGS_STORE_FPR 3 /* Note, that FPR must be at least 20 bytes. */ static gpg_error_t store_fpr (app_t app, int keynumber, u32 timestamp, unsigned char *fpr, int algo, ...) { unsigned int n, nbits; unsigned char *buffer, *p; int tag, tag2; int rc; const unsigned char *m[MAX_ARGS_STORE_FPR]; size_t mlen[MAX_ARGS_STORE_FPR]; va_list ap; int argc; int i; n = 6; /* key packet version, 4-byte timestamps, and algorithm */ if (algo == PUBKEY_ALGO_ECDH) argc = 3; else argc = 2; va_start (ap, algo); for (i = 0; i < argc; i++) { m[i] = va_arg (ap, const unsigned char *); mlen[i] = va_arg (ap, size_t); if (algo == PUBKEY_ALGO_RSA || i == 1) n += 2; n += mlen[i]; } va_end (ap); p = buffer = xtrymalloc (3 + n); if (!buffer) return gpg_error_from_syserror (); *p++ = 0x99; /* ctb */ *p++ = n >> 8; /* 2 byte length header */ *p++ = n; *p++ = 4; /* key packet version */ *p++ = timestamp >> 24; *p++ = timestamp >> 16; *p++ = timestamp >> 8; *p++ = timestamp; *p++ = algo; for (i = 0; i < argc; i++) { if (algo == PUBKEY_ALGO_RSA || i == 1) { nbits = count_bits (m[i], mlen[i]); *p++ = nbits >> 8; *p++ = nbits; } memcpy (p, m[i], mlen[i]); p += mlen[i]; } gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3); xfree (buffer); tag = (app->card_version > 0x0007? 0xC7 : 0xC6) + keynumber; flush_cache_item (app, 0xC5); tag2 = 0xCE + keynumber; flush_cache_item (app, 0xCD); rc = iso7816_put_data (app->slot, 0, tag, fpr, 20); if (rc) log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc)); if (!rc && app->card_version > 0x0100) { unsigned char buf[4]; buf[0] = timestamp >> 24; buf[1] = timestamp >> 16; buf[2] = timestamp >> 8; buf[3] = timestamp; rc = iso7816_put_data (app->slot, 0, tag2, buf, 4); if (rc) log_error (_("failed to store the creation date: %s\n"), gpg_strerror (rc)); } return rc; } static void send_fpr_if_not_null (ctrl_t ctrl, const char *keyword, int number, const unsigned char *fpr) { int i; char buf[41]; char numbuf[25]; for (i=0; i < 20 && !fpr[i]; i++) ; if (i==20) return; /* All zero. */ bin2hex (fpr, 20, buf); if (number == -1) *numbuf = 0; /* Don't print the key number */ else sprintf (numbuf, "%d", number); send_status_info (ctrl, keyword, numbuf, (size_t)strlen(numbuf), buf, (size_t)strlen (buf), NULL, 0); } static void send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword, int number, const unsigned char *stamp) { char numbuf1[50], numbuf2[50]; unsigned long value; value = buf32_to_ulong (stamp); if (!value) return; sprintf (numbuf1, "%d", number); sprintf (numbuf2, "%lu", value); send_status_info (ctrl, keyword, numbuf1, (size_t)strlen(numbuf1), numbuf2, (size_t)strlen(numbuf2), NULL, 0); } static void send_key_data (ctrl_t ctrl, const char *name, const unsigned char *a, size_t alen) { char *buffer, *buf; size_t buflen; buffer = buf = bin2hex (a, alen, NULL); if (!buffer) { log_error ("memory allocation error in send_key_data\n"); return; } buflen = strlen (buffer); /* 768 is the hexified size for the modulus of an 3072 bit key. We use extra chunks to transmit larger data (i.e for 4096 bit). */ for ( ;buflen > 768; buflen -= 768, buf += 768) send_status_info (ctrl, "KEY-DATA", "-", 1, buf, 768, NULL, 0); send_status_info (ctrl, "KEY-DATA", name, (size_t)strlen(name), buf, buflen, NULL, 0); xfree (buffer); } static void send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int keyno) { char buffer[200]; assert (keyno >=0 && keyno < DIM(app->app_local->keyattr)); if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA) snprintf (buffer, sizeof buffer, "%d 1 rsa%u %u %d", keyno+1, app->app_local->keyattr[keyno].rsa.n_bits, app->app_local->keyattr[keyno].rsa.e_bits, app->app_local->keyattr[keyno].rsa.format); else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC) { snprintf (buffer, sizeof buffer, "%d %d %s", keyno+1, keyno==1? PUBKEY_ALGO_ECDH : (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)? PUBKEY_ALGO_EDDSA : PUBKEY_ALGO_ECDSA, app->app_local->keyattr[keyno].ecc.curve); } else snprintf (buffer, sizeof buffer, "%d 0 0 UNKNOWN", keyno+1); send_status_direct (ctrl, keyword, buffer); } #define RSA_SMALL_SIZE_KEY 1952 #define RSA_SMALL_SIZE_OP 2048 static int determine_rsa_response (app_t app, int keyno) { int size; size = 2 + 3 /* header */ + 4 /* tag+len */ + (app->app_local->keyattr[keyno].rsa.n_bits+7)/8 + 2 /* tag+len */ + (app->app_local->keyattr[keyno].rsa.e_bits+7)/8; return size; } /* Implement the GETATTR command. This is similar to the LEARN command but returns just one value via the status interface. */ static gpg_error_t do_getattr (app_t app, ctrl_t ctrl, const char *name) { static struct { const char *name; int tag; int special; } table[] = { { "DISP-NAME", 0x005B }, { "LOGIN-DATA", 0x005E }, { "DISP-LANG", 0x5F2D }, { "DISP-SEX", 0x5F35 }, { "PUBKEY-URL", 0x5F50 }, { "KEY-FPR", 0x00C5, 3 }, { "KEY-TIME", 0x00CD, 4 }, { "KEY-ATTR", 0x0000, -5 }, { "CA-FPR", 0x00C6, 3 }, { "CHV-STATUS", 0x00C4, 1 }, { "SIG-COUNTER", 0x0093, 2 }, { "SERIALNO", 0x004F, -1 }, { "AID", 0x004F }, { "EXTCAP", 0x0000, -2 }, { "PRIVATE-DO-1", 0x0101 }, { "PRIVATE-DO-2", 0x0102 }, { "PRIVATE-DO-3", 0x0103 }, { "PRIVATE-DO-4", 0x0104 }, { "$AUTHKEYID", 0x0000, -3 }, { "$DISPSERIALNO",0x0000, -4 }, { "KDF", 0x00F9 }, { NULL, 0 } }; int idx, i, rc; void *relptr; unsigned char *value; size_t valuelen; for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++) ; if (!table[idx].name) return gpg_error (GPG_ERR_INV_NAME); if (table[idx].special == -1) { /* The serial number is very special. We could have used the AID DO to retrieve it. The AID DO is available anyway but not hex formatted. */ char *serial = app_get_serialno (app); if (serial) { send_status_direct (ctrl, "SERIALNO", serial); xfree (serial); } return 0; } if (table[idx].special == -2) { char tmp[110]; snprintf (tmp, sizeof tmp, "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d " "sm=%d si=%u dec=%d bt=%d kdf=%d", app->app_local->extcap.get_challenge, app->app_local->extcap.key_import, app->app_local->extcap.change_force_chv, app->app_local->extcap.private_dos, app->app_local->extcap.max_certlen_3, app->app_local->extcap.algo_attr_change, (app->app_local->extcap.sm_supported ? (app->app_local->extcap.sm_algo == 0? CIPHER_ALGO_3DES : (app->app_local->extcap.sm_algo == 1? CIPHER_ALGO_AES : CIPHER_ALGO_AES256)) : 0), app->app_local->status_indicator, app->app_local->extcap.has_decrypt, app->app_local->extcap.has_button, app->app_local->extcap.kdf_do); send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0); return 0; } if (table[idx].special == -3) { char const tmp[] = "OPENPGP.3"; send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0); return 0; } if (table[idx].special == -4) { char *serial = app_get_serialno (app); if (serial) { if (strlen (serial) > 16+12) { send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0); xfree (serial); return 0; } xfree (serial); } return gpg_error (GPG_ERR_INV_NAME); } if (table[idx].special == -5) { for (i=0; i < 3; i++) send_key_attr (ctrl, app, table[idx].name, i); return 0; } relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc); if (relptr) { if (table[idx].special == 1) { char numbuf[7*23]; for (i=0,*numbuf=0; i < valuelen && i < 7; i++) sprintf (numbuf+strlen (numbuf), " %d", value[i]); send_status_info (ctrl, table[idx].name, numbuf, strlen (numbuf), NULL, 0); } else if (table[idx].special == 2) { char numbuf[50]; sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen)); send_status_info (ctrl, table[idx].name, numbuf, strlen (numbuf), NULL, 0); } else if (table[idx].special == 3) { if (valuelen >= 60) for (i=0; i < 3; i++) send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20); } else if (table[idx].special == 4) { if (valuelen >= 12) for (i=0; i < 3; i++) send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4); } else send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0); xfree (relptr); } return rc; } /* Return the DISP-NAME without any padding characters. Caller must * free the result. If not found or empty NULL is returned. */ static char * get_disp_name (app_t app) { int rc; void *relptr; unsigned char *value; size_t valuelen; char *string; char *p, *given; char *result; relptr = get_one_do (app, 0x005B, &value, &valuelen, &rc); if (!relptr) return NULL; string = xtrymalloc (valuelen + 1); if (!string) { xfree (relptr); return NULL; } memcpy (string, value, valuelen); string[valuelen] = 0; xfree (relptr); /* Swap surname and given name. */ given = strstr (string, "<<"); for (p = string; *p; p++) if (*p == '<') *p = ' '; if (given && given[2]) { *given = 0; given += 2; result = strconcat (given, " ", string, NULL); } else { result = string; string = NULL; } xfree (string); return result; } /* Return the pretty formatted serialnumber. On error NULL is * returned. */ static char * get_disp_serialno (app_t app) { char *serial = app_get_serialno (app); /* For our OpenPGP cards we do not want to show the entire serial * number but a nicely reformatted actual serial number. */ if (serial && strlen (serial) > 16+12) { memmove (serial, serial+16, 4); serial[4] = ' '; /* memmove (serial+5, serial+20, 4); */ /* serial[9] = ' '; */ /* memmove (serial+10, serial+24, 4); */ /* serial[14] = 0; */ memmove (serial+5, serial+20, 8); serial[13] = 0; } return serial; } /* Return the number of remaining tries for the standard or the admin * pw. Returns -1 on card error. */ static int get_remaining_tries (app_t app, int adminpw) { void *relptr; unsigned char *value; size_t valuelen; int remaining; relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL); if (!relptr || valuelen < 7) { log_error (_("error retrieving CHV status from card\n")); xfree (relptr); return -1; } remaining = value[adminpw? 6 : 4]; xfree (relptr); return remaining; } /* Retrieve the fingerprint from the card inserted in SLOT and write the according hex representation to FPR. Caller must have provide a buffer at FPR of least 41 bytes. Returns 0 on success or an error code. */ #if GNUPG_MAJOR_VERSION > 1 static gpg_error_t retrieve_fpr_from_card (app_t app, int keyno, char *fpr) { gpg_error_t err = 0; void *relptr; unsigned char *value; size_t valuelen; assert (keyno >=0 && keyno <= 2); relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL); if (relptr && valuelen >= 60) bin2hex (value+keyno*20, 20, fpr); else err = gpg_error (GPG_ERR_NOT_FOUND); xfree (relptr); return err; } #endif /*GNUPG_MAJOR_VERSION > 1*/ /* Retrieve the public key material for the RSA key, whose fingerprint is FPR, from gpg output, which can be read through the stream FP. The RSA modulus will be stored at the address of M and MLEN, the public exponent at E and ELEN. Returns zero on success, an error code on failure. Caller must release the allocated buffers at M and E if the function returns success. */ #if GNUPG_MAJOR_VERSION > 1 static gpg_error_t retrieve_key_material (FILE *fp, const char *hexkeyid, const unsigned char **m, size_t *mlen, const unsigned char **e, size_t *elen) { gcry_error_t err = 0; char *line = NULL; /* read_line() buffer. */ size_t line_size = 0; /* Helper for for read_line. */ int found_key = 0; /* Helper to find a matching key. */ unsigned char *m_new = NULL; unsigned char *e_new = NULL; size_t m_new_n = 0; size_t e_new_n = 0; /* Loop over all records until we have found the subkey corresponding to the fingerprint. Inm general the first record should be the pub record, but we don't rely on that. Given that we only need to look at one key, it is sufficient to compare the keyid so that we don't need to look at "fpr" records. */ for (;;) { char *p; char *fields[6] = { NULL, NULL, NULL, NULL, NULL, NULL }; int nfields; size_t max_length; gcry_mpi_t mpi; int i; max_length = 4096; i = read_line (fp, &line, &line_size, &max_length); if (!i) break; /* EOF. */ if (i < 0) { err = gpg_error_from_syserror (); goto leave; /* Error. */ } if (!max_length) { err = gpg_error (GPG_ERR_TRUNCATED); goto leave; /* Line truncated - we better stop processing. */ } /* Parse the line into fields. */ for (nfields=0, p=line; p && nfields < DIM (fields); nfields++) { fields[nfields] = p; p = strchr (p, ':'); if (p) *(p++) = 0; } if (!nfields) continue; /* No fields at all - skip line. */ if (!found_key) { if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") ) && nfields > 4 && !strcmp (fields[4], hexkeyid)) found_key = 1; continue; } if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") ) break; /* Next key - stop. */ if ( strcmp (fields[0], "pkd") ) continue; /* Not a key data record. */ if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1 || (!i && m_new) || (i && e_new)) { err = gpg_error (GPG_ERR_GENERAL); goto leave; /* Error: Invalid key data record or not an RSA key. */ } err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL); if (err) mpi = NULL; else if (!i) err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi); else err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi); gcry_mpi_release (mpi); if (err) goto leave; } if (m_new && e_new) { *m = m_new; *mlen = m_new_n; m_new = NULL; *e = e_new; *elen = e_new_n; e_new = NULL; } else err = gpg_error (GPG_ERR_GENERAL); leave: xfree (m_new); xfree (e_new); xfree (line); return err; } #endif /*GNUPG_MAJOR_VERSION > 1*/ static gpg_error_t rsa_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno, const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp) { gpg_error_t err; const unsigned char *m, *e; size_t mlen, elen; unsigned char *mbuf = NULL, *ebuf = NULL; m = find_tlv (data, datalen, 0x0081, &mlen); if (!m) { log_error (_("response does not contain the RSA modulus\n")); return gpg_error (GPG_ERR_CARD); } e = find_tlv (data, datalen, 0x0082, &elen); if (!e) { log_error (_("response does not contain the RSA public exponent\n")); return gpg_error (GPG_ERR_CARD); } if (ctrl) { send_key_data (ctrl, "n", m, mlen); send_key_data (ctrl, "e", e, elen); } for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */ ; for (; elen && !*e; elen--, e++) /* strip leading zeroes */ ; if (ctrl) { unsigned char fprbuf[20]; err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA, m, mlen, e, elen); if (err) return err; send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf); } mbuf = xtrymalloc (mlen + 1); if (!mbuf) { err = gpg_error_from_syserror (); goto leave; } /* Prepend numbers with a 0 if needed. */ if (mlen && (*m & 0x80)) { *mbuf = 0; memcpy (mbuf+1, m, mlen); mlen++; } else memcpy (mbuf, m, mlen); ebuf = xtrymalloc (elen + 1); if (!ebuf) { err = gpg_error_from_syserror (); goto leave; } /* Prepend numbers with a 0 if needed. */ if (elen && (*e & 0x80)) { *ebuf = 0; memcpy (ebuf+1, e, elen); elen++; } else memcpy (ebuf, e, elen); err = gcry_sexp_build (r_sexp, NULL, "(public-key(rsa(n%b)(e%b)))", (int)mlen, mbuf, (int)elen, ebuf); leave: xfree (mbuf); xfree (ebuf); return err; } /* Determine KDF hash algorithm and KEK encryption algorithm by CURVE. */ static const unsigned char* ecdh_params (const char *curve) { unsigned int nbits; openpgp_curve_to_oid (curve, &nbits); /* See RFC-6637 for those constants. 0x03: Number of bytes 0x01: Version for this parameter format KDF hash algo KEK symmetric cipher algo */ if (nbits <= 256) return (const unsigned char*)"\x03\x01\x08\x07"; else if (nbits <= 384) return (const unsigned char*)"\x03\x01\x09\x08"; else return (const unsigned char*)"\x03\x01\x0a\x09"; } static gpg_error_t ecc_read_pubkey (app_t app, ctrl_t ctrl, u32 created_at, int keyno, const unsigned char *data, size_t datalen, gcry_sexp_t *r_sexp) { gpg_error_t err; unsigned char *qbuf = NULL; const unsigned char *ecc_q; size_t ecc_q_len; gcry_mpi_t oid = NULL; int n; const char *curve; const char *oidstr; const unsigned char *oidbuf; size_t oid_len; int algo; const char *format; ecc_q = find_tlv (data, datalen, 0x0086, &ecc_q_len); if (!ecc_q) { log_error (_("response does not contain the EC public key\n")); return gpg_error (GPG_ERR_CARD); } curve = app->app_local->keyattr[keyno].ecc.curve; oidstr = openpgp_curve_to_oid (curve, NULL); err = openpgp_oid_from_str (oidstr, &oid); if (err) return err; oidbuf = gcry_mpi_get_opaque (oid, &n); if (!oidbuf) { err = gpg_error_from_syserror (); goto leave; } oid_len = (n+7)/8; qbuf = xtrymalloc (ecc_q_len + 1); if (!qbuf) { err = gpg_error_from_syserror (); goto leave; } if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)) { /* Prepend 0x40 prefix. */ *qbuf = 0x40; memcpy (qbuf+1, ecc_q, ecc_q_len); ecc_q_len++; } else memcpy (qbuf, ecc_q, ecc_q_len); if (ctrl) { send_key_data (ctrl, "q", qbuf, ecc_q_len); send_key_data (ctrl, "curve", oidbuf, oid_len); } if (keyno == 1) { if (ctrl) send_key_data (ctrl, "kdf/kek", ecdh_params (curve), (size_t)4); algo = PUBKEY_ALGO_ECDH; } else { if ((app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)) algo = PUBKEY_ALGO_EDDSA; else algo = PUBKEY_ALGO_ECDSA; } if (ctrl) { unsigned char fprbuf[20]; err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len, qbuf, ecc_q_len, ecdh_params (curve), (size_t)4); if (err) goto leave; send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf); } if (!(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)) format = "(public-key(ecc(curve%s)(q%b)))"; else if (keyno == 1) format = "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))"; else format = "(public-key(ecc(curve%s)(flags eddsa)(q%b)))"; err = gcry_sexp_build (r_sexp, NULL, format, app->app_local->keyattr[keyno].ecc.curve, (int)ecc_q_len, qbuf); leave: gcry_mpi_release (oid); xfree (qbuf); return err; } /* Parse tag-length-value data for public key in BUFFER of BUFLEN length. Key of KEYNO in APP is updated with an S-expression of public key. When CTRL is not NULL, fingerprint is computed with CREATED_AT, and fingerprint is written to the card, and key data and fingerprint are send back to the client side. */ static gpg_error_t read_public_key (app_t app, ctrl_t ctrl, u32 created_at, int keyno, const unsigned char *buffer, size_t buflen) { gpg_error_t err; const unsigned char *data; size_t datalen; gcry_sexp_t s_pkey = NULL; data = find_tlv (buffer, buflen, 0x7F49, &datalen); if (!data) { log_error (_("response does not contain the public key data\n")); return gpg_error (GPG_ERR_CARD); } if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA) err = rsa_read_pubkey (app, ctrl, created_at, keyno, data, datalen, &s_pkey); else if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_ECC) err = ecc_read_pubkey (app, ctrl, created_at, keyno, data, datalen, &s_pkey); else err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); if (!err) { unsigned char *keybuf; size_t len; len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0); keybuf = xtrymalloc (len); if (!data) { err = gpg_error_from_syserror (); gcry_sexp_release (s_pkey); return err; } gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len); gcry_sexp_release (s_pkey); app->app_local->pk[keyno].key = keybuf; /* Decrement for trailing '\0' */ app->app_local->pk[keyno].keylen = len - 1; } return err; } /* Get the public key for KEYNO and store it as an S-expression with the APP handle. On error that field gets cleared. If we already know about the public key we will just return. Note that this does not mean a key is available; this is solely indicated by the presence of the app->app_local->pk[KEYNO].key field. Note that GnuPG 1.x does not need this and it would be too time consuming to send it just for the fun of it. However, given that we use the same code in gpg 1.4, we can't use the gcry S-expression here but need to open encode it. */ #if GNUPG_MAJOR_VERSION > 1 static gpg_error_t get_public_key (app_t app, int keyno) { gpg_error_t err = 0; unsigned char *buffer; const unsigned char *m, *e; size_t buflen; size_t mlen = 0; size_t elen = 0; char *keybuf = NULL; gcry_sexp_t s_pkey; size_t len; if (keyno < 0 || keyno > 2) return gpg_error (GPG_ERR_INV_ID); /* Already cached? */ if (app->app_local->pk[keyno].read_done) return 0; xfree (app->app_local->pk[keyno].key); app->app_local->pk[keyno].key = NULL; app->app_local->pk[keyno].keylen = 0; m = e = NULL; /* (avoid cc warning) */ if (app->card_version > 0x0100) { int exmode, le_value; /* We may simply read the public key out of these cards. */ if (app->app_local->cardcap.ext_lc_le && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA && app->app_local->keyattr[keyno].rsa.n_bits > RSA_SMALL_SIZE_KEY) { exmode = 1; /* Use extended length. */ le_value = determine_rsa_response (app, keyno); } else { exmode = 0; le_value = 256; /* Use legacy value. */ } err = iso7816_read_public_key (app->slot, exmode, (keyno == 0? "\xB6" : keyno == 1? "\xB8" : "\xA4"), 2, le_value, &buffer, &buflen); if (err) { log_error (_("reading public key failed: %s\n"), gpg_strerror (err)); goto leave; } err = read_public_key (app, NULL, 0U, keyno, buffer, buflen); } else { /* Due to a design problem in v1.0 cards we can't get the public key out of these cards without doing a verify on CHV3. Clearly that is not an option and thus we try to locate the key using an external helper. The helper we use here is gpg itself, which should know about the key in any case. */ char fpr[41]; char *hexkeyid; char *command = NULL; FILE *fp; int ret; buffer = NULL; /* We don't need buffer. */ err = retrieve_fpr_from_card (app, keyno, fpr); if (err) { log_error ("error while retrieving fpr from card: %s\n", gpg_strerror (err)); goto leave; } hexkeyid = fpr + 24; ret = gpgrt_asprintf (&command, "gpg --list-keys --with-colons --with-key-data '%s'", fpr); if (ret < 0) { err = gpg_error_from_syserror (); goto leave; } fp = popen (command, "r"); xfree (command); if (!fp) { err = gpg_error_from_syserror (); log_error ("running gpg failed: %s\n", gpg_strerror (err)); goto leave; } err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen); pclose (fp); if (err) { log_error ("error while retrieving key material through pipe: %s\n", gpg_strerror (err)); goto leave; } err = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%b)(e%b)))", (int)mlen, m, (int)elen, e); if (err) goto leave; len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0); keybuf = xtrymalloc (len); if (!keybuf) { err = gpg_error_from_syserror (); gcry_sexp_release (s_pkey); goto leave; } gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, keybuf, len); gcry_sexp_release (s_pkey); app->app_local->pk[keyno].key = (unsigned char*)keybuf; /* Decrement for trailing '\0' */ app->app_local->pk[keyno].keylen = len - 1; } leave: /* Set a flag to indicate that we tried to read the key. */ app->app_local->pk[keyno].read_done = 1; xfree (buffer); return err; } #endif /* GNUPG_MAJOR_VERSION > 1 */ /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3]. This is used by the LEARN command. */ static gpg_error_t send_keypair_info (app_t app, ctrl_t ctrl, int key) { int keyno = key - 1; gpg_error_t err = 0; /* Note that GnuPG 1.x does not need this and it would be too time consuming to send it just for the fun of it. */ #if GNUPG_MAJOR_VERSION > 1 unsigned char grip[20]; char gripstr[41]; char idbuf[50]; err = get_public_key (app, keyno); if (err) goto leave; assert (keyno >= 0 && keyno <= 2); if (!app->app_local->pk[keyno].key) goto leave; /* No such key - ignore. */ err = keygrip_from_canon_sexp (app->app_local->pk[keyno].key, app->app_local->pk[keyno].keylen, grip); if (err) goto leave; bin2hex (grip, 20, gripstr); sprintf (idbuf, "OPENPGP.%d", keyno+1); send_status_info (ctrl, "KEYPAIRINFO", gripstr, 40, idbuf, strlen (idbuf), NULL, (size_t)0); leave: #endif /* GNUPG_MAJOR_VERSION > 1 */ return err; } /* Handle the LEARN command for OpenPGP. */ static gpg_error_t do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags) { (void)flags; do_getattr (app, ctrl, "EXTCAP"); do_getattr (app, ctrl, "DISP-NAME"); do_getattr (app, ctrl, "DISP-LANG"); do_getattr (app, ctrl, "DISP-SEX"); do_getattr (app, ctrl, "PUBKEY-URL"); do_getattr (app, ctrl, "LOGIN-DATA"); do_getattr (app, ctrl, "KEY-FPR"); if (app->card_version > 0x0100) do_getattr (app, ctrl, "KEY-TIME"); do_getattr (app, ctrl, "CA-FPR"); do_getattr (app, ctrl, "CHV-STATUS"); do_getattr (app, ctrl, "SIG-COUNTER"); if (app->app_local->extcap.kdf_do) do_getattr (app, ctrl, "KDF"); if (app->app_local->extcap.private_dos) { do_getattr (app, ctrl, "PRIVATE-DO-1"); do_getattr (app, ctrl, "PRIVATE-DO-2"); if (app->did_chv2) do_getattr (app, ctrl, "PRIVATE-DO-3"); if (app->did_chv3) do_getattr (app, ctrl, "PRIVATE-DO-4"); } send_keypair_info (app, ctrl, 1); send_keypair_info (app, ctrl, 2); send_keypair_info (app, ctrl, 3); /* Note: We do not send the Cardholder Certificate, because that is relatively long and for OpenPGP applications not really needed. */ return 0; } /* Handle the READKEY command for OpenPGP. On success a canonical encoded S-expression with the public key will get stored at PK and its length (for assertions) at PKLEN; the caller must release that buffer. On error PK and PKLEN are not changed and an error code is returned. */ static gpg_error_t do_readkey (app_t app, int advanced, const char *keyid, unsigned char **pk, size_t *pklen) { #if GNUPG_MAJOR_VERSION > 1 gpg_error_t err; int keyno; unsigned char *buf; if (!strcmp (keyid, "OPENPGP.1")) keyno = 0; else if (!strcmp (keyid, "OPENPGP.2")) keyno = 1; else if (!strcmp (keyid, "OPENPGP.3")) keyno = 2; else return gpg_error (GPG_ERR_INV_ID); err = get_public_key (app, keyno); if (err) return err; buf = app->app_local->pk[keyno].key; if (!buf) return gpg_error (GPG_ERR_NO_PUBKEY); if (advanced) { gcry_sexp_t s_key; err = gcry_sexp_new (&s_key, buf, app->app_local->pk[keyno].keylen, 0); if (err) return err; *pklen = gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, NULL, 0); *pk = xtrymalloc (*pklen); if (!*pk) { err = gpg_error_from_syserror (); *pklen = 0; return err; } gcry_sexp_sprint (s_key, GCRYSEXP_FMT_ADVANCED, *pk, *pklen); gcry_sexp_release (s_key); /* Decrement for trailing '\0' */ *pklen = *pklen - 1; } else { *pklen = app->app_local->pk[keyno].keylen; *pk = xtrymalloc (*pklen); if (!*pk) { err = gpg_error_from_syserror (); *pklen = 0; return err; } memcpy (*pk, buf, *pklen); } return 0; #else return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } /* Read the standard certificate of an OpenPGP v2 card. It is returned in a freshly allocated buffer with that address stored at CERT and the length of the certificate stored at CERTLEN. CERTID needs to be set to "OPENPGP.3". */ static gpg_error_t do_readcert (app_t app, const char *certid, unsigned char **cert, size_t *certlen) { #if GNUPG_MAJOR_VERSION > 1 gpg_error_t err; unsigned char *buffer; size_t buflen; void *relptr; *cert = NULL; *certlen = 0; if (strcmp (certid, "OPENPGP.3")) return gpg_error (GPG_ERR_INV_ID); if (!app->app_local->extcap.is_v2) return gpg_error (GPG_ERR_NOT_FOUND); relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL); if (!relptr) return gpg_error (GPG_ERR_NOT_FOUND); if (!buflen) err = gpg_error (GPG_ERR_NOT_FOUND); else if (!(*cert = xtrymalloc (buflen))) err = gpg_error_from_syserror (); else { memcpy (*cert, buffer, buflen); *certlen = buflen; err = 0; } xfree (relptr); return err; #else return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } /* Decide if we use the pinpad of the reader for PIN input according to the user preference on the card, and the capability of the reader. This routine is only called when the reader has pinpad. Returns 0 if we use pinpad, 1 otherwise. */ static int check_pinpad_request (app_t app, pininfo_t *pininfo, int admin_pin) { if (app->app_local->pinpad.specified == 0) /* No preference on card. */ { if (pininfo->fixedlen == 0) /* Reader has varlen capability. */ return 0; /* Then, use pinpad. */ else /* * Reader has limited capability, and it may not match PIN of * the card. */ return 1; } if (admin_pin) pininfo->fixedlen = app->app_local->pinpad.fixedlen_admin; else pininfo->fixedlen = app->app_local->pinpad.fixedlen_user; if (pininfo->fixedlen == 0 /* User requests disable pinpad. */ || pininfo->fixedlen < pininfo->minlen || pininfo->fixedlen > pininfo->maxlen /* Reader doesn't have the capability to input a PIN which * length is FIXEDLEN. */) return 1; return 0; } /* Return a string with information about the card for use in a * prompt. Returns NULL on memory failure. */ static char * get_prompt_info (app_t app, int chvno, unsigned long sigcount, int remaining) { char *serial, *disp_name, *rembuf, *tmpbuf, *result; serial = get_disp_serialno (app); if (!serial) return NULL; disp_name = get_disp_name (app); if (chvno == 1) { /* TRANSLATORS: Put a \x1f right before a colon. This can be * used by pinentry to nicely align the names and values. Keep * the %s at the start and end of the string. */ result = xtryasprintf (_("%s" "Number\x1f: %s%%0A" "Holder\x1f: %s%%0A" "Counter\x1f: %lu" "%s"), "\x1e", serial, disp_name? disp_name:"", sigcount, ""); } else { result = xtryasprintf (_("%s" "Number\x1f: %s%%0A" "Holder\x1f: %s" "%s"), "\x1e", serial, disp_name? disp_name:"", ""); } xfree (disp_name); xfree (serial); if (remaining != -1) { /* TRANSLATORS: This is the number of remaining attempts to * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */ rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining); if (!rembuf) { xfree (result); return NULL; } tmpbuf = strconcat (result, "%0A%0A", rembuf, NULL); xfree (rembuf); if (!tmpbuf) { xfree (result); return NULL; } xfree (result); result = tmpbuf; } return result; } #define KDF_DATA_LENGTH_MIN 90 #define KDF_DATA_LENGTH_MAX 110 /* Compute hash if KDF-DO is available. CHVNO must be 0 for reset code, 1 or 2 for user pin and 3 for admin pin. */ static gpg_error_t pin2hash_if_kdf (app_t app, int chvno, char *pinvalue, int *r_pinlen) { gpg_error_t err = 0; void *relptr = NULL; unsigned char *buffer; size_t buflen; if (app->app_local->extcap.kdf_do && (relptr = get_one_do (app, 0x00F9, &buffer, &buflen, NULL)) && buflen >= KDF_DATA_LENGTH_MIN && (buffer[2] == 0x03)) { const char *salt; unsigned long s2k_count; char dek[32]; int salt_index; s2k_count = (((unsigned int)buffer[8] << 24) | (buffer[9] << 16) | (buffer[10] << 8) | buffer[11]); if (buflen == KDF_DATA_LENGTH_MIN) salt_index =14; else if (buflen == KDF_DATA_LENGTH_MAX) salt_index = (chvno==3 ? 34 : (chvno==0 ? 24 : 14)); else { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } salt = &buffer[salt_index]; err = gcry_kdf_derive (pinvalue, strlen (pinvalue), GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256, salt, 8, s2k_count, sizeof (dek), dek); if (!err) { /* pinvalue has a buffer of MAXLEN_PIN+1, 32 is OK. */ *r_pinlen = 32; memcpy (pinvalue, dek, *r_pinlen); wipememory (dek, *r_pinlen); } } else *r_pinlen = strlen (pinvalue); leave: xfree (relptr); return err; } /* Verify a CHV either using the pinentry or if possible by using a pinpad. PINCB and PINCB_ARG describe the usual callback for the pinentry. CHVNO must be either 1 or 2. SIGCOUNT is only used with CHV1. PINVALUE is the address of a pointer which will receive a newly allocated block with the actual PIN (this is useful in case that PIN shall be used for another verify operation). The caller needs to free this value. If the function returns with success and NULL is stored at PINVALUE, the caller should take this as an indication that the pinpad has been used. */ static gpg_error_t verify_a_chv (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, int chvno, unsigned long sigcount, char **pinvalue, int *pinlen) { int rc = 0; char *prompt_buffer = NULL; const char *prompt; pininfo_t pininfo; int minlen = 6; int remaining; log_assert (chvno == 1 || chvno == 2); *pinvalue = NULL; *pinlen = 0; remaining = get_remaining_tries (app, 0); if (remaining == -1) return gpg_error (GPG_ERR_CARD); if (chvno == 2 && app->app_local->flags.def_chv2) { /* Special case for def_chv2 mechanism. */ if (opt.verbose) log_info (_("using default PIN as %s\n"), "CHV2"); rc = iso7816_verify (app->slot, 0x82, "123456", 6); if (rc) { /* Verification of CHV2 with the default PIN failed, although the card pretends to have the default PIN set as CHV2. We better disable the def_chv2 flag now. */ log_info (_("failed to use default PIN as %s: %s" " - disabling further default use\n"), "CHV2", gpg_strerror (rc)); app->app_local->flags.def_chv2 = 0; } return rc; } memset (&pininfo, 0, sizeof pininfo); pininfo.fixedlen = -1; pininfo.minlen = minlen; { const char *firstline = _("||Please unlock the card"); char *infoblock = get_prompt_info (app, chvno, sigcount, remaining < 3? remaining : -1); prompt_buffer = strconcat (firstline, "%0A%0A", infoblock, NULL); if (prompt_buffer) prompt = prompt_buffer; else prompt = firstline; /* ENOMEM fallback. */ xfree (infoblock); } if (!opt.disable_pinpad && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo) && !check_pinpad_request (app, &pininfo, 0)) { /* The reader supports the verify command through the pinpad. Note that the pincb appends a text to the prompt telling the user to use the pinpad. */ rc = pincb (pincb_arg, prompt, NULL); prompt = NULL; xfree (prompt_buffer); prompt_buffer = NULL; if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); return rc; } rc = iso7816_verify_kp (app->slot, 0x80+chvno, &pininfo); /* Dismiss the prompt. */ pincb (pincb_arg, NULL, NULL); log_assert (!*pinvalue); } else { /* The reader has no pinpad or we don't want to use it. */ rc = pincb (pincb_arg, prompt, pinvalue); prompt = NULL; xfree (prompt_buffer); prompt_buffer = NULL; if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); return rc; } if (strlen (*pinvalue) < minlen) { log_error (_("PIN for CHV%d is too short;" " minimum length is %d\n"), chvno, minlen); xfree (*pinvalue); *pinvalue = NULL; return gpg_error (GPG_ERR_BAD_PIN); } rc = pin2hash_if_kdf (app, chvno, *pinvalue, pinlen); if (!rc) rc = iso7816_verify (app->slot, 0x80+chvno, *pinvalue, *pinlen); } if (rc) { log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc)); xfree (*pinvalue); *pinvalue = NULL; flush_cache_after_error (app); } return rc; } /* Verify CHV2 if required. Depending on the configuration of the card CHV1 will also be verified. */ static gpg_error_t verify_chv2 (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { int rc; char *pinvalue; int pinlen; if (app->did_chv2) return 0; /* We already verified CHV2. */ rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue, &pinlen); if (rc) return rc; app->did_chv2 = 1; if (!app->did_chv1 && !app->force_chv1 && pinvalue) { /* For convenience we verify CHV1 here too. We do this only if the card is not configured to require a verification before each CHV1 controlled operation (force_chv1) and if we are not using the pinpad (PINVALUE == NULL). */ rc = iso7816_verify (app->slot, 0x81, pinvalue, pinlen); if (gpg_err_code (rc) == GPG_ERR_BAD_PIN) rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED); if (rc) { log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc)); flush_cache_after_error (app); } else app->did_chv1 = 1; } xfree (pinvalue); return rc; } /* Build the prompt to enter the Admin PIN. The prompt depends on the current sdtate of the card. */ static gpg_error_t build_enter_admin_pin_prompt (app_t app, char **r_prompt) { int remaining; char *prompt; char *infoblock; *r_prompt = NULL; remaining = get_remaining_tries (app, 1); if (remaining == -1) return gpg_error (GPG_ERR_CARD); if (!remaining) { log_info (_("card is permanently locked!\n")); return gpg_error (GPG_ERR_BAD_PIN); } log_info (ngettext("%d Admin PIN attempt remaining before card" " is permanently locked\n", "%d Admin PIN attempts remaining before card" " is permanently locked\n", remaining), remaining); infoblock = get_prompt_info (app, 3, 0, remaining < 3? remaining : -1); /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at the start of the string. Use %0A (single percent) for a linefeed. */ prompt = strconcat (_("|A|Please enter the Admin PIN"), "%0A%0A", infoblock, NULL); xfree (infoblock); if (!prompt) return gpg_error_from_syserror (); *r_prompt = prompt; return 0; } /* Verify CHV3 if required. */ static gpg_error_t verify_chv3 (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { int rc = 0; #if GNUPG_MAJOR_VERSION != 1 if (!opt.allow_admin) { log_info (_("access to admin commands is not configured\n")); return gpg_error (GPG_ERR_EACCES); } #endif if (!app->did_chv3) { pininfo_t pininfo; int minlen = 8; char *prompt; memset (&pininfo, 0, sizeof pininfo); pininfo.fixedlen = -1; pininfo.minlen = minlen; rc = build_enter_admin_pin_prompt (app, &prompt); if (rc) return rc; if (!opt.disable_pinpad && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo) && !check_pinpad_request (app, &pininfo, 1)) { /* The reader supports the verify command through the pinpad. */ rc = pincb (pincb_arg, prompt, NULL); xfree (prompt); prompt = NULL; if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); return rc; } rc = iso7816_verify_kp (app->slot, 0x83, &pininfo); /* Dismiss the prompt. */ pincb (pincb_arg, NULL, NULL); } else { char *pinvalue; int pinlen; rc = pincb (pincb_arg, prompt, &pinvalue); xfree (prompt); prompt = NULL; if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); return rc; } if (strlen (pinvalue) < minlen) { log_error (_("PIN for CHV%d is too short;" " minimum length is %d\n"), 3, minlen); xfree (pinvalue); return gpg_error (GPG_ERR_BAD_PIN); } rc = pin2hash_if_kdf (app, 3, pinvalue, &pinlen); if (!rc) rc = iso7816_verify (app->slot, 0x83, pinvalue, pinlen); xfree (pinvalue); } if (rc) { log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc)); flush_cache_after_error (app); return rc; } app->did_chv3 = 1; } return rc; } /* Handle the SETATTR operation. All arguments are already basically checked. */ static gpg_error_t do_setattr (app_t app, const char *name, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *value, size_t valuelen) { gpg_error_t rc; int idx; static struct { const char *name; int tag; int flush_tag; /* The tag which needs to be flushed or 0. */ int need_chv; int special; unsigned int need_v2:1; } table[] = { { "DISP-NAME", 0x005B, 0, 3 }, { "LOGIN-DATA", 0x005E, 0, 3, 2 }, { "DISP-LANG", 0x5F2D, 0, 3 }, { "DISP-SEX", 0x5F35, 0, 3 }, { "PUBKEY-URL", 0x5F50, 0, 3 }, { "CHV-STATUS-1", 0x00C4, 0, 3, 1 }, { "CA-FPR-1", 0x00CA, 0x00C6, 3 }, { "CA-FPR-2", 0x00CB, 0x00C6, 3 }, { "CA-FPR-3", 0x00CC, 0x00C6, 3 }, { "PRIVATE-DO-1", 0x0101, 0, 2 }, { "PRIVATE-DO-2", 0x0102, 0, 3 }, { "PRIVATE-DO-3", 0x0103, 0, 2 }, { "PRIVATE-DO-4", 0x0104, 0, 3 }, { "CERT-3", 0x7F21, 0, 3, 0, 1 }, { "SM-KEY-ENC", 0x00D1, 0, 3, 0, 1 }, { "SM-KEY-MAC", 0x00D2, 0, 3, 0, 1 }, { "KEY-ATTR", 0, 0, 0, 3, 1 }, { "AESKEY", 0x00D5, 0, 3, 0, 1 }, { "KDF", 0x00F9, 0, 3, 4, 1 }, { NULL, 0 } }; int exmode; for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++) ; if (!table[idx].name) return gpg_error (GPG_ERR_INV_NAME); if (table[idx].need_v2 && !app->app_local->extcap.is_v2) return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported. */ if (table[idx].special == 3) return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen); switch (table[idx].need_chv) { case 2: rc = verify_chv2 (app, pincb, pincb_arg); break; case 3: rc = verify_chv3 (app, pincb, pincb_arg); break; default: rc = 0; } if (rc) return rc; /* Flush the cache before writing it, so that the next get operation will reread the data from the card and thus get synced in case of errors (e.g. data truncated by the card). */ flush_cache_item (app, table[idx].flush_tag? table[idx].flush_tag /* */ : table[idx].tag); if (app->app_local->cardcap.ext_lc_le && valuelen > 254) exmode = 1; /* Use extended length w/o a limit. */ else if (app->app_local->cardcap.cmd_chaining && valuelen > 254) exmode = -254; /* Command chaining with max. 254 bytes. */ else exmode = 0; rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen); if (rc) log_error ("failed to set '%s': %s\n", table[idx].name, gpg_strerror (rc)); if (table[idx].special == 1) app->force_chv1 = (valuelen && *value == 0); else if (table[idx].special == 2) parse_login_data (app); else if (table[idx].special == 4) { app->did_chv1 = 0; app->did_chv2 = 0; app->did_chv3 = 0; } return rc; } /* Handle the WRITECERT command for OpenPGP. This rites the standard certifciate to the card; CERTID needs to be set to "OPENPGP.3". PINCB and PINCB_ARG are the usual arguments for the pinentry callback. */ static gpg_error_t do_writecert (app_t app, ctrl_t ctrl, const char *certidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *certdata, size_t certdatalen) { (void)ctrl; #if GNUPG_MAJOR_VERSION > 1 if (strcmp (certidstr, "OPENPGP.3")) return gpg_error (GPG_ERR_INV_ID); if (!certdata || !certdatalen) return gpg_error (GPG_ERR_INV_ARG); if (!app->app_local->extcap.is_v2) return gpg_error (GPG_ERR_NOT_SUPPORTED); if (certdatalen > app->app_local->extcap.max_certlen_3) return gpg_error (GPG_ERR_TOO_LARGE); return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen); #else return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } /* Handle the PASSWD command. The following combinations are possible: Flags CHVNO Vers. Description RESET 1 1 Verify CHV3 and set a new CHV1 and CHV2 RESET 1 2 Verify PW3 and set a new PW1. RESET 2 1 Verify CHV3 and set a new CHV1 and CHV2. RESET 2 2 Verify PW3 and set a new Reset Code. RESET 3 any Returns GPG_ERR_INV_ID. - 1 1 Verify CHV2 and set a new CHV1 and CHV2. - 1 2 Verify PW1 and set a new PW1. - 2 1 Verify CHV2 and set a new CHV1 and CHV2. - 2 2 Verify Reset Code and set a new PW1. - 3 any Verify CHV3/PW3 and set a new CHV3/PW3. The CHVNO can be prefixed with "OPENPGP.". */ static gpg_error_t do_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, unsigned int flags, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { int rc = 0; int chvno; char *resetcode = NULL; char *oldpinvalue = NULL; char *pinvalue = NULL; int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET); int set_resetcode = 0; pininfo_t pininfo; int use_pinpad = 0; int minlen = 6; int pinlen0 = 0; int pinlen = 0; (void)ctrl; if (digitp (chvnostr)) chvno = atoi (chvnostr); else if (!ascii_strcasecmp (chvnostr, "OPENPGP.1")) chvno = 1; else if (!ascii_strcasecmp (chvnostr, "OPENPGP.2")) chvno = 2; else if (!ascii_strcasecmp (chvnostr, "OPENPGP.3")) chvno = 3; else return gpg_error (GPG_ERR_INV_ID); memset (&pininfo, 0, sizeof pininfo); pininfo.fixedlen = -1; pininfo.minlen = minlen; if ((flags & APP_CHANGE_FLAG_CLEAR)) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); if (reset_mode && chvno == 3) { rc = gpg_error (GPG_ERR_INV_ID); goto leave; } if (!app->app_local->extcap.is_v2) { /* Version 1 cards. */ if (reset_mode || chvno == 3) { /* We always require that the PIN is entered. */ app->did_chv3 = 0; rc = verify_chv3 (app, pincb, pincb_arg); if (rc) goto leave; } else if (chvno == 1 || chvno == 2) { /* On a v1.x card CHV1 and CVH2 should always have the same value, thus we enforce it here. */ int save_force = app->force_chv1; app->force_chv1 = 0; app->did_chv1 = 0; app->did_chv2 = 0; rc = verify_chv2 (app, pincb, pincb_arg); app->force_chv1 = save_force; if (rc) goto leave; } else { rc = gpg_error (GPG_ERR_INV_ID); goto leave; } } else { /* Version 2 cards. */ if (!opt.disable_pinpad && !iso7816_check_pinpad (app->slot, ISO7816_CHANGE_REFERENCE_DATA, &pininfo) && !check_pinpad_request (app, &pininfo, chvno == 3)) use_pinpad = 1; if (reset_mode) { /* To reset a PIN the Admin PIN is required. */ use_pinpad = 0; app->did_chv3 = 0; rc = verify_chv3 (app, pincb, pincb_arg); if (rc) goto leave; if (chvno == 2) set_resetcode = 1; } else if (chvno == 1 || chvno == 3) { if (!use_pinpad) { char *promptbuf = NULL; const char *prompt; if (chvno == 3) { minlen = 8; rc = build_enter_admin_pin_prompt (app, &promptbuf); if (rc) goto leave; prompt = promptbuf; } else prompt = _("||Please enter the PIN"); rc = pincb (pincb_arg, prompt, &oldpinvalue); xfree (promptbuf); promptbuf = NULL; if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); goto leave; } if (strlen (oldpinvalue) < minlen) { log_info (_("PIN for CHV%d is too short;" " minimum length is %d\n"), chvno, minlen); rc = gpg_error (GPG_ERR_BAD_PIN); goto leave; } } } else if (chvno == 2) { /* There is no PW2 for v2 cards. We use this condition to allow a PW reset using the Reset Code. */ void *relptr; unsigned char *value; size_t valuelen; int remaining; use_pinpad = 0; minlen = 8; relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL); if (!relptr || valuelen < 7) { log_error (_("error retrieving CHV status from card\n")); xfree (relptr); rc = gpg_error (GPG_ERR_CARD); goto leave; } remaining = value[5]; xfree (relptr); if (!remaining) { log_error (_("Reset Code not or not anymore available\n")); rc = gpg_error (GPG_ERR_BAD_PIN); goto leave; } rc = pincb (pincb_arg, _("||Please enter the Reset Code for the card"), &resetcode); if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); goto leave; } if (strlen (resetcode) < minlen) { log_info (_("Reset Code is too short; minimum length is %d\n"), minlen); rc = gpg_error (GPG_ERR_BAD_PIN); goto leave; } } else { rc = gpg_error (GPG_ERR_INV_ID); goto leave; } } if (chvno == 3) app->did_chv3 = 0; else app->did_chv1 = app->did_chv2 = 0; if (!use_pinpad) { /* TRANSLATORS: Do not translate the "|*|" prefixes but keep it at the start of the string. We need this elsewhere to get some infos on the string. */ rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") : chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"), &pinvalue); if (rc || pinvalue == NULL) { log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc)); goto leave; } } if (resetcode) { char *buffer; buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1); if (!buffer) rc = gpg_error_from_syserror (); else { strcpy (buffer, resetcode); rc = pin2hash_if_kdf (app, 0, buffer, &pinlen0); if (!rc) { strcpy (buffer+pinlen0, pinvalue); rc = pin2hash_if_kdf (app, 0, buffer+pinlen0, &pinlen); } if (!rc) rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81, buffer, pinlen0+pinlen); wipememory (buffer, pinlen0 + pinlen); xfree (buffer); } } else if (set_resetcode) { if (strlen (pinvalue) < 8) { log_error (_("Reset Code is too short; minimum length is %d\n"), 8); rc = gpg_error (GPG_ERR_BAD_PIN); } else { rc = pin2hash_if_kdf (app, 0, pinvalue, &pinlen); if (!rc) rc = iso7816_put_data (app->slot, 0, 0xD3, pinvalue, pinlen); } } else if (reset_mode) { rc = pin2hash_if_kdf (app, 1, pinvalue, &pinlen); if (!rc) rc = iso7816_reset_retry_counter (app->slot, 0x81, pinvalue, pinlen); if (!rc && !app->app_local->extcap.is_v2) rc = iso7816_reset_retry_counter (app->slot, 0x82, pinvalue, pinlen); } else if (!app->app_local->extcap.is_v2) { /* Version 1 cards. */ if (chvno == 1 || chvno == 2) { rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0, pinvalue, strlen (pinvalue)); if (!rc) rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0, pinvalue, strlen (pinvalue)); } else /* CHVNO == 3 */ { rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0, pinvalue, strlen (pinvalue)); } } else { /* Version 2 cards. */ assert (chvno == 1 || chvno == 3); if (use_pinpad) { rc = pincb (pincb_arg, chvno == 3 ? _("||Please enter the Admin PIN and New Admin PIN") : _("||Please enter the PIN and New PIN"), NULL); if (rc) { log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc)); goto leave; } rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0, &pininfo); pincb (pincb_arg, NULL, NULL); /* Dismiss the prompt. */ } else { rc = pin2hash_if_kdf (app, chvno, oldpinvalue, &pinlen0); if (!rc) rc = pin2hash_if_kdf (app, chvno, pinvalue, &pinlen); if (!rc) rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, oldpinvalue, pinlen0, pinvalue, pinlen); } } if (pinvalue) { wipememory (pinvalue, pinlen); xfree (pinvalue); } if (rc) flush_cache_after_error (app); leave: if (resetcode) { wipememory (resetcode, strlen (resetcode)); xfree (resetcode); } if (oldpinvalue) { wipememory (oldpinvalue, pinlen0); xfree (oldpinvalue); } return rc; } /* Check whether a key already exists. KEYIDX is the index of the key (0..2). If FORCE is TRUE a diagnositic will be printed but no error returned if the key already exists. The flag GENERATING is only used to print correct messages. */ static gpg_error_t does_key_exist (app_t app, int keyidx, int generating, int force) { const unsigned char *fpr; unsigned char *buffer; size_t buflen, n; int i; assert (keyidx >=0 && keyidx <= 2); if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen)) { log_error (_("error reading application data\n")); return gpg_error (GPG_ERR_GENERAL); } fpr = find_tlv (buffer, buflen, 0x00C5, &n); if (!fpr || n < 60) { log_error (_("error reading fingerprint DO\n")); xfree (buffer); return gpg_error (GPG_ERR_GENERAL); } fpr += 20*keyidx; for (i=0; i < 20 && !fpr[i]; i++) ; xfree (buffer); if (i!=20 && !force) { log_error (_("key already exists\n")); return gpg_error (GPG_ERR_EEXIST); } else if (i!=20) log_info (_("existing key will be replaced\n")); else if (generating) log_info (_("generating new key\n")); else log_info (_("writing new key\n")); return 0; } /* Create a TLV tag and value and store it at BUFFER. Return the length of tag and length. A LENGTH greater than 65535 is truncated. */ static size_t add_tlv (unsigned char *buffer, unsigned int tag, size_t length) { unsigned char *p = buffer; assert (tag <= 0xffff); if ( tag > 0xff ) *p++ = tag >> 8; *p++ = tag; if (length < 128) *p++ = length; else if (length < 256) { *p++ = 0x81; *p++ = length; } else { if (length > 0xffff) length = 0xffff; *p++ = 0x82; *p++ = length >> 8; *p++ = length; } return p - buffer; } static gpg_error_t build_privkey_template (app_t app, int keyno, const unsigned char *rsa_n, size_t rsa_n_len, const unsigned char *rsa_e, size_t rsa_e_len, const unsigned char *rsa_p, size_t rsa_p_len, const unsigned char *rsa_q, size_t rsa_q_len, const unsigned char *rsa_u, size_t rsa_u_len, const unsigned char *rsa_dp, size_t rsa_dp_len, const unsigned char *rsa_dq, size_t rsa_dq_len, unsigned char **result, size_t *resultlen) { size_t rsa_e_reqlen; unsigned char privkey[7*(1+3+3)]; size_t privkey_len; unsigned char exthdr[2+2+3]; size_t exthdr_len; unsigned char suffix[2+3]; size_t suffix_len; unsigned char *tp; size_t datalen; unsigned char *template; size_t template_size; *result = NULL; *resultlen = 0; switch (app->app_local->keyattr[keyno].rsa.format) { case RSA_STD: case RSA_STD_N: case RSA_CRT: case RSA_CRT_N: break; default: return gpg_error (GPG_ERR_INV_VALUE); } /* Get the required length for E. Rounded up to the nearest byte */ rsa_e_reqlen = (app->app_local->keyattr[keyno].rsa.e_bits + 7) / 8; assert (rsa_e_len <= rsa_e_reqlen); /* Build the 7f48 cardholder private key template. */ datalen = 0; tp = privkey; tp += add_tlv (tp, 0x91, rsa_e_reqlen); datalen += rsa_e_reqlen; tp += add_tlv (tp, 0x92, rsa_p_len); datalen += rsa_p_len; tp += add_tlv (tp, 0x93, rsa_q_len); datalen += rsa_q_len; if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N) { tp += add_tlv (tp, 0x94, rsa_u_len); datalen += rsa_u_len; tp += add_tlv (tp, 0x95, rsa_dp_len); datalen += rsa_dp_len; tp += add_tlv (tp, 0x96, rsa_dq_len); datalen += rsa_dq_len; } if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N) { tp += add_tlv (tp, 0x97, rsa_n_len); datalen += rsa_n_len; } privkey_len = tp - privkey; /* Build the extended header list without the private key template. */ tp = exthdr; *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4; *tp++ = 0; tp += add_tlv (tp, 0x7f48, privkey_len); exthdr_len = tp - exthdr; /* Build the 5f48 suffix of the data. */ tp = suffix; tp += add_tlv (tp, 0x5f48, datalen); suffix_len = tp - suffix; /* Now concatenate everything. */ template_size = (1 + 3 /* 0x4d and len. */ + exthdr_len + privkey_len + suffix_len + datalen); tp = template = xtrymalloc_secure (template_size); if (!template) return gpg_error_from_syserror (); tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen); memcpy (tp, exthdr, exthdr_len); tp += exthdr_len; memcpy (tp, privkey, privkey_len); tp += privkey_len; memcpy (tp, suffix, suffix_len); tp += suffix_len; memcpy (tp, rsa_e, rsa_e_len); if (rsa_e_len < rsa_e_reqlen) { /* Right justify E. */ memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len); memset (tp, 0, rsa_e_reqlen - rsa_e_len); } tp += rsa_e_reqlen; memcpy (tp, rsa_p, rsa_p_len); tp += rsa_p_len; memcpy (tp, rsa_q, rsa_q_len); tp += rsa_q_len; if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N) { memcpy (tp, rsa_u, rsa_u_len); tp += rsa_u_len; memcpy (tp, rsa_dp, rsa_dp_len); tp += rsa_dp_len; memcpy (tp, rsa_dq, rsa_dq_len); tp += rsa_dq_len; } if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N) { memcpy (tp, rsa_n, rsa_n_len); tp += rsa_n_len; } /* Sanity check. We don't know the exact length because we allocated 3 bytes for the first length header. */ assert (tp - template <= template_size); *result = template; *resultlen = tp - template; return 0; } static gpg_error_t build_ecc_privkey_template (app_t app, int keyno, const unsigned char *ecc_d, size_t ecc_d_len, const unsigned char *ecc_q, size_t ecc_q_len, unsigned char **result, size_t *resultlen) { unsigned char privkey[2+2]; size_t privkey_len; unsigned char exthdr[2+2+1]; size_t exthdr_len; unsigned char suffix[2+1]; size_t suffix_len; unsigned char *tp; size_t datalen; unsigned char *template; size_t template_size; int pubkey_required; pubkey_required = !!(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_PUBKEY); *result = NULL; *resultlen = 0; /* Build the 7f48 cardholder private key template. */ datalen = 0; tp = privkey; tp += add_tlv (tp, 0x92, ecc_d_len); datalen += ecc_d_len; if (pubkey_required) { tp += add_tlv (tp, 0x99, ecc_q_len); datalen += ecc_q_len; } privkey_len = tp - privkey; /* Build the extended header list without the private key template. */ tp = exthdr; *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4; *tp++ = 0; tp += add_tlv (tp, 0x7f48, privkey_len); exthdr_len = tp - exthdr; /* Build the 5f48 suffix of the data. */ tp = suffix; tp += add_tlv (tp, 0x5f48, datalen); suffix_len = tp - suffix; /* Now concatenate everything. */ template_size = (1 + 1 /* 0x4d and len. */ + exthdr_len + privkey_len + suffix_len + datalen); if (exthdr_len + privkey_len + suffix_len + datalen >= 128) template_size++; tp = template = xtrymalloc_secure (template_size); if (!template) return gpg_error_from_syserror (); tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen); memcpy (tp, exthdr, exthdr_len); tp += exthdr_len; memcpy (tp, privkey, privkey_len); tp += privkey_len; memcpy (tp, suffix, suffix_len); tp += suffix_len; memcpy (tp, ecc_d, ecc_d_len); tp += ecc_d_len; if (pubkey_required) { memcpy (tp, ecc_q, ecc_q_len); tp += ecc_q_len; } assert (tp - template == template_size); *result = template; *resultlen = tp - template; return 0; } /* Helper for do_writekley to change the size of a key. Not ethat this deletes the entire key without asking. */ static gpg_error_t change_keyattr (app_t app, int keyno, const unsigned char *buf, size_t buflen, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; assert (keyno >=0 && keyno <= 2); /* Prepare for storing the key. */ err = verify_chv3 (app, pincb, pincb_arg); if (err) return err; /* Change the attribute. */ err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buf, buflen); if (err) log_error ("error changing key attribute (key=%d)\n", keyno+1); else log_info ("key attribute changed (key=%d)\n", keyno+1); flush_cache (app); parse_algorithm_attribute (app, keyno); app->did_chv1 = 0; app->did_chv2 = 0; app->did_chv3 = 0; return err; } static gpg_error_t change_rsa_keyattr (app_t app, int keyno, unsigned int nbits, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err = 0; unsigned char *buf; size_t buflen; void *relptr; /* Read the current attributes into a buffer. */ relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL); if (!relptr) err = gpg_error (GPG_ERR_CARD); else if (buflen < 6) { /* Attributes too short. */ xfree (relptr); err = gpg_error (GPG_ERR_CARD); } else { /* If key attribute was RSA, we only change n_bits and don't touch anything else. Before we do so, we round up NBITS to a sensible way in the same way as gpg's key generation does it. This may help to sort out problems with a few bits too short keys. */ nbits = ((nbits + 31) / 32) * 32; buf[1] = (nbits >> 8); buf[2] = nbits; /* If it was not RSA, we need to fill other parts. */ if (buf[0] != PUBKEY_ALGO_RSA) { buf[0] = PUBKEY_ALGO_RSA; buf[3] = 0; buf[4] = 32; buf[5] = 0; buflen = 6; } err = change_keyattr (app, keyno, buf, buflen, pincb, pincb_arg); xfree (relptr); } return err; } /* Helper to process an setattr command for name KEY-ATTR. In (VALUE,VALUELEN), it expects following string: RSA: "--force rsa" ECC: "--force " */ static gpg_error_t change_keyattr_from_string (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *value, size_t valuelen) { gpg_error_t err = 0; char *string; int key, keyno, algo; int n = 0; /* VALUE is expected to be a string but not guaranteed to be terminated. Thus copy it to an allocated buffer first. */ string = xtrymalloc (valuelen+1); if (!string) return gpg_error_from_syserror (); memcpy (string, value, valuelen); string[valuelen] = 0; /* Because this function deletes the key we require the string "--force" in the data to make clear that something serious might happen. */ sscanf (string, "--force %d %d %n", &key, &algo, &n); if (n < 12) { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } keyno = key - 1; if (keyno < 0 || keyno > 2) err = gpg_error (GPG_ERR_INV_ID); else if (algo == PUBKEY_ALGO_RSA) { unsigned int nbits; errno = 0; nbits = strtoul (string+n+3, NULL, 10); if (errno) err = gpg_error (GPG_ERR_INV_DATA); else if (nbits < 1024) err = gpg_error (GPG_ERR_TOO_SHORT); else if (nbits > 4096) err = gpg_error (GPG_ERR_TOO_LARGE); else err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg); } else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA) { const char *oidstr; gcry_mpi_t oid; const unsigned char *oidbuf; size_t oid_len; oidstr = openpgp_curve_to_oid (string+n, NULL); if (!oidstr) { err = gpg_error (GPG_ERR_INV_DATA); goto leave; } err = openpgp_oid_from_str (oidstr, &oid); if (err) goto leave; oidbuf = gcry_mpi_get_opaque (oid, &n); oid_len = (n+7)/8; /* We have enough room at STRING. */ string[0] = algo; memcpy (string+1, oidbuf+1, oid_len-1); err = change_keyattr (app, keyno, string, oid_len, pincb, pincb_arg); gcry_mpi_release (oid); } else err = gpg_error (GPG_ERR_PUBKEY_ALGO); leave: xfree (string); return err; } static gpg_error_t rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, int keyno, const unsigned char *buf, size_t buflen, int depth) { gpg_error_t err; const unsigned char *tok; size_t toklen; int last_depth1, last_depth2; const unsigned char *rsa_n = NULL; const unsigned char *rsa_e = NULL; const unsigned char *rsa_p = NULL; const unsigned char *rsa_q = NULL; size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len; unsigned int nbits; unsigned int maxbits; unsigned char *template = NULL; unsigned char *tp; size_t template_len; unsigned char fprbuf[20]; u32 created_at = 0; if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA) { log_error (_("unsupported algorithm: %s"), "RSA"); err = gpg_error (GPG_ERR_INV_VALUE); goto leave; } last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) { err = gpg_error (GPG_ERR_UNKNOWN_SEXP); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && toklen == 1) { const unsigned char **mpi; size_t *mpi_len; switch (*tok) { case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break; case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break; case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break; case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break; default: mpi = NULL; mpi_len = NULL; break; } if (mpi && *mpi) { err = gpg_error (GPG_ERR_DUP_VALUE); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && mpi) { /* Strip off leading zero bytes and save. */ for (;toklen && !*tok; toklen--, tok++) ; *mpi = tok; *mpi_len = toklen; } } /* Skip until end of list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) goto leave; } /* Parse other attributes. */ last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) { err = gpg_error (GPG_ERR_UNKNOWN_SEXP); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen)) { if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen))) goto leave; if (tok) { for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9'; tok++, toklen--) created_at = created_at*10 + (*tok - '0'); } } /* Skip until end of list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) goto leave; } /* Check that we have all parameters and that they match the card description. */ if (!created_at) { log_error (_("creation timestamp missing\n")); err = gpg_error (GPG_ERR_INV_VALUE); goto leave; } maxbits = app->app_local->keyattr[keyno].rsa.n_bits; nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0; if (opt.verbose) log_info ("RSA modulus size is %u bits\n", nbits); if (nbits && nbits != maxbits && app->app_local->extcap.algo_attr_change) { /* Try to switch the key to a new length. */ err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg); if (!err) maxbits = app->app_local->keyattr[keyno].rsa.n_bits; } if (nbits != maxbits) { log_error (_("RSA modulus missing or not of size %d bits\n"), (int)maxbits); err = gpg_error (GPG_ERR_BAD_SECKEY); goto leave; } maxbits = app->app_local->keyattr[keyno].rsa.e_bits; if (maxbits > 32 && !app->app_local->extcap.is_v2) maxbits = 32; /* Our code for v1 does only support 32 bits. */ nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0; if (nbits < 2 || nbits > maxbits) { log_error (_("RSA public exponent missing or larger than %d bits\n"), (int)maxbits); err = gpg_error (GPG_ERR_BAD_SECKEY); goto leave; } maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2; nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0; if (nbits != maxbits) { log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", (int)maxbits); err = gpg_error (GPG_ERR_BAD_SECKEY); goto leave; } nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0; if (nbits != maxbits) { log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", (int)maxbits); err = gpg_error (GPG_ERR_BAD_SECKEY); goto leave; } /* We need to remove the cached public key. */ xfree (app->app_local->pk[keyno].key); app->app_local->pk[keyno].key = NULL; app->app_local->pk[keyno].keylen = 0; app->app_local->pk[keyno].read_done = 0; if (app->app_local->extcap.is_v2) { unsigned char *rsa_u, *rsa_dp, *rsa_dq; size_t rsa_u_len, rsa_dp_len, rsa_dq_len; gcry_mpi_t mpi_e, mpi_p, mpi_q; gcry_mpi_t mpi_u = gcry_mpi_snew (0); gcry_mpi_t mpi_dp = gcry_mpi_snew (0); gcry_mpi_t mpi_dq = gcry_mpi_snew (0); gcry_mpi_t mpi_tmp = gcry_mpi_snew (0); int exmode; /* Calculate the u, dp and dq components needed by RSA_CRT cards */ gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL); gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL); gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL); gcry_mpi_invm (mpi_u, mpi_q, mpi_p); gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1); gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp); gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1); gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp); gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u); gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp); gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq); gcry_mpi_release (mpi_e); gcry_mpi_release (mpi_p); gcry_mpi_release (mpi_q); gcry_mpi_release (mpi_u); gcry_mpi_release (mpi_dp); gcry_mpi_release (mpi_dq); gcry_mpi_release (mpi_tmp); /* Build the private key template as described in section 4.3.3.7 of the OpenPGP card specs version 2.0. */ err = build_privkey_template (app, keyno, rsa_n, rsa_n_len, rsa_e, rsa_e_len, rsa_p, rsa_p_len, rsa_q, rsa_q_len, rsa_u, rsa_u_len, rsa_dp, rsa_dp_len, rsa_dq, rsa_dq_len, &template, &template_len); xfree(rsa_u); xfree(rsa_dp); xfree(rsa_dq); if (err) goto leave; /* Prepare for storing the key. */ err = verify_chv3 (app, pincb, pincb_arg); if (err) goto leave; /* Store the key. */ if (app->app_local->cardcap.ext_lc_le && template_len > 254) exmode = 1; /* Use extended length w/o a limit. */ else if (app->app_local->cardcap.cmd_chaining && template_len > 254) exmode = -254; else exmode = 0; err = iso7816_put_data_odd (app->slot, exmode, 0x3fff, template, template_len); } else { /* Build the private key template as described in section 4.3.3.6 of the OpenPGP card specs version 1.1: 0xC0 public exponent 0xC1 prime p 0xC2 prime q */ assert (rsa_e_len <= 4); template_len = (1 + 1 + 4 + 1 + 1 + rsa_p_len + 1 + 1 + rsa_q_len); template = tp = xtrymalloc_secure (template_len); if (!template) { err = gpg_error_from_syserror (); goto leave; } *tp++ = 0xC0; *tp++ = 4; memcpy (tp, rsa_e, rsa_e_len); if (rsa_e_len < 4) { /* Right justify E. */ memmove (tp+4-rsa_e_len, tp, rsa_e_len); memset (tp, 0, 4-rsa_e_len); } tp += 4; *tp++ = 0xC1; *tp++ = rsa_p_len; memcpy (tp, rsa_p, rsa_p_len); tp += rsa_p_len; *tp++ = 0xC2; *tp++ = rsa_q_len; memcpy (tp, rsa_q, rsa_q_len); tp += rsa_q_len; assert (tp - template == template_len); /* Prepare for storing the key. */ err = verify_chv3 (app, pincb, pincb_arg); if (err) goto leave; /* Store the key. */ err = iso7816_put_data (app->slot, 0, (app->card_version > 0x0007? 0xE0:0xE9)+keyno, template, template_len); } if (err) { log_error (_("failed to store the key: %s\n"), gpg_strerror (err)); goto leave; } err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA, rsa_n, rsa_n_len, rsa_e, rsa_e_len); if (err) goto leave; leave: xfree (template); return err; } static gpg_error_t ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, int keyno, const unsigned char *buf, size_t buflen, int depth) { gpg_error_t err; const unsigned char *tok; size_t toklen; int last_depth1, last_depth2; const unsigned char *ecc_q = NULL; const unsigned char *ecc_d = NULL; size_t ecc_q_len, ecc_d_len; const char *curve = NULL; u32 created_at = 0; const char *oidstr; int flag_djb_tweak = 0; int algo; gcry_mpi_t oid = NULL; const unsigned char *oidbuf; unsigned int n; size_t oid_len; unsigned char fprbuf[20]; /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)): curve = "NIST P-256" */ /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)): curve = "secp256k1" */ /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)): curve = "Ed25519" */ last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) { err = gpg_error (GPG_ERR_UNKNOWN_SEXP); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && toklen == 5 && !memcmp (tok, "curve", 5)) { char *curve_name; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; curve_name = xtrymalloc (toklen+1); if (!curve_name) { err = gpg_error_from_syserror (); goto leave; } memcpy (curve_name, tok, toklen); curve_name[toklen] = 0; curve = openpgp_is_curve_supported (curve_name, NULL, NULL); xfree (curve_name); } else if (tok && toklen == 5 && !memcmp (tok, "flags", 5)) { if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok) { if ((toklen == 5 && !memcmp (tok, "eddsa", 5)) || (toklen == 9 && !memcmp (tok, "djb-tweak", 9))) flag_djb_tweak = 1; } } else if (tok && toklen == 1) { const unsigned char **buf2; size_t *buf2len; int native = flag_djb_tweak; switch (*tok) { case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break; case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; native = 0; break; default: buf2 = NULL; buf2len = NULL; break; } if (buf2 && *buf2) { err = gpg_error (GPG_ERR_DUP_VALUE); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && buf2) { if (!native) /* Strip off leading zero bytes and save. */ for (;toklen && !*tok; toklen--, tok++) ; *buf2 = tok; *buf2len = toklen; } } /* Skip until end of list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) goto leave; } /* Parse other attributes. */ last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) { err = gpg_error (GPG_ERR_UNKNOWN_SEXP); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen)) { if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen))) goto leave; if (tok) { for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9'; tok++, toklen--) created_at = created_at*10 + (*tok - '0'); } } /* Skip until end of list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) goto leave; } /* Check that we have all parameters and that they match the card description. */ if (!curve) { log_error (_("unsupported curve\n")); err = gpg_error (GPG_ERR_INV_VALUE); goto leave; } if (!created_at) { log_error (_("creation timestamp missing\n")); err = gpg_error (GPG_ERR_INV_VALUE); goto leave; } if (flag_djb_tweak && keyno != 1) algo = PUBKEY_ALGO_EDDSA; else if (keyno == 1) algo = PUBKEY_ALGO_ECDH; else algo = PUBKEY_ALGO_ECDSA; oidstr = openpgp_curve_to_oid (curve, NULL); err = openpgp_oid_from_str (oidstr, &oid); if (err) goto leave; oidbuf = gcry_mpi_get_opaque (oid, &n); if (!oidbuf) { err = gpg_error_from_syserror (); goto leave; } oid_len = (n+7)/8; if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC || app->app_local->keyattr[keyno].ecc.curve != curve || (flag_djb_tweak != (app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK))) { if (app->app_local->extcap.algo_attr_change) { unsigned char *keyattr; if (!oid_len) { err = gpg_error (GPG_ERR_INTERNAL); goto leave; } keyattr = xtrymalloc (oid_len); if (!keyattr) { err = gpg_error_from_syserror (); goto leave; } keyattr[0] = algo; memcpy (keyattr+1, oidbuf+1, oid_len-1); err = change_keyattr (app, keyno, keyattr, oid_len, pincb, pincb_arg); xfree (keyattr); if (err) goto leave; } else { log_error ("key attribute on card doesn't match\n"); err = gpg_error (GPG_ERR_INV_VALUE); goto leave; } } if (opt.verbose) log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len); /* We need to remove the cached public key. */ xfree (app->app_local->pk[keyno].key); app->app_local->pk[keyno].key = NULL; app->app_local->pk[keyno].keylen = 0; app->app_local->pk[keyno].read_done = 0; if (app->app_local->extcap.is_v2) { /* Build the private key template as described in section 4.3.3.7 of the OpenPGP card specs version 2.0. */ unsigned char *template; size_t template_len; int exmode; err = build_ecc_privkey_template (app, keyno, ecc_d, ecc_d_len, ecc_q, ecc_q_len, &template, &template_len); if (err) goto leave; /* Prepare for storing the key. */ err = verify_chv3 (app, pincb, pincb_arg); if (err) { xfree (template); goto leave; } /* Store the key. */ if (app->app_local->cardcap.ext_lc_le && template_len > 254) exmode = 1; /* Use extended length w/o a limit. */ else if (app->app_local->cardcap.cmd_chaining && template_len > 254) exmode = -254; else exmode = 0; err = iso7816_put_data_odd (app->slot, exmode, 0x3fff, template, template_len); xfree (template); } else err = gpg_error (GPG_ERR_NOT_SUPPORTED); if (err) { log_error (_("failed to store the key: %s\n"), gpg_strerror (err)); goto leave; } err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len, ecc_q, ecc_q_len, ecdh_params (curve), (size_t)4); leave: gcry_mpi_release (oid); return err; } /* Handle the WRITEKEY command for OpenPGP. This function expects a canonical encoded S-expression with the secret key in KEYDATA and its length (for assertions) in KEYDATALEN. KEYID needs to be the usual keyid which for OpenPGP is the string "OPENPGP.n" with n=1,2,3. Bit 0 of FLAGS indicates whether an existing key shall get overwritten. PINCB and PINCB_ARG are the usual arguments for the pinentry callback. */ static gpg_error_t do_writekey (app_t app, ctrl_t ctrl, const char *keyid, unsigned int flags, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *keydata, size_t keydatalen) { gpg_error_t err; int force = (flags & 1); int keyno; const unsigned char *buf, *tok; size_t buflen, toklen; int depth; (void)ctrl; if (!strcmp (keyid, "OPENPGP.1")) keyno = 0; else if (!strcmp (keyid, "OPENPGP.2")) keyno = 1; else if (!strcmp (keyid, "OPENPGP.3")) keyno = 2; else return gpg_error (GPG_ERR_INV_ID); err = does_key_exist (app, keyno, 0, force); if (err) return err; /* Parse the S-expression */ buf = keydata; buflen = keydatalen; depth = 0; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen)) { if (!tok) ; else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen)) log_info ("protected-private-key passed to writekey\n"); else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen)) log_info ("shadowed-private-key passed to writekey\n"); err = gpg_error (GPG_ERR_BAD_SECKEY); goto leave; } if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) goto leave; if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0) err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth); else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0) err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth); else { err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); goto leave; } leave: return err; } /* Handle the GENKEY command. */ static gpg_error_t do_genkey (app_t app, ctrl_t ctrl, const char *keynostr, const char *keytype, unsigned int flags, time_t createtime, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; char numbuf[30]; unsigned char *buffer = NULL; const unsigned char *keydata; size_t buflen, keydatalen; u32 created_at; int keyno = atoi (keynostr) - 1; int force = (flags & 1); time_t start_at; int exmode = 0; int le_value = 256; /* Use legacy value. */ (void)keytype; /* Ignored for OpenPGP cards. */ if (keyno < 0 || keyno > 2) return gpg_error (GPG_ERR_INV_ID); /* We flush the cache to increase the traffic before a key generation. This _might_ help a card to gather more entropy. */ flush_cache (app); /* Obviously we need to remove the cached public key. */ xfree (app->app_local->pk[keyno].key); app->app_local->pk[keyno].key = NULL; app->app_local->pk[keyno].keylen = 0; app->app_local->pk[keyno].read_done = 0; /* Check whether a key already exists. */ err = does_key_exist (app, keyno, 1, force); if (err) return err; if (app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA) { unsigned int keybits = app->app_local->keyattr[keyno].rsa.n_bits; /* Because we send the key parameter back via status lines we need to put a limit on the max. allowed keysize. 2048 bit will already lead to a 527 byte long status line and thus a 4096 bit key would exceed the Assuan line length limit. */ if (keybits > 4096) return gpg_error (GPG_ERR_TOO_LARGE); if (app->app_local->cardcap.ext_lc_le && keybits > RSA_SMALL_SIZE_KEY && app->app_local->keyattr[keyno].key_type == KEY_TYPE_RSA) { exmode = 1; /* Use extended length w/o a limit. */ le_value = determine_rsa_response (app, keyno); /* No need to check le_value because it comes from a 16 bit value and thus can't create an overflow on a 32 bit system. */ } } /* Prepare for key generation by verifying the Admin PIN. */ err = verify_chv3 (app, pincb, pincb_arg); if (err) return err; log_info (_("please wait while key is being generated ...\n")); start_at = time (NULL); err = iso7816_generate_keypair (app->slot, exmode, 0x80, 0, (keyno == 0? "\xB6" : keyno == 1? "\xB8" : "\xA4"), 2, le_value, &buffer, &buflen); if (err) { log_error (_("generating key failed\n")); return gpg_error (GPG_ERR_CARD); } { int nsecs = (int)(time (NULL) - start_at); log_info (ngettext("key generation completed (%d second)\n", "key generation completed (%d seconds)\n", nsecs), nsecs); } keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen); if (!keydata) { err = gpg_error (GPG_ERR_CARD); log_error (_("response does not contain the public key data\n")); goto leave; } created_at = (u32)(createtime? createtime : gnupg_get_time ()); sprintf (numbuf, "%u", created_at); send_status_info (ctrl, "KEY-CREATED-AT", numbuf, (size_t)strlen(numbuf), NULL, 0); err = read_public_key (app, ctrl, created_at, keyno, buffer, buflen); leave: xfree (buffer); return err; } static unsigned long convert_sig_counter_value (const unsigned char *value, size_t valuelen) { unsigned long ul; if (valuelen == 3 ) ul = (value[0] << 16) | (value[1] << 8) | value[2]; else { log_error (_("invalid structure of OpenPGP card (DO 0x93)\n")); ul = 0; } return ul; } static unsigned long get_sig_counter (app_t app) { void *relptr; unsigned char *value; size_t valuelen; unsigned long ul; relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL); if (!relptr) return 0; ul = convert_sig_counter_value (value, valuelen); xfree (relptr); return ul; } static gpg_error_t compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr) { const unsigned char *fpr; unsigned char *buffer; size_t buflen, n; int rc, i; assert (keyno >= 0 && keyno <= 2); rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0); if (rc) { log_error (_("error reading application data\n")); return gpg_error (GPG_ERR_GENERAL); } fpr = find_tlv (buffer, buflen, 0x00C5, &n); if (!fpr || n != 60) { xfree (buffer); log_error (_("error reading fingerprint DO\n")); return gpg_error (GPG_ERR_GENERAL); } fpr += keyno*20; for (i=0; i < 20; i++) if (sha1fpr[i] != fpr[i]) { xfree (buffer); log_info (_("fingerprint on card does not match requested one\n")); return gpg_error (GPG_ERR_WRONG_SECKEY); } xfree (buffer); return 0; } /* If a fingerprint has been specified check it against the one on the card. This allows for a meaningful error message in case the key on the card has been replaced but the shadow information known to gpg has not been updated. If there is no fingerprint we assume that this is okay. */ static gpg_error_t check_against_given_fingerprint (app_t app, const char *fpr, int key) { unsigned char tmp[20]; const char *s; int n; for (s=fpr, n=0; hexdigitp (s); s++, n++) ; if (n != 40) return gpg_error (GPG_ERR_INV_ID); else if (!*s) ; /* okay */ else return gpg_error (GPG_ERR_INV_ID); for (s=fpr, n=0; n < 20; s += 2, n++) tmp[n] = xtoi_2 (s); return compare_fingerprint (app, key-1, tmp); } /* Compute a digital signature on INDATA which is expected to be the raw message digest. For this application the KEYIDSTR consists of the serialnumber and the fingerprint delimited by a slash. Note that this function may return the error code GPG_ERR_WRONG_CARD to indicate that the card currently present does not match the one required for the requested action (e.g. the serial number does not match). As a special feature a KEYIDSTR of "OPENPGP.3" redirects the operation to the auth command. */ static gpg_error_t do_sign (app_t app, const char *keyidstr, int hashalgo, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen ) { 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 }; int rc; unsigned char data[19+64]; size_t datalen; unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */ const char *s; int n; const char *fpr = NULL; unsigned long sigcount; int use_auth = 0; int exmode, le_value; if (!keyidstr || !*keyidstr) return gpg_error (GPG_ERR_INV_VALUE); /* Strip off known prefixes. */ #define X(a,b,c,d) \ if (hashalgo == GCRY_MD_ ## a \ && (d) \ && indatalen == sizeof b ## _prefix + (c) \ && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \ { \ indata = (const char*)indata + sizeof b ## _prefix; \ indatalen -= sizeof b ## _prefix; \ } if (indatalen == 20) ; /* Assume a plain SHA-1 or RMD160 digest has been given. */ else X(SHA1, sha1, 20, 1) else X(RMD160, rmd160, 20, 1) else X(SHA224, sha224, 28, app->app_local->extcap.is_v2) else X(SHA256, sha256, 32, app->app_local->extcap.is_v2) else X(SHA384, sha384, 48, app->app_local->extcap.is_v2) else X(SHA512, sha512, 64, app->app_local->extcap.is_v2) else if ((indatalen == 28 || indatalen == 32 || indatalen == 48 || indatalen ==64) && app->app_local->extcap.is_v2) ; /* Assume a plain SHA-3 digest has been given. */ else { log_error (_("card does not support digest algorithm %s\n"), gcry_md_algo_name (hashalgo)); /* Or the supplied digest length does not match an algorithm. */ return gpg_error (GPG_ERR_INV_VALUE); } #undef X /* Check whether an OpenPGP card of any version has been requested. */ if (!strcmp (keyidstr, "OPENPGP.1")) ; else if (!strcmp (keyidstr, "OPENPGP.3")) use_auth = 1; else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12)) return gpg_error (GPG_ERR_INV_ID); else { for (s=keyidstr, n=0; hexdigitp (s); s++, n++) ; if (n != 32) return gpg_error (GPG_ERR_INV_ID); else if (!*s) ; /* no fingerprint given: we allow this for now. */ else if (*s == '/') fpr = s + 1; else return gpg_error (GPG_ERR_INV_ID); for (s=keyidstr, n=0; n < 16; s += 2, n++) tmp_sn[n] = xtoi_2 (s); if (app->serialnolen != 16) return gpg_error (GPG_ERR_INV_CARD); if (memcmp (app->serialno, tmp_sn, 16)) return gpg_error (GPG_ERR_WRONG_CARD); } /* If a fingerprint has been specified check it against the one on the card. This is allows for a meaningful error message in case the key on the card has been replaced but the shadow information known to gpg was not updated. If there is no fingerprint, gpg will detect a bogus signature anyway due to the verify-after-signing feature. */ rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0; if (rc) return rc; /* Concatenate prefix and digest. */ #define X(a,b,d) \ if (hashalgo == GCRY_MD_ ## a && (d) ) \ { \ datalen = sizeof b ## _prefix + indatalen; \ assert (datalen <= sizeof data); \ memcpy (data, b ## _prefix, sizeof b ## _prefix); \ memcpy (data + sizeof b ## _prefix, indata, indatalen); \ } if (use_auth || app->app_local->keyattr[use_auth? 2: 0].key_type == KEY_TYPE_RSA) { X(SHA1, sha1, 1) else X(RMD160, rmd160, 1) else X(SHA224, sha224, app->app_local->extcap.is_v2) else X(SHA256, sha256, app->app_local->extcap.is_v2) else X(SHA384, sha384, app->app_local->extcap.is_v2) else X(SHA512, sha512, app->app_local->extcap.is_v2) else return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); } else { datalen = indatalen; memcpy (data, indata, indatalen); } #undef X /* Redirect to the AUTH command if asked to. */ if (use_auth) { return do_auth (app, "OPENPGP.3", pincb, pincb_arg, data, datalen, outdata, outdatalen); } /* Show the number of signature done using this key. */ sigcount = get_sig_counter (app); log_info (_("signatures created so far: %lu\n"), sigcount); /* Check CHV if needed. */ if (!app->did_chv1 || app->force_chv1) { char *pinvalue; int pinlen; rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue, &pinlen); if (rc) return rc; app->did_chv1 = 1; /* For cards with versions < 2 we want to keep CHV1 and CHV2 in sync, thus we verify CHV2 here using the given PIN. Cards with version2 to not have the need for a separate CHV2 and internally use just one. Obviously we can't do that if the pinpad has been used. */ if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2) { rc = iso7816_verify (app->slot, 0x82, pinvalue, pinlen); if (gpg_err_code (rc) == GPG_ERR_BAD_PIN) rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED); if (rc) { log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc)); xfree (pinvalue); flush_cache_after_error (app); return rc; } app->did_chv2 = 1; } xfree (pinvalue); } if (app->app_local->cardcap.ext_lc_le && app->app_local->keyattr[0].key_type == KEY_TYPE_RSA && app->app_local->keyattr[0].rsa.n_bits > RSA_SMALL_SIZE_OP) { exmode = 1; /* Use extended length. */ le_value = app->app_local->keyattr[0].rsa.n_bits / 8; } else { exmode = 0; le_value = 0; } rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value, outdata, outdatalen); if (!rc && app->force_chv1) app->did_chv1 = 0; return rc; } /* Compute a digital signature using the INTERNAL AUTHENTICATE command on INDATA which is expected to be the raw message digest. For this application the KEYIDSTR consists of the serialnumber and the fingerprint delimited by a slash. Optionally the id OPENPGP.3 may be given. Note that this function may return the error code GPG_ERR_WRONG_CARD to indicate that the card currently present does not match the one required for the requested action (e.g. the serial number does not match). */ static gpg_error_t do_auth (app_t app, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen ) { int rc; unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */ const char *s; int n; const char *fpr = NULL; if (!keyidstr || !*keyidstr) return gpg_error (GPG_ERR_INV_VALUE); if (app->app_local->keyattr[2].key_type == KEY_TYPE_RSA && indatalen > 101) /* For a 2048 bit key. */ return gpg_error (GPG_ERR_INV_VALUE); if (app->app_local->keyattr[2].key_type == KEY_TYPE_ECC) { if (!(app->app_local->keyattr[2].ecc.flags & ECC_FLAG_DJB_TWEAK) && (indatalen == 51 || indatalen == 67 || indatalen == 83)) { const char *p = (const char *)indata + 19; indata = p; indatalen -= 19; } else { const char *p = (const char *)indata + 15; indata = p; indatalen -= 15; } } /* Check whether an OpenPGP card of any version has been requested. */ if (!strcmp (keyidstr, "OPENPGP.3")) ; else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12)) return gpg_error (GPG_ERR_INV_ID); else { for (s=keyidstr, n=0; hexdigitp (s); s++, n++) ; if (n != 32) return gpg_error (GPG_ERR_INV_ID); else if (!*s) ; /* no fingerprint given: we allow this for now. */ else if (*s == '/') fpr = s + 1; else return gpg_error (GPG_ERR_INV_ID); for (s=keyidstr, n=0; n < 16; s += 2, n++) tmp_sn[n] = xtoi_2 (s); if (app->serialnolen != 16) return gpg_error (GPG_ERR_INV_CARD); if (memcmp (app->serialno, tmp_sn, 16)) return gpg_error (GPG_ERR_WRONG_CARD); } /* If a fingerprint has been specified check it against the one on the card. This is allows for a meaningful error message in case the key on the card has been replaced but the shadow information known to gpg was not updated. If there is no fingerprint, gpg will detect a bogus signature anyway due to the verify-after-signing feature. */ rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0; if (rc) return rc; rc = verify_chv2 (app, pincb, pincb_arg); if (!rc) { int exmode, le_value; if (app->app_local->cardcap.ext_lc_le && app->app_local->keyattr[2].key_type == KEY_TYPE_RSA && app->app_local->keyattr[2].rsa.n_bits > RSA_SMALL_SIZE_OP) { exmode = 1; /* Use extended length. */ le_value = app->app_local->keyattr[2].rsa.n_bits / 8; } else { exmode = 0; le_value = 0; } rc = iso7816_internal_authenticate (app->slot, exmode, indata, indatalen, le_value, outdata, outdatalen); } return rc; } static gpg_error_t do_decipher (app_t app, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen, unsigned int *r_info) { int rc; unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */ const char *s; int n; const char *fpr = NULL; int exmode, le_value; unsigned char *fixbuf = NULL; int padind = 0; int fixuplen = 0; if (!keyidstr || !*keyidstr || !indatalen) return gpg_error (GPG_ERR_INV_VALUE); /* Check whether an OpenPGP card of any version has been requested. */ if (!strcmp (keyidstr, "OPENPGP.2")) ; else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12)) return gpg_error (GPG_ERR_INV_ID); else { for (s=keyidstr, n=0; hexdigitp (s); s++, n++) ; if (n != 32) return gpg_error (GPG_ERR_INV_ID); else if (!*s) ; /* no fingerprint given: we allow this for now. */ else if (*s == '/') fpr = s + 1; else return gpg_error (GPG_ERR_INV_ID); for (s=keyidstr, n=0; n < 16; s += 2, n++) tmp_sn[n] = xtoi_2 (s); if (app->serialnolen != 16) return gpg_error (GPG_ERR_INV_CARD); if (memcmp (app->serialno, tmp_sn, 16)) return gpg_error (GPG_ERR_WRONG_CARD); } /* If a fingerprint has been specified check it against the one on the card. This is allows for a meaningful error message in case the key on the card has been replaced but the shadow information known to gpg was not updated. If there is no fingerprint, the decryption won't produce the right plaintext anyway. */ rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0; if (rc) return rc; rc = verify_chv2 (app, pincb, pincb_arg); if (rc) return rc; if ((indatalen == 16 + 1 || indatalen == 32 + 1) && ((char *)indata)[0] == 0x02) { /* PSO:DECIPHER with symmetric key. */ padind = -1; } else if (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA) { /* We might encounter a couple of leading zeroes in the cryptogram. Due to internal use of MPIs these leading zeroes are stripped. However the OpenPGP card expects exactly 128 bytes for the cryptogram (for a 1k key). Thus we need to fix it up. We do this for up to 16 leading zero bytes; a cryptogram with more than this is with a very high probability anyway broken. If a signed conversion was used we may also encounter one leading zero followed by the correct length. We fix that as well. */ if (indatalen >= (128-16) && indatalen < 128) /* 1024 bit key. */ fixuplen = 128 - indatalen; else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key. */ fixuplen = 192 - indatalen; else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key. */ fixuplen = 256 - indatalen; else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key. */ fixuplen = 384 - indatalen; else if (indatalen >= (512-16) && indatalen < 512) /* 4096 bit key. */ fixuplen = 512 - indatalen; else if (!*(const char *)indata && (indatalen == 129 || indatalen == 193 || indatalen == 257 || indatalen == 385 || indatalen == 513)) fixuplen = -1; else fixuplen = 0; if (fixuplen > 0) { /* While we have to prepend stuff anyway, we can also include the padding byte here so that iso1816_decipher does not need to do another data mangling. */ fixuplen++; fixbuf = xtrymalloc (fixuplen + indatalen); if (!fixbuf) return gpg_error_from_syserror (); memset (fixbuf, 0, fixuplen); memcpy (fixbuf+fixuplen, indata, indatalen); indata = fixbuf; indatalen = fixuplen + indatalen; padind = -1; /* Already padded. */ } else if (fixuplen < 0) { /* We use the extra leading zero as the padding byte. */ padind = -1; } } else if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC) { int old_format_len = 0; if ((app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK)) { if (indatalen > 32 && (indatalen % 2)) { /* * Skip the prefix. It may be 0x40 (in new format), or MPI * head of 0x00 (in old format). */ indata = (const char *)indata + 1; indatalen--; } else if (indatalen < 32) { /* * Old format trancated by MPI handling. */ old_format_len = indatalen; indatalen = 32; } } n = 0; if (indatalen < 128) fixuplen = 7; else fixuplen = 10; fixbuf = xtrymalloc (fixuplen + indatalen); if (!fixbuf) return gpg_error_from_syserror (); /* Build 'Cipher DO' */ fixbuf[n++] = '\xa6'; if (indatalen < 128) fixbuf[n++] = (char)(indatalen+5); else { fixbuf[n++] = 0x81; fixbuf[n++] = (char)(indatalen+7); } fixbuf[n++] = '\x7f'; fixbuf[n++] = '\x49'; if (indatalen < 128) fixbuf[n++] = (char)(indatalen+2); else { fixbuf[n++] = 0x81; fixbuf[n++] = (char)(indatalen+3); } fixbuf[n++] = '\x86'; if (indatalen < 128) fixbuf[n++] = (char)indatalen; else { fixbuf[n++] = 0x81; fixbuf[n++] = (char)indatalen; } if (old_format_len) { memset (fixbuf+fixuplen, 0, 32 - old_format_len); memcpy (fixbuf+fixuplen + 32 - old_format_len, indata, old_format_len); } else { memcpy (fixbuf+fixuplen, indata, indatalen); } indata = fixbuf; indatalen = fixuplen + indatalen; padind = -1; } else return gpg_error (GPG_ERR_INV_VALUE); if (app->app_local->cardcap.ext_lc_le && (indatalen > 254 || (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA && app->app_local->keyattr[1].rsa.n_bits > RSA_SMALL_SIZE_OP))) { exmode = 1; /* Extended length w/o a limit. */ le_value = app->app_local->keyattr[1].rsa.n_bits / 8; } else if (app->app_local->cardcap.cmd_chaining && indatalen > 254) { exmode = -254; /* Command chaining with max. 254 bytes. */ le_value = 0; } else exmode = le_value = 0; rc = iso7816_decipher (app->slot, exmode, indata, indatalen, le_value, padind, outdata, outdatalen); xfree (fixbuf); if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC) { unsigned char prefix = 0; if (app->app_local->keyattr[1].ecc.flags & ECC_FLAG_DJB_TWEAK) prefix = 0x40; else if ((*outdatalen % 2) == 0) /* No 0x04 -> x-coordinate only */ prefix = 0x41; if (prefix) { /* Add the prefix */ fixbuf = xtrymalloc (*outdatalen + 1); if (!fixbuf) { xfree (*outdata); return gpg_error_from_syserror (); } fixbuf[0] = prefix; memcpy (fixbuf+1, *outdata, *outdatalen); xfree (*outdata); *outdata = fixbuf; *outdatalen = *outdatalen + 1; } } if (gpg_err_code (rc) == GPG_ERR_CARD /* actual SW is 0x640a */ && app->app_local->manufacturer == 5 && app->card_version == 0x0200) log_info ("NOTE: Cards with manufacturer id 5 and s/n <= 346 (0x15a)" " do not work with encryption keys > 2048 bits\n"); *r_info |= APP_DECIPHER_INFO_NOPAD; return rc; } /* Perform a simple verify operation for CHV1 and CHV2, so that further operations won't ask for CHV2 and it is possible to do a cheap check on the PIN: If there is something wrong with the PIN entry system, only the regular CHV will get blocked and not the dangerous CHV3. KEYIDSTR is the usual card's serial number; an optional fingerprint part will be ignored. There is a special mode if the keyidstr is "[CHV3]" with the "[CHV3]" being a literal string: The Admin Pin is checked if and only if the retry counter is still at 3. */ static gpg_error_t do_check_pin (app_t app, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { unsigned char tmp_sn[20]; const char *s; int n; int admin_pin = 0; if (!keyidstr || !*keyidstr) return gpg_error (GPG_ERR_INV_VALUE); /* Check whether an OpenPGP card of any version has been requested. */ if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12)) return gpg_error (GPG_ERR_INV_ID); for (s=keyidstr, n=0; hexdigitp (s); s++, n++) ; if (n != 32) return gpg_error (GPG_ERR_INV_ID); else if (!*s) ; /* No fingerprint given: we allow this for now. */ else if (*s == '/') ; /* We ignore a fingerprint. */ else if (!strcmp (s, "[CHV3]") ) admin_pin = 1; else return gpg_error (GPG_ERR_INV_ID); for (s=keyidstr, n=0; n < 16; s += 2, n++) tmp_sn[n] = xtoi_2 (s); if (app->serialnolen != 16) return gpg_error (GPG_ERR_INV_CARD); if (memcmp (app->serialno, tmp_sn, 16)) return gpg_error (GPG_ERR_WRONG_CARD); /* Yes, there is a race conditions: The user might pull the card right here and we won't notice that. However this is not a problem and the check above is merely for a graceful failure between operations. */ if (admin_pin) { void *relptr; unsigned char *value; size_t valuelen; int count; relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL); if (!relptr || valuelen < 7) { log_error (_("error retrieving CHV status from card\n")); xfree (relptr); return gpg_error (GPG_ERR_CARD); } count = value[6]; xfree (relptr); if (!count) { log_info (_("card is permanently locked!\n")); return gpg_error (GPG_ERR_BAD_PIN); } else if (count < 3) { log_info (_("verification of Admin PIN is currently prohibited " "through this command\n")); return gpg_error (GPG_ERR_GENERAL); } app->did_chv3 = 0; /* Force verification. */ return verify_chv3 (app, pincb, pincb_arg); } else return verify_chv2 (app, pincb, pincb_arg); } /* Show information about card capabilities. */ static void show_caps (struct app_local_s *s) { log_info ("Version-2+ .....: %s\n", s->extcap.is_v2? "yes":"no"); log_info ("Extcap-v3 ......: %s\n", s->extcap.extcap_v3? "yes":"no"); log_info ("Button .........: %s\n", s->extcap.has_button? "yes":"no"); log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no"); if (s->extcap.sm_supported) log_printf (" (%s)", s->extcap.sm_algo==2? "3DES": (s->extcap.sm_algo==2? "AES-128" : "AES-256")); log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no"); if (s->extcap.get_challenge) log_printf (" (%u bytes max)", s->extcap.max_get_challenge); log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no"); log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no"); log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no"); log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no"); log_info ("Symmetric Crypto: %s\n", s->extcap.has_decrypt? "yes":"no"); log_info ("KDF-Support ....: %s\n", s->extcap.kdf_do? "yes":"no"); log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3); if (s->extcap.extcap_v3) { log_info ("PIN-Block-2 ....: %s\n", s->extcap.pin_blk2? "yes":"no"); log_info ("MSE-Support ....: %s\n", s->extcap.mse? "yes":"no"); log_info ("Max-Special-DOs : %u\n", s->extcap.max_special_do); } log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no"); log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no"); log_info ("Status-Indicator: %02X\n", s->status_indicator); log_info ("GnuPG-No-Sync ..: %s\n", s->flags.no_sync? "yes":"no"); log_info ("GnuPG-Def-PW2 ..: %s\n", s->flags.def_chv2? "yes":"no"); } /* Parse the historical bytes in BUFFER of BUFLEN and store them in APPLOC. */ static void parse_historical (struct app_local_s *apploc, const unsigned char * buffer, size_t buflen) { /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00 */ if (buflen < 4) { log_error ("warning: historical bytes are too short\n"); return; /* Too short. */ } if (*buffer) { log_error ("warning: bad category indicator in historical bytes\n"); return; } /* Skip category indicator. */ buffer++; buflen--; /* Get the status indicator. */ apploc->status_indicator = buffer[buflen-3]; buflen -= 3; /* Parse the compact TLV. */ while (buflen) { unsigned int tag = (*buffer & 0xf0) >> 4; unsigned int len = (*buffer & 0x0f); if (len+1 > buflen) { log_error ("warning: bad Compact-TLV in historical bytes\n"); return; /* Error. */ } buffer++; buflen--; if (tag == 7 && len == 3) { /* Card capabilities. */ apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80); apploc->cardcap.ext_lc_le = !!(buffer[2] & 0x40); } buffer += len; buflen -= len; } } /* * Check if the OID in an DER encoding is available by GnuPG/libgcrypt, * and return the curve name. Return NULL if not available. * The constant string is not allocated dynamically, never free it. */ static const char * ecc_curve (unsigned char *buf, size_t buflen) { gcry_mpi_t oid; char *oidstr; const char *result; unsigned char *oidbuf; oidbuf = xtrymalloc (buflen + 1); if (!oidbuf) return NULL; memcpy (oidbuf+1, buf, buflen); oidbuf[0] = buflen; oid = gcry_mpi_set_opaque (NULL, oidbuf, (buflen+1) * 8); if (!oid) { xfree (oidbuf); return NULL; } oidstr = openpgp_oid_to_str (oid); gcry_mpi_release (oid); if (!oidstr) return NULL; result = openpgp_oid_to_curve (oidstr, 1); xfree (oidstr); return result; } /* Parse and optionally show the algorithm attributes for KEYNO. KEYNO must be in the range 0..2. */ static void parse_algorithm_attribute (app_t app, int keyno) { unsigned char *buffer; size_t buflen; void *relptr; const char desc[3][5] = {"sign", "encr", "auth"}; assert (keyno >=0 && keyno <= 2); app->app_local->keyattr[keyno].key_type = KEY_TYPE_RSA; app->app_local->keyattr[keyno].rsa.n_bits = 0; relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL); if (!relptr) { log_error ("error reading DO 0x%02X\n", 0xc1+keyno); return; } if (buflen < 1) { log_error ("error reading DO 0x%02X\n", 0xc1+keyno); xfree (relptr); return; } if (opt.verbose) log_info ("Key-Attr-%s ..: ", desc[keyno]); if (*buffer == PUBKEY_ALGO_RSA && (buflen == 5 || buflen == 6)) { app->app_local->keyattr[keyno].rsa.n_bits = (buffer[1]<<8 | buffer[2]); app->app_local->keyattr[keyno].rsa.e_bits = (buffer[3]<<8 | buffer[4]); app->app_local->keyattr[keyno].rsa.format = 0; if (buflen < 6) app->app_local->keyattr[keyno].rsa.format = RSA_STD; else app->app_local->keyattr[keyno].rsa.format = (buffer[5] == 0? RSA_STD : buffer[5] == 1? RSA_STD_N : buffer[5] == 2? RSA_CRT : buffer[5] == 3? RSA_CRT_N : RSA_UNKNOWN_FMT); if (opt.verbose) log_printf ("RSA, n=%u, e=%u, fmt=%s\n", app->app_local->keyattr[keyno].rsa.n_bits, app->app_local->keyattr[keyno].rsa.e_bits, app->app_local->keyattr[keyno].rsa.format == RSA_STD? "std" : app->app_local->keyattr[keyno].rsa.format == RSA_STD_N?"std+n": app->app_local->keyattr[keyno].rsa.format == RSA_CRT? "crt" : app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N?"crt+n":"?"); } else if (*buffer == PUBKEY_ALGO_ECDH || *buffer == PUBKEY_ALGO_ECDSA || *buffer == PUBKEY_ALGO_EDDSA) { const char *curve; int oidlen = buflen - 1; app->app_local->keyattr[keyno].ecc.flags = 0; if (buffer[buflen-1] == 0x00 || buffer[buflen-1] == 0xff) { /* Found "pubkey required"-byte for private key template. */ oidlen--; if (buffer[buflen-1] == 0xff) app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_PUBKEY; } curve = ecc_curve (buffer + 1, oidlen); if (!curve) log_printhex ("Curve with OID not supported: ", buffer+1, buflen-1); else { app->app_local->keyattr[keyno].key_type = KEY_TYPE_ECC; app->app_local->keyattr[keyno].ecc.curve = curve; if (*buffer == PUBKEY_ALGO_EDDSA || (*buffer == PUBKEY_ALGO_ECDH && !strcmp (app->app_local->keyattr[keyno].ecc.curve, "Curve25519"))) app->app_local->keyattr[keyno].ecc.flags |= ECC_FLAG_DJB_TWEAK; if (opt.verbose) log_printf ("ECC, curve=%s%s\n", app->app_local->keyattr[keyno].ecc.curve, !(app->app_local->keyattr[keyno].ecc.flags & ECC_FLAG_DJB_TWEAK)? "": keyno==1? " (djb-tweak)": " (eddsa)"); } } else if (opt.verbose) log_printhex ("", buffer, buflen); xfree (relptr); } /* Select the OpenPGP application on the card in SLOT. This function must be used before any other OpenPGP application functions. */ gpg_error_t app_select_openpgp (app_t app) { static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 }; int slot = app->slot; int rc; unsigned char *buffer; size_t buflen; void *relptr; /* Note that the card can't cope with P2=0xCO, thus we need to pass a special flag value. */ rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001); if (!rc) { unsigned int manufacturer; app->apptype = "OPENPGP"; app->did_chv1 = 0; app->did_chv2 = 0; app->did_chv3 = 0; app->app_local = NULL; /* The OpenPGP card returns the serial number as part of the AID; because we prefer to use OpenPGP serial numbers, we replace a possibly already set one from a EF.GDO with this one. Note, that for current OpenPGP cards, no EF.GDO exists and thus it won't matter at all. */ rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen); if (rc) goto leave; if (opt.verbose) { log_info ("AID: "); log_printhex ("", buffer, buflen); } app->card_version = buffer[6] << 8; app->card_version |= buffer[7]; manufacturer = (buffer[8]<<8 | buffer[9]); xfree (app->serialno); app->serialno = buffer; app->serialnolen = buflen; buffer = NULL; app->app_local = xtrycalloc (1, sizeof *app->app_local); if (!app->app_local) { rc = gpg_error (gpg_err_code_from_errno (errno)); goto leave; } app->app_local->manufacturer = manufacturer; if (app->card_version >= 0x0200) app->app_local->extcap.is_v2 = 1; if (app->card_version >= 0x0300) app->app_local->extcap.extcap_v3 = 1; /* Read the historical bytes. */ relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL); if (relptr) { if (opt.verbose) { log_info ("Historical Bytes: "); log_printhex ("", buffer, buflen); } parse_historical (app->app_local, buffer, buflen); xfree (relptr); } /* Read the force-chv1 flag. */ relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL); if (!relptr) { log_error (_("can't access %s - invalid OpenPGP card?\n"), "CHV Status Bytes"); goto leave; } app->force_chv1 = (buflen && *buffer == 0); xfree (relptr); /* Read the extended capabilities. */ relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL); if (!relptr) { log_error (_("can't access %s - invalid OpenPGP card?\n"), "Extended Capability Flags" ); goto leave; } if (buflen) { app->app_local->extcap.sm_supported = !!(*buffer & 0x80); app->app_local->extcap.get_challenge = !!(*buffer & 0x40); app->app_local->extcap.key_import = !!(*buffer & 0x20); app->app_local->extcap.change_force_chv = !!(*buffer & 0x10); app->app_local->extcap.private_dos = !!(*buffer & 0x08); app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04); app->app_local->extcap.has_decrypt = !!(*buffer & 0x02); app->app_local->extcap.kdf_do = !!(*buffer & 0x01); } if (buflen >= 10) { /* Available with cards of v2 or later. */ app->app_local->extcap.sm_algo = buffer[1]; app->app_local->extcap.max_get_challenge = (buffer[2] << 8 | buffer[3]); app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]); /* Interpretation is different between v2 and v3, unfortunately. */ if (app->app_local->extcap.extcap_v3) { app->app_local->extcap.max_special_do = (buffer[6] << 8 | buffer[7]); app->app_local->extcap.pin_blk2 = !!(buffer[8] & 0x01); app->app_local->extcap.mse= !!(buffer[9] & 0x01); } } xfree (relptr); /* Some of the first cards accidentally don't set the CHANGE_FORCE_CHV bit but allow it anyway. */ if (app->card_version <= 0x0100 && manufacturer == 1) app->app_local->extcap.change_force_chv = 1; /* Check optional DO of "General Feature Management" for button. */ relptr = get_one_do (app, 0x7f74, &buffer, &buflen, NULL); if (relptr) /* It must be: 03 81 01 20 */ app->app_local->extcap.has_button = 1; parse_login_data (app); if (opt.verbose) show_caps (app->app_local); parse_algorithm_attribute (app, 0); parse_algorithm_attribute (app, 1); parse_algorithm_attribute (app, 2); if (opt.verbose > 1) dump_all_do (slot); app->fnc.deinit = do_deinit; app->fnc.learn_status = do_learn_status; app->fnc.readcert = do_readcert; app->fnc.readkey = do_readkey; app->fnc.getattr = do_getattr; app->fnc.setattr = do_setattr; app->fnc.writecert = do_writecert; app->fnc.writekey = do_writekey; app->fnc.genkey = do_genkey; app->fnc.sign = do_sign; app->fnc.auth = do_auth; app->fnc.decipher = do_decipher; app->fnc.change_pin = do_change_pin; app->fnc.check_pin = do_check_pin; } leave: if (rc) do_deinit (app); return rc; } diff --git a/scd/ccid-driver.c b/scd/ccid-driver.c index 5bab0b176..d7b6b5a4e 100644 --- a/scd/ccid-driver.c +++ b/scd/ccid-driver.c @@ -1,3893 +1,3893 @@ /* ccid-driver.c - USB ChipCardInterfaceDevices driver * Copyright (C) 2003, 2004, 2005, 2006, 2007 * 2008, 2009, 2013 Free Software Foundation, Inc. * Written by 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 . * * ALTERNATIVELY, this file may be distributed under the terms of the * following license, in which case the provisions of this license are * required INSTEAD OF the GNU General Public License. If you wish to * allow use of your version of this file only under the terms of the * GNU General Public License, and not to allow others to use your * version of this file under the terms of the following license, * indicate your decision by deleting this paragraph and the license * below. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* CCID (ChipCardInterfaceDevices) is a specification for accessing smartcard via a reader connected to the USB. This is a limited driver allowing to use some CCID drivers directly without any other specila drivers. This is a fallback driver to be used when nothing else works or the system should be kept minimal for security reasons. It makes use of the libusb library to gain portable access to USB. This driver has been tested with the SCM SCR335 and SPR532 smartcard readers and requires that a reader implements APDU or TPDU level exchange and does fully automatic initialization. */ #ifdef HAVE_CONFIG_H # include #endif #if defined(HAVE_LIBUSB) || defined(TEST) #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_NPTH # include #endif /*HAVE_NPTH*/ #include #include "scdaemon.h" #include "iso7816.h" #define CCID_DRIVER_INCLUDE_USB_IDS 1 #include "ccid-driver.h" #define DRVNAME "ccid-driver: " /* Max length of buffer with out CCID message header of 10-byte Sending: 547 for RSA-4096 key import APDU size = 540 (24+4+256+256) commnd + lc + le = 4 + 3 + 0 Sending: write data object of cardholder certificate APDU size = 2048 commnd + lc + le = 4 + 3 + 0 Receiving: 2048 for cardholder certificate */ #define CCID_MAX_BUF (2048+7+10) /* CCID command timeout. */ #define CCID_CMD_TIMEOUT (5*1000) /* OpenPGPcard v2.1 requires huge timeout for key generation. */ #define CCID_CMD_TIMEOUT_LONGER (60*1000) /* Depending on how this source is used we either define our error output to go to stderr or to the GnuPG based logging functions. We use the latter when GNUPG_MAJOR_VERSION or GNUPG_SCD_MAIN_HEADER are defined. */ #if defined(GNUPG_MAJOR_VERSION) || defined(GNUPG_SCD_MAIN_HEADER) #if defined(GNUPG_SCD_MAIN_HEADER) # include GNUPG_SCD_MAIN_HEADER #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */ # include "options.h" # include "util.h" # include "memory.h" # include "cardglue.h" # else /* This is the modularized GnuPG 1.9 or later. */ # include "scdaemon.h" #endif # define DEBUGOUT(t) do { if (debug_level) \ log_debug (DRVNAME t); } while (0) # define DEBUGOUT_1(t,a) do { if (debug_level) \ log_debug (DRVNAME t,(a)); } while (0) # define DEBUGOUT_2(t,a,b) do { if (debug_level) \ log_debug (DRVNAME t,(a),(b)); } while (0) # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \ log_debug (DRVNAME t,(a),(b),(c));} while (0) # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \ log_debug (DRVNAME t,(a),(b),(c),(d));} while (0) # define DEBUGOUT_CONT(t) do { if (debug_level) \ log_printf (t); } while (0) # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \ log_printf (t,(a)); } while (0) # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \ log_printf (t,(a),(b)); } while (0) # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \ log_printf (t,(a),(b),(c)); } while (0) # define DEBUGOUT_LF() do { if (debug_level) \ log_printf ("\n"); } while (0) #else /* Other usage of this source - don't use gnupg specifics. */ # define DEBUGOUT(t) do { if (debug_level) \ fprintf (stderr, DRVNAME t); } while (0) # define DEBUGOUT_1(t,a) do { if (debug_level) \ fprintf (stderr, DRVNAME t, (a)); } while (0) # define DEBUGOUT_2(t,a,b) do { if (debug_level) \ fprintf (stderr, DRVNAME t, (a), (b)); } while (0) # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \ fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0) # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \ fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0) # define DEBUGOUT_CONT(t) do { if (debug_level) \ fprintf (stderr, t); } while (0) # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \ fprintf (stderr, t, (a)); } while (0) # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \ fprintf (stderr, t, (a), (b)); } while (0) # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \ fprintf (stderr, t, (a), (b), (c)); } while (0) # define DEBUGOUT_LF() do { if (debug_level) \ putc ('\n', stderr); } while (0) #endif /* This source not used by scdaemon. */ #ifndef EAGAIN #define EAGAIN EWOULDBLOCK #endif enum { RDR_to_PC_NotifySlotChange= 0x50, RDR_to_PC_HardwareError = 0x51, PC_to_RDR_SetParameters = 0x61, PC_to_RDR_IccPowerOn = 0x62, PC_to_RDR_IccPowerOff = 0x63, PC_to_RDR_GetSlotStatus = 0x65, PC_to_RDR_Secure = 0x69, PC_to_RDR_T0APDU = 0x6a, PC_to_RDR_Escape = 0x6b, PC_to_RDR_GetParameters = 0x6c, PC_to_RDR_ResetParameters = 0x6d, PC_to_RDR_IccClock = 0x6e, PC_to_RDR_XfrBlock = 0x6f, PC_to_RDR_Mechanical = 0x71, PC_to_RDR_Abort = 0x72, PC_to_RDR_SetDataRate = 0x73, RDR_to_PC_DataBlock = 0x80, RDR_to_PC_SlotStatus = 0x81, RDR_to_PC_Parameters = 0x82, RDR_to_PC_Escape = 0x83, RDR_to_PC_DataRate = 0x84 }; /* Two macro to detect whether a CCID command has failed and to get the error code. These macros assume that we can access the mandatory first 10 bytes of a CCID message in BUF. */ #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40) #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8]) /* Store information on the driver's state. A pointer to such a structure is used as handle for most functions. */ struct ccid_driver_s { libusb_device_handle *idev; unsigned int bai; unsigned short id_vendor; unsigned short id_product; int ifc_no; int ep_bulk_out; int ep_bulk_in; int ep_intr; int seqno; unsigned char t1_ns; unsigned char t1_nr; unsigned char nonnull_nad; int max_ifsd; int max_ccid_msglen; int ifsc; unsigned char apdu_level:2; /* Reader supports short APDU level exchange. With a value of 2 short and extended level is supported.*/ unsigned int auto_voltage:1; unsigned int auto_param:1; unsigned int auto_pps:1; unsigned int auto_ifsd:1; unsigned int has_pinpad:2; unsigned int enodev_seen:1; int powered_off; time_t last_progress; /* Last time we sent progress line. */ /* The progress callback and its first arg as supplied to ccid_set_progress_cb. */ void (*progress_cb)(void *, const char *, int, int, int); void *progress_cb_arg; void (*prompt_cb)(void *, int); void *prompt_cb_arg; unsigned char intr_buf[64]; struct libusb_transfer *transfer; }; static int initialized_usb; /* Tracks whether USB has been initialized. */ static int debug_level; /* Flag to control the debug output. 0 = No debugging 1 = USB I/O info 2 = Level 1 + T=1 protocol tracing 3 = Level 2 + USB/I/O tracing of SlotStatus. */ static int ccid_usb_thread_is_alive; static unsigned int compute_edc (const unsigned char *data, size_t datalen, int use_crc); static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen, int no_debug); static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length, size_t *nread, int expected_type, int seqno, int timeout, int no_debug); static int abort_cmd (ccid_driver_t handle, int seqno); static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data, size_t datalen, unsigned char *result, size_t resultmax, size_t *resultlen); /* Convert a little endian stored 4 byte value into an unsigned integer. */ static unsigned int convert_le_u32 (const unsigned char *buf) { return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24); } /* Convert a little endian stored 2 byte value into an unsigned integer. */ static unsigned int convert_le_u16 (const unsigned char *buf) { return buf[0] | (buf[1] << 8); } static void set_msg_len (unsigned char *msg, unsigned int length) { msg[1] = length; msg[2] = length >> 8; msg[3] = length >> 16; msg[4] = length >> 24; } static void print_progress (ccid_driver_t handle) { time_t ct = time (NULL); /* We don't want to print progress lines too often. */ if (ct == handle->last_progress) return; if (handle->progress_cb) handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0); handle->last_progress = ct; } /* Pint an error message for a failed CCID command including a textual error code. MSG shall be the CCID message at a minimum of 10 bytes. */ static void print_command_failed (const unsigned char *msg) { const char *t; char buffer[100]; int ec; if (!debug_level) return; ec = CCID_ERROR_CODE (msg); switch (ec) { case 0x00: t = "Command not supported"; break; case 0xE0: t = "Slot busy"; break; case 0xEF: t = "PIN cancelled"; break; case 0xF0: t = "PIN timeout"; break; case 0xF2: t = "Automatic sequence ongoing"; break; case 0xF3: t = "Deactivated Protocol"; break; case 0xF4: t = "Procedure byte conflict"; break; case 0xF5: t = "ICC class not supported"; break; case 0xF6: t = "ICC protocol not supported"; break; case 0xF7: t = "Bad checksum in ATR"; break; case 0xF8: t = "Bad TS in ATR"; break; case 0xFB: t = "An all inclusive hardware error occurred"; break; case 0xFC: t = "Overrun error while talking to the ICC"; break; case 0xFD: t = "Parity error while talking to the ICC"; break; case 0xFE: t = "CCID timed out while talking to the ICC"; break; case 0xFF: t = "Host aborted the current activity"; break; default: if (ec > 0 && ec < 128) sprintf (buffer, "Parameter error at offset %d", ec); else sprintf (buffer, "Error code %02X", ec); t = buffer; break; } DEBUGOUT_1 ("CCID command failed: %s\n", t); } static void print_pr_data (const unsigned char *data, size_t datalen, size_t off) { int any = 0; for (; off < datalen; off++) { if (!any || !(off % 16)) { if (any) DEBUGOUT_LF (); DEBUGOUT_1 (" [%04lu] ", (unsigned long) off); } DEBUGOUT_CONT_1 (" %02X", data[off]); any = 1; } if (any && (off % 16)) DEBUGOUT_LF (); } static void print_p2r_header (const char *name, const unsigned char *msg, size_t msglen) { DEBUGOUT_1 ("%s:\n", name); if (msglen < 7) return; DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1)); DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]); DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]); } static void print_p2r_iccpoweron (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen); if (msglen < 10) return; DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7], msg[7] == 0? "auto": msg[7] == 1? "5.0 V": msg[7] == 2? "3.0 V": msg[7] == 3? "1.8 V":""); print_pr_data (msg, msglen, 8); } static void print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_getslotstatus (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_xfrblock (const unsigned char *msg, size_t msglen) { unsigned int val; print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]); val = convert_le_u16 (msg+8); DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val, val == 1? " (continued)": val == 2? " (continues+ends)": val == 3? " (continues+continued)": val == 16? " (DataBlock-expected)":""); print_pr_data (msg, msglen, 10); } static void print_p2r_getparameters (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_resetparameters (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_setparameters (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]); print_pr_data (msg, msglen, 8); } static void print_p2r_escape (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_Escape", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_iccclock (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_IccClock", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]); print_pr_data (msg, msglen, 8); } static void print_p2r_to0apdu (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]); DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]); DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]); print_pr_data (msg, msglen, 10); } static void print_p2r_secure (const unsigned char *msg, size_t msglen) { unsigned int val; print_p2r_header ("PC_to_RDR_Secure", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]); val = convert_le_u16 (msg+8); DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val, val == 1? " (continued)": val == 2? " (continues+ends)": val == 3? " (continues+continued)": val == 16? " (DataBlock-expected)":""); print_pr_data (msg, msglen, 10); } static void print_p2r_mechanical (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]); print_pr_data (msg, msglen, 8); } static void print_p2r_abort (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_Abort", msg, msglen); print_pr_data (msg, msglen, 7); } static void print_p2r_setdatarate (const unsigned char *msg, size_t msglen) { print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen); if (msglen < 10) return; print_pr_data (msg, msglen, 7); } static void print_p2r_unknown (const unsigned char *msg, size_t msglen) { print_p2r_header ("Unknown PC_to_RDR command", msg, msglen); if (msglen < 10) return; print_pr_data (msg, msglen, 0); } static void print_r2p_header (const char *name, const unsigned char *msg, size_t msglen) { DEBUGOUT_1 ("%s:\n", name); if (msglen < 9) return; DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1)); DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]); DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]); DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]); if (msg[8]) DEBUGOUT_1 (" bError ............: %u\n", msg[8]); } static void print_r2p_datablock (const unsigned char *msg, size_t msglen) { print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen); if (msglen < 10) return; if (msg[9]) DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9], msg[9] == 1? " (continued)": msg[9] == 2? " (continues+ends)": msg[9] == 3? " (continues+continued)": msg[9] == 16? " (XferBlock-expected)":""); print_pr_data (msg, msglen, 10); } static void print_r2p_slotstatus (const unsigned char *msg, size_t msglen) { print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen); if (msglen < 10) return; DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9], msg[9] == 0? " (running)": msg[9] == 1? " (stopped-L)": msg[9] == 2? " (stopped-H)": msg[9] == 3? " (stopped)":""); print_pr_data (msg, msglen, 10); } static void print_r2p_parameters (const unsigned char *msg, size_t msglen) { print_r2p_header ("RDR_to_PC_Parameters", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]); if (msglen == 17 && msg[9] == 1) { /* Protocol T=1. */ DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]); DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]); DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]); DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]); DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]); DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]); DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]); } else print_pr_data (msg, msglen, 10); } static void print_r2p_escape (const unsigned char *msg, size_t msglen) { print_r2p_header ("RDR_to_PC_Escape", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]); print_pr_data (msg, msglen, 10); } static void print_r2p_datarate (const unsigned char *msg, size_t msglen) { print_r2p_header ("RDR_to_PC_DataRate", msg, msglen); if (msglen < 10) return; if (msglen >= 18) { DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10)); DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14)); print_pr_data (msg, msglen, 18); } else print_pr_data (msg, msglen, 10); } static void print_r2p_unknown (const unsigned char *msg, size_t msglen) { print_r2p_header ("Unknown RDR_to_PC command", msg, msglen); if (msglen < 10) return; DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]); DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]); print_pr_data (msg, msglen, 10); } /* Parse a CCID descriptor, optionally print all available features and test whether this reader is usable by this driver. Returns 0 if it is usable. Note, that this code is based on the one in lsusb.c of the usb-utils package, I wrote on 2003-09-01. -wk. */ static int parse_ccid_descriptor (ccid_driver_t handle, unsigned short bcd_device, const unsigned char *buf, size_t buflen) { unsigned int i; unsigned int us; int have_t1 = 0, have_tpdu=0; handle->nonnull_nad = 0; handle->auto_ifsd = 0; handle->max_ifsd = 32; handle->has_pinpad = 0; handle->apdu_level = 0; handle->auto_voltage = 0; handle->auto_param = 0; handle->auto_pps = 0; DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n", handle->id_vendor, handle->id_product, bcd_device); if (buflen < 54 || buf[0] < 54) { DEBUGOUT ("CCID device descriptor is too short\n"); return -1; } DEBUGOUT ("ChipCard Interface Descriptor:\n"); DEBUGOUT_1 (" bLength %5u\n", buf[0]); DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]); DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]); if (buf[3] != 1 || buf[2] != 0) DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)"); DEBUGOUT_LF (); DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]); DEBUGOUT_2 (" bVoltageSupport %5u %s\n", buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V" : buf[5] == 3? "1.8V":"?")); us = convert_le_u32 (buf+6); DEBUGOUT_1 (" dwProtocols %5u ", us); if ((us & 1)) DEBUGOUT_CONT (" T=0"); if ((us & 2)) { DEBUGOUT_CONT (" T=1"); have_t1 = 1; } if ((us & ~3)) DEBUGOUT_CONT (" (Invalid values detected)"); DEBUGOUT_LF (); us = convert_le_u32(buf+10); DEBUGOUT_1 (" dwDefaultClock %5u\n", us); us = convert_le_u32(buf+14); DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us); DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]); us = convert_le_u32(buf+19); DEBUGOUT_1 (" dwDataRate %7u bps\n", us); us = convert_le_u32(buf+23); DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us); DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]); us = convert_le_u32(buf+28); DEBUGOUT_1 (" dwMaxIFSD %5u\n", us); handle->max_ifsd = us; us = convert_le_u32(buf+32); DEBUGOUT_1 (" dwSyncProtocols %08X ", us); if ((us&1)) DEBUGOUT_CONT ( " 2-wire"); if ((us&2)) DEBUGOUT_CONT ( " 3-wire"); if ((us&4)) DEBUGOUT_CONT ( " I2C"); DEBUGOUT_LF (); us = convert_le_u32(buf+36); DEBUGOUT_1 (" dwMechanical %08X ", us); if ((us & 1)) DEBUGOUT_CONT (" accept"); if ((us & 2)) DEBUGOUT_CONT (" eject"); if ((us & 4)) DEBUGOUT_CONT (" capture"); if ((us & 8)) DEBUGOUT_CONT (" lock"); DEBUGOUT_LF (); us = convert_le_u32(buf+40); DEBUGOUT_1 (" dwFeatures %08X\n", us); if ((us & 0x0002)) { DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n"); handle->auto_voltage = 1; } if ((us & 0x0004)) DEBUGOUT (" Auto activation on insert\n"); if ((us & 0x0008)) { DEBUGOUT (" Auto voltage selection\n"); handle->auto_voltage = 1; } if ((us & 0x0010)) DEBUGOUT (" Auto clock change\n"); if ((us & 0x0020)) DEBUGOUT (" Auto baud rate change\n"); if ((us & 0x0040)) { DEBUGOUT (" Auto parameter negotiation made by CCID\n"); handle->auto_param = 1; } else if ((us & 0x0080)) { DEBUGOUT (" Auto PPS made by CCID\n"); handle->auto_pps = 1; } if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080)) DEBUGOUT (" WARNING: conflicting negotiation features\n"); if ((us & 0x0100)) DEBUGOUT (" CCID can set ICC in clock stop mode\n"); if ((us & 0x0200)) { DEBUGOUT (" NAD value other than 0x00 accepted\n"); handle->nonnull_nad = 1; } if ((us & 0x0400)) { DEBUGOUT (" Auto IFSD exchange\n"); handle->auto_ifsd = 1; } if ((us & 0x00010000)) { DEBUGOUT (" TPDU level exchange\n"); have_tpdu = 1; } else if ((us & 0x00020000)) { DEBUGOUT (" Short APDU level exchange\n"); handle->apdu_level = 1; } else if ((us & 0x00040000)) { DEBUGOUT (" Short and extended APDU level exchange\n"); handle->apdu_level = 2; } else if ((us & 0x00070000)) DEBUGOUT (" WARNING: conflicting exchange levels\n"); us = convert_le_u32(buf+44); DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us); handle->max_ccid_msglen = us; DEBUGOUT ( " bClassGetResponse "); if (buf[48] == 0xff) DEBUGOUT_CONT ("echo\n"); else DEBUGOUT_CONT_1 (" %02X\n", buf[48]); DEBUGOUT ( " bClassEnvelope "); if (buf[49] == 0xff) DEBUGOUT_CONT ("echo\n"); else DEBUGOUT_CONT_1 (" %02X\n", buf[48]); DEBUGOUT ( " wlcdLayout "); if (!buf[50] && !buf[51]) DEBUGOUT_CONT ("none\n"); else DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]); DEBUGOUT_1 (" bPINSupport %5u ", buf[52]); if ((buf[52] & 1)) { DEBUGOUT_CONT ( " verification"); handle->has_pinpad |= 1; } if ((buf[52] & 2)) { DEBUGOUT_CONT ( " modification"); handle->has_pinpad |= 2; } DEBUGOUT_LF (); DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]); if (buf[0] > 54) { DEBUGOUT (" junk "); for (i=54; i < buf[0]-54; i++) DEBUGOUT_CONT_1 (" %02X", buf[i]); DEBUGOUT_LF (); } if (!have_t1 || !(have_tpdu || handle->apdu_level)) { DEBUGOUT ("this drivers requires that the reader supports T=1, " "TPDU or APDU level exchange - this is not available\n"); return -1; } /* SCM drivers get stuck in their internal USB stack if they try to send a frame of n*wMaxPacketSize back to us. Given that wMaxPacketSize is 64 for these readers we set the IFSD to a value lower than that: 64 - 10 CCID header - 4 T1frame - 2 reserved = 48 Product Ids: 0xe001 - SCR 331 0x5111 - SCR 331-DI 0x5115 - SCR 335 0xe003 - SPR 532 The 0x5117 - SCR 3320 USB ID-000 reader seems to be very slow but enabling this workaround boosts the performance to a more or less acceptable level (tested by David). */ if (handle->id_vendor == VENDOR_SCM && handle->max_ifsd > 48 && ( (handle->id_product == SCM_SCR331 && bcd_device < 0x0516) ||(handle->id_product == SCM_SCR331DI && bcd_device < 0x0620) ||(handle->id_product == SCM_SCR335 && bcd_device < 0x0514) ||(handle->id_product == SCM_SPR532 && bcd_device < 0x0504) ||(handle->id_product == SCM_SCR3320 && bcd_device < 0x0522) )) { DEBUGOUT ("enabling workaround for buggy SCM readers\n"); handle->max_ifsd = 48; } if (handle->id_vendor == VENDOR_GEMPC) { DEBUGOUT ("enabling product quirk: disable non-null NAD\n"); handle->nonnull_nad = 0; } return 0; } static char * get_escaped_usb_string (libusb_device_handle *idev, int idx, const char *prefix, const char *suffix) { int rc; unsigned char buf[280]; unsigned char *s; unsigned int langid; size_t i, n, len; char *result; if (!idx) return NULL; /* Fixme: The next line is for the current Valgrid without support for USB IOCTLs. */ memset (buf, 0, sizeof buf); /* First get the list of supported languages and use the first one. If we do don't find it we try to use English. Note that this is all in a 2 bute Unicode encoding using little endian. */ #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8), 0, (char*)buf, sizeof buf, 1000 /* ms timeout */); #ifdef USE_NPTH npth_protect (); #endif if (rc < 4) langid = 0x0409; /* English. */ else langid = (buf[3] << 8) | buf[2]; #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) + idx, langid, (char*)buf, sizeof buf, 1000 /* ms timeout */); #ifdef USE_NPTH npth_protect (); #endif if (rc < 2 || buf[1] != LIBUSB_DT_STRING) return NULL; /* Error or not a string. */ len = buf[0]; if (len > rc) return NULL; /* Larger than our buffer. */ for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2) { if (s[1]) n++; /* High byte set. */ else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':') n += 3 ; else n++; } result = malloc (strlen (prefix) + n + strlen (suffix) + 1); if (!result) return NULL; strcpy (result, prefix); n = strlen (prefix); for (s=buf+2, i=2; i+1 < len; i += 2, s += 2) { if (s[1]) result[n++] = '\xff'; /* High byte set. */ else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':') { sprintf (result+n, "%%%02X", *s); n += 3; } else result[n++] = *s; } strcpy (result+n, suffix); return result; } /* This function creates an reader id to be used to find the same physical reader after a reset. It returns an allocated and possibly percent escaped string or NULL if not enough memory is available. */ static char * make_reader_id (libusb_device_handle *idev, unsigned int vendor, unsigned int product, unsigned char serialno_index) { char *rid; char prefix[20]; sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff)); rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0"); if (!rid) { rid = malloc (strlen (prefix) + 3 + 1); if (!rid) return NULL; strcpy (rid, prefix); strcat (rid, "X:0"); } return rid; } /* Helper to find the endpoint from an interface descriptor. */ static int find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode) { int no; int want_bulk_in = 0; if (mode == 1) want_bulk_in = 0x80; for (no=0; no < ifcdesc->bNumEndpoints; no++) { const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no; if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT) ; else if (mode == 2 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_INTERRUPT) && (ep->bEndpointAddress & 0x80)) return ep->bEndpointAddress; else if ((mode == 0 || mode == 1) && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_BULK) && (ep->bEndpointAddress & 0x80) == want_bulk_in) return ep->bEndpointAddress; } return -1; } /* Helper for scan_devices. This function returns true if a requested device has been found or the caller should stop scanning for other reasons. */ static void scan_usb_device (int *count, char **rid_list, struct libusb_device *dev) { int ifc_no; int set_no; const struct libusb_interface_descriptor *ifcdesc; char *rid; libusb_device_handle *idev = NULL; int err; struct libusb_config_descriptor *config; struct libusb_device_descriptor desc; char *p; err = libusb_get_device_descriptor (dev, &desc); if (err) return; err = libusb_get_active_config_descriptor (dev, &config); if (err) return; for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++) for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++) { ifcdesc = (config->interface[ifc_no].altsetting + set_no); /* The second condition is for older SCM SPR 532 who did not know about the assigned CCID class. The third condition does the same for a Cherry SmartTerminal ST-2000. Instead of trying to interpret the strings we simply check the product ID. */ if (ifcdesc && ifcdesc->extra && ((ifcdesc->bInterfaceClass == 11 && ifcdesc->bInterfaceSubClass == 0 && ifcdesc->bInterfaceProtocol == 0) || (ifcdesc->bInterfaceClass == 255 && desc.idVendor == VENDOR_SCM && desc.idProduct == SCM_SPR532) || (ifcdesc->bInterfaceClass == 255 && desc.idVendor == VENDOR_CHERRY && desc.idProduct == CHERRY_ST2000))) { ++*count; err = libusb_open (dev, &idev); if (err) { DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (err)); continue; /* with next setting. */ } rid = make_reader_id (idev, desc.idVendor, desc.idProduct, desc.iSerialNumber); if (!rid) { libusb_free_config_descriptor (config); return; } /* We are collecting infos about all available CCID readers. Store them and continue. */ DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", *count, rid); p = malloc ((*rid_list? strlen (*rid_list):0) + 1 + strlen (rid) + 1); if (p) { *p = 0; if (*rid_list) { strcat (p, *rid_list); free (*rid_list); } strcat (p, rid); strcat (p, "\n"); *rid_list = p; } else /* Out of memory. */ { libusb_free_config_descriptor (config); free (rid); return; } free (rid); libusb_close (idev); idev = NULL; } } libusb_free_config_descriptor (config); } /* Scan all CCID devices. The function returns 0 if a reader has been found or when a scan returned without error. R_RID should be the address where to store the list of reader_ids we found. If on return this list is empty, no CCID device has been found; otherwise it points to an allocated linked list of reader IDs. */ static int scan_devices (char **r_rid) { char *rid_list = NULL; int count = 0; libusb_device **dev_list = NULL; libusb_device *dev; int i; ssize_t n; /* Set return values to a default. */ if (r_rid) *r_rid = NULL; n = libusb_get_device_list (NULL, &dev_list); for (i = 0; i < n; i++) { dev = dev_list[i]; scan_usb_device (&count, &rid_list, dev); } libusb_free_device_list (dev_list, 1); *r_rid = rid_list; return 0; } /* Set the level of debugging to LEVEL and return the old level. -1 just returns the old level. A level of 0 disables debugging, 1 enables debugging, 2 enables additional tracing of the T=1 protocol, 3 additionally enables debugging for GetSlotStatus, other values are not yet defined. Note that libusb may provide its own debugging feature which is enabled by setting the envvar USB_DEBUG. */ int ccid_set_debug_level (int level) { int old = debug_level; if (level != -1) debug_level = level; return old; } char * ccid_get_reader_list (void) { char *reader_list; if (!initialized_usb) { int rc; if ((rc = libusb_init (NULL))) { DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc)); return NULL; } initialized_usb = 1; } if (scan_devices (&reader_list)) return NULL; /* Error. */ return reader_list; } /* Vendor specific custom initialization. */ static int ccid_vendor_specific_init (ccid_driver_t handle) { if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA) { int r; /* * Vega alpha has a feature to show retry counter on the pinpad * display. But it assumes that the card returns the value of * retry counter by VERIFY with empty data (return code of * 63Cx). Unfortunately, existing OpenPGP cards don't support * VERIFY command with empty data. This vendor specific command * sequence is to disable the feature. */ const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' }; r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL); if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE && r != CCID_DRIVER_ERR_NO_CARD) return r; } return 0; } #define MAX_DEVICE 4 /* See MAX_READER in apdu.c. */ struct ccid_dev_table { int n; /* Index to ccid_usb_dev_list */ int interface_number; int setting_number; unsigned char *ifcdesc_extra; int ep_bulk_out; int ep_bulk_in; int ep_intr; size_t ifcdesc_extra_len; }; static libusb_device **ccid_usb_dev_list; static struct ccid_dev_table ccid_dev_table[MAX_DEVICE]; gpg_error_t ccid_dev_scan (int *idx_max_p, struct ccid_dev_table **t_p) { ssize_t n; libusb_device *dev; int i; int ifc_no; int set_no; int idx = 0; int err = 0; *idx_max_p = 0; *t_p = NULL; if (!initialized_usb) { int rc; if ((rc = libusb_init (NULL))) { DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc)); return gpg_error (GPG_ERR_ENODEV); } initialized_usb = 1; } n = libusb_get_device_list (NULL, &ccid_usb_dev_list); for (i = 0; i < n; i++) { struct libusb_config_descriptor *config; struct libusb_device_descriptor desc; dev = ccid_usb_dev_list[i]; if (libusb_get_device_descriptor (dev, &desc)) continue; if (libusb_get_active_config_descriptor (dev, &config)) continue; for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++) for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++) { const struct libusb_interface_descriptor *ifcdesc; ifcdesc = &config->interface[ifc_no].altsetting[set_no]; /* The second condition is for older SCM SPR 532 who did not know about the assigned CCID class. The third condition does the same for a Cherry SmartTerminal ST-2000. Instead of trying to interpret the strings we simply check the product ID. */ if (ifcdesc && ifcdesc->extra && ((ifcdesc->bInterfaceClass == 11 && ifcdesc->bInterfaceSubClass == 0 && ifcdesc->bInterfaceProtocol == 0) || (ifcdesc->bInterfaceClass == 255 && desc.idVendor == VENDOR_SCM && desc.idProduct == SCM_SPR532) || (ifcdesc->bInterfaceClass == 255 && desc.idVendor == VENDOR_CHERRY && desc.idProduct == CHERRY_ST2000))) { /* Found a reader. */ unsigned char *ifcdesc_extra; ifcdesc_extra = malloc (ifcdesc->extra_length); if (!ifcdesc_extra) { err = gpg_error_from_syserror (); libusb_free_config_descriptor (config); goto scan_finish; } memcpy (ifcdesc_extra, ifcdesc->extra, ifcdesc->extra_length); ccid_dev_table[idx].n = i; ccid_dev_table[idx].interface_number = ifc_no; ccid_dev_table[idx].setting_number = set_no; ccid_dev_table[idx].ifcdesc_extra = ifcdesc_extra; ccid_dev_table[idx].ifcdesc_extra_len = ifcdesc->extra_length; ccid_dev_table[idx].ep_bulk_out = find_endpoint (ifcdesc, 0); ccid_dev_table[idx].ep_bulk_in = find_endpoint (ifcdesc, 1); ccid_dev_table[idx].ep_intr = find_endpoint (ifcdesc, 2); idx++; if (idx >= MAX_DEVICE) { libusb_free_config_descriptor (config); err = 0; goto scan_finish; } } } libusb_free_config_descriptor (config); } scan_finish: if (err) { for (i = 0; i < idx; i++) { free (ccid_dev_table[idx].ifcdesc_extra); ccid_dev_table[idx].n = 0; ccid_dev_table[idx].interface_number = 0; ccid_dev_table[idx].setting_number = 0; ccid_dev_table[idx].ifcdesc_extra = NULL; ccid_dev_table[idx].ifcdesc_extra_len = 0; ccid_dev_table[idx].ep_bulk_out = 0; ccid_dev_table[idx].ep_bulk_in = 0; ccid_dev_table[idx].ep_intr = 0; } libusb_free_device_list (ccid_usb_dev_list, 1); ccid_usb_dev_list = NULL; } else { *idx_max_p = idx; if (idx) *t_p = ccid_dev_table; else *t_p = NULL; } return err; } void ccid_dev_scan_finish (struct ccid_dev_table *tbl, int max) { int i; for (i = 0; i < max; i++) { free (tbl[i].ifcdesc_extra); tbl[i].n = 0; tbl[i].interface_number = 0; tbl[i].setting_number = 0; tbl[i].ifcdesc_extra = NULL; tbl[i].ifcdesc_extra_len = 0; tbl[i].ep_bulk_out = 0; tbl[i].ep_bulk_in = 0; tbl[i].ep_intr = 0; } libusb_free_device_list (ccid_usb_dev_list, 1); ccid_usb_dev_list = NULL; } unsigned int ccid_get_BAI (int idx, struct ccid_dev_table *tbl) { int n; int bus, addr, intf; unsigned int bai; libusb_device *dev; n = tbl[idx].n; dev = ccid_usb_dev_list[n]; bus = libusb_get_bus_number (dev); addr = libusb_get_device_address (dev); intf = tbl[idx].interface_number; bai = (bus << 16) | (addr << 8) | intf; return bai; } int ccid_compare_BAI (ccid_driver_t handle, unsigned int bai) { return handle->bai == bai; } static void intr_cb (struct libusb_transfer *transfer) { ccid_driver_t handle = transfer->user_data; DEBUGOUT_1 ("CCID: interrupt callback %d\n", transfer->status); if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) { int err; submit_again: /* Submit the URB again to keep watching the INTERRUPT transfer. */ err = libusb_submit_transfer (transfer); if (err == LIBUSB_ERROR_NO_DEVICE) goto device_removed; DEBUGOUT_1 ("CCID submit transfer again %d\n", err); } else if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { if (transfer->actual_length == 2 && transfer->buffer[0] == 0x50 && (transfer->buffer[1] & 1) == 0) { DEBUGOUT ("CCID: card removed\n"); handle->powered_off = 1; scd_kick_the_loop (); } else { /* Event other than card removal. */ goto submit_again; } } else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) handle->powered_off = 1; else { device_removed: DEBUGOUT ("CCID: device removed\n"); handle->powered_off = 1; scd_kick_the_loop (); } } static void ccid_setup_intr (ccid_driver_t handle) { struct libusb_transfer *transfer; int err; transfer = libusb_alloc_transfer (0); handle->transfer = transfer; libusb_fill_interrupt_transfer (transfer, handle->idev, handle->ep_intr, handle->intr_buf, sizeof (handle->intr_buf), intr_cb, handle, 0); err = libusb_submit_transfer (transfer); DEBUGOUT_2 ("CCID submit transfer (%x): %d", handle->ep_intr, err); } static void * ccid_usb_thread (void *arg) { libusb_context *ctx = arg; while (ccid_usb_thread_is_alive) { #ifdef USE_NPTH npth_unprotect (); #endif libusb_handle_events_completed (ctx, NULL); #ifdef USE_NPTH npth_protect (); #endif } return NULL; } static int ccid_open_usb_reader (const char *spec_reader_name, int idx, struct ccid_dev_table *ccid_table, ccid_driver_t *handle, char **rdrname_p) { libusb_device *dev; libusb_device_handle *idev = NULL; char *rid = NULL; int rc = 0; int ifc_no, set_no; struct libusb_device_descriptor desc; int n; int bus, addr; unsigned int bai; n = ccid_table[idx].n; ifc_no = ccid_table[idx].interface_number; set_no = ccid_table[idx].setting_number; dev = ccid_usb_dev_list[n]; bus = libusb_get_bus_number (dev); addr = libusb_get_device_address (dev); bai = (bus << 16) | (addr << 8) | ifc_no; rc = libusb_open (dev, &idev); if (rc) { DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (rc)); free (*handle); *handle = NULL; return rc; } if (ccid_usb_thread_is_alive++ == 0) { npth_t thread; npth_attr_t tattr; int err; err = npth_attr_init (&tattr); if (err) { DEBUGOUT_1 ("npth_attr_init failed: %s\n", strerror (err)); free (*handle); *handle = NULL; return err; } npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, ccid_usb_thread, NULL); if (err) { DEBUGOUT_1 ("npth_create failed: %s\n", strerror (err)); free (*handle); *handle = NULL; return err; } npth_attr_destroy (&tattr); } rc = libusb_get_device_descriptor (dev, &desc); if (rc) { DEBUGOUT ("get_device_descripor failed\n"); goto leave; } rid = make_reader_id (idev, desc.idVendor, desc.idProduct, desc.iSerialNumber); /* Check to see if reader name matches the spec. */ if (spec_reader_name && strncmp (rid, spec_reader_name, strlen (spec_reader_name))) { DEBUGOUT ("device not matched\n"); rc = CCID_DRIVER_ERR_NO_READER; goto leave; } (*handle)->id_vendor = desc.idVendor; (*handle)->id_product = desc.idProduct; (*handle)->idev = idev; (*handle)->bai = bai; (*handle)->ifc_no = ifc_no; (*handle)->ep_bulk_out = ccid_table[idx].ep_bulk_out; (*handle)->ep_bulk_in = ccid_table[idx].ep_bulk_in; (*handle)->ep_intr = ccid_table[idx].ep_intr; DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", idx, rid); if (parse_ccid_descriptor (*handle, desc.bcdDevice, ccid_table[idx].ifcdesc_extra, ccid_table[idx].ifcdesc_extra_len)) { DEBUGOUT ("device not supported\n"); rc = CCID_DRIVER_ERR_NO_READER; goto leave; } rc = libusb_claim_interface (idev, ifc_no); if (rc) { DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc); rc = CCID_DRIVER_ERR_CARD_IO_ERROR; goto leave; } if (set_no != 0) { rc = libusb_set_interface_alt_setting (idev, ifc_no, set_no); if (rc) { DEBUGOUT_1 ("usb_set_interface_alt_setting failed: %d\n", rc); rc = CCID_DRIVER_ERR_CARD_IO_ERROR; goto leave; } } rc = ccid_vendor_specific_init (*handle); leave: if (rc) { --ccid_usb_thread_is_alive; free (rid); libusb_close (idev); free (*handle); *handle = NULL; } else { if (rdrname_p) *rdrname_p = rid; else free (rid); } return rc; } /* Open the reader with the internal number READERNO and return a pointer to be used as handle in HANDLE. Returns 0 on success. */ int ccid_open_reader (const char *spec_reader_name, int idx, struct ccid_dev_table *ccid_table, ccid_driver_t *handle, char **rdrname_p) { *handle = calloc (1, sizeof **handle); if (!*handle) { DEBUGOUT ("out of memory\n"); return CCID_DRIVER_ERR_OUT_OF_CORE; } return ccid_open_usb_reader (spec_reader_name, idx, ccid_table, handle, rdrname_p); } int ccid_require_get_status (ccid_driver_t handle) { /* When a card reader supports interrupt transfer to check the status of card, it is possible to submit only an interrupt transfer, and no check is required by application layer. USB can detect removal of a card and can detect removal of a reader. */ if (handle->ep_intr >= 0) return 0; /* Libusb actually detects the removal of USB device in use. However, there is no good API to handle the removal (yet), cleanly and with good portability. There is libusb_set_pollfd_notifiers function, but it doesn't offer libusb_device_handle* data to its callback. So, when it watches multiple devices, there is no way to know which device is removed. Once, we will have a good programming interface of libusb, we can list tokens (with no interrupt transfer support, but always with card inserted) here to return 0, so that scdaemon can submit minimum packet on wire. */ return 1; } static void do_close_reader (ccid_driver_t handle) { int rc; unsigned char msg[100]; size_t msglen; unsigned char seqno; if (!handle->powered_off) { msg[0] = PC_to_RDR_IccPowerOff; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, 0); msglen = 10; rc = bulk_out (handle, msg, msglen, 0); if (!rc) bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus, seqno, 2000, 0); } if (handle->transfer) { if (!handle->powered_off) { DEBUGOUT ("libusb_cancel_transfer\n"); rc = libusb_cancel_transfer (handle->transfer); if (rc != LIBUSB_ERROR_NOT_FOUND) while (!handle->powered_off) { DEBUGOUT ("libusb_handle_events_completed\n"); #ifdef USE_NPTH npth_unprotect (); #endif libusb_handle_events_completed (NULL, &handle->powered_off); #ifdef USE_NPTH npth_protect (); #endif } } libusb_free_transfer (handle->transfer); handle->transfer = NULL; } libusb_release_interface (handle->idev, handle->ifc_no); --ccid_usb_thread_is_alive; libusb_close (handle->idev); handle->idev = NULL; } int ccid_set_progress_cb (ccid_driver_t handle, void (*cb)(void *, const char *, int, int, int), void *cb_arg) { if (!handle) return CCID_DRIVER_ERR_INV_VALUE; handle->progress_cb = cb; handle->progress_cb_arg = cb_arg; return 0; } int ccid_set_prompt_cb (ccid_driver_t handle, void (*cb)(void *, int), void *cb_arg) { if (!handle) return CCID_DRIVER_ERR_INV_VALUE; handle->prompt_cb = cb; handle->prompt_cb_arg = cb_arg; return 0; } /* Close the reader HANDLE. */ int ccid_close_reader (ccid_driver_t handle) { if (!handle) return 0; do_close_reader (handle); free (handle); return 0; } /* Return False if a card is present and powered. */ int ccid_check_card_presence (ccid_driver_t handle) { (void)handle; /* Not yet implemented. */ return -1; } /* Write a MSG of length MSGLEN to the designated bulk out endpoint. Returns 0 on success. */ static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen, int no_debug) { int rc; int transferred; /* No need to continue and clutter the log with USB write error messages after we got the first ENODEV. */ if (handle->enodev_seen) return CCID_DRIVER_ERR_NO_READER; if (debug_level && (!no_debug || debug_level >= 3)) { switch (msglen? msg[0]:0) { case PC_to_RDR_IccPowerOn: print_p2r_iccpoweron (msg, msglen); break; case PC_to_RDR_IccPowerOff: print_p2r_iccpoweroff (msg, msglen); break; case PC_to_RDR_GetSlotStatus: print_p2r_getslotstatus (msg, msglen); break; case PC_to_RDR_XfrBlock: print_p2r_xfrblock (msg, msglen); break; case PC_to_RDR_GetParameters: print_p2r_getparameters (msg, msglen); break; case PC_to_RDR_ResetParameters: print_p2r_resetparameters (msg, msglen); break; case PC_to_RDR_SetParameters: print_p2r_setparameters (msg, msglen); break; case PC_to_RDR_Escape: print_p2r_escape (msg, msglen); break; case PC_to_RDR_IccClock: print_p2r_iccclock (msg, msglen); break; case PC_to_RDR_T0APDU: print_p2r_to0apdu (msg, msglen); break; case PC_to_RDR_Secure: print_p2r_secure (msg, msglen); break; case PC_to_RDR_Mechanical: print_p2r_mechanical (msg, msglen); break; case PC_to_RDR_Abort: print_p2r_abort (msg, msglen); break; case PC_to_RDR_SetDataRate: print_p2r_setdatarate (msg, msglen); break; default: print_p2r_unknown (msg, msglen); break; } } #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out, (char*)msg, msglen, &transferred, 5000 /* ms timeout */); #ifdef USE_NPTH npth_protect (); #endif if (rc == 0 && transferred == msglen) return 0; if (rc) { DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc)); if (rc == LIBUSB_ERROR_NO_DEVICE) { handle->enodev_seen = 1; return CCID_DRIVER_ERR_NO_READER; } } return 0; } /* Read a maximum of LENGTH bytes from the bulk in endpoint into BUFFER and return the actual read number if bytes in NREAD. SEQNO is the sequence number used to send the request and EXPECTED_TYPE the type of message we expect. Does checks on the ccid header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to avoid debug messages in case of no error; this can be overriden with a glibal debug level of at least 3. Returns 0 on success. */ static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length, size_t *nread, int expected_type, int seqno, int timeout, int no_debug) { int rc; int msglen; int notified = 0; /* Fixme: The next line for the current Valgrind without support for USB IOCTLs. */ memset (buffer, 0, length); retry: #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in, (char*)buffer, length, &msglen, timeout); #ifdef USE_NPTH npth_protect (); #endif if (rc) { DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc)); if (rc == LIBUSB_ERROR_NO_DEVICE) { handle->enodev_seen = 1; return CCID_DRIVER_ERR_NO_READER; } return CCID_DRIVER_ERR_CARD_IO_ERROR; } if (msglen < 0) return CCID_DRIVER_ERR_INV_VALUE; /* Faulty libusb. */ *nread = msglen; if (msglen < 10) { DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen); abort_cmd (handle, seqno); return CCID_DRIVER_ERR_INV_VALUE; } if (buffer[5] != 0) { DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]); return CCID_DRIVER_ERR_INV_VALUE; } if (buffer[6] != seqno) { DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n", seqno, buffer[6]); /* Retry until we are synced again. */ goto retry; } /* We need to handle the time extension request before we check that we got the expected message type. This is in particular required for the Cherry keyboard which sends a time extension request for each key hit. */ if (!(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80) { /* Card present and active, time extension requested. */ DEBUGOUT_2 ("time extension requested (%02X,%02X)\n", buffer[7], buffer[8]); /* Gnuk enhancement to prompt user input by ack button */ if (buffer[8] == 0xff && !notified) { notified = 1; handle->prompt_cb (handle->prompt_cb_arg, 1); } goto retry; } if (notified) handle->prompt_cb (handle->prompt_cb_arg, 0); if (buffer[0] != expected_type && buffer[0] != RDR_to_PC_SlotStatus) { DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]); abort_cmd (handle, seqno); return CCID_DRIVER_ERR_INV_VALUE; } if (debug_level && (!no_debug || debug_level >= 3)) { switch (buffer[0]) { case RDR_to_PC_DataBlock: print_r2p_datablock (buffer, msglen); break; case RDR_to_PC_SlotStatus: print_r2p_slotstatus (buffer, msglen); break; case RDR_to_PC_Parameters: print_r2p_parameters (buffer, msglen); break; case RDR_to_PC_Escape: print_r2p_escape (buffer, msglen); break; case RDR_to_PC_DataRate: print_r2p_datarate (buffer, msglen); break; default: print_r2p_unknown (buffer, msglen); break; } } if (CCID_COMMAND_FAILED (buffer)) print_command_failed (buffer); /* Check whether a card is at all available. Note: If you add new error codes here, check whether they need to be ignored in send_escape_cmd. */ switch ((buffer[7] & 0x03)) { case 0: /* no error */ break; case 1: rc = CCID_DRIVER_ERR_CARD_INACTIVE; break; case 2: rc = CCID_DRIVER_ERR_NO_CARD; break; case 3: /* RFU */ break; } if (rc) { /* * Communication failure by device side. * Possibly, it was forcibly suspended and resumed. * * Only detect this kind of failure when interrupt transfer is * not supported. For card reader with interrupt transfer * support removal is detected by intr_cb. */ if (handle->ep_intr < 0) { DEBUGOUT ("CCID: card inactive/removed\n"); handle->powered_off = 1; scd_kick_the_loop (); } } return rc; } /* Send an abort sequence and wait until everything settled. */ static int abort_cmd (ccid_driver_t handle, int seqno) { int rc; char dummybuf[8]; unsigned char msg[100]; int msglen; seqno &= 0xff; DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno); /* Send the abort command to the control pipe. Note that we don't need to keep track of sent abort commands because there should never be another thread using the same slot concurrently. */ #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_control_transfer (handle->idev, 0x21,/* bmRequestType: host-to-device, class specific, to interface. */ 1, /* ABORT */ (seqno << 8 | 0 /* slot */), handle->ifc_no, dummybuf, 0, 1000 /* ms timeout */); #ifdef USE_NPTH npth_protect (); #endif if (rc) { DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc)); return CCID_DRIVER_ERR_CARD_IO_ERROR; } /* Now send the abort command to the bulk out pipe using the same SEQNO and SLOT. Do this in a loop to so that all seqno are tried. */ seqno--; /* Adjust for next increment. */ do { int transferred; seqno++; msg[0] = PC_to_RDR_Abort; msg[5] = 0; /* slot */ msg[6] = seqno; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ msglen = 10; set_msg_len (msg, 0); #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out, (char*)msg, msglen, &transferred, 5000 /* ms timeout */); #ifdef USE_NPTH npth_protect (); #endif if (rc == 0 && transferred == msglen) rc = 0; else if (rc) DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n", libusb_error_name (rc)); if (rc) return rc; #ifdef USE_NPTH npth_unprotect (); #endif rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in, (char*)msg, sizeof msg, &msglen, 5000 /*ms timeout*/); #ifdef USE_NPTH npth_protect (); #endif if (rc) { DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n", libusb_error_name (rc)); return CCID_DRIVER_ERR_CARD_IO_ERROR; } if (msglen < 10) { DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n", (unsigned int)msglen); return CCID_DRIVER_ERR_INV_VALUE; } if (msg[5] != 0) { DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]); return CCID_DRIVER_ERR_INV_VALUE; } DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n", msg[7], msg[8], msg[9]); if (CCID_COMMAND_FAILED (msg)) print_command_failed (msg); } while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno); handle->seqno = ((seqno + 1) & 0xff); DEBUGOUT ("sending abort sequence succeeded\n"); return 0; } /* Note that this function won't return the error codes NO_CARD or CARD_INACTIVE. IF RESULT is not NULL, the result from the operation will get returned in RESULT and its length in RESULTLEN. If the response is larger than RESULTMAX, an error is returned and the required buffer length returned in RESULTLEN. */ static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data, size_t datalen, unsigned char *result, size_t resultmax, size_t *resultlen) { int rc; unsigned char msg[100]; size_t msglen; unsigned char seqno; if (resultlen) *resultlen = 0; if (datalen > sizeof msg - 10) return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */ msg[0] = PC_to_RDR_Escape; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ memcpy (msg+10, data, datalen); msglen = 10 + datalen; set_msg_len (msg, datalen); rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape, seqno, 5000, 0); if (result) switch (rc) { /* We need to ignore certain errorcode here. */ case 0: case CCID_DRIVER_ERR_CARD_INACTIVE: case CCID_DRIVER_ERR_NO_CARD: { if (msglen > resultmax) rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */ else { memcpy (result, msg, msglen); if (resultlen) *resultlen = msglen; rc = 0; } } break; default: break; } return rc; } int ccid_transceive_escape (ccid_driver_t handle, const unsigned char *data, size_t datalen, unsigned char *resp, size_t maxresplen, size_t *nresp) { return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp); } /* experimental */ int ccid_poll (ccid_driver_t handle) { int rc; unsigned char msg[10]; int msglen; int i, j; rc = libusb_interrupt_transfer (handle->idev, handle->ep_intr, (char*)msg, sizeof msg, &msglen, 0 /* ms timeout */ ); if (rc == LIBUSB_ERROR_TIMEOUT) return 0; if (rc) { DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc)); return CCID_DRIVER_ERR_CARD_IO_ERROR; } if (msglen < 1) { DEBUGOUT ("intr-in msg too short\n"); return CCID_DRIVER_ERR_INV_VALUE; } if (msg[0] == RDR_to_PC_NotifySlotChange) { DEBUGOUT ("notify slot change:"); for (i=1; i < msglen; i++) for (j=0; j < 4; j++) DEBUGOUT_CONT_3 (" %d:%c%c", (i-1)*4+j, (msg[i] & (1<<(j*2)))? 'p':'-', (msg[i] & (2<<(j*2)))? '*':' '); DEBUGOUT_LF (); } else if (msg[0] == RDR_to_PC_HardwareError) { DEBUGOUT ("hardware error occurred\n"); } else { DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]); } return 0; } /* Note that this function won't return the error codes NO_CARD or CARD_INACTIVE */ int ccid_slot_status (ccid_driver_t handle, int *statusbits, int on_wire) { int rc; unsigned char msg[100]; size_t msglen; unsigned char seqno; int retries = 0; if (handle->powered_off) return CCID_DRIVER_ERR_NO_READER; /* If the card (with its lower-level driver) doesn't require GET_STATUS on wire (because it supports INTERRUPT transfer for status change, or it's a token which has a card always inserted), no need to send on wire. */ if (!on_wire && !ccid_require_get_status (handle)) { /* Setup interrupt transfer at the initial call of slot_status with ON_WIRE == 0 */ if (handle->transfer == NULL && handle->ep_intr >= 0) ccid_setup_intr (handle); *statusbits = 0; return 0; } retry: msg[0] = PC_to_RDR_GetSlotStatus; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, 0); rc = bulk_out (handle, msg, 10, 1); if (rc) return rc; /* Note that we set the NO_DEBUG flag here, so that the logs won't get cluttered up by a ticker function checking for the slot status and debugging enabled. */ rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus, seqno, retries? 1000 : 200, 1); if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3) { if (!retries) { DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n"); #ifdef USE_NPTH npth_unprotect (); #endif libusb_clear_halt (handle->idev, handle->ep_bulk_in); libusb_clear_halt (handle->idev, handle->ep_bulk_out); #ifdef USE_NPTH npth_protect (); #endif } else DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n"); retries++; goto retry; } if (rc && rc != CCID_DRIVER_ERR_NO_CARD && rc != CCID_DRIVER_ERR_CARD_INACTIVE) return rc; *statusbits = (msg[7] & 3); return 0; } /* Parse ATR string (of ATRLEN) and update parameters at PARAM. Calling this routine, it should prepare default values at PARAM beforehand. This routine assumes that card is accessed by T=1 protocol. It doesn't analyze historical bytes at all. Returns < 0 value on error: -1 for parse error or integrity check error -2 for card doesn't support T=1 protocol -3 for parameters are nod explicitly defined by ATR -4 for this driver doesn't support CRC Returns >= 0 on success: 0 for card is negotiable mode 1 for card is specific mode (and not negotiable) */ static int update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen) { int i = -1; int t, y, chk; int historical_bytes_num, negotiable = 1; #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0) NEXTBYTE (); if (atr[i] == 0x3F) param[1] |= 0x02; /* Convention is inverse. */ NEXTBYTE (); y = (atr[i] >> 4); historical_bytes_num = atr[i] & 0x0f; NEXTBYTE (); if ((y & 1)) { param[0] = atr[i]; /* TA1 - Fi & Di */ NEXTBYTE (); } if ((y & 2)) NEXTBYTE (); /* TB1 - ignore */ if ((y & 4)) { param[2] = atr[i]; /* TC1 - Guard Time */ NEXTBYTE (); } if ((y & 8)) { y = (atr[i] >> 4); /* TD1 */ t = atr[i] & 0x0f; NEXTBYTE (); if ((y & 1)) { /* TA2 - PPS mode */ if ((atr[i] & 0x0f) != 1) return -2; /* Wrong card protocol (!= 1). */ if ((atr[i] & 0x10) != 0x10) return -3; /* Transmission parameters are implicitly defined. */ negotiable = 0; /* TA2 means specific mode. */ NEXTBYTE (); } if ((y & 2)) NEXTBYTE (); /* TB2 - ignore */ if ((y & 4)) NEXTBYTE (); /* TC2 - ignore */ if ((y & 8)) { y = (atr[i] >> 4); /* TD2 */ t = atr[i] & 0x0f; NEXTBYTE (); } else y = 0; while (y) { if ((y & 1)) { /* TAx */ if (t == 1) param[5] = atr[i]; /* IFSC */ else if (t == 15) /* XXX: check voltage? */ param[4] = (atr[i] >> 6); /* ClockStop */ NEXTBYTE (); } if ((y & 2)) { if (t == 1) param[3] = atr[i]; /* TBx - BWI & CWI */ NEXTBYTE (); } if ((y & 4)) { if (t == 1) param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */ NEXTBYTE (); if (param[1] & 0x01) return -4; /* CRC not supported yet. */ } if ((y & 8)) { y = (atr[i] >> 4); /* TDx */ t = atr[i] & 0x0f; NEXTBYTE (); } else y = 0; } } i += historical_bytes_num - 1; NEXTBYTE (); if (atrlen != i+1) return -1; #undef NEXTBYTE chk = 0; do { chk ^= atr[i]; i--; } while (i > 0); if (chk != 0) return -1; return negotiable; } /* Return the ATR of the card. This is not a cached value and thus an actual reset is done. */ int ccid_get_atr (ccid_driver_t handle, unsigned char *atr, size_t maxatrlen, size_t *atrlen) { int rc; int statusbits; unsigned char msg[100]; unsigned char *tpdu; size_t msglen, tpdulen; unsigned char seqno; int use_crc = 0; unsigned int edc; int tried_iso = 0; int got_param; unsigned char param[7] = { /* For Protocol T=1 */ 0x11, /* bmFindexDindex */ 0x10, /* bmTCCKST1 */ 0x00, /* bGuardTimeT1 */ 0x4d, /* bmWaitingIntegersT1 */ 0x00, /* bClockStop */ 0x20, /* bIFSC */ 0x00 /* bNadValue */ }; /* First check whether a card is available. */ rc = ccid_slot_status (handle, &statusbits, 1); if (rc) return rc; if (statusbits == 2) return CCID_DRIVER_ERR_NO_CARD; /* * In the first invocation of ccid_slot_status, card reader may * return CCID_DRIVER_ERR_CARD_INACTIVE and handle->powered_off may * become 1. Because inactive card is no problem (we are turning it * ON here), clear the flag. */ handle->powered_off = 0; /* For an inactive and also for an active card, issue the PowerOn command to get the ATR. */ again: msg[0] = PC_to_RDR_IccPowerOn; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */ msg[7] = handle->auto_voltage ? 0 : 1; msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, 0); msglen = 10; rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock, seqno, 5000, 0); if (rc) return rc; if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb && ((handle->id_vendor == VENDOR_CHERRY && handle->id_product == 0x0005) || (handle->id_vendor == VENDOR_GEMPC && handle->id_product == 0x4433) )) { tried_iso = 1; /* Try switching to ISO mode. */ if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2, NULL, 0, NULL)) goto again; } else if (CCID_COMMAND_FAILED (msg)) return CCID_DRIVER_ERR_CARD_IO_ERROR; handle->powered_off = 0; if (atr) { size_t n = msglen - 10; if (n > maxatrlen) n = maxatrlen; memcpy (atr, msg+10, n); *atrlen = n; } param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0; rc = update_param_by_atr (param, msg+10, msglen - 10); if (rc < 0) { DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc); return CCID_DRIVER_ERR_CARD_IO_ERROR; } got_param = 0; if (handle->auto_param) { msg[0] = PC_to_RDR_GetParameters; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, 0); msglen = 10; rc = bulk_out (handle, msg, msglen, 0); if (!rc) rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters, seqno, 2000, 0); if (rc) DEBUGOUT ("GetParameters failed\n"); else if (msglen == 17 && msg[9] == 1) got_param = 1; } else if (handle->auto_pps) ; else if (rc == 1) /* It's negotiable, send PPS. */ { msg[0] = PC_to_RDR_XfrBlock; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; msg[8] = 0; msg[9] = 0; msg[10] = 0xff; /* PPSS */ msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */ msg[12] = param[0]; /* PPS1: Fi / Di */ msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */ set_msg_len (msg, 4); msglen = 10 + 4; rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock, seqno, 5000, 0); if (rc) return rc; if (msglen != 10 + 4) { DEBUGOUT_1 ("Setting PPS failed: %zu\n", msglen); return CCID_DRIVER_ERR_CARD_IO_ERROR; } if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0]) { DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]); return CCID_DRIVER_ERR_CARD_IO_ERROR; } } /* Setup parameters to select T=1. */ msg[0] = PC_to_RDR_SetParameters; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 1; /* Select T=1. */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ if (!got_param) memcpy (&msg[10], param, 7); set_msg_len (msg, 7); msglen = 10 + 7; rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters, seqno, 5000, 0); if (rc) DEBUGOUT ("SetParameters failed (ignored)\n"); if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 ) handle->ifsc = msg[15]; else handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */ if (handle->nonnull_nad && msglen > 16 && msg[16] == 0) { DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n"); handle->nonnull_nad = 0; } handle->t1_ns = 0; handle->t1_nr = 0; /* Send an S-Block with our maximum IFSD to the CCID. */ if (!handle->apdu_level && !handle->auto_ifsd) { tpdu = msg+10; /* NAD: DAD=1, SAD=0 */ tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0; tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */ tpdu[2] = 1; tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32; tpdulen = 4; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; msg[0] = PC_to_RDR_XfrBlock; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, tpdulen); msglen = 10 + tpdulen; if (debug_level > 1) DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n", ((msg[11] & 0xc0) == 0x80)? 'R' : (msg[11] & 0x80)? 'S' : 'I', ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)), (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":"")); rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock, seqno, 5000, 0); if (rc) return rc; tpdu = msg + 10; tpdulen = msglen - 10; if (tpdulen < 4) return CCID_DRIVER_ERR_ABORTED; if (debug_level > 1) DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n", ((msg[11] & 0xc0) == 0x80)? 'R' : (msg[11] & 0x80)? 'S' : 'I', ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)), ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0, (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":"")); if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1) { DEBUGOUT ("invalid response for S-block (Change-IFSD)\n"); return -1; } DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]); } return 0; } static unsigned int compute_edc (const unsigned char *data, size_t datalen, int use_crc) { if (use_crc) { return 0x42; /* Not yet implemented. */ } else { unsigned char crc = 0; for (; datalen; datalen--) crc ^= *data++; return crc; } } /* Return true if APDU is an extended length one. */ static int is_exlen_apdu (const unsigned char *apdu, size_t apdulen) { if (apdulen < 7 || apdu[4]) return 0; /* Too short or no Z byte. */ return 1; } /* Helper for ccid_transceive used for APDU level exchanges. */ static int ccid_transceive_apdu_level (ccid_driver_t handle, const unsigned char *apdu_buf, size_t apdu_len, unsigned char *resp, size_t maxresplen, size_t *nresp) { int rc; unsigned char msg[CCID_MAX_BUF]; const unsigned char *apdu_p; size_t apdu_part_len; size_t msglen; unsigned char seqno; int bwi = 4; unsigned char chain = 0; if (apdu_len == 0 || apdu_len > sizeof (msg) - 10) return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */ apdu_p = apdu_buf; while (1) { apdu_part_len = apdu_len; if (apdu_part_len > handle->max_ccid_msglen - 10) { apdu_part_len = handle->max_ccid_msglen - 10; chain |= 0x01; } msg[0] = PC_to_RDR_XfrBlock; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = bwi; msg[8] = chain; msg[9] = 0; memcpy (msg+10, apdu_p, apdu_part_len); set_msg_len (msg, apdu_part_len); msglen = 10 + apdu_part_len; rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; apdu_p += apdu_part_len; apdu_len -= apdu_part_len; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0); if (rc) return rc; if (!(chain & 0x01)) break; chain = 0x02; } apdu_len = 0; while (1) { apdu_part_len = msglen - 10; if (resp && apdu_len + apdu_part_len <= maxresplen) memcpy (resp + apdu_len, msg+10, apdu_part_len); apdu_len += apdu_part_len; if (!(msg[9] & 0x01)) break; msg[0] = PC_to_RDR_XfrBlock; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = bwi; msg[8] = 0x10; /* Request next data block */ msg[9] = 0; set_msg_len (msg, 0); msglen = 10; rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0); if (rc) return rc; } if (resp) { if (apdu_len > maxresplen) { DEBUGOUT_2 ("provided buffer too short for received data " "(%u/%u)\n", (unsigned int)apdu_len, (unsigned int)maxresplen); return CCID_DRIVER_ERR_INV_VALUE; } *nresp = apdu_len; } return 0; } /* Protocol T=1 overview Block Structure: Prologue Field: 1 byte Node Address (NAD) 1 byte Protocol Control Byte (PCB) 1 byte Length (LEN) Information Field: 0-254 byte APDU or Control Information (INF) Epilogue Field: 1 byte Error Detection Code (EDC) NAD: bit 7 unused bit 4..6 Destination Node Address (DAD) bit 3 unused bit 2..0 Source Node Address (SAD) If node adresses are not used, SAD and DAD should be set to 0 on the first block sent to the card. If they are used they should have different values (0 for one is okay); that first block sets up the addresses of the nodes. PCB: Information Block (I-Block): bit 7 0 bit 6 Sequence number (yep, that is modulo 2) bit 5 Chaining flag bit 4..0 reserved Received-Ready Block (R-Block): bit 7 1 bit 6 0 bit 5 0 bit 4 Sequence number bit 3..0 0 = no error 1 = EDC or parity error 2 = other error other values are reserved Supervisory Block (S-Block): bit 7 1 bit 6 1 bit 5 clear=request,set=response - bit 4..0 0 = resyncronisation request + bit 4..0 0 = resynchronization request 1 = information field size request 2 = abort request 3 = extension of BWT request 4 = VPP error other values are reserved */ int ccid_transceive (ccid_driver_t handle, const unsigned char *apdu_buf, size_t apdu_buflen, unsigned char *resp, size_t maxresplen, size_t *nresp) { int rc; /* The size of the buffer used to be 10+259. For the via_escape hack we need one extra byte, thus 11+259. */ unsigned char send_buffer[11+259], recv_buffer[11+259]; const unsigned char *apdu; size_t apdulen; unsigned char *msg, *tpdu, *p; size_t msglen, tpdulen, last_tpdulen, n; unsigned char seqno; unsigned int edc; int use_crc = 0; int hdrlen, pcboff; size_t dummy_nresp; int via_escape = 0; int next_chunk = 1; int sending = 1; int retries = 0; int resyncing = 0; int nad_byte; int wait_more = 0; if (!nresp) nresp = &dummy_nresp; *nresp = 0; /* Smarter readers allow sending APDUs directly; divert here. */ if (handle->apdu_level) { /* We employ a hack for Omnikey readers which are able to send TPDUs using an escape sequence. There is no documentation but the Windows driver does it this way. Tested using a CM6121. This method works also for the Cherry XX44 keyboards; however there are problems with the ccid_transceive_secure which leads to a loss of sync on the CCID level. If Cherry wants to make their keyboard work again, they should hand over some docs. */ if ((handle->id_vendor == VENDOR_OMNIKEY) && handle->apdu_level < 2 && is_exlen_apdu (apdu_buf, apdu_buflen)) via_escape = 1; else return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen, resp, maxresplen, nresp); } /* The other readers we support require sending TPDUs. */ tpdulen = 0; /* Avoid compiler warning about no initialization. */ msg = send_buffer; hdrlen = via_escape? 11 : 10; /* NAD: DAD=1, SAD=0 */ nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0; if (via_escape) nad_byte = 0; last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */ for (;;) { if (next_chunk) { next_chunk = 0; apdu = apdu_buf; apdulen = apdu_buflen; assert (apdulen); /* Construct an I-Block. */ tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */ if (apdulen > handle->ifsc ) { apdulen = handle->ifsc; apdu_buf += handle->ifsc; apdu_buflen -= handle->ifsc; tpdu[1] |= (1 << 5); /* Set more bit. */ } tpdu[2] = apdulen; memcpy (tpdu+3, apdu, apdulen); tpdulen = 3 + apdulen; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; } if (via_escape) { msg[0] = PC_to_RDR_Escape; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* RFU */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ msg[10] = 0x1a; /* Omnikey command to send a TPDU. */ set_msg_len (msg, 1 + tpdulen); } else { msg[0] = PC_to_RDR_XfrBlock; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 4; /* bBWI */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ set_msg_len (msg, tpdulen); } msglen = hdrlen + tpdulen; if (!resyncing) last_tpdulen = tpdulen; pcboff = hdrlen+1; if (debug_level > 1) DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n", ((msg[pcboff] & 0xc0) == 0x80)? 'R' : (msg[pcboff] & 0x80)? 'S' : 'I', ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10) : !!(msg[pcboff] & 0x40)), (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)? " [more]":"")); rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; msg = recv_buffer; rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen, via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock, seqno, wait_more? CCID_CMD_TIMEOUT_LONGER: CCID_CMD_TIMEOUT, 0); if (rc) return rc; tpdu = msg + hdrlen; tpdulen = msglen - hdrlen; resyncing = 0; if (tpdulen < 4) { #ifdef USE_NPTH npth_unprotect (); #endif libusb_clear_halt (handle->idev, handle->ep_bulk_in); #ifdef USE_NPTH npth_protect (); #endif return CCID_DRIVER_ERR_ABORTED; } if (debug_level > 1) DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n", ((msg[pcboff] & 0xc0) == 0x80)? 'R' : (msg[pcboff] & 0x80)? 'S' : 'I', ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10) : !!(msg[pcboff] & 0x40)), ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0, (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)? " [more]":"")); if (!(tpdu[1] & 0x80)) { /* This is an I-block. */ retries = 0; if (sending) { /* last block sent was successful. */ handle->t1_ns ^= 1; sending = 0; } if (!!(tpdu[1] & 0x40) != handle->t1_nr) { /* Response does not match our sequence number. */ msg = send_buffer; tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */ tpdu[2] = 0; tpdulen = 3; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; continue; } handle->t1_nr ^= 1; p = tpdu + 3; /* Skip the prologue field. */ n = tpdulen - 3 - 1; /* Strip the epilogue field. */ /* fixme: verify the checksum. */ if (resp) { if (n > maxresplen) { DEBUGOUT_2 ("provided buffer too short for received data " "(%u/%u)\n", (unsigned int)n, (unsigned int)maxresplen); return CCID_DRIVER_ERR_INV_VALUE; } memcpy (resp, p, n); resp += n; *nresp += n; maxresplen -= n; } if (!(tpdu[1] & 0x20)) return 0; /* No chaining requested - ready. */ msg = send_buffer; tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */ tpdu[2] = 0; tpdulen = 3; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; } else if ((tpdu[1] & 0xc0) == 0x80) { /* This is a R-block. */ if ( (tpdu[1] & 0x0f)) { retries++; if (via_escape && retries == 1 && (msg[pcboff] & 0x0f)) { /* Error probably due to switching to TPDU. Send a resync request. We use the recv_buffer so that we don't corrupt the send_buffer. */ msg = recv_buffer; tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = 0xc0; /* S-block resync request. */ tpdu[2] = 0; tpdulen = 3; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; resyncing = 1; DEBUGOUT ("T=1: requesting resync\n"); } else if (retries > 3) { DEBUGOUT ("T=1: 3 failed retries\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } else { /* Error: repeat last block */ msg = send_buffer; tpdulen = last_tpdulen; } } else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns) { /* Response does not match our sequence number. */ DEBUGOUT ("R-block with wrong seqno received on more bit\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } else if (sending) { /* Send next chunk. */ retries = 0; msg = send_buffer; next_chunk = 1; handle->t1_ns ^= 1; } else { DEBUGOUT ("unexpected ACK R-block received\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } } else { /* This is a S-block. */ retries = 0; DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n", (tpdu[1] & 0x20)? "response": "request", (tpdu[1] & 0x1f)); if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1) { /* Information field size request. */ unsigned char ifsc = tpdu[3]; if (ifsc < 16 || ifsc > 254) return CCID_DRIVER_ERR_CARD_IO_ERROR; msg = send_buffer; tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */ tpdu[2] = 1; tpdu[3] = ifsc; tpdulen = 4; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc); } else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2]) { /* Wait time extension request. */ unsigned char bwi = tpdu[3]; /* Check if it's unsual value which can't be expressed in ATR. */ if (bwi > 15) wait_more = 1; msg = send_buffer; tpdu = msg + hdrlen; tpdu[0] = nad_byte; tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */ tpdu[2] = 1; tpdu[3] = bwi; tpdulen = 4; edc = compute_edc (tpdu, tpdulen, use_crc); if (use_crc) tpdu[tpdulen++] = (edc >> 8); tpdu[tpdulen++] = edc; DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi); print_progress (handle); } else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2]) { DEBUGOUT ("T=1: resync ack from reader\n"); /* Repeat previous block. */ msg = send_buffer; tpdulen = last_tpdulen; } else return CCID_DRIVER_ERR_CARD_IO_ERROR; } } /* end T=1 protocol loop. */ return 0; } /* Send the CCID Secure command to the reader. APDU_BUF should contain the APDU template. PIN_MODE defines how the pin gets formatted: 1 := The PIN is ASCII encoded and of variable length. The length of the PIN entered will be put into Lc by the reader. The APDU should me made up of 4 bytes without Lc. PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0 may be used t enable reasonable defaults. When called with RESP and NRESP set to NULL, the function will merely check whether the reader supports the secure command for the given APDU and PIN_MODE. */ int ccid_transceive_secure (ccid_driver_t handle, const unsigned char *apdu_buf, size_t apdu_buflen, pininfo_t *pininfo, unsigned char *resp, size_t maxresplen, size_t *nresp) { int rc; unsigned char send_buffer[10+259], recv_buffer[10+259]; unsigned char *msg, *tpdu, *p; size_t msglen, tpdulen, n; unsigned char seqno; size_t dummy_nresp; int testmode; int cherry_mode = 0; int add_zero = 0; int enable_varlen = 0; testmode = !resp && !nresp; if (!nresp) nresp = &dummy_nresp; *nresp = 0; if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1)) ; else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2)) ; else return CCID_DRIVER_ERR_NO_PINPAD; if (!pininfo->minlen) pininfo->minlen = 1; if (!pininfo->maxlen) pininfo->maxlen = 15; /* Note that the 25 is the maximum value the SPR532 allows. */ if (pininfo->minlen < 1 || pininfo->minlen > 25 || pininfo->maxlen < 1 || pininfo->maxlen > 25 || pininfo->minlen > pininfo->maxlen) return CCID_DRIVER_ERR_INV_VALUE; /* We have only tested a few readers so better don't risk anything and do not allow the use with other readers. */ switch (handle->id_vendor) { case VENDOR_SCM: /* Tested with SPR 532. */ case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */ case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */ pininfo->maxlen = 25; enable_varlen = 1; break; case VENDOR_REINER:/* Tested with cyberJack go */ case VENDOR_VASCO: /* Tested with DIGIPASS 920 */ enable_varlen = 1; break; case VENDOR_CHERRY: pininfo->maxlen = 15; enable_varlen = 1; /* The CHERRY XX44 keyboard echos an asterisk for each entered character on the keyboard channel. We use a special variant of PC_to_RDR_Secure which directs these characters to the smart card's bulk-in channel. We also need to append a zero Lc byte to the APDU. It seems that it will be replaced with the actual length instead of being appended before the APDU is send to the card. */ add_zero = 1; if (handle->id_product != CHERRY_ST2000) cherry_mode = 1; break; case VENDOR_NXP: if (handle->id_product == CRYPTOUCAN){ pininfo->maxlen = 25; enable_varlen = 1; } break; default: if ((handle->id_vendor == VENDOR_GEMPC && handle->id_product == GEMPC_PINPAD) || (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)) { enable_varlen = 0; pininfo->minlen = 4; pininfo->maxlen = 8; break; } return CCID_DRIVER_ERR_NOT_SUPPORTED; } if (enable_varlen) pininfo->fixedlen = 0; if (testmode) return 0; /* Success */ if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16) return CCID_DRIVER_ERR_NOT_SUPPORTED; msg = send_buffer; if (handle->id_vendor == VENDOR_SCM) { DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n"); rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3, NULL, 0, NULL); if (rc) return rc; } msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure; msg[5] = 0; /* slot */ msg[6] = seqno = handle->seqno++; msg[7] = 0; /* bBWI */ msg[8] = 0; /* RFU */ msg[9] = 0; /* RFU */ msg[10] = apdu_buf[1] == 0x20 ? 0 : 1; /* Perform PIN verification or PIN modification. */ msg[11] = 0; /* Timeout in seconds. */ msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */ if (handle->id_vendor == VENDOR_SCM) { /* For the SPR532 the next 2 bytes need to be zero. We do this for all SCM products. Kudos to Martin Paljak for this hint. */ msg[13] = msg[14] = 0; } else { msg[13] = pininfo->fixedlen; /* bmPINBlockString: 0 bits of pin length to insert. PIN block size by fixedlen. */ msg[14] = 0x00; /* bmPINLengthFormat: Units are bytes, position is 0. */ } msglen = 15; if (apdu_buf[1] == 0x24) { msg[msglen++] = 0; /* bInsertionOffsetOld */ msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */ } /* The following is a little endian word. */ msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */ msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */ if (apdu_buf[1] == 0x24) msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01; /* bConfirmPIN * 0x00: new PIN once * 0x01: new PIN twice (confirmation) * 0x02: old PIN and new PIN once * 0x03: old PIN and new PIN twice (confirmation) */ msg[msglen] = 0x02; /* bEntryValidationCondition: Validation key pressed */ if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen) msg[msglen] |= 0x01; /* Max size reached. */ msglen++; if (apdu_buf[1] == 0x20) msg[msglen++] = 0x01; /* bNumberMessage. */ else msg[msglen++] = 0x03; /* bNumberMessage. */ msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */ msg[msglen++] = 0x04; /* wLangId-High. */ if (apdu_buf[1] == 0x20) msg[msglen++] = 0; /* bMsgIndex. */ else { msg[msglen++] = 0; /* bMsgIndex1. */ msg[msglen++] = 1; /* bMsgIndex2. */ msg[msglen++] = 2; /* bMsgIndex3. */ } /* Calculate Lc. */ n = pininfo->fixedlen; if (apdu_buf[1] == 0x24) n += pininfo->fixedlen; /* bTeoProlog follows: */ msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0; msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */ if (n) msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */ else msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */ /* APDU follows: */ msg[msglen++] = apdu_buf[0]; /* CLA */ msg[msglen++] = apdu_buf[1]; /* INS */ msg[msglen++] = apdu_buf[2]; /* P1 */ msg[msglen++] = apdu_buf[3]; /* P2 */ if (add_zero) msg[msglen++] = 0; else if (pininfo->fixedlen != 0) { msg[msglen++] = n; memset (&msg[msglen], 0xff, n); msglen += n; } /* An EDC is not required. */ set_msg_len (msg, msglen - 10); rc = bulk_out (handle, msg, msglen, 0); if (rc) return rc; msg = recv_buffer; rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen, RDR_to_PC_DataBlock, seqno, 30000, 0); if (rc) return rc; tpdu = msg + 10; tpdulen = msglen - 10; if (handle->apdu_level) { if (resp) { if (tpdulen > maxresplen) { DEBUGOUT_2 ("provided buffer too short for received data " "(%u/%u)\n", (unsigned int)tpdulen, (unsigned int)maxresplen); return CCID_DRIVER_ERR_INV_VALUE; } memcpy (resp, tpdu, tpdulen); *nresp = tpdulen; } return 0; } if (tpdulen < 4) { #ifdef USE_NPTH npth_unprotect (); #endif libusb_clear_halt (handle->idev, handle->ep_bulk_in); #ifdef USE_NPTH npth_protect (); #endif return CCID_DRIVER_ERR_ABORTED; } if (debug_level > 1) DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n", ((msg[11] & 0xc0) == 0x80)? 'R' : (msg[11] & 0x80)? 'S' : 'I', ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)), ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0, (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":"")); if (!(tpdu[1] & 0x80)) { /* This is an I-block. */ /* Last block sent was successful. */ handle->t1_ns ^= 1; if (!!(tpdu[1] & 0x40) != handle->t1_nr) { /* Response does not match our sequence number. */ DEBUGOUT ("I-block with wrong seqno received\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } handle->t1_nr ^= 1; p = tpdu + 3; /* Skip the prologue field. */ n = tpdulen - 3 - 1; /* Strip the epilogue field. */ /* fixme: verify the checksum. */ if (resp) { if (n > maxresplen) { DEBUGOUT_2 ("provided buffer too short for received data " "(%u/%u)\n", (unsigned int)n, (unsigned int)maxresplen); return CCID_DRIVER_ERR_INV_VALUE; } memcpy (resp, p, n); *nresp += n; } if (!(tpdu[1] & 0x20)) return 0; /* No chaining requested - ready. */ DEBUGOUT ("chaining requested but not supported for Secure operation\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } else if ((tpdu[1] & 0xc0) == 0x80) { /* This is a R-block. */ if ( (tpdu[1] & 0x0f)) { /* Error: repeat last block */ DEBUGOUT ("No retries supported for Secure operation\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } else if (!!(tpdu[1] & 0x10) == handle->t1_ns) { /* Response does not match our sequence number. */ DEBUGOUT ("R-block with wrong seqno received on more bit\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } else { /* Send next chunk. */ DEBUGOUT ("chaining not supported on Secure operation\n"); return CCID_DRIVER_ERR_CARD_IO_ERROR; } } else { /* This is a S-block. */ DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n", (tpdu[1] & 0x20)? "response": "request", (tpdu[1] & 0x1f)); return CCID_DRIVER_ERR_CARD_IO_ERROR; } return 0; } #ifdef TEST static void print_error (int err) { const char *p; char buf[50]; switch (err) { case 0: p = "success"; case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break; case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break; case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break; case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break; case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break; case CCID_DRIVER_ERR_BUSY: p = "busy"; break; case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break; case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break; case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break; case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break; case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break; case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break; default: sprintf (buf, "0x%05x", err); p = buf; break; } fprintf (stderr, "operation failed: %s\n", p); } static void print_data (const unsigned char *data, size_t length) { if (length >= 2) { fprintf (stderr, "operation status: %02X%02X\n", data[length-2], data[length-1]); length -= 2; } if (length) { fputs (" returned data:", stderr); for (; length; length--, data++) fprintf (stderr, " %02X", *data); putc ('\n', stderr); } } static void print_result (int rc, const unsigned char *data, size_t length) { if (rc) print_error (rc); else if (data) print_data (data, length); } int main (int argc, char **argv) { int rc; ccid_driver_t ccid; int slotstat; unsigned char result[512]; size_t resultlen; int no_pinpad = 0; int verify_123456 = 0; int did_verify = 0; int no_poll = 0; if (argc) { argc--; argv++; } while (argc) { if ( !strcmp (*argv, "--list")) { char *p; p = ccid_get_reader_list (); if (!p) return 1; fputs (p, stderr); free (p); return 0; } else if ( !strcmp (*argv, "--debug")) { ccid_set_debug_level (ccid_set_debug_level (-1)+1); argc--; argv++; } else if ( !strcmp (*argv, "--no-poll")) { no_poll = 1; argc--; argv++; } else if ( !strcmp (*argv, "--no-pinpad")) { no_pinpad = 1; argc--; argv++; } else if ( !strcmp (*argv, "--verify-123456")) { verify_123456 = 1; argc--; argv++; } else break; } rc = ccid_open_reader (&ccid, argc? *argv:NULL, NULL); if (rc) return 1; if (!no_poll) ccid_poll (ccid); fputs ("getting ATR ...\n", stderr); rc = ccid_get_atr (ccid, NULL, 0, NULL); if (rc) { print_error (rc); return 1; } if (!no_poll) ccid_poll (ccid); fputs ("getting slot status ...\n", stderr); rc = ccid_slot_status (ccid, &slotstat, 1); if (rc) { print_error (rc); return 1; } if (!no_poll) ccid_poll (ccid); fputs ("selecting application OpenPGP ....\n", stderr); { static unsigned char apdu[] = { 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01}; rc = ccid_transceive (ccid, apdu, sizeof apdu, result, sizeof result, &resultlen); print_result (rc, result, resultlen); } if (!no_poll) ccid_poll (ccid); fputs ("getting OpenPGP DO 0x65 ....\n", stderr); { static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 }; rc = ccid_transceive (ccid, apdu, sizeof apdu, result, sizeof result, &resultlen); print_result (rc, result, resultlen); } if (!no_pinpad) { } if (!no_pinpad) { static unsigned char apdu[] = { 0, 0x20, 0, 0x81 }; if (ccid_transceive_secure (ccid, apdu, sizeof apdu, 1, 0, 0, 0, NULL, 0, NULL)) fputs ("can't verify using a PIN-Pad reader\n", stderr); else { fputs ("verifying CHV1 using the PINPad ....\n", stderr); rc = ccid_transceive_secure (ccid, apdu, sizeof apdu, 1, 0, 0, 0, result, sizeof result, &resultlen); print_result (rc, result, resultlen); did_verify = 1; } } if (verify_123456 && !did_verify) { fputs ("verifying that CHV1 is 123456....\n", stderr); { static unsigned char apdu[] = {0, 0x20, 0, 0x81, 6, '1','2','3','4','5','6'}; rc = ccid_transceive (ccid, apdu, sizeof apdu, result, sizeof result, &resultlen); print_result (rc, result, resultlen); } } if (!rc) { fputs ("getting OpenPGP DO 0x5E ....\n", stderr); { static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 }; rc = ccid_transceive (ccid, apdu, sizeof apdu, result, sizeof result, &resultlen); print_result (rc, result, resultlen); } } ccid_close_reader (ccid); return 0; } /* * Local Variables: * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c" * End: */ #endif /*TEST*/ #endif /*HAVE_LIBUSB*/