diff --git a/ChangeLog b/ChangeLog index f96332e20..db51b56d9 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,1190 +1,1194 @@ +2010-03-12 Werner Koch + + * configure.ac (AC_INIT): Prepare for using git. + 2010-03-10 Werner Koch * jnlib/: Move all code to common/. * Makefile.am (SUBDIRS): Remove jnlib. * configure.ac (AC_CONFIG_FILES): Remove jnlib/Makefile. * configure.ac (AM_PATH_LIBASSUAN): Remove double test. * acinclude.m4 (GNUPG_CHECK_ENDIAN): Remove bogus warning. 2010-03-09 Werner Koch * configure.ac: Add option --disable-ccid-driver. (AH_BOTTOM): Define GPG_ERR_ENABLE_GETTEXT_MACROS. 2010-02-26 Werner Koch * gl/mkdtemp.c (__set_errno) [W32CE]: Use gpg_err_set_errno. * gl/setenv.c (__set_errno) [W32CE]: Ditto. * gl/unsetenv.c (__set_errno) [W32CE]: Ditto. * configure.ac (HAVE_W32CE_SYSTEM): New ac_define and am_conditional. (signal.h, getenv): Check for them. * autogen.sh: New option --build-w32ce. Remove obsolete option --without-included-gettext. 2009-12-08 Werner Koch * configure.ac (USE_DNS_CERT): Support ADNS. 2009-12-07 Werner Koch * configure.ac: Check for ADNS before checking for the BIND resolver. (USE_ADNS): Fallback macro for PKA and CERT lookups. 2009-10-20 Marcus Brinkmann * configure.ac: Check for fusermount and encfs. 2009-10-16 Marcus Brinkmann * configure.ac: Check for libassuan instead of libassuan-pth. 2009-10-12 Werner Koch * configure.ac: Use -O3 because newer gcc versions require that for uninitialized variable warnings. 2009-09-23 Werner Koch * configure.ac (HAVE_ASSUAN_SET_IO_MONITOR): Remove test. (_ASSUAN_ONLY_GPG_ERRORS): Remove. 2009-09-23 Marcus Brinkmann * configure.ac (NEED_LIBASSUAN_API, NEED_LIBASSUAN_VERSION): Update to new API (2, 1.1.0). 2009-09-21 Werner Koch Start a new development branch in the SVN trunk. The stable one is now known in the SVN as branches/GNUPG-STABLE-2-0. 2009-09-04 Werner Koch Release 2.0.13. 2009-06-29 Werner Koch * configure.ac: Take care of --without-adns. Suggested by Arfrever Frehtes Taifersar Arahesis. 2009-06-17 Werner Koch Release 2.0.12. 2009-06-05 David Shaw * configure.ac: Remove Camellia restriction. 2009-04-01 Werner Koch * configure.ac: Test for fsync. 2009-03-18 Werner Koch * configure.ac: Test for getrlimit. 2009-03-03 Werner Koch Release 2.0.11. 2009-01-12 Werner Koch Release 2.0.10. 2008-12-09 Werner Koch Release 2.0.10rc1. 2008-10-17 Werner Koch * configure.ac: Use more warning options with modern GCCs. 2008-09-29 Werner Koch * configure.ac: Require libgcrypt 1.4. 2008-08-27 David Shaw * configure.ac: Use printf for the most portable SVN version detection. * configure.ac: Darwin's /bin/sh has a builtin echo that doesn't understand '-n'. Use tr to trim the carriage return instead. 2008-04-23 Werner Koch * configure.ac: Call gl_HEADER_SYS_SOCKET and gl_TYPE_SOCKLEN_T. 2008-04-07 Werner Koch * configure.ac (ADNSLIBS): Test for adns. (GPGKEYS_KDNS): New. 2008-04-01 Werner Koch * configure.ac: Require curl 7.10 (Oct 1 2002) or later as we use curl_version_info(). (AC_INIT): Fix quoting. 2008-03-27 Werner Koch * Makefile.am (dist_doc_DATA): New. Install README. 2008-03-26 Werner Koch Release 2.0.9. 2008-02-19 Werner Koch * configure.ac: Remove --with-pkits-tests. 2008-02-15 Werner Koch * gl/allocsa.h, gl/m4/allocsa.m4: Replace HAVE_LONG_LONG by HAVE_LONG_LONG_INT. 2008-02-15 gettextize * configure.ac (AM_GNU_GETTEXT_VERSION): Bump to 0.17. 2007-12-20 Werner Koch Released 2.0.8. 2007-12-17 Werner Koch * configure.ac: Add treatment for HAVE_LDAP_START_TLS_SA. 2007-12-14 Werner Koch Released 2.0.8rc1. 2007-12-12 Werner Koch * configure.ac (USE_CAMELLIA): Define by new option --enable-camellia. 2007-12-03 Werner Koch * configure.ac: Add test gt_LC_MESSAGES.. 2007-10-01 Werner Koch * configure.ac: Require assuan 1.0.4. 2007-09-14 Werner Koch * configure.ac (GNUPG_LIBASSUAN_VERSION): New. 2007-09-10 Werner Koch Released 2.0.7. 2007-08-27 Werner Koch * configure.ac: Remove remaining support for internal regex. Define DISABLE_REGEX automake conditional. Add option --with-regex. * autogen.sh [--build-w32]: Remove --disable-regex. Use --with-regex. 2007-08-16 Werner Koch Released 2.0.6. 2007-08-08 Werner Koch * configure.ac: Use AC_CANONICAL_HOST and not AC_CANONICAL_TARGET. 2007-07-09 Werner Koch * configure.ac (AM_ICONV): Check for it even when building without NLS. 2007-07-05 Werner Koch Released 2.0.5. * configure.ac: Require libassuan 1.0.2. 2007-07-05 Marcus Brinkmann * configure.ac: Invoke AM_LANGINFO_CODESET. 2007-07-04 Werner Koch * Makefile.am (AUTOMAKE_OPTIONS): Add no-dist-gzip. Switched entire package to GPLv3+. * configure.ac: Require libksba 1.0.2. * COPYING: Updated to GPLv3. * COPYING.LIB: New as jnlib/ uses this license. * gl/: Switched to GPLv3+. * intl/ Removed. * configure.ac (AM_GNU_GETTEXT): Add external flag. (AM_ICONV): New. 2007-07-03 Werner Koch * configure.ac [W32]: Use ws2_32 instead of wsock32. 2007-06-25 Werner Koch * gl/mkdtemp.c (gen_tempname) [MKDIR_TAKES_ONE_ARG]: Avoid compiler warning by using the proper config macro. 2007-06-15 Werner Koch * configure.ac: Call AM_PO_SUBDIRS. (W32SOCKLIBS): New. * autogen.sh: Use = and not == in test to be POSIXly correct. : Disable use of regex. 2007-06-14 Werner Koch * configure.ac [AH_BOTTOM]: Remove the hardwired names of modules. 2007-06-12 Werner Koch * configure.ac [AH_BOTTOM]: Define HTTP_NO_WSASTARTUP. 2007-06-11 Werner Koch * am/cmacros.am (libcommonstd, libcommonpth, libcommonstd_ldadd) (libcommonpth_ldadd): Add macros. 2007-06-06 Werner Koch * configure.ac: Add a few notices message so make browsing of the log file easier. (CC_FOR_BUILD): New. 2007-05-30 Werner Koch * configure.ac [W32]: Do not create a symlink to w32-pth.h. Require the installation of the w32pth package. 2007-05-29 Werner Koch * gl/: Updated to a newer version. 2007-05-24 Werner Koch * configure.ac: Use -Wpointer-arith is possible. 2007-05-15 Werner Koch * configure.ac: Renamed the estream macros. Remove -Wformat-nonliteral. * configure.ac: Call ESTREAM_INIT and define the memory allocators for estream_asprintf. (gl_MODULES): Remove vasprintf. 2007-05-09 Werner Koch Released 2.0.4. 2007-05-07 Werner Koch * configure.ac: Require libgcrypt 1.2.2 to avoid compiler warnings. 2007-05-07 gettextize * configure.ac (AM_GNU_GETTEXT_VERSION): Bump to 0.16.1. 2007-05-07 Werner Koch * configure.ac: Bail out if no C-89 compiler has been found. 2007-05-04 Werner Koch * Makefile.am (DISTCHECK_CONFIGURE_FLAGS): Add --enable-mailto * configure.ac: Require automake 1.10 (AC_CONFIG_FILES): Rename gpgkeys_ to gpg2keys_. (AM_PROG_CC_C_O): New. 2007-03-08 Werner Koch Released 2.0.3. * autogen.sh: Add option --force. 2007-01-31 Werner Koch Released 2.0.2. 2006-11-30 Werner Koch * configure.ac: Save original LIBS when testing for dlopen. 2006-11-28 Werner Koch Released 2.0.1. 2006-11-23 Werner Koch Released 2.0.1rc1. 2006-11-21 Werner Koch * configure.ac [AH_BOTTOM]: Disable PTH soft mapping. (AC_CHECK_SIZEOF): Check for time_t. (BUILD_INCLUDED_LIBINTL): Remove AM_PO_SUBDIRS as it is not required for C. 2006-11-15 Werner Koch * autogen.sh: Add convenience option --build-amd64. 2006-11-14 Werner Koch * configure.ac (HAVE_ASSUAN_SET_IO_MONITOR): Test for it. 2006-11-11 Werner Koch Released 2.0.0. 2006-11-06 Werner Koch Released 1.9.95. 2006-11-03 Werner Koch * configure.ac: Test for pty.h. From Gentoo. 2006-10-24 Werner Koch Released 1.9.94. 2006-10-20 Werner Koch * Makefile.am (stowinstall): Add convenience target. 2006-10-18 Werner Koch * configure.ac: svn revison magic fixes for old bashs. Suggested by Alain Guibert. 2006-10-18 Werner Koch Released 1.9.93. 2006-10-17 Werner Koch * autogen.sh <--build-w32>: Test also for a host "mingw32". * configure.ac: Removed W32LIBS. Use NETLIBS instead. 2006-10-11 Werner Koch Released 1.9.92. * configure.ac: Require libassuan 0.9.3. 2006-10-09 Werner Koch * acinclude.m4: Moved pth check to m4/gnupg-pth.m4. 2006-10-06 Werner Koch * configure.ac: Also check for libassuan's pth version. 2006-10-04 Werner Koch Released 1.9.91. * configure.ac: Require libassuan 0.9.1 which fixes a problem with gpgsm. 2006-09-27 Werner Koch * gl/strsep.h, gl/strsep.c, gl/m4/strsep.m4: Removed. * gl/strpbrk.h, gl/strpbrk.c, gl/m4/strpbrk.m4: Removed. * gl/Makefile.am: Removed module strsep and strpbrk. * configure.ac: Check for strsep in the context of jnlib. Remove check from gl_MODULES. Moved check for timegm into the jnlib context. 2006-09-27 Marcus Brinkmann * Makefile.am: Fix cut & paste error. 2006-09-25 Werner Koch Released 1.9.90. 2006-09-22 Werner Koch * AUTHORS: Add information about used licenses. 2006-09-20 Werner Koch * Makefile.am (dist-hook): Removed distfiles cruft. (SUBDIRS): Added include 2006-09-18 Werner Koch Released 1.9.23. * configure.ac (--enable-agent-only): Donot build tools and doc (--disable-tools,--disable-doc): New. * Makefile.am (SUBDIRS): Allow to conditional build tools and doc. 2006-09-14 Werner Koch Replaced all call gpg_error_from_errno(errno) by gpg_error_from_syserror(). * configure.ac: Build gpg by default. (GNUPG_SYS_SO_PEERCRED): Removed. 2006-09-13 Werner Koch * autogen.sh: Better detection of the cross compiler kit. 2006-09-06 Marcus Brinkmann * configure.ac: New automake conditional RUN_GPG_TESTS. 2006-09-06 Werner Koch * configure.ac: Define _ASSUAN_ONLY_GPG_ERRORS. Require Assuan 0.9 and libgpg-error 1.4. 2006-08-31 Werner Koch * configure.ac: Require libksba 1.0 and added API check for it. (GPG_ERR_LOCKED): Removed DECL check as we require 1.2 anyway. (have_libusb): New to give a feedback about CCID support 2006-08-21 Werner Koch * configure.ac: Removed docbook tests. (AC_CONFIG_FILES): Added gpgkeys_test and gpgkeys_mailto. * Makefile.am (DISTCHECK_CONFIGURE_FLAGS): Enable gpg. 2006-08-17 Werner Koch * THANKS: Merged with the 1.4 one. 2006-08-16 Werner Koch * configure.ac: Removed test for capabilities and mlock. 2006-08-15 Werner Koch * Makefile.am (keyserver): Enable building of keyserver helpers. * configure.ac: Merged with the current configure from 1.4.5. Require libgpg-error 1.2 and libksba 0.9.16. 2006-07-29 Marcus Brinkmann * README: Spelling fixes. 2006-07-27 Werner Koch Released 1.9.22. * configure.ac: Call AB_INIT. 2006-07-03 Werner Koch * configure.ac: Test for ksba_dn_teststr. 2006-06-30 Werner Koch * keyserver/: New. Taken from 1.4.4 * Makefile.am (SUBDIRS): Include keyserver/. * configure.ac: Include keyserver/. (FAKE_CURL, GPGKEYS_CURL): New. 2006-06-20 Werner Koch Released 1.9.21. 2006-06-08 Marcus Brinkmann * configure.ac (PTH_LIBS): Add --all to pth-config invocation. 2006-05-24 Werner Koch * configure.ac: New option --disable-optimization taked from 1.4.3. 2006-05-23 Werner Koch * configure.ac (ZLIBS): New for zlib link commands. Add bzip2 support. 2006-05-22 Werner Koch * configure.ac (EXEEXT): New. 2006-04-18 Werner Koch * configure.ac (PK_UID_CACHE_SIZE): New. 2006-04-07 Werner Koch * configure.ac: Use new method to include the SVN revison. Now it is the actual global revision number. 2005-12-20 Werner Koch Released 1.9.20. 2005-11-28 Werner Koch * configure.ac: Append the revision to the version string. 2005-11-13 Werner Koch * am/cmacros.am (-DGNUPG_SYSCONFDIR): Define it. 2005-11-11 Werner Koch * configure.ac (NEED_KSBA_VERSION: Require 0.9.13. 2005-09-12 Werner Koch Released 1.9.19. 2005-08-01 Werner Koch Released 1.9.18. * configure.ac: Require libksba 0.9.12 to match new features in gpgsm. 2005-06-20 Werner Koch Released 1.9.17. 2005-06-02 Werner Koch * configure.ac (HAVE_PTH): Define as alias for USE_GNU_PTH. It is used by common/estream.c. 2005-06-01 Werner Koch * configure.ac (gl_INIT): Add gnulib stuff. (fseeko, ftello, ttyname, isascii): Replaced the AC_REPLACE_FUNCS by a simple check. (putc_unlocked): Removed check. Not used. (strsep, mkdtemp, asprintf): Replaced checks by gnulib checks. (xsize): Added will probably come handy soon. (CFLAGS): Use -Wformat-security instead of -Wformat-nonliteral. Add --Wno-format-y2k. * gl/, gl/m4/: New. 2005-05-15 Werner Koch * configure.ac: Remove option --disable-threads; require the use of GNU Pth. 2005-04-27 Werner Koch * configure.ac: Removed OpenSC detection and options. * acinclude.m4: Ditto. 2005-04-21 Werner Koch Released 1.9.16. * configure.ac: Do not build gpg by default. 2005-04-20 Werner Koch * configure.ac: Test whether GPG_ERR_LOCKED is declared and provide a replacement if not. 2005-04-15 Werner Koch * configure.ac: Require libksba 0.9.11. 2005-04-15 Marcus Brinkmann * configure.ac: Check for /usr/bin/shred and define SHRED. * configure.ac: Add --enable-symcryptrun, disabled by default. Define automake variable BUILD_SYMCRYPTRUN. Check for openpty -lutil, define LIBUTIL_LIBS. 2005-03-03 Werner Koch * acinclude.m4 (GNUPG_PTH_VERSION_CHECK): Accidently used --ldflags instead of --cflags. Reported by Kazu Yamamoto. 2005-02-03 Werner Koch * AUTHORS: Copied from 1.4 and edited to refelct the changes in 1.9. 2005-01-17 Werner Koch * configure.ac: Make --without-included-regex work as expected. Fixed FTP location info for some libraries. 2005-01-13 Werner Koch Released 1.9.15. * acinclude.m4 (GNUPG_PTH_VERSION_CHECK): Link a simple test program to see whether the installation is sane. 2005-01-07 Werner Koch * configure.ac: Require gpg-error 1.0. 2005-01-04 Werner Koch * configure.ac: Remove hack not to build gpg2 for W32. * autogen.sh : Pass option --disable-gpg instead. 2004-12-22 Werner Koch Released 1.9.14. 2004-12-20 Werner Koch * configure.ac: Add PATHSEP_C and PATHSEP_S. For W32 let all directories default to c:/gnupg. Require libassuan 0.6.9. 2004-12-18 Werner Koch * configure.ac (AH_BOTTOM): Define EXEEXT_S. * autogen.sh: Updated --build-w32 feature. 2004-12-15 Werner Koch * Makefile.am (SUBDIRS) [W32]: Do not build in tests/. * acinclude.m4: Add proper macro name quoting for use with automake 1.9. * configure.ac: Add replacement check for ttyname. Removed support for a included zlib. 2004-12-06 Werner Koch * configure.ac (have_w32_system): New. Disable Pth checks for W32. Link jnlib/w32-pth.h to pth.h. 2004-12-03 Werner Koch Released 1.9.13. 2004-11-26 Werner Koch * configure.ac: Replace strsep. Replaced use of "target" by "host". 2004-10-22 Werner Koch Released 1.9.12. * Makefile.am (AUTOMAKE_OPTIONS): Set option to create bzip2 tarball. 2004-10-01 Werner Koch Released 1.9.11. 2004-09-30 Werner Koch * README: Minor updates. 2004-09-30 gettextize * configure.ac (AM_GNU_GETTEXT_VERSION): Bump to 0.14.1. 2004-08-16 Werner Koch * configure.ac: Build Makefile for tests/pkits. New option --with-pkits-tests. 2004-08-05 Werner Koch * configure.ac: Changed tests for libusb to also suuport the stable version 0.1.x. 2004-07-22 Werner Koch Released 1.9.10. * configure.ac: Define AM conditional HAVE_OPENSC. 2004-07-21 Werner Koch * configure.ac: Don't set DIE to no after it might has been set to yes. 2004-07-20 Werner Koch * Makefile.am (sm): Build kbx only if gpgsm is to be build. 2004-07-20 Werner Koch * configure.ac: New option --enable-agent-only. 2004-06-08 Werner Koch Released 1.9.9. 2004-06-06 Werner Koch * configure.ac: Require libksba 0.9.7. 2004-04-29 Werner Koch Released 1.9.8. 2004-04-20 Werner Koch * configure.ac: Remove the fopencookie test. We don't need the dummy function because we conditionally use fopencookie, fpencookie or a replacement at place. 2004-04-02 Thomas Schwinge * autogen.sh: Added ACLOCAL_FLAGS. 2004-04-06 Werner Koch Released 1.9.7. * configure.ac: Require libgcrypt 1.1.94. Introduce PACKAGE_GT and set it to gnupg2. 2004-03-23 Werner Koch * configure.ac: Define SAFE_VERSION_DASH and SAFE_VERSION_DOT. 2004-03-09 Werner Koch * configure.ac (NEED_GPG_ERROR_VERSION): Set to 0.7. 2004-03-06 Werner Koch Released 1.9.6. * configure.ac: Check the Libgcrypt API. 2004-02-25 Werner Koch * configure.ac: New option --disable-threads to inhibit unintentional builds without Pth. 2004-02-21 Werner Koch Released 1.9.5. 2004-02-20 Werner Koch * configure.ac: Fixed URLs in the notice messages. 2004-02-18 Werner Koch * acinclude.m4: Removed macros to detect gpg-error, libgcrypt, libassuan and ksba as they are now distributed in m4/. 2004-02-13 Werner Koch * configure.ac: Require libksba 0.9.4 and libgcrypt 1.1.92. 2004-02-12 Werner Koch * autogen.sh: Removed cruft from debugging. * am/cmacros.am: New. 2004-02-11 Werner Koch * configure.ac: Removed the need for g10defs.h. Reworked the --with-foo-pgm stuff. * autogen.sh (check_version): Removed bashism and simplified. * acinclude.m4 (AM_PATH_OPENSC): Kludge to avoid error output for a bad opensc-config. 2004-01-30 Werner Koch Released 1.9.4. * configure.ac: Require libksba 0.9.3 due to another bug fix there. 2004-01-29 Werner Koch * README: Updated. * configure.ac: Require libksba 0.9.2 due to bug fixes. 2004-01-24 Werner Koch * configure.ac: Now requires libassuan 0.6.3. 2003-12-23 Werner Koch Released 1.9.3. * README-alpha: Removed. * configure.ac, Makefile.am: Add the tests and tools directories. 2003-12-19 Werner Koch * configure.ac: Now require libgcrypt 1.1.91 to help testing the latest libgcrypt changes. Requires libksab 0.9.1. 2003-12-17 Werner Koch * configure.ac: Requires now libassuan 0.6.2. (CFLAGS): Add --Wformat-noliteral in gcc mode. 2003-12-16 Werner Koch * configure.ac: Check for funopen and fopencookie as part of the jnlib checks. 2003-12-09 Werner Koch * configure.ac: Add a min_automake_version. * README.CVS: New. * autogen.sh: Revamped except for the --build-w32 hack. * Makefile.am: Add README.CVS 2003-11-17 Werner Koch Release 1.9.2. * configure.ac: Requires now libassuan 0.6.1. 2003-10-31 Werner Koch * configure.ac (NEED_KSBA_VERSION): Set to 0.9.0 due the changed time interface. 2003-10-21 Werner Koch * configure.ac (PRINTABLE_OS_NAME): Remove special case for The Hurd; Robert Millan reported that the uname test is now sufficient. 2003-10-01 Werner Koch * configure.ac (AH_BOTTOM): Define GNUPG_MAJOR_VERSION. 2003-09-23 Werner Koch Merged most of David Shaw's changes in 1.3 since 2003-06-03. * configure.ac: Drop all TIGER/192 support. (uint64_t): Check for UINT64_C to go along with uint64_t. (getaddrinfo): Check for it. (sigset_t): Check for sigset_t and struct sigaction. This is for Forte c89 on Solaris which seems to define only the function call half of the two pairs by default. (W32LIBS): Include wsock32 in W32LIBS. This is different from NETLIBS so we don't need to force other platforms to pull in the netlibs when they aren't actually needed. 2003-09-06 Werner Koch Released 1.9.1. * configure.ac: Require newer versions of some libraries. 2003-09-02 Werner Koch * configure.ac (HAVE_LIBUSB): Added a simple test for libusb. 2003-08-19 Marcus Brinkmann * configure.ac (AM_PATH_GPG_ERROR): Add missing comma in invocation. 2003-08-06 Werner Koch * configure.ac: Check for libgpg-error. Print infos about missing libraries more nicely. * acinclude.m4 (AM_PATH_GPG_ERROR): Added. 2003-08-05 Werner Koch Released 1.9.0. * configure.ac (GNUPG_DEFAULT_HONMEDIR): Changed back to ~/.gnupg. 2003-07-31 Werner Koch * Makefile.am (DISTCLEANFILES): Add g10defs.h 2003-06-18 Werner Koch * configure.ac (GNUPG_DEFAULT_HOMEDIR): Changed temporary to .gnupg2 to avoid accidential use with production keys. 2003-06-11 Werner Koch * configure.ac: Merged all stuff from current 1.3 version in. * acinclude.m4: Merged required macros from current 1.2 version in. 2003-06-04 Werner Koch * configure.ac, Makefile.am: Enable building of gpg. 2003-04-29 Werner Koch * configure.ac: Build a limited version of scdaemon if libopensc is not available. * configure.ac (ALL_LINUGAS): Removed. * Makefile.am (ACLOCAL_AMFLAGS): New. * configure.ac (AM_GNU_GETTEXT_VERSION): New. Set to 0.11.5. 2003-04-29 gettextize * Makefile.am (SUBDIRS): Add m4. (ACLOCAL_AMFLAGS): New variable. (EXTRA_DIST): Add scripts/config.rpath. * configure.ac (AC_CONFIG_FILES): Add m4/Makefile. 2003-04-29 Werner Koch * assuan/ : Removed. We now use libassuan. * Makefile.am (SUBDIRS): Removed assuan * configure.ac: Check for libassuan. 2003-01-09 Werner Koch * configure.ac (GNUPG_PROTECT_TOOL): New option --with-protect-tool. (NEED_KSBA_VERSION): Does now require 0.4.6. * README: Noted where to find gpg-protect-tool. 2002-10-31 Neal H. Walfield * configure.ac: Check for flockfile and funlockfile. Check for isascii and putc_unlocked replacing them if not found. * configure.ac (PTH_LIBS): If pth is found, add the output of `$PTH_CONFIG --ldflags`, not just `$PTH_CONFIG --libs`. 2002-10-19 Werner Koch * configure.ac: Bumped version number to 1.9.0-cvs. NewPG (Aegypten project) to GnuPG merge. 2002-09-20 Werner Koch Released 0.9.2. 2002-09-05 Neal H. Walfield * configure.ac: Check for makeinfo. 2002-09-03 Neal H. Walfield * autogen.sh (have_version): New function. Generalize and simplify logic for finding and determining the versions of GNU programs. Use it. 2002-08-23 Werner Koch Released 0.9.1. * acinclude.m4 (AM_PATH_LIBGCRYPT): Updated from Libgcrypt. (AM_PATH_OPENSC): Strip non-digits from the micro version. 2002-08-21 Werner Koch Released 0.9.0. * configure.ac: Changed the default homedir to .gnupg. * README-alpha: Removed. 2002-08-19 Werner Koch * acinclude.m4: Removed -lpcsclite from KSBA_LIBS; copy+paste bug. 2002-08-13 Werner Koch * acinclude.m4 (AM_PATH_OPENSC, AM_PATH_KSBA): New. * configure.ac: Use them. 2002-08-10 Werner Koch Released 0.3.10. * configure.ac (NEED_LIBKSBA_VERSION): Require 0.4.4. Add support for gettext. 2002-07-22 Werner Koch * configure.ac: Check for ftello and provide a replacement. 2002-07-01 Werner Koch Released 0.3.9. * README: Short note on how to export in pkcs-12 format. 2002-06-29 Werner Koch * configure.ac: Define --with options to set the default location of the agent, scdaemon, pinentry and dirmngr. 2002-06-27 Werner Koch * README: Short blurb on how to import a PKCS-12 file. * configure.ac (AH_BOTTOM): New to define some constants. 2002-06-25 Werner Koch Released 0.3.8. * configure.ac (NEED_LIBGCRYPT_VERSION): Set to 1.1.8. 2002-06-12 Werner Koch * configure.ac (NEED_LIBKSBA_VERSION): We need 0.4.3 now. 2002-06-04 Werner Koch Released 0.3.7. 2002-05-21 Werner Koch * configure.ac: We now require libgcrypt 1.1.7 and libksba 0.4.2. 2002-05-14 Werner Koch * doc/: New * configure.ac, Makefile.am: Added doc/. 2002-05-03 Werner Koch Released 0.3.6. 2002-04-25 Werner Koch * configure.ac: Check for setlocale. 2002-04-24 Marcus Brinkmann * configure.ac: Check for locale.h. 2002-04-15 Werner Koch Released 0.3.5. * NEWS: Started to describe release notes. * configure.ac (NEED_LIBKSBA_VERSION, NEED_LIBGCRYPT_VERSION): Defined 2002-04-01 Werner Koch Released 0.3.4. 2002-03-18 Werner Koch Released 0.3.3. 2002-03-08 Werner Koch * README: Add some explanation on how to specify a user ID. 2002-03-06 Werner Koch Released 0.3.2. 2002-03-04 Werner Koch Released 0.3.1. * README: Explained some options and files. 2002-02-14 Werner Koch * configure.ac: Fixed status messages related to presence of Pth. 2002-02-13 Werner Koch * acinclude.m4 (GNUPG_SYS_SO_PEERCRED): New. * configure.ac: use it. 2002-02-12 Werner Koch * configure.ac: Check for PTH. Provide replacement fucntions for apsrintf and fopencookie. * acinclude.m4 (GNUPG_PTH_VERSION_CHECK): New. 2002-02-07 Werner Koch Released 0.3.0. * configure.ac: Require libgcrypt 1.1.6. 2002-02-01 Marcus Brinkmann * configure.ac (KSBA_CONFIG): Remove superfluous x in front of variable. 2002-01-26 Werner Koch * configure.ac: Add options to disable the build of some programs and print a configure status at the end. * acinclude.m4 (GNUPG_BUILD_PROGRAM): New. * scd/ : New. Added to Makefile and configure. * configure.ac: Check for libopensc * Makefile.am: Build scd only when libopensc is available 2002-01-23 Werner Koch * configure.ac (mkdtemp): See whether we have to provide a replacement. 2001-12-18 Werner Koch Released 0.0.0. 2001-12-17 Werner Koch * acinclude.m4: Add AM_PATH_LIBGCRYPT macro. * configure.ac: and use it here. Figure out the location of libksba 2001-12-15 Werner Koch * configure.ac (missing_dir): Bail out if asprintf and fopencookie are not available. 2001-12-04 Werner Koch * configure.ac (HAVE_JNLIB_LOGGING): always define it. Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007. 2010 Free Software Foundation, Inc. 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/common/ChangeLog b/common/ChangeLog index 6f33deee8..d9ff6a729 100644 --- a/common/ChangeLog +++ b/common/ChangeLog @@ -1,1697 +1,1713 @@ +2010-03-12 Werner Koch + + * status.h (STATUS_ENTER): New. + + * ttyio.c (tty_fprintf): Change to use estream. + + * miscellaneous.c (print_utf8_string): Rename to print_utf8_buffer + and change FP arg to an estream. Change all callers. + (print_utf8_string2): Ditto; new name is to print_utf8_buffer2. + 2010-03-11 Werner Koch + * miscellaneous.c (print_string): Remove. + * estream.c (es_setvbuf): Fix parameter check. (es_set_buffering): Allow a SIZE of 0. * asshelp.c (setup_libassuan_logging, my_libassuan_log_handler): New. * logging.c (do_logv): Add arg IGNORE_ARG_PTR. Change all callers. (log_string): New. + (log_flush): New. + (set_file_fd): Simplify by using estreams es_stderr. + + * estream.h (es_stdout, es_stderr, es_stdin): New. 2010-03-10 Werner Koch * estream.c (es_func_fp_read, es_func_fp_write, es_func_fp_seek) (es_func_fp_destroy): Allow a NULL FP to implement a dummy stream. (do_fpopen): Ditto. (es_vfprintf_unlocked): New. (es_fprintf_unlocked): Make public. (es_fputs_unlocked): New. * logging.h: Replace FILE* by estream_t. * logging.c: Remove USE_FUNWRITER cpp conditional because we now use estream. (my_funopen_hook_ret_t, my_funopen_hook_size_t): Replace by ssize_t. (log_get_stream): Change to return an estream_t. (set_file_fd): Always close the log stream because it can't be assigned to stderr or stdout directly. Use a dummy estream as last resort log stream. (log_test_fd, log_get_fd): Use es_fileno. (log_get_stream): Assert that we have a log stream. (do_logv): Use estream functions and lock the output. 2010-03-10 Werner Koch * util.h: Replace jnlib path part by common. (snprintf): Use the replacement macro on all platforms. * Makefile.am (jnlib_sources): New. (libcommon_a_SOURCES, libcommonpth_a_SOURCES): Add jnlib_sources. (jnlib_tests): New. (noinst_PROGRAMS, TESTS): Add jnlib_tests. (t_common_ldadd): Remove libjnlib.a. * README.jnlib, ChangeLog.jnlib, libjnlib-config.h, argparse.c * argparse.h, dotlock.c, dotlock.h, dynload.h, logging.c * logging.h, mischelp.c, mischelp.h, stringhelp.c, stringhelp.h * strlist.c, strlist.h, types.h, utf8conv.c, utf8conv.h * w32-afunix.c, w32-afunix.h, w32-reg.c, w32help.h, xmalloc.c * xmalloc.h, t-stringhelp.c, t-support.c, t-support.h * t-timestuff.c, t-w32-reg.c: Move from jnlib to here. * init.c: Remove "estream.h". * util.h: Include "estream.h". * xasprintf.c, ttyio.c: Remove "estream-printf.h". 2010-03-08 Werner Koch * exechelp.c [!HAVE_SIGNAL_H]: Do not include signal.h. (DETACHED_PROCESS, CREATE_NEW_PROCESS_GROUP) [W32CE]: Provide stubs. * iobuf.h (iobuf_ioctl_t): New. Use the new macros instead of the hard wired values. * iobuf.c (iobuf_append): Remove. (iobuf_fdopen): Factor code out to ... (do_iobuf_fdopen): ... new. (iobuf_fdopen_nc): New. (iobuf_open_fd_or_name): Implement using iobuf_fdopen_nc. * iobuf.c (INVALID_FD): Replace by GNUPG_INVALID_FD. (fp_or_fd_t): Replace by gnupg_fd_t. (my_fileno): Replace by the FD2INT macro. (FILEP_OR_FD_FOR_STDIN, FILEP_OR_FD_FOR_STDOUT): Rename to FD_FOR_STDIN, FD_FOR_STDOUT. (file_filter): Make full use of FD_FOR_STDIN. (USE_SETMODE): Remove. Not needed without stdio. (my_fopen_ro, my_fopen): Replace unneeded macros. * iobuf.c [FILE_FILTER_USES_STDIO]: Remove all code. It has not been used for a long time. * exechelp.h: Include "estream.h". * exechelp.c (gnupg_spawn_process): Change OUTFILE to an estream_t. 2010-03-02 Werner Koch * estream.c, estream.h, estream-printf.c, estream-printf.h: Update from libestream. 2010-03-01 Werner Koch * signal.c [!HAVE_SIGNAL_H]: Don't include signal.h. * iobuf.c (direct_open) [W32CE]: Make filename to wchar_t. (iobuf_cancel) [W32CE]: Use DeleteFile. * gettime.c (dump_isotime): Use "%s" to print "none". * homedir.c (standard_homedir) [W32CE]: Use wchar_t to create the directory. (w32_rootdir) [W32CE]: Likewise. * sysutils.c (translate_sys2libc_fd) [W32CE]: Add support. (gnupg_tmpfile) [W32CE]: Ditto. (_gnupg_getenv) [W32CE]: New. * util.h (getpid, getenv) [W32CE]: New. * i18n.c (i18n_switchto_utf8) (i18n_switchback) [USE_SIMPLE_GETTEXT]: Use new function from libgpg-error which supports proper restoring. * sysutils.c (get_session_marker): Simplified by using gcrypt. 2009-12-08 Marcus Brinkmann * Makefile.am (audit-events.h, status.h) [!MAINTAINER_MODE]: No longer include these rules if not in maintainer mode. 2009-12-08 Werner Koch * userids.h, userids.c: New. (classify_user_id): Merged from similar fucntions in sm/ and g10/. * dns-cert.c (get_dns_cert): Add support for ADNS. 2009-12-08 Marcus Brinkmann * asshelp.c (start_new_gpg_agent): Convert posix FD to assuan FD. * asshelp.c (start_new_gpg_agent) [HAVE_W32_SYSTEM]: Add missing argument in assuan_socket_connect invocation. * iobuf.c (iobuf_open_fd_or_name): Fix type of FD in function declaration. 2009-12-07 Werner Koch * pka.c (get_pka_info): Add support for ADNS. * src.v (getsrv): Add support for ADNS. * srv.c (getsrv): s/xrealloc/xtryrealloc/. 2009-12-04 Werner Koch * Makefile.am (audit-events.h, status-codes.h): Create files in the source dir. Fixes bug#1164. 2009-12-02 Werner Koch * audit.c (proc_type_decrypt, proc_type_sign): Implemented. (proc_type_verify): Print hash algo infos. * audit.h (AUDIT_DATA_CIPHER_ALGO, AUDIT_BAD_DATA_CIPHER_ALSO) (AUDIT_NEW_RECP, AUDIT_DECRYPTION_RESULT, AUDIT_RECP_RESULT) (AUDIT_ATTR_HASH_ALGO, AUDIT_SIGNED_BY, AUDIT_SIGNING_DONE): 2009-11-05 Marcus Brinkmann * asshelp.c (start_new_gpg_agent): Update use of assuan_socket_connect and assuan_pipe_connect. 2009-11-02 Marcus Brinkmann * get-passphrase.c (default_inq_cb, membuf_data_cb): Change return type to gpg_error_t. 2009-10-28 Werner Koch * status.h (STATUS_MOUNTPOINT): New. 2009-10-16 Marcus Brinkmann * Makefile.am (libcommon_a_CFLAGS): Use LIBASSUAN_CFLAGS instead of LIBASSUAN_PTH_CFLAGS. 2009-10-13 Werner Koch * exechelp.c (gnupg_kill_process): New. 2009-09-29 Werner Koch * exechelp.c (create_inheritable_pipe): Rename to create_inheritable_pipe_w. (create_inheritable_pipe_r): New. (gnupg_create_outbound_pipe): New. * iobuf.h: Include "sysutils.h" * iobuf.c (iobuf_open_fd_or_name): New. (iobuf_get_fname_nonnull): New. 2009-09-23 Marcus Brinkmann * asshelp.c (start_new_gpg_agent): Allocate assuan context before starting server. 2009-09-03 Werner Koch Update from libestream: * estream-printf.c: Include stdint.h only if HAVE_STDINT_H is defined. * estream-printf.c: Remove all test code. Use macro DEBUG instead of TEST for debugging. * estream-printf.c (pr_float): Make buffer larger for silly high numbers. 2009-08-11 David Shaw * ttyio.h, ttyio.c (tty_enable_completion): Some ifdefs around HAVE_LIBREADLINE to allow building when readline isn't available. 2009-08-06 Werner Koch * status.h (STATUS_INV_SGNR, STATUS_NO_SGNR): New. * status.c (get_inv_recpsgnr_code): New. 2009-07-23 David Shaw * srv.c (getsrv): Fix type-punning warning. 2009-07-23 Werner Koch * util.h (GPG_ERR_NOT_ENABLED): New. * audit.h (enum): Add AUDIT_CRL_CHECK. * audit.c (proc_type_verify): Show CRL check result. 2009-07-06 Werner Koch * get-passphrase.c (struct agentargs): Add SESSION_ENV and remove obsolete args. (gnupg_prepare_get_passphrase): Ditto. * session-env.c, session-env.h: New. * t-session-env.c: New. * Makefile.am (common_sources, module_tests): Add them. * asshelp.h: Include "session-env.h" * asshelp.c (send_one_option): Add arg PUTENV. (send_pinentry_environment): Replace most args by SESSION_ENV and rewrite fucntion. (start_new_gpg_agent): Likewise. * t-exechelp.c (test_close_all_fds): Remove debug code. 2009-07-01 Werner Koch * sexputil.c (get_pk_algo_from_canon_sexp): New. 2009-06-29 Werner Koch * estream.c (BUFFER_ROUND_TO_BLOCK): Remove unused macro. (es_func_mem_write): Rewrite reallocation part. * estream.c (es_write_sanitized_utf8_buffer): Typo typo fix. 2009-06-25 Werner Koch * estream.c (es_write_sanitized_utf8_buffer): Typo fix. 2009-06-24 Werner Koch * estream.c (es_read_line): In the malloc error case, set MAX_LENGTH to 0 only if requested. * xreadline.c (read_line): Ditto. * estream.c (es_write_sanitized_utf8_buffer): Pass on error from es_fputs. * sexputil.c (get_rsa_pk_from_canon_sexp): Check for error after the loop. Reported by Fabian Keil. 2009-06-22 Werner Koch * estream.c (es_pth_read, es_pth_write) [W32]: New. (ESTREAM_SYS_READ, ESTREAM_SYS_WRITE) [HAVE_PTH]: Use them. 2009-06-03 Werner Koch * estream.c (es_convert_mode): Rewrite and support the "x" flag. 2009-05-28 David Shaw From 1.4: * http.h, http.c (send_request) Pass in a STRLIST for additional headers. Change all callers. 2009-05-27 David Shaw From 1.4: * http.h, http.c (send_request): Pass in srvtag and make its presence sufficient to turn the feature on. (http_open): From here. (http_document): And here. * srv.c (getsrv): Raise maximum packet size to 2048, as PACKETSZ is too small these days. 2009-05-22 Werner Koch * ttyio.c (tty_cleanup_after_signal): New. 2009-05-19 Werner Koch * simple-pwquery.c (agent_open): Use SUN_LEN (JNLIB_NEED_AFLOCAL): Define and include mischelp.h. 2009-05-07 Werner Koch * sexputil.c (get_rsa_pk_from_canon_sexp): New. * t-sexputil.c (test_make_canon_sexp_from_rsa_pk): Extend the test. 2009-04-28 Werner Koch * sexputil.c (make_canon_sexp_from_rsa_pk): New. * t-sexputil.c (test_make_canon_sexp_from_rsa_pk): New. 2009-04-01 Werner Koch * iobuf.c: Port David's changes from 1.4: (fd_cache_invalidate): Pass return code from close back. (direct_open, iobuf_ioctl): Check that return value. (fd_cache_synchronize): New. (iobuf_ioctl): Add new sub command 4 (fsync). * iobuf.c (fd_cache_strcmp): New. Taken from 1.4. (fd_cache_invalidate, fd_cache_close, fd_cache_open): Use it. * exechelp.c (gnupg_spawn_process): Implement new flag bit 6. * sysutils.c (gnupg_allow_set_foregound_window): Allow the use of ASFW_ANY. * membuf.c (put_membuf, get_membuf): Wipe memory on out of core. 2009-03-31 Werner Koch * percent.c (percent_unescape, percent_plus_unescape): New. (percent_plus_unescape_inplace, percent_unescape_inplace): New. (do_plus_or_plain_unescape, count_unescape, do_unescape): New. (do_unescape_inplace): New. * t-percent.c (test_percent_plus_escape): Test percent_plus_unescape. * get-passphrase.c, get-passphrase.h: New. * Makefile.am (without_pth_sources): New. 2009-03-18 Werner Koch * exechelp.c: Include sys/resource.h and sys/stat.h. (get_max_open_fds): New. (do_exec): Use it. (get_all_open_fds): New. (close_all_fds): New. (do_exec): Use close_all_fds. * t-exechelp.c: New. 2009-03-13 David Shaw * http.c (do_parse_uri): Properly handle IPv6 literal addresses as per RFC-2732. Adapted from patch by Phil Pennock. 2009-03-12 Werner Koch * gettime.c: Include i18n.h. (dump_isotime): New. 2009-03-06 Werner Koch * sexputil.c (make_canon_sexp): New. 2009-03-03 Werner Koch * exechelp.c (do_exec): Make sure that /dev/null connected FDs are not closed. 2009-01-19 Werner Koch * audit.c (writeout_li): Translate a few more result strings. Fixes bug#970. * convert.c (hex2str): Fix optimization to append a nul character. 2008-12-05 Werner Koch * percent.c, t-percent.c: New. * exechelp.c (gnupg_spawn_process, gnupg_spawn_process_fd) (gnupg_spawn_process_detached) [W32]: Remove debug output. 2008-11-20 Werner Koch * audit.c (writeout_li): Translate OKTEXT. 2008-11-04 Werner Koch * i18n.c (i18n_init) [USE_SIMPLE_GETTEXT]: Adjust for changed w32-gettext.c. * homedir.c (gnupg_localedir): New. 2008-10-20 Werner Koch * http.c (http_register_tls_callback) [!HTTP_USE_GNUTLS]: Mark unused arg. * localename.c (do_nl_locale_name): Ditto. * audit.c (event2str): Silent gcc warning. * sysutils.c (translate_sys2libc_fd): Mark unused arg. (translate_sys2libc_fd_int): Ditto. * iobuf.c (translate_file_handle): Ditto. * asshelp.c (send_one_option): Ditto. * exechelp.c (gnupg_spawn_process): Ditto. * signal.c (got_usr_signal): Ditto * estream.c (es_func_fd_create) [!W32]: Ditto. (es_func_fp_create) [!W32]: Ditto. (es_write_hexstring): Ditto. (dummy_mutex_call_void, dummy_mutex_call_int) [HAVE_PTH]: New. (ESTREAM_MUTEX_LOCK, ESTREAM_MUTEX_UNLOCK, ESTREAM_MUTEX_TRYLOCK) (ESTREAM_MUTEX_INITIALIZE) [HAVE_PTH]: Use dummy calls so to mark unused arg. 2008-10-19 Werner Koch * estream-printf.c (estream_vsnprintf): Fix return value. (check_snprintf): Add a new test. (one_test) [W32]: Disable test. 2008-10-17 Werner Koch * util.h (snprintf) [W32]: Redefine to estream_snprintf. 2008-09-03 Werner Koch * convert.c (hex2str): New. (hex2str_alloc): New. * t-convert.c (test_hex2str): New. 2008-08-19 Werner Koch * iobuf.c: Avoid passing a NULL (iobuf_t)->desc to the log function. Should in general never be NULL, but well. Reported by M. Heneka. 2008-06-26 Werner Koch * estream.c (es_write_sanitized): Loose check for control characters to better cope with utf-8. The range 0x80..0x9f is nowadays not anymore accidently used for control charaters. 2008-06-25 Marcus Brinkmann Revert last three changes related to handle translation. * sysutils.c: (FD_TRANSLATE_MAX, fd_translate, fd_translate_len) (translate_table_init, translate_table_lookup): Removed. * iobuf.c (check_special_filename): Do not use translate_table_lookup. * sysutils.h (translate_table_init, translate_table_lookup): Remove prototypes. 2008-06-19 Werner Koch * sysutils.c: Remove . (fd_translate_max): Use macro for the size. (translate_table_init): Protect read against EINTR and replace isspace by spacep. 2008-06-18 Marcus Brinkmann * sysutils.c (TRANS_MAX): Bump up to 350 to be on the safe side. * sysutils.h (translate_table_init, translate_table_lookup): New prototypes. * sysutils.c: Include . (FD_TRANSLATE_MAX): New macro. (fd_translate, fd_translate_len): New static variables. (translate_table_init, translate_table_lookup): New functions. (translate_sys2libc_fd_int): Translate file descriptor. * iobuf.c (check_special_filename): Translate handle values from special filenames. 2008-06-16 Werner Koch * homedir.c (w32_commondir): New. (gnupg_sysconfdir): Use it. 2008-06-09 Werner Koch * b64dec.c: New. 2008-06-05 Werner Koch * util.h (gnupg_copy_time): Replace strcpy by memcpy. 2008-05-26 Werner Koch * asshelp.c (send_one_option, send_pinentry_environment): use xfree and xtrystrdup. * i18n.c (i18n_switchto_utf8) [USE_SIMPLE_GETTEXT]: Return NULL. * homedir.c (gnupg_module_name): Add GNUPG_MODULE_NAME_CONNECT_AGENT and GNUPG_MODULE_NAME_GPGCONF. 2008-04-21 Werner Koch * http.c (http_wait_response) [W32]: Use DuplicateHandle because it is a socket. (cookie_read) [W32]: Use recv in place of read. 2008-04-08 Werner Koch * i18n.c (i18n_switchto_utf8, i18n_switchback) [USE_SIMPLE_GETTEXT]: Implement. 2008-04-07 Werner Koch * b64enc.c (b64enc_start): Detect PGP mode. (b64enc_finish): Write PGP CRC. * util.h (struct b64state): Add field CRC. * t-b64.c: New. * pka.c (get_pka_info): Use xtrymalloc and check result. 2008-03-25 Werner Koch * localename.c: Strip all W32 code. Include w32help.h. (gnupg_messages_locale_name) [W32]: Use the gettext_localename. 2008-03-17 Werner Koch * iobuf.c (IOBUF_BUFFER_SIZE): Actually use this macro. * simple-pwquery.c (agent_send_all_options): Fix last change. 2008-03-06 Werner Koch * simple-pwquery.c (agent_send_all_options): Add support for XAUTHORITY and PINENTRY_USER_DATA. 2008-02-15 Marcus Brinkmann * exechelp.c (gnupg_spawn_process_fd): Add flag DETACHED_PROCESS unconditionally (required for all callers at the moment). 2008-02-14 Werner Koch * sysutils.c (gnupg_allow_set_foregound_window): New. (WINVER) [W32]: Define. 2008-01-31 Werner Koch * audit.c (audit_print_result): Make sure that the output is always UTF8. 2008-01-27 Werner Koch * exechelp.c (gnupg_spawn_process): Add arg FLAGS and changed all callers to pass 0 for it. 2007-12-13 Werner Koch * sexputil.c (hash_algo_from_sigval): New. * t-sexputil.c: New. * Makefile.am (module_tests): Add it. 2007-12-11 Werner Koch * asshelp.c (send_pinentry_environment): Allow using of old gpg-agents not capabale of the xauthority and pinentry_user_data options. 2007-12-04 Werner Koch * Makefile.am (t_helpfile_LDADD, module_maint_tests): New. * t-helpfile.c: New. * helpfile.c: New. * membuf.h (is_membuf_ready, MEMBUF_ZERO): New. * localename.c: New. Taken from gettext with modifications as done for GpgOL. Export one new function. * util.h (gnupg_messages_locale_name, gnupg_get_help_string): Added. * sysutils.c (gnupg_reopen_std): New. Taken from ../g10/gpg.c. 2007-11-27 Werner Koch * Makefile.am (CLEANFILES): New. * homedir.c (dirmngr_socket_name): Use CSIDL_WINDOWS. 2007-11-15 Werner Koch * asshelp.c (send_pinentry_environment): Add args XAUTHORITY and PINENTRY_USER_DATA. (start_new_gpg_agent): Ditto. 2007-11-07 Werner Koch * status.h: New. * errors.h: Remove. 2007-11-05 Werner Koch * audit.c, audit.h: New. * Makefile.am: Add rules to build audit-events.h. * exaudit.awk: New. * mkstrtable.awk: New. Taken from libgpg-error. 2007-10-19 Werner Koch * i18n.c (i18n_switchto_utf8, i18n_switchback): New. 2007-10-01 Werner Koch * sysutils.h (FD2INT, INT2FD): New. 2007-09-21 Werner Koch * homedir.c (default_homedir): Make registry work. Reported by Marc Mutz. 2007-08-29 Werner Koch * exechelp.c (gnupg_wait_process): Add arg EXITCODE. Changed all callers. (gnupg_create_inbound_pipe): New. * util.h (GNUPG_MODULE_NAME_GPGSM, GNUPG_MODULE_NAME_GPG): New. * homedir.c (gnupg_module_name): Add them 2007-08-28 Werner Koch * gettime.c (check_isotime, add_isotime): New. Originally written for DirMngr by me. (add_days_to_isotime): New. (date2jd, jd2date, days_per_month, days_per_year): New. Taken from my ancient (1988) code used in Wedit (time2.c). 2007-08-27 Werner Koch * util.h (GNUPG_MODULE_NAME_CHECK_PATTERN): New. * homedir.c (gnupg_module_name): Add it. * exechelp.c (w32_fd_or_null) [W32]: New. (gnupg_spawn_process_fd): New. (gnupg_wait_process) [W32]: Close the handle after if the process has returned. 2007-08-22 Werner Koch Updated estream from libestream. * estream.c (mem_malloc, mem_realloc, mem_free): New. Use them instead of the ES_MEM_foo. * estream.c (estream_cookie_mem): Remove members DONT_FREE, APPEND_ZERO, PTR and SIZE. Add MEMORY_LIMIT. Put GROW into a new FLAGS struct. (es_func_mem_create): Remove APPEND_ZERO, DONT_FREE, PTR and SIZE. Add MEMORY_LIMIT. (es_func_mem_write, es_func_mem_seek, es_func_mem_destroy): Revamp. (es_open_memstream): Change API to just take a memory limit and a mode argument. Rename to .. (es_fopenmem): .. this. (HAVE_W32_SYSTEM) [_WIN32]: Define if not defined. (tmpfd) [W32]: Implement directly using the W32 API. (es_fgets): Rewrite without using doreadline. 2007-08-21 Werner Koch * sysutils.c (gnupg_tmpfile): New. * t-sysutils.c: New. * Makefile.am (module_tests): Add t-sysutils. 2007-08-20 Werner Koch * exechelp.c [W32]: Redefine X_OK to F_OK. 2007-08-16 Werner Koch * Makefile.am (t_convert_DEPENDENCIES): Remove ($(PROGRAMS)): Remove. (t_common_ldadd): Use libcommon.a and not the macro. 2007-08-14 Werner Koch * homedir.c (dirmngr_socket_name): New. 2007-08-07 Werner Koch * tlv.c, tlv.h: Move from ../scd/. * tlv.c (parse_sexp, parse_ber_header): Add ERRSOURCE arg and prefix name with a _. * tlv.h: Use macro to convey ERRSOURCE. 2007-08-02 Werner Koch * gc-opt-flags.h: New. 2007-08-01 Werner Koch * estream-printf.c (read_dummy_value): Removed as it is useless now. (read_values): Remove check on !vaargs which is not anymore needed and anyway not portable. Reported by Peter O'Gorman. 2007-07-16 Werner Koch * estream.c (es_func_file_create): Clear NO_CLOSE flag. 2007-07-12 Werner Koch * sysutils.h (gnupg_fd_t): New. * sysutils.c (translate_sys2libc_fd): Use that type instead of int. (translate_sys2libc_fd_int): New. 2007-07-09 Werner Koch * t-gettime.c (test_isotime2epoch): Use time_t and not u32. 2007-07-05 Werner Koch * t-gettime.c: New. * gettime.c (isotime2epoch, epoch2isotime): New. 2007-07-04 Werner Koch * estream.c (es_init_do): Do not throw an error if pth has already been initialized. 2007-06-26 Werner Koch * Makefile.am ($(PROGRAMS)): New. * util.h (init_common_subsystems): Moved to .. * init.h: .. New. * util.h: Include init.h. * homedir.c (standard_homedir): New. (default_homedir) [W32]: Reimplemented in terms of standard_homedir. Fixed memory leak. 2007-06-25 Werner Koch * iobuf.c: Add more documentation and slighly restructured macro defintion for better readability. (FILEP_OR_FD): Rename to fp_or_fd_t. (CLOSE_CACHE): Rename to close_cache_t. * sysutils.c (translate_sys2libc_fd): New using the code from iobuf.c. * iobuf.c: Include sysutils.h. (iobuf_translate_file_handle): Remove. (translate_file_handle): Use new function. * estream-printf.c [TEST]: Header including fixes. (do_format): Do not append a trailing Nul. This avoids spurious Nuls in the es_printf output. (estream_vsnprintf, estream_vasprintf): Take this in account. * estream.h (struct es__stream): Change FLAGS to a bit structure. (ES__FLAG_WRITING): Replace by a bit from FLAGS. * estream.c (struct estream_internal): Rename FLAGS to MODEFLAGS so that they are not confused with the estream flags. (es_initialize, es_create): Add arg MODEFLAGS so that we can setup the intial writemode. Changed all callers to pass them. (es_convert_mode): Set O_BINARY. (es_func_fd_create, es_func_fp_create, es_func_file_create) [W32]: Call setmode if requested. 2007-06-24 Werner Koch * estream.c (do_fpopen, es_fpopen, es_fpopen_nc): New. (es_func_fp_create, es_func_fp_read, es_func_fp_write) (es_func_fp_seek, es_func_fp_destroy): New. 2007-06-22 Werner Koch * estream.c (es_fdopen): Factored code out to.. (do_fdopen): .. new. (es_fdopen_nc): New. (estream_cookie_fd): Add field NO_CLOSE. (es_func_fd_create): Add arg NO_CLOSE and changed all callers. (es_func_fd_destroy): Handle the new flag. * homedir.c (gnupg_libexecdir) [W32]: Factor code out to .. (w32_rootdir): .. new. (gnupg_sysconfdir, gnupg_libdir, gnupg_datadir) [W32]: Return name based on w32_rootdir(). 2007-06-21 Werner Koch * membuf.h (get_membuf_len): New. * membuf.c (init_membuf_secure): Really allocate in secure memory. (put_membuf_str): New. * ttyio.c (tty_getf): New. * util.h (ctrl_t): Declare it here. * asshelp.c (start_new_gpg_agent): New. Based on code from ../sm/call-agent.c 2007-06-20 Werner Koch * sysutils.c (gnupg_sleep): New. * sysutils.h [W32]: Remove _sleep wrapper. Changed all callers to use gnupg_sleep. * exechelp.c (build_w32_commandline_copy): New. (build_w32_commandline): Factored some code out to new function and correctly process a PGMNAME with spaces. (gnupg_spawn_process_detached) [W32]: Implement. 2007-06-14 Werner Koch * simple-pwquery.h (MAP_SPWQ_ERROR_IMPL): New. (SPWQ_NO_PIN_ENTRY): New. * simple-pwquery.c (simple_pw_set_socket): New. (agent_open): Use it if GPG_AGENT_INFO is not set. (simple_pwquery): Extended to allow returning of otehyr error codes. * util.h (GNUPG_MODULE_NAME_AGENT, GNUPG_MODULE_NAME_PINENTRY) (GNUPG_MODULE_NAME_SCDAEMON, GNUPG_MODULE_NAME_DIRMNGR) (GNUPG_MODULE_NAME_PROTECT_TOOL): New. * homedir.c (gnupg_module_name): New. (gnupg_bindir): New. 2007-06-12 Werner Koch * homedir.c (gnupg_sysconfdir): New. (gnupg_libexecdir): New. Taken from g10/misc.c:get_libexecdir. (gnupg_datadir): New. (gnupg_libdir): New. * http.c (connect_server) [W32]: Do not call init_sockets if HTTP_NO_WSASTARTUP is defined. * init.c: New. * estream.c (es_init_do): Init stream lock here because we can't use a static initialization with W32pth. 2007-06-11 Werner Koch * Makefile.am (t_common_ldadd): Use libcommonstd macro. 2007-06-06 Werner Koch * Makefile.am: Include am/cmacros.am. * sysutils.h [W32]: Remove prototypes for the registry access. * w32reg.c: Move to ../jnlib/w32-reg.c. * i18n.c (i18n_init): New. * simple-gettext.c: Remove. * iobuf.c (iobuf_get_filelength): Rename SIZE to EXSIZE to silent shadowing warning. 2007-06-04 Werner Koch * http.c [W32]: Include unistd.h also in this case. (write_server) [W32]: Fixed error code. (init_sockets): Fixed syntax error. (cookie_close): Replace close by sock_close macro. * estream.c [w32]: Do not init Mutex. * Makefile.am (common_sources) [USE_SNS_SRV]: Build srv.c only when needed. * ttyio.c (init_ttyfp) [W32]: Do not use TTYFP. * util.h: Include ../jnlib/dynload.h. * dynload.h: Move to ../jnlib. 2007-05-30 Werner Koch * estream.c (MEM_FREE, MEM_ALLOC, MEM_REALLOC): Prefix with ES_ as windows.h also has such definitions, 2007-05-15 Werner Koch * util.h: Do not include gnulib's vasprintf. Redefine asprintf and vasprintf. * xasprintf.c (xasprintf, xtryasprintf): Use estream_vasprintf. * estream-printf.h, estream-printf.c: New. Taken from current libestream SVN. * Makefile.am (common_sources): Add them. 2007-05-14 Werner Koch * sexp-parse.h (smklen): New. * sexputil.c: Include sexp-parse.h. (make_simple_sexp_from_hexstr): Replace sprintf by smklen. 2007-05-07 Werner Koch * signal.c (got_fatal_signal): Protect SIG from being clobbered by a faulty signal implementaion. Suggested by James Juran. 2007-04-25 Werner Koch * i18n.h (ngettext): New. * simple-gettext.c (ngettext): New. 2007-04-20 Werner Koch * miscellaneous.c (my_gcry_logger, my_gcry_outofcore_handler): Moved from gpg-agent to here. (my_gcry_fatalerror_handler): new. (setup_libgcrypt_logging): New. 2007-03-19 Werner Koch * miscellaneous.c (print_hexstring): New. * estream.c (es_fprintf_unlocked): New. (es_write_sanitized): New. (es_write_hexstring): New. (es_write_sanitized_utf8_buffer) [GNUPG_MAJOR_VERSION]: New. 2007-03-09 David Shaw From STABLE-BRANCH-1-4 * http.c (do_parse_uri): Remove the hkp port 11371 detection. We implement hkp in the keyserver handler, and the support here makes it appear like a bad hkp request actually succeeded. 2007-01-31 Werner Koch * Makefile.am (t_common_ldadd): Add LIBINCONV and LIBINTL. 2007-01-25 Werner Koch * simple-pwquery.c (simple_pwquery): New arg OPT_CHECK. 2006-12-13 David Shaw * Makefile.am (AM_CPPFLAGS): Include intl/ so we can reference the built-in headers. 2006-11-23 Werner Koch * http.c: Include i18n.h 2006-11-21 Werner Koch * estream.c: Remove explicit Pth soft mapping diabling becuase it is now done in config.h. 2006-11-15 Werner Koch * estream.c: Disabled Pth soft mapping. (my_funopen_hook_ret_t): New. (print_fun_writer): Use it here. * iobuf.c (fd_cache_close): Use %d instead of %p for debug output. 2006-11-03 Werner Koch * Makefile.am (t_convert_DEPENDENCIES): Add libcommon. From Gentoo. 2006-10-24 Marcus Brinkmann * Makefile.am (libcommon_a_CFLAGS): Add $(LIBASSUAN_CFLAGS). (libsimple_pwquery_a_CFLAGS): New variable. 2006-10-20 Werner Koch * convert.c (hex2bin): New. 2006-10-17 Werner Koch * estream.c (struct estream_internal, es_initialize) (es_deinitialize, print_fun_writer, es_print): New and modified functions to avoid tempfiles for printf style printing. * Makefile.am (libcommonpth_a_SOURCES): New. We now build a secon version of the library with explicit Pth support. * exechelp.c, estream.c: Make use of WITHOUT_GNU_PTH. 2006-10-08 Werner Koch * gpgrlhelp.c: Trun all functions into dummies if readline is not available. 2006-10-06 Werner Koch * Makefile.am (AM_CFLAGS): Use PTH version of libassuan. * util.h (GNUPG_GCC_A_SENTINEL): Defined for gcc >= 4. 2006-10-04 David Shaw * gpgrlhelp.c: readline requires stdio.h. 2006-10-04 Werner Koch * membuf.c (init_membuf_secure): New. (put_membuf): Make sure that ERRNO is set even if the underlying malloc code does not work properly. (get_membuf): Set ERRNO on error. (get_membuf): Allow to pass LEN as NULL. 2006-10-02 Werner Koch * iobuf.c (iobuf_unread): Removed. This code is not required. Also removed the entire unget buffer stuff. 2006-09-27 Werner Koch * util.h: Do not include strsep.h and strpbrk.h. (isascii): Removed as it is now in jnlib. * iobuf.c (pop_filter, underflow, iobuf_close): Free the unget buffer. 2006-09-27 Florian Weimer (wk) * iobuf.c (iobuf_unread): New. 2006-09-22 Werner Koch * i18n.h: Changed license to an all permissive one. * ttyio.c (tty_get): We need to use readline too. Added two more hooks. 2006-09-21 Werner Koch * ttyio.c (tty_private_set_rl_hooks): New. (tty_enable_completion, tty_disable_completion): Use a hook to enable readline support. Now always available. (tty_cleanup_rl_after_signal): New. * ttyio.h: Removed readline specific stuff. Included util.h. * common-defs.h: New. 2006-09-15 Werner Koch * convert.c: New. (hexcolon2bin): New. (bin2hex, bin2hexcolon, do_binhex): New. * t-convert.c: New 2006-09-14 Werner Koch * util.h (out_of_core): Use new gpg_error_from_syserror function. * http.c (init_sockets): Changed it to require 2.2 unless it is build within gnupg 1 where we require 1.1 (and not anymore allow for 1.0). 2006-09-07 Werner Koch * exechelp.c (gnupg_spawn_process): Factor out post fork code to .. (do_exec): .. new function. Allow passing of -1 for the fds. (gnupg_spawn_process): Terminate gcrypt's secure memory in the child. (gnupg_spawn_process_detached): New. 2006-09-06 Werner Koch * maperror.c: Removed. * util.h (out_of_core): New. 2006-09-04 Werner Koch * http.c (http_get_header): New. (capitalize_header_name, store_header): New. (parse_response): Store headers away. (send_request): Return GPG_ERR_NOT_FOUND if connect_server failed. * http.h: New flag HTTP_FLAG_NEED_HEADER. 2006-08-21 Werner Koch * Makefile.am (libcommon_a_SOURCES): Added keyserver.h * openpgpdefs.h: New. Stripped from ..g10/packet.h. 2006-08-16 Werner Koch * keyserver.h: Moved from ../include to here. * http.c: Include srv.h. * srv.c, srv.h: New. Taken from GnuPG 1.4 2006-08-14 Werner Koch * http.h (struct http_context_s): Moved to implementation. * http.c (http_open): Changed call to return a context. (http_open_document): Ditto. (http_get_read_ptr, http_get_read_ptr, http_get_status_code): New. (do_parse_uri): Replaced strlwr by straight code to ease standalone use of this file. (http_wait_response): Removed arg STATUS_CODE as it is available through an accessor function. Adjusted caller. (http_escape_string): New. * estream.c (es_read_line): Renamed to .. (doreadline): .. this. Changed all callers. (es_read_line): New. This is theusual limited getline variabnt as used at several places. Here taken and adjusted from xreadline.c (es_free): New. 2006-08-11 Werner Koch * http.c: Major internal changes to optionallly support GNUTLS and ESTREAM. (http_open): Move initialization of the stream ... (send_request): .. here. (http_register_tls_callback): New. * estream.c (es_writen): Try to seek only is a seek function has been registered. 2006-08-09 Werner Koch * http.c, http.h: New. Taken from gnupg 1.4.5, merged with changes done for the Dirmngr project (by g10 Code) and cleaned up some stuff. (make_header_line): New. Change all caller to make user of the new * Makefile.am (libcommon_a_SOURCES): Added http.c and http.h. 2006-05-23 Werner Koch * gettime.c (isotimestamp): New. * ttyio.c (tty_get_ttyname): Posixly correct usage of ctermid. * dns-cert.c: New. Taken from 1.4.3's util/cert.c. * dns-cert.h: New. 2006-05-22 Werner Koch * pka.c: New. Taked from 1.4.3. * pka.h: New. * Makefile.am: Added pka. 2006-05-19 Werner Koch * yesno.c (answer_is_yes_no_default, answer_is_yes_no_quit): Updated from 1.4.3. (answer_is_okay_cancel): new. From 1.4.3. * miscellaneous.c (match_multistr): New. Taken from 1.4.3. * ttyio.c (tty_enable_completion, tty_disable_completion): New dummy functions. * ttyio.h: Add prototypes and stubs. 2006-04-19 Werner Koch * iobuf.c (iobuf_get_fd): New. Taken from 1.4.3. (iobuf_is_pipe_filename): New. (pop_filter): Made static. (iobuf_skip_rest): New. Orginal patch by Florian Weimer. Added new argument PARTIAL. (block_filter): Remove the old gpg indeterminate length mode. (block_filter): Properly handle a partial body stream that ends with a 5-byte length that happens to be zero. (iobuf_set_block_mode, iobuf_in_block_mode): Removed as superfluous. (iobuf_get_filelength): New arg OVERFLOW. (iobuf_get_filelength) [W32]: Use GetFileSizeEx if available * miscellaneous.c (is_file_compressed): Take care of OVERFLOW. 2006-04-18 Werner Koch * homedir.c (w32_shgetfolderpath): New. Taken from gpg 1.4.3. (default_homedir): Use it. 2005-10-08 Marcus Brinkmann * signal.c (get_signal_name): Check value of HAVE_DECL_SYS_SIGLIST instead of just if it is defined. 2005-09-28 Marcus Brinkmann * Makefile.am (AM_CFLAGS): Add $(LIBASSUAN_CFLAGS). 2005-07-04 Marcus Brinkmann * simple-pwquery.h (simple_pwclear): New prototype. * simple-pwquery.c (simple_pwclear): New function. 2005-06-15 Werner Koch * miscellaneous.c (make_printable_string): Made P a void*. * sexputil.c (keygrip_from_canon_sexp, cmp_simple_canon_sexp): Fixed signed/unsigned pointer mismatch. (make_simple_sexp_from_hexstr): Ditto. This is all too ugly; I wonder why gcc-4's default is to warn about them and forcing us to use cast the warning away. * iobuf.c (block_filter): Ditto. (iobuf_flush): Ditto. (iobuf_read_line): Ditto. (iobuf_read): Make BUFFER a void *. (iobuf_write): Make BUFFER a const void *. * ttyio.c (tty_print_utf8_string2): Ditto. * estream.c (estream_cookie_mem): Make MEMORY unsigned char*. (es_write): Make BUFFER a void *. (es_writen): Ditto. (es_func_fd_read, es_func_fd_write, es_func_mem_read) (es_func_mem_write): Ditto. (es_read, es_readn): Ditto. (es_func_mem_write): Made MEMORY_NEW an unsigned char *. * estream.h (es_cookie_read_function_t) (es_cookie_write_function_t): Changed buffer arg to void*. 2005-06-03 Werner Koch * estream.c: Use HAVE_CONFIG_H and not USE_CONFIG_H! (es_func_fd_read, es_func_fd_write): Protect against EINTR. 2005-06-01 Werner Koch * Makefile.am (AM_CPPFLAGS): Added. * util.h: Add some includes for gnulib. (ttyname, isascii): Define them inline. * fseeko.c, ftello.c: Removed. * strsep.c, mkdtemp.c: Removed. * ttyname.c, isascii.c: Removed. 2005-05-31 Werner Koch * dynload.h: s/__inline__/inline/. 2005-05-13 Werner Koch * signal.c (got_fatal_signal): Print the signal number if we can't get a name for it. (get_signal_name): Return NULL if no name is available. Fixed conditional for sys_siglist to the correct one. 2005-04-17 Werner Koch * sexputil.c (cmp_simple_canon_sexp): New. (make_simple_sexp_from_hexstr): New. 2005-04-07 Werner Koch * sexputil.c: New. 2005-04-11 Marcus Brinkmann * simple-pwquery.c (simple_pwquery): Use spwq_secure_free. 2005-03-03 Werner Koch * Makefile.am (AM_CFLAGS): Added PTH_CFLAGS. Noted by Kazu Yamamoto. 2005-02-25 Werner Koch * xasprintf.c (xtryasprintf): New. 2005-01-26 Moritz Schulte * Makefile.am (libcommon_a_SOURCES): New source files: estream.c, estream.h. * estream.c, estream.h: New files. 2005-01-03 Werner Koch * asshelp.c (send_pinentry_environment): Fixed changed from 2004-12-18; cut+paste error for lc-messages. 2004-12-21 Werner Koch * simple-pwquery.c (agent_open) [W32]: Implement for W32. (readline) [W32]: Use recv instead of read. (writen) [W32]: Use send instead of write. (my_stpcpy): Define a stpcpy replacement so that this file continues to be self-contained. (agent_send_all_options) [W32]: Don't call ttyname. 2004-12-21 Marcus Brinkmann * simple-pwquery.h (simple_query): Add prototype. * simple-pwquery.c (simple_query): New function. 2004-12-21 Werner Koch * signal.c (got_fatal_signal, got_usr_signal) (got_fatal_signal) [DOSISH]: Don't build. * simple-gettext.c: Include sysutils.h * homedir.c: New. Use CSIDL_APPDATA for W32 as the default home directory. * Makefile.am (libcommon_a_SOURCES): Add it. (EXTRA_DIST): Removed mkerror and mkerrtok. 2004-12-20 Werner Koch * sysutils.h [W32]: Define sleep. * util.h: Add prototype for mkdtemp. * membuf.c (put_membuf): Wipe out buffer after a failed realloc. 2004-12-19 Werner Koch * maperror.c (map_assuan_err_with_source): Oops, args were swapped. 2004-12-18 Werner Koch * maperror.c (map_assuan_err): Renamed to .. (map_assuan_err_with_source): .. this and add arg SOURCE.c * asshelp.c (send_pinentry_environment, send_one_option): Add arg ERRSOURCE. 2004-12-15 Werner Koch * sysutils.h [W32]: Prototypes for registry functions. * w32reg.c: Include sysutils.h * simple-pwquery.c [W32]: Dummy code to allow a build. * exechelp.c [W32]: Implemented for W32 . * ttyname.c: New. * asshelp.c (send_one_option): New. (send_pinentry_environment): Cleaned up and made sure that empty values are not send. 2004-12-07 Werner Koch * asshelp.c (send_pinentry_environment) [W32]: Do not use ttyname. 2004-12-06 Werner Koch * exechelp.h, exechelp.c: New. Based on code from ../sm/import.c. 2004-12-03 Werner Koch * strsep.c: Fixed copyright comments. 2004-11-26 Werner Koch * simple-gettext.c: New taken from gnupg 1.3.x * simple-pwquery.c [_WIN32]: Include winsock2.h. (agent_open): Disable it until we have our AF_UNIX implementation ready. * fseeko.c, ftello.c: Include sys/types for the sake of W32. 2004-11-23 Werner Koch * b64enc.c: Include stdio.h and string.h 2004-08-18 Werner Koch * simple-pwquery.c (simple_pwquery): Handle gpg-error style return code for canceled. 2004-07-20 Werner Koch * maperror.c: Removed header ksba.h. Not required anymore. 2004-06-14 Werner Koch * xreadline.c: New. Based on the iobuf_read_line function. 2004-05-12 Werner Koch * util.h (xtrycalloc_secure,xtrymalloc_secure): New. 2004-05-11 Werner Koch * sysutils.c (disable_core_dumps): Only set the current limit. (enable_core_dumps): New. 2004-04-13 Werner Koch * simple-pwquery.c (copy_and_escape): Relaxed quoting. 2004-04-05 Werner Koch * errors.h (STATUS_NEWSIG): New. 2004-03-11 Werner Koch * dynload.h [__MINGW32__]: Define RTLD_LAZY. 2004-03-09 Werner Koch * maperror.c (map_assuan_err): Map the Locale_Problem item. 2004-03-03 Werner Koch * asshelp.c, asshelp.h: New. (send_pinentry_environment): New. Code taken from ../sm/call-agent.c. 2004-02-19 Werner Koch * simple-pwquery.c (agent_open): Don't mangle INFOSTR. 2004-02-17 Werner Koch * simple-pwquery.c (agent_open): Ignore an empty GPG_AGENT_INFO. * errors.h: Added STATUS_IMPORT_OK. 2004-02-10 Werner Koch * b64enc.c: New. Based on code from ../sm/base64.c. 2004-01-30 Marcus Brinkmann * Makefile.am (libcommon_a_SOURCES): Add xasprintf.c. * miscellaneous.c (xasprintf): Moved to ... * xasprintf (xasprintf): ... here. New file. This allows to use xasprintf without sucking in gpg-error. 2004-01-27 Werner Koch * sexp-parse.h: New; moved from../agent. * util.h (xtoi_4): New. 2003-12-23 Werner Koch * maperror.c (map_assuan_err): Prepared for a new error code. 2003-12-17 Werner Koch * gettime.c (asctimestamp): Add a note on a non-avoidable gcc warning. * util.h [!HAVE_VASPRINTF]: Add printf format attribute to the replacement function. * miscellaneous.c (xasprintf): New. 2003-11-14 Werner Koch * mkdtemp.c (mkdtemp): Use gcry_create_nonce. * cryptmiss.c: Removed. 2003-11-13 Werner Koch * util.h (vasprintf): Also fixed the prototype. * vasprintf.c (vasprintf): ARGS should not be a pointer. Fixed segv on Solaris. Reported by Andrew J. Schorr. 2003-11-12 Werner Koch * maperror.c (map_ksba_err, map_gcry_err, map_kbx_err): Removed. 2003-10-31 Werner Koch * util.h (gnupg_isotime_t): New. (gnupg_copy_time): New. * gettime.c (gnupg_get_isotime): New. 2003-09-23 Werner Koch * iobuf.c (check_special_filename): Replaced is isdigit by digitp to avoid passing negative values and potential locale problems. Problem noted by Christian Biere. * util.h (ascii_isspace): New. 2003-09-18 Werner Koch * ttyio.c (tty_fprintf): New. (tty_print_string, tty_print_utf8_string2) (tty_print_utf8_string): Made P argument const byte*. 2003-08-20 Marcus Brinkmann * maperror.c (map_ksba_err): Map -1. Use gpg_err_make to set the error source. 2003-08-14 Timo Schulz * dynload.h. New. W32 wrapper around the dynload mechanism. 2003-07-15 Werner Koch * simple-pwquery.c, simple-pwquery.h: New; moved from ../agent. * Makefile.am (libsimple_pwquery_a_LIBADD): New. 2003-06-25 Werner Koch * maperror.c (map_to_assuan_status): Directly map 0 to 0. 2003-06-17 Werner Koch * gettime.c (scan_isodatestr,add_days_to_timestamp,strtimevalue) (strtimestamp,asctimestamp): New. Code taken from gnupg 1.3.2 mischelp.c. * yesno.c: New. Code taken from gnupg 1.3.2 mischelp.c * miscellaneous.c: New. * util.h: Include utf8conf.h 2003-06-16 Werner Koch * gettime.c (make_timestamp): New. * ttyio.c: New. Taken from gnupg 1.2. * ttyio.h: Move from ../include. 2003-06-13 Werner Koch * util.h (seterr): Removed macro. (xmalloc_secure,xcalloc_secure): New. 2003-06-11 Werner Koch * iobuf.c (iobuf_writebyte,iobuf_write): Return error code from iobuf_flush. (iobuf_writestr): Ditto. 2003-06-10 Werner Koch * iobuf.c, iobuf.h: New. Taken from current gnupg 1.3 CVS. Run indent on it and adjusted error handling to libgpg-error style. Replaced IOBUF by iobuf_t. Renamed malloc functions. 2003-06-04 Werner Koch * errors.h: Removed all error codes. We keep the status codes for now. * Makefile.am: Do not create errors.c anymore; remove it from the sources. * maperror.c: Don't include error.h. Change all error codes to libgpg-error style. (map_assuan_err): Changed to new Assuan error code convention. (map_to_assuan_status): Likewise. (map_gcry_err,map_kbx_err): Not needed. For now dummy functions. * membuf.c, membuf.h: New. Code taken from ../sm/call-agent.h. * Makefile.am: Added above. 2003-04-29 Werner Koch * util.h (fopencokokie): Removed prototype and struct. * fopencookie.c: Removed. * maperror.c: Use system assuan.h 2002-10-31 Neal H. Walfield * isascii.c: New file. * putc_unlocked.c: Likewise. 2002-10-28 Neal H. Walfield * signal.c (caught_fatal_sig): Remove superfluous zero initializer. (caught_sigusr1): Likewise. 2002-09-04 Neal H. Walfield * vasprintf.c (vasprintf) [va_copy]: Use va_copy. [!va_copy && __va_copy]: Use __va_copy. [!va_copy && !__va_copy]: Only now fall back to using memcpy. 2002-08-21 Werner Koch * errors.h: Added STATUS_IMPORT_PROBLEM. 2002-08-20 Werner Koch * vasprintf.c: Hack to handle NULL for %s. 2002-08-09 Werner Koch * signal.c: New. Taken from GnuPG 1.1.91. 2002-07-23 Werner Koch * util.h (_IO_cookie_io_functions_t): Fixed typo. Noted by Richard Lefebvre. 2002-07-22 Werner Koch * fseeko.c, ftello.c: New. 2002-06-28 Werner Koch * maperror.c (map_to_assuan_status): Map more errorcodes to Bad Certificate. 2002-06-26 Werner Koch * maperror.c (map_to_assuan_status): Map EOF to No_Data_Available. 2002-06-10 Werner Koch * errors.h (gnupg_error_token): Add new prototype. (STATUS_ERROR): New. * mkerrtok: New. * Makefile.am: Use it to create the new error token function. 2002-06-04 Werner Koch * maperror.c (map_to_assuan_status): Map Bad_CA_Certificate. 2002-05-23 Werner Koch * no-pth.c, Makefile.am: Removed. 2002-05-22 Werner Koch * mkdtemp.c: Replaced byte by unsigned char because it is no longer defined in gcrypt.h. 2002-05-21 Werner Koch * maperror.c (map_gcry_err): Add libgcrypt's new S-expression errors. (map_ksba_err): Add a few mappings. 2002-05-14 Werner Koch * gettime.c: New. 2002-05-03 Werner Koch * errors.h: Added STARUS_EXPSIG and STATUS_EXPKEYSIG. 2002-04-15 Werner Koch * cryptmiss.c: New. 2002-02-14 Werner Koch * maperror.c: Add more assuan<->gnupg mappings. 2002-02-12 Werner Koch * fopencookie.c: Dummy function. * vasprintf.c: New. Taken from binutils-2.9.1 and dropped all non ANSI-C stuff. Merged with asprintf version. * no-pth.c: New. 2002-01-23 Werner Koch * mkdtemp.c: Copied from gnupg-1.0.6c and changed to use libgcrypt. 2002-01-19 Werner Koch * sysutils.c: New. This is the misc.c file from gnupg 1.0.6 with the OpenPGP stuff removed. * sysutils.h: New. 2002-01-15 Werner Koch * maperror.c: Add mapping for Not_Trusted. 2002-01-11 Werner Koch * maperror.c (map_assuan_err): Codes for CRL 2002-01-08 Werner Koch * util.h (spacep): New. 2002-01-02 Werner Koch * maperror.c (map_to_assuan_status): New. Merged from ../agent and ../sm. 2001-12-20 Werner Koch * maperror.c (map_gcry_err): Add some mappings. 2001-12-18 Werner Koch * Makefile.am (AM_CPPFLAGS): Include flags for gcrypt and ksba 2001-12-14 Werner Koch * util.h (digitp, hexdigitp): New ctype like macros. (atoi_1,atoi_2,atoi_4,xtoi_1,xtoi_2): New. Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. 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/common/asshelp.c b/common/asshelp.c index 76518485f..f9878f3b3 100644 --- a/common/asshelp.c +++ b/common/asshelp.c @@ -1,376 +1,378 @@ /* asshelp.c - Helper functions for Assuan * Copyright (C) 2002, 2004, 2007, 2009 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_LOCALE_H #include #endif #define JNLIB_NEED_LOG_LOGV #include "i18n.h" #include "util.h" #include "exechelp.h" #include "sysutils.h" #include "status.h" #include "asshelp.h" static int my_libassuan_log_handler (assuan_context_t ctx, void *hook, unsigned int cat, const char *msg) { unsigned int dbgval; + (void)ctx; + if (cat != ASSUAN_LOG_CONTROL) return 0; /* We only want the control channel messages. */ dbgval = hook? *(unsigned int*)hook : 0; if (!(dbgval & 1024)) return 0; /* Assuan debugging is not enabled. */ if (msg) log_string (JNLIB_LOG_DEBUG, msg); return 1; } /* Setup libassuan to use our own logging functions. Should be used early at startup. */ void setup_libassuan_logging (unsigned int *debug_var_address) { assuan_set_log_cb (my_libassuan_log_handler, debug_var_address); } static gpg_error_t send_one_option (assuan_context_t ctx, gpg_err_source_t errsource, const char *name, const char *value, int use_putenv) { gpg_error_t err; char *optstr; (void)errsource; if (!value || !*value) err = 0; /* Avoid sending empty strings. */ else if (asprintf (&optstr, "OPTION %s%s=%s", use_putenv? "putenv=":"", name, value) < 0) err = gpg_error_from_syserror (); else { err = assuan_transact (ctx, optstr, NULL, NULL, NULL, NULL, NULL, NULL); xfree (optstr); } return err; } /* Send the assuan commands pertaining to the pinentry environment. The OPT_* arguments are optional and may be used to override the defaults taken from the current locale. */ gpg_error_t send_pinentry_environment (assuan_context_t ctx, gpg_err_source_t errsource, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env) { gpg_error_t err = 0; char *old_lc = NULL; char *dft_lc = NULL; const char *dft_ttyname; int iterator; const char *name, *assname, *value; int is_default; iterator = 0; while ((name = session_env_list_stdenvnames (&iterator, &assname))) { value = session_env_getenv_or_default (session_env, name, NULL); if (!value) continue; if (assname) err = send_one_option (ctx, errsource, assname, value, 0); else { err = send_one_option (ctx, errsource, name, value, 1); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Server too old; can't pass the new envvars. */ } if (err) return err; } dft_ttyname = session_env_getenv_or_default (session_env, "GPG_TTY", &is_default); if (dft_ttyname && !is_default) dft_ttyname = NULL; /* We need the default value. */ /* Send the value for LC_CTYPE. */ #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) old_lc = setlocale (LC_CTYPE, NULL); if (old_lc) { old_lc = xtrystrdup (old_lc); if (!old_lc) return gpg_error_from_syserror (); } dft_lc = setlocale (LC_CTYPE, ""); #endif if (opt_lc_ctype || (dft_ttyname && dft_lc)) { err = send_one_option (ctx, errsource, "lc-ctype", opt_lc_ctype ? opt_lc_ctype : dft_lc, 0); } #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) if (old_lc) { setlocale (LC_CTYPE, old_lc); xfree (old_lc); } #endif if (err) return err; /* Send the value for LC_MESSAGES. */ #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) old_lc = setlocale (LC_MESSAGES, NULL); if (old_lc) { old_lc = xtrystrdup (old_lc); if (!old_lc) return gpg_error_from_syserror (); } dft_lc = setlocale (LC_MESSAGES, ""); #endif if (opt_lc_messages || (dft_ttyname && dft_lc)) { err = send_one_option (ctx, errsource, "lc-messages", opt_lc_messages ? opt_lc_messages : dft_lc, 0); } #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) if (old_lc) { setlocale (LC_MESSAGES, old_lc); xfree (old_lc); } #endif if (err) return err; return 0; } /* Try to connect to the agent via socket or fork it off and work by pipes. Handle the server's initial greeting. Returns a new assuan context at R_CTX or an error code. */ gpg_error_t start_new_gpg_agent (assuan_context_t *r_ctx, gpg_err_source_t errsource, const char *homedir, const char *agent_program, const char *opt_lc_ctype, const char *opt_lc_messages, session_env_t session_env, int verbose, int debug, gpg_error_t (*status_cb)(ctrl_t, int, ...), ctrl_t status_cb_arg) { /* If we ever failed to connect via a socket we will force the use of the pipe based server for the lifetime of the process. */ static int force_pipe_server = 0; gpg_error_t rc = 0; char *infostr, *p; assuan_context_t ctx; *r_ctx = NULL; rc = assuan_new (&ctx); if (rc) { log_error ("error allocating assuan context: %s\n", gpg_strerror (rc)); return rc; } restart: infostr = force_pipe_server? NULL : getenv ("GPG_AGENT_INFO"); if (!infostr || !*infostr) { char *sockname; /* First check whether we can connect at the standard socket. */ sockname = make_filename (homedir, "S.gpg-agent", NULL); rc = assuan_socket_connect (ctx, sockname, 0, 0); if (rc) { /* With no success start a new server. */ if (verbose) log_info (_("no running gpg-agent - starting one\n")); if (status_cb) status_cb (status_cb_arg, STATUS_PROGRESS, "starting_agent ? 0 0", NULL); if (fflush (NULL)) { gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno)); log_error ("error flushing pending output: %s\n", strerror (errno)); xfree (sockname); assuan_release (ctx); return tmperr; } if (!agent_program || !*agent_program) agent_program = gnupg_module_name (GNUPG_MODULE_NAME_AGENT); #ifdef HAVE_W32_SYSTEM { /* Under Windows we start the server in daemon mode. This is because the default is to use the standard socket and thus there is no need for the GPG_AGENT_INFO envvar. This is possible as we don't have a real unix domain socket but use a plain file and thus there is no need to care about non-local file systems. */ const char *argv[3]; argv[0] = "--daemon"; argv[1] = "--use-standard-socket"; argv[2] = NULL; rc = gnupg_spawn_process_detached (agent_program, argv, NULL); if (rc) log_debug ("failed to start agent `%s': %s\n", agent_program, gpg_strerror (rc)); else { /* Give the agent some time to prepare itself. */ gnupg_sleep (3); /* Now try again to connect the agent. */ rc = assuan_socket_connect (ctx, sockname, 0, 0); } } #else /*!HAVE_W32_SYSTEM*/ { const char *pgmname; const char *argv[3]; int no_close_list[3]; int i; if ( !(pgmname = strrchr (agent_program, '/'))) pgmname = agent_program; else pgmname++; argv[0] = pgmname; argv[1] = "--server"; argv[2] = NULL; i=0; if (log_get_fd () != -1) no_close_list[i++] = assuan_fd_from_posix_fd (log_get_fd ()); no_close_list[i++] = assuan_fd_from_posix_fd (fileno (stderr)); no_close_list[i] = -1; /* Connect to the agent and perform initial handshaking. */ rc = assuan_pipe_connect (ctx, agent_program, argv, no_close_list, NULL, NULL, 0); } #endif /*!HAVE_W32_SYSTEM*/ } xfree (sockname); } else { int prot; int pid; infostr = xstrdup (infostr); if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr) { log_error (_("malformed GPG_AGENT_INFO environment variable\n")); xfree (infostr); force_pipe_server = 1; goto restart; } *p++ = 0; pid = atoi (p); while (*p && *p != PATHSEP_C) p++; prot = *p? atoi (p+1) : 0; if (prot != 1) { log_error (_("gpg-agent protocol version %d is not supported\n"), prot); xfree (infostr); force_pipe_server = 1; goto restart; } rc = assuan_socket_connect (ctx, infostr, pid, 0); xfree (infostr); if (gpg_err_code (rc) == GPG_ERR_ASS_CONNECT_FAILED) { log_info (_("can't connect to the agent - trying fall back\n")); force_pipe_server = 1; goto restart; } } if (rc) { log_error ("can't connect to the agent: %s\n", gpg_strerror (rc)); assuan_release (ctx); return gpg_error (GPG_ERR_NO_AGENT); } if (debug) log_debug ("connection to agent established\n"); rc = assuan_transact (ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL); if (!rc) rc = send_pinentry_environment (ctx, errsource, opt_lc_ctype, opt_lc_messages, session_env); if (rc) { assuan_release (ctx); return rc; } *r_ctx = ctx; return 0; } diff --git a/common/estream.c b/common/estream.c index 32567e631..075a56564 100644 --- a/common/estream.c +++ b/common/estream.c @@ -1,3414 +1,3482 @@ /* estream.c - Extended Stream I/O Library * Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010 g10 Code GmbH * * This file is part of Libestream. * * Libestream 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 2 of the License, * or (at your option) any later version. * * Libestream 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 Libestream; if not, see . * * ALTERNATIVELY, Libestream 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. */ #ifdef USE_ESTREAM_SUPPORT_H # include #endif #ifdef HAVE_CONFIG_H # include #endif #if defined(_WIN32) && !defined(HAVE_W32_SYSTEM) # define HAVE_W32_SYSTEM 1 # if defined(__MINGW32CE__) && !defined (HAVE_W32CE_SYSTEM) # define HAVE_W32CE_SYSTEM # endif #endif #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # include #endif #ifdef HAVE_W32CE_SYSTEM # include /* ERRNO replacement. */ #endif #ifdef WITHOUT_GNU_PTH /* Give the Makefile a chance to build without Pth. */ # undef HAVE_PTH # undef USE_GNU_PTH #endif #ifdef HAVE_PTH # include #endif /* This is for the special hack to use estream.c in GnuPG. */ #ifdef GNUPG_MAJOR_VERSION # include "../common/util.h" #endif #ifndef HAVE_MKSTEMP int mkstemp (char *template); #endif #ifndef HAVE_MEMRCHR void *memrchr (const void *block, int c, size_t size); #endif #include #include #ifndef O_BINARY #define O_BINARY 0 #endif #ifdef HAVE_W32CE_SYSTEM # define _set_errno(a) gpg_err_set_errno ((a)) #else # define _set_errno(a) do { errno = (a); } while (0) #endif /* Generally used types. */ typedef void *(*func_realloc_t) (void *mem, size_t size); typedef void (*func_free_t) (void *mem); /* Buffer management layer. */ #define BUFFER_BLOCK_SIZE BUFSIZ #define BUFFER_UNREAD_SIZE 16 /* Locking. */ #ifdef HAVE_PTH typedef pth_mutex_t estream_mutex_t; # define ESTREAM_MUTEX_INITIALIZER PTH_MUTEX_INIT # define ESTREAM_MUTEX_LOCK(mutex) \ pth_mutex_acquire (&(mutex), 0, NULL) # define ESTREAM_MUTEX_UNLOCK(mutex) \ pth_mutex_release (&(mutex)) # define ESTREAM_MUTEX_TRYLOCK(mutex) \ ((pth_mutex_acquire (&(mutex), 1, NULL) == TRUE) ? 0 : -1) # define ESTREAM_MUTEX_INITIALIZE(mutex) \ pth_mutex_init (&(mutex)) #else typedef void *estream_mutex_t; static inline void dummy_mutex_call_void (estream_mutex_t mutex) { (void)mutex; } static inline int dummy_mutex_call_int (estream_mutex_t mutex) { (void)mutex; return 0; } # define ESTREAM_MUTEX_INITIALIZER NULL # define ESTREAM_MUTEX_LOCK(mutex) dummy_mutex_call_void ((mutex)) # define ESTREAM_MUTEX_UNLOCK(mutex) dummy_mutex_call_void ((mutex)) # define ESTREAM_MUTEX_TRYLOCK(mutex) dummy_mutex_call_int ((mutex)) # define ESTREAM_MUTEX_INITIALIZE(mutex) dummy_mutex_call_void ((mutex)) #endif /* Primitive system I/O. */ #ifdef HAVE_PTH # define ESTREAM_SYS_READ es_pth_read # define ESTREAM_SYS_WRITE es_pth_write #else # define ESTREAM_SYS_READ read # define ESTREAM_SYS_WRITE write #endif /* Misc definitions. */ #define ES_DEFAULT_OPEN_MODE (S_IRUSR | S_IWUSR) /* An internal stream object. */ struct estream_internal { unsigned char buffer[BUFFER_BLOCK_SIZE]; unsigned char unread_buffer[BUFFER_UNREAD_SIZE]; estream_mutex_t lock; /* Lock. */ void *cookie; /* Cookie. */ void *opaque; /* Opaque data. */ unsigned int modeflags; /* Flags for the backend. */ off_t offset; es_cookie_read_function_t func_read; es_cookie_write_function_t func_write; es_cookie_seek_function_t func_seek; es_cookie_close_function_t func_close; int strategy; int fd; struct { unsigned int err: 1; unsigned int eof: 1; } indicators; unsigned int deallocate_buffer: 1; + unsigned int is_stdstream:1; /* This is a standard stream. */ + unsigned int stdstream_fd:2; /* 0, 1 or 2 for a standard stream. */ unsigned int print_err: 1; /* Error in print_fun_writer. */ int print_errno; /* Errno from print_fun_writer. */ size_t print_ntotal; /* Bytes written from in print_fun_writer. */ FILE *print_fp; /* Stdio stream used by print_fun_writer. */ }; typedef struct estream_internal *estream_internal_t; #define ESTREAM_LOCK(stream) ESTREAM_MUTEX_LOCK (stream->intern->lock) #define ESTREAM_UNLOCK(stream) ESTREAM_MUTEX_UNLOCK (stream->intern->lock) #define ESTREAM_TRYLOCK(stream) ESTREAM_MUTEX_TRYLOCK (stream->intern->lock) /* Stream list. */ typedef struct estream_list *estream_list_t; struct estream_list { estream_t car; estream_list_t cdr; estream_list_t *prev_cdr; }; static estream_list_t estream_list; static estream_mutex_t estream_list_lock; #define ESTREAM_LIST_LOCK ESTREAM_MUTEX_LOCK (estream_list_lock) #define ESTREAM_LIST_UNLOCK ESTREAM_MUTEX_UNLOCK (estream_list_lock) #ifndef EOPNOTSUPP # define EOPNOTSUPP ENOSYS #endif /* Macros. */ /* Calculate array dimension. */ #ifndef DIM #define DIM(array) (sizeof (array) / sizeof (*array)) #endif #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) /* Evaluate EXPRESSION, setting VARIABLE to the return code, if VARIABLE is zero. */ #define SET_UNLESS_NONZERO(variable, tmp_variable, expression) \ do \ { \ tmp_variable = expression; \ if ((! variable) && tmp_variable) \ variable = tmp_variable; \ } \ while (0) /* Malloc wrappers to overcome problems on some older OSes. */ static void * mem_alloc (size_t n) { if (!n) n++; return malloc (n); } static void * mem_realloc (void *p, size_t n) { if (!p) return mem_alloc (n); return realloc (p, n); } static void mem_free (void *p) { if (p) free (p); } /* * List manipulation. */ -/* Add STREAM to the list of registered stream objects. */ +/* Add STREAM to the list of registered stream objects. If + WITH_LOCKED_LIST is true we assumed that the list of streams is + already locked. */ static int -es_list_add (estream_t stream) +es_list_add (estream_t stream, int with_locked_list) { estream_list_t list_obj; int ret; list_obj = mem_alloc (sizeof (*list_obj)); if (! list_obj) ret = -1; else { - ESTREAM_LIST_LOCK; + if (!with_locked_list) + ESTREAM_LIST_LOCK; list_obj->car = stream; list_obj->cdr = estream_list; list_obj->prev_cdr = &estream_list; if (estream_list) estream_list->prev_cdr = &list_obj->cdr; estream_list = list_obj; - ESTREAM_LIST_UNLOCK; + if (!with_locked_list) + ESTREAM_LIST_UNLOCK; ret = 0; } return ret; } /* Remove STREAM from the list of registered stream objects. */ static void -es_list_remove (estream_t stream) +es_list_remove (estream_t stream, int with_locked_list) { estream_list_t list_obj; - ESTREAM_LIST_LOCK; + if (!with_locked_list) + ESTREAM_LIST_LOCK; for (list_obj = estream_list; list_obj; list_obj = list_obj->cdr) if (list_obj->car == stream) { *list_obj->prev_cdr = list_obj->cdr; if (list_obj->cdr) list_obj->cdr->prev_cdr = list_obj->prev_cdr; mem_free (list_obj); break; } - ESTREAM_LIST_UNLOCK; + if (!with_locked_list) + ESTREAM_LIST_UNLOCK; } /* Type of an stream-iterator-function. */ typedef int (*estream_iterator_t) (estream_t stream); /* Iterate over list of registered streams, calling ITERATOR for each of them. */ static int es_list_iterate (estream_iterator_t iterator) { estream_list_t list_obj; int ret = 0; ESTREAM_LIST_LOCK; for (list_obj = estream_list; list_obj; list_obj = list_obj->cdr) ret |= (*iterator) (list_obj->car); ESTREAM_LIST_UNLOCK; return ret; } /* * I/O Helper * * Unfortunately our Pth emulation for Windows expects system handles * for pth_read and pth_write. We use a simple approach to fix this: * If the function returns an error we fall back to a vanilla read or * write, assuming that we do I/O on a plain file where the operation * can't block. */ #ifdef HAVE_PTH static int es_pth_read (int fd, void *buffer, size_t size) { # ifdef HAVE_W32_SYSTEM int rc = pth_read (fd, buffer, size); if (rc == -1 && errno == EINVAL) rc = read (fd, buffer, size); return rc; # else /*!HAVE_W32_SYSTEM*/ return pth_read (fd, buffer, size); # endif /* !HAVE_W32_SYSTEM*/ } static int es_pth_write (int fd, const void *buffer, size_t size) { # ifdef HAVE_W32_SYSTEM int rc = pth_write (fd, buffer, size); if (rc == -1 && errno == EINVAL) rc = write (fd, buffer, size); return rc; # else /*!HAVE_W32_SYSTEM*/ return pth_write (fd, buffer, size); # endif /* !HAVE_W32_SYSTEM*/ } #endif /*HAVE_PTH*/ /* * Initialization. */ static int es_init_do (void) { #ifdef HAVE_PTH static int initialized; if (!initialized) { if (!pth_init () && errno != EPERM ) return -1; if (pth_mutex_init (&estream_list_lock)) initialized = 1; } #endif return 0; } /* * I/O methods. */ /* Implementation of Memory I/O. */ /* Cookie for memory objects. */ typedef struct estream_cookie_mem { unsigned int modeflags; /* Open flags. */ unsigned char *memory; /* Allocated data buffer. */ size_t memory_size; /* Allocated size of MEMORY. */ size_t memory_limit; /* Caller supplied maximum allowed allocation size or 0 for no limit. */ size_t offset; /* Current offset in MEMORY. */ size_t data_len; /* Used length of data in MEMORY. */ size_t block_size; /* Block size. */ struct { unsigned int grow: 1; /* MEMORY is allowed to grow. */ } flags; func_realloc_t func_realloc; func_free_t func_free; } *estream_cookie_mem_t; /* Create function for memory objects. DATA is either NULL or a user supplied buffer with the initial conetnt of the memory buffer. If DATA is NULL, DATA_N and DATA_LEN need to be 0 as well. If DATA is not NULL, DATA_N gives the allocated size of DATA and DATA_LEN the used length in DATA. */ static int es_func_mem_create (void *ES__RESTRICT *ES__RESTRICT cookie, unsigned char *ES__RESTRICT data, size_t data_n, size_t data_len, size_t block_size, unsigned int grow, func_realloc_t func_realloc, func_free_t func_free, unsigned int modeflags, size_t memory_limit) { estream_cookie_mem_t mem_cookie; int err; if (!data && (data_n || data_len)) { _set_errno (EINVAL); return -1; } mem_cookie = mem_alloc (sizeof (*mem_cookie)); if (!mem_cookie) err = -1; else { mem_cookie->modeflags = modeflags; mem_cookie->memory = data; mem_cookie->memory_size = data_n; mem_cookie->memory_limit = memory_limit; mem_cookie->offset = 0; mem_cookie->data_len = data_len; mem_cookie->block_size = block_size; mem_cookie->flags.grow = !!grow; mem_cookie->func_realloc = func_realloc ? func_realloc : mem_realloc; mem_cookie->func_free = func_free ? func_free : mem_free; *cookie = mem_cookie; err = 0; } return err; } /* Read function for memory objects. */ static ssize_t es_func_mem_read (void *cookie, void *buffer, size_t size) { estream_cookie_mem_t mem_cookie = cookie; ssize_t ret; if (size > mem_cookie->data_len - mem_cookie->offset) size = mem_cookie->data_len - mem_cookie->offset; if (size) { memcpy (buffer, mem_cookie->memory + mem_cookie->offset, size); mem_cookie->offset += size; } ret = size; return ret; } /* Write function for memory objects. */ static ssize_t es_func_mem_write (void *cookie, const void *buffer, size_t size) { estream_cookie_mem_t mem_cookie = cookie; ssize_t ret; size_t nleft; if (!size) return 0; /* A flush is a NOP for memory objects. */ if (mem_cookie->modeflags & O_APPEND) { /* Append to data. */ mem_cookie->offset = mem_cookie->data_len; } assert (mem_cookie->memory_size >= mem_cookie->offset); nleft = mem_cookie->memory_size - mem_cookie->offset; /* If we are not allowed to grow limit the size to the left space. */ if (!mem_cookie->flags.grow && size > nleft) size = nleft; /* Enlarge the memory buffer if needed. */ if (size > nleft) { unsigned char *newbuf; size_t newsize; if (!mem_cookie->memory_size) newsize = size; /* Not yet allocated. */ else newsize = mem_cookie->memory_size + (nleft - size); if (newsize < mem_cookie->offset) { _set_errno (EINVAL); return -1; } /* Round up to the next block length. BLOCK_SIZE should always be set; we check anyway. */ if (mem_cookie->block_size) { newsize += mem_cookie->block_size - 1; if (newsize < mem_cookie->offset) { _set_errno (EINVAL); return -1; } newsize /= mem_cookie->block_size; newsize *= mem_cookie->block_size; } /* Check for a total limit. */ if (mem_cookie->memory_limit && newsize > mem_cookie->memory_limit) { _set_errno (ENOSPC); return -1; } newbuf = mem_cookie->func_realloc (mem_cookie->memory, newsize); if (!newbuf) return -1; mem_cookie->memory = newbuf; mem_cookie->memory_size = newsize; assert (mem_cookie->memory_size >= mem_cookie->offset); nleft = mem_cookie->memory_size - mem_cookie->offset; assert (size <= nleft); } memcpy (mem_cookie->memory + mem_cookie->offset, buffer, size); if (mem_cookie->offset + size > mem_cookie->data_len) mem_cookie->data_len = mem_cookie->offset + size; mem_cookie->offset += size; ret = size; return ret; } /* Seek function for memory objects. */ static int es_func_mem_seek (void *cookie, off_t *offset, int whence) { estream_cookie_mem_t mem_cookie = cookie; off_t pos_new; switch (whence) { case SEEK_SET: pos_new = *offset; break; case SEEK_CUR: pos_new = mem_cookie->offset += *offset; break; case SEEK_END: pos_new = mem_cookie->data_len += *offset; break; default: _set_errno (EINVAL); return -1; } if (pos_new > mem_cookie->memory_size) { size_t newsize; void *newbuf; if (!mem_cookie->flags.grow) { _set_errno (ENOSPC); return -1; } newsize = pos_new + mem_cookie->block_size - 1; if (newsize < pos_new) { _set_errno (EINVAL); return -1; } newsize /= mem_cookie->block_size; newsize *= mem_cookie->block_size; if (mem_cookie->memory_limit && newsize > mem_cookie->memory_limit) { _set_errno (ENOSPC); return -1; } newbuf = mem_cookie->func_realloc (mem_cookie->memory, newsize); if (!newbuf) return -1; mem_cookie->memory = newbuf; mem_cookie->memory_size = newsize; } if (pos_new > mem_cookie->data_len) { /* Fill spare space with zeroes. */ memset (mem_cookie->memory + mem_cookie->data_len, 0, pos_new - mem_cookie->data_len); mem_cookie->data_len = pos_new; } mem_cookie->offset = pos_new; *offset = pos_new; return 0; } /* Destroy function for memory objects. */ static int es_func_mem_destroy (void *cookie) { estream_cookie_mem_t mem_cookie = cookie; if (cookie) { mem_cookie->func_free (mem_cookie->memory); mem_free (mem_cookie); } return 0; } static es_cookie_io_functions_t estream_functions_mem = { es_func_mem_read, es_func_mem_write, es_func_mem_seek, es_func_mem_destroy }; /* Implementation of fd I/O. */ /* Cookie for fd objects. */ typedef struct estream_cookie_fd { int fd; /* The file descriptor we are using for actual output. */ int no_close; /* If set we won't close the file descriptor. */ } *estream_cookie_fd_t; /* Create function for fd objects. */ static int es_func_fd_create (void **cookie, int fd, unsigned int modeflags, int no_close) { estream_cookie_fd_t fd_cookie; int err; fd_cookie = mem_alloc (sizeof (*fd_cookie)); if (! fd_cookie) err = -1; else { #ifdef HAVE_DOSISH_SYSTEM /* Make sure it is in binary mode if requested. */ if ( (modeflags & O_BINARY) ) setmode (fd, O_BINARY); #else (void)modeflags; #endif fd_cookie->fd = fd; fd_cookie->no_close = no_close; *cookie = fd_cookie; err = 0; } return err; } /* Read function for fd objects. */ static ssize_t es_func_fd_read (void *cookie, void *buffer, size_t size) { estream_cookie_fd_t file_cookie = cookie; ssize_t bytes_read; do bytes_read = ESTREAM_SYS_READ (file_cookie->fd, buffer, size); while (bytes_read == -1 && errno == EINTR); return bytes_read; } /* Write function for fd objects. */ static ssize_t es_func_fd_write (void *cookie, const void *buffer, size_t size) { estream_cookie_fd_t file_cookie = cookie; ssize_t bytes_written; do bytes_written = ESTREAM_SYS_WRITE (file_cookie->fd, buffer, size); while (bytes_written == -1 && errno == EINTR); return bytes_written; } /* Seek function for fd objects. */ static int es_func_fd_seek (void *cookie, off_t *offset, int whence) { estream_cookie_fd_t file_cookie = cookie; off_t offset_new; int err; offset_new = lseek (file_cookie->fd, *offset, whence); if (offset_new == -1) err = -1; else { *offset = offset_new; err = 0; } return err; } /* Destroy function for fd objects. */ static int es_func_fd_destroy (void *cookie) { estream_cookie_fd_t fd_cookie = cookie; int err; if (fd_cookie) { err = fd_cookie->no_close? 0 : close (fd_cookie->fd); mem_free (fd_cookie); } else err = 0; return err; } static es_cookie_io_functions_t estream_functions_fd = { es_func_fd_read, es_func_fd_write, es_func_fd_seek, es_func_fd_destroy }; /* Implementation of FILE* I/O. */ /* Cookie for fp objects. */ typedef struct estream_cookie_fp { FILE *fp; /* The file pointer we are using for actual output. */ int no_close; /* If set we won't close the file pointer. */ } *estream_cookie_fp_t; /* Create function for fd objects. */ static int es_func_fp_create (void **cookie, FILE *fp, unsigned int modeflags, int no_close) { estream_cookie_fp_t fp_cookie; int err; fp_cookie = mem_alloc (sizeof *fp_cookie); if (!fp_cookie) err = -1; else { #ifdef HAVE_DOSISH_SYSTEM /* Make sure it is in binary mode if requested. */ if ( (modeflags & O_BINARY) ) setmode (fileno (fp), O_BINARY); #else (void)modeflags; #endif fp_cookie->fp = fp; fp_cookie->no_close = no_close; *cookie = fp_cookie; err = 0; } return err; } /* Read function for FILE* objects. */ static ssize_t es_func_fp_read (void *cookie, void *buffer, size_t size) { estream_cookie_fp_t file_cookie = cookie; ssize_t bytes_read; if (file_cookie->fp) bytes_read = fread (buffer, 1, size, file_cookie->fp); else bytes_read = 0; if (!bytes_read && ferror (file_cookie->fp)) return -1; return bytes_read; } /* Write function for FILE* objects. */ static ssize_t es_func_fp_write (void *cookie, const void *buffer, size_t size) { estream_cookie_fp_t file_cookie = cookie; size_t bytes_written; if (file_cookie->fp) bytes_written = fwrite (buffer, 1, size, file_cookie->fp); else bytes_written = size; /* Successfully written to the bit bucket. */ if (bytes_written != size) return -1; return bytes_written; } /* Seek function for FILE* objects. */ static int es_func_fp_seek (void *cookie, off_t *offset, int whence) { estream_cookie_fp_t file_cookie = cookie; long int offset_new; if (!file_cookie->fp) { _set_errno (ESPIPE); return -1; } if ( fseek (file_cookie->fp, (long int)*offset, whence) ) { /* fprintf (stderr, "\nfseek failed: errno=%d (%s)\n", */ /* errno,strerror (errno)); */ return -1; } offset_new = ftell (file_cookie->fp); if (offset_new == -1) { /* fprintf (stderr, "\nftell failed: errno=%d (%s)\n", */ /* errno,strerror (errno)); */ return -1; } *offset = offset_new; return 0; } /* Destroy function for fd objects. */ static int es_func_fp_destroy (void *cookie) { estream_cookie_fp_t fp_cookie = cookie; int err; if (fp_cookie) { if (fp_cookie->fp) { fflush (fp_cookie->fp); err = fp_cookie->no_close? 0 : fclose (fp_cookie->fp); } else err = 0; mem_free (fp_cookie); } else err = 0; return err; } static es_cookie_io_functions_t estream_functions_fp = { es_func_fp_read, es_func_fp_write, es_func_fp_seek, es_func_fp_destroy }; /* Implementation of file I/O. */ /* Create function for file objects. */ static int es_func_file_create (void **cookie, int *filedes, const char *path, unsigned int modeflags) { estream_cookie_fd_t file_cookie; int err; int fd; err = 0; fd = -1; file_cookie = mem_alloc (sizeof (*file_cookie)); if (! file_cookie) { err = -1; goto out; } fd = open (path, modeflags, ES_DEFAULT_OPEN_MODE); if (fd == -1) { err = -1; goto out; } #ifdef HAVE_DOSISH_SYSTEM /* Make sure it is in binary mode if requested. */ if ( (modeflags & O_BINARY) ) setmode (fd, O_BINARY); #endif file_cookie->fd = fd; file_cookie->no_close = 0; *cookie = file_cookie; *filedes = fd; out: if (err) mem_free (file_cookie); return err; } static es_cookie_io_functions_t estream_functions_file = { es_func_fd_read, es_func_fd_write, es_func_fd_seek, es_func_fd_destroy }; static int es_convert_mode (const char *mode, unsigned int *modeflags) { unsigned int omode, oflags; switch (*mode) { case 'r': omode = O_RDONLY; oflags = 0; break; case 'w': omode = O_WRONLY; oflags = O_TRUNC | O_CREAT; break; case 'a': omode = O_WRONLY; oflags = O_APPEND | O_CREAT; break; default: _set_errno (EINVAL); return -1; } for (mode++; *mode; mode++) { switch (*mode) { case '+': omode = O_RDWR; break; case 'b': oflags |= O_BINARY; break; case 'x': oflags |= O_EXCL; break; default: /* Ignore unknown flags. */ break; } } *modeflags = (omode | oflags); return 0; } /* * Low level stream functionality. */ static int es_fill (estream_t stream) { size_t bytes_read = 0; int err; if (!stream->intern->func_read) { _set_errno (EOPNOTSUPP); err = -1; } else { es_cookie_read_function_t func_read = stream->intern->func_read; ssize_t ret; ret = (*func_read) (stream->intern->cookie, stream->buffer, stream->buffer_size); if (ret == -1) { bytes_read = 0; err = -1; } else { bytes_read = ret; err = 0; } } if (err) stream->intern->indicators.err = 1; else if (!bytes_read) stream->intern->indicators.eof = 1; stream->intern->offset += stream->data_len; stream->data_len = bytes_read; stream->data_offset = 0; return err; } static int es_flush (estream_t stream) { es_cookie_write_function_t func_write = stream->intern->func_write; int err; assert (stream->flags.writing); if (stream->data_offset) { size_t bytes_written; size_t data_flushed; ssize_t ret; if (! func_write) { err = EOPNOTSUPP; goto out; } /* Note: to prevent an endless loop caused by user-provided write-functions that pretend to have written more bytes than they were asked to write, we have to check for "(stream->data_offset - data_flushed) > 0" instead of "stream->data_offset - data_flushed". */ data_flushed = 0; err = 0; while ((((ssize_t) (stream->data_offset - data_flushed)) > 0) && (! err)) { ret = (*func_write) (stream->intern->cookie, stream->buffer + data_flushed, stream->data_offset - data_flushed); if (ret == -1) { bytes_written = 0; err = -1; } else bytes_written = ret; data_flushed += bytes_written; if (err) break; } stream->data_flushed += data_flushed; if (stream->data_offset == data_flushed) { stream->intern->offset += stream->data_offset; stream->data_offset = 0; stream->data_flushed = 0; /* Propagate flush event. */ (*func_write) (stream->intern->cookie, NULL, 0); } } else err = 0; out: if (err) stream->intern->indicators.err = 1; return err; } /* Discard buffered data for STREAM. */ static void es_empty (estream_t stream) { assert (!stream->flags.writing); stream->data_len = 0; stream->data_offset = 0; stream->unread_data_len = 0; } /* Initialize STREAM. */ static void es_initialize (estream_t stream, void *cookie, int fd, es_cookie_io_functions_t functions, unsigned int modeflags) { stream->intern->cookie = cookie; stream->intern->opaque = NULL; stream->intern->offset = 0; stream->intern->func_read = functions.func_read; stream->intern->func_write = functions.func_write; stream->intern->func_seek = functions.func_seek; stream->intern->func_close = functions.func_close; stream->intern->strategy = _IOFBF; stream->intern->fd = fd; stream->intern->print_err = 0; stream->intern->print_errno = 0; stream->intern->print_ntotal = 0; stream->intern->print_fp = NULL; stream->intern->indicators.err = 0; stream->intern->indicators.eof = 0; + stream->intern->is_stdstream = 0; + stream->intern->stdstream_fd = 0; stream->intern->deallocate_buffer = 0; stream->data_len = 0; stream->data_offset = 0; stream->data_flushed = 0; stream->unread_data_len = 0; /* Depending on the modeflags we set whether we start in writing or reading mode. This is required in case we are working on a - wronly stream which is not seeekable (like stdout). Without this + stream which is not seeekable (like stdout). Without this pre-initialization we would do a seek at the first write call and as this will fail no utput will be delivered. */ if ((modeflags & O_WRONLY) || (modeflags & O_RDWR) ) stream->flags.writing = 1; else stream->flags.writing = 0; } /* Deinitialize STREAM. */ static int es_deinitialize (estream_t stream) { es_cookie_close_function_t func_close; int err, tmp_err; if (stream->intern->print_fp) { int save_errno = errno; fclose (stream->intern->print_fp); stream->intern->print_fp = NULL; _set_errno (save_errno); } func_close = stream->intern->func_close; err = 0; if (stream->flags.writing) SET_UNLESS_NONZERO (err, tmp_err, es_flush (stream)); if (func_close) SET_UNLESS_NONZERO (err, tmp_err, (*func_close) (stream->intern->cookie)); return err; } /* Create a new stream object, initialize it. */ static int es_create (estream_t *stream, void *cookie, int fd, - es_cookie_io_functions_t functions, unsigned int modeflags) + es_cookie_io_functions_t functions, unsigned int modeflags, + int with_locked_list) { estream_internal_t stream_internal_new; estream_t stream_new; int err; stream_new = NULL; stream_internal_new = NULL; stream_new = mem_alloc (sizeof (*stream_new)); if (! stream_new) { err = -1; goto out; } stream_internal_new = mem_alloc (sizeof (*stream_internal_new)); if (! stream_internal_new) { err = -1; goto out; } stream_new->buffer = stream_internal_new->buffer; stream_new->buffer_size = sizeof (stream_internal_new->buffer); stream_new->unread_buffer = stream_internal_new->unread_buffer; stream_new->unread_buffer_size = sizeof (stream_internal_new->unread_buffer); stream_new->intern = stream_internal_new; ESTREAM_MUTEX_INITIALIZE (stream_new->intern->lock); es_initialize (stream_new, cookie, fd, functions, modeflags); - err = es_list_add (stream_new); + err = es_list_add (stream_new, with_locked_list); if (err) goto out; *stream = stream_new; out: if (err) { if (stream_new) { es_deinitialize (stream_new); mem_free (stream_new); } } return err; } /* Deinitialize a stream object and destroy it. */ static int -es_destroy (estream_t stream) +es_destroy (estream_t stream, int with_locked_list) { int err = 0; if (stream) { - es_list_remove (stream); + es_list_remove (stream, with_locked_list); err = es_deinitialize (stream); mem_free (stream->intern); mem_free (stream); } return err; } /* Try to read BYTES_TO_READ bytes FROM STREAM into BUFFER in unbuffered-mode, storing the amount of bytes read in *BYTES_READ. */ static int es_read_nbf (estream_t ES__RESTRICT stream, unsigned char *ES__RESTRICT buffer, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read) { es_cookie_read_function_t func_read = stream->intern->func_read; size_t data_read; ssize_t ret; int err; data_read = 0; err = 0; while (bytes_to_read - data_read) { ret = (*func_read) (stream->intern->cookie, buffer + data_read, bytes_to_read - data_read); if (ret == -1) { err = -1; break; } else if (ret) data_read += ret; else break; } stream->intern->offset += data_read; *bytes_read = data_read; return err; } /* Try to read BYTES_TO_READ bytes FROM STREAM into BUFFER in fully-buffered-mode, storing the amount of bytes read in *BYTES_READ. */ static int es_read_fbf (estream_t ES__RESTRICT stream, unsigned char *ES__RESTRICT buffer, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read) { size_t data_available; size_t data_to_read; size_t data_read; int err; data_read = 0; err = 0; while ((bytes_to_read - data_read) && (! err)) { if (stream->data_offset == stream->data_len) { /* Nothing more to read in current container, try to fill container with new data. */ err = es_fill (stream); if (! err) if (! stream->data_len) /* Filling did not result in any data read. */ break; } if (! err) { /* Filling resulted in some new data. */ data_to_read = bytes_to_read - data_read; data_available = stream->data_len - stream->data_offset; if (data_to_read > data_available) data_to_read = data_available; memcpy (buffer + data_read, stream->buffer + stream->data_offset, data_to_read); stream->data_offset += data_to_read; data_read += data_to_read; } } *bytes_read = data_read; return err; } /* Try to read BYTES_TO_READ bytes FROM STREAM into BUFFER in line-buffered-mode, storing the amount of bytes read in *BYTES_READ. */ static int es_read_lbf (estream_t ES__RESTRICT stream, unsigned char *ES__RESTRICT buffer, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read) { int err; err = es_read_fbf (stream, buffer, bytes_to_read, bytes_read); return err; } /* Try to read BYTES_TO_READ bytes FROM STREAM into BUFFER, storing *the amount of bytes read in BYTES_READ. */ static int es_readn (estream_t ES__RESTRICT stream, void *ES__RESTRICT buffer_arg, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read) { unsigned char *buffer = (unsigned char *)buffer_arg; size_t data_read_unread, data_read; int err; data_read_unread = 0; data_read = 0; err = 0; if (stream->flags.writing) { /* Switching to reading mode -> flush output. */ err = es_flush (stream); if (err) goto out; stream->flags.writing = 0; } /* Read unread data first. */ while ((bytes_to_read - data_read_unread) && stream->unread_data_len) { buffer[data_read_unread] = stream->unread_buffer[stream->unread_data_len - 1]; stream->unread_data_len--; data_read_unread++; } switch (stream->intern->strategy) { case _IONBF: err = es_read_nbf (stream, buffer + data_read_unread, bytes_to_read - data_read_unread, &data_read); break; case _IOLBF: err = es_read_lbf (stream, buffer + data_read_unread, bytes_to_read - data_read_unread, &data_read); break; case _IOFBF: err = es_read_fbf (stream, buffer + data_read_unread, bytes_to_read - data_read_unread, &data_read); break; } out: if (bytes_read) *bytes_read = data_read_unread + data_read; return err; } /* Try to unread DATA_N bytes from DATA into STREAM, storing the amount of bytes successfully unread in *BYTES_UNREAD. */ static void es_unreadn (estream_t ES__RESTRICT stream, const unsigned char *ES__RESTRICT data, size_t data_n, size_t *ES__RESTRICT bytes_unread) { size_t space_left; space_left = stream->unread_buffer_size - stream->unread_data_len; if (data_n > space_left) data_n = space_left; if (! data_n) goto out; memcpy (stream->unread_buffer + stream->unread_data_len, data, data_n); stream->unread_data_len += data_n; stream->intern->indicators.eof = 0; out: if (bytes_unread) *bytes_unread = data_n; } /* Seek in STREAM. */ static int es_seek (estream_t ES__RESTRICT stream, off_t offset, int whence, off_t *ES__RESTRICT offset_new) { es_cookie_seek_function_t func_seek = stream->intern->func_seek; int err, ret; off_t off; if (! func_seek) { _set_errno (EOPNOTSUPP); err = -1; goto out; } if (stream->flags.writing) { /* Flush data first in order to prevent flushing it to the wrong offset. */ err = es_flush (stream); if (err) goto out; stream->flags.writing = 0; } off = offset; if (whence == SEEK_CUR) { off = off - stream->data_len + stream->data_offset; off -= stream->unread_data_len; } ret = (*func_seek) (stream->intern->cookie, &off, whence); if (ret == -1) { err = -1; goto out; } err = 0; es_empty (stream); if (offset_new) *offset_new = off; stream->intern->indicators.eof = 0; stream->intern->offset = off; out: if (err) stream->intern->indicators.err = 1; return err; } /* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in unbuffered-mode, storing the amount of bytes written in *BYTES_WRITTEN. */ static int es_write_nbf (estream_t ES__RESTRICT stream, const unsigned char *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written) { es_cookie_write_function_t func_write = stream->intern->func_write; size_t data_written; ssize_t ret; int err; if (bytes_to_write && (! func_write)) { err = EOPNOTSUPP; goto out; } data_written = 0; err = 0; while (bytes_to_write - data_written) { ret = (*func_write) (stream->intern->cookie, buffer + data_written, bytes_to_write - data_written); if (ret == -1) { err = -1; break; } else data_written += ret; } stream->intern->offset += data_written; *bytes_written = data_written; out: return err; } /* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in fully-buffered-mode, storing the amount of bytes written in *BYTES_WRITTEN. */ static int es_write_fbf (estream_t ES__RESTRICT stream, const unsigned char *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written) { size_t space_available; size_t data_to_write; size_t data_written; int err; data_written = 0; err = 0; while ((bytes_to_write - data_written) && (! err)) { if (stream->data_offset == stream->buffer_size) /* Container full, flush buffer. */ err = es_flush (stream); if (! err) { /* Flushing resulted in empty container. */ data_to_write = bytes_to_write - data_written; space_available = stream->buffer_size - stream->data_offset; if (data_to_write > space_available) data_to_write = space_available; memcpy (stream->buffer + stream->data_offset, buffer + data_written, data_to_write); stream->data_offset += data_to_write; data_written += data_to_write; } } *bytes_written = data_written; return err; } /* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in line-buffered-mode, storing the amount of bytes written in *BYTES_WRITTEN. */ static int es_write_lbf (estream_t ES__RESTRICT stream, const unsigned char *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written) { size_t data_flushed = 0; size_t data_buffered = 0; unsigned char *nlp; int err = 0; nlp = memrchr (buffer, '\n', bytes_to_write); if (nlp) { /* Found a newline, directly write up to (including) this character. */ err = es_flush (stream); if (!err) err = es_write_nbf (stream, buffer, nlp - buffer + 1, &data_flushed); } if (!err) { /* Write remaining data fully buffered. */ err = es_write_fbf (stream, buffer + data_flushed, bytes_to_write - data_flushed, &data_buffered); } *bytes_written = data_flushed + data_buffered; return err; } /* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in, storing the amount of bytes written in BYTES_WRITTEN. */ static int es_writen (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written) { size_t data_written; int err; data_written = 0; err = 0; if (!stream->flags.writing) { /* Switching to writing mode -> discard input data and seek to position at which reading has stopped. We can do this only if a seek function has been registered. */ if (stream->intern->func_seek) { err = es_seek (stream, 0, SEEK_CUR, NULL); if (err) { if (errno == ESPIPE) err = 0; else goto out; } } } switch (stream->intern->strategy) { case _IONBF: err = es_write_nbf (stream, buffer, bytes_to_write, &data_written); break; case _IOLBF: err = es_write_lbf (stream, buffer, bytes_to_write, &data_written); break; case _IOFBF: err = es_write_fbf (stream, buffer, bytes_to_write, &data_written); break; } out: if (bytes_written) *bytes_written = data_written; if (data_written) if (!stream->flags.writing) stream->flags.writing = 1; return err; } static int es_peek (estream_t ES__RESTRICT stream, unsigned char **ES__RESTRICT data, size_t *ES__RESTRICT data_len) { int err; if (stream->flags.writing) { /* Switching to reading mode -> flush output. */ err = es_flush (stream); if (err) goto out; stream->flags.writing = 0; } if (stream->data_offset == stream->data_len) { /* Refill container. */ err = es_fill (stream); if (err) goto out; } if (data) *data = stream->buffer + stream->data_offset; if (data_len) *data_len = stream->data_len - stream->data_offset; err = 0; out: return err; } /* Skip SIZE bytes of input data contained in buffer. */ static int es_skip (estream_t stream, size_t size) { int err; if (stream->data_offset + size > stream->data_len) { _set_errno (EINVAL); err = -1; } else { stream->data_offset += size; err = 0; } return err; } static int doreadline (estream_t ES__RESTRICT stream, size_t max_length, char *ES__RESTRICT *ES__RESTRICT line, size_t *ES__RESTRICT line_length) { size_t space_left; size_t line_size; estream_t line_stream; char *line_new; void *line_stream_cookie; char *newline; unsigned char *data; size_t data_len; int err; line_new = NULL; line_stream = NULL; line_stream_cookie = NULL; err = es_func_mem_create (&line_stream_cookie, NULL, 0, 0, BUFFER_BLOCK_SIZE, 1, mem_realloc, mem_free, O_RDWR, 0); if (err) goto out; err = es_create (&line_stream, line_stream_cookie, -1, - estream_functions_mem, O_RDWR); + estream_functions_mem, O_RDWR, 0); if (err) goto out; space_left = max_length; line_size = 0; while (1) { if (max_length && (space_left == 1)) break; err = es_peek (stream, &data, &data_len); if (err || (! data_len)) break; if (data_len > (space_left - 1)) data_len = space_left - 1; newline = memchr (data, '\n', data_len); if (newline) { data_len = (newline - (char *) data) + 1; err = es_write (line_stream, data, data_len, NULL); if (! err) { space_left -= data_len; line_size += data_len; es_skip (stream, data_len); break; } } else { err = es_write (line_stream, data, data_len, NULL); if (! err) { space_left -= data_len; line_size += data_len; es_skip (stream, data_len); } } if (err) break; } if (err) goto out; /* Complete line has been written to line_stream. */ if ((max_length > 1) && (! line_size)) { stream->intern->indicators.eof = 1; goto out; } err = es_seek (line_stream, 0, SEEK_SET, NULL); if (err) goto out; if (! *line) { line_new = mem_alloc (line_size + 1); if (! line_new) { err = -1; goto out; } } else line_new = *line; err = es_read (line_stream, line_new, line_size, NULL); if (err) goto out; line_new[line_size] = '\0'; if (! *line) *line = line_new; if (line_length) *line_length = line_size; out: if (line_stream) - es_destroy (line_stream); + es_destroy (line_stream, 0); else if (line_stream_cookie) es_func_mem_destroy (line_stream_cookie); if (err) { if (! *line) mem_free (line_new); stream->intern->indicators.err = 1; } return err; } /* Output fucntion used for estream_format. */ static int print_writer (void *outfncarg, const char *buf, size_t buflen) { estream_t stream = outfncarg; size_t nwritten; int rc; nwritten = 0; rc = es_writen (stream, buf, buflen, &nwritten); stream->intern->print_ntotal += nwritten; return rc; } /* The core of our printf function. This is called in locked state. */ static int es_print (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, va_list ap) { int rc; stream->intern->print_ntotal = 0; rc = estream_format (print_writer, stream, format, ap); if (rc) return -1; return (int)stream->intern->print_ntotal; } static void es_set_indicators (estream_t stream, int ind_err, int ind_eof) { if (ind_err != -1) stream->intern->indicators.err = ind_err ? 1 : 0; if (ind_eof != -1) stream->intern->indicators.eof = ind_eof ? 1 : 0; } static int es_get_indicator (estream_t stream, int ind_err, int ind_eof) { int ret = 0; if (ind_err) ret = stream->intern->indicators.err; else if (ind_eof) ret = stream->intern->indicators.eof; return ret; } static int es_set_buffering (estream_t ES__RESTRICT stream, char *ES__RESTRICT buffer, int mode, size_t size) { int err; /* Flush or empty buffer depending on mode. */ if (stream->flags.writing) { err = es_flush (stream); if (err) goto out; } else es_empty (stream); es_set_indicators (stream, -1, 0); /* Free old buffer in case that was allocated by this function. */ if (stream->intern->deallocate_buffer) { stream->intern->deallocate_buffer = 0; mem_free (stream->buffer); stream->buffer = NULL; } if (mode == _IONBF) stream->buffer_size = 0; else { void *buffer_new; if (buffer) buffer_new = buffer; else { if (!size) size = BUFSIZ; buffer_new = mem_alloc (size); if (! buffer_new) { err = -1; goto out; } } stream->buffer = buffer_new; stream->buffer_size = size; if (! buffer) stream->intern->deallocate_buffer = 1; } stream->intern->strategy = mode; err = 0; out: return err; } static off_t es_offset_calculate (estream_t stream) { off_t offset; offset = stream->intern->offset + stream->data_offset; if (offset < stream->unread_data_len) /* Offset undefined. */ offset = 0; else offset -= stream->unread_data_len; return offset; } static void es_opaque_ctrl (estream_t ES__RESTRICT stream, void *ES__RESTRICT opaque_new, void **ES__RESTRICT opaque_old) { if (opaque_old) *opaque_old = stream->intern->opaque; if (opaque_new) stream->intern->opaque = opaque_new; } static int es_get_fd (estream_t stream) { return stream->intern->fd; } /* API. */ int es_init (void) { int err; err = es_init_do (); return err; } estream_t es_fopen (const char *ES__RESTRICT path, const char *ES__RESTRICT mode) { unsigned int modeflags; int create_called; estream_t stream; void *cookie; int err; int fd; stream = NULL; cookie = NULL; create_called = 0; err = es_convert_mode (mode, &modeflags); if (err) goto out; err = es_func_file_create (&cookie, &fd, path, modeflags); if (err) goto out; create_called = 1; - err = es_create (&stream, cookie, fd, estream_functions_file, modeflags); + err = es_create (&stream, cookie, fd, estream_functions_file, modeflags, 0); if (err) goto out; out: if (err && create_called) (*estream_functions_file.func_close) (cookie); return stream; } estream_t es_mopen (unsigned char *ES__RESTRICT data, size_t data_n, size_t data_len, unsigned int grow, func_realloc_t func_realloc, func_free_t func_free, const char *ES__RESTRICT mode) { unsigned int modeflags; int create_called; estream_t stream; void *cookie; int err; cookie = 0; stream = NULL; create_called = 0; err = es_convert_mode (mode, &modeflags); if (err) goto out; err = es_func_mem_create (&cookie, data, data_n, data_len, BUFFER_BLOCK_SIZE, grow, func_realloc, func_free, modeflags, 0); if (err) goto out; create_called = 1; - err = es_create (&stream, cookie, -1, estream_functions_mem, modeflags); + err = es_create (&stream, cookie, -1, estream_functions_mem, modeflags, 0); out: if (err && create_called) (*estream_functions_mem.func_close) (cookie); return stream; } estream_t es_fopenmem (size_t memlimit, const char *ES__RESTRICT mode) { unsigned int modeflags; estream_t stream = NULL; void *cookie = NULL; /* Memory streams are always read/write. We use MODE only to get the append flag. */ if (es_convert_mode (mode, &modeflags)) return NULL; modeflags |= O_RDWR; if (es_func_mem_create (&cookie, NULL, 0, 0, BUFFER_BLOCK_SIZE, 1, mem_realloc, mem_free, modeflags, memlimit)) return NULL; - if (es_create (&stream, cookie, -1, estream_functions_mem, modeflags)) + if (es_create (&stream, cookie, -1, estream_functions_mem, modeflags, 0)) (*estream_functions_mem.func_close) (cookie); return stream; } estream_t es_fopencookie (void *ES__RESTRICT cookie, const char *ES__RESTRICT mode, es_cookie_io_functions_t functions) { unsigned int modeflags; estream_t stream; int err; stream = NULL; modeflags = 0; err = es_convert_mode (mode, &modeflags); if (err) goto out; - err = es_create (&stream, cookie, -1, functions, modeflags); + err = es_create (&stream, cookie, -1, functions, modeflags, 0); if (err) goto out; out: return stream; } estream_t do_fdopen (int filedes, const char *mode, int no_close) { unsigned int modeflags; int create_called; estream_t stream; void *cookie; int err; stream = NULL; cookie = NULL; create_called = 0; err = es_convert_mode (mode, &modeflags); if (err) goto out; err = es_func_fd_create (&cookie, filedes, modeflags, no_close); if (err) goto out; create_called = 1; - err = es_create (&stream, cookie, filedes, estream_functions_fd, modeflags); + err = es_create (&stream, cookie, filedes, estream_functions_fd, + modeflags, 0); out: if (err && create_called) (*estream_functions_fd.func_close) (cookie); return stream; } estream_t es_fdopen (int filedes, const char *mode) { return do_fdopen (filedes, mode, 0); } /* A variant of es_fdopen which does not close FILEDES at the end. */ estream_t es_fdopen_nc (int filedes, const char *mode) { return do_fdopen (filedes, mode, 1); } estream_t -do_fpopen (FILE *fp, const char *mode, int no_close) +do_fpopen (FILE *fp, const char *mode, int no_close, int with_locked_list) { unsigned int modeflags; int create_called; estream_t stream; void *cookie; int err; stream = NULL; cookie = NULL; create_called = 0; err = es_convert_mode (mode, &modeflags); if (err) goto out; if (fp) fflush (fp); err = es_func_fp_create (&cookie, fp, modeflags, no_close); if (err) goto out; create_called = 1; err = es_create (&stream, cookie, fp? fileno (fp):-1, estream_functions_fp, - modeflags); + modeflags, with_locked_list); out: if (err && create_called) (*estream_functions_fp.func_close) (cookie); return stream; } /* Create an estream from the stdio stream FP. This mechanism is useful in case the stdio streams have special properties and may not be mixed with fd based functions. This is for example the case under Windows where the 3 standard streams are associated with the console whereas a duped and fd-opened stream of one of this stream won't be associated with the console. As this messes things up it is easier to keep on using the standard I/O stream as a backend for estream. */ estream_t es_fpopen (FILE *fp, const char *mode) { - return do_fpopen (fp, mode, 0); + return do_fpopen (fp, mode, 0, 0); } /* Same as es_fpopen but does not close FP at the end. */ estream_t es_fpopen_nc (FILE *fp, const char *mode) { - return do_fpopen (fp, mode, 1); + return do_fpopen (fp, mode, 1, 0); +} + + +estream_t +_es_get_std_stream (int fd) +{ + estream_list_t list_obj; + estream_t stream = NULL; + + fd %= 3; /* We only allow 0, 1 or 2 but we don't want to return an error. */ + ESTREAM_LIST_LOCK; + for (list_obj = estream_list; list_obj; list_obj = list_obj->cdr) + if (list_obj->car->intern->is_stdstream + && list_obj->car->intern->stdstream_fd == fd) + { + stream = list_obj->car; + break; + } + if (!stream) + { + /* Standard stream not yet created - do it now. */ + if (!fd) + stream = do_fpopen (stdin, "r", 1, 1); + else if (fd == 1) + stream = do_fpopen (stdout, "a", 1, 1); + else + stream = do_fpopen (stderr, "a", 1, 1); + + if (!stream) /* Fallback: Create a bit bucket. */ + { + stream = do_fpopen (NULL, fd? "a":"r", 0, 1); + if (!stream) + { + fprintf (stderr, "fatal: error creating a dummy estream" + " for %d: %s\n", fd, strerror (errno)); + abort(); + } + } + stream->intern->is_stdstream = 1; + stream->intern->stdstream_fd = fd; + if (fd == 2) + es_set_buffering (stream, NULL, _IOLBF, 0); + } + ESTREAM_LIST_UNLOCK; + return stream; } estream_t es_freopen (const char *ES__RESTRICT path, const char *ES__RESTRICT mode, estream_t ES__RESTRICT stream) { int err; if (path) { unsigned int modeflags; int create_called; void *cookie; int fd; cookie = NULL; create_called = 0; ESTREAM_LOCK (stream); es_deinitialize (stream); err = es_convert_mode (mode, &modeflags); if (err) goto leave; err = es_func_file_create (&cookie, &fd, path, modeflags); if (err) goto leave; create_called = 1; es_initialize (stream, cookie, fd, estream_functions_file, modeflags); leave: if (err) { if (create_called) es_func_fd_destroy (cookie); - es_destroy (stream); + es_destroy (stream, 0); stream = NULL; } else ESTREAM_UNLOCK (stream); } else { /* FIXME? We don't support re-opening at the moment. */ _set_errno (EINVAL); es_deinitialize (stream); - es_destroy (stream); + es_destroy (stream, 0); stream = NULL; } return stream; } int es_fclose (estream_t stream) { int err; - err = es_destroy (stream); + err = es_destroy (stream, 0); return err; } int es_fileno_unlocked (estream_t stream) { return es_get_fd (stream); } void es_flockfile (estream_t stream) { ESTREAM_LOCK (stream); } int es_ftrylockfile (estream_t stream) { return ESTREAM_TRYLOCK (stream); } void es_funlockfile (estream_t stream) { ESTREAM_UNLOCK (stream); } int es_fileno (estream_t stream) { int ret; ESTREAM_LOCK (stream); ret = es_fileno_unlocked (stream); ESTREAM_UNLOCK (stream); return ret; } int es_feof_unlocked (estream_t stream) { return es_get_indicator (stream, 0, 1); } int es_feof (estream_t stream) { int ret; ESTREAM_LOCK (stream); ret = es_feof_unlocked (stream); ESTREAM_UNLOCK (stream); return ret; } int es_ferror_unlocked (estream_t stream) { return es_get_indicator (stream, 1, 0); } int es_ferror (estream_t stream) { int ret; ESTREAM_LOCK (stream); ret = es_ferror_unlocked (stream); ESTREAM_UNLOCK (stream); return ret; } void es_clearerr_unlocked (estream_t stream) { es_set_indicators (stream, 0, 0); } void es_clearerr (estream_t stream) { ESTREAM_LOCK (stream); es_clearerr_unlocked (stream); ESTREAM_UNLOCK (stream); } +static int +do_fflush (estream_t stream) +{ + int err; + + if (stream->flags.writing) + err = es_flush (stream); + else + { + es_empty (stream); + err = 0; + } + + return err; +} + + int es_fflush (estream_t stream) { int err; if (stream) { ESTREAM_LOCK (stream); - if (stream->flags.writing) - err = es_flush (stream); - else - { - es_empty (stream); - err = 0; - } + err = do_fflush (stream); ESTREAM_UNLOCK (stream); } else - err = es_list_iterate (es_fflush); + err = es_list_iterate (do_fflush); return err ? EOF : 0; } int es_fseek (estream_t stream, long int offset, int whence) { int err; ESTREAM_LOCK (stream); err = es_seek (stream, offset, whence, NULL); ESTREAM_UNLOCK (stream); return err; } int es_fseeko (estream_t stream, off_t offset, int whence) { int err; ESTREAM_LOCK (stream); err = es_seek (stream, offset, whence, NULL); ESTREAM_UNLOCK (stream); return err; } long int es_ftell (estream_t stream) { long int ret; ESTREAM_LOCK (stream); ret = es_offset_calculate (stream); ESTREAM_UNLOCK (stream); return ret; } off_t es_ftello (estream_t stream) { off_t ret = -1; ESTREAM_LOCK (stream); ret = es_offset_calculate (stream); ESTREAM_UNLOCK (stream); return ret; } void es_rewind (estream_t stream) { ESTREAM_LOCK (stream); es_seek (stream, 0L, SEEK_SET, NULL); es_set_indicators (stream, 0, -1); ESTREAM_UNLOCK (stream); } int _es_getc_underflow (estream_t stream) { int err; unsigned char c; size_t bytes_read; err = es_readn (stream, &c, 1, &bytes_read); return (err || (! bytes_read)) ? EOF : c; } int _es_putc_overflow (int c, estream_t stream) { unsigned char d = c; int err; err = es_writen (stream, &d, 1, NULL); return err ? EOF : c; } int es_fgetc (estream_t stream) { int ret; ESTREAM_LOCK (stream); ret = es_getc_unlocked (stream); ESTREAM_UNLOCK (stream); return ret; } int es_fputc (int c, estream_t stream) { int ret; ESTREAM_LOCK (stream); ret = es_putc_unlocked (c, stream); ESTREAM_UNLOCK (stream); return ret; } int es_ungetc (int c, estream_t stream) { unsigned char data = (unsigned char) c; size_t data_unread; ESTREAM_LOCK (stream); es_unreadn (stream, &data, 1, &data_unread); ESTREAM_UNLOCK (stream); return data_unread ? c : EOF; } int es_read (estream_t ES__RESTRICT stream, void *ES__RESTRICT buffer, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read) { int err; if (bytes_to_read) { ESTREAM_LOCK (stream); err = es_readn (stream, buffer, bytes_to_read, bytes_read); ESTREAM_UNLOCK (stream); } else err = 0; return err; } int es_write (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written) { int err; if (bytes_to_write) { ESTREAM_LOCK (stream); err = es_writen (stream, buffer, bytes_to_write, bytes_written); ESTREAM_UNLOCK (stream); } else err = 0; return err; } size_t es_fread (void *ES__RESTRICT ptr, size_t size, size_t nitems, estream_t ES__RESTRICT stream) { size_t ret, bytes; int err; if (size * nitems) { ESTREAM_LOCK (stream); err = es_readn (stream, ptr, size * nitems, &bytes); ESTREAM_UNLOCK (stream); ret = bytes / size; } else ret = 0; return ret; } size_t es_fwrite (const void *ES__RESTRICT ptr, size_t size, size_t nitems, estream_t ES__RESTRICT stream) { size_t ret, bytes; int err; if (size * nitems) { ESTREAM_LOCK (stream); err = es_writen (stream, ptr, size * nitems, &bytes); ESTREAM_UNLOCK (stream); ret = bytes / size; } else ret = 0; return ret; } char * es_fgets (char *ES__RESTRICT buffer, int length, estream_t ES__RESTRICT stream) { unsigned char *s = (unsigned char*)buffer; int c; if (!length) return NULL; c = EOF; ESTREAM_LOCK (stream); while (length > 1 && (c = es_getc_unlocked (stream)) != EOF && c != '\n') { *s++ = c; length--; } ESTREAM_UNLOCK (stream); if (c == EOF && s == (unsigned char*)buffer) return NULL; /* Nothing read. */ if (c != EOF && length > 1) *s++ = c; *s = 0; return buffer; } int es_fputs_unlocked (const char *ES__RESTRICT s, estream_t ES__RESTRICT stream) { size_t length; int err; length = strlen (s); err = es_writen (stream, s, length, NULL); return err ? EOF : 0; } int es_fputs (const char *ES__RESTRICT s, estream_t ES__RESTRICT stream) { size_t length; int err; length = strlen (s); ESTREAM_LOCK (stream); err = es_writen (stream, s, length, NULL); ESTREAM_UNLOCK (stream); return err ? EOF : 0; } ssize_t es_getline (char *ES__RESTRICT *ES__RESTRICT lineptr, size_t *ES__RESTRICT n, estream_t ES__RESTRICT stream) { char *line = NULL; size_t line_n = 0; int err; ESTREAM_LOCK (stream); err = doreadline (stream, 0, &line, &line_n); ESTREAM_UNLOCK (stream); if (err) goto out; if (*n) { /* Caller wants us to use his buffer. */ if (*n < (line_n + 1)) { /* Provided buffer is too small -> resize. */ void *p; p = mem_realloc (*lineptr, line_n + 1); if (! p) err = -1; else { if (*lineptr != p) *lineptr = p; } } if (! err) { memcpy (*lineptr, line, line_n + 1); if (*n != line_n) *n = line_n; } mem_free (line); } else { /* Caller wants new buffers. */ *lineptr = line; *n = line_n; } out: return err ? err : (ssize_t)line_n; } /* Same as fgets() but if the provided buffer is too short a larger one will be allocated. This is similar to getline. A line is considered a byte stream ending in a LF. If MAX_LENGTH is not NULL, it shall point to a value with the maximum allowed allocation. Returns the length of the line. EOF is indicated by a line of length zero. A truncated line is indicated my setting the value at MAX_LENGTH to 0. If the returned value is less then 0 not enough memory was enable or another error occurred; ERRNO is then set accordingly. If a line has been truncated, the file pointer is moved forward to the end of the line so that the next read starts with the next line. Note that MAX_LENGTH must be re-initialzied in this case. The caller initially needs to provide the address of a variable, initialized to NULL, at ADDR_OF_BUFFER and don't change this value anymore with the following invocations. LENGTH_OF_BUFFER should be the address of a variable, initialized to 0, which is also maintained by this function. Thus, both paramaters should be considered the state of this function. Note: The returned buffer is allocated with enough extra space to allow the caller to append a CR,LF,Nul. The buffer should be released using es_free. */ ssize_t es_read_line (estream_t stream, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length) { int c; char *buffer = *addr_of_buffer; size_t length = *length_of_buffer; size_t nbytes = 0; size_t maxlen = max_length? *max_length : 0; char *p; if (!buffer) { /* No buffer given - allocate a new one. */ length = 256; buffer = mem_alloc (length); *addr_of_buffer = buffer; if (!buffer) { *length_of_buffer = 0; if (max_length) *max_length = 0; return -1; } *length_of_buffer = length; } if (length < 4) { /* This should never happen. If it does, the function has been called with wrong arguments. */ _set_errno (EINVAL); return -1; } length -= 3; /* Reserve 3 bytes for CR,LF,EOL. */ ESTREAM_LOCK (stream); p = buffer; while ((c = es_getc_unlocked (stream)) != EOF) { if (nbytes == length) { /* Enlarge the buffer. */ if (maxlen && length > maxlen) { /* We are beyond our limit: Skip the rest of the line. */ while (c != '\n' && (c=es_getc_unlocked (stream)) != EOF) ; *p++ = '\n'; /* Always append a LF (we reserved some space). */ nbytes++; if (max_length) *max_length = 0; /* Indicate truncation. */ break; /* the while loop. */ } length += 3; /* Adjust for the reserved bytes. */ length += length < 1024? 256 : 1024; *addr_of_buffer = mem_realloc (buffer, length); if (!*addr_of_buffer) { int save_errno = errno; mem_free (buffer); *length_of_buffer = 0; if (max_length) *max_length = 0; ESTREAM_UNLOCK (stream); _set_errno (save_errno); return -1; } buffer = *addr_of_buffer; *length_of_buffer = length; length -= 3; p = buffer + nbytes; } *p++ = c; nbytes++; if (c == '\n') break; } *p = 0; /* Make sure the line is a string. */ ESTREAM_UNLOCK (stream); return nbytes; } /* Wrapper around free() to match the memory allocation system used by estream. Should be used for all buffers returned to the caller by libestream. */ void es_free (void *a) { mem_free (a); } int es_vfprintf_unlocked (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, va_list ap) { return es_print (stream, format, ap); } int es_vfprintf (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, va_list ap) { int ret; ESTREAM_LOCK (stream); ret = es_print (stream, format, ap); ESTREAM_UNLOCK (stream); return ret; } int es_fprintf_unlocked (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, ...) { int ret; va_list ap; va_start (ap, format); ret = es_print (stream, format, ap); va_end (ap); return ret; } int es_fprintf (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, ...) { int ret; va_list ap; va_start (ap, format); ESTREAM_LOCK (stream); ret = es_print (stream, format, ap); ESTREAM_UNLOCK (stream); va_end (ap); return ret; } /* A variant of asprintf. The function returns the allocated buffer or NULL on error; ERRNO is set in the error case. The caller should use es_free to release the buffer. This function actually belongs into estream-printf but we put it here as a convenience and because es_free is required anyway. */ char * es_asprintf (const char *ES__RESTRICT format, ...) { int rc; va_list ap; char *buf; va_start (ap, format); rc = estream_vasprintf (&buf, format, ap); va_end (ap); if (rc < 0) return NULL; return buf; } /* A variant of vasprintf. The function returns the allocated buffer or NULL on error; ERRNO is set in the error case. The caller should use es_free to release the buffer. This function actually belongs into estream-printf but we put it here as a convenience and because es_free is required anyway. */ char * es_vasprintf (const char *ES__RESTRICT format, va_list ap) { int rc; char *buf; rc = estream_vasprintf (&buf, format, ap); if (rc < 0) return NULL; return buf; } static int tmpfd (void) { #ifdef HAVE_W32_SYSTEM int attempts, n; #ifdef HAVE_W32CE_SYSTEM wchar_t buffer[MAX_PATH+9+12+1]; # define mystrlen(a) wcslen (a) wchar_t *name, *p; #else char buffer[MAX_PATH+9+12+1]; # define mystrlen(a) strlen (a) char *name, *p; #endif HANDLE file; int pid = GetCurrentProcessId (); unsigned int value; int i; n = GetTempPath (MAX_PATH+1, buffer); if (!n || n > MAX_PATH || mystrlen (buffer) > MAX_PATH) { _set_errno (ENOENT); return -1; } p = buffer + mystrlen (buffer); #ifdef HAVE_W32CE_SYSTEM wcscpy (p, L"_estream"); #else strcpy (p, "_estream"); #endif p += 8; /* We try to create the directory but don't care about an error as it may already exist and the CreateFile would throw an error anyway. */ CreateDirectory (buffer, NULL); *p++ = '\\'; name = p; for (attempts=0; attempts < 10; attempts++) { p = name; value = (GetTickCount () ^ ((pid<<16) & 0xffff0000)); for (i=0; i < 8; i++) { *p++ = tohex (((value >> 28) & 0x0f)); value <<= 4; } #ifdef HAVE_W32CE_SYSTEM wcscpy (p, L".tmp"); #else strcpy (p, ".tmp"); #endif file = CreateFile (buffer, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (file != INVALID_HANDLE_VALUE) { #ifdef HAVE_W32CE_SYSTEM int fd = (int)file; #else int fd = _open_osfhandle ((long)file, 0); if (fd == -1) { CloseHandle (file); return -1; } #endif return fd; } Sleep (1); /* One ms as this is the granularity of GetTickCount. */ } _set_errno (ENOENT); return -1; #else /*!HAVE_W32_SYSTEM*/ FILE *fp; int fp_fd; int fd; fp = NULL; fd = -1; fp = tmpfile (); if (! fp) goto out; fp_fd = fileno (fp); fd = dup (fp_fd); out: if (fp) fclose (fp); return fd; #endif /*!HAVE_W32_SYSTEM*/ } estream_t es_tmpfile (void) { unsigned int modeflags; int create_called; estream_t stream; void *cookie; int err; int fd; create_called = 0; stream = NULL; modeflags = O_RDWR | O_TRUNC | O_CREAT; cookie = NULL; fd = tmpfd (); if (fd == -1) { err = -1; goto out; } err = es_func_fd_create (&cookie, fd, modeflags, 0); if (err) goto out; create_called = 1; - err = es_create (&stream, cookie, fd, estream_functions_fd, modeflags); + err = es_create (&stream, cookie, fd, estream_functions_fd, modeflags, 0); out: if (err) { if (create_called) es_func_fd_destroy (cookie); else if (fd != -1) close (fd); stream = NULL; } return stream; } int es_setvbuf (estream_t ES__RESTRICT stream, char *ES__RESTRICT buf, int type, size_t size) { int err; if ((type == _IOFBF || type == _IOLBF || type == _IONBF) && (!buf || size || type == _IONBF)) { ESTREAM_LOCK (stream); err = es_set_buffering (stream, buf, type, size); ESTREAM_UNLOCK (stream); } else { _set_errno (EINVAL); err = -1; } return err; } void es_setbuf (estream_t ES__RESTRICT stream, char *ES__RESTRICT buf) { ESTREAM_LOCK (stream); es_set_buffering (stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ); ESTREAM_UNLOCK (stream); } void es_opaque_set (estream_t stream, void *opaque) { ESTREAM_LOCK (stream); es_opaque_ctrl (stream, opaque, NULL); ESTREAM_UNLOCK (stream); } void * es_opaque_get (estream_t stream) { void *opaque; ESTREAM_LOCK (stream); es_opaque_ctrl (stream, NULL, &opaque); ESTREAM_UNLOCK (stream); return opaque; } /* Print a BUFFER to STREAM while replacing all control characters and the characters in DELIMITERS by standard C escape sequences. Returns 0 on success or -1 on error. If BYTES_WRITTEN is not NULL the number of bytes actually written are stored at this address. */ int es_write_sanitized (estream_t ES__RESTRICT stream, const void * ES__RESTRICT buffer, size_t length, const char * delimiters, size_t * ES__RESTRICT bytes_written) { const unsigned char *p = buffer; size_t count = 0; int ret; ESTREAM_LOCK (stream); for (; length; length--, p++, count++) { if (*p < 0x20 || *p == 0x7f || (delimiters && (strchr (delimiters, *p) || *p == '\\'))) { es_putc_unlocked ('\\', stream); count++; if (*p == '\n') { es_putc_unlocked ('n', stream); count++; } else if (*p == '\r') { es_putc_unlocked ('r', stream); count++; } else if (*p == '\f') { es_putc_unlocked ('f', stream); count++; } else if (*p == '\v') { es_putc_unlocked ('v', stream); count++; } else if (*p == '\b') { es_putc_unlocked ('b', stream); count++; } else if (!*p) { es_putc_unlocked('0', stream); count++; } else { es_fprintf_unlocked (stream, "x%02x", *p); count += 3; } } else { es_putc_unlocked (*p, stream); count++; } } if (bytes_written) *bytes_written = count; ret = es_ferror_unlocked (stream)? -1 : 0; ESTREAM_UNLOCK (stream); return ret; } /* Write LENGTH bytes of BUFFER to STREAM as a hex encoded string. RESERVED must be 0. Returns 0 on success or -1 on error. If BYTES_WRITTEN is not NULL the number of bytes actually written are stored at this address. */ int es_write_hexstring (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t length, int reserved, size_t *ES__RESTRICT bytes_written ) { int ret; const unsigned char *s; size_t count = 0; (void)reserved; #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) if (!length) return 0; ESTREAM_LOCK (stream); for (s = buffer; length; s++, length--) { es_putc_unlocked ( tohex ((*s>>4)&15), stream); es_putc_unlocked ( tohex (*s&15), stream); count += 2; } if (bytes_written) *bytes_written = count; ret = es_ferror_unlocked (stream)? -1 : 0; ESTREAM_UNLOCK (stream); return ret; #undef tohex } #ifdef GNUPG_MAJOR_VERSION /* Special estream function to print an UTF8 string in the native encoding. The interface is the same as es_write_sanitized, however only one delimiter may be supported. THIS IS NOT A STANDARD ESTREAM FUNCTION AND ONLY USED BY GNUPG!. */ int es_write_sanitized_utf8_buffer (estream_t stream, const void *buffer, size_t length, const char *delimiters, size_t *bytes_written) { const char *p = buffer; size_t i; /* We can handle plain ascii simpler, so check for it first. */ for (i=0; i < length; i++ ) { if ( (p[i] & 0x80) ) break; } if (i < length) { int delim = delimiters? *delimiters : 0; char *buf; int ret; /*(utf8 conversion already does the control character quoting). */ buf = utf8_to_native (p, length, delim); if (bytes_written) *bytes_written = strlen (buf); ret = es_fputs (buf, stream); xfree (buf); return ret == EOF? ret : (int)i; } else return es_write_sanitized (stream, p, length, delimiters, bytes_written); } #endif /*GNUPG_MAJOR_VERSION*/ diff --git a/common/estream.h b/common/estream.h index 477aface8..67856bf76 100644 --- a/common/estream.h +++ b/common/estream.h @@ -1,363 +1,371 @@ /* estream.h - Extended stream I/O Library * Copyright (C) 2004, 2005, 2006, 2007, 2010 g10 Code GmbH * * This file is part of Libestream. * * Libestream 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 2 of the License, * or (at your option) any later version. * * Libestream 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 Libestream; if not, see . * * ALTERNATIVELY, Libestream 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. */ #ifndef ESTREAM_H #define ESTREAM_H #include #include #include /* To use this file with libraries the following macro is useful: #define _ESTREAM_EXT_SYM_PREFIX _foo_ This prefixes all external symbols with "_foo_". */ #ifdef _ESTREAM_EXT_SYM_PREFIX #ifndef _ESTREAM_PREFIX #define _ESTREAM_PREFIX1(x,y) x ## y #define _ESTREAM_PREFIX2(x,y) _ESTREAM_PREFIX1(x,y) #define _ESTREAM_PREFIX(x) _ESTREAM_PREFIX2(_ESTREAM_EXT_SYM_PREFIX,x) #endif /*_ESTREAM_PREFIX*/ #define es_fopen _ESTREAM_PREFIX(es_fopen) #define es_mopen _ESTREAM_PREFIX(es_mopen) #define es_fopenmem _ESTREAM_PREFIX(es_fopenmem) #define es_fdopen _ESTREAM_PREFIX(es_fdopen) #define es_fdopen_nc _ESTREAM_PREFIX(es_fdopen_nc) #define es_fpopen _ESTREAM_PREFIX(es_fpopen) #define es_fpopen_nc _ESTREAM_PREFIX(es_fpopen_nc) +#define _es_get_std_stream _ESTREAM_PREFIX(_es_get_std_stream) #define es_freopen _ESTREAM_PREFIX(es_freopen) #define es_fopencookie _ESTREAM_PREFIX(es_fopencookie) #define es_fclose _ESTREAM_PREFIX(es_fclose) #define es_fileno _ESTREAM_PREFIX(es_fileno) #define es_fileno_unlocked _ESTREAM_PREFIX(es_fileno_unlocked) #define es_flockfile _ESTREAM_PREFIX(es_flockfile) #define es_ftrylockfile _ESTREAM_PREFIX(es_ftrylockfile) #define es_funlockfile _ESTREAM_PREFIX(es_funlockfile) #define es_feof _ESTREAM_PREFIX(es_feof) #define es_feof_unlocked _ESTREAM_PREFIX(es_feof_unlocked) #define es_ferror _ESTREAM_PREFIX(es_ferror) #define es_ferror_unlocked _ESTREAM_PREFIX(es_ferror_unlocked) #define es_clearerr _ESTREAM_PREFIX(es_clearerr) #define es_clearerr_unlocked _ESTREAM_PREFIX(es_clearerr_unlocked) #define es_fflush _ESTREAM_PREFIX(es_fflush) #define es_fseek _ESTREAM_PREFIX(es_fseek) #define es_fseeko _ESTREAM_PREFIX(es_fseeko) #define es_ftell _ESTREAM_PREFIX(es_ftell) #define es_ftello _ESTREAM_PREFIX(es_ftello) #define es_rewind _ESTREAM_PREFIX(es_rewind) #define es_fgetc _ESTREAM_PREFIX(es_fgetc) #define es_fputc _ESTREAM_PREFIX(es_fputc) #define _es_getc_underflow _ESTREAM_PREFIX(_es_getc_underflow) #define _es_putc_overflow _ESTREAM_PREFIX(_es_putc_overflow) #define es_ungetc _ESTREAM_PREFIX(es_ungetc) #define es_read _ESTREAM_PREFIX(es_read) #define es_write _ESTREAM_PREFIX(es_write) #define es_write_sanitized _ESTREAM_PREFIX(es_write_sanitized) #define es_write_hexstring _ESTREAM_PREFIX(es_write_hexstring) #define es_fread _ESTREAM_PREFIX(es_fread) #define es_fwrite _ESTREAM_PREFIX(es_fwrite) #define es_fgets _ESTREAM_PREFIX(es_fgets) #define es_fputs _ESTREAM_PREFIX(es_fputs) #define es_fputs_unlocked _ESTREAM_PREFIX(es_fputs_unlocked) #define es_getline _ESTREAM_PREFIX(es_getline) #define es_read_line _ESTREAM_PREFIX(es_read_line) #define es_free _ESTREAM_PREFIX(es_free) #define es_fprintf _ESTREAM_PREFIX(es_fprintf) #define es_fprintf_unlocked _ESTREAM_PREFIX(es_fprintf_unlocked) #define es_vfprintf _ESTREAM_PREFIX(es_vfprint) #define es_vfprintf_unlocked _ESTREAM_PREFIX(es_vfprint_unlocked) #define es_setvbuf _ESTREAM_PREFIX(es_setvbuf) #define es_setbuf _ESTREAM_PREFIX(es_setbuf) #define es_tmpfile _ESTREAM_PREFIX(es_tmpfile) #define es_opaque_set _ESTREAM_PREFIX(es_opaque_set) #define es_opaque_get _ESTREAM_PREFIX(es_opaque_get) #define es_write_sanitized_utf8_buffer \ _ESTREAM_PREFIX(es_write_sanitized_utf8_buffer) #endif /*_ESTREAM_EXT_SYM_PREFIX*/ #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* Forward declaration for the (opaque) internal type. */ struct estream_internal; /* The definition of this struct is entirely private. You must not use it for anything. It is only here so some functions can be implemented as macros. */ struct es__stream { /* The layout of this struct must never change. It may be grown, but only if all functions which access the new members are versioned. */ /* A pointer to the stream buffer. */ unsigned char *buffer; /* The size of the buffer in bytes. */ size_t buffer_size; /* The length of the usable data in the buffer, only valid when in read mode (see flags). */ size_t data_len; /* The current position of the offset pointer, valid in read and write mode. */ size_t data_offset; size_t data_flushed; unsigned char *unread_buffer; size_t unread_buffer_size; /* The number of unread bytes. */ size_t unread_data_len; /* Various flags. */ struct { unsigned int writing: 1; unsigned int reserved: 7; } flags; /* A pointer to our internal data for this stream. */ struct estream_internal *intern; }; /* The opaque type for an estream. */ typedef struct es__stream *estream_t; typedef ssize_t (*es_cookie_read_function_t) (void *cookie, void *buffer, size_t size); typedef ssize_t (*es_cookie_write_function_t) (void *cookie, const void *buffer, size_t size); typedef int (*es_cookie_seek_function_t) (void *cookie, off_t *pos, int whence); typedef int (*es_cookie_close_function_t) (void *cookie); typedef struct es_cookie_io_functions { es_cookie_read_function_t func_read; es_cookie_write_function_t func_write; es_cookie_seek_function_t func_seek; es_cookie_close_function_t func_close; } es_cookie_io_functions_t; #ifndef _ESTREAM_GCC_A_PRINTF #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) # define _ESTREAM_GCC_A_PRINTF( f, a ) __attribute__ ((format (printf,f,a))) #else # define _ESTREAM_GCC_A_PRINTF( f, a ) #endif #endif /*_ESTREAM_GCC_A_PRINTF*/ #ifndef ES__RESTRICT # if defined __GNUC__ && defined __GNUC_MINOR__ # if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 92)) # define ES__RESTRICT __restrict__ # endif # endif #endif #ifndef ES__RESTRICT # define ES__RESTRICT #endif int es_init (void); estream_t es_fopen (const char *ES__RESTRICT path, const char *ES__RESTRICT mode); estream_t es_mopen (unsigned char *ES__RESTRICT data, size_t data_n, size_t data_len, unsigned int grow, void *(*func_realloc) (void *mem, size_t size), void (*func_free) (void *mem), const char *ES__RESTRICT mode); estream_t es_fopenmem (size_t memlimit, const char *ES__RESTRICT mode); estream_t es_fdopen (int filedes, const char *mode); estream_t es_fdopen_nc (int filedes, const char *mode); estream_t es_fpopen (FILE *fp, const char *mode); estream_t es_fpopen_nc (FILE *fp, const char *mode); estream_t es_freopen (const char *ES__RESTRICT path, const char *ES__RESTRICT mode, estream_t ES__RESTRICT stream); estream_t es_fopencookie (void *ES__RESTRICT cookie, const char *ES__RESTRICT mode, es_cookie_io_functions_t functions); int es_fclose (estream_t stream); int es_fileno (estream_t stream); int es_fileno_unlocked (estream_t stream); +estream_t _es_get_std_stream (int fd); + +#define es_stdin _es_get_std_stream (0) +#define es_stdout _es_get_std_stream (1) +#define es_stderr _es_get_std_stream (2) + + void es_flockfile (estream_t stream); int es_ftrylockfile (estream_t stream); void es_funlockfile (estream_t stream); int es_feof (estream_t stream); int es_feof_unlocked (estream_t stream); int es_ferror (estream_t stream); int es_ferror_unlocked (estream_t stream); void es_clearerr (estream_t stream); void es_clearerr_unlocked (estream_t stream); int es_fflush (estream_t stream); int es_fseek (estream_t stream, long int offset, int whence); int es_fseeko (estream_t stream, off_t offset, int whence); long int es_ftell (estream_t stream); off_t es_ftello (estream_t stream); void es_rewind (estream_t stream); int es_fgetc (estream_t stream); int es_fputc (int c, estream_t stream); int _es_getc_underflow (estream_t stream); int _es_putc_overflow (int c, estream_t stream); #define es_getc_unlocked(stream) \ (((!(stream)->flags.writing) \ && ((stream)->data_offset < (stream)->data_len) \ && (! (stream)->unread_data_len)) \ ? ((int) (stream)->buffer[((stream)->data_offset)++]) \ : _es_getc_underflow ((stream))) #define es_putc_unlocked(c, stream) \ (((stream)->flags.writing \ && ((stream)->data_offset < (stream)->buffer_size) \ && (c != '\n')) \ ? ((int) ((stream)->buffer[((stream)->data_offset)++] = (c))) \ : _es_putc_overflow ((c), (stream))) #define es_getc(stream) es_fgetc (stream) #define es_putc(c, stream) es_fputc (c, stream) int es_ungetc (int c, estream_t stream); int es_read (estream_t ES__RESTRICT stream, void *ES__RESTRICT buffer, size_t bytes_to_read, size_t *ES__RESTRICT bytes_read); int es_write (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t bytes_to_write, size_t *ES__RESTRICT bytes_written); int es_write_sanitized (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t length, const char *delimiters, size_t *ES__RESTRICT bytes_written); int es_write_hexstring (estream_t ES__RESTRICT stream, const void *ES__RESTRICT buffer, size_t length, int reserved, size_t *ES__RESTRICT bytes_written); size_t es_fread (void *ES__RESTRICT ptr, size_t size, size_t nitems, estream_t ES__RESTRICT stream); size_t es_fwrite (const void *ES__RESTRICT ptr, size_t size, size_t memb, estream_t ES__RESTRICT stream); char *es_fgets (char *ES__RESTRICT s, int n, estream_t ES__RESTRICT stream); int es_fputs (const char *ES__RESTRICT s, estream_t ES__RESTRICT stream); int es_fputs_unlocked (const char *ES__RESTRICT s, estream_t ES__RESTRICT stream); ssize_t es_getline (char *ES__RESTRICT *ES__RESTRICT lineptr, size_t *ES__RESTRICT n, estream_t stream); ssize_t es_read_line (estream_t stream, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); void es_free (void *a); int es_fprintf (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, ...) _ESTREAM_GCC_A_PRINTF(2,3); int es_fprintf_unlocked (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, ...) _ESTREAM_GCC_A_PRINTF(2,3); int es_vfprintf (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, va_list ap) _ESTREAM_GCC_A_PRINTF(2,0); int es_vfprintf_unlocked (estream_t ES__RESTRICT stream, const char *ES__RESTRICT format, va_list ap) _ESTREAM_GCC_A_PRINTF(2,0); int es_setvbuf (estream_t ES__RESTRICT stream, char *ES__RESTRICT buf, int mode, size_t size); void es_setbuf (estream_t ES__RESTRICT stream, char *ES__RESTRICT buf); estream_t es_tmpfile (void); void es_opaque_set (estream_t ES__RESTRICT stream, void *ES__RESTRICT opaque); void *es_opaque_get (estream_t stream); #ifdef GNUPG_MAJOR_VERSION int es_write_sanitized_utf8_buffer (estream_t stream, const void *buffer, size_t length, const char *delimiters, size_t *bytes_written); #endif /*GNUPG_MAJOR_VERSION*/ #ifdef __cplusplus } #endif #endif /*ESTREAM_H*/ diff --git a/common/logging.c b/common/logging.c index 3b767cb97..6bc35eee5 100644 --- a/common/logging.c +++ b/common/logging.c @@ -1,643 +1,628 @@ /* logging.c - Useful logging functions * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, * 2009, 2010 Free Software Foundation, Inc. * * This file is part of JNLIB. * * JNLIB is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * JNLIB is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #include #endif /*!HAVE_W32_SYSTEM*/ #include #include #include #define JNLIB_NEED_LOG_LOGV 1 #define JNLIB_NEED_AFLOCAL 1 #include "libjnlib-config.h" #include "logging.h" static estream_t logstream; static int log_socket = -1; static char prefix_buffer[80]; static int with_time; static int with_prefix; static int with_pid; static unsigned long (*get_tid_callback)(void); static int running_detached; static int force_prefixes; static int missing_lf; static int errorcount; int log_get_errorcount (int clear) { int n = errorcount; if( clear ) errorcount = 0; return n; } void log_inc_errorcount (void) { errorcount++; } /* The following 3 functions are used by es_fopencookie to write logs to a socket. */ struct fun_cookie_s { int fd; int quiet; int want_socket; int is_socket; char name[1]; }; /* Write NBYTES of BUFFER to file descriptor FD. */ static int writen (int fd, const void *buffer, size_t nbytes) { const char *buf = buffer; size_t nleft = nbytes; int nwritten; while (nleft > 0) { nwritten = write (fd, buf, nleft); if (nwritten < 0 && errno == EINTR) continue; if (nwritten < 0) return -1; nleft -= nwritten; buf = buf + nwritten; } return 0; } static ssize_t fun_writer (void *cookie_arg, const void *buffer, size_t size) { struct fun_cookie_s *cookie = cookie_arg; /* Note that we always try to reconnect to the socket but print error messages only the first time an error occured. If RUNNING_DETACHED is set we don't fall back to stderr and even do not print any error messages. This is needed because detached processes often close stderr and by writing to file descriptor 2 we might send the log message to a file not intended for logging (e.g. a pipe or network connection). */ if (cookie->want_socket && cookie->fd == -1) { /* Not yet open or meanwhile closed due to an error. */ cookie->is_socket = 0; cookie->fd = socket (PF_LOCAL, SOCK_STREAM, 0); if (cookie->fd == -1) { if (!cookie->quiet && !running_detached && isatty (fileno (stderr))) fprintf (stderr, "failed to create socket for logging: %s\n", strerror(errno)); } else { struct sockaddr_un addr; size_t addrlen; memset (&addr, 0, sizeof addr); addr.sun_family = PF_LOCAL; strncpy (addr.sun_path, cookie->name, sizeof (addr.sun_path)-1); addr.sun_path[sizeof (addr.sun_path)-1] = 0; addrlen = SUN_LEN (&addr); if (connect (cookie->fd, (struct sockaddr *) &addr, addrlen) == -1) { if (!cookie->quiet && !running_detached && isatty (fileno (stderr))) fprintf (stderr, "can't connect to `%s': %s\n", cookie->name, strerror(errno)); close (cookie->fd); cookie->fd = -1; } } if (cookie->fd == -1) { if (!running_detached) { /* Due to all the problems with apps not running detached but being called with stderr closed or used for a different purposes, it does not make sense to switch to stderr. We therefore disable it. */ if (!cookie->quiet) { /* fputs ("switching logging to stderr\n", stderr);*/ cookie->quiet = 1; } cookie->fd = -1; /*fileno (stderr);*/ } } else /* Connection has been established. */ { cookie->quiet = 0; cookie->is_socket = 1; } } log_socket = cookie->fd; if (cookie->fd != -1 && !writen (cookie->fd, buffer, size)) return (ssize_t)size; /* Okay. */ if (!running_detached && cookie->fd != -1 && isatty (fileno (stderr))) { if (*cookie->name) fprintf (stderr, "error writing to `%s': %s\n", cookie->name, strerror(errno)); else fprintf (stderr, "error writing to file descriptor %d: %s\n", cookie->fd, strerror(errno)); } if (cookie->is_socket && cookie->fd != -1) { close (cookie->fd); cookie->fd = -1; log_socket = -1; } return (ssize_t)size; } static int fun_closer (void *cookie_arg) { struct fun_cookie_s *cookie = cookie_arg; if (cookie->fd != -1 && cookie->fd != 2) close (cookie->fd); jnlib_free (cookie); log_socket = -1; return 0; } /* Common function to either set the logging to a file or a file descriptor. */ static void set_file_fd (const char *name, int fd) { estream_t fp; int want_socket; struct fun_cookie_s *cookie; /* Close an open log stream. */ if (logstream) { es_fclose (logstream); logstream = NULL; } /* Figure out what kind of logging we want. */ if (name && !strcmp (name, "-")) { name = NULL; fd = fileno (stderr); } if (name) { want_socket = (!strncmp (name, "socket://", 9) && name[9]); if (want_socket) name += 9; } else { want_socket = 0; } /* Setup a new stream. */ /* The xmalloc below is justified because we can expect that this function is called only during initialization and there is no easy way out of this error condition. */ cookie = jnlib_xmalloc (sizeof *cookie + (name? strlen (name):0)); strcpy (cookie->name, name? name:""); cookie->quiet = 0; cookie->is_socket = 0; cookie->want_socket = want_socket; if (!name) cookie->fd = fd; else if (want_socket) cookie->fd = -1; else { do cookie->fd = open (name, O_WRONLY|O_APPEND|O_CREAT, (S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH)); while (cookie->fd == -1 && errno == EINTR); } log_socket = cookie->fd; { es_cookie_io_functions_t io = { NULL }; io.func_write = fun_writer; io.func_close = fun_closer; fp = es_fopencookie (cookie, "w", io); } /* On error default to a stderr based estream. */ if (!fp) - { - fp = es_fpopen (stderr, "a"); - if (fp) - { - if (name) - es_fprintf (fp, "failed to open log file `%s': %s\n", - name, strerror (errno)); - else - es_fprintf (fp, "failed to fdopen file descriptor %d: %s\n", - fd, strerror (errno)); - } - else - { - fprintf (stderr, "failed to use stderr as log stream: %s\n", - strerror (errno)); - /* No way to log something. Create a dummy estream so that - there is something we can use. */ - fp = es_fpopen (NULL, "a"); - if (!fp) - { - fprintf (stderr, "fatal: failed to open dummy stream: %s\n", - strerror (errno)); - abort(); - } - } - } + fp = es_stderr; es_setvbuf (fp, NULL, _IOLBF, 0); logstream = fp; /* We always need to print the prefix and the pid for socket mode, so that the server reading the socket can do something meaningful. */ force_prefixes = want_socket; missing_lf = 0; } /* Set the file to write log to. The special names NULL and "-" may be used to select stderr and names formatted like "socket:///home/foo/mylogs" may be used to write the logging to the socket "/home/foo/mylogs". If the connection to the socket fails or a write error is detected, the function writes to stderr and tries the next time again to connect the socket. */ void log_set_file (const char *name) { set_file_fd (name? name: "-", -1); } void log_set_fd (int fd) { set_file_fd (NULL, fd); } void log_set_get_tid_callback (unsigned long (*cb)(void)) { get_tid_callback = cb; } void log_set_prefix (const char *text, unsigned int flags) { if (text) { strncpy (prefix_buffer, text, sizeof (prefix_buffer)-1); prefix_buffer[sizeof (prefix_buffer)-1] = 0; } with_prefix = (flags & JNLIB_LOG_WITH_PREFIX); with_time = (flags & JNLIB_LOG_WITH_TIME); with_pid = (flags & JNLIB_LOG_WITH_PID); running_detached = (flags & JNLIB_LOG_RUN_DETACHED); } const char * log_get_prefix (unsigned int *flags) { if (flags) { *flags = 0; if (with_prefix) *flags |= JNLIB_LOG_WITH_PREFIX; if (with_time) *flags |= JNLIB_LOG_WITH_TIME; if (with_pid) *flags |= JNLIB_LOG_WITH_PID; if (running_detached) *flags |= JNLIB_LOG_RUN_DETACHED; } return prefix_buffer; } /* This function returns true if the file descriptor FD is in use for logging. This is preferable over a test using log_get_fd in that it allows the logging code to use more then one file descriptor. */ int log_test_fd (int fd) { if (logstream) { int tmp = es_fileno (logstream); if ( tmp != -1 && tmp == fd) return 1; } if (log_socket != -1 && log_socket == fd) return 1; return 0; } int log_get_fd () { return logstream? es_fileno(logstream) : -1; } estream_t log_get_stream () { assert (logstream); return logstream; } static void do_logv (int level, int ignore_arg_ptr, const char *fmt, va_list arg_ptr) { if (!logstream) { log_set_file (NULL); /* Make sure a log stream has been set. */ assert (logstream); } es_flockfile (logstream); if (missing_lf && level != JNLIB_LOG_CONT) es_putc_unlocked ('\n', logstream ); missing_lf = 0; if (level != JNLIB_LOG_CONT) { /* Note this does not work for multiple line logging as we would * need to print to a buffer first */ if (with_time && !force_prefixes) { struct tm *tp; time_t atime = time (NULL); tp = localtime (&atime); es_fprintf_unlocked (logstream, "%04d-%02d-%02d %02d:%02d:%02d ", 1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec ); } if (with_prefix || force_prefixes) es_fputs_unlocked (prefix_buffer, logstream); if (with_pid || force_prefixes) { if (get_tid_callback) es_fprintf_unlocked (logstream, "[%u.%lx]", (unsigned int)getpid (), get_tid_callback ()); else es_fprintf_unlocked (logstream, "[%u]", (unsigned int)getpid ()); } if (!with_time || force_prefixes) es_putc_unlocked (':', logstream); /* A leading backspace suppresses the extra space so that we can correctly output, programname, filename and linenumber. */ if (fmt && *fmt == '\b') fmt++; else es_putc_unlocked (' ', logstream); } switch (level) { case JNLIB_LOG_BEGIN: break; case JNLIB_LOG_CONT: break; case JNLIB_LOG_INFO: break; case JNLIB_LOG_WARN: break; case JNLIB_LOG_ERROR: break; case JNLIB_LOG_FATAL: es_fputs_unlocked ("Fatal: ",logstream ); break; case JNLIB_LOG_BUG: es_fputs_unlocked ("Ohhhh jeeee: ", logstream); break; case JNLIB_LOG_DEBUG: es_fputs_unlocked ("DBG: ", logstream ); break; default: es_fprintf_unlocked (logstream,"[Unknown log level %d]: ", level); break; } if (fmt) { if (ignore_arg_ptr) es_fputs_unlocked (fmt, logstream); else es_vfprintf_unlocked (logstream, fmt, arg_ptr); if (*fmt && fmt[strlen(fmt)-1] != '\n') missing_lf = 1; } if (level == JNLIB_LOG_FATAL) { if (missing_lf) es_putc_unlocked ('\n', logstream); es_funlockfile (logstream); exit (2); } else if (level == JNLIB_LOG_BUG) { if (missing_lf) es_putc_unlocked ('\n', logstream ); es_funlockfile (logstream); abort (); } else es_funlockfile (logstream); } static void do_log (int level, const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt) ; do_logv (level, 0, fmt, arg_ptr); va_end (arg_ptr); } void log_logv (int level, const char *fmt, va_list arg_ptr) { do_logv (level, 0, fmt, arg_ptr); } void log_string (int level, const char *string) { /* We need to provide a dummy arg_ptr. volatile is needed to suppress compiler warnings. */ volatile va_list dummy_arg_ptr; do_logv (level, 1, string, dummy_arg_ptr); } void log_info (const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt); do_logv (JNLIB_LOG_INFO, 0, fmt, arg_ptr); va_end (arg_ptr); } void log_error (const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt); do_logv (JNLIB_LOG_ERROR, 0, fmt, arg_ptr); va_end (arg_ptr); /* Protect against counter overflow. */ if (errorcount < 30000) errorcount++; } void log_fatal (const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt); do_logv (JNLIB_LOG_FATAL, 0, fmt, arg_ptr); va_end (arg_ptr); abort (); /* Never called; just to make the compiler happy. */ } void log_bug (const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt); do_logv (JNLIB_LOG_BUG, 0, fmt, arg_ptr); va_end (arg_ptr); abort (); /* Never called; just to make the compiler happy. */ } void log_debug (const char *fmt, ...) { va_list arg_ptr ; va_start (arg_ptr, fmt); do_logv (JNLIB_LOG_DEBUG, 0, fmt, arg_ptr); va_end (arg_ptr); } void log_printf (const char *fmt, ...) { va_list arg_ptr; va_start (arg_ptr, fmt); do_logv (fmt ? JNLIB_LOG_CONT : JNLIB_LOG_BEGIN, 0, fmt, arg_ptr); va_end (arg_ptr); } +/* Flush the log - this is useful to make sure that the trailing + linefeed has been printed. */ +void +log_flush (void) +{ + volatile va_list dummy_arg_ptr; + do_logv (JNLIB_LOG_CONT, 1, NULL, dummy_arg_ptr); +} + + /* Print a hexdump of BUFFER. With TEXT of NULL print just the raw dump, with TEXT just an empty string, print a trailing linefeed, otherwise print an entire debug line. */ void log_printhex (const char *text, const void *buffer, size_t length) { if (text && *text) log_debug ("%s ", text); if (length) { const unsigned char *p = buffer; log_printf ("%02X", *p); for (length--, p++; length--; p++) log_printf (" %02X", *p); } if (text) log_printf ("\n"); } #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) void bug_at( const char *file, int line, const char *func ) { do_log (JNLIB_LOG_BUG, ("... this is a bug (%s:%d:%s)\n"), file, line, func); abort (); /* Never called; just to make the compiler happy. */ } #else void bug_at( const char *file, int line ) { do_log (JNLIB_LOG_BUG, _("you found a bug ... (%s:%d)\n"), file, line); abort (); /* Never called; just to make the compiler happy. */ } #endif diff --git a/common/logging.h b/common/logging.h index f089cf0b5..2c29a0b1b 100644 --- a/common/logging.h +++ b/common/logging.h @@ -1,91 +1,92 @@ /* logging.h * Copyright (C) 1999, 2000, 2001, 2004, 2006, * 2010 Free Software Foundation, Inc. * * This file is part of JNLIB. * * JNLIB is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * JNLIB is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . */ #ifndef LIBJNLIB_LOGGING_H #define LIBJNLIB_LOGGING_H #include #include "estream.h" #include "mischelp.h" /* Flag values for log_set_prefix. */ #define JNLIB_LOG_WITH_PREFIX 1 #define JNLIB_LOG_WITH_TIME 2 #define JNLIB_LOG_WITH_PID 4 #define JNLIB_LOG_RUN_DETACHED 256 int log_get_errorcount (int clear); void log_inc_errorcount (void); void log_set_file( const char *name ); void log_set_fd (int fd); void log_set_get_tid_callback (unsigned long (*cb)(void)); void log_set_prefix (const char *text, unsigned int flags); const char *log_get_prefix (unsigned int *flags); int log_test_fd (int fd); int log_get_fd(void); estream_t log_get_stream (void); #ifdef JNLIB_GCC_M_FUNCTION void bug_at( const char *file, int line, const char *func ) JNLIB_GCC_A_NR; # define BUG() bug_at( __FILE__ , __LINE__, __FUNCTION__ ) #else void bug_at( const char *file, int line ); # define BUG() bug_at( __FILE__ , __LINE__ ) #endif /* To avoid mandatory inclusion of stdarg and other stuff, do it only if explicitly requested to do so. */ #ifdef JNLIB_NEED_LOG_LOGV #include enum jnlib_log_levels { JNLIB_LOG_BEGIN, JNLIB_LOG_CONT, JNLIB_LOG_INFO, JNLIB_LOG_WARN, JNLIB_LOG_ERROR, JNLIB_LOG_FATAL, JNLIB_LOG_BUG, JNLIB_LOG_DEBUG }; void log_logv (int level, const char *fmt, va_list arg_ptr); void log_string (int level, const char *string); #endif /*JNLIB_NEED_LOG_LOGV*/ void log_bug( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); void log_fatal( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); void log_error( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void log_info( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void log_debug( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); void log_printf( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); +void log_flush (void); /* Print a hexdump of BUFFER. With TEXT passes as NULL print just the raw dump, with TEXT being an empty string, print a trailing linefeed, otherwise print an entire debug line with TEXT followed by the hexdump and a final LF. */ void log_printhex (const char *text, const void *buffer, size_t length); #endif /*LIBJNLIB_LOGGING_H*/ diff --git a/common/miscellaneous.c b/common/miscellaneous.c index 396f7224f..01d8c97be 100644 --- a/common/miscellaneous.c +++ b/common/miscellaneous.c @@ -1,239 +1,238 @@ /* miscellaneous.c - Stuff not fitting elsewhere * Copyright (C) 2003, 2006 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #define JNLIB_NEED_LOG_LOGV #include "util.h" #include "iobuf.h" #include "i18n.h" /* Used by libgcrypt for logging. */ static void my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr) { (void)dummy; /* Map the log levels. */ switch (level) { case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break; case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break; case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break; case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break; case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break; case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break; case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break; default: level = JNLIB_LOG_ERROR; break; } log_logv (level, fmt, arg_ptr); } /* This function is called by libgcrypt on a fatal error. */ static void my_gcry_fatalerror_handler (void *opaque, int rc, const char *text) { (void)opaque; log_fatal ("libgcrypt problem: %s\n", text ? text : gpg_strerror (rc)); abort (); } /* This function is called by libgcrypt if it ran out of core and there is no way to return that error to the caller. We do our own function here to make use of our logging functions. */ static int my_gcry_outofcore_handler (void *opaque, size_t req_n, unsigned int flags) { static int been_here; /* Used to protect against recursive calls. */ (void)opaque; if (!been_here) { been_here = 1; if ( (flags & 1) ) log_fatal (_("out of core in secure memory " "while allocating %lu bytes"), (unsigned long)req_n); else log_fatal (_("out of core while allocating %lu bytes"), (unsigned long)req_n); } return 0; /* Let libgcrypt call its own fatal error handler. Actually this will turn out to be my_gcry_fatalerror_handler. */ } /* Setup libgcrypt to use our own logging functions. Should be used early at startup. */ void setup_libgcrypt_logging (void) { gcry_set_log_handler (my_gcry_logger, NULL); gcry_set_fatalerror_handler (my_gcry_fatalerror_handler, NULL); gcry_set_outofcore_handler (my_gcry_outofcore_handler, NULL); } /* Decide whether the filename is stdout or a real filename and return * an appropriate string. */ const char * print_fname_stdout (const char *s) { if( !s || (*s == '-' && !s[1]) ) return "[stdout]"; return s; } /* Decide whether the filename is stdin or a real filename and return * an appropriate string. */ const char * print_fname_stdin (const char *s) { if( !s || (*s == '-' && !s[1]) ) return "[stdin]"; return s; } -/* fixme: Globally replace it by print_sanitized_buffer. */ -void -print_string( FILE *fp, const byte *p, size_t n, int delim ) -{ - print_sanitized_buffer (fp, p, n, delim); -} void -print_utf8_string2 ( FILE *fp, const byte *p, size_t n, int delim ) +print_utf8_buffer2 (estream_t stream, const void *p, size_t n, int delim) { - print_sanitized_utf8_buffer (fp, p, n, delim); + char tmp[2]; + + tmp[0] = delim; + tmp[1] = 0; + es_write_sanitized_utf8_buffer (stream, p, n, tmp, NULL); } + void -print_utf8_string( FILE *fp, const byte *p, size_t n ) +print_utf8_buffer (estream_t stream, const void *p, size_t n) { - print_utf8_string2 (fp, p, n, 0); + es_write_sanitized_utf8_buffer (stream, p, n, NULL, NULL); } /* Write LENGTH bytes of BUFFER to FP as a hex encoded string. RESERVED must be 0. */ void print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved) { #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) const unsigned char *s; (void)reserved; for (s = buffer; length; s++, length--) { putc ( tohex ((*s>>4)&15), fp); putc ( tohex (*s&15), fp); } #undef tohex } char * make_printable_string (const void *p, size_t n, int delim ) { return sanitize_buffer (p, n, delim); } /* * Check if the file is compressed. */ int is_file_compressed (const char *s, int *ret_rc) { iobuf_t a; byte buf[4]; int i, rc = 0; int overflow; struct magic_compress_s { size_t len; byte magic[4]; } magic[] = { { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */ { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */ { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */ }; if ( iobuf_is_pipe_filename (s) || !ret_rc ) return 0; /* We can't check stdin or no file was given */ a = iobuf_open( s ); if ( a == NULL ) { *ret_rc = gpg_error_from_syserror (); return 0; } if ( iobuf_get_filelength( a, &overflow ) < 4 && !overflow) { *ret_rc = 0; goto leave; } if ( iobuf_read( a, buf, 4 ) == -1 ) { *ret_rc = a->error; goto leave; } for ( i = 0; i < DIM( magic ); i++ ) { if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) { *ret_rc = 0; rc = 1; break; } } leave: iobuf_close( a ); return rc; } /* Try match against each substring of multistr, delimited by | */ int match_multistr (const char *multistr,const char *match) { do { size_t seglen = strcspn (multistr,"|"); if (!seglen) break; /* Using the localized strncasecmp! */ if (strncasecmp(multistr,match,seglen)==0) return 1; multistr += seglen; if (*multistr == '|') multistr++; } while (*multistr); return 0; } diff --git a/common/status.h b/common/status.h index bb5429dc0..0533c4a92 100644 --- a/common/status.h +++ b/common/status.h @@ -1,137 +1,138 @@ /* status.h - Status codes * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_STATUS_H #define GNUPG_COMMON_STATUS_H enum { STATUS_ENTER, STATUS_LEAVE, STATUS_ABORT, STATUS_GOODSIG, STATUS_BADSIG, STATUS_ERRSIG, STATUS_BADARMOR, STATUS_RSA_OR_IDEA, STATUS_TRUST_UNDEFINED, STATUS_TRUST_NEVER, STATUS_TRUST_MARGINAL, STATUS_TRUST_FULLY, STATUS_TRUST_ULTIMATE, STATUS_NEED_PASSPHRASE, STATUS_VALIDSIG, STATUS_SIG_ID, STATUS_ENC_TO, STATUS_NODATA, STATUS_BAD_PASSPHRASE, STATUS_NO_PUBKEY, STATUS_NO_SECKEY, STATUS_NEED_PASSPHRASE_SYM, STATUS_DECRYPTION_FAILED, STATUS_DECRYPTION_OKAY, STATUS_MISSING_PASSPHRASE, STATUS_GOOD_PASSPHRASE, STATUS_GOODMDC, STATUS_BADMDC, STATUS_ERRMDC, STATUS_IMPORTED, STATUS_IMPORT_OK, STATUS_IMPORT_PROBLEM, STATUS_IMPORT_RES, STATUS_IMPORT_CHECK, STATUS_FILE_START, STATUS_FILE_DONE, STATUS_FILE_ERROR, STATUS_BEGIN_DECRYPTION, STATUS_END_DECRYPTION, STATUS_BEGIN_ENCRYPTION, STATUS_END_ENCRYPTION, STATUS_BEGIN_SIGNING, STATUS_DELETE_PROBLEM, STATUS_GET_BOOL, STATUS_GET_LINE, STATUS_GET_HIDDEN, STATUS_GOT_IT, STATUS_PROGRESS, STATUS_SIG_CREATED, STATUS_SESSION_KEY, STATUS_NOTATION_NAME, STATUS_NOTATION_DATA, STATUS_POLICY_URL, STATUS_BEGIN_STREAM, STATUS_END_STREAM, STATUS_KEY_CREATED, STATUS_USERID_HINT, STATUS_UNEXPECTED, STATUS_INV_RECP, STATUS_INV_SGNR, STATUS_NO_RECP, STATUS_NO_SGNR, STATUS_ALREADY_SIGNED, STATUS_KEYEXPIRED, STATUS_KEYREVOKED, STATUS_SIGEXPIRED, STATUS_EXPSIG, STATUS_EXPKEYSIG, STATUS_ATTRIBUTE, STATUS_REVKEYSIG, STATUS_NEWSIG, STATUS_SIG_SUBPACKET, STATUS_PLAINTEXT, STATUS_PLAINTEXT_LENGTH, STATUS_KEY_NOT_CREATED, STATUS_NEED_PASSPHRASE_PIN, STATUS_CARDCTRL, STATUS_SC_OP_FAILURE, STATUS_SC_OP_SUCCESS, STATUS_BACKUP_KEY_CREATED, STATUS_PKA_TRUST_BAD, STATUS_PKA_TRUST_GOOD, STATUS_TRUNCATED, STATUS_MOUNTPOINT, - STATUS_ERROR + STATUS_ERROR, + STATUS_SUCCESS }; const char *get_status_string (int code); const char *get_inv_recpsgnr_code (gpg_error_t err); #endif /*GNUPG_COMMON_STATUS_H*/ diff --git a/common/ttyio.c b/common/ttyio.c index ec26b06e8..4f30b4b44 100644 --- a/common/ttyio.c +++ b/common/ttyio.c @@ -1,689 +1,689 @@ /* ttyio.c - tty i/O functions * Copyright (C) 1998,1999,2000,2001,2002,2003,2004,2006,2007, - * 2009 Free Software Foundation, Inc. + * 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #ifdef HAVE_TCGETATTR #include #else #ifdef HAVE_TERMIO_H /* simulate termios with termio */ #include #define termios termio #define tcsetattr ioctl #define TCSAFLUSH TCSETAF #define tcgetattr(A,B) ioctl(A,TCGETA,B) #define HAVE_TCGETATTR #endif #endif #ifdef _WIN32 /* use the odd Win32 functions */ #include #ifdef HAVE_TCGETATTR #error mingw32 and termios #endif #endif #include #include #include "util.h" #include "ttyio.h" #include "common-defs.h" #define CONTROL_D ('D' - 'A' + 1) #ifdef _WIN32 /* use the odd Win32 functions */ static struct { HANDLE in, out; } con; #define DEF_INPMODE (ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT \ |ENABLE_PROCESSED_INPUT ) #define HID_INPMODE (ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT ) #define DEF_OUTMODE (ENABLE_WRAP_AT_EOL_OUTPUT|ENABLE_PROCESSED_OUTPUT) #else /* yeah, we have a real OS */ static FILE *ttyfp = NULL; #endif static int initialized; static int last_prompt_len; static int batchmode; static int no_terminal; #ifdef HAVE_TCGETATTR static struct termios termsave; static int restore_termios; #endif /* Hooks set by gpgrlhelp.c if required. */ static void (*my_rl_set_completer) (rl_completion_func_t *); static void (*my_rl_inhibit_completion) (int); static void (*my_rl_cleanup_after_signal) (void); static void (*my_rl_init_stream) (FILE *); static char *(*my_rl_readline) (const char*); static void (*my_rl_add_history) (const char*); /* This is a wrapper around ttyname so that we can use it even when the standard streams are redirected. It figures the name out the first time and returns it in a statically allocated buffer. */ const char * tty_get_ttyname (void) { static char *name; /* On a GNU system ctermid() always return /dev/tty, so this does not make much sense - however if it is ever changed we do the Right Thing now. */ #ifdef HAVE_CTERMID static int got_name; if (!got_name) { const char *s; /* Note that despite our checks for these macros the function is not necessarily thread save. We mainly do this for portability reasons, in case L_ctermid is not defined. */ # if defined(_POSIX_THREAD_SAFE_FUNCTIONS) || defined(_POSIX_TRHEADS) char buffer[L_ctermid]; s = ctermid (buffer); # else s = ctermid (NULL); # endif if (s) name = strdup (s); got_name = 1; } #endif /*HAVE_CTERMID*/ /* Assume the standard tty on memory error or when tehre is no certmid. */ return name? name : "/dev/tty"; } #ifdef HAVE_TCGETATTR static void cleanup(void) { if( restore_termios ) { restore_termios = 0; /* do it prios in case it is interrupted again */ if( tcsetattr(fileno(ttyfp), TCSAFLUSH, &termsave) ) log_error("tcsetattr() failed: %s\n", strerror(errno) ); } } #endif static void init_ttyfp(void) { if( initialized ) return; #if defined(_WIN32) { SECURITY_ATTRIBUTES sa; memset(&sa, 0, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; con.out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0 ); if( con.out == INVALID_HANDLE_VALUE ) log_fatal("open(CONOUT$) failed: rc=%d", (int)GetLastError() ); memset(&sa, 0, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; con.in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0 ); if( con.in == INVALID_HANDLE_VALUE ) log_fatal("open(CONIN$) failed: rc=%d", (int)GetLastError() ); } SetConsoleMode(con.in, DEF_INPMODE ); SetConsoleMode(con.out, DEF_OUTMODE ); #elif defined(__EMX__) ttyfp = stdout; /* Fixme: replace by the real functions: see wklib */ if (my_rl_init_stream) my_rl_init_stream (ttyfp); #else ttyfp = batchmode? stderr : fopen (tty_get_ttyname (), "r+"); if( !ttyfp ) { log_error("cannot open `%s': %s\n", tty_get_ttyname (), strerror(errno) ); exit(2); } if (my_rl_init_stream) my_rl_init_stream (ttyfp); #endif #ifdef HAVE_TCGETATTR atexit( cleanup ); #endif initialized = 1; } int tty_batchmode( int onoff ) { int old = batchmode; if( onoff != -1 ) batchmode = onoff; return old; } int tty_no_terminal(int onoff) { int old = no_terminal; no_terminal = onoff ? 1 : 0; return old; } void tty_printf( const char *fmt, ... ) { va_list arg_ptr; if (no_terminal) return; if( !initialized ) init_ttyfp(); va_start( arg_ptr, fmt ) ; #ifdef _WIN32 { char *buf = NULL; int n; DWORD nwritten; n = vasprintf(&buf, fmt, arg_ptr); if( !buf ) log_bug("vasprintf() failed\n"); if( !WriteConsoleA( con.out, buf, n, &nwritten, NULL ) ) log_fatal("WriteConsole failed: rc=%d", (int)GetLastError() ); if( n != nwritten ) log_fatal("WriteConsole failed: %d != %d\n", n, (int)nwritten ); last_prompt_len += n; xfree (buf); } #else last_prompt_len += vfprintf(ttyfp,fmt,arg_ptr) ; fflush(ttyfp); #endif va_end(arg_ptr); } /* Same as tty_printf but if FP is not NULL, behave like a regular fprintf. */ void -tty_fprintf (FILE *fp, const char *fmt, ... ) +tty_fprintf (estream_t fp, const char *fmt, ... ) { va_list arg_ptr; if (fp) { va_start (arg_ptr, fmt) ; - vfprintf (fp, fmt, arg_ptr ); + es_vfprintf (fp, fmt, arg_ptr ); va_end (arg_ptr); return; } if (no_terminal) return; - if( !initialized ) - init_ttyfp(); + if (!initialized) + init_ttyfp (); - va_start( arg_ptr, fmt ) ; + va_start (arg_ptr, fmt); #ifdef _WIN32 - { - char *buf = NULL; - int n; - DWORD nwritten; - - n = vasprintf(&buf, fmt, arg_ptr); - if( !buf ) - log_bug("vasprintf() failed\n"); - - if( !WriteConsoleA( con.out, buf, n, &nwritten, NULL ) ) - log_fatal("WriteConsole failed: rc=%d", (int)GetLastError() ); - if( n != nwritten ) - log_fatal("WriteConsole failed: %d != %d\n", n, (int)nwritten ); - last_prompt_len += n; - xfree (buf); - } + { + char *buf = NULL; + int n; + DWORD nwritten; + + n = vasprintf(&buf, fmt, arg_ptr); + if (!buf) + log_bug("vasprintf() failed\n"); + + if (!WriteConsoleA( con.out, buf, n, &nwritten, NULL )) + log_fatal("WriteConsole failed: rc=%d", (int)GetLastError() ); + if (n != nwritten) + log_fatal("WriteConsole failed: %d != %d\n", n, (int)nwritten ); + last_prompt_len += n; + xfree (buf); + } #else - last_prompt_len += vfprintf(ttyfp,fmt,arg_ptr) ; - fflush(ttyfp); + last_prompt_len += vfprintf(ttyfp,fmt,arg_ptr) ; + fflush(ttyfp); #endif - va_end(arg_ptr); + va_end(arg_ptr); } /**************** * Print a string, but filter all control characters out. */ void tty_print_string ( const byte *p, size_t n ) { if (no_terminal) return; if( !initialized ) init_ttyfp(); #ifdef _WIN32 /* not so effective, change it if you want */ for( ; n; n--, p++ ) if( iscntrl( *p ) ) { if( *p == '\n' ) tty_printf("\\n"); else if( !*p ) tty_printf("\\0"); else tty_printf("\\x%02x", *p); } else tty_printf("%c", *p); #else for( ; n; n--, p++ ) if( iscntrl( *p ) ) { putc('\\', ttyfp); if( *p == '\n' ) putc('n', ttyfp); else if( !*p ) putc('0', ttyfp); else fprintf(ttyfp, "x%02x", *p ); } else putc(*p, ttyfp); #endif } void tty_print_utf8_string2( const byte *p, size_t n, size_t max_n ) { size_t i; char *buf; if (no_terminal) return; /* we can handle plain ascii simpler, so check for it first */ for(i=0; i < n; i++ ) { if( p[i] & 0x80 ) break; } if( i < n ) { buf = utf8_to_native( (const char *)p, n, 0 ); if( max_n && (strlen( buf ) > max_n )) { buf[max_n] = 0; } /*(utf8 conversion already does the control character quoting)*/ tty_printf("%s", buf ); xfree( buf ); } else { if( max_n && (n > max_n) ) { n = max_n; } tty_print_string( p, n ); } } void tty_print_utf8_string( const byte *p, size_t n ) { tty_print_utf8_string2( p, n, 0 ); } static char * do_get( const char *prompt, int hidden ) { char *buf; #ifndef __riscos__ byte cbuf[1]; #endif int c, n, i; if( batchmode ) { log_error("Sorry, we are in batchmode - can't get input\n"); exit(2); } if (no_terminal) { log_error("Sorry, no terminal at all requested - can't get input\n"); exit(2); } if( !initialized ) init_ttyfp(); last_prompt_len = 0; tty_printf( "%s", prompt ); buf = xmalloc((n=50)); i = 0; #ifdef _WIN32 /* windoze version */ if( hidden ) SetConsoleMode(con.in, HID_INPMODE ); for(;;) { DWORD nread; if( !ReadConsoleA( con.in, cbuf, 1, &nread, NULL ) ) log_fatal("ReadConsole failed: rc=%d", (int)GetLastError() ); if( !nread ) continue; if( *cbuf == '\n' ) break; if( !hidden ) last_prompt_len++; c = *cbuf; if( c == '\t' ) c = ' '; else if( c > 0xa0 ) ; /* we don't allow 0xa0, as this is a protected blank which may * confuse the user */ else if( iscntrl(c) ) continue; if( !(i < n-1) ) { n += 50; buf = xrealloc (buf, n); } buf[i++] = c; } if( hidden ) SetConsoleMode(con.in, DEF_INPMODE ); #elif defined(__riscos__) do { c = riscos_getchar(); if (c == 0xa || c == 0xd) { /* Return || Enter */ c = (int) '\n'; } else if (c == 0x8 || c == 0x7f) { /* Backspace || Delete */ if (i>0) { i--; if (!hidden) { last_prompt_len--; fputc(8, ttyfp); fputc(32, ttyfp); fputc(8, ttyfp); fflush(ttyfp); } } else { fputc(7, ttyfp); fflush(ttyfp); } continue; } else if (c == (int) '\t') { /* Tab */ c = ' '; } else if (c > 0xa0) { ; /* we don't allow 0xa0, as this is a protected blank which may * confuse the user */ } else if (iscntrl(c)) { continue; } if(!(i < n-1)) { n += 50; buf = xrealloc (buf, n); } buf[i++] = c; if (!hidden) { last_prompt_len++; fputc(c, ttyfp); fflush(ttyfp); } } while (c != '\n'); i = (i>0) ? i-1 : 0; #else /* unix version */ if( hidden ) { #ifdef HAVE_TCGETATTR struct termios term; if( tcgetattr(fileno(ttyfp), &termsave) ) log_fatal("tcgetattr() failed: %s\n", strerror(errno) ); restore_termios = 1; term = termsave; term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); if( tcsetattr( fileno(ttyfp), TCSAFLUSH, &term ) ) log_fatal("tcsetattr() failed: %s\n", strerror(errno) ); #endif } /* fixme: How can we avoid that the \n is echoed w/o disabling * canonical mode - w/o this kill_prompt can't work */ while( read(fileno(ttyfp), cbuf, 1) == 1 && *cbuf != '\n' ) { if( !hidden ) last_prompt_len++; c = *cbuf; if( c == CONTROL_D ) log_info("control d found\n"); if( c == '\t' ) c = ' '; else if( c > 0xa0 ) ; /* we don't allow 0xa0, as this is a protected blank which may * confuse the user */ else if( iscntrl(c) ) continue; if( !(i < n-1) ) { n += 50; buf = xrealloc (buf, n ); } buf[i++] = c; } if( *cbuf != '\n' ) { buf[0] = CONTROL_D; i = 1; } if( hidden ) { #ifdef HAVE_TCGETATTR if( tcsetattr(fileno(ttyfp), TCSAFLUSH, &termsave) ) log_error("tcsetattr() failed: %s\n", strerror(errno) ); restore_termios = 0; #endif } #endif /* end unix version */ buf[i] = 0; return buf; } char * tty_get( const char *prompt ) { if (!batchmode && !no_terminal && my_rl_readline && my_rl_add_history) { char *line; char *buf; if (!initialized) init_ttyfp(); last_prompt_len = 0; line = my_rl_readline (prompt?prompt:""); /* We need to copy it to memory controlled by our malloc implementations; further we need to convert an EOF to our convention. */ buf = xmalloc(line? strlen(line)+1:2); if (line) { strcpy (buf, line); trim_spaces (buf); if (strlen (buf) > 2 ) my_rl_add_history (line); /* Note that we test BUF but add LINE. */ free (line); } else { buf[0] = CONTROL_D; buf[1] = 0; } return buf; } else return do_get ( prompt, 0 ); } /* Variable argument version of tty_get. The prompt is is actually a format string with arguments. */ char * tty_getf (const char *promptfmt, ... ) { va_list arg_ptr; char *prompt; char *answer; va_start (arg_ptr, promptfmt); if (estream_vasprintf (&prompt, promptfmt, arg_ptr) < 0) log_fatal ("estream_vasprintf failed: %s\n", strerror (errno)); va_end (arg_ptr); answer = tty_get (prompt); xfree (prompt); return answer; } char * tty_get_hidden( const char *prompt ) { return do_get( prompt, 1 ); } void tty_kill_prompt() { if ( no_terminal ) return; if( !initialized ) init_ttyfp(); if( batchmode ) last_prompt_len = 0; if( !last_prompt_len ) return; #ifdef _WIN32 tty_printf("\r%*s\r", last_prompt_len, ""); #else { int i; putc('\r', ttyfp); for(i=0; i < last_prompt_len; i ++ ) putc(' ', ttyfp); putc('\r', ttyfp); fflush(ttyfp); } #endif last_prompt_len = 0; } int tty_get_answer_is_yes( const char *prompt ) { int yes; char *p = tty_get( prompt ); tty_kill_prompt(); yes = answer_is_yes(p); xfree(p); return yes; } /* Called by gnupg_rl_initialize to setup the readline support. */ void tty_private_set_rl_hooks (void (*init_stream) (FILE *), void (*set_completer) (rl_completion_func_t*), void (*inhibit_completion) (int), void (*cleanup_after_signal) (void), char *(*readline_fun) (const char*), void (*add_history_fun) (const char*)) { my_rl_init_stream = init_stream; my_rl_set_completer = set_completer; my_rl_inhibit_completion = inhibit_completion; my_rl_cleanup_after_signal = cleanup_after_signal; my_rl_readline = readline_fun; my_rl_add_history = add_history_fun; } #ifdef HAVE_LIBREADLINE void tty_enable_completion (rl_completion_func_t *completer) { if (no_terminal || !my_rl_set_completer ) return; if (!initialized) init_ttyfp(); my_rl_set_completer (completer); } void tty_disable_completion (void) { if (no_terminal || !my_rl_inhibit_completion) return; if (!initialized) init_ttyfp(); my_rl_inhibit_completion (1); } #endif void tty_cleanup_after_signal (void) { #ifdef HAVE_TCGETATTR cleanup (); #endif } void tty_cleanup_rl_after_signal (void) { if (my_rl_cleanup_after_signal) my_rl_cleanup_after_signal (); } diff --git a/common/ttyio.h b/common/ttyio.h index eb2116a02..e1dc0f053 100644 --- a/common/ttyio.h +++ b/common/ttyio.h @@ -1,63 +1,63 @@ /* ttyio.h * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2006, * 2009 Free Software Foundation, Inc. * * This file is part of GNUPG. * * GNUPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GNUPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_TTYIO_H #define GNUPG_COMMON_TTYIO_H #include "util.h" /* Make sure our readline typedef is available. */ const char *tty_get_ttyname (void); int tty_batchmode (int onoff); #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) void tty_printf (const char *fmt, ... ) __attribute__ ((format (printf,1,2))); -void tty_fprintf (FILE *fp, const char *fmt, ... ) +void tty_fprintf (estream_t fp, const char *fmt, ... ) __attribute__ ((format (printf,2,3))); char *tty_getf (const char *promptfmt, ... ) __attribute__ ((format (printf,1,2))); #else void tty_printf (const char *fmt, ... ); -void tty_fprintf (FILE *fp, const char *fmt, ... ); +void tty_fprintf (estream_t fp, const char *fmt, ... ); char *tty_getf (const char *promptfmt, ... ); #endif void tty_print_string (const unsigned char *p, size_t n); void tty_print_utf8_string (const unsigned char *p, size_t n); void tty_print_utf8_string2 (const unsigned char *p, size_t n, size_t max_n); char *tty_get (const char *prompt); char *tty_get_hidden (const char *prompt); void tty_kill_prompt (void); int tty_get_answer_is_yes (const char *prompt); int tty_no_terminal (int onoff); #ifdef HAVE_LIBREADLINE void tty_enable_completion (rl_completion_func_t *completer); void tty_disable_completion (void); #else /* Use a macro to stub out these functions since a macro has no need to typedef a "rl_completion_func_t" which would be undefined without readline. */ #define tty_enable_completion(x) #define tty_disable_completion() #endif void tty_cleanup_after_signal (void); void tty_cleanup_rl_after_signal (void); #endif /*GNUPG_COMMON_TTYIO_H*/ diff --git a/common/util.h b/common/util.h index 32d4085e7..6deee38e1 100644 --- a/common/util.h +++ b/common/util.h @@ -1,338 +1,337 @@ /* util.h - Utility functions for GnuPG * Copyright (C) 2001, 2002, 2003, 2004, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_UTIL_H #define GNUPG_COMMON_UTIL_H #include /* We need this for the memory function protos. */ #include /* We need time_t. */ #include /* We need errno. */ #include /* We need gpg_error_t. */ /* Add error codes available only in newer versions of libgpg-error. */ #ifndef GPG_ERR_NOT_ENABLED #define GPG_ERR_NOT_ENABLED 179 #endif /* Hash function used with libksba. */ #define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write) /* Estream replaces most uses of stdio. */ #include "../common/estream.h" #include "../common/estream-printf.h" /* Get all the stuff from jnlib. */ #include "../common/logging.h" #include "../common/argparse.h" #include "../common/stringhelp.h" #include "../common/mischelp.h" #include "../common/strlist.h" #include "../common/dotlock.h" #include "../common/utf8conv.h" #include "../common/dynload.h" #include "init.h" /* Redefine asprintf by our estream version which uses our own memory allocator.. */ #define asprintf estream_asprintf #define vasprintf estream_vasprintf /* Due to a bug in mingw32's snprintf related to the 'l' modifier and for increased portability we use our snprintf on all systems. */ #define snprintf estream_snprintf /* GCC attributes. */ #if __GNUC__ >= 4 # define GNUPG_GCC_A_SENTINEL(a) __attribute__ ((sentinel(a))) #else # define GNUPG_GCC_A_SENTINEL(a) #endif /* We need this type even if we are not using libreadline and or we did not include libreadline in the current file. */ #ifndef GNUPG_LIBREADLINE_H_INCLUDED typedef char **rl_completion_func_t (const char *, int, int); #endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/ /* Handy malloc macros - please use only them. */ #define xtrymalloc(a) gcry_malloc ((a)) #define xtrymalloc_secure(a) gcry_malloc_secure ((a)) #define xtrycalloc(a,b) gcry_calloc ((a),(b)) #define xtrycalloc_secure(a,b) gcry_calloc_secure ((a),(b)) #define xtryrealloc(a,b) gcry_realloc ((a),(b)) #define xtrystrdup(a) gcry_strdup ((a)) #define xfree(a) gcry_free ((a)) #define xmalloc(a) gcry_xmalloc ((a)) #define xmalloc_secure(a) gcry_xmalloc_secure ((a)) #define xcalloc(a,b) gcry_xcalloc ((a),(b)) #define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b)) #define xrealloc(a,b) gcry_xrealloc ((a),(b)) #define xstrdup(a) gcry_xstrdup ((a)) /* For compatibility with gpg 1.4 we also define these: */ #define xmalloc_clear(a) gcry_xcalloc (1, (a)) #define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a)) /* Convenience function to return a gpg-error code for memory allocation failures. This function makes sure that an error will be returned even if accidently ERRNO is not set. */ static inline gpg_error_t out_of_core (void) { return gpg_error_from_syserror (); } /* A type to hold the ISO time. Note that this this is the same as the the KSBA type ksba_isotime_t. */ typedef char gnupg_isotime_t[16]; /*-- gettime.c --*/ time_t gnupg_get_time (void); void gnupg_get_isotime (gnupg_isotime_t timebuf); void gnupg_set_time (time_t newtime, int freeze); int gnupg_faked_time_p (void); u32 make_timestamp (void); u32 scan_isodatestr (const char *string); time_t isotime2epoch (const char *string); void epoch2isotime (gnupg_isotime_t timebuf, time_t atime); u32 add_days_to_timestamp (u32 stamp, u16 days); const char *strtimevalue (u32 stamp); const char *strtimestamp (u32 stamp); /* GMT */ const char *isotimestamp (u32 stamp); /* GMT */ const char *asctimestamp (u32 stamp); /* localized */ gpg_error_t add_seconds_to_isotime (gnupg_isotime_t atime, int nseconds); gpg_error_t add_days_to_isotime (gnupg_isotime_t atime, int ndays); gpg_error_t check_isotime (const gnupg_isotime_t atime); void dump_isotime (const gnupg_isotime_t atime); /* Copy one ISO date to another, this is inline so that we can do a minimal sanity check. A null date (empty string) is allowed. */ static inline void gnupg_copy_time (gnupg_isotime_t d, const gnupg_isotime_t s) { if (*s) { if ((strlen (s) != 15 || s[8] != 'T')) BUG(); memcpy (d, s, 15); d[15] = 0; } else *d = 0; } /*-- signal.c --*/ void gnupg_init_signals (int mode, void (*fast_cleanup)(void)); void gnupg_pause_on_sigusr (int which); void gnupg_block_all_signals (void); void gnupg_unblock_all_signals (void); /*-- yesno.c --*/ int answer_is_yes (const char *s); int answer_is_yes_no_default (const char *s, int def_answer); int answer_is_yes_no_quit (const char *s); int answer_is_okay_cancel (const char *s, int def_answer); /*-- xreadline.c --*/ ssize_t read_line (FILE *fp, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); /*-- b64enc.c and b64dec.c --*/ struct b64state { unsigned int flags; int idx; int quad_count; FILE *fp; char *title; unsigned char radbuf[4]; u32 crc; int stop_seen:1; int invalid_encoding:1; }; gpg_error_t b64enc_start (struct b64state *state, FILE *fp, const char *title); gpg_error_t b64enc_write (struct b64state *state, const void *buffer, size_t nbytes); gpg_error_t b64enc_finish (struct b64state *state); gpg_error_t b64dec_start (struct b64state *state, const char *title); gpg_error_t b64dec_proc (struct b64state *state, void *buffer, size_t length, size_t *r_nbytes); gpg_error_t b64dec_finish (struct b64state *state); /*-- sexputil.c */ gpg_error_t make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen, unsigned char *grip); int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b); unsigned char *make_simple_sexp_from_hexstr (const char *line, size_t *nscanned); int hash_algo_from_sigval (const unsigned char *sigval); unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen, const void *e, size_t elen, size_t *r_len); gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_n, size_t *r_nlen, unsigned char const **r_e, size_t *r_elen); gpg_error_t get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, int *r_algo); /*-- convert.c --*/ int hex2bin (const char *string, void *buffer, size_t length); int hexcolon2bin (const char *string, void *buffer, size_t length); char *bin2hex (const void *buffer, size_t length, char *stringbuf); char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf); const char *hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen); char *hex2str_alloc (const char *hexstring, size_t *r_count); /*-- percent.c --*/ char *percent_plus_escape (const char *string); char *percent_plus_unescape (const char *string, int nulrepl); char *percent_unescape (const char *string, int nulrepl); size_t percent_plus_unescape_inplace (char *string, int nulrepl); size_t percent_unescape_inplace (char *string, int nulrepl); /*-- homedir.c --*/ const char *standard_homedir (void); const char *default_homedir (void); const char *gnupg_sysconfdir (void); const char *gnupg_bindir (void); const char *gnupg_libexecdir (void); const char *gnupg_libdir (void); const char *gnupg_datadir (void); const char *gnupg_localedir (void); const char *dirmngr_socket_name (void); /* All module names. We also include gpg and gpgsm for the sake for gpgconf. */ #define GNUPG_MODULE_NAME_AGENT 1 #define GNUPG_MODULE_NAME_PINENTRY 2 #define GNUPG_MODULE_NAME_SCDAEMON 3 #define GNUPG_MODULE_NAME_DIRMNGR 4 #define GNUPG_MODULE_NAME_PROTECT_TOOL 5 #define GNUPG_MODULE_NAME_CHECK_PATTERN 6 #define GNUPG_MODULE_NAME_GPGSM 7 #define GNUPG_MODULE_NAME_GPG 8 #define GNUPG_MODULE_NAME_CONNECT_AGENT 9 #define GNUPG_MODULE_NAME_GPGCONF 10 const char *gnupg_module_name (int which); /*-- gpgrlhelp.c --*/ void gnupg_rl_initialize (void); /*-- helpfile.c --*/ char *gnupg_get_help_string (const char *key, int only_current_locale); /*-- localename.c --*/ const char *gnupg_messages_locale_name (void); /*-- miscellaneous.c --*/ /* This function is called at startup to tell libgcrypt to use our own logging subsystem. */ void setup_libgcrypt_logging (void); /* Same as estream_asprintf but die on memory failure. */ char *xasprintf (const char *fmt, ...) JNLIB_GCC_A_PRINTF(1,2); /* This is now an alias to estream_asprintf. */ char *xtryasprintf (const char *fmt, ...) JNLIB_GCC_A_PRINTF(1,2); const char *print_fname_stdout (const char *s); const char *print_fname_stdin (const char *s); -void print_string (FILE *fp, const byte *p, size_t n, int delim); -void print_utf8_string2 ( FILE *fp, const byte *p, size_t n, int delim); -void print_utf8_string (FILE *fp, const byte *p, size_t n); +void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim); +void print_utf8_buffer (estream_t fp, const void *p, size_t n); void print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved); char *make_printable_string (const void *p, size_t n, int delim); int is_file_compressed (const char *s, int *ret_rc); int match_multistr (const char *multistr,const char *match); /*-- Simple replacement functions. */ #ifndef HAVE_TTYNAME /* Systems without ttyname (W32) will merely return NULL. */ static inline char * ttyname (int fd) { (void)fd; return NULL; } #endif /* !HAVE_TTYNAME */ #ifdef HAVE_W32CE_SYSTEM #define getpid() GetCurrentProcessId () char *_gnupg_getenv (const char *name); /* See sysutils.c */ #define getenv(a) _gnupg_getenv ((a)) #endif /*-- Macros to replace ctype ones to avoid locale problems. --*/ #define spacep(p) (*(p) == ' ' || *(p) == '\t') #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* Note this isn't identical to a C locale isspace() without \f and \v, but works for the purposes used here. */ #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t') /* The atoi macros assume that the buffer has only valid digits. */ #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) #define xtoi_4(p) ((xtoi_2(p) * 256) + xtoi_2((p)+2)) /*-- Forward declaration of the commonly used server control structure. */ /* (We need it here as it is used by some callback prototypes.) */ struct server_control_s; typedef struct server_control_s *ctrl_t; #endif /*GNUPG_COMMON_UTIL_H*/ diff --git a/configure.ac b/configure.ac index c02fb1423..982a5923e 100644 --- a/configure.ac +++ b/configure.ac @@ -1,1534 +1,1537 @@ # configure.ac - for GnuPG 2.1 # Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, # 2006, 2007, 2008, 2009 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 . # Process this file with autoconf to produce a configure script. AC_PREREQ(2.61) min_automake_version="1.10" # Remember to change the version number immediately *after* a release. # Set my_issvn to "yes" for non-released code. Remember to run an # "svn up" and "autogen.sh" right before creating a distribution. m4_define([my_version], [2.1.0]) m4_define([my_issvn], [yes]) m4_define([svn_revision], m4_esyscmd([printf "%d" $(svn info 2>/dev/null \ | sed -n '/^Revision:/ s/[^0-9]//gp'|head -1)])) +m4_define([git_revision], m4_esyscmd([git branch -v 2>/dev/null \ + | awk '/^\* / {printf "%s",$3}'])) AC_INIT([gnupg], - [my_version[]m4_if(my_issvn,[yes],[-svn[]svn_revision])], + [my_version[]m4_if(my_issvn,[yes], + [m4_if(git_revision,[],[-svn[]svn_revision],[-git[]git_revision])])], [http://bugs.gnupg.org]) # Set development_version to yes if the minor number is odd or you # feel that the default check for a development version is not # sufficient. development_version=no NEED_GPG_ERROR_VERSION=1.4 NEED_LIBGCRYPT_API=1 NEED_LIBGCRYPT_VERSION=1.4.0 NEED_LIBASSUAN_API=2 NEED_LIBASSUAN_VERSION=2.0.0 NEED_KSBA_API=1 NEED_KSBA_VERSION=1.0.2 PACKAGE=$PACKAGE_NAME PACKAGE_GT=${PACKAGE_NAME}2 VERSION=$PACKAGE_VERSION AC_CONFIG_AUX_DIR(scripts) AC_CONFIG_SRCDIR(sm/gpgsm.c) AM_CONFIG_HEADER(config.h) AM_INIT_AUTOMAKE($PACKAGE, $VERSION) AC_CANONICAL_HOST AB_INIT AC_GNU_SOURCE # Some status variables. have_gpg_error=no have_libgcrypt=no have_libassuan=no have_ksba=no have_pth=no have_libusb=no have_adns=no use_bzip2=yes use_exec=yes disable_keyserver_path=no use_ccid_driver=yes GNUPG_BUILD_PROGRAM(gpg, yes) GNUPG_BUILD_PROGRAM(gpgsm, yes) GNUPG_BUILD_PROGRAM(agent, yes) GNUPG_BUILD_PROGRAM(scdaemon, yes) GNUPG_BUILD_PROGRAM(g13, yes) GNUPG_BUILD_PROGRAM(tools, yes) GNUPG_BUILD_PROGRAM(doc, yes) GNUPG_BUILD_PROGRAM(symcryptrun, no) AC_SUBST(PACKAGE) AC_SUBST(PACKAGE_GT) AC_SUBST(VERSION) AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package]) AC_DEFINE_UNQUOTED(PACKAGE_GT, "$PACKAGE_GT", [Name of this package for gettext]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package]) AC_DEFINE_UNQUOTED(PACKAGE_BUGREPORT, "$PACKAGE_BUGREPORT", [Bug report address]) AC_DEFINE_UNQUOTED(NEED_LIBGCRYPT_VERSION, "$NEED_LIBGCRYPT_VERSION", [Required version of Libgcrypt]) AC_DEFINE_UNQUOTED(NEED_KSBA_VERSION, "$NEED_KSBA_VERSION", [Required version of Libksba]) # The default is to use the modules from this package and the few # other packages in a standard place; i.e where this package gets # installed. With these options it is possible to override these # ${prefix} depended values with fixed paths, which can't be replaced # at make time. See also am/cmacros.am and the defaults in AH_BOTTOM. AC_ARG_WITH(agent-pgm, [ --with-agent-pgm=PATH Use PATH as the default for the agent)], GNUPG_AGENT_PGM="$withval", GNUPG_AGENT_PGM="" ) AC_SUBST(GNUPG_AGENT_PGM) AM_CONDITIONAL(GNUPG_AGENT_PGM, test -n "$GNUPG_AGENT_PGM") show_gnupg_agent_pgm="(default)" test -n "$GNUPG_AGENT_PGM" && show_gnupg_agent_pgm="$GNUPG_AGENT_PGM" AC_ARG_WITH(pinentry-pgm, [ --with-pinentry-pgm=PATH Use PATH as the default for the pinentry)], GNUPG_PINENTRY_PGM="$withval", GNUPG_PINENTRY_PGM="" ) AC_SUBST(GNUPG_PINENTRY_PGM) AM_CONDITIONAL(GNUPG_PINENTRY_PGM, test -n "$GNUPG_PINENTRY_PGM") show_gnupg_pinentry_pgm="(default)" test -n "$GNUPG_PINENTRY_PGM" && show_gnupg_pinentry_pgm="$GNUPG_PINENTRY_PGM" AC_ARG_WITH(scdaemon-pgm, [ --with-scdaemon-pgm=PATH Use PATH as the default for the scdaemon)], GNUPG_SCDAEMON_PGM="$withval", GNUPG_SCDAEMON_PGM="" ) AC_SUBST(GNUPG_SCDAEMON_PGM) AM_CONDITIONAL(GNUPG_SCDAEMON_PGM, test -n "$GNUPG_SCDAEMON_PGM") show_gnupg_scdaemon_pgm="(default)" test -n "$GNUPG_SCDAEMON_PGM" && show_gnupg_scdaemon_pgm="$GNUPG_SCDAEMON_PGM" AC_ARG_WITH(dirmngr-pgm, [ --with-dirmngr-pgm=PATH Use PATH as the default for the dirmngr)], GNUPG_DIRMNGR_PGM="$withval", GNUPG_DIRMNGR_PGM="" ) AC_SUBST(GNUPG_DIRMNGR_PGM) AM_CONDITIONAL(GNUPG_DIRMNGR_PGM, test -n "$GNUPG_DIRMNGR_PGM") show_gnupg_dirmngr_pgm="(default)" test -n "$GNUPG_DIRMNGR_PGM" && show_gnupg_dirmngr_pgm="$GNUPG_DIRMNGR_PGM" AC_ARG_WITH(protect-tool-pgm, [ --with-protect-tool-pgm=PATH Use PATH as the default for the protect-tool)], GNUPG_PROTECT_TOOL_PGM="$withval", GNUPG_PROTECT_TOOL_PGM="" ) AC_SUBST(GNUPG_PROTECT_TOOL_PGM) AM_CONDITIONAL(GNUPG_PROTECT_TOOL_PGM, test -n "$GNUPG_PROTECT_TOOL_PGM") show_gnupg_protect_tool_pgm="(default)" test -n "$GNUPG_PROTECT_TOOL_PGM" \ && show_gnupg_protect_tool_pgm="$GNUPG_PROTECT_TOOL_PGM" # Some folks want to use only the agent from this packet. Make it # easier for them by providing the configure option # --enable-only-agent. AC_ARG_ENABLE(agent-only, AC_HELP_STRING([--enable-agent-only],[build only the gpg-agent]), build_agent_only=$enableval) # SELinux support includes tracking of sensitive files to avoid # leaking their contents through processing these files by gpg itself AC_MSG_CHECKING([whether SELinux support is requested]) AC_ARG_ENABLE(selinux-support, AC_HELP_STRING([--enable-selinux-support], [enable SELinux support]), selinux_support=$enableval, selinux_support=no) AC_MSG_RESULT($selinux_support) # Allow disabling of bzib2 support. # It is defined only after we confirm the library is available later AC_MSG_CHECKING([whether to enable the BZIP2 compression algorithm]) AC_ARG_ENABLE(bzip2, AC_HELP_STRING([--disable-bzip2],[disable the BZIP2 compression algorithm]), use_bzip2=$enableval) AC_MSG_RESULT($use_bzip2) # Configure option to allow or disallow execution of external # programs, like a photo viewer. AC_MSG_CHECKING([whether to enable external program execution]) AC_ARG_ENABLE(exec, AC_HELP_STRING([--disable-exec],[disable all external program execution]), use_exec=$enableval) AC_MSG_RESULT($use_exec) if test "$use_exec" = no ; then AC_DEFINE(NO_EXEC,1,[Define to disable all external program execution]) fi if test "$use_exec" = yes ; then AC_MSG_CHECKING([whether to enable photo ID viewing]) AC_ARG_ENABLE(photo-viewers, [ --disable-photo-viewers disable photo ID viewers], [if test "$enableval" = no ; then AC_DEFINE(DISABLE_PHOTO_VIEWER,1,[define to disable photo viewing]) fi],enableval=yes) gnupg_cv_enable_photo_viewers=$enableval AC_MSG_RESULT($enableval) if test "$gnupg_cv_enable_photo_viewers" = yes ; then AC_MSG_CHECKING([whether to use a fixed photo ID viewer]) AC_ARG_WITH(photo-viewer, [ --with-photo-viewer=FIXED_VIEWER set a fixed photo ID viewer], [if test "$withval" = yes ; then withval=no elif test "$withval" != no ; then AC_DEFINE_UNQUOTED(FIXED_PHOTO_VIEWER,"$withval", [if set, restrict photo-viewer to this]) fi],withval=no) AC_MSG_RESULT($withval) fi AC_MSG_CHECKING([whether to enable external keyserver helpers]) AC_ARG_ENABLE(keyserver-helpers, [ --disable-keyserver-helpers disable all external keyserver support], [if test "$enableval" = no ; then AC_DEFINE(DISABLE_KEYSERVER_HELPERS,1, [define to disable keyserver helpers]) fi],enableval=yes) gnupg_cv_enable_keyserver_helpers=$enableval AC_MSG_RESULT($enableval) if test "$gnupg_cv_enable_keyserver_helpers" = yes ; then # LDAP is defined only after we confirm the library is available later AC_MSG_CHECKING([whether LDAP keyserver support is requested]) AC_ARG_ENABLE(ldap, AC_HELP_STRING([--disable-ldap],[disable LDAP keyserver interface only]), try_ldap=$enableval, try_ldap=yes) AC_MSG_RESULT($try_ldap) AC_MSG_CHECKING([whether HKP keyserver support is requested]) AC_ARG_ENABLE(hkp, AC_HELP_STRING([--disable-hkp],[disable HKP keyserver interface only]), try_hkp=$enableval, try_hkp=yes) AC_MSG_RESULT($try_hkp) AC_MSG_CHECKING([whether finger key fetching support is requested]) AC_ARG_ENABLE(finger, AC_HELP_STRING([--disable-finger], [disable finger key fetching interface only]), try_finger=$enableval, try_finger=yes) AC_MSG_RESULT($try_finger) AC_MSG_CHECKING([whether generic object key fetching support is requested]) AC_ARG_ENABLE(generic, AC_HELP_STRING([--disable-generic], [disable generic object key fetching interface only]), try_generic=$enableval, try_generic=yes) AC_MSG_RESULT($try_generic) AC_MSG_CHECKING([whether email keyserver support is requested]) AC_ARG_ENABLE(mailto, AC_HELP_STRING([--enable-mailto], [enable email keyserver interface only]), try_mailto=$enableval, try_mailto=no) AC_MSG_RESULT($try_mailto) fi AC_MSG_CHECKING([whether keyserver exec-path is enabled]) AC_ARG_ENABLE(keyserver-path, AC_HELP_STRING([--disable-keyserver-path], [disable the exec-path option for keyserver helpers]), [if test "$enableval" = no ; then disable_keyserver_path=yes fi],enableval=yes) AC_MSG_RESULT($enableval) fi # # Check for the key/uid cache size. This can't be zero, but can be # pretty small on embedded systems. This is used for the gpg part. # AC_MSG_CHECKING([for the size of the key and uid cache]) AC_ARG_ENABLE(key-cache, AC_HELP_STRING([--enable-key-cache=SIZE], [Set key cache to SIZE (default 4096)]),,enableval=4096) if test "$enableval" = "no"; then enableval=5 elif test "$enableval" = "yes" || test "$enableval" = ""; then enableval=4096 fi changequote(,)dnl key_cache_size=`echo "$enableval" | sed 's/[A-Za-z]//g'` changequote([,])dnl if test "$enableval" != "$key_cache_size" || test "$key_cache_size" -lt 5; then AC_MSG_ERROR([invalid key-cache size]) fi AC_MSG_RESULT($key_cache_size) AC_DEFINE_UNQUOTED(PK_UID_CACHE_SIZE,$key_cache_size, [Size of the key and UID caches]) # # Check whether we want to use Linux capabilities # AC_MSG_CHECKING([whether use of capabilities is requested]) AC_ARG_WITH(capabilities, [ --with-capabilities use linux capabilities [default=no]], [use_capabilities="$withval"],[use_capabilities=no]) AC_MSG_RESULT($use_capabilities) # # Allow disabling of internal CCID support. # It is defined only after we confirm the library is available later # AC_MSG_CHECKING([whether to enable the internal CCID driver]) AC_ARG_ENABLE(ccid-driver, AC_HELP_STRING([--disable-ccid-driver], [disable the internal CCID driver]), use_ccid_driver=$enableval) AC_MSG_RESULT($use_ccid_driver) # # To avoid double inclusion of config.h which might happen at some # places, we add the usual double inclusion protection at the top of # config.h. # AH_TOP([ #ifndef GNUPG_CONFIG_H_INCLUDED #define GNUPG_CONFIG_H_INCLUDED ]) # # Stuff which goes at the bottom of config.h. # AH_BOTTOM([ /* This is the major version number of GnuPG so that source included files can test for this. Note, that we use 2 here even for GnuPG 1.9.x. */ #define GNUPG_MAJOR_VERSION 2 /* Now to separate file name parts. Please note that the string version must not contain more than one character because the code assumes strlen()==1 */ #ifdef HAVE_DOSISH_SYSTEM #define DIRSEP_C '\\' #define DIRSEP_S "\\" #define EXTSEP_C '.' #define EXTSEP_S "." #define PATHSEP_C ';' #define PATHSEP_S ";" #define EXEEXT_S ".exe" #else #define DIRSEP_C '/' #define DIRSEP_S "/" #define EXTSEP_C '.' #define EXTSEP_S "." #define PATHSEP_C ':' #define PATHSEP_S ":" #define EXEEXT_S "" #endif /* This is the same as VERSION, but should be overridden if the platform cannot handle things like dots '.' in filenames. Set SAFE_VERSION_DOT and SAFE_VERSION_DASH to whatever SAFE_VERSION uses for dots and dashes. */ #define SAFE_VERSION VERSION #define SAFE_VERSION_DOT '.' #define SAFE_VERSION_DASH '-' /* Some global constants. */ #ifdef HAVE_DRIVE_LETTERS #define GNUPG_DEFAULT_HOMEDIR "c:/gnupg" #elif defined(__VMS) #define GNUPG_DEFAULT_HOMEDIR "/SYS\$LOGIN/gnupg" #else #define GNUPG_DEFAULT_HOMEDIR "~/.gnupg" #endif #define GNUPG_PRIVATE_KEYS_DIR "private-keys-v1.d" /* For some systems (DOS currently), we hardcode the path here. For POSIX systems the values are constructed by the Makefiles, so that the values may be overridden by the make invocations; this is to comply with the GNU coding standards. */ #ifdef HAVE_DRIVE_LETTERS /* FIXME: We need to use a function to determine these values depending on the actual installation directory. */ #define GNUPG_BINDIR "c:\\gnupg" #define GNUPG_LIBEXECDIR "c:\\gnupg" #define GNUPG_LIBDIR "c:\\gnupg" #define GNUPG_DATADIR "c:\\gnupg" #define GNUPG_SYSCONFDIR "c:\\gnupg" #endif /* Derive some other constants. */ #if !(defined(HAVE_FORK) && defined(HAVE_PIPE) && defined(HAVE_WAITPID)) #define EXEC_TEMPFILE_ONLY #endif /* We didn't define endianness above, so get it from OS macros. This is intended for making fat binary builds on OS X. */ #if !defined(BIG_ENDIAN_HOST) && !defined(LITTLE_ENDIAN_HOST) #if defined(__BIG_ENDIAN__) #define BIG_ENDIAN_HOST 1 #elif defined(__LITTLE_ENDIAN__) #define LITTLE_ENDIAN_HOST 1 #else #error "No endianness found" #endif #endif /* Hack used for W32: ldap.m4 also tests for the ASCII version of ldap_start_tls_s because that is the actual symbol used in the library. winldap.h redefines it to our commonly used value, thus we define our usual macro here. */ #ifdef HAVE_LDAP_START_TLS_SA # ifndef HAVE_LDAP_START_TLS_S # define HAVE_LDAP_START_TLS_S 1 # endif #endif /* Tell libgcrypt not to use its own libgpg-error implementation. */ #define USE_LIBGPG_ERROR 1 /* We use jnlib, so tell other modules about it. */ #define HAVE_JNLIB_LOGGING 1 /* Our HTTP code is used in estream mode. */ #define HTTP_USE_ESTREAM 1 /* Under W32 we do an explicit socket initialization, thus we need to avoid the on-demand initialization which would also install an atexit handler. */ #define HTTP_NO_WSASTARTUP /* We always include support for the OpenPGP card. */ #define ENABLE_CARD_SUPPORT 1 /* We explicitly need to disable PTH's soft mapping as Debian currently enables it by default for no reason. */ #define PTH_SYSCALL_SOFT 0 /* We want to use the libgcrypt provided memory allocation for asprintf. */ #define _ESTREAM_PRINTF_MALLOC gcry_malloc #define _ESTREAM_PRINTF_FREE gcry_free #define _ESTREAM_PRINTF_EXTRA_INCLUDE "../common/util.h" /* Under Windows we use the gettext code from libgpg-error. */ #define GPG_ERR_ENABLE_GETTEXT_MACROS #endif /*GNUPG_CONFIG_H_INCLUDED*/ ]) AM_MAINTAINER_MODE # Checks for programs. AC_MSG_NOTICE([checking for programs]) AC_PROG_MAKE_SET AM_SANITY_CHECK missing_dir=`cd $ac_aux_dir && pwd` AM_MISSING_PROG(ACLOCAL, aclocal, $missing_dir) AM_MISSING_PROG(AUTOCONF, autoconf, $missing_dir) AM_MISSING_PROG(AUTOMAKE, automake, $missing_dir) AM_MISSING_PROG(AUTOHEADER, autoheader, $missing_dir) AM_MISSING_PROG(MAKEINFO, makeinfo, $missing_dir) AC_PROG_AWK AC_PROG_CC AC_PROG_CPP AM_PROG_CC_C_O if test "x$ac_cv_prog_cc_c89" = "xno" ; then AC_MSG_ERROR([[No C-89 compiler found]]) fi AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_RANLIB AC_CHECK_TOOL(AR, ar, :) AC_PATH_PROG(PERL,"perl") AC_CHECK_TOOL(WINDRES, windres, :) AC_ISC_POSIX gl_EARLY AC_SYS_LARGEFILE GNUPG_CHECK_FAQPROG GNUPG_CHECK_USTAR # We need to compile and run a program on the build machine. A # comment in libgpg-error says that the AC_PROG_CC_FOR_BUILD macro in # the AC archive is broken for autoconf 2.57. Given that tehre is no # newer version of that macro, we assume that it is also broken for # autoconf 2.61 and thus we use a simple but usually sufficient # approach. AC_MSG_CHECKING(for cc for build) if test "$cross_compiling" = "yes"; then CC_FOR_BUILD="${CC_FOR_BUILD-cc}" else CC_FOR_BUILD="${CC_FOR_BUILD-$CC}" fi AC_MSG_RESULT($CC_FOR_BUILD) AC_ARG_VAR(CC_FOR_BUILD,[build system C compiler]) try_gettext=yes have_dosish_system=no have_w32_system=no have_w32ce_system=no use_simple_gettext=no case "${host}" in *-mingw32*) # special stuff for Windoze NT ac_cv_have_dev_random=no AC_DEFINE(USE_ONLY_8DOT3,1, [set this to limit filenames to the 8.3 format]) AC_DEFINE(HAVE_DRIVE_LETTERS,1, [defined if we must run on a stupid file system]) AC_DEFINE(USE_SIMPLE_GETTEXT,1, [because the Unix gettext has too much overhead on MingW32 systems and these systems lack Posix functions, we use a simplified version of gettext]) disable_keyserver_path=yes have_dosish_system=yes have_w32_system=yes case "${host}" in *-mingw32ce*) have_w32ce_system=yes ;; esac try_gettext="no" use_simple_gettext=yes ;; i?86-emx-os2 | i?86-*-os2*emx ) # OS/2 with the EMX environment ac_cv_have_dev_random=no AC_DEFINE(HAVE_DRIVE_LETTERS) have_dosish_system=yes try_gettext="no" ;; i?86-*-msdosdjgpp*) # DOS with the DJGPP environment ac_cv_have_dev_random=no AC_DEFINE(HAVE_DRIVE_LETTERS) have_dosish_system=yes try_gettext="no" ;; *-*-freebsd*) # FreeBSD CPPFLAGS="$CPPFLAGS -I/usr/local/include" LDFLAGS="$LDFLAGS -L/usr/local/lib" ;; *-*-hpux*) if test -z "$GCC" ; then CFLAGS="$CFLAGS -Ae -D_HPUX_SOURCE" fi ;; *-dec-osf4*) if test -z "$GCC" ; then # Suppress all warnings # to get rid of the unsigned/signed char mismatch warnings. CFLAGS="$CFLAGS -w" fi ;; *-dec-osf5*) if test -z "$GCC" ; then # Use the newer compiler `-msg_disable ptrmismatch1' to # get rid of the unsigned/signed char mismatch warnings. # Using this may hide other pointer mismatch warnings, but # it at least lets other warning classes through CFLAGS="$CFLAGS -msg_disable ptrmismatch1" fi ;; m68k-atari-mint) ;; *) ;; esac if test "$have_dosish_system" = yes; then AC_DEFINE(HAVE_DOSISH_SYSTEM,1, [Defined if we run on some of the PCDOS like systems (DOS, Windoze. OS/2) with special properties like no file modes]) fi AM_CONDITIONAL(HAVE_DOSISH_SYSTEM, test "$have_dosish_system" = yes) AM_CONDITIONAL(USE_SIMPLE_GETTEXT, test x"$use_simple_gettext" = xyes) if test "$have_w32_system" = yes; then AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system]) if test "$have_w32ce_system" = yes; then AC_DEFINE(HAVE_W32CE_SYSTEM,1,[Defined if we run on WindowsCE]) fi fi AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes) AM_CONDITIONAL(HAVE_W32CE_SYSTEM, test "$have_w32ce_system" = yes) if test "$disable_keyserver_path" = yes; then AC_DEFINE(DISABLE_KEYSERVER_PATH,1, [Defined to disable exec-path for keyserver helpers]) fi # (These need to go after AC_PROG_CC so that $EXEEXT is defined) AC_DEFINE_UNQUOTED(EXEEXT,"$EXEEXT",[The executable file extension, if any]) if test x"$try_hkp" = xyes ; then AC_SUBST(GPGKEYS_HKP,"gpg2keys_hkp$EXEEXT") fi if test x"$try_finger" = xyes ; then AC_SUBST(GPGKEYS_FINGER,"gpg2keys_finger$EXEEXT") fi # # Checks for libraries. # AC_MSG_NOTICE([checking for libraries]) # # libgpg-error is a library with error codes shared between GnuPG # related projects. # AM_PATH_GPG_ERROR("$NEED_GPG_ERROR_VERSION", have_gpg_error=yes,have_gpg_error=no) # # Libgcrypt is our generic crypto library # AM_PATH_LIBGCRYPT("$NEED_LIBGCRYPT_API:$NEED_LIBGCRYPT_VERSION", have_libgcrypt=yes,have_libgcrypt=no) # # libassuan is used for IPC # AM_PATH_LIBASSUAN("$NEED_LIBASSUAN_API:$NEED_LIBASSUAN_VERSION", have_libassuan=yes,have_libassuan=no) if test "$have_libassuan" = "yes"; then AC_DEFINE_UNQUOTED(GNUPG_LIBASSUAN_VERSION, "$libassuan_version", [version of the libassuan library]) fi # # libksba is our X.509 support library # AM_PATH_KSBA("$NEED_KSBA_API:$NEED_KSBA_VERSION",have_ksba=yes,have_ksba=no) # # libusb allows us to use the integrated CCID smartcard reader driver. # # FiXME: Use GNUPG_CHECK_LIBUSB and modify to use separate AC_SUBSTs. if test "$use_ccid_driver" = yes ; then AC_CHECK_LIB(usb, usb_bulk_write, [ LIBUSB_LIBS="$LIBUSB_LIBS -lusb" AC_DEFINE(HAVE_LIBUSB,1, [defined if libusb is available]) have_libusb=yes ]) AC_CHECK_FUNCS(usb_create_match) fi AC_SUBST(LIBUSB_LIBS) # # Check wether it is necessary to link against libdl. # gnupg_dlopen_save_libs="$LIBS" LIBS="" AC_SEARCH_LIBS(dlopen, c dl,,,) DL_LIBS=$LIBS AC_SUBST(DL_LIBS) LIBS="$gnupg_dlopen_save_libs" # Checks for g13 AC_PATH_PROG(ENCFS, encfs, /usr/bin/encfs) AC_DEFINE_UNQUOTED(ENCFS, "${ENCFS}", [defines the filename of the encfs program]) AC_PATH_PROG(FUSERMOUNT, fusermount, /usr/bin/fusermount) AC_DEFINE_UNQUOTED(FUSERMOUNT, "${FUSERMOUNT}", [defines the filename of the fusermount program]) # # Checks for symcryptrun: # # libutil has openpty() and login_tty(). AC_CHECK_LIB(util, openpty, [ LIBUTIL_LIBS="$LIBUTIL_LIBS -lutil" AC_DEFINE(HAVE_LIBUTIL,1, [defined if libutil is available]) ]) AC_SUBST(LIBUTIL_LIBS) # shred is used to clean temporary plain text files. AC_PATH_PROG(SHRED, shred, /usr/bin/shred) AC_DEFINE_UNQUOTED(SHRED, "${SHRED}", [defines the filename of the shred program]) # # Check whether the GNU Pth library is available # Note, that we include a Pth emulation for W32. # GNUPG_PATH_PTH if test "$have_pth" = "yes"; then AC_DEFINE(USE_GNU_PTH, 1, [Defined if the GNU Portable Thread Library should be used]) else AC_MSG_WARN([[ *** *** To support concurrent access to the gpg-agent and the SCdaemon *** we need the support of the GNU Portable Threads Library. *** Download it from ftp://ftp.gnu.org/gnu/pth/ *** On a Debian GNU/Linux system you might want to try *** apt-get install libpth-dev ***]]) fi AC_MSG_NOTICE([checking for networking options]) # # Must check for network library requirements before doing link tests # for ldap, for example. If ldap libs are static (or dynamic and without # ELF runtime link paths), then link will fail and LDAP support won't # be detected. # AC_CHECK_FUNC(gethostbyname, , AC_CHECK_LIB(nsl, gethostbyname, [NETLIBS="-lnsl $NETLIBS"])) AC_CHECK_FUNC(setsockopt, , AC_CHECK_LIB(socket, setsockopt, [NETLIBS="-lsocket $NETLIBS"])) # # Check for ADNS. # _cppflags="${CPPFLAGS}" _ldflags="${LDFLAGS}" AC_ARG_WITH(adns, AC_HELP_STRING([--with-adns=DIR], [look for the adns library in DIR]), [if test -d "$withval"; then CPPFLAGS="${CPPFLAGS} -I$withval/include" LDFLAGS="${LDFLAGS} -L$withval/lib" fi]) if test "$with_adns" != "no"; then AC_CHECK_HEADERS(adns.h, AC_CHECK_LIB(adns, adns_init, [have_adns=yes], [CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}]), [CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}]) fi if test "$have_adns" = "yes"; then ADNSLIBS="-ladns" fi AC_SUBST(ADNSLIBS) # Newer adns versions feature a free function to be used under W32. AC_CHECK_FUNCS(adns_free) # # Now try for the resolver functions so we can use DNS for SRV, PA and CERT. # if test x"$try_hkp" = xyes || test x"$try_http" = xyes ; then AC_ARG_ENABLE(dns-srv, AC_HELP_STRING([--disable-dns-srv], [disable the use of DNS SRV in HKP and HTTP]), use_dns_srv=$enableval,use_dns_srv=yes) fi AC_ARG_ENABLE(dns-pka, AC_HELP_STRING([--disable-dns-pka], [disable the use of PKA records in DNS]), use_dns_pka=$enableval,use_dns_pka=yes) AC_ARG_ENABLE(dns-cert, AC_HELP_STRING([--disable-dns-cert], [disable the use of CERT records in DNS]), use_dns_cert=$enableval,use_dns_cert=yes) if test x"$use_dns_pka" = xyes || test x"$use_dns_srv" = xyes \ || test x"$use_dns_cert" = xyes; then _dns_save_libs=$LIBS LIBS="" # the double underscore thing is a glibc-ism? AC_SEARCH_LIBS(res_query,resolv bind,, AC_SEARCH_LIBS(__res_query,resolv bind,,have_resolver=no)) AC_SEARCH_LIBS(dn_expand,resolv bind,, AC_SEARCH_LIBS(__dn_expand,resolv bind,,have_resolver=no)) AC_SEARCH_LIBS(dn_skipname,resolv bind,, AC_SEARCH_LIBS(__dn_skipname,resolv bind,,have_resolver=no)) if test x"$have_resolver" != xno ; then # Make sure that the BIND 4 resolver interface is workable before # enabling any code that calls it. At some point I'll rewrite the # code to use the BIND 8 resolver API. # We might also want to use adns instead. Problem with ADNS is that # it does not support v6. AC_MSG_CHECKING([whether the resolver is usable]) AC_LINK_IFELSE([AC_LANG_PROGRAM([#include #include #include #include ], [[unsigned char answer[PACKETSZ]; res_query("foo.bar",C_IN,T_A,answer,PACKETSZ); dn_skipname(0,0); dn_expand(0,0,0,0,0); ]])],have_resolver=yes,have_resolver=no) AC_MSG_RESULT($have_resolver) # This is Apple-specific and somewhat bizarre as they changed the # define in bind 8 for some reason. if test x"$have_resolver" != xyes ; then AC_MSG_CHECKING( [whether I can make the resolver usable with BIND_8_COMPAT]) AC_LINK_IFELSE([AC_LANG_PROGRAM([#define BIND_8_COMPAT #include #include #include #include ], [[unsigned char answer[PACKETSZ]; res_query("foo.bar",C_IN,T_A,answer,PACKETSZ); dn_skipname(0,0); dn_expand(0,0,0,0,0); ]])],[have_resolver=yes ; need_compat=yes]) AC_MSG_RESULT($have_resolver) fi fi if test x"$have_resolver" = xyes ; then DNSLIBS=$LIBS if test x"$use_dns_srv" = xyes ; then AC_DEFINE(USE_DNS_SRV,1,[define to use DNS SRV]) fi if test x"$use_dns_pka" = xyes ; then AC_DEFINE(USE_DNS_PKA,1,[define to use our experimental DNS PKA]) fi if test x"$use_dns_cert" = xyes ; then AC_DEFINE(USE_DNS_CERT,1,[define to use DNS CERT]) fi if test x"$need_compat" = xyes ; then AC_DEFINE(BIND_8_COMPAT,1,[an Apple OSXism]) fi else # If we have no resolver library but ADNS (e.g. under W32) enable the # code parts which can be used with ADNS. if test x"$have_adns" = xyes ; then DNSLIBS="$ADNSLIBS" AC_DEFINE(USE_ADNS,1,[Use ADNS as resolver library.]) if test x"$use_dns_srv" = xyes ; then AC_DEFINE(USE_DNS_SRV,1) fi if test x"$use_dns_pka" = xyes ; then AC_DEFINE(USE_DNS_PKA,1) fi if test x"$use_dns_cert" = xyes ; then AC_DEFINE(USE_DNS_CERT,1,[define to use DNS CERT]) fi else use_dns_srv=no use_dns_pka=no use_dns_cert=no fi fi LIBS=$_dns_save_libs fi AC_SUBST(DNSLIBS) AM_CONDITIONAL(USE_DNS_SRV, test x"$use_dns_srv" = xyes) # # Check for LDAP # if test "$try_ldap" = yes ; then GNUPG_CHECK_LDAP($NETLIBS) fi # # Check for curl. We fake the curl API if libcurl isn't installed. # We require 7.10 or later as we use curl_version_info(). # LIBCURL_CHECK_CONFIG([yes],[7.10],,[fake_curl=yes]) AM_CONDITIONAL(FAKE_CURL,test x"$fake_curl" = xyes) # Generic, for us, means curl if test x"$try_generic" = xyes ; then AC_SUBST(GPGKEYS_CURL,"gpg2keys_curl$EXEEXT") fi # # Check for sendmail # # This isn't necessarily sendmail itself, but anything that gives a # sendmail-ish interface to the outside world. That includes Exim, # Postfix, etc. Basically, anything that can handle "sendmail -t". if test "$try_mailto" = yes ; then AC_ARG_WITH(mailprog, AC_HELP_STRING([--with-mailprog=NAME], [use "NAME -t" for mail transport]), ,with_mailprog=yes) if test x"$with_mailprog" = xyes ; then AC_PATH_PROG(SENDMAIL,sendmail,,$PATH:/usr/sbin:/usr/libexec:/usr/lib) if test "$ac_cv_path_SENDMAIL" ; then GPGKEYS_MAILTO="gpg2keys_mailto" fi elif test x"$with_mailprog" != xno ; then AC_MSG_CHECKING([for a mail transport program]) AC_SUBST(SENDMAIL,$with_mailprog) AC_MSG_RESULT($with_mailprog) GPGKEYS_MAILTO="gpg2keys_mailto" fi fi AC_SUBST(GPGKEYS_MAILTO) # # Construct a printable name of the OS # case "${host}" in *-mingw32ce*) PRINTABLE_OS_NAME="W32CE" ;; *-mingw32*) PRINTABLE_OS_NAME="MingW32" ;; *-*-cygwin*) PRINTABLE_OS_NAME="Cygwin" ;; i?86-emx-os2 | i?86-*-os2*emx ) PRINTABLE_OS_NAME="OS/2" ;; i?86-*-msdosdjgpp*) PRINTABLE_OS_NAME="MSDOS/DJGPP" try_dynload=no ;; *-linux*) PRINTABLE_OS_NAME="GNU/Linux" ;; *) PRINTABLE_OS_NAME=`uname -s || echo "Unknown"` ;; esac AC_DEFINE_UNQUOTED(PRINTABLE_OS_NAME, "$PRINTABLE_OS_NAME", [A human readable text with the name of the OS]) # # Checking for iconv # AM_ICONV # # Check for gettext # # This is "GNU gnupg" - The project-id script from gettext # needs this string # AC_MSG_NOTICE([checking for gettext]) AM_PO_SUBDIRS AM_GNU_GETTEXT_VERSION([0.17]) if test "$try_gettext" = yes; then AM_GNU_GETTEXT([external],[need-ngettext]) # gettext requires some extra checks. These really should be part of # the basic AM_GNU_GETTEXT macro. TODO: move other gettext-specific # function checks to here. AC_CHECK_FUNCS(strchr) else USE_NLS=no USE_INCLUDED_LIBINTL=no BUILD_INCLUDED_LIBINTL=no POSUB=po AC_SUBST(USE_NLS) AC_SUBST(USE_INCLUDED_LIBINTL) AC_SUBST(BUILD_INCLUDED_LIBINTL) AC_SUBST(POSUB) fi # We use HAVE_LANGINFO_CODESET in a couple of places. AM_LANGINFO_CODESET # Checks required for our use locales gt_LC_MESSAGES # # SELinux support # if test "$selinux_support" = yes ; then AC_DEFINE(ENABLE_SELINUX_HACKS,1,[Define to enable SELinux support]) fi # # Checks for header files. # AC_MSG_NOTICE([checking for header files]) AC_HEADER_STDC AC_CHECK_HEADERS([string.h unistd.h langinfo.h termio.h locale.h getopt.h \ pty.h pwd.h inttypes.h signal.h]) AC_HEADER_TIME # # Checks for typedefs, structures, and compiler characteristics. # AC_MSG_NOTICE([checking for system characteristics]) AC_C_CONST AC_C_INLINE AC_C_VOLATILE AC_TYPE_SIZE_T AC_TYPE_MODE_T AC_TYPE_SIGNAL AC_DECL_SYS_SIGLIST gl_HEADER_SYS_SOCKET gl_TYPE_SOCKLEN_T AC_ARG_ENABLE(endian-check, AC_HELP_STRING([--disable-endian-check], [disable the endian check and trust the OS provided macros]), endiancheck=$enableval,endiancheck=yes) if test x"$endiancheck" = xyes ; then GNUPG_CHECK_ENDIAN fi # fixme: we should get rid of the byte type GNUPG_CHECK_TYPEDEF(byte, HAVE_BYTE_TYPEDEF) GNUPG_CHECK_TYPEDEF(ushort, HAVE_USHORT_TYPEDEF) GNUPG_CHECK_TYPEDEF(ulong, HAVE_ULONG_TYPEDEF) GNUPG_CHECK_TYPEDEF(u16, HAVE_U16_TYPEDEF) GNUPG_CHECK_TYPEDEF(u32, HAVE_U32_TYPEDEF) AC_CHECK_SIZEOF(unsigned short) AC_CHECK_SIZEOF(unsigned int) AC_CHECK_SIZEOF(unsigned long) AC_CHECK_SIZEOF(unsigned long long) AC_CHECK_SIZEOF(time_t,,[[ #include #if TIME_WITH_SYS_TIME # include # include #else # if HAVE_SYS_TIME_H # include # else # include # endif #endif ]]) # Ensure that we have UINT64_C before we bother to check for uint64_t # Fixme: really needed in gnupg? I think it is only useful in libcgrypt. AC_CACHE_CHECK([for UINT64_C],[gnupg_cv_uint64_c_works], AC_COMPILE_IFELSE(AC_LANG_PROGRAM([#include uint64_t foo=UINT64_C(42);]), gnupg_cv_uint64_c_works=yes,gnupg_cv_uint64_c_works=no)) if test "$gnupg_cv_uint64_c_works" = "yes" ; then AC_CHECK_SIZEOF(uint64_t) fi if test "$ac_cv_sizeof_unsigned_short" = "0" \ || test "$ac_cv_sizeof_unsigned_int" = "0" \ || test "$ac_cv_sizeof_unsigned_long" = "0"; then AC_MSG_WARN([Hmmm, something is wrong with the sizes - using defaults]); fi # # Checks for library functions. # AC_MSG_NOTICE([checking for library functions]) AC_CHECK_DECLS(getpagesize) AC_FUNC_FSEEKO AC_FUNC_VPRINTF AC_FUNC_FORK AC_CHECK_FUNCS([strerror strlwr tcgetattr mmap]) AC_CHECK_FUNCS([strcasecmp strncasecmp ctermid times gmtime_r]) AC_CHECK_FUNCS([unsetenv fcntl ftruncate]) AC_CHECK_FUNCS([gettimeofday getrusage getrlimit setrlimit clock_gettime]) AC_CHECK_FUNCS([atexit raise getpagesize strftime nl_langinfo setlocale]) AC_CHECK_FUNCS([waitpid wait4 sigaction sigprocmask pipe stat getaddrinfo]) AC_CHECK_FUNCS([ttyname rand ftello fsync]) AC_CHECK_TYPES([struct sigaction, sigset_t],,,[#include ]) # # These are needed by the jnlib parts in common. # Note: We already checked pwd.h. AC_CHECK_HEADERS([signal.h]) AC_CHECK_FUNCS([memicmp stpcpy strsep strlwr strtoul memmove stricmp strtol \ memrchr isascii timegm getrusage setrlimit stat setlocale \ flockfile funlockfile fopencookie funopen getpwnam getpwuid \ getenv ]) # # gnulib checks # gl_SOURCE_BASE([gl]) gl_M4_BASE([gl/m4]) gl_MODULES([setenv mkdtemp xsize strpbrk]) gl_INIT # # W32 specific test # GNUPG_FUNC_MKDIR_TAKES_ONE_ARG # # Sanity check regex. Tests adapted from mutt. # AC_MSG_CHECKING([whether regular expression support is requested]) AC_ARG_ENABLE(regex, AC_HELP_STRING([--disable-regex], [do not handle regular expressions in trust signatures]), use_regex=$enableval, use_regex=yes) AC_MSG_RESULT($use_regex) if test "$use_regex" = yes ; then _cppflags="${CPPFLAGS}" _ldflags="${LDFLAGS}" AC_ARG_WITH(regex, AC_HELP_STRING([--with-regex=DIR],[look for regex in DIR]), [ if test -d "$withval" ; then CPPFLAGS="${CPPFLAGS} -I$withval/include" LDFLAGS="${LDFLAGS} -L$withval/lib" fi ],withval="") # Does the system have regex functions at all? AC_SEARCH_LIBS([regcomp], [regex]) AC_CHECK_FUNC(regcomp, gnupg_cv_have_regex=yes, gnupg_cv_have_regex=no) if test $gnupg_cv_have_regex = no; then use_regex=no else if test x"$cross_compiling" = xyes; then AC_MSG_WARN([cross compiling; assuming regexp libray is not broken]) else AC_CACHE_CHECK([whether your system's regexp library is broken], [gnupg_cv_regex_broken], AC_TRY_RUN([ #include #include main() { regex_t blah ; regmatch_t p; p.rm_eo = p.rm_eo; return regcomp(&blah, "foo.*bar", REG_NOSUB) || regexec (&blah, "foobar", 0, NULL, 0); }], gnupg_cv_regex_broken=no, gnupg_cv_regex_broken=yes, gnupg_cv_regex_broken=yes)) if test $gnupg_cv_regex_broken = yes; then AC_MSG_WARN([your regex is broken - disabling regex use]) use_regex=no fi fi fi CPPFLAGS="${_cppflags}" LDFLAGS="${_ldflags}" fi if test "$use_regex" != yes ; then AC_DEFINE(DISABLE_REGEX,1, [Define to disable regular expression support]) fi AM_CONDITIONAL(DISABLE_REGEX, test x"$use_regex" != xyes) # # Do we have zlib? Must do it here because Solaris failed # when compiling a conftest (due to the "-lz" from LIBS). # Note that we combine zlib and bzlib2 in ZLIBS. # _cppflags="${CPPFLAGS}" _ldflags="${LDFLAGS}" AC_ARG_WITH(zlib, [ --with-zlib=DIR use libz in DIR],[ if test -d "$withval"; then CPPFLAGS="${CPPFLAGS} -I$withval/include" LDFLAGS="${LDFLAGS} -L$withval/lib" fi ]) AC_CHECK_HEADER(zlib.h, AC_CHECK_LIB(z, deflateInit2_, ZLIBS="-lz", CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}), CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}) # # Check whether we can support bzip2 # if test "$use_bzip2" = yes ; then _cppflags="${CPPFLAGS}" _ldflags="${LDFLAGS}" AC_ARG_WITH(bzip2, AC_HELP_STRING([--with-bzip2=DIR],[look for bzip2 in DIR]), [ if test -d "$withval" ; then CPPFLAGS="${CPPFLAGS} -I$withval/include" LDFLAGS="${LDFLAGS} -L$withval/lib" fi ],withval="") # Checking alongside stdio.h as an early version of bzip2 (1.0) # required stdio.h to be included before bzlib.h, and Solaris 9 is # woefully out of date. if test "$withval" != no ; then AC_CHECK_HEADER(bzlib.h, AC_CHECK_LIB(bz2,BZ2_bzCompressInit, [ have_bz2=yes ZLIBS="$ZLIBS -lbz2" AC_DEFINE(HAVE_BZIP2,1, [Defined if the bz2 compression library is available]) ], CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}), CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags},[#include ]) fi fi AM_CONDITIONAL(ENABLE_BZIP2_SUPPORT,test x"$have_bz2" = "xyes") AC_SUBST(ZLIBS) # Check for readline support GNUPG_CHECK_READLINE # # Allow users to append something to the version string without # flagging it as development version. The user version parts is # considered everything after a dash. # if test "$development_version" != yes; then changequote(,)dnl tmp_pat='[a-zA-Z]' changequote([,])dnl if echo "$VERSION" | sed 's/-.*//' | grep "$tmp_pat" >/dev/null ; then development_version=yes fi fi if test "$development_version" = yes; then AC_DEFINE(IS_DEVELOPMENT_VERSION,1, [Defined if this is not a regular release]) fi AM_CONDITIONAL(CROSS_COMPILING, test x$cross_compiling = xyes) GNUPG_CHECK_GNUMAKE # Add some extra libs here so that previous tests don't fail for # mysterious reasons - the final link step should bail out. # W32SOCKLIBS is also defined so that if can be used for tools not # requiring any network stuff but linking to code in libcommon which # tracks in winsock stuff (e.g. init_common_subsystems. if test "$have_w32_system" = yes; then W32SOCKLIBS="-lws2_32" NETLIBS="${NETLIBS} ${W32SOCKLIBS}" fi AC_SUBST(NETLIBS) AC_SUBST(W32SOCKLIBS) # # Setup gcc specific options # AC_MSG_NOTICE([checking for cc features]) if test "$GCC" = yes; then # Note that it is okay to use CFLAGS here because this are just # warning options and the user should have a chance of overriding # them. if test "$USE_MAINTAINER_MODE" = "yes"; then CFLAGS="$CFLAGS -O3 -Wall -Wcast-align -Wshadow -Wstrict-prototypes" CFLAGS="$CFLAGS -Wformat -Wno-format-y2k -Wformat-security" AC_MSG_CHECKING([if gcc supports -Wno-missing-field-initializers]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wno-missing-field-initializers" AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_wopt=yes,_gcc_wopt=no) AC_MSG_RESULT($_gcc_wopt) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_wopt" = xyes ; then CFLAGS="$CFLAGS -W -Wno-sign-compare -Wno-missing-field-initializers" fi AC_MSG_CHECKING([if gcc supports -Wdeclaration-after-statement]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wdeclaration-after-statement" AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_wopt=yes,_gcc_wopt=no) AC_MSG_RESULT($_gcc_wopt) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_wopt" = xyes ; then CFLAGS="$CFLAGS -Wdeclaration-after-statement" fi else CFLAGS="$CFLAGS -Wall" fi AC_MSG_CHECKING([if gcc supports -Wno-pointer-sign]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wno-pointer-sign" AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_psign=yes,_gcc_psign=no) AC_MSG_RESULT($_gcc_psign) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_psign" = xyes ; then CFLAGS="$CFLAGS -Wno-pointer-sign" fi AC_MSG_CHECKING([if gcc supports -Wpointer-arith]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wpointer-arith" AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_psign=yes,_gcc_psign=no) AC_MSG_RESULT($_gcc_psign) CFLAGS=$_gcc_cflags_save; if test x"$_gcc_psign" = xyes ; then CFLAGS="$CFLAGS -Wpointer-arith" fi fi # # This is handy for debugging so the compiler doesn't rearrange # things and eliminate variables. # AC_ARG_ENABLE(optimization, AC_HELP_STRING([--disable-optimization], [disable compiler optimization]), [if test $enableval = no ; then CFLAGS=`echo $CFLAGS | sed 's/-O[[0-9]]//'` fi]) # # Prepare building of estream # estream_INIT # # Decide what to build # if test "$have_adns" = "yes"; then AC_SUBST(GPGKEYS_KDNS, "gpg2keys_kdns$EXEEXT") fi missing_pth=no if test $have_ksba = no; then build_gpgsm=no build_scdaemon=no fi build_agent_threaded="" if test "$build_agent" = "yes"; then if test $have_pth = no; then build_agent_threaded="(not multi-threaded)" missing_pth=yes fi fi build_scdaemon_extra="" if test "$build_scdaemon" = "yes"; then tmp="" if test $have_pth = no; then build_scdaemon_extra="not multi-threaded" tmp=", " missing_pth=yes fi if test $have_libusb = no; then build_scdaemon_extra="${tmp}without internal CCID driver" tmp=", " fi if test -n "$build_scdaemon_extra"; then build_scdaemon_extra="(${build_scdaemon_extra})" fi fi if test "$build_agent_only" = "yes" ; then build_gpg=no build_gpgsm=no build_scdaemon=no build_tools=no build_doc=no fi AM_CONDITIONAL(BUILD_GPG, test "$build_gpg" = "yes") AM_CONDITIONAL(BUILD_GPGSM, test "$build_gpgsm" = "yes") AM_CONDITIONAL(BUILD_AGENT, test "$build_agent" = "yes") AM_CONDITIONAL(BUILD_SCDAEMON, test "$build_scdaemon" = "yes") AM_CONDITIONAL(BUILD_G13, test "$build_g13" = "yes") AM_CONDITIONAL(BUILD_TOOLS, test "$build_tools" = "yes") AM_CONDITIONAL(BUILD_DOC, test "$build_doc" = "yes") AM_CONDITIONAL(BUILD_SYMCRYPTRUN, test "$build_symcryptrun" = "yes") AM_CONDITIONAL(RUN_GPG_TESTS, test x$cross_compiling = xno -a "$build_gpg" = yes ) # # Print errors here so that they are visible all # together and the user can acquire them all together. # die=no if test "$have_gpg_error" = "no"; then die=yes AC_MSG_NOTICE([[ *** *** You need libgpg-error to build this program. ** This library is for example available at *** ftp://ftp.gnupg.org/gcrypt/libgpg-error *** (at least version $NEED_GPG_ERROR_VERSION is required.) ***]]) fi if test "$have_libgcrypt" = "no"; then die=yes AC_MSG_NOTICE([[ *** *** You need libgcrypt to build this program. ** This library is for example available at *** ftp://ftp.gnupg.org/gcrypt/libgcrypt/ *** (at least version $NEED_LIBGCRYPT_VERSION using API $NEED_LIBGCRYPT_API is required.) ***]]) fi if test "$have_libassuan" = "no"; then die=yes AC_MSG_NOTICE([[ *** *** You need libassuan to build this program. *** This library is for example available at *** ftp://ftp.gnupg.org/gcrypt/libassuan/ *** (at least version $NEED_LIBASSUAN_VERSION (API $NEED_LIBASSUAN_API) is required). ***]]) fi if test "$have_ksba" = "no"; then AC_MSG_NOTICE([[ *** *** You need libksba to build this program. *** This library is for example available at *** ftp://ftp.gnupg.org/gcrypt/libksba/ *** (at least version $NEED_KSBA_VERSION using API $NEED_KSBA_API is required). ***]]) fi if test "$missing_pth" = "yes"; then AC_MSG_NOTICE([[ *** *** It is now required to build with support for the *** GNU Portable Threads Library (Pth). Please install this *** library first. The library is for example available at *** ftp://ftp.gnu.org/gnu/pth/ *** On a Debian GNU/Linux system you can install it using *** apt-get install libpth-dev *** To build GnuPG for Windows you need to use the W32PTH *** package; available at: *** ftp://ftp.g10code.com/g10code/w32pth/ ***]]) die=yes fi if test "$die" = "yes"; then AC_MSG_ERROR([[ *** *** Required libraries not found. Please consult the above messages *** and install them before running configure again. ***]]) fi AC_CONFIG_FILES([ m4/Makefile Makefile po/Makefile.in gl/Makefile include/Makefile common/Makefile kbx/Makefile g10/Makefile sm/Makefile agent/Makefile scd/Makefile g13/Makefile keyserver/Makefile keyserver/gpg2keys_mailto keyserver/gpg2keys_test tools/gpg-zip tools/Makefile doc/Makefile tests/Makefile tests/openpgp/Makefile tests/pkits/Makefile ]) AC_OUTPUT echo " GnuPG v${VERSION} has been configured as follows: Platform: $PRINTABLE_OS_NAME ($host) OpenPGP: $build_gpg S/MIME: $build_gpgsm Agent: $build_agent $build_agent_threaded Smartcard: $build_scdaemon $build_scdaemon_extra G13: $build_g13 Protect tool: $show_gnupg_protect_tool_pgm Default agent: $show_gnupg_agent_pgm Default pinentry: $show_gnupg_pinentry_pgm Default scdaemon: $show_gnupg_scdaemon_pgm Default dirmngr: $show_gnupg_dirmngr_pgm " if test x"$use_regex" != xyes ; then echo " Warning: No regular expression support available. OpenPGP trust signatures won't work. gpg-check-pattern will not be build. " fi diff --git a/doc/DETAILS b/doc/DETAILS index ae978f2d5..ef8d3cdb3 100644 --- a/doc/DETAILS +++ b/doc/DETAILS @@ -1,1271 +1,1277 @@ -*- text -*- Format of colon listings ======================== First an example: $ gpg --fixed-list-mode --with-colons --list-keys \ --with-fingerprint --with-fingerprint wk@gnupg.org pub:f:1024:17:6C7EE1B8621CC013:899817715:1055898235::m:::scESC: fpr:::::::::ECAF7590EB3443B5C7CF3ACB6C7EE1B8621CC013: uid:f::::::::Werner Koch : uid:f::::::::Werner Koch : sub:f:1536:16:06AD222CADF6A6E1:919537416:1036177416:::::e: fpr:::::::::CF8BCC4B18DE08FCD8A1615906AD222CADF6A6E1: sub:r:1536:20:5CE086B5B5A18FF4:899817788:1025961788:::::esc: fpr:::::::::AB059359A3B81F410FCFF97F5CE086B5B5A18FF4: The double --with-fingerprint prints the fingerprint for the subkeys too. --fixed-list-mode is the modern listing way printing dates in seconds since Epoch and does not merge the first userID with the pub record; gpg2 does this by default and the option is a dummy. 1. Field: Type of record pub = public key crt = X.509 certificate crs = X.509 certificate and private key available sub = subkey (secondary key) sec = secret key ssb = secret subkey (secondary key) uid = user id (only field 10 is used). uat = user attribute (same as user id except for field 10). sig = signature rev = revocation signature fpr = fingerprint: (fingerprint is in field 10) pkd = public key data (special field format, see below) grp = reserved for gpgsm rvk = revocation key tru = trust database information spk = signature subpacket 2. Field: A letter describing the calculated validity. This is a single letter, but be prepared that additional information may follow in some future versions. (not used for secret keys) o = Unknown (this key is new to the system) i = The key is invalid (e.g. due to a missing self-signature) d = The key has been disabled (deprecated - use the 'D' in field 12 instead) r = The key has been revoked e = The key has expired - = Unknown validity (i.e. no value assigned) q = Undefined validity '-' and 'q' may safely be treated as the same value for most purposes n = The key is valid m = The key is marginal valid. f = The key is fully valid u = The key is ultimately valid. This often means that the secret key is available, but any key may be marked as ultimately valid. If the validity information is given for a UID or UAT record, it describes the validity calculated based on this user ID. If given for a key record it describes the best validity taken from the best rated user ID. For X.509 certificates a 'u' is used for a trusted root certificate (i.e. for the trust anchor) and an 'f' for all other valid certificates. 3. Field: length of key in bits. 4. Field: Algorithm: 1 = RSA 16 = Elgamal (encrypt only) 17 = DSA (sometimes called DH, sign only) 20 = Elgamal (sign and encrypt - don't use them!) (for other id's see include/cipher.h) 5. Field: KeyID 6. Field: Creation Date (in UTC). For UID and UAT records, this is the self-signature date. Note that the date is usally printed in seconds since epoch, however, we are migrating to an ISO 8601 format (e.g. "19660205T091500"). This is currently only relevant for X.509. A simple way to detect the new format is to scan for the 'T'. 7. Field: Key or user ID/user attribute expiration date or empty if none. 8. Field: Used for serial number in crt records (used to be the Local-ID). For UID and UAT records, this is a hash of the user ID contents used to represent that exact user ID. For trust signatures, this is the trust depth seperated by the trust value by a space. 9. Field: Ownertrust (primary public keys only) This is a single letter, but be prepared that additional information may follow in some future versions. For trust signatures with a regular expression, this is the regular expression value, quoted as in field 10. 10. Field: User-ID. The value is quoted like a C string to avoid control characters (the colon is quoted "\x3a"). For a "pub" record this field is not used on --fixed-list-mode. A UAT record puts the attribute subpacket count here, a space, and then the total attribute subpacket size. In gpgsm the issuer name comes here An FPR record stores the fingerprint here. The fingerprint of an revocation key is stored here. 11. Field: Signature class as per RFC-4880. This is a 2 digit hexnumber followed by either the letter 'x' for an exportable signature or the letter 'l' for a local-only signature. The class byte of an revocation key is also given here, 'x' and 'l' is used the same way. IT is not used for X.509. 12. Field: Key capabilities: e = encrypt s = sign c = certify a = authentication A key may have any combination of them in any order. In addition to these letters, the primary key has uppercase versions of the letters to denote the _usable_ capabilities of the entire key, and a potential letter 'D' to indicate a disabled key. 13. Field: Used in FPR records for S/MIME keys to store the fingerprint of the issuer certificate. This is useful to build the certificate path based on certificates stored in the local keyDB; it is only filled if the issuer certificate is available. The root has been reached if this is the same string as the fingerprint. The advantage of using this value is that it is guaranteed to have been been build by the same lookup algorithm as gpgsm uses. For "uid" records this lists the preferences in the same way the gpg's --edit-key menu does. For "sig" records, this is the fingerprint of the key that issued the signature. Note that this is only filled in if the signature verified correctly. Note also that for various technical reasons, this fingerprint is only available if --no-sig-cache is used. 14. Field Flag field used in the --edit menu output: 15. Field Used in sec/sbb to print the serial number of a token (internal protect mode 1002) or a '#' if that key is a simple stub (internal protect mode 1001) All dates are displayed in the format yyyy-mm-dd unless you use the option --fixed-list-mode in which case they are displayed as seconds since Epoch. More fields may be added later, so parsers should be prepared for this. When parsing a number the parser should stop at the first non-number character so that additional information can later be added. If field 1 has the tag "pkd", a listing looks like this: pkd:0:1024:B665B1435F4C2 .... FF26ABB: ! ! !-- the value ! !------ for information number of bits in the value !--------- index (eg. DSA goes from 0 to 3: p,q,g,y) Example for a "tru" trust base record: tru:o:0:1166697654:1:3:1:5 The fields are: 2: Reason for staleness of trust. If this field is empty, then the trustdb is not stale. This field may have multiple flags in it: o: Trustdb is old t: Trustdb was built with a different trust model than the one we are using now. 3: Trust model: 0: Classic trust model, as used in PGP 2.x. 1: PGP trust model, as used in PGP 6 and later. This is the same as the classic trust model, except for the addition of trust signatures. GnuPG before version 1.4 used the classic trust model by default. GnuPG 1.4 and later uses the PGP trust model by default. 4: Date trustdb was created in seconds since 1970-01-01. 5: Date trustdb will expire in seconds since 1970-01-01. 6: Number of marginally trusted users to introduce a new key signer (gpg's option --marginals-needed) 7: Number of completely trusted users to introduce a new key signer. (gpg's option --completes-needed) 8: Maximum depth of a certification chain. *gpg's option --max-cert-depth) The "spk" signature subpacket records have the fields: 2: Subpacket number as per RFC-4880 and later. 3: Flags in hex. Currently the only two bits assigned are 1, to indicate that the subpacket came from the hashed part of the signature, and 2, to indicate the subpacket was marked critical. 4: Length of the subpacket. Note that this is the length of the subpacket, and not the length of field 5 below. Due to the need for %-encoding, the length of field 5 may be up to 3x this value. 5: The subpacket data. Printable ASCII is shown as ASCII, but other values are rendered as %XX where XX is the hex value for the byte. Format of the "--status-fd" output ================================== Every line is prefixed with "[GNUPG:] ", followed by a keyword with the type of the status line and a some arguments depending on the type (maybe none); an application should always be prepared to see more arguments in future versions. NEWSIG May be issued right before a signature verification starts. This is useful to define a context for parsing ERROR status messages. No arguments are currently defined. GOODSIG The signature with the keyid is good. For each signature only one of the codes GOODSIG, BADSIG, EXPSIG, EXPKEYSIG, REVKEYSIG or ERRSIG will be emitted. In the past they were used as a marker for a new signature; new code should use the NEWSIG status instead. The username is the primary one encoded in UTF-8 and %XX escaped. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. EXPSIG The signature with the keyid is good, but the signature is expired. The username is the primary one encoded in UTF-8 and %XX escaped. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. EXPKEYSIG The signature with the keyid is good, but the signature was made by an expired key. The username is the primary one encoded in UTF-8 and %XX escaped. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. REVKEYSIG The signature with the keyid is good, but the signature was made by a revoked key. The username is the primary one encoded in UTF-8 and %XX escaped. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. BADSIG The signature with the keyid has not been verified okay. The username is the primary one encoded in UTF-8 and %XX escaped. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. ERRSIG \ It was not possible to check the signature. This may be caused by a missing public key or an unsupported algorithm. A RC of 4 indicates unknown algorithm, a 9 indicates a missing public key. The other fields give more information about this signature. sig_class is a 2 byte hex-value. The fingerprint may be used instead of the long keyid if it is available. This is the case with CMS and might eventually also be available for OpenPGP. Note, that TIMESTAMP may either be a number with seconds since epoch or an ISO 8601 string which can be detected by the presence of the letter 'T' inside. VALIDSIG [ ] The signature with the keyid is good. This is the same as GOODSIG but has the fingerprint as the argument. Both status lines are emitted for a good signature. All arguments here are on one long line. sig-timestamp is the signature creation time in seconds after the epoch. expire-timestamp is the signature expiration time in seconds after the epoch (zero means "does not expire"). sig-version, pubkey-algo, hash-algo, and sig-class (a 2-byte hex value) are all straight from the signature packet. PRIMARY-KEY-FPR is the fingerprint of the primary key or identical to the first argument. This is useful to get back to the primary key without running gpg again for this purpose. The primary-key-fpr parameter is used for OpenPGP and not available for CMS signatures. The sig-version as well as the sig class is not defined for CMS and currently set to 0 and 00. Note, that *-TIMESTAMP may either be a number with seconds since epoch or an ISO 8601 string which can be detected by the presence of the letter 'T' inside. SIG_ID This is emitted only for signatures of class 0 or 1 which have been verified okay. The string is a signature id and may be used in applications to detect replay attacks of signed messages. Note that only DLP algorithms give unique ids - others may yield duplicated ones when they have been created in the same second. Note, that SIG-TIMESTAMP may either be a number with seconds since epoch or an ISO 8601 string which can be detected by the presence of the letter 'T' inside. ENC_TO The message is encrypted to this LONG_KEYID. KEYTYPE is the numerical value of the public key algorithm or 0 if it is not known, KEYLENGTH is the length of the key or 0 if it is not known (which is currently always the case). Gpg prints this line always; Gpgsm only if it knows the certificate. NODATA No data has been found. Codes for what are: 1 - No armored data. 2 - Expected a packet but did not found one. 3 - Invalid packet found, this may indicate a non OpenPGP message. 4 - signature expected but not found You may see more than one of these status lines. UNEXPECTED Unexpected data has been encountered 0 - not further specified 1 TRUST_UNDEFINED TRUST_NEVER TRUST_MARGINAL [0 []] TRUST_FULLY [0 []] TRUST_ULTIMATE [0 []] For good signatures one of these status lines are emitted to indicate the validity of the key used to create the signature. The error token values are currently only emitted by gpgsm. VALIDATION_MODEL describes the algorithm used to check the validity of the key. The defaults are the standard Web of Trust model for gpg and the the standard X.509 model for gpgsm. The defined values are "pgp" for the standard PGP WoT. "shell" for the standard X.509 model. "chain" for the chain model. Note that we use the term "TRUST_" in the status names for historic reasons; we now speak of validity. PKA_TRUST_GOOD PKA_TRUST_BAD Depending on the outcome of the PKA check one of the above status codes is emitted in addition to a TRUST_* status. Without PKA info available or SIGEXPIRED This is deprecated in favor of KEYEXPIRED. KEYEXPIRED The key has expired. expire-timestamp is the expiration time in seconds since Epoch. This status line is not very useful because it will also be emitted for expired subkeys even if this subkey is not used. To check whether a key used to sign a message has expired, the EXPKEYSIG status line is to be used. Note, that TIMESTAMP may either be a number with seconds since epoch or an ISO 8601 string which can be detected by the presence of the letter 'T' inside. KEYREVOKED The used key has been revoked by its owner. No arguments yet. BADARMOR The ASCII armor is corrupted. No arguments yet. RSA_OR_IDEA The IDEA algorithms has been used in the data. A program might want to fallback to another program to handle the data if GnuPG failed. This status message used to be emitted also for RSA but this has been dropped after the RSA patent expired. However we can't change the name of the message. SHM_INFO SHM_GET SHM_GET_BOOL SHM_GET_HIDDEN GET_BOOL GET_LINE GET_HIDDEN GOT_IT NEED_PASSPHRASE Issued whenever a passphrase is needed. keytype is the numerical value of the public key algorithm or 0 if this is not applicable, keylength is the length of the key or 0 if it is not known (this is currently always the case). NEED_PASSPHRASE_SYM Issued whenever a passphrase for symmetric encryption is needed. NEED_PASSPHRASE_PIN [] Issued whenever a PIN is requested to unlock a card. MISSING_PASSPHRASE No passphrase was supplied. An application which encounters this message may want to stop parsing immediately because the next message will probably be a BAD_PASSPHRASE. However, if the application is a wrapper around the key edit menu functionality it might not make sense to stop parsing but simply ignoring the following BAD_PASSPHRASE. BAD_PASSPHRASE The supplied passphrase was wrong or not given. In the latter case you may have seen a MISSING_PASSPHRASE. GOOD_PASSPHRASE The supplied passphrase was good and the secret key material is therefore usable. DECRYPTION_FAILED The symmetric decryption failed - one reason could be a wrong passphrase for a symmetrical encrypted message. DECRYPTION_OKAY The decryption process succeeded. This means, that either the correct secret key has been used or the correct passphrase for a conventional encrypted message was given. The program itself may return an errorcode because it may not be possible to verify a signature for some reasons. NO_PUBKEY NO_SECKEY The key is not available IMPORT_CHECK This status is emitted in interactive mode right before the "import.okay" prompt. IMPORTED The keyid and name of the signature just imported IMPORT_OK [] The key with the primary key's FINGERPRINT has been imported. Reason flags: 0 := Not actually changed 1 := Entirely new key. 2 := New user IDs 4 := New signatures 8 := New subkeys 16 := Contains private key. The flags may be ORed. IMPORT_PROBLEM [] Issued for each import failure. Reason codes are: 0 := "No specific reason given". 1 := "Invalid Certificate". 2 := "Issuer Certificate missing". 3 := "Certificate Chain too long". 4 := "Error storing certificate". IMPORT_RES Final statistics on import process (this is one long line) FILE_START Start processing a file . indicates the performed operation: 1 - verify 2 - encrypt 3 - decrypt FILE_DONE Marks the end of a file processing which has been started by FILE_START. BEGIN_DECRYPTION END_DECRYPTION Mark the start and end of the actual decryption process. These are also emitted when in --list-only mode. BEGIN_ENCRYPTION END_ENCRYPTION Mark the start and end of the actual encryption process. BEGIN_SIGNING Mark the start of the actual signing process. This may be used as an indication that all requested secret keys are ready for use. DELETE_PROBLEM reason_code Deleting a key failed. Reason codes are: 1 - No such key 2 - Must delete secret key first 3 - Ambigious specification PROGRESS what char cur total Used by the primegen and Public key functions to indicate progress. "char" is the character displayed with no --status-fd enabled, with the linefeed replaced by an 'X'. "cur" is the current amount done and "total" is amount to be done; a "total" of 0 indicates that the total amount is not known. The condition TOATL && CUR == TOTAL may be used to detect the end of an operation. Well known values for WHAT: "pk_dsa" - DSA key generation "pk_elg" - Elgamal key generation "primegen" - Prime generation "need_entropy" - Waiting for new entropy in the RNG "file:XXX" - processing file XXX (note that current gpg versions leave out the "file:" prefix). "tick" - generic tick without any special meaning - useful for letting clients know that the server is still working. "starting_agent" - A gpg-agent was started because it is not running as a daemon. "learncard" Send by the agent and gpgsm while learing the data of a smartcard. "card_busy" A smartcard is still working SIG_CREATED A signature has been created using these parameters. type: 'D' = detached 'C' = cleartext 'S' = standard (only the first character should be checked) class: 2 hex digits with the signature class Note, that TIMESTAMP may either be a number with seconds since epoch or an ISO 8601 string which can be detected by the presence of the letter 'T' inside. KEY_CREATED [] A key has been created type: 'B' = primary and subkey 'P' = primary 'S' = subkey The fingerprint is one of the primary key for type B and P and the one of the subkey for S. Handle is an arbitrary non-whitespace string used to match key parameters from batch key creation run. KEY_NOT_CREATED [] The key from batch run has not been created due to errors. SESSION_KEY : The session key used to decrypt the message. This message will only be emitted when the special option --show-session-key is used. The format is suitable to be passed to the option --override-session-key NOTATION_NAME NOTATION_DATA name and string are %XX escaped; the data may be split among several NOTATION_DATA lines. USERID_HINT Give a hint about the user ID for a certain keyID. POLICY_URL string is %XX escaped BEGIN_STREAM END_STREAM Issued by pipemode. INV_RECP INV_SGNR Issued for each unusable recipient/sender. The reasons codes currently in use are: 0 := "No specific reason given". 1 := "Not Found" 2 := "Ambigious specification" 3 := "Wrong key usage" 4 := "Key revoked" 5 := "Key expired" 6 := "No CRL known" 7 := "CRL too old" 8 := "Policy mismatch" 9 := "Not a secret key" 10 := "Key not trusted" 11 := "Missing certificate" (e.g. intermediate or root cert.) Note that for historical reasons the INV_RECP status is also used for gpgsm's SIGNER command where it relates to signer's of course. Newer GnuPG versions are using INV_SGNR; applications should ignore the INV_RECP during the sender's command processing once they have seen an INV_SGNR. We use different code so that we can distinguish them while doing an encrypt+sign. NO_RECP NO_SGNR Issued when no recipients/senders are usable. ALREADY_SIGNED Warning: This is experimental and might be removed at any time. TRUNCATED The output was truncated to MAXNO items. This status code is issued for certain external requests ERROR [] This is a generic error status message, it might be followed by error location specific data. and should not contain spaces. The error code is a either a string commencing with a letter or such a string prefixed with a numerical error code and an underscore; e.g.: "151011327_EOF". + SUCCESS [] + Postive confirimation that an operation succeeded. + is optional but if given should not contain spaces. + Used only with a few commands. + + ATTRIBUTE This is one long line issued for each attribute subpacket when an attribute packet is seen during key listing. is the fingerprint of the key. is the length of the attribute subpacket. is the attribute type (1==image). / indicates that this is the Nth indexed subpacket of count total subpackets in this attribute packet. and are from the self-signature on the attribute packet. If the attribute packet does not have a valid self-signature, then the timestamp is 0. are a bitwise OR of: 0x01 = this attribute packet is a primary uid 0x02 = this attribute packet is revoked 0x04 = this attribute packet is expired CARDCTRL [] This is used to control smartcard operations. Defined values for WHAT are: 1 = Request insertion of a card. Serialnumber may be given to request a specific card. Used by gpg 1.4 w/o scdaemon. 2 = Request removal of a card. Used by gpg 1.4 w/o scdaemon. 3 = Card with serialnumber detected 4 = No card available. 5 = No card reader available 6 = No card support available PLAINTEXT This indicates the format of the plaintext that is about to be written. The format is a 1 byte hex code that shows the format of the plaintext: 62 ('b') is binary data, 74 ('t') is text data with no character set specified, and 75 ('u') is text data encoded in the UTF-8 character set. The timestamp is in seconds since the epoch. If a filename is available it gets printed as the third argument, percent-escaped as usual. PLAINTEXT_LENGTH This indicates the length of the plaintext that is about to be written. Note that if the plaintext packet has partial length encoding it is not possible to know the length ahead of time. In that case, this status tag does not appear. SIG_SUBPACKET This indicates that a signature subpacket was seen. The format is the same as the "spk" record above. SC_OP_FAILURE [] An operation on a smartcard definitely failed. Currently there is no indication of the actual error code, but application should be prepared to later accept more arguments. Defined values for CODE are: 0 - unspecified error (identically to a missing CODE) 1 - canceled 2 - bad PIN SC_OP_SUCCESS A smart card operaion succeeded. This status is only printed for certain operation and is mostly useful to check whether a PIN change really worked. BACKUP_KEY_CREATED fingerprint fname A backup key named FNAME has been created for the key with KEYID. MOUNTPOINT NAME is a percent-plus escaped filename describing the mountpoint for the current operation (e.g. g13 --mount). This may either be the specified mountpoint or one randomly choosen by g13. Format of the "--attribute-fd" output ===================================== When --attribute-fd is set, during key listings (--list-keys, --list-secret-keys) GnuPG dumps each attribute packet to the file descriptor specified. --attribute-fd is intended for use with --status-fd as part of the required information is carried on the ATTRIBUTE status tag (see above). The contents of the attribute data is specified by RFC 4880. For convenience, here is the Photo ID format, as it is currently the only attribute defined: Byte 0-1: The length of the image header. Due to a historical accident (i.e. oops!) back in the NAI PGP days, this is a little-endian number. Currently 16 (0x10 0x00). Byte 2: The image header version. Currently 0x01. Byte 3: Encoding format. 0x01 == JPEG. Byte 4-15: Reserved, and currently unused. All other data after this header is raw image (JPEG) data. Format of the "--list-config" output ==================================== --list-config outputs information about the GnuPG configuration for the benefit of frontends or other programs that call GnuPG. There are several list-config items, all colon delimited like the rest of the --with-colons output. The first field is always "cfg" to indicate configuration information. The second field is one of (with examples): version: the third field contains the version of GnuPG. cfg:version:1.3.5 pubkey: the third field contains the public key algorithmdcaiphers this version of GnuPG supports, separated by semicolons. The algorithm numbers are as specified in RFC-4880. Note that in contrast to the --status-fd interface these are _not_ the Libgcrypt identifiers. cfg:pubkey:1;2;3;16;17 cipher: the third field contains the symmetric ciphers this version of GnuPG supports, separated by semicolons. The cipher numbers are as specified in RFC-4880. cfg:cipher:2;3;4;7;8;9;10 digest: the third field contains the digest (hash) algorithms this version of GnuPG supports, separated by semicolons. The digest numbers are as specified in RFC-4880. cfg:digest:1;2;3;8;9;10 compress: the third field contains the compression algorithms this version of GnuPG supports, separated by semicolons. The algorithm numbers are as specified in RFC-4880. cfg:compress:0;1;2;3 group: the third field contains the name of the group, and the fourth field contains the values that the group expands to, separated by semicolons. For example, a group of: group mynames = paige 0x12345678 joe patti would result in: cfg:group:mynames:patti;joe;0x12345678;paige Key generation ============== See the Libcrypt manual. Unattended key generation ========================= This feature allows unattended generation of keys controlled by a parameter file. To use this feature, you use --gen-key together with --batch and feed the parameters either from stdin or from a file given on the commandline. The format of this file is as follows: o Text only, line length is limited to about 1000 chars. o You must use UTF-8 encoding to specify non-ascii characters. o Empty lines are ignored. o Leading and trailing spaces are ignored. o A hash sign as the first non white space character indicates a comment line. o Control statements are indicated by a leading percent sign, the arguments are separated by white space from the keyword. o Parameters are specified by a keyword, followed by a colon. Arguments are separated by white space. o The first parameter must be "Key-Type", control statements may be placed anywhere. o Key generation takes place when either the end of the parameter file is reached, the next "Key-Type" parameter is encountered or at the control statement "%commit" o Control statements: %echo Print . %dry-run Suppress actual key generation (useful for syntax checking). %commit Perform the key generation. An implicit commit is done at the next "Key-Type" parameter. %pubring %secring Do not write the key to the default or commandline given keyring but to . This must be given before the first commit to take place, duplicate specification of the same filename is ignored, the last filename before a commit is used. The filename is used until a new filename is used (at commit points) and all keys are written to that file. If a new filename is given, this file is created (and overwrites an existing one). Both control statements must be given. %ask-passphrase Enable a mode where the command "passphrase" is ignored and instead the usual passphrase dialog is used. This does not make sense for batch key generation; however the unattended key generation feature is also used by GUIs and this feature relinquishes the GUI from implementing its own passphrase entry code. This is a global option. %no-ask-passphrase Disable the ask-passphrase mode. o The order of the parameters does not matter except for "Key-Type" which must be the first parameter. The parameters are only for the generated keyblock and parameters from previous key generations are not used. Some syntactically checks may be performed. The currently defined parameters are: Key-Type: | Starts a new parameter block by giving the type of the primary key. The algorithm must be capable of signing. This is a required parameter. It may be "default" to use the default one; in this case don't give a Key-Usage and use "default" for the Subkey-Type. Key-Length: Length of the key in bits. The default is returned by running the command "gpg --gpgconf-list". Key-Usage: Space or comma delimited list of key usage, allowed values are "encrypt", "sign", and "auth". This is used to generate the key flags. Please make sure that the algorithm is capable of this usage. Note that OpenPGP requires that all primary keys are capable of certification, so no matter what usage is given here, the "cert" flag will be on. If no Key-Usage is specified and the key-type is not "default", all allowed usages for that particular algorithm are used; if it is not given but "default" is used the usage will be "sign". Subkey-Type: | This generates a secondary key. Currently only one subkey can be handled. "default" is also supported. Subkey-Length: Length of the subkey in bits. The default is returned by running the command "gpg --gpgconf-list". Subkey-Usage: Similar to Key-Usage. Passphrase: If you want to specify a passphrase for the secret key, enter it here. Default is not to use any passphrase. Name-Real: Name-Comment: Name-Email: The 3 parts of a key. Remember to use UTF-8 here. If you don't give any of them, no user ID is created. Expire-Date: |([d|w|m|y]) Set the expiration date for the key (and the subkey). It may either be entered in ISO date format (2000-08-15) or as number of days, weeks, month or years. The special notation "seconds=N" is also allowed to directly give an Epoch value. Without a letter days are assumed. Note that there is no check done on the overflow of the type used by OpenPGP for timestamps. Thus you better make sure that the given value make sense. Although OpenPGP works with time intervals, GnuPG uses an absolute value internally and thus the last year we can represent is 2105. Creation-Date: Set the creation date of the key as stored in the key information and which is also part of the fingerprint calculation. Either a date like "1986-04-26" or a full timestamp like "19860426T042640" may be used. The time is considered to be UTC. If it is not given the current time is used. Preferences: Set the cipher, hash, and compression preference values for this key. This expects the same type of string as "setpref" in the --edit menu. Revoker: : [sensitive] Add a designated revoker to the generated key. Algo is the public key algorithm of the designated revoker (i.e. RSA=1, DSA=17, etc.) Fpr is the fingerprint of the designated revoker. The optional "sensitive" flag marks the designated revoker as sensitive information. Only v4 keys may be designated revokers. Handle: This is an optional parameter only used with the status lines KEY_CREATED and KEY_NOT_CREATED. STRING may be up to 100 characters and should not contain spaces. It is useful for batch key generation to associate a key parameter block with a status line. Keyserver: This is an optional parameter that specifies the preferred keyserver URL for the key. Here is an example on how to create a key: $ cat >foo < ssb 1024g/8F70E2C0 2000-03-09 If you want to create a key with the default algorithms you would use these parameters: %echo Generating a default key Key-Type: default Subkey-Type: default Name-Real: Joe Tester Name-Comment: with stupid passphrase Name-Email: joe@foo.bar Expire-Date: 0 Passphrase: abc %pubring foo.pub %secring foo.sec # Do a commit here, so that we can later print "done" :-) %commit %echo done Layout of the TrustDB ===================== The TrustDB is built from fixed length records, where the first byte describes the record type. All numeric values are stored in network byte order. The length of each record is 40 bytes. The first record of the DB is always of type 1 and this is the only record of this type. FIXME: The layout changed, document it here. Record type 0: -------------- Unused record, can be reused for any purpose. Record type 1: -------------- Version information for this TrustDB. This is always the first record of the DB and the only one with type 1. 1 byte value 1 3 bytes 'gpg' magic value 1 byte Version of the TrustDB (2) 1 byte marginals needed 1 byte completes needed 1 byte max_cert_depth The three items are used to check whether the cached validity value from the dir record can be used. 1 u32 locked flags [not used] 1 u32 timestamp of trustdb creation 1 u32 timestamp of last modification which may affect the validity of keys in the trustdb. This value is checked against the validity timestamp in the dir records. 1 u32 timestamp of last validation [currently not used] (Used to keep track of the time, when this TrustDB was checked against the pubring) 1 u32 record number of keyhashtable [currently not used] 1 u32 first free record 1 u32 record number of shadow directory hash table [currently not used] It does not make sense to combine this table with the key table because the keyid is not in every case a part of the fingerprint. 1 u32 record number of the trusthashtbale Record type 2: (directory record) -------------- Informations about a public key certificate. These are static values which are never changed without user interaction. 1 byte value 2 1 byte reserved 1 u32 LID . (This is simply the record number of this record.) 1 u32 List of key-records (the first one is the primary key) 1 u32 List of uid-records 1 u32 cache record 1 byte ownertrust 1 byte dirflag 1 byte maximum validity of all the user ids 1 u32 time of last validity check. 1 u32 Must check when this time has been reached. (0 = no check required) Record type 3: (key record) -------------- Informations about a primary public key. (This is mainly used to lookup a trust record) 1 byte value 3 1 byte reserved 1 u32 LID 1 u32 next - next key record 7 bytes reserved 1 byte keyflags 1 byte pubkey algorithm 1 byte length of the fingerprint (in bytes) 20 bytes fingerprint of the public key (This is the value we use to identify a key) Record type 4: (uid record) -------------- Informations about a userid We do not store the userid but the hash value of the userid because that is sufficient. 1 byte value 4 1 byte reserved 1 u32 LID points to the directory record. 1 u32 next next userid 1 u32 pointer to preference record 1 u32 siglist list of valid signatures 1 byte uidflags 1 byte validity of the key calculated over this user id 20 bytes ripemd160 hash of the username. Record type 5: (pref record) -------------- This record type is not anymore used. 1 byte value 5 1 byte reserved 1 u32 LID; points to the directory record (and not to the uid record!). (or 0 for standard preference record) 1 u32 next 30 byte preference data Record type 6 (sigrec) ------------- Used to keep track of key signatures. Self-signatures are not stored. If a public key is not in the DB, the signature points to a shadow dir record, which in turn has a list of records which might be interested in this key (and the signature record here is one). 1 byte value 6 1 byte reserved 1 u32 LID points back to the dir record 1 u32 next next sigrec of this uid or 0 to indicate the last sigrec. 6 times 1 u32 Local_id of signatures dir or shadow dir record 1 byte Flag: Bit 0 = checked: Bit 1 is valid (we have a real directory record for this) 1 = valid is set (but may be revoked) Record type 8: (shadow directory record) -------------- This record is used to reserve a LID for a public key. We need this to create the sig records of other keys, even if we do not yet have the public key of the signature. This record (the record number to be more precise) will be reused as the dir record when we import the real public key. 1 byte value 8 1 byte reserved 1 u32 LID (This is simply the record number of this record.) 2 u32 keyid 1 byte pubkey algorithm 3 byte reserved 1 u32 hintlist A list of records which have references to this key. This is used for fast access to signature records which are not yet checked. Note, that this is only a hint and the actual records may not anymore hold signature records for that key but that the code cares about this. 18 byte reserved Record Type 10 (hash table) -------------- Due to the fact that we use fingerprints to lookup keys, we can implement quick access by some simple hash methods, and avoid the overhead of gdbm. A property of fingerprints is that they can be used directly as hash values. (They can be considered as strong random numbers.) What we use is a dynamic multilevel architecture, which combines hashtables, record lists, and linked lists. This record is a hashtable of 256 entries; a special property is that all these records are stored consecutively to make one big table. The hash value is simple the 1st, 2nd, ... byte of the fingerprint (depending on the indirection level). When used to hash shadow directory records, a different table is used and indexed by the keyid. 1 byte value 10 1 byte reserved n u32 recnum; n depends on the record length: n = (reclen-2)/4 which yields 9 for the current record length of 40 bytes. the total number of such record which makes up the table is: m = (256+n-1) / n which is 29 for a record length of 40. To look up a key we use the first byte of the fingerprint to get the recnum from this hashtable and look up the addressed record: - If this record is another hashtable, we use 2nd byte to index this hash table and so on. - if this record is a hashlist, we walk all entries until we found one a matching one. - if this record is a key record, we compare the fingerprint and to decide whether it is the requested key; Record type 11 (hash list) -------------- see hash table for an explanation. This is also used for other purposes. 1 byte value 11 1 byte reserved 1 u32 next next hash list record n times n = (reclen-5)/5 1 u32 recnum For the current record length of 40, n is 7 Record type 254 (free record) --------------- All these records form a linked list of unused records. 1 byte value 254 1 byte reserved (0) 1 u32 next_free GNU extensions to the S2K algorithm =================================== S2K mode 101 is used to identify these extensions. After the hash algorithm the 3 bytes "GNU" are used to make clear that these are extensions for GNU, the next bytes gives the GNU protection mode - 1000. Defined modes are: 1001 - do not store the secret part at all 1002 - a stub to access smartcards (not used in 1.2.x) Other Notes =========== * For packet version 3 we calculate the keyids this way: RSA := low 64 bits of n ELGAMAL := build a v3 pubkey packet (with CTB 0x99) and calculate a rmd160 hash value from it. This is used as the fingerprint and the low 64 bits are the keyid. * Revocation certificates consist only of the signature packet; "import" knows how to handle this. The rationale behind it is to keep them small. OIDs below the GnuPG arc: ========================= 1.3.6.1.4.1.11591.2 GnuPG 1.3.6.1.4.1.11591.2.1 notation 1.3.6.1.4.1.11591.2.1.1 pkaAddress 1.3.6.1.4.1.11591.2.12242973 invalid encoded OID Keyserver Message Format ========================= The keyserver may be contacted by a Unix Domain socket or via TCP. The format of a request is: ==== command-tag "Content-length:" digits CRLF ======= Where command-tag is NOOP GET PUT DELETE The format of a response is: ====== "GNUPG/1.0" status-code status-text "Content-length:" digits CRLF ============ followed by bytes of data Status codes are: o 1xx: Informational - Request received, continuing process o 2xx: Success - The action was successfully received, understood, and accepted o 4xx: Client Error - The request contains bad syntax or cannot be fulfilled o 5xx: Server Error - The server failed to fulfill an apparently valid request Documentation on HKP (the http keyserver protocol): A minimalistic HTTP server on port 11371 recognizes a GET for /pks/lookup. The standard http URL encoded query parameters are this (always key=value): - op=index (like pgp -kv), op=vindex (like pgp -kvv) and op=get (like pgp -kxa) - search=. This is a list of words that must occur in the key. The words are delimited with space, points, @ and so on. The delimiters are not searched for and the order of the words doesn't matter (but see next option). - exact=on. This switch tells the hkp server to only report exact matching keys back. In this case the order and the "delimiters" are important. - fingerprint=on. Also reports the fingerprints when used with 'index' or 'vindex' The keyserver also recognizes http-POSTs to /pks/add. Use this to upload keys. A better way to do this would be a request like: /pks/lookup/?op= This can be implemented using Hurd's translator mechanism. However, I think the whole key server stuff has to be re-thought; I have some ideas and probably create a white paper. diff --git a/g10/ChangeLog b/g10/ChangeLog index 878627c12..dbb913e6e 100644 --- a/g10/ChangeLog +++ b/g10/ChangeLog @@ -1,11100 +1,11134 @@ +2010-03-15 Werner Koch + + * card-util.c: Replace stdio by estream. + * keylist.c: Ditto. + +2010-03-12 Werner Koch + + * plaintext.c (setup_plaintext_name): Do not encode pipe like + filenames. This helps with bug#1201. + + * seckey-cert.c (do_check): Return GPG_ERR_CANCELED. + * keyedit.c (change_passphrase): Add arg R_ERR. + (keyedit_passwd): Return the correct error or emit a success + status message. + 2010-03-11 Werner Koch + * misc.c (mpi_print): Change to take a estream_t arg. + + * parse-packet.c (listfp): Change to an estream_t. Change all + users to use estream functions. + + * kbnode.c (dump_kbnode): Change to use log functions. + * pkclist.c (do_show_revocation_reason): Ditto + + * armor.c (parse_header_line): Replace print_string by + es_print_sanitized. + (fake_packet): Ditto. + * keyedit.c (print_and_check_one_sig_colon): Ditto. + (show_key_with_all_names_colon): Ditto. + (ask_revoke_sig): Ditto. + * keylist.c (list_keyblock_colon): Ditto. + * mainproc.c (print_userid, list_node): Ditto. + * trustdb.c (dump_key_array): Ditto. + * gpg.c (list_config): ditto. + * gpg.c: Include "asshelp.h". (main): Remove assuan_set_assuan_log_prefix. Add assuan_set_log_cb. * server.c (gpg_server): Remove assuan_set_log_stream. 2010-03-10 Werner Koch * Makefile.am (needed_libs): Remove libjnlib.a. * main.h: Remove "estream.h". 2010-03-08 Werner Koch * main.h: Include "estream.h" * openfile.c (open_outfile): Replace dup/iobuf_fdopen by iobuf_fdopen_nc. * mainproc.c (proc_signature_packets_by_fd): Return error on memory failure. * plaintext.c (hash_datafile_by_fd): Ditto. * verify.c (gpg_verify): Use iobuf_fdopen_nc. Change OUT_FP to an estream_t. * server.c (cmd_verify): Do not dup the fds. Use macros for iobuf_ioctl commands. 2010-02-17 Werner Koch * keygen.c (ask_user_id): Avoid infinite loop in case of invalid data. Fixes bug#1186. 2010-02-02 Werner Koch * keyedit.c (keyedit_menu): Change prompt to "gpg". * card-util.c (card_edit): Change prompt to "gpg/card". 2010-01-11 Werner Koch * sign.c (only_old_style, write_onepass_sig_packets, hash_for) (write_signature_packets, print_status_sig_created) (clearsign_file, make_keysig_packet, mk_notation_policy_etc) (complete_sig, do_sign, update_keysig_packet): Replace all secret key access by the matching public key. * keylist.c (print_seckey_info): Ditto. * revoke.c (gen_desig_revoke): Ditto. * skclist.c (release_sk_list): Ditto. * keyedit.c (sign_uids): Ditto. * misc.c (get_signature_count): Ditto. * main.h (struct expand_args): s/sk/pksk/. Change all users. * keyedit.c (keyedit_passwd): Finish implementation. 2010-01-10 Werner Koch * skclist.c (GCRYCTL_FAKED_RANDOM_P): Remove because we require libgcrypt 1.4. (is_insecure, key_present_in_sk_list): Work with public keys. (build_sk_list): Change to work on public keys. * keydb.h (struct sk_list): Replace field SK by a PK field. * keylist.c (list_keyblock_print): Always look for the public key and ignore all secret key packets. (list_keyblock_colon): Ditto. (print_capabilities): Remove arg SK and all secret key stuff. Adjust all callers. (dump_attribs): Ditto. * getkey.c (getkey_bynames, getkey_next, get_pubkey_end): New. (getkey_byname): New. (getkey_ctx_s): Add WANT_SECRET. (key_byname): Set it. (merge_keys_and_selfsig): Remove all the secret key merging. (lookup): Simplify by removing secret key code. * keylist.c (list_all): Scan public keys and use have_secret_key to filter secret keys. (list_one): Use the new get_key functions. * gpg.h (kbnode_t): Add as alias for KBNODE. * keydb.h (getkey_ctx_t): Add as alias for GETKEY_CTX. 2010-01-09 Werner Koch * getkey.c, keylist.c: Re-indent. 2010-01-08 Werner Koch * cpr.c (write_status_error): Rename to write_status_errcode. Change all callers. (write_status_error): New. * gpg.c: Add option --passwd. (aPasswd): New. (main): Implement. * keyedit.c (keyedit_passwd): New. * gpg.c (oPasswd, oPasswdFD, oPasswdFile, oPasswdRepeat): Change to oPassphrase, oPassphraseFD, oPassphraseFile, oPassphraseRepeat. * options.h (struct): s/passwd_repeat/passphrase_repeat/. * gpg.c (main): Ditto. * passphrase.c (passphrase_to_dek_ext): Ditto. 2009-12-21 Werner Koch * call-agent.c (agent_get_s2k_count): New. * gpg.c (main): Set s2k_count to 0. * (encode_s2k_iterations): Move ... * passphrase.c (encode_s2k_iterations): ... here. Call agent_get_s2k_count if called with a 0 arg. (passphrase_to_dek_ext): Set S2K_COUNT via encode_s2k_iterations. 2009-12-17 Werner Koch * sig-check.c (do_check_messages): Evaluate the HAS_EXPIRED flag. Fixes bug#1059. * gpg.c: Add new option --faked-system-time. 2009-12-15 Werner Koch * keydb.c (keydb_add_resource): s/readonly/read_only/g. * keyring.c (keyring_register_filename): Ditto. * tdbio.c (tdbio_set_dbname): Do not call log_fatal after creating the directory. Fixes bug#1169. Reported by Daniel Leidert. 2009-12-08 Werner Koch * keyring.h: Include userids.h. * gpg.h (KEYDB_SEARCH_DESC): Remove. * packet.h: Include userids.h. (PKT_user_id): Declare using gpg_pkt_user_id_s. * keydb.h (KeydbSearchMode, struct keydb_search_desc): Remove. We now use those in ../kbx. * getkey.c (classify_user_id): Remove. It is now in common/. (key_byname): Adjust for changed classify_user_id. * delkey.c (do_delete_key): Ditto. * trustdb.c (register_trusted_key): Ditto. * revoke.c (gen_desig_revoke, gen_revoke): Ditto. * keyserver.c (parse_keyrec, keyserver_export, keyserver_import) (keyidlist): Ditto. * export.c (do_export_stream): Ditto. * pkclist.c (find_and_check_key): Replace GPG_ERR_INV_NAME by GPG_ERR_INV_USER_ID. 2009-12-04 Werner Koch * keygen.c (DEFAULT_STD_ALGO, DEFAULT_STD_KEYSIZE): New. (ask_keysize): Use new macro. (gen_rsa): Set default size if NBITS is 0. (get_parameter_algo): Add algo name "default". Add arg R_DEFAULT. (proc_parameter_file): Process default flag. 2009-12-03 Werner Koch * gpg.c (set_debug): Allow for numerical debug leveles. Print active debug flags. 2009-11-27 Werner Koch * keyedit.c (cmds, keyedit_menu): New command "checkbkupkey". 2009-11-25 Marcus Brinkmann * server.c (gpg_server): Use assuan_fd_t and assuan_fdopen on fds. 2009-11-23 Werner Koch * gpg.c (gpgconf_list): Add key "default_pubkey_algo". 2009-11-18 Werner Koch * gpg.c: Add option --skip-hidden-recipients and no- variant. * options.h (struct opt): Add field SKIP_HIDDEN_RECIPIENTS. * pubkey-enc.c (get_session_key): Implement that option. 2009-11-04 Werner Koch * server.c (register_commands): Add NULL arg to assuan_register_command. 2009-11-02 Marcus Brinkmann * server.c (reset_notify, input_notify, output_notify): Update to new assuan interface. (register_commands): Use assuan_handler_t. 2009-10-19 Werner Koch * options.h (glo_ctrl): Add field LASTERR. * mainproc.c (proc_encrypted): Set LASTERR. * server.c (cmd_decrypt): Check LASTERR. 2009-10-02 Werner Koch * server.c (cmd_encrypt, cmd_decrypt): Implement. * decrypt.c (decrypt_message_fd): New. * options.h (struct opt): Add field OUTFP. * plaintext.c (handle_plaintext): Support opt.outfp. * encr-data.c: Rename to decrypt-data.c to reflect the action and not the processed packet type. 2009-10-02 Werner Koch * encr-data.c (decode_filter_context_s): Add fields PARTIAL and LENGTH. (decrypt_data): Set them. Simplify premature EOF detection. (mdc_decode_filter): Take fixed length packets in account. (decode_filter): Ditto. Better EOF detection. * parse-packet.c (parse_encrypted): Store ed->LEN without the MDC version byte. 2009-09-30 Werner Koch * parse-packet.c (skip_packet, parse_gpg_control) : Take care of premature EOFs. * gpg.c (main): Remove obsolete GCRYCTL_DISABLE_INTERNAL_LOCKING. 2009-09-29 Werner Koch * openfile.c (open_outfile): Re-indent. Use xstrconcat. (NAME_OF_DEV_NULL): New. (open_outfile): Use it. (overwrite_filep): Use it. Also use case insensitive compare when needed. Re-indent. (open_outfile): Add arg INP_FD. Change all callers. * encrypt.c (encrypt_crypt): Add new args FILEFD, OUTPUTFD and PROVIDED_KEYS. Change all callers. 2009-09-28 Werner Koch * server.c (skip_options, has_option): New. (cmd_recipient): Implement. * keydb.h (pk_list_t): New. * pkclist.c (send_status_inv_recp): New. Replace direct calls. (build_pk_list): Factor some code out to ... (find_and_check_key): ... new. * encode.c: Rename to encrypt.c. Re-indent all. * encrypt.c (encode_symmetric, encode_store, encode_seskey) (encode_simple, encode_crypt, encode_filter) (encode_crypt_files): Rename all to encrypt_*. Change all callers. * trustdb.c (get_validity_info): Take care of a NULL PK. Fixes bug#1138. (get_validity_string): Ditto. 2009-09-25 Werner Koch * pkglue.c (pk_sign, pk_verify, pk_encrypt, pk_decrypt) (pk_check_secret_key): Allow deprecated RSA identifiers 2 and 3. Fixes bug#1139. 2009-09-23 Marcus Brinkmann * call-agent.c: Include "scdaemon.h" before because of GPG_ERR_SOURCE_DEFAULT check. (learn_status_cb, dummy_data_cb, get_serialno_cb, default_inq_cb) (learn_status_cb, inq_writecert_parms, inq_writekey_parms) (scd_genkey_cb, membuf_data_cb): Return gpg_error_t instead of int. * gpg.c: Include "scdaemon.h" before because of GPG_ERR_SOURCE_DEFAULT check. (main): Update to new Assuan API. * server.c: Include "scdaemon.h" before because of GPG_ERR_SOURCE_DEFAULT check. (option_handler, cmd_recipient, cmd_signer, cmd_encrypt) (cmd_decrypt, cmd_verify, cmd_sign, cmd_import, cmd_export) (cmd_delkeys, cmd_message, do_listkeys, cmd_listkeys) (cmd_listsecretkeys, cmd_genkey, cmd_getinfo): Return gpg_error_t instead of int. (register_commands): Allocate assuan context before starting server. (gpg_server): Allocate assuan_context before starting server. 2009-09-04 Werner Koch * keyedit.c (menu_select_uid): Use IDX ==-1 t select all. (menu_select_key): Ditto. (keyedit_menu) : Allow '*' to select all. 2009-09-03 Werner Koch * keyedit.c (menu_adduid): Pass keyblock to generate_user_id. * keygen.c (generate_user_id): Add arg KEYBLOCK. Factor code out to ... (uid_from_string): ... new. (ask_user_id): Add arg KEYBLOCK and check for duplicates. Fix bug#1122. * Makefile.am (uninstall-local): New. * compress-bz2.c (do_uncompress): Detect unexpected EOF. Fix bug#1011. 2009-08-26 Werner Koch * keyedit.c (menu_revsig): Check for signature right away. Fix Debian-bug#543530. 2009-08-20 Daiki Ueno * mainproc.c (proc_encrypted): Clear passphrase cached with S2K cache ID if decryption failed. * passphrase.c (passphrase_to_dek_ext): Set dek->s2k_cacheid. * gpgv.c (passphrase_clear_cache): New stub. 2009-08-11 Werner Koch * call-agent.c (get_serialno_cb): New. From ../agent/call-scd.c. (gpg_agent_get_confirmation): New. (select_openpgp): New. (agent_scd_pkdecrypt, agent_scd_pksign): Use it here. 2009-08-06 Werner Koch * skclist.c (build_sk_list): Print INV_SGNR status line. * seckey-cert.c (do_check): Return G10ERR_UNU_SECKEY instead of general error. 2009-08-05 Werner Koch * card-util.c: Enable readline support also in GnuPG-2. * call-agent.c (agent_learn): Always select the card first. * gpg.c: Add --key-edit alias. * call-agent.c (scd_genkey_cb): Forward progress status lines. * card-util.c (generate_card_keys): Remove special case for GnuPG-2. Ask for the keysize and change it. (card_generate_subkey): Ask for the keysize and change it. (get_info_for_key_operation): Read KEY-ATTR. (show_keysize_warning, ask_card_keysize): New. (do_change_keysize): New. 2009-07-31 David Shaw * gpg.c (main): --pgp6 includes --disable-mdc. 2009-07-23 David Shaw * keyserver.c (keyserver_import_ldap): Try a DNS-SD lookup to find a domain-specific LDAP server before resorting to keys.{domain}. 2009-07-22 Werner Koch * card-util.c (generate_card_keys): Ask for off-card keys only if the card supports it. (get_info_for_key_operation): Read EXTCAP. (card_store_subkey): Check for non matching sizes. * call-agent.h (struct agent_card_info_s): Add field EXTCAP. * call-agent.c (agent_learn): Use a direct SCD command. (did_early_card_test): New. (start_agent): Perform an early test for the card. Add arg FOR_CARD. (status_sc_op_failure): New. (agent_scd_setattr, agent_scd_writekey, agent_scd_genkey) (agent_scd_pksign, agent_scd_pkdecrypt, agent_scd_change_pin) (agent_scd_checkpin): Call new function. (learn_status_cb): Parse KEY_TIME and EXTCAP. * gpg.c (main) : Show commands to run. * trustdb.c (how_to_fix_the_trustdb): New. * tdbio.c (tdbio_invalid): Show commands to re-create the trustdb. Fixes bug#929. 2009-07-20 Werner Koch * keygen.c (generate_keypair): Allow Elgamal > 3072 in BOTH mode. Reported by Jeroen Schot. Fixes bug#1091. 2009-07-17 Werner Koch * keyring.c (keyring_rebuild_cache): Replace the assert by a proper error message and allow to delete a bad keyblock. 2009-07-13 Werner Koch * exec.c: Fix function name indentation. (expand_args): Simplify by using membuf functions. (exec_write): Fix memory leak on error. (w32_system): Use DETACHED_PROCESS so that a new console is not created. 2009-07-09 Werner Koch * card-util.c (card_store_subkey): Do not restrict to 1024 bit keys. Print an error message on write errors. * gpg.c (main): Remove the SHA-1 default from the personal digest list. This was used in the past as a hack to avoid preferring RMD-160. * keygen.c (keygen_set_std_prefs): Remove RMD-160 from the list. Change order to SHA-256, SHA-1, SHA-384, SHA-512, SHA-224. (gen_dsa): Use a 256 bit Q for 2048 bit P. Round to FIPS allowed values in non-expert mode. 2009-07-07 Werner Koch * gpg.c (set_opt_session_env): New. (main): Allocate opt.session_env. Use it for oDisplay, oTTYname, oTTYtype and oXauthority. * options.h: Include session_env.h. (opt): Add field SESSION_ENV, remove obsolete fields. * call-agent.c (start_agent): Adjust start_new_gpg_agent for changed args. 2009-06-24 Werner Koch * keyedit.c (menu_select_key): Remove dead assign to I. (menu_select_uid): Ditto. * keyring.c (keyring_search): Remove dead assign to NAME. * card-util.c (card_edit): Remove useless DID_CHECKPIN. * call-agent.c (unhexify_fpr): Remove dead op on N. * passphrase.c (passphrase_to_dek_ext): Do not deref a NULL PW. * revoke.c (gen_revoke): Remove unused malloc of PK. * parse-packet.c (mpi_read): Init NREAD. Reported by Fabian Keil. 2009-06-17 Werner Koch * parse-packet.c (parse): Use a casted -1 instead of a 32 bit constant to check for a garbled package. Fixes bug#1040. * card-util.c (put_data_to_file, read_cert): New. (card_edit): Add command "readcert". (fetch_url): Allow code also for this gnupg major version 2. * call-agent.c (agent_scd_readcert): New. 2009-06-15 Werner Koch * keyserver.c (keyserver_search_prompt): No prompt in batch+colons mode. 2009-06-09 Werner Koch * card-util.c (write_sc_op_status): New. (change_pin): Use it. (change_url, change_login, change_private_do, change_cert) (change_lang, change_sex, change_cafpr, toggle_forcesig) (check_pin_for_key_operation): Ditto. 2009-06-05 David Shaw * gpg.c (main), misc.c (openpgp_cipher_test_algo): Remove Camellia restriction. * misc.c (map_cipher_openpgp_to_gcry), main.h: Add macros for openpgp_cipher_open, openpgp_cipher_get_algo_keylen, and openpgp_cipher_get_algo_blklen to wrap around the corresponding gcry_* functions, but pass the algorithm number through map_cipher_openpgp_to_gcry. This is needed in case the gcry algorithm number doesn't match the OpenPGP number (c.f. Camellia). * encr-data.c, pubkey-enc.c, mainproc.c, cipher.c, encode.c, seskey.c, passphrase.c, seckey-cert.c: Use new openpgp_cipher_* macros here. 2009-06-02 Werner Koch * card-util.c (get_manufacturer): Add new manufacturer. 2009-05-26 Werner Koch * parse-packet.c (mpi_read): Workaround for zero-length MPI bug in libgcrypt<1.5.0. 2009-05-22 Werner Koch * signal.c (got_fatal_signal): Call new function tty_cleanup_after_signal. 2009-05-20 Werner Koch * gpg.c (main): Fix --fingerprint/--with-fingerprint command detection. Fixes bug#1044. * keygen.c (ask_keysize): Allow selection of DSA key size even without --enable-dsa2. (gen_dsa): Remove size check. * keygen.c (ask_key_flags): Fix bug in the translation check. Fixes bug#1056. 2009-05-18 Daiki Ueno (wk) * encode.c (encode_simple): Tell passphrase_to_dek to cache the passphrase. (setup_symkey): Ditto. * mainproc.c (proc_symkey_enc): Tell passphrase_to_dek to cache the passphrase. (proc_encrypted): Ditto. * passphrase.c (hash_passphrase): Remove arg CREATE. (passphrase_to_dek): New mode 3 and 4 for caching passphrase for symmetric encryption. 2009-05-17 Werner Koch * keygen.c (ask_algo): Add arg R_SUBKEY_ALGO. Change return value semantics. Change presented order of algorithms. Make RSA+RSA the default. (generate_keypair): Adjust for change. (ask_keysize): Add arg PRIMARY_KEYSIZE for subkey creation. Change callers. 2009-05-15 Werner Koch * keygen.c (gen_card_key_with_backup): Get the size of the key from the card. * call-agent.h (struct agent_card_info_s): Add field KEY_ATTR. * call-agent.c (learn_status_cb): Support KEY-ATTR. * card-util.c (card_status): Print key attributes. 2009-05-15 Marcus Brinkmann * gpg.c (gpgconf_list): Remove dead entry "allow-pka-lookup" (a verify option for a couple of years now). 2009-05-14 Werner Koch * call-agent.c (agent_get_passphrase): Add arg CHECK. * passphrase.c (passphrase_get): Pass new arg. * keygen.c (gen_card_key_with_backup): Print a status error. (do_generate_keypair): Ditto. (do_ask_passphrase): Add arg MODE. (generate_raw_key): Call with mode 1. * passphrase.c (ask_passphrase): Remove becuase it is not used. (passphrase_to_dek): Factor code out to ... (passphrase_to_dek_ext): .. New. Add args CUSTDESC and CUSTPROMPT. 2009-05-13 Werner Koch * keygen.c (parse_expire_string): Base ISO date string at noon. Also allow full ISO timestamp. 2009-05-11 Werner Koch * parse-packet.c (parse_key): Print the key id in list mode. * skclist.c (build_sk_list): Use log_info for "duplicated entry". Fixes bug#1045. * encode.c (encode_simple): Print empty file warning only in verbose mode. Closes bug#1039. (encode_crypt): Ditto. * sign.c (write_plaintext_packet): Ditto. 2009-05-10 David Shaw * keyserver.c (keyserver_typemap): gpgkeys_hkp handles hkps as well. From 1.4. 2009-05-06 Werner Koch * getkey.c (finish_lookup): Remove dead code. * keyring.c (keyring_get_keyblock): Fix memory leak due to ring trust packets. Fixes bug#1034. 2009-04-03 Werner Koch * gpgv.c (main): Open keyrings readonly. * keydb.c (keydb_add_resource): Add readonly flag bit. (keydb_rebuild_caches): Don't act on readonly resources. * keyring.c (keyring_register_filename): Add arg READONLY. (struct keyring_name): Add field READONLY. (keyring_is_writable): Implement readonly feature. (keyring_update_keyblock): Return GPG_ERR_EACCES for readonly keyrings. (keyring_insert_keyblock, keyring_delete_keyblock): Ditto. 2009-04-01 Werner Koch * gpg.c (main): Properly handle UTF8 usernames with --sign-key and --lsign-key. From 1.4, David 2008-12-21. 2009-03-20 David Shaw (wk) * keyring.c (rename_tmp_file): Force a fsync (via iobuf_ioctl) on secret keyring files to be extra safe on filesystems that may not sync data and metadata together (ext4). Also check return code from the cache invalidation to make sure we're safe over NFS and similar. 2009-03-31 Werner Koch * passphrase.c (ask_passphrase): Use percent_plus_unescape. * misc.c (unescape_percent_string): Remove. * call-agent.c (unescape_status_string): Chnage to use percent_plus_unescape. 2009-03-25 Werner Koch * mainproc.c (print_pkenc_list): Use snprintf. 2009-03-17 Werner Koch * call-agent.c (my_percent_plus_escape): Remove. (agent_get_passphrase): Rewrite using percent_plus_escape. 2009-03-17 Daiki Ueno * passphrase.c (passphrase_get): Add extra arg REPEAT and adjust callers; remove special treatment for MODE==2. (passphrase_to_dek): Move --passphrase-repeat handling to gpg-agent. * call-agent.c (agent_get_passphrase): Add extra arg REPEAT. * call-agent.h: Ditto. 2009-03-16 Werner Koch * gpg.c (my_strusage): Revert last change. Systems w/o a gpg1 may, and actually do, install gpg2 as gpg. * gpgv.c (my_strusage): Ditto. 2009-03-14 David Shaw * gpg.c (my_strusage): gpg2 and gpgv2 (not gpg and gpgv). * gpgv.c (my_strusage): Same. * gpgv.c (my_strusage): Fix name of program in "Syntax" line. 2009-02-27 Werner Koch * call-agent.c (agent_scd_pksign, agent_scd_pkdecrypt): First send the SERIALNO command. 2009-02-24 Werner Koch * pkglue.c (pk_verify): Return an error for improper DATA instead of calling BUG(). 2009-02-09 Werner Koch * keylist.c (print_capabilities): Take care of cert-only keys. Fixes bug#998. * keyedit.c (show_key_with_all_names_colon): Print the capabilities. 2009-01-26 Werner Koch * card-util.c (card_status): Detect a Geldkarte. 2009-01-13 Werner Koch * call-agent.c (dummy_data_cb): New. (agent_learn): Use it. * card-util.c (card_status): Print type of non-OpenPGP card. * call-agent.h (agent_card_info_s): Add field APPTYPE. 2009-01-12 Werner Koch * getkey.c (finish_lookup): Take care of keys with a zero timestamp. Reported by Peter Gutmann. 2009-01-08 Werner Koch * misc.c (has_invalid_email_chars): Let non-ascii pass through. * cpr.c [USE_SHM_COPROCESSING]: Remove this code. 2008-12-12 Werner Koch * passphrase.c (passphrase_get): Write a STATUS_ERROR. * cpr.c (write_status_error): New. * Makefile.am (common_source): Add rmd160.h. 2008-12-11 Werner Koch * sig-check.c (signature_check2): Change algorithm used to compute the SIG_ID. (check_revocation_keys): Close message digest. * rmd160.c, rmd160.h: New. Based on code from GnuPG-1.4. * t-rmd160.c: New. * Makefile.am: Add support to run tests. * keyid.c (namehash_from_uid): Use rmd160_hash_buffer. 2008-12-10 Werner Koch * trustdb.h (NAMEHASH_HASH): Remove unsued constant. * gpg.c (print_mds): Print RMD160 only is enabled. * keygen.c (keygen_set_std_prefs): Include RMD160 only if available. 2008-12-09 Werner Koch * gpg.c (main) [IS_DEVELOPMENT_VERSION]: Fix strusage use. 2008-12-09 Werner Koch * keygen.c (proc_parameter_file): Check that key and subkey usages are allowed. 2008-12-09 David Shaw (wk) * trustdb.c (validate_one_keyblock): Fix the trust signature calculations so that we lower the trust depth of signatures to fit within the current chain, rather than discarding any signature that does not fit within the trust depth. 2008-12-09 Werner Koch * keyserver.c (show_prompt): Flush stdout. * gpg.c (open_info_file): Add arg BINARY and adjust callers. * gpg.c (main): Call i18n_init before init_common_subsystems. * gpgv.c (main): Ditto. * keylist.c (set_attrib_fd): Do not close ATTRIB_FP if it is the log stream. (set_attrib_fd) [W32]: Set to binary mode. (dump_attribs): Flush the stream after writing. 2008-12-05 Werner Koch * call-agent.c (percent_plus_escape): Rename to my_percent_plus_escape and also escape the percent character. Change all callers. 2008-11-18 Werner Koch * gpg.c (build_lib_list): Remove. (make_libversion): New. (my_strusage): Use it. * gpgv.c (make_libversion): New. (my_strusage): Print libgcrypt version. 2008-11-13 Werner Koch * gpgv.c: Use new ARGPARSE macros and re-indent. 2008-11-11 Werner Koch * gpg.c (opts): Use new ARGPARSE macros for clarity. 2008-10-24 Werner Koch * keyedit.c (change_passphrase): Clear passphrase cache. 2008-10-20 Werner Koch * gpgv.c: Mark all args of the stub fucntions as unused. * card-util.c (generate_card_keys): Remove unused arg SERIALNO and adjust caller. * build-packet.c (write_sign_packet_header): Mark unused arg. * gpg.c (gpg_init_default_ctrl, gpg_deinit_default_ctrl): Ditto. * getkey.c (skip_unusable): Ditto. (write_version): Ditto. * keydb.c (keydb_locate_writable): Ditto. * keyring.c (update_offset_hash_table): Ditto. (keyring_lock): Ditto. * misc.c (register_secured_file): Ditto. (unregister_secured_file): Ditto. (is_secured_file): Ditto. (is_secured_filename): Ditto. * parse-packet.c (parse_marker): Ditto. (parse_key, parse_attribute): Ditto. (parse_trust, parse_compressed, parse_mdc, parse_gpg_control): Ditto. * cpr.c (progress_cb): Ditto. * passphrase.c (passphrase_clear_cache): Ditto. (ask_passphrase): Ditto. * keyedit.c (keyedit_completion): Ditto. * import.c (import_revoke_cert): Ditto. (chk_self_sigs, delete_inv_parts, append_uid): Ditto. (merge_sigs, merge_keysigs, append_key): Ditto. * trustdb.c (list_trust_path): Ditto. (enum_cert_paths, enum_cert_paths_print): Ditto. * tdbdump.c (list_trustdb): Ditto. * keygen.c (keygen_upd_std_prefs): Ditto. (genhelp_factors): Ditto. * call-agent.c (agent_scd_setattr): Ditto. (agent_scd_writekey, agent_scd_change_pin, agent_scd_genkey): Ditto. (agent_clear_pin_cache): Ditto. * server.c (option_handler): Mark non yet used arg. (input_notify, output_notify): Ditto. (cmd_recipient, cmd_signer, cmd_encrypt, cmd_decrypt, cmd_verify) (cmd_sign, cmd_import, cmd_export, cmd_delkeys, do_listkeys) (cmd_genkey): Ditto. * verify.c (gpg_verify): Ditto. 2008-10-17 Werner Koch * main.h (idea_cipher_warn): Use do while construct in place of an empty definition. 2008-10-03 David Shaw * main.h, mainproc.c (check_sig_and_print) * keylist.c (list_keyblock_print) * pkclist.c (do_edit_ownertrust) * keyedit.c (menu_showphoto) * photoid.c (generate_photo_id, show_photos) * misc.c (pct_expando): Add %v and %V expandos so that displaying photo IDs can show the attribute validity tag (%v) and string (%V). Originally by Daniel Gillmor. 2008-09-29 Werner Koch * gpg.c (main): Remove -sat kludge. Note that we printed a warning for two years. * seskey.c (encode_md_value): Remove extra gcry_md_test_algo since it is not needed with Libgcrypt 1.4. * skclist.c (random_is_faked): Simplify. * sign.c (match_dsa_hash): Remove runtime check for SHA224. * gpg.c (print_mds): Use GCRY_MD_SHA224 constant. 2008-09-25 David Shaw * keyedit.c (keyedit_menu): Fix bug where a modified keyring loses its modified status after a "clean" or "minimize" that doesn't need to do anything. 2008-09-25 Werner Koch * parse-packet.c (parse): Remove special treatment for compressed new style packets. Fixes bug#931. * card-util.c (change_pin): Support setting of the reset code. 2008-09-24 Werner Koch * call-agent.h (struct agent_card_info_s): Add field IS_V2. * call-agent.c (learn_status_cb): That that field. * card-util.c (change_pin): Rename first arg to UNBLOCK_v2 and use it this way. (card_edit): Add new command UNBLOCK. 2008-09-23 David Shaw * pkclist.c (select_algo_from_prefs): Redo function to rank prefs and pick a consensus winner across all keys. 2008-09-16 Werner Koch * card-util.c (fpr_is_ff): New. (card_status): Do not print general key info for an all-ff fpr. (change_login, change_private_do): Factor common code out to ... (get_data_from_file): .. new. (change_cert): New. (card_edit): Add command "writecert". * call-agent.c (writecert_parm_s): New. (inq_writecert_parms, agent_scd_writecert): New. 2008-09-04 David Shaw * keyserver.c (keyserver_import_cert): Allow keyserver URLs in addition to full URLs in CERT records. 2008-08-11 Werner Koch * keygen.c (ask_expire_interval): Check for time overflow of an u32. Fixes bug #947. 2008-08-01 Werner Koch * tdbio.c (open_db) [!EROFS]: Move closing parens out of the ifdef. Reported by Ken Takusagawa. 2008-06-25 Marcus Brinkmann * gpg.c (enum cmd_and_opt_values): Remove option oEnableW32HandleTranslation. (opts): Remove option --enable-w32-handle-translation. (main): Remove variable w32_handle_translation. 2008-06-19 Werner Koch * gpg.c (gpgconf_list): Add "group". 2008-06-18 Marcus Brinkmann * gpg.c (enum cmd_and_opt_values): New option oEnableW32HandleTranslation. (opts): New option --enable-w32-handle-translation. (main): New variable w32_handle_translation to keep track of option. 2008-06-16 Werner Koch * keygen.c (output_control_s): Add ASK_PASSPHRASE. (read_parameter_file): Add commands %ask-passphrase and %no-ask-passphrase. 2008-06-11 Werner Koch * gpg.c: Make --fixed-list-mode a dummy. * options.h (struct): Removed FIXED_LIST_MODE. * keyid.c (colon_strtime, colon_datestr_from_pk) (colon_datestr_from_sk, colon_datestr_from_sig) (colon_expirestr_from_sig): Remove fixed_list_mode case. * keylist.c (list_keyblock_colon): Ditto. Remove all now unsed code and reindent. 2008-05-31 Werner Koch * keygen.c (ask_user_id): Change the string printed as header of the user ID generation. Use code to not break existing translations. Suggested by Eric Tetz. 2008-05-08 Werner Koch * sig-check.c (do_check_messages): Print a revocation diagnostic in verbose mode. 2008-05-07 Werner Koch * gpg.c: New command --locate-keys. New options --with-sig-list and --with-sig-check. * keylist.c (locate_one): New. (public_key_list): Add arg LOCATE_MODE and use locate_one. * getkey.c (get_pubkey_byname): Fix nodefault case. Add option RETCTX, change all callers. (struct getkey_ctx_s): Add field extra_ptr; (get_pubkey_end): Free it. 2008-04-18 Werner Koch * misc.c (map_cipher_openpgp_to_gcry, map_cipher_gcry_to_openpgp) (openpgp_cipher_test_algo): Add camellia-192. (openpgp_cipher_blocklen): New. * parse-packet.c (parse_key): Use new function here. 2008-04-15 David Shaw * getkey.c (merge_selfsigs_subkey): If there are multiple 0x19 backsigs, take the most recent one. 2008-04-08 Werner Koch * options.h (opt): Add AKL_NODEFAULT and AKL_LOCAL. * getkey.c (parse_auto_key_locate): Parse them. (get_pubkey_byname): Implement them. Add arg NO_AKL and use that in all cases where a local key is expected. * import.c (import_one): Fill in the fingerprint in all cases. Use log_get_stream. * keyserver.c (keyserver_import_pka): Set FPR to NULL on error. Return G10ERR_NO_PUBKEY if no PKA info is available or no key URI is given in the PKA record.. (keyserver_import_cert): Return G10ERR_NO_PUBKEY if a CERT record was not found. * getkey.c (get_pubkey_byname): Release FPR in the error case. Continue with next mechanism on error. Better diagnostics. 2008-04-07 Werner Koch * keyserver.c (parse_keyserver_uri): Allow a default host name. * getkey.c (get_pubkey_byname): Replace sprintf by bin2hex. 2008-04-02 Werner Koch * gpg.c (main): Do not allow DSA2 with a too old Libgcrypt. 2008-03-26 Werner Koch * tdbio.c (lookup_hashtable): Make cmp args const. (cmp_trec_fpr): Make FPR const. (tdbio_search_trust_byfpr): Remove cast. 2008-03-25 Werner Koch * keyserver.c (parse_keyrec): Take care of char defaulting to unsigned when using hextobyte. 2008-03-25 David Shaw (wk) * import.c (collapse_uids): Fix bug 894: possible memory corruption around deduplication of user IDs. 2008-03-25 Werner Koch * parse-packet.c (parse_key): Parse a secret key encrypted with Camellia. * options.skel: Make the default keyserver keys.gnupg.net. 2008-03-18 Werner Koch * seckey-cert.c (do_check): Use GCRYMPI_FMT_PGP for v3 keys. Reported by Petr Cerny. 2008-03-13 Werner Koch * passphrase.c (PROMPTSTRING): Change string to me more similar to the X.509 prompt. 2008-02-26 Werner Koch * getkey.c (get_pubkey_byname): Fix comment. 2008-02-14 Werner Koch * call-agent.c (default_inq_cb): New. (agent_learn, agent_scd_getattr, agent_scd_pksign) (agent_scd_pkdecrypt, agent_scd_change_pin, agent_scd_checkpin) (agent_get_passphrase, agent_clear_passphrase): Use new callback. (inq_writekey_parms): Fall back to the new callback for other inquiries. (start_agent): Tell agent that we accept pinentry notifications. 2008-02-11 Werner Koch * server.c (cmd_getinfo): New. (register_commands): Register GETINFO. 2008-02-09 Marcus Brinkmann * gpg.c (main): New variable default_configname. Use it if save_configname is NULL (can happen if default configfile does not exist). Move default configname determination to ... (get_default_configname): ... this new function. 2008-01-30 Werner Koch * keydb.c (maybe_create_keyring): Fixed last change. * tdbio.c (tdbio_set_dbname): Also test for forward slash. 2008-01-29 Werner Koch * keydb.c (maybe_create_keyring): Take care of a missing slash. (maybe_create_keyring) [W32]: Also test for forward slash. 2008-01-26 Werner Koch * card-util.c (get_manufacturer): Add vendor 0004. 2008-01-02 Werner Koch * gpg.c: Add --logger-file as an alias for log-file. 2007-12-14 Werner Koch * gpg.c (main): Set opt.no_homedir_creation during the first option parsing pass. 2007-12-12 Werner Koch * misc.c (print_pubkey_algo_note): Print a warning if a type 20 key is used. (openpgp_pk_test_algo, openpgp_pk_test_algo2) (openpgp_pk_algo_usage): Allow type 20 keys only in rfc2440 mode. 2007-12-12 David Shaw (wk) * trustdb.c (sanitize_regexp): New. Protect against dangerous regexps (malloc bombs) by force-commenting any characters aside from the ones we explicitly want. (check_regexp): Use it here before passing the regexp to regcomp(). 2007-12-12 Werner Koch * misc.c (map_cipher_openpgp_to_gcry): New. Used to map Camellia algorithms to Gcrypt. (openpgp_cipher_test_algo): Call new map function. Replace all remaining calls to gcry_cipher_test_algo by a call to this. (openpgp_cipher_algo_name): New. Replace all remaining calls to gcry_cipher_algo_name by a call to this. (map_cipher_gcry_to_openpgp): New. (string_to_cipher_algo): Use it. * gpg.c (main): Print a warning if Camellia support is build in. * gpg.c (print_algo_names): New. From the 1.4 branch by David. (list_config): Use it here for the "ciphername" and "digestname" config items so we can get a script-parseable list of the names. * parse-packet.c (parse_onepass_sig): Sigclass is hex, so include the 0x. * sign.c (match_dsa_hash): Remove conditional builds dending on USE_SHAxxx. We don't need this becuase it can be expected that libgcrypt provides it. However we need to runtime test for SHA244 becuase that is only available with libgcrypt 2.4. 2007-12-11 Werner Koch * mainproc.c (proc_pubkey_enc): Allow type 20 Elgamal key for decryption. 2007-12-10 Werner Koch * import.c (auto_create_card_key_stub): Do not clear the entire fingerprint. This finally makes the stub creation work. My past tests seemed to work because there was a key with a all zero fingerprint available (Elgamal signing keys). 2007-12-08 Werner Koch * misc.c (openpgp_pk_algo_usage): Allow Elgamal type 20 for encryption. 2007-12-04 Werner Koch * helptext.c (get_help_from_file): New. (display_online_help): Use it to geting the help through a file. (helptexts): Remove. 2007-12-03 Werner Koch * keygen.c (ask_key_flags): Add a translation remark and implement a workaround. * gpg.c (reopen_std): Moved to ../common and renamed to gnupg_reopen_std. * gpg.c: Remove second inclusion of fcntl.h. 2007-11-19 Werner Koch * keyedit.c (keyedit_menu): String grammar fix. 2007-11-15 Werner Koch * gpg.c (main): New option --xauthority. * call-agent.c (start_agent): Adjust changed start_new_gpg_agent. 2007-11-12 Werner Koch * cpr.c (do_get_from_fd): s/bool/getbool/ to overcome problems with Mac OS 10.5 which seems to include stdbool.h silently. 2007-11-07 Werner Koch Replace all includes of errors.h by status.h (found in common/). * status.h: Remove. * status.h: Move prototypes to main.h. * status.c: Rename to .. * cpr.c: .. this. (get_status_string): Remove. We take this now from common/. 2007-10-25 David Shaw (wk) From 1.4 (October): * gpg.c (main): Add --require-cross-certification to --openpgp/--rfc4880 mode. * gpg.c (main): Disable --rfc2440-text and --force-v3-sigs by default. Enable --require-cross-certification by default. --openpgp (--rfc4880) is the same as --rfc2440 except with "--enable-dsa2 --no-rfc2440-text --escape-from-lines". * misc.c (compliance_option_string, compliance_failure): Minor cleanup. * armor.c (is_armor_header): Comment about 4880. * options.h, gpg.c (main): Add --rfc4880, and make --openpgp an alias to it. --rfc2440 now stands alone. For now, use the old 2440 defaults for 4880. * misc.c (compliance_option_string): Ditto. * keyedit.c (keyedit_menu): Use compliance_option_string() instead of printing the compliance modes here. 2007-10-25 David Shaw (wk) From 1.4 (September): * import.c (collapse_uids): Significant speedup for de-duping user IDs. 2007-10-25 David Shaw (wk) From 1.4 (July): * armor.c (parse_header_line): Improve test so that the header test only allows "Hash" in the signed data section. * armor.c (is_armor_tag): New. Detect if an armor header matches 2440bis-21. (parse_header_line): Call it here, as bis-21 requires warning the user (but continuing to process the message) when seeing an unknown header. * encode.c (encode_crypt): Missed one call to setup_plaintext_name(). This is bug#809. * sign.c (mk_notation_policy_etc): Expect all sigs that this is called for are >=v4. (write_signature_packets, make_keysig_packet): Only call it for >=v4 sigs. This allows --force-v3-sigs and --force-v4-certs to enable or disable notations, policies, and keyserver URLs. This is bug#800. 2007-10-19 Werner Koch * passphrase.c (passphrase_get): Use new utf8 switching fucntions. 2007-09-14 Werner Koch * gpg.c (build_lib_list): New. (my_strusage): Print lib info. 2007-08-27 Werner Koch * trustdb.c (USE_INTERNAL_REGEX): Remove support. 2007-08-24 Werner Koch * keyring.c (keyring_register_filename): Use same_file_p(). 2007-08-21 Werner Koch * misc.c (openpgp_md_test_algo): Remove rfc2440bis hash algorithms. (openpgp_cipher_test_algo): Likewise for algos 5 and 6. 2007-08-02 Werner Koch * gpg.c: Include gc-opt-flags.h and remove their definition here. 2007-07-17 Werner Koch * gpg.c (gpgconf_list): Declare --encrypt-to and --default-key. * card-util.c (get_manufacturer): Add the unmanaged S/N range. 2007-07-12 Werner Koch * gpg.c (main): Use translate_sys2libc_fd_int when passing an int value. * gpgv.c (main): Ditto. 2007-07-05 Werner Koch * card-util.c (card_generate_subkey, card_store_subkey): Enable the code also for GnuPG-2. * keygen.c (make_backsig): Add arg TIMESTAMP. (write_keybinding): Add arg TIMESTAMP, pass it to make_backsig. (write_direct_sig, write_selfsigs): Add arg TIMESTAMP. (gen_elg, gen_dsa, gen_rsa): Add arg TIMESTAMP. (do_create): Ditto. (do_generate_keypair): Use the same timestamp for key creation time and all key signatures. Return an error if write_direct_sig for the secret key fails. (generate_subkeypair): Ditto. (gen_card_key): New arg TIMESTAMP. (generate_card_subkeypair): Pass current time to gen_card_key. (gen_card_key_with_backup): New arg TIMESTAMP. (read_parameter_file): Add option Creation-Date. (parse_creation_string): New. (do_generate_keypair): Use the Creation-Date if available. (save_unprotected_key_to_card): Use P for P and not D. * call-agent.c (agent_scd_genkey): Add arg CREATETIME. * keyedit.c (menu_backsign): Use the same timestamp for all backsigs. 2007-06-26 Werner Koch * openfile.c (try_make_homedir): Support W32; use standard_homedir. 2007-06-25 Werner Koch * gpg.c, gpgv.c: Include sysutils.h. (main): Replace iobuf_translate_file_handle by translate_sys2libc_fd. 2007-06-21 Werner Koch * main.h: Include util.h. * call-agent.c (start_agent): Factored almost all code out to ../common/asshelp.c. * gpg.h (ctrl_t): Remove. It is now declared in ../common/util.h. 2007-06-20 Werner Koch * misc.c (setsysinfo, trap_unaligned): Remove. It is also in common/sysutils.c. (disable_core_dumps, get_session_marker): * sign.c (sleep): Remove sleep wrapper. 2007-06-18 Marcus Brinkmann * gpg.c (gpgconf_list): Percent escape output of --gpgconf-list. 2007-06-14 Werner Koch * call-agent.c (start_agent): Use gnupg_module_name. 2007-06-12 Werner Koch * openfile.c (copy_options_file): Use gnupg_datadir. * misc.c (get_libexecdir): Remove. Changed all callers to use gnupg_libexecdir. * gpg.c (check_permissions): Use gnupg_libdir. * gpg.c (main): Replace some calls by init_common_subsystems. * gpgv.c (main): Ditto. 2007-06-11 Werner Koch * Makefile.am (needed_libs): Use libcommonstd macro. * gpgv.c (main) [W32]: Call pth_init. * gpg.c (main) [W32]: Call pth_init. 2007-06-08 Werner Koch * Makefile.am (gpg2_LDADD): Syntax fix. 2007-06-06 Werner Koch * passphrase.c (passphrase_get) [!ENABLE_NLS]: Do not define orig_codeset. * Makefile.am (gpgv2_LDADD, gpg2_LDADD): Include LDADD before libgcrypt. * plaintext.c (handle_plaintext): Replace eof by eof_seen as W32's io.h has a symbol with that name. * misc.c: Do not include dynload.h. (w32_shgetfolderpath): Remove. It is now in common/homedir.c. * gpgv.c (i18n_init): Remove. * gpg.c (i18n_init): Remove. (main): Make --load-extension a dummy 2007-05-19 Marcus Brinkmann * passphrase.c (passphrase_get): Use PACKAGE_GT, not PACKAGE. * passphrase.c (passphrase_get): Free ORIG_CODESET on error. 2007-05-16 Werner Koch * sig-check.c (check_backsig): Check the digest algorithm before using it. Fixed bug 797. 2007-05-09 Werner Koch * openfile.c (overwrite_filep, open_outfile) [W32]: Need to use just "nul". Though, I am pretty sure that some MSDOS versions grok the extra /dev/. 2007-05-07 Werner Koch * openfile.c (open_outfile, overwrite_filep) [W32]: Use "/dev/nul". 2007-05-02 David Shaw * packet.h, mainproc.c (reset_literals_seen): New function to reset the literals count. * verify.c (verify_one_file), decrypt.c (decrypt_messages): Call it here so we allow multiple literals in --multifile mode (in different files - not concatenated together). 2007-04-26 Marcus Brinkmann * passphrase.c (passphrase_to_dek): Write missing passphrase status message in case of cancellation. 2007-04-16 Werner Koch * build-packet.c (mpi_write): Made buffer a bit larger. Reported by Alexander Feigl. 2007-04-13 Werner Koch * call-agent.c (start_agent): Don't use log_error when using the fallback hack to start the agent. This is bug 782. 2007-04-05 David Shaw From STABLE-BRANCH-1-4 * parse-packet.c (parse_marker): New. Enforce that the marker contains 'P', 'G', 'P', and nothing but. (parse): Call it here. (skip_packet): No longer need to handle marker packets here. 2007-03-14 David Shaw From STABLE-BRANCH-1-4 * keyserver.c: Windows Vista doesn't grok X_OK and so fails access() tests. Previous versions interpreted X_OK as F_OK anyway, so we'll just use F_OK directly. 2007-03-09 David Shaw From STABLE-BRANCH-1-4 * parse-packet.c (parse_signature): It's hex. * getkey.c (merge_selfsigs_subkey): Avoid listing the contents of a backsig when list mode is on. Noted by Timo Schulz. 2007-03-08 Werner Koch * plaintext.c (handle_plaintext): Add two extra fflush for stdout. 2007-03-08 David Shaw (wk) * keyedit.c (keyedit_menu): If we modify the keyblock (via fix_keyblock() or collapse_uids()) make sure we reprocess the keyblock so the flags are correct. Noted by Robin H. Johnson. * getkey.c (fixup_uidnode): Properly clear flags that don't apply to us (revoked, expired) so that we can reprocess a uid. 2007-03-05 Werner Koch Converted this file to UTF-8. Ported David and my multiple messages changes from 1.4.7. * options.h, gpg.c (main), mainproc.c (check_sig_and_print): Allow multiple sig verification again as this is protected via the multiple-messages code. New option --allow-multiple-messages and --no variant. * status.h (STATUS_ERROR): New status code. * status.c (get_status_string): Ditto. * mainproc.c (proc_plaintext): Emit it if multiple messages are detected. Error out if more than one plaintext packet is encountered. * mainproc.c (literals_seen): New. 2007-02-26 Werner Koch * gpg.c (main): Add verify option show-primary-uid-only. * options.h (VERIFY_SHOW_PRIMARY_UID_ONLY): New. * mainproc.c (check_sig_and_print): Implement it. 2007-02-22 Werner Koch * encr-data.c (decrypt_data): Correctly test for unknown algorithm. * import.c (check_prefs): Ditto. * keyedit.c (show_prefs): Ditto. * mainproc.c (proc_symkey_enc): Ditto. 2007-02-06 Werner Koch * export.c (do_export_stream): Allow reset-subkey-passwd along with sexp-format. 2007-02-04 Werner Koch * parse-packet.c (parse_signature): Limit bytes read for an unknown alogorithm. Fixes Debian bug#402592. 2007-01-31 Werner Koch * verify.c (verify_signatures): Do no dereference a NULL afx. * passphrase.c (passphrase_get): Set the cancel flag on all error from the agent. Fixes a bug reported by Tom Duerbusch. 2007-01-30 Werner Koch * status.c (write_status_begin_signing): New. * sign.c (sign_file, sign_symencrypt_file): Call it. * textfilter.c (copy_clearsig_text): Call it. * call-agent.c (agent_scd_pksign): Pass --hash-rmd160 to SCD if required. * gpg.c (main): Let --no-use-agent and --gpg-agent-info print a warning. * misc.c (obsolete_option): New. 2007-01-29 Werner Koch * pkclist.c (do_we_trust_pre): Issue a user-id-hint status code. 2007-01-15 Werner Koch * parse-packet.c (read_protected_v3_mpi): Make sure to stop reading even for corrupted packets. * keygen.c (generate_user_id): Need to allocate one byte more. Reported by Felix von Leitner. 2006-12-21 Werner Koch * gpg.c (main): New command --server. * gpg.h (struct server_control_s, ctrl_t): New. * server.c: New. * verify.c (gpg_verify): New. * mainproc.c (mainproc_context): Made SIGNED_DATA a structure. (proc_signature_packets_by_fd): New. (proc_compressed_cb): Divert depending on SIGNED_DATA. * plaintext.c (hash_datafile_by_fd): New. * mainproc.c (proc_tree): Use it here. * verify.c (verify_signatures): Init AFX only when needed. Don't leak a context on error. (verify_one_file): Don't leak a context on error. 2006-12-07 Werner Koch * openfile.c (copy_options_file): Use log_info instead of log_error to avoid an error return of gpg due to a missing skeleton file. 2006-12-07 David Shaw * Makefile.am: Link to iconv for jnlib dependency. 2006-12-05 Werner Koch * passphrase.c (passphrase_to_dek): Handle a Cancel request correctly. [Bug#737] * mainproc.c (proc_symkey_enc): Removed workaround for bogus cancel processing. * encode.c (encode_simple): Distinguish error message between cancel and invalid passphrase. (setup_symkey): Ditto. * sign.c (sign_symencrypt_file): Ditto * keyedit.c (change_passphrase): Allow cancellation. * keygen.c (do_ask_passphrase): New arg R_CANCELED. (generate_keypair): Handle a passphrase cancellation. (generate_raw_key): Ditto. (generate_subkeypair): Ditto. 2006-12-04 Werner Koch * filter.h (armor_filter_context_t): New element REFCOUNT. * armor.c (armor_filter): Made static. (push_armor_filter, release_armor_context, new_armor_context): New. (armor_filter): Release the context. * gpg.c (main): Use new armor context functions and push_armor_filter. * export.c (do_export): Ditto. * encode.c (encode_simple, encode_crypt): Ditto. * decrypt.c (decrypt_message, decrypt_messages): Ditto. * dearmor.c (dearmor_file, enarmor_file): Ditto. * verify.c (verify_signatures, verify_one_file): Ditto. * sign.c (sign_file, clearsign_file, sign_symencrypt_file): Ditto. * revoke.c (gen_desig_revoke, gen_revoke): Ditto. * keyserver.c (keyserver_spawn): Ditto. * keygen.c (output_control_s): Turn AFX fields into pointers. (read_parameter_file): Allocate and release AFX fields. (do_generate_keypair): Use push_armor_filter. * import.c (import): Replace iobuf_push_filter2 hack by the new armor context stuff. 2006-12-03 Werner Koch * filter.h: New element REFCOUNT. (handle_progress): Remove prototype. * progress.c (new_progress_context, release_progress_context): New. (progress_filter): Use new function to release context. Made static. (handle_progress): Bumb reference counter. No more check for enabled progress as this is handled by new_progress_context. * verify.c (verify_signatures, verify_one_file): Replace stack based progress context by a heap based one. * sign.c (sign_file, clearsign_file, sign_symencrypt_file): Ditto. * plaintext.c (ask_for_detached_datafile, hash_datafiles): Ditto. * encode.c (encode_simple, encode_crypt): Ditto. * decrypt.c (decrypt_message, decrypt_messages): Ditto. * keyedit.c (menu_clean): Made strings translatable. 2006-12-03 David Shaw * keyedit.c (menu_clean): Show "already minimized" rather than "already clean" when a minimized key is minimized again. From Dirk Traulsen. 2006-12-02 David Shaw * options.h, gpg.c (main), passphrase.c (passphrase_to_dek): Add --passphrase-repeat option to control how many times gpg will re-prompt for a passphrase to ensure the user has typed it correctly. Defaults to 1. 2006-12-02 Werner Koch * encr-data.c: Allocate DFX context on the heap and not on the stack. Changes at several places. Fixes CVE-2006-6235. 2006-11-27 Werner Koch * openfile.c (ask_outfile_name): Fixed buffer overflow occurring if make_printable_string returns a longer string. Fixes bug 728. 2006-11-21 Werner Koch * Makefile.am (needed_libs): libgnu needs to come after libcommon. * keygen.c (ask_expire_interval): Print y2038 warning only for 32 bit time_t. (save_unprotected_key_to_card): Made RSA_N_LEN et al a size_t. Cast printf args. (get_parameter_algo): Allow "ELG" as alias for "ELG-E". * seckey-cert.c (do_check): Made NBYTES a size_t. (do_check): Made NDATA a size_t. (protect_secret_key): Made NARR a size_t. (protect_secret_key): Made NVYES a size_t. * pubkey-enc.c (get_it): Made INDATALEN a size_t. (get_it): Made NFRAME a size_t. * keyid.c (hash_public_key): Made NBITS an unsigned int. * misc.c (checksum_mpi): Made NBYTES a size_t. (openpgp_pk_test_algo2): Made USE_BUF a size_t. * seskey.c (encode_session_key): Made NFRAME a size_t. (do_encode_md): Ditto. (encode_md_value): Cast size_t argument of printf. (encode_md_value): Ditto. 2006-11-10 Werner Koch * parse-packet.c (mpi_read): Changed NREAD to size_t to match the gcry_mpi-scan prototype. (mpi_read): Fixed double increment of bytes read to correctly detect overlong MPIs. 2006-11-05 Werner Koch * gpg.c (main): Remove the default --require-cross-certification. * options.skel: Enable require-cross-certification. 2006-10-31 Werner Koch * pkclist.c (warn_missing_aes_from_pklist): New. * encode.c (encrypt_filter, encode_crypt): Use it here. 2006-10-27 Werner Koch * pkclist.c (warn_missing_mdc_from_pklist): New. * encode.c (use_mdc): Use it here. 2006-10-24 Marcus Brinkmann * Makefile.am (AM_CFLAGS): Add $(LIBASSUAN_CFLAGS). 2006-10-23 Werner Koch * gpg.c (main): New command --gpgconf-test. * Makefile.am (bzip2_source): New. 2006-10-20 Werner Koch * getkey.c (classify_user_id): Reserve '&' for search by keygrip. 2006-10-19 Werner Koch * keygen.c (get_parameter_algo): Add special case for ELG_E which is not supported by libgcrypt's mapping function. 2006-10-18 Werner Koch * keyid.c (v3_keyid): Don't use mempcy as we need to hold the keyids in the native endian format. * import.c (import_print_stats): Use log_printf. * build-packet.c (do_public_key): Care about mpi_write errors. (do_secret_key, do_pubkey_enc, do_signature): Ditto. (mpi_write): Print an extra warning on error. 2006-10-17 Werner Koch * Makefile.am (LDADD): Replaced W32LIBS by NETLIBS. 2006-10-12 David Shaw * parse-packet.c (parse_symkeyenc): Show the unpacked as well as the packed s2k iteration count. * main.h, options.h, gpg.c (encode_s2k_iterations, main), passphrase.c (hash_passphrase): Add --s2k-count option to specify the number of s2k hash iterations. 2006-10-08 Werner Koch * gpgv.c: Remove the tty stubs as we are now required to link to tty anyway (it is included in libcommand and has dependencies to other modules as well). * keyedit.c (keyedit_menu): Use keyedit_completion only if readline is available. It would be better to move this code into gpgrlhelp.c 2006-10-06 Werner Koch * Makefile.am (AM_CFLAGS): Use PTH version of libassuan. 2006-10-06 David Shaw * keyserver.c (keyserver_spawn): Write the 16-digit keyid rather than whatever key selector the user used on the command line. 2006-10-05 Werner Koch * status.c (progress_cb): Changed to libgcrypt API. (set_status_fd): Register the progress cb. * seskey.c (encode_md_value): Check that the hash algo is valid before getting the OID. 2006-10-04 Werner Koch * passphrase.c: Allow for a static passphrase in batch mode. * call-agent.c (agent_havekey): Removed. (percent_plus_escape): New. (agent_get_passphrase): New. (agent_clear_passphrase): New. * passphrase.c: Changed so that we always require the agent. (agent_send_option, agent_send_all_options, agent_open): Removed. (agent_get_passphrase): Cleaned up. Does now use the call-agent functions. Renamed to (passphrase_get): .. this. Changed all callers. (passphrase_clear_cache): Rewritten. (passphrase_to_dek, hash_passphrase): Re-indented. * gpg.c (main): Made --use-agent a dummy option. * seckey-cert.c (check_secret_key): We require the agent, so always allow for 3 tries. * gpg.c (main): Print a warning if -sat has been used. (main): Removed the special treatment of the -k option. -k is now an alias for --list-keys. (main): Removed --list-ownertrust. 2006-10-02 Werner Koch * encr-data.c (decrypt_data, mdc_decode_filter): Check the MDC right here and don't let parse-packet handle the MDC. 2006-09-29 Werner Koch * compress.c (do_uncompress): Removed use of Z_PARTIAL_FLUSH. This is outdated and old zlib versions which still require it have security problems. 2006-09-27 Werner Koch Replaced all STRLIST by strlist_t. 2006-09-21 Werner Koch * signal.c (got_fatal_signal): Replaced readline stuff by a tty function. * Makefile.am (LDADD): Include libgpgrl.a. * gpg.c (main): Call gpg_rl_initialize. * keyedit.c: Removed double inclusion of stdio.h. 2006-09-20 Werner Koch * call-agent.c: Include asshelp.h. (start_agent): Use send_pinentry_environment. 2006-09-14 Werner Koch Replaced all call gpg_error_from_errno(errno) by gpg_error_from_syserror(). 2006-09-13 Werner Koch * gpg.c (main): Made --require-cross-certification the default. 2006-09-06 Marcus Brinkmann * Makefile.am (gpg2_LDADD, gpgv2_LDADD): Replace -lassuan and -lgpg-error with $(LIBASSUAN_LIBS) and $(GPG_ERROR_LIBS). (AM_CFLAGS): Add $(LIBASSUAN_CFLAGS) and $(GPG_ERROR_CFLAGS). 2006-09-06 Werner Koch * gpg.c (main): Enable new assuan API. * call-agent.c: Changed to new Assuan API. 2006-09-01 Werner Koch * call-agent.c: Do not force using the pipe server. * gpg.c (main): Enable card related commands. 2006-08-22 Werner Koch * mainproc.c (proc_plaintext): Fixed a #warning 2006-08-21 Werner Koch * skclist.c (random_is_faked): Implemented. (is_insecure): Also test for the old uppercase version of the insecure string. * gpg.c (main): Renamed --quick-random to debug-quick-quick-random. * gpg.c (print_mds): Do not use the USE_SHA macros. * mainproc.c (proc_encrypted): Remove assign inside condition for better readibility. * packet.h: Moved consts to new header ../common/openpgpdefs.h. 2006-08-16 Werner Koch * keyserver.c (GPGKEYS_PREFIX): Rename to gpg2keys_. This is so that we can install helpers from 1.4 and 2 without conflicts and first of all don't get lost with weird bug reports. * keyid.c (serialno_and_fpr_from_sk): New. Actually lost during the last 1.4 to 1.9 merge. * gpg.c (list_config): Output ccid-reader-id only for gnupg 1. * call-agent.c (agent_scd_writekey): New. (inq_writekey_parms): New. * gpgv.c: Include call-agent.h for use by stubs. * misc.c: Include call-agent.h for use by get_signature_count. 2006-07-27 Werner Koch * parse-packet.c (parse_comment): Cap comments at 65k. (parse_gpg_control): Skip too large control packets. 2006-07-24 David Shaw (wk) * keydb.h, pkclist.c (select_algo_from_prefs, algo_available): Pass a union for preference hints rather than doing void * games. * sign.c (sign_file): Use it here. * sign.c (sign_file): When signing with multiple DSA keys, one being DSA1 and one being DSA2 and encrypting at the same time, if the recipient preferences give a hash that can work with the DSA2 key, then allow the DSA1 key to be promoted rather than giving up and using hash_for(). * pkclist.c (algo_available): Automatically enable DSA2 mode when handling a key that clearly isn't DSA1 (i.e. q!=160). 2006-06-30 Werner Koch * misc.c (checksum_mpi): No need for nbits as they are alredy included in the buffer. 2006-06-29 Werner Koch * parse-packet.c (parse_signature, parse_key): Need store the length of opaque data as number of bits. * card-util.c (card_store_subkey): Ditto. * mainproc.c (print_pkenc_list, check_sig_and_print): Replaced log_get_stream by calls to log_printf. This avoids the extra LFs inserted by the logging function. They are a bit too smart sometimes. * pkclist.c (do_show_revocation_reason): Print final LF through log_printf to avoid extra LFs. * pubkey-enc.c (get_it): Ditto. * seskey.c (encode_md_value): Fix call to gcry. 2006-06-27 Werner Koch Applied patches from 1.4.x (2006-05-22 to 2006-06-23) from David: * keygen.c (keygen_upd_std_prefs, keygen_add_std_prefs) (proc_parameter_file): Add --default-keyserver-url to specify a keyserver URL at key generation time, and "Keyserver:" keyword for doing the same through a batch file. * options.h, gpg.c (main): Ditto. * sign.c (do_sign): For now don't accept a truncated hash even for DSA1 keys (be liberal in what you accept, etc). * import.c (import_one): Add a flag (from_sk) so we don't check prefs on an autoconverted public key. The check should only happen on the sk side. Noted by Dirk Traulsen. * keygen.c (gen_card_key): Add optional argument to return a pointer (not a copy) of the stub secret key for the secret key we just generated on the card. (generate_card_subkeypair): Use it here so that the signing key on the card can use the card to generate the 0x19 backsig on the primary key. Noted by Janko Heilgeist and Jonas Oberg. * parse-packet.c (parse_user_id): Cap the user ID size at 2048 bytes. This prevents a memory allocation attack with a very large user ID. A very large packet length could even cause the allocation (a u32) to wrap around to a small number. Noted by Evgeny Legerov on full-disclosure. * keygen.c (gen_dsa): Allow generating DSA2 keys. Allow specifying sizes > 1024 when --enable-dsa2 is set. The size of q is set automatically based on the key size. (ask_keysize, generate_keypair): Ask for DSA size when --enable-dsa2 is set. * exec.c (make_tempdir) [W32]: Fix bug with a temporary directory on W32 that is over 256 bytes long. Noted by Israel G. Lugo. * gpg.c (reopen_std): New function to reopen fd 0, 1, or 2 if we are called with them closed. This is to protect our keyring/trustdb files from corruption if they get attached to one of the standard fds. Print a warning if possible that this has happened, and fail completely if we cannot reopen (should never happen). (main): Call it here. * parse-packet.c (dump_sig_subpkt, parse_signature): Fix meaning of key expiration and sig expiration subpackets - zero means "never expire" according to 2440, not "expire instantly". * build-packet.c (build_sig_subpkt_from_sig): Ditto. * getkey.c (fixup_uidnode, merge_selfsigs_main) (merge_selfsigs_subkey): Ditto. * keygen.c (keygen_add_key_expire): Ditto. * getkey.c (get_pubkey_byname) * import.c (import_one): Fix key selection problem when auto-key-locate returns a list of keys, not all of which are usable (revoked, expired, etc). Noted by Simon Josefsson. 2006-05-24 Werner Koch * keyid.c (hash_public_key): Do not double hash the length bytes, they are already included by mpi_print. * misc.c (openpgp_pk_test_algo2): Get test call right. * misc.c (string_to_cipher_algo, string_to_digest_algo): New. * keygen.c (keygen_set_std_prefs): use them here. * gpg.c (main): and here. 2006-05-23 Werner Koch * card-util.c (generate_card_keys): Removed temporary kludge for generate_keypair. * call-agent.c (agent_scd_setattr): Add arg SERIALNO. (agent_scd_genkey): Ditto. (agent_scd_change_pin): Ditto. * call-agent.h (struct agent_card_info_s): Updated to match the one of 1.4.3. * Makefile.am (LDADD): Include ZLIBS. * gpgv.c: Removed stubs not anymore useful due to libgcrypt. 2006-05-22 Werner Koch * keyserver.c (keyidlist): Replaced mpi_get_keyid by v3_keyid. * keydb.h (v3_keyid): Added. * import.c (import): Better initialize KEYBLOCK as to quiet compiler warning. * skclist.c (random_is_faked): New. * mainproc.c: Include pka.h. 2006-05-19 Werner Koch * misc.c (openpgp_pk_test_algo2): Need to use gcry_pk_algo_info directly. (string_count_chr): New. * armor.c (parse_header_line): Use renamed function length_sans_trailing_ws. * options.h, gpg.c: Option --strict is not used thus removed code but kept option. 2006-04-28 David Shaw (wk) * keyserver.c (direct_uri_map): New. (keyserver_spawn): Used here to add "_uri" to certain gpgkeys_xxx helpers when the meaning is different if a path is provided (i.e. ldap). (keyserver_import_cert): Show warning if there is a CERT fingerprint, but no --keyserver set. * keyserver.c: Fix build problem with platforms that stick libcurl in a place not in the regular include search path. * options.h, gpg.c (main): Add --enable-dsa2 and --disable-dsa2. Defaults to disable. * pkclist.c (algo_available): If --enable-dsa2 is set, we're allowed to truncate hashes to fit DSA keys. * sign.c (match_dsa_hash): New. Return the best match hash for a given q size. (do_sign, hash_for, sign_file): When signing with a DSA key, if it has q==160, assume it is an old DSA key and don't allow truncation unless --enable-dsa2 is also set. q!=160 always allows truncation since they must be DSA2 keys. (make_keysig_packet): If the user doesn't specify a --cert-digest-algo, use match_dsa_hash to pick the best hash for key signatures. * gpg.c (print_mds): Add SHA-224. * armor.c (armor_filter, parse_hash_header): Add SHA-224. * sign.c (write_plaintext_packet): Factor common literal packet setup code from here, to... * encode.c (encode_simple): .. there. * main.h, plaintext.c (setup_plaintext_name): Here. New. Make sure the literal packet filename field is UTF-8 encoded. * options.h, gpg.c (main): Make sure --set-filename is UTF-8 encoded and note when filenames are already UTF-8. * keyedit.c (menu_backsign): Give some more verbose errors when we have no need to backsign. * getkey.c (parse_auto_key_locate): Fix dupe-removal code. * keyedit.c (menu_backsign): Allow backsigning even if the secret subkey doesn't have a binding signature. * armor.c (radix64_read): Don't report EOF when reading only a pad (=) character. The EOF actually starts after the pad. * gpg.c (main): Make --export, --send-keys, --recv-keys, --refresh-keys, and --fetch-keys follow their arguments from left to right. Suggested by Peter Palfrader. 2006-04-18 Werner Koch * tdbio.c (open_db, migrate_from_v2): Removed feature to migration from old trustdb version 2. * gpg.c, mainproc.c: Removed pipemode feature. * status.c: Removed shared memory coprocess stuff Merged with current gpg 1.4.3 code. * keygen.c, keyid.c, misc.c, openfile.c, verify.c, trustdb.c * textfilter.c, tdbio.c, tdbdump.c, status.c, skclist.c, signal.c * sign.c, sig-check.c, seskey.c, seckey-cert.c, revoke.c * pubkey-enc.c, progress.c, plaintext.c, pkclist.c, photoid.c * passphrase.c, parse-packet.c, mdfilter.c, mainproc.c * keyserver.c, keyring.c, keylist.c, keyedit.c, keydb.c, kbnode.c * import.c, getkey.c, gpgv.c, helptext.c, free-packet.c * build-packet.c, cipher.c, compress.c, dearmor.c, decrypt.c * delkey.c, encr-data.c, encode.c, exec.c, export.c * gpg.c, armor.c: Updated from gnupg-1.4.3 and merged back gcry and gnupg-1.9 related changes. * trustdb.h, tdbio.h, status.h, photoid.h, packet.h, options.h * main.h, keyserver-internal.h, keyring.h, keydb.h, filter.h * exec.h: Ditto. * global.h: Removed after merging constants with gpg.h. * comment.c, pipemode.c: Removed. * card-util.c: Updated from gnupg-1.4.3. * compress-bz2.c: New. 2005-06-15 Werner Koch * g10.c (print_hashline, add_group): Fixes for signed/unsigned pointer mismatch warnings. 2005-06-01 Werner Koch * mkdtemp.c: Removed. * exec.c: Include mkdtemp.h 2004-12-21 Werner Koch * gpgv.c, g10.c (main): Use default_hoemdir (). 2004-12-18 Werner Koch * gpg.h (map_assuan_err): Define in terms of map_assuan_err_with_source. 2004-12-15 Werner Koch * Makefile.am (LDADD): Remove ZLIBS. 2004-10-22 Werner Koch * g10.c (main): Display a bit fat warning that this gpg should not be used. * card-util.c (fetch_url): Disable for gnupg 1.9 (card_generate_subkey): Ditto. (card_store_subkey): Ditto. 2004-09-30 Werner Koch * gpgv.c (i18n_init): Always use LC_ALL. * Makefile.am (LDADD): Adjusted for gettext 0.14. 2004-09-20 Werner Koch * keyedit.c (show_key_with_all_names): Print the card S/N. 2004-09-11 Moritz Schulte * openfile.c (copy_options_file): Fixed last commit (added a `+'). 2004-08-31 Werner Koch * openfile.c (copy_options_file): Use gpg-conf.skel. Better take the length of SKELEXT into account, someone might make it larger. * Makefile.am: Install options.skel as gpg-conf.skel. 2004-08-18 Marcus Brinkmann * passphrase.c (agent_get_passphrase): Fix detection of gpg-agent cancellation. 2004-07-01 Werner Koch * card-util.c (change_login): Kludge to allow reading data from a file. (card_edit): Pass ARG_STRING to change_login. (card_status): Print CA fingerprints. (change_cafpr): New. (card_edit): New command CAFPR. * call-agent.h: Add members for CA fingerprints. * call-agent.c (agent_release_card_info): Invalid them. (learn_status_cb): Store them. 2004-04-30 Werner Koch * g10.c (main) : Use gpg.conf and not /dev/null as default filename. 2004-04-28 Werner Koch * card-util.c (card_edit): Remove PIN verification. (generate_card_keys): New arg SERIALNO. Do PIN verification here after resetting forced_chv1. 2004-04-26 Werner Koch * card-util.c (change_name): Check that the NAME is not too long. (change_url): Likewise. (change_login): Likewise. 2004-03-23 Werner Koch * g10.c: New options --gpgconf-list, --debug-level and --log-file (set_debug): Add arg DEBUG_LEVEL. (main): Look at less and less version specific config files. From gnupg 1.3. 2004-02-17 Werner Koch * call-agent.c (start_agent): Ignore an empty GPG_AGENT_INFO. * passphrase.c (agent_open): Ditto. 2004-02-12 Werner Koch * gpgv.c: Removed g10defs.h. * Makefile.am: Include cmacros.am for common flags. 2004-02-11 Werner Koch * openfile.c (try_make_homedir): Use GNUPG_DEFAULT_HOMEDIR. * gpgv.c (main): Ditto. * g10.c (main): Ditto. 2004-01-19 Moritz Schulte * keygen.c (do_generate_keypair): Print member fname, instead of newfname, again. (do_generate_keypair): Don't try to execute certain pieces of code in case an error occured. (gen_card_key): Don't print out a message, which is already printed by do_generate_keypair(). 2004-01-18 Moritz Schulte * keygen.c (do_generate_keypair): Print member fname, instead of newfname. 2003-12-17 Werner Koch * card-util.c (print_name): Fixed bad format string usage. (print_isoname): Ditto. * trustdb.c (check_regexp): s/exp/expr/. * keyedit.c (trustsig_prompt): Removed a "> 255" term; it is always false due to the data type. * passphrase.c (agent_get_passphrase): Use xasprintf and avoid non-literal format strings. * tdbio.c (upd_hashtable, drop_from_hashtable, lookup_hashtable): Fixed log_error format string bugs. Kudos to the now working gcc-3.3 -Wformat-nonliteral and Florian Weimer's investigations in gnupg 1.2.3. 2003-12-15 Werner Koch * seckey-cert.c (protect_secret_key): Use gry_create_nonce for the IV; there is not need for real strong random here and it even better protect the random bits used for the key. 2003-11-16 Moritz Schulte * signal.c: Removed unused file. 2003-11-10 Moritz Schulte * Makefile.am (INCLUDES): Added: @LIBGCRYPT_CFLAGS@. 2003-10-25 Werner Koch * call-agent.c (learn_status_cb, scd_genkey_cb): Fixed faulty use of !spacep(). 2003-10-20 Werner Koch * card-util.c (card_edit): New command "passwd". Add logic to check the PIN in advance. (card_status): Add new args to return the serial number. Changed all callers. * call-agent.c (agent_scd_checkpin): New. 2003-10-08 Werner Koch * call-agent.c (agent_scd_getattr): Don't clear the passed info structure, so that it can indeed be updated. * card-util.c (fpr_is_zero): New. (generate_card_keys): New. (card_edit): New command "generate". * keygen.c (generate_keypair): New arg CARD_SERIALNO, removed call to check_smartcard. (check_smartcard,show_smartcard): Removed. (show_sha1_fpr,fpr_is_zero): Removed. 2003-10-01 Werner Koch * card-util.c: Tweaked to use this source also under 1.3. 2003-09-30 Werner Koch * keylist.c (print_card_serialno): New. (list_keyblock_print): Use it here. * card-util.c (toggle_forcesig): New. (card_edit): New command "forcesig". * card-util.c (print_name, print_isoname): Use 0 and not LF fro the max_n arg of tty_print_utf8_string2. * call-agent.c (agent_scd_getattr): New. (learn_status_cb): Release values before assignment so that it can be used by getattr to update the structure. * card-util.c (change_pin): Simplified. We now have only a PIN and an Admin PIN. 2003-09-27 Werner Koch * sign.c (do_sign): Removed disabled testcode. 2003-09-26 Timo Schulz * card_status (card_status): Do not use fputs since the fp parameter can be NULL. This fixes a segv. 2003-09-24 Werner Koch * card-util.c (print_isoname,card_status): Handle opt.with_colons. (print_sha1_fpr_colon): New. 2003-09-23 Werner Koch Merged most of David Shaw's changes in 1.3 since 2003-06-03. * Makefile.am: Include W32LIBS where appropriate. * armor.c (parse_hash_header,armor_filter): Drop TIGER/192 support. * g10.c (print_hex,print_mds): Ditto. * pkclist.c (algo_available): Ditto. * armor.c (armor_filter): Allow using --comment multiple times to get multiple Comment header lines. --no-comments resets list. * options.h, g10.c (main): Ditto. Deprecate --default-comment in favor of --no-comments. * g10.c (main): Trim --help to commonly used options. Remove -f. * g10.c (main): Add --multifile as an alias to turn --encrypt into --encrypt-files (plus --verify-files, --decrypt-files). Error out if --multifile is used with the commands that don't support it yet. * encode.c (use_mdc), g10.c (main): Use RFC1991 and RFC2440 directly to check for MDC usability. Do not set the force_mdc or disable_mdc flags since there is no point any longer. * g10.c (main): Use "keyserver-url" instead of "preferred-keyserver" for the sake of short and simple commands. (add_keyserver_url): Clarify a few strings. It's a "preferred keyserver URL". * keyedit.c (keyedit_menu): Ditto. * sign.c (mk_notation_policy_etc): Ditto. * main.h, keygen.c (keygen_add_keyserver_url): Signature callback for adding a keyserver URL. * keyedit.c (keyedit_menu, menu_set_keyserver_url): New command to set preferred keyserver to specified (or all) user IDs. * build-packet.c (build_sig_subpkt): Set preferred keyserver flag while building a preferred keyserver subpacket. * keylist.c (show_policy_url, show_keyserver_url): URLs might be UTF8. * keyedit.c (menu_addrevoker): Fix leaking a few bytes. * keyedit.c (show_key_with_all_names): Use list-option show-long-keyid in main --edit-key display. * keyedit.c (print_and_check_one_sig): Use list-option show-long-keyid in --edit-key "check" function. * passphrase.c (agent_send_all_options): Make use of $GPG_TTY. * g10.c (main): Disable use-agent if passphrase-fd is given later. Suggested by Kurt Garloff. * exec.c, g10.c, gpgv.c, passphrase.c, photoid.c: s/__MINGW32__/_WIN32/ to help building on native Windows compilers. Requested by Brian Gladman. From Werner on stable branch. * options.h, g10.c (main): Add list-option list-preferred-keyserver. * keyedit.c (change_passphrase): When responding 'no' to the blank passphrase question, re-prompt for a new passphrase. This is bug #202. * mainproc.c (check_sig_and_print): Use two different preferred keyserver displays - one if the key is not present (to tell the user where to get the key), the other if it is present (to tell the user where the key can be refreshed). * packet.h, parse-packet.c (parse_signature): Set flag if a preferred keyserver is present. * keylist.c (list_keyblock_print): Show keyserver url in listings with list-option show-keyserver-url. * mainproc.c (check_sig_and_print): Get the uid validity before printing any sig results to avoid munging the output with trustdb warnings. * g10.c (main): Don't include --show-keyring in --help as it is deprecated. * options.skel: Note that keyserver.pgp.com isn't synchronized, and explain the roundrobin a bit better. * sig-check.c (check_key_signature2), import.c (import_one, import_revoke_cert, chk_self_sigs, delete_inv_parts, collapse_uids, merge_blocks): Make much quieter during import of slightly munged, but recoverable, keys. Use log_error for unrecoverable import failures. * keyring.c (keyring_rebuild_cache): Comment. * sign.c (mk_notation_and_policy): Making a v3 signature with notations or policy urls is an error, not an info (i.e. increment the errorcount). Don't print the notation or policy url to stdout since it can be mixed into the output stream when piping and munge the stream. * packet.h, sig-check.c (signature_check2, do_check, do_check_messages): Provide a signing-key-is-revoked flag. Change all callers. * status.h, status.c (get_status_string): New REVKEYSIG status tag for a good signature from a revoked key. * mainproc.c (do_check_sig, check_sig_and_print): Use it here. * import.c (import_revoke_cert, merge_blocks, merge_sigs): Compare actual signatures on import rather than using keyid or class matching. This does not change actual behavior with a key, but does mean that all sigs are imported whether they will be used or not. * parse-packet.c (parse_signature): Don't give "signature packet without xxxx" warnings for experimental pk algorithms. An experimental algorithm may not have a notion of (for example) a keyid (i.e. PGP's x.509 stuff). * options.h, g10.c (main), keylist.c (list_keyblock_print), keyedit.c (print_and_check_one_sig): New "show-sig-expire" list-option to show signature expiration dates (if any). * options.h, g10.c (main, add_keyserver_url): Add --sig-preferred-keyserver to implant a "where to get my key" subpacket into a signature. * sign.c (mk_notation_and_policy): Rename to mk_notation_policy_etc and add preferred keyserver support for signatures. * keygen.c (do_add_key_flags): Don't set the certify flag for subkeys. (ask_algo): Provide key flags for DSA, Elgamal_e, and Elgamal subkeys. (generate_keypair): Provide key flags for the default DSA/Elgamal keys. * sig-check.c (signature_check, signature_check2, check_key_signature, check_key_signature2): Allow passing NULLs for unused parameters in the x2 form of each function to avoid the need for dummy variables. getkey.c, mainproc.c: Change all callers. * trustdb.h, trustdb.c (read_trust_options): New. Returns items from the trustdb version record. * keylist.c (public_key_list): Use it here for the new "tru" record. * gpgv.c (read_trust_options): Stub. * keyedit.c (show_key_with_all_names): Use list-option show-validity in --edit-key interface as well. * options.h, g10.c (main), mainproc.c (check_sig_and_print): Add verify-options "show-validity" and "show-long-keyid" to show trustdb validity and long keyids during (file) signature verification. * packet.h, main.h, sig-check.c (signature_check2) (check_key_signature2, do_check): If ret_pk is set, fill in the pk used to verify the signature. Change all callers in getkey.c, mainproc.c, and sig-check.c. * keylist.c (list_keyblock_colon): Use the ret_pk from above to put the fingerprint of the signing key in "sig" records during a --with-colons --check-sigs. This requires --no-sig-cache as well since we don't cache fingerprints. * parse-packet.c (parse_signature): No need to reserve 8 bytes for the unhashed signature cache any longer. * misc.c (pct_expando): Add two new expandos - signer's fingerprint (%g), and signer's primary fingerprint (%p). * g10.c (main): Add --rfc2440 alias for --openpgp since in a few months, they won't be the same thing. * keyserver.c (parse_keyserver_uri): Accept "http" as an alias for "hkp", since it is occasionally written that way. (keyserver_spawn): Use ascii_isspace to avoid locale issues. * keygen.c (ask_user_id): Make --allow-freeform-uid apply to the email field as well as the name field, and allow mixing fields when it is set. * trustdb.c (validate_one_keyblock): Certifications on revoked or expired uids do not count in the web of trust. * signal.c (init_one_signal, pause_on_sigusr, do_block): Only use sigprocmask() if we have sigset_t, and only use sigaction() if we have struct sigaction. This is for Forte c89 on Solaris which seems to define only the function call half of the two pairs by default. (pause_on_sigusr): Typo. (do_block): If we can't use sigprocmask() and sigset_t, try to get the number of signals from NSIG as well as MAXSIG, and if we can't, fail with an explanation. * signal.c, tdbio.c: Comment out the transaction code. It was not used in this version, and was causing some build problems on quasi-posix platforms (Solaris and Forte c89). * keylist.c (list_keyblock_colon): Don't include validity values when listing secret keys since they can be incorrect and/or misleading. This is a temporary kludge, and will be handled properly in 1.9/2.0. * mainproc.c (check_sig_and_print): Only show the "key available from" preferred keyserver line if the key is not currently present. * keyedit.c (sign_uids): Do not sign expired uids without --expert (same behavior as revoked uids). Do not allow signing a user ID without a self-signature. --expert overrides. Add additional prompt to the signature level question. (menu_expire): When changing expiration dates, don't replace selfsigs on revoked uids since this would effectively unrevoke them. There is also no point in replacing expired selfsigs. This is bug #181 * g10.c (add_notation_data): Make sure that only ascii is passed to iscntrl. Noted by Christian Biere. * getkey.c (classify_user_id2): Replaced isspace by spacep * keygen.c (ask_user_id): Ditto. (get_parameter_algo): Ditto. * keyedit.c (keyedit_menu): Ditto. * tdbdump.c (import_ownertrust): Ditto. s/isxdigit/hexdigitp/. * revoke.c (ask_revocation_reason): * keyserver.c (keyserver_spawn): Dito. * parse-packet.c (parse): Disallow old style partial length for all key material packets to avoid possible corruption of keyrings. * import.c (import_keys_internal): Invalidate the cache so that the file descriptor gets closed. Fixes bug reported by Juan F. Codagnone. * options.h, g10.c (main), main.h, keylist.c (show_keyserver_url), mainproc.c (check_sig_and_print), parse-packet.c (dump_sig_subpkt, parse_one_sig_subpkt, can_handle_critical): Add read-only support for preferred keyserver subpackets. They're basically policy URLs with a different name. Add a verify-option "show-preferred-keyserver" to turn them on and off (on by default, as per stable branch). * g10.c (main): Add "--set-notation" as alias to "--notation-data" this is to make things consistent with --set-policy-url meaning both sigs and certs. * options.h, g10.c (main), keylist.c (list_keyblock_print): Add "show-validity" and "show-long-keyid" list-options. * gpgv.c (get_validity, trust_value_to_string): Stubs. * g10.c (main): Use SAFE_VERSION instead of VERSION in the version-specific gpg.conf file so it can be overridden on RISCOS. * keyedit.c (show_key_with_all_names): Fix assertion failure when using toggle to see a secret key. Reported by Maxim Britov. 2003-09-22 Timo Schulz * card-util.c (card_status): Free pk in case of an error and return if the card is no OpenPGP card. 2003-09-18 Werner Koch * g10.c: New command --card-edit. * card-util.c (card_status): Use tty_fprintf for all output. (print_sha1_fpr, print_isoname): Ditto. (get_one_name,change_name, change_url, change_login,change_lang) (change_sex): New; taken from keygen.c. * keygen.c (smartcard_get_one_name, smartcard_change_name) (smartcard_change_url, smartcard_change_login_data) (smartcard_change_lang, smartcard_change_sex): Removed. (check_smartcard): Removed most menu items. 2003-09-06 Werner Koch * misc.c (openpgp_pk_algo_usage): Allow AUTH where SIGN is allowed. * keygen.c (ask_passphrase): No need to allocated S2K in secure memory. 2003-09-04 Werner Koch * keygen.c (do_add_key_flags, parse_parameter_usage) (do_generate_keypair): Add support the proposed AUTH key flag. * getkey.c (fixup_uidnode, merge_selfsigs_main) (merge_selfsigs_subkey, premerge_public_with_secret): Ditto. * keylist.c (print_capabilities): Ditto. 2003-08-25 Timo Schulz * pkglue.c (mpi_from_sexp): New. Used to factor out some common code. 2003-08-24 Werner Koch * keygen.c (do_generate_keypair): Print a reminder to use --gen-revoke. 2003-08-18 Timo Schulz * encode.c (encode_sesskey): Checked the code and removed the warning since all compatibility checks with PGP succeeded. * mainproc.c (symkey_decrypt_sesskey): Better check for the algorithm and check the return values of some functions. * mdc.c (use_mdc): Simplified. 2003-08-07 Werner Koch * pkglue.c (pk_sign): Fix last change. (pk_verify): Check for valid DATA array so that we don't segv in Libgcrypt. (pk_verify): Ditto. 2003-08-06 Werner Koch * pkglue.c (pk_sign): Allow signing using RSA. 2003-08-05 Werner Koch * Makefile.am (install-data-local): Dropped check for the ancient gpgm tool. (bin_PROGRAMS): Renamed gpg to gpg2 and gpgv to gpgv2. This is so that it won't conflict with the current stable version of gpg. * pkglue.c (pk_check_secret_key): New. * seckey-cert.c (do_check): Reenable this test here again. * g10.c (main): Add command -K as an alias for --list-secret-keys. Command "-k" is now an alias to --list-keys. Remove special treatment of -kv and -kvv. (set_cmd): Ditto. (main): Strip a "-cvs" suffix when testing for a version specific config file. * status.h, status.c, g10.c [USE_SHM_COPROCESSING]: Removed. This is not any longer available. 2003-07-29 Werner Koch * g10.c (main): Add secmem features and set the random seed file. (g10_exit): Update the random seed file. * parse-packet.c (parse_signature,read_protected_v3_mpi) (parse_key): Fixed use of mpi_set_opaque. * keygen.c (gen_card_key): Ditto. 2003-07-28 Werner Koch * status.c (progress_cb): Adjusted for use with Libcgrypt. (set_status_fd): Register that callback. * keygen.c (smartcard_change_login_data): New. (smartcard_change_lang): New. (smartcard_change_sex): New. (check_smartcard): Add menu entries to edit the above. (gen_elg,gen_dsa,gen_rsa): Reimplemented in terms of Libgcrypt. (genhelp_protect, genhelp_factors, key_from_sexp): New. * comment.c (make_comment_node_from_buffer): New. (make_comment_node): Reimplemented in terms of above. 2003-07-27 Werner Koch Adjusted for gcry_mpi_print and gcry_mpi_scan API change. 2003-07-24 Werner Koch * g10.c: New command --card-status. * card-util.c (card_status): New. * call-agent.c (learn_status_cb): Parse more information. * keylist.c (print_pubkey_info): Add FP arg for optional printing to a stream. Changed all callers. 2003-07-23 Werner Koch * keygen.c (generate_keypair): Create an AUTHKEYTYPE entry for cards. (do_generate_keypair): Abd generate the authkey. (check_smartcard): Changed menu accordingly. 2003-07-22 Werner Koch * g10.c: New command --change-pin. * card-util.c: New. * call-agent.c (agent_scd_change_pin): New. (agent_release_card_info): New. * keygen.c (check_smartcard): Use it here. 2003-07-16 Werner Koch * export.c (parse_export_options): New option sexp-format. (export_seckeys,export_secsubkeys): Check sexp-format option. (do_export): Ignore armor for sexp format. (do_export_stream): Handle sexp-format. (write_sexp_line,write_sexp_keyparm, build_sexp_seckey): New. (build_sexp): New. 2003-07-03 Werner Koch * options.h (DBG_CIPHER): Reintroduced it. * seskey.c (encode_session_key): Debug output of the session key. * pubkey-enc.c (get_it): Handle card case. * call-agent.c (agent_scd_pkdecrypt): New. * pkglue.c (pk_encrypt): Add RSA support. * g10.c (main): Default to --use-agent. * keygen.c (show_smartcard): Print info about the public key. (check_smartcard): Check for existing key here. (gen_card_key): And not anymore here. (fpr_is_zero): New. (generate_keypair): Generate both keys for a card. (smartcard_change_url): Nw. 2003-07-02 Werner Koch * seckey-cert.c (is_secret_key_protected): Let it handle mode 1002. 2003-07-01 Werner Koch * keygen.c (gen_card_key): Obviously we should use the creation date received from SCDAEMON, so that the fingerprints will match. * sign.c (do_sign): Pass the serialno to the sign code. * keyid.c (serialno_and_fpr_from_sk): New. 2003-06-30 Werner Koch * call-agent.h (agent_card_info_s): Add field serialno. * call-agent.c (store_serialno): New. (learn_status_cb): Store the serial number. * keygen.c (gen_card_key): Store the serial number (check_smartcard): New argument to return the serial number. (generate_keypair): Get the serial number from check_smartcard and store it as a parameter. * parse-packet.c (parse_key): Use the protect.iv field to store the serial number. * build-packet.c (do_secret_key): Write the serial number. 2003-06-27 Werner Koch * seckey-cert.c (check_secret_key): Bypass the unprotection for mode 1002. * sign.c (do_sign): Handle card case (i.e. mode 1002). 2003-06-26 Werner Koch * build-packet.c (do_secret_key): Implement special protection mode 1002. * parse-packet.c (parse_key): Likewise. * keygen.c (smartcard_gen_key): New. * call-agent.c (agent_scd_setattr): New. 2003-06-24 Werner Koch * Makefile.am: Removed signal.c * g10.c (emergency_cleanup): New. (main): Use gnupg_init_signals and register malloc for assuan. 2003-06-23 Werner Koch * keyid.c (do_fingerprint_md): Made it work again. 2003-06-19 Werner Koch Fixed all "==" comparisons against error code constants to use gpg_err_code(). * import.c (import_secret_one): (import_revoke_cert): (chk_self_sigs): * misc.c (openpgp_md_map_name): Check also for the Hx format. (openpgp_cipher_map_name): Check also for the Sx format. (pubkey_get_npkey): Adjusted for changed gcrypt API. (pubkey_get_nskey): Ditto. (pubkey_get_nsig): Ditto. (pubkey_get_nenc): Ditto. 2003-06-18 Werner Koch Finished the bulk of changes for gnupg 1.9. This included switching to libgcrypt functions, using shared error codes from libgpg-error, replacing the old functions we used to have in ../util by those in ../jnlib and ../common, renaming the malloc functions and a couple of types. Note, that not all changes are listed below becuause they are too similar and done at far too many places. As of today the code builds using the current libgcrypt from CVS but it is very unlikely that it actually works. * sig-check.c (cmp_help): Removed. Was never used. * pkglue.c: New. Most stuff taken from gnupg 1.1.2. * pkglue.h: New. * misc.c (pull_in_libs): Removed. * keygen.c (count_chr): New. (ask_user_id): Removed faked RNG support. * misc.c (openpgp_md_map_name,openpgp_cipher_map_name) (openpgp_pk_map_name): New. * skclist.c (build_sk_list): Removed faked RNG support. (is_insecure): Removed. * comment.c (make_mpi_comment_node): Use gcry MPI print function. * keyid.c (v3_keyid): New. * misc.c (mpi_write,mpi_write_opaque,mpi_read,mpi_read_opaque) (mpi_print): New. Taken from gnupg 1.1.2. (checksum_mpi): Replaced by implementation from 1.1.2. * g10.c (my_strusage): Renamed from strusage and return NULL instead calling a default function. (add_to_strlist2): New. Taken from ../util/strgutil.c of gnupg 1.2. * plaintext.c (handle_plaintext): New arg CREATE_FILE to cope with the fact that gpg-error does not have this error code anymore. * mainproc.c (symkey_decrypt_sesskey): Ditto. * seskey.c (make_session_key): Adjusted for use with libgcrypt. (encode_session_key): Ditto. (do_encode_md): Ditto. (encode_md_value): Ditto. * keyring.c: Use libgpg-error instead of READ_ERROR etc. * g10.c: Adjusted all algorithm name/id mapping functions. (set_debug): Pass MPI and CRYPTO debug values to libgcrypt. * Makefile.am (INCLUDES): Define LOCALEDIR and the default error source. * g10.c (i18n_init): s/G10_LOCALEDIR/LOCALEDIR/. Renamed m_alloc et al to xmalloc et al. s/g10_errstr/gpg_strerror/ s/MPI/gcry_mpi_t/ Adjusted all md_open calls to the libgcrypt API. * build-packet.c (do_comment): Return error code from iobuf write function. (do_user_id): Ditto. (do_public_key): Ditto. * Makefile.am: Add new files, link gpg with libgpg-error. * g10.c, options.h: New option --agent-program. * call-agent.c: New. * gpg.h, call-agent.h: New. 2003-06-03 David Shaw * options.h, g10.c (main), keylist.c (list_keyblock_print): Add "show-validity" and "show-long-keyid" list-options. * gpgv.c (get_validity, trust_value_to_string): Stubs. * g10.c (main): Use SAFE_VERSION instead of VERSION in the version-specific gpg.conf file so it can be overridden on RISCOS. 2003-06-01 David Shaw * g10.c (main), keylist.c (show_policy_url, show_notation), mainproc.c (check_sig_and_print): Emulate the old policy and notation behavior (display by default). Send to status-fd whether it is displayed on the screen or not. * g10.c (main): Since we now have some options in devel that won't work in a stable branch gpg.conf file, try for a version-specific gpg.conf-VERSION file before falling back to gpg.conf. * main.h, options.h: Move various option flags to options.h. 2003-05-31 David Shaw * mainproc.c (check_sig_and_print), main.h, keylist.c (show_policy, show_notation): Collapse the old print_notation_data into show_policy() and show_notation() so there is only one function to print notations and policy URLs. * options.h, main.h, g10.c (main), keyedit.c (print_and_check_one_sig), keylist.c (list_one, list_keyblock_print), pkclist.c (do_edit_ownertrust), sign.c (mk_notation_and_policy): New "list-options" and "verify-options" commands. These replace the existing --show-photos/--no-show-photos, --show-notation/--no-show-notation, --show-policy-url/--no-show-policy-url, and --show-keyring options. The new method is more flexible since a user can specify (for example) showing photos during sig verification, but not in key listings. The old options are emulated. * main.h, misc.c (parse_options): New general option line parser. Fix the bug in the old version that did not handle report syntax errors after a valid entry. * import.c (parse_import_options), export.c (parse_export_options): Call it here instead of duplicating the code. 2003-05-30 David Shaw * keylist.c (list_one): Don't show the keyring filename when in --with-colons mode. Actually translate "Keyring" string. * mainproc.c (proc_tree): We can't currently handle multiple signatures of different classes or digests (we'd pretty much have to run a different hash context for each), but if they are all the same, make an exception. This is Debian bug #194292. * sig-check.c (check_key_signature2): Make string translatable. * packet.h, getkey.c (fixup_uidnode): Mark real primary uids differently than assumed primaries. * keyedit.c (no_primary_warning): Use the differently marked primaries here in a new function to warn when an --edit-key command might rearrange the self-sig dates enough to change which uid is primary. (menu_expire, menu_set_preferences): Use no_primary_warning() here. * Makefile.am: Use @DLLIBS@ for -ldl. 2003-05-26 David Shaw * getkey.c (premerge_public_with_secret): Made "no secret subkey for" warning a verbose item and translatable. (From wk on stable branch) * sig-check.c (check_key_signature2): Made "no subkey for subkey binding packet" a verbose item instead of a !quiet one. There are too many garbled keys out in the wild. (From wk on stable branch) * filter.h: Remove const from WHAT. (From wk on stable branch) * progress.c (handle_progress): Store a copy of NAME. (progress_filter): Release WHAT, make sure not to print a NULL WHAT. (From wk on stable branch) * openfile.c (open_sigfile): Adjust free for new progress semantics. (From wk on stable branch) * plaintext.c (ask_for_detached_datafile): Don't dealloc pfx->WHAT. (From wk on stable branch) * seckey-cert.c (do_check): Issue the RSA_OR_IDEA status when the cipher algo is IDEA to make it easier to track down the problem. (From twoaday on stable branch) 2003-05-24 David Shaw * armor.c, g10.c, kbnode.c, misc.c, pkclist.c, sign.c, build-packet.c, getkey.c, keydb.c, openfile.c, plaintext.c, status.c, gpgv.c, keygen.c, options.h, sig-check.c, tdbio.h, encode.c, mainproc.c, parse-packet.c, signal.c, textfilter.c: Edit all preprocessor instructions to remove whitespace before the '#'. This is not required by C89, but there are some compilers out there that don't like it. 2003-05-21 David Shaw * trustdb.h, trustdb.c (is_disabled), gpgv.c (is_disabled): Rename is_disabled to cache_disabled_value, which now takes a pk and not just the keyid. This is for speed since there is no need to re-fetch a key when we already have that key handy. Cache the result of the check so we don't need to hit the trustdb more than once. * getkey.c (skip_disabled): New function to get a pk and call is_disabled on it. (key_byname): Use it here. * packet.h, getkey.c (skip_disabled), keylist.c (print_capabilities): New "pk_is_disabled" macro to retrieve the cached disabled value if available, and fill it in via cache_disabled_value if not available. * trustdb.c (get_validity): Cache the disabled value since we have it handy and it might be useful later. * parse-packet.c (parse_key): Clear disabled flag when parsing a new key. Just in case someone forgets to clear the whole key. * getkey.c (merge_selfsigs_main): Add an "if all else fails" path for setting a single user ID primary when there are multiple set primaries all at the same second, or no primaries set and the most recent user IDs are at the same second, or no signed user IDs at all. This is arbitrary, but deterministic. * exec.h, photoid.h: Add copyright message. * keylist.c (list_keyblock_print): Don't dump attribs for revoked/expired/etc uids for non-colon key listings. This is for consistency with --show-photos. * main.h, keylist.c (dump_attribs), mainproc.c (check_sig_and_print): Dump attribs if --attrib-fd is set when verifying signatures. * g10.c (main): New --gnupg option to disable the various --openpgp, --pgpX, etc. options. This is the same as --no-XXXX for those options. * revoke.c (ask_revocation_reason): Clear old reason if user elects to repeat question. This is bug 153. * keyedit.c (sign_uids): Show keyid of the key making the signature. 2003-05-21 Werner Koch * progress.c (handle_progress) * sign.c (write_plaintext_packet) * encode.c (encode_simple,encode_crypt): Make sure that a filename of "-" is considered to be stdin so that iobuf_get_filelength won't get called. This fixes bug 156 reported by Gregery Barton. 2003-05-02 David Shaw * packet.h, build-packet.c (build_sig_subpkt), export.c (do_export_stream), import.c (remove_bad_stuff, import), parse-packet.c (dump_sig_subpkt, parse_one_sig_subpkt): Remove vestigal code for the old sig cache subpacket. This wasn't completely harmless as it caused subpacket 101 to disappear on import and export. * options.h, armor.c, cipher.c, g10.c, keyedit.c, pkclist.c, sign.c, encode.c, getkey.c, revoke.c: The current flags for different levels of PGP-ness are massively complex. This is step one in simplifying them. No functional change yet, just use a macro to check for compliance level. * sign.c (sign_file): Fix bug that causes spurious compression preference warning. * sign.c (clearsign_file): Fix bug that prevents proper warning message from appearing when clearsigning in --pgp2 mode with a non-v3 RSA key. * main.h, misc.c (compliance_option_string, compliance_string, compliance_failure), pkclist.c (build_pk_list), sign.c (sign_file, clearsign_file), encode.c (encode_crypt, write_pubkey_enc_from_list): New functions to put the "this message may not be usable...." warning in one place. * options.h, g10.c (main): Part two of the simplification. Use a single enum to indicate what we are compliant to (1991, 2440, PGPx, etc.) * g10.c (main): Show errors for failure in export, send-keys, recv-keys, and refresh-keys. * options.h, g10.c (main): Give algorithm warnings for algorithms chosen against the --pgpX and --openpgp rules. * keydb.h, pkclist.c (algo_available): Make TIGER192 invalid in --openpgp mode. * sign.c (sign_file), pkclist.c (algo_available): Allow passing a hint of 0. 2003-05-01 David Shaw * tdbio.c (create_version_record): Only create new trustdbs with TM_CLASSIC or TM_PGP. * trustdb.h, trustdb.c (trust_string, get_ownertrust_string, get_validity_string, ask_ownertrust, validate_keys), pkclist.c (do_edit_ownertrust): Rename trust_string to trust_value_to_string for naming consistency. * trustdb.h, trustdb.c (string_to_trust_value): New function to translate a string to a trust value. * g10.c (main): Use string_to_trust_value here for --force-ownertrust. * options.h, g10.c (main), trustdb.c (trust_model_string, init_trustdb, check_trustdb, update_trustdb, get_validity, validate_one_keyblock): An "OpenPGP" trust model is misleading since there is no official OpenPGP trust model. Use "PGP" instead. 2003-04-30 David Shaw * build-packet.c (build_sig_subpkt): Comments. * exec.c (exec_write): Cast NULL to void* to properly terminate varargs list. * keyedit.c (show_key_with_all_names): Just for safety, catch an invalid pk algorithm. * sign.c (make_keysig_packet): Crucial that the call to mksubpkt comes LAST before the calls to finalize the sig as that makes it possible for the mksubpkt function to get a reliable pointer to the subpacket area. * pkclist.c (do_we_trust_pre): If an untrusted key was chosen by a particular user ID, use that ID as the one to ask about when prompting whether to use the key anyway. (build_pk_list): Similar change here when adding keys to the recipient list. * trustdb.c (update_validity): Fix bug that prevented more than one validity record per trust record. (get_validity): When retrieving validity for a (user) supplied user ID, return the validity for that user ID only, and do not fall back to the general key validity. (validate_one_keyblock): Some commentary on whether non-self-signed user IDs belong in the web of trust (arguably, they do). 2003-04-27 David Shaw * g10.c (main): Add --no-textmode. * export.c (do_export_stream), keyedit.c (show_key_with_all_names, menu_addrevoker), mainproc.c (check_sig_and_print), photoid.c (show_photos), sign.c (mk_notation_and_policy), trustdb.c (get_validity, reset_trust_records, validate_keys): Make some strings translatable. * mainproc.c (check_sig_and_print): Show digest algorithm and sig class when verifying a sig with --verbose on, and add version, pk and hash algorithms and sig class to VALIDSIG. * parse-packet.c (enum_sig_subpkt): Make a warning message a --verbose warning message since we don't need to warn every time we see an unknown critical (we only need to invalidate the signature). * trustdb.c (init_trustdb): Check the trustdb options even with TM_AUTO since the auto may become TM_CLASSIC or TM_OPENPGP. 2003-04-26 David Shaw * sign.c (do_sign): Show the hash used when making a signature in verbose mode. * tdbio.h, tdbio.c (tdbio_read_model): New function to return the trust model used in a given trustdb. * options.h, g10.c (main), trustdb.c (init_trustdb, check_trustdb, update_trustdb): Use tdbio_read_model to implement an "auto" trust model which is set via the trustdb. 2003-04-23 David Shaw * import.c (import_revoke_cert): Remove ultimate trust when revoking an ultimately trusted key. * keyedit.c (sign_uids): Allow replacing expired signatures. Allow duplicate signatures with --expert. * pkclist.c (check_signatures_trust): Don't display a null fingerprint when checking a signature with --always-trust enabled. * filter.h (progress_filter_context_t), progress.c (handle_progress), plaintext.c (ask_for_detached_datafile, hash_datafiles): Fix compiler warnings. Make "what" constant. * build-packet.c (do_plaintext): Do not create invalid literal packets with >255-byte names. 2003-04-15 Werner Koch * Makefile.am (AM_CFLAGS): Make use of AM_CFLAGS and AM_LDFLAGS. * g10.c, options.h: New option --enable-progress-filter. * progress.c (handle_progress): Make use of it. 2003-04-15 Marcus Brinkmann * progress.c: New file. * Makefile.am (common_source): Add progress.c. * filter.h (progress_filter_context_t): New type. (progress_filter, handle_progress): New prototypes. * main.h (open_sigfile): New argument for prototype. * openfile.c (open_sigfile): New argument to install progress filter. * encode.c (encode_simple): New variable PFX. Register progress filter. Install text_filter after that. (encode_crypt): Likewise. * sign.c (sign_file): Likewise. (clearsign_file): Likewise. * decrypt.c (decrypt_message): Likewise. (decrypt_messages): Likewise. * verify.c (verify_signatures): Likewise. (verify_one_file): Likewise. * plaintext.c (hash_datafiles): Likewise. (ask_for_detached_datafile): Likewise. 2003-04-10 Werner Koch * passphrase.c (read_passphrase_from_fd): Do a dummy read if the agent is to be used. Noted by Ingo Klöcker. (agent_get_passphrase): Inhibit caching when we have no fingerprint. This is required for key generation as well as for symmetric only encryption. * passphrase .c (agent_get_passphrase): New arg CANCELED. (passphrase_to_dek): Ditto. Passed to above. Changed all callers to pass NULL. * seckey-cert.c (do_check): New arg CANCELED. (check_secret_key): Terminate loop when canceled. * keyedit.c (change_passphrase): Pass ERRTEXT untranslated to passphrase_to_dek and translate where appropriate. * seckey-cert.c (check_secret_key): Ditto. * keygen.c (ask_passphrase): Ditto. * passphrase.c (agent_get_passphrase): Translate the TRYAGAIN_TEXT. Switch the codeset to utf-8. 2003-04-09 Werner Koch * decrypt.c (decrypt_messages): Fixed error handling; the function used to re-loop with same file after an error. Reported by Joseph Walton. 2003-04-08 David Shaw * main.h, g10.c (main), import.c (parse_import_options, fix_pks_corruption): It's really PKS corruption, not HKP corruption. Keep the old repair-hkp-subkey-bug command as an alias. * g10.c (main): Rename --no-version to --no-emit-version for consistency. Keep --no-version as an alias. 2003-04-04 David Shaw * pkclist.c (algo_available): PGP 8 can use the SHA-256 hash. * sign.c (sign_file, clearsign_file, sign_symencrypt_file): Remove unused code. 2003-04-01 Werner Koch * mainproc.c (check_sig_and_print): Add primary key fpr to VALIDSIG status. 2003-03-24 David Shaw * keydb.h: Err on the side of making an unknown signature a SIG rather than a CERT. * import.c (delete_inv_parts): Discard any key signatures that aren't key types (i.e. 0x00, 0x01, etc.) * g10.c (main): Add deprecated option warning for --list-ownertrust. Add --compression-algo alias for --compress-algo. Change --version output strings to match "showpref" strings, and make translatable. * status.c (do_get_from_fd): Accept 'y' as well as 'Y' for --command-fd boolean input. * trustdb.c: Fix typo (DISABLE_REGEXP -> DISABLE_REGEX) * keyedit.c (show_key_with_all_names_colon): Show no-ks-modify flag. 2003-03-11 David Shaw * options.h, g10.c (main), keyserver.c (kopts): Add "try-dns-srv" keyserver option. Defaults to on. * passphrase.c (agent_get_passphrase): Fix memory leak with symmetric messages. Fix segfault with symmetric messages. Fix incorrect prompt with symmetric messages. 2003-03-10 Werner Koch * compress.c (init_uncompress): Use a 15 bit window size so that the output of implementations which don't run for PGP 2 compatibility won't get garbled. 2003-03-04 David Shaw * trustdb.c (validate_keys): Mask the ownertrust when building the list of fully valid keys so that disabled keys are still counted in the web of trust. (get_ownertrust_with_min): Do the same for the minimum ownertrust calculation. * parse-packet.c (dump_sig_subpkt): Show the notation names for not-human-readable notations. Fix cosmetic off-by-one length counter. * options.skel: Add explantion and commented-out "no-mangle-dos-filenames". * mainproc.c (proc_encrypted): Make string translatable. * keyserver.c (keyserver_spawn): Quote ':', '%', and any 8-bit characters in the uid strings sent to the keyserver helper. * keyring.c (keyring_rebuild_cache): Lock the keyring while rebuilding the signature caches to prevent another gpg from tampering with the temporary copy. * keygen.c (keygen_set_std_prefs): Include AES192 and AES256 in default prefs. * keyedit.c (show_prefs): Make strings translatable. * keydb.c: Double the maximum number of keyrings to 40. * gpgv.c (main): Fix bug #113 - gpgv should accept the --ignore-time-conflict option. * g10.c (main): --openpgp disables --pgpX. Double the amount of secure memory to 32k (keys are getting bigger these days). * Makefile.am: Makefile.am: Use @CAPLIBS@ to link in -lcap if we are using capabilities. 2003-02-26 David Shaw * keyserver.c (keyserver_spawn): Include various pieces of information about the key in the data sent to the keyserver helper. This allows the helper to use it in instructing a remote server which may not have any actual OpenPGP smarts in parsing keys. * main.h, export.c (export_pubkeys_stream, do_export_stream): Add ability to return only the first match in an exported keyblock for keyserver usage. This should be replaced at some point with a more flexible solution where each key can be armored seperately. 2003-02-22 David Shaw * sign.c (sign_file): Do not push textmode filter onto an unopened IOBUF (segfault). Noted by Marcus Brinkmann. Push and reinitialize textmode filter for each file in a multiple file list. * packet.h, getkey.c (fixup_uidnode), keyedit.c (show_prefs): Set and show the keyserver no-modify flag. * keygen.c (add_keyserver_modify): New. (keygen_upd_std_prefs): Call it here. (keygen_set_std_prefs): Accept "ks-modify" and "no-ks-modify" as prefs to set and unset keyserver modify flag. * g10.c (main): Accept "s1" in addition to "idea" to match the other ciphers. * main.h, misc.c (idea_cipher_warn): We don't need this if IDEA has been disabled. 2003-02-21 David Shaw * keygen.c (keygen_set_std_prefs): Don't put AES or CAST5 in default prefs if they are disabled. * g10.c (main): Use 3DES instead of CAST5 if we don't have CAST5 support. Use 3DES for the s2k cipher in --openpgp mode. (print_mds): #ifdef all of the optional digest algorithms. 2003-02-12 David Shaw * keydb.h, getkey.c (classify_user_id, classify_user_id2): Make 'exact' a per-desc item. Merge into one function since 'force_exact' is no longer needed. (key_byname): Use new classify_user_id function, and new exact flag in KEYDB_SEARCH_DESC. * keyring.h, keyring.c (keyring_search): Return an optional index to show which KEYDB_SEARCH_DESC was the matching one. * keydb.h, keydb.c (keydb_search): Rename to keydb_search2, and pass the optional index to keyring_search. Add a macro version of keydb_search that calls this new function. * export.c (do_export_stream): If the keyid! syntax is used, export only that specified key. If the key in question is a subkey, export the primary plus that subkey only. 2003-02-11 David Shaw * exec.c (set_exec_path): Add debugging line. * g10.c (print_hex, print_mds): Print long hash strings a lot neater. This assumes at least an 80-character display, as there are a few other similar assumptions here and there. Users who need unformatted hashes can still use with-colons. Check that SHA384 and 512 are available before using them as they are no longer always available. * Makefile.am: Use a local copy of libexecdir along with @PACKAGE@ as GNUPG_LIBEXECDIR so it can be easily overridden at make time. 2003-02-04 David Shaw * armor.c (parse_hash_header, armor_filter): Accept the new SHAs in the armor Hash: header. * g10.c (print_hex): Print long hash strings a little neater. (print_mds): Add the new SHAs to the hash list. 2003-02-02 David Shaw * keyedit.c (menu_revuid): Properly handle a nonselfsigned uid on a v4 key (treat as a v4 revocation). * import.c (print_import_check): Do not re-utf8 convert user IDs. 2003-01-27 David Shaw * mainproc.c (list_node): Show signature expiration date in with-colons sig records. * keylist.c (list_keyblock_colon), mainproc.c (list_node): Show trust sig information in with-colons sig records. 2003-01-16 David Shaw * g10.c (add_group): Trim whitespace after a group name so it does not matter where the user puts the = sign. * options.skel: Comment out the first three lines in case someone manually copies the skel file to their homedir. * sign.c (clearsign_file): Only use pgp2mode with v3 keys and MD5. This matches what we do when decoding such messages and prevents creating a message (v3+RIPEMD/160) that we can't verify. * sig-check.c (signature_check2): Use G10ERR_GENERAL as the error for signature digest conflict. BAD_SIGN implies that a signature was checked and we may try and print out a user ID for a key that doesn't exist. 2003-01-15 David Shaw * trustdb.c (init_trustdb, get_validity): Don't use a changed trust model to indicate a dirty trustdb, and never auto-rebuild a dirty trustdb with the "always" trust model. * g10.c (add_group): Last commit missed the \t ;) 2003-01-14 David Shaw * packet.h, parse-packet.c (setup_user_id), free-packet.c (free_user_id), keydb.h, keyid.c (namehash_from_uid): New function to rmd160-hash the contents of a user ID packet and cache it in the uid object. * keylist.c (list_keyblock_colon): Use namehash in field 8 of uids. Show dates for creation (selfsig date), and expiration in fields 6 and 7. * trustdb.c (get_validity, get_validity_counts, update_validity): Use new namehash function rather than hashing it locally. 2003-01-14 Werner Koch * g10.c (add_group): Fixed group parsing to allow more than one delimiter in a row and also allow tab as delimiter. 2003-01-12 David Shaw * tdbio.c (tdbio_set_dbname): Fix assertion failure with non-fully-qualified trustdb names. 2003-01-11 David Shaw * trustdb.c (get_validity_info, get_ownertrust_info, trust_letter): Simplify by returning a ? for error directly. * keyedit.c (show_key_with_all_names): Use get_validity_string and get_ownertrust_string to show full word versions of trust (i.e. "full" instead of 'f'). * trustdb.h, trustdb.c (get_ownertrust_string, get_validity_string): Same as get_ownertrust_info, and get_validity_info, except returns a full string. * trustdb.c (get_ownertrust_with_min): New. Same as 'get_ownertrust' but takes the min_ownertrust value into account. 2003-01-10 David Shaw * armor.c (armor_filter): Comment about PGP's end of line tab problem. * trustdb.h, trustdb.c (trust_letter): Make static. (get_ownertrust_info, get_validity_info): Don't mask the trust level twice. * trustdb.h, gpgv.c, trustdb.c (get_validity, get_validity_info), keylist.c (list_keyblock_colon), keyedit.c (show_key_with_all_names_colon, menu_revuid): Pass a user ID in rather than a namehash, so we only have to do the hashing in one place. * packet.h, pkclist.c (build_pk_list), free-packet.c (release_public_key_parts): Remove unused namehash element for public keys. 2003-01-07 David Shaw * keygen.c (keygen_set_std_prefs): Warn when setting an IDEA preference when IDEA is not available. 2003-01-06 David Shaw * trustdb.c (get_validity_info): 'd' for disabled is not a validity value any more. * packet.h, tdbio.h, tdbio.c (tdbio_read_record, tdbio_write_record), trustdb.c (update_validity): Store temporary full & marginal counts in the trustdb. (clear_validity, get_validity_counts): Return and clear temp counts. (store_validation_status): Keep track of which keyids have been stored. (validate_one_keyblock, validate_key_list): Use per-uid copies of the full & marginal counts so they can be recalled for multiple levels. (validate_keys): Only use unused keys for each new round. (reset_unconnected_keys): Rename to reset_trust_records, and only skip specifically excluded records. * keylist.c (print_capabilities): Show 'D' for disabled keys in capabilities section. * trustdb.c (is_disabled): Remove incorrect comment. 2003-01-03 David Shaw * import.c (import_one): Only do the work to create the status display for interactive import if status is enabled. * keyring.c (keyring_search): skipfnc didn't work properly with non-keyid searches. Noted by Stefan Bellon. * getkey.c (merge_selfsigs_main): Remove some unused code and make sure that the pk selfsigversion member accounts for 1F direct sigs. 2003-01-02 Werner Koch * keydb.c (keydb_add_resource): Don't assume that try_make_homedir terminates but check again for the existence of the directory and continue then. * openfile.c (copy_options_file): Print a warning if the skeleton file has active options. 2002-12-29 David Shaw * getkey.c (merge_selfsigs_main), main.h, sig-check.c (check_key_signature2): Pass the ultimately trusted pk directly to check_key_signature2 to avoid going through the key selection mechanism. This prevents a deadly embrace when two keys without selfsigs each sign the other. 2002-12-27 David Shaw * keyserver.c (keyserver_refresh): Don't print the "refreshing..." line if there are no keys to refresh or if there is no keyserver set. * getkey.c (merge_selfsigs_main): Any valid user ID should make a key valid, not just the last one. This also fixes Debian bug #174276. 2002-12-27 Stefan Bellon * import.c (print_import_check): Changed int to size_t. 2002-12-27 David Shaw * keyedit.c (keyedit_menu, menu_revuid): Add "revuid" feature to revoke a user ID. This is the same as issuing a revocation for the self-signature, but a much simpler interface to do it. 2002-12-26 David Shaw * keydb.h, getkey.c (key_byname): Flag to enable or disable including disabled keys. Keys specified via keyid (i.e. 0x...) are always included. * getkey.c (get_pubkey_byname, get_seckey_byname2, get_seckey_bynames), keyedit.c (keyedit_menu, menu_addrevoker): Include disabled keys in these functions. * pkclist.c (build_pk_list): Do not include disabled keys for -r or the key prompt. Do include disabled keys for the default key and --encrypt-to. * trustdb.h, trustdb.c (is_disabled): New skipfnc for skipping disabled keys. * gpgv.c (is_disabled): Stub. * keygen.c (keygen_add_key_expire): Properly handle updating a key expiration to a no-expiration value. * keyedit.c (enable_disable_key): Comment. * import.c (import_one): When in interactive mode and --verbose, don't repeat some key information twice. 2002-12-22 Timo Schulz * import.c (print_import_check): New. (import_one): Use it here. Use merge_keys_and_selfsig in the interactive mode to avoid wrong key information. * status.h: Add new status code. * status.c: Ditto. 2002-12-13 David Shaw * pkclist.c (do_we_trust): Tweak language to refer to the "named user" rather than "owner". Noted by Stefan Bellon. * trustdb.h, trustdb.c (trustdb_pending_check): New function to check if the trustdb needs a check. * import.c (import_keys_internal): Used here so we don't rebuild the trustdb if it is still clean. (import_one, chk_self_sigs): Only mark trustdb dirty if the key that is being imported has any sigs other than self-sigs. Suggested by Adrian von Bidder. * options.skel: Include the required '=' sign in the sample 'group' option. Noted by Stefan Bellon. * import.c (chk_self_sigs): Don't try and check a subkey as if it was a signature. 2002-12-11 David Shaw * tdbio.c (tdbio_read_record, tdbio_write_record): Compact the RECTYPE_TRUST records a bit. * g10.c (main): Comment out --list-trust-path until it can be implemented. * import.c (import_one): Warn when importing an Elgamal primary that this may take some time (to verify self-sigs). (chk_self_sigs): Try and cache all self-sigs so the keyblock is written to the keyring with a good rich cache. * keygen.c (ask_algo): Make the Elgamal sign+encrypt warning stronger, and remove the RSA sign+encrypt warning. 2002-12-06 Stefan Bellon * options.h: Fixed typo (mangle_dos_names instead of mangle_dos_filenames). 2002-12-05 Werner Koch * g10.c: New options --[no-]mangle-dos-filenames. * options.h (opt): Added mangle-dos-filenames. * openfile.c (open_outfile) [USE_ONLY_8DOT3]: Truncate the filename only when this option is set; this is the default. 2002-12-04 David Shaw * main.h, keyedit.c, keygen.c: Back out previous (2002-12-01) change. Minimal isn't always best. * sign.c (update_keysig_packet): Use the current time rather then a modification of the original signature time. Make sure that this doesn't cause a time warp. * keygen.c (keygen_add_key_expire): Properly handle a key expiration date in the past (use a duration of 0). * keyedit.c (menu_expire): Use update_keysig_packet so any sig subpackets are maintained during the update. * build-packet.c (build_sig_subpkt): Mark sig expired or unexpired when the sig expiration subpacket is added. (build_sig_subpkt_from_sig): Handle making an expiration subpacket from a sig that has already expired (use a duration of 0). * packet.h, sign.c (update_keysig_packet), keyedit.c (menu_set_primary_uid, menu_set_preferences): Add ability to issue 0x18 subkey binding sigs to update_keysig_packet and change all callers. * trustdb.c (validate_keys): Show trust parameters when building the trustdb, and make sure that the version record update was successful. (init_trustdb): If the current parameters aren't what was used for building the trustdb, the trustdb is invalid. * tbio.c (tdbio_db_matches_options): Update to work with new trustdbs. 2002-12-03 David Shaw * tdbio.h, tdbio.c (tdbio_read_record, tdbio_write_record): Store trust model in the trustdb version record. (tdbio_update_version_record): New function to update version record values during a trustdb check or update. (tdbio_dump_record): Show trust model in dump. * trustdb.c (validate_keys): Call tdbio_update_version_record on success so that the correct options are stored in the trustdb. * options.h: rearrange trust models so that CLASSIC is 0 and OPENPGP is 1. * options.h, g10.c (main), encode.c (write_pubkey_enc_from_list), pkclist.c (algo_available), revoke.c (gen_revoke): Add --pgp8 mode. This is basically identical to --pgp7 in all ways except that signing subkeys, v4 data sigs (including expiration), and SK comments are allowed. * getkey.c (finish_lookup): Comment. * main.h, keylist.c (reorder_keyblock), keyedit.c (keyedit_menu): Reorder user ID display in the --edit-key menu to match that of the --list-keys display. * g10.c (add_notation_data): Fix initialization. 2002-12-01 David Shaw * keyedit.c (menu_expire): Don't lose key flags when changing the expiration date of a subkey. This is not the most optimal solution, but it is minimal change on the stable branch. * main.h, keygen.c (do_copy_key_flags): New function to copy key flags, if any, from one sig to another. (do_add_key_expire): New function to add key expiration to a sig. (keygen_copy_flags_add_expire): New version of keygen_add_key_expire that also copies key flags. (keygen_add_key_flags_and_expire): Use do_add_key_expire. * import.c (fix_hkp_corruption): Comment. 2002-11-25 Stefan Bellon * plaintext.c (handle_plaintext) [__riscos__]: If nooutput is set, no filetype is needed obviously. 2002-11-24 David Shaw * main.h, misc.c (default_cipher_algo, default_compress_algo): New. Return the default algorithm by trying --cipher-algo/--compress-algo, then the first item in the pref list, then s2k-cipher-algo or ZIP. * sign.c (sign_file, sign_symencrypt_file), encode.c (encode_simple, encode_crypt): Call default_cipher_algo and default_compress_algo to get algorithms. * g10.c (main): Allow pref selection for compress algo with --openpgp. * mainproc.c (proc_encrypted): Use --s2k-digest-algo for passphrase mangling rather than --digest-algo. * sign.c (hash_for): If --digest-algo is not set, but --personal-digest-preferences is, then use the first hash algorithm in the personal list. If the signing algorithm is DSA, then use the first 160-bit hash algorithm in the personal list. If --pgp2 is set and it's a v3 RSA key, use MD5. * g10.c (main), keydb.c (keydb_add_resource, keydb_locate_writable): Rename --default-keyring as --primary-keyring. Stefan wins the naming contest. 2002-11-23 David Shaw * g10.c (add_notation_data): Disallow notation names that do not contain a '@', unless --expert is set. This is to help prevent people from polluting the (as yet unused) IETF namespace. * main.h: Comments about default algorithms. * photoid.c (image_type_to_string): Comments about 3-letter file extensions. * encode.c (encode_simple), passphrase.c (passphrase_to_dek), sign.c (sign_symencrypt_file): Use --s2k-digest-algo for passphrase mangling rather than --digest-algo. 2002-11-21 David Shaw * keygen.c (keygen_set_std_prefs): Properly handle an empty preference string. * misc.c (string_to_compress_algo): "none" is a bad choice since it conflicts with the "none" in setpref. 2002-11-14 David Shaw * g10.c (main): Allow compression algorithm names as the argument to --compress-algo. The old algorithm names still work for backwards compatibility. * misc.c (string_to_compress_algo): Allow "none" as an alias for "uncompressed". 2002-11-13 Stefan Bellon * getkey.c (get_pubkey_byfprint_fast): Fixed type incompatibility, was unsigned char instead of byte. 2002-11-13 David Shaw * encode.c (encode_simple): Make sure that files larger than about 4G use partial length encoding. This is required because OpenPGP allows only for 32 bit length fields. From Werner on stable branch. * getkey.c (get_pubkey_direct): Renamed to... (get_pubkey_fast): this and made extern. (get_pubkey_byfprint_fast): New. From Werner on stable branch. * keydb.h, import.c (import_one): Use get_pubkey_fast instead of get_pubkey. We don't need a merged key and actually this might lead to recursions. (revocation_present): Likewise for search by fingerprint. From Werner on stable branch. * g10.c (main): Try to create the trustdb even for non-colon-mode list-key operations. This is required because getkey needs to know whether a a key is ultimately trusted. From Werner on stable branch. * exec.c [__CYGWIN32__]: Keep cygwin separate from Mingw32; we don't need it here as it behaves more like a Posix system. From Werner on stable branch. * passphrase.c (agent_get_passphrase): Ditto. From Werner on stable branch. * tdbio.c (MY_O_BINARY): Need binary mode with Cygwin. From Werner on stable branch. * g10.c, gpgv.c (main) [__CYGWIN32__]: Don't get the homedir from the registry. From Werner on stable branch. * keyedit.c (show_key_with_all_names_colon): Make --with-colons --edit display match the validity and trust of --with-colons --list-keys. * passphrase.c (agent_send_all_options): Fix compile warning. * keylist.c (list_keyblock_colon): Validity for subkeys should match that of the primary key, and not that of the last user ID. * getkey.c (merge_selfsigs): Revoked/expired/invalid primary keys carry these facts onto all their subkeys, but only after the subkey has a chance to be marked valid. This is to fix an incorrect "invalid public key" error verifying a signature made by a revoked signing subkey, with a valid unrevoked primary key. 2002-11-09 Werner Koch * passphrase.c (agent_send_all_options): Use tty_get_ttyname to get the default ttyname. 2002-11-07 David Shaw * keyring.h, keyring.c (keyring_register_filename): Return the pointer if a given keyring is registered twice. * keydb.h, keydb.c (keydb_add_resource): Use flags to indicate a default keyring. (keydb_locate_writable): Prefer the default keyring if possible. * g10.c (main): Add --default-keyring option. 2002-11-06 David Shaw * options.h, g10.c (main), trustdb.c (ask_ownertrust): Add --force-ownertrust option for debugging purposes. This allows setting a whole keyring to a given trust during an --update-trustdb. Not for normal use - it's just easier than hitting "4" all the time to test a large trustdb. * pubkey-enc.c (get_session_key): With hidden recipients or try a given passphrase against all secret keys rather than trying all secret keys in turn. Don't if --try-all-secrets or --status-fd is enabled. * passphrase.c (passphrase_to_dek): Mode 1 means do a regular passphrase query, but don't prompt with the key info. * seckey-cert.c (do_check, check_secret_key): A negative ask count means to enable passphrase mode 1. * keydb.h, getkey.c (enum_secret_keys): Add flag to include secret-parts-missing keys (or not) in the list. 2002-11-05 David Shaw * keyserver.c (keyserver_search_prompt): When --with-colons is enabled, don't try and fit the search output to the screen size - just dump the whole list. 2002-11-04 David Shaw * keyserver.c (keyserver_search_prompt): When --with-colons is enabled, just dump the raw keyserver protocol to stdout and don't print the menu. * keyserver.c (show_prompt): Don't show a prompt when command-fd is being used. * trustdb.c (trust_model_string, check_trustdb, update_trustdb, validate_one_keyblock): It's not clear what a trustdb rebuild or check means with a trust model other than "classic" or "openpgp", so disallow this. 2002-11-03 David Shaw * options.h, g10.c (main): Add --trust-model option. Current models are "openpgp" which is classic+trustsigs, "classic" which is classic only, and "always" which is the same as the current option --always-trust (which still works). Default is "openpgp". * trustdb.c (validate_one_keyblock): Use "openpgp" trust model to enable trust sigs. * gpgv.c (main), mainproc.c (check_sig_and_print), pkclist.c (do_we_trust, do_we_trust_pre, check_signatures_trust): Use new --trust-model option in place of --always-trust. * keyedit.c (sign_mk_attrib, trustsig_prompt, sign_uids, keyedit_menu): Prompt for and create a trust signature with "tsign". This is functional, but needs better UI text. * build-packet.c (build_sig_subpkt): Able to build trust and regexp subpackets. * pkclist.c (do_edit_ownertrust): Comment. 2002-11-02 David Shaw * keygen.c (set_one_pref, keygen_set_std_prefs): Allow using the full algorithm name (CAST5, SHA1) rather than the short form (S3, H2). * main.h, keygen.c (keygen_get_std_prefs), keyedit.c (keyedit_menu): Return and use a fake uid packet rather than a string since we already have a nice parser/printer in keyedit.c:show_prefs. * main.h, misc.c (string_to_compress_algo): New. 2002-11-01 David Shaw * g10.c (main): Add --no-throw-keyid. * keydb.h, encode.c (write_pubkey_enc_from_list), g10.c (main), pkclist.c (build_pk_list): Add --hidden-recipient (-R) and --hidden-encrypt-to, which do a single-user variation on --throw-keyid. The "hide this key" flag is carried in bit 0 of the pk_list flags field. * keyserver.c (parse_keyrec): Fix shadowing warning. 2002-10-31 Stefan Bellon * compress.c (init_compress) [__riscos__]: Use riscos_load_module() to load ZLib module. * g10.c (main) [__riscos__]: Renames due to changes in riscos.c (e.g. prefixes all RISC OS specific functions with riscos_*). * photoid.c (show_photos) [__riscos__]: Likewise. * signal.c (got_fatal_signal) [__riscos__]: Likewise. * trustdb.c (check_regexp) [__riscos__]: Branch to RISC OS RegEx handling. 2002-10-31 David Shaw * build-packet.c (do_plaintext), encode.c (encode_sesskey, encode_simple, encode_crypt), sign.c (write_plaintext_packet): Use wipememory() instead of memset() to wipe sensitive memory as the memset() might be optimized away. 2002-10-30 David Shaw * trustdb.c (check_regexp): Modern regexps require REG_EXTENDED. 2002-10-29 David Shaw * packet.h, trustdb.h, trustdb.c (trust_string): New. Return a string like "fully trusted", "marginally trusted", etc. (get_min_ownertrust): New. Return minimum ownertrust. (update_min_ownertrust): New. Set minimum ownertrust. (check_regexp): New. Check a regular epression against a user ID. (ask_ownertrust): Allow specifying a minimum value. (get_ownertrust_info): Follow the minimum ownertrust when returning a letter. (clear_validity): Remove minimum ownertrust when a key becomes invalid. (release_key_items): Release regexp along with the rest of the info. (validate_one_keyblock, validate_keys): Build a trust sig chain while validating. Call check_regexp for regexps. Use the minimum ownertrust if the user does not specify a genuine ownertrust. * pkclist.c (do_edit_ownertrust): Only allow user to select a trust level greater than the minimum value. * parse-packet.c (can_handle_critical): Can handle critical trust and regexp subpackets. * trustdb.h, trustdb.c (clear_ownertrusts), delkey.c (do_delete_key), import.c (import_one): Rename clear_ownertrust to clear_ownertrusts and have it clear the min_ownertrust value as well. * keylist.c (list_keyblock_print): Indent uid to match pub and sig. * keyedit.c (print_and_check_one_sig, show_key_and_fingerprint, menu_addrevoker), keylist.c (list_keyblock_print, print_fingerprint): Show "T" or the trust depth for trust signatures, and add spaces to some strings to make room for it. * packet.h, parse-packet.c (dump_sig_subpkt, parse_one_sig_subpkt, parse_signature): Parse trust signature values. * tdbio.h, tdbio.c (tdbio_read_record, tdbio_write_record): Reserve a byte for the minimum ownertrust value (for use with trust signatures). 2002-10-29 Stefan Bellon * build-packet.c (calc_plaintext, do_plaintext): Removed RISC OS specific filetype parts (it's now done in make_basename()). * plaintext.c (handle_plaintext): Tidied up RISC OS specific filetype parts. * encode.c (encode_simple, encode_crypt): Added argument to make_basename() call. * sign.c (write_plaintext_packet): Added argument to make_basename() call. 2002-10-28 Stefan Bellon * build-packet.c (calc_plaintext, do_plaintext): Added filetype handling for RISC OS' file types. * plaintext.c (handle_plaintext) [__riscos__]: Added filetype handling for RISC OS' file types. 2002-10-23 David Shaw * main.h, import.c (sec_to_pub_keyblock, import_secret_one, parse_import_options), g10.c (main): New import-option "convert-sk-to-pk" to convert a secret key into a public key during import. It is on by default. 2002-10-23 Werner Koch * pubkey-enc.c (get_it): Fix segv, test for revoked only when PK has been assigned. 2002-10-18 Timo Schulz * keylist.c: (print_pubkey_info): New. (print_seckey_info): New. * main.h: Prototypes for the new functions. * delkey.c (do_delete_key): Use it here. * revoke.c (gen_desig_revoke): Ditto. 2002-10-17 Werner Koch * pkclist.c (do_edit_ownertrust): Show all user IDs. This should be enhanced to also show the current trust level. Suggested by Florian Weimer. 2002-10-17 David Shaw * g10.c (main): Handle --strict and --no-strict from the command line before the options file is loaded. 2002-10-15 David Shaw * g10.c (main): Disable --textmode when encrypting (symmetric or pk) in --pgp2 mode as PGP 2 can't handle the unknown length literal packet. Reported by Michael Richardson. 2002-10-14 David Shaw * keyserver-internal.h, keyserver.c (print_keyrec, parse_keyrec, show_prompt, keyserver_search_prompt, keyserver_spawn): Go to version 1 of the keyserver protocol. This is a better design, similar to --with-colons, that allows for keys with multiple user IDs rather than using multiple keys. It also matches the machine readable pksd format. Also use a prettier --search-keys listing format that can fill different size windows (currently set at 24 lines). 2002-10-12 Werner Koch * keygen.c (print_status_key_created): New. (do_generate_keypair): Use it to print the fingerprint. (generate_subkeypair): Likewise. 2002-10-11 David Shaw * keyedit.c (menu_addrevoker): Properly back out if the signature fails. Also, do not allow appointing the same revoker twice, and report ALREADY_SIGNED if the user tries it. 2002-10-07 David Shaw * import.c (import_keys_internal): Missed one s/inp/inp2/. * keylist.c (print_capabilities): Properly indicate per-key capabilities of sign&encrypt primary keys that have secret-parts-missing (i.e. no capabilities at all) * mainproc.c (symkey_decrypt_sesskey): Fix compiler warning. 2002-10-04 David Shaw * getkey.c (get_pubkey_direct): Don't cache keys retrieved via this function as they may not have all their fields filled in. * sig-check.c (signature_check2): Use new is_primary flag to check rather than comparing main_keyid with keyid as this still works in the case of a not fully filled in pk. 2002-10-04 Werner Koch * import.c (import_keys_internal): s/inp/inp2/ to avoid shadowing warning. * passphrase.c (agent_get_passphrase): Fixed signed/unsigned char problem in %-escaping. Noted by Ingo Klöcker. 2002-10-03 David Shaw * options.h, g10.c (main): Add --strict and --no-strict to switch the log_warning severity level from info to error. * keylist.c (print_capabilities): Secret-parts-missing keys should show that fact in the capabilities, and only primary signing keys can certify other keys. * packet.h, parse_packet.c (parse_key): Add is_primary flag for public keys (it already exists for secret keys). 2002-10-02 David Shaw * import.c (import_secret_one): Check for an illegal (>110) protection cipher when importing a secret key. * keylist.c (list_keyblock_print): Show a '#' for a secret-parts-missing key. * parse_packet.c (parse_key): Some comments. * revoke.c (gen_revoke): Remove some debugging code. * trustdb.c (verify_own_keys): Make trusted-key a non-deprecated option again. * seckey-cert.c (do_check): Don't give the IDEA warning unless the cipher in question is in fact IDEA. 2002-10-01 David Shaw * import.c (import_one): Make sure that a newly imported key starts with a clean ownertrust. 2002-10-01 Werner Koch * getkey.c (get_pubkey_direct): New. (merge_selfsigs_main): Use it here to look for an ultimately trusted key. Using the full get_pubkey might lead to an infinitive recursion. 2002-09-29 David Shaw * keyserver.c (parse_keyserver_uri): Force the keyserver URI scheme to lowercase to be case-insensitive. 2002-09-28 David Shaw * export.c (do_export_stream): Comment. * sig-check.c (check_key_signature2): Properly handle a non-designated revocation import. 2002-09-26 Werner Koch * g10.c (set_homedir): New. Changed all direct assignments to use this. * gpgv.c (set_homedir): Ditto. 2002-09-25 David Shaw * Makefile.am: Link gpg with EGDLIBS (i.e. NETLIBS) as EGD uses sockets. Remove the old NETLIBS variable since the keyserver stuff is no longer internal. 2002-09-24 David Shaw * import.c (import_keys_stream): Fix compiler type warning. * keyring.c (keyring_rebuild_cache), sig-check.c (check_key_signature2), import.c (import, chk_self_sigs): Minor language cleanups. 2002-09-23 Stefan Bellon * main.h: Introduced fast-import as import option. Removed fast as separate option from prototypes. * import.c (parse_import_options): Added fast-import option. (import_*): Removed fast as separate option. * g10.c (main): Added option fast-import, removed old fast as separate argument. * keyserver.c (keyserver_spawn): Removed old fast as separate argument. 2002-09-22 Stefan Bellon * import.c (import_keys, import_keys_stream, import_keys_internal): Added trustdb update/check to key import if not fast-import and interactive set/no-auto-check-trustdb unset. Avoided function clone by introducing import_keys_internal. 2002-09-19 David Shaw * keyserver.c (keyserver_spawn): Properly handle line truncation. Don't leak memory (~10-20 bytes) on searches. (keyserver_search_prompt): Cleanup. * keylist.c (list_keyblock_colon): Show 1F direct key signatures in --with-colons listing. 2002-09-16 David Shaw * keyedit.c (menu_addrevoker): The direct key signature for revocation keys must be at least v4 to carry the revocation key subpacket. Add a PGP 2.x warning for revocation keys. 2002-09-14 David Shaw * g10.c (check_permissions): Rearrange strings to make translating easier (don't incorporate string parts). * keyedit.c (sign_uids): Make strings translatable. * sig-check.c (check_key_signature2): Make string translatable. 2002-09-13 David Shaw * getkey.c (check_revocation_keys): Move.... * main.h, sig-check.c (check_revocation_keys): to here. Also return the signature_check error code rather than 0/1 and cache the sig result. * sig-check.c (check_key_signature2): Divert to check_revocation_keys if a revocation sig is made by someone other than the pk owner. * getkey.c (merge_selfsigs_main): Tidy. 2002-09-13 Werner Koch * g10.c (main) [__MINGW32__]: Activate oLoadExtension. 2002-09-12 David Shaw * Makefile.am, hkp.c, hkp.h, keyserver.c (keyserver_work): Remove internal HKP support. * keyserver.c (keyserver_spawn): Remove whitespace after keyserver commands. 2002-09-10 David Shaw * exec.c (expand_args): Remove loop left over from earlier implementation. (exec_write): Missed one tick. 2002-09-10 Werner Koch * g10.c, options.h: Removed option --emulate-checksum-bug. * misc.c (checksum_u16_nobug): Removed. (checksum_u16): Removed the bug emulation. (checksum_mpi): Ditto. (checksum_mpi_counted_nbits): Removed and replaced all calls with checksum_mpi. * parse-packet.c (read_protected_v3_mpi): New. (parse_key): Use it here to store it as an opaque MPI. * seckey-cert.c (do_check): Changed the v3 unprotection to the new why to store these keys. (protect_secret_key): Likewise. * build-packet.c (do_secret_key): And changed the writing. * tdbio.c (tdbio_set_dbname, open_db): Use new macro MY_O_BINARY to avoid silly ifdefs. (open_db): Fallback to RDONLY so that gpg may be used from a RO-medium. * encode.c (encode_simple): Make sure we don't use an ESK packet when we don't have a salt in the S2K. * misc.c (pct_expando) : Make sure that LEN is initialized. * exec.c (exec_finish): Use ticks to denote filenames in messages. (make_tempdir, exec_write): Changed format of messages. * keyserver.c (print_keyinfo): Release USERID in on error. (keyserver_work) [!DISABLE_KEYSERVER_HELPERS]: Exclude the unused code. 2002-09-09 Werner Koch * parse-packet.c (make_attribute_uidname): Add new ar MAX_NAMELEN for sanity checks. Changed both callers. Limit the size of an %s. * options.skel: Comment lock-once out, so that this file does not change anything when copied to a new home directory. * openfile.c (try_make_homedir): Don't exit after copying the option skeleton. * options.h: Don't use a comma when declaring variables over more than one line. * mainproc.c (symkey_decrypt_sesskey): Check length of the session key. * hkp.c (dehtmlize): Use ascii_tolower to protect against weird locales. Cast the argument for isspace for the sake of broken HP/UXes. (parse_hkp_index): s/ascii_memcasecmp/ascii_strncasecmp/. * g10.c: Removed option --emulate-3des-s2k-bug. * passphrase.c (hash_passphrase): Was used here. * export.c (parse_export_options) * keyserver.c (parse_keyserver_options) * import.c (parse_import_options) * g10.c (check_permissions): s/ascii_memcasecmp/ascii_strncasecmp/. 2002-09-09 David Shaw * g10.c (add_group): Use '=' to separate group name from group members. Use a better error message for when no = is found. * hkp.c (hkp_export): Use CRLF in headers. 2002-09-03 David Shaw * mainproc.c (print_pkenc_list): Don't increment the error counter when printing the list of keys a message was encrypted to. This would make gpg give a non-zero exit code even for completely valid messages if the message was encrypted to more than one key that the user owned. 2002-09-02 Werner Koch * g10.c (main): Try to set a default character set. Print the used one in verbosity level 3. * gpgv.c (main): Try to set a default character set. * status.c, status.h (STATUS_IMPORT_OK): New. * import.c (import_one,import_secret_one): Print new status. 2002-08-30 David Shaw * pkclist.c (build_pk_list): Add new status code to indicate an untrusted user. This (or a disabled key) fail with "unavailable pubkey" (G10ERR_UNU_PUBKEY). * pkclist.c (build_pk_list): Fail if any recipient keys are unusable. * options.skel: The PGP LDAP keyserver is back. Use MIT keyserver as a sample rather than cryptnet as cryptnet does not support searching yet. * keyedit.c (show_key_with_all_names): Fix error message (preferences are userid/selfsig and not key specific). 2002-08-30 Werner Koch * pkclist.c (do_we_trust_pre): Changed the wording of a warning. * encode.c (encode_simple,encode_crypt): Use new style CTB for compressssed packets when using MDC. We need to do this so that concatenated messages are properly decrypted. Old style compression assumes that it is the last packet; given that we can't determine the length in advance, the uncompressor does not know where to start. Actually we should use the new CTB always but this would break PGP 2 compatibility. * parse-packet.c (parse): Special treatment for new style CTB compressed packets. * build-packet.c (do_mdc): Removed. Was not used. (do_encrypted_mdc): Count in the version number and the MDC packet. 2002-08-28 David Shaw * sig-check.c (do_check_messages, do_check): Show keyid in error messages. * keyserver.c (print_keyinfo): More readable key listings for --search-keys responses. 2002-08-26 David Shaw * hkp.c (parse_hkp_index, dehtmlize): Move HTML functionality into new "dehtmlize" function. Remove HTML before trying to parse each line from the keyserver. If the keyserver provides key type information in the listing, use it. 2002-08-23 David Shaw * sig-check.c (do_check, do_check_messages): Emit the usual sig warnings even for cached sigs. This also serves to protect against missing a sig expiring while cached. * getkey.c (merge_selfsigs_main): Don't check UID self-sigs twice. 2002-08-22 David Shaw * import.c (clean_subkeys, chk_self_sigs): Merge clean_subkeys into chk_self_sigs. This improves efficiency as the same signatures are not checked multiple times. Clarify when a subkey is revoked (any revocation signature, even if it is dated before the binding signature). * getkey.c (merge_selfsigs_subkey): Subkey revocation comments. * keylist.c (list_one): Stats are only for public key listings. * g10.c (main), options.skel: Default should be include-revoked for keyserver operations. 2002-08-21 Werner Koch * import.c (import_print_stats): Print new non_imported counter which is currently not used because we terminate on errors. 2002-08-20 David Shaw * options.skel: Document no-include-attributes for keyserver-options. * keylist.c, keyedit.c, keyserver.c, sign.c: Some TODOs and comments. * export.c (do_export_stream): Fix noop bug in exporting sensitive revocation keys. * pkclist.c (do_edit_ownertrust): Comment out the option for showing trust paths until it can be implemented. 2002-08-19 Werner Koch * getkey.c (get_user_id_native): Renamed to .. (get_user_id_printable): this. Filter out all dangerous characters. Checked all usages. (get_user_id_string_native): Renamed to.. (get_user_id_string_printable): this. Filter out all dangerous characters. Checked all usages. * keyedit.c (show_basic_key_info): New. * keylist.c (print_fingerprint): New mode 3. * import.c (import_one): Use new function to display the user ID. 2002-08-16 Timo Schulz * g10.c (main): Enable opt.interactive. * import.c (import_one): Ask the user if the key shall be imported when the interactive mode is used. Useful to extract selected keys from a file. 2002-08-16 Werner Koch * seckey-cert.c: Workaround to allow decryption of v3 keys created with a bug in the mpi_get_secure_buffer. 2002-08-14 David Shaw * hkp.c (parse_hkp_index): Properly handle really large keys (5 digit key length) in HKP searches. 2002-08-13 David Shaw * encode.c (encode_simple): Fix problem with using compression algo 2 and symmetric compressed files. * encode.c (encode_simple, encode_crypt): If we are not using a MDC, compress even if a file is already compressed. This is to help against the chosen ciphertext attack. * pkclist.c (select_algo_from_prefs): Fix requested algorithm bug so the request succeeds even if the requested algorithm is not the first found. * cipher.c (write_header), encode.c (use_mdc, encode_simple, encode_crypt, encrypt_filter), g10.c (main): Be more eager to use a MDC. We use a MDC if the keys directly support it, if the keys list AES (any) or TWOFISH anywhere in the prefs, or if the cipher chosen does not have a 64 bit blocksize. 2002-08-08 David Shaw * options.skel: Some language tweaks, and remove the load-extension section for random gatherers. * keyring.c (create_tmp_file, rename_tmp_file): Create tmp files with user-only permissions, but restore the original permissions if the user has something special set. * openfile.c (copy_options_file): Create new options file (gpg.conf) with user-only permissions. * keydb.c (keydb_add_resource): Create new keyrings with user-only permissions. * tdbio.c (tdbio_set_dbname): Create new trustdbs with user-only permissions. 2002-08-07 David Shaw * sig-check.c (signature_check2): Sanity check that the md has a context for the hash that the sig is expecting. This can happen if a onepass sig header does not match the actual sig, and also if the clearsign "Hash:" header is missing or does not match the actual sig. * keyedit.c (menu_revsig): Properly show a uid is revoked without restarting gpg. This is Debian bug 124219, though their supplied patch will not do the right thing. * main.h, tdbio.c (tdbio_set_dbname), misc.c (removed check_permissions), keydb.c (keydb_add_resource), g10.c (main, check_permissions): Significant reworking of the permission check mechanism. The new behavior is to check everything in the homedir by checking the homedir itself. If the user wants to put (possibly shared) keyrings outside the homedir, they are not checked. The options file and any extension files are checked wherever they are, as well as their enclosing directories. This is Debian bug 147760. 2002-08-06 Stefan Bellon * g10.c (main): Use of EXTSEP_S in new gpg.conf string. * openfile.c (copy_options_file): Ditto. 2002-08-06 David Shaw * options.h, g10.c (main), mainproc.c (proc_encrypted): --ignore-mdc-error option to turn a MDC check error into a warning. * encode.c (encode_crypt), g10.c (main), sign.c (sign_file, clearsign_file): Use the same --pgpX warning string everywhere to ease translations. * encode.c (write_pubkey_enc_from_list): Warn when using --throw-keyid with --pgpX. Noted by Vedaal Nistar. * revoke.c (export_minimal_pk, gen_desig_revoke, gen_revoke): Export a minimal pk along with the revocation cert when in --pgpX mode so that PGP can import it. 2002-08-06 Werner Koch * options.skel: Changed comments. * g10.c (main): Try to use "gpg.conf" as default option file. * openfile.c (copy_options_file): Changed name of created file. 2002-08-02 Werner Koch * Makefile.am (LDFLAGS): Removed DYNLINK_LDFLAGS. 2002-07-30 David Shaw * options.h, g10.c (main), mainproc.c (proc_encrypted): Return a decryption failed error if a MDC does not verify. Warn if a MDC is not present (can disable via --no-mdc-warning). * exec.c (exec_write), g10.c (main), keyserver.c (keyserver_spawn): Use new DISABLE_KEYSERVER_PATH rather than FIXED_EXEC_PATH. 2002-07-28 David Shaw * sig-check.c (do_check): Properly validate v4 sigs with no hashed section at all. 2002-07-25 Werner Koch * delkey.c (do_delete_key): Always allow to delete a key in batch mode when specified by fingerprint. Suggested by Enzo Michelangeli. 2002-07-25 David Shaw * keyedit.c (menu_revsig): Change "revsig" to honor selected uids so the user can revoke sigs from particular uids only. * keylist.c (list_keyblock_print): Don't display expired uids in --list-keys unless -v and not --list-sigs (just like revoked uids). * exec.c, export.c, import.c, keyedit.c, keyserver.c, misc.c: "Warning" -> "WARNING" 2002-07-24 David Shaw * main.h, import.c (parse_import_options, fix_hkp_corruption, import_one, delete_inv_parts), g10.c (main): New import-option "repair-hkp-subkey-bug", which repairs as much as possible the HKP mangling multiple subkeys bug. It is on by default for keyserver receives, and off by default for regular --import. * main.h, import.c (import, import_one, delete_inv_parts), hkp.c (hkp_ask_import), keyserver.c (keyserver_spawn): Use keyserver import options when doing keyserver receives. * options.h, exec.h, exec.c (set_exec_path, exec_write), g10.c (main), keyserver.c (keyserver_spawn): If the user does not use "exec-path", completely replace $PATH with GNUPG_LIBEXECDIR before calling the keyserver helper. If the user does use "exec-path", append GNUPG_LIBEXECDIR after the specified path. 2002-07-23 David Shaw * import.c (parse_import_options), export.c (parse_export_options): Fix offset problem with reversed ("no-") meanings. * import.c (delete_inv_parts): Discard subkey signatures (0x18 and 0x28) if found in the userid section of the key. * sig-check.c (signature_check2): Signatures made by invalid subkeys (bad/missing binding sig) are also invalid. * keylist.c (print_fingerprint): Show the primary as well as the secondary key fingerprint in modes 1 & 2. 2002-07-22 David Shaw * options.h, main.h, g10.c (main), import.c (parse_import_options, delete_inv_parts), keyserver.c (parse_keyserver_options): add new --import-options option. The only current flag is "allow-local-sigs". * g10.c (main): Don't disable MDC in pgp7 mode. * options.h, g10.c (main), keyserver.c (parse_keyserver_options): Remove old keyserver-option include-attributes now that there is an export-option for the same thing. * options.h, main.h, export.c (parse_export_options, do_export_stream), g10.c (main): add new --export-options option. Current flags are "include-non-rfc", "include-local-sigs", "include-attributes", and "include-sensitive-revkeys". * options.h, hkp.c (hkp_export), keyserver.c (parse_keyserver_options, keyserver_spawn): try passing unknown keyserver options to export options, and if successful, use them when doing a keyserver --send-key. * build-packet.c (build_sig_subpkt): We do not generate SIGSUBPKT_PRIV_VERIFY_CACHE anymore. * revoke.c (gen_desig_revoke): Lots more comments about including sensitive revkeys along with the revocation sig itself. * keyserver.c (parse_keyserver_options): Simpler implementation that can skip one pass over the options. 2002-07-18 David Shaw * keyedit.c (keyedit_menu, menu_addrevoker): Allow specifying "sensitive" as an argument to an addrevoker command. This sets the 0x40 sensitive revoker flag. * revoke.c (gen_desig_revoke): When generating a designated revocation, include the direct key sig that contains the designated revoker subpacket. This allows sensitive designated revocation subpackets to be exported. Also indicate which revokers are sensitive in the first place. 2002-07-17 David Shaw * keyedit.c (show_key_with_all_names_colon): The 0x40 class bit in a designated revoker means "sensitive", not "local". It's exportable under the right circumstances. * main.h, options.h, export.c (do_export_stream), g10.c (main), hkp.c (hkp_export), keyserver.c (keyserver_spawn: Add a flag to skip attribute packets and their signatures while exporting. This is to accomodate keyservers (pksd again) that choke on attributes. Use keyserver-option "include-attributes" to control it. This defaults to ON (i.e. don't skip). 2002-07-09 David Shaw * options.h, keyserver.c (parse_keyserver_uri, keyserver_spawn, keyserver_work), hkp.c (hkp_ask_import, hkp_export, hkp_search): Use a much more strict reading of RFC-2396 for the keyserver URIs. Specifically, don't try and be smart about checking the value of ":port" so long as it is all digits, and properly handle opaque data (those scheme specific parts that do not start with "//"). 2002-07-04 David Shaw * photoid.c (get_default_photo_command, show_photos): Honor FIXED_PHOTO_VIEWER and DISABLE_PHOTO_VIEWER. * mainproc.c (check_sig_and_print): Use --show-photos to show photos when verifying a sig made by a key with a photo. * keyserver.c (parse_keyserver_uri): Properly parse a URI with no :port section and an empty file path, but with a terminating '/'. (keyserver_work): Honor DISABLE_KEYSERVER_HELPERS. * hkp.c (hkp_ask_import): Display keyserver URI as a URI, but only if verbose. * exec.c, g10.c: USE_EXEC_PATH -> FIXED_EXEC_PATH 2002-07-03 David Shaw * exec.h, exec.c (set_exec_path, exec_write), g10.c (main): If USE_EXEC_PATH is defined at compile time, use it to lock the exec-path and not allow the user to change it. 2002-07-02 David Shaw * options.h, g10.c (main), keyserver.c (keyserver_refresh): Maintain and use the original keyserver URI for cosmetics rather than trying to recreate it when needed. * mainproc.c (check_sig_and_print): Properly disregard expired uids. Make sure that the first uid listed is a real uid and not an attribute (attributes should only be listed in the "aka" section). When there are no valid textual userids, try for an invalid textual userid before using any attribute uid. 2002-07-01 David Shaw * options.skel: Fix a few typos, clarify "group", and remove sample photo viewers for Win32 since they are the defaults now. * parse-packet.c (make_attribute_uidname), keylist.c (dump_attribs): Fix two typecast warnings. * packet.h, build-packet.c (build_attribute_subpkt), exec.c (expand_args), mkdtemp.c (mkdtemp), photoid.c (parse_image_header): Fix some signedness compiler warnings. 2002-07-01 Werner Koch * photoid.c (get_default_photo_command): Also use __MINGW32__ instead of HAVE_DOSISH_SYSTEM. * encode.c (encode_symmetric): Do not use the new encryption code. 2002-06-30 Werner Koch * photoid.c: Use __MINGW32__ to include windows because HAVE_DOSISH_SYSTEM is also set for OS/2 and plain DOS. Provide constant missing in older mingw installations. 2002-06-21 Stefan Bellon * g10.c [__riscos__]: Moved RISC OS specific stuff to util/riscos.c and include/util.h. * gpgv.c [__riscos__]: Likewise. 2002-06-20 David Shaw * keydb.h, pkclist.c (select_algo_from_prefs): Allow passing a suggested algorithm which will be used if available. * encode.c (encode_crypt, encrypt_filter), sign.c (sign_file): Use new select_algo_from_prefs feature to check if forcing an algorithm would violate the recipient preferences. * photoid.c (get_default_photo_command, show_photos): Use different default viewers on different platforms. Currently we have Win 9x, Win NT (2k, xp), Mac OSX, RISC OS, and "everybody else". These are #ifdefs as much as possible to avoid clutter. * g10.c (strusage, build_list), keyedit.c (show_prefs), main.h, misc.c (compress_algo_to_string, check_compress_algo), pkclist.c (algo_available), keygen.c (keygen_set_std_prefs): New algo_to_string and check functions for compress algorithms. 2002-06-20 Werner Koch * misc.c (setsysinfo): Removed a #warning for Alpha's uniligedn trap disabling - it is quite possible that this is a debug relict. 2002-06-20 Stefan Bellon * g10.c [__riscos__]: Added image file system feature. * gpgv.c [__riscos__]: Added image file system feature. * photoid.c (show_photos) [__riscos__]: Set RISC OS filetype of photo id according to MIME type. 2002-06-19 David Shaw * hkp.c (parse_hkp_index): Don't leak memory when failing out of a bad HKP keyserver. * g10.c (add_notation_data): Relax slightly the rules as to what can go into a notation name - 2440 allows "@", for example. 2002-06-17 David Shaw * import.c (clean_subkeys, import_one): Only allow at most 1 binding sig and at most 1 revocation sig on a subkey, as per 2440:11.1. * hkp.c (parse_hkp_index, hkp_search): Error if the keyserver returns an unparseable HKP response. 2002-06-15 David Shaw * keyedit.c (show_key_with_all_names), keylist.c (list_keyblock_print): Show "[expired]" before expired uids. * keyedit.c (show_key_with_all_names_colon), mainproc.c (list_node), keylist.c (list_keyblock_colon): Show flag 'e' for expired user ids. Use "uat" for user attribute packets instead of "uid". Also use ' ' rather than the fake user id string on attributes. * keygen.c (keygen_add_revkey): Remove unused code. * misc.c (check_permissions): Check directory permissions properly - they are not special files. * pkclist.c (expand_id, expand_group, build_pk_list): When expanding groups before building a pk list, inherit flags from the original pre-expanded string. * pubkey-enc.c (is_algo_in_prefs): Don't use prefs from expired uids. 2002-06-14 David Shaw * free-packet.c (copy_signature): Properly copy a signature that carries a revocation key on it. * pkclist.c (expand_id, expand_group, build_pk_list): Groups now work properly when used in the "Enter the user ID" prompt. 2002-06-14 David Shaw * keyedit.c (show_key_with_all_names): Display warning if a user tries to show prefs on a v3 key with a v3 selfsig. * kbnode.c (dump_kbnode): Show if a uid is expired. * import.c (merge_blocks, import_revoke_cert): Show user ID receiving a revocation certificate. * free-packet.c (cmp_user_ids): Properly compare attribute ids. * pkclist.c (expand_groups): Maintain the strlist flags while expanding. Members of an expansion inherit their flags from the expansion key. * options.h, cipher.c (write_header), g10.c (main), keygen.c (keygen_set_std_prefs): remove the personal_mdc flag. It no longer serves a purpose now that the personal preference lists are split into cipher/digest/zip. 2002-06-14 Timo Schulz * skclist.c (is_insecure): Implemented. 2002-06-12 David Shaw * keyserver.c (keyserver_spawn): Properly handle PROGRAM responses when they have a CRLF ending. Noted by Keith Ray. * keyserver.c (keyserver_spawn): Handle CRLF endings from keyserver helpers. Also don't leak the last line worth of memory from the keyserver response. * main.h, misc.c (deprecated_warning): New function to warn about deprecated options and commands. * g10.c (main), keyserver-internal.h, keyserver.c (parse_keyserver_uri): Use new deprecated function to warn about honor-http-proxy, auto-key-retrieve, and x-broken-hkp. 2002-06-11 David Shaw * Makefile.am: link gpg with NETLIBS for the built-in HKP access. 2002-06-10 David Shaw * options.h, keyserver.c (keyserver_opts), g10.c (main): New keyserver option "include-subkeys". This feature already existed, but now can be turned off. It defaults to on. * options.h, keyserver.c (parse_keyserver_options, keyserver_spawn): There are now enough options to justify making a structure for the keyserver options rather than a page of if-then-else-if-then-etc. * getkey.c (merge_keys_and_selfsig, merge_selfsigs_main): Fix bug in calculating key expiration dates. 2002-06-09 David Shaw * keydb.h, getkey.c (get_user_id_native), import.c (import_one): Display user ID while importing a key. Note this applies to both --import and keyserver --recv-keys. * exec.c (exec_finish): Log unnatural exit (core dump, killed manually, etc) for fork/exec/pipe child processes. 2002-06-08 Timo Schulz * encode.c (encode_symmetric): Disable the compat flag when the expert mode is enabled. 2002-06-07 David Shaw * options.skel, options.h, main.h, keydb.h, pkclist.c (build_pk_list, expand_groups), g10.c (main, add_group): Add new "group" command to allow one name to expand into multiple keys. For simplicity, and to avoid potential loops, we only expand once - you can't make an alias that points to an alias. * main.h, g10.c (main), keygen.c (build_personal_digest_list): Simplify the default digest list - there is really no need for the other hashes since they will never be used after SHA-1 in the list. * options.skel, options.h, g10.c (main), hkp.c (hkp_ask_import, hkp_export, hkp_search), keyserver.c (parse_keyserver_options, parse_keyserver_uri, keyserver_work, keyserver_refresh): Make the "x-broken-hkp" keyserver scheme into keyserver-option "broken-http-proxy". Move honor_http_proxy into keyserver_options. Canonicalize the three variations of "hkp", "x-hkp", and "x-broken-hkp" into "hkp". 2002-06-07 Stefan Bellon * g10.c [__riscos__]: Added --attribute-file to do the same as --attribute-fd, but with a filename not a fd as argument. Added magic symbol for RISC OS to use different memory management. * gpgv.c [__riscos__]: Added magic symbol for RISC OS to use different memory management. 2002-06-06 David Shaw * main.h, g10.c (main), keygen.c (build_personal_digest_list): Put in a default digest preference list consisting of SHA-1, followed by every other installed digest except MD5. Note this is the same as having no digest preference at all except for SHA-1 being favored. * options.h, g10.c (main), keygen.c (keygen_set_std_prefs), pkclist.c (select_algo_from_prefs): Split --personal-preference-list into three: --personal-{cipher|digest|compress}-preferences. This allows a user to set one without affecting another (i.e. setting only a digest pref doesn't imply an empty cipher pref). * exec.c (exec_read): This is a safer way of guessing the return value of system(). Noted by Stefan Bellon. 2002-06-05 David Shaw * hkp.c (parse_hkp_index): Be more robust with keyservers returning very unparseable responses. * exec.c (exec_read): Catch and display an error when the remote process exits unnaturally (i.e. segfault) so the user knows what happened. Also fix exec_write stub which has a different number of arguments now. 2002-06-05 Timo Schulz * encode.c (encode_simple): Ignore the new mode for RFC1991. * mainproc.c (symkey_decrypt_sesskey): Better check for weird keysizes. 2002-06-05 Timo Schulz * encode.c (encode_sesskey): New. (encode_simple): Use it here. But by default we use the compat mode which supress to generate encrypted session keys. 2002-06-05 Timo Schulz * mainproc.c (symkey_decrypt_sesskey): New. (proc_symkey_enc): Support for encrypted session keys. 2002-06-04 David Shaw * sign.c (hash_for, sign_file): When encrypting and signing at the same time, consult the various hash prefs to pick a hash algorithm to use. Pass in a 160-bit hint if any of the signing keys are DSA. * keydb.h, pkclist.c (select_algo_from_prefs, algo_available): Pass a "hints" opaque pointer in to let the caller give hints as to what algorithms would be acceptable. The only current hint is for PREFTYPE_HASH to require a 160-bit hash for DSA. Change all callers in encode.c (encode_crypt, encrypt_filter) and sign.c (sign_file). If we settle on MD5 as the best algorithm based solely on recepient keys and SHA1 is also a possibility, use SHA1 unless the user intentionally chose MD5. This is as per 2440:13. * exec.c (make_tempdir): Fix duplicated filename problem. 2002-06-03 David Shaw * packet.h, parse-packet.c (enum_sig_subpkt): Report back from enum_sig_subpkt when a subpacket is critical and change all callers in keylist.c (show_policy_url, show_notation), mainproc.c (print_notation_data), and pkclist.c (do_show_revocation_reason). * keylist.c (show_policy_url, show_notation): Display if the policy or notation is critical. 2002-06-03 David Shaw * main.h, g10.c (main), keylist.c (dump_attribs, set_attrib_fd, list_keyblock_print, list_keyblock_colon), status.h, status.c (get_status_string): New --attribute-fd feature to dump the contents of attribute subpackets for frontends. If --status-fd is also used, then a new status tag ATTRIBUTE is provided for each subpacket. * packet.h, getkey.c (fixup_uidnode, merge_selfsigs_main, merge_selfsigs_subkey), parse-packet.c (setup_user_id): Keep track of the expiration time of a user ID, and while we're at it, use the expired flag from the selfsig rather than reparsing the SIG_EXPIRE subpacket. * photoid.c (generate_photo_id): When adding a new photo ID, showing the photo for confirmation is not safe when noninteractive since the "user" may not be able to dismiss a viewer window. Noted by Timo Schulz. 2002-06-03 David Shaw * options.skel: Sample photo viewers for Win32. * misc.c (pct_expando): Use the seckey for %k/%K if the pubkey is not available. * photoid.h, photoid.c (show_photos): Include the seckey in case a user tries to view a photo on a secret key, and change all callers in keyedit.c (menu_showphoto), keylist.c (list_keyblock_print), and photoid.c (generate_photo_id). 2002-06-02 David Shaw * photoid.c (show_photos): Work properly when not called with a public key. 2002-05-31 David Shaw * sign.c (mk_notation_and_policy): Free unneeded buffer. * hkp.c (parse_hkp_index): Properly handle the '&' character (i.e. "&") in HKP responses. * getkey.c (merge_selfsigs_main): Fix reversed expiration time check with self-sigs. * keyedit.c (sign_uids): When making a new self-sig on a v3 key, make a v3 self-sig unless it is currently a v3 self-sig being promoted to v4. 2002-05-31 Timo Schulz * pkclist.c (do_show_revocation_reason): Don't use capital letters for non-interactive output. (show_revocation_reason): Now it is global. * pubkey-enc.c (get_it): Show if the key has been revoked. 2002-05-30 David Shaw * sign.c (write_signature_packets, sign_file, clearsign_file, sign_symencrypt_file): Make a v4 signature if a policy URL or notation is set, unless v3 sigs are forced via rfc1991 or force-v3-sigs. Also remove some doubled code and clarify an error message (we don't sign in PGP2 mode - just detach-sign). * parse-packet.c (parse_one_sig_subpkt): Add KS_FLAGS to the "any size" section. 2002-05-29 David Shaw * keygen.c (keygen_set_std_prefs, add_feature_mdc): Use "mdc" and "no-mdc" in the prefs string to allow switching on and off the MDC feature. This is needed to properly export a key from GnuPG for use on PGP which does not support MDC - without this, MDC-capable implementations will still try and generate MDCs which will break PGP. * keygen.c (keygen_get_std_prefs): Show "[mdc]" in prefs string if it is enabled. * options.h, g10.c (main), cipher.c (write_header), keygen.c (keygen_set_std_prefs): For consistency, allow the user to specify mdc/no-mdc in the --personal-preference-list. If disabled, it acts just like --disable-mdc. 2002-05-29 David Shaw * options.h, exec.c: Add some debugging info, using the 1024 debug flag. * exec.c (win_system): New system()-like function for win32 that does not return until the child process terminates. Of course, this doesn't help if the process itself exits before it is finished. 2002-05-29 Werner Koch * encode.c (encode_simple): Intialize PKT when --no-literal is used. * keyedit.c (show_key_with_all_names_colon): Renamed the record for revocation keys to "rvk". 2002-05-27 Werner Koch * keyedit.c (show_key_with_all_names_colon): New. (show_key_with_all_names): Divert to new function when required. Sanitize printing of revoker name. 2002-05-27 David Shaw * build-packet.c (build_sig_subpkt): Handle setting sig flags for certain subpacket types (notation, policy url, exportable, revocable). keyedit.c (sign_mk_attrib): Flags no longer need to be set here. * packet.h, parse-packet.c (parse_one_sig_subpkt), build-packet.c (build_sig_subpkt): Call parse_one_sig_subpkt to sanity check buffer lengths before building a sig subpacket. 2002-05-26 David Shaw * sign.c (mk_notation_and_policy): Include secret key to enable %s expandos, and pass notations through pct_expando as well. * main.h, misc.c (pct_expando): Add %s and %S expandos for signer's keyid. 2002-05-25 David Shaw * g10.c (strusage, build_list): Add compress algorithms to --version list. Show algorithm numbers when --verbose --version is done. 2002-05-22 David Shaw * options.h, main.h, keygen.c (keygen_set_set_prefs, keygen_get_std_prefs, keygen_upd_std_prefs), keyedit.c (keyedit_menu), g10.c (main), pkclist.c (select_algo_from_prefs): Add --personal-preference-list which allows the user to factor in their own preferred algorithms when the preference lists are consulted. Obviously, this does not let the user violate a recepient's preferences (and the RFC) - this only influences the ranking of the agreed-on (and available) algorithms from the recepients. Suggested by David Hollenberg. * options.h, keygen.c (keygen_set_std_prefs), g10.c (main): Rename --preference-list to --default-preference-list (as that is what it really is), and make it a true default in that if the user selects "default" they get this list and not the compiled-in list. 2002-05-22 Werner Koch * g10.c (main): Add missing LF in a info printout and made it translatable. Noted by Michael Tokarev. 2002-05-21 Werner Koch * g10.c (main): Removed the undef of USE_SHM_COPROCESSING which was erroneously introduced on 2002-01-09. * signal.c (got_fatal_signal): Don't write the Nul to stderr. Reported by David Hollenberg. 2002-05-18 David Shaw * main.h, g10.c (main), revoke.c (gen_desig_revoke): Generate a designated revocation via --desig-revoke * keyedit.c (keyedit_menu, menu_addrevoker): New "addrevoker" command to add a designated revoker to a key. 2002-05-17 David Shaw * gpgv.c: Add stub for get_ownertrust(). * g10.c (main): --allow-freeform-uid should be implied by OpenPGP. Add --no-allow-freeform-uid. * keyedit.c (sign_uids): Issue a warning when signing a non-selfsigned uid. * getkey.c (merge_selfsigs_main): If a key has no selfsigs, and allow-non-selfsigned-uid is not set, still try and make the key valid by checking all uids for a signature from an ultimately trusted key. 2002-05-16 David Shaw * main.h, keygen.c (keygen_add_revkey): Add revocation key subpackets to a signature (callable by make_keysig_packet). (write_direct_sig): Write a 1F direct key signature. (parse_revocation_key): Parse a string in algo:fpr:sensitive format into a revocation key. (get_parameter_revkey, do_generate_keypair): Call above functions when prompted from a batch key generation file. * build-packet.c (build_sig_subpkt): Allow multiple revocation key subpackets in a single sig. * keydb.h, getkey.c (get_seckey_byfprint): Same as get_pubkey_byfprint, except for secret keys. We only know the fingerprint of a revocation key, so this is needed to retrieve the secret key needed to issue a revokation. * packet.h, parse-packet.c (parse_signature, parse_revkeys): Split revkey parsing off into a new function that can be used to reparse after manipulating the revkey list. * sign.c (make_keysig_packet): Ability to make 1F direct key signatures. 2002-05-15 David Shaw * options.skel: keyserver.pgp.com is gone, so list pgp.surfnet.nl as a sample LDAP server instead. * getkey.c (merge_selfsigs_main): Properly handle multiple revocation keys in a single packet. Properly handle revocation keys that are in out-of-order packets. Remove duplicates in revocation key list. 2002-05-14 Timo Schulz * exec.c (make_tempdir) [MINGW32]: Added missing '\'. 2002-05-14 Stefan Bellon * exec.c (make_tempdir): Make use of EXTSEP_S instead of hardcoded dot as extension separator. 2002-05-13 David Shaw * photoid.c (show_photos): Use the long keyid as the filename for the photo. Use the short keyid as the filename on 8.3 systems. * exec.h, exec.c (make_tempdir, exec_write, exec_finish): Allow caller to specify filename. This should make things easier on windows and macs where the file extension is required, but a whole filename is even better. * keyedit.c (show_key_with_all_names, show_prefs): Show proper prefs for a v4 key uid with no selfsig at all. * misc.c (check_permissions): Don't check permissions on non-normal files (pipes, character devices, etc.) 2002-05-11 Werner Koch * mainproc.c (proc_symkey_enc): Avoid segv in case the parser encountered an invalid packet. * keyserver.c (keyserver_export): Get confirmation before sending all keys. 2002-05-10 Stefan Bellon * g10.c, hkp.c, keyedit.c, keyserver.c: Replaced all occurrances of strcasecmp with ascii_strcasecmp and all occurrances of strncasecmp with ascii_memcasecmp. 2002-05-10 David Shaw * packet.h, getkey.c (fixup_uidnode), keyedit.c (show_prefs): Show assumed prefs for hash and compression as well as the cipher pref. Show assumed prefs if there are no prefs at all on a v4 self-signed key. * options.h, g10.c (main), sign.c (make_keysig_packet): New --cert-digest-algo function to override the default key signing hash algorithm. 2002-05-09 David Shaw * getkey.c (merge_selfsigs_main): Make sure the revocation key list starts clean as this function may be called more than once (e.g. from functions in --edit). * g10.c, encode.c (encode_crypt), sign.c (sign_file, sign_symencrypt_file): Make --compress-algo work like the documentation says. It should be like --cipher-algo and --digest-algo in that it can override the preferences calculation and impose the setting the user wants. No --compress-algo setting allows the usual preferences calculation to take place. * main.h, compress.c (compress_filter): use new DEFAULT_COMPRESS_ALGO define, and add a sanity check for compress algo value. 2002-05-08 David Shaw * pkclist.c (select_algo_from_prefs): There is an assumed compression preference for uncompressed data. 2002-05-07 David Shaw * options.h, g10.c (main), getkey.c (finish_lookup), pkclist.c (algo_available): --pgp7, identical to --pgp6 except that it permits a few algorithms that PGP 7 added: AES128, AES192, AES256, and TWOFISH. Any more of these --pgpX flags, and it'll be time to start looking at a generic --emulate-pgp X option. * export.c (do_export_stream): Warn the user when exporting a secret key if it or any of its secret subkeys are protected with SHA1 while simple_sk_checksum is set. * parse-packet.c (parse_key): Show when the SHA1 protection is used in --list-packets. * options.h, build-packet.c (do_comment), g10.c (main): Rename --no-comment as --sk-comments/--no-sk-comments (--no-comment still works) and make the default be --no-sk-comments. 2002-05-07 Werner Koch * keygen.c (get_parameter_algo): Never allow generation of the deprecated RSA-E or RSA-S flavors of PGP RSA. (ask_algo): Allow generation of RSA sign and encrypt in expert mode. Don't allow ElGamal S+E unless in expert mode. * helptext.c: Added entry keygen.algo.rsa_se. 2002-05-07 David Shaw * keyedit.c (sign_uids): If --expert is set, allow re-signing a uid to promote a v3 self-sig to a v4 one. This essentially deletes the old v3 self-sig and replaces it with a v4 one. * packet.h, parse-packet.c (parse_key), getkey.c (merge_keys_and_selfsig, merge_selfsigs_main): a v3 key with a v4 self-sig must never let the v4 self-sig express a key expiration time that extends beyond the original v3 expiration time. 2002-05-06 David Shaw * keyedit.c (sign_uids): When making a self-signature via "sign" don't ask about sig level or expiration, and include the usual preferences and such for v4 self-sigs. (menu_set_preferences): Convert uids from UTF8 to native before printing. * keyedit.c (sign_uids): Convert uids from UTF8 to native before printing. (menu_set_primary_uid): Show error if the user tries to make a uid with a v3 self-sig primary. 2002-05-05 David Shaw * import.c (import_one): When merging with a key we already have, don't let a key conflict (same keyid but different key) stop the import: just skip the bad key and continue. * exec.c (make_tempdir): Under Win32, don't try environment variables for temp directories - GetTempDir tries environment variables internally, and it's better not to second-guess it in case MS adds some sort of temp dir handling to Windows at some point. 2002-05-05 Timo Schulz * mainproc.c (proc_symkey_enc): Don't ask for a passphrase in the list only mode. 2002-05-05 David Shaw * keyserver.c (keyserver_refresh): --refresh-keys implies --merge-only so as not to import keys with keyids that match the ones being refreshed. Noted by Florian Weimer. 2002-05-04 Stefan Bellon * free-packet.c (copy_public_key): Don't call m_alloc(0), therefore added consistency check for revkey and numrefkeys. * getkey.c (check_revocation_keys): Added consistency check for revkey and numrefkeys. * keyedit.c (show_key_with_all_names): Likewise. 2002-05-03 David Shaw * photoid.c: Provide default image viewer for Win32. * misc.c (pct_expando): %t means extension, not name ("jpg", not "jpeg"). * keyserver.c (keyserver_spawn), photoid.c (show_photos), exec.h, exec.c: Allow the caller to determine the temp file extension when starting an exec_write and change all callers. * keyedit.c (sign_uids): Nonrevocable key signatures cause an automatic promotion to v4. * exec.c: Provide stubs for exec_ functions when NO_EXEC is defined. 2002-05-02 David Shaw * photoid.h, photoid.c (parse_image_header, image_type_to_string): Useful functions to return data about an image. * packet.h, parse-packet.c (make_attribute_uidname, parse_attribute_subpkts, parse_attribute), photoid.h, photoid.c (show_photos): Handle multiple images in a single attribute packet. * main.h, misc.c (pct_expando), sign.c (mk_notation_and_policy), photoid.c (show_photos): Simpler expando code that does not require using compile-time string sizes. Call image_type_to_string to get image strings (i.e. "jpg", "image/jpeg"). Change all callers. * keyedit.c (menu_showphoto), keylist.c (list_keyblock_print): Allow viewing multiple images within a single attribute packet. * gpgv.c: Various stubs for link happiness. 2002-05-02 David Shaw * build-packet.c (build_sig_subpkt), keyedit.c (sign_uids), options.h, sign.c (mk_notation_and_policy), g10.c (main, add_notation_data, add_policy_url (new), check_policy_url (removed)): Allow multiple policy URLs on a given signature. Split "--notation-data" into "--cert-notation" and "--sig-notation" so the user can set different policies for key and data signing. For backwards compatibility, "--notation-data" sets both, as before. 2002-05-02 Werner Koch * options.skel: Removed the comment on trusted-keys because this option is now deprecated. 2002-05-01 David Shaw * keyedit.c (menu_adduid): 2440bis04 says that multiple attribute packets on a given key are legal. * keyserver.c (keyserver_refresh): the fake v3 keyid hack applies to "mailto" URLs as well since they are also served by pksd. 2002-04-29 Werner Koch Added a copyright year for files changed this year. 2002-04-25 Werner Koch * g10.c, options.h: New options --display, --ttyname, --ttytype, --lc-ctype, --lc-messages to be used with future versions of the gpg-agent. * passphrase.c (agent_send_option,agent_send_all_options): New. (agent_open): Send options to the agent. * trustdb.c (update_ownertrust, clear_ownertrust): Do an explicit do_sync because revalidation_mark does it only if when the timestamp actually changes. 2002-04-23 David Shaw * main.h, keygen.c (do_generate_keypair), keylist.c (print_signature_stats, list_all, list_one, list_keyblock, list_keyblock_print, list_keyblock_colon): After generating a new key, show the key information (name, keyid, fingerprint, etc.) Also do not print uncheckable signatures (missing key..) in --check-sigs. Print statistics (N missing keys, etc.) after --check-sigs. * keyedit.c (sign_uids): When signing a key with an expiration date on it, the "Do you want your signature to expire at the same time?" question should default to YES. 2002-04-22 David Shaw * parse-packet.c (parse_plaintext), packet.h, plaintext.c (handle_plaintext): Fix bug in handling literal packets with zero-length data (no data was being confused with partial body length). * misc.c (pct_expando), options.skel: %t means extension ("jpg"). %T means MIME type ("image/jpeg"). * import.c (import_one): Only trigger trust update if the keyring is actually changed. * export.c (do_export_stream): Missing a m_free. 2002-04-22 Stefan Bellon * keyid.c (expirestr_from_sk, expirestr_from_sig): Added _() to string constant. * exec.c (make_tempdir) [__riscos__]: Better placement of temporary file. 2002-04-20 David Shaw * keygen.c (generate_subkeypair): 2440bis04 adds that creating subkeys on v3 keys is a MUST NOT. * getkey.c (finish_lookup): The --pgp6 "use the primary key" behavior should only apply while data signing and not encryption. Noted by Roger Sondermann. 2002-04-19 Werner Koch * keygen.c (keygen_set_std_prefs): Put back 3DES because the RFC says it is good form to do so. 2002-04-19 David Shaw * keyedit.c (menu_deluid): Only cause a trust update if we delete a non-revoked user id. * hkp.c (hkp_ask_import), keyserver.c (parse_keyserver_options, keyserver_spawn), options.h: Remove fast-import keyserver option (no longer meaningful). * g10.c (main), keyedit.c (sign_uids), options.h: Change --default-check-level to --default-cert-check-level as it makes clear what it operates on. * g10.c (main): --pgp6 also implies --no-ask-sig-expire. * delkey.c (do_delete_key): Comment. * keyedit.c (sign_uids, keyedit_menu, menu_deluid, menu_delsig, menu_expire, menu_revsig, menu_revkey): Only force a trustdb check if we did something that changes it. * g10.c: add "--auto-check-trustdb" to override a "--no-auto-check-trustdb" 2002-04-19 Werner Koch * tdbio.c (tdbio_write_nextcheck): Return a status whether the stamp was actually changed. * trustdb.c (revalidation_mark): Sync the changes. Removed the sync operation done by its callers. (get_validity): Add logic for maintaining a pending_check flag. (clear_ownertrust): New. * keyedit.c (sign_uids): Don't call revalidation_mark depending on primary_pk. (keyedit_menu): Call revalidation_mark after "trust". (show_key_with_all_names): Print a warning on the wrong listed key validity. * delkey.c (do_delete_key): Clear the owenertrust information when deleting a public key. 2002-04-18 Werner Koch * seskey.c (encode_md_value): Print an error message if a wrong digest algorithm is used with DSA. Changed all callers to cope with a NULL return. Problem noted by Imad R. Faiad. 2002-04-18 David Shaw * trustdb.c (mark_usable_uid_certs): Properly handle nonrevocable signatures that can expire. In short, the only thing that can override an unexpired nonrevocable signature is another unexpired nonrevocable signature. * getkey.c (finish_lookup): Always use primary signing key for signatures when --pgp6 is on since pgp6 and 7 do not understand signatures made by signing subkeys. 2002-04-18 Werner Koch * trustdb.c (validate_keys): Never schedule a nextcheck into the past. (validate_key_list): New arg curtime use it to set next_expire. (validate_one_keyblock): Take the current time from the caller. (clear_validity, reset_unconnected_keys): New. (validate_keys): Reset all unconnected keys. * getkey.c (premerge_public_with_secret): Fixed 0x12345678! syntax for use with secret keys. (lookup): Advance the searchmode after a search FIRST. * seckey-cert.c (do_check): Always calculate the old checksum for use after unprotection. * g10.c, options.skel: New option --no-escape-from. Made --escape-from and --force-v3-sigs the default and removed them from the options skeleton. 2002-04-16 Werner Koch * parse-packet.c (parse_key): Support a SHA1 checksum as per draft-rfc2440-bis04. * packet.h (PKT_secret_key): Add field sha1chk. * seckey-cert.c (do_check): Check the SHA1 checksum (protect_secret_key): And create it. * build-packet.c (do_secret_key): Mark it as sha-1 protected. * g10.c, options.h: New option --simple-sk-checksum. 2002-04-13 David Shaw * parse-packet.c (parse_signature): Minor fix - signatures should expire at their expiration time and not one second later. * keygen.c (proc_parameter_file): Allow specifying preferences string (i.e. "s5 s2 z1 z2", etc) in a batchmode key generation file. * keyedit.c (keyedit_menu): Print standard error message when signing a revoked key (no new translation). * getkey.c (merge_selfsigs): Get the default set of key prefs from the real (not attribute) primary uid. 2002-04-12 David Shaw * pkclist.c (build_pk_list): Fix bug that allowed a key to be selected twice in batch mode if one instance was the default recipient and the other was an encrypt-to. Noted by Stefan Bellon. * parse-packet.c (dump_sig_subpkt): Show data in trust and regexp sig subpackets. * keyedit.c (keyedit_menu): Use new function real_uids_left to prevent deleting the last real (i.e. non-attribute) uid. Again, according to the attribute draft. (menu_showphoto): Make another string translatable. 2002-04-11 David Shaw * build-packet.c (build_sig_subpkt): Delete subpackets from both hashed and unhashed area on update. (find_subpkt): No longer needed. * keyedit.c (sign_uids): With --pgp2 on, refuse to sign a v3 key with a v4 signature. As usual, --expert overrides. Try to tweak some strings to a closer match so they can all be translated in one place. Use different helptext keys to allow different help text for different questions. * keygen.c (keygen_upd_std_prefs): Remove preferences from both hashed and unhashed areas if they are not going to be used. 2002-04-10 David Shaw * misc.c (pct_expando), options.skel: Use %t to indicate type of a photo ID (in this version, it's always "jpeg"). Also tweak string expansion loop to minimize reallocs. * mainproc.c (do_check_sig): Variable type fix. * keyedit.c (menu_set_primary_uid): Differentiate between true user IDs and attribute user IDs when making one of them primary. That is, if we are making a user ID primary, we alter user IDs. If we are making an attribute packet primary, we alter attribute packets. This matches the language in the latest attribute packet draft. * keyedit.c (sign_uids): No need for the empty string hack. * getkey.c (fixup_uidnode): Only accept preferences from the hashed segment of the self-sig. 2002-04-10 Werner Koch * tdbio.c (migrate_from_v2): Fixed the offset to read the old ownertrust value and only add entries to the table if we really have a value. 2002-04-08 David Shaw * status.h, status.c (get_status_string): Add KEYEXPIRED, EXPSIG, and EXPKEYSIG. Add "deprecated-use-keyexpired-instead" to SIGEXPIRED. * sig-check.c (do_check): Start transition from SIGEXPIRED to KEYEXPIRED, since the actual event is signature verification by an expired key and not an expired signature. (do_signature_check, packet.h): Rename as signature_check2, make public, and change all callers. * mainproc.c (check_sig_and_print, do_check_sig): Use status EXPSIG for an expired, but good, signature. Add the expiration time (or 0) to the VALIDSIG status line. Use status KEYEXPSIG for a good signature from an expired key. * g10.c (main): remove checks for no arguments now that argparse does it. 2002-04-06 Werner Koch * keyring.c (keyring_get_keyblock): Disable the keylist mode here. * encode.c (encode_simple, encode_crypt): Only test on compressed files if a compress level was not explicity set. * keygen.c (keygen_set_std_prefs): Removed Blowfish and Twofish from the list of default preferences, swapped the preferences of RMD160 and SHA1. Don't include a preference to 3DES unless the IDEA kludge gets used. * free-packet.c (free_packet): call free_encrypted also for PKT_ENCRYPTED_MDC. * compress.c (release_context): New. (handle_compressed): Allocate the context and setup a closure to release the context. This is required because there is no guarantee that the filter gets popped from the chain at the end of the function. Problem noted by Timo and probably also the cause for a couple of other reports. (compress_filter): Use the release function if set. * tdbio.c [__CYGWIN32__]: Don't rename ftruncate. Noted by Disastry. * parse-packet.c (parse_signature): Put parens around a bit test. * exec.c (make_tempdir): Double backslash for TMP directory creation under Windows. Better strlen the DIRSEP_S constants for allocation measurements. * decrypt.c (decrypt_messages): Release the passphrase aquired by get_last_passphrase. 2002-04-02 Werner Koch * Makefile.am (EXTRA_DIST): Removed OPTIONS an pubring.asc - they are no longer of any use. 2002-04-03 David Shaw * keyserver.c (parse_keyserver_options): fix auto-key-retrieve to actually work as a keyserver-option (noted by Roger Sondermann). * keylist.c (reorder_keyblock): do not reorder the primary attribute packet - the first user ID must be a genuine one. 2002-03-31 David Shaw * keylist.c (list_keyblock_colon): Fix ownertrust display with --with-colons. * keygen.c (generate_user_id), photoid.c (generate_photo_id): Properly initialize the user ID refcount. A few more "y/n" -> "y/N" in photoid.c. * keyedit.c (ask_revoke_sig): Warn the user if they are about to revoke an expired sig (not a problem, but they should know). Also tweak a few prompts to change "y/n" to "y/N", which is how most other prompts are written. * keyserver.c (keyserver_search_prompt): Control-d escapes the keyserver search prompt. * pkclist.c (show_revocation_reason & callers): If a subkey is considered revoked solely because the parent key is revoked, print the revocation reason from the parent key. * trustdb.c (get_validity): Allow revocation/expiration to apply to a uid/key with no entry in the trustdb. 2002-03-29 David Shaw * keyserver.c (printunquoted): unquote backslashes from keyserver searches * hkp.c (write_quoted): quote backslashes from keyserver searches 2002-03-26 Werner Koch * keygen.c (ask_keysize): Removed the warning for key sizes > 1536. 2002-03-25 Werner Koch * keyedit.c (sign_uids): Use 2 strings and not a %s so that translations can be done the right way. * helptext.c: Fixed small typo. 2002-03-23 David Shaw * import.c (append_uid, merge_sigs): it is okay to import completely non-signed uids now (with --allow-non-selfsigned-uid). * getkey.c (get_primary_uid, merge_selfsigs_main): do not choose an attribute packet (i.e. photo) as primary uid. This prevents oddities like "Good signature from [image of size 2671]". This is still not perfect (one can still select an attribute packet as primary in --edit), but is closer to the way the draft is going. * g10.c (build_list): algorithms should include 110. * g10.c (main): --pgp2 implies --no-ask-sig-expire and --no-ask-cert-expire as those would cause a v4 sig/cert. * armor.c (is_armor_header): be more lenient in what constitutes a valid armor header (i.e. -----BEGIN blah blah-----) as some Windows programs seem to add spaces at the end. --openpgp makes it strict again. 2002-03-18 David Shaw * keyserver.c (keyserver_search_prompt): Properly handle a "no keys found" case from the internal HKP code (external HKP is ok). Also, make a COUNT -1 (i.e. streamed) keyserver response a little more efficient. * g10.c (main): Add --no-allow-non-selfsigned-uid 2002-03-17 David Shaw * g10.c (main): --openpgp implies --allow-non-selfsigned-uid. * getkey.c (merge_selfsigs_main): If none of the uids are primary (because none are valid) then pick the first to be primary (but still invalid). This is for cosmetics in case some display needs to print a user ID from a non-selfsigned key. Also use --allow-non-selfsigned-uid to make such a key valid and not --always-trust. The key is *not* automatically trusted via --allow-non-selfsigned-uid. * mainproc.c (check_sig_and_print): Make sure non-selfsigned uids print [uncertain] on verification even though one is primary now. * getkey.c (merge_selfsigs): If the main key is not valid, then neither are the subkeys. * import.c (import_one): Allow --allow-non-selfsigned-uid to work on completely unsigned keys. Print the uids in UTF8. Remove mark_non_selfsigned_uids_valid(). * keyedit.c (show_key_with_all_names): Show revocation key as UTF8. * sign.c (clearsign_file): Allow --not-dash-escaped to work with v3 keys. 2002-03-14 Werner Koch * main.h: Changed the default algorithms to CAST5 and SHA1. 2002-03-13 David Shaw * import.c (chk_self_sigs): Show which user ID a bad self-sig (invald sig or unsupported public key algorithm) resides on. * import.c (chk_self_sigs): any valid self-sig should mark a user ID or subkey as valid - otherwise, an attacker could DoS the user by inventing a bogus invalid self-signature. 2002-03-07 David Shaw * g10.c (main): make a few more strings translatable. * options.h, options.skel, g10.c (main), gpgv.c, mainproc.c (check_sig_and_print), keyserver.c (parse_keyserver_options): --auto-key-retrieve should really be a keyserver-option variable. * import.c (revocation_present): new function to print a warning if a key is imported that has been revoked by designated revoker, but the designated revoker is not present to verify the revocation. If keyserver-options auto-key-retrieve is set, try and fetch the designated revoker from the keyserver. * import.c (import_one): call revocation_present after importing a new key. Note that this applies to --import, --recv-keys, and --search-keys. * keyserver-internal.h, keyserver.c (keyserver_import_fprint): import via fingerprint (for revocation keys). * keyserver.c (keyserver_import_keyid): much simpler implementation now that we're using KEYDB_SEARCH_DESC internally. 2002-03-04 David Shaw * revoke.c (gen_revoke): do not prompt for revocation reason for v3 revocations (unless force-v4-certs is on) since they wouldn't be used anyway. * keyedit.c (menu_revsig): show the status of the sigs (exportable? revocable?) to the user before prompting for which sig to revoke. Also, make sure that local signatures get local revocations. * keyedit.c (ask_revoke_sig): remind the user which sigs are local. * g10.c (main): Add "exec-path" variable to override PATH for execing programs. * export.c (do_export_stream): properly check return code from classify_user_id to catch unclassifiable keys. 2002-03-03 David Shaw * parse-packet.c (parse_signature): variable type tweak for RISC OS (from Stefan) 2002-02-28 David Shaw * getkey.c (check_revocation_keys): New function to check a revocation against a list of potential revocation keys. Note the loop-breaking code here. This is to prevent blowing up if A is B's revocation key, while B is also A's. Note also that this is written so that a revoked revoker can still issue revocations: i.e. If A revokes B, but A is revoked, B is still revoked. I'm not completely convinced this is the proper behavior, but it matches how PGP does it. It does at least have the advantage of much simpler code - my first version of this had lots of loop maintaining code so you could chain revokers many levels deep and if D was revoked, C was not, which meant that B was, and so on. It was sort of scary, actually. * getkey.c (merge_selfsigs_main): Add any revocation keys onto the pk. This is particularly interesting since we normally only get data from the most recent 1F signature, but you need multiple 1F sigs to properly handle revocation keys (PGP does it this way, and a revocation key could be marked "sensitive" and hence in a different signature). Also, if a pk has a revocation key set, check for revocation sigs that were not made by us - if made by a valid revocation key, mark the pk revoked. * packet.h, getkey.c (cache_public_key): do not cache key if "dont_cache" is set. This allows the revocation key code to look up a key and return information that may be inaccurate to prevent loops without caching the fake data. * packet.h, sig-check.c (do_signature_check): Record if a signature was made by a revoked pk. * packet.h, parse-packet.c (parse_one_sig_subpkt, can_handle_critical, parse_signature): Get revocation key information out of direct sigs. * keylist.c (list_keyblock_print): don't assume that the presence of a 0x20 signature means the key is revoked. With revocation keys, this may not be true if the revocation key is not around to verify it or if verification failed. Also, 0x1F should get listed as "sig", and not "unexpected signature class". * keyedit.c (show_key_with_all_names): Add a flag for printing revoker information and change all callers. * import.c (merge_blocks): merge in any new direct key (0x1F) sigs. * import.c (import_revoke_cert): don't keep processing after a revocation is rejected. * import.c (delete_inv_parts): Allow importing a revocation signature even if it was not issued by the key. This allows a revocation key to issue it. Of course, the sig still needs to be checked before we trust it. * free-packet.c (copy_public_key): Include a new copy of the revocation keys when duping a pk. * free-packet.c (free_seckey_enc, release_public_key_parts): Free any revocation keys that are attached to a sig or pk. * export.c (do_export_stream): Do not export signatures with "sensitive" revocation keys in them. 2002-02-27 David Shaw * export.c (do_export_stream): Do not include v3 keys in a --export-secret-subkeys export. * getkey.c (merge_selfsigs_main): If a key isn't valid (say, because of no self-signature), allow --always-trust to force it valid so it can be trusted. 2002-02-25 David Shaw * hkp.c (hkp_ask_import), hkp.h, keyserver.c (all): treat key lists internally as fingerprints when possible. All this is via KEYDB_SEARCH_DESC - no point in reinventing the wheel. This allows the helper program to search the keyserver by fingerprint if desired (and the keyserver supports it). Note that automatic fingerprint promotion during refresh only applies to v4 keys as a v4 fingerprint can be easily changed into a long or short key id, and a v3 cannot. * pubkey-enc.c, getkey.c, misc.c, main.h: Take two copies of hextobyte() from pubkey-enc.c and getkey.c and make them into one copy in misc.c. 2002-02-22 David Shaw * keyserver.c (keyserver_search_prompt): Detect a "no keys found" case even if the helper program does not explicitly say how many keys were found. * hkp.c (parse_hkp_index): Bug fix - don't report non-revoked keys as revoked in HKP key searches. 2002-02-19 Werner Koch * parse-packet.c (parse_trust): Made parsing more robust. 2002-02-19 David Shaw * hkp.c (parse_hkp_index): Catch corruption in HKP index lines (can be caused by broken or malicious keyservers). * keyserver.c (keyserver_work): Add KEYSERVER_NOT_SUPPORTED for unsupported actions (say, a keyserver that has no way to search, or a readonly keyserver that has no way to add). Also add a USE_EXTERNAL_HKP define to disable the internal HKP keyserver code. 2002-02-14 Werner Koch * g10.c: New option --no-use-agent. * pkclist.c (check_signatures_trust): Always print the warning for unknown and undefined trust. Removed the did_add cruft. Reported by Janusz A. Urbanowicz. 2002-02-11 David Shaw * hkp.c (parse_hkp_index): Bug fix - properly handle user IDs with colons (":") in them while HKP searching. 2002-02-09 David Shaw * misc.c (pct_expando): More comments. * keydb.h, sign.c (mk_notation_and_policy): Clarify what is a sig and what is a cert. A sig has sigclass 0x00, 0x01, 0x02, or 0x40, and everything else is a cert. * g10.c (main), keyedit.c (keyedit_menu): Add a "nrlsign" for nonrevocable and local key signatures. * g10.c (main): Add a --no-force-mdc to undo --force-mdc. * options.h, g10.c (main), cipher.c (write_header): Add a knob to --disable-mdc/--no-disable-mdc. Off by default, of course, but is used in --pgp2 and --pgp6 modes. * pkclist.c (build_pk_list): Allow specifying multiple users in the "Enter the user ID" loop. Enter a blank line to stop. Show each key+id as it is added. * keylist.c (show_policy_url), mainproc.c (print_notation_data): It is not illegal (though possibly silly) to have multiple policy URLs in a given signature, so print all that are present. * hkp.c (hkp_search): More efficient implementation of URL-ifying code. 2002-02-04 David Shaw * main.h, misc.c (pct_expando): New function to generalize %-expando processing in any arbitrary string. * photoid.c (show_photo): Call the new pct_expando function rather than expand strings internally. * sign.c (mk_notation_and_policy): Show policy URLs and notations when making a signature if show-policy/show-notation is on. %-expand policy URLs during generation. This lets the user have policy URLs of the form "http://notary.jabberwocky.com/keysign/%K" which will generate a per-signature policy URL. * main.h, keylist.c (show_policy_url, show_notation): Add amount to indent so the same function can be used in key listings as well as during sig generation. Change all callers. 2002-02-04 David Shaw * keyserver.c, options.h (parse_keyserver_options, keyidlist): Workaround for the pksd and OKS keyserver bug that calculates v4 RSA keyids as if they were v3. The workaround/hack is to fetch both the v4 (e.g. 99242560) and v3 (e.g. 68FDDBC7) keyids. This only happens for key refresh while using the HKP scheme and the refresh-add-fake-v3-keyids keyserver option must be set. This should stay off by default. 2002-02-03 David Shaw * keyserver.c (keyserver_spawn): Bug fix - do not append keys to each other when --sending more than one. 2002-02-02 David Shaw * options.h, g10.c (main), keyedit.c (sign_uids), sign.c (mk_notation_and_policy): Split "--set-policy-url" into "--cert-policy-url" and "--sig-policy-url" so the user can set different policies for key and data signing. For backwards compatibility, "--set-policy-url" sets both, as before. 2002-01-30 Werner Koch * g10.c (main): --gen-random --armor does now output a base64 encoded string. 2002-01-28 David Shaw * g10.c (main), options.h, pkclist.c (algo_available): --pgp6 flag. This is not nearly as involved as --pgp2. In short, it turns off force_mdc, turns on no_comment, escape_from, and force_v3_sigs, and sets compression to 1. It also restricts the user to IDEA (if present), 3DES, CAST5, MD5, SHA1, and RIPEMD160. See the comments above algo_available() for lots of discussion on why you would want to do this. 2002-01-27 David Shaw * keygen.c (keygen_set_std_prefs): Comment * keyedit.c (sign_uids): Bug fix - when signing with multiple secret keys at the same time, make sure each key gets the sigclass prompt. * exec.c (exec_finish): Close the iobuf and FILE before trying to waitpid, so the remote process will get a SIGPIPE and exit. This is only a factor when using a pipe to communicate. * exec.c (exec_write): Disable cache-on-close of the fd iobuf (is this right? Why is a fd iobuf cached at all?) 2002-01-26 Werner Koch * g10.c, options.h: New option --gpg-agent-info * passphrase.c (agent_open): Let it override the environment info. * seckey-cert.c (check_secret_key): Always try 3 times when the agent is enabled. * options.skel: Describe --use-agent. 2002-01-24 David Shaw * pubkey-enc.c (is_algo_in_prefs, get_it): Only check preferences against keys with v4 self sigs - there is really little point in warning for every single non-IDEA message encrypted to an old key. * pkclist.c (select_algo_from_prefs): Only put in the fake IDEA preference if --pgp2 is on. * mainproc.c (check_sig_and_print): Print "Expired" for expired but good signatures (this still prints "BAD" for expired but bad signatures). 2002-01-23 David Shaw * keygen.c (ask_keysize): Cosmetic: don't present a RSA signing key as a "keypair" which can be 768 bits long (as RSA minimum is 1024). * pubkey-enc.c (is_algo_in_prefs): Allow IDEA as a fake preference for v3 keys with v3 selfsigs. 2002-01-22 David Shaw * packet.h, getkey.c (merge_selfsigs_main), pkclist.c (select_algo_from_prefs): Implement the fake IDEA preference as per RFC2440:12.1. This doesn't mean that IDEA will be used (the plugin may not be present), but it does mean that a v3 key with a v3 selfsig has an implicit IDEA preference instead of 3DES. v3 keys with v4 selfsigs use preferences as normal. * encode.c (encode_crypt): if select_algo_from_prefs fails, this means that we could not find a cipher that both keys like. Since all v4 keys have an implicit 3DES preference, this means there is a v3 key with a v3 selfsig in the list. Use 3DES in this case as it is the safest option (we know the v4 key can handle it, and we'll just hope the v3 key is being used in an implementation that can handle it). If --pgp2 is on, warn the user what we're doing since it'll probably break PGP2 compatibility. * g10.c (main): Do not force using IDEA for encrypted files in --pgp2 mode - let the fake IDEA preference choose this for us for better compatibility when encrypting to multiple keys, only some of which are v3. * keygen.c (keygen_set_std_prefs): Put 3DES on the end of the default cipher pref list (RFC2440: "...it is good form to place it there explicitly."). If the user has the IDEA plugin installed, put a preference for IDEA *after* 3DES to effectively disable its use for everything except encrypting along with v3 keys. * encode.c, g10.c, sign.c: Change the PGP2 warning line from "... will not be usable ..." to "... may not be usable ..." as the user could be using one of the enhanced PGP2 variations. * helptext.c: Revise the sign_uid.class help text as suggested by Stefan. 2002-01-20 Werner Koch * passphrase.c (passphrase_to_dek): Add tryagain_text arg to be used with the agent. Changed all callers. (agent_get_passphrase): Likewise and send it to the agent * seckey-cert.c (do_check): New arg tryagain_text. (check_secret_key): Pass the string to do_check. * keygen.c (ask_passphrase): Set the error text is required. * keyedit.c (change_passphrase): Ditto. * passphrase.c (agent_open): Disable opt.use_agent in case of a problem with the agent. (agent_get_passphrase): Ditto. (passphrase_clear_cache): Ditto. 2002-01-19 Werner Koch * passphrase.c (agent_open): Add support for the new Assuan based gpg-agent. New arg to return the used protocol version. (agent_get_passphrase): Implemented new protocol here. (passphrase_clear_cache): Ditto. (readline): New. 2002-01-15 Timo Schulz * encode.c (encode_crypt_files): Fail if --output is used. * g10.c: New command --decrypt-files. * decrypt.c (decrypt_messages): New. 2002-01-09 David Shaw * g10.c, misc.c, gpgv.c: move idea_cipher_warn to misc.c so gpgv.c doesn't need a stub for it any longer. * g10.c (get_temp_dir), main.h: no longer used (it's in exec.c now) * g10.c (main), delkey.c (delete_keys), main.h : Allow --delete-key (now --delete-keys, though --delete-key still works, of course) to delete multiple keys in one go. This applies to --delete-secret-key(s) and --delete-secret-and-public-key(s) as well. 2002-01-09 Timo Schulz * encode.c (encode_crypt_files): Now it behaves like verify_files. * g10.c (main): We don't need to check argc for encode_crypt_files any longer. 2002-01-09 Timo Schulz * exec.c: Include windows.h for dosish systems. 2002-01-08 Timo Schulz * g10.c (main): New description for --encrypt-files. 2002-01-08 Werner Koch * g10.c (main): Must register the secring for encryption because it is needed to figure out the default recipient. Reported by Roger Sondermann. 2002-01-05 David Shaw * keyedit.c (menu_adduid): Require --expert before adding a photo ID to a v3 key, and before adding a second photo ID to any key. * keyedit.c (keyedit_menu): Don't allow adding photo IDs in rfc1991 or pgp2 mode. * getkey.c (merge_selfsigs_subkey): Permit v3 subkeys. Believe it or not, this is allowed by rfc 2440, and both PGP 6 and PGP 7 work fine with them. * g10.c, options.h, keyedit.c, sign.c: Move the "ask for expiration" switch off of --expert, which was getting quite overloaded, and onto ask-sig-expire and ask-cert-expire. Both default to off. * g10.c (main): Change the default compression algo to 1, to be more OpenPGP compliant (PGP also uses this, so it'll help with interoperability problems as well). * encode.c (encode_crypt): Handle compression algo 2, since the default is now 1. * build-packet.c (build_attribute_subpkt): Fix off-by-one error. 2002-01-05 Werner Koch * g10.c (main): Do not register the secret keyrings for certain commands. * keydb.c (keydb_add_resource): Use access to test for keyring existence. This avoids cached opened files which are bad under RISC OS. 2002-01-04 David Shaw * sign.c (sign_file, sign_symencrypt_file): always use one-pass packets unless rfc1991 is enabled. This allows a signature made with a v3 key to work in PGP 6 and 7. Signatures made with v4 keys are unchanged. * g10.c (main): Disallow non-detached signatures in PGP2 mode. Move the "you must use files and not pipes" PGP2 warning up so all the PGP2 stuff is together. * encode.c (encode_simple): Use the actual filesize instead of partial length packets in the internal literal packet from a symmetric message. This breaks PGP5(?), but fixes PGP2, 6, and 7. It's a decent tradeoff. Note there was only an issue with old-style RFC1991 symmetric messages. 2440-style messages in 6 and 7 work with or without partial length packets. 2002-01-03 David Shaw * g10.c (main): Removed --no-default-check-level option, as it is not consistent with other "default" options. Plus, it is the same as saying --default-check-level 0. * exec.c (exec_read): Disallow caching tempfile from child process, as this keeps the file handle open and can cause unlink problems on some platforms. * keyserver.c (keyserver_search_prompt): Minor tweak - don't bother to transform keyids into textual form if they're just going to be transformed back to numbers. 2002-01-03 Timo Schulz * g10.c: New command --encrypt-files. * verify.c (print_file_status): Removed the static because encode_crypt_files also uses this function. * main.h (print_files_status): New. (encode_crypt_files): New. * encode.c (encode_crypt_files): New. 2002-01-02 Stefan Bellon * keyserver.c: Moved util.h include down in order to avoid redefinition problems on RISC OS. * keyring.c (keyring_lock): Only lock keyrings that are writable. * keyring.c (keyring_update_keyblock): Close unused iobuf. * hkp.c (parse_hkp_index, hkp_search) [__riscos__]: Changed unsigned char* to char* because of compiler issues. * exec.c (exec_finish) [__riscos__]: Invalidate close cache so that file can be unlinked. 2001-12-28 David Shaw * g10.c (main): Use a different strlist to check extensions since they need to be handled seperately now. * misc.c,main.h (check_permissions): Properly handle permission and ownership checks on files in the lib directory (e.g. /usr/local/lib/gnupg), which are owned by root and are world-readable, and change all callers to specify extension or per-user file. * photoid.c (show_photo), keyserver.c (keyserver_spawn): Bug fix - don't call exec_finish if exec_write fails. * keyserver.c (keyserver_spawn): Look for OPTIONS from the keyserver helper - specifically, a "OUTOFBAND" option for the email keyserver. * mainproc.c (list_node), keylist.c (list_keyblock_colon), import.c (delete_inv_parts), export.c (do_export_stream): Use signature flags for exportability check rather than re-parsing the subpacket. * keyid.c, keydb.h (get_lsign_letter): No longer needed. 2001-12-27 David Shaw * exec.c (exec_finish): Show errors when temp files cannot be deleted for whatever reason. * exec.c (exec_read): Don't rely on WEXITSTATUS being present. * exec.c (make_tempdir): Add temp file creator for win32. Don't create an incoming temp file if the exec is write-only. * keyserver.c (keyserver_spawn): Clean up error handling, for when the spawn fails. * photoid.c (show_photo): Clean up error handling. * misc.c (check_permissions): Neaten. 2001-12-25 David Shaw * mkdtemp.c (mkdtemp): Add copyleft info and tweak the 'X' counter to be a bit simpler. * keyserver.c, photoid.c: Remove unused headers left over from when the exec functions lived there. 2001-12-23 Timo Schulz * misc.c (check_permissions): Do not use it for W32 systems. * tdbio.c (migrate_from_v2): Define ftruncate as chsize() for W32. * mkdtemp.c: W32 support. * photoid.c: Ditto. * exec.c: Ditto. 2001-12-22 David Shaw * exec.c (make_tempdir): avoid compiler warning with const * mkdtemp.c (mkdtemp): catch the empty ("") string case in case someone repurposes mkdtemp at some point. * photoid.c (generate_photo_id, show_photo): some type changes from Stefan Bellon. * exec.c (make_tempdir): handle Win32 systems, suggested by Timo Schulz. 2001-12-22 Werner Koch * encode.c (encode_simple, encode_crypt): i18n 2 strings. 2001-12-22 Timo Schulz * encode.c (encode_simple, encode_crypt): Use is_file_compressed to avoid to compress compressed files. 2001-12-22 Werner Koch * keyserver.c (keyserver_spawn): Removed some variables declaration due to shadowing warnings. * build-packet.c (build_attribute_subpkt): s/index/idx/ to avoid compiler warnig due to index(3). * getkey.c (get_ctx_handle): Use KEYDB_HANDLE as return value. * keylist.c (list_one): Made resname const. * keyedit.c (keyedit_menu): Allow "addphoto" only when --openpgp is not used. * options.skel: Changed one example photo viewer to qiv. 2001-12-21 David Shaw * Makefile.am: add exec.c, exec.h, photoid.c, and photoid.h * build-packet.c (build_attribute_subpkt): new function to build the raw attribute subpacket. Note that attribute subpackets have the same format as signature subpackets. * exec.c: new file with generic exec-a-program functionality. Used by both photo IDs and keyserver helpers. This is pretty much the same code that used to be keyserver specific, with some changes to be usable generically. * free-packet.c (free_attributes (new)): function to free an attribute packet. * gpgv.c: added stub show_photo * keyedit.c (keyedit_menu, menu_adduid, menu_showphoto): can add a photo (calls generate_photo_id), or display a photo (calls show_photo) from the --edit menu. New commands are "addphoto", and "delphoto" (same as "deluid"). * keylist.c (list_keyblock_print): show photos during key list if --show-photos enabled. * keyserver.c (keyserver_spawn): use the generic exec_xxx functions to call keyserver helper. * g10.c, options.h: three new options - --{no-}show-photos, and --photo-viewer to give the command line to display a picture. * options.skel: instructions for the photo viewer * parse-packet.c (parse_user_id, setup_user_id (new)): common code for both user IDs and attribute IDs moved to setup_user_id. * parse-packet.c (make_attribute_uidname (new)): constructs a fake "name" for attribute packets (e.g. "[image of size ...]") * parse-packet.c (parse_attribute (replaces parse_photo_id), parse_attribute_subpkts): Builds an array of individual attributes. Currently only handles attribute image / type jpeg subpackets. * sign.c (hash_uid): Fix bug in signing attribute (formerly photo_id) packets. * packet.h, and callers: globally change "photo_id" to "attribute" and add structures for attributes. The packet format is generic attributes, even though the only attribute type thus far defined is jpeg. 2001-12-21 David Shaw * parse-packet.c (can_handle_critical): Can handle critical revocation subpackets now. * trustdb.c (mark_usable_uid_certs): Disregard revocations for nonrevocable sigs. Note that this allows a newer revocable signature to override an older nonrevocable signature. * sign.c (make_keysig_packet): add a duration field and change all callers. This makes make_keysig_packet closer to write_signature_packets and removes some duplicated expiration code. * keyedit.c (keyedit_menu, menu_revsig, sign_uids, sign_mk_attrib): Add nrsign command, don't allow revoking a nonrevocable signature, * g10.c (main): Add --nrsign option to nonrevocably sign a key from the command line. * build-packet.c (build_sig_subpkt_from_sig): Comment to explain the use of CRITICAL. 2001-12-21 Werner Koch * g10.c. options.h : New option --show-keyring * getkey.c (get_ctx_handle): New. * keylist.c (list_one): Implement option here. By David Champion. 2001-12-20 David Shaw * keyserver.c (keyserver_spawn): Use mkdtemp() to make temp directory. * mkdtemp.c: replacement function for those platforms that don't have mkdtemp (make a temp directory securely). 2001-12-19 David Shaw * misc.c (check_permissions): New function to stat() and ensure the permissions of GNUPGHOME and the files have safe permissions. * keydb.c (keydb_add_resource): Check keyring permissions. * tdbio.c (tdbio_set_dbname): Check permissions of trustdb.gpg * keyserver.c (keyserver_spawn): Disable keyserver schemes that involve running external programs if the options file has unsafe permissions or ownership. * g10.c, options.h: New option --no-permission-warning to disable the permission warning message(s). This also permits use of the keyserver if it had been disabled (see above). Also check the permissions/ownership of random_seed. * keyserver.c (keyserver_spawn): The new glibc prints a warning when using mktemp() (the code was already secure, but the warning was bound to cause confusion). Use a different implementation based on get_random_bits() instead. Also try a few times to get the temp dir before giving up. 2001-12-19 Werner Koch * g10.c, passphrase.c [CYGWIN32]: Allow this as an alias for MINGW32. 2001-12-18 David Shaw * g10.c (idea_cipher_warn): Add a flag to show the warning always or once per session and change all callers (show always except for the secret key protection and unknown cipher from an encrypted message errors). Also make the strings translatable. * pubkey-enc.c (get_it): Add the IDEA cipher warning if the user tries to decrypt an IDEA encrypted message without the IDEA plugin. * keyserver.c (parse_keyserver_uri): More strict checking of the keyserver URI. Specifically, fail if the ":port" section is anything except a number between 1 and 65535. 2001-12-17 David Shaw * keyserver.c (print_keyinfo): No need to check for control/illegal characters, as utf8_to_native does this for us. * mainproc.c (proc_encrypted): Use generic IDEA warning. * gpgv.c: add stub for idea_cipher_warn * g10.c, hkp.c, keyserver.c: Fix capitalization and plural issues. * encode.c (encode_crypt), sign.c (sign_file, clearsign_file): disable pgp2 mode after the message is no longer pgp2 compatible. * g10.c (main): Tweak the PGP2.x IDEA warning to use the generic warning, and not merely fail if the IDEA plugin isn't there. * g10.c (main, idea_cipher_warn), keygen.c (set_one_pref), seckey-cert.c (do_check): Add a generic IDEA warning for when the IDEA plugin is not present. This pops up when the user uses "--cipher-algo idea", when setpref is used to set a "S1" preference, and when a secret key protected with IDEA is used. 2001-12-15 Werner Koch * keyserver.c (keyserver_spawn): Assert that we have dropped privs. 2001-12-13 Werner Koch * pubkey-enc.c (get_session_key): Check that the public key algorithm is indeed usable for en/decryption. This avoid a strange error message from pubkey_decrypt if for some reasons a bad algorithm indentifier is passed. 2001-12-12 David Shaw * Fixed some types for portability. Noted by Stefan Bellon. 2001-12-11 Werner Koch * hkp.c (hkp_export): Do not print possible control characters from a keyserver response. (parse_hkp_index): Made uid an unsigned char* because it is passed to isspace(). (hkp_search): Ditto for the char* vars. * g10.c (main): Print the IDEA warning also for -c and -se. * g10.c (get_temp_dir): Assert that we have dropped privs * encode.c (encode_crypt): Include the first key into the --pgp2 check. 2001-12-07 David Shaw * g10.c, options.h: New option --pgp2. This is identical to "--rfc1991 --cipher-algo idea --compress-algo 1 --digest-algo md5 --force_v3_sigs" with the addition of an warning to advise the user not to use a pipe (which would break pgp2 compatibility). * encode.c (encode_crypt): warn if the user tries to encrypt to any key that is not RSA and <= 2048 bits when the --pgp2 option is used. * sign.c (sign_file, clearsign_file): When using --pgp2, make a v3 sig, and warn if the signature is made with a non-v3 key. 2001-12-05 David Shaw * sign.c (sign_file, clearsign_file, sign_symencrypt_file): Prompt for sig expiration if --expert is set and --force-v3-sigs is not set (v3 sigs cannot expire). * mainproc.c (check_sig_and_print): After checking a sig, print expiration status. This causes a error return if the sig is expired. * build-packet.c (build_sig_subpkt_from_sig): Include a critical sig expiration subpacket if the sig is to expire. * keyedit.c (sign_uids): Do not sign an expired key unless --expert is set, in which case prompt. Also, offer to expire a signature when the key the user is signing expires. * keygen.c (ask_expire_interval): Add a value to determine whether to prompt for a key or sig expiration and change all callers. * keyid.c: New functions: expirestr_from_sig and colon_expirestr_from_sig. * keylist.c (list_keyblock_colon): Show sig expiration date in the --with-colons listing. * sign.c (make_keysig_packet, write_signature_packets): Pass in an optional timestamp for the signature packet, and change all callers. * keyedit.c (sign_mk_attrib): Include a critical expiration subpacket in the signature if an expiration date is given. 2001-12-04 David Shaw * keyedit.c (sign_uids): If the user tries to sign a locally-signed key, allow the cert to be promoted to a full exportable signature. This essentially deletes the old non-exportable sig, and replaces it with a new exportable one. 2001-12-04 David Shaw * keyedit.c (keyedit_menu): Do not allow signing a revoked key unless --expert is set, and ask even then. * keyedit.c (sign_uids): Do not allow signing a revoked UID unless --expert is set, and ask even then. * g10.c, options.h : New option --expert 2001-11-16 David Shaw * Allow the user to select no compression via "--compress-algo 0" on the command line. * keyedit.c (show_prefs): Show compression preferences in the long-form "showpref" style. * keygen.c (set_one_pref): Permit setting a no-compression ("Z0") preference. * getkey.c (fixup_uidnode): Fix compression preference corruption bug. 2001-12-02 David Shaw * g10.c: Add advisory --for-your-eyes-only option as per section 5.9 of 2440. 2001-12-05 David Shaw * Force a V4 sig if the user has a notation or policy URL set. 2001-12-04 David Shaw * g10.c: Add options --keyserver-options, --temp-directory, and auto-key-retrieve (the opposite of no-auto-key-retrieve). * hkp.c (hkp_search): New function to handle searching a HKP keyserver for a key * hkp.c (hkp_ask_import, hkp_export): Pretty large changes to make them communicate via the generic functions in keyserver.c * keyserver.c: new file with generic keyserver routines for getting keys from a keyserver, sending keys to a keyserver, and searching for keys on a keyserver. Calls the internal HKP stuff in hkp.c for HKP keyserver functions. Other calls are handled by an external program which is spawned and written to and read from via pipes. Platforms that don't have pipes use temp files. 2001-11-20 David Shaw * options.h, g10.c: New options show-notation, no-show-notation, default-check-level, no-default-check-level, show-policy-url, no-show-policy-url. * packet.h, sign.c (make_keysig_packet), parse-packet.c (parse_signature), free-packet.c (free_seckey_enc): Fill in structures for notation, policy, sig class, exportability, etc. * keyedit.c, keylist.c (print_and_check_one_sig, list_keyblock_print): Show flags in signature display for cert details (class, local, notation, policy, revocable). If selected, show the notation and policy url. * keyedit.c (sign_uids): Prompt for and use different key sig classes. * helptext.c (helptexts): Add help text to explain different key signature classes 2001-11-26 David Shaw * trustdb.c (mark_usable_uid_certs): Fix segfault from bad initialization and fix reversed key signature expiration check. 2001-11-09 Werner Koch * export.c (do_export_stream): Put all given names into a search description and change the loop so that all matching names are returned. 2001-11-08 Werner Koch * pubkey-enc.c (get_it): To reduce the number of questions on the MLs print the the name of cipher algorithm 1 with the error message. * mainproc.c: Changed the way old rfc1991 encryption cipher is selected. Based on a patch by W Lewis. * pkclist.c (do_edit_ownertrust): Allow to skip over keys, the non working "show info" is now assigned to "i" * trustdb.c (ask_ownertrust, validate_keys): Implement a real quit here. Both are by David Shaw. * trustdb.c (validate_keys): Make sure next_exipire is initialized. * sign.c (make_keysig_packet): Use SHA-1 with v4 RSA keys. * g10.c, options.h : New option --[no-]froce-v4-certs. * sign.c (make_keysig_packet): Create v4 sigs on v4 keys even with a v3 key. Use that new option. By David Shaw * revoke.c (ask_revocation_reason): Allow to select "no reason". By David Shaw. * keyid.c (fingerprint_from_sk): Calculation of an v3 fpr was plain wrong - nearly the same code in fingerprint_from_pk is correct. * build-packet.c (do_secret_key): Added a few comments to the code. 2001-11-07 Werner Koch * g10.c (main): Print a warning when -r is used w/o encryption. Suggested by Pascal Scheffers. 2001-10-23 Werner Koch * keyedit.c (keyedit_menu): Changed helptext for showpref command. Suggested by Reinhard Wobst. * keyring.c (keyring_search): When marking the offtbl ready, take into account that we may have more than one keyring. 2001-10-22 Werner Koch * Makefile.am: Do not use OMIT_DEPENDENCIES * build-packet.c (build_sig_subpkt): Default is now to put all types of subpackets into the hashed area and only list those which should go into the unhashed area. 2001-10-18 Werner Koch * keydb.c (keydb_add_resource): Rearranged the way we keep track of the resource. There will now be an entry for each keyring here and not in keyring.c itself. Store a token to allow creation of a keyring handle. Changed all functions to utilize this new design. (keydb_locate_writable): Make a real implementation. * keyring.c (next_kr): Removed and changed all callers to set the resource directly from the one given with the handle. (keyring_is_writable): New. (keyring_rebuild_cache): Add an arg to pass the token from keydb. 2001-10-17 Werner Koch * keyring.c (keyring_search): Enabled word search mode but print a warning that it is buggy. 2001-10-11 Werner Koch * hkp.c (hkp_ask_import): No more need to set the port number for the x-hkp scheme. (hkp_export): Ditto. 2001-10-06 Stefan Bellon * passphrase.c [__riscos__]: Disabled agent specific stuff. * g10.c: New option --no-force-v3-sigs. 2001-10-04 Werner Koch * export.c (do_export_stream): Do not push the compress filter here because the context would run out of scope due to the iobuf_close done by the caller. (do_export): Do it here instead. 2001-09-28 Werner Koch * keyedit.c (sign_uids): Always use the primary key to sign keys. * getkey.c (finish_lookup): Hack to return only the primary key if a certification key has been requested. * trustdb.c (cmp_kid_for_make_key_array): Renamed to (validate_one_keyblock): this and changed arg for direct calling. (make_key_array): Renamed to (validate_one_keyblock): this and changed args for direct calling. (mark_usable_uid_certs, validate_one_keyblock) (validate_key_list): Add next_expire arg to keep track of expiration times. (validate_keys): Ditto for UTKs and write the stamp. * tdbio.c (migrate_from_v2): Check return code of tbdio_sync. * tdbdump.c (import_ownertrust): Do a tdbio_sync(). * keyring.c: Made the offtbl an global object. 2001-09-27 Werner Koch * pkclist.c (do_edit_ownertrust): Allow settin of ultimate trust. * trustdb.c (mark_keyblock_seen): New. (make_key_array): Use it to mark the subkeys too. (validate_keys): Store validity for ultimatly trusted keys. 2001-09-26 Werner Koch * pkclist.c (check_signatures_trust, do_we_trust): Removed the invocation of add_ownertrust. Minor changes to the wording. (add_ownertrust, add_ownertrust_cb): Removed. * trustdb.c (get_validity): Allow to lookup the validity using a subkey. * trustdb.c (new_key_hash_table): Increased the table size to 1024 and changed the masks accordingly. (validate): Changed stats printing. (mark_usable_uid_certs): New. (cmp_kid_for_make_key_array): Does now check the signatures and figures out a usable one. 2001-09-25 Werner Koch * keyring.c (new_offset_item,release_offset_items) (new_offset_hash_table, lookup_offset_hash_table) (update_offset_hash_table, update_offset_hash_table_from_kb): New. (keyring_search): Use a offset table to optimize search for unknown keys. (keyring_update_keyblock, keyring_insert_keyblock): Insert new offsets. * getkey.c (MAX_UNK_CACHE_ENTRIES): Removed the unknown keys caching code. * g10.c, options.h, import.c: Removed the entire allow-secret-key-import stuff because the validity is now controlled by other means. * g10.c: New command --rebuild-keydb-caches. * keydb.c (keydb_rebuild_caches): New. * keyring.c (do_copy): Moved some code to (create_tmp_file, rename_tmp_file, write_keyblock): new functions. (keyring_rebuild_cache): New. * packet.h (PKT_ring_trust): Add sigcache field. * parse-packet.c (parse_trust): Parse sigcache. * keyring.c (do_copy): Always insert a sigcache packet. (keyring_get_keyblock): Copy the sigcache packet to the signature. * sig-check.c (cache_sig_result): Renamed from cache_selfsig_result. Changed implementation to use the flag bits and changed all callers. (mdc_kludge_check): Removed this unused code. (do_check): Do not set the sig flags here. * import.c (read_block): Make sure that ring_trust packets are never imported. * export.c (do_export_stream): and never export them. * trustdb.c (make_key_array): Skip revoked and expired keys. 2001-09-24 Werner Koch * g10.c, options.h: New option --no-auto-check-trustdb. * keygen.c (do_generate_keypair): Set newly created keys to ultimately trusted. * tdbio.h, tdbio.c: Removed all support for records DIR, KEY, UID, PREF, SIG, SDIR and CACH. Changed migration function to work direct on the file. (tdbio_read_nextcheck): New. (tdbio_write_nextcheck): New. 2001-09-21 Werner Koch Revamped the entire key validation system. * trustdb.c: Complete rewrite. No more validation on demand, removed some functions, adjusted to all callers to use the new and much simpler interface. Does not use the LID anymore. * tdbio.c, tdbio.h: Add new record types trust and valid. Wrote a migration function to convert to the new trustdb layout. * getkey.c (classify_user_id2): Do not allow the use of the "#" prefix. * keydb.h: Removed the TDBIDX mode add a skipfnc to the descriptor. * keyring.c (keyring_search): Implemented skipfnc. * passphrase.c (agent_open): Add missing bracket. Include windows.h. 2001-09-19 Werner Koch * keylist.c (print_fingerprint): Renamed from fingerprint, made global available. Added new arg to control the print style. * mainproc.c (print_fingerprint): Removed. * pkclist.c (print_fpr, fpr_info): Removed and changed callers to use print_fingerprint. * keyedit.c (show_fingerprint): Ditto. * passphrase.c (writen, readn) (agent_open, agent_close) (agent_get_passphrase) (passphrase_clear_cache): Support for W32. Contributed by Timo. * import.c (import_one): Release keydb handles at 2 more places. * keyring.c (keyring_release): Close the iobuf. (keyring_get_keyblock): Init ret_kb to NULL and store error contidion. * import.c (import_new_stats_handle): New. (import_release_stats_handle): New. (import_print_stats): Renamed from static fnc print_stats. (import_keys, import_keys_stream): Add an optional status handle arg and changed all callers. * hkp.c (hkp_ask_import): Add an stats_handle arg and changed all callers. * mainproc.c (print_pkenc_list): Use print_utf8_string2(). 2001-09-18 Werner Koch * g10.c: New command --refresh-keys. * hkp.c (hkp_refresh_keys): New. Contributed by Timo Schulz. * parse-packet.c (parse): Stop on impossible packet lengths. 2001-09-17 Werner Koch * mainproc.c (print_notation_data): Wrap notation data status lines after 50 chars. * mainproc.c (proc_pubkey_enc): Make option try-all-secrets work. By disastry@saiknes.lv. 2001-09-14 Werner Koch * parse-packet.c (dump_sig_subpkt): List key server preferences and show the revocable flag correctly. Contributed by David Shaw. 2001-09-09 Werner Koch * keyedit.c (keyedit_menu): No need to define another p. * keylist.c (print_capabilities): s/used/use/ so that it does not shadow a global. * sign.c (sign_file): Renamed arg encrypt to encryptflag * keygen.c: Replaced all "usage" by "use". * misc.c (openpgp_pk_algo_usage): Ditto. * pubkey-enc.c (get_it): Renamed arg k to enc so that the later defined k does not shadow it. * parse-packet.c (parse_gpg_control): No need to define another i. * getkey.c (get_pubkey_byfprint): Must use the enum values and not the fprint_len. * keyring.c (keyring_search): Removed a non-sense break. Both bugs pointed out by Stefan. 2001-09-07 Werner Koch * status.c, status.h: Added NO_RECP and ALREADY_SIGNED. * pkclist.c (build_pk_list): Issue NO_RECP. * keyedit.c (sign_uids): Added experimental ALREADY_SIGNED * hkp.c (hkp_import): Use log_error. Bug reported by Neal H Walfield. * getkey.c (classify_user_id2): Change args to take the desc union direct. It was a stupid idea to pass the individual fields of an union to this function. Changed all callers. (classify_user_id): Ditto and allow to pass NULL as the description. 2001-09-06 Werner Koch * getkey.c (fixup_uidnode): Features flag is now a bit vector. * keygen.c (add_feature_mdc): Ditto. Revamped the entire key I/O code to be prepared for other ways of key storages and to get rid of the existing shit. GDBM support has gone. * keydb.c: New * keyring.c, keyring.h: New. * ringedit.c: Removed. Moved some stuff to keyring.c * getkey.c: Changed everything related to the key retrieving functions which are now using the keydb_ functions. (prepare_search, word_match_chars, word_match) (prepare_word_match, compare_name): Moved to keyring.c (get_pubkey_byname): Removed ctx arg and add ret_kdbhd arg. Changed all callers. (key_byname): Use get_pubkey_end to release the context and take new ret_kbdhd arg. Changed all callers. (classify_user_id2): Fill the 16 byte fingerprint up with 4 null bytes not with zero bytes of value 4, tsss. * import.c (import_one): Updated to use the new keydb interface. (import_secret_one): Ditto. (import_revoke_cert): Ditto. * delkey.c (do_delete_key): Ditto. * keyedit.c (keyedit_menu): Ditto. (get_keyblock_byname): Removed. * revoke.c (gen_revoke): Ditto. * export.c (do_export_stream): Ditto. * trustdb.c (update_trustdb): Ditto. * g10.c, gpgv.c (main): Renamed add_keyblock_resource to keydb_add_resource. * Makefile.am: Added and removed files. * keydb.h: Moved KBNODE typedef and MAX_FINGERPRINT_LEN to * global.h: this new header. 2001-09-03 Werner Koch * passphrase.c (agent_get_passphrase): Changed nread to size_t. (passphrase_clear_cache): Ditto. * keyid.c (mk_datestr): Avoid trigraphs. (fingerprint_from_pk): Cache the keyid in the pk. * options.h: Add opt.with_fingerprint so that we know whether the corresponding options was used. * g10.c (main): Set it here. * pkclist.c (check_signatures_trust): Always print fingerprint when this option is used. Mixed a minor memory leak. * status.c, status.h: New status INV_RECP. * pkclist.c (build_pk_list): Issue this status. 2001-08-31 Werner Koch * parse-packet.c (parse_key,parse_pubkeyenc) (parse_signature): Return error on reading bad MPIs. * mainproc.c (check_sig_and_print): Always print the user ID even if it is not bound by a signature. Use the primary UID in the status messages and encode them in UTF-8 * status.c (write_status_text_and_buffer): New. 2001-08-30 Werner Koch * packet.h (sigsubpkttype_t): Add SIGSUBPKT_FEATURES. (PKT_public_key, PKT_user_id): Add a flag for it. * parse-packet.c, build-packet.c: Add support for them. * getkey.c (fixup_uidnode, merge_selfsigs): Set the MDC flags. * keygen.c (add_feature_mdc): New. (keygen_upd_std_prefs): Always set the MDC feature. * keyedit.c (show_prefs): List the MDC flag * pkclist.c (select_mdc_from_pklist): New. * encode.c (encode_crypt, encrypt_filter): Test whether MDC should be used. * cipher.c (write_header): Set MDC use depending on the above test. Print more status info. * delkey.c (do_delete_key): Kludge to delete a secret key with no public key available. * ringedit.c (find_secret_keyblock_direct): New. * getkey.c (seckey_available): Simplified. * ringedit.c (cmp_seckey): Now compares the secret key against the public key while ignoring all secret parts. (keyring_search): Use a public key packet as arg. Allow to search for subnkeys (search): Likewise. Changed all callers. (find_secret_keyblock_bypk): New. (find_secret_keyblock_byname): First locate the pubkey and then find the correponding secret key. * parse-packet.c (parse): Renamed pkttype arg to onlykeypkts and changed code accordingly. Changed all callers. (search_packet): Removed pkttype arg. * keyedit.c (keyedit_menu): First locate the public key and then try to locate a secret key. * ringedit.c (locate_keyblock_by_fpr): Removed. (locate_keyblock_by_keyid): Removed. (find_keyblock_bysk): Removed. * sig-check.c (check_key_signature2): Print the keyid along with the wrong sig class errors. 2001-08-24 Werner Koch * sign.c (sign_file): Stripped the disabled comment packet code. (sign_file, sign_symencrypt_file): Moved common code to .. (write_onepass_sig_packets): .. this new function. (sign_file, clearsign_file, sign_symencrypt_file): Moved common code to (write_signature_packets): this new function. (write_signature_packets, make_keysig_packet) (update_keysig_packet): Moved common code to (hash_uid, hash_sigclass_to_magic): these new functions (sign_file, sign_symencrypt_file): Moved common code to (write_plaintext_packet): this new function. 2001-08-21 Stefan Bellon * trustdb.c (query_trust_info): Changed trustlevel to signed int. * g10.c [__riscos__]: Fixed handling of --use-agent --lock-multiple. 2001-08-20 Werner Koch * encr-data.c (decrypt_data): Keep track on whether we already printed information about the used algorithm. * mainproc.c (proc_encrypted): Removed the non-working IDEA hack and print a message about the assumed algorithm. * passphrase.c (passphrase_to_dek): Use the same algorithm as above. (proc_symkey_enc): Print the algorithm, so that the user knows it before entering the passphrase. (proc_pubkey_enc, proc_pubkey_enc): Zero the DEK out. * encode.c (encode_crypt, encrypt_filter): Ditto. * g10.c: Allow for --sign --symmetric. * sign.c (sign_and_symencrypt): New. Applied patches from Stefan Bellon to support RISC OS. Nearly all of these patches are identified by the __riscos__ macro. * compress.c: Added a couple of casts. * g10.c [__riscos__]: Some patches and new options foo-file similar to all foo-fd options. * gpgv.c, openfile.c, ringedit.c, tdbio.c: Minor fixes. Mainly replaced hardcoded path separators with EXTSEP_S like macros. * passprase.c [__riscos__]: Disabled agent stuff * trustdb.c (check_trust): Changed r_trustlevel to signed int to avoid mismatch problems in pkclist.c * pkclist.c (add_ownertrust): Ditto. * plaintext.c (handle_plaintext) [__riscos__]: Print a note when file can't be created. * options.h [__riscos__]: Use an extern unless included from the main module. * signal.c (got_fatal_signal) [__riscos__]: Close all files. 2001-08-14 Werner Koch * keygen.c (ask_algo): New arg r_usage. Allow for RSA keys. (gen_rsa): Enabled the code. (do_create): Enabled RSA branch. (parse_parameter_usage): New. (proc_parameter_file): Handle usage parameter. (read_parameter_file): Ditto. (generate_keypair): Ditto. (generate_subkeypair): Ditto. (do_generate_keypair): Ditto. (do_add_key_flags): New. (keygen_add_std_prefs): Use the new function. (keygen_add_key_flags_and_expire): New. (write_selfsig, write_keybinding): Handle new usage arg. * build-packet.c (build_sig_subpkt): Make sure that key flags go into the hashed area. * keygen.c (write_uid): Initialize the reference cunter. * keyedit.c (keyedit_menu): No more need to update the trustdb for preferences. Added calls to merge keblock. * kbnode.c (dump_kbnode): Print some more flags. 2001-08-10 Werner Koch Revamped the preference handling. * packet.h (prefitem_t, preftype_t): New. (PKT_public_key): Added a uid field. (PKT_user_id): Added field to store preferences and a reference counter. * parse-packet.c (parse_user_id,parse_photo_id): Initialize them * free-packet.c (free_user_id): Free them. (copy_user_id): Removed. (scopy_user_id): New. (cmp_user_ids): Optimized for identical pointers. (release_public_key_parts): Release the uid. (copy_public_key_with_new_namehash): Removed. (copy_prefs): New. * keyedit.c (menu_adduid): Use the new shallow copy user id. (show_prefs): Adjusted implementation. (keyedit_menu): No more need to update the trustdb after changing preferences. * getkey.c (fixup_uidnode): Store preferences. (find_by_name): Return a user id packet and remove namehash stuff. (lookup): Removed the unused namehash stuff. (finish_lookup): Added foundu arg. (pk_from_block): Removed the namehash arg and changed all callers. (merge_selfsigs): Copy prefs to all keys. * trustdb.c (get_pref_data): Removed. (is_algo_in_prefs): Removed. (make_pref_record): Deleted and removed all class. * pkclist.c (select_algo_from_prefs): Adjusted for the new preference implementation. * pubkey-enc.c (is_algo_in_prefs): New. (get_it): Use that new function. 2001-08-09 Werner Koch * build-packet.c (build_sig_subpkt): Fixed calculation of newarea->size. * g10.c (main): New option "--preference-list" * keyedit.c (keyedit_menu): New commands "setpref" and "updpref". (menu_set_preferences): New. * keygen.c (keygen_set_std_prefs): New. (set_one_pref): New. (check_zip_algo): New. (keygen_get_std_prefs): New. (keygen_upd_std_prefs): New (keygen_add_std_prefs): Move the pref setting code into the above fnc. * build-packet.c (build_sig_subpkt): Updated the list of allowed to update subpackets. 2001-08-08 Werner Koch * packet.h (subpktarea_t): New. (PKT_signature): Use that type for hashed_data and unhashed_data and removed the _data prefix from those fields. Changed all users. * parse-packet.c (parse_signature): Changed allocation for that. (parse_sig_subpkt): Changed declaration (enum_sig_subpkt): Ditto and changed implementation accordingly. * free-packet.c (cp_subpktarea): Renamed from cp_data_block and adjusted implementation. Changed caller. * sig-check.c (mdc_kludge_check): Adjusted the hashing. (do_check): Ditto. * sign.c (sign_file, clearsign_file, make_keysig_packet, update_keysig_packet): Ditto. * build-packet.c (build_sig_subpkt): Partial rewrite. (find_subpkt): Adjusted and made static. (delete_sig_subpkt): Adjusted. (do_signature): Ditto. * keygen.c (ask_keysize): Do not print the notes about suggested key sizes if just a DSA key is generated. * trustdb.c (add_ultimate_key): s/log_error/log_info/ for duplicated inserted trusted keys. 2001-08-07 Werner Koch * sign.c (sleep): Redefine for W32. * g10.c, options.h: Set new flag opt.no_homedir_creation when --no-options is given. * openfile.c (try_make_homedir): Don't create the homedir in that case. 2001-08-03 Werner Koch * armor.c (armor_filter): Removed the default comment string because it could get us in trouble due to translations using non ascii characters. 2001-08-01 Werner Koch * keylist.c (list_keyblock_print): Do not list revoked UIDs unless in verbose mode and we do no signature listing. * getkey.c (finish_lookup): Skip subkeys which are not yet valid. * g10.c, options.h: New option --ignore-valid-from. * sign.c (make_keysig_packet): Added new sigversion argument to allow the caller to force generation of required signature version. Changed all callers. Suggested by Thomas Roessler. * keyedit.c (sign_uids): Force v4 signature generation for local sigs. Removed the check for local signature and pre-v4 keys. 2001-07-27 Werner Koch * keyedit.c (sign_uids): Check that we are not trying to to a lsign with a pre-v4 key. Bug noticed by Thomas Roessler. 2001-07-26 Werner Koch * parse-packet.c (parse_photo_id): Reset all variables. * getkey.c (merge_selfsigs_main): Removed checks on PHOTO_ID because this is handled identically to a user ID. 2001-07-06 Werner Koch * cipher.c (write_header): Don't use MDC with --rfc1991. Suggested by disastry@saiknes.lv. 2001-07-05 Werner Koch * g10.c, options.h: New option --preserve-permissions. * ringedit.c (add_keyblock_resource): Use it here (keyring_copy): and here. * trustdb.c (verify_own_keys): Be more silent on --quiet. Suggested by Thomas Roessler. * sig-check.c (check_key_signature2): Ditto. * mainproc.c (proc_encrypted, proc_tree): Ditto * getkey.c (lookup): Ditto. 2001-07-04 Werner Koch * ringedit.c (add_keyblock_resource): Restore filename in case of error. 2001-06-25 Werner Koch * kbnode.c (dump_kbnode): Print the signature timestamp. * keyedit.c (keyedit_menu): New menu point "primary". (change_primary_uid_cb): New. (menu_set_primary_uid): New. * sign.c (update_keysig_packet): New. * build-packet.c (build_sig_subpkt): Put the primary UID flag into the hashed area. Allow update of some more packets. 2001-06-15 Werner Koch * getkey.c (merge_selfsigs): Exit gracefully when a secret key is encountered. May happen if a secret key is in public keyring. Reported by Francesco Potorti. 2001-06-12 Werner Koch * getkey.c (compare_name): Use ascii_memistr(), ascii_memcasecmp() * keyedit.c (keyedit_menu): Use ascii_strcasecmp(). * armor.c (radix64_read): Use ascii_toupper(). * ringedit.c (do_bm_search): Ditto. * keygen.c (read_parameter_file): Ditto. * openfile.c (CMP_FILENAME): Ditto. * g10.c (i18n_init): We can now use just LC_ALL. 2001-05-29 Werner Koch * keygen.c (generate_subkeypair): Print a warning if a subkey is created on a v3 key. Suggested by Brian M. Carlson. 2001-05-27 Werner Koch * keyid.c (get_lsign_letter): New. * keylist.c (list_keyblock_colon): Use it here. * mainproc.c (list_node): and here. * getkey.c, packet.h, free-packet.c: Removed that useless key created field; I dunno why I introducded this at all - the creation time is always bound to the key packet and subject to fingerprint calculation etc. * getkey.c (fixup_uidnode): Add keycreated arg and use this instead of the signature timestamp to calculate the help_key_expire. Bug reported by David R. Bergstein. (merge_selfsigs_main): Correct key expiration time calculation. (merge_selfsigs_subkey): Ditto. 2001-05-25 Werner Koch * revoke.c (gen_revoke): Add a cast to a tty_printf arg. * delkey.c (do_delete_key): Ditto. * keyedit.c (print_and_check_one_sig): Ditto. (ask_revoke_sig): Ditto. (menu_revsig): Ditto. (check_all_keysigs): Removed unused arg. 2001-05-23 Werner Koch * g10.c (opts): Typo fix by Robert C. Ames. 2001-05-06 Werner Koch * revoke.c: Small typo fix 2001-05-04 Werner Koch * passphrase.c (passphrase_clear_cache): Shortcut if agent usage is not enabled. 2001-05-01 Werner Koch * passphrase.c (writen): Replaced ssize_t by int. Thanks to to Robert Joop for reporting that SunOS 4.1.4 does not have it. 2001-04-28 Werner Koch * getkey.c (merge_public_with_secret): pkttype was not set to subkey. 2001-04-27 Werner Koch * skclist.c (build_sk_list): Changed one log_debug to log_info. 2001-04-25 Werner Koch * keyedit.c (show_prefs): Add a verbose mode. (show_key_with_all_names): Pass verbose flag for special value of with_pref. (keyedit_menu): New command "showpref" (show_key_with_all_names): Mark revoked uids and the primary key. 2001-04-24 Werner Koch * getkey.c (get_primary_uid): Return a different string in case of error and made it translatable. * build-packet.c (do_secret_key): Ugly, we wrote a zero instead of the computed ndays. Thanks to M Taylor for complaining about a secret key import problem. 2001-04-23 Werner Koch * hkp.c (hkp_ask_import): Allow to specify a port number for the keyserver. Add a kudge to set the no_shutdown flag. (hkp_export): Ditto. * options.skel: Document the changes 2001-04-20 Werner Koch * options.skel: Add some more comments. 2001-04-19 Werner Koch * keyid.c (mk_datestr): New. Handles negative times. We must do this because Windoze segvs on negative times passed to gmtime(). Changed all datestr_from function to use this one. * keyid.c, keyid.h (colon_strtime): New. To implement the fixed-list-mode. (colon_datestr_from_pk): New. (colon_datestr_from_sk): New. (colon_datestr_from_sig): New. * keylist.c (list_keyblock_colon): Use these functions here. * mainproc.c (list_node): Ditto. 2001-04-18 Werner Koch * openfile.c (open_sigfile): Fixed the handling of ".sign". * mainproc.c (proc_tree): Use iobuf_get_real_fname. Both are by Vincent Broman. 2001-04-14 Werner Koch * getkey.c (fixup_uidnode): Removed check for !sig which is pointless here. Thanks to Jan Niehusmann. 2001-04-10 Werner Koch * sig-check.c (check_key_signature2): Use log_info instead of log_error so that messed up keys do not let gpg return an error. Suggested by Christian Kurz. * getkey.c (merge_selfsigs_main): Do a fixup_uidnode only if we have both, uid and sig. Thanks to M Taylor. 2001-04-05 Werner Koch * armor.c (unarmor_pump_new,unarmor_pump_release): New. (unarmor_pump): New. * pipemode.c (pipemode_filter): Use the unarmor_pump to handle armored or non-armored detached signatures. We can't use the regular armor_filter because this does only check for armored signatures the very first time. In pipemode we may have a mix of armored and binary detached signatures. * mainproc.c (proc_tree): Do not print the "old style" notice when this is a pipemode processes detached signature. (proc_plaintext): Special handling of pipemode detached sigs. * packet.h (CTRLPKT_PLAINTEXT_MARK): New. * parse-packet.c (create_gpg_control): New. * kbnode.c (dump_kbnode): Support it here. * mainproc.c (check_sig_and_print): Fixed the check for bad sequences of multiple signatures. (proc_plaintext): Add the marker packet. (proc_tree): We can now check multiple detached signatures. 2001-04-02 Werner Koch The length of encrypted packets for blocksizes != 8 was not correct encoded. I think this is a minor problem, because we usually use partial length packets. Kudos to Kahil D. Jallad for pointing this out. * packet.h: Add extralen to PKT_encrypted. * cipher.c (write_header): Set extralen. * build-packet.c (do_encrypted): Use extralen instead of const 10. (do_encrypted_mdc): Ditto. * parse-packet.c (parse_encrypted): Set extralen to 0 because we don't know it here. 2001-03-30 Werner Koch * getkey.c (premerge_public_with_secret): Changed wording an add the keyID to the info message. 2001-03-29 Werner Koch * getkey.c (premerge_public_with_secret): Use log_info instead of log_error when no secret key was found for a public one. Fix the usage if the secret parts of a key are not available. * openfile.c (ask_outfile_name): Trim spaces. (open_outfile): Allow to enter an alternate filename. Thanks to Stefan Bellon. * plaintext.c (handle_plaintext): Ditto. 2001-03-28 Werner Koch * mainproc.c (do_check_sig): Allow direct key and subkey revocation signature. * sig-check.c (check_key_signature2): Check direct key signatures. Print the signature class along with an error. 2001-03-27 Werner Koch * packet.h: Add a missing typedef to an enum. Thanks to Stefan Bellon. * g10.c: New option --no-sig-create-check. * sign.c (do_sign): Implement it here. * g10.c: New option --no-sig-cache. * sig-check.c (check_key_signature2): Implement it here. (cache_selfsig_result): and here. * keylist.c (list_keyblock): Removed debugging stuff. * getkey.c (cache_public_key): Made global. * keygen.c (write_selfsig, write_keybinding): Cache the new key. * getkey.c (key_byname): Add new arg secmode and changed all callers to request explicitly the mode. Deriving this information from the other supplied parameters does not work if neither pk nor sk are supplied. 2001-03-25 Werner Koch * packet.h (ctrlpkttype_t): New. * mainproc.c (add_gpg_control,proc_plaintext,proc_tree): Use the new enum values. * pipemode.c (make_control): Ditto. * armor.c (armor_filter): Ditto. 2001-03-24 Werner Koch * sign.c (do_sign): Verify the signature right after creation. 2001-03-23 Werner Koch * status.c, status.h (STATUS_UNEXPECTED): New. * mainproc.c (do_proc_packets): And emit it here. 2001-03-21 Werner Koch * status.c: Add sys/types.h so that it runs on Ultrix. Reported by Georg Schwarz.x * build-packet.c (build_sig_subpkt): Fixed generaton of packet length header in case where 2 bytes headers are needed. Thanks to Piotr Krukowiecki. 2001-03-19 Werner Koch * g10.c (main): the default keyring is no always used unless --no-default-keyring is given. * ringedit.c (add_keyblock_resource): invalidate cache after file creation. 2001-03-15 Werner Koch * keygen.c (ask_algo): Changed the warning of the ElGamal S+E Algo. * keylist.c (print_capabilities): New. (list_keyblock_colon): and use it here. 2001-03-13 Werner Koch * main.c, options.h: New option --fixed_list_mode. * keylist.c (list_keyblock_colon): use it here. * getkey.c (merge_keys_and_selfsig): Divert merging of public keys to the function used in key selection.. * keylist.c (is_uid_valid): Removed. (list_keyblock): Splitted into .. (list_keyblock_print, list_keyblock_colon): .. these. functions. Changed them to use the flags set in the key lookup code. (reorder_keyblock): New, so that primary user IDs are listed first. * ringedit.c (keyring_copy): flush the new iobuf chaces before rename or remove operations. This is mainly needed for W32. * hkp.c [HAVE_DOSISH_SYSTEM]: Removed the disabled code because we have now W32 socket support in ../util/http.c * skclist.c (key_present_in_sk_list): New. (is_duplicated_entry): New. (build_sk_list): Check for duplicates and do that before unlocking. 2001-03-12 Werner Koch * armor.c (parse_header_line): Removed double empty line check. (parse_header_line): Replaced trim_trailing_ws with a counting function so that we can adjust for the next read. * options.skel: Fixed 3 typos. By Thomas Klausner. Replaced the keyserver example by a better working server. * parse-packet.c (parse_symkeyenc): Return Invalid_Packet on error. (parse_pubkeyenc): Ditto. (parse_onepass_sig): Ditto. (parse_plaintext): Ditto. (parse_encrypted): Ditto. (parse_signature): Return error at other places too. (parse_key): Ditto. * g10.c (main): Set opt.list_packets to another value when invoked with the --list-packets command. * mainproc.c (do_proc_packets): Don's stop processing when running under --list-packets command. * signal.c (do_sigaction): Removed. (init_one_signal): New to replace the above. Needed to support systems without sigactions. Suggested by Dave Dykstra. (got_fatal_signal,init_signals): Use the above here. (do_block): Use sigset() if sigprocmask() is not available. * armor.c (parse_hash_header): Test on TIGER192, which is the correct value as per rfc2440. By Edwin Woudt. 2001-03-08 Werner Koch * misc.c: Include time.h. By James Troup. * getkey.c: Re-enabled the unknown user Id and PK caches and increased their sizes. * getkey.c (merge_selfsigs_main): Set expire date and continue processing even if we found a revoked key. (merge_selfsigs_subkeys): Ditto. * packet.h: Add an is_revoked flag to the user_id packet. * getkey.c (fixup_uidnode): Set that flag here. (merge_selfsigs_main): Fix so that the latest signature is used to find the self-signature for an UID. * parse-packet.c (parse_user_id): Zero out all fields. * mainproc.c (check_sig_and_print): Print the primary user ID according the the node flag and then all other non-revoked user IDs. (is_uid_revoked): Removed; it is now handled by the key selection code. Changed the year list of all copyright notices. 2001-03-07 Werner Koch * getkey.c (finish_lookup): Print an info message only in verbose mode. 2001-03-05 Werner Koch * packet.h: Replaced sigsubpkt_t value 101 by PRIV_VERIFY_CACHE. We have never used the old value, so we can do this without any harm. * parse-packet.c (dump_sig_subpkt): Ditto. (parse_one_sig_subpkt): Parse that new sub packet. * build-packet.c (build_sig_subpkt): Removed the old one from the hashed area. (delete_sig_subpkt): New. (build_sig_subpkt): Allow an update of that new subpkt. * sig-check.c (check_key_signature2): Add verification caching (cache_selfsig_result): New. * export.c (do_export_stream): Delete that sig subpkt before exporting. * import.c (remove_bad_stuff): New. (import): Apply that function to all imported data 2001-03-03 Werner Koch * getkey.c: Introduced a new lookup context flag "exact" and used it in all place where we once used primary. (classify_user_id2): Replaced the old function and add an extra argument to return whether an exact keyID has been requested. (key_byname): Removed the unused ctx.primary flag (get_seckey_byname2): Ditto. (finish_lookup): Changed debugging output. 2001-03-02 Werner Koch * keylist.c (list_one): Remove the merge key calls. 2001-03-01 Werner Koch * getkey.c (finish_lookup): Don't use it if we no specific usage has been requested. (merge_selfsigs_main): fix UID only if we have an signature. (lookup): Return UNU_PUBKEY etc. instead of NO_PUBKEY if we found a key but the requested usage does not allow this key. * import.c (import_one): Take UNU_PUBKEY into account. * mainproc.c (list_node): Ditto. * keylist.c (list_keyblock): Ditto. * keyedit.c (print_and_check_one_sig): Ditto. 2001-02-09 Werner Koch * delkey.c (delete_key): Removed that silly assert which rendered the whole new stuff meaningless. 2001-02-08 Werner Koch * getkey.c (key_byname): It can happen that we have both, sk and pk NULL, fix for that. * parse-packet.c (parse_one_sig_subpkt): Add support for primary_uid and key_flags. (can_handle_critical): Ditto * parse-packet.c (parse_encrypted): Fixed listing of pktlen for MDC packets. * getkey.c: Backported the version of this file from gpg 1.1. this involved some changes in other files too. * parse-packet.c (parse_key): Clear req_usage. * skclist.c (build_sk_list): Use req_usage to pass the usage information to the lookup function. * pkclist.c (build_pk_list): Ditto. * free-packet.c (copy_public_parts_to_secret_key): New. * keydb.h: Add IS_* macros to check the sig_class. * misc.c (openpgp_cipher_test_algo): New. (openpgp_pk_test_algo): New. (openpgp_pk_algo_usage): New. (openpgp_md_test_algo): New. * packet.h: Add a few fields to PKT_{public,secret}_key and PKT_user_id. * seckey-cert.c (do_check): Use the new main_keyid field. 2001-02-04 Werner Koch * encr-data.c (decrypt_data): Catch error when we had problems to parse the encrypted packet. By Timo. 2001-01-29 Werner Koch * g10.c (main): --batch does now set nogreeting. * delkey.c (do_delete_key): Fixed delete-both functionality. 2001-01-22 Werner Koch * g10.c: New command --delete-secret-and-public-key. * delkey.c (delete_key): Add new arg allow_both. (do_delete_key): Move most stuff from above to this new function. 2001-01-12 Werner Koch * passphrase.c (passphrase_to_dek): Use MD5 when IDEA is installed and we have no S2K. * mainproc.c (proc_encrypted): Likewise 2001-01-11 Werner Koch * sig-check.c (do_check): Print the signature key expire message only in verbose mode and added the keyID. 2001-01-09 Werner Koch * status.c, status.h: New status USERID_HINT. (write_status_text): Replace LF and CR int text by C-escape sequence. * passphrase.c (passphrase_to_dek): Fixed the NEED_PASSPHRASE output. It does now always print 2 keyIDs. Emit the new USERID_HINT. 2001-01-08 Werner Koch * g10.c, options.h: New option --no-expensive-trust-checks. * keylist.c (list_keyblock): Act on this option. 2001-01-04 Werner Koch * g10.c (main): Set homedir only in the pre-parsing phase and replace backslashes in the W32 version. 2001-01-03 Werner Koch * status.c, status.h : New status KEY_CREATED * keygen.c (do_generate_keypair,generate_subkeypair): Emit it. 2000-12-28 Werner Koch * signal.c (got_fatal_signal): Remove lockfiles here because the atexit stuff does not work due to the use of raise. Suggested by Peter Fales. * gpgv.c (remove_lockfiles): New stub. 2000-12-19 Werner Koch * status.c, status.h (cpr_get_no_help): New. * keyedit.c (keyedit_menu): Use it here because we have our own help list here. 2000-12-18 Werner Koch * mainproc.c (print_failed_pkenc): Don't print the sometimes confusing message about unavailabe secret key. Renamed ... (print_pkenc_list): ... to this and introduced failed arg. (proc_encrypted): Print the failed encryption keys and then the one to be used. (proc_pubkey_enc): Store also the key we are going to use. * mainproc.c (check_sig_and_print): Don't list revoked user IDs. (is_uid_revoked): New. 2000-12-08 Werner Koch * pipemode.c: Made the command work. Currently only for non-armored detached signatures. * mainproc.c (release_list): Reset the new pipemode vars. (add_gpg_control): Handle the control packets for pipemode * status.c, status.h: New stati {BEGIN,END}_STREAM. 2000-12-07 Werner Koch * g10.c: New option --allow-secret-key-import. * import.c (import_keys,import_keys_stream): Honor this option. (import): New arg allow_secret and pass that arg down to ... (import_secret_one): to this and print a warning if secret key importing is not allowed. 2000-12-05 Werner Koch * cipher.c (cipher_filter): Moved the end_encryption status ... * encode.c (encode_simple,encode_crypt): to here * sign.c (sign_file): and here. * status.c (mywrite): Removed. (get_status_string): Removed the LFs from the strings. (set_status_fd,is_status_enabed,write_status_text, write_status_buffer): Replaced all mywrite by stdio calls and use fdopen to create a strem. This is needed to make things smoother in the W32 version. 2000-12-04 Werner Koch * import.c (merge_blocks): Increment n_sigs for revocations. 2000-11-30 Werner Koch * g10.c (main): Use iobuf_translate_file_handle for all options with filehandles as arguments. This is function does some magic for the W32 API. * verify.c (verify_signatures): Add a comment rant about the detached signature problem. * mainproc.c (proc_tree): Issue an error if a detached signature is assumed but a standard one was found. * plaintext.c (hash_datafiles): Don't fall back to read signature from stdin. * openfile.c (open_sigfile): Print verbose message only if the file could be accessed. 2000-11-24 Werner Koch * passphrase.c [HAVE_DOSISH_SYSTEM]: Disabled all the agent stuff. 2000-11-16 Werner Koch * g10.c: New option --use-agent * passphrase.c (agent_open,agent_close): New. (agent_get_passphrase,agent_clear_passphrase): New. (passphrase_clear_cache): New. (passphrase_to_dek): Use the agent here. * seckey-cert.c (do_check): Clear cached passphrases. 2000-11-15 Werner Koch * status.c (write_status_text): Moved the big switch to ... (get_status_string): ... new function. (write_status_buffer): New. * status.c (mywrite): New and replaced all write() by this. * status.c, status.h: Add 3 status lcodes for notaions and policy. * mainproc.c (print_notation_data): Do status output of notations. 2000-11-13 Werner Koch * sign.c (clearsign_file): Use LF macro to print linefeed. 2000-11-11 Paul Eggert Clean up the places in the code that incorrectly use "long" or "unsigned long" for file offsets. The correct type to use is "off_t". The difference is important on large-file hosts, where "off_t" is longer than "long". * keydb.h (struct keyblock_pos_struct.offset): Use off_t, not ulong, for file offsets. * packet.h (dbg_search_packet, dbg_copy_some_packets, search_packet, copy_some_packets): Likewise. * parse-packet.c (parse, dbg_search_packet, search_packet, dbg_copy_some_packets, copy_some_packets): Likewise. * ringedit.c (keyring_search): Likewise. * parse-packet.c (parse): Do not use %lu to report file offsets in error diagnostics; it's not portable. * ringedit.c (keyring_search): Likewise. 2000-11-09 Werner Koch * g10.c (main): New option --enable-special-filenames. 2000-11-07 Werner Koch * g10.c (main): New command --pipemode. * pipemode.c: New. 2000-10-23 Werner Koch * armor.c (armor_filter): Changed output of hdrlines, so that a CR is emitted for DOS systems. * keygen.c (read_parameter_file): Add a cast for isspace(). * status.c (myread): Use SIGINT instead of SIGHUP for DOS. 2000-10-19 Werner Koch * g10.c: New option --ignore-crc-error * armor.c (invalid_crc): New. (radix64_read): Act on new option. * openfile.c (try_make_homedir): Klaus Singvogel fixed a stupid error introduced on Sep 6th. 2000-10-18 Werner Koch * misc.c (print_cipher_algo_note): Don't print the note for AES. Changed wording. 2000-10-16 Werner Koch * mainproc.c (do_proc_packets): Hack to fix the problem that signatures are not detected when there is a MDC packet but no compression packet. * g10.c (print_hashline): New. (print_mds): Use above func with --with-colons. * mainproc.c (check_sig_and_print): Detect multiple signatures and don't verify them. 2000-10-14 Werner Koch * mainproc.c (add_onepass_sig): There is an easier solution to the error fixed yesterday; just check that we only have onepass packets. However, the other solution provides an cleaner interface and opens the path to get access to other information from the armore headers. (release_list): Reset some more variables. 2000-10-13 Werner Koch * mainproc.c (add_gpg_control): New. (do_proc_packets): use it. (proc_plaintext): Changed logic to detect clearsigns. (proc_tree): Check the cleartext sig with some new code. * packet.h: New packet PKT_GPG_CONTROL. * parse-packet.c (parse_gpg_control): New. * misc.c (get_session_marker): New. * armor.c (armor_filter): Replaced the faked 1-pass packet by the new control packet. * keyedit.c (keyedit_menu): Allow batchmode with a command_fd. * status.c (my_read): New. (do_get_from_fd): use it. 2000-10-12 Werner Koch * keygen.c (keygen_add_std_prefs): Add Rijndael to the prefs. 2000-10-07 Werner Koch * gpgv.c: Add more stubs for ununsed code to make the binary smaller. Wed Oct 4 15:50:18 CEST 2000 Werner Koch * sign.c (hash_for): New arg to take packet version in account, changed call callers. * gpgv.c: New. * Makefile.am: Rearranged source files so that gpgv can be build with at least files as possible. Mon Sep 18 12:13:52 CEST 2000 Werner Koch * hkp.c (not_implemented): Print a notice for W32 Fri Sep 15 18:40:36 CEST 2000 Werner Koch * keygen.c (keygen_add_std_prefs): Changed order of preferences to twofish, cast5, blowfish. * pkclist.c (algo_available): Removed hack to disable Twofish. Thu Sep 14 17:45:11 CEST 2000 Werner Koch * parse-packet.c (dump_sig_subpkt): Dump key flags. Print special warning in case of faked ARRs. * getkey.c (finsih_lookup): Hack so that for v4 RSA keys the subkey is used for encryption. Thu Sep 14 14:20:38 CEST 2000 Werner Koch * g10.c (main): Default S2K algorithms are now SHA1 and CAST5 - this should solve a lot of compatibility problems with other OpenPGP apps because those algorithms are SHOULD and not optional. The old way to force it was by using the --openpgp option whith the drawback that this would disable a couple of workarounds for PGP. * g10.c (main): Don't set --quite along with --no-tty. By Frank Tobin. * misc.c (disable_core_dump): Don't display a warning here but a return a status value and ... * g10.c (main): ...print warnining here. Suggested by Sam Roberts. Wed Sep 13 18:12:34 CEST 2000 Werner Koch * keyedit.c (keyedit_menu): Allow to use "debug" on the secret key. * ringedit.c (cmp_seckey): Fix for v4 RSA keys. * seckey-cert.c (do_check): Workaround for PGP 7 bug. Wed Sep 6 17:55:47 CEST 2000 Werner Koch * misc.c (print_pubkey_algo_note): Do not print the RSA notice. * sig-check.c (do_signature_check): Do not emit the RSA status message. * pubkey-enc.c (get_session_key): Ditto. * encode.c (encode_simple, encode_crypt): Fix for large files. * sign.c (sign_file): Ditto. Wed Sep 6 14:59:09 CEST 2000 Werner Koch * passphrase.c (hash_passphrase): Removed funny assert. Reported by David Mathog. * openfile.c (try_make_homedir): Changes for non-Posix systems. * g10.c (main): Take the default homedir from macro. * g10.c: The --trusted-key option is back. * trustdb.c (verify_own_key): Handle this option. (add_ultimate_key): Moved stuff from verify_own_key to this new func. (register_trusted_key): New. Fri Aug 25 16:05:38 CEST 2000 Werner Koch * parse-packet.c (dump_sig_subpkt): Print info about the ARR. * openfile.c (overwrite_filep): Always return okay if the file is called /dev/null. (make_outfile_name): Add ".sign" to the list of know extensions. (open_sigfile): Ditto. Wed Aug 23 19:52:51 CEST 2000 Werner Koch * g10.c: New option --allow-freeform-uid. By Jeroen C. van Gelderen. * keygen.c (ask_user_id): Implemented here. Fri Aug 4 14:23:05 CEST 2000 Werner Koch * status.c (do_get_from_fd): Ooops, we used fd instead of opt.command_fd. Thanks to Michael Tokarev. Tue Aug 1 20:06:23 CEST 2000 Werner Koch * g10.c: New opttion --try-all-secrets on suggestion from Matthias Urlichs. * pubkey-enc.c (get_session_key): Quite easy to implement here. Thu Jul 27 17:33:04 CEST 2000 Werner Koch * g10.c: New option --merge-only. Suggested by Brendan O'Dea. * import.c (import_one): Implemented it here (import_secret_one): Ditto. (print_stats): and give some stats. Thu Jul 27 12:01:00 CEST 2000 Werner Koch * g10.c: New options --show-session-key and --override-session-key * pubkey-enc.c (hextobyte): New. (get_override_session_key): New. * mainproc.c (proc_pubkey_enc): Add session-key stuff. * status.h, status.c (STATUS_SESSION_KEY): New. Thu Jul 27 10:02:38 CEST 2000 Werner Koch * g10.c (main): Use setmode(O_BINARY) for MSDOS while generating random bytes (print_mds): Likewise for stdin. * plaintext.c (handle_plaintext): Likewise for stdout. Mon Jul 24 10:30:17 CEST 2000 Werner Koch * keyedit.c (menu_expire): expire date for primary key can be set again. Wed Jul 19 11:26:43 CEST 2000 Werner Koch * keylist.c (is_uid_valid): New. (list_keyblock): Print validity information for all user IDs. Note, this has to be done at other places too; for now we have only minimal support. Wed Jul 12 13:32:06 CEST 2000 Werner Koch * helptext.c, pkclist.c: s/superseeded/superseded/ Mon Jul 10 16:08:57 CEST 2000 Werner Koch * parse-packet.c (enum_sig_subpkt): Fixed testing on crtitical bit in case of a NULL buffer. Reported by Peter Marschall. Wed Jul 5 13:28:45 CEST 2000 Werner Koch * keyedit.c, keyid.c: Add some _() * argparse.c: Changed the flag to suppress --version handling to also suppress --help. Wed Jun 28 11:54:44 CEST 2000 Werner Koch * armor.c (armor_filter): Set sigclass to 0 in case of non-dash-escaped clearsig. This makes this mode work again. * mainproc.c (proc_tree): Fixed handling of one-pass-sig packets in textmode. Disabled the ugly workaround for PGP 5 - let's see whether thi breaks less cases. Found by Ted Cabeen. * options.h (DBG_HASHING): New. All commented md_start_debug are now controlled by this debug option. * sign.c (print_status_sig_created): New and called from 2 places. * keygen.c (gen_rsa): New, but commented. (ask_algo): Commented support for RSA. * seckey-cert.c (protect_secret_key): Started to fix the code for v4 RSA keys - it is not solved yet. However, we have time until, Sep 20th ;) Wed Jun 14 12:27:09 CEST 2000 Werner Koch * status.c (init_shm_coprocessing): Changed the sequence of the get,attach to cope with the changes in newer Linux kernels. This bug has been found by who also proposed this solution. Hopefully this does not break gpg on to many systems. * cipher.c (write_header): Protect the IV with the MDC too. * encr-data.c (decrypt_data): Likewise. Fri Jun 9 10:09:52 CEST 2000 Werner Koch * g10.c: New options --no-auto-key-retrieve * options.h (auto_key_retrieve): New. * mainproc.c (check_sig_and_print): Implemented that. Wed Jun 7 19:19:09 CEST 2000 Werner Koch * sig-check.c (do_check): Use EMULATE_MDENCODE also on v4 packets. Wed Jun 7 17:25:38 CEST 2000 Werner Koch * cipher.c (write_header): Use plain CFB mode for MDC encrypted packets. * encr-data.c (decrypt_data): Ditto. Mon Jun 5 23:41:54 CEST 2000 Werner Koch * seskey.c (do_encode_md, encode_md_value): Add new arg v3compathack to work around a bug in old versions. * sig-check.c (do_check): use the aboved workaround when enabled. * g10.c: New option --emulate-md-decode-bug Mon Jun 5 12:37:43 CEST 2000 Werner Koch * build-packet.c (do_mdc): New. (do_encrypted_mdc): Changed for the new proposal. * parse-packet.c (parse_mdc): New. (parse_encrypted): Fixed for the new proposal. * packet.h (PKT_MDC): New. * cipher.c (cipher_filter): Build the MDC packet here. * g10.c (main): Enable --force-mdc. * encr-data.c (mdc_decode_filter): Fixed for new MDC method * options.h(rfc2440): New. * g10.c (main): Changed the selected values for --openpgp to not include optional algorithms. Thu May 18 11:38:54 CEST 2000 Werner Koch * keyedit.c (keyedit_menu): Add a keyword arg to the prompt. * status.c, status.h: Added 3 new status tokens. * status.c (do_get_from_fd): New. (cpr_enabled,cpr_get,cpr_get_hidden,cpr_kill_prompt, cpr_get_answer_is_yes,cpr_get_answer_yes_no_quit): Modified to work with the new function. * g10.c: Add new option --command-fd. * status.c (progress_cb): New. (set_status_fd): Register progress functions Fri May 12 14:01:20 CEST 2000 Werner Koch * delkey.c (delete_key): Add 2 new status messages * status.c, status.h (STATUS_DELETE_PROBLEM): New. Fixed years of copyright in all source files. Mon May 1 17:08:14 CEST 2000 Werner Koch * trustdb.c (propagate_validity): Fixed the bug that only one uid gets fully trusted even when all are signed by an ultimate key. Mon May 1 15:38:04 CEST 2000 Werner Koch * getkey.c (key_byname): Always returned a defined context. Fixed a segv for invalid user id specifications. Reported by Walter Koch. * getkey.c (get_user_id): I18ned "no user id" string. By Walter. * pkclist.c (do_show_revocation_reason): Typo fixes. * helptext.c: Ditto. * armor.c (armor_filter): Fixed some CRLF issues. By Mike McEwan. Fri Apr 14 19:37:08 CEST 2000 Werner Koch * pkclist.c (do_show_revocation_reason): New. (show_revocation_reason): New and called at various places. * g10.c (main): Fixed small typo. * pkclist.c (do_we_trust): Act on always_trust but not for revoked keys. Suggested by Chip Salzenberg. * g10.c: New option --lock-never. * ringedit.c (get_writable_keyblock_file): New. * keygen.c (do_generate_keypair): Use this instead of the hardwired one. * keygen.c (ask_user_id): Check that the email address is in the correct field. Suggested by Christian Kurz. Mon Apr 10 13:34:19 CEST 2000 Werner Koch * keyedit.c (show_key_with_all_names): s/sbb/ssb/ Tue Mar 28 14:26:58 CEST 2000 Werner Koch * trustdb.c (verify_own_keys): Do not print warning about unprotected key when in quiet mode. Wed Mar 22 13:50:24 CET 2000 Werner Koch * mainproc.c (print_userid): Do UTF8 conversion before printing. * import.c (import_one): Ditto. (import_secret_one): Ditto. (delete_inv_parts): Ditto. Thu Mar 16 16:20:23 CET 2000 Werner Koch * keylist.c (print_key_data): Handle a NULL pk gracefully. * getkey.c (merge_one_pk_and_selfsig): Fixed silly code for getting the primary keys keyID but kept using the one from the subkey. * pubkey-enc.c (get_it): Print a note for expired subkeys. * getkey.c (has_expired): New. (subkeys_expiretime): New. (finish_lookup): Check for expired subkeys needed for encryption. (merge_keys_and_selfsig): Fixed expiration date merging for subkeys. * keylist.c (list_keyblock): Print expiration time for "sub". (list_one): Add missing merging for public keys. * mainproc.c (list_node): Ditto. 2000-03-14 13:49:38 Werner Koch (wk@habibti.openit.de) * keygen.c (keyedit_menu): Do not allow to use certain commands while the secret key is selected. 2000-03-09 12:53:09 Werner Koch (wk@habibti.openit.de) * keygen.c (ask_expire_interval): Movede parsig to ... (parse_expire_string): ... this new function. And some new control commands. (proc_parameter_file): Add expire date parsing. (do_generate_keypair): Allow the use of specified output files. 2000-03-08 10:38:38 Werner Koch (wk@habibti.openit.de) * keygen.c (ask_algo): Removed is_v4 return value and the commented code to create Elg keys in a v3 packet. Removed the rounding of key sizes here. (do_create): Likewise removed arg v4_packet. (gen_elg): Likewise removed arg version. Now rounding keysizes here. (gen_dsa): Rounding keysize now here. (release_parameter_list): New (get_parameter*): New. (proc_parameter_file): New. (read_parameter_file): New. (generate_keypair): Splitted. Now uses read_parameter_file when in batch mode. Additional argument to specify a parameter file. (do_generate_keypair): Main bulk of above fucntion and uses the parameter list. (do_create): Don't print long notice in batch mode. * g10.c (main): Allow batched key generation. Thu Mar 2 15:37:46 CET 2000 Werner Koch * pubkey-enc.c (get_it): Print a note about unknown cipher algos. * g10.c (opts): Add a note to the help listing about the man page and removed some options from the help listing. * keyedit.c (print_and_check_one_sig): Use a new function to truncate the output of the user ID. Suggested by Jan-Benedict Glaw. Wed Feb 23 10:07:57 CET 2000 Werner Koch * helptext.c: typo fix. Thu Feb 17 13:39:32 CET 2000 Werner Koch * revoke.c: Removed a bunch of commented code. * packet.h (SIGSUBPKT_REVOC_REASON): New. * build-packet.c (build_sig_subpkt): Support new sub packet. * parse-packet.c (parse_one_sig_subpkt): Ditto. (dump_sig_subpkt): Ditto. * revoke.c (ask_revocation_reason): New. (release_revocation_reason_info): New. (revocation_reason_build_cb): New. (gen_revoke): Ask for reason. * main.h (struct revocation_reason_info): Add declaration. * keyedit.c (menu_revsig): Add support for revocation reason. (menu_revkey): Ditto. (sign_uid_mk_attrib): Renamed to ... (sign_mk_attrib): ... this, made static and add support for reasons. Tue Feb 15 08:48:13 CET 2000 Werner Koch * build-packet.c (build_packet): Fixed fixing of old comment packets. * import.c (import_keys): Fixed importing from stdin when called with nnames set to zero as it normally happens. Mon Feb 14 14:30:20 CET 2000 Werner Koch * sig-check.c (check_key_signature2): Add new arg r_expired. (do_signature_check): New arg to pass it down to ... (do_check): New arg r-expire which is set when the signature has expired. * trustdb.c (check_sig_record): Set SIGF_EXPIRED flag and set the expiretime to zero so that thi signature will not be checked anymore. Fri Feb 11 17:44:40 CET 2000 Werner Koch * g10.c (g10_exit): Update the random seed_file. (main): Set the random seed file. New option --no-random-seed-file. Thu Feb 10 17:39:44 CET 2000 Werner Koch * keyedit.c (menu_expire): Fixed segv due to unitialized sub_pk. By Rémi. Thu Feb 10 11:39:41 CET 2000 Werner Koch * keylist.c (list_keyblock): Don't print warnings in the middle of regulat output lines. By Rémi. * sig-check.c: Include options.h Wed Feb 9 15:33:44 CET 2000 Werner Koch * gpg.c: New option --ignore-time-conflict * sig-check.c (do_check): Implemented this option. * trustdb.c (check_trust): Ditto. * sign.c (do_sign): Ditto. * keygen.c (generate_subkeypair): Ditto. * encode.c (encode_simple): use iobuf_cancel after open failure. Reported by Huy Le. Fri Jan 14 18:32:01 CET 2000 Werner Koch * packet.h (STRING2KEY): Changed mode from byte to int. * parse-packet.c (parse_key): Add the special GNU protection stuff * build-packet.c (so_secret_key): Ditto. * seckey-cert.c (do_check): Ditto. * keyedit.c (change_passphrase): Ditto. * export.c (export_secsubkeys): New. (do_export_stream): Hack to export the primary key using mode 1001. * g10.c: New command --export-secret-subkeys Thu Jan 13 19:31:58 CET 2000 Werner Koch * armor.c (is_armored): Check for 1-pass-sig packets. Reported by David Hallinan . (armor_filter): Replaced one LF by the LF macro. Reported by Wolfgang Redtenbacher. Wed Jan 5 11:51:17 CET 2000 Werner Koch * g10.c (main): Reset new global flag opt.pgp2_workarounds when --openpgp is used. * mainproc.c (proc_plaintext): Do the PGP2,5 workarounds only when the global flag is set. (proc_tree): Ditto. * textfilter.c (copy_clearsig_text): Ditto. * armor.c (armor_filter): Ditto. * g10.c: New option --list-only * mainproc.c (proc_tree): Don't do it if opt.list_only is active. (proc_pubkey_enc): Implement option. * status.h, status.c ({BEGIN,END}_{EN,DE}CRYPTION): New. * cipher.c (cipher_filter): New status outputs. * mainproc.c (proc_encrypted): New status outputs. Fri Dec 31 14:08:15 CET 1999 Werner Koch * armor.c (armor_filter): Made the "Comment:" header translatable. * hkp.c (hkp_import): Make sure that the program does not return success when there is a connection problem. Reported by Phillip Jones. Sun Dec 19 15:22:26 CET 1999 Werner Koch * armor.c (LF): Use this new macro at all places where a line LF is needed. This way DOSish textfiles should be created when the input data is also in dos mode. * sign.c (LF): Ditto. * textfilter.c (LF): Ditto. (copy_clearsig_text): Disabled the forcing of CR,LF sequences for DOS systems. * plaintext.c (handle_plaintext): Fixes for line endings on DOS. and react on a LF in cleartext. * armor.c (fake_packet): Restore the original line ending after removing trailing spaces. * signal.c (got_fatal_signal): DOS fix. Thu Dec 16 10:07:58 CET 1999 Werner Koch * mainproc.c (print_failed_pkenc): Fix for unknown algorithm. Found by fygrave@epr0.org. Thu Dec 9 10:31:05 CET 1999 Werner Koch * hkp.c: i18n the strings. Sat Dec 4 15:32:20 CET 1999 Werner Koch * trustdb.c (verify_key): Shortcut for ultimately trusted keys. Sat Dec 4 12:30:28 CET 1999 Werner Koch * pkclist.c (build_pk_list): Validate the trust using the namehash if this one has been set by the key lookup. * g10.c: Add --delete-secret-key to the help page. * openfile.c (copy_options_file): Made static. (try_make_homedir): New. * ringedit.c (add_keyblock_resource): Use the try_make_hoemdir logic. * tdbio.c (tdbio_set_dbname): Likewise. * keygen.c (generate_user_id): Use m_alloc_clear() here. We should better use an allocation function specific to the user_id packet. * keygen.c (keygen_add_std_prefs): Changed symmetric preferences to include Blowfish again. This is due to it's better speed compared to CAST5. * g10.c (strusage): Print the home directory. * armor.c (armor_filter): Take action on the cancel control msg. * filter.h (armor_filter_context_t): Add cancel flag. Mon Nov 29 21:52:11 CET 1999 Werner Koch * g10.c: New option --fast-list-mode .. * keylist.c (list_keyblock): .. and implemented. * mainproc.c (list_node): Ditto. * import.c (mark_non_selfsigned_uids_valid): Fixed the case that there is a uid without any packet following. Mon Nov 22 11:14:53 CET 1999 Werner Koch * mainproc.c (proc_plaintext): Never enable the hash processing when skip_verify is active. * armor.c (parse_header_line): Stop parsing on a WS line too. Suggested by Aric Cyr. * tdbdump.c (HEXTOBIN): Changed the name of the argument, so that traditional cpp don't mess up the macros. Suggested by Jos Backus. * mainproc.c (list_node): Print the PK algo in the --with-colon mode. * keylist.c (list_keyblock): Ditto. * signal.c (got_fatal_signal): Found the reason why exit(8) did not work - it is better to set the disposition back to default before raising the signal. Print the notice on stderr always. Fri Nov 12 20:33:19 CET 1999 Werner Koch * g10.c (make_username): Swapped the logic. * keylist.c (public_key_list): Now takes a STRLIST as arg and moved the creation ot this list to the caller, so that he can copy with UTF-conversion of user IDs. Changed all callers. (secret_key_list): Likewise. * getkey.c (get_user_id_string_native): New and ... * encode.c (write_pubkey_enc_from_list): ... use it here. * pubring.asc: Updated. * packet.h (PKT_PHOTO_ID): New. * parse-packet.c (parse_photo_id): New. * build-packet.c (do_user_id: Handle photo IDs. (build_packet): Change CTB for photo IDs * free-packet.c (free_user_id): Release memory used for photo IDs * sig-check.c (hash_uid_node): Handle photo IDs too. * trustdb.c (print_uid_from_keyblock): Hash photo ID. (make_uid_records): Ditto. * getkey.c (find_by_name): Ditto. * keyedit.c (show_prefs): Ditto. * keylist.c (list_keyblock): Ditto. Thu Oct 28 16:08:20 CEST 1999 Werner Koch * keygen.c (ask_expire_interval): Print a warning for systems with a signed 32 time_t if the exiration time is beyoind 2038. Fri Oct 8 20:40:50 CEST 1999 Werner Koch * ringedit.c (enum_keyblocks): The last fix way really stupid; reverted and set rt to Unknown. Fri Oct 8 20:32:01 CEST 1999 Werner Koch * ringedit.c (enum_keyblocks): Zero the entire kbpos out on open. * g10.c (oEntropyDLL): Removed option. (main): Made the warning on development versions more verbose. * g10.c (oHonorHttpProxy): New option. * hkp.c (hkp_ask_import,hkp_export): Implement this option. * options.skel: Enable this option for new installations Mon Oct 4 21:23:04 CEST 1999 Werner Koch * import.c (import_keys): Changed calling interface, adjusted caller. (import): Moved printing of stats out ... (print_stats): New. ... to here. (import_keys_stream): Call stats print here. (import_keys): Print stats as totals for all files. * tdbio.h (DIRF_NEWKEYS): New * tdbio.c (tdbio_dump_record): Print the new flag. * trustdb.c (check_trust_record): New arg sigs_only. Adapted all callers. (do_update_trust_record): Removed recheck arg and add a new sigs_only do we can later improve on the performance. Changed all callers too. (check_trustdb): Evalutate the new flag and add a status output. Do a check when the dir record has not been checked. (build_cert_tree): Evaluate the new flag. (check_trust): Ditto. Do a trust_record check, when the dir record is not marked as checked. (mark_fresh_keys): New. (clear_lid_table): New. (sync_trustdb): New. * import.c (import_keys): Call sync_trustdb() after processing. (import_keys_stream): Ditto. * tdbdump.c (import_ownertrust): Ditto. * import.c (import_revoke_cert): Notify the trust DB. (do_update_trust_record): Use |= to set the REVOKED bit and not &=; shame on me for this bad copy+paste introduced bug. (do_we_trust): Add trustmask to allow revoked key override to work. Chnaged are to allow return of a mofified trustlevel. Adapted the one caller. * g10.c: New options --emulate-3des-s2k-bug * passphrase.c (hash_passphrase): Implemented above. * mainproc.c (proc_tree): Check for standalone signatures. (do_check_sig): Print a notice for a standalone revocation (check_sig_and_print): Do not print an error for unchecked standalone revocations. Tue Sep 28 20:54:37 CEST 1999 Werner Koch * encode.c (encode_simple): Use new CTB when we don't have the length of the file. This is somewhat strange as the comment above indicates that this part is actually fixed for PGP 5 - maybe I simply lost the source line, tsss. * armor.c (armor_filter): Set a flag if no OpenPGP data has been found. * verify.c (verify_signatures): Add an error helptext. Thu Sep 23 19:24:30 CEST 1999 Werner Koch * openfile.c (open_outfile): Fixed the 8dot3 handling. * passphrase.c (passphrase_to_dek): Print uid using utf8 func. * delkey.c (delete_key): Ditto. * pkclist.c (show_paths,do_edit_ownertrust,do_we_trust): Ditto (do_we_trust_pre): Ditto. * trustdb.c (print_user_id,check_uidsigs): Ditto. * revoke.c (gen_revoke,ask_revoke_sig): Ditto. Thu Sep 23 09:52:58 CEST 1999 Werner Koch * verify.c (print_file_status): New. (verify_one_file): Moved status print to th new fnc. Add error status. * status.c, status.h (STATUS_FILE_ERROR): New Wed Sep 22 10:14:17 CEST 1999 Werner Koch * openfile.c (make_outfile_name): Use case-insenstive compare for DOS systems. Add ".pgp" to the list of know extensions. (open_outfile): For DOS systems try to replace the suffiy instead of appending it. * status.c, status.h: Add STATUS_FILE_{START,DONE}. * verify.c (verify_one_file): Emit these new stati. * sign.c (clearsign_file): Avoid duplicated Entries in the "Hash:" line. Those headers are now only _not_ printed when there are only old-style keys _and_ all hashs are MD5. Mon Sep 20 12:24:41 CEST 1999 Werner Koch * verify.c (verify_files, ferify_one_file): New. * g10.c: New command --verify-files Fri Sep 17 12:56:42 CEST 1999 Werner Koch * g10.c: Add UK spelling as alias for armor options ;-) * import.c (append_uid): Fixed a SEGV when there is no selfsig and no subkey. (merge_sigs): Ditto. Removed the assertion. Wed Sep 15 16:22:17 CEST 1999 Werner Koch * g10.c: New option --entropy-dll-name Mon Sep 13 10:51:29 CEST 1999 Werner Koch * signal.c (got_fatal_signal): Print message using write(2) and only for development versions. Mon Sep 6 19:59:08 CEST 1999 Werner Koch * tdbio.c (tdbio_set_dbname): Use mkdir macro * ringedit.c (add_keyblock_resource): Ditto. Fri Sep 3 10:04:45 CEST 1999 Werner Koch * pkclist.c (build_pk_list): Skip keys set with --encrypt-to also when asking for a key. * plaintext.c (handle_plaintext): Make sure that we don't read a second EOF in the read loop for partial length packets. * mainproc.c (check_sig_and_print): print user ID as utf-8. Thu Sep 2 16:40:55 CEST 1999 Werner Koch * import.c (merge_blocks): First add new subkeys, then merge subkey certificates. (merge_sigs): Don't merge subkey signatures here. Wed Sep 1 15:30:44 CEST 1999 Werner Koch * keygen.c (ask_expire_interval): Fixed bug related to cpr_xx (tnx Francis J. Lacoste). Tue Aug 31 17:20:44 CEST 1999 Werner Koch * plaintext.c (do_hash): Hash CR,LF for a single CR. (ask_for_detached_datafile): Changed arguments to be closer to those of hash_datafiles and cleanup the code a bit. * mainproc.c (proc_tree): Workaround for pgp5 textmode detached signatures. Changed behavior of asking for data file to be the same as with provided data files. * keylist.c (list_keyblock): Use UTF8 print functions. Mon Aug 30 20:38:33 CEST 1999 Werner Koch * import.c (chk_self_sigs): some s/log_error/log_info/ so that gpg does not return an error if a key has some invalid packets. * helptext.c: Fixed some typos and changed the way the translation works. The english text is now the keyword for gettext and not anymore the keyword supplied to the function. Done after some discussion with Walter who thinks this is much easier for the translators. * misc.c (disable_core_dumps): Don't do it for DOSish systems. * signal.c (signal_name): Bounds check on signum. Wed Aug 4 10:34:18 CEST 1999 Werner Koch * pubring.asc: Updated. * pkclist.c (do_we_trust_pre,check_signatures_trust): Do not print the warning about --always_trust when --quiet is used. * pkclist.c (fpr_info): New and called at several places. * parse-packet.c (dump_sig_subpkt): List revocation key contents. Mon Jul 26 09:34:46 CEST 1999 Werner Koch * pkclist.c (build_pk_list): Fixed typo in format string. * trustdb.c (create_shadow_dir): Don't translate the error string. * g10.c (main): Fixed spelling of user-id. * getkey.c (find_by_name_pk,find_by_name_sk, find_by_keyid,find_by_keyid_sk): Ditto and translate it. * import.c (mark_non_selfsigned_uids_valid,delete_inv_parts): Ditto. Mon Jul 26 01:01:39 CEST 1999 Michael Roth * g10.c, options.h: New options --no-literal and --set-filesize * encode.c (encode_simple, encode_crypt): Support for the options --no-literal and --set-filesize. * sign.c (sign_file): ditto. Fri Jul 23 13:53:03 CEST 1999 Werner Koch * ringedit.c (enum_keyblocks): Removed annoying error message in cases when we have no keyring at all to enum. * getkey.c (classify_user_id): Rewrote to relax the recognition of keyIDs and fingerprints (Michael). * mainproc.c (check_sig_and_print): Print status NO_PUBKEY. (print_failed_pkenc): Print status NO_SECKEY. * import.c (mark_non_selfsigned_uids_valid): New. * g10.c: New option --allow-non-selfsigned-uid. * pkclist.c (print_fpr): New. (do_we_trust_pre): Print the fpr before asking whether to use the key anyway. (do_edit_ownertrust): Likewise. Thu Jul 22 20:03:03 CEST 1999 Werner Koch * ringedit.c (enum_keyblocks): Removed annoying error message in cases when we have no keyring at all to enum. * getkey.c (classify_user_id): Rewrote to relax the recognition of keyIDs and fingerprints (Michael). * mainproc.c (check_sig_and_print): Print status NO_PUBKEY. (print_failed_pkenc): Print status NO_SECKEY. * import.c (mark_non_selfsigned_uids_valid): New. * g10.c: New option --allow-non-selfsigned-uid. Thu Jul 15 10:15:35 CEST 1999 Werner Koch * g10.c: New options --disable-{cipher,pubkey}-algo. Wed Jul 14 19:42:08 CEST 1999 Werner Koch * status.h (STATUS_IMPORTED): New. * import.c (import): Print some status information (Holger Schurig). * g10.c (main): Make --no-greeting work again. Add a warning when --force-mds is used. Tue Jul 13 17:39:25 CEST 1999 Werner Koch * pkclist.c (do_edit_ownertrust): Changed the way help works. (build_pk_list): Implemented default recipient stuff. * g10.c: New options --default-recipient[-self] (main): Suppress greeting in most cases, entering a passphrase or a missing value is not considered to be interactive use. Merged --print-md and --print-mds; the latter is now obsolete. Changed the way --gen-random works and documented it. Changed the way --gen-prime works and add a man entry. * g10.c (MAINTAINER_OPTIONS): Removed. Mon Jul 12 18:45:57 CEST 1999 Werner Koch * keyedit.c (keyedit_menu): Add arg sign_mode and changed callers * g10.c (main): New command --lsign-key. Mon Jul 12 14:55:34 CEST 1999 Werner Koch * mainproc.c (kidlist_item): New. (release_list): Release failed pk-enc-list. (print_failed_pkenc): New (proc_encrypted): Print info about failed PK enc. * openfile.c (make_outfile_name): s/error/info/ * passphrase.c (passphrase_to_dek): Return an empty passphrase when in batch mode and don't make the warning message fatal * seckey-cert.c (check_secret_key): Try only once when in batch mode. * g10.c (make_username): New. Thu Jul 8 16:21:27 CEST 1999 Werner Koch * packet.h (PKT_ring_trust): New * parse-packet.c (parse_trust): Store trust value * build-packet (build_packet): Ignore ring trust packets. * mainproc.c (add_ring_trust): New. (list_node): Print "rtv" records. * g10.c: New option --with-fingerprint. * trustdb.c (verify_own_keys): Don't insert if we are dry running (check_trust): Ditto. Wed Jul 7 13:08:40 CEST 1999 Werner Koch * Makefile.am: Support for libtool. * keygen.c (ask_expire_interval): Hack to allow for an expire date. * trustdb.c (do_update_trust_record,update_trust_record): Splitted. (check_trust_record): New. (check_trust,build_cert_tree): Check the dir record as needed. (upd_pref_record): Removed. (make_pref_record): New. (propagate_validity): Stop as soon as we have enough validity. * tbdio.c (MAX_CACHE_ENTRIES_HARD): Increased the limit. Fri Jul 2 11:45:54 CEST 1999 Werner Koch * g10.c (g10_exit): Dump random stats. * sig-check.c (check_key_signature,check_key_signature2): Enhanced version and wrapper for old function. (do_signature_check,signature_check): Ditto. Thu Jul 1 12:47:31 CEST 1999 Werner Koch * keyedit.c (show_key_with_all_names): Print a notice for disabled keys. (enable_disable_keys): Add functionality * pkclist.c (edit_ownertrust): preserve disabled state. (build_pk_list): Skip disabled keys. * trustdb.c (upd_one_ownertrust): Ditto. (build_cert_tree): Mask the ownertrust. (trust_letter): Mask the value. (do_check): Take disabled flag into account. * passphrase.c (passphrase_to_dek): Add a pubkey_algo arg and changed all callers. * g10.c (utf8_strings): 2 new options. * trustdb.c (insert_trust_record_by_pk): New, replaces the next one. (insert_trust_record): Now takes a keyblock as arg. Changed all callers to use the appropritae function. * openfile.c (ask_outfile_name): New. * plaintext.c (handle_plaintext): Ask for filename if there is no valid syntax. Don't use fname varbatim but filter it. Tue Jun 29 21:44:25 CEST 1999 Werner Koch * trustdb.h (TRUST_FLAG_DISABLED): New. * status.c (USE_CAPABILITIES): Capabilities support (Remi). * tdbio.c : Added new fields to the DIR record. (tdbio_write_record): Fixed the update of the hash tables. (tdbio_delete_record): Drop the record from the hash tables. (drop_from_hashtbl): New. * status.c (cpr_get): Special online help mode. * helptext.c ("keyedit.cmd"): Removed. * keyedit.c (keyedit_menu): Use only help system. (enable_disable_key): New bit doies not yet work. Sat Jun 26 12:15:59 CEST 1999 Werner Koch * dearmor.c (enarmor_file): Fixed comment string. * tdbdump.c (export_ownertrust): Text fix. * tbio.c (tdbio_invalid): Ditto. * parse-packet.c (parse_key): Made temp buffer larger. * Makefile.am (install-data-local): Add missing backslashes Tue Jun 15 12:21:08 CEST 1999 Werner Koch * g10.c (main): Made iterated+salted the default S2K method. * Makefile.am (install-data-local): Use DESTDIR. * passphrase.c (passphrase_to_dek): Emit missing-passphrase while in batchmode. * parse-packet.c (parse_pubkeyenc): Fixed a SEGV. Mon Jun 14 21:18:54 CEST 1999 Michael Roth * g10.c: New options --openpgp, --no-tty, --emit-version, --default-comment and --lock-multiple Thu Jun 10 14:18:23 CEST 1999 Werner Koch * free-packet.c (free_encrypted): Fixed EOF case (Remi). (free_plaintext): Ditto. * helptext.c (keyedit.delsig.unknown): New (Remi). * keyedit.c (print_and_check_one_sig): Add arg print_without_key and changed all callers to make use of it (Remi): Tue Jun 8 13:36:25 CEST 1999 Werner Koch * keylist.c (print_key_data): New and called elsewhere. * g10.c: New option --with-key-data Wed Jun 2 14:17:19 CEST 1999 Werner Koch * mainproc.c (proc_tree): Yet another bad hack to cope with broken pgp2 created detached messages in textmode. Tue Jun 1 16:01:46 CEST 1999 Werner Koch * openfile.c (make_outfile_name): New. * plaintext.c (handle_plaintext): Outputfile is now the inputfile without the suffix. * g10.c: New option --use-embedded-filename Mon May 31 19:41:10 CEST 1999 Werner Koch * g10.c (main): Fix for SHM init (Michael). * compress.c, encr-data.c, mdfilter.c, plaintext.c, free-packet.c: Speed patches (Rémi). Thu May 27 09:40:55 CEST 1999 Werner Koch * status.c (cpr_get_answer_yes_no_quit): New. * keyedit.c (menu_delsig): New. (check_all_keysigs): Splitted. (print_and_check_one_sig): New. Wed May 26 14:36:29 CEST 1999 Werner Koch * build-packet.c (build_sig_subpkt): Support large packets. * parse-packet.c (enum_sig_subpkt): Replaces parse_sig_subpkt. * mainproc.c (print_notation_data): Print all notation packets. * g10.c (add_notation_data): Add a way to specify the critical flag. (main): Add option --set-policy-url. (check_policy_url): Basic checks. * sign.c (mk_notation_and_policy): Replaces mk_notation. * parse-packet.c (can_handle_critical): Moved decision whether we can handle critical subpacket to an extra function. Tue May 25 19:50:32 CEST 1999 Werner Koch * sign.c (sign_file): Always use compression algo 1 for signed onyl file becuase we can´ be sure the the verifier supports other algorithms. * build-packet.c (build_sig_subpkt): Support for notation data. * sign.c (sign_file,clearsign_file,make_keysig_packet): Ditto. (mk_notation): New. * g10.c (add_notation_data): New and add option -N * mainproc.c (print_notation_data): New. (check_sig_and_print): Print any notation data of the signed text. Sun May 23 14:20:22 CEST 1999 Werner Koch * pkclist.c (check_signatures_trust): Print a warning and return immediateley if opt.always_trust is true. * g10.c (main): Corrected handling of no-default-keyring * pkclist.c (algo_available): Disable Twofish until we have settled how to do the MDC. * hkp.c: Disable everything for mingw32 Sat May 22 22:47:26 CEST 1999 Werner Koch * mainproc.c (check_sig_and_print): Add sig creation time to the VALIDSIG status output. Add more info to the ERRSIG output. * sig-check.c (signature_check): Add sig time after epoch to SIG_ID. * import.c (import_one): Merge duplicate user IDs. (collapse_uids): New. * kbnode.c (move_kbnode): New. (remove_kbnode): New. * keyedit.c (keyedit_menu): Call collapse_uids. * g10.c: new option --logger-fd. * import.c: s/log_*_f/log_*/ Thu May 20 14:04:08 CEST 1999 Werner Koch * misc.c (pull_in_libs): do the volatile only for gcc * sig-check (signature_check): Emit SIG_iD only for classes 0 and 1. * armor.c (armor_filter): Add detection of PGP2 created clearsigs. (fake_packet): A tab is not a WS for pgp2 - handle this. * textfilter.c (len_without_trailing_chars): New. (copy_clearsig_text): Add pgp2mode arg. * sign.c (clearsign_file): pass old_style to the above fnc. Wed May 19 16:04:30 CEST 1999 Werner Koch * g10.c: New option --interactive. * mainproc.c (proc_plaintext): Add workaround for pgp2 bug (do_check_sig): Ditto. (proc_tree): Ditto. * plaintext.c (do_hash): Ditto. (hash_datafiles): Ditto, add an arg, changed all callers. * mdfilter.c (md_filter): Add support for the alternate hash context. Mon May 17 21:54:43 CEST 1999 Werner Koch * parse-packet.c (parse_encrypted): Support for PKT_ENCRYPTED_MDC. * build-packet.c (do_encrypted_mdc): Ditto. * cipher.c (write_header): Add mdc hashing. (cipher_filter): write out the hash. * mainproc.c (do_proc_packets): Add PKT_ENCRYPTED_MDC. * encr-data.c (decrypt_data): Add mdc hashing. (mdc_decode_filter): New. * parse-packet.c (parse_sig_subpkt): Fixed stupid bug for subpkt length calculation (parse_signature): Fixed even more stupid bug. Sat May 8 19:28:08 CEST 1999 Werner Koch * build-packet.c (do_signature): Removed MDC hack. * encode.c (encode_crypt_mdc): Removed. * mainproc.c (do_check_sig): Removed MDC hack. (check_sig_and_print): Ditto. * parse-packet.c (parse_signature): Ditto. * sig-check.c (mdc_kludge_check): Ditto. * free-packte.c (copy_signature, free_seckey_enc): Ditto. * parse-packet.c (parse_signature,parse_key): Store data of unknown algorithms with mpi_set_opaque inseatd of the old faked data stuff. (read_rest): Removed. (read_rest2): Renamed to read_rest * build-packet.c (write_fake_data): Use mpi_get_opaque. * free-packet.c (cp_fake_data): Removed and cahnged all callers to use mpi_copy. (free_pubkey_enc,free_seckey_enc,release_public_key_parts, release_secret_key_parts): Use mpi_free for opaque data. Thu May 6 14:18:17 CEST 1999 Werner Koch * trustdb.c (check_trust): Check for revoked subkeys. * pkclist.c (do_we_trust): Handled revoked subkeys. (do_we_trust_pre): Ditto. (check_signatures_trust): Ditto. * build-packet.c (hash_public_key): Fix for ancient g10 keys. * mainproc.c (do_proc_packets): Return EOF if no data has been read. * g10.c (main): Catch errors for default operation. Thu Apr 29 12:29:22 CEST 1999 Werner Koch * sign.c (sign_file): Fixed hashing in case of no subpackets. (clearsign_file): Ditto. (make_keysig_packet): Ditto. Wed Apr 28 13:03:03 CEST 1999 Werner Koch * keyedit.c (keyedit_menu): Add new command revkey. * (menu_revkey): New. Mon Apr 26 17:48:15 CEST 1999 Werner Koch * parse-packet.c (parse_signature): Add the MDC hack. * build-packet.c (do_signature): Ditto. * free-packet.c (free_seckey_enc,copy_signature,cmp_signatures): Ditto. * mainproc.c (do_check_sig): Ditto. * sig-check.c (mdc_kludge_check): New. * encode.c (encrypt_mdc_file): New. * keyedit.c (check_all_keysigs): List revocations. * (menu_revsig): New. * sign (make_keysig_packet): Support for class 0x30. Sun Apr 18 20:48:15 CEST 1999 Werner Koch * pkclist.c (select_algo_from_prefs): Fixed the case that one key has no preferences (Remi Guyomarch). keylist.c (list_keyblock): ulti_hack to propagate trust to all uids. Sun Apr 18 10:11:28 CEST 1999 Werner Koch * seckey-cert.c (do_check): Use real IV instead of a 0 one, so that it works even if the length of the IV doesn't match the blocksize. Removed the save_iv stuff. (protect_secret_key): Likewise. Create the IV here. * packet.h (PKT_secret_key): Increased size of IV field and add a ivlen field. * parse-packet.c (parse_key): Use the len protect.ivlen. * build-packet.c (do_secret_key). Ditto. * getkey.c (key_byname): Close keyblocks. * Makefile.am (gpgm): Removed this * g10.c: Merged gpg and gpgm * import.c (import): Utilize option quiet. * tdbio.c (tdbio_set_dbname): Ditto. * ringedit.c (add_keyblock_resource,keyring_copy): Ditto. * keyedit.c (sign_uids): Add some batch support. * g10.c (main): add call to tty_batchmode. Fri Apr 9 12:26:25 CEST 1999 Werner Koch * status.c (write_status_text): Some more status codes. * passphrase_to_dek (passphrase_to_dek): add a status code. * seckey_cert.c (check_secret_key): Likewise. * encr-data.c (decrypt_data): Reverse the last changes * cipher.c (write_header): Ditto. * parse-packet.c (parse_key): Dropped kludge for ancient blowfish mode. Thu Apr 8 09:35:53 CEST 1999 Werner Koch * mainproc.c (proc_encrypted): Add a new status output * passphrase.c (passphrase_to_dek): Ditto. * status.h status.c: Add new status tokens. Wed Apr 7 20:51:39 CEST 1999 Werner Koch * encr-data.c (decrypt_data): Fixes for 128 bit blocksize * cipher.c (write_header): Ditto. * seckey-cert.c (do_check): Ditto. (protect_secret_key). Ditto. * misc.c (print_cipher_algo_note): Twofish is now a standard algo. * keygen.c (do_create): Fixed spelling (Gaël Quéri) (ask_keysize): Only allow keysizes up to 4096 * ringedit.c (add_keyblock_resource): chmod newly created secrings. * import.c (delete_inv_parts): Fixed accidently deleted subkeys. Tue Apr 6 19:58:12 CEST 1999 Werner Koch * armor.c: Removed duped include (John Bley) * mainproc.c: Ditto. * build-packet.c (hash_public_key): Fixed hashing of the header. * import.c (delete_inv_parts): Allow import of own non-exportable sigs. Sat Mar 20 13:59:47 CET 1999 Werner Koch * armor.c (fake_packet): Fix for not not-dash-escaped Sat Mar 20 11:44:21 CET 1999 Werner Koch * g10.c (main): Added command --recv-keys * hkp.c (hkp_import): New. Wed Mar 17 13:09:03 CET 1999 Werner Koch * trustdb.c (check_trust): add new arg add_fnc and changed all callers. (do_check): Ditto. (verify_key): Ditto. (propagate_validity): Use the new add_fnc arg. (print_user_id): Add the FILE arg. (propagate_ownertrust): New. * pkclist.c (add_ownertrust_cb): New and changed the add_ownertrust logic. * getkey.c (get_keyblock_bylid): New. * trustdb.c (print_uid_from_keyblock): New. (dump_tn_tree_with_colons): New. (list_trust_path): Add colon print mode. * trustdb.c (insert_trust_record): Always use the primary key. * encode.c (encode_simple): Added text_mode filter (Rémi Guyomarch) (encode_crypt): Ditto. * mainproc.c (proc_pubkey_enc): Added status ENC_TO. * armor.c (armor_filter): Added status NODATA. * passphrase.c (passphrase_to_dek): Always print NEED_PASSPHRASE * seckey_cert.c (check_secret_key): Added BAD_PASS status. * g10.c (main): Set g10_opt_homedir. Sun Mar 14 19:34:36 CET 1999 Werner Koch * keygen.c (do_create): Changed wording of the note (Hugh Daniel) Thu Mar 11 16:39:46 CET 1999 Werner Koch * tdbdump.c: New * trustdb.c (walk_sigrecs,do_list_sigs,list_sigs, list_records,list_trustdb,export_ownertrust,import_ownertrust): Moved to tdbdump.c (init_trustdb): renamed to setup_trustdb. Changed all callers. (do_init_trustdb): renamed to init_trustdb(). * trustdb.c (die_invalid_db): replaced by tdbio_invalid. * tdbio.c (tdbio_invalid): New. * import.c (delete_inv_parts): Skip non exportable signatures. * keyedit.c (sign_uid_mk_attrib): New. (sign_uids): Add the local argument. (keyedit_menu): New "lsign" command. * trustdb.c (register_trusted_key): Removed this and all related stuff. * g10.c (oTrustedKey): Removed option. * tdbio.h (dir.valcheck): New trustdb field. * tdbio.c: Add support for this field (tdbio_read_modify_stamp): New. (tdbio_write_modify_stamp): New. * trustdb.c (do_check): Check against this field. Removed cache update. (verify_key): Add cache update. (upd_uid_record): Some functional changes. (upd_cert_record): Ditto Wed Mar 10 11:26:18 CET 1999 Werner Koch * keylist.c (list_keyblock): Fixed segv in uid. Print 'u' as validity of sks. Mon Mar 8 20:47:17 CET 1999 Werner Koch * getkey.c (classify_user_id): Add new mode 12 (#). * seckey-cert.c (check_secret_key): replaced error by info. * trustdb.c (query_trust_info): Add another arg, changed all callers. (check_trust): Ditto. (do_check): Ditto. (verify_key): Handle namehash. * keylist.c (list_keyblock): print trust info for user ids. * sig-check.c (signature_check): Add sig-created to status output. Tue Mar 2 16:44:57 CET 1999 Werner Koch * textfilter.c (copy_clearsig_text): New. (clearsign): Removed. * sign.c (clearsign_file): does not use textfiler anymore. * keygen.c (ask_user_id): print a note about the used charset. Tue Mar 2 10:38:42 CET 1999 Werner Koch * sig-check.c (signature_check): sig-id now works for all algos. * armor.c (armor_filter): Fixed armor bypassing. Sun Feb 28 19:11:00 CET 1999 Werner Koch * keygen.c (ask_user_id): Don't change the case of email addresses. (has_invalid_email_chars): Adjusted. * keylist.c (list_one): Really list serect keys (Remi Guyomarch) * keyedit.c (menu_select_uid): Add some braces to make egcs happy. (menu_select_key): Ditto. * mainproc.c (do_proc_packets): List sym-enc packets (Remi Guyomarch) Fri Feb 26 17:55:41 CET 1999 Werner Koch * pkclist.c (build_pk_list): Return error if there are no recipients. * sig-check.c (signature_check): New signature id feature. * armor.c (make_radic64_string): New. * mainproc.c (proc_pubkey_enc): early check for seckey availability. * pkclist.c (do_we_trust_pre): print user id before asking. * ringedit.c (add_keyblock_resource,get_keyblock_handle): Cleaner handling of default resource. Thu Feb 25 18:47:39 CET 1999 Werner Koch * pkclist.c (algo_available): New. (select_algo_from_prefs): Check whether algo is available. * ringedit.c (keyring_copy): Take care of opt.dry_run. (do_gdbm_store): Ditto. * openfile.c (open_outfile). Ditto. (copy_options_file): Ditto. * trustdb.c (update_trustdb): Ditto. (clear_trust_checked_flag): Ditto. (update_trust_record): Ditto. (insert_trust_record): Ditto. Wed Feb 24 11:07:27 CET 1999 Werner Koch * keylist.c (secret_key_list): Now really list the secret key. * trustdb.c (do_init_trustdb): New. Init is now deferred. Mon Feb 22 20:04:00 CET 1999 Werner Koch * getkey.c (lookup_sk): Return G10ERR_NO_SECKEY and not x_PUBKEY. Fri Feb 19 15:49:15 CET 1999 Werner Koch * pkclist.c (select_algo_from_prefs): retrieve LID if not there. * armor.c (fake_packet): Replaced ugly lineending handling. * g10.c (oNoEncryptTo): New. * pkclist.c (build_pk_list): Implemented this option. * g10.c (main): Greeting is now printed to stderr and not to tty. Use add_to_strlist() instead of direct coding. * import.c (import): Use iobuf_push_filter2. * mainproc.c (check_sig_and_print): Print all user ids for good signatures. * getkey.c (get_pubkeyblock): New. * import.c (chk_self_sigs): Fixed SEGV for unbounded class 0x18 keys. (delete_inv_parts): Delete special marked packets. Tue Feb 16 14:10:02 CET 1999 Werner Koch * g10.c (main): New option --encrypt-to * pkclist.c (build_pk_list): Implemented encrypt-to. * parse-packet.c (parse_user_id): Removed the hack to work with utf-8 strings. * g10.c (main): Install lockfile cleanup handler. * tdbio.c (cleanup): Removed: this is now handled by dotlock. Sat Feb 13 14:13:04 CET 1999 Werner Koch * tdbio.c (tdbio_set_dbname): Init lockhandle for a new trustdb Wed Feb 10 17:15:39 CET 1999 Werner Koch * g10.c (main): check for development version now in configure * tdbio.c (tdbio_write_record): Add uid.validity (tdbio_read_record) : Ditto. (tdbio_dump_record) : Ditto. * keygen.c (keygen_add_std_prefs): Replaced Blowfish by Twofish, removed MD5 and Tiger. * pubkey-enc.c (get_it): Suppress warning about missing Blowfish in preferences in certain cases. * ringedit.c (lock_rentry,unlock_rentry): New. * getkey.c (key_byname): Pass ret_kb down to lookup_xx. * armor.c (armor_filter): No output of of empty comment lines. Add option --no-version to suppress the output of the version string. * getkey.c: Release the getkey context for auto context variables. Sun Jan 24 18:16:26 CET 1999 Werner Koch * getkey.c: Changed the internal design to allow simultaneous lookup of multible user ids (get_pubkey_bynames): New. (get_seckey_bynames): New. (get_seckey_next): New. (get_seckey_end): New. * keylist.c (list_one): Use the new functions. * keylist.c (list_keyblock): add a newline for normal listings. * g10.c (--recipient): New option name to replace --remote-user Wed Jan 20 18:59:49 CET 1999 Werner Koch * textfilter.c: Mostly rewritten * plaintext.c (handle_plaintext): Use now text_filter semantics. Tue Jan 19 19:34:58 CET 1999 Werner Koch * export.c (export_pubkeys_stream): New. (do_export_stream): New. * g10.c (aSendKeys): New command. * hkp.c (hkp_export): New. * compress.c (do_uncompress): Hack for algo 1 and 1.1.3 Sun Jan 17 11:04:33 CET 1999 Werner Koch * textfilter.c (text_filter): Now uses iobuf_read_line(). (read_line): Removed. * armor.c (trim_trailing_spaces): Removed and replaced by trim_trailing_ws from libutil Sat Jan 16 12:03:27 CET 1999 Werner Koch * hkp.c (hkp_ask_import): Use only the short keyid Sat Jan 16 09:27:30 CET 1999 Werner Koch * import.c (import_key_stream): New (import): New, moved most of import_keys here. * g10.c: New option --keyserver * mainproc.c (check_sig_and_print): Hook to import a pubkey. * pref.c pref.h : Removed * hkp.c hkp.h: New Wed Jan 13 14:10:15 CET 1999 Werner Koch * armor.c (radix64_read): Print an error if a bad armor was detected. Wed Jan 13 12:49:36 CET 1999 Werner Koch * armor.c (radix64_read): Now handles malformed armors produced by some buggy MUAs. Tue Jan 12 11:17:18 CET 1999 Werner Koch * ringedit.c (find_keyblock_bysk): New. * skc_list.c (is_insecure): New. (build_sk_list): usage check for insecure keys. * import.c (chk_self_sigs): Add handling for subkeys. (delete_inv_parts): Skip unsigned subkeys * sig-check.c (do_check): Print info if the signature is older than the key. * keygen.c (generate_subkeypair): Fail on time warp. * sign.c (do_sign): Ditto. Sun Jan 10 15:10:02 CET 1999 Werner Koch * armor.c (fake_packet): Fixed not-dash-escaped bug. Sat Jan 9 16:02:23 CET 1999 Werner Koch * sig-check.c (do_check): Output time diff on error * status.c (STATUS_VALIDSIG): New. (is_status_enabled): New. * mainproc.c (check_sig_and_print): Issue that status message. * plaintext.c (special_md_putc): Removed * armor.c (armor_filter): print error for truncated lines. * free-packet.c (free_encrypted): Revomed call to set_block_mode. (free_plaintext): Ditto. Thu Jan 7 18:00:58 CET 1999 Werner Koch * pkclist.c (add_ownertrust): Fixed return value. * encr-data.c (decrypt_data): Disabled iobuf_set_limit and iobuf_pop_filter stuff. * compress.c (handle_compressed): Disabled iobuf_pop_filter. * packet.h (PKT_secret_key): Add is_primary flag. * parse-packet.c (parse_key): Set this flag. * passphrase.c (passphrase_to_dek): Kludge to print the primary keyid - changed the API: keyid must now hold 2 keyids. * getkey.c (get_primary_seckey): New. * seckey-cert.c (do_check): pass primary keyid to passphrase query * tbdio.c (open_db): removed the atexit (tdbio_set_dbname): and moved it to here. * armor.c: Rewrote large parts. Tue Dec 29 19:55:38 CET 1998 Werner Koch * revoke.c (gen_revoke): Removed compression. * pkclist.c (do_we_trust_pre): special check for revoked keys * trustdb.c (update_trust_record): Fixed revoke flag. Tue Dec 29 14:41:47 CET 1998 Werner Koch * misc.c (disable_core_dumps): Check for EINVAL (Atari) * getkey (merge_one_pk_and_selfsig): Fixed search of expiredate. (merge_keys_and_selfsig): Ditto. * free-packet.c (cmp_public_keys): cmp expire only for v3 packets (cmp_secret_keys): Ditto. (cmp_public_secret_key): Ditto. Wed Dec 23 17:12:24 CET 1998 Werner Koch * armor.c (find_header): Reset not_dashed at every header Wed Dec 23 13:18:14 CET 1998 Werner Koch * pkclist.c (add_ownertrust): Refresh validity values. * trustdb.c (enum_cert_paths_print): New arg refresh. * ringedit.c: Fixed problems fix keyrings * parse-packet.c (dbg_parse_packet): New debug functions. * getkey.c (getkey_disable_caches): New. * import.c (import_keys): Disable caches. Thu Dec 17 18:31:15 CET 1998 Werner Koch * misc.c (trap_unaligned): Only for glibc 1 * sign.c (write_dash_escaped): Now escapes "From " lines * g10.c: New option --escape-from-lines * trustdb.c (sort_tsl_list): New (list_trust_path): Now prints sorted list. (enum_cert_paths): Likewise. (enum_cert_paths_print): New. (print_paths): New printing format. * pkclist.c (add_ownertrust): New arg quit. (edit_ownertrust): New quit selection and does not query the recipients ownertrust anymore. (add_ownertrust): Print the ceritficate path. Mon Dec 14 21:18:49 CET 1998 Werner Koch * parse-packet.c (parse_signature): Now checks for critical bit (parse_sig_subpkt): Splitted. (parse_one_sig_subpkt): New. * sig-check.c (do_check): handle critical bit. Sun Dec 13 14:10:56 CET 1998 Werner Koch * pcklist.c (select_algo_from_prefs): Preferences should now work (lost the != ? ) Thu Dec 10 20:15:36 CET 1998 Werner Koch * ringedit.c (gdbm_store): Fix for inserts * g10.c (main): New option --export-all * export.c (export_pubkeys): New arg. (do_export): Now may skip old keys. * status.c: Minor patches for Sun's cc * keygen.c (ask_algo): Disabled v3 ElGamal choice, rearranged the numbers. Add a warning question when a sign+encrypt key is selected. * g10.c (do_not_use_RSA): Removed. * misc.c (print_pubkey_algo_note): New as replacement for the do_not_use_RSA() and chnaged all callers. (print_cipher_algo_note): New. (print_hash_algo_note): New. * cipher.c (write_header): Add a call to print_cipher_algo_note. * seckey-cert.c (protect_secret_key): Ditto * sign.c (do_sign): Add a call to print_digest_algo_note. * getkey.c (get_long_user_id_string): New. * mainproc.c (check_sig_and_print): Changed the format of the status output. * encrypt.c (write_pubkey_enc_from_list): print used symmetric cipher. * pkclist.c (do_we_trust): Changed a message. Wed Dec 9 13:41:06 CET 1998 Werner Koch * misc.c (trap_unaligned) [ALPHA]: Only if UAC_SIGBUS is defined. * sign.c (write_dash_escaped): Add the forgotten patch by Brian Moore. * compress.c (do_uncompress): Fixed the inflating bug. Tue Dec 8 13:15:16 CET 1998 Werner Koch * trustdb.c (upd_uid_record): Now uses the newest self-signature (insert_trust_record): Now calls update with recheck set to true. (register_trusted_key): New. (verify_own_keys): Enhanced by list of trusted keys. * g10.c (main): Print a warning when a devel version is used. (main): New option --trusted-key * import.c (merge_blocks): Fixed merging of new user ids and added merging of subkeys. (append_uid): Ditto. (merge_keysig): New. (append_key): New. * getkey.c (merge_one_pk_and_selfsig): Get the expiration time from the newest self-signature. (merge_keys_and_selfsig): Ditto. * free-packet.c (cmp_secret_key): New. Fri Nov 27 21:37:41 CET 1998 Werner Koch * g10.c: New option --lock-once * tdbio.c (open_db): Add an atexit (cleanup): New. (tdbio_sync): Add locking. (tdbio_end_transaction): Ditto. (put_record_into_cache): Ditto. * ringedit.c (keyring_copy): Ditto. (cleanup): New. (add_keyblock_resource): Add an atexit. Fri Nov 27 15:30:24 CET 1998 Werner Koch * armor.c (find_header): Another fix for clearsigs. Fri Nov 27 12:39:29 CET 1998 Werner Koch * status.c (display_help): Removed. * helptext.c: New and removed the N_() from all cpr_gets. Fri Nov 20 16:54:52 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): New option --not-dash-escaped * sign.c (write_dashed_escaped): Ditto. * armor.c (find_header): Support for NotDashEscaped header. * getkey.c: print "disabled cache.." only if verbose is used. Thu Nov 19 07:17:31 1998 Werner Koch * parse-packet.c (dump_sig_subpkt): Fixed expire listing * getkey.c (merge_keys_and_selfsig): Fixed expire calculation. (merge_one_pk_and_selfsig): Ditto. * keyedit.c (menu_expire). Ditto. * keygen.c (keygen_add_key_expire): Ditto. (ask_expire_interval): New and changed all local function to use this instead. (keygen_add_key_expire): Opaque should now be a public key; changed all callers. * parse.packet.c (parse): use skip_rest to skip packets. * keyedit.c (keyedit_menu): New arg for cmdline cmds. Wed Nov 18 20:33:50 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (check_trustdb): Now rechecks all gived userids. (collect_paths): Some fixes. (upd_pref_records): Skips empty items, evaluate all items. * parse-packet.c (dump_sig_subpkt): Better listing of prefs. (skip_packet): Now knows about marker packet * g10.c: removed cmd "--edit-sig". * pubring.asc: Updated. Sat Nov 14 14:01:29 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Changed syntax of --list-trust-path * trustdb.c (list_trust_path): Replaced max_depth by opt.max_cert_depth Fri Nov 13 07:39:58 1998 Werner Koch * trustdb.c (collect_paths): Removed a warning message. (enum_trust_web): Removed. (enum_cert_paths): New. * pkclist.c (add_ownertrust): Changed to use enum_cert_paths. (edit_ownertrust): Now list ceritficates on request. (show_paths): New. Wed Nov 11 18:05:44 1998 Werner Koch * g10.c (main): New option --max-cert-depth * tdbio.h: add new fields to ver and dir record. * tdbio.c: read/write/dump of these fields. (tdbio_db_matches_options): New. * trustdb.c: replaced MAC_CERT_DEPTH by opt.max_cert_depth. (do_check): cache validity and changed other functions to reset the cached value. * keylist.c (list_one): Now lists the ownertrust. * mainproc.c (list_node): Ditto. Tue Nov 10 10:08:59 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (g10_exit): Now looks at the new g10_errors_seen. * mainproc.c (check_sig_and_print): Sets g10_errors_seen. * *.c : i18n many more strings. * ringedit.c (locate_keyblock_by_keyid): Add HAVE_LIBGDBM (locate_keyblock_by_fpr): Ditto. * g10.c (main): removed unsused "int errors". (main): Add new option --charset. * g10.c (main): special message for the unix newbie. Mon Nov 9 07:17:42 1998 Werner Koch * getkey.c (finish_lookup): Kludge to prefere algo 16. * trustdb.c (new_lid_table): Clear cached item. * status.c (cpr_get_utf8): New. * pkclist.c (build_pk_list): Uses this. Sun Nov 8 17:20:39 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c (check_sig_and_print): Why did I use strlen()-1 in the printf? - This truncated the TZ. Sat Nov 7 15:57:28 1998 me,,, (wk@tobold) * getkey.c (lookup): Changes to support a read_next. (get_pubkey): Fixed a memory leak. * keylist.c (list_one): Now lists all matching user IDs. Tue Nov 3 16:19:21 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (ask_user_id): Now converted to UTF-8 * g10.c (main): Kludge for pgp clearsigs and textmode. Fri Oct 30 16:40:39 1998 me,,, (wk@tobold) * signal.c (block_all_signals): New. (unblock_all_signals): New * tdbio.c (tdbio_end_transaction): Now blocks all signals. * trustdb.c (new_lid_table): Changed the representation of the former local_lid_info stuff. * trustdb.c (update_trust_record): Reorganized the whole thing. * sig-check.c (check_key_signature): Now handles class 0x28 Wed Oct 28 18:56:33 1998 me,,, (wk@tobold) * export.c (do_export): Takes care of the exportable sig flag. Tue Oct 27 14:53:04 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (update_trust_record): New "fast" parameter. Sun Oct 25 19:32:05 1998 Werner Koch (wk@isil.d.shuttle.de) * openfile.c (copy_options_File): New. * ringedit.c (add_keyblock_resource): Creates options file * tdbio.c (tdbio_set_dbname): Ditto. Sat Oct 24 14:10:53 1998 brian moore * mainproc.c (proc_pubkey_enc): Don't release the DEK (do_proc_packets): Ditto. Fri Oct 23 06:49:38 1998 me,,, (wk@tobold) * keyedit.c (keyedit_menu): Comments are now allowed * trustdb.c: Rewrote large parts. Thu Oct 22 15:56:45 1998 Michael Roth (mroth@nessie.de) * encode.c: (encode_simple): Only the plain filename without a given directory is stored in generated packets. (encode_crypt): Ditto. * sign.c: (sign_file) Ditto. Thu Oct 22 10:53:41 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (update_trust_record): Add new optional arg. * import.c (import_keys): Add statistics output * trustdb.c (update_trustdb): Ditto. (insert_trustdb): Ditto. * tdbio.c (tdbio_begin_transaction): New. (tdbio_end_transaction): New. (tdbio_cancel_transaction): New. * g10.c (main): New option --quit. * trustdb.c (check_hint_sig): No tests for user-id w/o sig. This caused an assert while checking the sigs. * trustdb.c (upd_sig_record): Splitted into several functions. * import.c (import_keys): New arg "fast". * g10.c (main): New command --fast-import. Wed Oct 21 18:19:36 1998 Michael Roth * ringedit.c (add_keyblock_resource): Directory is now created. * tdbio.c (tdbio_set_dbname): New info message. Wed Oct 21 11:52:04 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (update_trustdb): released keyblock in loop. * keylist.c (list_block): New. (list_all): Changed to use list_block. * trustdb.c: Completed support for GDBM * sign.c (only_old_style): Changed the way force_v3 is handled (sign_file): Ditto. (clearsign_file): Ditto. * keygen.c (has_invalid_email_chars): Splitted into mailbox and host part. * keylist.c (list_one): Add a merge_keys_and_selfsig. * mainproc.c (proc_tree): Ditto. Sun Oct 18 11:49:03 1998 Werner Koch (wk@isil.d.shuttle.de) * sign.c (only_old_style): Add option force_v3_sigs (sign_file): Fixed a bug in sig->version (clearsign_file): Ditto. * parse-packet.c (dump_sig_subpkt): New * keyedit.c (menu_expire): New. * free-packet.c (cmp_signatures): New Sat Oct 17 10:22:39 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c: changed output line length from 72 to 64. * keyedit.c (fix_keyblock): New. Fri Oct 16 10:24:47 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c: Rewrote most. * tdbio.c: Add cache and generalized hash tables. * options.h (ENABLE_COMMENT_PACKETS): New but undef'ed. * encode.c, sign.c, keygen.c: Disabled comment packets. * export.c (do_export): Comment packets are never exported, except for those in the secret keyring. * g10.c (main): Removed option do-no-export-rsa; should be be replaced by a secpial tool. * export.c (do_export): Removed the code for the above option. * armor.c (find_header): Support for new only_keyblocks. * import.c (import_keys): Only looks for keyblock armors. * packet.h: replaced valid_days by expiredate and changed all users. * build-packet.c (do_public_key): calculates valid-days (do_secret_key): Ditto. * parse-packet.c (parse_key): expiredate is calucated from the valid_period in v3 packets. * keyid.c (do_fingerprint_md): calculates valid_dates. * keygen.c (add_key_expire): fixed key expiration time for v4 packets. * armor.c (find_header): A LF in the first 28 bytes was skipped for non-armored data. Thu Oct 8 11:35:51 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (is_armored): Add test on old comment packets. * tdbio.c (tdbio_search_dir_bypk): fixed memory leak. * getkey.c: Changed the caching algorithms. Wed Oct 7 19:33:28 1998 Werner Koch (wk@isil.d.shuttle.de) * kbnodes.c (unused_nodes): New. Wed Oct 7 11:15:36 1998 Werner Koch (wk@isil.d.shuttle.de) * keyedit.c (sign_uids): Fixed a problem with SK which could caused a save of an unprotected key. (menu_adduid): Ditto. * keyedit.c (keyedit_menu): Prefs are now correctly listed for new user ids. * trustdb.c (update_trust_record): New. (insert_trust_record): Now makes use of update_trust_record. Tue Oct 6 16:18:03 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (read_record): replaces most of the tdbio_read_records. (write_record): Ditto. Sat Oct 3 11:01:21 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (ask_alogo): enable ElGamal enc-only only for addmode. Wed Sep 30 10:15:33 1998 Werner Koch (wk@isil.d.shuttle.de) * import.c (import_one): Fixed update of wrong keyblock. Tue Sep 29 08:32:08 1998 me,,, (wk@tobold) * mainproc.c (proc_plaintext): Display note for special filename. * plaintext.c (handle_plaintext): Suppress output of special file. Mon Sep 28 12:57:12 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (verify_own_keys): Add warning if a key is not protected. * passphrase (hash_passphrase): Fixed iterated+salted mode and setup for keysizes > hashsize. * g10.c (main): New options: --s2k-{cipher,digest,mode}. Fri Sep 25 09:34:23 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c: Chnaged some help texts. Tue Sep 22 19:34:39 1998 Werner Koch (wk@isil.d.shuttle.de) * passphrase.c (read_passphrase_from_fd): fixed bug for long passphrases. Mon Sep 21 11:28:05 1998 Werner Koch (wk@(none)) * getkey.c (lookup): Add code to use the sub key if the primary one does not match the usage. * armor.c (armor_filter): New error message: no valid data found. (radix64_read): Changes to support multiple messages. (i18n.h): New. * mainproc.c (add_onepass_sig): bug fix. Mon Sep 21 08:03:16 1998 Werner Koch (wk@isil.d.shuttle.de) * pkclist.c (do_we_trust): Add keyid to most messages. * passphrase.c (read_passphrase_from_fd): New. (have_static_passphrase): New (get_passphrase_fd): Removed. (set_passphrase_fd): Removed. * g10.c (main): passphrase is now read here. * keyedit.c (keyedit_menu): "help" texts should now translate fine. Mon Sep 21 06:40:02 1998 Werner Koch (wk@isil.d.shuttle.de) * encode.c (encode_simple): Now disables compression when --rfc1991 is used. (encode_crypt): Ditto. Fri Sep 18 16:50:32 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (merge_key_and_selfsig): New. Fri Sep 18 10:20:11 1998 Werner Koch (wk@isil.d.shuttle.de) * pkclist.c (select_algo_from_prefs): Removed 3DES kludge. * seskey.c (make_session_key): Fixed SERIOUS bug introduced by adding the weak key detection code. * sign.c (sign_file): Changed aremor header in certain cases. Tue Sep 15 17:52:55 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c (check_sig_and_print): Replaced ascime by asctimestamp. Mon Sep 14 11:40:52 1998 Werner Koch (wk@isil.d.shuttle.de) * seskey.c (make_session_key): Now detects weak keys. * trustdb (clear_trust_checked_flag): New. * plaintext.c (handle_plaintext): Does no anymore suppress CR from cleartext signed messages. Sun Sep 13 12:54:29 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (insert_trust_record): Fixed a stupid bug in the free liunked list loops. Sat Sep 12 15:49:16 1998 Werner Koch (wk@isil.d.shuttle.de) * status.c (remove_shmid): New. (init_shm_comprocess): Now sets permission to the real uid. Wed Sep 9 11:15:03 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h (PKT_pubkey_enc): New flah throw_keyid, and add logic to implement it. * g10.c (main): New Option --throw-keyid * getkey.c (enum_secret_keys): Add new ar and changed all callers. Tue Sep 8 20:04:09 1998 Werner Koch (wk@isil.d.shuttle.de) * delkey.c (delete_key): Moved from keyedit.c. Mon Sep 7 16:37:52 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (calc_length_header): New arg new_ctb to correctly calculate the length of new style packets. * armor.c (is_armored): Checks for symkey_enc packets. * pkclist.c (select_algo_from_prefs): 3DEs substitute is now CAST5. Tue Aug 11 17:54:50 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (do_secret_key): Fixed handling of old keys. * getkey.c (compare_name): Fixed exact and email matching * openfile.c (open_outfile): Changed arguments and all callers. Tue Aug 11 09:14:35 1998 Werner Koch (wk@isil.d.shuttle.de) * encode.c (encode_simple): Applied option set-filename and comment. (encode_crypt): Ditto. * sign.c (sign_file): Ditto. * armor.c (armor_filter): Applied option comment. * encode.c (encode_crypt): Moved init_packet to the begin. (encode_simple): add an init_packet(). * comment (write_comment): Now enforces a hash sign as the 1st byte. * import.c (import_one): Add explanation for "no user ids". * compress.c (do_uncompress): Applied Brian Warner's patch to support zlib 1.1.3 etc. * trustdb.c (check_trust): Fixed a problem after inserting new keys. * getkey (lookup): do not return the primary key if usage is given (lookup_sk): Ditto and take usage into account. * status.c (cpr_get_answer_is_yes): add display_help. Mon Aug 10 10:11:28 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (lookup_sk): Now always returns the primary if arg primary is true. (lookup): Likewise. (get_pubkey_byname): Now returns the primary key (get_seckey_byname): Ditto. Mon Aug 10 08:34:03 1998 Werner Koch (wk@isil.d.shuttle.de) * keyid.c (pubkey_letter): ELG_E is now a small g. Sat Aug 8 17:26:12 1998 Werner Koch (wk@isil.d.shuttle.de) * openfile (overwrite_filep): Changed semantics and all callers. Sat Aug 8 12:17:07 1998 Werner Koch (wk@isil.d.shuttle.de) * status.c (display_help): New. Thu Aug 6 16:30:41 1998 Werner Koch,mobil,,, (wk@tobold) * seskey.c (encode_session_key): Now uses get_random_bits(). Thu Aug 6 07:34:56 1998 Werner Koch,mobil,,, (wk@tobold) * ringedit.c (keyring_copy): No more backupfiles for secret keyrings and add additional warning in case of a failed secret keyring operation. Wed Aug 5 11:54:37 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (check_opts): Moved to main. Changed def_cipher_algo semantics and chnaged all users. * pubkey-enc.c (get_sssion_key): New informational output about preferences. * parse-packet.c (parse_symkeyenc): Fixed salted+iterated S2K (parse_key): Ditto. * build-packet.c (do_secret_key): Ditto. (do_symkey_enc): Ditto. Tue Aug 4 08:59:10 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (enum_secret_keys): Now returns only primary keys. * getkey (lookup): Now sets the new namehash field. * parse-packet.c (parse_sig_subpkt2): New. * sign.c (sign_file): one-pass sigs are now emiited reverse. Preference data is considered when selecting the compress algo. Wed Jul 29 12:53:03 1998 Werner Koch (wk@isil.d.shuttle.de) * free-packet.c (copy_signature): New. * keygen.c (generate_subkeypair): rewritten * g10.c (aKeyadd): Removed option --add-key Mon Jul 27 10:37:28 1998 Werner Koch (wk@isil.d.shuttle.de) * seckey-cert.c (do_check): Additional check on cipher blocksize. (protect_secret_key): Ditto. * encr-data.c: Support for other blocksizes. * cipher.c (write_header): Ditto. Fri Jul 24 16:47:59 1998 Werner Koch (wk@isil.d.shuttle.de) * kbnode.c (insert_kbnode): Changed semantics and all callers. * keyedit.c : More or less a complete rewrite Wed Jul 22 17:10:04 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (write_sign_packet_header): New. Tue Jul 21 14:37:09 1998 Werner Koch (wk@isil.d.shuttle.de) * import.c (import_one): Now creates a trustdb record. * g10.c (main): New command --check-trustdb Mon Jul 20 11:15:07 1998 Werner Koch (wk@isil.d.shuttle.de) * genkey.c (generate_keypair): Default key is now DSA with encryption only ElGamal subkey. Thu Jul 16 10:58:33 1998 Werner Koch (wk@isil.d.shuttle.de) * keyid.c (keyid_from_fingerprint): New. * getkey.c (get_pubkey_byfprint): New. Tue Jul 14 18:09:51 1998 Werner Koch (wk@isil.d.shuttle.de) * keyid.c (fingerprint_from_pk): Add argument and changed all callers. (fingerprint_from_sk): Ditto. Tue Jul 14 10:10:03 1998 Werner Koch (wk@isil.d.shuttle.de) * plaintext.c (handle_plaintext): Now returns create error if the file could not be created or the user responded not to overwrite the file. * mainproc.c (proc_plaintext): Tries again if the file could not be created to check the signature without output. * misc.c (disable_core_dumps): New. * g10.c (main): disable coredumps for gpg * g10.c (MAINTAINER_OPTIONS): New to disable some options Mon Jul 13 16:47:54 1998 Werner Koch (wk@isil.d.shuttle.de) * plaintext.c (hash_datafiles): New arg for better support of detached sigs. Changed all callers. * mainproc.c (proc_signature_packets): Ditto. * g10.c (main): New option "compress-sigs" * sig.c (sign_file): detached signatures are not anymore compressed unless the option --compress-sigs is used. Thu Jul 9 19:54:54 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c: Fixes to allow zero length cleartext signatures Thu Jul 9 14:52:47 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (build_list): Now drops setuid. (main): Changed the way keyrings and algorithms are registered . Wed Jul 8 14:17:30 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h (PKT_public_key): Add field keyid. * parse-packet.c (parse_key): Reset the above field. * keyid.c (keyid_from_pk): Use above field as cache. * tdbio.c, tdbio.h: New * trustdb.c: Moved some functions to tdbio.c. (print_keyid): New. * pkclist.c (check_signatures_trust): New. Wed Jul 8 10:45:28 1998 Werner Koch (wk@isil.d.shuttle.de) * plaintext.c (special_md_putc): New. (handle_plaintext): add clearsig argument * mainproc.c (proc_plaintext): detection of clearsig * sign.c (write_dased_escaped): Changed clearsig format Tue Jul 7 18:56:19 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (find_header): Now makes sure that there is only one empty line for clearsigs, as this is what OP now says. Mon Jul 6 13:09:07 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): New option default-secret-key * getkey.c (get_seckey_byname): support for this option. Mon Jul 6 09:03:49 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (add_keyring): Keyrings are now added to end of the list of keyrings. The first added keyringwill be created. (add_secret_keyring): Likewise. * ringedit.c (add_keyblock_resource): Files are created here. * g10.c (aNOP): Removed * getkey.c (lookup): Add checking of usage for name lookups * packet.h (pubkey_usage): Add a field which may be used to store usage capabilities. * pkclist.c (build_pk_list): getkey now called with usage arg. * skclist.c (build_sk_list): Ditto. * sign.c (clearsign_file): Fixed "Hash:" headers Sat Jul 4 13:33:31 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (list_ownertrust): New. * g10.c (aListOwnerTrust): New. * g10.c (def_pubkey_algo): Removed. * trustdb.c (verify_private_data): Removed and also the call to it. (sign_private_data): Removed. Fri Jul 3 13:26:10 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (aEditKey): was aEditSig. Changed usage msg. * keyedit.c: Done some i18n stuff. * g10.c (do_not_use_RSA): New. * sign.c (do_sign): Add call to above function. * encode.c (write_pubkey_enc_from_list): Ditto. Thu Jul 2 21:01:25 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c: Now is able sto store data of unknown algorithms. * free-packet.c: Support for this. * build-packet.c: Can write data of packet with unknown algos. Thu Jul 2 11:46:36 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (parse): fixed 4 byte length header Wed Jul 1 12:36:55 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h (new_ctb): New field for some packets * build-packet.c (build_packet): Support for new_ctb * parse-packet.c (parse): Ditto. Mon Jun 29 12:54:45 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h: changed all "_cert" to "_key", "subcert" to "subkey". * free-packet.c (free_packet): Removed memory leak for subkeys. Sun Jun 28 18:32:27 1998 Werner Koch (wk@isil.d.shuttle.de) * import.c (import_keys): Renamed from import_pubkeys. (import_secret_one): New. * g10.c (aExportSecret): New. * export.c (export_seckeys): New. * parse-packet.c (parse_certificate): Cleaned up. (parse_packet): Trust packets are now considered as unknown. (parse_pubkey_warning): New. Fri Jun 26 10:37:35 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (has_invalid_email_chars): New. Wed Jun 24 16:40:22 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (armor_filter): Now creates valid onepass_sig packets with all detected hash algorithms. * mainproc.c (proc_plaintext): Now uses the hash algos as specified in the onepass_sig packets (if there are any) Mon Jun 22 11:54:08 1998 Werner Koch (wk@isil.d.shuttle.de) * plaintext.c (handle_plaintext): add arg to disable outout * mainproc.c (proc_plaintext): disable output when in sigs_only mode. Thu Jun 18 13:17:27 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c: Removed all rsa packet stuff, chnaged defaults for key generation. Sun Jun 14 21:28:31 1998 Werner Koch (wk@isil.d.shuttle.de) * misc.c (checksum_u16): Fixed a stupid bug which caused a wrong checksum calculation for the secret key protection and add a backward compatibility option. * g10.c (main): Add option --emulate-checksum-bug. Thu Jun 11 13:26:44 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h: Major changes to the structure of public key material which is now stored in an array and not anaymore in a union of algorithm specific structures. These is needed to make the system more extendable and makes a lot of stuff much simpler. Changed all over the system. * dsa.c, rsa.c, elg.c: Removed. Wed Jun 10 07:22:02 1998 Werner Koch,mobil,,, (wk@tobold) * g10.c ("load-extension"): New option. Mon Jun 8 22:23:37 1998 Werner Koch (wk@isil.d.shuttle.de) * seckey-cert.c (do_check): Removed cipher constants (protect_secret_key): Ditto. Fri May 29 10:00:28 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (query_trust_info): New. * keylist.c (list_one): Add output of trust info * mainproc (list_node): ditto. * g10.c (main): full trustdb init if -with-colons and any of the key list modes. Thu May 28 10:34:42 1998 Werner Koch (wk@isil.d.shuttle.de) * status.c (STATUS_RSA_OR_IDEA): New. * sig-check.c (check_signature): Output special status message. * pubkey-enc.c (get_session_key): Ditto. * mainproc.c (check_sig_and_print): Changed format of output. * passpharse.c (passphrase_to_dek): Likewise. Wed May 27 13:46:48 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (aListSecretKeys): New option --list-secret-keys * keylist.c (std_key_list): Renamed to public_key_list. (secret_key_list): New (list_one, list_all): Add support for secret keys. * getkey.c (get_secret_keyring): New. * mainproc.c (list_node): Add option --with-colons for secret keys * sig-check.c (check_key_signature): detection of selfsigs * mainproc.c (list_node): fixed listing. * g10.c (aListSecretKeys): New option --always-trust * pkclist.c (do_we_trust): Override per option added * status.c (write_status_text): Add a prefix to every output line. Wed May 27 07:49:21 1998 Werner Koch (wk@isil.d.shuttle.de) * g10 (--compress-keys): New. * options.h (compress_keys): New. * export.c (export_pubkeys): Only compresses with the new option. Tue May 26 11:24:33 1998 Werner Koch (wk@isil.d.shuttle.de) * passphrase.c (get_last_passphrase): New (set_next_passphrase): New. (passphrase_to_dek): add support for the above functions. * keyedit.c (make_keysig_packet): Add sigclass 0x18, changed all callers due to a new argument. * keygen.c (write_keybinding): New (generate_subkeypair): Add functionality (ask_algo, ask_keysize, ask_valid_days): Broke out of generate_keypair (ask_user_id, ask_passphrase): Ditto. Thu May 21 11:26:13 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c,gpgd.c (main): Does now return an int, so that egcs does not complain. * armor.c (fake_packet): Removed erro message and add a noticed that this part should be fixed. * sign.c (sign_file): Compression now comes in front of encryption. * encode.c (encode_simple): Ditto. (encode_crypt): Ditto. Tue May 19 16:18:19 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (fake_packet): Changed assertion to log_error Sat May 16 16:02:06 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (build_packet): Add SUBKEY packets. Fri May 15 17:57:23 1998 Werner Koch (wk@isil.d.shuttle.de) * sign.c (hash_for): New and used in all places here. * main.h (DEFAULT_): new macros. * g10.c (opt.def_digest_algo): Now set to 0 * compress.c (init_compress): Add support for algo 1 * options.h (def_compress_algo): New * g10.c (main): New option --compress-algo Fri May 15 13:23:59 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (print_mds): New feature to print only one hash, chnaged formatting. Thu May 14 15:36:24 1998 Werner Koch (wk@isil.d.shuttle.de) * misc.c (trap_unaligned) [__alpha__]: New * g10.c (trap_unaligned): Add call to this to track down SIGBUS on Alphas (to avoid the slow emulation code). Wed May 13 11:48:27 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (do_signature): Support for v4 pakets. * keyedit.c (make_keysig_packet): Ditto. * build-packet.c (build_sig_subpkt_from_sig): New. (build_sig_subpkt): New. * elg.c (g10_elg_sign): removed keyid_from_skc. * dsa.c (g10_dsa_sign): Ditto. * rsa.c (g10_rsa_sign): Ditto. * keyedit.c (make_keysig_packet): Add call to keyid_from_skc * sign.c (clearsign_file): Support for v4 signatures. (sign_file): Ditto. Wed May 6 09:31:24 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (do_parse): add support for 5 byte length leader. (parse_subpkt): Ditto. * build-packet.c (write_new_header): Ditto. * packet.h (SIGSUBPKT_): New constants. * parse-packet.c (parse_sig_subpkt): Changed name, made global, and arg to return packet length, chnaged all callers Tue May 5 22:11:59 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (gen_dsa): New. * build_packet.c (do_secret_cert): Support for DSA Mon May 4 19:01:25 1998 Werner Koch (wk@isil.d.shuttle.de) * compress.c: doubled buffer sizes * parse-packet.c (do_plaintext): now uses iobuf_read/write. Mon May 4 09:35:53 1998 Werner Koch (wk@isil.d.shuttle.de) * seskey.c (encode_md_value): Add optional argument hash_algo, changed all callers. * passphrase.c (make_dek_from_passphrase): Removed * (get_passhrase_hash): Changed name to passphrase_to_dek, add arg, changed all callers. * all: Introduced the new ELG identifier and added support for the encryption only one (which is okay to use by GNUPG for signatures). Sun May 3 17:50:26 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h (PKT_OLD_COMMENT): New name for type 16. * parse-packet.c (parse_comment): Now uses type 61 Fri May 1 12:44:39 1998 Werner Koch,mobil,,, (wk@tobold) * packet.h (count): Chnaged s2k count from byte to u32. * seckey-cert.c (do_check): Changed s2k algo 3 to 4, changed reading of count. * build-packet.c (do_secret_cert): ditto. * parse-packet.c (parse_certificate): ditto. * parse-packet.c (parse_symkeyenc): New. * build-packet.c (do_symkey_enc): New. Thu Apr 30 16:33:34 1998 Werner Koch (wk@isil.d.shuttle.de) * sign.c (clearsign_file): Fixed "Hash: " armor line. Tue Apr 28 14:27:42 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (parse_subpkt): Some new types. Mon Apr 27 12:53:59 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Add option --skip-verify. * mainproc.c (check_sig_and_print): Ditto. * g10.c (print_mds): Add output for Tiger. * sign.c (sign_file): Now uses partial length headers if used in canonical textmode (kludge to fix a bug). * parse-packet.c (parse_certificate): Changed BLOWFISH id. * pubkey-enc.c (get_session_key): Ditto. * seskey.c (make_session_key): Ditto. * seckey-cert.c (protect_secret_key,do_check): Add BLOWFISH160. Fri Apr 24 17:38:48 1998 Werner Koch,mobil,,, (wk@tobold) * sig-check.c (check_key_signature): Add sig-class 0x14..0x17 * keyedit.c (sign-key): Some changes to start with support of the above new sig-classes. Wed Apr 22 09:01:57 1998 Werner Koch,mobil,,, (wk@tobold) * getkey.c (compare_name): add email matching Tue Apr 21 16:17:12 1998 Werner Koch,mobil,,, (wk@tobold) * armor.c (armor_filter): fixed missing last LF before CSUM. Thu Apr 9 11:35:22 1998 Werner Koch (wk@isil.d.shuttle.de) * seckey-cert.c (do_check): New; combines all the check functions into one. * sign.c: removed all key management functions * keyedit.c: New. Thu Apr 9 09:49:36 1998 Werner Koch (wk@isil.d.shuttle.de) * import.c (chk_self_sigs): Changed an error message. Wed Apr 8 16:19:39 1998 Werner Koch (wk@isil.d.shuttle.de) * packet.h: packet structs now uses structs from the pubkey, removed all copy operations from packet to pubkey structs. Wed Apr 8 13:40:33 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (verify_own_certs): Fixed "public key not found". * getkey.c (key_byname): New, combines public and secret key search. * pkclist.c (build_pkc_list): Add new arg usage, changed all callers. * skclist.c (build_skc_list): Likewise. * ringedit.c (find_keyblock, keyring_search2): Removed. Wed Apr 8 09:47:21 1998 Werner Koch (wk@isil.d.shuttle.de) * sig-check.c (do_check): Applied small fix from Ulf Möller. Tue Apr 7 19:28:07 1998 Werner Koch (wk@isil.d.shuttle.de) * cipher.c, encr-data.c, seckey-cert.c: Now uses cipher_xxxx functions instead of blowfish_xxx or cast_xxx Tue Apr 7 11:04:02 1998 Werner Koch (wk@isil.d.shuttle.de) * Makefile.am (g10maint.o): Changed the way it is created. Mon Apr 6 11:17:08 1998 Werner Koch (wk@isil.d.shuttle.de) * misc.c: New. * keygen.c (checksum,checksum_u16,checksum_mpi): Moved to misc.c * seckey-cert.c: Kludge for wrong ELG checksum implementation. Sat Apr 4 20:07:01 1998 Werner Koch (wk@isil.d.shuttle.de) * cipher.c (cipher_filter): Support for CAST5 * encr-data.c (decode_filter): Ditto. (decrypt_data): Ditto. * seskey.c (make_session_key): Ditto. * seckey-cert.c (check_elg, check_dsa): Ditto, (protect_secret_key): Ditto. * pubkey-enc.c (get_session_key): Ditto. * passphrase.c (hash_passphrase): Ditto. Thu Apr 2 20:22:35 1998 Werner Koch (wk@isil.d.shuttle.de) * gpgd.c: New Thu Apr 2 10:38:16 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (generate_keypair): Add valid_days stuff. * trustdb.c (check_trust): Add check for valid_days. Wed Apr 1 16:15:58 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (generate_keypair): Addional question whether the selected large keysize is really needed. Wed Apr 1 15:56:33 1998 Werner Koch (wk@isil.d.shuttle.de) * seckey-cert.c (protect_secret_key): merged protect_xxx to here. Wed Apr 1 10:34:46 1998 Werner Koch (wk@isil.d.shuttle.de) * Makefile.am (g10maint.c): Changed creation rule, so that it works on FreeBSD (missing CFLAGS). * parse-packet.c (parse_subkey): Removed. Thu Mar 19 15:22:36 1998 Werner Koch (wk@isil.d.shuttle.de) * ringedit.c (keyring_enum): Fixed problem with reading too many packets. Add support to read secret keyrings. * getkey.c (scan_keyring): Removed (lookup): New to replace scan_keyring. (scan_secret_keyring): Removed. (lookup_skc): New. Wed Mar 18 11:47:34 1998 Werner Koch (wk@isil.d.shuttle.de) * ringedit.c (enum_keyblocks): New read mode 11. * keyid.c (elg_fingerprint_md): New and changed all other functions to call this if the packet version is 4 or above. Tue Mar 17 20:46:16 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (parse_certificate): Add listing support for subkeys. Tue Mar 17 20:32:22 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (is_armored): Allow marker packet. Thu Mar 12 13:36:49 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (check_trust): Checks timestamp of pubkey. * sig-check. (do_check): Compares timestamps. Tue Mar 10 17:01:56 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Add call to init_signals. * signal.c: New. Mon Mar 9 12:43:42 1998 Werner Koch (wk@isil.d.shuttle.de) * dsa.c: New * packet.h, free-packet.c, parse-packet.c : Add support for DSA * sig-check.c, getkey.c, keyid.c, ringedit.c: Ditto. * seckey-cert.c: Ditto. * packet.h : Moved .digest_algo of signature packets to outer structure. Changed all references Sun Mar 8 13:06:42 1998 Werner Koch (wk@isil.d.shuttle.de) * openfile.c : Support for stdout filename "-". * mainproc.c (check_sig_and_print): Enhanced status output: * status.c (write_status_text): New. Fri Mar 6 16:10:54 1998 Werner Koch (wk@isil.d.shuttle.de) * kbnode.c (clone_kbnode): Fixed private_flag. * mainproc.c (list_node): Output of string "Revoked" as user-id. Fri Mar 6 14:26:39 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Add userids to "-kv" and cleaned up this stuff. Fri Mar 6 12:45:58 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Changed semantics of the list-... commands and added a new one. Removed option "-d" * decrypt.c: New. * trustdb.c (init_trustdb): Autocreate directory only if it ends in "/.gnupg". Thu Mar 5 12:12:11 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c (do_proc_packets): New. Common part of proc_packet. (proc_signature_packets): special version to handle signature data. * verify.c: New. * g10.c (aVerify): New. * plaintext.c (hash_datafiles): New. * compress.c (handle_compressed): Add callback arg, changed caller. Thu Mar 5 10:20:06 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c: Is nom the common source for gpg and gpgm * g10maint.c: Removed * Makefile.am: Add rule to build g10maint.c Thu Mar 5 08:43:59 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Changed the way clear text sigs are faked. Wed Mar 4 19:47:37 1998 Werner Koch (wk@isil.d.shuttle.de) * g10maint.c (aMuttKeyList): New * keylist.c: New. Wed Mar 4 17:20:33 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (get_pubkey_byname): Kludge to allow 0x prefix. Tue Mar 3 13:46:55 1998 Werner Koch (wk@isil.d.shuttle.de) * g10maint.c (main): New option --gen-random. Tue Mar 3 09:50:08 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (aDeleteSecretKey): New. (aEditSig): Add option "--edit-key" as synonym for "--edit-sig". (aDeleteSecretKey): New. * getkey.c (seckey_available): New. * sign.c (delete_key): Enhanced to delete secret keys, changed all callers. Mon Mar 2 21:23:48 1998 Werner Koch (wk@isil.d.shuttle.de) * pkc_list.c (build_pkc_list): Add interactive input of user ID. Mon Mar 2 20:54:05 1998 Werner Koch (wk@isil.d.shuttle.de) * pkclist.c (do_we_trust_pre): New. (add_ownertrust): Add message. * trustdb.c (enum_trust_web): Quick fix. Mon Mar 2 13:50:53 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): New action aDeleteKey * sign.c (delete_key): New. Sun Mar 1 16:38:58 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (do_check): No returns TRUST_UNDEFINED instead of eof error. Fri Feb 27 18:14:03 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (find_header): Removed trailing CR on headers. Fri Feb 27 18:02:48 1998 Werner Koch (wk@isil.d.shuttle.de) * ringedit.c (keyring_search) [MINGW32]: Open and close file here because rename does not work on open files. Chnaged callers. Fri Feb 27 16:43:11 1998 Werner Koch (wk@isil.d.shuttle.de) * sig-check.c (do_check): Add an md_enable. * mainproc.c (do_check_sig): Use md_open in case of detached sig (proc_tree): Take detached sigs into account. Fri Feb 27 15:22:46 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): Make use of GNUPGHOME envvar. * g10main.c (main): Ditto. Wed Feb 25 11:40:04 1998 Werner Koch (wk@isil.d.shuttle.de) * plaintext.c (ask_for_detached_datafile): add opt.verbose to info output. * openfile.c (open_sigfile): Try also name ending in ".asc" Wed Feb 25 08:41:00 1998 Werner Koch (wk@isil.d.shuttle.de) * keygen.c (generate_keypair): Fixed memory overflow. Tue Feb 24 15:51:55 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (parse_certificate): Support for S2K. * build-packet.c (do_secret_cert): Ditto. * keygen.c (gen_elg): Ditto. * seckey-cert.c (check_elg): Ditto (protect_elg): Ditto. * sign.c (chnage_passphrase): Ditto. * passphrase.c (get_passphrase_hash): Support for a salt and changed all callers. (make_dek_from_passphrase): Ditto. Tue Feb 24 12:30:56 1998 Werner Koch (wk@isil.d.shuttle.de) * build-packet.c (hash_public_cert): Disabled debug output. Fri Feb 20 17:22:28 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (init_trustdb) [MINGW32]: Removed 2nd mkdir arg. (keyring_copy) [MINGW32]: Add a remove prior to the renames. Wed Feb 18 18:39:02 1998 Werner Koch (wk@isil.d.shuttle.de) * Makefile.am (OMIT_DEPENDENCIES): New. * rsa.c: Replaced log_bug by BUG. Wed Feb 18 13:35:58 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c (do_check_sig): Now uses hash_public_cert. * parse-packet.c (parse_certificate): Removed hashing. * packet.h (public_cert): Removed hash variable. * free-packet.c (copy_public_cert, free_public_cert): Likewise. * sig-check.c (check_key_signatures): Changed semantics. Wed Feb 18 12:11:28 1998 Werner Koch (wk@isil.d.shuttle.de) * trustdb.c (do_check): Add handling for revocation certificates. (build_sigrecs): Ditto. (check_sigs): Ditto. Wed Feb 18 09:31:04 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (armor_filter): Add afx->hdrlines. * revoke.c (gen_revoke): Add comment line. * dearmor.c (enarmor_file): Ditto. * sig-check.c (check_key_signature): Add handling for class 0x20. * mainproc.c : Ditto. Tue Feb 17 21:24:17 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c : Add header lines "...ARMORED FILE .." * dearmor.c (enarmor_file): New. * g10maint.c (main): New option "--enarmor" Tue Feb 17 19:03:33 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c : Changed a lot, because the packets are now stored a simple linlked list and not anymore in a complicatd tree structure. Tue Feb 17 10:14:48 1998 Werner Koch (wk@isil.d.shuttle.de) * free_packet.c (cmp_public_certs): New. (cmp_user_ids): New. * kbnode.c (clone_kbnode): New. (release_kbnode): Add clone support. * ringedit.c (find_keyblock_bypkc): New. * sign.c (remove_keysigs): Self signatures are now skipped, changed arguments and all callers. * import.c : Add functionality. Tue Feb 17 09:31:40 1998 Werner Koch (wk@isil.d.shuttle.de) * options.h (homedir): New option. * g10.c, g10maint.c, getkey.c, keygen.c, trustdb.c (opt.homedir): New. * trustdb.c (init_trustdb): mkdir for hoem directory (sign_private_data): Renamed "sig" to "g10.sig" Mon Feb 16 20:02:03 1998 Werner Koch (wk@isil.d.shuttle.de) * kbnode.c (commit_kbnode): New. (delete_kbnode): removed unused first arg. Changed all Callers. * ringedit.c (keyblock_resource_name): New. (get_keyblock_handle): NULL for filename returns default resource. Mon Feb 16 19:38:48 1998 Werner Koch (wk@isil.d.shuttle.de) * sig-check.s (check_key_signature): Now uses the supplied public key to check the signature and not any more the one from the getkey.c (do_check): New. (check_signature): Most work moved to do_check. Mon Feb 16 14:48:57 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (find_header): Fixed another bug. Mon Feb 16 12:18:34 1998 Werner Koch (wk@isil.d.shuttle.de) * getkey.c (scan_keyring): Add handling of compressed keyrings. Mon Feb 16 10:44:51 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c, g10maint.c (strusage): Rewrote. (build_list): New Mon Feb 16 08:58:41 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (use_armor): New. Sat Feb 14 14:30:57 1998 Werner Koch (wk@isil.d.shuttle.de) * mainproc.c (proc_tree): Sigclass fix. Sat Feb 14 14:16:33 1998 Werner Koch (wk@isil.d.shuttle.de) * armor.c (armor_filter): Changed version and comment string. * encode.c, sign.c, keygen.c: Changed all comment packet strings. Sat Feb 14 12:39:24 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (aGenRevoke): New command. * revoke.c: New. * sign.c (make_keysig_packet): Add support for sigclass 0x20. Fri Feb 13 20:18:14 1998 Werner Koch (wk@isil.d.shuttle.de) * ringedit.c (enum_keyblocks, keyring_enum): New. Fri Feb 13 19:33:40 1998 Werner Koch (wk@isil.d.shuttle.de) * export.c: Add functionality. * keygen.c (generate_keypair): Moved the leading comment behind the key packet. * kbnode.c (walk_kbnode): Fixed. * g10.c (main): listing armored keys now work. Fri Feb 13 16:17:43 1998 Werner Koch (wk@isil.d.shuttle.de) * parse-packet.c (parse_publickey, parse_signature): Fixed calls to mpi_read used for ELG b. Fri Feb 13 15:13:23 1998 Werner Koch (wk@isil.d.shuttle.de) * g10.c (main): changed formatting of help output. Thu Feb 12 22:24:42 1998 Werner Koch (wk@frodo) * pubkey-enc.c (get_session_key): rewritten Copyright 1998,1999,2000,2001,2002,2003,2004,2005, 2006,2007,2008,2009,2010 Free Software Foundation, Inc. This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/g10/armor.c b/g10/armor.c index 2dde9fe05..19cca3fd4 100644 --- a/g10/armor.c +++ b/g10/armor.c @@ -1,1497 +1,1498 @@ /* armor.c - Armor flter * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include "gpg.h" #include "status.h" #include "iobuf.h" #include "util.h" #include "filter.h" #include "packet.h" #include "options.h" #include "main.h" #include "status.h" #include "i18n.h" #define MAX_LINELEN 20000 #define CRCINIT 0xB704CE #define CRCPOLY 0X864CFB #define CRCUPDATE(a,c) do { \ a = ((a) << 8) ^ crc_table[((a)&0xff >> 16) ^ (c)]; \ a &= 0x00ffffff; \ } while(0) static u32 crc_table[256]; static byte bintoasc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static byte asctobin[256]; /* runtime initialized */ static int is_initialized; typedef enum { fhdrHASArmor = 0, fhdrNOArmor, fhdrINIT, fhdrINITCont, fhdrINITSkip, fhdrCHECKBegin, fhdrWAITHeader, fhdrWAITClearsig, fhdrSKIPHeader, fhdrCLEARSIG, fhdrREADClearsig, fhdrNullClearsig, fhdrEMPTYClearsig, fhdrCHECKClearsig, fhdrCHECKClearsig2, fhdrCHECKDashEscaped, fhdrCHECKDashEscaped2, fhdrCHECKDashEscaped3, fhdrREADClearsigNext, fhdrENDClearsig, fhdrENDClearsigHelp, fhdrTESTSpaces, fhdrCLEARSIGSimple, fhdrCLEARSIGSimpleNext, fhdrTEXT, fhdrTEXTSimple, fhdrERROR, fhdrERRORShow, fhdrEOF } fhdr_state_t; /* if we encounter this armor string with this index, go * into a mode which fakes packets and wait for the next armor */ #define BEGIN_SIGNATURE 2 #define BEGIN_SIGNED_MSG_IDX 3 static char *head_strings[] = { "BEGIN PGP MESSAGE", "BEGIN PGP PUBLIC KEY BLOCK", "BEGIN PGP SIGNATURE", "BEGIN PGP SIGNED MESSAGE", "BEGIN PGP ARMORED FILE", /* gnupg extension */ "BEGIN PGP PRIVATE KEY BLOCK", "BEGIN PGP SECRET KEY BLOCK", /* only used by pgp2 */ NULL }; static char *tail_strings[] = { "END PGP MESSAGE", "END PGP PUBLIC KEY BLOCK", "END PGP SIGNATURE", "END dummy", "END PGP ARMORED FILE", "END PGP PRIVATE KEY BLOCK", "END PGP SECRET KEY BLOCK", NULL }; static int armor_filter ( void *opaque, int control, iobuf_t chain, byte *buf, size_t *ret_len); /* Create a new context for armor filters. */ armor_filter_context_t * new_armor_context (void) { armor_filter_context_t *afx; afx = xcalloc (1, sizeof *afx); afx->refcount = 1; return afx; } /* Release an armor filter context. Passing NULL is explicitly allowed and a no-op. */ void release_armor_context (armor_filter_context_t *afx) { if (!afx) return; assert (afx->refcount); if ( --afx->refcount ) return; xfree (afx); } /* Push the armor filter onto the iobuf stream IOBUF. */ int push_armor_filter (armor_filter_context_t *afx, iobuf_t iobuf) { int rc; afx->refcount++; rc = iobuf_push_filter (iobuf, armor_filter, afx); if (rc) afx->refcount--; return rc; } static void initialize(void) { int i, j; u32 t; byte *s; /* init the crc lookup table */ crc_table[0] = 0; for(i=j=0; j < 128; j++ ) { t = crc_table[j]; if( t & 0x00800000 ) { t <<= 1; crc_table[i++] = t ^ CRCPOLY; crc_table[i++] = t; } else { t <<= 1; crc_table[i++] = t; crc_table[i++] = t ^ CRCPOLY; } } /* build the helptable for radix64 to bin conversion */ for(i=0; i < 256; i++ ) asctobin[i] = 255; /* used to detect invalid characters */ for(s=bintoasc,i=0; *s; s++,i++ ) asctobin[*s] = i; is_initialized=1; } /**************** * Check whether this is an armored file or not See also * parse-packet.c for details on this code For unknown historic * reasons we use a string here but only the first byte will be used. * Returns: True if it seems to be armored */ static int is_armored( const byte *buf ) { int ctb, pkttype; ctb = *buf; if( !(ctb & 0x80) ) return 1; /* invalid packet: assume it is armored */ pkttype = ctb & 0x40 ? (ctb & 0x3f) : ((ctb>>2)&0xf); switch( pkttype ) { case PKT_MARKER: case PKT_SYMKEY_ENC: case PKT_ONEPASS_SIG: case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_PUBKEY_ENC: case PKT_SIGNATURE: case PKT_COMMENT: case PKT_OLD_COMMENT: case PKT_PLAINTEXT: case PKT_COMPRESSED: case PKT_ENCRYPTED: return 0; /* seems to be a regular packet: not armored */ } return 1; } /**************** * Try to check whether the iobuf is armored * Returns true if this may be the case; the caller should use the * filter to do further processing. */ int use_armor_filter( IOBUF a ) { byte buf[1]; int n; /* fixme: there might be a problem with iobuf_peek */ n = iobuf_peek(a, buf, 1 ); if( n == -1 ) return 0; /* EOF, doesn't matter whether armored or not */ if( !n ) return 1; /* can't check it: try armored */ return is_armored(buf); } static void invalid_armor(void) { write_status(STATUS_BADARMOR); g10_exit(1); /* stop here */ } /**************** * check whether the armor header is valid on a signed message. * this is for security reasons: the header lines are not included in the * hash and by using some creative formatting rules, Mallory could fake * any text at the beginning of a document; assuming it is read with * a simple viewer. We only allow the Hash Header. */ static int parse_hash_header( const char *line ) { const char *s, *s2; unsigned found = 0; if( strlen(line) < 6 || strlen(line) > 60 ) return 0; /* too short or too long */ if( memcmp( line, "Hash:", 5 ) ) return 0; /* invalid header */ s = line+5; for(s=line+5;;s=s2) { for(; *s && (*s==' ' || *s == '\t'); s++ ) ; if( !*s ) break; for(s2=s+1; *s2 && *s2!=' ' && *s2 != '\t' && *s2 != ','; s2++ ) ; if( !strncmp( s, "RIPEMD160", s2-s ) ) found |= 1; else if( !strncmp( s, "SHA1", s2-s ) ) found |= 2; else if( !strncmp( s, "MD5", s2-s ) ) found |= 4; else if( !strncmp( s, "SHA224", s2-s ) ) found |= 8; else if( !strncmp( s, "SHA256", s2-s ) ) found |= 16; else if( !strncmp( s, "SHA384", s2-s ) ) found |= 32; else if( !strncmp( s, "SHA512", s2-s ) ) found |= 64; else return 0; for(; *s2 && (*s2==' ' || *s2 == '\t'); s2++ ) ; if( *s2 && *s2 != ',' ) return 0; if( *s2 ) s2++; } return found; } /* Returns true if this is a valid armor tag as per RFC-2440bis-21. */ static int is_armor_tag(const char *line) { if(strncmp(line,"Version",7)==0 || strncmp(line,"Comment",7)==0 || strncmp(line,"MessageID",9)==0 || strncmp(line,"Hash",4)==0 || strncmp(line,"Charset",7)==0) return 1; return 0; } /**************** * Check whether this is a armor line. * returns: -1 if it is not a armor header or the index number of the * armor header. */ static int is_armor_header( byte *line, unsigned len ) { const char *s; byte *save_p, *p; int save_c; int i; if( len < 15 ) return -1; /* too short */ if( memcmp( line, "-----", 5 ) ) return -1; /* no */ p = strstr( line+5, "-----"); if( !p ) return -1; save_p = p; p += 5; /* Some Windows environments seem to add whitespace to the end of the line, so we strip it here. This becomes strict if --rfc2440 is set since 2440 reads "The header lines, therefore, MUST start at the beginning of a line, and MUST NOT have text following them on the same line." It is unclear whether "text" refers to all text or just non-whitespace text. 4880 clarified this was only non-whitespace text. */ if(RFC2440) { if( *p == '\r' ) p++; if( *p == '\n' ) p++; } else while(*p==' ' || *p=='\r' || *p=='\n' || *p=='\t') p++; if( *p ) return -1; /* garbage after dashes */ save_c = *save_p; *save_p = 0; p = line+5; for(i=0; (s=head_strings[i]); i++ ) if( !strcmp(s, p) ) break; *save_p = save_c; if( !s ) return -1; /* unknown armor line */ if( opt.verbose > 1 ) log_info(_("armor: %s\n"), head_strings[i]); return i; } /**************** * Parse a header lines * Return 0: Empty line (end of header lines) * -1: invalid header line * >0: Good header line */ static int parse_header_line( armor_filter_context_t *afx, byte *line, unsigned int len ) { byte *p; int hashes=0; unsigned int len2; len2 = length_sans_trailing_ws ( line, len ); if( !len2 ) { afx->buffer_pos = len2; /* (it is not the fine way to do it here) */ return 0; /* WS only: same as empty line */ } /* This is fussy. The spec says that a header line is delimited with a colon-space pair. This means that a line such as "Comment: " (with nothing else) is actually legal as an empty string comment. However, email and cut-and-paste being what it is, that trailing space may go away. Therefore, we accept empty headers delimited with only a colon. --rfc2440, as always, makes this strict and enforces the colon-space pair. -dms */ p = strchr( line, ':'); if( !p || (RFC2440 && p[1]!=' ') || (!RFC2440 && p[1]!=' ' && p[1]!='\n' && p[1]!='\r')) { - log_error(_("invalid armor header: ")); - print_string( stderr, line, len, 0 ); - putc('\n', stderr); + log_error (_("invalid armor header: ")); + es_write_sanitized (log_get_stream (), line, len, NULL, NULL); + log_printf ("\n"); return -1; } /* Chop off the whitespace we detected before */ len=len2; line[len2]='\0'; if( opt.verbose ) { log_info(_("armor header: ")); - print_string( stderr, line, len, 0 ); - putc('\n', stderr); + es_write_sanitized (log_get_stream (), line, len, NULL, NULL); + log_printf ("\n"); } if( afx->in_cleartext ) { if( (hashes=parse_hash_header( line )) ) afx->hashes |= hashes; else if( strlen(line) > 15 && !memcmp( line, "NotDashEscaped:", 15 ) ) afx->not_dash_escaped = 1; else { log_error(_("invalid clearsig header\n")); return -1; } } else if(!is_armor_tag(line)) { /* Section 6.2: "Unknown keys should be reported to the user, but OpenPGP should continue to process the message." Note that in a clearsigned message this applies to the signature part (i.e. "BEGIN PGP SIGNATURE") and not the signed data ("BEGIN PGP SIGNED MESSAGE"). The only key allowed in the signed data section is "Hash". */ log_info(_("unknown armor header: ")); - print_string( stderr, line, len, 0 ); - putc('\n', stderr); + es_write_sanitized (log_get_stream (), line, len, NULL, NULL); + log_printf ("\n"); } return 1; } /* figure out whether the data is armored or not */ static int check_input( armor_filter_context_t *afx, IOBUF a ) { int rc = 0; int i; byte *line; unsigned len; unsigned maxlen; int hdr_line = -1; /* read the first line to see whether this is armored data */ maxlen = MAX_LINELEN; len = afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); line = afx->buffer; if( !maxlen ) { /* line has been truncated: assume not armored */ afx->inp_checked = 1; afx->inp_bypass = 1; return 0; } if( !len ) { return -1; /* eof */ } /* (the line is always a C string but maybe longer) */ if( *line == '\n' || ( len && (*line == '\r' && line[1]=='\n') ) ) ; else if( !is_armored( line ) ) { afx->inp_checked = 1; afx->inp_bypass = 1; return 0; } /* find the armor header */ while(len) { i = is_armor_header( line, len ); if( i >= 0 && !(afx->only_keyblocks && i != 1 && i != 5 && i != 6 )) { hdr_line = i; if( hdr_line == BEGIN_SIGNED_MSG_IDX ) { if( afx->in_cleartext ) { log_error(_("nested clear text signatures\n")); rc = gpg_error (GPG_ERR_INV_ARMOR); } afx->in_cleartext = 1; } break; } /* read the next line (skip all truncated lines) */ do { maxlen = MAX_LINELEN; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); line = afx->buffer; len = afx->buffer_len; } while( !maxlen ); } /* Parse the header lines. */ while(len) { /* Read the next line (skip all truncated lines). */ do { maxlen = MAX_LINELEN; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); line = afx->buffer; len = afx->buffer_len; } while( !maxlen ); i = parse_header_line( afx, line, len ); if( i <= 0 ) { if (i && RFC2440) rc = G10ERR_INVALID_ARMOR; break; } } if( rc ) invalid_armor(); else if( afx->in_cleartext ) afx->faked = 1; else { afx->inp_checked = 1; afx->crc = CRCINIT; afx->idx = 0; afx->radbuf[0] = 0; } return rc; } #define PARTIAL_CHUNK 512 #define PARTIAL_POW 9 /**************** * Fake a literal data packet and wait for the next armor line * fixme: empty line handling and null length clear text signature are * not implemented/checked. */ static int fake_packet( armor_filter_context_t *afx, IOBUF a, size_t *retn, byte *buf, size_t size ) { int rc = 0; size_t len = 0; int lastline = 0; unsigned maxlen, n; byte *p; byte tempbuf[PARTIAL_CHUNK]; size_t tempbuf_len=0; while( !rc && size-len>=(PARTIAL_CHUNK+1)) { /* copy what we have in the line buffer */ if( afx->faked == 1 ) afx->faked++; /* skip the first (empty) line */ else { /* It's full, so write this partial chunk */ if(tempbuf_len==PARTIAL_CHUNK) { buf[len++]=0xE0+PARTIAL_POW; memcpy(&buf[len],tempbuf,PARTIAL_CHUNK); len+=PARTIAL_CHUNK; tempbuf_len=0; continue; } while( tempbuf_len < PARTIAL_CHUNK && afx->buffer_pos < afx->buffer_len ) tempbuf[tempbuf_len++] = afx->buffer[afx->buffer_pos++]; if( tempbuf_len==PARTIAL_CHUNK ) continue; } /* read the next line */ maxlen = MAX_LINELEN; afx->buffer_pos = 0; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); if( !afx->buffer_len ) { rc = -1; /* eof (should not happen) */ continue; } if( !maxlen ) afx->truncated++; p = afx->buffer; n = afx->buffer_len; /* Armor header or dash-escaped line? */ if(p[0]=='-') { /* 2440bis-10: When reversing dash-escaping, an implementation MUST strip the string "- " if it occurs at the beginning of a line, and SHOULD warn on "-" and any character other than a space at the beginning of a line. */ if(p[1]==' ' && !afx->not_dash_escaped) { /* It's a dash-escaped line, so skip over the escape. */ afx->buffer_pos = 2; } else if(p[1]=='-' && p[2]=='-' && p[3]=='-' && p[4]=='-') { /* Five dashes in a row mean it's probably armor header. */ int type = is_armor_header( p, n ); if( afx->not_dash_escaped && type != BEGIN_SIGNATURE ) ; /* this is okay */ else { if( type != BEGIN_SIGNATURE ) { log_info(_("unexpected armor: ")); - print_string( stderr, p, n, 0 ); - putc('\n', stderr); + es_write_sanitized (log_get_stream (), p, n, + NULL, NULL); + log_printf ("\n"); } lastline = 1; rc = -1; } } else if(!afx->not_dash_escaped) { /* Bad dash-escaping. */ - log_info(_("invalid dash escaped line: ")); - print_string( stderr, p, n, 0 ); - putc('\n', stderr); + log_info (_("invalid dash escaped line: ")); + es_write_sanitized (log_get_stream (), p, n, NULL, NULL); + log_printf ("\n"); } } /* Now handle the end-of-line canonicalization */ if( !afx->not_dash_escaped ) { int crlf = n > 1 && p[n-2] == '\r' && p[n-1]=='\n'; /* PGP2 does not treat a tab as white space character */ afx->buffer_len= trim_trailing_chars( &p[afx->buffer_pos], n-afx->buffer_pos, afx->pgp2mode ? " \r\n" : " \t\r\n"); afx->buffer_len+=afx->buffer_pos; /* the buffer is always allocated with enough space to append * the removed [CR], LF and a Nul * The reason for this complicated procedure is to keep at least * the original type of lineending - handling of the removed * trailing spaces seems to be impossible in our method * of faking a packet; either we have to use a temporary file * or calculate the hash here in this module and somehow find * a way to send the hash down the processing line (well, a special * faked packet could do the job). */ if( crlf ) afx->buffer[afx->buffer_len++] = '\r'; afx->buffer[afx->buffer_len++] = '\n'; afx->buffer[afx->buffer_len] = '\0'; } } if( lastline ) { /* write last (ending) length header */ if(tempbuf_len<192) buf[len++]=tempbuf_len; else { buf[len++]=((tempbuf_len-192)/256) + 192; buf[len++]=(tempbuf_len-192) % 256; } memcpy(&buf[len],tempbuf,tempbuf_len); len+=tempbuf_len; rc = 0; afx->faked = 0; afx->in_cleartext = 0; /* and now read the header lines */ afx->buffer_pos = 0; for(;;) { int i; /* read the next line (skip all truncated lines) */ do { maxlen = MAX_LINELEN; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); } while( !maxlen ); p = afx->buffer; n = afx->buffer_len; if( !n ) { rc = -1; break; /* eof */ } i = parse_header_line( afx, p , n ); if( i <= 0 ) { if( i ) invalid_armor(); break; } } afx->inp_checked = 1; afx->crc = CRCINIT; afx->idx = 0; afx->radbuf[0] = 0; } *retn = len; return rc; } static int invalid_crc(void) { if ( opt.ignore_crc_error ) return 0; log_inc_errorcount(); return gpg_error (GPG_ERR_INV_ARMOR); } static int radix64_read( armor_filter_context_t *afx, IOBUF a, size_t *retn, byte *buf, size_t size ) { byte val; int c=0, c2; /*init c because gcc is not clever enough for the continue*/ int checkcrc=0; int rc = 0; size_t n = 0; int idx, i, onlypad=0; u32 crc; crc = afx->crc; idx = afx->idx; val = afx->radbuf[0]; for( n=0; n < size; ) { if( afx->buffer_pos < afx->buffer_len ) c = afx->buffer[afx->buffer_pos++]; else { /* read the next line */ unsigned maxlen = MAX_LINELEN; afx->buffer_pos = 0; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); if( !maxlen ) afx->truncated++; if( !afx->buffer_len ) break; /* eof */ continue; } again: if( c == '\n' || c == ' ' || c == '\r' || c == '\t' ) continue; else if( c == '=' ) { /* pad character: stop */ /* some mailers leave quoted-printable encoded characters * so we try to workaround this */ if( afx->buffer_pos+2 < afx->buffer_len ) { int cc1, cc2, cc3; cc1 = afx->buffer[afx->buffer_pos]; cc2 = afx->buffer[afx->buffer_pos+1]; cc3 = afx->buffer[afx->buffer_pos+2]; if( isxdigit(cc1) && isxdigit(cc2) && strchr( "=\n\r\t ", cc3 )) { /* well it seems to be the case - adjust */ c = isdigit(cc1)? (cc1 - '0'): (ascii_toupper(cc1)-'A'+10); c <<= 4; c |= isdigit(cc2)? (cc2 - '0'): (ascii_toupper(cc2)-'A'+10); afx->buffer_pos += 2; afx->qp_detected = 1; goto again; } } else if(n==0) onlypad=1; if( idx == 1 ) buf[n++] = val; checkcrc++; break; } else if( (c = asctobin[(c2=c)]) == 255 ) { log_error(_("invalid radix64 character %02X skipped\n"), c2); continue; } switch(idx) { case 0: val = c << 2; break; case 1: val |= (c>>4)&3; buf[n++]=val;val=(c<<4)&0xf0;break; case 2: val |= (c>>2)&15; buf[n++]=val;val=(c<<6)&0xc0;break; case 3: val |= c&0x3f; buf[n++] = val; break; } idx = (idx+1) % 4; } for(i=0; i < n; i++ ) crc = (crc << 8) ^ crc_table[((crc >> 16)&0xff) ^ buf[i]]; crc &= 0x00ffffff; afx->crc = crc; afx->idx = idx; afx->radbuf[0] = val; if( checkcrc ) { afx->any_data = 1; afx->inp_checked=0; afx->faked = 0; for(;;) { /* skip lf and pad characters */ if( afx->buffer_pos < afx->buffer_len ) c = afx->buffer[afx->buffer_pos++]; else { /* read the next line */ unsigned maxlen = MAX_LINELEN; afx->buffer_pos = 0; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); if( !maxlen ) afx->truncated++; if( !afx->buffer_len ) break; /* eof */ continue; } if( c == '\n' || c == ' ' || c == '\r' || c == '\t' || c == '=' ) continue; break; } if( c == -1 ) log_error(_("premature eof (no CRC)\n")); else { u32 mycrc = 0; idx = 0; do { if( (c = asctobin[c]) == 255 ) break; switch(idx) { case 0: val = c << 2; break; case 1: val |= (c>>4)&3; mycrc |= val << 16;val=(c<<4)&0xf0;break; case 2: val |= (c>>2)&15; mycrc |= val << 8;val=(c<<6)&0xc0;break; case 3: val |= c&0x3f; mycrc |= val; break; } for(;;) { if( afx->buffer_pos < afx->buffer_len ) c = afx->buffer[afx->buffer_pos++]; else { /* read the next line */ unsigned maxlen = MAX_LINELEN; afx->buffer_pos = 0; afx->buffer_len = iobuf_read_line( a, &afx->buffer, &afx->buffer_size, &maxlen ); if( !maxlen ) afx->truncated++; if( !afx->buffer_len ) break; /* eof */ continue; } break; } if( !afx->buffer_len ) break; /* eof */ } while( ++idx < 4 ); if( c == -1 ) { log_info(_("premature eof (in CRC)\n")); rc = invalid_crc(); } else if( idx == 0 ) { /* No CRC at all is legal ("MAY") */ rc=0; } else if( idx != 4 ) { log_info(_("malformed CRC\n")); rc = invalid_crc(); } else if( mycrc != afx->crc ) { log_info (_("CRC error; %06lX - %06lX\n"), (ulong)afx->crc, (ulong)mycrc); rc = invalid_crc(); } else { rc = 0; /* FIXME: Here we should emit another control packet, * so that we know in mainproc that we are processing * a clearsign message */ #if 0 for(rc=0;!rc;) { rc = 0 /*check_trailer( &fhdr, c )*/; if( !rc ) { if( (c=iobuf_get(a)) == -1 ) rc = 2; } } if( rc == -1 ) rc = 0; else if( rc == 2 ) { log_error(_("premature eof (in trailer)\n")); rc = G10ERR_INVALID_ARMOR; } else { log_error(_("error in trailer line\n")); rc = G10ERR_INVALID_ARMOR; } #endif } } } if( !n && !onlypad ) rc = -1; *retn = n; return rc; } /**************** * This filter is used to handle the armor stuff */ static int armor_filter( void *opaque, int control, IOBUF a, byte *buf, size_t *ret_len) { size_t size = *ret_len; armor_filter_context_t *afx = opaque; int rc=0, i, c; byte radbuf[3]; int idx, idx2; size_t n=0; u32 crc; #if 0 static FILE *fp ; if( !fp ) { fp = fopen("armor.out", "w"); assert(fp); } #endif if( DBG_FILTER ) log_debug("armor-filter: control: %d\n", control ); if( control == IOBUFCTRL_UNDERFLOW && afx->inp_bypass ) { n = 0; if( afx->buffer_len ) { for(; n < size && afx->buffer_pos < afx->buffer_len; n++ ) buf[n++] = afx->buffer[afx->buffer_pos++]; if( afx->buffer_pos >= afx->buffer_len ) afx->buffer_len = 0; } for(; n < size; n++ ) { if( (c=iobuf_get(a)) == -1 ) break; buf[n] = c & 0xff; } if( !n ) rc = -1; *ret_len = n; } else if( control == IOBUFCTRL_UNDERFLOW ) { /* We need some space for the faked packet. The minmum * required size is the PARTIAL_CHUNK size plus a byte for the * length itself */ if( size < PARTIAL_CHUNK+1 ) BUG(); /* supplied buffer too short */ if( afx->faked ) rc = fake_packet( afx, a, &n, buf, size ); else if( !afx->inp_checked ) { rc = check_input( afx, a ); if( afx->inp_bypass ) { for(n=0; n < size && afx->buffer_pos < afx->buffer_len; ) buf[n++] = afx->buffer[afx->buffer_pos++]; if( afx->buffer_pos >= afx->buffer_len ) afx->buffer_len = 0; if( !n ) rc = -1; } else if( afx->faked ) { unsigned int hashes = afx->hashes; const byte *sesmark; size_t sesmarklen; sesmark = get_session_marker( &sesmarklen ); if ( sesmarklen > 20 ) BUG(); /* the buffer is at least 15+n*15 bytes long, so it * is easy to construct the packets */ hashes &= 1|2|4|8|16|32|64; if( !hashes ) { hashes |= 4; /* default to MD 5 */ /* This is non-ideal since PGP 5-8 have the same end-of-line bugs as PGP 2. However, we only enable pgp2mode if there is no Hash: header. */ if( opt.pgp2_workarounds ) afx->pgp2mode = 1; } n=0; /* First a gpg control packet... */ buf[n++] = 0xff; /* new format, type 63, 1 length byte */ n++; /* see below */ memcpy(buf+n, sesmark, sesmarklen ); n+= sesmarklen; buf[n++] = CTRLPKT_CLEARSIGN_START; buf[n++] = afx->not_dash_escaped? 0:1; /* sigclass */ if( hashes & 1 ) buf[n++] = DIGEST_ALGO_RMD160; if( hashes & 2 ) buf[n++] = DIGEST_ALGO_SHA1; if( hashes & 4 ) buf[n++] = DIGEST_ALGO_MD5; if( hashes & 8 ) buf[n++] = DIGEST_ALGO_SHA224; if( hashes & 16 ) buf[n++] = DIGEST_ALGO_SHA256; if( hashes & 32 ) buf[n++] = DIGEST_ALGO_SHA384; if( hashes & 64 ) buf[n++] = DIGEST_ALGO_SHA512; buf[1] = n - 2; /* ...followed by an invented plaintext packet. Amusingly enough, this packet is not compliant with 2440 as the initial partial length is less than 512 bytes. Of course, we'll accept it anyway ;) */ buf[n++] = 0xCB; /* new packet format, type 11 */ buf[n++] = 0xE1; /* 2^1 == 2 bytes */ buf[n++] = 't'; /* canonical text mode */ buf[n++] = 0; /* namelength */ buf[n++] = 0xE2; /* 2^2 == 4 more bytes */ memset(buf+n, 0, 4); /* timestamp */ n += 4; } else if( !rc ) rc = radix64_read( afx, a, &n, buf, size ); } else rc = radix64_read( afx, a, &n, buf, size ); #if 0 if( n ) if( fwrite(buf, n, 1, fp ) != 1 ) BUG(); #endif *ret_len = n; } else if( control == IOBUFCTRL_FLUSH && !afx->cancel ) { if( !afx->status ) { /* write the header line */ const char *s; strlist_t comment=opt.comments; if( afx->what >= DIM(head_strings) ) log_bug("afx->what=%d", afx->what); iobuf_writestr(a, "-----"); iobuf_writestr(a, head_strings[afx->what] ); iobuf_writestr(a, "-----" ); iobuf_writestr(a,afx->eol); if( !opt.no_version ) { iobuf_writestr(a, "Version: GnuPG v" VERSION " (" PRINTABLE_OS_NAME ")" ); iobuf_writestr(a,afx->eol); } /* write the comment strings */ for(s=comment->d;comment;comment=comment->next,s=comment->d) { iobuf_writestr(a, "Comment: " ); for( ; *s; s++ ) { if( *s == '\n' ) iobuf_writestr(a, "\\n" ); else if( *s == '\r' ) iobuf_writestr(a, "\\r" ); else if( *s == '\v' ) iobuf_writestr(a, "\\v" ); else iobuf_put(a, *s ); } iobuf_writestr(a,afx->eol); } if ( afx->hdrlines ) { for ( s = afx->hdrlines; *s; s++ ) { #ifdef HAVE_DOSISH_SYSTEM if ( *s == '\n' ) iobuf_put( a, '\r'); #endif iobuf_put(a, *s ); } } iobuf_writestr(a,afx->eol); afx->status++; afx->idx = 0; afx->idx2 = 0; afx->crc = CRCINIT; } crc = afx->crc; idx = afx->idx; idx2 = afx->idx2; for(i=0; i < idx; i++ ) radbuf[i] = afx->radbuf[i]; for(i=0; i < size; i++ ) crc = (crc << 8) ^ crc_table[((crc >> 16)&0xff) ^ buf[i]]; crc &= 0x00ffffff; for( ; size; buf++, size-- ) { radbuf[idx++] = *buf; if( idx > 2 ) { idx = 0; c = bintoasc[(*radbuf >> 2) & 077]; iobuf_put(a, c); c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077]; iobuf_put(a, c); c = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077]; iobuf_put(a, c); c = bintoasc[radbuf[2]&077]; iobuf_put(a, c); if( ++idx2 >= (64/4) ) { /* pgp doesn't like 72 here */ iobuf_writestr(a,afx->eol); idx2=0; } } } for(i=0; i < idx; i++ ) afx->radbuf[i] = radbuf[i]; afx->idx = idx; afx->idx2 = idx2; afx->crc = crc; } else if( control == IOBUFCTRL_INIT ) { if( !is_initialized ) initialize(); /* Figure out what we're using for line endings if the caller didn't specify. */ if(afx->eol[0]==0) { #ifdef HAVE_DOSISH_SYSTEM afx->eol[0]='\r'; afx->eol[1]='\n'; #else afx->eol[0]='\n'; #endif } } else if( control == IOBUFCTRL_CANCEL ) { afx->cancel = 1; } else if( control == IOBUFCTRL_FREE ) { if( afx->cancel ) ; else if( afx->status ) { /* pad, write cecksum, and bottom line */ crc = afx->crc; idx = afx->idx; idx2 = afx->idx2; for(i=0; i < idx; i++ ) radbuf[i] = afx->radbuf[i]; if( idx ) { c = bintoasc[(*radbuf>>2)&077]; iobuf_put(a, c); if( idx == 1 ) { c = bintoasc[((*radbuf << 4) & 060) & 077]; iobuf_put(a, c); iobuf_put(a, '='); iobuf_put(a, '='); } else { /* 2 */ c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1]>>4)&017))&077]; iobuf_put(a, c); c = bintoasc[((radbuf[1] << 2) & 074) & 077]; iobuf_put(a, c); iobuf_put(a, '='); } if( ++idx2 >= (64/4) ) { /* pgp doesn't like 72 here */ iobuf_writestr(a,afx->eol); idx2=0; } } /* may need a linefeed */ if( idx2 ) iobuf_writestr(a,afx->eol); /* write the CRC */ iobuf_put(a, '='); radbuf[0] = crc >>16; radbuf[1] = crc >> 8; radbuf[2] = crc; c = bintoasc[(*radbuf >> 2) & 077]; iobuf_put(a, c); c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077]; iobuf_put(a, c); c = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077]; iobuf_put(a, c); c = bintoasc[radbuf[2]&077]; iobuf_put(a, c); iobuf_writestr(a,afx->eol); /* and the the trailer */ if( afx->what >= DIM(tail_strings) ) log_bug("afx->what=%d", afx->what); iobuf_writestr(a, "-----"); iobuf_writestr(a, tail_strings[afx->what] ); iobuf_writestr(a, "-----" ); iobuf_writestr(a,afx->eol); } else if( !afx->any_data && !afx->inp_bypass ) { log_error(_("no valid OpenPGP data found.\n")); afx->no_openpgp_data = 1; write_status_text( STATUS_NODATA, "1" ); } if( afx->truncated ) log_info(_("invalid armor: line longer than %d characters\n"), MAX_LINELEN ); /* issue an error to enforce dissemination of correct software */ if( afx->qp_detected ) log_error(_("quoted printable character in armor - " "probably a buggy MTA has been used\n") ); xfree( afx->buffer ); afx->buffer = NULL; release_armor_context (afx); } else if( control == IOBUFCTRL_DESC ) *(char**)buf = "armor_filter"; return rc; } /**************** * create a radix64 encoded string. */ char * make_radix64_string( const byte *data, size_t len ) { char *buffer, *p; buffer = p = xmalloc( (len+2)/3*4 + 1 ); for( ; len >= 3 ; len -= 3, data += 3 ) { *p++ = bintoasc[(data[0] >> 2) & 077]; *p++ = bintoasc[(((data[0] <<4)&060)|((data[1] >> 4)&017))&077]; *p++ = bintoasc[(((data[1]<<2)&074)|((data[2]>>6)&03))&077]; *p++ = bintoasc[data[2]&077]; } if( len == 2 ) { *p++ = bintoasc[(data[0] >> 2) & 077]; *p++ = bintoasc[(((data[0] <<4)&060)|((data[1] >> 4)&017))&077]; *p++ = bintoasc[((data[1]<<2)&074)]; } else if( len == 1 ) { *p++ = bintoasc[(data[0] >> 2) & 077]; *p++ = bintoasc[(data[0] <<4)&060]; } *p = 0; return buffer; } /*********************************************** * For the pipemode command we can't use the armor filter for various * reasons, so we use this new unarmor_pump stuff to remove the armor */ enum unarmor_state_e { STA_init = 0, STA_bypass, STA_wait_newline, STA_wait_dash, STA_first_dash, STA_compare_header, STA_found_header_wait_newline, STA_skip_header_lines, STA_skip_header_lines_non_ws, STA_read_data, STA_wait_crc, STA_read_crc, STA_ready }; struct unarmor_pump_s { enum unarmor_state_e state; byte val; int checkcrc; int pos; /* counts from 0..3 */ u32 crc; u32 mycrc; /* the one store in the data */ }; UnarmorPump unarmor_pump_new (void) { UnarmorPump x; if( !is_initialized ) initialize(); x = xmalloc_clear (sizeof *x); return x; } void unarmor_pump_release (UnarmorPump x) { xfree (x); } /* * Get the next character from the ascii armor taken from the IOBUF * created earlier by unarmor_pump_new(). * Return: c = Character * 256 = ignore this value * -1 = End of current armor * -2 = Premature EOF (not used) * -3 = Invalid armor */ int unarmor_pump (UnarmorPump x, int c) { int rval = 256; /* default is to ignore the return value */ switch (x->state) { case STA_init: { byte tmp[1]; tmp[0] = c; if ( is_armored (tmp) ) x->state = c == '-'? STA_first_dash : STA_wait_newline; else { x->state = STA_bypass; return c; } } break; case STA_bypass: return c; /* return here to avoid crc calculation */ case STA_wait_newline: if (c == '\n') x->state = STA_wait_dash; break; case STA_wait_dash: x->state = c == '-'? STA_first_dash : STA_wait_newline; break; case STA_first_dash: /* just need for initalization */ x->pos = 0; x->state = STA_compare_header; case STA_compare_header: if ( "-----BEGIN PGP SIGNATURE-----"[++x->pos] == c ) { if ( x->pos == 28 ) x->state = STA_found_header_wait_newline; } else x->state = c == '\n'? STA_wait_dash : STA_wait_newline; break; case STA_found_header_wait_newline: /* to make CR,LF issues easier we simply allow for white space behind the 5 dashes */ if ( c == '\n' ) x->state = STA_skip_header_lines; else if ( c != '\r' && c != ' ' && c != '\t' ) x->state = STA_wait_dash; /* garbage after the header line */ break; case STA_skip_header_lines: /* i.e. wait for one empty line */ if ( c == '\n' ) { x->state = STA_read_data; x->crc = CRCINIT; x->val = 0; x->pos = 0; } else if ( c != '\r' && c != ' ' && c != '\t' ) x->state = STA_skip_header_lines_non_ws; break; case STA_skip_header_lines_non_ws: /* like above but we already encountered non white space */ if ( c == '\n' ) x->state = STA_skip_header_lines; break; case STA_read_data: /* fixme: we don't check for the trailing dash lines but rely * on the armor stop characters */ if( c == '\n' || c == ' ' || c == '\r' || c == '\t' ) break; /* skip all kind of white space */ if( c == '=' ) { /* pad character: stop */ if( x->pos == 1 ) /* in this case val has some value */ rval = x->val; x->state = STA_wait_crc; break; } { int c2; if( (c = asctobin[(c2=c)]) == 255 ) { log_error(_("invalid radix64 character %02X skipped\n"), c2); break; } } switch(x->pos) { case 0: x->val = c << 2; break; case 1: x->val |= (c>>4)&3; rval = x->val; x->val = (c<<4)&0xf0; break; case 2: x->val |= (c>>2)&15; rval = x->val; x->val = (c<<6)&0xc0; break; case 3: x->val |= c&0x3f; rval = x->val; break; } x->pos = (x->pos+1) % 4; break; case STA_wait_crc: if( c == '\n' || c == ' ' || c == '\r' || c == '\t' || c == '=' ) break; /* skip ws and pad characters */ /* assume that we are at the next line */ x->state = STA_read_crc; x->pos = 0; x->mycrc = 0; case STA_read_crc: if( (c = asctobin[c]) == 255 ) { rval = -1; /* ready */ if( x->crc != x->mycrc ) { log_info (_("CRC error; %06lX - %06lX\n"), (ulong)x->crc, (ulong)x->mycrc); if ( invalid_crc() ) rval = -3; } x->state = STA_ready; /* not sure whether this is correct */ break; } switch(x->pos) { case 0: x->val = c << 2; break; case 1: x->val |= (c>>4)&3; x->mycrc |= x->val << 16; x->val = (c<<4)&0xf0; break; case 2: x->val |= (c>>2)&15; x->mycrc |= x->val << 8; x->val = (c<<6)&0xc0; break; case 3: x->val |= c&0x3f; x->mycrc |= x->val; break; } x->pos = (x->pos+1) % 4; break; case STA_ready: rval = -1; break; } if ( !(rval & ~255) ) { /* compute the CRC */ x->crc = (x->crc << 8) ^ crc_table[((x->crc >> 16)&0xff) ^ rval]; x->crc &= 0x00ffffff; } return rval; } diff --git a/g10/card-util.c b/g10/card-util.c index 9bd5013a1..0723a1c51 100644 --- a/g10/card-util.c +++ b/g10/card-util.c @@ -1,1993 +1,1996 @@ /* card-util.c - Utility functions for the OpenPGP card. * Copyright (C) 2003, 2004, 2005, 2009 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_LIBREADLINE # define GNUPG_LIBREADLINE_H_INCLUDED # include #endif /*HAVE_LIBREADLINE*/ #if GNUPG_MAJOR_VERSION != 1 # include "gpg.h" #endif /*GNUPG_MAJOR_VERSION != 1*/ #include "util.h" #include "i18n.h" #include "ttyio.h" #include "status.h" #include "options.h" #include "main.h" #include "keyserver-internal.h" #if GNUPG_MAJOR_VERSION == 1 # include "cardglue.h" #else /*GNUPG_MAJOR_VERSION!=1*/ # include "call-agent.h" #endif /*GNUPG_MAJOR_VERSION!=1*/ #define CONTROL_D ('D' - 'A' + 1) static void write_sc_op_status (gpg_error_t err) { switch (gpg_err_code (err)) { case 0: write_status (STATUS_SC_OP_SUCCESS); break; #if GNUPG_MAJOR_VERSION != 1 case GPG_ERR_CANCELED: write_status_text (STATUS_SC_OP_FAILURE, "1"); break; case GPG_ERR_BAD_PIN: write_status_text (STATUS_SC_OP_FAILURE, "2"); break; default: write_status (STATUS_SC_OP_FAILURE); break; #endif /* GNUPG_MAJOR_VERSION != 1 */ } } /* Change the PIN of a an OpenPGP card. This is an interactive function. */ void change_pin (int unblock_v2, int allow_admin) { struct agent_card_info_s info; int rc; rc = agent_learn (&info); if (rc) { log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc)); return; } log_info (_("OpenPGP card no. %s detected\n"), info.serialno? info.serialno : "[none]"); agent_clear_pin_cache (info.serialno); if (opt.batch) { agent_release_card_info (&info); log_error (_("can't do this in batch mode\n")); return; } if (unblock_v2) { if (!info.is_v2) log_error (_("This command is only available for version 2 cards\n")); else if (!info.chvretry[1]) log_error (_("Reset Code not or not anymore available\n")); else { rc = agent_scd_change_pin (2, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } } else if (!allow_admin) { rc = agent_scd_change_pin (1, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else for (;;) { char *answer; tty_printf ("\n"); tty_printf ("1 - change PIN\n" "2 - unblock PIN\n" "3 - change Admin PIN\n" "4 - set the Reset Code\n" "Q - quit\n"); tty_printf ("\n"); answer = cpr_get("cardutil.change_pin.menu",_("Your selection? ")); cpr_kill_prompt(); if (strlen (answer) != 1) continue; rc = 0; if (*answer == '1') { /* Change PIN. */ rc = agent_scd_change_pin (1, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else if (*answer == '2') { /* Unblock PIN. */ rc = agent_scd_change_pin (101, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN unblocked and new PIN set.\n"); } else if (*answer == '3') { /* Change Admin PIN. */ rc = agent_scd_change_pin (3, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc)); else tty_printf ("PIN changed.\n"); } else if (*answer == '4') { /* Set a new Reset Code. */ rc = agent_scd_change_pin (102, info.serialno); write_sc_op_status (rc); if (rc) tty_printf ("Error setting the Reset Code: %s\n", gpg_strerror (rc)); else tty_printf ("Reset Code set.\n"); } else if (*answer == 'q' || *answer == 'Q') { break; } } agent_release_card_info (&info); } static const char * get_manufacturer (unsigned int no) { /* Note: Make sure that there is no colon or linefeed in the string. */ switch (no) { case 0x0001: return "PPC Card Systems"; case 0x0002: return "Prism"; case 0x0003: return "OpenFortress"; case 0x0004: return "Wewid AB"; case 0x0005: return "ZeitControl"; case 0x002A: return "Magrathea"; /* 0x00000 and 0xFFFF are defined as test cards per spec, 0xFFF00 to 0xFFFE are assigned for use with randomly created serial numbers. */ case 0x0000: case 0xffff: return "test card"; default: return (no & 0xff00) == 0xff00? "unmanaged S/N range":"unknown"; } } static void -print_sha1_fpr (FILE *fp, const unsigned char *fpr) +print_sha1_fpr (estream_t fp, const unsigned char *fpr) { int i; if (fpr) { for (i=0; i < 20 ; i+=2, fpr += 2 ) { if (i == 10 ) tty_fprintf (fp, " "); tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]); } } else tty_fprintf (fp, " [none]"); tty_fprintf (fp, "\n"); } static void -print_sha1_fpr_colon (FILE *fp, const unsigned char *fpr) +print_sha1_fpr_colon (estream_t fp, const unsigned char *fpr) { int i; if (fpr) { for (i=0; i < 20 ; i++, fpr++) - fprintf (fp, "%02X", *fpr); + es_fprintf (fp, "%02X", *fpr); } - putc (':', fp); + es_putc (':', fp); } static void -print_name (FILE *fp, const char *text, const char *name) +print_name (estream_t fp, const char *text, const char *name) { tty_fprintf (fp, "%s", text); /* FIXME: tty_printf_utf8_string2 eats everything after and including an @ - e.g. when printing an url. */ if (name && *name) { if (fp) - print_utf8_string2 (fp, name, strlen (name), '\n'); + print_utf8_buffer2 (fp, name, strlen (name), '\n'); else tty_print_utf8_string2 (name, strlen (name), 0); } else tty_fprintf (fp, _("[not set]")); tty_fprintf (fp, "\n"); } static void -print_isoname (FILE *fp, const char *text, const char *tag, const char *name) +print_isoname (estream_t fp, const char *text, + const char *tag, const char *name) { if (opt.with_colons) - fprintf (fp, "%s:", tag); + es_fprintf (fp, "%s:", tag); else tty_fprintf (fp, "%s", text); if (name && *name) { char *p, *given, *buf = xstrdup (name); given = strstr (buf, "<<"); for (p=buf; *p; p++) if (*p == '<') *p = ' '; if (given && given[2]) { *given = 0; given += 2; if (opt.with_colons) - print_string (fp, given, strlen (given), ':'); + es_write_sanitized (fp, given, strlen (given), ":", NULL); else if (fp) - print_utf8_string2 (fp, given, strlen (given), '\n'); + print_utf8_buffer2 (fp, given, strlen (given), '\n'); else tty_print_utf8_string2 (given, strlen (given), 0); if (opt.with_colons) - putc (':', fp); + es_putc (':', fp); else if (*buf) tty_fprintf (fp, " "); } if (opt.with_colons) - print_string (fp, buf, strlen (buf), ':'); + es_write_sanitized (fp, buf, strlen (buf), ":", NULL); else if (fp) - print_utf8_string2 (fp, buf, strlen (buf), '\n'); + print_utf8_buffer2 (fp, buf, strlen (buf), '\n'); else tty_print_utf8_string2 (buf, strlen (buf), 0); xfree (buf); } else { if (opt.with_colons) - putc (':', fp); + es_putc (':', fp); else tty_fprintf (fp, _("[not set]")); } if (opt.with_colons) - fputs (":\n", fp); + es_fputs (":\n", fp); else tty_fprintf (fp, "\n"); } /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */ static int fpr_is_zero (const char *fpr) { int i; for (i=0; i < 20 && !fpr[i]; i++) ; return (i == 20); } /* Return true if the SHA1 fingerprint FPR consists only of 0xFF. */ static int fpr_is_ff (const char *fpr) { int i; for (i=0; i < 20 && fpr[i] == '\xff'; i++) ; return (i == 20); } /* Print all available information about the current card. */ void -card_status (FILE *fp, char *serialno, size_t serialnobuflen) +card_status (estream_t fp, char *serialno, size_t serialnobuflen) { struct agent_card_info_s info; PKT_public_key *pk = xcalloc (1, sizeof *pk); int rc; unsigned int uval; const unsigned char *thefpr; int i; if (serialno && serialnobuflen) *serialno = 0; rc = agent_learn (&info); if (rc) { if (opt.with_colons) - fputs ("AID:::\n", fp); - log_error (_("OpenPGP card not available: %s\n"), - gpg_strerror (rc)); + es_fputs ("AID:::\n", fp); + log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc)); xfree (pk); return; } if (opt.with_colons) - fprintf (fp, "AID:%s:", info.serialno? info.serialno : ""); + es_fprintf (fp, "AID:%s:", info.serialno? info.serialno : ""); else tty_fprintf (fp, "Application ID ...: %s\n", info.serialno? info.serialno : "[none]"); if (!info.serialno || strncmp (info.serialno, "D27600012401", 12) || strlen (info.serialno) != 32 ) { if (info.apptype && !strcmp (info.apptype, "NKS")) { if (opt.with_colons) - fputs ("netkey-card:\n", fp); + es_fputs ("netkey-card:\n", fp); log_info ("this is a NetKey card\n"); } else if (info.apptype && !strcmp (info.apptype, "DINSIG")) { if (opt.with_colons) - fputs ("dinsig-card:\n", fp); + es_fputs ("dinsig-card:\n", fp); log_info ("this is a DINSIG compliant card\n"); } else if (info.apptype && !strcmp (info.apptype, "P15")) { if (opt.with_colons) - fputs ("pkcs15-card:\n", fp); + es_fputs ("pkcs15-card:\n", fp); log_info ("this is a PKCS#15 compliant card\n"); } else if (info.apptype && !strcmp (info.apptype, "GELDKARTE")) { if (opt.with_colons) - fputs ("geldkarte-card:\n", fp); + es_fputs ("geldkarte-card:\n", fp); log_info ("this is a Geldkarte compliant card\n"); } else { if (opt.with_colons) - fputs ("unknown:\n", fp); + es_fputs ("unknown:\n", fp); } log_info ("not an OpenPGP card\n"); agent_release_card_info (&info); xfree (pk); return; } if (!serialno) ; else if (strlen (serialno)+1 > serialnobuflen) log_error ("serial number longer than expected\n"); else strcpy (serialno, info.serialno); if (opt.with_colons) - fputs ("openpgp-card:\n", fp); + es_fputs ("openpgp-card:\n", fp); if (opt.with_colons) { - fprintf (fp, "version:%.4s:\n", info.serialno+12); + es_fprintf (fp, "version:%.4s:\n", info.serialno+12); uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18); - fprintf (fp, "vendor:%04x:%s:\n", uval, get_manufacturer (uval)); - fprintf (fp, "serial:%.8s:\n", info.serialno+20); + es_fprintf (fp, "vendor:%04x:%s:\n", uval, get_manufacturer (uval)); + es_fprintf (fp, "serial:%.8s:\n", info.serialno+20); print_isoname (fp, "Name of cardholder: ", "name", info.disp_name); - fputs ("lang:", fp); + es_fputs ("lang:", fp); if (info.disp_lang) - print_string (fp, info.disp_lang, strlen (info.disp_lang), ':'); - fputs (":\n", fp); + es_write_sanitized (fp, info.disp_lang, strlen (info.disp_lang), + ":", NULL); + es_fputs (":\n", fp); - fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm': + es_fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm': info.disp_sex == 2? 'f' : 'u')); - fputs ("url:", fp); + es_fputs ("url:", fp); if (info.pubkey_url) - print_string (fp, info.pubkey_url, strlen (info.pubkey_url), ':'); - fputs (":\n", fp); + es_write_sanitized (fp, info.pubkey_url, strlen (info.pubkey_url), + ":", NULL); + es_fputs (":\n", fp); - fputs ("login:", fp); + es_fputs ("login:", fp); if (info.login_data) - print_string (fp, info.login_data, strlen (info.login_data), ':'); - fputs (":\n", fp); + es_write_sanitized (fp, info.login_data, strlen (info.login_data), + ":", NULL); + es_fputs (":\n", fp); - fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached); + es_fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached); for (i=0; i < DIM (info.key_attr); i++) if (info.key_attr[0].algo) - fprintf (fp, "keyattr:%d:%d:%u:\n", i+1, - info.key_attr[i].algo, info.key_attr[i].nbits); - fprintf (fp, "maxpinlen:%d:%d:%d:\n", - info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]); - fprintf (fp, "pinretry:%d:%d:%d:\n", - info.chvretry[0], info.chvretry[1], info.chvretry[2]); - fprintf (fp, "sigcount:%lu:::\n", info.sig_counter); + es_fprintf (fp, "keyattr:%d:%d:%u:\n", i+1, + info.key_attr[i].algo, info.key_attr[i].nbits); + es_fprintf (fp, "maxpinlen:%d:%d:%d:\n", + info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]); + es_fprintf (fp, "pinretry:%d:%d:%d:\n", + info.chvretry[0], info.chvretry[1], info.chvretry[2]); + es_fprintf (fp, "sigcount:%lu:::\n", info.sig_counter); for (i=0; i < 4; i++) { if (info.private_do[i]) { - fprintf (fp, "private_do:%d:", i+1); - print_string (fp, info.private_do[i], - strlen (info.private_do[i]), ':'); - fputs (":\n", fp); + es_fprintf (fp, "private_do:%d:", i+1); + es_write_sanitized (fp, info.private_do[i], + strlen (info.private_do[i]), ":", NULL); + es_fputs (":\n", fp); } } - fputs ("cafpr:", fp); + es_fputs ("cafpr:", fp); print_sha1_fpr_colon (fp, info.cafpr1valid? info.cafpr1:NULL); print_sha1_fpr_colon (fp, info.cafpr2valid? info.cafpr2:NULL); print_sha1_fpr_colon (fp, info.cafpr3valid? info.cafpr3:NULL); - putc ('\n', fp); - fputs ("fpr:", fp); + es_putc ('\n', fp); + es_fputs ("fpr:", fp); print_sha1_fpr_colon (fp, info.fpr1valid? info.fpr1:NULL); print_sha1_fpr_colon (fp, info.fpr2valid? info.fpr2:NULL); print_sha1_fpr_colon (fp, info.fpr3valid? info.fpr3:NULL); - putc ('\n', fp); - fprintf (fp, "fprtime:%lu:%lu:%lu:\n", + es_putc ('\n', fp); + es_fprintf (fp, "fprtime:%lu:%lu:%lu:\n", (unsigned long)info.fpr1time, (unsigned long)info.fpr2time, (unsigned long)info.fpr3time); } else { tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n", info.serialno[12] == '0'?"":info.serialno+12, info.serialno[13], info.serialno[14] == '0'?"":info.serialno+14, info.serialno[15]); tty_fprintf (fp, "Manufacturer .....: %s\n", get_manufacturer (xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18))); tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20); print_isoname (fp, "Name of cardholder: ", "name", info.disp_name); print_name (fp, "Language prefs ...: ", info.disp_lang); tty_fprintf (fp, "Sex ..............: %s\n", info.disp_sex == 1? _("male"): info.disp_sex == 2? _("female") : _("unspecified")); print_name (fp, "URL of public key : ", info.pubkey_url); print_name (fp, "Login data .......: ", info.login_data); if (info.private_do[0]) print_name (fp, "Private DO 1 .....: ", info.private_do[0]); if (info.private_do[1]) print_name (fp, "Private DO 2 .....: ", info.private_do[1]); if (info.private_do[2]) print_name (fp, "Private DO 3 .....: ", info.private_do[2]); if (info.private_do[3]) print_name (fp, "Private DO 4 .....: ", info.private_do[3]); if (info.cafpr1valid) { tty_fprintf (fp, "CA fingerprint %d .:", 1); print_sha1_fpr (fp, info.cafpr1); } if (info.cafpr2valid) { tty_fprintf (fp, "CA fingerprint %d .:", 2); print_sha1_fpr (fp, info.cafpr2); } if (info.cafpr3valid) { tty_fprintf (fp, "CA fingerprint %d .:", 3); print_sha1_fpr (fp, info.cafpr3); } tty_fprintf (fp, "Signature PIN ....: %s\n", info.chv1_cached? _("not forced"): _("forced")); if (info.key_attr[0].algo) { tty_fprintf (fp, "Key attributes ...:"); for (i=0; i < DIM (info.key_attr); i++) tty_fprintf (fp, " %u%c", info.key_attr[i].nbits, info.key_attr[i].algo == 1? 'R': info.key_attr[i].algo == 17? 'D': '?'); tty_fprintf (fp, "\n"); } tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n", info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]); tty_fprintf (fp, "PIN retry counter : %d %d %d\n", info.chvretry[0], info.chvretry[1], info.chvretry[2]); tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter); tty_fprintf (fp, "Signature key ....:"); print_sha1_fpr (fp, info.fpr1valid? info.fpr1:NULL); if (info.fpr1valid && info.fpr1time) tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr1time)); tty_fprintf (fp, "Encryption key....:"); print_sha1_fpr (fp, info.fpr2valid? info.fpr2:NULL); if (info.fpr2valid && info.fpr2time) tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr2time)); tty_fprintf (fp, "Authentication key:"); print_sha1_fpr (fp, info.fpr3valid? info.fpr3:NULL); if (info.fpr3valid && info.fpr3time) tty_fprintf (fp, " created ....: %s\n", isotimestamp (info.fpr3time)); tty_fprintf (fp, "General key info..: "); thefpr = (info.fpr1valid? info.fpr1 : info.fpr2valid? info.fpr2 : info.fpr3valid? info.fpr3 : NULL); /* If the fingerprint is all 0xff, the key has no asssociated OpenPGP certificate. */ if ( thefpr && !fpr_is_ff (thefpr) && !get_pubkey_byfprint (pk, thefpr, 20)) { KBNODE keyblock = NULL; print_pubkey_info (fp, pk); if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) ) print_card_key_info (fp, keyblock); else if ( !get_keyblock_byfprint (&keyblock, thefpr, 20) ) { release_kbnode (keyblock); keyblock = NULL; if (!auto_create_card_key_stub (info.serialno, info.fpr1valid? info.fpr1:NULL, info.fpr2valid? info.fpr2:NULL, info.fpr3valid? info.fpr3:NULL)) { if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) ) print_card_key_info (fp, keyblock); } } release_kbnode (keyblock); } else tty_fprintf (fp, "[none]\n"); } free_public_key (pk); agent_release_card_info (&info); } static char * get_one_name (const char *prompt1, const char *prompt2) { char *name; int i; for (;;) { name = cpr_get (prompt1, prompt2); if (!name) return NULL; trim_spaces (name); cpr_kill_prompt (); for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++) ; /* The name must be in Latin-1 and not UTF-8 - lacking the code to ensure this we restrict it to ASCII. */ if (name[i]) tty_printf (_("Error: Only plain ASCII is currently allowed.\n")); else if (strchr (name, '<')) tty_printf (_("Error: The \"<\" character may not be used.\n")); else if (strstr (name, " ")) tty_printf (_("Error: Double spaces are not allowed.\n")); else return name; xfree (name); } } static int change_name (void) { char *surname = NULL, *givenname = NULL; char *isoname, *p; int rc; surname = get_one_name ("keygen.smartcard.surname", _("Cardholder's surname: ")); givenname = get_one_name ("keygen.smartcard.givenname", _("Cardholder's given name: ")); if (!surname || !givenname || (!*surname && !*givenname)) { xfree (surname); xfree (givenname); return -1; /*canceled*/ } isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1); strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname); xfree (surname); xfree (givenname); for (p=isoname; *p; p++) if (*p == ' ') *p = '<'; if (strlen (isoname) > 39 ) { tty_printf (_("Error: Combined name too long " "(limit is %d characters).\n"), 39); xfree (isoname); return -1; } rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname), NULL ); if (rc) log_error ("error setting Name: %s\n", gpg_strerror (rc)); xfree (isoname); return rc; } static int change_url (void) { char *url; int rc; url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: ")); if (!url) return -1; trim_spaces (url); cpr_kill_prompt (); if (strlen (url) > 254 ) { tty_printf (_("Error: URL too long " "(limit is %d characters).\n"), 254); xfree (url); return -1; } rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url), NULL ); if (rc) log_error ("error setting URL: %s\n", gpg_strerror (rc)); xfree (url); write_sc_op_status (rc); return rc; } /* Fetch the key from the URL given on the card or try to get it from the default keyserver. */ static int fetch_url(void) { int rc; struct agent_card_info_s info; memset(&info,0,sizeof(info)); rc=agent_scd_getattr("PUBKEY-URL",&info); if(rc) log_error("error retrieving URL from card: %s\n",gpg_strerror(rc)); else { struct keyserver_spec *spec=NULL; rc=agent_scd_getattr("KEY-FPR",&info); if(rc) log_error("error retrieving key fingerprint from card: %s\n", gpg_strerror(rc)); else if (info.pubkey_url && *info.pubkey_url) { spec=parse_keyserver_uri(info.pubkey_url,1,NULL,0); if(spec && info.fpr1valid) { /* This is not perfectly right. Currently, all card fingerprints are 20 digits, but what about fingerprints for a future v5 key? We should get the length from somewhere lower in the code. In any event, the fpr/keyid is not meaningful for straight HTTP fetches, but using it allows the card to point to HKP and LDAP servers as well. */ rc=keyserver_import_fprint(info.fpr1,20,spec); free_keyserver_spec(spec); } } else if (info.fpr1valid) { rc = keyserver_import_fprint (info.fpr1, 20, opt.keyserver); } } return rc; } /* Read data from file FNAME up to MAXLEN characters. On error return -1 and store NULL at R_BUFFER; on success return the number of bytes read and store the address of a newly allocated buffer at R_BUFFER. */ static int get_data_from_file (const char *fname, size_t maxlen, char **r_buffer) { - FILE *fp; + estream_t fp; char *data; int n; *r_buffer = NULL; - fp = fopen (fname, "rb"); + fp = es_fopen (fname, "rb"); #if GNUPG_MAJOR_VERSION == 1 if (fp && is_secured_file (fileno (fp))) { fclose (fp); fp = NULL; errno = EPERM; } #endif if (!fp) { tty_printf (_("can't open `%s': %s\n"), fname, strerror (errno)); return -1; } data = xtrymalloc (maxlen? maxlen:1); if (!data) { tty_printf (_("error allocating enough memory: %s\n"), strerror (errno)); - fclose (fp); + es_fclose (fp); return -1; } if (maxlen) - n = fread (data, 1, maxlen, fp); + n = es_fread (data, 1, maxlen, fp); else n = 0; - fclose (fp); + es_fclose (fp); if (n < 0) { tty_printf (_("error reading `%s': %s\n"), fname, strerror (errno)); xfree (data); return -1; } *r_buffer = data; return n; } /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on success. */ static int put_data_to_file (const char *fname, const void *buffer, size_t length) { - FILE *fp; + estream_t fp; - fp = fopen (fname, "wb"); + fp = es_fopen (fname, "wb"); #if GNUPG_MAJOR_VERSION == 1 if (fp && is_secured_file (fileno (fp))) { fclose (fp); fp = NULL; errno = EPERM; } #endif if (!fp) { tty_printf (_("can't create `%s': %s\n"), fname, strerror (errno)); return -1; } - if (length && fwrite (buffer, length, 1, fp) != 1) + if (length && es_fwrite (buffer, length, 1, fp) != 1) { tty_printf (_("error writing `%s': %s\n"), fname, strerror (errno)); - fclose (fp); + es_fclose (fp); return -1; } - fclose (fp); + es_fclose (fp); return 0; } static int change_login (const char *args) { char *data; int n; int rc; if (args && *args == '<') /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, 254, &data); if (n < 0) return -1; } else { data = cpr_get ("cardedit.change_login", _("Login data (account name): ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); n = strlen (data); } if (n > 254 ) { tty_printf (_("Error: Login data too long " "(limit is %d characters).\n"), 254); xfree (data); return -1; } rc = agent_scd_setattr ("LOGIN-DATA", data, n, NULL ); if (rc) log_error ("error setting login data: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_private_do (const char *args, int nr) { char do_name[] = "PRIVATE-DO-X"; char *data; int n; int rc; assert (nr >= 1 && nr <= 4); do_name[11] = '0' + nr; if (args && (args = strchr (args, '<'))) /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, 254, &data); if (n < 0) return -1; } else { data = cpr_get ("cardedit.change_private_do", _("Private DO data: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); n = strlen (data); } if (n > 254 ) { tty_printf (_("Error: Private DO too long " "(limit is %d characters).\n"), 254); xfree (data); return -1; } rc = agent_scd_setattr (do_name, data, n, NULL ); if (rc) log_error ("error setting private DO: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_cert (const char *args) { char *data; int n; int rc; if (args && *args == '<') /* Read it from a file */ { for (args++; spacep (args); args++) ; n = get_data_from_file (args, 16384, &data); if (n < 0) return -1; } else { tty_printf ("usage error: redirection to file required\n"); return -1; } rc = agent_scd_writecert ("OPENPGP.3", data, n); if (rc) log_error ("error writing certificate to card: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int read_cert (const char *args) { const char *fname; void *buffer; size_t length; int rc; if (args && *args == '>') /* Write it to a file */ { for (args++; spacep (args); args++) ; fname = args; } else { tty_printf ("usage error: redirection to file required\n"); return -1; } rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length); if (rc) log_error ("error reading certificate from card: %s\n", gpg_strerror (rc)); else rc = put_data_to_file (fname, buffer, length); xfree (buffer); write_sc_op_status (rc); return rc; } static int change_lang (void) { char *data, *p; int rc; data = cpr_get ("cardedit.change_lang", _("Language preferences: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); if (strlen (data) > 8 || (strlen (data) & 1)) { tty_printf (_("Error: invalid length of preference string.\n")); xfree (data); return -1; } for (p=data; *p && *p >= 'a' && *p <= 'z'; p++) ; if (*p) { tty_printf (_("Error: invalid characters in preference string.\n")); xfree (data); return -1; } rc = agent_scd_setattr ("DISP-LANG", data, strlen (data), NULL ); if (rc) log_error ("error setting lang: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_sex (void) { char *data; const char *str; int rc; data = cpr_get ("cardedit.change_sex", _("Sex ((M)ale, (F)emale or space): ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); if (!*data) str = "9"; else if ((*data == 'M' || *data == 'm') && !data[1]) str = "1"; else if ((*data == 'F' || *data == 'f') && !data[1]) str = "2"; else { tty_printf (_("Error: invalid response.\n")); xfree (data); return -1; } rc = agent_scd_setattr ("DISP-SEX", str, 1, NULL ); if (rc) log_error ("error setting sex: %s\n", gpg_strerror (rc)); xfree (data); write_sc_op_status (rc); return rc; } static int change_cafpr (int fprno) { char *data; const char *s; int i, c, rc; unsigned char fpr[20]; data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: ")); if (!data) return -1; trim_spaces (data); cpr_kill_prompt (); for (i=0, s=data; i < 20 && *s; ) { while (spacep(s)) s++; if (*s == ':') s++; while (spacep(s)) s++; c = hextobyte (s); if (c == -1) break; fpr[i++] = c; s += 2; } xfree (data); if (i != 20 || *s) { tty_printf (_("Error: invalid formatted fingerprint.\n")); return -1; } rc = agent_scd_setattr (fprno==1?"CA-FPR-1": fprno==2?"CA-FPR-2": fprno==3?"CA-FPR-3":"x", fpr, 20, NULL ); if (rc) log_error ("error setting cafpr: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); return rc; } static void toggle_forcesig (void) { struct agent_card_info_s info; int rc; int newstate; memset (&info, 0, sizeof info); rc = agent_scd_getattr ("CHV-STATUS", &info); if (rc) { log_error ("error getting current status: %s\n", gpg_strerror (rc)); return; } newstate = !info.chv1_cached; agent_release_card_info (&info); rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1, NULL); if (rc) log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); } /* Helper for the key generation/edit functions. */ static int get_info_for_key_operation (struct agent_card_info_s *info) { int rc; memset (info, 0, sizeof *info); rc = agent_scd_getattr ("SERIALNO", info); if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12) || strlen (info->serialno) != 32 ) { log_error (_("key operation not possible: %s\n"), rc ? gpg_strerror (rc) : _("not an OpenPGP card")); return rc? rc: -1; } rc = agent_scd_getattr ("KEY-FPR", info); if (!rc) rc = agent_scd_getattr ("CHV-STATUS", info); if (!rc) rc = agent_scd_getattr ("DISP-NAME", info); if (!rc) rc = agent_scd_getattr ("EXTCAP", info); if (!rc) rc = agent_scd_getattr ("KEY-ATTR", info); if (rc) log_error (_("error getting current key info: %s\n"), gpg_strerror (rc)); return rc; } /* Helper for the key generation/edit functions. */ static int check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1) { int rc = 0; agent_clear_pin_cache (info->serialno); *forced_chv1 = !info->chv1_cached; if (*forced_chv1) { /* Switch off the forced mode so that during key generation we don't get bothered with PIN queries for each self-signature. */ rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1, info->serialno); if (rc) { log_error ("error clearing forced signature PIN flag: %s\n", gpg_strerror (rc)); *forced_chv1 = 0; } } if (!rc) { /* Check the PIN now, so that we won't get asked later for each binding signature. */ rc = agent_scd_checkpin (info->serialno); if (rc) { log_error ("error checking the PIN: %s\n", gpg_strerror (rc)); write_sc_op_status (rc); } } return rc; } /* Helper for the key generation/edit functions. */ static void restore_forced_chv1 (int *forced_chv1) { int rc; if (*forced_chv1) { /* Switch back to forced state. */ rc = agent_scd_setattr ("CHV-STATUS-1", "", 1, NULL); if (rc) { log_error ("error setting forced signature PIN flag: %s\n", gpg_strerror (rc)); } } } /* Helper for the key generation/edit functions. */ static void show_card_key_info (struct agent_card_info_s *info) { tty_fprintf (NULL, "Signature key ....:"); print_sha1_fpr (NULL, info->fpr1valid? info->fpr1:NULL); tty_fprintf (NULL, "Encryption key....:"); print_sha1_fpr (NULL, info->fpr2valid? info->fpr2:NULL); tty_fprintf (NULL, "Authentication key:"); print_sha1_fpr (NULL, info->fpr3valid? info->fpr3:NULL); tty_printf ("\n"); } /* Helper for the key generation/edit functions. */ static int replace_existing_key_p (struct agent_card_info_s *info, int keyno) { assert (keyno >= 0 && keyno <= 3); if ((keyno == 1 && info->fpr1valid) || (keyno == 2 && info->fpr2valid) || (keyno == 3 && info->fpr3valid)) { tty_printf ("\n"); log_info ("WARNING: such a key has already been stored on the card!\n"); tty_printf ("\n"); if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key", _("Replace existing key? (y/N) "))) return -1; } return 0; } static void show_keysize_warning (void) { static int shown; if (shown) return; shown = 1; tty_printf (_("NOTE: There is no guarantee that the card " "supports the requested size.\n" " If the key generation does not succeed, " "please check the\n" " documentation of your card to see what " "sizes are allowed.\n")); } /* Ask for the size of a card key. NBITS is the current size configured for the card. KEYNO is the number of the key used to select the prompt. Returns 0 to use the default size (i.e. NBITS) or the selected size. */ static unsigned int ask_card_keysize (int keyno, unsigned int nbits) { unsigned int min_nbits = 1024; unsigned int max_nbits = 3072; /* GnuPG limit due to Assuan. */ char *prompt, *answer; unsigned int req_nbits; for (;;) { prompt = xasprintf (keyno == 0? _("What keysize do you want for the Signature key? (%u) "): keyno == 1? _("What keysize do you want for the Encryption key? (%u) "): _("What keysize do you want for the Authentication key? (%u) "), nbits); answer = cpr_get ("cardedit.genkeys.size", prompt); cpr_kill_prompt (); req_nbits = *answer? atoi (answer): nbits; xfree (prompt); xfree (answer); if (req_nbits != nbits && (req_nbits % 32) ) { req_nbits = ((req_nbits + 31) / 32) * 32; tty_printf (_("rounded up to %u bits\n"), req_nbits); } if (req_nbits == nbits) return 0; /* Use default. */ if (req_nbits < min_nbits || req_nbits > max_nbits) { tty_printf (_("%s keysizes must be in the range %u-%u\n"), "RSA", min_nbits, max_nbits); } else { tty_printf (_("The card will now be re-configured " "to generate a key of %u bits\n"), req_nbits); show_keysize_warning (); return req_nbits; } } } /* Change the size of key KEYNO (0..2) to NBITS and show an error message if that fails. */ static gpg_error_t do_change_keysize (int keyno, unsigned int nbits) { gpg_error_t err; char args[100]; snprintf (args, sizeof args, "--force %d 1 %u", keyno+1, nbits); err = agent_scd_setattr ("KEY-ATTR", args, strlen (args), NULL); if (err) log_error (_("error changing size of key %d to %u bits: %s\n"), keyno+1, nbits, gpg_strerror (err)); return err; } static void generate_card_keys (void) { struct agent_card_info_s info; int forced_chv1; int want_backup; int keyno; if (get_info_for_key_operation (&info)) return; if (info.extcap.ki) { char *answer; answer = cpr_get ("cardedit.genkeys.backup_enc", _("Make off-card backup of encryption key? (Y/n) ")); want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/); cpr_kill_prompt (); xfree (answer); } else want_backup = 0; if ( (info.fpr1valid && !fpr_is_zero (info.fpr1)) || (info.fpr2valid && !fpr_is_zero (info.fpr2)) || (info.fpr3valid && !fpr_is_zero (info.fpr3))) { tty_printf ("\n"); log_info (_("NOTE: keys are already stored on the card!\n")); tty_printf ("\n"); if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys", _("Replace existing keys? (y/N) "))) { agent_release_card_info (&info); return; } } /* If no displayed name has been set, we assume that this is a fresh card and print a hint about the default PINs. */ if (!info.disp_name || !*info.disp_name) { tty_printf ("\n"); tty_printf (_("Please note that the factory settings of the PINs are\n" " PIN = `%s' Admin PIN = `%s'\n" "You should change them using the command --change-pin\n"), "123456", "12345678"); tty_printf ("\n"); } if (check_pin_for_key_operation (&info, &forced_chv1)) goto leave; /* If the cards features changeable key attributes, we ask for the key size. */ if (info.is_v2 && info.extcap.aac) { unsigned int nbits; for (keyno = 0; keyno < DIM (info.key_attr); keyno++) { nbits = ask_card_keysize (keyno, info.key_attr[keyno].nbits); if (nbits && do_change_keysize (keyno, nbits)) { /* Error: Better read the default key size again. */ agent_release_card_info (&info); if (get_info_for_key_operation (&info)) goto leave; /* Ask again for this key size. */ keyno--; } } /* Note that INFO has not be synced. However we will only use the serialnumber and thus it won't harm. */ } generate_keypair (NULL, info.serialno, want_backup? opt.homedir:NULL); leave: agent_release_card_info (&info); restore_forced_chv1 (&forced_chv1); } /* This function is used by the key edit menu to generate an arbitrary subkey. */ int card_generate_subkey (KBNODE pub_keyblock, KBNODE sec_keyblock) { struct agent_card_info_s info; int okay = 0; int forced_chv1 = 0; int keyno; if (get_info_for_key_operation (&info)) return 0; show_card_key_info (&info); tty_printf (_("Please select the type of key to generate:\n")); tty_printf (_(" (1) Signature key\n")); tty_printf (_(" (2) Encryption key\n")); tty_printf (_(" (3) Authentication key\n")); for (;;) { char *answer = cpr_get ("cardedit.genkeys.subkeytype", _("Your selection? ")); cpr_kill_prompt(); if (*answer == CONTROL_D) { xfree (answer); goto leave; } keyno = *answer? atoi(answer): 0; xfree(answer); if (keyno >= 1 && keyno <= 3) break; /* Okay. */ tty_printf(_("Invalid selection.\n")); } if (replace_existing_key_p (&info, keyno)) goto leave; if (check_pin_for_key_operation (&info, &forced_chv1)) goto leave; /* If the cards features changeable key attributes, we ask for the key size. */ if (info.is_v2 && info.extcap.aac) { unsigned int nbits; ask_again: nbits = ask_card_keysize (keyno-1, info.key_attr[keyno-1].nbits); if (nbits && do_change_keysize (keyno-1, nbits)) { /* Error: Better read the default key size again. */ agent_release_card_info (&info); if (get_info_for_key_operation (&info)) goto leave; goto ask_again; } /* Note that INFO has not be synced. However we will only use the serialnumber and thus it won't harm. */ } okay = generate_card_subkeypair (pub_keyblock, sec_keyblock, keyno, info.serialno); leave: agent_release_card_info (&info); restore_forced_chv1 (&forced_chv1); return okay; } /* Store the key at NODE into the smartcard and modify NODE to carry the serialno stuff instead of the actual secret key parameters. USE is the usage for that key; 0 means any usage. */ int card_store_subkey (KBNODE node, int use) { struct agent_card_info_s info; int okay = 0; int rc; int keyno, i; PKT_secret_key *copied_sk = NULL; PKT_secret_key *sk; size_t n; const char *s; int allow_keyno[3]; unsigned int nbits; assert (node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY); sk = node->pkt->pkt.secret_key; if (get_info_for_key_operation (&info)) return 0; if (!info.extcap.ki) { tty_printf ("The card does not support the import of keys\n"); tty_printf ("\n"); goto leave; } show_card_key_info (&info); nbits = nbits_from_sk (sk); if (!is_RSA (sk->pubkey_algo) || (!info.is_v2 && nbits != 1024) ) { tty_printf ("You may only store a 1024 bit RSA key on the card\n"); tty_printf ("\n"); goto leave; } allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG))); allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC))); allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH))); tty_printf (_("Please select where to store the key:\n")); if (allow_keyno[0]) tty_printf (_(" (1) Signature key\n")); if (allow_keyno[1]) tty_printf (_(" (2) Encryption key\n")); if (allow_keyno[2]) tty_printf (_(" (3) Authentication key\n")); for (;;) { char *answer = cpr_get ("cardedit.genkeys.storekeytype", _("Your selection? ")); cpr_kill_prompt(); if (*answer == CONTROL_D || !*answer) { xfree (answer); goto leave; } keyno = *answer? atoi(answer): 0; xfree(answer); if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1]) { if (info.is_v2 && !info.extcap.aac && info.key_attr[keyno-1].nbits != nbits) { tty_printf ("Key does not match the card's capability.\n"); } else break; /* Okay. */ } else tty_printf(_("Invalid selection.\n")); } if (replace_existing_key_p (&info, keyno)) goto leave; /* Unprotect key. */ switch (is_secret_key_protected (sk) ) { case 0: /* Not protected. */ break; case -1: log_error (_("unknown key protection algorithm\n")); goto leave; default: if (sk->protect.s2k.mode == 1001) { log_error (_("secret parts of key are not available\n")); goto leave; } if (sk->protect.s2k.mode == 1002) { log_error (_("secret key already stored on a card\n")); goto leave; } /* We better copy the key before we unprotect it. */ copied_sk = sk = copy_secret_key (NULL, sk); rc = check_secret_key (sk, 0); if (rc) goto leave; } rc = save_unprotected_key_to_card (sk, keyno); if (rc) { log_error (_("error writing key to card: %s\n"), gpg_strerror (rc)); goto leave; } /* Get back to the maybe protected original secret key. */ if (copied_sk) { free_secret_key (copied_sk); copied_sk = NULL; } sk = node->pkt->pkt.secret_key; /* Get rid of the secret key parameters and store the serial numer. */ n = pubkey_get_nskey (sk->pubkey_algo); for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++) { gcry_mpi_release (sk->skey[i]); sk->skey[i] = NULL; } i = pubkey_get_npkey (sk->pubkey_algo); sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8); sk->is_protected = 1; sk->protect.s2k.mode = 1002; s = info.serialno; for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1]; sk->protect.ivlen++, s += 2) sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s); okay = 1; leave: if (copied_sk) free_secret_key (copied_sk); agent_release_card_info (&info); return okay; } /* Data used by the command parser. This needs to be outside of the function scope to allow readline based command completion. */ enum cmdids { cmdNOP = 0, cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY, cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR, cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT, cmdREADCERT, cmdUNBLOCK, cmdINVCMD }; static struct { const char *name; enum cmdids id; int admin_only; const char *desc; } cmds[] = { { "quit" , cmdQUIT , 0, N_("quit this menu")}, { "q" , cmdQUIT , 0, NULL }, { "admin" , cmdADMIN , 0, N_("show admin commands")}, { "help" , cmdHELP , 0, N_("show this help")}, { "?" , cmdHELP , 0, NULL }, { "list" , cmdLIST , 0, N_("list all available data")}, { "l" , cmdLIST , 0, NULL }, { "debug" , cmdDEBUG , 0, NULL }, { "name" , cmdNAME , 1, N_("change card holder's name")}, { "url" , cmdURL , 1, N_("change URL to retrieve key")}, { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")}, { "login" , cmdLOGIN , 1, N_("change the login name")}, { "lang" , cmdLANG , 1, N_("change the language preferences")}, { "sex" , cmdSEX , 1, N_("change card holder's sex")}, { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")}, { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")}, { "generate", cmdGENERATE, 1, N_("generate new keys")}, { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")}, { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")}, { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code") }, /* Note, that we do not announce these command yet. */ { "privatedo", cmdPRIVATEDO, 0, NULL }, { "readcert", cmdREADCERT, 0, NULL }, { "writecert", cmdWRITECERT, 1, NULL }, { NULL, cmdINVCMD, 0, NULL } }; #ifdef HAVE_LIBREADLINE /* These two functions are used by readline for command completion. */ static char * command_generator(const char *text,int state) { static int list_index,len; const char *name; /* If this is a new word to complete, initialize now. This includes saving the length of TEXT for efficiency, and initializing the index variable to 0. */ if(!state) { list_index=0; len=strlen(text); } /* Return the next partial match */ while((name=cmds[list_index].name)) { /* Only complete commands that have help text */ if(cmds[list_index++].desc && strncmp(name,text,len)==0) return strdup(name); } return NULL; } static char ** card_edit_completion(const char *text, int start, int end) { (void)end; /* If we are at the start of a line, we try and command-complete. If not, just do nothing for now. */ if(start==0) return rl_completion_matches(text,command_generator); rl_attempted_completion_over=1; return NULL; } #endif /*HAVE_LIBREADLINE*/ /* Menu to edit all user changeable values on an OpenPGP card. Only Key creation is not handled here. */ void card_edit (strlist_t commands) { enum cmdids cmd = cmdNOP; int have_commands = !!commands; int redisplay = 1; char *answer = NULL; int allow_admin=0; char serialnobuf[50]; if (opt.command_fd != -1) ; else if (opt.batch && !have_commands) { log_error(_("can't do this in batch mode\n")); goto leave; } for (;;) { int arg_number; const char *arg_string = ""; const char *arg_rest = ""; char *p; int i; int cmd_admin_only; tty_printf("\n"); if (redisplay ) { if (opt.with_colons) { - card_status (stdout, serialnobuf, DIM (serialnobuf)); + card_status (es_stdout, serialnobuf, DIM (serialnobuf)); fflush (stdout); } else { card_status (NULL, serialnobuf, DIM (serialnobuf)); tty_printf("\n"); } redisplay = 0; } do { xfree (answer); if (have_commands) { if (commands) { answer = xstrdup (commands->d); commands = commands->next; } else if (opt.batch) { answer = xstrdup ("quit"); } else have_commands = 0; } if (!have_commands) { tty_enable_completion (card_edit_completion); answer = cpr_get_no_help("cardedit.prompt", _("gpg/card> ")); cpr_kill_prompt(); tty_disable_completion (); } trim_spaces(answer); } while ( *answer == '#' ); arg_number = 0; /* Yes, here is the init which egcc complains about */ cmd_admin_only = 0; if (!*answer) cmd = cmdLIST; /* Default to the list command */ else if (*answer == CONTROL_D) cmd = cmdQUIT; else { if ((p=strchr (answer,' '))) { *p++ = 0; trim_spaces (answer); trim_spaces (p); arg_number = atoi(p); arg_string = p; arg_rest = p; while (digitp (arg_rest)) arg_rest++; while (spacep (arg_rest)) arg_rest++; } for (i=0; cmds[i].name; i++ ) if (!ascii_strcasecmp (answer, cmds[i].name )) break; cmd = cmds[i].id; cmd_admin_only = cmds[i].admin_only; } if (!allow_admin && cmd_admin_only) { tty_printf ("\n"); tty_printf (_("Admin-only command\n")); continue; } switch (cmd) { case cmdHELP: for (i=0; cmds[i].name; i++ ) if(cmds[i].desc && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin))) tty_printf("%-10s %s\n", cmds[i].name, _(cmds[i].desc) ); break; case cmdADMIN: if ( !strcmp (arg_string, "on") ) allow_admin = 1; else if ( !strcmp (arg_string, "off") ) allow_admin = 0; else if ( !strcmp (arg_string, "verify") ) { /* Force verification of the Admin Command. However, this is only done if the retry counter is at initial state. */ char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1); strcpy (stpcpy (tmp, serialnobuf), "[CHV3]"); allow_admin = !agent_scd_checkpin (tmp); xfree (tmp); } else /* Toggle. */ allow_admin=!allow_admin; if(allow_admin) tty_printf(_("Admin commands are allowed\n")); else tty_printf(_("Admin commands are not allowed\n")); break; case cmdVERIFY: agent_scd_checkpin (serialnobuf); redisplay = 1; break; case cmdLIST: redisplay = 1; break; case cmdNAME: change_name (); break; case cmdURL: change_url (); break; case cmdFETCH: fetch_url(); break; case cmdLOGIN: change_login (arg_string); break; case cmdLANG: change_lang (); break; case cmdSEX: change_sex (); break; case cmdCAFPR: if ( arg_number < 1 || arg_number > 3 ) tty_printf ("usage: cafpr N\n" " 1 <= N <= 3\n"); else change_cafpr (arg_number); break; case cmdPRIVATEDO: if ( arg_number < 1 || arg_number > 4 ) tty_printf ("usage: privatedo N\n" " 1 <= N <= 4\n"); else change_private_do (arg_string, arg_number); break; case cmdWRITECERT: if ( arg_number != 3 ) tty_printf ("usage: writecert 3 < FILE\n"); else change_cert (arg_rest); break; case cmdREADCERT: if ( arg_number != 3 ) tty_printf ("usage: readcert 3 > FILE\n"); else read_cert (arg_rest); break; case cmdFORCESIG: toggle_forcesig (); break; case cmdGENERATE: generate_card_keys (); break; case cmdPASSWD: change_pin (0, allow_admin); break; case cmdUNBLOCK: change_pin (1, allow_admin); break; case cmdQUIT: goto leave; case cmdNOP: break; case cmdINVCMD: default: tty_printf ("\n"); tty_printf (_("Invalid command (try \"help\")\n")); break; } /* End command switch. */ } /* End of main menu loop. */ leave: xfree (answer); } diff --git a/g10/gpg.c b/g10/gpg.c index b24157b29..e365a8b8d 100644 --- a/g10/gpg.c +++ b/g10/gpg.c @@ -1,4390 +1,4392 @@ /* gpg.c - The GnuPG utility (main for gpg) * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, * 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #ifdef HAVE_STAT #include /* for stat() */ #endif #include #ifdef HAVE_W32_SYSTEM #include #endif #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include #include "packet.h" #include "../common/iobuf.h" #include "util.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "cipher.h" #include "filter.h" #include "ttyio.h" #include "i18n.h" #include "sysutils.h" #include "status.h" #include "keyserver-internal.h" #include "exec.h" #include "gc-opt-flags.h" #include "asshelp.h" #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__) #define MY_O_BINARY O_BINARY #ifndef S_IRGRP # define S_IRGRP 0 # define S_IWGRP 0 #endif #else #define MY_O_BINARY 0 #endif enum cmd_and_opt_values { aNull = 0, oArmor = 'a', aDetachedSign = 'b', aSym = 'c', aDecrypt = 'd', aEncr = 'e', oInteractive = 'i', aListKeys = 'k', oDryRun = 'n', oOutput = 'o', oQuiet = 'q', oRecipient = 'r', oHiddenRecipient = 'R', aSign = 's', oTextmodeShort= 't', oLocalUser = 'u', oVerbose = 'v', oCompress = 'z', oSetNotation = 'N', aListSecretKeys = 'K', oBatch = 500, oMaxOutput, oSigNotation, oCertNotation, oShowNotation, oNoShowNotation, aEncrFiles, aEncrSym, aDecryptFiles, aClearsign, aStore, aKeygen, aSignEncr, aSignEncrSym, aSignSym, aSignKey, aLSignKey, aListConfig, aGPGConfList, aGPGConfTest, aListPackets, aEditKey, aDeleteKeys, aDeleteSecretKeys, aDeleteSecretAndPublicKeys, aImport, aFastImport, aVerify, aVerifyFiles, aListSigs, aSendKeys, aRecvKeys, aLocateKeys, aSearchKeys, aRefreshKeys, aFetchKeys, aExport, aExportSecret, aExportSecretSub, aCheckKeys, aGenRevoke, aDesigRevoke, aPrimegen, aPrintMD, aPrintMDs, aCheckTrustDB, aUpdateTrustDB, aFixTrustDB, aListTrustDB, aListTrustPath, aExportOwnerTrust, aImportOwnerTrust, aDeArmor, aEnArmor, aGenRandom, aRebuildKeydbCaches, aCardStatus, aCardEdit, aChangePIN, aPasswd, aServer, oTextmode, oNoTextmode, oExpert, oNoExpert, oDefSigExpire, oAskSigExpire, oNoAskSigExpire, oDefCertExpire, oAskCertExpire, oNoAskCertExpire, oDefCertLevel, oMinCertLevel, oAskCertLevel, oNoAskCertLevel, oFingerprint, oWithFingerprint, oAnswerYes, oAnswerNo, oKeyring, oPrimaryKeyring, oSecretKeyring, oShowKeyring, oDefaultKey, oDefRecipient, oDefRecipientSelf, oNoDefRecipient, oOptions, oDebug, oDebugLevel, oDebugAll, oDebugCCIDDriver, oStatusFD, oStatusFile, oAttributeFD, oAttributeFile, oEmitVersion, oNoEmitVersion, oCompletesNeeded, oMarginalsNeeded, oMaxCertDepth, oLoadExtension, oGnuPG, oRFC1991, oRFC2440, oRFC4880, oOpenPGP, oPGP2, oPGP6, oPGP7, oPGP8, oRFC2440Text, oNoRFC2440Text, oCipherAlgo, oDigestAlgo, oCertDigestAlgo, oCompressAlgo, oCompressLevel, oBZ2CompressLevel, oBZ2DecompressLowmem, oPassphrase, oPassphraseFD, oPassphraseFile, oPassphraseRepeat, oCommandFD, oCommandFile, oQuickRandom, oNoVerbose, oTrustDBName, oNoSecmemWarn, oRequireSecmem, oNoRequireSecmem, oNoPermissionWarn, oNoMDCWarn, oNoArmor, oNoDefKeyring, oNoGreeting, oNoTTY, oNoOptions, oNoBatch, oHomedir, oWithColons, oWithKeyData, oWithSigList, oWithSigCheck, oSkipVerify, oSkipHiddenRecipients, oNoSkipHiddenRecipients, oCompressKeys, oCompressSigs, oAlwaysTrust, oTrustModel, oForceOwnertrust, oSetFilename, oForYourEyesOnly, oNoForYourEyesOnly, oSetPolicyURL, oSigPolicyURL, oCertPolicyURL, oShowPolicyURL, oNoShowPolicyURL, oSigKeyserverURL, oUseEmbeddedFilename, oNoUseEmbeddedFilename, oComment, oDefaultComment, oNoComments, oThrowKeyids, oNoThrowKeyids, oShowPhotos, oNoShowPhotos, oPhotoViewer, oForceV3Sigs, oNoForceV3Sigs, oForceV4Certs, oNoForceV4Certs, oForceMDC, oNoForceMDC, oDisableMDC, oNoDisableMDC, oS2KMode, oS2KDigest, oS2KCipher, oS2KCount, oSimpleSKChecksum, oDisplayCharset, oNotDashEscaped, oEscapeFrom, oNoEscapeFrom, oLockOnce, oLockMultiple, oLockNever, oKeyServer, oKeyServerOptions, oImportOptions, oExportOptions, oListOptions, oVerifyOptions, oTempDir, oExecPath, oEncryptTo, oHiddenEncryptTo, oNoEncryptTo, oLoggerFD, oLoggerFile, oUtf8Strings, oNoUtf8Strings, oDisableCipherAlgo, oDisablePubkeyAlgo, oAllowNonSelfsignedUID, oNoAllowNonSelfsignedUID, oAllowFreeformUID, oNoAllowFreeformUID, oAllowSecretKeyImport, oEnableSpecialFilenames, oNoLiteral, oSetFilesize, oHonorHttpProxy, oFastListMode, oListOnly, oIgnoreTimeConflict, oIgnoreValidFrom, oIgnoreCrcError, oIgnoreMDCError, oShowSessionKey, oOverrideSessionKey, oNoRandomSeedFile, oAutoKeyRetrieve, oNoAutoKeyRetrieve, oUseAgent, oNoUseAgent, oGpgAgentInfo, oMergeOnly, oTryAllSecrets, oTrustedKey, oNoExpensiveTrustChecks, oFixedListMode, oNoSigCache, oNoSigCreateCheck, oAutoCheckTrustDB, oNoAutoCheckTrustDB, oPreservePermissions, oDefaultPreferenceList, oDefaultKeyserverURL, oPersonalCipherPreferences, oPersonalDigestPreferences, oPersonalCompressPreferences, oAgentProgram, oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages, oXauthority, oGroup, oUnGroup, oNoGroups, oStrict, oNoStrict, oMangleDosFilenames, oNoMangleDosFilenames, oEnableProgressFilter, oMultifile, oKeyidFormat, oExitOnStatusWriteError, oLimitCardInsertTries, oRequireCrossCert, oNoRequireCrossCert, oAutoKeyLocate, oNoAutoKeyLocate, oAllowMultisigVerification, oEnableDSA2, oDisableDSA2, oAllowMultipleMessages, oNoAllowMultipleMessages, oFakedSystemTime, oNoop }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aSign, "sign", N_("make a signature")), ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")), ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")), ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")), ARGPARSE_c (aEncrFiles, "encrypt-files", "@"), ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")), ARGPARSE_c (aStore, "store", "@"), ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")), ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"), ARGPARSE_c (aVerify, "verify" , N_("verify a signature")), ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ), ARGPARSE_c (aListKeys, "list-keys", N_("list keys")), ARGPARSE_c (aListKeys, "list-public-keys", "@" ), ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")), ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")), ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")), ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")), ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")), ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")), ARGPARSE_c (aDeleteKeys,"delete-keys", N_("remove keys from the public keyring")), ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys", N_("remove keys from the secret keyring")), ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")), ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")), ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")), ARGPARSE_c (aEditKey, "key-edit" ,"@"), ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")), ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ), ARGPARSE_c (aExport, "export" , N_("export keys") ), ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ), ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ), ARGPARSE_c (aSearchKeys, "search-keys" , N_("search for keys on a key server") ), ARGPARSE_c (aRefreshKeys, "refresh-keys", N_("update all keys from a keyserver")), ARGPARSE_c (aLocateKeys, "locate-keys", "@"), ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ), ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ), ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ), ARGPARSE_c (aImport, "import", N_("import/merge keys")), ARGPARSE_c (aFastImport, "fast-import", "@"), #ifdef ENABLE_CARD_SUPPORT ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")), ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")), ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")), #endif ARGPARSE_c (aListConfig, "list-config", "@"), ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ), ARGPARSE_c (aListPackets, "list-packets","@"), ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"), ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"), ARGPARSE_c (aUpdateTrustDB,"update-trustdb", N_("update the trust database")), ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"), ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"), ARGPARSE_c (aDeArmor, "dearmor", "@"), ARGPARSE_c (aDeArmor, "dearmour", "@"), ARGPARSE_c (aEnArmor, "enarmor", "@"), ARGPARSE_c (aEnArmor, "enarmour", "@"), ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")), ARGPARSE_c (aPrimegen, "gen-prime", "@" ), ARGPARSE_c (aGenRandom,"gen-random", "@" ), ARGPARSE_c (aServer, "server", N_("run in server mode")), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")), ARGPARSE_s_n (oArmor, "armour", "@"), ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")), ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"), ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */ ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"), ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"), ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), ARGPARSE_s_s (oTempDir, "temp-directory", "@"), ARGPARSE_s_s (oExecPath, "exec-path", "@"), ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"), ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"), ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"), ARGPARSE_s_s (oLocalUser, "local-user", N_("|USER-ID|use USER-ID to sign or decrypt")), ARGPARSE_s_i (oCompress, NULL, N_("|N|set compress level to N (0 disables)")), ARGPARSE_s_i (oCompressLevel, "compress-level", "@"), ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"), ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"), ARGPARSE_s_n (oTextmodeShort, NULL, "@"), ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")), ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"), ARGPARSE_s_n (oExpert, "expert", "@"), ARGPARSE_s_n (oNoExpert, "no-expert", "@"), ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"), ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"), ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"), ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"), ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"), ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"), ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"), ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"), ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"), ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")), ARGPARSE_p_u (oMaxOutput, "max-output", "@"), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", "@"), ARGPARSE_s_n (oNoTTY, "no-tty", "@"), ARGPARSE_s_n (oForceV3Sigs, "force-v3-sigs", "@"), ARGPARSE_s_n (oNoForceV3Sigs, "no-force-v3-sigs", "@"), ARGPARSE_s_n (oForceV4Certs, "force-v4-certs", "@"), ARGPARSE_s_n (oNoForceV4Certs, "no-force-v4-certs", "@"), ARGPARSE_s_n (oForceMDC, "force-mdc", "@"), ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"), ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"), ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"), ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")), ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")), ARGPARSE_s_n (oUseAgent, "use-agent", "@"), ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"), ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"), ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_n (oAnswerYes, "yes", "@"), ARGPARSE_s_n (oAnswerNo, "no", "@"), ARGPARSE_s_s (oKeyring, "keyring", "@"), ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"), ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"), ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"), ARGPARSE_s_s (oDefaultKey, "default-key", "@"), ARGPARSE_s_s (oKeyServer, "keyserver", "@"), ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"), ARGPARSE_s_s (oImportOptions, "import-options", "@"), ARGPARSE_s_s (oExportOptions, "export-options", "@"), ARGPARSE_s_s (oListOptions, "list-options", "@"), ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"), ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"), ARGPARSE_s_s (oDisplayCharset, "charset", "@"), ARGPARSE_s_s (oOptions, "options", "@"), ARGPARSE_p_u (oDebug, "debug", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_i (oStatusFD, "status-fd", "@"), ARGPARSE_s_s (oStatusFile, "status-file", "@"), ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"), ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"), ARGPARSE_s_n (oNoop, "sk-comments", "@"), ARGPARSE_s_n (oNoop, "no-sk-comments", "@"), ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"), ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"), ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ), ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"), ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */ ARGPARSE_s_n (oGnuPG, "gnupg", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"), ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"), ARGPARSE_s_n (oRFC1991, "rfc1991", "@"), ARGPARSE_s_n (oRFC2440, "rfc2440", "@"), ARGPARSE_s_n (oRFC4880, "rfc4880", "@"), ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")), ARGPARSE_s_n (oPGP2, "pgp2", "@"), ARGPARSE_s_n (oPGP6, "pgp6", "@"), ARGPARSE_s_n (oPGP7, "pgp7", "@"), ARGPARSE_s_n (oPGP8, "pgp8", "@"), ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"), ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"), ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"), ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"), ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"), ARGPARSE_s_i (oS2KCount, "s2k-count", "@"), ARGPARSE_s_n (oSimpleSKChecksum, "simple-sk-checksum", "@"), ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"), ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"), ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"), ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"), ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */ ARGPARSE_s_n (oThrowKeyids, "throw-keyid", "@"), ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"), ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyid", "@"), ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"), ARGPARSE_s_n (oShowPhotos, "show-photos", "@"), ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"), ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"), ARGPARSE_s_s (oSetNotation, "set-notation", "@"), ARGPARSE_s_s (oSetNotation, "notation-data", "@"), /* Alias */ ARGPARSE_s_s (oSigNotation, "sig-notation", "@"), ARGPARSE_s_s (oCertNotation, "cert-notation", "@"), ARGPARSE_group (302, N_( "@\n(See the man page for a complete listing of all commands and options)\n" )), ARGPARSE_group (303, N_("@\nExamples:\n\n" " -se -r Bob [file] sign and encrypt for user Bob\n" " --clearsign [file] make a clear text signature\n" " --detach-sign [file] make a detached signature\n" " --list-keys [names] show keys\n" " --fingerprint [names] show fingerprints\n")), /* More hidden commands and options. */ ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */ ARGPARSE_c (aListTrustDB, "list-trustdb", "@"), /* Not yet used: ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */ ARGPARSE_c (aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys", "@"), ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"), ARGPARSE_s_s (oPassphrase, "passphrase", "@"), ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"), ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"), ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"), ARGPARSE_s_i (oCommandFD, "command-fd", "@"), ARGPARSE_s_s (oCommandFile, "command-file", "@"), ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"), ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"), ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"), ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"), ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"), ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"), ARGPARSE_s_n (oNoArmor, "no-armor", "@"), ARGPARSE_s_n (oNoArmor, "no-armour", "@"), ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_n (oNoOptions, "no-options", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_n (oNoBatch, "no-batch", "@"), ARGPARSE_s_n (oWithColons, "with-colons", "@"), ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"), ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"), ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"), ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */ ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */ ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */ ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"), ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"), ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"), ARGPARSE_s_n (oCompressKeys, "compress-keys", "@"), ARGPARSE_s_n (oCompressSigs, "compress-sigs", "@"), ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */ ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"), ARGPARSE_s_s (oTrustModel, "trust-model", "@"), ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"), ARGPARSE_s_s (oSetFilename, "set-filename", "@"), ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"), ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"), ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"), ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"), ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"), ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"), ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"), ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"), ARGPARSE_s_n (oShowNotation, "show-notation", "@"), ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"), ARGPARSE_s_s (oComment, "comment", "@"), ARGPARSE_s_n (oDefaultComment, "default-comment", "@"), ARGPARSE_s_n (oNoComments, "no-comments", "@"), ARGPARSE_s_n (oEmitVersion, "emit-version", "@"), ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"), ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */ ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"), ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"), ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"), ARGPARSE_s_n (oLockOnce, "lock-once", "@"), ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"), ARGPARSE_s_n (oLockNever, "lock-never", "@"), ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"), ARGPARSE_s_s (oLoggerFile, "log-file", "@"), ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */ ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"), ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"), ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"), ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"), ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"), ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"), ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"), ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"), ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"), ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"), ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"), ARGPARSE_s_n (oNoLiteral, "no-literal", "@"), ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"), ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"), ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"), ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"), ARGPARSE_s_n (oListOnly, "list-only", "@"), ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"), ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"), ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"), ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"), ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"), ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"), ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"), ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"), ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"), ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"), ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"), ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"), ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"), ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ), ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"), ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"), ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"), ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"), ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"), ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"), ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"), ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"), ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"), ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-preferences", "@"), ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"), /* Aliases. I constantly mistype these, and assume other people do as well. */ ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"), ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"), ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDisplay, "display", "@"), ARGPARSE_s_s (oTTYname, "ttyname", "@"), ARGPARSE_s_s (oTTYtype, "ttytype", "@"), ARGPARSE_s_s (oLCctype, "lc-ctype", "@"), ARGPARSE_s_s (oLCmessages, "lc-messages","@"), ARGPARSE_s_s (oXauthority, "xauthority", "@"), ARGPARSE_s_s (oGroup, "group", "@"), ARGPARSE_s_s (oUnGroup, "ungroup", "@"), ARGPARSE_s_n (oNoGroups, "no-groups", "@"), ARGPARSE_s_n (oStrict, "strict", "@"), ARGPARSE_s_n (oNoStrict, "no-strict", "@"), ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"), ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"), ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"), ARGPARSE_s_n (oMultifile, "multifile", "@"), ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"), ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"), ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"), ARGPARSE_s_n (oAllowMultisigVerification, "allow-multisig-verification", "@"), ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"), ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"), ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"), ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"), /* These two are aliases to help users of the PGP command line product use gpg with minimal pain. Many commands are common already as they seem to have borrowed commands from us. Now I'm returning the favor. */ ARGPARSE_s_s (oLocalUser, "sign-with", "@"), ARGPARSE_s_s (oRecipient, "user", "@"), ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"), ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"), ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"), ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"), /* New options. Fixme: Should go more to the top. */ ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"), ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"), ARGPARSE_end () }; #ifdef ENABLE_SELINUX_HACKS #define ALWAYS_ADD_KEYRINGS 1 #else #define ALWAYS_ADD_KEYRINGS 0 #endif int g10_errors_seen = 0; static int utf8_strings = 0; static int maybe_setuid = 1; static char *build_list( const char *text, char letter, const char *(*mapf)(int), int (*chkf)(int) ); static void set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd ); static void print_mds( const char *fname, int algo ); static void add_notation_data( const char *string, int which ); static void add_policy_url( const char *string, int which ); static void add_keyserver_url( const char *string, int which ); static void emergency_cleanup (void); static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; if (maybe_setuid) { gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ maybe_setuid = 0; } s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } static const char * my_strusage( int level ) { static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry; const char *p; switch( level ) { case 11: p = "gpg (GnuPG)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; #ifdef IS_DEVELOPMENT_VERSION case 25: p="NOTE: THIS IS A DEVELOPMENT VERSION!"; break; case 26: p="It is only intended for test purposes and should NOT be"; break; case 27: p="used in a production environment or with production keys!"; break; #endif case 1: case 40: p = _("Usage: gpg [options] [files] (-h for help)"); break; case 41: p = _("Syntax: gpg [options] [files]\n" "sign, check, encrypt or decrypt\n" "default operation depends on the input data\n"); break; case 31: p = "\nHome: "; break; #ifndef __riscos__ case 32: p = opt.homedir; break; #else /* __riscos__ */ case 32: p = make_filename(opt.homedir, NULL); break; #endif /* __riscos__ */ case 33: p = _("\nSupported algorithms:\n"); break; case 34: if (!pubkeys) pubkeys = build_list (_("Pubkey: "), 0, gcry_pk_algo_name, openpgp_pk_test_algo ); p = pubkeys; break; case 35: if( !ciphers ) ciphers = build_list(_("Cipher: "), 'S', openpgp_cipher_algo_name, openpgp_cipher_test_algo ); p = ciphers; break; case 36: if( !digests ) digests = build_list(_("Hash: "), 'H', gcry_md_algo_name, openpgp_md_test_algo ); p = digests; break; case 37: if( !zips ) zips = build_list(_("Compression: "),'Z', compress_algo_to_string, check_compress_algo); p = zips; break; default: p = NULL; } return p; } static char * build_list( const char *text, char letter, const char * (*mapf)(int), int (*chkf)(int) ) { int i; const char *s; size_t n=strlen(text)+2; char *list, *p, *line=NULL; if (maybe_setuid) gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ for(i=0; i <= 110; i++ ) if( !chkf(i) && (s=mapf(i)) ) n += strlen(s) + 7 + 2; list = xmalloc( 21 + n ); *list = 0; for(p=NULL, i=0; i <= 110; i++ ) { if( !chkf(i) && (s=mapf(i)) ) { if( !p ) { p = stpcpy( list, text ); line=p; } else p = stpcpy( p, ", "); if(strlen(line)>60) { int spaces=strlen(text); list=xrealloc(list,n+spaces+1); /* realloc could move the block, so find the end again */ p=list; while(*p) p++; p=stpcpy(p, "\n"); line=p; for(;spaces;spaces--) p=stpcpy(p, " "); } p = stpcpy(p, s ); if(opt.verbose && letter) { char num[8]; sprintf(num," (%c%d)",letter,i); p = stpcpy(p,num); } } } if( p ) p = stpcpy(p, "\n" ); return list; } static void wrong_args( const char *text) { fputs(_("usage: gpg [options] "),stderr); fputs(text,stderr); putc('\n',stderr); g10_exit(2); } static char * make_username( const char *string ) { char *p; if( utf8_strings ) p = xstrdup(string); else p = native_to_utf8( string ); return p; } static void set_opt_session_env (const char *name, const char *value) { gpg_error_t err; err = session_env_setenv (opt.session_env, name, value); if (err) log_fatal ("error setting session environment: %s\n", gpg_strerror (err)); } /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (const char *level) { int numok = (level && digitp (level)); int numlvl = numok? atoi (level) : 0; if (!level) ; else if (!strcmp (level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_MEMSTAT_VALUE; else if (!strcmp (level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE; else if (!strcmp (level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE); else if (!strcmp (level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level `%s' given\n"), level); g10_exit (2); } if (opt.debug & DBG_MEMORY_VALUE ) memory_debug_mode = 1; if (opt.debug & DBG_MEMSTAT_VALUE ) memory_stat_debug_mode = 1; if (opt.debug & DBG_MPI_VALUE) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2); if (opt.debug & DBG_CIPHER_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); if (opt.debug & DBG_IOBUF_VALUE ) iobuf_debug_mode = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) log_info ("enabled debug flags:%s%s%s%s%s%s%s%s%s%s%s%s%s\n", (opt.debug & DBG_PACKET_VALUE )? " packet":"", (opt.debug & DBG_MPI_VALUE )? " mpi":"", (opt.debug & DBG_CIPHER_VALUE )? " cipher":"", (opt.debug & DBG_FILTER_VALUE )? " filter":"", (opt.debug & DBG_IOBUF_VALUE )? " iobuf":"", (opt.debug & DBG_MEMORY_VALUE )? " memory":"", (opt.debug & DBG_CACHE_VALUE )? " cache":"", (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"", (opt.debug & DBG_TRUST_VALUE )? " trust":"", (opt.debug & DBG_HASHING_VALUE)? " hashing":"", (opt.debug & DBG_EXTPROG_VALUE)? " extprog":"", (opt.debug & DBG_CARD_IO_VALUE)? " cardio":"", (opt.debug & DBG_ASSUAN_VALUE )? " assuan":""); } /* We need the home directory also in some other directories, so make sure that both variables are always in sync. */ static void set_homedir (const char *dir) { if (!dir) dir = ""; opt.homedir = dir; } /* We set the screen dimensions for UI purposes. Do not allow screens smaller than 80x24 for the sake of simplicity. */ static void set_screen_dimensions(void) { #ifndef HAVE_W32_SYSTEM char *str; str=getenv("COLUMNS"); if(str) opt.screen_columns=atoi(str); str=getenv("LINES"); if(str) opt.screen_lines=atoi(str); #endif if(opt.screen_columns<80 || opt.screen_columns>255) opt.screen_columns=80; if(opt.screen_lines<24 || opt.screen_lines>255) opt.screen_lines=24; } /* Helper to open a file FNAME either for reading or writing to be used with --status-file etc functions. Not generally useful but it avoids the riscos specific functions and well some Windows people might like it too. Prints an error message and returns -1 on error. On success the file descriptor is returned. */ static int open_info_file (const char *fname, int for_write, int binary) { #ifdef __riscos__ return riscos_fdopenfile (fname, for_write); #elif defined (ENABLE_SELINUX_HACKS) /* We can't allow these even when testing for a secured filename because files to be secured might not yet been secured. This is similar to the option file but in that case it is unlikely that sensitive information may be retrieved by means of error messages. */ (void)fname; (void)for_write; (void)binary; return -1; #else int fd; if (binary) binary = MY_O_BINARY; /* if (is_secured_filename (fname)) */ /* { */ /* fd = -1; */ /* errno = EPERM; */ /* } */ /* else */ /* { */ do { if (for_write) fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); else fd = open (fname, O_RDONLY | binary); } while (fd == -1 && errno == EINTR); /* } */ if ( fd == -1) log_error ( for_write? _("can't create `%s': %s\n") : _("can't open `%s': %s\n"), fname, strerror(errno)); return fd; #endif } static void set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd ) { enum cmd_and_opt_values cmd = *ret_cmd; if( !cmd || cmd == new_cmd ) cmd = new_cmd; else if( cmd == aSign && new_cmd == aEncr ) cmd = aSignEncr; else if( cmd == aEncr && new_cmd == aSign ) cmd = aSignEncr; else if( cmd == aSign && new_cmd == aSym ) cmd = aSignSym; else if( cmd == aSym && new_cmd == aSign ) cmd = aSignSym; else if( cmd == aSym && new_cmd == aEncr ) cmd = aEncrSym; else if( cmd == aEncr && new_cmd == aSym ) cmd = aEncrSym; else if (cmd == aSignEncr && new_cmd == aSym) cmd = aSignEncrSym; else if (cmd == aSignSym && new_cmd == aEncr) cmd = aSignEncrSym; else if (cmd == aEncrSym && new_cmd == aSign) cmd = aSignEncrSym; else if( ( cmd == aSign && new_cmd == aClearsign ) || ( cmd == aClearsign && new_cmd == aSign ) ) cmd = aClearsign; else { log_error(_("conflicting commands\n")); g10_exit(2); } *ret_cmd = cmd; } static void add_group(char *string) { char *name,*value; struct groupitem *item; /* Break off the group name */ name=strsep(&string,"="); if(string==NULL) { log_error(_("no = sign found in group definition `%s'\n"),name); return; } trim_trailing_ws(name,strlen(name)); /* Does this group already exist? */ for(item=opt.grouplist;item;item=item->next) if(strcasecmp(item->name,name)==0) break; if(!item) { item=xmalloc(sizeof(struct groupitem)); item->name=name; item->next=opt.grouplist; item->values=NULL; opt.grouplist=item; } /* Break apart the values */ while ((value= strsep(&string," \t"))) { if (*value) add_to_strlist2(&item->values,value,utf8_strings); } } static void rm_group(char *name) { struct groupitem *item,*last=NULL; trim_trailing_ws(name,strlen(name)); for(item=opt.grouplist;item;last=item,item=item->next) { if(strcasecmp(item->name,name)==0) { if(last) last->next=item->next; else opt.grouplist=item->next; free_strlist(item->values); xfree(item); break; } } } /* We need to check three things. 0) The homedir. It must be x00, a directory, and owned by the user. 1) The options/gpg.conf file. Okay unless it or its containing directory is group or other writable or not owned by us. Disable exec in this case. 2) Extensions. Same as #1. Returns true if the item is unsafe. */ static int check_permissions(const char *path,int item) { #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM) static int homedir_cache=-1; char *tmppath,*dir; struct stat statbuf,dirbuf; int homedir=0,ret=0,checkonly=0; int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0; if(opt.no_perm_warn) return 0; assert(item==0 || item==1 || item==2); /* extensions may attach a path */ if(item==2 && path[0]!=DIRSEP_C) { if(strchr(path,DIRSEP_C)) tmppath=make_filename(path,NULL); else tmppath=make_filename(gnupg_libdir (),path,NULL); } else tmppath=xstrdup(path); /* If the item is located in the homedir, but isn't the homedir, don't continue if we already checked the homedir itself. This is to avoid user confusion with an extra options file warning which could be rectified if the homedir itself had proper permissions. */ if(item!=0 && homedir_cache>-1 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0) { ret=homedir_cache; goto end; } /* It's okay if the file or directory doesn't exist */ if(stat(tmppath,&statbuf)!=0) { ret=0; goto end; } /* Now check the enclosing directory. Theoretically, we could walk this test up to the root directory /, but for the sake of sanity, I'm stopping at one level down. */ dir=make_dirname(tmppath); if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode)) { /* Weird error */ ret=1; goto end; } xfree(dir); /* Assume failure */ ret=1; if(item==0) { /* The homedir must be x00, a directory, and owned by the user. */ if(S_ISDIR(statbuf.st_mode)) { if(statbuf.st_uid==getuid()) { if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0) ret=0; else perm=1; } else own=1; homedir_cache=ret; } } else if(item==1 || item==2) { /* The options or extension file. Okay unless it or its containing directory is group or other writable or not owned by us or root. */ if(S_ISREG(statbuf.st_mode)) { if(statbuf.st_uid==getuid() || statbuf.st_uid==0) { if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0) { /* it's not writable, so make sure the enclosing directory is also not writable */ if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0) { if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0) ret=0; else enc_dir_perm=1; } else enc_dir_own=1; } else { /* it's writable, so the enclosing directory had better not let people get to it. */ if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0) { if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0) ret=0; else perm=enc_dir_perm=1; /* unclear which one to fix! */ } else enc_dir_own=1; } } else own=1; } } else BUG(); if(!checkonly) { if(own) { if(item==0) log_info(_("WARNING: unsafe ownership on" " homedir `%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe ownership on" " configuration file `%s'\n"),tmppath); else log_info(_("WARNING: unsafe ownership on" " extension `%s'\n"),tmppath); } if(perm) { if(item==0) log_info(_("WARNING: unsafe permissions on" " homedir `%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe permissions on" " configuration file `%s'\n"),tmppath); else log_info(_("WARNING: unsafe permissions on" " extension `%s'\n"),tmppath); } if(enc_dir_own) { if(item==0) log_info(_("WARNING: unsafe enclosing directory ownership on" " homedir `%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe enclosing directory ownership on" " configuration file `%s'\n"),tmppath); else log_info(_("WARNING: unsafe enclosing directory ownership on" " extension `%s'\n"),tmppath); } if(enc_dir_perm) { if(item==0) log_info(_("WARNING: unsafe enclosing directory permissions on" " homedir `%s'\n"),tmppath); else if(item==1) log_info(_("WARNING: unsafe enclosing directory permissions on" " configuration file `%s'\n"),tmppath); else log_info(_("WARNING: unsafe enclosing directory permissions on" " extension `%s'\n"),tmppath); } } end: xfree(tmppath); if(homedir) homedir_cache=ret; return ret; #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */ return 0; } /* Print the OpenPGP defined algo numbers. */ static void print_algo_numbers(int (*checker)(int)) { int i,first=1; for(i=0;i<=110;i++) { if(!checker(i)) { if(first) first=0; else printf(";"); printf("%d",i); } } } static void print_algo_names(int (*checker)(int),const char *(*mapper)(int)) { int i,first=1; for(i=0;i<=110;i++) { if(!checker(i)) { if(first) first=0; else printf(";"); printf("%s",mapper(i)); } } } /* In the future, we can do all sorts of interesting configuration output here. For now, just give "group" as the Enigmail folks need it, and pubkey, cipher, hash, and compress as they may be useful for frontends. */ static void list_config(char *items) { int show_all=(items==NULL); char *name=NULL; if(!opt.with_colons) return; while(show_all || (name=strsep(&items," "))) { int any=0; if(show_all || ascii_strcasecmp(name,"group")==0) { struct groupitem *iter; for(iter=opt.grouplist;iter;iter=iter->next) { strlist_t sl; - printf("cfg:group:"); - print_string(stdout,iter->name,strlen(iter->name),':'); - printf(":"); + es_fprintf (es_stdout, "cfg:group:"); + es_write_sanitized (es_stdout, iter->name, strlen(iter->name), + ":", NULL); + es_putc (':', es_stdout); for(sl=iter->values;sl;sl=sl->next) { print_sanitized_string2 (stdout, sl->d, ':',';'); if(sl->next) printf(";"); } printf("\n"); } any=1; } if(show_all || ascii_strcasecmp(name,"version")==0) { printf("cfg:version:"); - print_string(stdout,VERSION,strlen(VERSION),':'); + es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL); printf("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"pubkey")==0) { printf("cfg:pubkey:"); print_algo_numbers (openpgp_pk_test_algo); printf("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"cipher")==0) { printf("cfg:cipher:"); print_algo_numbers(openpgp_cipher_test_algo); printf("\n"); any=1; } if (show_all || !ascii_strcasecmp (name,"ciphername")) { printf ("cfg:ciphername:"); print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name); printf ("\n"); any = 1; } if(show_all || ascii_strcasecmp(name,"digest")==0 || ascii_strcasecmp(name,"hash")==0) { printf("cfg:digest:"); print_algo_numbers(openpgp_md_test_algo); printf("\n"); any=1; } if (show_all || !ascii_strcasecmp(name,"digestname") || !ascii_strcasecmp(name,"hashname")) { printf ("cfg:digestname:"); print_algo_names (openpgp_md_test_algo, gcry_md_algo_name); printf("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"compress")==0) { printf("cfg:compress:"); print_algo_numbers(check_compress_algo); printf("\n"); any=1; } if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0) { #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \ && GNUPG_MAJOR_VERSION == 1 char *p, *p2, *list = ccid_get_reader_list (); for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1) { *p2 = 0; printf("cfg:ccid-reader-id:%s\n", p); } free (list); #endif any=1; } if(show_all) break; if(!any) log_error(_("unknown configuration item `%s'\n"),name); } } /* List options and default values in the GPG Conf format. This is a new tool distributed with gnupg 1.9.x but we also want some limited support in older gpg versions. The output is the name of the configuration file and a list of options available for editing by gpgconf. */ static void gpgconf_list (const char *configfile) { char *configfile_esc = percent_escape (configfile, NULL); printf ("gpgconf-gpg.conf:%lu:\"%s\n", GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null"); printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE); printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE); printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE); printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE); printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE); printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE); printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE); printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE); printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT); printf ("group:%lu:\n", GC_OPT_FLAG_NONE); /* The next one is an info only item and should match the macros at the top of keygen.c */ printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "RSA-2048"); xfree (configfile_esc); } static int parse_subpacket_list(char *list) { char *tok; byte subpackets[128],i; int count=0; if(!list) { /* No arguments means all subpackets */ memset(subpackets+1,1,sizeof(subpackets)-1); count=127; } else { memset(subpackets,0,sizeof(subpackets)); /* Merge with earlier copy */ if(opt.show_subpackets) { byte *in; for(in=opt.show_subpackets;*in;in++) { if(*in>127 || *in<1) BUG(); if(!subpackets[*in]) count++; subpackets[*in]=1; } } while((tok=strsep(&list," ,"))) { if(!*tok) continue; i=atoi(tok); if(i>127 || i<1) return 0; if(!subpackets[i]) count++; subpackets[i]=1; } } xfree(opt.show_subpackets); opt.show_subpackets=xmalloc(count+1); opt.show_subpackets[count--]=0; for(i=1;i<128 && count>=0;i++) if(subpackets[i]) opt.show_subpackets[count--]=i; return 1; } static int parse_list_options(char *str) { char *subpackets=""; /* something that isn't NULL */ struct parse_options lopts[]= { {"show-photos",LIST_SHOW_PHOTOS,NULL, N_("display photo IDs during key listings")}, {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL, N_("show policy URLs during signature listings")}, {"show-notations",LIST_SHOW_NOTATIONS,NULL, N_("show all notations during signature listings")}, {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL, N_("show IETF standard notations during signature listings")}, {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL, NULL}, {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL, N_("show user-supplied notations during signature listings")}, {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL, N_("show preferred keyserver URLs during signature listings")}, {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL, N_("show user ID validity during key listings")}, {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL, N_("show revoked and expired user IDs in key listings")}, {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL, N_("show revoked and expired subkeys in key listings")}, {"show-keyring",LIST_SHOW_KEYRING,NULL, N_("show the keyring name in key listings")}, {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL, N_("show expiration dates during signature listings")}, {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL, NULL}, {NULL,0,NULL,NULL} }; /* C99 allows for non-constant initializers, but we'd like to compile everywhere, so fill in the show-sig-subpackets argument here. Note that if the parse_options array changes, we'll have to change the subscript here. */ lopts[12].value=&subpackets; if(parse_options(str,&opt.list_options,lopts,1)) { if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS) { /* Unset so users can pass multiple lists in. */ opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS; if(!parse_subpacket_list(subpackets)) return 0; } else if(subpackets==NULL && opt.show_subpackets) { /* User did 'no-show-subpackets' */ xfree(opt.show_subpackets); opt.show_subpackets=NULL; } return 1; } else return 0; } /* Collapses argc/argv into a single string that must be freed */ static char * collapse_args(int argc,char *argv[]) { char *str=NULL; int i,first=1,len=0; for(i=0;iflags=2; break; case oShowKeyring: deprecated_warning(configname,configlineno,"--show-keyring", "--list-options ","show-keyring"); opt.list_options|=LIST_SHOW_KEYRING; break; case oDebug: opt.debug |= pargs.r.ret_ulong; break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs.r.ret_str; break; case oStatusFD: set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) ); break; case oStatusFile: set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) ); break; case oAttributeFD: set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) ); break; case oAttributeFile: set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) ); break; case oLoggerFD: log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFile: logfile = pargs.r.ret_str; break; case oWithFingerprint: opt.with_fingerprint = 1; opt.fingerprint++; break; case oFingerprint: opt.fingerprint++; fpr_maybe_cmd = 1; break; case oSecretKeyring: append_to_strlist( &sec_nrings, pargs.r.ret_str); break; case oOptions: /* config files may not be nested (silently ignore them) */ if( !configfp ) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoArmor: opt.no_armor=1; opt.armor=0; break; case oNoDefKeyring: default_keyring = 0; break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); opt.list_sigs=0; break; case oQuickRandom: gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); break; case oEmitVersion: opt.no_version=0; break; case oNoEmitVersion: opt.no_version=1; break; case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break; case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break; case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break; case oTrustDBName: trustdb_name = pargs.r.ret_str; break; case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break; case oDefRecipient: if( *pargs.r.ret_str ) opt.def_recipient = make_username(pargs.r.ret_str); break; case oDefRecipientSelf: xfree(opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 1; break; case oNoDefRecipient: xfree(opt.def_recipient); opt.def_recipient = NULL; opt.def_recipient_self = 0; break; case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */ case oHomedir: break; case oNoBatch: opt.batch = 0; break; case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/ case oWithColons: opt.with_colons=':'; break; case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/ case oWithSigList: opt.list_sigs = 1; break; case oSkipVerify: opt.skip_verify=1; break; case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break; case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break; case oCompressKeys: opt.compress_keys = 1; break; case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break; /* There are many programs (like mutt) that call gpg with --always-trust so keep this option around for a long time. */ case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break; case oTrustModel: parse_trust_model(pargs.r.ret_str); break; case oForceOwnertrust: log_info(_("NOTE: %s is not for normal use!\n"), "--force-ownertrust"); opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str); if(opt.force_ownertrust==-1) { log_error("invalid ownertrust `%s'\n",pargs.r.ret_str); opt.force_ownertrust=0; } break; case oLoadExtension: /* Dummy so that gpg 1.4 conf files can work. Should eventually be removed. */ break; case oRFC1991: opt.compliance = CO_RFC1991; opt.force_v4_certs = 0; opt.escape_from = 1; break; case oOpenPGP: case oRFC4880: /* This is effectively the same as RFC2440, but with "--enable-dsa2 --no-rfc2440-text --escape-from-lines --require-cross-certification". */ opt.compliance = CO_RFC4880; opt.flags.dsa2 = 1; opt.flags.require_cross_cert = 1; opt.rfc2440_text = 0; opt.allow_non_selfsigned_uid = 1; opt.allow_freeform_uid = 1; opt.pgp2_workarounds = 0; opt.escape_from = 1; opt.force_v3_sigs = 0; opt.compress_keys = 0; /* not mandated, but we do it */ opt.compress_sigs = 0; /* ditto. */ opt.not_dash_escaped = 0; opt.def_cipher_algo = 0; opt.def_digest_algo = 0; opt.cert_digest_algo = 0; opt.compress_algo = -1; opt.s2k_mode = 3; /* iterated+salted */ opt.s2k_digest_algo = DIGEST_ALGO_SHA1; opt.s2k_cipher_algo = CIPHER_ALGO_3DES; break; case oRFC2440: opt.compliance = CO_RFC2440; opt.flags.dsa2 = 0; opt.rfc2440_text = 1; opt.allow_non_selfsigned_uid = 1; opt.allow_freeform_uid = 1; opt.pgp2_workarounds = 0; opt.escape_from = 0; opt.force_v3_sigs = 0; opt.compress_keys = 0; /* not mandated, but we do it */ opt.compress_sigs = 0; /* ditto. */ opt.not_dash_escaped = 0; opt.def_cipher_algo = 0; opt.def_digest_algo = 0; opt.cert_digest_algo = 0; opt.compress_algo = -1; opt.s2k_mode = 3; /* iterated+salted */ opt.s2k_digest_algo = DIGEST_ALGO_SHA1; opt.s2k_cipher_algo = CIPHER_ALGO_3DES; break; case oPGP2: opt.compliance = CO_PGP2; break; case oPGP6: opt.compliance = CO_PGP6; break; case oPGP7: opt.compliance = CO_PGP7; break; case oPGP8: opt.compliance = CO_PGP8; break; case oGnuPG: opt.compliance = CO_GNUPG; break; case oCompressSigs: opt.compress_sigs = 1; break; case oRFC2440Text: opt.rfc2440_text=1; break; case oNoRFC2440Text: opt.rfc2440_text=0; break; case oSetFilename: if(utf8_strings) opt.set_filename = pargs.r.ret_str; else opt.set_filename = native_to_utf8(pargs.r.ret_str); break; case oForYourEyesOnly: eyes_only = 1; break; case oNoForYourEyesOnly: eyes_only = 0; break; case oSetPolicyURL: add_policy_url(pargs.r.ret_str,0); add_policy_url(pargs.r.ret_str,1); break; case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break; case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break; case oShowPolicyURL: deprecated_warning(configname,configlineno,"--show-policy-url", "--list-options ","show-policy-urls"); deprecated_warning(configname,configlineno,"--show-policy-url", "--verify-options ","show-policy-urls"); opt.list_options|=LIST_SHOW_POLICY_URLS; opt.verify_options|=VERIFY_SHOW_POLICY_URLS; break; case oNoShowPolicyURL: deprecated_warning(configname,configlineno,"--no-show-policy-url", "--list-options ","no-show-policy-urls"); deprecated_warning(configname,configlineno,"--no-show-policy-url", "--verify-options ","no-show-policy-urls"); opt.list_options&=~LIST_SHOW_POLICY_URLS; opt.verify_options&=~VERIFY_SHOW_POLICY_URLS; break; case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break; case oUseEmbeddedFilename: opt.flags.use_embedded_filename=1; break; case oNoUseEmbeddedFilename: opt.flags.use_embedded_filename=0; break; case oComment: if(pargs.r.ret_str[0]) append_to_strlist(&opt.comments,pargs.r.ret_str); break; case oDefaultComment: deprecated_warning(configname,configlineno, "--default-comment","--no-comments",""); /* fall through */ case oNoComments: free_strlist(opt.comments); opt.comments=NULL; break; case oThrowKeyids: opt.throw_keyid = 1; break; case oNoThrowKeyids: opt.throw_keyid = 0; break; case oShowPhotos: deprecated_warning(configname,configlineno,"--show-photos", "--list-options ","show-photos"); deprecated_warning(configname,configlineno,"--show-photos", "--verify-options ","show-photos"); opt.list_options|=LIST_SHOW_PHOTOS; opt.verify_options|=VERIFY_SHOW_PHOTOS; break; case oNoShowPhotos: deprecated_warning(configname,configlineno,"--no-show-photos", "--list-options ","no-show-photos"); deprecated_warning(configname,configlineno,"--no-show-photos", "--verify-options ","no-show-photos"); opt.list_options&=~LIST_SHOW_PHOTOS; opt.verify_options&=~VERIFY_SHOW_PHOTOS; break; case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break; case oForceV3Sigs: opt.force_v3_sigs = 1; break; case oNoForceV3Sigs: opt.force_v3_sigs = 0; break; case oForceV4Certs: opt.force_v4_certs = 1; break; case oNoForceV4Certs: opt.force_v4_certs = 0; break; case oForceMDC: opt.force_mdc = 1; break; case oNoForceMDC: opt.force_mdc = 0; break; case oDisableMDC: opt.disable_mdc = 1; break; case oNoDisableMDC: opt.disable_mdc = 0; break; case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break; case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break; case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break; case oS2KCount: if (pargs.r.ret_int) opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int); else opt.s2k_count = 0; /* Auto-calibrate when needed. */ break; case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break; case oNoEncryptTo: opt.no_encrypt_to = 1; break; case oEncryptTo: /* store the recipient in the second list */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = 1; break; case oHiddenEncryptTo: /* store the recipient in the second list */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = 1|2; break; case oRecipient: /* store the recipient */ add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); any_explicit_recipient = 1; break; case oHiddenRecipient: /* store the recipient with a flag */ sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings ); sl->flags = 2; any_explicit_recipient = 1; break; case oTextmodeShort: opt.textmode = 2; break; case oTextmode: opt.textmode=1; break; case oNoTextmode: opt.textmode=0; break; case oExpert: opt.expert = 1; break; case oNoExpert: opt.expert = 0; break; case oDefSigExpire: if(*pargs.r.ret_str!='\0') { if(parse_expire_string(pargs.r.ret_str)==(u32)-1) log_error(_("`%s' is not a valid signature expiration\n"), pargs.r.ret_str); else opt.def_sig_expire=pargs.r.ret_str; } break; case oAskSigExpire: opt.ask_sig_expire = 1; break; case oNoAskSigExpire: opt.ask_sig_expire = 0; break; case oDefCertExpire: if(*pargs.r.ret_str!='\0') { if(parse_expire_string(pargs.r.ret_str)==(u32)-1) log_error(_("`%s' is not a valid signature expiration\n"), pargs.r.ret_str); else opt.def_cert_expire=pargs.r.ret_str; } break; case oAskCertExpire: opt.ask_cert_expire = 1; break; case oNoAskCertExpire: opt.ask_cert_expire = 0; break; case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break; case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break; case oAskCertLevel: opt.ask_cert_level = 1; break; case oNoAskCertLevel: opt.ask_cert_level = 0; break; case oLocalUser: /* store the local users */ add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings ); break; case oCompress: /* this is the -z command line option */ opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int; break; case oCompressLevel: opt.compress_level = pargs.r.ret_int; break; case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break; case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break; case oPassphrase: set_passphrase_from_string(pargs.r.ret_str); break; case oPassphraseFD: pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0); break; case oPassphraseFile: pwfd = open_info_file (pargs.r.ret_str, 0, 1); break; case oPassphraseRepeat: opt.passphrase_repeat=pargs.r.ret_int; break; case oCommandFD: opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0); break; case oCommandFile: opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1); break; case oCipherAlgo: def_cipher_string = xstrdup(pargs.r.ret_str); break; case oDigestAlgo: def_digest_string = xstrdup(pargs.r.ret_str); break; case oCompressAlgo: /* If it is all digits, stick a Z in front of it for later. This is for backwards compatibility with versions that took the compress algorithm number. */ { char *pt=pargs.r.ret_str; while(*pt) { if (!isascii (*pt) || !isdigit (*pt)) break; pt++; } if(*pt=='\0') { compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2); strcpy(compress_algo_string,"Z"); strcat(compress_algo_string,pargs.r.ret_str); } else compress_algo_string = xstrdup(pargs.r.ret_str); } break; case oCertDigestAlgo: cert_digest_string = xstrdup(pargs.r.ret_str); break; case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break; case oRequireSecmem: require_secmem=1; break; case oNoRequireSecmem: require_secmem=0; break; case oNoPermissionWarn: opt.no_perm_warn=1; break; case oNoMDCWarn: opt.no_mdc_warn=1; break; case oDisplayCharset: if( set_native_charset( pargs.r.ret_str ) ) log_error(_("`%s' is not a valid character set\n"), pargs.r.ret_str); break; case oNotDashEscaped: opt.not_dash_escaped = 1; break; case oEscapeFrom: opt.escape_from = 1; break; case oNoEscapeFrom: opt.escape_from = 0; break; case oLockOnce: opt.lock_once = 1; break; case oLockNever: disable_dotlock (); break; case oLockMultiple: #ifndef __riscos__ opt.lock_once = 0; #else /* __riscos__ */ riscos_not_implemented("lock-multiple"); #endif /* __riscos__ */ break; case oKeyServer: { struct keyserver_spec *keyserver; keyserver=parse_keyserver_uri(pargs.r.ret_str,0, configname,configlineno); if(!keyserver) log_error(_("could not parse keyserver URL\n")); else { keyserver->next=opt.keyserver; opt.keyserver=keyserver; } } break; case oKeyServerOptions: if(!parse_keyserver_options(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid keyserver options\n"), configname,configlineno); else log_error(_("invalid keyserver options\n")); } break; case oImportOptions: if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1)) { if(configname) log_error(_("%s:%d: invalid import options\n"), configname,configlineno); else log_error(_("invalid import options\n")); } break; case oExportOptions: if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1)) { if(configname) log_error(_("%s:%d: invalid export options\n"), configname,configlineno); else log_error(_("invalid export options\n")); } break; case oListOptions: if(!parse_list_options(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid list options\n"), configname,configlineno); else log_error(_("invalid list options\n")); } break; case oVerifyOptions: { struct parse_options vopts[]= { {"show-photos",VERIFY_SHOW_PHOTOS,NULL, N_("display photo IDs during signature verification")}, {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL, N_("show policy URLs during signature verification")}, {"show-notations",VERIFY_SHOW_NOTATIONS,NULL, N_("show all notations during signature verification")}, {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL, N_("show IETF standard notations during signature verification")}, {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL, NULL}, {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL, N_("show user-supplied notations during signature verification")}, {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL, N_("show preferred keyserver URLs during signature verification")}, {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL, N_("show user ID validity during signature verification")}, {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL, N_("show revoked and expired user IDs in signature verification")}, {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL, N_("show only the primary user ID in signature verification")}, {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL, N_("validate signatures with PKA data")}, {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL, N_("elevate the trust of signatures with valid PKA data")}, {NULL,0,NULL,NULL} }; if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1)) { if(configname) log_error(_("%s:%d: invalid verify options\n"), configname,configlineno); else log_error(_("invalid verify options\n")); } } break; case oTempDir: opt.temp_dir=pargs.r.ret_str; break; case oExecPath: if(set_exec_path(pargs.r.ret_str)) log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str); else opt.exec_path_set=1; break; case oSetNotation: add_notation_data( pargs.r.ret_str, 0 ); add_notation_data( pargs.r.ret_str, 1 ); break; case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break; case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break; case oShowNotation: deprecated_warning(configname,configlineno,"--show-notation", "--list-options ","show-notations"); deprecated_warning(configname,configlineno,"--show-notation", "--verify-options ","show-notations"); opt.list_options|=LIST_SHOW_NOTATIONS; opt.verify_options|=VERIFY_SHOW_NOTATIONS; break; case oNoShowNotation: deprecated_warning(configname,configlineno,"--no-show-notation", "--list-options ","no-show-notations"); deprecated_warning(configname,configlineno,"--no-show-notation", "--verify-options ","no-show-notations"); opt.list_options&=~LIST_SHOW_NOTATIONS; opt.verify_options&=~VERIFY_SHOW_NOTATIONS; break; case oUtf8Strings: utf8_strings = 1; break; case oNoUtf8Strings: utf8_strings = 0; break; case oDisableCipherAlgo: { int algo = string_to_cipher_algo (pargs.r.ret_str); gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo); } break; case oDisablePubkeyAlgo: { int algo = gcry_pk_map_name (pargs.r.ret_str); gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo); } break; case oNoSigCache: opt.no_sig_cache = 1; break; case oNoSigCreateCheck: opt.no_sig_create_check = 1; break; case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break; case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break; case oAllowFreeformUID: opt.allow_freeform_uid = 1; break; case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break; case oNoLiteral: opt.no_literal = 1; break; case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break; case oHonorHttpProxy: add_to_strlist(&opt.keyserver_options.other,"http-proxy"); deprecated_warning(configname,configlineno, "--honor-http-proxy", "--keyserver-options ","http-proxy"); break; case oFastListMode: opt.fast_list_mode = 1; break; case oFixedListMode: /* Dummy */ break; case oListOnly: opt.list_only=1; break; case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break; case oIgnoreValidFrom: opt.ignore_valid_from = 1; break; case oIgnoreCrcError: opt.ignore_crc_error = 1; break; case oIgnoreMDCError: opt.ignore_mdc_error = 1; break; case oNoRandomSeedFile: use_random_seed = 0; break; case oAutoKeyRetrieve: case oNoAutoKeyRetrieve: if(pargs.r_opt==oAutoKeyRetrieve) opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE; else opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE; deprecated_warning(configname,configlineno, pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve": "--no-auto-key-retrieve","--keyserver-options ", pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve": "no-auto-key-retrieve"); break; case oShowSessionKey: opt.show_session_key = 1; break; case oOverrideSessionKey: opt.override_session_key = pargs.r.ret_str; break; case oMergeOnly: deprecated_warning(configname,configlineno,"--merge-only", "--import-options ","merge-only"); opt.import_options|=IMPORT_MERGE_ONLY; break; case oAllowSecretKeyImport: /* obsolete */ break; case oTryAllSecrets: opt.try_all_secrets = 1; break; case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break; case oEnableSpecialFilenames: iobuf_enable_special_filenames (1); break; case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break; case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break; case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break; case oPreservePermissions: opt.preserve_permissions=1; break; case oDefaultPreferenceList: opt.def_preference_list = pargs.r.ret_str; break; case oDefaultKeyserverURL: { struct keyserver_spec *keyserver; keyserver=parse_keyserver_uri(pargs.r.ret_str,1, configname,configlineno); if(!keyserver) log_error(_("could not parse keyserver URL\n")); else free_keyserver_spec(keyserver); opt.def_keyserver_url = pargs.r.ret_str; } break; case oPersonalCipherPreferences: pers_cipher_list=pargs.r.ret_str; break; case oPersonalDigestPreferences: pers_digest_list=pargs.r.ret_str; break; case oPersonalCompressPreferences: pers_compress_list=pargs.r.ret_str; break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDisplay: set_opt_session_env ("DISPLAY", pargs.r.ret_str); break; case oTTYname: set_opt_session_env ("GPG_TTY", pargs.r.ret_str); break; case oTTYtype: set_opt_session_env ("TERM", pargs.r.ret_str); break; case oXauthority: set_opt_session_env ("XAUTHORITY", pargs.r.ret_str); break; case oLCctype: opt.lc_ctype = pargs.r.ret_str; break; case oLCmessages: opt.lc_messages = pargs.r.ret_str; break; case oGroup: add_group(pargs.r.ret_str); break; case oUnGroup: rm_group(pargs.r.ret_str); break; case oNoGroups: while(opt.grouplist) { struct groupitem *iter=opt.grouplist; free_strlist(iter->values); opt.grouplist=opt.grouplist->next; xfree(iter); } break; case oStrict: case oNoStrict: /* Not used */ break; case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break; case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break; case oEnableProgressFilter: opt.enable_progress_filter = 1; break; case oMultifile: multifile=1; break; case oKeyidFormat: if(ascii_strcasecmp(pargs.r.ret_str,"short")==0) opt.keyid_format=KF_SHORT; else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0) opt.keyid_format=KF_LONG; else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0) opt.keyid_format=KF_0xSHORT; else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0) opt.keyid_format=KF_0xLONG; else log_error("unknown keyid-format `%s'\n",pargs.r.ret_str); break; case oExitOnStatusWriteError: opt.exit_on_status_write_error = 1; break; case oLimitCardInsertTries: opt.limit_card_insert_tries = pargs.r.ret_int; break; case oRequireCrossCert: opt.flags.require_cross_cert=1; break; case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break; case oAutoKeyLocate: if(!parse_auto_key_locate(pargs.r.ret_str)) { if(configname) log_error(_("%s:%d: invalid auto-key-locate list\n"), configname,configlineno); else log_error(_("invalid auto-key-locate list\n")); } break; case oNoAutoKeyLocate: release_akl(); break; case oEnableDSA2: opt.flags.dsa2=1; break; case oDisableDSA2: opt.flags.dsa2=0; break; case oAllowMultisigVerification: case oAllowMultipleMessages: opt.flags.allow_multiple_messages=1; break; case oNoAllowMultipleMessages: opt.flags.allow_multiple_messages=0; break; case 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 oNoop: break; default: pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR; break; } } if( configfp ) { fclose( configfp ); configfp = NULL; /* Remember the first config file name. */ if (!save_configname) save_configname = configname; else xfree(configname); configname = NULL; goto next_pass; } xfree( configname ); configname = NULL; if( log_get_errorcount(0) ) g10_exit(2); /* The command --gpgconf-list is pretty simple and may be called directly after the option parsing. */ if (cmd == aGPGConfList) { gpgconf_list (save_configname ? save_configname : default_configname); g10_exit (0); } xfree (save_configname); xfree (default_configname); if( nogreeting ) greeting = 0; if( greeting ) { fprintf(stderr, "%s %s; %s\n", strusage(11), strusage(13), strusage(14) ); fprintf(stderr, "%s\n", strusage(15) ); } #ifdef IS_DEVELOPMENT_VERSION if (!opt.batch) { const char *s; if((s=strusage(25))) log_info("%s\n",s); if((s=strusage(26))) log_info("%s\n",s); if((s=strusage(27))) log_info("%s\n",s); } #endif /* FIXME: We should use logging to a file only in server mode; however we have not yet implemetyed that. Thus we try to get away with --batch as indication for logging to file required. */ if (logfile && opt.batch) { log_set_file (logfile); log_set_prefix (NULL, 1|2|4); } /* Older Libgcrypts fail with an assertion during DSA key generation. Better disable DSA2 entirely. */ if (opt.flags.dsa2 && !gcry_check_version ("1.4.0") ) { log_info ("WARNING: " "DSA2 is only available with Libgcrypt 1.4 and later\n"); opt.flags.dsa2 = 0; } if (opt.verbose > 2) log_info ("using character set `%s'\n", get_native_charset ()); if( may_coredump && !opt.quiet ) log_info(_("WARNING: program may create a core file!\n")); if (eyes_only) { if (opt.set_filename) log_info(_("WARNING: %s overrides %s\n"), "--for-your-eyes-only","--set-filename"); opt.set_filename="_CONSOLE"; } if (opt.no_literal) { log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal"); if (opt.textmode) log_error(_("%s not allowed with %s!\n"), "--textmode", "--no-literal" ); if (opt.set_filename) log_error(_("%s makes no sense with %s!\n"), eyes_only?"--for-your-eyes-only":"--set-filename", "--no-literal" ); } if (opt.set_filesize) log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize"); if( opt.batch ) tty_batchmode( 1 ); if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } gcry_control (GCRYCTL_RESUME_SECMEM_WARN); if(require_secmem && !got_secmem) { log_info(_("will not run with insecure memory due to %s\n"), "--require-secmem"); g10_exit(2); } set_debug (debug_level); /* Do these after the switch(), so they can override settings. */ if(PGP2) { int unusable=0; if(cmd==aSign && !detached_sig) { log_info(_("you can only make detached or clear signatures " "while in --pgp2 mode\n")); unusable=1; } else if(cmd==aSignEncr || cmd==aSignSym) { log_info(_("you can't sign and encrypt at the " "same time while in --pgp2 mode\n")); unusable=1; } else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym)) { log_info(_("you must use files (and not a pipe) when " "working with --pgp2 enabled.\n")); unusable=1; } else if(cmd==aEncr || cmd==aSym) { /* Everything else should work without IDEA (except using a secret key encrypted with IDEA and setting an IDEA preference, but those have their own error messages). */ if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA)) { log_info(_("encrypting a message in --pgp2 mode requires " "the IDEA cipher\n")); idea_cipher_warn(1); unusable=1; } else if(cmd==aSym) { /* This only sets IDEA for symmetric encryption since it is set via select_algo_from_prefs for pk encryption. */ xfree(def_cipher_string); def_cipher_string = xstrdup("idea"); } /* PGP2 can't handle the output from the textmode filter, so we disable it for anything that could create a literal packet (only encryption and symmetric encryption, since we disable signing above). */ if(!unusable) opt.textmode=0; } if(unusable) compliance_failure(); else { opt.force_v4_certs = 0; opt.escape_from = 1; opt.force_v3_sigs = 1; opt.pgp2_workarounds = 1; opt.ask_sig_expire = 0; opt.ask_cert_expire = 0; xfree(def_digest_string); def_digest_string = xstrdup("md5"); xfree(s2k_digest_string); s2k_digest_string = xstrdup("md5"); opt.compress_algo = COMPRESS_ALGO_ZIP; } } else if(PGP6) { opt.disable_mdc=1; opt.escape_from=1; opt.force_v3_sigs=1; opt.ask_sig_expire=0; } else if(PGP7) { opt.escape_from=1; opt.force_v3_sigs=1; opt.ask_sig_expire=0; } else if(PGP8) { opt.escape_from=1; } if( def_cipher_string ) { opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string); if(opt.def_cipher_algo==0 && (ascii_strcasecmp(def_cipher_string,"idea")==0 || ascii_strcasecmp(def_cipher_string,"s1")==0)) idea_cipher_warn(1); xfree(def_cipher_string); def_cipher_string = NULL; if ( openpgp_cipher_test_algo (opt.def_cipher_algo) ) log_error(_("selected cipher algorithm is invalid\n")); } if( def_digest_string ) { opt.def_digest_algo = string_to_digest_algo (def_digest_string); xfree(def_digest_string); def_digest_string = NULL; if ( openpgp_md_test_algo (opt.def_digest_algo) ) log_error(_("selected digest algorithm is invalid\n")); } if( compress_algo_string ) { opt.compress_algo = string_to_compress_algo(compress_algo_string); xfree(compress_algo_string); compress_algo_string = NULL; if( check_compress_algo(opt.compress_algo) ) log_error(_("selected compression algorithm is invalid\n")); } if( cert_digest_string ) { opt.cert_digest_algo = string_to_digest_algo (cert_digest_string); xfree(cert_digest_string); cert_digest_string = NULL; if (openpgp_md_test_algo(opt.cert_digest_algo)) log_error(_("selected certification digest algorithm is invalid\n")); } if( s2k_cipher_string ) { opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string); xfree(s2k_cipher_string); s2k_cipher_string = NULL; if (openpgp_cipher_test_algo (opt.s2k_cipher_algo)) log_error(_("selected cipher algorithm is invalid\n")); } if( s2k_digest_string ) { opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string); xfree(s2k_digest_string); s2k_digest_string = NULL; if (openpgp_md_test_algo(opt.s2k_digest_algo)) log_error(_("selected digest algorithm is invalid\n")); } if( opt.completes_needed < 1 ) log_error(_("completes-needed must be greater than 0\n")); if( opt.marginals_needed < 2 ) log_error(_("marginals-needed must be greater than 1\n")); if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 ) log_error(_("max-cert-depth must be in the range from 1 to 255\n")); if(opt.def_cert_level<0 || opt.def_cert_level>3) log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n")); if( opt.min_cert_level < 1 || opt.min_cert_level > 3 ) log_error(_("invalid min-cert-level; must be 1, 2, or 3\n")); switch( opt.s2k_mode ) { case 0: log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n")); break; case 1: case 3: break; default: log_error(_("invalid S2K mode; must be 0, 1 or 3\n")); } /* This isn't actually needed, but does serve to error out if the string is invalid. */ if(opt.def_preference_list && keygen_set_std_prefs(opt.def_preference_list,0)) log_error(_("invalid default preferences\n")); if(pers_cipher_list && keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM)) log_error(_("invalid personal cipher preferences\n")); if(pers_digest_list && keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH)) log_error(_("invalid personal digest preferences\n")); if(pers_compress_list && keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP)) log_error(_("invalid personal compress preferences\n")); /* We don't support all possible commands with multifile yet */ if(multifile) { char *cmdname; switch(cmd) { case aSign: cmdname="--sign"; break; case aClearsign: cmdname="--clearsign"; break; case aDetachedSign: cmdname="--detach-sign"; break; case aSym: cmdname="--symmetric"; break; case aEncrSym: cmdname="--symmetric --encrypt"; break; case aStore: cmdname="--store"; break; default: cmdname=NULL; break; } if(cmdname) log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile"); } if( log_get_errorcount(0) ) g10_exit(2); if(opt.compress_level==0) opt.compress_algo=COMPRESS_ALGO_NONE; /* Check our chosen algorithms against the list of legal algorithms. */ if(!GNUPG) { const char *badalg=NULL; preftype_t badtype=PREFTYPE_NONE; if(opt.def_cipher_algo && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL)) { badalg = openpgp_cipher_algo_name (opt.def_cipher_algo); badtype = PREFTYPE_SYM; } else if(opt.def_digest_algo && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL)) { badalg = gcry_md_algo_name (opt.def_digest_algo); badtype = PREFTYPE_HASH; } else if(opt.cert_digest_algo && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL)) { badalg = gcry_md_algo_name (opt.cert_digest_algo); badtype = PREFTYPE_HASH; } else if(opt.compress_algo!=-1 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL)) { badalg = compress_algo_to_string(opt.compress_algo); badtype = PREFTYPE_ZIP; } if(badalg) { switch(badtype) { case PREFTYPE_SYM: log_info(_("you may not use cipher algorithm `%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; case PREFTYPE_HASH: log_info(_("you may not use digest algorithm `%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; case PREFTYPE_ZIP: log_info(_("you may not use compression algorithm `%s'" " while in %s mode\n"), badalg,compliance_option_string()); break; default: BUG(); } compliance_failure(); } } /* Set the random seed file. */ if( use_random_seed ) { char *p = make_filename(opt.homedir, "random_seed", NULL ); gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p); if (!access (p, F_OK)) register_secured_file (p); xfree(p); } /* If there is no command but the --fingerprint is given, default to the --list-keys command. */ if (!cmd && fpr_maybe_cmd) { set_cmd (&cmd, aListKeys); } if( opt.verbose > 1 ) set_packet_list_mode(1); /* Add the keyrings, but not for some special commands. Also avoid adding the secret keyring for a couple of commands to avoid unneeded access in case the secrings are stored on a floppy. We always need to add the keyrings if we are running under SELinux, this is so that the rings are added to the list of secured files. */ if( ALWAYS_ADD_KEYRINGS || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) ) { if (ALWAYS_ADD_KEYRINGS || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys && cmd != aVerify && cmd != aSym && cmd != aLocateKeys)) { if (!sec_nrings || default_keyring) /* add default secret rings */ keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1); for (sl = sec_nrings; sl; sl = sl->next) keydb_add_resource ( sl->d, 0, 1 ); } if( !nrings || default_keyring ) /* add default ring */ keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0); for(sl = nrings; sl; sl = sl->next ) keydb_add_resource ( sl->d, sl->flags, 0 ); } FREE_STRLIST(nrings); FREE_STRLIST(sec_nrings); if (cmd == aGPGConfTest) g10_exit(0); if( pwfd != -1 ) /* Read the passphrase now. */ read_passphrase_from_fd( pwfd ); fname = argc? *argv : NULL; if(fname && utf8_strings) opt.flags.utf8_filename=1; switch( cmd ) { case aPrimegen: case aPrintMD: case aPrintMDs: case aGenRandom: case aDeArmor: case aEnArmor: break; case aFixTrustDB: case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break; case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break; default: rc = setup_trustdb(1, trustdb_name ); break; } if( rc ) log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc)); switch (cmd) { case aStore: case aSym: case aSign: case aSignSym: case aClearsign: if (!opt.quiet && any_explicit_recipient) log_info (_("WARNING: recipients (-r) given " "without using public key encryption\n")); break; default: break; } switch( cmd ) { case aServer: { ctrl_t ctrl = xtrycalloc (1, sizeof *ctrl); gpg_init_default_ctrl (ctrl); gpg_server (ctrl); gpg_deinit_default_ctrl (ctrl); xfree (ctrl); } break; case aStore: /* only store the file */ if( argc > 1 ) wrong_args(_("--store [filename]")); if( (rc = encrypt_store(fname)) ) log_error ("storing `%s' failed: %s\n", print_fname_stdin(fname),g10_errstr(rc) ); break; case aSym: /* encrypt the given file only with the symmetric cipher */ if( argc > 1 ) wrong_args(_("--symmetric [filename]")); if( (rc = encrypt_symmetric(fname)) ) log_error (_("symmetric encryption of `%s' failed: %s\n"), print_fname_stdin(fname),g10_errstr(rc) ); break; case aEncr: /* encrypt the given file */ if(multifile) encrypt_crypt_files(argc, argv, remusr); else { if( argc > 1 ) wrong_args(_("--encrypt [filename]")); if( (rc = encrypt_crypt (-1, fname, remusr, 0, NULL, -1)) ) log_error("%s: encryption failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); } break; case aEncrSym: /* This works with PGP 8 in the sense that it acts just like a symmetric message. It doesn't work at all with 2 or 6. It might work with 7, but alas, I don't have a copy to test with right now. */ if( argc > 1 ) wrong_args(_("--symmetric --encrypt [filename]")); else if(opt.s2k_mode==0) log_error(_("you cannot use --symmetric --encrypt" " with --s2k-mode 0\n")); else if(PGP2 || PGP6 || PGP7 || RFC1991) log_error(_("you cannot use --symmetric --encrypt" " while in %s mode\n"),compliance_option_string()); else { if( (rc = encrypt_crypt (-1, fname, remusr, 1, NULL, -1)) ) log_error("%s: encryption failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); } break; case aSign: /* sign the given file */ sl = NULL; if( detached_sig ) { /* sign all files */ for( ; argc; argc--, argv++ ) add_to_strlist( &sl, *argv ); } else { if( argc > 1 ) wrong_args(_("--sign [filename]")); if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } } if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) ) log_error("signing failed: %s\n", g10_errstr(rc) ); free_strlist(sl); break; case aSignEncr: /* sign and encrypt the given file */ if( argc > 1 ) wrong_args(_("--sign --encrypt [filename]")); if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } else sl = NULL; if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) ) log_error("%s: sign+encrypt failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); free_strlist(sl); break; case aSignEncrSym: /* sign and encrypt the given file */ if( argc > 1 ) wrong_args(_("--symmetric --sign --encrypt [filename]")); else if(opt.s2k_mode==0) log_error(_("you cannot use --symmetric --sign --encrypt" " with --s2k-mode 0\n")); else if(PGP2 || PGP6 || PGP7 || RFC1991) log_error(_("you cannot use --symmetric --sign --encrypt" " while in %s mode\n"),compliance_option_string()); else { if( argc ) { sl = xmalloc_clear( sizeof *sl + strlen(fname)); strcpy(sl->d, fname); } else sl = NULL; if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) ) log_error("%s: symmetric+sign+encrypt failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); free_strlist(sl); } break; case aSignSym: /* sign and conventionally encrypt the given file */ if (argc > 1) wrong_args(_("--sign --symmetric [filename]")); rc = sign_symencrypt_file (fname, locusr); if (rc) log_error("%s: sign+symmetric failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); break; case aClearsign: /* make a clearsig */ if( argc > 1 ) wrong_args(_("--clearsign [filename]")); if( (rc = clearsign_file(fname, locusr, NULL)) ) log_error("%s: clearsign failed: %s\n", print_fname_stdin(fname), g10_errstr(rc) ); break; case aVerify: if(multifile) { if( (rc = verify_files( argc, argv ) )) log_error("verify files failed: %s\n", g10_errstr(rc) ); } else { if( (rc = verify_signatures( argc, argv ) )) log_error("verify signatures failed: %s\n", g10_errstr(rc) ); } break; case aDecrypt: if(multifile) decrypt_messages(argc, argv); else { if( argc > 1 ) wrong_args(_("--decrypt [filename]")); if( (rc = decrypt_message( fname ) )) log_error("decrypt_message failed: %s\n", g10_errstr(rc) ); } break; case aSignKey: if( argc != 1 ) wrong_args(_("--sign-key user-id")); /* fall through */ case aLSignKey: if( argc != 1 ) wrong_args(_("--lsign-key user-id")); /* fall through */ sl=NULL; if(cmd==aSignKey) append_to_strlist(&sl,"sign"); else if(cmd==aLSignKey) append_to_strlist(&sl,"lsign"); else BUG(); append_to_strlist( &sl, "save" ); username = make_username( fname ); keyedit_menu (username, locusr, sl, 0, 0 ); xfree(username); free_strlist(sl); break; case aEditKey: /* Edit a key signature */ if( !argc ) wrong_args(_("--edit-key user-id [commands]")); username = make_username( fname ); if( argc > 1 ) { sl = NULL; for( argc--, argv++ ; argc; argc--, argv++ ) append_to_strlist( &sl, *argv ); keyedit_menu( username, locusr, sl, 0, 1 ); free_strlist(sl); } else keyedit_menu(username, locusr, NULL, 0, 1 ); xfree(username); break; case aPasswd: if (argc != 1) wrong_args (_("--passwd ")); else { username = make_username (fname); keyedit_passwd (username); xfree (username); } break; case aDeleteKeys: case aDeleteSecretKeys: case aDeleteSecretAndPublicKeys: sl = NULL; /* I'm adding these in reverse order as add_to_strlist2 reverses them again, and it's easier to understand in the proper order :) */ for( ; argc; argc-- ) add_to_strlist2( &sl, argv[argc-1], utf8_strings ); delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys); free_strlist(sl); break; case aCheckKeys: opt.check_sigs = 1; case aListSigs: opt.list_sigs = 1; case aListKeys: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); public_key_list( sl, 0 ); free_strlist(sl); break; case aListSecretKeys: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); secret_key_list( sl ); free_strlist(sl); break; case aLocateKeys: sl = NULL; for (; argc; argc--, argv++) add_to_strlist2( &sl, *argv, utf8_strings ); public_key_list (sl, 1); free_strlist (sl); break; case aKeygen: /* generate a key */ if( opt.batch ) { if( argc > 1 ) wrong_args("--gen-key [parameterfile]"); generate_keypair( argc? *argv : NULL, NULL, NULL ); } else { if( argc ) wrong_args("--gen-key"); generate_keypair(NULL, NULL, NULL); } break; case aFastImport: opt.import_options |= IMPORT_FAST; case aImport: import_keys( argc? argv:NULL, argc, NULL, opt.import_options ); break; /* TODO: There are a number of command that use this same "make strlist, call function, report error, free strlist" pattern. Join them together here and avoid all that duplicated code. */ case aExport: case aSendKeys: case aRecvKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); if( cmd == aSendKeys ) rc=keyserver_export( sl ); else if( cmd == aRecvKeys ) rc=keyserver_import( sl ); else rc=export_pubkeys( sl, opt.export_options ); if(rc) { if(cmd==aSendKeys) log_error(_("keyserver send failed: %s\n"),g10_errstr(rc)); else if(cmd==aRecvKeys) log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc)); else log_error(_("key export failed: %s\n"),g10_errstr(rc)); } free_strlist(sl); break; case aSearchKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); rc=keyserver_search( sl ); if(rc) log_error(_("keyserver search failed: %s\n"),g10_errstr(rc)); free_strlist(sl); break; case aRefreshKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); rc=keyserver_refresh(sl); if(rc) log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc)); free_strlist(sl); break; case aFetchKeys: sl = NULL; for( ; argc; argc--, argv++ ) append_to_strlist2( &sl, *argv, utf8_strings ); rc=keyserver_fetch(sl); if(rc) log_error("key fetch failed: %s\n",g10_errstr(rc)); free_strlist(sl); break; case aExportSecret: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); export_seckeys( sl ); free_strlist(sl); break; case aExportSecretSub: sl = NULL; for( ; argc; argc--, argv++ ) add_to_strlist2( &sl, *argv, utf8_strings ); export_secsubkeys( sl ); free_strlist(sl); break; case aGenRevoke: if( argc != 1 ) wrong_args("--gen-revoke user-id"); username = make_username(*argv); gen_revoke( username ); xfree( username ); break; case aDesigRevoke: if( argc != 1 ) wrong_args("--desig-revoke user-id"); username = make_username(*argv); gen_desig_revoke( username, locusr ); xfree( username ); break; case aDeArmor: if( argc > 1 ) wrong_args("--dearmor [file]"); rc = dearmor_file( argc? *argv: NULL ); if( rc ) log_error(_("dearmoring failed: %s\n"), g10_errstr(rc)); break; case aEnArmor: if( argc > 1 ) wrong_args("--enarmor [file]"); rc = enarmor_file( argc? *argv: NULL ); if( rc ) log_error(_("enarmoring failed: %s\n"), g10_errstr(rc)); break; case aPrimegen: #if 0 /*FIXME*/ { int mode = argc < 2 ? 0 : atoi(*argv); if( mode == 1 && argc == 2 ) { - mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1); + mpi_print (es_stdout, + generate_public_prime( atoi(argv[1]) ), 1); } else if( mode == 2 && argc == 3 ) { - mpi_print( stdout, generate_elg_prime( + mpi_print (es_stdout, generate_elg_prime( 0, atoi(argv[1]), atoi(argv[2]), NULL,NULL ), 1); } else if( mode == 3 && argc == 3 ) { MPI *factors; - mpi_print( stdout, generate_elg_prime( + mpi_print (es_stdout, generate_elg_prime( 1, atoi(argv[1]), atoi(argv[2]), NULL,&factors ), 1); putchar('\n'); - mpi_print( stdout, factors[0], 1 ); /* print q */ + mpi_print (es_stdout, factors[0], 1 ); /* print q */ } else if( mode == 4 && argc == 3 ) { MPI g = mpi_alloc(1); - mpi_print( stdout, generate_elg_prime( + mpi_print (es_stdout, generate_elg_prime( 0, atoi(argv[1]), atoi(argv[2]), g, NULL ), 1); putchar('\n'); - mpi_print( stdout, g, 1 ); - mpi_free(g); + mpi_print (es_stdout, g, 1 ); + mpi_free (g); } else wrong_args("--gen-prime mode bits [qbits] "); putchar('\n'); } #endif wrong_args("--gen-prime not yet supported "); break; case aGenRandom: { int level = argc ? atoi(*argv):0; int count = argc > 1 ? atoi(argv[1]): 0; int endless = !count; if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 ) wrong_args("--gen-random 0|1|2 [count]"); while( endless || count ) { byte *p; /* Wee need a multiple of 3, so that in case of armored output we get a correct string. No linefolding is done, as it is best to levae this to other tools */ size_t n = !endless && count < 99? count : 99; p = gcry_random_bytes (n, level); #ifdef HAVE_DOSISH_SYSTEM setmode ( fileno(stdout), O_BINARY ); #endif if (opt.armor) { char *tmp = make_radix64_string (p, n); fputs (tmp, stdout); xfree (tmp); if (n%3 == 1) putchar ('='); if (n%3) putchar ('='); } else { fwrite( p, n, 1, stdout ); } xfree(p); if( !endless ) count -= n; } if (opt.armor) putchar ('\n'); } break; case aPrintMD: if( argc < 1) wrong_args("--print-md algo [files]"); { int all_algos = (**argv=='*' && !(*argv)[1]); int algo = all_algos? 0 : gcry_md_map_name (*argv); if( !algo && !all_algos ) log_error(_("invalid hash algorithm `%s'\n"), *argv ); else { argc--; argv++; if( !argc ) print_mds(NULL, algo); else { for(; argc; argc--, argv++ ) print_mds(*argv, algo); } } } break; case aPrintMDs: /* old option */ if( !argc ) print_mds(NULL,0); else { for(; argc; argc--, argv++ ) print_mds(*argv,0); } break; case aListTrustDB: if( !argc ) list_trustdb(NULL); else { for( ; argc; argc--, argv++ ) list_trustdb( *argv ); } break; case aUpdateTrustDB: if( argc ) wrong_args("--update-trustdb"); update_trustdb(); break; case aCheckTrustDB: /* Old versions allowed for arguments - ignore them */ check_trustdb(); break; case aFixTrustDB: how_to_fix_the_trustdb (); break; case aListTrustPath: if( !argc ) wrong_args("--list-trust-path "); for( ; argc; argc--, argv++ ) { username = make_username( *argv ); list_trust_path( username ); xfree(username); } break; case aExportOwnerTrust: if( argc ) wrong_args("--export-ownertrust"); export_ownertrust(); break; case aImportOwnerTrust: if( argc > 1 ) wrong_args("--import-ownertrust [file]"); import_ownertrust( argc? *argv:NULL ); break; case aRebuildKeydbCaches: if (argc) wrong_args ("--rebuild-keydb-caches"); keydb_rebuild_caches (1); break; #ifdef ENABLE_CARD_SUPPORT case aCardStatus: if (argc) wrong_args ("--card-status"); - card_status (stdout, NULL, 0); + card_status (es_stdout, NULL, 0); break; case aCardEdit: if (argc) { sl = NULL; for (argc--, argv++ ; argc; argc--, argv++) append_to_strlist (&sl, *argv); card_edit (sl); free_strlist (sl); } else card_edit (NULL); break; case aChangePIN: if (!argc) change_pin (0,1); else if (argc == 1) change_pin (atoi (*argv),1); else wrong_args ("--change-pin [no]"); break; #endif /* ENABLE_CARD_SUPPORT*/ case aListConfig: { char *str=collapse_args(argc,argv); list_config(str); xfree(str); } break; case aListPackets: opt.list_packets=2; default: if( argc > 1 ) wrong_args(_("[filename]")); /* Issue some output for the unix newbie */ if( !fname && !opt.outfile && isatty( fileno(stdin) ) && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) ) log_info(_("Go ahead and type your message ...\n")); a = iobuf_open(fname); if (a && is_secured_file (iobuf_get_fd (a))) { iobuf_close (a); a = NULL; errno = EPERM; } if( !a ) log_error(_("can't open `%s'\n"), print_fname_stdin(fname)); else { if( !opt.no_armor ) { if( use_armor_filter( a ) ) { afx = new_armor_context (); push_armor_filter (afx, a); } } if( cmd == aListPackets ) { set_packet_list_mode(1); opt.list_packets=1; } rc = proc_packets(NULL, a ); if( rc ) log_error("processing message failed: %s\n", g10_errstr(rc) ); iobuf_close(a); } break; } /* cleanup */ release_armor_context (afx); FREE_STRLIST(remusr); FREE_STRLIST(locusr); g10_exit(0); return 8; /*NEVER REACHED*/ } /* Note: This function is used by signal handlers!. */ static void emergency_cleanup (void) { gcry_control (GCRYCTL_TERM_SECMEM ); } void g10_exit( int rc ) { gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE); if ( (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 ); emergency_cleanup (); rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit (rc); } /* Pretty-print hex hashes. This assumes at least an 80-character display, but there are a few other similar assumptions in the display code. */ static void print_hex( gcry_md_hd_t md, int algo, const char *fname ) { int i,n,count,indent=0; const byte *p; if(fname) indent=printf("%s: ",fname); if(indent>40) { printf("\n"); indent=0; } if(algo==DIGEST_ALGO_RMD160) indent+=printf("RMD160 = "); else if(algo>0) indent+=printf("%6s = ", gcry_md_algo_name (algo)); else algo=abs(algo); count=indent; p = gcry_md_read (md, algo); n = gcry_md_get_algo_dlen (algo); count += printf ("%02X",*p++); for(i=1;i79) { printf("\n%*s",indent," "); count=indent; } else count+=printf(" "); if(!(i%8)) count+=printf(" "); } else if (n==20) { if(!(i%2)) { if(count+4>79) { printf("\n%*s",indent," "); count=indent; } else count+=printf(" "); } if(!(i%10)) count+=printf(" "); } else { if(!(i%4)) { if(count+8>79) { printf("\n%*s",indent," "); count=indent; } else count+=printf(" "); } } count+=printf("%02X",*p); } printf("\n"); } static void print_hashline( gcry_md_hd_t md, int algo, const char *fname ) { int i, n; const byte *p; if ( fname ) { for (p = fname; *p; p++ ) { if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' ) printf("%%%02X", *p ); else putchar( *p ); } } putchar(':'); printf("%d:", algo ); p = gcry_md_read (md, algo); n = gcry_md_get_algo_dlen (algo); for(i=0; i < n ; i++, p++ ) printf("%02X", *p ); putchar(':'); putchar('\n'); } static void print_mds( const char *fname, int algo ) { FILE *fp; char buf[1024]; size_t n; gcry_md_hd_t md; if( !fname ) { fp = stdin; #ifdef HAVE_DOSISH_SYSTEM setmode ( fileno(fp) , O_BINARY ); #endif } else { fp = fopen( fname, "rb" ); if (fp && is_secured_file (fileno (fp))) { fclose (fp); fp = NULL; errno = EPERM; } } if( !fp ) { log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) ); return; } gcry_md_open (&md, 0, 0); if( algo ) gcry_md_enable (md, algo); else { gcry_md_enable (md, GCRY_MD_MD5); gcry_md_enable (md, GCRY_MD_SHA1); gcry_md_enable (md, GCRY_MD_RMD160); if (!openpgp_md_test_algo (GCRY_MD_SHA224)) gcry_md_enable (md, GCRY_MD_SHA224); if (!openpgp_md_test_algo (GCRY_MD_SHA256)) gcry_md_enable (md, GCRY_MD_SHA256); if (!openpgp_md_test_algo (GCRY_MD_SHA384)) gcry_md_enable (md, GCRY_MD_SHA384); if (!openpgp_md_test_algo (GCRY_MD_SHA512)) gcry_md_enable (md, GCRY_MD_SHA512); } while( (n=fread( buf, 1, DIM(buf), fp )) ) gcry_md_write (md, buf, n); if( ferror(fp) ) log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) ); else { gcry_md_final (md); if ( opt.with_colons ) { if ( algo ) print_hashline( md, algo, fname ); else { print_hashline( md, GCRY_MD_MD5, fname ); print_hashline( md, GCRY_MD_SHA1, fname ); if (!gcry_md_test_algo (GCRY_MD_RMD160)) print_hashline( md, GCRY_MD_RMD160, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA224)) print_hashline (md, GCRY_MD_SHA224, fname); if (!gcry_md_test_algo (GCRY_MD_SHA256)) print_hashline( md, GCRY_MD_SHA256, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA384)) print_hashline ( md, GCRY_MD_SHA384, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA512)) print_hashline ( md, GCRY_MD_SHA512, fname ); } } else { if( algo ) print_hex(md,-algo,fname); else { print_hex( md, GCRY_MD_MD5, fname ); print_hex( md, GCRY_MD_SHA1, fname ); if (!gcry_md_test_algo (GCRY_MD_RMD160)) print_hex( md, GCRY_MD_RMD160, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA224)) print_hex (md, GCRY_MD_SHA224, fname); if (!gcry_md_test_algo (GCRY_MD_SHA256)) print_hex( md, GCRY_MD_SHA256, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA384)) print_hex( md, GCRY_MD_SHA384, fname ); if (!gcry_md_test_algo (GCRY_MD_SHA512)) print_hex( md, GCRY_MD_SHA512, fname ); } } } gcry_md_close(md); if( fp != stdin ) fclose(fp); } /**************** * Check the supplied name,value string and add it to the notation * data to be used for signatures. which==0 for sig notations, and 1 * for cert notations. */ static void add_notation_data( const char *string, int which ) { struct notation *notation; notation=string_to_notation(string,utf8_strings); if(notation) { if(which) { notation->next=opt.cert_notations; opt.cert_notations=notation; } else { notation->next=opt.sig_notations; opt.sig_notations=notation; } } } static void add_policy_url( const char *string, int which ) { unsigned int i,critical=0; strlist_t sl; if(*string=='!') { string++; critical=1; } for(i=0;iflags |= 1; } static void add_keyserver_url( const char *string, int which ) { unsigned int i,critical=0; strlist_t sl; if(*string=='!') { string++; critical=1; } for(i=0;iflags |= 1; } diff --git a/g10/import.c b/g10/import.c index 8de1d29f0..a46542f65 100644 --- a/g10/import.c +++ b/g10/import.c @@ -1,2463 +1,2463 @@ /* import.c - import a key into our key storage. * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "keydb.h" #include "util.h" #include "trustdb.h" #include "main.h" #include "i18n.h" #include "ttyio.h" #include "status.h" #include "keyserver-internal.h" struct stats_s { ulong count; ulong no_user_id; ulong imported; ulong imported_rsa; ulong n_uids; ulong n_sigs; ulong n_subk; ulong unchanged; ulong n_revoc; ulong secret_read; ulong secret_imported; ulong secret_dups; ulong skipped_new_keys; ulong not_imported; ulong n_sigs_cleaned; ulong n_uids_cleaned; }; static int import( IOBUF inp, const char* fname,struct stats_s *stats, unsigned char **fpr,size_t *fpr_len,unsigned int options ); static int read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root ); static void revocation_present(KBNODE keyblock); static int import_one(const char *fname, KBNODE keyblock,struct stats_s *stats, unsigned char **fpr,size_t *fpr_len, unsigned int options,int from_sk); static int import_secret_one( const char *fname, KBNODE keyblock, struct stats_s *stats, unsigned int options); static int import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats); static int chk_self_sigs( const char *fname, KBNODE keyblock, PKT_public_key *pk, u32 *keyid, int *non_self ); static int delete_inv_parts( const char *fname, KBNODE keyblock, u32 *keyid, unsigned int options ); static int merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock, u32 *keyid, int *n_uids, int *n_sigs, int *n_subk ); static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs, const char *fname, u32 *keyid ); static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs, const char *fname, u32 *keyid ); static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs, const char *fname, u32 *keyid ); static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs, const char *fname, u32 *keyid ); int parse_import_options(char *str,unsigned int *options,int noisy) { struct parse_options import_opts[]= { {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL, N_("import signatures that are marked as local-only")}, {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL, N_("repair damage from the pks keyserver during import")}, {"fast-import",IMPORT_FAST,NULL, N_("do not update the trustdb after import")}, {"convert-sk-to-pk",IMPORT_SK2PK,NULL, N_("create a public key when importing a secret key")}, {"merge-only",IMPORT_MERGE_ONLY,NULL, N_("only accept updates to existing keys")}, {"import-clean",IMPORT_CLEAN,NULL, N_("remove unusable parts from key after import")}, {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL, N_("remove as much as possible from key after import")}, /* Aliases for backward compatibility */ {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL}, {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL}, /* dummy */ {"import-unusable-sigs",0,NULL,NULL}, {"import-clean-sigs",0,NULL,NULL}, {"import-clean-uids",0,NULL,NULL}, {NULL,0,NULL,NULL} }; return parse_options(str,options,import_opts,noisy); } void * import_new_stats_handle (void) { return xmalloc_clear ( sizeof (struct stats_s) ); } void import_release_stats_handle (void *p) { xfree (p); } /**************** * Import the public keys from the given filename. Input may be armored. * This function rejects all keys which are not validly self signed on at * least one userid. Only user ids which are self signed will be imported. * Other signatures are not checked. * * Actually this function does a merge. It works like this: * * - get the keyblock * - check self-signatures and remove all userids and their signatures * without/invalid self-signatures. * - reject the keyblock, if we have no valid userid. * - See whether we have this key already in one of our pubrings. * If not, simply add it to the default keyring. * - Compare the key and the self-signatures of the new and the one in * our keyring. If they are different something weird is going on; * ask what to do. * - See whether we have only non-self-signature on one user id; if not * ask the user what to do. * - compare the signatures: If we already have this signature, check * that they compare okay; if not, issue a warning and ask the user. * (consider looking at the timestamp and use the newest?) * - Simply add the signature. Can't verify here because we may not have * the signature's public key yet; verification is done when putting it * into the trustdb, which is done automagically as soon as this pubkey * is used. * - Proceed with next signature. * * Key revocation certificates have special handling. * */ static int import_keys_internal( IOBUF inp, char **fnames, int nnames, void *stats_handle, unsigned char **fpr, size_t *fpr_len, unsigned int options ) { int i, rc = 0; struct stats_s *stats = stats_handle; if (!stats) stats = import_new_stats_handle (); if (inp) { rc = import( inp, "[stream]", stats, fpr, fpr_len, options); } else { if( !fnames && !nnames ) nnames = 1; /* Ohh what a ugly hack to jump into the loop */ for(i=0; i < nnames; i++ ) { const char *fname = fnames? fnames[i] : NULL; IOBUF inp2 = iobuf_open(fname); if( !fname ) fname = "[stdin]"; if (inp2 && is_secured_file (iobuf_get_fd (inp2))) { iobuf_close (inp2); inp2 = NULL; errno = EPERM; } if( !inp2 ) log_error(_("can't open `%s': %s\n"), fname, strerror(errno) ); else { rc = import( inp2, fname, stats, fpr, fpr_len, options ); iobuf_close(inp2); /* Must invalidate that ugly cache to actually close it. */ iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname); if( rc ) log_error("import from `%s' failed: %s\n", fname, g10_errstr(rc) ); } if( !fname ) break; } } if (!stats_handle) { import_print_stats (stats); import_release_stats_handle (stats); } /* If no fast import and the trustdb is dirty (i.e. we added a key or userID that had something other than a selfsig, a signature that was other than a selfsig, or any revocation), then update/check the trustdb if the user specified by setting interactive or by not setting no-auto-check-trustdb */ if(!(options&IMPORT_FAST)) trustdb_check_or_update(); return rc; } void import_keys( char **fnames, int nnames, void *stats_handle, unsigned int options ) { import_keys_internal(NULL,fnames,nnames,stats_handle,NULL,NULL,options); } int import_keys_stream( IOBUF inp, void *stats_handle, unsigned char **fpr, size_t *fpr_len,unsigned int options ) { return import_keys_internal(inp,NULL,0,stats_handle,fpr,fpr_len,options); } static int import( IOBUF inp, const char* fname,struct stats_s *stats, unsigned char **fpr,size_t *fpr_len,unsigned int options ) { PACKET *pending_pkt = NULL; KBNODE keyblock = NULL; /* Need to initialize because gcc can't grasp the return semantics of read_block. */ int rc = 0; getkey_disable_caches(); if( !opt.no_armor ) { /* armored reading is not disabled */ armor_filter_context_t *afx; afx = new_armor_context (); afx->only_keyblocks = 1; push_armor_filter (afx, inp); release_armor_context (afx); } while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) { if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) rc = import_one( fname, keyblock, stats, fpr, fpr_len, options, 0); else if( keyblock->pkt->pkttype == PKT_SECRET_KEY ) rc = import_secret_one( fname, keyblock, stats, options ); else if( keyblock->pkt->pkttype == PKT_SIGNATURE && keyblock->pkt->pkt.signature->sig_class == 0x20 ) rc = import_revoke_cert( fname, keyblock, stats ); else { log_info( _("skipping block of type %d\n"), keyblock->pkt->pkttype ); } release_kbnode(keyblock); /* fixme: we should increment the not imported counter but this does only make sense if we keep on going despite of errors. */ if( rc ) break; if( !(++stats->count % 100) && !opt.quiet ) log_info(_("%lu keys processed so far\n"), stats->count ); } if( rc == -1 ) rc = 0; else if( rc && rc != G10ERR_INV_KEYRING ) log_error( _("error reading `%s': %s\n"), fname, g10_errstr(rc)); return rc; } void import_print_stats (void *hd) { struct stats_s *stats = hd; if( !opt.quiet ) { log_info(_("Total number processed: %lu\n"), stats->count ); if( stats->skipped_new_keys ) log_info(_(" skipped new keys: %lu\n"), stats->skipped_new_keys ); if( stats->no_user_id ) log_info(_(" w/o user IDs: %lu\n"), stats->no_user_id ); if( stats->imported || stats->imported_rsa ) { log_info(_(" imported: %lu"), stats->imported ); if (stats->imported_rsa) log_printf (" (RSA: %lu)", stats->imported_rsa ); log_printf ("\n"); } if( stats->unchanged ) log_info(_(" unchanged: %lu\n"), stats->unchanged ); if( stats->n_uids ) log_info(_(" new user IDs: %lu\n"), stats->n_uids ); if( stats->n_subk ) log_info(_(" new subkeys: %lu\n"), stats->n_subk ); if( stats->n_sigs ) log_info(_(" new signatures: %lu\n"), stats->n_sigs ); if( stats->n_revoc ) log_info(_(" new key revocations: %lu\n"), stats->n_revoc ); if( stats->secret_read ) log_info(_(" secret keys read: %lu\n"), stats->secret_read ); if( stats->secret_imported ) log_info(_(" secret keys imported: %lu\n"), stats->secret_imported ); if( stats->secret_dups ) log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups ); if( stats->not_imported ) log_info(_(" not imported: %lu\n"), stats->not_imported ); if( stats->n_sigs_cleaned) log_info(_(" signatures cleaned: %lu\n"),stats->n_sigs_cleaned); if( stats->n_uids_cleaned) log_info(_(" user IDs cleaned: %lu\n"),stats->n_uids_cleaned); } if( is_status_enabled() ) { char buf[14*20]; sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", stats->count, stats->no_user_id, stats->imported, stats->imported_rsa, stats->unchanged, stats->n_uids, stats->n_subk, stats->n_sigs, stats->n_revoc, stats->secret_read, stats->secret_imported, stats->secret_dups, stats->skipped_new_keys, stats->not_imported ); write_status_text( STATUS_IMPORT_RES, buf ); } } /**************** * Read the next keyblock from stream A. * PENDING_PKT should be initialzed to NULL * and not chnaged form the caller. * Retunr: 0 = okay, -1 no more blocks or another errorcode. */ static int read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root ) { int rc; PACKET *pkt; KBNODE root = NULL; int in_cert; if( *pending_pkt ) { root = new_kbnode( *pending_pkt ); *pending_pkt = NULL; in_cert = 1; } else in_cert = 0; pkt = xmalloc( sizeof *pkt ); init_packet(pkt); while( (rc=parse_packet(a, pkt)) != -1 ) { if( rc ) { /* ignore errors */ if( rc != G10ERR_UNKNOWN_PACKET ) { log_error("read_block: read error: %s\n", g10_errstr(rc) ); rc = G10ERR_INV_KEYRING; goto ready; } free_packet( pkt ); init_packet(pkt); continue; } if( !root && pkt->pkttype == PKT_SIGNATURE && pkt->pkt.signature->sig_class == 0x20 ) { /* this is a revocation certificate which is handled * in a special way */ root = new_kbnode( pkt ); pkt = NULL; goto ready; } /* make a linked list of all packets */ switch( pkt->pkttype ) { case PKT_COMPRESSED: if(check_compress_algo(pkt->pkt.compressed->algorithm)) { rc = G10ERR_COMPR_ALGO; goto ready; } else { compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx ); pkt->pkt.compressed->buf = NULL; push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1); } free_packet( pkt ); init_packet(pkt); break; case PKT_RING_TRUST: /* skip those packets */ free_packet( pkt ); init_packet(pkt); break; case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: if( in_cert ) { /* store this packet */ *pending_pkt = pkt; pkt = NULL; goto ready; } in_cert = 1; default: if( in_cert ) { if( !root ) root = new_kbnode( pkt ); else add_kbnode( root, new_kbnode( pkt ) ); pkt = xmalloc( sizeof *pkt ); } init_packet(pkt); break; } } ready: if( rc == -1 && root ) rc = 0; if( rc ) release_kbnode( root ); else *ret_root = root; free_packet( pkt ); xfree( pkt ); return rc; } /* Walk through the subkeys on a pk to find if we have the PKS disease: multiple subkeys with their binding sigs stripped, and the sig for the first subkey placed after the last subkey. That is, instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have "pk uid sig sub1 sub2 sub3 bind1". We can't do anything about sub2 and sub3, as they are already lost, but we can try and rescue sub1 by reordering the keyblock so that it reads "pk uid sig sub1 bind1 sub2 sub3". Returns TRUE if the keyblock was modified. */ static int fix_pks_corruption(KBNODE keyblock) { int changed=0,keycount=0; KBNODE node,last=NULL,sknode=NULL; /* First determine if we have the problem at all. Look for 2 or more subkeys in a row, followed by a single binding sig. */ for(node=keyblock;node;last=node,node=node->next) { if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY) { keycount++; if(!sknode) sknode=node; } else if(node->pkt->pkttype==PKT_SIGNATURE && node->pkt->pkt.signature->sig_class==0x18 && keycount>=2 && node->next==NULL) { /* We might have the problem, as this key has two subkeys in a row without any intervening packets. */ /* Sanity check */ if(last==NULL) break; /* Temporarily attach node to sknode. */ node->next=sknode->next; sknode->next=node; last->next=NULL; /* Note we aren't checking whether this binding sig is a selfsig. This is not necessary here as the subkey and binding sig will be rejected later if that is the case. */ if(check_key_signature(keyblock,node,NULL)) { /* Not a match, so undo the changes. */ sknode->next=node->next; last->next=node; node->next=NULL; break; } else { sknode->flag |= 1; /* Mark it good so we don't need to check it again */ changed=1; break; } } else keycount=0; } return changed; } static void print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason) { byte array[MAX_FINGERPRINT_LEN], *s; char buf[MAX_FINGERPRINT_LEN*2+30], *p; size_t i, n; sprintf (buf, "%u ", reason); p = buf + strlen (buf); if (pk) fingerprint_from_pk (pk, array, &n); else fingerprint_from_sk (sk, array, &n); s = array; for (i=0; i < n ; i++, s++, p += 2) sprintf (p, "%02X", *s); write_status_text (STATUS_IMPORT_OK, buf); } static void print_import_check (PKT_public_key * pk, PKT_user_id * id) { char * buf; byte fpr[24]; u32 keyid[2]; size_t i, pos = 0, n; buf = xmalloc (17+41+id->len+32); keyid_from_pk (pk, keyid); sprintf (buf, "%08X%08X ", keyid[0], keyid[1]); pos = 17; fingerprint_from_pk (pk, fpr, &n); for (i = 0; i < n; i++, pos += 2) sprintf (buf+pos, "%02X", fpr[i]); strcat (buf, " "); pos += 1; strcat (buf, id->name); write_status_text (STATUS_IMPORT_CHECK, buf); xfree (buf); } static void check_prefs_warning(PKT_public_key *pk) { log_info(_("WARNING: key %s contains preferences for unavailable\n" "algorithms on these user IDs:\n"), keystr_from_pk(pk)); } static void check_prefs(KBNODE keyblock) { KBNODE node; PKT_public_key *pk; int problem=0; merge_keys_and_selfsig(keyblock); pk=keyblock->pkt->pkt.public_key; for(node=keyblock;node;node=node->next) { if(node->pkt->pkttype==PKT_USER_ID && node->pkt->pkt.user_id->created && node->pkt->pkt.user_id->prefs) { PKT_user_id *uid=node->pkt->pkt.user_id; prefitem_t *prefs=uid->prefs; char *user=utf8_to_native(uid->name,strlen(uid->name),0); for(;prefs->type;prefs++) { char num[10]; /* prefs->value is a byte, so we're over safe here */ sprintf(num,"%u",prefs->value); if(prefs->type==PREFTYPE_SYM) { if (openpgp_cipher_test_algo (prefs->value)) { const char *algo = (openpgp_cipher_test_algo (prefs->value) ? num : openpgp_cipher_algo_name (prefs->value)); if(!problem) check_prefs_warning(pk); log_info(_(" \"%s\": preference for cipher" " algorithm %s\n"), user, algo); problem=1; } } else if(prefs->type==PREFTYPE_HASH) { if(openpgp_md_test_algo(prefs->value)) { const char *algo = (gcry_md_test_algo (prefs->value) ? num : gcry_md_algo_name (prefs->value)); if(!problem) check_prefs_warning(pk); log_info(_(" \"%s\": preference for digest" " algorithm %s\n"), user, algo); problem=1; } } else if(prefs->type==PREFTYPE_ZIP) { if(check_compress_algo (prefs->value)) { const char *algo=compress_algo_to_string(prefs->value); if(!problem) check_prefs_warning(pk); log_info(_(" \"%s\": preference for compression" " algorithm %s\n"),user,algo?algo:num); problem=1; } } } xfree(user); } } if(problem) { log_info(_("it is strongly suggested that you update" " your preferences and\n")); log_info(_("re-distribute this key to avoid potential algorithm" " mismatch problems\n")); if(!opt.batch) { strlist_t sl=NULL,locusr=NULL; size_t fprlen=0; byte fpr[MAX_FINGERPRINT_LEN],*p; char username[(MAX_FINGERPRINT_LEN*2)+1]; unsigned int i; p=fingerprint_from_pk(pk,fpr,&fprlen); for(i=0;ipkt->pkt.public_key; keyid_from_pk( pk, keyid ); uidnode = find_next_kbnode( keyblock, PKT_USER_ID ); if( opt.verbose && !opt.interactive ) { log_info( "pub %4u%c/%s %s ", nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr_from_pk(pk), datestr_from_pk(pk) ); if (uidnode) - print_utf8_string (log_get_stream (), + print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name, uidnode->pkt->pkt.user_id->len ); log_printf ("\n"); } if( !uidnode ) { log_error( _("key %s: no user ID\n"), keystr_from_pk(pk)); return 0; } if (opt.interactive) { if(is_status_enabled()) print_import_check (pk, uidnode->pkt->pkt.user_id); merge_keys_and_selfsig (keyblock); tty_printf ("\n"); show_basic_key_info (keyblock); tty_printf ("\n"); if (!cpr_get_answer_is_yes ("import.okay", "Do you want to import this key? (y/N) ")) return 0; } collapse_uids(&keyblock); /* Clean the key that we're about to import, to cut down on things that we have to clean later. This has no practical impact on the end result, but does result in less logging which might confuse the user. */ if(options&IMPORT_CLEAN) clean_key(keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL); clear_kbnode_flags( keyblock ); if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock) && opt.verbose) log_info(_("key %s: PKS subkey corruption repaired\n"), keystr_from_pk(pk)); rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self ); if( rc ) return rc== -1? 0:rc; /* If we allow such a thing, mark unsigned uids as valid */ if( opt.allow_non_selfsigned_uid ) for( node=keyblock; node; node = node->next ) if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) ) { char *user=utf8_to_native(node->pkt->pkt.user_id->name, node->pkt->pkt.user_id->len,0); node->flag |= 1; log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"), keystr_from_pk(pk),user); xfree(user); } if( !delete_inv_parts( fname, keyblock, keyid, options ) ) { log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk)); if( !opt.quiet ) log_info(_("this may be caused by a missing self-signature\n")); stats->no_user_id++; return 0; } /* do we have this key already in one of our pubrings ? */ pk_orig = xmalloc_clear( sizeof *pk_orig ); rc = get_pubkey_fast ( pk_orig, keyid ); if( rc && rc != G10ERR_NO_PUBKEY && rc != G10ERR_UNU_PUBKEY ) { log_error( _("key %s: public key not found: %s\n"), keystr(keyid), g10_errstr(rc)); } else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) ) { if( opt.verbose ) log_info( _("key %s: new key - skipped\n"), keystr(keyid)); rc = 0; stats->skipped_new_keys++; } else if( rc ) { /* insert this key */ KEYDB_HANDLE hd = keydb_new (0); rc = keydb_locate_writable (hd, NULL); if (rc) { log_error (_("no writable keyring found: %s\n"), g10_errstr (rc)); keydb_release (hd); return G10ERR_GENERAL; } if( opt.verbose > 1 ) log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) ); rc = keydb_insert_keyblock (hd, keyblock ); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc)); else { /* This should not be possible since we delete the ownertrust when a key is deleted, but it can happen if the keyring and trustdb are out of sync. It can also be made to happen with the trusted-key command. */ clear_ownertrusts (pk); if(non_self) revalidation_mark (); } keydb_release (hd); /* we are ready */ if( !opt.quiet ) { char *p=get_user_id_native (keyid); log_info( _("key %s: public key \"%s\" imported\n"), keystr(keyid),p); xfree(p); } if( is_status_enabled() ) { char *us = get_long_user_id_string( keyid ); write_status_text( STATUS_IMPORTED, us ); xfree(us); print_import_ok (pk,NULL, 1); } stats->imported++; if( is_RSA( pk->pubkey_algo ) ) stats->imported_rsa++; new_key = 1; } else { /* merge */ KEYDB_HANDLE hd; int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned; /* Compare the original against the new key; just to be sure nothing * weird is going on */ if( cmp_public_keys( pk_orig, pk ) ) { log_error( _("key %s: doesn't match our copy\n"),keystr(keyid)); goto leave; } /* now read the original keyblock */ hd = keydb_new (0); { byte afp[MAX_FINGERPRINT_LEN]; size_t an; fingerprint_from_pk (pk_orig, afp, &an); while (an < MAX_FINGERPRINT_LEN) afp[an++] = 0; rc = keydb_search_fpr (hd, afp); } if( rc ) { log_error (_("key %s: can't locate original keyblock: %s\n"), keystr(keyid), g10_errstr(rc)); keydb_release (hd); goto leave; } rc = keydb_get_keyblock (hd, &keyblock_orig ); if (rc) { log_error (_("key %s: can't read original keyblock: %s\n"), keystr(keyid), g10_errstr(rc)); keydb_release (hd); goto leave; } /* and try to merge the block */ clear_kbnode_flags( keyblock_orig ); clear_kbnode_flags( keyblock ); n_uids = n_sigs = n_subk = n_sigs_cleaned = n_uids_cleaned = 0; rc = merge_blocks( fname, keyblock_orig, keyblock, keyid, &n_uids, &n_sigs, &n_subk ); if( rc ) { keydb_release (hd); goto leave; } if(options&IMPORT_CLEAN) clean_key(keyblock_orig,opt.verbose,options&IMPORT_MINIMAL, &n_uids_cleaned,&n_sigs_cleaned); if( n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned) { mod_key = 1; /* keyblock_orig has been updated; write */ rc = keydb_update_keyblock (hd, keyblock_orig); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc) ); else if(non_self) revalidation_mark (); /* we are ready */ if( !opt.quiet ) { char *p=get_user_id_native(keyid); if( n_uids == 1 ) log_info( _("key %s: \"%s\" 1 new user ID\n"), keystr(keyid),p); else if( n_uids ) log_info( _("key %s: \"%s\" %d new user IDs\n"), keystr(keyid),p,n_uids); if( n_sigs == 1 ) log_info( _("key %s: \"%s\" 1 new signature\n"), keystr(keyid), p); else if( n_sigs ) log_info( _("key %s: \"%s\" %d new signatures\n"), keystr(keyid), p, n_sigs ); if( n_subk == 1 ) log_info( _("key %s: \"%s\" 1 new subkey\n"), keystr(keyid), p); else if( n_subk ) log_info( _("key %s: \"%s\" %d new subkeys\n"), keystr(keyid), p, n_subk ); if(n_sigs_cleaned==1) log_info(_("key %s: \"%s\" %d signature cleaned\n"), keystr(keyid),p,n_sigs_cleaned); else if(n_sigs_cleaned) log_info(_("key %s: \"%s\" %d signatures cleaned\n"), keystr(keyid),p,n_sigs_cleaned); if(n_uids_cleaned==1) log_info(_("key %s: \"%s\" %d user ID cleaned\n"), keystr(keyid),p,n_uids_cleaned); else if(n_uids_cleaned) log_info(_("key %s: \"%s\" %d user IDs cleaned\n"), keystr(keyid),p,n_uids_cleaned); xfree(p); } stats->n_uids +=n_uids; stats->n_sigs +=n_sigs; stats->n_subk +=n_subk; stats->n_sigs_cleaned +=n_sigs_cleaned; stats->n_uids_cleaned +=n_uids_cleaned; if (is_status_enabled ()) print_import_ok (pk, NULL, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0))); } else { same_key = 1; if (is_status_enabled ()) print_import_ok (pk, NULL, 0); if( !opt.quiet ) { char *p=get_user_id_native(keyid); log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p); xfree(p); } stats->unchanged++; } keydb_release (hd); hd = NULL; } leave: if (mod_key || new_key || same_key) { /* A little explanation for this: we fill in the fingerprint when importing keys as it can be useful to know the fingerprint in certain keyserver-related cases (a keyserver asked for a particular name, but the key doesn't have that name). However, in cases where we're importing more than one key at a time, we cannot know which key to fingerprint. In these cases, rather than guessing, we do not fingerprinting at all, and we must hope the user ID on the keys are useful. Note that we need to do this for new keys, merged keys and even for unchanged keys. This is required because for example the --auto-key-locate feature may import an already imported key and needs to know the fingerprint of the key in all cases. */ if (fpr) { xfree (*fpr); /* Note that we need to compare against 0 here because COUNT gets only incremented after returning form this function. */ if (stats->count == 0) *fpr = fingerprint_from_pk (pk, NULL, fpr_len); else *fpr = NULL; } } /* Now that the key is definitely incorporated into the keydb, we need to check if a designated revocation is present or if the prefs are not rational so we can warn the user. */ if(mod_key) { revocation_present(keyblock_orig); if(!from_sk && seckey_available(keyid)==0) check_prefs(keyblock_orig); } else if(new_key) { revocation_present(keyblock); if(!from_sk && seckey_available(keyid)==0) check_prefs(keyblock); } release_kbnode( keyblock_orig ); free_public_key( pk_orig ); return rc; } /* Walk a secret keyblock and produce a public keyblock out of it. */ static KBNODE sec_to_pub_keyblock(KBNODE sec_keyblock) { KBNODE secnode,pub_keyblock=NULL,ctx=NULL; while((secnode=walk_kbnode(sec_keyblock,&ctx,0))) { KBNODE pubnode; if(secnode->pkt->pkttype==PKT_SECRET_KEY || secnode->pkt->pkttype==PKT_SECRET_SUBKEY) { /* Make a public key. We only need to convert enough to write the keyblock out. */ PKT_secret_key *sk=secnode->pkt->pkt.secret_key; PACKET *pkt=xmalloc_clear(sizeof(PACKET)); PKT_public_key *pk=xmalloc_clear(sizeof(PKT_public_key)); int n; if(secnode->pkt->pkttype==PKT_SECRET_KEY) pkt->pkttype=PKT_PUBLIC_KEY; else pkt->pkttype=PKT_PUBLIC_SUBKEY; pkt->pkt.public_key=pk; pk->version=sk->version; pk->timestamp=sk->timestamp; pk->expiredate=sk->expiredate; pk->pubkey_algo=sk->pubkey_algo; n=pubkey_get_npkey(pk->pubkey_algo); if(n==0) { /* we can't properly extract the pubkey without knowing the number of MPIs */ release_kbnode(pub_keyblock); return NULL; } else { int i; for(i=0;ipkey[i]=mpi_copy(sk->skey[i]); } pubnode=new_kbnode(pkt); } else { pubnode=clone_kbnode(secnode); } if(pub_keyblock==NULL) pub_keyblock=pubnode; else add_kbnode(pub_keyblock,pubnode); } return pub_keyblock; } /**************** * Ditto for secret keys. Handling is simpler than for public keys. * We allow secret key importing only when allow is true, this is so * that a secret key can not be imported accidently and thereby tampering * with the trust calculation. */ static int import_secret_one( const char *fname, KBNODE keyblock, struct stats_s *stats, unsigned int options) { PKT_secret_key *sk; KBNODE node, uidnode; u32 keyid[2]; int rc = 0; /* get the key and print some info about it */ node = find_kbnode( keyblock, PKT_SECRET_KEY ); if( !node ) BUG(); sk = node->pkt->pkt.secret_key; keyid_from_sk( sk, keyid ); uidnode = find_next_kbnode( keyblock, PKT_USER_ID ); if( opt.verbose ) { log_info( "sec %4u%c/%s %s ", nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ), keystr_from_sk(sk), datestr_from_sk(sk) ); if( uidnode ) - print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name, + print_utf8_buffer (es_stderr, uidnode->pkt->pkt.user_id->name, uidnode->pkt->pkt.user_id->len ); log_printf ("\n"); } stats->secret_read++; if( !uidnode ) { log_error( _("key %s: no user ID\n"), keystr_from_sk(sk)); return 0; } if(sk->protect.algo>110) { log_error(_("key %s: secret key with invalid cipher %d" " - skipped\n"),keystr_from_sk(sk),sk->protect.algo); return 0; } #ifdef ENABLE_SELINUX_HACKS if (1) { /* We don't allow to import secret keys because that may be used to put a secret key into the keyring and the user might later be tricked into signing stuff with that key. */ log_error (_("importing secret keys not allowed\n")); return 0; } #endif clear_kbnode_flags( keyblock ); /* do we have this key already in one of our secrings ? */ rc = seckey_available( keyid ); if( rc == G10ERR_NO_SECKEY && !(opt.import_options&IMPORT_MERGE_ONLY) ) { /* simply insert this key */ KEYDB_HANDLE hd = keydb_new (1); /* get default resource */ rc = keydb_locate_writable (hd, NULL); if (rc) { log_error (_("no default secret keyring: %s\n"), g10_errstr (rc)); keydb_release (hd); return G10ERR_GENERAL; } rc = keydb_insert_keyblock (hd, keyblock ); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc) ); keydb_release (hd); /* we are ready */ if( !opt.quiet ) log_info( _("key %s: secret key imported\n"), keystr_from_sk(sk)); stats->secret_imported++; if (is_status_enabled ()) print_import_ok (NULL, sk, 1|16); if(options&IMPORT_SK2PK) { /* Try and make a public key out of this. */ KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock); if(pub_keyblock) { import_one(fname,pub_keyblock,stats, NULL,NULL,opt.import_options,1); release_kbnode(pub_keyblock); } } /* Now that the key is definitely incorporated into the keydb, if we have the public part of this key, we need to check if the prefs are rational. */ node=get_pubkeyblock(keyid); if(node) { check_prefs(node); release_kbnode(node); } } else if( !rc ) { /* we can't merge secret keys */ log_error( _("key %s: already in secret keyring\n"), keystr_from_sk(sk)); stats->secret_dups++; if (is_status_enabled ()) print_import_ok (NULL, sk, 16); /* TODO: if we ever do merge secret keys, make sure to handle the sec_to_pub_keyblock feature as well. */ } else log_error( _("key %s: secret key not found: %s\n"), keystr_from_sk(sk), g10_errstr(rc)); return rc; } /**************** * Import a revocation certificate; this is a single signature packet. */ static int import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats ) { PKT_public_key *pk=NULL; KBNODE onode, keyblock = NULL; KEYDB_HANDLE hd = NULL; u32 keyid[2]; int rc = 0; (void)fname; assert( !node->next ); assert( node->pkt->pkttype == PKT_SIGNATURE ); assert( node->pkt->pkt.signature->sig_class == 0x20 ); keyid[0] = node->pkt->pkt.signature->keyid[0]; keyid[1] = node->pkt->pkt.signature->keyid[1]; pk = xmalloc_clear( sizeof *pk ); rc = get_pubkey( pk, keyid ); if( rc == G10ERR_NO_PUBKEY ) { log_error(_("key %s: no public key -" " can't apply revocation certificate\n"), keystr(keyid)); rc = 0; goto leave; } else if( rc ) { log_error(_("key %s: public key not found: %s\n"), keystr(keyid), g10_errstr(rc)); goto leave; } /* read the original keyblock */ hd = keydb_new (0); { byte afp[MAX_FINGERPRINT_LEN]; size_t an; fingerprint_from_pk (pk, afp, &an); while (an < MAX_FINGERPRINT_LEN) afp[an++] = 0; rc = keydb_search_fpr (hd, afp); } if (rc) { log_error (_("key %s: can't locate original keyblock: %s\n"), keystr(keyid), g10_errstr(rc)); goto leave; } rc = keydb_get_keyblock (hd, &keyblock ); if (rc) { log_error (_("key %s: can't read original keyblock: %s\n"), keystr(keyid), g10_errstr(rc)); goto leave; } /* it is okay, that node is not in keyblock because * check_key_signature works fine for sig_class 0x20 in this * special case. */ rc = check_key_signature( keyblock, node, NULL); if( rc ) { log_error( _("key %s: invalid revocation certificate" ": %s - rejected\n"), keystr(keyid), g10_errstr(rc)); goto leave; } /* check whether we already have this */ for(onode=keyblock->next; onode; onode=onode->next ) { if( onode->pkt->pkttype == PKT_USER_ID ) break; else if( onode->pkt->pkttype == PKT_SIGNATURE && !cmp_signatures(node->pkt->pkt.signature, onode->pkt->pkt.signature)) { rc = 0; goto leave; /* yes, we already know about it */ } } /* insert it */ insert_kbnode( keyblock, clone_kbnode(node), 0 ); /* and write the keyblock back */ rc = keydb_update_keyblock (hd, keyblock ); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc) ); keydb_release (hd); hd = NULL; /* we are ready */ if( !opt.quiet ) { char *p=get_user_id_native (keyid); log_info( _("key %s: \"%s\" revocation certificate imported\n"), keystr(keyid),p); xfree(p); } stats->n_revoc++; /* If the key we just revoked was ultimately trusted, remove its ultimate trust. This doesn't stop the user from putting the ultimate trust back, but is a reasonable solution for now. */ if(get_ownertrust(pk)==TRUST_ULTIMATE) clear_ownertrusts(pk); revalidation_mark (); leave: keydb_release (hd); release_kbnode( keyblock ); free_public_key( pk ); return rc; } /**************** * loop over the keyblock and check all self signatures. * Mark all user-ids with a self-signature by setting flag bit 0. * Mark all user-ids with an invalid self-signature by setting bit 1. * This works also for subkeys, here the subkey is marked. Invalid or * extra subkey sigs (binding or revocation) are marked for deletion. * non_self is set to true if there are any sigs other than self-sigs * in this keyblock. */ static int chk_self_sigs( const char *fname, KBNODE keyblock, PKT_public_key *pk, u32 *keyid, int *non_self ) { KBNODE n,knode=NULL; PKT_signature *sig; int rc; u32 bsdate=0,rsdate=0; KBNODE bsnode=NULL,rsnode=NULL; (void)fname; (void)pk; for( n=keyblock; (n = find_next_kbnode(n, 0)); ) { if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY) { knode=n; bsdate=0; rsdate=0; bsnode=NULL; rsnode=NULL; continue; } else if( n->pkt->pkttype != PKT_SIGNATURE ) continue; sig = n->pkt->pkt.signature; if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) { /* This just caches the sigs for later use. That way we import a fully-cached key which speeds things up. */ if(!opt.no_sig_cache) check_key_signature(keyblock,n,NULL); if( IS_UID_SIG(sig) || IS_UID_REV(sig) ) { KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID ); if( !unode ) { log_error( _("key %s: no user ID for signature\n"), keystr(keyid)); return -1; /* the complete keyblock is invalid */ } /* If it hasn't been marked valid yet, keep trying */ if(!(unode->flag&1)) { rc = check_key_signature( keyblock, n, NULL); if( rc ) { if( opt.verbose ) { char *p=utf8_to_native(unode->pkt->pkt.user_id->name, strlen(unode->pkt->pkt.user_id->name),0); log_info( rc == G10ERR_PUBKEY_ALGO ? _("key %s: unsupported public key " "algorithm on user ID \"%s\"\n"): _("key %s: invalid self-signature " "on user ID \"%s\"\n"), keystr(keyid),p); xfree(p); } } else unode->flag |= 1; /* mark that signature checked */ } } else if( sig->sig_class == 0x18 ) { /* Note that this works based solely on the timestamps like the rest of gpg. If the standard gets revocation targets, this may need to be revised. */ if( !knode ) { if(opt.verbose) log_info( _("key %s: no subkey for key binding\n"), keystr(keyid)); n->flag |= 4; /* delete this */ } else { rc = check_key_signature( keyblock, n, NULL); if( rc ) { if(opt.verbose) log_info(rc == G10ERR_PUBKEY_ALGO ? _("key %s: unsupported public key" " algorithm\n"): _("key %s: invalid subkey binding\n"), keystr(keyid)); n->flag|=4; } else { /* It's valid, so is it newer? */ if(sig->timestamp>=bsdate) { knode->flag |= 1; /* the subkey is valid */ if(bsnode) { bsnode->flag|=4; /* Delete the last binding sig since this one is newer */ if(opt.verbose) log_info(_("key %s: removed multiple subkey" " binding\n"),keystr(keyid)); } bsnode=n; bsdate=sig->timestamp; } else n->flag|=4; /* older */ } } } else if( sig->sig_class == 0x28 ) { /* We don't actually mark the subkey as revoked right now, so just check that the revocation sig is the most recent valid one. Note that we don't care if the binding sig is newer than the revocation sig. See the comment in getkey.c:merge_selfsigs_subkey for more */ if( !knode ) { if(opt.verbose) log_info( _("key %s: no subkey for key revocation\n"), keystr(keyid)); n->flag |= 4; /* delete this */ } else { rc = check_key_signature( keyblock, n, NULL); if( rc ) { if(opt.verbose) log_info(rc == G10ERR_PUBKEY_ALGO ? _("key %s: unsupported public" " key algorithm\n"): _("key %s: invalid subkey revocation\n"), keystr(keyid)); n->flag|=4; } else { /* It's valid, so is it newer? */ if(sig->timestamp>=rsdate) { if(rsnode) { rsnode->flag|=4; /* Delete the last revocation sig since this one is newer */ if(opt.verbose) log_info(_("key %s: removed multiple subkey" " revocation\n"),keystr(keyid)); } rsnode=n; rsdate=sig->timestamp; } else n->flag|=4; /* older */ } } } } else *non_self=1; } return 0; } /**************** * delete all parts which are invalid and those signatures whose * public key algorithm is not available in this implemenation; * but consider RSA as valid, because parse/build_packets knows * about it. * returns: true if at least one valid user-id is left over. */ static int delete_inv_parts( const char *fname, KBNODE keyblock, u32 *keyid, unsigned int options) { KBNODE node; int nvalid=0, uid_seen=0, subkey_seen=0; (void)fname; for(node=keyblock->next; node; node = node->next ) { if( node->pkt->pkttype == PKT_USER_ID ) { uid_seen = 1; if( (node->flag & 2) || !(node->flag & 1) ) { if( opt.verbose ) { char *p=utf8_to_native(node->pkt->pkt.user_id->name, node->pkt->pkt.user_id->len,0); log_info( _("key %s: skipped user ID \"%s\"\n"), keystr(keyid),p); xfree(p); } delete_kbnode( node ); /* the user-id */ /* and all following packets up to the next user-id */ while( node->next && node->next->pkt->pkttype != PKT_USER_ID && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){ delete_kbnode( node->next ); node = node->next; } } else nvalid++; } else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY ) { if( (node->flag & 2) || !(node->flag & 1) ) { if( opt.verbose ) log_info( _("key %s: skipped subkey\n"),keystr(keyid)); delete_kbnode( node ); /* the subkey */ /* and all following signature packets */ while( node->next && node->next->pkt->pkttype == PKT_SIGNATURE ) { delete_kbnode( node->next ); node = node->next; } } else subkey_seen = 1; } else if (node->pkt->pkttype == PKT_SIGNATURE && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo) && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA ) delete_kbnode( node ); /* build_packet() can't handle this */ else if( node->pkt->pkttype == PKT_SIGNATURE && !node->pkt->pkt.signature->flags.exportable && !(options&IMPORT_LOCAL_SIGS) && seckey_available( node->pkt->pkt.signature->keyid ) ) { /* here we violate the rfc a bit by still allowing * to import non-exportable signature when we have the * the secret key used to create this signature - it * seems that this makes sense */ if(opt.verbose) log_info( _("key %s: non exportable signature" " (class 0x%02X) - skipped\n"), keystr(keyid), node->pkt->pkt.signature->sig_class ); delete_kbnode( node ); } else if( node->pkt->pkttype == PKT_SIGNATURE && node->pkt->pkt.signature->sig_class == 0x20 ) { if( uid_seen ) { if(opt.verbose) log_info( _("key %s: revocation certificate" " at wrong place - skipped\n"),keystr(keyid)); delete_kbnode( node ); } else { /* If the revocation cert is from a different key than the one we're working on don't check it - it's probably from a revocation key and won't be verifiable with this key anyway. */ if(node->pkt->pkt.signature->keyid[0]==keyid[0] && node->pkt->pkt.signature->keyid[1]==keyid[1]) { int rc = check_key_signature( keyblock, node, NULL); if( rc ) { if(opt.verbose) log_info( _("key %s: invalid revocation" " certificate: %s - skipped\n"), keystr(keyid), g10_errstr(rc)); delete_kbnode( node ); } } } } else if( node->pkt->pkttype == PKT_SIGNATURE && (node->pkt->pkt.signature->sig_class == 0x18 || node->pkt->pkt.signature->sig_class == 0x28) && !subkey_seen ) { if(opt.verbose) log_info( _("key %s: subkey signature" " in wrong place - skipped\n"), keystr(keyid)); delete_kbnode( node ); } else if( node->pkt->pkttype == PKT_SIGNATURE && !IS_CERT(node->pkt->pkt.signature)) { if(opt.verbose) log_info(_("key %s: unexpected signature class (0x%02X) -" " skipped\n"),keystr(keyid), node->pkt->pkt.signature->sig_class); delete_kbnode(node); } else if( (node->flag & 4) ) /* marked for deletion */ delete_kbnode( node ); } /* note: because keyblock is the public key, it is never marked * for deletion and so keyblock cannot change */ commit_kbnode( &keyblock ); return nvalid; } /**************** * It may happen that the imported keyblock has duplicated user IDs. * We check this here and collapse those user IDs together with their * sigs into one. * Returns: True if the keyblock has changed. */ int collapse_uids( KBNODE *keyblock ) { KBNODE uid1; int any=0; for(uid1=*keyblock;uid1;uid1=uid1->next) { KBNODE uid2; if(is_deleted_kbnode(uid1)) continue; if(uid1->pkt->pkttype!=PKT_USER_ID) continue; for(uid2=uid1->next;uid2;uid2=uid2->next) { if(is_deleted_kbnode(uid2)) continue; if(uid2->pkt->pkttype!=PKT_USER_ID) continue; if(cmp_user_ids(uid1->pkt->pkt.user_id, uid2->pkt->pkt.user_id)==0) { /* We have a duplicated uid */ KBNODE sig1,last; any=1; /* Now take uid2's signatures, and attach them to uid1 */ for(last=uid2;last->next;last=last->next) { if(is_deleted_kbnode(last)) continue; if(last->next->pkt->pkttype==PKT_USER_ID || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY || last->next->pkt->pkttype==PKT_SECRET_SUBKEY) break; } /* Snip out uid2 */ (find_prev_kbnode(*keyblock,uid2,0))->next=last->next; /* Now put uid2 in place as part of uid1 */ last->next=uid1->next; uid1->next=uid2; delete_kbnode(uid2); /* Now dedupe uid1 */ for(sig1=uid1->next;sig1;sig1=sig1->next) { KBNODE sig2; if(is_deleted_kbnode(sig1)) continue; if(sig1->pkt->pkttype==PKT_USER_ID || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY || sig1->pkt->pkttype==PKT_SECRET_SUBKEY) break; if(sig1->pkt->pkttype!=PKT_SIGNATURE) continue; for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next) { if(is_deleted_kbnode(sig2)) continue; if(sig2->pkt->pkttype==PKT_USER_ID || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY || sig2->pkt->pkttype==PKT_SECRET_SUBKEY) break; if(sig2->pkt->pkttype!=PKT_SIGNATURE) continue; if(cmp_signatures(sig1->pkt->pkt.signature, sig2->pkt->pkt.signature)==0) { /* We have a match, so delete the second signature */ delete_kbnode(sig2); sig2=last; } } } } } } commit_kbnode(keyblock); if(any && !opt.quiet) { const char *key="???"; if( (uid1=find_kbnode( *keyblock, PKT_PUBLIC_KEY )) ) key=keystr_from_pk(uid1->pkt->pkt.public_key); else if( (uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY )) ) key=keystr_from_sk(uid1->pkt->pkt.secret_key); log_info(_("key %s: duplicated user ID detected - merged\n"),key); } return any; } /* Check for a 0x20 revocation from a revocation key that is not present. This may be called without the benefit of merge_xxxx so you can't rely on pk->revkey and friends. */ static void revocation_present(KBNODE keyblock) { KBNODE onode,inode; PKT_public_key *pk=keyblock->pkt->pkt.public_key; for(onode=keyblock->next;onode;onode=onode->next) { /* If we reach user IDs, we're done. */ if(onode->pkt->pkttype==PKT_USER_ID) break; if(onode->pkt->pkttype==PKT_SIGNATURE && onode->pkt->pkt.signature->sig_class==0x1F && onode->pkt->pkt.signature->revkey) { int idx; PKT_signature *sig=onode->pkt->pkt.signature; for(idx=0;idxnumrevkeys;idx++) { u32 keyid[2]; keyid_from_fingerprint(sig->revkey[idx]->fpr, MAX_FINGERPRINT_LEN,keyid); for(inode=keyblock->next;inode;inode=inode->next) { /* If we reach user IDs, we're done. */ if(inode->pkt->pkttype==PKT_USER_ID) break; if(inode->pkt->pkttype==PKT_SIGNATURE && inode->pkt->pkt.signature->sig_class==0x20 && inode->pkt->pkt.signature->keyid[0]==keyid[0] && inode->pkt->pkt.signature->keyid[1]==keyid[1]) { /* Okay, we have a revocation key, and a revocation issued by it. Do we have the key itself? */ int rc; rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr, MAX_FINGERPRINT_LEN); if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY) { char *tempkeystr=xstrdup(keystr_from_pk(pk)); /* No, so try and get it */ if(opt.keyserver && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)) { log_info(_("WARNING: key %s may be revoked:" " fetching revocation key %s\n"), tempkeystr,keystr(keyid)); keyserver_import_fprint(sig->revkey[idx]->fpr, MAX_FINGERPRINT_LEN, opt.keyserver); /* Do we have it now? */ rc=get_pubkey_byfprint_fast (NULL, sig->revkey[idx]->fpr, MAX_FINGERPRINT_LEN); } if(rc==G10ERR_NO_PUBKEY || rc==G10ERR_UNU_PUBKEY) log_info(_("WARNING: key %s may be revoked:" " revocation key %s not present.\n"), tempkeystr,keystr(keyid)); xfree(tempkeystr); } } } } } } } /**************** * compare and merge the blocks * * o compare the signatures: If we already have this signature, check * that they compare okay; if not, issue a warning and ask the user. * o Simply add the signature. Can't verify here because we may not have * the signature's public key yet; verification is done when putting it * into the trustdb, which is done automagically as soon as this pubkey * is used. * Note: We indicate newly inserted packets with flag bit 0 */ static int merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock, u32 *keyid, int *n_uids, int *n_sigs, int *n_subk ) { KBNODE onode, node; int rc, found; /* 1st: handle revocation certificates */ for(node=keyblock->next; node; node=node->next ) { if( node->pkt->pkttype == PKT_USER_ID ) break; else if( node->pkt->pkttype == PKT_SIGNATURE && node->pkt->pkt.signature->sig_class == 0x20 ) { /* check whether we already have this */ found = 0; for(onode=keyblock_orig->next; onode; onode=onode->next ) { if( onode->pkt->pkttype == PKT_USER_ID ) break; else if( onode->pkt->pkttype == PKT_SIGNATURE && onode->pkt->pkt.signature->sig_class == 0x20 && !cmp_signatures(onode->pkt->pkt.signature, node->pkt->pkt.signature)) { found = 1; break; } } if( !found ) { KBNODE n2 = clone_kbnode(node); insert_kbnode( keyblock_orig, n2, 0 ); n2->flag |= 1; ++*n_sigs; if(!opt.quiet) { char *p=get_user_id_native (keyid); log_info(_("key %s: \"%s\" revocation" " certificate added\n"), keystr(keyid),p); xfree(p); } } } } /* 2nd: merge in any direct key (0x1F) sigs */ for(node=keyblock->next; node; node=node->next ) { if( node->pkt->pkttype == PKT_USER_ID ) break; else if( node->pkt->pkttype == PKT_SIGNATURE && node->pkt->pkt.signature->sig_class == 0x1F ) { /* check whether we already have this */ found = 0; for(onode=keyblock_orig->next; onode; onode=onode->next ) { if( onode->pkt->pkttype == PKT_USER_ID ) break; else if( onode->pkt->pkttype == PKT_SIGNATURE && onode->pkt->pkt.signature->sig_class == 0x1F && !cmp_signatures(onode->pkt->pkt.signature, node->pkt->pkt.signature)) { found = 1; break; } } if( !found ) { KBNODE n2 = clone_kbnode(node); insert_kbnode( keyblock_orig, n2, 0 ); n2->flag |= 1; ++*n_sigs; if(!opt.quiet) log_info( _("key %s: direct key signature added\n"), keystr(keyid)); } } } /* 3rd: try to merge new certificates in */ for(onode=keyblock_orig->next; onode; onode=onode->next ) { if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) { /* find the user id in the imported keyblock */ for(node=keyblock->next; node; node=node->next ) if( node->pkt->pkttype == PKT_USER_ID && !cmp_user_ids( onode->pkt->pkt.user_id, node->pkt->pkt.user_id ) ) break; if( node ) { /* found: merge */ rc = merge_sigs( onode, node, n_sigs, fname, keyid ); if( rc ) return rc; } } } /* 4th: add new user-ids */ for(node=keyblock->next; node; node=node->next ) { if( node->pkt->pkttype == PKT_USER_ID) { /* do we have this in the original keyblock */ for(onode=keyblock_orig->next; onode; onode=onode->next ) if( onode->pkt->pkttype == PKT_USER_ID && !cmp_user_ids( onode->pkt->pkt.user_id, node->pkt->pkt.user_id ) ) break; if( !onode ) { /* this is a new user id: append */ rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid); if( rc ) return rc; ++*n_uids; } } } /* 5th: add new subkeys */ for(node=keyblock->next; node; node=node->next ) { onode = NULL; if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { /* do we have this in the original keyblock? */ for(onode=keyblock_orig->next; onode; onode=onode->next ) if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY && !cmp_public_keys( onode->pkt->pkt.public_key, node->pkt->pkt.public_key ) ) break; if( !onode ) { /* this is a new subkey: append */ rc = append_key( keyblock_orig, node, n_sigs, fname, keyid); if( rc ) return rc; ++*n_subk; } } else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) { /* do we have this in the original keyblock? */ for(onode=keyblock_orig->next; onode; onode=onode->next ) if( onode->pkt->pkttype == PKT_SECRET_SUBKEY && !cmp_secret_keys( onode->pkt->pkt.secret_key, node->pkt->pkt.secret_key ) ) break; if( !onode ) { /* this is a new subkey: append */ rc = append_key( keyblock_orig, node, n_sigs, fname, keyid); if( rc ) return rc; ++*n_subk; } } } /* 6th: merge subkey certificates */ for(onode=keyblock_orig->next; onode; onode=onode->next ) { if( !(onode->flag & 1) && ( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) { /* find the subkey in the imported keyblock */ for(node=keyblock->next; node; node=node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY && !cmp_public_keys( onode->pkt->pkt.public_key, node->pkt->pkt.public_key ) ) break; else if( node->pkt->pkttype == PKT_SECRET_SUBKEY && !cmp_secret_keys( onode->pkt->pkt.secret_key, node->pkt->pkt.secret_key ) ) break; } if( node ) { /* found: merge */ rc = merge_keysigs( onode, node, n_sigs, fname, keyid ); if( rc ) return rc; } } } return 0; } /**************** * append the userid starting with NODE and all signatures to KEYBLOCK. */ static int append_uid (KBNODE keyblock, KBNODE node, int *n_sigs, const char *fname, u32 *keyid ) { KBNODE n, n_where=NULL; (void)fname; (void)keyid; assert(node->pkt->pkttype == PKT_USER_ID ); /* find the position */ for( n = keyblock; n; n_where = n, n = n->next ) { if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY || n->pkt->pkttype == PKT_SECRET_SUBKEY ) break; } if( !n ) n_where = NULL; /* and append/insert */ while( node ) { /* we add a clone to the original keyblock, because this * one is released first */ n = clone_kbnode(node); if( n_where ) { insert_kbnode( n_where, n, 0 ); n_where = n; } else add_kbnode( keyblock, n ); n->flag |= 1; node->flag |= 1; if( n->pkt->pkttype == PKT_SIGNATURE ) ++*n_sigs; node = node->next; if( node && node->pkt->pkttype != PKT_SIGNATURE ) break; } return 0; } /**************** * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID. * (how should we handle comment packets here?) */ static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs, const char *fname, u32 *keyid ) { KBNODE n, n2; int found=0; (void)fname; (void)keyid; assert(dst->pkt->pkttype == PKT_USER_ID ); assert(src->pkt->pkttype == PKT_USER_ID ); for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) { if( n->pkt->pkttype != PKT_SIGNATURE ) continue; if( n->pkt->pkt.signature->sig_class == 0x18 || n->pkt->pkt.signature->sig_class == 0x28 ) continue; /* skip signatures which are only valid on subkeys */ found = 0; for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next) if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature)) { found++; break; } if( !found ) { /* This signature is new or newer, append N to DST. * We add a clone to the original keyblock, because this * one is released first */ n2 = clone_kbnode(n); insert_kbnode( dst, n2, PKT_SIGNATURE ); n2->flag |= 1; n->flag |= 1; ++*n_sigs; } } return 0; } /**************** * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY. */ static int merge_keysigs (KBNODE dst, KBNODE src, int *n_sigs, const char *fname, u32 *keyid) { KBNODE n, n2; int found=0; (void)fname; (void)keyid; assert( dst->pkt->pkttype == PKT_PUBLIC_SUBKEY || dst->pkt->pkttype == PKT_SECRET_SUBKEY ); for(n=src->next; n ; n = n->next ) { if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY || n->pkt->pkttype == PKT_PUBLIC_KEY ) break; if( n->pkt->pkttype != PKT_SIGNATURE ) continue; found = 0; for(n2=dst->next; n2; n2 = n2->next){ if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY || n2->pkt->pkttype == PKT_PUBLIC_KEY ) break; if( n2->pkt->pkttype == PKT_SIGNATURE && n->pkt->pkt.signature->keyid[0] == n2->pkt->pkt.signature->keyid[0] && n->pkt->pkt.signature->keyid[1] == n2->pkt->pkt.signature->keyid[1] && n->pkt->pkt.signature->timestamp <= n2->pkt->pkt.signature->timestamp && n->pkt->pkt.signature->sig_class == n2->pkt->pkt.signature->sig_class ) { found++; break; } } if( !found ) { /* This signature is new or newer, append N to DST. * We add a clone to the original keyblock, because this * one is released first */ n2 = clone_kbnode(n); insert_kbnode( dst, n2, PKT_SIGNATURE ); n2->flag |= 1; n->flag |= 1; ++*n_sigs; } } return 0; } /**************** * append the subkey starting with NODE and all signatures to KEYBLOCK. * Mark all new and copied packets by setting flag bit 0. */ static int append_key (KBNODE keyblock, KBNODE node, int *n_sigs, const char *fname, u32 *keyid) { KBNODE n; (void)fname; (void)keyid; assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY ); while( node ) { /* we add a clone to the original keyblock, because this * one is released first */ n = clone_kbnode(node); add_kbnode( keyblock, n ); n->flag |= 1; node->flag |= 1; if( n->pkt->pkttype == PKT_SIGNATURE ) ++*n_sigs; node = node->next; if( node && node->pkt->pkttype != PKT_SIGNATURE ) break; } return 0; } /* Walk a public keyblock and produce a secret keyblock out of it. Instead of inserting the secret key parameters (which we don't have), we insert a stub. */ static KBNODE pub_to_sec_keyblock (KBNODE pub_keyblock) { KBNODE pubnode, secnode; KBNODE sec_keyblock = NULL; KBNODE walkctx = NULL; while((pubnode = walk_kbnode (pub_keyblock,&walkctx,0))) { if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY || pubnode->pkt->pkttype == PKT_PUBLIC_SUBKEY) { /* Make a secret key. We only need to convert enough to write the keyblock out. */ PKT_public_key *pk = pubnode->pkt->pkt.public_key; PACKET *pkt = xmalloc_clear (sizeof *pkt); PKT_secret_key *sk = xmalloc_clear (sizeof *sk); int i, n; if (pubnode->pkt->pkttype == PKT_PUBLIC_KEY) pkt->pkttype = PKT_SECRET_KEY; else pkt->pkttype = PKT_SECRET_SUBKEY; pkt->pkt.secret_key = sk; copy_public_parts_to_secret_key ( pk, sk ); sk->version = pk->version; sk->timestamp = pk->timestamp; n = pubkey_get_npkey (pk->pubkey_algo); if (!n) n = 1; /* Unknown number of parameters, however the data is stored in the first mpi. */ for (i=0; i < n; i++ ) sk->skey[i] = mpi_copy (pk->pkey[i]); sk->is_protected = 1; sk->protect.s2k.mode = 1001; secnode = new_kbnode (pkt); } else { secnode = clone_kbnode (pubnode); } if(!sec_keyblock) sec_keyblock = secnode; else add_kbnode (sec_keyblock, secnode); } return sec_keyblock; } /* Walk over the secret keyring SEC_KEYBLOCK and update any simple stub keys with the serial number SNNUM of the card if one of the fingerprints FPR1, FPR2 or FPR3 match. Print a note if the key is a duplicate (may happen in case of backed uped keys). Returns: True if anything changed. */ static int update_sec_keyblock_with_cardinfo (KBNODE sec_keyblock, const unsigned char *fpr1, const unsigned char *fpr2, const unsigned char *fpr3, const char *serialnostr) { KBNODE node; KBNODE walkctx = NULL; PKT_secret_key *sk; byte array[MAX_FINGERPRINT_LEN]; size_t n; int result = 0; const char *s; while((node = walk_kbnode (sec_keyblock, &walkctx, 0))) { if (node->pkt->pkttype != PKT_SECRET_KEY && node->pkt->pkttype != PKT_SECRET_SUBKEY) continue; sk = node->pkt->pkt.secret_key; fingerprint_from_sk (sk, array, &n); if (n != 20) continue; /* Can't be a card key. */ if ( !((fpr1 && !memcmp (array, fpr1, 20)) || (fpr2 && !memcmp (array, fpr2, 20)) || (fpr3 && !memcmp (array, fpr3, 20))) ) continue; /* No match. */ if (sk->is_protected == 1 && sk->protect.s2k.mode == 1001) { /* Standard case: migrate that stub to a key stub. */ sk->protect.s2k.mode = 1002; s = serialnostr; for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1]; sk->protect.ivlen++, s += 2) sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s); result = 1; } else if (sk->is_protected == 1 && sk->protect.s2k.mode == 1002) { s = serialnostr; for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1]; sk->protect.ivlen++, s += 2) if (sk->protect.iv[sk->protect.ivlen] != xtoi_2 (s)) { log_info (_("NOTE: a key's S/N does not " "match the card's one\n")); break; } } else { if (node->pkt->pkttype != PKT_SECRET_KEY) log_info (_("NOTE: primary key is online and stored on card\n")); else log_info (_("NOTE: secondary key is online and stored on card\n")); } } return result; } /* Check whether a secret key stub exists for the public key PK. If not create such a stub key and store it into the secring. If it exists, add appropriate subkey stubs and update the secring. Return 0 if the key could be created. */ int auto_create_card_key_stub ( const char *serialnostr, const unsigned char *fpr1, const unsigned char *fpr2, const unsigned char *fpr3) { KBNODE pub_keyblock; KBNODE sec_keyblock; KEYDB_HANDLE hd; int rc; /* We only want to do this for an OpenPGP card. */ if (!serialnostr || strncmp (serialnostr, "D27600012401", 12) || strlen (serialnostr) != 32 ) return G10ERR_GENERAL; /* First get the public keyring from any of the provided fingerprints. */ if ( (fpr1 && !get_keyblock_byfprint (&pub_keyblock, fpr1, 20)) || (fpr2 && !get_keyblock_byfprint (&pub_keyblock, fpr2, 20)) || (fpr3 && !get_keyblock_byfprint (&pub_keyblock, fpr3, 20))) ; else return G10ERR_GENERAL; hd = keydb_new (1); /* Now check whether there is a secret keyring. */ { PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key; byte afp[MAX_FINGERPRINT_LEN]; size_t an; fingerprint_from_pk (pk, afp, &an); if (an < MAX_FINGERPRINT_LEN) memset (afp+an, 0, MAX_FINGERPRINT_LEN-an); rc = keydb_search_fpr (hd, afp); } if (!rc) { rc = keydb_get_keyblock (hd, &sec_keyblock); if (rc) { log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) ); rc = G10ERR_GENERAL; } else { merge_keys_and_selfsig (sec_keyblock); /* FIXME: We need to add new subkeys first. */ if (update_sec_keyblock_with_cardinfo (sec_keyblock, fpr1, fpr2, fpr3, serialnostr)) { rc = keydb_update_keyblock (hd, sec_keyblock ); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc) ); } } } else /* A secret key does not exists - create it. */ { sec_keyblock = pub_to_sec_keyblock (pub_keyblock); update_sec_keyblock_with_cardinfo (sec_keyblock, fpr1, fpr2, fpr3, serialnostr); rc = keydb_locate_writable (hd, NULL); if (rc) { log_error (_("no default secret keyring: %s\n"), g10_errstr (rc)); rc = G10ERR_GENERAL; } else { rc = keydb_insert_keyblock (hd, sec_keyblock ); if (rc) log_error (_("error writing keyring `%s': %s\n"), keydb_get_resource_name (hd), g10_errstr(rc) ); } } release_kbnode (sec_keyblock); release_kbnode (pub_keyblock); keydb_release (hd); return rc; } diff --git a/g10/kbnode.c b/g10/kbnode.c index 3d7d9be5c..f481c9fdb 100644 --- a/g10/kbnode.c +++ b/g10/kbnode.c @@ -1,398 +1,406 @@ /* kbnode.c - keyblock node utility functions * Copyright (C) 1998, 1999, 2000, 2001, 2002, - * 2005 Free Software Foundation, Inc. + * 2005, 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 "gpg.h" #include "util.h" #include "packet.h" #include "keydb.h" #define USE_UNUSED_NODES 1 static KBNODE unused_nodes; static KBNODE alloc_node(void) { KBNODE n; n = unused_nodes; if( n ) unused_nodes = n->next; else n = xmalloc( sizeof *n ); n->next = NULL; n->pkt = NULL; n->flag = 0; n->private_flag=0; n->recno = 0; return n; } static void free_node( KBNODE n ) { if( n ) { #if USE_UNUSED_NODES n->next = unused_nodes; unused_nodes = n; #else xfree( n ); #endif } } KBNODE new_kbnode( PACKET *pkt ) { KBNODE n = alloc_node(); n->pkt = pkt; return n; } KBNODE clone_kbnode( KBNODE node ) { KBNODE n = alloc_node(); n->pkt = node->pkt; n->private_flag = node->private_flag | 2; /* mark cloned */ return n; } void release_kbnode( KBNODE n ) { KBNODE n2; while( n ) { n2 = n->next; if( !is_cloned_kbnode(n) ) { free_packet( n->pkt ); xfree( n->pkt ); } free_node( n ); n = n2; } } /**************** * Delete NODE. * Note: This only works with walk_kbnode!! */ void delete_kbnode( KBNODE node ) { node->private_flag |= 1; } /**************** * Append NODE to ROOT. ROOT must exist! */ void add_kbnode( KBNODE root, KBNODE node ) { KBNODE n1; for(n1=root; n1->next; n1 = n1->next) ; n1->next = node; } /**************** * Insert NODE into the list after root but before a packet which is not of * type PKTTYPE * (only if PKTTYPE != 0) */ void insert_kbnode( KBNODE root, KBNODE node, int pkttype ) { if( !pkttype ) { node->next = root->next; root->next = node; } else { KBNODE n1; for(n1=root; n1->next; n1 = n1->next) if( pkttype != n1->next->pkt->pkttype ) { node->next = n1->next; n1->next = node; return; } /* no such packet, append */ node->next = NULL; n1->next = node; } } /**************** * Find the previous node (if PKTTYPE = 0) or the previous node * with pkttype PKTTYPE in the list starting with ROOT of NODE. */ KBNODE find_prev_kbnode( KBNODE root, KBNODE node, int pkttype ) { KBNODE n1; for (n1=NULL; root && root != node; root = root->next ) { if (!pkttype ||root->pkt->pkttype == pkttype) n1 = root; } return n1; } /**************** * Ditto, but find the next packet. The behaviour is trivial if * PKTTYPE is 0 but if it is specified, the next node with a packet * of this type is returned. The function has some knowledge about * the valid ordering of packets: e.g. if the next signature packet * is requested, the function will not return one if it encounters * a user-id. */ KBNODE find_next_kbnode( KBNODE node, int pkttype ) { for( node=node->next ; node; node = node->next ) { if( !pkttype ) return node; else if( pkttype == PKT_USER_ID && ( node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_SECRET_KEY ) ) return NULL; else if( pkttype == PKT_SIGNATURE && ( node->pkt->pkttype == PKT_USER_ID || node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_SECRET_KEY ) ) return NULL; else if( node->pkt->pkttype == pkttype ) return node; } return NULL; } KBNODE find_kbnode( KBNODE node, int pkttype ) { for( ; node; node = node->next ) { if( node->pkt->pkttype == pkttype ) return node; } return NULL; } /**************** * Walk through a list of kbnodes. This function returns * the next kbnode for each call; before using the function the first * time, the caller must set CONTEXT to NULL (This has simply the effect * to start with ROOT). */ KBNODE walk_kbnode( KBNODE root, KBNODE *context, int all ) { KBNODE n; do { if( !*context ) { *context = root; n = root; } else { n = (*context)->next; *context = n; } } while( !all && n && is_deleted_kbnode(n) ); return n; } void clear_kbnode_flags( KBNODE n ) { for( ; n; n = n->next ) { n->flag = 0; } } /**************** * Commit changes made to the kblist at ROOT. Note that ROOT my change, * and it is therefore passed by reference. * The function has the effect of removing all nodes marked as deleted. * returns true if any node has been changed */ int commit_kbnode( KBNODE *root ) { KBNODE n, nl; int changed = 0; for( n = *root, nl=NULL; n; n = nl->next ) { if( is_deleted_kbnode(n) ) { if( n == *root ) *root = nl = n->next; else nl->next = n->next; if( !is_cloned_kbnode(n) ) { free_packet( n->pkt ); xfree( n->pkt ); } free_node( n ); changed = 1; } else nl = n; } return changed; } void remove_kbnode( KBNODE *root, KBNODE node ) { KBNODE n, nl; for( n = *root, nl=NULL; n; n = nl->next ) { if( n == node ) { if( n == *root ) *root = nl = n->next; else nl->next = n->next; if( !is_cloned_kbnode(n) ) { free_packet( n->pkt ); xfree( n->pkt ); } free_node( n ); } else nl = n; } } /**************** * Move NODE behind right after WHERE or to the beginning if WHERE is NULL. */ void move_kbnode( KBNODE *root, KBNODE node, KBNODE where ) { KBNODE tmp, prev; if( !root || !*root || !node ) return; /* sanity check */ for( prev = *root; prev && prev->next != node; prev = prev->next ) ; if( !prev ) return; /* node is not in the list */ if( !where ) { /* move node before root */ if( node == *root ) /* move to itself */ return; prev->next = node->next; node->next = *root; *root = node; return; } /* move it after where */ if( node == where ) return; tmp = node->next; node->next = where->next; where->next = node; prev->next = tmp; } void -dump_kbnode( KBNODE node ) +dump_kbnode (KBNODE node) { - for(; node; node = node->next ) { - const char *s; - switch( node->pkt->pkttype ) { - case 0: s="empty"; break; - case PKT_PUBLIC_KEY: s="public-key"; break; - case PKT_SECRET_KEY: s="secret-key"; break; - case PKT_SECRET_SUBKEY: s= "secret-subkey"; break; - case PKT_PUBKEY_ENC: s="public-enc"; break; - case PKT_SIGNATURE: s="signature"; break; - case PKT_ONEPASS_SIG: s="onepass-sig"; break; - case PKT_USER_ID: s="user-id"; break; - case PKT_PUBLIC_SUBKEY: s="public-subkey"; break; - case PKT_COMMENT: s="comment"; break; - case PKT_RING_TRUST: s="trust"; break; - case PKT_PLAINTEXT: s="plaintext"; break; - case PKT_COMPRESSED: s="compressed"; break; - case PKT_ENCRYPTED: s="encrypted"; break; - case PKT_GPG_CONTROL: s="gpg-control"; break; - default: s="unknown"; break; + for (; node; node = node->next ) + { + const char *s; + switch (node->pkt->pkttype) + { + case 0: s="empty"; break; + case PKT_PUBLIC_KEY: s="public-key"; break; + case PKT_SECRET_KEY: s="secret-key"; break; + case PKT_SECRET_SUBKEY: s= "secret-subkey"; break; + case PKT_PUBKEY_ENC: s="public-enc"; break; + case PKT_SIGNATURE: s="signature"; break; + case PKT_ONEPASS_SIG: s="onepass-sig"; break; + case PKT_USER_ID: s="user-id"; break; + case PKT_PUBLIC_SUBKEY: s="public-subkey"; break; + case PKT_COMMENT: s="comment"; break; + case PKT_RING_TRUST: s="trust"; break; + case PKT_PLAINTEXT: s="plaintext"; break; + case PKT_COMPRESSED: s="compressed"; break; + case PKT_ENCRYPTED: s="encrypted"; break; + case PKT_GPG_CONTROL: s="gpg-control"; break; + default: s="unknown"; break; } - fprintf(stderr, "node %p %02x/%02x type=%s", - node, node->flag, node->private_flag, s); - if( node->pkt->pkttype == PKT_USER_ID ) { - PKT_user_id *uid = node->pkt->pkt.user_id; - fputs(" \"", stderr); - print_string( stderr, uid->name, uid->len, 0 ); - fprintf (stderr, "\" %c%c%c%c\n", - uid->is_expired? 'e':'.', - uid->is_revoked? 'r':'.', - uid->created? 'v':'.', - uid->is_primary? 'p':'.' ); - } - else if( node->pkt->pkttype == PKT_SIGNATURE ) { - fprintf(stderr, " class=%02x keyid=%08lX ts=%lu\n", - node->pkt->pkt.signature->sig_class, - (ulong)node->pkt->pkt.signature->keyid[1], - (ulong)node->pkt->pkt.signature->timestamp); - } - else if( node->pkt->pkttype == PKT_GPG_CONTROL ) { - fprintf(stderr, " ctrl=%d len=%u\n", - node->pkt->pkt.gpg_control->control, - (unsigned int)node->pkt->pkt.gpg_control->datalen); - } - else if( node->pkt->pkttype == PKT_PUBLIC_KEY - || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { - PKT_public_key *pk = node->pkt->pkt.public_key; - fprintf(stderr, " keyid=%08lX a=%d u=%d %c%c%c%c\n", - (ulong)keyid_from_pk( pk, NULL ), - pk->pubkey_algo, pk->pubkey_usage, - pk->has_expired? 'e':'.', - pk->is_revoked? 'r':'.', - pk->is_valid? 'v':'.', - pk->mdc_feature? 'm':'.'); - } - else - fputs("\n", stderr); + log_debug ("node %p %02x/%02x type=%s", + node, node->flag, node->private_flag, s); + if (node->pkt->pkttype == PKT_USER_ID) + { + PKT_user_id *uid = node->pkt->pkt.user_id; + log_printf (" \""); + es_write_sanitized (log_get_stream (), uid->name, uid->len, + NULL, NULL); + log_printf ("\" %c%c%c%c\n", + uid->is_expired? 'e':'.', + uid->is_revoked? 'r':'.', + uid->created? 'v':'.', + uid->is_primary? 'p':'.' ); + } + else if (node->pkt->pkttype == PKT_SIGNATURE) + { + log_printf (" class=%02x keyid=%08lX ts=%lu\n", + node->pkt->pkt.signature->sig_class, + (ulong)node->pkt->pkt.signature->keyid[1], + (ulong)node->pkt->pkt.signature->timestamp); + } + else if (node->pkt->pkttype == PKT_GPG_CONTROL) + { + log_printf (" ctrl=%d len=%u\n", + node->pkt->pkt.gpg_control->control, + (unsigned int)node->pkt->pkt.gpg_control->datalen); + } + else if (node->pkt->pkttype == PKT_PUBLIC_KEY + || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) + { + PKT_public_key *pk = node->pkt->pkt.public_key; + + log_printf (" keyid=%08lX a=%d u=%d %c%c%c%c\n", + (ulong)keyid_from_pk( pk, NULL ), + pk->pubkey_algo, pk->pubkey_usage, + pk->has_expired? 'e':'.', + pk->is_revoked? 'r':'.', + pk->is_valid? 'v':'.', + pk->mdc_feature? 'm':'.'); + } + + log_flush (); } } diff --git a/g10/keyedit.c b/g10/keyedit.c index 270b3bacb..e9b92b232 100644 --- a/g10/keyedit.c +++ b/g10/keyedit.c @@ -1,5302 +1,5305 @@ /* keyedit.c - keyedit stuff * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LIBREADLINE #define GNUPG_LIBREADLINE_H_INCLUDED #include #endif #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "iobuf.h" #include "keydb.h" #include "photoid.h" #include "util.h" #include "main.h" #include "trustdb.h" #include "filter.h" #include "ttyio.h" #include "status.h" #include "i18n.h" #include "keyserver-internal.h" static void show_prefs( PKT_user_id *uid, PKT_signature *selfsig, int verbose); static void show_names(KBNODE keyblock,PKT_public_key *pk, unsigned int flag,int with_prefs); static void show_key_with_all_names( KBNODE keyblock, int only_marked, int with_revoker, int with_fpr, int with_subkeys, int with_prefs ); static void show_key_and_fingerprint( KBNODE keyblock ); static int menu_adduid( KBNODE keyblock, KBNODE sec_keyblock, int photo, const char *photo_name ); static void menu_deluid( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_delsig( KBNODE pub_keyblock ); static int menu_clean(KBNODE keyblock,int self_only); static void menu_delkey( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_addrevoker( KBNODE pub_keyblock, KBNODE sec_keyblock, int sensitive ); static int menu_expire( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_backsign(KBNODE pub_keyblock,KBNODE sec_keyblock); static int menu_set_primary_uid( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_set_preferences( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_set_keyserver_url (const char *url, KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_set_notation(const char *string, KBNODE pub_keyblock,KBNODE sec_keyblock); static int menu_select_uid( KBNODE keyblock, int idx ); static int menu_select_uid_namehash( KBNODE keyblock, const char *namehash ); static int menu_select_key( KBNODE keyblock, int idx ); static int count_uids( KBNODE keyblock ); static int count_uids_with_flag( KBNODE keyblock, unsigned flag ); static int count_keys_with_flag( KBNODE keyblock, unsigned flag ); static int count_selected_uids( KBNODE keyblock ); static int real_uids_left( KBNODE keyblock ); static int count_selected_keys( KBNODE keyblock ); static int menu_revsig( KBNODE keyblock ); static int menu_revuid( KBNODE keyblock, KBNODE sec_keyblock ); static int menu_revkey( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int menu_revsubkey( KBNODE pub_keyblock, KBNODE sec_keyblock ); static int enable_disable_key( KBNODE keyblock, int disable ); static void menu_showphoto( KBNODE keyblock ); static int update_trust=0; #define CONTROL_D ('D' - 'A' + 1) #define NODFLG_BADSIG (1<<0) /* bad signature */ #define NODFLG_NOKEY (1<<1) /* no public key */ #define NODFLG_SIGERR (1<<2) /* other sig error */ #define NODFLG_MARK_A (1<<4) /* temporary mark */ #define NODFLG_DELSIG (1<<5) /* to be deleted */ #define NODFLG_SELUID (1<<8) /* indicate the selected userid */ #define NODFLG_SELKEY (1<<9) /* indicate the selected key */ #define NODFLG_SELSIG (1<<10) /* indicate a selected signature */ struct sign_attrib { int non_exportable,non_revocable; struct revocation_reason_info *reason; byte trust_depth,trust_value; char *trust_regexp; }; #ifdef ENABLE_CARD_SUPPORT /* Given a node SEC_NODE with a secret key or subkey, locate the corresponding public key from pub_keyblock. */ static PKT_public_key * find_pk_from_sknode (KBNODE pub_keyblock, KBNODE sec_node) { KBNODE node = pub_keyblock; PKT_secret_key *sk; PKT_public_key *pk; if (sec_node->pkt->pkttype == PKT_SECRET_KEY && node->pkt->pkttype == PKT_PUBLIC_KEY) return node->pkt->pkt.public_key; if (sec_node->pkt->pkttype != PKT_SECRET_SUBKEY) return NULL; sk = sec_node->pkt->pkt.secret_key; for (; node; node = node->next) if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { pk = node->pkt->pkt.public_key; if (pk->keyid[0] == sk->keyid[0] && pk->keyid[1] == sk->keyid[1]) return pk; } return NULL; } #endif /* ENABLE_CARD_SUPPORT */ /* TODO: Fix duplicated code between here and the check-sigs/list-sigs code in keylist.c. */ static int print_and_check_one_sig_colon( KBNODE keyblock, KBNODE node, int *inv_sigs, int *no_key, int *oth_err, int *is_selfsig, int print_without_key ) { PKT_signature *sig = node->pkt->pkt.signature; int rc, sigrc; /* TODO: Make sure a cached sig record here still has the pk that issued it. See also keylist.c:list_keyblock_print */ switch((rc=check_key_signature(keyblock,node,is_selfsig))) { case 0: node->flag &= ~(NODFLG_BADSIG|NODFLG_NOKEY|NODFLG_SIGERR); sigrc = '!'; break; case G10ERR_BAD_SIGN: node->flag = NODFLG_BADSIG; sigrc = '-'; if( inv_sigs ) ++*inv_sigs; break; case G10ERR_NO_PUBKEY: case G10ERR_UNU_PUBKEY: node->flag = NODFLG_NOKEY; sigrc = '?'; if( no_key ) ++*no_key; break; default: node->flag = NODFLG_SIGERR; sigrc = '%'; if( oth_err ) ++*oth_err; break; } if( sigrc != '?' || print_without_key ) { printf("sig:%c::%d:%08lX%08lX:%lu:%lu:", sigrc,sig->pubkey_algo,(ulong)sig->keyid[0],(ulong)sig->keyid[1], (ulong)sig->timestamp,(ulong)sig->expiredate); if(sig->trust_depth || sig->trust_value) printf("%d %d",sig->trust_depth,sig->trust_value); printf(":"); if(sig->trust_regexp) - print_string(stdout,sig->trust_regexp,strlen(sig->trust_regexp),':'); + es_write_sanitized (es_stdout, + sig->trust_regexp, strlen (sig->trust_regexp), + ":", NULL); printf("::%02x%c\n",sig->sig_class,sig->flags.exportable?'x':'l'); if(opt.show_subpackets) print_subpackets_colon(sig); } return (sigrc == '!'); } /**************** * Print information about a signature, check it and return true * if the signature is okay. NODE must be a signature packet. */ static int print_and_check_one_sig( KBNODE keyblock, KBNODE node, int *inv_sigs, int *no_key, int *oth_err, int *is_selfsig, int print_without_key ) { PKT_signature *sig = node->pkt->pkt.signature; int rc, sigrc; int is_rev = sig->sig_class == 0x30; /* TODO: Make sure a cached sig record here still has the pk that issued it. See also keylist.c:list_keyblock_print */ switch( (rc = check_key_signature( keyblock, node, is_selfsig)) ) { case 0: node->flag &= ~(NODFLG_BADSIG|NODFLG_NOKEY|NODFLG_SIGERR); sigrc = '!'; break; case G10ERR_BAD_SIGN: node->flag = NODFLG_BADSIG; sigrc = '-'; if( inv_sigs ) ++*inv_sigs; break; case G10ERR_NO_PUBKEY: case G10ERR_UNU_PUBKEY: node->flag = NODFLG_NOKEY; sigrc = '?'; if( no_key ) ++*no_key; break; default: node->flag = NODFLG_SIGERR; sigrc = '%'; if( oth_err ) ++*oth_err; break; } if( sigrc != '?' || print_without_key ) { tty_printf("%s%c%c %c%c%c%c%c%c %s %s", is_rev? "rev":"sig",sigrc, (sig->sig_class-0x10>0 && sig->sig_class-0x10<4)?'0'+sig->sig_class-0x10:' ', sig->flags.exportable?' ':'L', sig->flags.revocable?' ':'R', sig->flags.policy_url?'P':' ', sig->flags.notation?'N':' ', sig->flags.expired?'X':' ', (sig->trust_depth>9)?'T': (sig->trust_depth>0)?'0'+sig->trust_depth:' ', keystr(sig->keyid),datestr_from_sig(sig)); if(opt.list_options&LIST_SHOW_SIG_EXPIRE) tty_printf(" %s",expirestr_from_sig(sig)); tty_printf(" "); if( sigrc == '%' ) tty_printf("[%s] ", g10_errstr(rc) ); else if( sigrc == '?' ) ; else if( *is_selfsig ) { tty_printf( is_rev? _("[revocation]") : _("[self-signature]") ); } else { size_t n; char *p = get_user_id( sig->keyid, &n ); tty_print_utf8_string2(p, n, opt.screen_columns-keystrlen()-26- ((opt.list_options&LIST_SHOW_SIG_EXPIRE)?11:0)); xfree(p); } tty_printf("\n"); if(sig->flags.policy_url && (opt.list_options&LIST_SHOW_POLICY_URLS)) show_policy_url(sig,3,0); if(sig->flags.notation && (opt.list_options&LIST_SHOW_NOTATIONS)) show_notation(sig,3,0, ((opt.list_options&LIST_SHOW_STD_NOTATIONS)?1:0)+ ((opt.list_options&LIST_SHOW_USER_NOTATIONS)?2:0)); if(sig->flags.pref_ks && (opt.list_options&LIST_SHOW_KEYSERVER_URLS)) show_keyserver_url(sig,3,0); } return (sigrc == '!'); } /**************** * Check the keysigs and set the flags to indicate errors. * Returns true if error found. */ static int check_all_keysigs( KBNODE keyblock, int only_selected ) { KBNODE kbctx; KBNODE node; int inv_sigs = 0; int no_key = 0; int oth_err = 0; int has_selfsig = 0; int mis_selfsig = 0; int selected = !only_selected; int anyuid = 0; for( kbctx=NULL; (node=walk_kbnode( keyblock, &kbctx, 0)) ; ) { if( node->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *uid = node->pkt->pkt.user_id; if( only_selected ) selected = (node->flag & NODFLG_SELUID); if( selected ) { tty_printf("uid "); tty_print_utf8_string( uid->name, uid->len ); tty_printf("\n"); if( anyuid && !has_selfsig ) mis_selfsig++; has_selfsig = 0; anyuid = 1; } } else if( selected && node->pkt->pkttype == PKT_SIGNATURE && ( (node->pkt->pkt.signature->sig_class&~3) == 0x10 || node->pkt->pkt.signature->sig_class == 0x30 ) ) { int selfsig; if( print_and_check_one_sig( keyblock, node, &inv_sigs, &no_key, &oth_err, &selfsig, 0 ) ) { if( selfsig ) has_selfsig = 1; } /* Hmmm: should we update the trustdb here? */ } } if( !has_selfsig ) mis_selfsig++; if( inv_sigs == 1 ) tty_printf(_("1 bad signature\n") ); else if( inv_sigs ) tty_printf(_("%d bad signatures\n"), inv_sigs ); if( no_key == 1 ) tty_printf(_("1 signature not checked due to a missing key\n") ); else if( no_key ) tty_printf(_("%d signatures not checked due to missing keys\n"), no_key ); if( oth_err == 1 ) tty_printf(_("1 signature not checked due to an error\n") ); else if( oth_err ) tty_printf(_("%d signatures not checked due to errors\n"), oth_err ); if( mis_selfsig == 1 ) tty_printf(_("1 user ID without valid self-signature detected\n")); else if( mis_selfsig ) tty_printf(_("%d user IDs without valid self-signatures detected\n"), mis_selfsig); return inv_sigs || no_key || oth_err || mis_selfsig; } static int sign_mk_attrib( PKT_signature *sig, void *opaque ) { struct sign_attrib *attrib = opaque; byte buf[8]; if( attrib->non_exportable ) { buf[0] = 0; /* not exportable */ build_sig_subpkt( sig, SIGSUBPKT_EXPORTABLE, buf, 1 ); } if( attrib->non_revocable ) { buf[0] = 0; /* not revocable */ build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 ); } if( attrib->reason ) revocation_reason_build_cb( sig, attrib->reason ); if(attrib->trust_depth) { /* Not critical. If someone doesn't understand trust sigs, this can still be a valid regular signature. */ buf[0] = attrib->trust_depth; buf[1] = attrib->trust_value; build_sig_subpkt(sig,SIGSUBPKT_TRUST,buf,2); /* Critical. If someone doesn't understands regexps, this whole sig should be invalid. Note the +1 for the length - regexps are null terminated. */ if(attrib->trust_regexp) build_sig_subpkt(sig,SIGSUBPKT_FLAG_CRITICAL|SIGSUBPKT_REGEXP, attrib->trust_regexp, strlen(attrib->trust_regexp)+1); } return 0; } static void trustsig_prompt(byte *trust_value,byte *trust_depth,char **regexp) { char *p; *trust_value=0; *trust_depth=0; *regexp=NULL; /* Same string as pkclist.c:do_edit_ownertrust */ tty_printf(_("Please decide how far you trust this user to correctly verify" " other users' keys\n(by looking at passports, checking" " fingerprints from different sources, etc.)\n")); tty_printf("\n"); tty_printf (_(" %d = I trust marginally\n"), 1); tty_printf (_(" %d = I trust fully\n"), 2); tty_printf("\n"); while(*trust_value==0) { p = cpr_get("trustsig_prompt.trust_value",_("Your selection? ")); trim_spaces(p); cpr_kill_prompt(); /* 60 and 120 are as per RFC2440 */ if(p[0]=='1' && !p[1]) *trust_value=60; else if(p[0]=='2' && !p[1]) *trust_value=120; xfree(p); } tty_printf("\n"); tty_printf(_( "Please enter the depth of this trust signature.\n" "A depth greater than 1 allows the key you are signing to make\n" "trust signatures on your behalf.\n")); tty_printf("\n"); while(*trust_depth==0) { p = cpr_get("trustsig_prompt.trust_depth",_("Your selection? ")); trim_spaces(p); cpr_kill_prompt(); *trust_depth=atoi(p); xfree(p); } tty_printf("\n"); tty_printf(_("Please enter a domain to restrict this signature, " "or enter for none.\n")); tty_printf("\n"); p=cpr_get("trustsig_prompt.trust_regexp",_("Your selection? ")); trim_spaces(p); cpr_kill_prompt(); if(strlen(p)>0) { char *q=p; int regexplen=100,ind; *regexp=xmalloc(regexplen); /* Now mangle the domain the user entered into a regexp. To do this, \-escape everything that isn't alphanumeric, and attach "<[^>]+[@.]" to the front, and ">$" to the end. */ strcpy(*regexp,"<[^>]+[@.]"); ind=strlen(*regexp); while(*q) { if(!((*q>='A' && *q<='Z') || (*q>='a' && *q<='z') || (*q>='0' && *q<='9'))) (*regexp)[ind++]='\\'; (*regexp)[ind++]=*q; if((regexplen-ind)<3) { regexplen+=100; *regexp=xrealloc(*regexp,regexplen); } q++; } (*regexp)[ind]='\0'; strcat(*regexp,">$"); } xfree(p); tty_printf("\n"); } /**************** * Loop over all locusr and and sign the uids after asking. * If no user id is marked, all user ids will be signed; * if some user_ids are marked those will be signed. */ static int sign_uids( KBNODE keyblock, strlist_t locusr, int *ret_modified, int local, int nonrevocable, int trust, int interactive ) { int rc = 0; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; PKT_public_key *pk = NULL; KBNODE node, uidnode; PKT_public_key *primary_pk=NULL; int select_all = !count_selected_uids(keyblock) || interactive; int all_v3=1; /* Are there any non-v3 sigs on this key already? */ if(PGP2) for(node=keyblock;node;node=node->next) if(node->pkt->pkttype==PKT_SIGNATURE && node->pkt->pkt.signature->version>3) { all_v3=0; break; } /* build a list of all signators. * * We use the CERT flag to request the primary which must always * be one which is capable of signing keys. I can't see a reason * why to sign keys using a subkey. Implementation of USAGE_CERT * is just a hack in getkey.c and does not mean that a subkey * marked as certification capable will be used. */ rc=build_sk_list( locusr, &sk_list, 0, PUBKEY_USAGE_CERT); if( rc ) goto leave; /* loop over all signators */ for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { u32 sk_keyid[2],pk_keyid[2]; char *p,*trust_regexp=NULL; int force_v4=0,class=0,selfsig=0; u32 duration=0,timestamp=0; byte trust_depth=0,trust_value=0; if(local || nonrevocable || trust || opt.cert_policy_url || opt.cert_notations) force_v4=1; /* We have to use a copy of the pk, because make_keysig_packet * may remove the protection from sk and if we did other * changes to the secret key, we would save the unprotected * version. FIXME: This can be removed because all protection * is now done by gpg-agent. */ if (pk) free_public_key (pk); pk = copy_public_key (NULL, sk_rover->pk); keyid_from_pk (pk, sk_keyid); /* set mark A for all selected user ids */ for( node=keyblock; node; node = node->next ) { if( select_all || (node->flag & NODFLG_SELUID) ) node->flag |= NODFLG_MARK_A; else node->flag &= ~NODFLG_MARK_A; } /* reset mark for uids which are already signed */ uidnode = NULL; for( node=keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) { primary_pk=node->pkt->pkt.public_key; keyid_from_pk( primary_pk, pk_keyid ); /* Is this a self-sig? */ if(pk_keyid[0]==sk_keyid[0] && pk_keyid[1]==sk_keyid[1]) { selfsig=1; /* Do not force a v4 sig here, otherwise it would be difficult to remake a v3 selfsig. If this is a v3->v4 promotion case, then we set force_v4 later anyway. */ force_v4=0; } } else if( node->pkt->pkttype == PKT_USER_ID ) { uidnode = (node->flag & NODFLG_MARK_A)? node : NULL; if(uidnode) { int yesreally=0; char *user=utf8_to_native(uidnode->pkt->pkt.user_id->name, uidnode->pkt->pkt.user_id->len, 0); if(uidnode->pkt->pkt.user_id->is_revoked) { tty_printf(_("User ID \"%s\" is revoked."),user); if(selfsig) tty_printf("\n"); else if(opt.expert) { tty_printf("\n"); /* No, so remove the mark and continue */ if(!cpr_get_answer_is_yes("sign_uid.revoke_okay", _("Are you sure you " "still want to sign " "it? (y/N) "))) { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; } else if(interactive) yesreally=1; } else { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; tty_printf(_(" Unable to sign.\n")); } } else if(uidnode->pkt->pkt.user_id->is_expired) { tty_printf(_("User ID \"%s\" is expired."),user); if(selfsig) tty_printf("\n"); else if(opt.expert) { tty_printf("\n"); /* No, so remove the mark and continue */ if(!cpr_get_answer_is_yes("sign_uid.expire_okay", _("Are you sure you " "still want to sign " "it? (y/N) "))) { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; } else if(interactive) yesreally=1; } else { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; tty_printf(_(" Unable to sign.\n")); } } else if(!uidnode->pkt->pkt.user_id->created && !selfsig) { tty_printf(_("User ID \"%s\" is not self-signed."), user); if(opt.expert) { tty_printf("\n"); /* No, so remove the mark and continue */ if(!cpr_get_answer_is_yes("sign_uid.nosig_okay", _("Are you sure you " "still want to sign " "it? (y/N) "))) { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; } else if(interactive) yesreally=1; } else { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; tty_printf(_(" Unable to sign.\n")); } } if(uidnode && interactive && !yesreally) { tty_printf(_("User ID \"%s\" is signable. "),user); if(!cpr_get_answer_is_yes("sign_uid.sign_okay", _("Sign it? (y/N) "))) { uidnode->flag &= ~NODFLG_MARK_A; uidnode=NULL; } } xfree(user); } } else if( uidnode && node->pkt->pkttype == PKT_SIGNATURE && (node->pkt->pkt.signature->sig_class&~3) == 0x10 ) { if( sk_keyid[0] == node->pkt->pkt.signature->keyid[0] && sk_keyid[1] == node->pkt->pkt.signature->keyid[1] ) { char buf[50]; char *user=utf8_to_native(uidnode->pkt->pkt.user_id->name, uidnode->pkt->pkt.user_id->len, 0); /* It's a v3 self-sig. Make it into a v4 self-sig? */ if(node->pkt->pkt.signature->version<4 && selfsig) { tty_printf(_("The self-signature on \"%s\"\n" "is a PGP 2.x-style signature.\n"),user); /* Note that the regular PGP2 warning below still applies if there are no v4 sigs on this key at all. */ if(opt.expert) if(cpr_get_answer_is_yes("sign_uid.v4_promote_okay", _("Do you want to promote " "it to an OpenPGP self-" "signature? (y/N) "))) { force_v4=1; node->flag|=NODFLG_DELSIG; xfree(user); continue; } } /* Is the current signature expired? */ if(node->pkt->pkt.signature->flags.expired) { tty_printf(_("Your current signature on \"%s\"\n" "has expired.\n"),user); if(cpr_get_answer_is_yes("sign_uid.replace_expired_okay", _("Do you want to issue a " "new signature to replace " "the expired one? (y/N) "))) { /* Mark these for later deletion. We don't want to delete them here, just in case the replacement signature doesn't happen for some reason. We only delete these after the replacement is already in place. */ node->flag|=NODFLG_DELSIG; xfree(user); continue; } } if(!node->pkt->pkt.signature->flags.exportable && !local) { /* It's a local sig, and we want to make a exportable sig. */ tty_printf(_("Your current signature on \"%s\"\n" "is a local signature.\n"),user); if(cpr_get_answer_is_yes("sign_uid.local_promote_okay", _("Do you want to promote " "it to a full exportable " "signature? (y/N) "))) { /* Mark these for later deletion. We don't want to delete them here, just in case the replacement signature doesn't happen for some reason. We only delete these after the replacement is already in place. */ node->flag|=NODFLG_DELSIG; xfree(user); continue; } } /* Fixme: see whether there is a revocation in which * case we should allow to sign it again. */ if (!node->pkt->pkt.signature->flags.exportable && local) tty_printf(_( "\"%s\" was already locally signed by key %s\n"), user,keystr_from_pk (pk)); else tty_printf(_("\"%s\" was already signed by key %s\n"), user,keystr_from_pk (pk)); if(opt.expert && cpr_get_answer_is_yes("sign_uid.dupe_okay", _("Do you want to sign it " "again anyway? (y/N) "))) { /* Don't delete the old sig here since this is an --expert thing. */ xfree(user); continue; } snprintf (buf, sizeof buf, "%08lX%08lX", (ulong)pk->keyid[0], (ulong)pk->keyid[1]); write_status_text (STATUS_ALREADY_SIGNED, buf); uidnode->flag &= ~NODFLG_MARK_A; /* remove mark */ xfree(user); } } } /* check whether any uids are left for signing */ if( !count_uids_with_flag(keyblock, NODFLG_MARK_A) ) { tty_printf (_("Nothing to sign with key %s\n"), keystr_from_pk (pk)); continue; } /* Ask whether we really should sign these user id(s) */ tty_printf("\n"); show_key_with_all_names( keyblock, 1, 0, 1, 0, 0 ); tty_printf("\n"); if(primary_pk->expiredate && !selfsig) { u32 now=make_timestamp(); if(primary_pk->expiredate<=now) { tty_printf(_("This key has expired!")); if(opt.expert) { tty_printf(" "); if(!cpr_get_answer_is_yes("sign_uid.expired_okay", _("Are you sure you still " "want to sign it? (y/N) "))) continue; } else { tty_printf(_(" Unable to sign.\n")); continue; } } else { tty_printf(_("This key is due to expire on %s.\n"), expirestr_from_pk(primary_pk)); if(opt.ask_cert_expire) { char *answer=cpr_get("sign_uid.expire", _("Do you want your signature to " "expire at the same time? (Y/n) ")); if(answer_is_yes_no_default(answer,1)) { /* This fixes the signature timestamp we're going to make as now. This is so the expiration date is exactly correct, and not a few seconds off (due to the time it takes to answer the questions, enter the passphrase, etc). */ timestamp=now; duration=primary_pk->expiredate-now; force_v4=1; } cpr_kill_prompt(); xfree(answer); } } } /* Only ask for duration if we haven't already set it to match the expiration of the pk */ if(!duration && !selfsig) { if(opt.ask_cert_expire) duration=ask_expire_interval(1,opt.def_cert_expire); else duration=parse_expire_string(opt.def_cert_expire); } if(duration) force_v4=1; /* Is --pgp2 on, it's a v3 key, all the sigs on the key are currently v3 and we're about to sign it with a v4 sig? If so, danger! */ if(PGP2 && all_v3 && (pk->version > 3 || force_v4) && primary_pk->version <= 3) { tty_printf(_("You may not make an OpenPGP signature on a " "PGP 2.x key while in --pgp2 mode.\n")); tty_printf(_("This would make the key unusable in PGP 2.x.\n")); if(opt.expert) { if(!cpr_get_answer_is_yes("sign_uid.v4_on_v3_okay", _("Are you sure you still " "want to sign it? (y/N) "))) continue; all_v3=0; } else continue; } if(selfsig) ; else { if(opt.batch || !opt.ask_cert_level) class=0x10+opt.def_cert_level; else { char *answer; tty_printf(_("How carefully have you verified the key you are " "about to sign actually belongs\nto the person " "named above? If you don't know what to " "answer, enter \"0\".\n")); tty_printf("\n"); tty_printf(_(" (0) I will not answer.%s\n"), opt.def_cert_level==0?" (default)":""); tty_printf(_(" (1) I have not checked at all.%s\n"), opt.def_cert_level==1?" (default)":""); tty_printf(_(" (2) I have done casual checking.%s\n"), opt.def_cert_level==2?" (default)":""); tty_printf(_(" (3) I have done very careful checking.%s\n"), opt.def_cert_level==3?" (default)":""); tty_printf("\n"); while(class==0) { answer = cpr_get("sign_uid.class",_("Your selection? " "(enter `?' for more information): ")); if(answer[0]=='\0') class=0x10+opt.def_cert_level; /* Default */ else if(ascii_strcasecmp(answer,"0")==0) class=0x10; /* Generic */ else if(ascii_strcasecmp(answer,"1")==0) class=0x11; /* Persona */ else if(ascii_strcasecmp(answer,"2")==0) class=0x12; /* Casual */ else if(ascii_strcasecmp(answer,"3")==0) class=0x13; /* Positive */ else tty_printf(_("Invalid selection.\n")); xfree(answer); } } if(trust) trustsig_prompt(&trust_value,&trust_depth,&trust_regexp); } p=get_user_id_native(sk_keyid); tty_printf (_("Are you sure that you want to sign this key with your\n" "key \"%s\" (%s)\n"), p, keystr_from_pk (pk)); xfree(p); if(selfsig) { tty_printf("\n"); tty_printf(_("This will be a self-signature.\n")); if( local ) { tty_printf("\n"); tty_printf( _("WARNING: the signature will not be marked " "as non-exportable.\n")); } if( nonrevocable ) { tty_printf("\n"); tty_printf( _("WARNING: the signature will not be marked " "as non-revocable.\n")); } } else { if( local ) { tty_printf("\n"); tty_printf( _("The signature will be marked as non-exportable.\n")); } if( nonrevocable ) { tty_printf("\n"); tty_printf( _("The signature will be marked as non-revocable.\n")); } switch(class) { case 0x11: tty_printf("\n"); tty_printf(_("I have not checked this key at all.\n")); break; case 0x12: tty_printf("\n"); tty_printf(_("I have checked this key casually.\n")); break; case 0x13: tty_printf("\n"); tty_printf(_("I have checked this key very carefully.\n")); break; } } tty_printf("\n"); if( opt.batch && opt.answer_yes ) ; else if( !cpr_get_answer_is_yes("sign_uid.okay", _("Really sign? (y/N) ")) ) continue; /* now we can sign the user ids */ reloop: /* (must use this, because we are modifing the list) */ primary_pk = NULL; for( node=keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) primary_pk = node->pkt->pkt.public_key; else if( node->pkt->pkttype == PKT_USER_ID && (node->flag & NODFLG_MARK_A) ) { PACKET *pkt; PKT_signature *sig; struct sign_attrib attrib; assert( primary_pk ); memset( &attrib, 0, sizeof attrib ); attrib.non_exportable = local; attrib.non_revocable = nonrevocable; attrib.trust_depth = trust_depth; attrib.trust_value = trust_value; attrib.trust_regexp = trust_regexp; node->flag &= ~NODFLG_MARK_A; /* we force creation of a v4 signature for local * signatures, otherwise we would not generate the * subpacket with v3 keys and the signature becomes * exportable */ if(selfsig) rc = make_keysig_packet( &sig, primary_pk, node->pkt->pkt.user_id, NULL, pk, 0x13, 0, force_v4?4:0, 0, 0, keygen_add_std_prefs, primary_pk); else rc = make_keysig_packet( &sig, primary_pk, node->pkt->pkt.user_id, NULL, pk, class, 0, force_v4?4:0, timestamp, duration, sign_mk_attrib, &attrib ); if( rc ) { log_error(_("signing failed: %s\n"), g10_errstr(rc)); goto leave; } *ret_modified = 1; /* we changed the keyblock */ update_trust = 1; pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( node, new_kbnode(pkt), PKT_SIGNATURE ); goto reloop; } } /* Delete any sigs that got promoted */ for( node=keyblock; node; node = node->next ) if( node->flag & NODFLG_DELSIG) delete_kbnode(node); } /* end loop over signators */ leave: release_sk_list( sk_list ); if (pk) free_public_key (pk); return rc; } /**************** * Change the passphrase of the primary and all secondary keys. * We use only one passphrase for all keys. */ static int -change_passphrase( KBNODE keyblock ) +change_passphrase (KBNODE keyblock, int *r_err) { int rc = 0; int changed=0; KBNODE node; PKT_secret_key *sk; char *passphrase = NULL; int no_primary_secrets = 0; int any; node = find_kbnode( keyblock, PKT_SECRET_KEY ); if( !node ) { log_error("Oops; secret key not found anymore!\n"); goto leave; } sk = node->pkt->pkt.secret_key; for (any = 0, node=keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { PKT_secret_key *tmpsk = node->pkt->pkt.secret_key; if (!(tmpsk->is_protected && (tmpsk->protect.s2k.mode == 1001 || tmpsk->protect.s2k.mode == 1002))) { any = 1; break; } } } if (!any) { tty_printf (_("Key has only stub or on-card key items - " "no passphrase to change.\n")); goto leave; } /* See how to handle this key. */ switch( is_secret_key_protected( sk ) ) { case -1: rc = G10ERR_PUBKEY_ALGO; break; case 0: tty_printf(_("This key is not protected.\n")); break; default: if( sk->protect.s2k.mode == 1001 ) { tty_printf(_("Secret parts of key are not available.\n")); no_primary_secrets = 1; } else if( sk->protect.s2k.mode == 1002 ) { tty_printf(_("Secret parts of key are stored on-card.\n")); no_primary_secrets = 1; } else { u32 keyid[2]; tty_printf(_("Key is protected.\n")); /* Clear the passphrase cache so that the user is required to enter the old passphrase. */ keyid_from_sk (sk, keyid); passphrase_clear_cache (keyid, NULL, 0); rc = check_secret_key( sk, 0 ); if( !rc ) passphrase = get_last_passphrase(); } break; } /* Unprotect all subkeys (use the supplied passphrase or ask)*/ for(node=keyblock; !rc && node; node = node->next ) { if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) { PKT_secret_key *subsk = node->pkt->pkt.secret_key; if ( !(subsk->is_protected && (subsk->protect.s2k.mode == 1001 || subsk->protect.s2k.mode == 1002))) { set_next_passphrase( passphrase ); rc = check_secret_key( subsk, 0 ); if( !rc && !passphrase ) passphrase = get_last_passphrase(); } } } if( rc ) tty_printf(_("Can't edit this key: %s\n"), g10_errstr(rc)); else { DEK *dek = NULL; STRING2KEY *s2k = xmalloc_secure( sizeof *s2k ); const char *errtext = NULL; tty_printf(_("Enter the new passphrase for this secret key.\n\n") ); set_next_passphrase( NULL ); for(;;) { int canceled; s2k->mode = opt.s2k_mode; s2k->hash_algo = S2K_DIGEST_ALGO; dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2, errtext, &canceled); if (!dek && canceled) { rc = GPG_ERR_CANCELED; break; } else if( !dek ) { errtext = N_("passphrase not correctly repeated; try again"); tty_printf ("%s.\n", _(errtext)); } else if( !dek->keylen ) { rc = 0; tty_printf(_( "You don't want a passphrase -" " this is probably a *bad* idea!\n\n")); if( cpr_get_answer_is_yes("change_passwd.empty.okay", _("Do you really want to do this? (y/N) "))) { changed++; break; } } else { /* okay */ rc = 0; if( !no_primary_secrets ) { sk->protect.algo = dek->algo; sk->protect.s2k = *s2k; rc = protect_secret_key( sk, dek ); } for(node=keyblock; !rc && node; node = node->next ) { if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) { PKT_secret_key *subsk = node->pkt->pkt.secret_key; if ( !(subsk->is_protected && (subsk->protect.s2k.mode == 1001 || subsk->protect.s2k.mode == 1002))) { subsk->protect.algo = dek->algo; subsk->protect.s2k = *s2k; rc = protect_secret_key( subsk, dek ); } } } if( rc ) log_error("protect_secret_key failed: %s\n", g10_errstr(rc) ); else { u32 keyid[2]; /* Clear the cahce again so that the user is required to enter the new passphrase at the next operation. */ keyid_from_sk (sk, keyid); passphrase_clear_cache (keyid, NULL, 0); changed++; } break; } } xfree(s2k); xfree(dek); } leave: xfree( passphrase ); set_next_passphrase( NULL ); + if (r_err) + *r_err = rc; return changed && !rc; } /**************** * There are some keys out (due to a bug in gnupg), where the sequence * of the packets is wrong. This function fixes that. * Returns: true if the keyblock has been fixed. * * Note: This function does not work if there is more than one user ID. */ static int fix_keyblock( KBNODE keyblock ) { KBNODE node, last, subkey; int fixed=0; /* locate key signatures of class 0x10..0x13 behind sub key packets */ for( subkey=last=NULL, node = keyblock; node; last=node, node = node->next ) { switch( node->pkt->pkttype ) { case PKT_PUBLIC_SUBKEY: case PKT_SECRET_SUBKEY: if( !subkey ) subkey = last; /* actually it is the one before the subkey */ break; case PKT_SIGNATURE: if( subkey ) { PKT_signature *sig = node->pkt->pkt.signature; if( sig->sig_class >= 0x10 && sig->sig_class <= 0x13 ) { log_info(_( "moving a key signature to the correct place\n")); last->next = node->next; node->next = subkey->next; subkey->next = node; node = last; fixed=1; } } break; default: break; } } return fixed; } static int parse_sign_type(const char *str,int *localsig,int *nonrevokesig,int *trustsig) { const char *p=str; while(*p) { if(ascii_strncasecmp(p,"l",1)==0) { *localsig=1; p++; } else if(ascii_strncasecmp(p,"nr",2)==0) { *nonrevokesig=1; p+=2; } else if(ascii_strncasecmp(p,"t",1)==0) { *trustsig=1; p++; } else return 0; } return 1; } /**************** * Menu driven key editor. If seckey_check is true, then a secret key * that matches username will be looked for. If it is false, not all * commands will be available. * * Note: to keep track of some selection we use node->mark MARKBIT_xxxx. */ /* Need an SK for this command */ #define KEYEDIT_NEED_SK 1 /* Cannot be viewing the SK for this command */ #define KEYEDIT_NOT_SK 2 /* Must be viewing the SK for this command */ #define KEYEDIT_ONLY_SK 4 /* Match the tail of the string */ #define KEYEDIT_TAIL_MATCH 8 enum cmdids { cmdNONE = 0, cmdQUIT, cmdHELP, cmdFPR, cmdLIST, cmdSELUID, cmdCHECK, cmdSIGN, cmdREVSIG, cmdREVKEY, cmdREVUID, cmdDELSIG, cmdPRIMARY, cmdDEBUG, cmdSAVE, cmdADDUID, cmdADDPHOTO, cmdDELUID, cmdADDKEY, cmdDELKEY, cmdADDREVOKER, cmdTOGGLE, cmdSELKEY, cmdPASSWD, cmdTRUST, cmdPREF, cmdEXPIRE, cmdBACKSIGN, cmdENABLEKEY, cmdDISABLEKEY, cmdSHOWPREF, cmdSETPREF, cmdPREFKS, cmdNOTATION, cmdINVCMD, cmdSHOWPHOTO, cmdUPDTRUST, cmdCHKTRUST, cmdADDCARDKEY, cmdKEYTOCARD, cmdBKUPTOCARD, cmdCHECKBKUPKEY, cmdCLEAN, cmdMINIMIZE, cmdNOP }; static struct { const char *name; enum cmdids id; int flags; const char *desc; } cmds[] = { { "quit" , cmdQUIT , 0, N_("quit this menu") }, { "q" , cmdQUIT , 0, NULL }, { "save" , cmdSAVE , 0, N_("save and quit") }, { "help" , cmdHELP , 0, N_("show this help") }, { "?" , cmdHELP , 0, NULL }, { "fpr" , cmdFPR , 0, N_("show key fingerprint") }, { "list" , cmdLIST , 0, N_("list key and user IDs") }, { "l" , cmdLIST , 0, NULL }, { "uid" , cmdSELUID , 0, N_("select user ID N") }, { "key" , cmdSELKEY , 0, N_("select subkey N") }, { "check" , cmdCHECK , 0, N_("check signatures") }, { "c" , cmdCHECK , 0, NULL }, { "cross-certify", cmdBACKSIGN , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL }, { "backsign", cmdBACKSIGN , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL }, { "sign" , cmdSIGN , KEYEDIT_NOT_SK|KEYEDIT_TAIL_MATCH, N_("sign selected user IDs [* see below for related commands]") }, { "s" , cmdSIGN , KEYEDIT_NOT_SK, NULL }, /* "lsign" and friends will never match since "sign" comes first and it is a tail match. They are just here so they show up in the help menu. */ { "lsign" , cmdNOP , 0, N_("sign selected user IDs locally") }, { "tsign" , cmdNOP , 0, N_("sign selected user IDs with a trust signature") }, { "nrsign" , cmdNOP , 0, N_("sign selected user IDs with a non-revocable signature") }, { "debug" , cmdDEBUG , 0, NULL }, { "adduid" , cmdADDUID , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("add a user ID") }, { "addphoto", cmdADDPHOTO , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("add a photo ID") }, { "deluid" , cmdDELUID , KEYEDIT_NOT_SK, N_("delete selected user IDs") }, /* delphoto is really deluid in disguise */ { "delphoto", cmdDELUID , KEYEDIT_NOT_SK, NULL }, { "addkey" , cmdADDKEY , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("add a subkey") }, #ifdef ENABLE_CARD_SUPPORT { "addcardkey", cmdADDCARDKEY , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("add a key to a smartcard") }, { "keytocard", cmdKEYTOCARD , KEYEDIT_NEED_SK|KEYEDIT_ONLY_SK, N_("move a key to a smartcard")}, { "bkuptocard", cmdBKUPTOCARD , KEYEDIT_NEED_SK|KEYEDIT_ONLY_SK, N_("move a backup key to a smartcard")}, { "checkbkupkey", cmdCHECKBKUPKEY, KEYEDIT_NEED_SK|KEYEDIT_ONLY_SK, NULL}, #endif /*ENABLE_CARD_SUPPORT*/ { "delkey" , cmdDELKEY , KEYEDIT_NOT_SK, N_("delete selected subkeys") }, { "addrevoker",cmdADDREVOKER,KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("add a revocation key") }, { "delsig" , cmdDELSIG , KEYEDIT_NOT_SK, N_("delete signatures from the selected user IDs") }, { "expire" , cmdEXPIRE , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("change the expiration date for the key or selected subkeys") }, { "primary" , cmdPRIMARY , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("flag the selected user ID as primary")}, { "toggle" , cmdTOGGLE , KEYEDIT_NEED_SK, N_("toggle between the secret and public key listings") }, { "t" , cmdTOGGLE , KEYEDIT_NEED_SK, NULL }, { "pref" , cmdPREF , KEYEDIT_NOT_SK, N_("list preferences (expert)")}, { "showpref", cmdSHOWPREF , KEYEDIT_NOT_SK, N_("list preferences (verbose)") }, { "setpref" , cmdSETPREF , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("set preference list for the selected user IDs") }, /* Alias */ { "updpref" , cmdSETPREF , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL }, { "keyserver",cmdPREFKS , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("set the preferred keyserver URL for the selected user IDs")}, { "notation", cmdNOTATION , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("set a notation for the selected user IDs")}, { "passwd" , cmdPASSWD , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("change the passphrase") }, /* Alias */ { "password", cmdPASSWD , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL }, { "trust" , cmdTRUST , KEYEDIT_NOT_SK, N_("change the ownertrust") }, { "revsig" , cmdREVSIG , KEYEDIT_NOT_SK, N_("revoke signatures on the selected user IDs") }, { "revuid" , cmdREVUID , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("revoke selected user IDs") }, /* Alias */ { "revphoto", cmdREVUID , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL }, { "revkey" , cmdREVKEY , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, N_("revoke key or selected subkeys") }, { "enable" , cmdENABLEKEY , KEYEDIT_NOT_SK, N_("enable key") }, { "disable" , cmdDISABLEKEY, KEYEDIT_NOT_SK, N_("disable key") }, { "showphoto",cmdSHOWPHOTO , 0, N_("show selected photo IDs") }, { "clean", cmdCLEAN , KEYEDIT_NOT_SK, N_("compact unusable user IDs and remove unusable signatures from key")}, { "minimize", cmdMINIMIZE , KEYEDIT_NOT_SK, N_("compact unusable user IDs and remove all signatures from key") }, { NULL, cmdNONE, 0, NULL } }; #ifdef HAVE_LIBREADLINE /* These two functions are used by readline for command completion. */ static char * command_generator(const char *text,int state) { static int list_index,len; const char *name; /* If this is a new word to complete, initialize now. This includes saving the length of TEXT for efficiency, and initializing the index variable to 0. */ if(!state) { list_index=0; len=strlen(text); } /* Return the next partial match */ while((name=cmds[list_index].name)) { /* Only complete commands that have help text */ if(cmds[list_index++].desc && strncmp(name,text,len)==0) return strdup(name); } return NULL; } static char ** keyedit_completion(const char *text, int start, int end) { /* If we are at the start of a line, we try and command-complete. If not, just do nothing for now. */ (void)end; if(start==0) return rl_completion_matches(text,command_generator); rl_attempted_completion_over=1; return NULL; } #endif /* HAVE_LIBREADLINE */ void keyedit_menu( const char *username, strlist_t locusr, strlist_t commands, int quiet, int seckey_check ) { enum cmdids cmd = 0; int rc = 0; KBNODE keyblock = NULL; KEYDB_HANDLE kdbhd = NULL; KBNODE sec_keyblock = NULL; KEYDB_HANDLE sec_kdbhd = NULL; KBNODE cur_keyblock; char *answer = NULL; int redisplay = 1; int modified = 0; int sec_modified = 0; int toggle; int have_commands = !!commands; if ( opt.command_fd != -1 ) ; else if( opt.batch && !have_commands ) { log_error(_("can't do this in batch mode\n")); goto leave; } #ifdef HAVE_W32_SYSTEM /* Due to Windows peculiarities we need to make sure that the trustdb stale check is done before we open another file (i.e. by searching for a key). In theory we could make sure that the files are closed after use but the open/close caches inhibits that and flushing the cache right before the stale check is not easy to implement. Thus we take the easy way out and run the stale check as early as possible. Note, that for non- W32 platforms it is run indirectly trough a call to get_validity (). */ check_trustdb_stale (); #endif /* Get the public key */ rc = get_pubkey_byname (NULL, NULL, username, &keyblock, &kdbhd, 1, 1); if( rc ) goto leave; if( fix_keyblock( keyblock ) ) modified++; if( collapse_uids( &keyblock ) ) modified++; reorder_keyblock(keyblock); /* We modified the keyblock, so let's make sure the flags are right. */ if (modified) merge_keys_and_selfsig (keyblock); if(seckey_check) {/* see whether we have a matching secret key */ PKT_public_key *pk = keyblock->pkt->pkt.public_key; sec_kdbhd = keydb_new (1); { byte afp[MAX_FINGERPRINT_LEN]; size_t an; fingerprint_from_pk (pk, afp, &an); while (an < MAX_FINGERPRINT_LEN) afp[an++] = 0; rc = keydb_search_fpr (sec_kdbhd, afp); } if (!rc) { rc = keydb_get_keyblock (sec_kdbhd, &sec_keyblock); if (rc) { log_error (_("error reading secret keyblock \"%s\": %s\n"), username, g10_errstr(rc)); } else { merge_keys_and_selfsig( sec_keyblock ); if( fix_keyblock( sec_keyblock ) ) sec_modified++; } } if (rc) { sec_keyblock = NULL; keydb_release (sec_kdbhd); sec_kdbhd = NULL; rc = 0; } if( sec_keyblock && !quiet ) tty_printf(_("Secret key is available.\n")); } toggle = 0; cur_keyblock = keyblock; for(;;) { /* main loop */ int i, arg_number, photo; const char *arg_string = ""; char *p; PKT_public_key *pk=keyblock->pkt->pkt.public_key; tty_printf("\n"); if( redisplay && !quiet ) { show_key_with_all_names( cur_keyblock, 0, 1, 0, 1, 0 ); tty_printf("\n"); redisplay = 0; } do { xfree(answer); if( have_commands ) { if( commands ) { answer = xstrdup( commands->d ); commands = commands->next; } else if( opt.batch ) { answer = xstrdup("quit"); } else have_commands = 0; } if( !have_commands ) { #ifdef HAVE_LIBREADLINE tty_enable_completion(keyedit_completion); #endif answer = cpr_get_no_help ("keyedit.prompt", "gpg> "); cpr_kill_prompt(); tty_disable_completion(); } trim_spaces(answer); } while( *answer == '#' ); arg_number = 0; /* Yes, here is the init which egcc complains about */ photo = 0; /* This too */ if( !*answer ) cmd = cmdLIST; else if( *answer == CONTROL_D ) cmd = cmdQUIT; else if( digitp(answer ) ) { cmd = cmdSELUID; arg_number = atoi(answer); } else { if( (p=strchr(answer,' ')) ) { *p++ = 0; trim_spaces(answer); trim_spaces(p); arg_number = atoi(p); arg_string = p; } for(i=0; cmds[i].name; i++ ) { if(cmds[i].flags & KEYEDIT_TAIL_MATCH) { size_t l=strlen(cmds[i].name); size_t a=strlen(answer); if(a>=l) { if(ascii_strcasecmp(&answer[a-l],cmds[i].name)==0) { answer[a-l]='\0'; break; } } } else if( !ascii_strcasecmp( answer, cmds[i].name ) ) break; } if((cmds[i].flags & KEYEDIT_NEED_SK) && !sec_keyblock ) { tty_printf(_("Need the secret key to do this.\n")); cmd = cmdNOP; } else if(((cmds[i].flags & KEYEDIT_NOT_SK) && sec_keyblock && toggle) ||((cmds[i].flags & KEYEDIT_ONLY_SK) && sec_keyblock && !toggle)) { tty_printf(_("Please use the command \"toggle\" first.\n")); cmd = cmdNOP; } else cmd = cmds[i].id; } switch( cmd ) { case cmdHELP: for(i=0; cmds[i].name; i++ ) { if((cmds[i].flags & KEYEDIT_NEED_SK) && !sec_keyblock ) ; /* skip if we do not have the secret key */ else if( cmds[i].desc ) tty_printf("%-11s %s\n", cmds[i].name, _(cmds[i].desc) ); } tty_printf("\n"); tty_printf(_( "* The `sign' command may be prefixed with an `l' for local " "signatures (lsign),\n" " a `t' for trust signatures (tsign), an `nr' for non-revocable signatures\n" " (nrsign), or any combination thereof (ltsign, tnrsign, etc.).\n")); break; case cmdLIST: redisplay = 1; break; case cmdFPR: show_key_and_fingerprint( keyblock ); break; case cmdSELUID: if(strlen(arg_string)==NAMEHASH_LEN*2) redisplay=menu_select_uid_namehash(cur_keyblock,arg_string); else { if (*arg_string == '*' && (!arg_string[1] || spacep (arg_string+1))) arg_number = -1; /* Select all. */ redisplay = menu_select_uid (cur_keyblock, arg_number); } break; case cmdSELKEY: { if (*arg_string == '*' && (!arg_string[1] || spacep (arg_string+1))) arg_number = -1; /* Select all. */ if (menu_select_key( cur_keyblock, arg_number)) redisplay = 1; } break; case cmdCHECK: /* we can only do this with the public key becuase the * check functions can't cope with secret keys and it * is questionable whether this would make sense at all */ check_all_keysigs( keyblock, count_selected_uids(keyblock) ); break; case cmdSIGN: /* sign (only the public key) */ { int localsig=0,nonrevokesig=0,trustsig=0,interactive=0; if( pk->is_revoked ) { tty_printf(_("Key is revoked.")); if(opt.expert) { tty_printf(" "); if(!cpr_get_answer_is_yes("keyedit.sign_revoked.okay", _("Are you sure you still want" " to sign it? (y/N) "))) break; } else { tty_printf(_(" Unable to sign.\n")); break; } } if(count_uids(keyblock) > 1 && !count_selected_uids(keyblock) && !cpr_get_answer_is_yes("keyedit.sign_all.okay", _("Really sign all user IDs?" " (y/N) "))) { if(opt.interactive) interactive=1; else { tty_printf(_("Hint: Select the user IDs to sign\n")); have_commands = 0; break; } } /* What sort of signing are we doing? */ if(!parse_sign_type(answer,&localsig,&nonrevokesig,&trustsig)) { tty_printf(_("Unknown signature type `%s'\n"),answer); break; } sign_uids(keyblock, locusr, &modified, localsig, nonrevokesig, trustsig, interactive); } break; case cmdDEBUG: dump_kbnode( cur_keyblock ); break; case cmdTOGGLE: toggle = !toggle; cur_keyblock = toggle? sec_keyblock : keyblock; redisplay = 1; break; case cmdADDPHOTO: if (RFC2440 || RFC1991 || PGP2) { tty_printf( _("This command is not allowed while in %s mode.\n"), compliance_option_string()); break; } photo=1; /* fall through */ case cmdADDUID: if( menu_adduid( keyblock, sec_keyblock, photo, arg_string ) ) { update_trust = 1; redisplay = 1; sec_modified = modified = 1; merge_keys_and_selfsig( sec_keyblock ); merge_keys_and_selfsig( keyblock ); } break; case cmdDELUID: { int n1; if( !(n1=count_selected_uids(keyblock)) ) tty_printf(_("You must select at least one user ID.\n")); else if( real_uids_left(keyblock) < 1 ) tty_printf(_("You can't delete the last user ID!\n")); else if( cpr_get_answer_is_yes("keyedit.remove.uid.okay", n1 > 1? _("Really remove all selected user IDs? (y/N) ") : _("Really remove this user ID? (y/N) ") ) ) { menu_deluid( keyblock, sec_keyblock ); redisplay = 1; modified = 1; if( sec_keyblock ) sec_modified = 1; } } break; case cmdDELSIG: { int n1; if( !(n1=count_selected_uids(keyblock)) ) tty_printf(_("You must select at least one user ID.\n")); else if( menu_delsig( keyblock ) ) { /* no redisplay here, because it may scroll away some * status output of delsig */ modified = 1; } } break; case cmdADDKEY: if( generate_subkeypair( keyblock, sec_keyblock ) ) { redisplay = 1; sec_modified = modified = 1; merge_keys_and_selfsig( sec_keyblock ); merge_keys_and_selfsig( keyblock ); } break; #ifdef ENABLE_CARD_SUPPORT case cmdADDCARDKEY: if (card_generate_subkey (keyblock, sec_keyblock)) { redisplay = 1; sec_modified = modified = 1; merge_keys_and_selfsig( sec_keyblock ); merge_keys_and_selfsig( keyblock ); } break; case cmdKEYTOCARD: { KBNODE node=NULL; switch ( count_selected_keys (sec_keyblock) ) { case 0: if (cpr_get_answer_is_yes ("keyedit.keytocard.use_primary", /* TRANSLATORS: Please take care: This is about moving the key and not about removing it. */ _("Really move the primary key? (y/N) "))) node = sec_keyblock; break; case 1: for (node = sec_keyblock; node; node = node->next ) { if (node->pkt->pkttype == PKT_SECRET_SUBKEY && node->flag & NODFLG_SELKEY) break; } break; default: tty_printf(_("You must select exactly one key.\n")); break; } if (node) { PKT_public_key *xxpk = find_pk_from_sknode (keyblock, node); if (card_store_subkey (node, xxpk?xxpk->pubkey_usage:0)) { redisplay = 1; sec_modified = 1; } } } break; case cmdBKUPTOCARD: case cmdCHECKBKUPKEY: { /* Ask for a filename, check whether this is really a backup key as generated by the card generation, parse that key and store it on card. */ KBNODE node; const char *fname; PACKET *pkt; IOBUF a; fname = arg_string; if (!*fname) { tty_printf (_("Command expects a filename argument\n")); break; } /* Open that file. */ a = iobuf_open (fname); if (a && is_secured_file (iobuf_get_fd (a))) { iobuf_close (a); a = NULL; errno = EPERM; } if (!a) { tty_printf (_("Can't open `%s': %s\n"), fname, strerror(errno)); break; } /* Parse and check that file. */ pkt = xmalloc (sizeof *pkt); init_packet (pkt); rc = parse_packet (a, pkt); iobuf_close (a); iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname); if (!rc && pkt->pkttype != PKT_SECRET_KEY && pkt->pkttype != PKT_SECRET_SUBKEY) rc = G10ERR_NO_SECKEY; if (rc) { tty_printf(_("Error reading backup key from `%s': %s\n"), fname, g10_errstr (rc)); free_packet (pkt); xfree (pkt); break; } node = new_kbnode (pkt); if (cmd == cmdCHECKBKUPKEY) { PKT_secret_key *sk = node->pkt->pkt.secret_key; switch (is_secret_key_protected (sk) ) { case 0: /* Not protected. */ tty_printf (_("This key is not protected.\n")); break; case -1: log_error (_("unknown key protection algorithm\n")); break; default: if (sk->protect.s2k.mode == 1001) tty_printf (_("Secret parts of key" " are not available.\n")); if (sk->protect.s2k.mode == 1002) tty_printf (_("Secret parts of key" " are stored on-card.\n")); else check_secret_key (sk, 0); } } else /* Store it. */ { if (card_store_subkey (node, 0)) { redisplay = 1; sec_modified = 1; } } release_kbnode (node); } break; #endif /* ENABLE_CARD_SUPPORT */ case cmdDELKEY: { int n1; if( !(n1=count_selected_keys( keyblock )) ) tty_printf(_("You must select at least one key.\n")); else if( !cpr_get_answer_is_yes( "keyedit.remove.subkey.okay", n1 > 1? _("Do you really want to delete the selected keys? (y/N) "): _("Do you really want to delete this key? (y/N) ") )) ; else { menu_delkey( keyblock, sec_keyblock ); redisplay = 1; modified = 1; if( sec_keyblock ) sec_modified = 1; } } break; case cmdADDREVOKER: { int sensitive=0; if(ascii_strcasecmp(arg_string,"sensitive")==0) sensitive=1; if( menu_addrevoker( keyblock, sec_keyblock, sensitive ) ) { redisplay = 1; sec_modified = modified = 1; merge_keys_and_selfsig( sec_keyblock ); merge_keys_and_selfsig( keyblock ); } } break; case cmdREVUID: { int n1; if( !(n1=count_selected_uids(keyblock)) ) tty_printf(_("You must select at least one user ID.\n")); else if( cpr_get_answer_is_yes( "keyedit.revoke.uid.okay", n1 > 1? _("Really revoke all selected user IDs? (y/N) ") : _("Really revoke this user ID? (y/N) ") ) ) { if(menu_revuid(keyblock,sec_keyblock)) { modified=1; redisplay=1; } } } break; case cmdREVKEY: { int n1; if( !(n1=count_selected_keys( keyblock )) ) { if(cpr_get_answer_is_yes("keyedit.revoke.subkey.okay", _("Do you really want to revoke" " the entire key? (y/N) "))) { if(menu_revkey(keyblock,sec_keyblock)) modified=1; redisplay=1; } } else if(cpr_get_answer_is_yes("keyedit.revoke.subkey.okay", n1 > 1? _("Do you really want to revoke" " the selected subkeys? (y/N) "): _("Do you really want to revoke" " this subkey? (y/N) "))) { if( menu_revsubkey( keyblock, sec_keyblock ) ) modified = 1; redisplay = 1; } if(modified) merge_keys_and_selfsig( keyblock ); } break; case cmdEXPIRE: if( menu_expire( keyblock, sec_keyblock ) ) { merge_keys_and_selfsig( sec_keyblock ); merge_keys_and_selfsig( keyblock ); sec_modified = 1; modified = 1; redisplay = 1; } break; case cmdBACKSIGN: if(menu_backsign(keyblock,sec_keyblock)) { sec_modified = 1; modified = 1; redisplay = 1; } break; case cmdPRIMARY: if( menu_set_primary_uid ( keyblock, sec_keyblock ) ) { merge_keys_and_selfsig( keyblock ); modified = 1; redisplay = 1; } break; case cmdPASSWD: - if( change_passphrase( sec_keyblock ) ) + if (change_passphrase (sec_keyblock, NULL)) sec_modified = 1; break; case cmdTRUST: if(opt.trust_model==TM_EXTERNAL) { tty_printf (_("Owner trust may not be set while " "using a user provided trust database\n")); break; } show_key_with_all_names( keyblock, 0, 0, 0, 1, 0 ); tty_printf("\n"); if( edit_ownertrust( find_kbnode( keyblock, PKT_PUBLIC_KEY )->pkt->pkt.public_key, 1 ) ) { redisplay = 1; /* No real need to set update_trust here as edit_ownertrust() calls revalidation_mark() anyway. */ update_trust=1; } break; case cmdPREF: { int count=count_selected_uids(keyblock); assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); show_names(keyblock,keyblock->pkt->pkt.public_key, count?NODFLG_SELUID:0,1); } break; case cmdSHOWPREF: { int count=count_selected_uids(keyblock); assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); show_names(keyblock,keyblock->pkt->pkt.public_key, count?NODFLG_SELUID:0,2); } break; case cmdSETPREF: { PKT_user_id *tempuid; keygen_set_std_prefs(!*arg_string?"default" : arg_string, 0); tempuid=keygen_get_std_prefs(); tty_printf(_("Set preference list to:\n")); show_prefs(tempuid,NULL,1); free_user_id(tempuid); if(cpr_get_answer_is_yes("keyedit.setpref.okay", count_selected_uids (keyblock)? _("Really update the preferences" " for the selected user IDs? (y/N) "): _("Really update the preferences? (y/N) "))) { if ( menu_set_preferences (keyblock, sec_keyblock) ) { merge_keys_and_selfsig (keyblock); modified = 1; redisplay = 1; } } } break; case cmdPREFKS: if( menu_set_keyserver_url ( *arg_string?arg_string:NULL, keyblock, sec_keyblock ) ) { merge_keys_and_selfsig( keyblock ); modified = 1; redisplay = 1; } break; case cmdNOTATION: if( menu_set_notation ( *arg_string?arg_string:NULL, keyblock, sec_keyblock ) ) { merge_keys_and_selfsig( keyblock ); modified = 1; redisplay = 1; } break; case cmdNOP: break; case cmdREVSIG: if( menu_revsig( keyblock ) ) { redisplay = 1; modified = 1; } break; case cmdENABLEKEY: case cmdDISABLEKEY: if( enable_disable_key( keyblock, cmd == cmdDISABLEKEY ) ) { redisplay = 1; modified = 1; } break; case cmdSHOWPHOTO: menu_showphoto(keyblock); break; case cmdCLEAN: if(menu_clean(keyblock,0)) redisplay=modified=1; break; case cmdMINIMIZE: if(menu_clean(keyblock,1)) redisplay=modified=1; break; case cmdQUIT: if( have_commands ) goto leave; if( !modified && !sec_modified ) goto leave; if( !cpr_get_answer_is_yes("keyedit.save.okay", _("Save changes? (y/N) ")) ) { if( cpr_enabled() || cpr_get_answer_is_yes("keyedit.cancel.okay", _("Quit without saving? (y/N) "))) goto leave; break; } /* fall thru */ case cmdSAVE: if( modified || sec_modified ) { if( modified ) { rc = keydb_update_keyblock (kdbhd, keyblock); if( rc ) { log_error(_("update failed: %s\n"), g10_errstr(rc) ); break; } } if( sec_modified ) { rc = keydb_update_keyblock (sec_kdbhd, sec_keyblock ); if( rc ) { log_error( _("update secret failed: %s\n"), g10_errstr(rc) ); break; } } } else tty_printf(_("Key not changed so no update needed.\n")); if( update_trust ) { revalidation_mark (); update_trust=0; } goto leave; case cmdINVCMD: default: tty_printf("\n"); tty_printf(_("Invalid command (try \"help\")\n")); break; } } /* end main loop */ leave: release_kbnode( keyblock ); release_kbnode( sec_keyblock ); keydb_release (kdbhd); xfree(answer); } /* Change the passphrase of the secret key identified by USERNAME. */ void keyedit_passwd (const char *username) { gpg_error_t err; PKT_public_key *pk; unsigned char fpr[MAX_FINGERPRINT_LEN]; size_t fprlen; KEYDB_HANDLE kdh = NULL; kbnode_t keyblock = NULL; pk = xtrycalloc (1, sizeof *pk); if (!pk) { err = gpg_error_from_syserror (); goto leave; } err = getkey_byname (NULL, pk, username, 1, NULL); if (err) goto leave; fingerprint_from_pk (pk, fpr, &fprlen); while (fprlen < MAX_FINGERPRINT_LEN) fpr[fprlen++] = 0; /* FIXME: Call an agent function instead. */ kdh = keydb_new (1); if (!kdh) { err = gpg_error (GPG_ERR_GENERAL); goto leave; } err = keydb_search_fpr (kdh, fpr); if (err == -1 || gpg_err_code (err) == GPG_ERR_EOF) err = gpg_error (GPG_ERR_NO_SECKEY); if (err) goto leave; err = keydb_get_keyblock (kdh, &keyblock); if (err) goto leave; - if (!change_passphrase (keyblock)) - { - err = gpg_error (GPG_ERR_GENERAL); - goto leave; - } + if (!change_passphrase (keyblock, &err)) + goto leave; err = keydb_update_keyblock (kdh, keyblock); if (err) log_error( _("update secret failed: %s\n"), gpg_strerror (err)); leave: release_kbnode (keyblock); if (pk) free_public_key (pk); keydb_release (kdh); if (err) { log_info ("error changing the passphrase for `%s': %s\n", username, gpg_strerror (err)); write_status_error ("keyedit.passwd", err); } + else + write_status_text (STATUS_SUCCESS, "keyedit.passwd"); } static void tty_print_notations(int indent,PKT_signature *sig) { int first=1; struct notation *notation,*nd; if(indent<0) { first=0; indent=-indent; } notation=sig_to_notation(sig); for(nd=notation;nd;nd=nd->next) { if(!first) tty_printf("%*s",indent,""); else first=0; tty_print_utf8_string(nd->name,strlen(nd->name)); tty_printf("="); tty_print_utf8_string(nd->value,strlen(nd->value)); tty_printf("\n"); } free_notation(notation); } /**************** * show preferences of a public keyblock. */ static void show_prefs (PKT_user_id *uid, PKT_signature *selfsig, int verbose) { const prefitem_t fake={0,0}; const prefitem_t *prefs; int i; if( !uid ) return; if( uid->prefs ) prefs=uid->prefs; else if(verbose) prefs=&fake; else return; if (verbose) { int any, des_seen=0, sha1_seen=0, uncomp_seen=0; tty_printf (" "); tty_printf (_("Cipher: ")); for(i=any=0; prefs[i].type; i++ ) { if( prefs[i].type == PREFTYPE_SYM ) { if (any) tty_printf (", "); any = 1; /* We don't want to display strings for experimental algos */ if (!openpgp_cipher_test_algo (prefs[i].value) && prefs[i].value < 100 ) tty_printf ("%s", openpgp_cipher_algo_name (prefs[i].value)); else tty_printf ("[%d]", prefs[i].value); if (prefs[i].value == CIPHER_ALGO_3DES ) des_seen = 1; } } if (!des_seen) { if (any) tty_printf (", "); tty_printf ("%s", openpgp_cipher_algo_name (CIPHER_ALGO_3DES)); } tty_printf ("\n "); tty_printf (_("Digest: ")); for(i=any=0; prefs[i].type; i++ ) { if( prefs[i].type == PREFTYPE_HASH ) { if (any) tty_printf (", "); any = 1; /* We don't want to display strings for experimental algos */ if (!gcry_md_test_algo (prefs[i].value) && prefs[i].value < 100 ) tty_printf ("%s", gcry_md_algo_name (prefs[i].value) ); else tty_printf ("[%d]", prefs[i].value); if (prefs[i].value == DIGEST_ALGO_SHA1 ) sha1_seen = 1; } } if (!sha1_seen) { if (any) tty_printf (", "); tty_printf ("%s", gcry_md_algo_name (DIGEST_ALGO_SHA1)); } tty_printf ("\n "); tty_printf (_("Compression: ")); for(i=any=0; prefs[i].type; i++ ) { if( prefs[i].type == PREFTYPE_ZIP ) { const char *s=compress_algo_to_string(prefs[i].value); if (any) tty_printf (", "); any = 1; /* We don't want to display strings for experimental algos */ if (s && prefs[i].value < 100 ) tty_printf ("%s", s ); else tty_printf ("[%d]", prefs[i].value); if (prefs[i].value == COMPRESS_ALGO_NONE ) uncomp_seen = 1; } } if (!uncomp_seen) { if (any) tty_printf (", "); else { tty_printf ("%s",compress_algo_to_string(COMPRESS_ALGO_ZIP)); tty_printf (", "); } tty_printf ("%s",compress_algo_to_string(COMPRESS_ALGO_NONE)); } if(uid->flags.mdc || !uid->flags.ks_modify) { tty_printf ("\n "); tty_printf (_("Features: ")); any=0; if(uid->flags.mdc) { tty_printf ("MDC"); any=1; } if(!uid->flags.ks_modify) { if(any) tty_printf (", "); tty_printf (_("Keyserver no-modify")); } } tty_printf("\n"); if(selfsig) { const byte *pref_ks; size_t pref_ks_len; pref_ks=parse_sig_subpkt(selfsig->hashed, SIGSUBPKT_PREF_KS,&pref_ks_len); if(pref_ks && pref_ks_len) { tty_printf (" "); tty_printf(_("Preferred keyserver: ")); tty_print_utf8_string(pref_ks,pref_ks_len); tty_printf("\n"); } if(selfsig->flags.notation) { tty_printf (" "); tty_printf(_("Notations: ")); tty_print_notations(5+strlen(_("Notations: ")),selfsig); } } } else { tty_printf(" "); for(i=0; prefs[i].type; i++ ) { tty_printf( " %c%d", prefs[i].type == PREFTYPE_SYM ? 'S' : prefs[i].type == PREFTYPE_HASH ? 'H' : prefs[i].type == PREFTYPE_ZIP ? 'Z':'?', prefs[i].value); } if (uid->flags.mdc) tty_printf (" [mdc]"); if (!uid->flags.ks_modify) tty_printf (" [no-ks-modify]"); tty_printf("\n"); } } /* This is the version of show_key_with_all_names used when opt.with_colons is used. It prints all available data in a easy to parse format and does not translate utf8 */ static void show_key_with_all_names_colon (KBNODE keyblock) { KBNODE node; int i, j, ulti_hack=0; byte pk_version=0; PKT_public_key *primary=NULL; /* the keys */ for ( node = keyblock; node; node = node->next ) { if (node->pkt->pkttype == PKT_PUBLIC_KEY || (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) ) { PKT_public_key *pk = node->pkt->pkt.public_key; u32 keyid[2]; if (node->pkt->pkttype == PKT_PUBLIC_KEY) { pk_version = pk->version; primary=pk; } keyid_from_pk (pk, keyid); fputs (node->pkt->pkttype == PKT_PUBLIC_KEY?"pub:":"sub:", stdout); if (!pk->is_valid) putchar ('i'); else if (pk->is_revoked) putchar ('r'); else if (pk->has_expired) putchar ('e'); else if (!(opt.fast_list_mode || opt.no_expensive_trust_checks )) { int trust = get_validity_info (pk, NULL); if(trust=='u') ulti_hack=1; putchar (trust); } printf (":%u:%d:%08lX%08lX:%lu:%lu::", nbits_from_pk (pk), pk->pubkey_algo, (ulong)keyid[0], (ulong)keyid[1], (ulong)pk->timestamp, (ulong)pk->expiredate ); if (node->pkt->pkttype==PKT_PUBLIC_KEY && !(opt.fast_list_mode || opt.no_expensive_trust_checks )) putchar(get_ownertrust_info (pk)); putchar(':'); putchar (':'); putchar (':'); /* Print capabilities. */ if ( (pk->pubkey_usage & PUBKEY_USAGE_ENC) ) putchar ('e'); if ( (pk->pubkey_usage & PUBKEY_USAGE_SIG) ) putchar ('s'); if ( (pk->pubkey_usage & PUBKEY_USAGE_CERT) ) putchar ('c'); if ( (pk->pubkey_usage & PUBKEY_USAGE_AUTH) ) putchar ('a'); putchar('\n'); print_fingerprint (pk, NULL, 0); print_revokers(pk); } } /* the user ids */ i = 0; for (node = keyblock; node; node = node->next) { if ( node->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *uid = node->pkt->pkt.user_id; ++i; if(uid->attrib_data) printf("uat:"); else printf("uid:"); if ( uid->is_revoked ) printf("r::::::::"); else if ( uid->is_expired ) printf("e::::::::"); else if ( opt.fast_list_mode || opt.no_expensive_trust_checks ) printf("::::::::"); else { int uid_validity; if( primary && !ulti_hack ) uid_validity = get_validity_info( primary, uid ); else uid_validity = 'u'; printf("%c::::::::",uid_validity); } if(uid->attrib_data) printf ("%u %lu",uid->numattribs,uid->attrib_len); else - print_string (stdout, uid->name, uid->len, ':'); + es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL); putchar (':'); /* signature class */ putchar (':'); /* capabilities */ putchar (':'); /* preferences */ if (pk_version>3 || uid->selfsigversion>3) { const prefitem_t *prefs = uid->prefs; for (j=0; prefs && prefs[j].type; j++) { if (j) putchar (' '); printf ("%c%d", prefs[j].type == PREFTYPE_SYM ? 'S' : prefs[j].type == PREFTYPE_HASH ? 'H' : prefs[j].type == PREFTYPE_ZIP ? 'Z':'?', prefs[j].value); } if (uid->flags.mdc) printf (",mdc"); if (!uid->flags.ks_modify) printf (",no-ks-modify"); } putchar (':'); /* flags */ printf ("%d,", i); if (uid->is_primary) putchar ('p'); if (uid->is_revoked) putchar ('r'); if (uid->is_expired) putchar ('e'); if ((node->flag & NODFLG_SELUID)) putchar ('s'); if ((node->flag & NODFLG_MARK_A)) putchar ('m'); putchar (':'); putchar('\n'); } } } static void show_names(KBNODE keyblock,PKT_public_key *pk,unsigned int flag,int with_prefs) { KBNODE node; int i=0; for( node = keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_USER_ID && !is_deleted_kbnode(node)) { PKT_user_id *uid = node->pkt->pkt.user_id; ++i; if(!flag || (flag && (node->flag & flag))) { if(!(flag&NODFLG_MARK_A) && pk) tty_printf("%s ",uid_trust_string_fixed(pk,uid)); if( flag & NODFLG_MARK_A ) tty_printf(" "); else if( node->flag & NODFLG_SELUID ) tty_printf("(%d)* ", i); else if( uid->is_primary ) tty_printf("(%d). ", i); else tty_printf("(%d) ", i); tty_print_utf8_string( uid->name, uid->len ); tty_printf("\n"); if(with_prefs && pk) { if(pk->version>3 || uid->selfsigversion>3) { PKT_signature *selfsig=NULL; KBNODE signode; for(signode=node->next; signode && signode->pkt->pkttype==PKT_SIGNATURE; signode=signode->next) { if(signode->pkt->pkt.signature-> flags.chosen_selfsig) { selfsig=signode->pkt->pkt.signature; break; } } show_prefs (uid, selfsig, with_prefs == 2); } else tty_printf(_("There are no preferences on a" " PGP 2.x-style user ID.\n")); } } } } } /**************** * Display the key a the user ids, if only_marked is true, do only * so for user ids with mark A flag set and dont display the index number */ static void show_key_with_all_names( KBNODE keyblock, int only_marked, int with_revoker, int with_fpr, int with_subkeys, int with_prefs ) { KBNODE node; int i; int do_warn = 0; byte pk_version=0; PKT_public_key *primary=NULL; if (opt.with_colons) { show_key_with_all_names_colon (keyblock); return; } /* the keys */ for( node = keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY || (with_subkeys && node->pkt->pkttype == PKT_PUBLIC_SUBKEY && !is_deleted_kbnode(node)) ) { PKT_public_key *pk = node->pkt->pkt.public_key; const char *otrust="err",*trust="err"; if( node->pkt->pkttype == PKT_PUBLIC_KEY ) { /* do it here, so that debug messages don't clutter the * output */ static int did_warn = 0; trust = get_validity_string (pk, NULL); otrust = get_ownertrust_string (pk); /* Show a warning once */ if (!did_warn && (get_validity (pk, NULL) & TRUST_FLAG_PENDING_CHECK)) { did_warn = 1; do_warn = 1; } pk_version=pk->version; primary=pk; } if(pk->is_revoked) { char *user=get_user_id_string_native(pk->revoked.keyid); const char *algo = gcry_pk_algo_name (pk->revoked.algo); tty_printf(_("This key was revoked on %s by %s key %s\n"), revokestr_from_pk(pk),algo?algo:"?",user); xfree(user); } if(with_revoker) { if( !pk->revkey && pk->numrevkeys ) BUG(); else for(i=0;inumrevkeys;i++) { u32 r_keyid[2]; char *user; const char *algo; algo = gcry_pk_algo_name (pk->revkey[i].algid); keyid_from_fingerprint(pk->revkey[i].fpr, MAX_FINGERPRINT_LEN,r_keyid); user=get_user_id_string_native(r_keyid); tty_printf(_("This key may be revoked by %s key %s"), algo?algo:"?",user); if(pk->revkey[i].class&0x40) { tty_printf(" "); tty_printf(_("(sensitive)")); } tty_printf ("\n"); xfree(user); } } keyid_from_pk(pk,NULL); tty_printf("%s%c %4u%c/%s ", node->pkt->pkttype == PKT_PUBLIC_KEY? "pub":"sub", (node->flag & NODFLG_SELKEY)? '*':' ', nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr(pk->keyid)); tty_printf(_("created: %s"),datestr_from_pk(pk)); tty_printf(" "); if(pk->is_revoked) tty_printf(_("revoked: %s"),revokestr_from_pk(pk)); else if(pk->has_expired) tty_printf(_("expired: %s"),expirestr_from_pk(pk)); else tty_printf(_("expires: %s"),expirestr_from_pk(pk)); tty_printf(" "); tty_printf(_("usage: %s"),usagestr_from_pk(pk)); tty_printf("\n"); if( node->pkt->pkttype == PKT_PUBLIC_KEY ) { if(opt.trust_model!=TM_ALWAYS) { tty_printf("%*s", (int)keystrlen()+13,""); /* Ownertrust is only meaningful for the PGP or classic trust models */ if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC) { int width=14-strlen(otrust); if(width<=0) width=1; tty_printf(_("trust: %s"), otrust); tty_printf("%*s",width,""); } tty_printf(_("validity: %s"), trust ); tty_printf("\n"); } if( node->pkt->pkttype == PKT_PUBLIC_KEY && (get_ownertrust (pk)&TRUST_FLAG_DISABLED)) { tty_printf("*** "); tty_printf(_("This key has been disabled")); tty_printf("\n"); } } if( node->pkt->pkttype == PKT_PUBLIC_KEY && with_fpr ) { print_fingerprint ( pk, NULL, 2 ); tty_printf("\n"); } } else if( node->pkt->pkttype == PKT_SECRET_KEY || (with_subkeys && node->pkt->pkttype == PKT_SECRET_SUBKEY) ) { PKT_secret_key *sk = node->pkt->pkt.secret_key; tty_printf("%s%c %4u%c/%s ", node->pkt->pkttype == PKT_SECRET_KEY? "sec":"ssb", (node->flag & NODFLG_SELKEY)? '*':' ', nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ), keystr_from_sk(sk)); tty_printf(_("created: %s"),datestr_from_sk(sk)); tty_printf(" "); tty_printf(_("expires: %s"),expirestr_from_sk(sk)); tty_printf("\n"); if (sk->is_protected && sk->protect.s2k.mode == 1002) { tty_printf(" "); tty_printf(_("card-no: ")); if (sk->protect.ivlen == 16 && !memcmp (sk->protect.iv, "\xD2\x76\x00\x01\x24\x01", 6)) { /* This is an OpenPGP card. */ for (i=8; i < 14; i++) { if (i == 10) tty_printf (" "); tty_printf ("%02X", sk->protect.iv[i]); } } else { /* Something is wrong: Print all. */ for (i=0; i < sk->protect.ivlen; i++) tty_printf ("%02X", sk->protect.iv[i]); } tty_printf ("\n"); } } } show_names(keyblock,primary,only_marked?NODFLG_MARK_A:0,with_prefs); if (do_warn) tty_printf (_("Please note that the shown key validity" " is not necessarily correct\n" "unless you restart the program.\n")); } /* Display basic key information. This function is suitable to show information on the key without any dependencies on the trustdb or any other internal GnuPG stuff. KEYBLOCK may either be a public or a secret key.*/ void show_basic_key_info ( KBNODE keyblock ) { KBNODE node; int i; /* The primary key */ for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_PUBLIC_KEY) { PKT_public_key *pk = node->pkt->pkt.public_key; /* Note, we use the same format string as in other show functions to make the translation job easier. */ tty_printf ("%s %4u%c/%s ", node->pkt->pkttype == PKT_PUBLIC_KEY? "pub":"sub", nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr_from_pk(pk)); tty_printf(_("created: %s"),datestr_from_pk(pk)); tty_printf(" "); tty_printf(_("expires: %s"),expirestr_from_pk(pk)); tty_printf("\n"); print_fingerprint ( pk, NULL, 3 ); tty_printf("\n"); } else if (node->pkt->pkttype == PKT_SECRET_KEY) { PKT_secret_key *sk = node->pkt->pkt.secret_key; tty_printf("%s %4u%c/%s", node->pkt->pkttype == PKT_SECRET_KEY? "sec":"ssb", nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ), keystr_from_sk(sk)); tty_printf(_("created: %s"),datestr_from_sk(sk)); tty_printf(" "); tty_printf(_("expires: %s"),expirestr_from_sk(sk)); tty_printf("\n"); print_fingerprint (NULL, sk, 3 ); tty_printf("\n"); } } /* The user IDs. */ for (i=0, node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = node->pkt->pkt.user_id; ++i; tty_printf (" "); if (uid->is_revoked) tty_printf("[%s] ",_("revoked")); else if ( uid->is_expired ) tty_printf("[%s] ",_("expired")); tty_print_utf8_string (uid->name, uid->len); tty_printf ("\n"); } } } static void show_key_and_fingerprint( KBNODE keyblock ) { KBNODE node; PKT_public_key *pk = NULL; for( node = keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) { pk = node->pkt->pkt.public_key; tty_printf("pub %4u%c/%s %s ", nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr_from_pk(pk), datestr_from_pk(pk) ); } else if( node->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *uid = node->pkt->pkt.user_id; tty_print_utf8_string( uid->name, uid->len ); break; } } tty_printf("\n"); if( pk ) print_fingerprint( pk, NULL, 2 ); } /* Show a warning if no uids on the key have the primary uid flag set. */ static void no_primary_warning(KBNODE keyblock) { KBNODE node; int have_primary=0,uid_count=0; /* TODO: if we ever start behaving differently with a primary or non-primary attribute ID, we will need to check for attributes here as well. */ for(node=keyblock; node; node = node->next) { if(node->pkt->pkttype==PKT_USER_ID && node->pkt->pkt.user_id->attrib_data==NULL) { uid_count++; if(node->pkt->pkt.user_id->is_primary==2) { have_primary=1; break; } } } if(uid_count>1 && !have_primary) log_info(_("WARNING: no user ID has been marked as primary. This command" " may\n cause a different user ID to become" " the assumed primary.\n")); } /**************** * Ask for a new user id, do the selfsignature and put it into * both keyblocks. * Return true if there is a new user id */ static int menu_adduid( KBNODE pub_keyblock, KBNODE sec_keyblock, int photo, const char *photo_name) { PKT_user_id *uid; PKT_public_key *pk=NULL; PKT_secret_key *sk=NULL; PKT_signature *sig=NULL; PACKET *pkt; KBNODE node; KBNODE pub_where=NULL, sec_where=NULL; int rc; for( node = pub_keyblock; node; pub_where = node, node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) pk = node->pkt->pkt.public_key; else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; } if( !node ) /* no subkey */ pub_where = NULL; for( node = sec_keyblock; node; sec_where = node, node = node->next ) { if( node->pkt->pkttype == PKT_SECRET_KEY ) sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) break; } if( !node ) /* no subkey */ sec_where = NULL; assert(pk && sk); if(photo) { int hasattrib=0; for( node = pub_keyblock; node; node = node->next ) if( node->pkt->pkttype == PKT_USER_ID && node->pkt->pkt.user_id->attrib_data!=NULL) { hasattrib=1; break; } /* It is legal but bad for compatibility to add a photo ID to a v3 key as it means that PGP2 will not be able to use that key anymore. Also, PGP may not expect a photo on a v3 key. Don't bother to ask this if the key already has a photo - any damage has already been done at that point. -dms */ if(pk->version==3 && !hasattrib) { if(opt.expert) { tty_printf(_("WARNING: This is a PGP2-style key. " "Adding a photo ID may cause some versions\n" " of PGP to reject this key.\n")); if(!cpr_get_answer_is_yes("keyedit.v3_photo.okay", _("Are you sure you still want " "to add it? (y/N) "))) return 0; } else { tty_printf(_("You may not add a photo ID to " "a PGP2-style key.\n")); return 0; } } uid = generate_photo_id(pk,photo_name); } else uid = generate_user_id (pub_keyblock); if( !uid ) return 0; rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x13, 0, 0, 0, 0, keygen_add_std_prefs, pk ); free_secret_key( sk ); if( rc ) { log_error("signing failed: %s\n", g10_errstr(rc) ); free_user_id(uid); return 0; } /* insert/append to secret keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_USER_ID; pkt->pkt.user_id = scopy_user_id(uid); node = new_kbnode(pkt); if( sec_where ) insert_kbnode( sec_where, node, 0 ); else add_kbnode( sec_keyblock, node ); pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = copy_signature(NULL, sig); if( sec_where ) insert_kbnode( node, new_kbnode(pkt), 0 ); else add_kbnode( sec_keyblock, new_kbnode(pkt) ); /* insert/append to public keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_USER_ID; pkt->pkt.user_id = uid; node = new_kbnode(pkt); if( pub_where ) insert_kbnode( pub_where, node, 0 ); else add_kbnode( pub_keyblock, node ); pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = copy_signature(NULL, sig); if( pub_where ) insert_kbnode( node, new_kbnode(pkt), 0 ); else add_kbnode( pub_keyblock, new_kbnode(pkt) ); return 1; } /**************** * Remove all selected userids from the keyrings */ static void menu_deluid( KBNODE pub_keyblock, KBNODE sec_keyblock ) { KBNODE node; int selected=0; for( node = pub_keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_USER_ID ) { selected = node->flag & NODFLG_SELUID; if( selected ) { /* Only cause a trust update if we delete a non-revoked user id */ if(!node->pkt->pkt.user_id->is_revoked) update_trust=1; delete_kbnode( node ); if( sec_keyblock ) { KBNODE snode; int s_selected = 0; PKT_user_id *uid = node->pkt->pkt.user_id; for( snode = sec_keyblock; snode; snode = snode->next ) { if( snode->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *suid = snode->pkt->pkt.user_id; s_selected = (uid->len == suid->len && !memcmp( uid->name, suid->name, uid->len)); if( s_selected ) delete_kbnode( snode ); } else if( s_selected && snode->pkt->pkttype == PKT_SIGNATURE ) delete_kbnode( snode ); else if( snode->pkt->pkttype == PKT_SECRET_SUBKEY ) s_selected = 0; } } } } else if( selected && node->pkt->pkttype == PKT_SIGNATURE ) delete_kbnode( node ); else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) selected = 0; } commit_kbnode( &pub_keyblock ); if( sec_keyblock ) commit_kbnode( &sec_keyblock ); } static int menu_delsig( KBNODE pub_keyblock ) { KBNODE node; PKT_user_id *uid = NULL; int changed=0; for( node = pub_keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_USER_ID ) { uid = (node->flag & NODFLG_SELUID)? node->pkt->pkt.user_id : NULL; } else if( uid && node->pkt->pkttype == PKT_SIGNATURE ) { int okay, valid, selfsig, inv_sig, no_key, other_err; tty_printf("uid "); tty_print_utf8_string( uid->name, uid->len ); tty_printf("\n"); okay = inv_sig = no_key = other_err = 0; if(opt.with_colons) valid = print_and_check_one_sig_colon( pub_keyblock, node, &inv_sig, &no_key, &other_err, &selfsig, 1 ); else valid = print_and_check_one_sig( pub_keyblock, node, &inv_sig, &no_key, &other_err, &selfsig, 1 ); if( valid ) { okay = cpr_get_answer_yes_no_quit( "keyedit.delsig.valid", _("Delete this good signature? (y/N/q)")); /* Only update trust if we delete a good signature. The other two cases do not affect trust. */ if(okay) update_trust=1; } else if( inv_sig || other_err ) okay = cpr_get_answer_yes_no_quit( "keyedit.delsig.invalid", _("Delete this invalid signature? (y/N/q)")); else if( no_key ) okay = cpr_get_answer_yes_no_quit( "keyedit.delsig.unknown", _("Delete this unknown signature? (y/N/q)")); if( okay == -1 ) break; if( okay && selfsig && !cpr_get_answer_is_yes( "keyedit.delsig.selfsig", _("Really delete this self-signature? (y/N)") )) okay = 0; if( okay ) { delete_kbnode( node ); changed++; } } else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) uid = NULL; } if( changed ) { commit_kbnode( &pub_keyblock ); tty_printf( changed == 1? _("Deleted %d signature.\n") : _("Deleted %d signatures.\n"), changed ); } else tty_printf( _("Nothing deleted.\n") ); return changed; } static int menu_clean(KBNODE keyblock,int self_only) { KBNODE uidnode; int modified=0,select_all=!count_selected_uids(keyblock); for(uidnode=keyblock->next; uidnode && uidnode->pkt->pkttype!=PKT_PUBLIC_SUBKEY; uidnode=uidnode->next) { if(uidnode->pkt->pkttype==PKT_USER_ID && (uidnode->flag&NODFLG_SELUID || select_all)) { int uids=0,sigs=0; char *user=utf8_to_native(uidnode->pkt->pkt.user_id->name, uidnode->pkt->pkt.user_id->len, 0); clean_one_uid(keyblock,uidnode,opt.verbose,self_only,&uids,&sigs); if(uids) { const char *reason; if(uidnode->pkt->pkt.user_id->is_revoked) reason=_("revoked"); else if(uidnode->pkt->pkt.user_id->is_expired) reason=_("expired"); else reason=_("invalid"); tty_printf (_("User ID \"%s\" compacted: %s\n"), user, reason); modified=1; } else if(sigs) { tty_printf(sigs==1? _("User ID \"%s\": %d signature removed\n") : _("User ID \"%s\": %d signatures removed\n"), user,sigs); modified=1; } else { tty_printf (self_only==1? _("User ID \"%s\": already minimized\n") : _("User ID \"%s\": already clean\n"), user); } xfree(user); } } return modified; } /**************** * Remove some of the secondary keys */ static void menu_delkey( KBNODE pub_keyblock, KBNODE sec_keyblock ) { KBNODE node; int selected=0; for( node = pub_keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { selected = node->flag & NODFLG_SELKEY; if( selected ) { delete_kbnode( node ); if( sec_keyblock ) { KBNODE snode; int s_selected = 0; u32 ki[2]; keyid_from_pk( node->pkt->pkt.public_key, ki ); for( snode = sec_keyblock; snode; snode = snode->next ) { if( snode->pkt->pkttype == PKT_SECRET_SUBKEY ) { u32 ki2[2]; keyid_from_sk( snode->pkt->pkt.secret_key, ki2 ); s_selected = (ki[0] == ki2[0] && ki[1] == ki2[1]); if( s_selected ) delete_kbnode( snode ); } else if( s_selected && snode->pkt->pkttype == PKT_SIGNATURE ) delete_kbnode( snode ); else s_selected = 0; } } } } else if( selected && node->pkt->pkttype == PKT_SIGNATURE ) delete_kbnode( node ); else selected = 0; } commit_kbnode( &pub_keyblock ); if( sec_keyblock ) commit_kbnode( &sec_keyblock ); /* No need to set update_trust here since signing keys are no longer used to certify other keys, so there is no change in trust when revoking/removing them */ } /**************** * Ask for a new revoker, do the selfsignature and put it into * both keyblocks. * Return true if there is a new revoker */ static int menu_addrevoker( KBNODE pub_keyblock, KBNODE sec_keyblock, int sensitive ) { PKT_public_key *pk=NULL,*revoker_pk=NULL; PKT_secret_key *sk=NULL; PKT_signature *sig=NULL; PACKET *pkt; struct revocation_key revkey; size_t fprlen; int rc; assert(pub_keyblock->pkt->pkttype==PKT_PUBLIC_KEY); assert(sec_keyblock->pkt->pkttype==PKT_SECRET_KEY); pk=pub_keyblock->pkt->pkt.public_key; if(pk->numrevkeys==0 && pk->version==3) { /* It is legal but bad for compatibility to add a revoker to a v3 key as it means that PGP2 will not be able to use that key anymore. Also, PGP may not expect a revoker on a v3 key. Don't bother to ask this if the key already has a revoker - any damage has already been done at that point. -dms */ if(opt.expert) { tty_printf(_("WARNING: This is a PGP 2.x-style key. " "Adding a designated revoker may cause\n" " some versions of PGP to reject this key.\n")); if(!cpr_get_answer_is_yes("keyedit.v3_revoker.okay", _("Are you sure you still want " "to add it? (y/N) "))) return 0; } else { tty_printf(_("You may not add a designated revoker to " "a PGP 2.x-style key.\n")); return 0; } } sk=copy_secret_key(NULL,sec_keyblock->pkt->pkt.secret_key); for(;;) { char *answer; if(revoker_pk) free_public_key(revoker_pk); revoker_pk=xmalloc_clear(sizeof(*revoker_pk)); tty_printf("\n"); answer=cpr_get_utf8("keyedit.add_revoker", _("Enter the user ID of the designated revoker: ")); if(answer[0]=='\0' || answer[0]=='\004') { xfree(answer); goto fail; } /* Note that I'm requesting CERT here, which usually implies primary keys only, but some casual testing shows that PGP and GnuPG both can handle a designated revokation from a subkey. */ revoker_pk->req_usage=PUBKEY_USAGE_CERT; rc=get_pubkey_byname (NULL, revoker_pk,answer,NULL,NULL,1, 1); if(rc) { log_error (_("key \"%s\" not found: %s\n"),answer,g10_errstr(rc)); xfree(answer); continue; } xfree(answer); fingerprint_from_pk(revoker_pk,revkey.fpr,&fprlen); if(fprlen!=20) { log_error(_("cannot appoint a PGP 2.x style key as a " "designated revoker\n")); continue; } revkey.class=0x80; if(sensitive) revkey.class|=0x40; revkey.algid=revoker_pk->pubkey_algo; if(cmp_public_keys(revoker_pk,pk)==0) { /* This actually causes no harm (after all, a key that designates itself as a revoker is the same as a regular key), but it's easy enough to check. */ log_error(_("you cannot appoint a key as its own " "designated revoker\n")); continue; } keyid_from_pk(pk,NULL); /* Does this revkey already exist? */ if(!pk->revkey && pk->numrevkeys) BUG(); else { int i; for(i=0;inumrevkeys;i++) { if(memcmp(&pk->revkey[i],&revkey, sizeof(struct revocation_key))==0) { char buf[50]; log_error(_("this key has already been designated " "as a revoker\n")); sprintf(buf,"%08lX%08lX", (ulong)pk->keyid[0],(ulong)pk->keyid[1]); write_status_text(STATUS_ALREADY_SIGNED,buf); break; } } if(inumrevkeys) continue; } print_pubkey_info(NULL,revoker_pk); print_fingerprint(revoker_pk,NULL,2); tty_printf("\n"); tty_printf(_("WARNING: appointing a key as a designated revoker " "cannot be undone!\n")); tty_printf("\n"); if(!cpr_get_answer_is_yes("keyedit.add_revoker.okay", _("Are you sure you want to appoint this " "key as a designated revoker? (y/N) "))) continue; free_public_key(revoker_pk); revoker_pk=NULL; break; } /* The 1F signature must be at least v4 to carry the revocation key subpacket. */ rc = make_keysig_packet( &sig, pk, NULL, NULL, sk, 0x1F, 0, 4, 0, 0, keygen_add_revkey,&revkey ); if( rc ) { log_error("signing failed: %s\n", g10_errstr(rc) ); goto fail; } free_secret_key(sk); sk=NULL; /* insert into secret keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = copy_signature(NULL, sig); insert_kbnode( sec_keyblock, new_kbnode(pkt), PKT_SIGNATURE ); /* insert into public keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( pub_keyblock, new_kbnode(pkt), PKT_SIGNATURE ); return 1; fail: if(sk) free_secret_key(sk); if(sig) free_seckey_enc(sig); if(revoker_pk) free_public_key(revoker_pk); return 0; } static int menu_expire( KBNODE pub_keyblock, KBNODE sec_keyblock ) { int n1, signumber, rc; u32 expiredate; int mainkey=0; PKT_secret_key *sk; /* copy of the main sk */ PKT_public_key *main_pk, *sub_pk; PKT_user_id *uid; KBNODE node; u32 keyid[2]; if( count_selected_keys( sec_keyblock ) ) { tty_printf(_("Please remove selections from the secret keys.\n")); return 0; } n1 = count_selected_keys( pub_keyblock ); if( n1 > 1 ) { tty_printf(_("Please select at most one subkey.\n")); return 0; } else if( n1 ) tty_printf(_("Changing expiration time for a subkey.\n")); else { tty_printf(_("Changing expiration time for the primary key.\n")); mainkey=1; no_primary_warning(pub_keyblock); } expiredate = ask_expiredate(); node = find_kbnode( sec_keyblock, PKT_SECRET_KEY ); sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); /* Now we can actually change the self signature(s) */ main_pk = sub_pk = NULL; uid = NULL; signumber = 0; for( node=pub_keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) { main_pk = node->pkt->pkt.public_key; keyid_from_pk( main_pk, keyid ); main_pk->expiredate = expiredate; } else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY && (node->flag & NODFLG_SELKEY ) ) { sub_pk = node->pkt->pkt.public_key; sub_pk->expiredate = expiredate; } else if( node->pkt->pkttype == PKT_USER_ID ) uid = node->pkt->pkt.user_id; else if( main_pk && node->pkt->pkttype == PKT_SIGNATURE && ( mainkey || sub_pk ) ) { PKT_signature *sig = node->pkt->pkt.signature; if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] && ( (mainkey && uid && uid->created && (sig->sig_class&~3) == 0x10) || (!mainkey && sig->sig_class == 0x18) ) && sig->flags.chosen_selfsig ) { /* this is a selfsignature which is to be replaced */ PKT_signature *newsig; PACKET *newpkt; KBNODE sn; int signumber2 = 0; signumber++; if( (mainkey && main_pk->version < 4) || (!mainkey && sub_pk->version < 4 ) ) { log_info(_( "You can't change the expiration date of a v3 key\n")); free_secret_key( sk ); return 0; } /* find the corresponding secret self-signature */ for( sn=sec_keyblock; sn; sn = sn->next ) { if( sn->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *b = sn->pkt->pkt.signature; if( keyid[0] == b->keyid[0] && keyid[1] == b->keyid[1] && sig->sig_class == b->sig_class && ++signumber2 == signumber ) break; } } if( !sn ) log_info(_("No corresponding signature in secret ring\n")); if( mainkey ) rc = update_keysig_packet(&newsig, sig, main_pk, uid, NULL, sk, keygen_add_key_expire, main_pk); else rc = update_keysig_packet(&newsig, sig, main_pk, NULL, sub_pk, sk, keygen_add_key_expire, sub_pk ); if( rc ) { log_error("make_keysig_packet failed: %s\n", g10_errstr(rc)); free_secret_key( sk ); return 0; } /* replace the packet */ newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = newsig; free_packet( node->pkt ); xfree( node->pkt ); node->pkt = newpkt; if( sn ) { newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = copy_signature( NULL, newsig ); free_packet( sn->pkt ); xfree( sn->pkt ); sn->pkt = newpkt; } sub_pk = NULL; } } } free_secret_key( sk ); update_trust=1; return 1; } static int menu_backsign(KBNODE pub_keyblock,KBNODE sec_keyblock) { int rc,modified=0; PKT_public_key *main_pk; PKT_secret_key *main_sk,*sub_sk=NULL; KBNODE node; u32 timestamp; assert(pub_keyblock->pkt->pkttype==PKT_PUBLIC_KEY); assert(sec_keyblock->pkt->pkttype==PKT_SECRET_KEY); merge_keys_and_selfsig(pub_keyblock); main_pk=pub_keyblock->pkt->pkt.public_key; main_sk=copy_secret_key(NULL,sec_keyblock->pkt->pkt.secret_key); keyid_from_pk(main_pk,NULL); /* We use the same timestamp for all backsigs so that we don't reveal information about the used machine. */ timestamp = make_timestamp (); for(node=pub_keyblock;node;node=node->next) { PKT_public_key *sub_pk=NULL; KBNODE node2,sig_pk=NULL,sig_sk=NULL; char *passphrase; if(sub_sk) { free_secret_key(sub_sk); sub_sk=NULL; } /* Find a signing subkey with no backsig */ if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY) { if(node->pkt->pkt.public_key->pubkey_usage&PUBKEY_USAGE_SIG) { if(node->pkt->pkt.public_key->backsig) tty_printf(_("signing subkey %s is already cross-certified\n"), keystr_from_pk(node->pkt->pkt.public_key)); else sub_pk=node->pkt->pkt.public_key; } else tty_printf(_("subkey %s does not sign and so does" " not need to be cross-certified\n"), keystr_from_pk(node->pkt->pkt.public_key)); } if(!sub_pk) continue; /* Find the selected selfsig on this subkey */ for(node2=node->next; node2 && node2->pkt->pkttype==PKT_SIGNATURE; node2=node2->next) if(node2->pkt->pkt.signature->version>=4 && node2->pkt->pkt.signature->flags.chosen_selfsig) { sig_pk=node2; break; } if(!sig_pk) continue; /* Find the secret subkey that matches the public subkey */ for(node2=sec_keyblock;node2;node2=node2->next) if(node2->pkt->pkttype==PKT_SECRET_SUBKEY && !cmp_public_secret_key(sub_pk,node2->pkt->pkt.secret_key)) { sub_sk=copy_secret_key(NULL,node2->pkt->pkt.secret_key); break; } if(!sub_sk) { tty_printf(_("no secret subkey for public subkey %s - ignoring\n"), keystr_from_pk(sub_pk)); continue; } /* Now finally find the matching selfsig on the secret subkey. We can't use chosen_selfsig here (it's not set for secret keys), so we just pick the selfsig with the right class. This is what menu_expire does as well. */ for(node2=node2->next; node2 && node2->pkt->pkttype!=PKT_SECRET_SUBKEY; node2=node2->next) if(node2->pkt->pkttype==PKT_SIGNATURE && node2->pkt->pkt.signature->version>=4 && node2->pkt->pkt.signature->keyid[0]==sig_pk->pkt->pkt.signature->keyid[0] && node2->pkt->pkt.signature->keyid[1]==sig_pk->pkt->pkt.signature->keyid[1] && node2->pkt->pkt.signature->sig_class==sig_pk->pkt->pkt.signature->sig_class) { sig_sk=node2; break; } /* Now we can get to work. We have a main key and secret part, a signing subkey with signature and secret part possibly with signature. */ passphrase=get_last_passphrase(); set_next_passphrase(passphrase); xfree(passphrase); rc = make_backsig (sig_pk->pkt->pkt.signature, main_pk, sub_pk, sub_sk, timestamp); if(rc==0) { PKT_signature *newsig; PACKET *newpkt; passphrase=get_last_passphrase(); set_next_passphrase(passphrase); xfree(passphrase); rc=update_keysig_packet(&newsig,sig_pk->pkt->pkt.signature,main_pk, NULL,sub_pk,main_sk,NULL,NULL); if(rc==0) { /* Put the new sig into place on the pubkey */ newpkt=xmalloc_clear(sizeof(*newpkt)); newpkt->pkttype=PKT_SIGNATURE; newpkt->pkt.signature=newsig; free_packet(sig_pk->pkt); xfree(sig_pk->pkt); sig_pk->pkt=newpkt; if(sig_sk) { /* Put the new sig into place on the seckey */ newpkt=xmalloc_clear(sizeof(*newpkt)); newpkt->pkttype=PKT_SIGNATURE; newpkt->pkt.signature=copy_signature(NULL,newsig); free_packet(sig_sk->pkt); xfree(sig_sk->pkt); sig_sk->pkt=newpkt; } modified=1; } else { log_error("update_keysig_packet failed: %s\n",g10_errstr(rc)); break; } } else { log_error("make_backsig failed: %s\n",g10_errstr(rc)); break; } } set_next_passphrase(NULL); free_secret_key(main_sk); if(sub_sk) free_secret_key(sub_sk); return modified; } static int change_primary_uid_cb ( PKT_signature *sig, void *opaque ) { byte buf[1]; /* first clear all primary uid flags so that we are sure none are * lingering around */ delete_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID); delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PRIMARY_UID); /* if opaque is set,we want to set the primary id */ if (opaque) { buf[0] = 1; build_sig_subpkt (sig, SIGSUBPKT_PRIMARY_UID, buf, 1 ); } return 0; } /* * Set the primary uid flag for the selected UID. We will also reset * all other primary uid flags. For this to work with have to update * all the signature timestamps. If we would do this with the current * time, we lose quite a lot of information, so we use a a kludge to * do this: Just increment the timestamp by one second which is * sufficient to updated a signature during import. */ static int menu_set_primary_uid ( KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_secret_key *sk; /* copy of the main sk */ PKT_public_key *main_pk; PKT_user_id *uid; KBNODE node; u32 keyid[2]; int selected; int attribute = 0; int modified = 0; if ( count_selected_uids (pub_keyblock) != 1 ) { tty_printf(_("Please select exactly one user ID.\n")); return 0; } node = find_kbnode( sec_keyblock, PKT_SECRET_KEY ); sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); /* Now we can actually change the self signature(s) */ main_pk = NULL; uid = NULL; selected = 0; /* Is our selected uid an attribute packet? */ for ( node=pub_keyblock; node; node = node->next ) if (node->pkt->pkttype == PKT_USER_ID && node->flag & NODFLG_SELUID) attribute = (node->pkt->pkt.user_id->attrib_data!=NULL); for ( node=pub_keyblock; node; node = node->next ) { if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; /* ready */ if ( node->pkt->pkttype == PKT_PUBLIC_KEY ) { main_pk = node->pkt->pkt.public_key; keyid_from_pk( main_pk, keyid ); } else if ( node->pkt->pkttype == PKT_USER_ID ) { uid = node->pkt->pkt.user_id; selected = node->flag & NODFLG_SELUID; } else if ( main_pk && uid && node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; if ( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] && (uid && (sig->sig_class&~3) == 0x10) && attribute == (uid->attrib_data!=NULL) && sig->flags.chosen_selfsig ) { if(sig->version < 4) { char *user=utf8_to_native(uid->name,strlen(uid->name),0); log_info(_("skipping v3 self-signature on user ID \"%s\"\n"), user); xfree(user); } else { /* This is a selfsignature which is to be replaced. We can just ignore v3 signatures because they are not able to carry the primary ID flag. We also ignore self-sigs on user IDs that are not of the same type that we are making primary. That is, if we are making a user ID primary, we alter user IDs. If we are making an attribute packet primary, we alter attribute packets. */ /* FIXME: We must make sure that we only have one self-signature per user ID here (not counting revocations) */ PKT_signature *newsig; PACKET *newpkt; const byte *p; int action; /* see whether this signature has the primary UID flag */ p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL ); if ( !p ) p = parse_sig_subpkt (sig->unhashed, SIGSUBPKT_PRIMARY_UID, NULL ); if ( p && *p ) /* yes */ action = selected? 0 : -1; else /* no */ action = selected? 1 : 0; if (action) { int rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL, sk, change_primary_uid_cb, action > 0? "x":NULL ); if( rc ) { log_error ("update_keysig_packet failed: %s\n", g10_errstr(rc)); free_secret_key( sk ); return 0; } /* replace the packet */ newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = newsig; free_packet( node->pkt ); xfree( node->pkt ); node->pkt = newpkt; modified = 1; } } } } } free_secret_key( sk ); return modified; } /* * Set preferences to new values for the selected user IDs */ static int menu_set_preferences (KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_secret_key *sk; /* copy of the main sk */ PKT_public_key *main_pk; PKT_user_id *uid; KBNODE node; u32 keyid[2]; int selected, select_all; int modified = 0; no_primary_warning(pub_keyblock); select_all = !count_selected_uids (pub_keyblock); node = find_kbnode( sec_keyblock, PKT_SECRET_KEY ); sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); /* Now we can actually change the self signature(s) */ main_pk = NULL; uid = NULL; selected = 0; for ( node=pub_keyblock; node; node = node->next ) { if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; /* ready */ if ( node->pkt->pkttype == PKT_PUBLIC_KEY ) { main_pk = node->pkt->pkt.public_key; keyid_from_pk( main_pk, keyid ); } else if ( node->pkt->pkttype == PKT_USER_ID ) { uid = node->pkt->pkt.user_id; selected = select_all || (node->flag & NODFLG_SELUID); } else if ( main_pk && uid && selected && node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; if ( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] && (uid && (sig->sig_class&~3) == 0x10) && sig->flags.chosen_selfsig ) { if( sig->version < 4 ) { char *user=utf8_to_native(uid->name,strlen(uid->name),0); log_info(_("skipping v3 self-signature on user ID \"%s\"\n"), user); xfree(user); } else { /* This is a selfsignature which is to be replaced * We have to ignore v3 signatures because they are * not able to carry the preferences */ PKT_signature *newsig; PACKET *newpkt; int rc; rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL, sk, keygen_upd_std_prefs, NULL ); if( rc ) { log_error ("update_keysig_packet failed: %s\n", g10_errstr(rc)); free_secret_key( sk ); return 0; } /* replace the packet */ newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = newsig; free_packet( node->pkt ); xfree( node->pkt ); node->pkt = newpkt; modified = 1; } } } } free_secret_key( sk ); return modified; } static int menu_set_keyserver_url (const char *url, KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_secret_key *sk; /* copy of the main sk */ PKT_public_key *main_pk; PKT_user_id *uid; KBNODE node; u32 keyid[2]; int selected, select_all; int modified = 0; char *answer,*uri; no_primary_warning(pub_keyblock); if(url) answer=xstrdup(url); else { answer=cpr_get_utf8("keyedit.add_keyserver", _("Enter your preferred keyserver URL: ")); if(answer[0]=='\0' || answer[0]=='\004') { xfree(answer); return 0; } } if(ascii_strcasecmp(answer,"none")==0) uri=NULL; else { struct keyserver_spec *keyserver=NULL; /* Sanity check the format */ keyserver=parse_keyserver_uri(answer,1,NULL,0); xfree(answer); if(!keyserver) { log_info(_("could not parse keyserver URL\n")); return 0; } uri=xstrdup(keyserver->uri); free_keyserver_spec(keyserver); } select_all = !count_selected_uids (pub_keyblock); node = find_kbnode( sec_keyblock, PKT_SECRET_KEY ); sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); /* Now we can actually change the self signature(s) */ main_pk = NULL; uid = NULL; selected = 0; for ( node=pub_keyblock; node; node = node->next ) { if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; /* ready */ if ( node->pkt->pkttype == PKT_PUBLIC_KEY ) { main_pk = node->pkt->pkt.public_key; keyid_from_pk( main_pk, keyid ); } else if ( node->pkt->pkttype == PKT_USER_ID ) { uid = node->pkt->pkt.user_id; selected = select_all || (node->flag & NODFLG_SELUID); } else if ( main_pk && uid && selected && node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; if ( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] && (uid && (sig->sig_class&~3) == 0x10) && sig->flags.chosen_selfsig) { char *user=utf8_to_native(uid->name,strlen(uid->name),0); if( sig->version < 4 ) log_info(_("skipping v3 self-signature on user ID \"%s\"\n"), user); else { /* This is a selfsignature which is to be replaced * We have to ignore v3 signatures because they are * not able to carry the subpacket. */ PKT_signature *newsig; PACKET *newpkt; int rc; const byte *p; size_t plen; p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen); if(p && plen) { tty_printf("Current preferred keyserver for user" " ID \"%s\": ",user); tty_print_utf8_string(p,plen); tty_printf("\n"); if(!cpr_get_answer_is_yes("keyedit.confirm_keyserver", uri?_("Are you sure you want to replace it? (y/N) "): _("Are you sure you want to delete it? (y/N) "))) continue; } else if(uri==NULL) { /* There is no current keyserver URL, so there is no point in trying to un-set it. */ continue; } rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL, sk, keygen_add_keyserver_url, uri ); if( rc ) { log_error ("update_keysig_packet failed: %s\n", g10_errstr(rc)); free_secret_key( sk ); xfree(uri); return 0; } /* replace the packet */ newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = newsig; free_packet( node->pkt ); xfree( node->pkt ); node->pkt = newpkt; modified = 1; } xfree(user); } } } xfree(uri); free_secret_key( sk ); return modified; } static int menu_set_notation(const char *string,KBNODE pub_keyblock,KBNODE sec_keyblock) { PKT_secret_key *sk; /* copy of the main sk */ PKT_public_key *main_pk; PKT_user_id *uid; KBNODE node; u32 keyid[2]; int selected, select_all; int modified = 0; char *answer; struct notation *notation; no_primary_warning(pub_keyblock); if(string) answer=xstrdup(string); else { answer=cpr_get_utf8("keyedit.add_notation", _("Enter the notation: ")); if(answer[0]=='\0' || answer[0]=='\004') { xfree(answer); return 0; } } if(ascii_strcasecmp(answer,"none")==0 || ascii_strcasecmp(answer,"-")==0) notation=NULL; /* delete them all */ else { notation=string_to_notation(answer,0); if(!notation) { xfree(answer); return 0; } } xfree(answer); select_all = !count_selected_uids (pub_keyblock); node = find_kbnode( sec_keyblock, PKT_SECRET_KEY ); sk = copy_secret_key( NULL, node->pkt->pkt.secret_key); /* Now we can actually change the self signature(s) */ main_pk = NULL; uid = NULL; selected = 0; for ( node=pub_keyblock; node; node = node->next ) { if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; /* ready */ if ( node->pkt->pkttype == PKT_PUBLIC_KEY ) { main_pk = node->pkt->pkt.public_key; keyid_from_pk( main_pk, keyid ); } else if ( node->pkt->pkttype == PKT_USER_ID ) { uid = node->pkt->pkt.user_id; selected = select_all || (node->flag & NODFLG_SELUID); } else if ( main_pk && uid && selected && node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; if ( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] && (uid && (sig->sig_class&~3) == 0x10) && sig->flags.chosen_selfsig) { char *user=utf8_to_native(uid->name,strlen(uid->name),0); if( sig->version < 4 ) log_info(_("skipping v3 self-signature on user ID \"%s\"\n"), user); else { PKT_signature *newsig; PACKET *newpkt; int rc,skip=0,addonly=1; if(sig->flags.notation) { tty_printf("Current notations for user ID \"%s\":\n", user); tty_print_notations(-9,sig); } else { tty_printf("No notations on user ID \"%s\"\n",user); if(notation==NULL) { /* There are no current notations, so there is no point in trying to un-set them. */ continue; } } if(notation) { struct notation *n; int deleting=0; notation->next=sig_to_notation(sig); for(n=notation->next;n;n=n->next) if(strcmp(n->name,notation->name)==0) { if(notation->value) { if(strcmp(n->value,notation->value)==0) { if(notation->flags.ignore) { /* Value match with a delete flag. */ n->flags.ignore=1; deleting=1; } else { /* Adding the same notation twice, so don't add it at all. */ skip=1; tty_printf("Skipping notation:" " %s=%s\n", notation->name, notation->value); break; } } } else { /* No value, so it means delete. */ n->flags.ignore=1; deleting=1; } if(n->flags.ignore) { tty_printf("Removing notation: %s=%s\n", n->name,n->value); addonly=0; } } if(!notation->flags.ignore && !skip) tty_printf("Adding notation: %s=%s\n", notation->name,notation->value); /* We tried to delete, but had no matches */ if(notation->flags.ignore && !deleting) continue; } else { tty_printf("Removing all notations\n"); addonly=0; } if(skip || (!addonly && !cpr_get_answer_is_yes("keyedit.confirm_notation", _("Proceed? (y/N) ")))) continue; rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL, sk, keygen_add_notations, notation ); if( rc ) { log_error ("update_keysig_packet failed: %s\n", g10_errstr(rc)); free_secret_key( sk ); free_notation(notation); xfree(user); return 0; } /* replace the packet */ newpkt = xmalloc_clear( sizeof *newpkt ); newpkt->pkttype = PKT_SIGNATURE; newpkt->pkt.signature = newsig; free_packet( node->pkt ); xfree( node->pkt ); node->pkt = newpkt; modified = 1; if(notation) { /* Snip off the notation list from the sig */ free_notation(notation->next); notation->next=NULL; } xfree(user); } } } } free_notation(notation); free_secret_key( sk ); return modified; } /* * Select one user id or remove all selection if IDX is 0 or select * all if IDX is -1. Returns: True if the selection changed. */ static int menu_select_uid (KBNODE keyblock, int idx) { KBNODE node; int i; if (idx == -1) /* Select all. */ { for (node = keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_USER_ID) node->flag |= NODFLG_SELUID; return 1; } else if (idx) /* Toggle. */ { for (i=0, node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) if (++i == idx) break; } if (!node) { tty_printf (_("No user ID with index %d\n"), idx ); return 0; } for (i=0, node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { if (++i == idx) { if ((node->flag & NODFLG_SELUID)) node->flag &= ~NODFLG_SELUID; else node->flag |= NODFLG_SELUID; } } } } else /* Unselect all */ { for (node = keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_USER_ID) node->flag &= ~NODFLG_SELUID; } return 1; } /* Search in the keyblock for a uid that matches namehash */ static int menu_select_uid_namehash( KBNODE keyblock, const char *namehash ) { byte hash[NAMEHASH_LEN]; KBNODE node; int i; assert(strlen(namehash)==NAMEHASH_LEN*2); for(i=0;inext;node;node=node->next) { if(node->pkt->pkttype==PKT_USER_ID) { namehash_from_uid(node->pkt->pkt.user_id); if(memcmp(node->pkt->pkt.user_id->namehash,hash,NAMEHASH_LEN)==0) { if(node->flag&NODFLG_SELUID) node->flag &= ~NODFLG_SELUID; else node->flag |= NODFLG_SELUID; break; } } } if(!node) { tty_printf(_("No user ID with hash %s\n"),namehash); return 0; } return 1; } /**************** * Select secondary keys * Returns: True if the selection changed. */ static int menu_select_key (KBNODE keyblock, int idx) { KBNODE node; int i; if (idx == -1) /* Select all. */ { for (node = keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) node->flag |= NODFLG_SELKEY; } else if (idx) /* Toggle selection. */ { for (i=0, node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) if (++i == idx) break; } if (!node) { tty_printf (_("No subkey with index %d\n"), idx ); return 0; } for (i=0, node = keyblock; node; node = node->next) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY ) if (++i == idx) { if ((node->flag & NODFLG_SELKEY)) node->flag &= ~NODFLG_SELKEY; else node->flag |= NODFLG_SELKEY; } } } else /* Unselect all. */ { for (node = keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) node->flag &= ~NODFLG_SELKEY; } return 1; } static int count_uids_with_flag( KBNODE keyblock, unsigned flag ) { KBNODE node; int i=0; for( node = keyblock; node; node = node->next ) if( node->pkt->pkttype == PKT_USER_ID && (node->flag & flag) ) i++; return i; } static int count_keys_with_flag( KBNODE keyblock, unsigned flag ) { KBNODE node; int i=0; for( node = keyblock; node; node = node->next ) if( ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) && (node->flag & flag) ) i++; return i; } static int count_uids( KBNODE keyblock ) { KBNODE node; int i=0; for( node = keyblock; node; node = node->next ) if( node->pkt->pkttype == PKT_USER_ID ) i++; return i; } /**************** * Returns true if there is at least one selected user id */ static int count_selected_uids( KBNODE keyblock ) { return count_uids_with_flag( keyblock, NODFLG_SELUID); } static int count_selected_keys( KBNODE keyblock ) { return count_keys_with_flag( keyblock, NODFLG_SELKEY); } /* returns how many real (i.e. not attribute) uids are unmarked */ static int real_uids_left( KBNODE keyblock ) { KBNODE node; int real=0; for(node=keyblock;node;node=node->next) if(node->pkt->pkttype==PKT_USER_ID && !(node->flag&NODFLG_SELUID) && !node->pkt->pkt.user_id->attrib_data) real++; return real; } /* * Ask whether the signature should be revoked. If the user commits this, * flag bit MARK_A is set on the signature and the user ID. */ static void ask_revoke_sig( KBNODE keyblock, KBNODE node ) { int doit=0; PKT_user_id *uid; PKT_signature *sig = node->pkt->pkt.signature; KBNODE unode = find_prev_kbnode( keyblock, node, PKT_USER_ID ); if( !unode ) { log_error("Oops: no user ID for signature\n"); return; } uid=unode->pkt->pkt.user_id; if(opt.with_colons) { if(uid->attrib_data) printf("uat:::::::::%u %lu",uid->numattribs,uid->attrib_len); else { printf("uid:::::::::"); - print_string (stdout, uid->name, uid->len, ':'); + es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL); } printf("\n"); print_and_check_one_sig_colon(keyblock,node,NULL,NULL,NULL,NULL,1); } else { char *p=utf8_to_native(unode->pkt->pkt.user_id->name, unode->pkt->pkt.user_id->len,0); tty_printf(_("user ID: \"%s\"\n"),p); xfree(p); tty_printf(_("signed by your key %s on %s%s%s\n"), keystr(sig->keyid),datestr_from_sig(sig), sig->flags.exportable?"":_(" (non-exportable)"),""); } if(sig->flags.expired) { tty_printf(_("This signature expired on %s.\n"), expirestr_from_sig(sig)); /* Use a different question so we can have different help text */ doit=cpr_get_answer_is_yes("ask_revoke_sig.expired", _("Are you sure you still want to revoke it? (y/N) ")); } else doit=cpr_get_answer_is_yes("ask_revoke_sig.one", _("Create a revocation certificate for this signature? (y/N) ")); if(doit) { node->flag |= NODFLG_MARK_A; unode->flag |= NODFLG_MARK_A; } } /**************** * Display all user ids of the current public key together with signatures * done by one of our keys. Then walk over all this sigs and ask the user * whether he wants to revoke this signature. * Return: True when the keyblock has changed. */ static int menu_revsig( KBNODE keyblock ) { PKT_signature *sig; PKT_public_key *primary_pk; KBNODE node; int changed = 0; int rc, any, skip=1, all=!count_selected_uids(keyblock); struct revocation_reason_info *reason = NULL; assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); /* First check whether we have any signatures at all. */ any = 0; for (node = keyblock; node; node = node->next ) { node->flag &= ~(NODFLG_SELSIG | NODFLG_MARK_A); if (node->pkt->pkttype == PKT_USER_ID) { if (node->flag&NODFLG_SELUID || all) skip = 0; else skip = 1; } else if (!skip && node->pkt->pkttype == PKT_SIGNATURE && ((sig = node->pkt->pkt.signature), !seckey_available(sig->keyid) )) { if ((sig->sig_class&~3) == 0x10) { any = 1; break; } } } if (!any) { tty_printf (_("Not signed by you.\n")); return 0; } /* FIXME: detect duplicates here */ tty_printf(_("You have signed these user IDs on key %s:\n"), keystr_from_pk(keyblock->pkt->pkt.public_key)); for( node = keyblock; node; node = node->next ) { node->flag &= ~(NODFLG_SELSIG | NODFLG_MARK_A); if( node->pkt->pkttype == PKT_USER_ID ) { if( node->flag&NODFLG_SELUID || all ) { PKT_user_id *uid = node->pkt->pkt.user_id; /* Hmmm: Should we show only UIDs with a signature? */ tty_printf(" "); tty_print_utf8_string( uid->name, uid->len ); tty_printf("\n"); skip=0; } else skip=1; } else if( !skip && node->pkt->pkttype == PKT_SIGNATURE && ((sig = node->pkt->pkt.signature), !seckey_available(sig->keyid) ) ) { if( (sig->sig_class&~3) == 0x10 ) { tty_printf(" "); tty_printf(_("signed by your key %s on %s%s%s\n"), keystr(sig->keyid), datestr_from_sig(sig), sig->flags.exportable?"":_(" (non-exportable)"), sig->flags.revocable?"":_(" (non-revocable)")); if(sig->flags.revocable) node->flag |= NODFLG_SELSIG; } else if( sig->sig_class == 0x30 ) { tty_printf(" "); tty_printf(_("revoked by your key %s on %s\n"), keystr(sig->keyid),datestr_from_sig(sig)); } } } tty_printf("\n"); /* ask */ for( node = keyblock; node; node = node->next ) { if( !(node->flag & NODFLG_SELSIG) ) continue; ask_revoke_sig( keyblock, node ); } /* present selected */ any = 0; for( node = keyblock; node; node = node->next ) { if( !(node->flag & NODFLG_MARK_A) ) continue; if( !any ) { any = 1; tty_printf(_("You are about to revoke these signatures:\n")); } if( node->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *uid = node->pkt->pkt.user_id; tty_printf(" "); tty_print_utf8_string( uid->name, uid->len ); tty_printf("\n"); } else if( node->pkt->pkttype == PKT_SIGNATURE ) { sig = node->pkt->pkt.signature; tty_printf(" "); tty_printf(_("signed by your key %s on %s%s%s\n"), keystr(sig->keyid), datestr_from_sig(sig),"", sig->flags.exportable?"":_(" (non-exportable)") ); } } if( !any ) return 0; /* none selected */ if( !cpr_get_answer_is_yes("ask_revoke_sig.okay", _("Really create the revocation certificates? (y/N) ")) ) return 0; /* forget it */ reason = ask_revocation_reason( 0, 1, 0 ); if( !reason ) { /* user decided to cancel */ return 0; } /* now we can sign the user ids */ reloop: /* (must use this, because we are modifing the list) */ primary_pk = keyblock->pkt->pkt.public_key; for( node=keyblock; node; node = node->next ) { KBNODE unode; PACKET *pkt; struct sign_attrib attrib; PKT_secret_key *sk; if( !(node->flag & NODFLG_MARK_A) || node->pkt->pkttype != PKT_SIGNATURE ) continue; unode = find_prev_kbnode( keyblock, node, PKT_USER_ID ); assert( unode ); /* we already checked this */ memset( &attrib, 0, sizeof attrib ); attrib.reason = reason; attrib.non_exportable=!node->pkt->pkt.signature->flags.exportable; node->flag &= ~NODFLG_MARK_A; sk = xmalloc_secure_clear( sizeof *sk ); if( get_seckey( sk, node->pkt->pkt.signature->keyid ) ) { log_info(_("no secret key\n")); continue; } rc = make_keysig_packet( &sig, primary_pk, unode->pkt->pkt.user_id, NULL, sk, 0x30, 0, 0, 0, 0, sign_mk_attrib, &attrib ); free_secret_key(sk); if( rc ) { log_error(_("signing failed: %s\n"), g10_errstr(rc)); release_revocation_reason_info( reason ); return changed; } changed = 1; /* we changed the keyblock */ update_trust = 1; /* Are we revoking our own uid? */ if(primary_pk->keyid[0]==sig->keyid[0] && primary_pk->keyid[1]==sig->keyid[1]) unode->pkt->pkt.user_id->is_revoked=1; pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( unode, new_kbnode(pkt), 0 ); goto reloop; } release_revocation_reason_info( reason ); return changed; } /* Revoke a user ID (i.e. revoke a user ID selfsig). Return true if keyblock changed. */ static int menu_revuid( KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key; PKT_secret_key *sk = copy_secret_key( NULL, sec_keyblock->pkt->pkt.secret_key ); KBNODE node; int changed = 0; int rc; struct revocation_reason_info *reason = NULL; /* Note that this is correct as per the RFCs, but nevertheless somewhat meaningless in the real world. 1991 did define the 0x30 sig class, but PGP 2.x did not actually implement it, so it would probably be safe to use v4 revocations everywhere. -ds */ for( node = pub_keyblock; node; node = node->next ) if(pk->version>3 || (node->pkt->pkttype==PKT_USER_ID && node->pkt->pkt.user_id->selfsigversion>3)) { if((reason = ask_revocation_reason( 0, 1, 4 ))) break; else goto leave; } reloop: /* (better this way because we are modifing the keyring) */ for( node = pub_keyblock; node; node = node->next ) if(node->pkt->pkttype == PKT_USER_ID && (node->flag & NODFLG_SELUID)) { PKT_user_id *uid=node->pkt->pkt.user_id; if(uid->is_revoked) { char *user=utf8_to_native(uid->name,uid->len,0); log_info(_("user ID \"%s\" is already revoked\n"),user); xfree(user); } else { PACKET *pkt; PKT_signature *sig; struct sign_attrib attrib; u32 timestamp=make_timestamp(); if(uid->created>=timestamp) { /* Okay, this is a problem. The user ID selfsig was created in the future, so we need to warn the user and set our revocation timestamp one second after that so everything comes out clean. */ log_info(_("WARNING: a user ID signature is dated %d" " seconds in the future\n"),uid->created-timestamp); timestamp=uid->created+1; } memset( &attrib, 0, sizeof attrib ); attrib.reason = reason; node->flag &= ~NODFLG_SELUID; rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x30, 0, (reason==NULL)?3:0, timestamp, 0, sign_mk_attrib, &attrib ); if( rc ) { log_error(_("signing failed: %s\n"), g10_errstr(rc)); goto leave; } else { pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( node, new_kbnode(pkt), 0 ); /* If the trustdb has an entry for this key+uid then the trustdb needs an update. */ if(!update_trust && (get_validity(pk,uid)&TRUST_MASK)>=TRUST_UNDEFINED) update_trust=1; changed = 1; node->pkt->pkt.user_id->is_revoked=1; goto reloop; } } } if(changed) commit_kbnode( &pub_keyblock ); leave: free_secret_key(sk); release_revocation_reason_info( reason ); return changed; } /**************** * Revoke the whole key. */ static int menu_revkey( KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_public_key *pk=pub_keyblock->pkt->pkt.public_key; PKT_secret_key *sk; int rc,changed = 0; struct revocation_reason_info *reason; PACKET *pkt; PKT_signature *sig; if(pk->is_revoked) { tty_printf(_("Key %s is already revoked.\n"),keystr_from_pk(pk)); return 0; } reason = ask_revocation_reason( 1, 0, 0 ); /* user decided to cancel */ if( !reason ) return 0; sk = copy_secret_key( NULL, sec_keyblock->pkt->pkt.secret_key ); rc = make_keysig_packet( &sig, pk, NULL, NULL, sk, 0x20, 0, opt.force_v4_certs?4:0, 0, 0, revocation_reason_build_cb, reason ); free_secret_key(sk); if( rc ) { log_error(_("signing failed: %s\n"), g10_errstr(rc)); goto scram; } changed = 1; /* we changed the keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( pub_keyblock, new_kbnode(pkt), 0 ); commit_kbnode( &pub_keyblock ); update_trust=1; scram: release_revocation_reason_info( reason ); return changed; } static int menu_revsubkey( KBNODE pub_keyblock, KBNODE sec_keyblock ) { PKT_public_key *mainpk; KBNODE node; int changed = 0; int rc; struct revocation_reason_info *reason = NULL; reason = ask_revocation_reason( 1, 0, 0 ); if( !reason ) { /* user decided to cancel */ return 0; } reloop: /* (better this way because we are modifing the keyring) */ mainpk = pub_keyblock->pkt->pkt.public_key; for( node = pub_keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY && (node->flag & NODFLG_SELKEY) ) { PACKET *pkt; PKT_signature *sig; PKT_secret_key *sk; PKT_public_key *subpk = node->pkt->pkt.public_key; struct sign_attrib attrib; if(subpk->is_revoked) { tty_printf(_("Subkey %s is already revoked.\n"), keystr_from_pk(subpk)); continue; } memset( &attrib, 0, sizeof attrib ); attrib.reason = reason; node->flag &= ~NODFLG_SELKEY; sk = copy_secret_key( NULL, sec_keyblock->pkt->pkt.secret_key ); rc = make_keysig_packet( &sig, mainpk, NULL, subpk, sk, 0x28, 0, 0, 0, 0, sign_mk_attrib, &attrib ); free_secret_key(sk); if( rc ) { log_error(_("signing failed: %s\n"), g10_errstr(rc)); release_revocation_reason_info( reason ); return changed; } changed = 1; /* we changed the keyblock */ pkt = xmalloc_clear( sizeof *pkt ); pkt->pkttype = PKT_SIGNATURE; pkt->pkt.signature = sig; insert_kbnode( node, new_kbnode(pkt), 0 ); goto reloop; } } commit_kbnode( &pub_keyblock ); /*commit_kbnode( &sec_keyblock );*/ /* No need to set update_trust here since signing keys no longer are used to certify other keys, so there is no change in trust when revoking/removing them */ release_revocation_reason_info( reason ); return changed; } /* Note that update_ownertrust is going to mark the trustdb dirty when enabling or disabling a key. This is arguably sub-optimal as disabled keys are still counted in the web of trust, but perhaps not worth adding extra complexity to change. -ds */ static int enable_disable_key( KBNODE keyblock, int disable ) { PKT_public_key *pk = find_kbnode( keyblock, PKT_PUBLIC_KEY ) ->pkt->pkt.public_key; unsigned int trust, newtrust; trust = newtrust = get_ownertrust (pk); newtrust &= ~TRUST_FLAG_DISABLED; if( disable ) newtrust |= TRUST_FLAG_DISABLED; if( trust == newtrust ) return 0; /* already in that state */ update_ownertrust(pk, newtrust ); return 0; } static void menu_showphoto( KBNODE keyblock ) { KBNODE node; int select_all = !count_selected_uids(keyblock); int count=0; PKT_public_key *pk=NULL; /* Look for the public key first. We have to be really, really, explicit as to which photo this is, and what key it is a UID on since people may want to sign it. */ for( node = keyblock; node; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_KEY ) pk = node->pkt->pkt.public_key; else if( node->pkt->pkttype == PKT_USER_ID ) { PKT_user_id *uid = node->pkt->pkt.user_id; count++; if((select_all || (node->flag & NODFLG_SELUID)) && uid->attribs!=NULL) { int i; for(i=0;inumattribs;i++) { byte type; u32 size; if(uid->attribs[i].type==ATTRIB_IMAGE && parse_image_header(&uid->attribs[i],&type,&size)) { tty_printf(_("Displaying %s photo ID of size %ld for " "key %s (uid %d)\n"), image_type_to_string(type,1), (ulong)size,keystr_from_pk(pk),count); show_photos(&uid->attribs[i],1,pk,NULL,uid); } } } } } } diff --git a/g10/keylist.c b/g10/keylist.c index f5a977362..6d70b2bb4 100644 --- a/g10/keylist.c +++ b/g10/keylist.c @@ -1,1633 +1,1598 @@ /* keylist.c - Print information about OpenPGP keys * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2008, 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_DOSISH_SYSTEM #include /* for setmode() */ #endif #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "keydb.h" #include "photoid.h" #include "util.h" #include "ttyio.h" #include "trustdb.h" #include "main.h" #include "i18n.h" #include "status.h" static void list_all (int); static void list_one (strlist_t names, int secret); static void locate_one (strlist_t names); static void print_card_serialno (PKT_secret_key * sk); struct sig_stats { int inv_sigs; int no_key; int oth_err; }; /* The stream used to write attribute packets to. */ -static FILE *attrib_fp = NULL; +static estream_t attrib_fp; /* List the keys. If list is NULL, all available keys are listed. With LOCATE_MODE set the locate algorithm is used to find a key. */ void public_key_list (strlist_t list, int locate_mode) { if (opt.with_colons) { byte trust_model, marginals, completes, cert_depth; ulong created, nextcheck; read_trust_options (&trust_model, &created, &nextcheck, &marginals, &completes, &cert_depth); - printf ("tru:"); + es_fprintf (es_stdout, "tru:"); if (nextcheck && nextcheck <= make_timestamp ()) - printf ("o"); + es_fprintf (es_stdout, "o"); if (trust_model != opt.trust_model) - printf ("t"); + es_fprintf (es_stdout, "t"); if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC) { if (marginals != opt.marginals_needed) - printf ("m"); + es_fprintf (es_stdout, "m"); if (completes != opt.completes_needed) - printf ("c"); + es_fprintf (es_stdout, "c"); if (cert_depth != opt.max_cert_depth) - printf ("d"); + es_fprintf (es_stdout, "d"); } - printf (":%d:%lu:%lu", trust_model, created, nextcheck); + es_fprintf (es_stdout, ":%d:%lu:%lu", trust_model, created, nextcheck); /* Only show marginals, completes, and cert_depth in the classic or PGP trust models since they are not meaningful otherwise. */ if (trust_model == TM_PGP || trust_model == TM_CLASSIC) - printf (":%d:%d:%d", marginals, completes, cert_depth); + es_fprintf (es_stdout, ":%d:%d:%d", marginals, completes, cert_depth); - printf ("\n"); + es_fprintf (es_stdout, "\n"); } /* We need to do the stale check right here because it might need to update the keyring while we already have the keyring open. This is very bad for W32 because of a sharing violation. For real OSes it might lead to false results if we are later listing a keyring which is associated with the inode of a deleted file. */ check_trustdb_stale (); if (locate_mode) locate_one (list); else if (!list) list_all (0); else list_one (list, 0); } void secret_key_list (strlist_t list) { check_trustdb_stale (); if (!list) list_all (1); else /* List by user id */ list_one (list, 1); } void print_seckey_info (PKT_public_key *pk) { u32 keyid[2]; char *p; keyid_from_pk (pk, keyid); p = get_user_id_native (keyid); tty_printf ("\nsec %4u%c/%s %s %s\n", nbits_from_pk (pk), pubkey_letter (pk->pubkey_algo), keystr (keyid), datestr_from_pk (pk), p); xfree (p); } /* Print information about the public key. With FP passed as NULL, the tty output interface is used, otherwise output is directted to the given stream. */ void -print_pubkey_info (FILE * fp, PKT_public_key * pk) +print_pubkey_info (estream_t fp, PKT_public_key * pk) { u32 keyid[2]; char *p; keyid_from_pk (pk, keyid); /* If the pk was chosen by a particular user ID, that is the one to print. */ if (pk->user_id) p = utf8_to_native (pk->user_id->name, pk->user_id->len, 0); else p = get_user_id_native (keyid); if (fp) - fprintf (fp, "pub %4u%c/%s %s %s\n", - nbits_from_pk (pk), - pubkey_letter (pk->pubkey_algo), - keystr (keyid), datestr_from_pk (pk), p); - else - tty_printf ("\npub %4u%c/%s %s %s\n", - nbits_from_pk (pk), pubkey_letter (pk->pubkey_algo), - keystr (keyid), datestr_from_pk (pk), p); - + tty_printf ("\n"); + tty_fprintf (fp, "pub %4u%c/%s %s %s\n", + nbits_from_pk (pk), + pubkey_letter (pk->pubkey_algo), + keystr (keyid), datestr_from_pk (pk), p); xfree (p); } /* Print basic information of a secret key including the card serial number information. */ void -print_card_key_info (FILE * fp, KBNODE keyblock) +print_card_key_info (estream_t fp, KBNODE keyblock) { KBNODE node; int i; for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_SECRET_KEY || (node->pkt->pkttype == PKT_SECRET_SUBKEY)) { PKT_secret_key *sk = node->pkt->pkt.secret_key; tty_fprintf (fp, "%s%c %4u%c/%s ", node->pkt->pkttype == PKT_SECRET_KEY ? "sec" : "ssb", (sk->protect.s2k.mode == 1001) ? '#' : (sk->protect.s2k.mode == 1002) ? '>' : ' ', nbits_from_sk (sk), pubkey_letter (sk->pubkey_algo), keystr_from_sk (sk)); tty_fprintf (fp, _("created: %s"), datestr_from_sk (sk)); tty_fprintf (fp, " "); tty_fprintf (fp, _("expires: %s"), expirestr_from_sk (sk)); if (sk->is_protected && sk->protect.s2k.mode == 1002) { tty_fprintf (fp, "\n "); tty_fprintf (fp, _("card-no: ")); if (sk->protect.ivlen == 16 && !memcmp (sk->protect.iv, "\xD2\x76\x00\x01\x24\x01", 6)) { /* This is an OpenPGP card. */ for (i = 8; i < 14; i++) { if (i == 10) tty_fprintf (fp, " "); tty_fprintf (fp, "%02X", sk->protect.iv[i]); } } else { /* Something is wrong: Print all. */ for (i = 0; i < sk->protect.ivlen; i++) tty_fprintf (fp, "%02X", sk->protect.iv[i]); } } tty_fprintf (fp, "\n"); } } } /* Flags = 0x01 hashed 0x02 critical. */ static void status_one_subpacket (sigsubpkttype_t type, size_t len, int flags, const byte * buf) { char status[40]; /* Don't print these. */ if (len > 256) return; - sprintf (status, "%d %u %u ", type, flags, (unsigned int) len); + snprintf (status, sizeof status, + "%d %u %u ", type, flags, (unsigned int) len); write_status_text_and_buffer (STATUS_SIG_SUBPACKET, status, buf, len, 0); } /* Print a policy URL. Allowed values for MODE are: * 0 - print to stdout. * 1 - use log_info and emit status messages. * 2 - emit only status messages. */ void show_policy_url (PKT_signature * sig, int indent, int mode) { const byte *p; size_t len; int seq = 0, crit; - FILE *fp = mode ? log_get_stream () : stdout; + estream_t fp = mode ? log_get_stream () : es_stdout; while ((p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, &len, &seq, &crit))) { if (mode != 2) { int i; const char *str; for (i = 0; i < indent; i++) - putchar (' '); + es_putc (' ', fp); if (crit) str = _("Critical signature policy: "); else str = _("Signature policy: "); if (mode) log_info ("%s", str); else - printf ("%s", str); - print_utf8_string (fp, p, len); - fprintf (fp, "\n"); + es_fprintf (fp, "%s", str); + print_utf8_buffer (fp, p, len); + es_fprintf (fp, "\n"); } if (mode) write_status_buffer (STATUS_POLICY_URL, p, len, 0); } } /* mode=0 for stdout. mode=1 for log_info + status messages mode=2 for status messages only */ /* TODO: use this */ void show_keyserver_url (PKT_signature * sig, int indent, int mode) { const byte *p; size_t len; int seq = 0, crit; - FILE *fp = mode ? log_get_stream () : stdout; + estream_t fp = mode ? log_get_stream () : es_stdout; while ((p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, &len, &seq, &crit))) { if (mode != 2) { int i; const char *str; for (i = 0; i < indent; i++) - putchar (' '); + es_putc (' ', es_stdout); if (crit) str = _("Critical preferred keyserver: "); else str = _("Preferred keyserver: "); if (mode) log_info ("%s", str); else - printf ("%s", str); - print_utf8_string (fp, p, len); - fprintf (fp, "\n"); + es_fprintf (es_stdout, "%s", str); + print_utf8_buffer (fp, p, len); + es_fprintf (fp, "\n"); } if (mode) status_one_subpacket (SIGSUBPKT_PREF_KS, len, (crit ? 0x02 : 0) | 0x01, p); } } /* mode=0 for stdout. mode=1 for log_info + status messages mode=2 for status messages only Defined bits in WHICH: 1 == standard notations 2 == user notations */ void show_notation (PKT_signature * sig, int indent, int mode, int which) { - FILE *fp = mode ? log_get_stream () : stdout; + estream_t fp = mode ? log_get_stream () : es_stdout; struct notation *nd, *notations; if (which == 0) which = 3; notations = sig_to_notation (sig); /* There may be multiple notations in the same sig. */ for (nd = notations; nd; nd = nd->next) { if (mode != 2) { int has_at = !!strchr (nd->name, '@'); if ((which & 1 && !has_at) || (which & 2 && has_at)) { int i; const char *str; for (i = 0; i < indent; i++) - putchar (' '); + es_putc (' ', es_stdout); if (nd->flags.critical) str = _("Critical signature notation: "); else str = _("Signature notation: "); if (mode) log_info ("%s", str); else - printf ("%s", str); + es_fprintf (es_stdout, "%s", str); /* This is all UTF8 */ - print_utf8_string (fp, nd->name, strlen (nd->name)); - fprintf (fp, "="); - print_utf8_string (fp, nd->value, strlen (nd->value)); - fprintf (fp, "\n"); + print_utf8_buffer (fp, nd->name, strlen (nd->name)); + es_fprintf (fp, "="); + print_utf8_buffer (fp, nd->value, strlen (nd->value)); + es_fprintf (fp, "\n"); } } if (mode) { write_status_buffer (STATUS_NOTATION_NAME, nd->name, strlen (nd->name), 0); write_status_buffer (STATUS_NOTATION_DATA, nd->value, strlen (nd->value), 50); } } free_notation (notations); } static void print_signature_stats (struct sig_stats *s) { if (s->inv_sigs == 1) tty_printf (_("1 bad signature\n")); else if (s->inv_sigs) tty_printf (_("%d bad signatures\n"), s->inv_sigs); if (s->no_key == 1) tty_printf (_("1 signature not checked due to a missing key\n")); else if (s->no_key) tty_printf (_("%d signatures not checked due to missing keys\n"), s->no_key); if (s->oth_err == 1) tty_printf (_("1 signature not checked due to an error\n")); else if (s->oth_err) tty_printf (_("%d signatures not checked due to errors\n"), s->oth_err); } static void list_all (int secret) { KEYDB_HANDLE hd; KBNODE keyblock = NULL; int rc = 0; const char *lastresname, *resname; struct sig_stats stats; memset (&stats, 0, sizeof (stats)); hd = keydb_new (0); if (!hd) rc = G10ERR_GENERAL; else rc = keydb_search_first (hd); if (rc) { if (rc != -1) log_error ("keydb_search_first failed: %s\n", g10_errstr (rc)); goto leave; } lastresname = NULL; do { rc = keydb_get_keyblock (hd, &keyblock); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc)); goto leave; } if (secret && have_secret_key (keyblock)) ; /* Secret key listing requested but this isn't one. */ else { if (!opt.with_colons) { resname = keydb_get_resource_name (hd); if (lastresname != resname) { int i; - printf ("%s\n", resname); + es_fprintf (es_stdout, "%s\n", resname); for (i = strlen (resname); i; i--) - putchar ('-'); - putchar ('\n'); + es_putc ('-', es_stdout); + es_putc ('\n', es_stdout); lastresname = resname; } } merge_keys_and_selfsig (keyblock); list_keyblock (keyblock, secret, opt.fingerprint, opt.check_sigs ? &stats : NULL); } release_kbnode (keyblock); keyblock = NULL; } while (!(rc = keydb_search_next (hd))); if (rc && rc != -1) log_error ("keydb_search_next failed: %s\n", g10_errstr (rc)); if (opt.check_sigs && !opt.with_colons) print_signature_stats (&stats); leave: release_kbnode (keyblock); keydb_release (hd); } static void list_one (strlist_t names, int secret) { int rc = 0; KBNODE keyblock = NULL; GETKEY_CTX ctx; const char *resname; const char *keyring_str = _("Keyring"); int i; struct sig_stats stats; memset (&stats, 0, sizeof (stats)); /* fixme: using the bynames function has the disadvantage that we * don't know wether one of the names given was not found. OTOH, * this function has the advantage to list the names in the * sequence as defined by the keyDB and does not duplicate * outputs. A solution could be do test whether all given have * been listed (this needs a way to use the keyDB search * functions) or to have the search function return indicators for * found names. Yet another way is to use the keydb search * facilities directly. */ rc = getkey_bynames (&ctx, NULL, names, secret, &keyblock); if (rc) { log_error ("error reading key: %s\n", g10_errstr (rc)); get_pubkey_end (ctx); return; } do { if ((opt.list_options & LIST_SHOW_KEYRING) && !opt.with_colons) { resname = keydb_get_resource_name (get_ctx_handle (ctx)); - printf ("%s: %s\n", keyring_str, resname); + es_fprintf (es_stdout, "%s: %s\n", keyring_str, resname); for (i = strlen (resname) + strlen (keyring_str) + 2; i; i--) - putchar ('-'); - putchar ('\n'); + es_putc ('-', es_stdout); + es_putc ('\n', es_stdout); } list_keyblock (keyblock, secret, opt.fingerprint, (!secret && opt.check_sigs)? &stats : NULL); release_kbnode (keyblock); } while (!getkey_next (ctx, NULL, &keyblock)); getkey_end (ctx); if (opt.check_sigs && !opt.with_colons) print_signature_stats (&stats); } static void locate_one (strlist_t names) { int rc = 0; strlist_t sl; GETKEY_CTX ctx = NULL; KBNODE keyblock = NULL; struct sig_stats stats; memset (&stats, 0, sizeof (stats)); for (sl = names; sl; sl = sl->next) { rc = get_pubkey_byname (&ctx, NULL, sl->d, &keyblock, NULL, 1, 0); if (rc) { if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY) log_error ("error reading key: %s\n", g10_errstr (rc)); } else { do { list_keyblock (keyblock, 0, opt.fingerprint, opt.check_sigs ? &stats : NULL); release_kbnode (keyblock); } while (ctx && !get_pubkey_next (ctx, NULL, &keyblock)); get_pubkey_end (ctx); ctx = NULL; } } if (opt.check_sigs && !opt.with_colons) print_signature_stats (&stats); } static void print_key_data (PKT_public_key * pk) { int n = pk ? pubkey_get_npkey (pk->pubkey_algo) : 0; int i; for (i = 0; i < n; i++) { - printf ("pkd:%d:%u:", i, mpi_get_nbits (pk->pkey[i])); - mpi_print (stdout, pk->pkey[i], 1); - putchar (':'); - putchar ('\n'); + es_fprintf (es_stdout, "pkd:%d:%u:", i, mpi_get_nbits (pk->pkey[i])); + mpi_print (es_stdout, pk->pkey[i], 1); + es_putc (':', es_stdout); + es_putc ('\n', es_stdout); } } static void print_capabilities (PKT_public_key *pk, KBNODE keyblock) { unsigned int use = pk->pubkey_usage; int c_printed = 0; if (use & PUBKEY_USAGE_ENC) - putchar ('e'); + es_putc ('e', es_stdout); if (use & PUBKEY_USAGE_SIG) { - putchar ('s'); + es_putc ('s', es_stdout); if (pk->is_primary) { - putchar ('c'); + es_putc ('c', es_stdout); /* The PUBKEY_USAGE_CERT flag was introduced later and we used to always print 'c' for a primary key. To avoid any regression here we better track whether we printed 'c' already. */ c_printed = 1; } } if ((use & PUBKEY_USAGE_CERT) && !c_printed) - putchar ('c'); + es_putc ('c', es_stdout); if ((use & PUBKEY_USAGE_AUTH)) - putchar ('a'); + es_putc ('a', es_stdout); if (keyblock) { /* Figure out the usable capabilities. */ KBNODE k; int enc = 0, sign = 0, cert = 0, auth = 0, disabled = 0; for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { pk = k->pkt->pkt.public_key; if (pk->is_primary) disabled = pk_is_disabled (pk); if (pk->is_valid && !pk->is_revoked && !pk->has_expired) { if (pk->pubkey_usage & PUBKEY_USAGE_ENC) enc = 1; if (pk->pubkey_usage & PUBKEY_USAGE_SIG) { sign = 1; if (pk->is_primary) cert = 1; } if (pk->pubkey_usage & PUBKEY_USAGE_CERT) cert = 1; if ((pk->pubkey_usage & PUBKEY_USAGE_AUTH)) auth = 1; } } } if (enc) - putchar ('E'); + es_putc ('E', es_stdout); if (sign) - putchar ('S'); + es_putc ('S', es_stdout); if (cert) - putchar ('C'); + es_putc ('C', es_stdout); if (auth) - putchar ('A'); + es_putc ('A', es_stdout); if (disabled) - putchar ('D'); + es_putc ('D', es_stdout); } - putchar (':'); + es_putc (':', es_stdout); } /* FLAGS: 0x01 hashed 0x02 critical */ static void print_one_subpacket (sigsubpkttype_t type, size_t len, int flags, const byte * buf) { size_t i; - printf ("spk:%d:%u:%u:", type, flags, (unsigned int) len); + es_fprintf (es_stdout, "spk:%d:%u:%u:", type, flags, (unsigned int) len); for (i = 0; i < len; i++) { /* printable ascii other than : and % */ if (buf[i] >= 32 && buf[i] <= 126 && buf[i] != ':' && buf[i] != '%') - printf ("%c", buf[i]); + es_fprintf (es_stdout, "%c", buf[i]); else - printf ("%%%02X", buf[i]); + es_fprintf (es_stdout, "%%%02X", buf[i]); } - printf ("\n"); + es_fprintf (es_stdout, "\n"); } void print_subpackets_colon (PKT_signature * sig) { byte *i; assert (opt.show_subpackets); for (i = opt.show_subpackets; *i; i++) { const byte *p; size_t len; int seq, crit; seq = 0; while ((p = enum_sig_subpkt (sig->hashed, *i, &len, &seq, &crit))) print_one_subpacket (*i, len, 0x01 | (crit ? 0x02 : 0), p); seq = 0; while ((p = enum_sig_subpkt (sig->unhashed, *i, &len, &seq, &crit))) print_one_subpacket (*i, len, 0x00 | (crit ? 0x02 : 0), p); } } void dump_attribs (const PKT_user_id *uid, PKT_public_key *pk) { int i; if (!attrib_fp) return; for (i = 0; i < uid->numattribs; i++) { if (is_status_enabled ()) { byte array[MAX_FINGERPRINT_LEN], *p; char buf[(MAX_FINGERPRINT_LEN * 2) + 90]; size_t j, n; if (!pk) BUG (); fingerprint_from_pk (pk, array, &n); p = array; for (j = 0; j < n; j++, p++) sprintf (buf + 2 * j, "%02X", *p); sprintf (buf + strlen (buf), " %lu %u %u %u %lu %lu %u", (ulong) uid->attribs[i].len, uid->attribs[i].type, i + 1, uid->numattribs, (ulong) uid->created, (ulong) uid->expiredate, ((uid->is_primary ? 0x01 : 0) | (uid-> is_revoked ? 0x02 : 0) | (uid->is_expired ? 0x04 : 0))); write_status_text (STATUS_ATTRIBUTE, buf); } - fwrite (uid->attribs[i].data, uid->attribs[i].len, 1, attrib_fp); - fflush (attrib_fp); + es_fwrite (uid->attribs[i].data, uid->attribs[i].len, 1, attrib_fp); + es_fflush (attrib_fp); } } static void list_keyblock_print (KBNODE keyblock, int secret, int fpr, void *opaque) { int rc = 0; KBNODE kbctx; KBNODE node; PKT_public_key *pk; struct sig_stats *stats = opaque; int skip_sigs = 0; int s2k_char; /* Get the keyid from the keyblock. */ node = find_kbnode (keyblock, PKT_PUBLIC_KEY); if (!node) { log_error ("Oops; key lost!\n"); dump_kbnode (keyblock); return; } pk = node->pkt->pkt.public_key; /* Fixme: Get s2k mode from the agent. */ s2k_char = (/*(sk->protect.s2k.mode == 1001)? '#' : (sk->protect.s2k.mode == 1002)? '>' : */' '); check_trustdb_stale (); - printf ("%s%c %4u%c/%s %s", + es_fprintf (es_stdout, "%s%c %4u%c/%s %s", secret? "sec":"pub", s2k_char, nbits_from_pk (pk), pubkey_letter (pk->pubkey_algo), keystr_from_pk (pk), datestr_from_pk (pk)); if (pk->is_revoked) { - printf (" ["); - printf (_("revoked: %s"), revokestr_from_pk (pk)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("revoked: %s"), revokestr_from_pk (pk)); + es_fprintf (es_stdout, "]"); } else if (pk->has_expired) { - printf (" ["); - printf (_("expired: %s"), expirestr_from_pk (pk)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("expired: %s"), expirestr_from_pk (pk)); + es_fprintf (es_stdout, "]"); } else if (pk->expiredate) { - printf (" ["); - printf (_("expires: %s"), expirestr_from_pk (pk)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("expires: %s"), expirestr_from_pk (pk)); + es_fprintf (es_stdout, "]"); } #if 0 /* I need to think about this some more. It's easy enough to include, but it looks sort of confusing in the listing... */ if (opt.list_options & LIST_SHOW_VALIDITY) { int validity = get_validity (pk, NULL); - printf (" [%s]", trust_value_to_string (validity)); + es_fprintf (es_stdout, " [%s]", trust_value_to_string (validity)); } #endif - printf ("\n"); + es_fprintf (es_stdout, "\n"); if (fpr) print_fingerprint (pk, NULL, 0); /* FIXME: Change this function to take a PK and ask the agent: */ /* if (secret) print_card_serialno (sk); */ if (opt.with_key_data) print_key_data (pk); for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));) { if (node->pkt->pkttype == PKT_USER_ID && !opt.fast_list_mode) { PKT_user_id *uid = node->pkt->pkt.user_id; if (pk && (uid->is_expired || uid->is_revoked) && !(opt.list_options & LIST_SHOW_UNUSABLE_UIDS)) { skip_sigs = 1; continue; } else skip_sigs = 0; if (attrib_fp && uid->attrib_data != NULL) dump_attribs (uid, pk); if ((uid->is_revoked || uid->is_expired) || ((opt.list_options & LIST_SHOW_UID_VALIDITY) && pk)) { const char *validity; int indent; validity = uid_trust_string_fixed (pk, uid); indent = (keystrlen () + 9) - atoi (uid_trust_string_fixed (NULL, NULL)); if (indent < 0 || indent > 40) indent = 0; - printf ("uid%*s%s ", indent, "", validity); + es_fprintf (es_stdout, "uid%*s%s ", indent, "", validity); } else - printf ("uid%*s", (int) keystrlen () + 10, ""); + es_fprintf (es_stdout, "uid%*s", (int) keystrlen () + 10, ""); - print_utf8_string (stdout, uid->name, uid->len); - putchar ('\n'); + print_utf8_buffer (es_stdout, uid->name, uid->len); + es_putc ('\n', es_stdout); if ((opt.list_options & LIST_SHOW_PHOTOS) && uid->attribs != NULL) show_photos (uid->attribs, uid->numattribs, pk, NULL, uid); } else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk2 = node->pkt->pkt.public_key; if ((pk2->is_revoked || pk2->has_expired) && !(opt.list_options & LIST_SHOW_UNUSABLE_SUBKEYS)) { skip_sigs = 1; continue; } else skip_sigs = 0; /* Fixme: Get s2k mode from the agent. */ s2k_char = (/*(sk->protect.s2k.mode == 1001)? '#' : (sk->protect.s2k.mode == 1002)? '>' : */' '); - printf ("%s%c %4u%c/%s %s", + es_fprintf (es_stdout, "%s%c %4u%c/%s %s", secret? "ssb":"sub", s2k_char, nbits_from_pk (pk2), pubkey_letter (pk2->pubkey_algo), keystr_from_pk (pk2), datestr_from_pk (pk2)); if (pk2->is_revoked) { - printf (" ["); - printf (_("revoked: %s"), revokestr_from_pk (pk2)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("revoked: %s"), revokestr_from_pk (pk2)); + es_fprintf (es_stdout, "]"); } else if (pk2->has_expired) { - printf (" ["); - printf (_("expired: %s"), expirestr_from_pk (pk2)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("expired: %s"), expirestr_from_pk (pk2)); + es_fprintf (es_stdout, "]"); } else if (pk2->expiredate) { - printf (" ["); - printf (_("expires: %s"), expirestr_from_pk (pk2)); - printf ("]"); + es_fprintf (es_stdout, " ["); + es_fprintf (es_stdout, _("expires: %s"), expirestr_from_pk (pk2)); + es_fprintf (es_stdout, "]"); } - putchar ('\n'); + es_putc ('\n', es_stdout); if (fpr > 1) { print_fingerprint (pk2, NULL, 0); /* FIXME: (see above) */ /* if (secret) */ /* print_card_serialno (sk2); */ } if (opt.with_key_data) print_key_data (pk2); } else if (opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE && !skip_sigs) { PKT_signature *sig = node->pkt->pkt.signature; int sigrc; char *sigstr; if (stats) { rc = check_key_signature (keyblock, node, NULL); switch (gpg_err_code (rc)) { case 0: sigrc = '!'; break; case GPG_ERR_BAD_SIGNATURE: stats->inv_sigs++; sigrc = '-'; break; case GPG_ERR_NO_PUBKEY: case GPG_ERR_UNUSABLE_PUBKEY: stats->no_key++; continue; default: stats->oth_err++; sigrc = '%'; break; } /* TODO: Make sure a cached sig record here still has the pk that issued it. See also keyedit.c:print_and_check_one_sig */ } else { rc = 0; sigrc = ' '; } if (sig->sig_class == 0x20 || sig->sig_class == 0x28 || sig->sig_class == 0x30) sigstr = "rev"; else if ((sig->sig_class & ~3) == 0x10) sigstr = "sig"; else if (sig->sig_class == 0x18) sigstr = "sig"; else if (sig->sig_class == 0x1F) sigstr = "sig"; else { - printf ("sig " + es_fprintf (es_stdout, "sig " "[unexpected signature class 0x%02x]\n", sig->sig_class); continue; } - fputs (sigstr, stdout); - printf ("%c%c %c%c%c%c%c%c %s %s", + es_fputs (sigstr, es_stdout); + es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s", sigrc, (sig->sig_class - 0x10 > 0 && sig->sig_class - 0x10 < 4) ? '0' + sig->sig_class - 0x10 : ' ', sig->flags.exportable ? ' ' : 'L', sig->flags.revocable ? ' ' : 'R', sig->flags.policy_url ? 'P' : ' ', sig->flags.notation ? 'N' : ' ', sig->flags.expired ? 'X' : ' ', (sig->trust_depth > 9) ? 'T' : (sig->trust_depth > 0) ? '0' + sig->trust_depth : ' ', keystr (sig->keyid), datestr_from_sig (sig)); if (opt.list_options & LIST_SHOW_SIG_EXPIRE) - printf (" %s", expirestr_from_sig (sig)); - printf (" "); + es_fprintf (es_stdout, " %s", expirestr_from_sig (sig)); + es_fprintf (es_stdout, " "); if (sigrc == '%') - printf ("[%s] ", g10_errstr (rc)); + es_fprintf (es_stdout, "[%s] ", g10_errstr (rc)); else if (sigrc == '?') ; else if (!opt.fast_list_mode) { size_t n; char *p = get_user_id (sig->keyid, &n); - print_utf8_string (stdout, p, n); + print_utf8_buffer (es_stdout, p, n); xfree (p); } - putchar ('\n'); + es_putc ('\n', es_stdout); if (sig->flags.policy_url && (opt.list_options & LIST_SHOW_POLICY_URLS)) show_policy_url (sig, 3, 0); if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS)) show_notation (sig, 3, 0, ((opt. list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0) + ((opt. list_options & LIST_SHOW_USER_NOTATIONS) ? 2 : 0)); if (sig->flags.pref_ks && (opt.list_options & LIST_SHOW_KEYSERVER_URLS)) show_keyserver_url (sig, 3, 0); /* fixme: check or list other sigs here */ } } - putchar ('\n'); + es_putc ('\n', es_stdout); } void print_revokers (PKT_public_key * pk) { /* print the revoker record */ if (!pk->revkey && pk->numrevkeys) BUG (); else { int i, j; for (i = 0; i < pk->numrevkeys; i++) { byte *p; - printf ("rvk:::%d::::::", pk->revkey[i].algid); + es_fprintf (es_stdout, "rvk:::%d::::::", pk->revkey[i].algid); p = pk->revkey[i].fpr; for (j = 0; j < 20; j++, p++) - printf ("%02X", *p); - printf (":%02x%s:\n", pk->revkey[i].class, + es_fprintf (es_stdout, "%02X", *p); + es_fprintf (es_stdout, ":%02x%s:\n", pk->revkey[i].class, (pk->revkey[i].class & 0x40) ? "s" : ""); } } } static void list_keyblock_colon (KBNODE keyblock, int secret, int fpr) { int rc = 0; KBNODE kbctx; KBNODE node; PKT_public_key *pk; u32 keyid[2]; int trustletter = 0; int ulti_hack = 0; int i; /* Get the keyid from the keyblock. */ node = find_kbnode (keyblock, PKT_PUBLIC_KEY); if (!node) { log_error ("Oops; key lost!\n"); dump_kbnode (keyblock); return; } pk = node->pkt->pkt.public_key; keyid_from_pk (pk, keyid); - fputs (secret? "sec:":"pub:", stdout); + es_fputs (secret? "sec:":"pub:", es_stdout); if (!pk->is_valid) - putchar ('i'); + es_putc ('i', es_stdout); else if (pk->is_revoked) - putchar ('r'); + es_putc ('r', es_stdout); else if (pk->has_expired) - putchar ('e'); + es_putc ('e', es_stdout); else if (opt.fast_list_mode || opt.no_expensive_trust_checks) ; else { trustletter = get_validity_info (pk, NULL); if (trustletter == 'u') ulti_hack = 1; - putchar (trustletter); + es_putc (trustletter, es_stdout); } - printf (":%u:%d:%08lX%08lX:%s:%s::", + es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s::", nbits_from_pk (pk), pk->pubkey_algo, (ulong) keyid[0], (ulong) keyid[1], colon_datestr_from_pk (pk), colon_strtime (pk->expiredate)); if (!opt.fast_list_mode && !opt.no_expensive_trust_checks) - putchar (get_ownertrust_info (pk)); - putchar (':'); + es_putc (get_ownertrust (pk), es_stdout); + es_putc (':', es_stdout); - putchar (':'); - putchar (':'); + es_putc (':', es_stdout); + es_putc (':', es_stdout); print_capabilities (pk, keyblock); if (secret) { - putchar (':'); /* End of field 13. */ - putchar (':'); /* End of field 14. */ + es_putc (':', es_stdout); /* End of field 13. */ + es_putc (':', es_stdout); /* End of field 14. */ if (/*FIXME sk->protect.s2k.mode*/1 == 1001) - putchar ('#'); /* Key is just a stub. */ + es_putc ('#', es_stdout); /* Key is just a stub. */ else if (/*FIXME sk->protect.s2k.mode*/1 == 1002) { /* Key is stored on an external token (card) or handled by the gpg-agent. Print the serial number of that token here. */ /* FIXME: for (i = 0; i < sk->protect.ivlen; i++) */ - /* printf ("%02X", sk->protect.iv[i]); */ + /* es_fprintf (es_stdout, "%02X", sk->protect.iv[i]); */ } - putchar (':'); /* End of field 15. */ + es_putc (':', es_stdout); /* End of field 15. */ } - putchar ('\n'); + es_putc ('\n', es_stdout); print_revokers (pk); if (fpr) print_fingerprint (pk, NULL, 0); if (opt.with_key_data) print_key_data (pk); for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));) { if (node->pkt->pkttype == PKT_USER_ID && !opt.fast_list_mode) { char *str; PKT_user_id *uid = node->pkt->pkt.user_id; if (attrib_fp && node->pkt->pkt.user_id->attrib_data != NULL) dump_attribs (node->pkt->pkt.user_id, pk); /* * Fixme: We need a is_valid flag here too */ str = uid->attrib_data ? "uat" : "uid"; if (uid->is_revoked) - printf ("%s:r::::", str); + es_fprintf (es_stdout, "%s:r::::", str); else if (uid->is_expired) - printf ("%s:e::::", str); + es_fprintf (es_stdout, "%s:e::::", str); else if (opt.no_expensive_trust_checks) - printf ("%s:::::", str); + es_fprintf (es_stdout, "%s:::::", str); else { int uid_validity; if (pk && !ulti_hack) uid_validity = get_validity_info (pk, uid); else uid_validity = 'u'; - printf ("%s:%c::::", str, uid_validity); + es_fprintf (es_stdout, "%s:%c::::", str, uid_validity); } - printf ("%s:", colon_strtime (uid->created)); - printf ("%s:", colon_strtime (uid->expiredate)); + es_fprintf (es_stdout, "%s:", colon_strtime (uid->created)); + es_fprintf (es_stdout, "%s:", colon_strtime (uid->expiredate)); namehash_from_uid (uid); for (i = 0; i < 20; i++) - printf ("%02X", uid->namehash[i]); + es_fprintf (es_stdout, "%02X", uid->namehash[i]); - printf ("::"); + es_fprintf (es_stdout, "::"); if (uid->attrib_data) - printf ("%u %lu", uid->numattribs, uid->attrib_len); + es_fprintf (es_stdout, "%u %lu", uid->numattribs, uid->attrib_len); else - print_string (stdout, uid->name, uid->len, ':'); - putchar (':'); - putchar ('\n'); + es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL); + es_putc (':', es_stdout); + es_putc ('\n', es_stdout); } else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { u32 keyid2[2]; PKT_public_key *pk2 = node->pkt->pkt.public_key; keyid_from_pk (pk2, keyid2); - fputs (secret? "ssb:":"sub:", stdout); + es_fputs (secret? "ssb:":"sub:", es_stdout); if (!pk2->is_valid) - putchar ('i'); + es_putc ('i', es_stdout); else if (pk2->is_revoked) - putchar ('r'); + es_putc ('r', es_stdout); else if (pk2->has_expired) - putchar ('e'); + es_putc ('e', es_stdout); else if (opt.fast_list_mode || opt.no_expensive_trust_checks) ; else { /* TRUSTLETTER should always be defined here. */ if (trustletter) - printf ("%c", trustletter); + es_fprintf (es_stdout, "%c", trustletter); } - printf (":%u:%d:%08lX%08lX:%s:%s:::::", + es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s:::::", nbits_from_pk (pk2), pk2->pubkey_algo, (ulong) keyid2[0], (ulong) keyid2[1], colon_datestr_from_pk (pk2), colon_strtime (pk2->expiredate) /* fixme: add LID and ownertrust here */ ); print_capabilities (pk2, NULL); if (secret) { - putchar (':'); /* End of field 13. */ - putchar (':'); /* End of field 14. */ + es_putc (':', es_stdout); /* End of field 13. */ + es_putc (':', es_stdout); /* End of field 14. */ if (/*FIXME:sk2->protect.s2k.mode*/1 == 1001) - putchar ('#'); /* Key is just a stub. */ + es_putc ('#', es_stdout); /* Key is just a stub. */ else if (/*FIXME: sk2->protect.s2k.mode*/1 == 1002) { /* Key is stored on an external token (card) or handled by the gpg-agent. Print the serial number of that token here. */ /* FIXME: for (i = 0; i < sk2->protect.ivlen; i++) - printf ("%02X", sk2->protect.iv[i]); */ + es_fprintf (es_stdout, "%02X", sk2->protect.iv[i]); */ } - putchar (':'); /* End of field 15. */ + es_putc (':', es_stdout); /* End of field 15. */ } - putchar ('\n'); + es_putc ('\n', es_stdout); if (fpr > 1) print_fingerprint (pk2, NULL, 0); if (opt.with_key_data) print_key_data (pk2); } else if (opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = node->pkt->pkt.signature; int sigrc, fprokay = 0; char *sigstr; size_t fplen; byte fparray[MAX_FINGERPRINT_LEN]; if (sig->sig_class == 0x20 || sig->sig_class == 0x28 || sig->sig_class == 0x30) sigstr = "rev"; else if ((sig->sig_class & ~3) == 0x10) sigstr = "sig"; else if (sig->sig_class == 0x18) sigstr = "sig"; else if (sig->sig_class == 0x1F) sigstr = "sig"; else { - printf ("sig::::::::::%02x%c:\n", + es_fprintf (es_stdout, "sig::::::::::%02x%c:\n", sig->sig_class, sig->flags.exportable ? 'x' : 'l'); continue; } if (opt.check_sigs) { PKT_public_key *signer_pk = NULL; fflush (stdout); if (opt.no_sig_cache) signer_pk = xmalloc_clear (sizeof (PKT_public_key)); rc = check_key_signature2 (keyblock, node, NULL, signer_pk, NULL, NULL, NULL); switch (gpg_err_code (rc)) { case 0: sigrc = '!'; break; case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break; case GPG_ERR_NO_PUBKEY: case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break; default: sigrc = '%'; break; } if (opt.no_sig_cache) { if (!rc) { fingerprint_from_pk (signer_pk, fparray, &fplen); fprokay = 1; } free_public_key (signer_pk); } } else { rc = 0; sigrc = ' '; } - fputs (sigstr, stdout); - putchar (':'); + es_fputs (sigstr, es_stdout); + es_putc (':', es_stdout); if (sigrc != ' ') - putchar (sigrc); - printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo, + es_putc (sigrc, es_stdout); + es_fprintf (es_stdout, "::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo, (ulong) sig->keyid[0], (ulong) sig->keyid[1], colon_datestr_from_sig (sig), colon_expirestr_from_sig (sig)); if (sig->trust_depth || sig->trust_value) - printf ("%d %d", sig->trust_depth, sig->trust_value); - printf (":"); + es_fprintf (es_stdout, "%d %d", sig->trust_depth, sig->trust_value); + es_fprintf (es_stdout, ":"); if (sig->trust_regexp) - print_string (stdout, sig->trust_regexp, - strlen (sig->trust_regexp), ':'); - printf (":"); + es_write_sanitized (es_stdout, sig->trust_regexp, + strlen (sig->trust_regexp), ":", NULL); + es_fprintf (es_stdout, ":"); if (sigrc == '%') - printf ("[%s] ", g10_errstr (rc)); + es_fprintf (es_stdout, "[%s] ", g10_errstr (rc)); else if (sigrc == '?') ; else if (!opt.fast_list_mode) { size_t n; char *p = get_user_id (sig->keyid, &n); - print_string (stdout, p, n, ':'); + es_write_sanitized (es_stdout, p, n, ":", NULL); xfree (p); } - printf (":%02x%c:", sig->sig_class, + es_fprintf (es_stdout, ":%02x%c:", sig->sig_class, sig->flags.exportable ? 'x' : 'l'); if (opt.no_sig_cache && opt.check_sigs && fprokay) { - putchar (':'); + es_putc (':', es_stdout); for (i = 0; i < fplen; i++) - printf ("%02X", fparray[i]); + es_fprintf (es_stdout, "%02X", fparray[i]); - putchar (':'); + es_putc (':', es_stdout); } - printf ("\n"); + es_fprintf (es_stdout, "\n"); if (opt.show_subpackets) print_subpackets_colon (sig); /* fixme: check or list other sigs here */ } } } /* * Reorder the keyblock so that the primary user ID (and not attribute * packet) comes first. Fixme: Replace this by a generic sort * function. */ static void do_reorder_keyblock (KBNODE keyblock, int attr) { KBNODE primary = NULL, primary0 = NULL, primary2 = NULL; KBNODE last, node; for (node = keyblock; node; primary0 = node, node = node->next) { if (node->pkt->pkttype == PKT_USER_ID && ((attr && node->pkt->pkt.user_id->attrib_data) || (!attr && !node->pkt->pkt.user_id->attrib_data)) && node->pkt->pkt.user_id->is_primary) { primary = primary2 = node; for (node = node->next; node; primary2 = node, node = node->next) { if (node->pkt->pkttype == PKT_USER_ID || node->pkt->pkttype == PKT_PUBLIC_SUBKEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { break; } } break; } } if (!primary) return; /* No primary key flag found (should not happen). */ for (last = NULL, node = keyblock; node; last = node, node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) break; } assert (node); assert (last); /* The user ID is never the first packet. */ assert (primary0); /* Ditto (this is the node before primary). */ if (node == primary) return; /* Already the first one. */ last->next = primary; primary0->next = primary2->next; primary2->next = node; } void reorder_keyblock (KBNODE keyblock) { do_reorder_keyblock (keyblock, 1); do_reorder_keyblock (keyblock, 0); } void list_keyblock (KBNODE keyblock, int secret, int fpr, void *opaque) { reorder_keyblock (keyblock); if (opt.with_colons) list_keyblock_colon (keyblock, secret, fpr); else list_keyblock_print (keyblock, secret, fpr, opaque); } /* * standard function to print the finperprint. * mode 0: as used in key listings, opt.with_colons is honored * 1: print using log_info () * 2: direct use of tty * 3: direct use of tty but only primary key. * modes 1 and 2 will try and print both subkey and primary key fingerprints */ void print_fingerprint (PKT_public_key * pk, PKT_secret_key * sk, int mode) { byte array[MAX_FINGERPRINT_LEN], *p; size_t i, n; - FILE *fp; + estream_t fp; const char *text; int primary = 0; if (sk) { if (sk->main_keyid[0] == sk->keyid[0] && sk->main_keyid[1] == sk->keyid[1]) primary = 1; } else { if (pk->main_keyid[0] == pk->keyid[0] && pk->main_keyid[1] == pk->keyid[1]) primary = 1; } /* Just to be safe */ if (mode & 0x80 && !primary) { log_error ("primary key is not really primary!\n"); return; } mode &= ~0x80; if (!primary && (mode == 1 || mode == 2)) { if (sk) { PKT_secret_key *primary_sk = xmalloc_clear (sizeof (*primary_sk)); get_seckey (primary_sk, sk->main_keyid); print_fingerprint (NULL, primary_sk, mode | 0x80); free_secret_key (primary_sk); } else { PKT_public_key *primary_pk = xmalloc_clear (sizeof (*primary_pk)); get_pubkey (primary_pk, pk->main_keyid); print_fingerprint (primary_pk, NULL, mode | 0x80); free_public_key (primary_pk); } } if (mode == 1) { fp = log_get_stream (); if (primary) text = _("Primary key fingerprint:"); else text = _(" Subkey fingerprint:"); } else if (mode == 2) { fp = NULL; /* Use tty. */ if (primary) /* TRANSLATORS: this should fit into 24 bytes to that the * fingerprint data is properly aligned with the user ID */ text = _(" Primary key fingerprint:"); else text = _(" Subkey fingerprint:"); } else if (mode == 3) { fp = NULL; /* Use tty. */ text = _(" Key fingerprint ="); } else { - fp = stdout; + fp = es_stdout; text = _(" Key fingerprint ="); } if (sk) fingerprint_from_sk (sk, array, &n); else fingerprint_from_pk (pk, array, &n); p = array; if (opt.with_colons && !mode) { - fprintf (fp, "fpr:::::::::"); + es_fprintf (fp, "fpr:::::::::"); for (i = 0; i < n; i++, p++) - fprintf (fp, "%02X", *p); - putc (':', fp); + es_fprintf (fp, "%02X", *p); + es_putc (':', fp); } else { - if (fp) - fputs (text, fp); - else - tty_printf ("%s", text); + tty_fprintf (fp, "%s", text); if (n == 20) { for (i = 0; i < n; i++, i++, p += 2) - { - if (fp) - { - if (i == 10) - putc (' ', fp); - fprintf (fp, " %02X%02X", *p, p[1]); - } - else - { - if (i == 10) - tty_printf (" "); - tty_printf (" %02X%02X", *p, p[1]); - } - } + tty_fprintf (fp, "%s %02X%02X", i==10? " ":"", *p, p[1]); } else { for (i = 0; i < n; i++, p++) - { - if (fp) - { - if (i && !(i % 8)) - putc (' ', fp); - fprintf (fp, " %02X", *p); - } - else - { - if (i && !(i % 8)) - tty_printf (" "); - tty_printf (" %02X", *p); - } - } + tty_fprintf (fp, "%s %02X", (i && !(i % 8))? " ":"", *p); } } - if (fp) - putc ('\n', fp); - else - tty_printf ("\n"); + tty_fprintf (fp, "\n"); } /* Print the serial number of an OpenPGP card if available. */ static void print_card_serialno (PKT_secret_key * sk) { int i; if (!sk) return; if (!sk->is_protected || sk->protect.s2k.mode != 1002) return; /* Not a card. */ if (opt.with_colons) return; /* Handled elsewhere. */ - fputs (_(" Card serial no. ="), stdout); - putchar (' '); + es_fputs (_(" Card serial no. ="), es_stdout); + es_putc (' ', es_stdout); if (sk->protect.ivlen == 16 && !memcmp (sk->protect.iv, "\xD2\x76\x00\x01\x24\x01", 6)) { /* This is an OpenPGP card. Just print the relevant part. */ for (i = 8; i < 14; i++) { if (i == 10) - putchar (' '); - printf ("%02X", sk->protect.iv[i]); + es_putc (' ', es_stdout); + es_fprintf (es_stdout, "%02X", sk->protect.iv[i]); } } else { /* Something is wrong: Print all. */ for (i = 0; i < sk->protect.ivlen; i++) - printf ("%02X", sk->protect.iv[i]); + es_fprintf (es_stdout, "%02X", sk->protect.iv[i]); } - putchar ('\n'); + es_putc ('\n', es_stdout); } void set_attrib_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; - if (attrib_fp && attrib_fp != stdout && attrib_fp != stderr - && attrib_fp != log_get_stream ()) - fclose (attrib_fp); + /* Fixme: Do we need to check for the log stream here? */ + if (attrib_fp && attrib_fp != log_get_stream ()) + es_fclose (attrib_fp); attrib_fp = NULL; if (fd == -1) return; #ifdef HAVE_DOSISH_SYSTEM setmode (fd, O_BINARY); #endif if (fd == 1) - attrib_fp = stdout; + attrib_fp = es_stdout; else if (fd == 2) - attrib_fp = stderr; + attrib_fp = es_stderr; else - attrib_fp = fdopen (fd, "wb"); + attrib_fp = es_fdopen (fd, "wb"); if (!attrib_fp) { log_fatal ("can't open fd %d for attribute output: %s\n", fd, strerror (errno)); } last_fd = fd; } diff --git a/g10/main.h b/g10/main.h index ec09124bd..8ce422f2c 100644 --- a/g10/main.h +++ b/g10/main.h @@ -1,352 +1,352 @@ /* main.h * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef G10_MAIN_H #define G10_MAIN_H #include "types.h" #include "iobuf.h" #include "cipher.h" #include "keydb.h" #include "util.h" /* It could be argued that the default cipher should be 3DES rather than CAST5, and the default compression should be 0 (i.e. uncompressed) rather than 1 (zip). However, the real world issues of speed and size come into play here. */ #define DEFAULT_CIPHER_ALGO CIPHER_ALGO_CAST5 #define DEFAULT_DIGEST_ALGO DIGEST_ALGO_SHA1 #define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_ZIP #define DEFAULT_S2K_DIGEST_ALGO DIGEST_ALGO_SHA1 #define S2K_DIGEST_ALGO (opt.s2k_digest_algo?opt.s2k_digest_algo:DEFAULT_S2K_DIGEST_ALGO) typedef struct { int header_okay; PK_LIST pk_list; DEK *symkey_dek; STRING2KEY *symkey_s2k; cipher_filter_context_t cfx; } encrypt_filter_context_t; struct groupitem { char *name; strlist_t values; struct groupitem *next; }; /*-- gpg.c --*/ extern int g10_errors_seen; #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) void g10_exit(int rc) __attribute__ ((noreturn)); #else void g10_exit(int rc); #endif void print_pubkey_algo_note( int algo ); void print_cipher_algo_note( int algo ); void print_digest_algo_note( int algo ); /*-- armor.c --*/ char *make_radix64_string( const byte *data, size_t len ); /*-- misc.c --*/ void trap_unaligned(void); int disable_core_dumps(void); void register_secured_file (const char *fname); void unregister_secured_file (const char *fname); int is_secured_file (int fd); int is_secured_filename (const char *fname); u16 checksum_u16( unsigned n ); u16 checksum( byte *p, unsigned n ); u16 checksum_mpi( gcry_mpi_t a ); u32 buffer_to_u32( const byte *buffer ); const byte *get_session_marker( size_t *rlen ); int map_cipher_openpgp_to_gcry (int algo); #define openpgp_cipher_open(_a,_b,_c,_d) gcry_cipher_open((_a),map_cipher_openpgp_to_gcry((_b)),(_c),(_d)) #define openpgp_cipher_get_algo_keylen(_a) gcry_cipher_get_algo_keylen(map_cipher_openpgp_to_gcry((_a))) #define openpgp_cipher_get_algo_blklen(_a) gcry_cipher_get_algo_blklen(map_cipher_openpgp_to_gcry((_a))) int openpgp_cipher_blocklen (int algo); int openpgp_cipher_test_algo( int algo ); const char *openpgp_cipher_algo_name (int algo); int openpgp_pk_test_algo( int algo ); int openpgp_pk_test_algo2 ( int algo, unsigned int use ); int openpgp_pk_algo_usage ( int algo ); int openpgp_md_test_algo( int algo ); #ifdef USE_IDEA void idea_cipher_warn( int show ); #else #define idea_cipher_warn(a) do { } while (0) #endif struct expando_args { PKT_public_key *pk; PKT_public_key *pksk; byte imagetype; int validity_info; const char *validity_string; }; char *pct_expando(const char *string,struct expando_args *args); void deprecated_warning(const char *configname,unsigned int configlineno, const char *option,const char *repl1,const char *repl2); void deprecated_command (const char *name); void obsolete_option (const char *configname, unsigned int configlineno, const char *name); int string_to_cipher_algo (const char *string); int string_to_digest_algo (const char *string); const char *compress_algo_to_string(int algo); int string_to_compress_algo(const char *string); int check_compress_algo(int algo); int default_cipher_algo(void); int default_compress_algo(void); const char *compliance_option_string(void); void compliance_failure(void); struct parse_options { char *name; unsigned int bit; char **value; char *help; }; char *optsep(char **stringp); char *argsplit(char *string); int parse_options(char *str,unsigned int *options, struct parse_options *opts,int noisy); int has_invalid_email_chars (const char *s); int is_valid_mailbox (const char *name); const char *get_libexecdir (void); int path_access(const char *file,int mode); /* Temporary helpers. */ int pubkey_get_npkey( int algo ); int pubkey_get_nskey( int algo ); int pubkey_get_nsig( int algo ); int pubkey_get_nenc( int algo ); unsigned int pubkey_nbits( int algo, gcry_mpi_t *pkey ); -int mpi_print( FILE *fp, gcry_mpi_t a, int mode ); +int mpi_print (estream_t stream, gcry_mpi_t a, int mode); /*-- status.c --*/ void set_status_fd ( int fd ); int is_status_enabled ( void ); void write_status ( int no ); void write_status_error (const char *where, gpg_error_t err); void write_status_errcode (const char *where, int errcode); void write_status_text ( int no, const char *text ); void write_status_buffer ( int no, const char *buffer, size_t len, int wrap ); void write_status_text_and_buffer ( int no, const char *text, const char *buffer, size_t len, int wrap ); void write_status_begin_signing (gcry_md_hd_t md); int cpr_enabled(void); char *cpr_get( const char *keyword, const char *prompt ); char *cpr_get_no_help( const char *keyword, const char *prompt ); char *cpr_get_utf8( const char *keyword, const char *prompt ); char *cpr_get_hidden( const char *keyword, const char *prompt ); void cpr_kill_prompt(void); int cpr_get_answer_is_yes( const char *keyword, const char *prompt ); int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt ); int cpr_get_answer_okay_cancel (const char *keyword, const char *prompt, int def_answer); /*-- helptext.c --*/ void display_online_help( const char *keyword ); /*-- encode.c --*/ int setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek); int encrypt_symmetric (const char *filename ); int encrypt_store (const char *filename ); int encrypt_crypt (int filefd, const char *filename, strlist_t remusr, int use_symkey, pk_list_t provided_keys, int outputfd); void encrypt_crypt_files (int nfiles, char **files, strlist_t remusr); int encrypt_filter (void *opaque, int control, iobuf_t a, byte *buf, size_t *ret_len); /*-- sign.c --*/ int complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md); int sign_file( strlist_t filenames, int detached, strlist_t locusr, int do_encrypt, strlist_t remusr, const char *outfile ); int clearsign_file( const char *fname, strlist_t locusr, const char *outfile ); int sign_symencrypt_file (const char *fname, strlist_t locusr); /*-- sig-check.c --*/ int check_revocation_keys (PKT_public_key *pk, PKT_signature *sig); int check_backsig(PKT_public_key *main_pk,PKT_public_key *sub_pk, PKT_signature *backsig); int check_key_signature( KBNODE root, KBNODE node, int *is_selfsig ); int check_key_signature2( KBNODE root, KBNODE node, PKT_public_key *check_pk, PKT_public_key *ret_pk, int *is_selfsig, u32 *r_expiredate, int *r_expired ); /*-- delkey.c --*/ int delete_keys( strlist_t names, int secret, int allow_both ); /*-- keyedit.c --*/ void keyedit_menu( const char *username, strlist_t locusr, strlist_t commands, int quiet, int seckey_check ); void keyedit_passwd (const char *username); void show_basic_key_info (KBNODE keyblock); /*-- keygen.c --*/ u32 parse_expire_string(const char *string); u32 ask_expire_interval(int object,const char *def_expire); u32 ask_expiredate(void); void generate_keypair( const char *fname, const char *card_serialno, const char *backup_encryption_dir ); int keygen_set_std_prefs (const char *string,int personal); PKT_user_id *keygen_get_std_prefs (void); int keygen_add_key_expire( PKT_signature *sig, void *opaque ); int keygen_add_std_prefs( PKT_signature *sig, void *opaque ); int keygen_upd_std_prefs( PKT_signature *sig, void *opaque ); int keygen_add_keyserver_url(PKT_signature *sig, void *opaque); int keygen_add_notations(PKT_signature *sig,void *opaque); int keygen_add_revkey(PKT_signature *sig, void *opaque); int make_backsig(PKT_signature *sig,PKT_public_key *pk, PKT_public_key *sub_pk,PKT_secret_key *sub_sk, u32 timestamp); int generate_subkeypair( KBNODE pub_keyblock, KBNODE sec_keyblock ); #ifdef ENABLE_CARD_SUPPORT int generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock, int keyno, const char *serialno); int save_unprotected_key_to_card (PKT_secret_key *sk, int keyno); #endif /*-- openfile.c --*/ int overwrite_filep( const char *fname ); char *make_outfile_name( const char *iname ); char *ask_outfile_name( const char *name, size_t namelen ); int open_outfile (int inp_fd, const char *iname, int mode, iobuf_t *a); iobuf_t open_sigfile( const char *iname, progress_filter_context_t *pfx ); void try_make_homedir( const char *fname ); /*-- seskey.c --*/ void make_session_key( DEK *dek ); gcry_mpi_t encode_session_key( DEK *dek, unsigned nbits ); gcry_mpi_t encode_md_value( PKT_public_key *pk, PKT_secret_key *sk, gcry_md_hd_t md, int hash_algo ); /*-- import.c --*/ int parse_import_options(char *str,unsigned int *options,int noisy); void import_keys( char **fnames, int nnames, void *stats_hd, unsigned int options ); int import_keys_stream( iobuf_t inp,void *stats_hd,unsigned char **fpr, size_t *fpr_len,unsigned int options ); void *import_new_stats_handle (void); void import_release_stats_handle (void *p); void import_print_stats (void *hd); int collapse_uids( KBNODE *keyblock ); int auto_create_card_key_stub ( const char *serialnostr, const unsigned char *fpr1, const unsigned char *fpr2, const unsigned char *fpr3); /*-- export.c --*/ int parse_export_options(char *str,unsigned int *options,int noisy); int export_pubkeys( strlist_t users, unsigned int options ); int export_pubkeys_stream( iobuf_t out, strlist_t users, KBNODE *keyblock_out, unsigned int options ); int export_seckeys( strlist_t users ); int export_secsubkeys( strlist_t users ); /* dearmor.c --*/ int dearmor_file( const char *fname ); int enarmor_file( const char *fname ); /*-- revoke.c --*/ struct revocation_reason_info; int gen_revoke( const char *uname ); int gen_desig_revoke( const char *uname, strlist_t locusr); int revocation_reason_build_cb( PKT_signature *sig, void *opaque ); struct revocation_reason_info * ask_revocation_reason( int key_rev, int cert_rev, int hint ); void release_revocation_reason_info( struct revocation_reason_info *reason ); /*-- keylist.c --*/ void public_key_list( strlist_t list, int locate_mode ); void secret_key_list( strlist_t list ); void print_subpackets_colon(PKT_signature *sig); void reorder_keyblock (KBNODE keyblock); void list_keyblock( KBNODE keyblock, int secret, int fpr, void *opaque ); void print_fingerprint (PKT_public_key *pk, PKT_secret_key *sk, int mode); void print_revokers(PKT_public_key *pk); void show_policy_url(PKT_signature *sig,int indent,int mode); void show_keyserver_url(PKT_signature *sig,int indent,int mode); void show_notation(PKT_signature *sig,int indent,int mode,int which); void dump_attribs (const PKT_user_id *uid, PKT_public_key *pk); void set_attrib_fd(int fd); void print_seckey_info (PKT_public_key *pk); -void print_pubkey_info (FILE *fp, PKT_public_key *pk); -void print_card_key_info (FILE *fp, KBNODE keyblock); +void print_pubkey_info (estream_t fp, PKT_public_key *pk); +void print_card_key_info (estream_t fp, KBNODE keyblock); /*-- verify.c --*/ void print_file_status( int status, const char *name, int what ); int verify_signatures( int nfiles, char **files ); int verify_files( int nfiles, char **files ); int gpg_verify (ctrl_t ctrl, int sig_fd, int data_fd, estream_t out_fp); /*-- decrypt.c --*/ int decrypt_message( const char *filename ); gpg_error_t decrypt_message_fd (int input_fd, int output_fd); void decrypt_messages(int nfiles, char *files[]); /*-- plaintext.c --*/ int hash_datafiles( gcry_md_hd_t md, gcry_md_hd_t md2, strlist_t files, const char *sigfilename, int textmode ); int hash_datafile_by_fd ( gcry_md_hd_t md, gcry_md_hd_t md2, int data_fd, int textmode ); PKT_plaintext *setup_plaintext_name(const char *filename,IOBUF iobuf); /*-- signal.c --*/ void init_signals(void); void pause_on_sigusr( int which ); void block_all_signals(void); void unblock_all_signals(void); /*-- server.c --*/ int gpg_server (ctrl_t); #ifdef ENABLE_CARD_SUPPORT /*-- card-util.c --*/ void change_pin (int no, int allow_admin); -void card_status (FILE *fp, char *serialno, size_t serialnobuflen); +void card_status (estream_t fp, char *serialno, size_t serialnobuflen); void card_edit (strlist_t commands); int card_generate_subkey (KBNODE pub_keyblock, KBNODE sec_keyblock); int card_store_subkey (KBNODE node, int use); #endif #define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6)) #endif /*G10_MAIN_H*/ diff --git a/g10/mainproc.c b/g10/mainproc.c index 5d568474b..a61325aba 100644 --- a/g10/mainproc.c +++ b/g10/mainproc.c @@ -1,2196 +1,2197 @@ /* mainproc.c - handle packets * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "packet.h" #include "iobuf.h" #include "options.h" #include "util.h" #include "cipher.h" #include "keydb.h" #include "filter.h" #include "main.h" #include "status.h" #include "i18n.h" #include "trustdb.h" #include "keyserver-internal.h" #include "photoid.h" #include "pka.h" struct kidlist_item { struct kidlist_item *next; u32 kid[2]; int pubkey_algo; int reason; }; /**************** * Structure to hold the context */ typedef struct mainproc_context *CTX; struct mainproc_context { struct mainproc_context *anchor; /* May be useful in the future. */ PKT_public_key *last_pubkey; PKT_secret_key *last_seckey; PKT_user_id *last_user_id; md_filter_context_t mfx; int sigs_only; /* Process only signatures and reject all other stuff. */ int encrypt_only; /* Process only encryption messages. */ /* Name of the file with the complete signature or the file with the detached signature. This is currently only used to deduce the file name of the data file if that has not been given. */ const char *sigfilename; /* A structure to describe the signed data in case of a detached signature. */ struct { /* A file descriptor of the the signed data. Only used if not -1. */ int data_fd; /* A list of filenames with the data files or NULL. This is only used if DATA_FD is -1. */ strlist_t data_names; /* Flag to indicated that either one of the next previous fields is used. This is only needed for better readability. */ int used; } signed_data; DEK *dek; int last_was_session_key; KBNODE list; /* The current list of packets. */ int have_data; IOBUF iobuf; /* Used to get the filename etc. */ int trustletter; /* Temporary usage in list_node. */ ulong symkeys; struct kidlist_item *pkenc_list; /* List of encryption packets. */ int any_sig_seen; /* Set to true if a signature packet has been seen. */ }; static int do_proc_packets( CTX c, IOBUF a ); static void list_node( CTX c, KBNODE node ); static void proc_tree( CTX c, KBNODE node ); static int literals_seen; void reset_literals_seen(void) { literals_seen=0; } static void release_list( CTX c ) { if( !c->list ) return; proc_tree(c, c->list ); release_kbnode( c->list ); while( c->pkenc_list ) { struct kidlist_item *tmp = c->pkenc_list->next; xfree( c->pkenc_list ); c->pkenc_list = tmp; } c->pkenc_list = NULL; c->list = NULL; c->have_data = 0; c->last_was_session_key = 0; xfree(c->dek); c->dek = NULL; } static int add_onepass_sig( CTX c, PACKET *pkt ) { KBNODE node; if ( c->list ) /* add another packet */ add_kbnode( c->list, new_kbnode( pkt )); else /* insert the first one */ c->list = node = new_kbnode( pkt ); return 1; } static int add_gpg_control( CTX c, PACKET *pkt ) { if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* New clear text signature. * Process the last one and reset everything */ release_list(c); } if( c->list ) /* add another packet */ add_kbnode( c->list, new_kbnode( pkt )); else /* insert the first one */ c->list = new_kbnode( pkt ); return 1; } static int add_user_id( CTX c, PACKET *pkt ) { if( !c->list ) { log_error("orphaned user ID\n" ); return 0; } add_kbnode( c->list, new_kbnode( pkt ) ); return 1; } static int add_subkey( CTX c, PACKET *pkt ) { if( !c->list ) { log_error("subkey w/o mainkey\n" ); return 0; } add_kbnode( c->list, new_kbnode( pkt ) ); return 1; } static int add_ring_trust( CTX c, PACKET *pkt ) { if( !c->list ) { log_error("ring trust w/o key\n" ); return 0; } add_kbnode( c->list, new_kbnode( pkt ) ); return 1; } static int add_signature( CTX c, PACKET *pkt ) { KBNODE node; c->any_sig_seen = 1; if( pkt->pkttype == PKT_SIGNATURE && !c->list ) { /* This is the first signature for the following datafile. * GPG does not write such packets; instead it always uses * onepass-sig packets. The drawback of PGP's method * of prepending the signature to the data is * that it is not possible to make a signature from data read * from stdin. (GPG is able to read PGP stuff anyway.) */ node = new_kbnode( pkt ); c->list = node; return 1; } else if( !c->list ) return 0; /* oops (invalid packet sequence)*/ else if( !c->list->pkt ) BUG(); /* so nicht */ /* add a new signature node id at the end */ node = new_kbnode( pkt ); add_kbnode( c->list, node ); return 1; } static int symkey_decrypt_seskey( DEK *dek, byte *seskey, size_t slen ) { gcry_cipher_hd_t hd; if(slen < 17 || slen > 33) { log_error ( _("weird size for an encrypted session key (%d)\n"), (int)slen); return G10ERR_BAD_KEY; } if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1)) BUG (); if (gcry_cipher_setkey ( hd, dek->key, dek->keylen )) BUG (); gcry_cipher_setiv ( hd, NULL, 0 ); gcry_cipher_decrypt ( hd, seskey, slen, NULL, 0 ); gcry_cipher_close ( hd ); /* Now we replace the dek components with the real session key to decrypt the contents of the sequencing packet. */ dek->keylen=slen-1; dek->algo=seskey[0]; if(dek->keylen > DIM(dek->key)) BUG (); /* This is not completely accurate, since a bad passphrase may have resulted in a garbage algorithm byte, but it's close enough since a bogus byte here will fail later. */ if(dek->algo==CIPHER_ALGO_IDEA) idea_cipher_warn(0); memcpy(dek->key, seskey + 1, dek->keylen); /*log_hexdump( "thekey", dek->key, dek->keylen );*/ return 0; } static void proc_symkey_enc( CTX c, PACKET *pkt ) { PKT_symkey_enc *enc; enc = pkt->pkt.symkey_enc; if (!enc) log_error ("invalid symkey encrypted packet\n"); else if(!c->dek) { int algo = enc->cipher_algo; const char *s = openpgp_cipher_algo_name (algo); if (!openpgp_cipher_test_algo (algo)) { if(!opt.quiet) { if(enc->seskeylen) log_info(_("%s encrypted session key\n"), s ); else log_info(_("%s encrypted data\n"), s ); } } else log_error(_("encrypted with unknown algorithm %d\n"), algo ); if(openpgp_md_test_algo (enc->s2k.hash_algo)) { log_error(_("passphrase generated with unknown digest" " algorithm %d\n"),enc->s2k.hash_algo); s=NULL; } c->last_was_session_key = 2; if(!s || opt.list_only) goto leave; if(opt.override_session_key) { c->dek = xmalloc_clear( sizeof *c->dek ); if(get_override_session_key(c->dek, opt.override_session_key)) { xfree(c->dek); c->dek = NULL; } } else { c->dek = passphrase_to_dek (NULL, 0, algo, &enc->s2k, 3, NULL, NULL); if(c->dek) { c->dek->symmetric=1; /* FIXME: This doesn't work perfectly if a symmetric key comes before a public key in the message - if the user doesn't know the passphrase, then there is a chance that the "decrypted" algorithm will happen to be a valid one, which will make the returned dek appear valid, so we won't try any public keys that come later. */ if(enc->seskeylen) { if(symkey_decrypt_seskey(c->dek, enc->seskey, enc->seskeylen)) { xfree(c->dek); c->dek=NULL; } } else c->dek->algo_info_printed = 1; } } } leave: c->symkeys++; free_packet(pkt); } static void proc_pubkey_enc( CTX c, PACKET *pkt ) { PKT_pubkey_enc *enc; int result = 0; /* check whether the secret key is available and store in this case */ c->last_was_session_key = 1; enc = pkt->pkt.pubkey_enc; /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/ /* Hmmm: why do I have this algo check here - anyway there is * function to check it. */ if( opt.verbose ) log_info(_("public key is %s\n"), keystr(enc->keyid) ); if( is_status_enabled() ) { char buf[50]; /* FIXME: For ECC support we need to map the OpenPGP algo number to the Libgcrypt definef one. This is due a chicken-egg problem: We need to have code in libgcrypt for a new algorithm so to implement a proposed new algorithm before the IANA will finally assign an OpenPGP indentifier. */ snprintf (buf, sizeof buf, "%08lX%08lX %d 0", (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo ); write_status_text( STATUS_ENC_TO, buf ); } if( !opt.list_only && opt.override_session_key ) { /* It does not make much sense to store the session key in * secure memory because it has already been passed on the * command line and the GCHQ knows about it. */ c->dek = xmalloc_clear( sizeof *c->dek ); result = get_override_session_key ( c->dek, opt.override_session_key ); if ( result ) { xfree(c->dek); c->dek = NULL; } } else if( is_ELGAMAL(enc->pubkey_algo) || enc->pubkey_algo == PUBKEY_ALGO_DSA || is_RSA(enc->pubkey_algo) || enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL) { /* Note that we also allow type 20 Elgamal keys for decryption. There are still a couple of those keys in active use as a subkey. */ /* FIXME: Store this all in a list and process it later so that we can prioritize what key to use. This gives a better user experience if wildcard keyids are used. */ if ( !c->dek && ((!enc->keyid[0] && !enc->keyid[1]) || opt.try_all_secrets || !seckey_available( enc->keyid )) ) { if( opt.list_only ) result = -1; else { c->dek = xmalloc_secure_clear( sizeof *c->dek ); if( (result = get_session_key( enc, c->dek )) ) { /* error: delete the DEK */ xfree(c->dek); c->dek = NULL; } } } else result = G10ERR_NO_SECKEY; } else result = G10ERR_PUBKEY_ALGO; if( result == -1 ) ; else { /* store it for later display */ struct kidlist_item *x = xmalloc( sizeof *x ); x->kid[0] = enc->keyid[0]; x->kid[1] = enc->keyid[1]; x->pubkey_algo = enc->pubkey_algo; x->reason = result; x->next = c->pkenc_list; c->pkenc_list = x; if( !result && opt.verbose > 1 ) log_info( _("public key encrypted data: good DEK\n") ); } free_packet(pkt); } /**************** * Print the list of public key encrypted packets which we could * not decrypt. */ static void print_pkenc_list( struct kidlist_item *list, int failed ) { for( ; list; list = list->next ) { PKT_public_key *pk; const char *algstr; if ( failed && !list->reason ) continue; if ( !failed && list->reason ) continue; algstr = gcry_pk_algo_name ( list->pubkey_algo ); pk = xmalloc_clear( sizeof *pk ); if( !algstr ) algstr = "[?]"; pk->pubkey_algo = list->pubkey_algo; if( !get_pubkey( pk, list->kid ) ) { char *p; log_info( _("encrypted with %u-bit %s key, ID %s, created %s\n"), nbits_from_pk( pk ), algstr, keystr_from_pk(pk), strtimestamp(pk->timestamp) ); p=get_user_id_native(list->kid); log_printf (_(" \"%s\"\n"),p); xfree(p); } else log_info(_("encrypted with %s key, ID %s\n"), algstr,keystr(list->kid)); free_public_key( pk ); if( list->reason == G10ERR_NO_SECKEY ) { if( is_status_enabled() ) { char buf[20]; snprintf (buf, sizeof buf, "%08lX%08lX", (ulong)list->kid[0], (ulong)list->kid[1]); write_status_text( STATUS_NO_SECKEY, buf ); } } else if (list->reason) log_info(_("public key decryption failed: %s\n"), g10_errstr(list->reason)); } } static void proc_encrypted( CTX c, PACKET *pkt ) { int result = 0; if (!opt.quiet) { if(c->symkeys>1) log_info(_("encrypted with %lu passphrases\n"),c->symkeys); else if(c->symkeys==1) log_info(_("encrypted with 1 passphrase\n")); print_pkenc_list ( c->pkenc_list, 1 ); print_pkenc_list ( c->pkenc_list, 0 ); } /* FIXME: Figure out the session key by looking at all pkenc packets. */ write_status( STATUS_BEGIN_DECRYPTION ); /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/ if( opt.list_only ) result = -1; else if( !c->dek && !c->last_was_session_key ) { int algo; STRING2KEY s2kbuf, *s2k = NULL; if(opt.override_session_key) { c->dek = xmalloc_clear( sizeof *c->dek ); result=get_override_session_key(c->dek, opt.override_session_key); if(result) { xfree(c->dek); c->dek = NULL; } } else { /* Assume this is old style conventional encrypted data. */ algo = opt.def_cipher_algo; if ( algo ) log_info (_("assuming %s encrypted data\n"), openpgp_cipher_algo_name (algo)); else if ( openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) ) { algo = opt.def_cipher_algo; if (!algo) algo = opt.s2k_cipher_algo; idea_cipher_warn(1); log_info (_("IDEA cipher unavailable, " "optimistically attempting to use %s instead\n"), openpgp_cipher_algo_name (algo)); } else { algo = CIPHER_ALGO_IDEA; if (!opt.s2k_digest_algo) { /* If no digest is given we assume MD5 */ s2kbuf.mode = 0; s2kbuf.hash_algo = DIGEST_ALGO_MD5; s2k = &s2kbuf; } log_info (_("assuming %s encrypted data\n"), "IDEA"); } c->dek = passphrase_to_dek ( NULL, 0, algo, s2k, 3, NULL, NULL ); if (c->dek) c->dek->algo_info_printed = 1; } } else if( !c->dek ) result = G10ERR_NO_SECKEY; if( !result ) result = decrypt_data( c, pkt->pkt.encrypted, c->dek ); if( result == -1 ) ; else if( !result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE && opt.ignore_mdc_error)) { write_status( STATUS_DECRYPTION_OKAY ); if( opt.verbose > 1 ) log_info(_("decryption okay\n")); if( pkt->pkt.encrypted->mdc_method && !result ) write_status( STATUS_GOODMDC ); else if(!opt.no_mdc_warn) log_info (_("WARNING: message was not integrity protected\n")); if(opt.show_session_key) { int i; char *buf = xmalloc ( c->dek->keylen*2 + 20 ); sprintf ( buf, "%d:", c->dek->algo ); for(i=0; i < c->dek->keylen; i++ ) sprintf(buf+strlen(buf), "%02X", c->dek->key[i] ); log_info( "session key: `%s'\n", buf ); write_status_text ( STATUS_SESSION_KEY, buf ); } } else if( result == G10ERR_BAD_SIGN ) { glo_ctrl.lasterr = result; log_error(_("WARNING: encrypted message has been manipulated!\n")); write_status( STATUS_BADMDC ); write_status( STATUS_DECRYPTION_FAILED ); } else { if (gpg_err_code (result) == GPG_ERR_BAD_KEY && *c->dek->s2k_cacheid != '\0') { log_debug(_("cleared passphrase cached with ID: %s\n"), c->dek->s2k_cacheid); passphrase_clear_cache (NULL, c->dek->s2k_cacheid, 0); } glo_ctrl.lasterr = result; write_status( STATUS_DECRYPTION_FAILED ); log_error(_("decryption failed: %s\n"), g10_errstr(result)); /* Hmmm: does this work when we have encrypted using multiple * ways to specify the session key (symmmetric and PK)*/ } xfree(c->dek); c->dek = NULL; free_packet(pkt); c->last_was_session_key = 0; write_status( STATUS_END_DECRYPTION ); } static void proc_plaintext( CTX c, PACKET *pkt ) { PKT_plaintext *pt = pkt->pkt.plaintext; int any, clearsig, only_md5, rc; KBNODE n; literals_seen++; if( pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8 ) ) log_info(_("NOTE: sender requested \"for-your-eyes-only\"\n")); else if( opt.verbose ) log_info(_("original file name='%.*s'\n"), pt->namelen, pt->name); free_md_filter_context( &c->mfx ); if (gcry_md_open (&c->mfx.md, 0, 0)) BUG (); /* fixme: we may need to push the textfilter if we have sigclass 1 * and no armoring - Not yet tested * Hmmm, why don't we need it at all if we have sigclass 1 * Should we assume that plaintext in mode 't' has always sigclass 1?? * See: Russ Allbery's mail 1999-02-09 */ any = clearsig = only_md5 = 0; for(n=c->list; n; n = n->next ) { if( n->pkt->pkttype == PKT_ONEPASS_SIG ) { /* For the onepass signature case */ if( n->pkt->pkt.onepass_sig->digest_algo ) { gcry_md_enable (c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo); if( !any && n->pkt->pkt.onepass_sig->digest_algo == DIGEST_ALGO_MD5 ) only_md5 = 1; else only_md5 = 0; any = 1; } if( n->pkt->pkt.onepass_sig->sig_class != 0x01 ) only_md5 = 0; } else if( n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* For the clearsigned message case */ size_t datalen = n->pkt->pkt.gpg_control->datalen; const byte *data = n->pkt->pkt.gpg_control->data; /* check that we have at least the sigclass and one hash */ if ( datalen < 2 ) log_fatal("invalid control packet CTRLPKT_CLEARSIGN_START\n"); /* Note that we don't set the clearsig flag for not-dash-escaped * documents */ clearsig = (*data == 0x01); for( data++, datalen--; datalen; datalen--, data++ ) gcry_md_enable (c->mfx.md, *data); any = 1; break; /* Stop here as one-pass signature packets are not expected. */ } else if(n->pkt->pkttype==PKT_SIGNATURE) { /* For the SIG+LITERAL case that PGP used to use. */ gcry_md_enable ( c->mfx.md, n->pkt->pkt.signature->digest_algo ); any=1; } } if( !any && !opt.skip_verify ) { /* This is for the old GPG LITERAL+SIG case. It's not legal according to 2440, so hopefully it won't come up that often. There is no good way to specify what algorithms to use in that case, so these three are the historical answer. */ gcry_md_enable( c->mfx.md, DIGEST_ALGO_RMD160 ); gcry_md_enable( c->mfx.md, DIGEST_ALGO_SHA1 ); gcry_md_enable( c->mfx.md, DIGEST_ALGO_MD5 ); } if( opt.pgp2_workarounds && only_md5 && !opt.skip_verify ) { /* This is a kludge to work around a bug in pgp2. It does only * catch those mails which are armored. To catch the non-armored * pgp mails we could see whether there is the signature packet * in front of the plaintext. If someone needs this, send me a patch. */ if ( gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0) ) BUG (); } if ( DBG_HASHING ) { gcry_md_start_debug ( c->mfx.md, "verify" ); if ( c->mfx.md2 ) gcry_md_start_debug ( c->mfx.md2, "verify2" ); } rc=0; if (literals_seen>1) { log_info (_("WARNING: multiple plaintexts seen\n")); if (!opt.flags.allow_multiple_messages) { write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA"); log_inc_errorcount (); rc = gpg_error (GPG_ERR_UNEXPECTED); } } if(!rc) { rc = handle_plaintext( pt, &c->mfx, c->sigs_only, clearsig ); if ( gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only ) { /* Can't write output but we hash it anyway to check the signature. */ rc = handle_plaintext( pt, &c->mfx, 1, clearsig ); } } if( rc ) log_error( "handle plaintext failed: %s\n", g10_errstr(rc)); free_packet(pkt); c->last_was_session_key = 0; /* We add a marker control packet instead of the plaintext packet. * This is so that we can later detect invalid packet sequences. */ n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0)); if (c->list) add_kbnode (c->list, n); else c->list = n; } static int proc_compressed_cb( IOBUF a, void *info ) { if ( ((CTX)info)->signed_data.used && ((CTX)info)->signed_data.data_fd != -1) return proc_signature_packets_by_fd (info, a, ((CTX)info)->signed_data.data_fd); else return proc_signature_packets (info, a, ((CTX)info)->signed_data.data_names, ((CTX)info)->sigfilename ); } static int proc_encrypt_cb( IOBUF a, void *info ) { return proc_encryption_packets( info, a ); } static void proc_compressed( CTX c, PACKET *pkt ) { PKT_compressed *zd = pkt->pkt.compressed; int rc; /*printf("zip: compressed data packet\n");*/ if( !zd->algorithm ) rc=G10ERR_COMPR_ALGO; else if( c->sigs_only ) rc = handle_compressed( c, zd, proc_compressed_cb, c ); else if( c->encrypt_only ) rc = handle_compressed( c, zd, proc_encrypt_cb, c ); else rc = handle_compressed( c, zd, NULL, NULL ); if( rc ) log_error("uncompressing failed: %s\n", g10_errstr(rc)); free_packet(pkt); c->last_was_session_key = 0; } /**************** * check the signature * Returns: 0 = valid signature or an error code */ static int do_check_sig( CTX c, KBNODE node, int *is_selfsig, int *is_expkey, int *is_revkey ) { PKT_signature *sig; gcry_md_hd_t md = NULL, md2 = NULL; int algo, rc; assert( node->pkt->pkttype == PKT_SIGNATURE ); if( is_selfsig ) *is_selfsig = 0; sig = node->pkt->pkt.signature; algo = sig->digest_algo; rc = openpgp_md_test_algo(algo); if (rc) return rc; if( sig->sig_class == 0x00 ) { if( c->mfx.md ) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); } else /* detached signature */ { /* signature_check() will enable the md*/ if (gcry_md_open (&md, 0, 0 )) BUG (); } } else if( sig->sig_class == 0x01 ) { /* how do we know that we have to hash the (already hashed) text * in canonical mode ??? (calculating both modes???) */ if( c->mfx.md ) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); if( c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2 )) BUG (); } else { /* detached signature */ log_debug("Do we really need this here?"); /* signature_check() will enable the md*/ if (gcry_md_open (&md, 0, 0 )) BUG (); if (gcry_md_open (&md2, 0, 0 )) BUG (); } } else if( (sig->sig_class&~3) == 0x10 || sig->sig_class == 0x18 || sig->sig_class == 0x1f || sig->sig_class == 0x20 || sig->sig_class == 0x28 || sig->sig_class == 0x30 ) { if( c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { return check_key_signature( c->list, node, is_selfsig ); } else if( sig->sig_class == 0x20 ) { log_error (_("standalone revocation - " "use \"gpg --import\" to apply\n")); return G10ERR_NOT_PROCESSED; } else { log_error("invalid root packet for sigclass %02x\n", sig->sig_class); return G10ERR_SIG_CLASS; } } else return G10ERR_SIG_CLASS; rc = signature_check2( sig, md, NULL, is_expkey, is_revkey, NULL ); if( gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2 ) rc = signature_check2( sig, md2, NULL, is_expkey, is_revkey, NULL ); gcry_md_close(md); gcry_md_close(md2); return rc; } static void print_userid( PACKET *pkt ) { if( !pkt ) BUG(); if( pkt->pkttype != PKT_USER_ID ) { printf("ERROR: unexpected packet type %d", pkt->pkttype ); return; } if( opt.with_colons ) { if(pkt->pkt.user_id->attrib_data) printf("%u %lu", pkt->pkt.user_id->numattribs, pkt->pkt.user_id->attrib_len); else - print_string( stdout, pkt->pkt.user_id->name, - pkt->pkt.user_id->len, ':'); + es_write_sanitized (es_stdout, pkt->pkt.user_id->name, + pkt->pkt.user_id->len, ":", NULL); } else - print_utf8_string( stdout, pkt->pkt.user_id->name, - pkt->pkt.user_id->len ); + print_utf8_buffer (es_stdout, pkt->pkt.user_id->name, + pkt->pkt.user_id->len ); } /**************** * List the certificate in a user friendly way */ static void list_node( CTX c, KBNODE node ) { int any=0; int mainkey; if( !node ) ; else if( (mainkey = (node->pkt->pkttype == PKT_PUBLIC_KEY) ) || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { PKT_public_key *pk = node->pkt->pkt.public_key; if( opt.with_colons ) { u32 keyid[2]; keyid_from_pk( pk, keyid ); if( mainkey ) c->trustletter = opt.fast_list_mode? 0 : get_validity_info( pk, NULL ); printf("%s:", mainkey? "pub":"sub" ); if( c->trustletter ) putchar( c->trustletter ); printf(":%u:%d:%08lX%08lX:%s:%s::", nbits_from_pk( pk ), pk->pubkey_algo, (ulong)keyid[0],(ulong)keyid[1], colon_datestr_from_pk( pk ), colon_strtime (pk->expiredate) ); if( mainkey && !opt.fast_list_mode ) putchar( get_ownertrust_info (pk) ); putchar(':'); if( node->next && node->next->pkt->pkttype == PKT_RING_TRUST) { putchar('\n'); any=1; if( opt.fingerprint ) print_fingerprint( pk, NULL, 0 ); printf("rtv:1:%u:\n", node->next->pkt->pkt.ring_trust->trustval ); } } else printf("%s %4u%c/%s %s%s", mainkey? "pub":"sub", nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr_from_pk( pk ), datestr_from_pk( pk ), mainkey?" ":""); if( mainkey ) { /* and now list all userids with their signatures */ for( node = node->next; node; node = node->next ) { if( node->pkt->pkttype == PKT_SIGNATURE ) { if( !any ) { if( node->pkt->pkt.signature->sig_class == 0x20 ) puts("[revoked]"); else putchar('\n'); any = 1; } list_node(c, node ); } else if( node->pkt->pkttype == PKT_USER_ID ) { if( any ) { if( opt.with_colons ) printf("%s:::::::::", node->pkt->pkt.user_id->attrib_data?"uat":"uid"); else printf( "uid%*s", 28, "" ); } print_userid( node->pkt ); if( opt.with_colons ) putchar(':'); putchar('\n'); if( opt.fingerprint && !any ) print_fingerprint( pk, NULL, 0 ); if( opt.with_colons && node->next && node->next->pkt->pkttype == PKT_RING_TRUST ) { printf("rtv:2:%u:\n", node->next->pkt->pkt.ring_trust? node->next->pkt->pkt.ring_trust->trustval : 0); } any=1; } else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { if( !any ) { putchar('\n'); any = 1; } list_node(c, node ); } } } else { /* of subkey */ if( pk->is_revoked ) { printf(" ["); printf(_("revoked: %s"),revokestr_from_pk(pk)); printf("]"); } else if( pk->expiredate ) { printf(" ["); printf(_("expires: %s"),expirestr_from_pk(pk)); printf("]"); } } if( !any ) putchar('\n'); if( !mainkey && opt.fingerprint > 1 ) print_fingerprint( pk, NULL, 0 ); } else if( (mainkey = (node->pkt->pkttype == PKT_SECRET_KEY) ) || node->pkt->pkttype == PKT_SECRET_SUBKEY ) { PKT_secret_key *sk = node->pkt->pkt.secret_key; if( opt.with_colons ) { u32 keyid[2]; keyid_from_sk( sk, keyid ); printf("%s::%u:%d:%08lX%08lX:%s:%s:::", mainkey? "sec":"ssb", nbits_from_sk( sk ), sk->pubkey_algo, (ulong)keyid[0],(ulong)keyid[1], colon_datestr_from_sk( sk ), colon_strtime (sk->expiredate) /* fixme: add LID */ ); } else printf("%s %4u%c/%s %s ", mainkey? "sec":"ssb", nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ), keystr_from_sk( sk ), datestr_from_sk( sk )); if( mainkey ) { /* and now list all userids with their signatures */ for( node = node->next; node; node = node->next ) { if( node->pkt->pkttype == PKT_SIGNATURE ) { if( !any ) { if( node->pkt->pkt.signature->sig_class == 0x20 ) puts("[revoked]"); else putchar('\n'); any = 1; } list_node(c, node ); } else if( node->pkt->pkttype == PKT_USER_ID ) { if( any ) { if( opt.with_colons ) printf("%s:::::::::", node->pkt->pkt.user_id->attrib_data?"uat":"uid"); else printf( "uid%*s", 28, "" ); } print_userid( node->pkt ); if( opt.with_colons ) putchar(':'); putchar('\n'); if( opt.fingerprint && !any ) print_fingerprint( NULL, sk, 0 ); any=1; } else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) { if( !any ) { putchar('\n'); any = 1; } list_node(c, node ); } } } if( !any ) putchar('\n'); if( !mainkey && opt.fingerprint > 1 ) print_fingerprint( NULL, sk, 0 ); } else if( node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; int is_selfsig = 0; int rc2=0; size_t n; char *p; int sigrc = ' '; if( !opt.verbose ) return; if( sig->sig_class == 0x20 || sig->sig_class == 0x30 ) fputs("rev", stdout); else fputs("sig", stdout); if( opt.check_sigs ) { fflush(stdout); rc2=do_check_sig( c, node, &is_selfsig, NULL, NULL ); switch (gpg_err_code (rc2)) { case 0: sigrc = '!'; break; case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break; case GPG_ERR_NO_PUBKEY: case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break; default: sigrc = '%'; break; } } else { /* check whether this is a self signature */ u32 keyid[2]; if( c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_SECRET_KEY ) { if( c->list->pkt->pkttype == PKT_PUBLIC_KEY ) keyid_from_pk( c->list->pkt->pkt.public_key, keyid ); else keyid_from_sk( c->list->pkt->pkt.secret_key, keyid ); if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) is_selfsig = 1; } } if( opt.with_colons ) { putchar(':'); if( sigrc != ' ' ) putchar(sigrc); printf("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo, (ulong)sig->keyid[0], (ulong)sig->keyid[1], colon_datestr_from_sig(sig), colon_expirestr_from_sig(sig)); if(sig->trust_depth || sig->trust_value) printf("%d %d",sig->trust_depth,sig->trust_value); printf(":"); if(sig->trust_regexp) - print_string(stdout,sig->trust_regexp, - strlen(sig->trust_regexp),':'); + es_write_sanitized (es_stdout,sig->trust_regexp, + strlen(sig->trust_regexp), ":", NULL); printf(":"); } else printf("%c %s %s ", sigrc, keystr(sig->keyid), datestr_from_sig(sig)); if( sigrc == '%' ) printf("[%s] ", g10_errstr(rc2) ); else if( sigrc == '?' ) ; else if( is_selfsig ) { if( opt.with_colons ) putchar(':'); fputs( sig->sig_class == 0x18? "[keybind]":"[selfsig]", stdout); if( opt.with_colons ) putchar(':'); } else if( !opt.fast_list_mode ) { p = get_user_id( sig->keyid, &n ); - print_string( stdout, p, n, opt.with_colons ); + es_write_sanitized (es_stdout, p, n, + opt.with_colons?":":NULL, NULL ); xfree(p); } if( opt.with_colons ) printf(":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l'); putchar('\n'); } else log_error("invalid node with packet of type %d\n", node->pkt->pkttype); } int proc_packets( void *anchor, IOBUF a ) { int rc; CTX c = xmalloc_clear( sizeof *c ); c->anchor = anchor; rc = do_proc_packets( c, a ); xfree( c ); return rc; } int proc_signature_packets( void *anchor, IOBUF a, strlist_t signedfiles, const char *sigfilename ) { CTX c = xmalloc_clear( sizeof *c ); int rc; c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = -1; c->signed_data.data_names = signedfiles; c->signed_data.used = !!signedfiles; c->sigfilename = sigfilename; rc = do_proc_packets( c, a ); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any_sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = G10ERR_NO_DATA; } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any_sig_seen) c->anchor->any_sig_seen = 1; xfree( c ); return rc; } int proc_signature_packets_by_fd (void *anchor, IOBUF a, int signed_data_fd ) { int rc; CTX c; c = xtrycalloc (1, sizeof *c); if (!c) return gpg_error_from_syserror (); c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = signed_data_fd; c->signed_data.data_names = NULL; c->signed_data.used = (signed_data_fd != -1); rc = do_proc_packets ( c, a ); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any_sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = gpg_error (GPG_ERR_NO_DATA); } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any_sig_seen) c->anchor->any_sig_seen = 1; xfree ( c ); return rc; } int proc_encryption_packets( void *anchor, IOBUF a ) { CTX c = xmalloc_clear( sizeof *c ); int rc; c->anchor = anchor; c->encrypt_only = 1; rc = do_proc_packets( c, a ); xfree( c ); return rc; } int do_proc_packets( CTX c, IOBUF a ) { PACKET *pkt = xmalloc( sizeof *pkt ); int rc=0; int any_data=0; int newpkt; c->iobuf = a; init_packet(pkt); while( (rc=parse_packet(a, pkt)) != -1 ) { any_data = 1; if( rc ) { free_packet(pkt); /* stop processing when an invalid packet has been encountered * but don't do so when we are doing a --list-packets. */ if (gpg_err_code (rc) == GPG_ERR_INV_PACKET && opt.list_packets != 2 ) break; continue; } newpkt = -1; if( opt.list_packets ) { switch( pkt->pkttype ) { case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break; case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break; case PKT_COMPRESSED: proc_compressed( c, pkt ); break; default: newpkt = 0; break; } } else if( c->sigs_only ) { switch( pkt->pkttype ) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: case PKT_SYMKEY_ENC: case PKT_PUBKEY_ENC: case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: write_status_text( STATUS_UNEXPECTED, "0" ); rc = G10ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break; case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break; case PKT_COMPRESSED: proc_compressed( c, pkt ); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break; default: newpkt = 0; break; } } else if( c->encrypt_only ) { switch( pkt->pkttype ) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: write_status_text( STATUS_UNEXPECTED, "0" ); rc = G10ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break; case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break; case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break; case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break; case PKT_COMPRESSED: proc_compressed( c, pkt ); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break; default: newpkt = 0; break; } } else { switch( pkt->pkttype ) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: release_list( c ); c->list = new_kbnode( pkt ); newpkt = 1; break; case PKT_PUBLIC_SUBKEY: case PKT_SECRET_SUBKEY: newpkt = add_subkey( c, pkt ); break; case PKT_USER_ID: newpkt = add_user_id( c, pkt ); break; case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break; case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break; case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break; case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break; case PKT_COMPRESSED: proc_compressed( c, pkt ); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break; case PKT_RING_TRUST: newpkt = add_ring_trust( c, pkt ); break; default: newpkt = 0; break; } } /* This is a very ugly construct and frankly, I don't remember why * I used it. Adding the MDC check here is a hack. * The right solution is to initiate another context for encrypted * packet and not to reuse the current one ... It works right * when there is a compression packet inbetween which adds just * an extra layer. * Hmmm: Rewrite this whole module here?? */ if( pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC ) c->have_data = pkt->pkttype == PKT_PLAINTEXT; if( newpkt == -1 ) ; else if( newpkt ) { pkt = xmalloc( sizeof *pkt ); init_packet(pkt); } else free_packet(pkt); } if( rc == G10ERR_INVALID_PACKET ) write_status_text( STATUS_NODATA, "3" ); if( any_data ) rc = 0; else if( rc == -1 ) write_status_text( STATUS_NODATA, "2" ); leave: release_list( c ); xfree(c->dek); free_packet( pkt ); xfree( pkt ); free_md_filter_context( &c->mfx ); return rc; } /* Helper for pka_uri_from_sig to parse the to-be-verified address out of the notation data. */ static pka_info_t * get_pka_address (PKT_signature *sig) { pka_info_t *pka = NULL; struct notation *nd,*notation; notation=sig_to_notation(sig); for(nd=notation;nd;nd=nd->next) { if(strcmp(nd->name,"pka-address@gnupg.org")!=0) continue; /* Not the notation we want. */ /* For now we only use the first valid PKA notation. In future we might want to keep additional PKA notations in a linked list. */ if (is_valid_mailbox (nd->value)) { pka = xmalloc (sizeof *pka + strlen(nd->value)); pka->valid = 0; pka->checked = 0; pka->uri = NULL; strcpy (pka->email, nd->value); break; } } free_notation(notation); return pka; } /* Return the URI from a DNS PKA record. If this record has already be retrieved for the signature we merely return it; if not we go out and try to get that DNS record. */ static const char * pka_uri_from_sig (PKT_signature *sig) { if (!sig->flags.pka_tried) { assert (!sig->pka_info); sig->flags.pka_tried = 1; sig->pka_info = get_pka_address (sig); if (sig->pka_info) { char *uri; uri = get_pka_info (sig->pka_info->email, sig->pka_info->fpr); if (uri) { sig->pka_info->valid = 1; if (!*uri) xfree (uri); else sig->pka_info->uri = uri; } } } return sig->pka_info? sig->pka_info->uri : NULL; } static int check_sig_and_print( CTX c, KBNODE node ) { PKT_signature *sig = node->pkt->pkt.signature; const char *astr; int rc, is_expkey=0, is_revkey=0; if (opt.skip_verify) { log_info(_("signature verification suppressed\n")); return 0; } /* Check that the message composition is valid. Per RFC-2440bis (-15) allowed: S{1,n} -- detached signature. S{1,n} P -- old style PGP2 signature O{1,n} P S{1,n} -- standard OpenPGP signature. C P S{1,n} -- cleartext signature. O = One-Pass Signature packet. S = Signature packet. P = OpenPGP Message packet (Encrypted | Compressed | Literal) (Note that the current rfc2440bis draft also allows for a signed message but that does not work as it introduces ambiguities.) We keep track of these packages using the marker packet CTRLPKT_PLAINTEXT_MARK. C = Marker packet for cleartext signatures. We reject all other messages. Actually we are calling this too often, i.e. for verification of each message but better have some duplicate work than to silently introduce a bug here. */ { KBNODE n; int n_onepass, n_sig; /* log_debug ("checking signature packet composition\n"); */ /* dump_kbnode (c->list); */ n = c->list; assert (n); if ( n->pkt->pkttype == PKT_SIGNATURE ) { /* This is either "S{1,n}" case (detached signature) or "S{1,n} P" (old style PGP2 signature). */ for (n = n->next; n; n = n->next) if (n->pkt->pkttype != PKT_SIGNATURE) break; if (!n) ; /* Okay, this is a detached signature. */ else if (n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK) ) { if (n->next) goto ambiguous; /* We only allow one P packet. */ } else goto ambiguous; } else if (n->pkt->pkttype == PKT_ONEPASS_SIG) { /* This is the "O{1,n} P S{1,n}" case (standard signature). */ for (n_onepass=1, n = n->next; n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next) n_onepass++; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (!n_sig) goto ambiguous; /* If we wanted to disallow multiple sig verification, we'd do something like this: if (n && !opt.allow_multisig_verification) goto ambiguous; However, now that we have --allow-multiple-messages, this can stay allowable as we can't get here unless multiple messages (i.e. multiple literals) are allowed. */ if (n_onepass != n_sig) { log_info ("number of one-pass packets does not match " "number of signature packets\n"); goto ambiguous; } } else if (n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* This is the "C P S{1,n}" case (clear text signature). */ n = n->next; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (n || !n_sig) goto ambiguous; } else { ambiguous: log_error(_("can't handle this ambiguous signature data\n")); return 0; } } /* (Indendation below not yet changed to GNU style.) */ astr = gcry_pk_algo_name ( sig->pubkey_algo ); if(keystrlen()>8) { log_info(_("Signature made %s\n"),asctimestamp(sig->timestamp)); log_info(_(" using %s key %s\n"), astr? astr: "?",keystr(sig->keyid)); } else log_info(_("Signature made %s using %s key ID %s\n"), asctimestamp(sig->timestamp), astr? astr: "?", keystr(sig->keyid)); rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey ); /* If the key isn't found, check for a preferred keyserver */ if(rc==G10ERR_NO_PUBKEY && sig->flags.pref_ks) { const byte *p; int seq=0; size_t n; while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL))) { /* According to my favorite copy editor, in English grammar, you say "at" if the key is located on a web page, but "from" if it is located on a keyserver. I'm not going to even try to make two strings here :) */ log_info(_("Key available at: ") ); - print_utf8_string( log_get_stream(), p, n ); + print_utf8_buffer (log_get_stream(), p, n); log_printf ("\n"); if(opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL) { struct keyserver_spec *spec; spec=parse_preferred_keyserver(sig); if(spec) { int res; glo_ctrl.in_auto_key_retrieve++; res=keyserver_import_keyid(sig->keyid,spec); glo_ctrl.in_auto_key_retrieve--; if(!res) rc=do_check_sig(c, node, NULL, &is_expkey, &is_revkey ); free_keyserver_spec(spec); if(!rc) break; } } } } /* If the preferred keyserver thing above didn't work, our second try is to use the URI from a DNS PKA record. */ if ( rc == G10ERR_NO_PUBKEY && opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE && opt.keyserver_options.options&KEYSERVER_HONOR_PKA_RECORD) { const char *uri = pka_uri_from_sig (sig); if (uri) { /* FIXME: We might want to locate the key using the fingerprint instead of the keyid. */ int res; struct keyserver_spec *spec; spec = parse_keyserver_uri (uri, 1, NULL, 0); if (spec) { glo_ctrl.in_auto_key_retrieve++; res = keyserver_import_keyid (sig->keyid, spec); glo_ctrl.in_auto_key_retrieve--; free_keyserver_spec (spec); if (!res) rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey ); } } } /* If the preferred keyserver thing above didn't work and we got no information from the DNS PKA, this is a third try. */ if( rc == G10ERR_NO_PUBKEY && opt.keyserver && opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) { int res; glo_ctrl.in_auto_key_retrieve++; res=keyserver_import_keyid ( sig->keyid, opt.keyserver ); glo_ctrl.in_auto_key_retrieve--; if(!res) rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey ); } if( !rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE ) { KBNODE un, keyblock; int count=0, statno; char keyid_str[50]; PKT_public_key *pk=NULL; if(rc) statno=STATUS_BADSIG; else if(sig->flags.expired) statno=STATUS_EXPSIG; else if(is_expkey) statno=STATUS_EXPKEYSIG; else if(is_revkey) statno=STATUS_REVKEYSIG; else statno=STATUS_GOODSIG; keyblock = get_pubkeyblock( sig->keyid ); sprintf (keyid_str, "%08lX%08lX [uncertain] ", (ulong)sig->keyid[0], (ulong)sig->keyid[1]); /* find and print the primary user ID */ for( un=keyblock; un; un = un->next ) { char *p; int valid; if(un->pkt->pkttype==PKT_PUBLIC_KEY) { pk=un->pkt->pkt.public_key; continue; } if( un->pkt->pkttype != PKT_USER_ID ) continue; if ( !un->pkt->pkt.user_id->created ) continue; if ( un->pkt->pkt.user_id->is_revoked ) continue; if ( un->pkt->pkt.user_id->is_expired ) continue; if ( !un->pkt->pkt.user_id->is_primary ) continue; /* We want the textual primary user ID here */ if ( un->pkt->pkt.user_id->attrib_data ) continue; assert(pk); /* Get it before we print anything to avoid interrupting the output with the "please do a --check-trustdb" line. */ valid=get_validity(pk,un->pkt->pkt.user_id); keyid_str[17] = 0; /* cut off the "[uncertain]" part */ write_status_text_and_buffer (statno, keyid_str, un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len, -1 ); p=utf8_to_native(un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len,0); if(rc) log_info(_("BAD signature from \"%s\""),p); else if(sig->flags.expired) log_info(_("Expired signature from \"%s\""),p); else log_info(_("Good signature from \"%s\""),p); xfree(p); if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY) log_printf (" [%s]\n",trust_value_to_string(valid)); else log_printf ("\n"); count++; } if( !count ) { /* just in case that we have no valid textual userid */ char *p; /* Try for an invalid textual userid */ for( un=keyblock; un; un = un->next ) { if( un->pkt->pkttype == PKT_USER_ID && !un->pkt->pkt.user_id->attrib_data ) break; } /* Try for any userid at all */ if(!un) { for( un=keyblock; un; un = un->next ) { if( un->pkt->pkttype == PKT_USER_ID ) break; } } if (opt.trust_model==TM_ALWAYS || !un) keyid_str[17] = 0; /* cut off the "[uncertain]" part */ write_status_text_and_buffer (statno, keyid_str, un? un->pkt->pkt.user_id->name:"[?]", un? un->pkt->pkt.user_id->len:3, -1 ); if(un) p=utf8_to_native(un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len,0); else p=xstrdup("[?]"); if(rc) log_info(_("BAD signature from \"%s\""),p); else if(sig->flags.expired) log_info(_("Expired signature from \"%s\""),p); else log_info(_("Good signature from \"%s\""),p); if (opt.trust_model!=TM_ALWAYS && un) log_printf (" %s",_("[uncertain]") ); log_printf ("\n"); } /* If we have a good signature and already printed * the primary user ID, print all the other user IDs */ if ( count && !rc && !(opt.verify_options&VERIFY_SHOW_PRIMARY_UID_ONLY)) { char *p; for( un=keyblock; un; un = un->next ) { if( un->pkt->pkttype != PKT_USER_ID ) continue; if((un->pkt->pkt.user_id->is_revoked || un->pkt->pkt.user_id->is_expired) && !(opt.verify_options&VERIFY_SHOW_UNUSABLE_UIDS)) continue; /* Only skip textual primaries */ if ( un->pkt->pkt.user_id->is_primary && !un->pkt->pkt.user_id->attrib_data ) continue; if(un->pkt->pkt.user_id->attrib_data) { dump_attribs (un->pkt->pkt.user_id, pk); if(opt.verify_options&VERIFY_SHOW_PHOTOS) show_photos(un->pkt->pkt.user_id->attribs, un->pkt->pkt.user_id->numattribs, pk,NULL,un->pkt->pkt.user_id); } p=utf8_to_native(un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len,0); log_info(_(" aka \"%s\""),p); xfree(p); if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY) { const char *valid; if(un->pkt->pkt.user_id->is_revoked) valid=_("revoked"); else if(un->pkt->pkt.user_id->is_expired) valid=_("expired"); else valid=trust_value_to_string(get_validity(pk, un->pkt-> pkt.user_id)); log_printf (" [%s]\n",valid); } else log_printf ("\n"); } } release_kbnode( keyblock ); if( !rc ) { if(opt.verify_options&VERIFY_SHOW_POLICY_URLS) show_policy_url(sig,0,1); else show_policy_url(sig,0,2); if(opt.verify_options&VERIFY_SHOW_KEYSERVER_URLS) show_keyserver_url(sig,0,1); else show_keyserver_url(sig,0,2); if(opt.verify_options&VERIFY_SHOW_NOTATIONS) show_notation(sig,0,1, ((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)+ ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)); else show_notation(sig,0,2,0); } if( !rc && is_status_enabled() ) { /* print a status response with the fingerprint */ PKT_public_key *vpk = xmalloc_clear( sizeof *vpk ); if( !get_pubkey( vpk, sig->keyid ) ) { byte array[MAX_FINGERPRINT_LEN], *p; char buf[MAX_FINGERPRINT_LEN*4+90], *bufp; size_t i, n; bufp = buf; fingerprint_from_pk( vpk, array, &n ); p = array; for(i=0; i < n ; i++, p++, bufp += 2) sprintf(bufp, "%02X", *p ); /* TODO: Replace the reserved '0' in the field below with bits for status flags (policy url, notation, etc.). Remember to make the buffer larger to match! */ sprintf(bufp, " %s %lu %lu %d 0 %d %d %02X ", strtimestamp( sig->timestamp ), (ulong)sig->timestamp,(ulong)sig->expiredate, sig->version,sig->pubkey_algo,sig->digest_algo, sig->sig_class); bufp = bufp + strlen (bufp); if (!vpk->is_primary) { u32 akid[2]; akid[0] = vpk->main_keyid[0]; akid[1] = vpk->main_keyid[1]; free_public_key (vpk); vpk = xmalloc_clear( sizeof *vpk ); if (get_pubkey (vpk, akid)) { /* impossible error, we simply return a zeroed out fpr */ n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20; memset (array, 0, n); } else fingerprint_from_pk( vpk, array, &n ); } p = array; for(i=0; i < n ; i++, p++, bufp += 2) sprintf(bufp, "%02X", *p ); write_status_text( STATUS_VALIDSIG, buf ); } free_public_key( vpk ); } if (!rc) { if(opt.verify_options&VERIFY_PKA_LOOKUPS) pka_uri_from_sig (sig); /* Make sure PKA info is available. */ rc = check_signatures_trust( sig ); } if(sig->flags.expired) { log_info(_("Signature expired %s\n"), asctimestamp(sig->expiredate)); rc=G10ERR_GENERAL; /* need a better error here? */ } else if(sig->expiredate) log_info(_("Signature expires %s\n"),asctimestamp(sig->expiredate)); if(opt.verbose) log_info(_("%s signature, digest algorithm %s\n"), sig->sig_class==0x00?_("binary"): sig->sig_class==0x01?_("textmode"):_("unknown"), gcry_md_algo_name (sig->digest_algo)); if( rc ) g10_errors_seen = 1; if( opt.batch && rc ) g10_exit(1); } else { char buf[50]; sprintf(buf, "%08lX%08lX %d %d %02x %lu %d", (ulong)sig->keyid[0], (ulong)sig->keyid[1], sig->pubkey_algo, sig->digest_algo, sig->sig_class, (ulong)sig->timestamp, rc ); write_status_text( STATUS_ERRSIG, buf ); if( rc == G10ERR_NO_PUBKEY ) { buf[16] = 0; write_status_text( STATUS_NO_PUBKEY, buf ); } if( rc != G10ERR_NOT_PROCESSED ) log_error(_("Can't check signature: %s\n"), g10_errstr(rc) ); } return rc; } /**************** * Process the tree which starts at node */ static void proc_tree( CTX c, KBNODE node ) { KBNODE n1; int rc; if( opt.list_packets || opt.list_only ) return; /* we must skip our special plaintext marker packets here becuase they may be the root packet. These packets are only used in addionla checks and skipping them here doesn't matter */ while ( node && node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK ) { node = node->next; } if (!node) return; c->trustletter = ' '; if( node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) { merge_keys_and_selfsig( node ); list_node( c, node ); } else if( node->pkt->pkttype == PKT_SECRET_KEY ) { merge_keys_and_selfsig( node ); list_node( c, node ); } else if( node->pkt->pkttype == PKT_ONEPASS_SIG ) { /* check all signatures */ if( !c->have_data ) { int use_textmode = 0; free_md_filter_context( &c->mfx ); /* prepare to create all requested message digests */ if (gcry_md_open (&c->mfx.md, 0, 0)) BUG (); /* fixme: why looking for the signature packet and not the one-pass packet? */ for ( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); ) { gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo); } if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01) use_textmode = 1; /* Ask for file and hash it. */ if( c->sigs_only ) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, NULL, c->signed_data.data_fd, use_textmode); else rc = hash_datafiles (c->mfx.md, NULL, c->signed_data.data_names, c->sigfilename, use_textmode ); } else { rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2, iobuf_get_real_fname(c->iobuf), use_textmode ); } if( rc ) { log_error("can't hash datafile: %s\n", g10_errstr(rc)); return; } } else if ( c->signed_data.used ) { log_error (_("not a detached signature\n") ); return; } for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); ) check_sig_and_print( c, n1 ); } else if( node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* clear text signed message */ if( !c->have_data ) { log_error("cleartext signature without data\n" ); return; } else if ( c->signed_data.used ) { log_error (_("not a detached signature\n") ); return; } for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); ) check_sig_and_print( c, n1 ); } else if( node->pkt->pkttype == PKT_SIGNATURE ) { PKT_signature *sig = node->pkt->pkt.signature; int multiple_ok=1; n1=find_next_kbnode(node, PKT_SIGNATURE); if(n1) { byte class=sig->sig_class; byte hash=sig->digest_algo; for(; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE))) { /* We can't currently handle multiple signatures of different classes or digests (we'd pretty much have to run a different hash context for each), but if they are all the same, make an exception. */ if(n1->pkt->pkt.signature->sig_class!=class || n1->pkt->pkt.signature->digest_algo!=hash) { multiple_ok=0; log_info(_("WARNING: multiple signatures detected. " "Only the first will be checked.\n")); break; } } } if( sig->sig_class != 0x00 && sig->sig_class != 0x01 ) log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class); else if( !c->have_data ) { /* detached signature */ free_md_filter_context( &c->mfx ); if (gcry_md_open (&c->mfx.md, sig->digest_algo, 0)) BUG (); if( !opt.pgp2_workarounds ) ; else if( sig->digest_algo == DIGEST_ALGO_MD5 && is_RSA( sig->pubkey_algo ) ) { /* enable a workaround for a pgp2 bug */ if (gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0)) BUG (); } else if( sig->digest_algo == DIGEST_ALGO_SHA1 && sig->pubkey_algo == PUBKEY_ALGO_DSA && sig->sig_class == 0x01 ) { /* enable the workaround also for pgp5 when the detached * signature has been created in textmode */ if (gcry_md_open (&c->mfx.md2, sig->digest_algo, 0 )) BUG (); } #if 0 /* workaround disabled */ /* Here we have another hack to work around a pgp 2 bug * It works by not using the textmode for detached signatures; * this will let the first signature check (on md) fail * but the second one (on md2) which adds an extra CR should * then produce the "correct" hash. This is very, very ugly * hack but it may help in some cases (and break others) */ /* c->mfx.md2? 0 :(sig->sig_class == 0x01) */ #endif if ( DBG_HASHING ) { gcry_md_start_debug( c->mfx.md, "verify" ); if ( c->mfx.md2 ) gcry_md_start_debug( c->mfx.md2, "verify2" ); } if( c->sigs_only ) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2, c->signed_data.data_fd, (sig->sig_class == 0x01)); else rc = hash_datafiles (c->mfx.md, c->mfx.md2, c->signed_data.data_names, c->sigfilename, (sig->sig_class == 0x01)); } else { rc = ask_for_detached_datafile( c->mfx.md, c->mfx.md2, iobuf_get_real_fname(c->iobuf), (sig->sig_class == 0x01) ); } if( rc ) { log_error("can't hash datafile: %s\n", g10_errstr(rc)); return; } } else if ( c->signed_data.used ) { log_error (_("not a detached signature\n") ); return; } else if (!opt.quiet) log_info(_("old style (PGP 2.x) signature\n")); if(multiple_ok) for( n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )) ) check_sig_and_print( c, n1 ); else check_sig_and_print( c, node ); } else { dump_kbnode (c->list); log_error(_("invalid root packet detected in proc_tree()\n")); dump_kbnode (node); } } diff --git a/g10/misc.c b/g10/misc.c index f34e1e36d..5e0ba9449 100644 --- a/g10/misc.c +++ b/g10/misc.c @@ -1,1419 +1,1421 @@ /* misc.c - miscellaneous functions * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009 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 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2 #include #include #endif #ifdef HAVE_SETRLIMIT #include #include #include #endif #ifdef ENABLE_SELINUX_HACKS #include #endif #ifdef HAVE_W32_SYSTEM #include #include #include #include #ifndef CSIDL_APPDATA #define CSIDL_APPDATA 0x001a #endif #ifndef CSIDL_LOCAL_APPDATA #define CSIDL_LOCAL_APPDATA 0x001c #endif #ifndef CSIDL_FLAG_CREATE #define CSIDL_FLAG_CREATE 0x8000 #endif #endif /*HAVE_W32_SYSTEM*/ #include "gpg.h" #ifdef HAVE_W32_SYSTEM # include "status.h" #endif /*HAVE_W32_SYSTEM*/ #include "util.h" #include "main.h" #include "photoid.h" #include "options.h" #include "call-agent.h" #include "i18n.h" static int string_count_chr (const char *string, int c) { int count; for (count=0; *string; string++ ) if ( *string == c ) count++; return count; } #ifdef ENABLE_SELINUX_HACKS /* A object and a global variable to keep track of files marked as secured. */ struct secured_file_item { struct secured_file_item *next; ino_t ino; dev_t dev; }; static struct secured_file_item *secured_files; #endif /*ENABLE_SELINUX_HACKS*/ /* For the sake of SELinux we want to restrict access through gpg to certain files we keep under our own control. This function registers such a file and is_secured_file may then be used to check whether a file has ben registered as secured. */ void register_secured_file (const char *fname) { #ifdef ENABLE_SELINUX_HACKS struct stat buf; struct secured_file_item *sf; /* Note that we stop immediatley if something goes wrong here. */ if (stat (fname, &buf)) log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname, "register_secured_file", strerror (errno)); /* log_debug ("registering `%s' i=%lu.%lu\n", fname, */ /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */ for (sf=secured_files; sf; sf = sf->next) { if (sf->ino == buf.st_ino && sf->dev == buf.st_dev) return; /* Already registered. */ } sf = xmalloc (sizeof *sf); sf->ino = buf.st_ino; sf->dev = buf.st_dev; sf->next = secured_files; secured_files = sf; #else /*!ENABLE_SELINUX_HACKS*/ (void)fname; #endif /*!ENABLE_SELINUX_HACKS*/ } /* Remove a file registered as secure. */ void unregister_secured_file (const char *fname) { #ifdef ENABLE_SELINUX_HACKS struct stat buf; struct secured_file_item *sf, *sfprev; if (stat (fname, &buf)) { log_error (_("fstat of `%s' failed in %s: %s\n"), fname, "unregister_secured_file", strerror (errno)); return; } /* log_debug ("unregistering `%s' i=%lu.%lu\n", fname, */ /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */ for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next) { if (sf->ino == buf.st_ino && sf->dev == buf.st_dev) { if (sfprev) sfprev->next = sf->next; else secured_files = sf->next; xfree (sf); return; } } #else /*!ENABLE_SELINUX_HACKS*/ (void)fname; #endif /*!ENABLE_SELINUX_HACKS*/ } /* Return true if FD is corresponds to a secured file. Using -1 for FS is allowed and will return false. */ int is_secured_file (int fd) { #ifdef ENABLE_SELINUX_HACKS struct stat buf; struct secured_file_item *sf; if (fd == -1) return 0; /* No file descriptor so it can't be secured either. */ /* Note that we print out a error here and claim that a file is secure if something went wrong. */ if (fstat (fd, &buf)) { log_error (_("fstat(%d) failed in %s: %s\n"), fd, "is_secured_file", strerror (errno)); return 1; } /* log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */ /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */ for (sf=secured_files; sf; sf = sf->next) { if (sf->ino == buf.st_ino && sf->dev == buf.st_dev) return 1; /* Yes. */ } #else /*!ENABLE_SELINUX_HACKS*/ (void)fd; #endif /*!ENABLE_SELINUX_HACKS*/ return 0; /* No. */ } /* Return true if FNAME is corresponds to a secured file. Using NULL, "" or "-" for FS is allowed and will return false. This function is used before creating a file, thus it won't fail if the file does not exist. */ int is_secured_filename (const char *fname) { #ifdef ENABLE_SELINUX_HACKS struct stat buf; struct secured_file_item *sf; if (iobuf_is_pipe_filename (fname) || !*fname) return 0; /* Note that we print out a error here and claim that a file is secure if something went wrong. */ if (stat (fname, &buf)) { if (errno == ENOENT || errno == EPERM || errno == EACCES) return 0; log_error (_("fstat of `%s' failed in %s: %s\n"), fname, "is_secured_filename", strerror (errno)); return 1; } /* log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */ /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */ for (sf=secured_files; sf; sf = sf->next) { if (sf->ino == buf.st_ino && sf->dev == buf.st_dev) return 1; /* Yes. */ } #else /*!ENABLE_SELINUX_HACKS*/ (void)fname; #endif /*!ENABLE_SELINUX_HACKS*/ return 0; /* No. */ } u16 checksum_u16( unsigned n ) { u16 a; a = (n >> 8) & 0xff; a += n & 0xff; return a; } u16 checksum( byte *p, unsigned n ) { u16 a; for(a=0; n; n-- ) a += *p++; return a; } u16 checksum_mpi (gcry_mpi_t a) { u16 csum; byte *buffer; size_t nbytes; if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) ) BUG (); /* Fixme: For numbers not in secure memory we should use a stack * based buffer and only allocate a larger one if mpi_print returns * an error. */ buffer = (gcry_is_secure(a)? gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes)); if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) ) BUG (); csum = checksum (buffer, nbytes); xfree (buffer); return csum; } u32 buffer_to_u32( const byte *buffer ) { unsigned long a; a = *buffer << 24; a |= buffer[1] << 16; a |= buffer[2] << 8; a |= buffer[3]; return a; } void print_pubkey_algo_note( int algo ) { if(algo >= 100 && algo <= 110) { static int warn=0; if(!warn) { warn=1; log_info (_("WARNING: using experimental public key algorithm %s\n"), gcry_pk_algo_name (algo)); } } else if (algo == 20) { log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n")); } } void print_cipher_algo_note( int algo ) { if(algo >= 100 && algo <= 110) { static int warn=0; if(!warn) { warn=1; log_info (_("WARNING: using experimental cipher algorithm %s\n"), openpgp_cipher_algo_name (algo)); } } } void print_digest_algo_note( int algo ) { if(algo >= 100 && algo <= 110) { static int warn=0; if(!warn) { warn=1; log_info (_("WARNING: using experimental digest algorithm %s\n"), gcry_md_algo_name (algo)); } } else if(algo==DIGEST_ALGO_MD5) log_info (_("WARNING: digest algorithm %s is deprecated\n"), gcry_md_algo_name (algo)); } /* Map OpenPGP algo numbers to those used by Libgcrypt. We need to do this for algorithms we implemented in Libgcrypt after they become part of OpenPGP. */ int map_cipher_openpgp_to_gcry (int algo) { switch (algo) { case CIPHER_ALGO_CAMELLIA128: return 310; case CIPHER_ALGO_CAMELLIA192: return 311; case CIPHER_ALGO_CAMELLIA256: return 312; default: return algo; } } /* The inverse fucntion of above. */ static int map_cipher_gcry_to_openpgp (int algo) { switch (algo) { case 310: return CIPHER_ALGO_CAMELLIA128; case 311: return CIPHER_ALGO_CAMELLIA192; case 312: return CIPHER_ALGO_CAMELLIA256; default: return algo; } } /* Return the block length of an OpenPGP cipher algorithm. */ int openpgp_cipher_blocklen (int algo) { /* We use the numbers from OpenPGP to be sure that we get the right block length. This is so that the packet parsing code works even for unknown algorithms (for which we assume 8 due to tradition). NOTE: If you change the the returned blocklen above 16, check the callers because they may use a fixed size buffer of that size. */ switch (algo) { case 7: case 8: case 9: /* AES */ case 10: /* Twofish */ case 11: case 12: case 13: /* Camellia */ return 16; default: return 8; } } /**************** * Wrapper around the libgcrypt function with additonal checks on * the OpenPGP contraints for the algo ID. */ int openpgp_cipher_test_algo( int algo ) { /* (5 and 6 are marked reserved by rfc4880.) */ if ( algo < 0 || algo > 110 || algo == 5 || algo == 6 ) return gpg_error (GPG_ERR_CIPHER_ALGO); return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo)); } /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this function returns "?". */ const char * openpgp_cipher_algo_name (int algo) { return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo)); } int openpgp_pk_test_algo( int algo ) { /* Dont't allow type 20 keys unless in rfc2440 mode. */ if (!RFC2440 && algo == 20) return gpg_error (GPG_ERR_PUBKEY_ALGO); if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (algo < 0 || algo > 110) return gpg_error (GPG_ERR_PUBKEY_ALGO); return gcry_pk_test_algo (algo); } int openpgp_pk_test_algo2( int algo, unsigned int use ) { size_t use_buf = use; /* Dont't allow type 20 keys unless in rfc2440 mode. */ if (!RFC2440 && algo == 20) return gpg_error (GPG_ERR_PUBKEY_ALGO); if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (algo < 0 || algo > 110) return gpg_error (GPG_ERR_PUBKEY_ALGO); return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf); } int openpgp_pk_algo_usage ( int algo ) { int use = 0; /* They are hardwired in gpg 1.0. */ switch ( algo ) { case PUBKEY_ALGO_RSA: use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH); break; case PUBKEY_ALGO_RSA_E: use = PUBKEY_USAGE_ENC; break; case PUBKEY_ALGO_RSA_S: use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG; break; case PUBKEY_ALGO_ELGAMAL: if (RFC2440) use = PUBKEY_USAGE_ENC; break; case PUBKEY_ALGO_ELGAMAL_E: use = PUBKEY_USAGE_ENC; break; case PUBKEY_ALGO_DSA: use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH; break; default: break; } return use; } int openpgp_md_test_algo( int algo ) { /* Note: If the list of actual supported OpenPGP algorithms changes, make sure that our hard coded values at print_status_begin_signing() gets updated. */ /* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the next revision of the standard. */ if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7)) return gpg_error (GPG_ERR_DIGEST_ALGO); return gcry_md_test_algo (algo); } #ifdef USE_IDEA /* Special warning for the IDEA cipher */ void idea_cipher_warn(int show) { static int warned=0; if(!warned || show) { log_info(_("the IDEA cipher plugin is not present\n")); log_info(_("please see %s for more information\n"), "http://www.gnupg.org/faq/why-not-idea.html"); warned=1; } } #endif static unsigned long get_signature_count (PKT_public_key *pk) { #ifdef ENABLE_CARD_SUPPORT /* FIXME: Need to call the agent. */ /* if(sk && sk->is_protected && sk->protect.s2k.mode==1002) */ /* { */ /* struct agent_card_info_s info; */ /* if(agent_scd_getattr("SIG-COUNTER",&info)==0) */ /* return info.sig_counter; */ /* } */ #endif /* How to do this without a card? */ return 0; } /* Expand %-strings. Returns a string which must be xfreed. Returns NULL if the string cannot be expanded (too large). */ char * pct_expando(const char *string,struct expando_args *args) { const char *ch=string; int idx=0,maxlen=0,done=0; u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0}; char *ret=NULL; if(args->pk) keyid_from_pk(args->pk,pk_keyid); if(args->pksk) keyid_from_pk (args->pksk, sk_keyid); /* This is used so that %k works in photoid command strings in --list-secret-keys (which of course has a sk, but no pk). */ if(!args->pk && args->pksk) keyid_from_pk (args->pksk, pk_keyid); while(*ch!='\0') { if(!done) { /* 8192 is way bigger than we'll need here */ if(maxlen>=8192) goto fail; maxlen+=1024; ret=xrealloc(ret,maxlen); } done=0; if(*ch=='%') { switch(*(ch+1)) { case 's': /* short key id */ if(idx+8pksk)); idx+=strlen(&ret[idx]); done=1; } break; case 'p': /* primary pk fingerprint of a sk */ case 'f': /* pk fingerprint */ case 'g': /* sk fingerprint */ { byte array[MAX_FINGERPRINT_LEN]; size_t len; int i; if((*(ch+1))=='p' && args->pksk) { if(args->pksk->is_primary) fingerprint_from_pk (args->pksk, array, &len); else if (args->pksk->main_keyid[0] || args->pksk->main_keyid[1]) { /* FIXME: Document teh code and check whether it is still needed. */ PKT_public_key *pk= xmalloc_clear(sizeof(PKT_public_key)); if (!get_pubkey_fast (pk,args->pksk->main_keyid)) fingerprint_from_pk (pk, array, &len); else memset (array, 0, (len=MAX_FINGERPRINT_LEN)); free_public_key (pk); } else memset(array,0,(len=MAX_FINGERPRINT_LEN)); } else if((*(ch+1))=='f' && args->pk) fingerprint_from_pk (args->pk, array, &len); else if((*(ch+1))=='g' && args->pksk) fingerprint_from_pk (args->pksk, array, &len); else memset(array,0,(len=MAX_FINGERPRINT_LEN)); if(idx+(len*2)validity_info && idx+1validity_info; ret[idx]='\0'; done=1; } break; /* The text string types */ case 't': case 'T': case 'V': { const char *str=NULL; switch(*(ch+1)) { case 't': /* e.g. "jpg" */ str=image_type_to_string(args->imagetype,0); break; case 'T': /* e.g. "image/jpeg" */ str=image_type_to_string(args->imagetype,2); break; case 'V': /* e.g. "full", "expired", etc. */ str=args->validity_string; break; } if(str && idx+strlen(str)=0 && algo<=3) return 0; #else if(algo>=0 && algo<=2) return 0; #endif return G10ERR_COMPR_ALGO; } int default_cipher_algo(void) { if(opt.def_cipher_algo) return opt.def_cipher_algo; else if(opt.personal_cipher_prefs) return opt.personal_cipher_prefs[0].value; else return opt.s2k_cipher_algo; } /* There is no default_digest_algo function, but see sign.c:hash_for() */ int default_compress_algo(void) { if(opt.compress_algo!=-1) return opt.compress_algo; else if(opt.personal_compress_prefs) return opt.personal_compress_prefs[0].value; else return DEFAULT_COMPRESS_ALGO; } const char * compliance_option_string(void) { char *ver="???"; switch(opt.compliance) { case CO_GNUPG: return "--gnupg"; case CO_RFC4880: return "--openpgp"; case CO_RFC2440: return "--rfc2440"; case CO_RFC1991: return "--rfc1991"; case CO_PGP2: return "--pgp2"; case CO_PGP6: return "--pgp6"; case CO_PGP7: return "--pgp7"; case CO_PGP8: return "--pgp8"; } return ver; } void compliance_failure(void) { char *ver="???"; switch(opt.compliance) { case CO_GNUPG: ver="GnuPG"; break; case CO_RFC4880: ver="OpenPGP"; break; case CO_RFC2440: ver="OpenPGP (older)"; break; case CO_RFC1991: ver="old PGP"; break; case CO_PGP2: ver="PGP 2.x"; break; case CO_PGP6: ver="PGP 6.x"; break; case CO_PGP7: ver="PGP 7.x"; break; case CO_PGP8: ver="PGP 8.x"; break; } log_info(_("this message may not be usable by %s\n"),ver); opt.compliance=CO_GNUPG; } /* Break a string into successive option pieces. Accepts single word options and key=value argument options. */ char * optsep(char **stringp) { char *tok,*end; tok=*stringp; if(tok) { end=strpbrk(tok," ,="); if(end) { int sawequals=0; char *ptr=end; /* what we need to do now is scan along starting with *end, If the next character we see (ignoring spaces) is an = sign, then there is an argument. */ while(*ptr) { if(*ptr=='=') sawequals=1; else if(*ptr!=' ') break; ptr++; } /* There is an argument, so grab that too. At this point, ptr points to the first character of the argument. */ if(sawequals) { /* Is it a quoted argument? */ if(*ptr=='"') { ptr++; end=strchr(ptr,'"'); if(end) end++; } else end=strpbrk(ptr," ,"); } if(end && *end) { *end='\0'; *stringp=end+1; } else *stringp=NULL; } else *stringp=NULL; } return tok; } /* Breaks an option value into key and value. Returns NULL if there is no value. Note that "string" is modified to remove the =value part. */ char * argsplit(char *string) { char *equals,*arg=NULL; equals=strchr(string,'='); if(equals) { char *quote,*space; *equals='\0'; arg=equals+1; /* Quoted arg? */ quote=strchr(arg,'"'); if(quote) { arg=quote+1; quote=strchr(arg,'"'); if(quote) *quote='\0'; } else { size_t spaces; /* Trim leading spaces off of the arg */ spaces=strspn(arg," "); arg+=spaces; } /* Trim tailing spaces off of the tag */ space=strchr(string,' '); if(space) *space='\0'; } return arg; } /* Return the length of the initial token, leaving off any argument. */ static size_t optlen(const char *s) { char *end=strpbrk(s," ="); if(end) return end-s; else return strlen(s); } int parse_options(char *str,unsigned int *options, struct parse_options *opts,int noisy) { char *tok; if (str && !strcmp (str, "help")) { int i,maxlen=0; /* Figure out the longest option name so we can line these up neatly. */ for(i=0;opts[i].name;i++) if(opts[i].help && maxlen='A' && file[0]<='Z') || (file[0]>='a' && file[0]<='z')) && file[1]==':') #else || file[0]=='/' #endif ) return access(file,mode); else { /* At least as large as, but most often larger than we need. */ char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1); char *split,*item,*path=xstrdup(envpath); split=path; while((item=strsep(&split,PATHSEP_S))) { strcpy(buffer,item); strcat(buffer,"/"); strcat(buffer,file); ret=access(buffer,mode); if(ret==0) break; } xfree(path); xfree(buffer); } return ret; } /* Temporary helper. */ int pubkey_get_npkey( int algo ) { size_t n; if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n)) n = 0; return n; } /* Temporary helper. */ int pubkey_get_nskey( int algo ) { size_t n; if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n )) n = 0; return n; } /* Temporary helper. */ int pubkey_get_nsig( int algo ) { size_t n; if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n)) n = 0; return n; } /* Temporary helper. */ int pubkey_get_nenc( int algo ) { size_t n; if (algo == GCRY_PK_ELG_E) algo = GCRY_PK_ELG; if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n )) n = 0; return n; } /* Temporary helper. */ unsigned int pubkey_nbits( int algo, gcry_mpi_t *key ) { int rc, nbits; gcry_sexp_t sexp; if( algo == GCRY_PK_DSA ) { rc = gcry_sexp_build ( &sexp, NULL, "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))", key[0], key[1], key[2], key[3] ); } else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) { rc = gcry_sexp_build ( &sexp, NULL, "(public-key(elg(p%m)(g%m)(y%m)))", key[0], key[1], key[2] ); } else if( algo == GCRY_PK_RSA ) { rc = gcry_sexp_build ( &sexp, NULL, "(public-key(rsa(n%m)(e%m)))", key[0], key[1] ); } else return 0; if ( rc ) BUG (); nbits = gcry_pk_get_nbits( sexp ); gcry_sexp_release( sexp ); return nbits; } /* FIXME: Use gcry_mpi_print directly. */ int -mpi_print( FILE *fp, gcry_mpi_t a, int mode ) +mpi_print (estream_t fp, gcry_mpi_t a, int mode) { - int n=0; - - if( !a ) - return fprintf(fp, "[MPI_NULL]"); - if( !mode ) { - unsigned int n1; - n1 = gcry_mpi_get_nbits(a); - n += fprintf(fp, "[%u bits]", n1); + int n=0; + + if (!a) + return es_fprintf (fp, "[MPI_NULL]"); + if (!mode) + { + unsigned int n1; + n1 = gcry_mpi_get_nbits(a); + n += es_fprintf (fp, "[%u bits]", n1); } - else { - unsigned char *buffer; - - if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a)) - BUG (); - fputs( buffer, fp ); - n += strlen(buffer); - gcry_free( buffer ); + else + { + unsigned char *buffer; + + if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a)) + BUG (); + es_fputs (buffer, fp); + n += strlen (buffer); + gcry_free (buffer); } - return n; + return n; } diff --git a/g10/parse-packet.c b/g10/parse-packet.c index e2a5ea39d..2065c22ef 100644 --- a/g10/parse-packet.c +++ b/g10/parse-packet.c @@ -1,2810 +1,2809 @@ /* parse-packet.c - read packets * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, - * 2007, 2009 Free Software Foundation, Inc. + * 2007, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "gpg.h" #include "packet.h" #include "iobuf.h" #include "util.h" #include "cipher.h" #include "filter.h" #include "photoid.h" #include "options.h" #include "main.h" #include "i18n.h" static int mpi_print_mode; static int list_mode; -static FILE *listfp; +static estream_t listfp; static int parse (IOBUF inp, PACKET * pkt, int onlykeypkts, off_t * retpos, int *skip, IOBUF out, int do_skip #ifdef DEBUG_PARSE_PACKET , const char *dbg_w, const char *dbg_f, int dbg_l #endif ); static int copy_packet (IOBUF inp, IOBUF out, int pkttype, unsigned long pktlen, int partial); static void skip_packet (IOBUF inp, int pkttype, unsigned long pktlen, int partial); static void *read_rest (IOBUF inp, size_t pktlen, int partial); static int parse_marker (IOBUF inp, int pkttype, unsigned long pktlen); static int parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static int parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static int parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen, PKT_onepass_sig * ops); static int parse_key (IOBUF inp, int pkttype, unsigned long pktlen, byte * hdr, int hdrlen, PACKET * packet); static int parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static int parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static int parse_comment (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static void parse_trust (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet); static int parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int new_ctb, int partial); static int parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int new_ctb); static int parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int new_ctb, int partial); static int parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int new_ctb); static int parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int partial); static unsigned short read_16 (IOBUF inp) { unsigned short a; a = iobuf_get_noeof (inp) << 8; a |= iobuf_get_noeof (inp); return a; } static unsigned long read_32 (IOBUF inp) { unsigned long a; a = iobuf_get_noeof (inp) << 24; a |= iobuf_get_noeof (inp) << 16; a |= iobuf_get_noeof (inp) << 8; a |= iobuf_get_noeof (inp); return a; } /* Read an external representation of an mpi and return the MPI. The * external format is a 16 bit unsigned value stored in network byte * order, giving the number of bits for the following integer. The * integer is stored with MSB first (left padded with zeroes to align * on a byte boundary). */ static gcry_mpi_t mpi_read (iobuf_t inp, unsigned int *ret_nread, int secure) { /*FIXME: Needs to be synced with gnupg14/mpi/mpicoder.c */ int c, c1, c2, i; unsigned int nbits, nbytes; size_t nread = 0; gcry_mpi_t a = NULL; byte *buf = NULL; byte *p; if ((c = c1 = iobuf_get (inp)) == -1) goto leave; nbits = c << 8; if ((c = c2 = iobuf_get (inp)) == -1) goto leave; nbits |= c; if (nbits > MAX_EXTERN_MPI_BITS) { log_error ("mpi too large (%u bits)\n", nbits); goto leave; } nread = 2; nbytes = (nbits + 7) / 8; buf = secure ? gcry_xmalloc_secure (nbytes + 2) : gcry_xmalloc (nbytes + 2); p = buf; p[0] = c1; p[1] = c2; for (i = 0; i < nbytes; i++) { p[i + 2] = iobuf_get (inp) & 0xff; nread++; } if (nread >= 2 && !(buf[0] << 8 | buf[1])) { /* Libgcrypt < 1.5.0 accidently rejects zero-length (i.e. zero) MPIs. We fix this here. */ a = gcry_mpi_new (0); } else { if (gcry_mpi_scan (&a, GCRYMPI_FMT_PGP, buf, nread, &nread)) a = NULL; } leave: gcry_free (buf); if (nread > *ret_nread) log_bug ("mpi larger than packet"); else *ret_nread = nread; return a; } int set_packet_list_mode (int mode) { int old = list_mode; list_mode = mode; /* FIXME(gcrypt) mpi_print_mode = DBG_MPI; */ /* We use stdout print only if invoked by the --list-packets command - but switch to stderr in all otehr cases. This breaks the + but switch to stderr in all other cases. This breaks the previous behaviour but that seems to be more of a bug than intentional. I don't believe that any application makes use of this long standing annoying way of printing to stdout except when doing a --list-packets. If this assumption fails, it will be easy to add an option for the listing stream. Note that we initialize it only once; mainly because some code may switch the option value later back to 1 and we want to have all output to the same stream. Using stderr is not actually very clean because it bypasses the - logging code but it is a special thing anyay. I am not sure + logging code but it is a special thing anyway. I am not sure whether using log_stream() would be better. Perhaps we should enable the list mdoe only with a special option. */ if (!listfp) - listfp = opt.list_packets == 2 ? stdout : stderr; + listfp = opt.list_packets == 2 ? es_stdout : es_stderr; return old; } static void unknown_pubkey_warning (int algo) { static byte unknown_pubkey_algos[256]; algo &= 0xff; if (!unknown_pubkey_algos[algo]) { if (opt.verbose) log_info (_("can't handle public key algorithm %d\n"), algo); unknown_pubkey_algos[algo] = 1; } } /* Parse a packet and return it in packet structure. * Returns: 0 := valid packet in pkt * -1 := no more packets * >0 := error * Note: The function may return an error and a partly valid packet; * caller must free this packet. */ #ifdef DEBUG_PARSE_PACKET int dbg_parse_packet (IOBUF inp, PACKET *pkt, const char *dbg_f, int dbg_l) { int skip, rc; do { rc = parse (inp, pkt, 0, NULL, &skip, NULL, 0, "parse", dbg_f, dbg_l); } while (skip); return rc; } #else /*!DEBUG_PARSE_PACKET*/ int parse_packet (IOBUF inp, PACKET * pkt) { int skip, rc; do { rc = parse (inp, pkt, 0, NULL, &skip, NULL, 0); } while (skip); return rc; } #endif /*!DEBUG_PARSE_PACKET*/ /* * Like parse packet, but only return secret or public (sub)key * packets. */ #ifdef DEBUG_PARSE_PACKET int dbg_search_packet (IOBUF inp, PACKET * pkt, off_t * retpos, int with_uid, const char *dbg_f, int dbg_l) { int skip, rc; do { rc = parse (inp, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0, "search", dbg_f, dbg_l); } while (skip); return rc; } #else /*!DEBUG_PARSE_PACKET*/ int search_packet (IOBUF inp, PACKET * pkt, off_t * retpos, int with_uid) { int skip, rc; do { rc = parse (inp, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0); } while (skip); return rc; } #endif /*!DEBUG_PARSE_PACKET*/ /* * Copy all packets from INP to OUT, thereby removing unused spaces. */ #ifdef DEBUG_PARSE_PACKET int dbg_copy_all_packets (IOBUF inp, IOBUF out, const char *dbg_f, int dbg_l) { PACKET pkt; int skip, rc = 0; do { init_packet (&pkt); } while (! (rc = parse (inp, &pkt, 0, NULL, &skip, out, 0, "copy", dbg_f, dbg_l))); return rc; } #else /*!DEBUG_PARSE_PACKET*/ int copy_all_packets (IOBUF inp, IOBUF out) { PACKET pkt; int skip, rc = 0; do { init_packet (&pkt); } while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0))); return rc; } #endif /*!DEBUG_PARSE_PACKET*/ /* * Copy some packets from INP to OUT, thereby removing unused spaces. * Stop at offset STOPoff (i.e. don't copy packets at this or later * offsets) */ #ifdef DEBUG_PARSE_PACKET int dbg_copy_some_packets (IOBUF inp, IOBUF out, off_t stopoff, const char *dbg_f, int dbg_l) { PACKET pkt; int skip, rc = 0; do { if (iobuf_tell (inp) >= stopoff) return 0; init_packet (&pkt); } while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0, "some", dbg_f, dbg_l))); return rc; } #else /*!DEBUG_PARSE_PACKET*/ int copy_some_packets (IOBUF inp, IOBUF out, off_t stopoff) { PACKET pkt; int skip, rc = 0; do { if (iobuf_tell (inp) >= stopoff) return 0; init_packet (&pkt); } while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0))); return rc; } #endif /*!DEBUG_PARSE_PACKET*/ /* * Skip over N packets */ #ifdef DEBUG_PARSE_PACKET int dbg_skip_some_packets (IOBUF inp, unsigned n, const char *dbg_f, int dbg_l) { int skip, rc = 0; PACKET pkt; for (; n && !rc; n--) { init_packet (&pkt); rc = parse (inp, &pkt, 0, NULL, &skip, NULL, 1, "skip", dbg_f, dbg_l); } return rc; } #else /*!DEBUG_PARSE_PACKET*/ int skip_some_packets (IOBUF inp, unsigned n) { int skip, rc = 0; PACKET pkt; for (; n && !rc; n--) { init_packet (&pkt); rc = parse (inp, &pkt, 0, NULL, &skip, NULL, 1); } return rc; } #endif /*!DEBUG_PARSE_PACKET*/ /* * Parse packet. Stores 1 at SKIP 1 if the packet should be skipped; * this is the case if either ONLYKEYPKTS is set and the parsed packet * isn't a key packet or the packet-type is 0, indicating deleted * stuff. If OUT is not NULL, a special copymode is used. */ static int parse (IOBUF inp, PACKET * pkt, int onlykeypkts, off_t * retpos, int *skip, IOBUF out, int do_skip #ifdef DEBUG_PARSE_PACKET , const char *dbg_w, const char *dbg_f, int dbg_l #endif ) { int rc = 0, c, ctb, pkttype, lenbytes; unsigned long pktlen; byte hdr[8]; int hdrlen; int new_ctb = 0, partial = 0; int with_uid = (onlykeypkts == 2); *skip = 0; assert (!pkt->pkt.generic); if (retpos) *retpos = iobuf_tell (inp); if ((ctb = iobuf_get (inp)) == -1) { rc = -1; goto leave; } hdrlen = 0; hdr[hdrlen++] = ctb; if (!(ctb & 0x80)) { log_error ("%s: invalid packet (ctb=%02x)\n", iobuf_where (inp), ctb); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } pktlen = 0; new_ctb = !!(ctb & 0x40); if (new_ctb) { pkttype = ctb & 0x3f; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 1st length byte missing\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } hdr[hdrlen++] = c; if (c < 192) pktlen = c; else if (c < 224) { pktlen = (c - 192) * 256; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 2nd length byte missing\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } hdr[hdrlen++] = c; pktlen += c + 192; } else if (c == 255) { pktlen = (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 24; pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 16; pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 8; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 4 byte length invalid\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } pktlen |= (hdr[hdrlen++] = c); } else /* Partial body length. */ { switch (pkttype) { case PKT_PLAINTEXT: case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_COMPRESSED: iobuf_set_partial_block_mode (inp, c & 0xff); pktlen = 0; /* To indicate partial length. */ partial = 1; break; default: log_error ("%s: partial length for invalid" " packet type %d\n", iobuf_where (inp), pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } } } else { pkttype = (ctb >> 2) & 0xf; lenbytes = ((ctb & 3) == 3) ? 0 : (1 << (ctb & 3)); if (!lenbytes) { pktlen = 0; /* Don't know the value. */ /* This isn't really partial, but we can treat it the same in a "read until the end" sort of way. */ partial = 1; if (pkttype != PKT_ENCRYPTED && pkttype != PKT_PLAINTEXT && pkttype != PKT_COMPRESSED) { log_error ("%s: indeterminate length for invalid" " packet type %d\n", iobuf_where (inp), pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } } else { for (; lenbytes; lenbytes--) { pktlen <<= 8; pktlen |= hdr[hdrlen++] = iobuf_get_noeof (inp); } } } if (pktlen == (unsigned long) (-1)) { /* With some probability this is caused by a problem in the * the uncompressing layer - in some error cases it just loops * and spits out 0xff bytes. */ log_error ("%s: garbled packet detected\n", iobuf_where (inp)); g10_exit (2); } if (out && pkttype) { rc = iobuf_write (out, hdr, hdrlen); if (!rc) rc = copy_packet (inp, out, pkttype, pktlen, partial); goto leave; } if (with_uid && pkttype == PKT_USER_ID) ; else if (do_skip || !pkttype || (onlykeypkts && pkttype != PKT_PUBLIC_SUBKEY && pkttype != PKT_PUBLIC_KEY && pkttype != PKT_SECRET_SUBKEY && pkttype != PKT_SECRET_KEY)) { iobuf_skip_rest (inp, pktlen, partial); *skip = 1; rc = 0; goto leave; } if (DBG_PACKET) { #ifdef DEBUG_PARSE_PACKET log_debug ("parse_packet(iob=%d): type=%d length=%lu%s (%s.%s.%d)\n", iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : "", dbg_w, dbg_f, dbg_l); #else log_debug ("parse_packet(iob=%d): type=%d length=%lu%s\n", iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : ""); #endif } pkt->pkttype = pkttype; rc = G10ERR_UNKNOWN_PACKET; /* default error */ switch (pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: pkt->pkt.public_key = xmalloc_clear (sizeof *pkt->pkt.public_key); rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt); break; case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: pkt->pkt.secret_key = xmalloc_clear (sizeof *pkt->pkt.secret_key); rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt); break; case PKT_SYMKEY_ENC: rc = parse_symkeyenc (inp, pkttype, pktlen, pkt); break; case PKT_PUBKEY_ENC: rc = parse_pubkeyenc (inp, pkttype, pktlen, pkt); break; case PKT_SIGNATURE: pkt->pkt.signature = xmalloc_clear (sizeof *pkt->pkt.signature); rc = parse_signature (inp, pkttype, pktlen, pkt->pkt.signature); break; case PKT_ONEPASS_SIG: pkt->pkt.onepass_sig = xmalloc_clear (sizeof *pkt->pkt.onepass_sig); rc = parse_onepass_sig (inp, pkttype, pktlen, pkt->pkt.onepass_sig); break; case PKT_USER_ID: rc = parse_user_id (inp, pkttype, pktlen, pkt); break; case PKT_ATTRIBUTE: pkt->pkttype = pkttype = PKT_USER_ID; /* we store it in the userID */ rc = parse_attribute (inp, pkttype, pktlen, pkt); break; case PKT_OLD_COMMENT: case PKT_COMMENT: rc = parse_comment (inp, pkttype, pktlen, pkt); break; case PKT_RING_TRUST: parse_trust (inp, pkttype, pktlen, pkt); rc = 0; break; case PKT_PLAINTEXT: rc = parse_plaintext (inp, pkttype, pktlen, pkt, new_ctb, partial); break; case PKT_COMPRESSED: rc = parse_compressed (inp, pkttype, pktlen, pkt, new_ctb); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: rc = parse_encrypted (inp, pkttype, pktlen, pkt, new_ctb, partial); break; case PKT_MDC: rc = parse_mdc (inp, pkttype, pktlen, pkt, new_ctb); break; case PKT_GPG_CONTROL: rc = parse_gpg_control (inp, pkttype, pktlen, pkt, partial); break; case PKT_MARKER: rc = parse_marker (inp, pkttype, pktlen); break; default: skip_packet (inp, pkttype, pktlen, partial); break; } leave: if (!rc && iobuf_error (inp)) rc = G10ERR_INV_KEYRING; return rc; } static void dump_hex_line (int c, int *i) { if (*i && !(*i % 8)) { if (*i && !(*i % 24)) - fprintf (listfp, "\n%4d:", *i); + es_fprintf (listfp, "\n%4d:", *i); else - putc (' ', listfp); + es_putc (' ', listfp); } if (c == -1) - fprintf (listfp, " EOF"); + es_fprintf (listfp, " EOF"); else - fprintf (listfp, " %02x", c); + es_fprintf (listfp, " %02x", c); ++*i; } static int copy_packet (IOBUF inp, IOBUF out, int pkttype, unsigned long pktlen, int partial) { int rc; int n; char buf[100]; if (partial) { while ((n = iobuf_read (inp, buf, 100)) != -1) if ((rc = iobuf_write (out, buf, n))) return rc; /* write error */ } else if (!pktlen && pkttype == PKT_COMPRESSED) { log_debug ("copy_packet: compressed!\n"); /* compressed packet, copy till EOF */ while ((n = iobuf_read (inp, buf, 100)) != -1) if ((rc = iobuf_write (out, buf, n))) return rc; /* write error */ } else { for (; pktlen; pktlen -= n) { n = pktlen > 100 ? 100 : pktlen; n = iobuf_read (inp, buf, n); if (n == -1) return gpg_error (GPG_ERR_EOF); if ((rc = iobuf_write (out, buf, n))) return rc; /* write error */ } } return 0; } static void skip_packet (IOBUF inp, int pkttype, unsigned long pktlen, int partial) { if (list_mode) { - fprintf (listfp, ":unknown packet: type %2d, length %lu\n", - pkttype, pktlen); + es_fprintf (listfp, ":unknown packet: type %2d, length %lu\n", + pkttype, pktlen); if (pkttype) { int c, i = 0; - fputs ("dump:", listfp); + es_fputs ("dump:", listfp); if (partial) { while ((c = iobuf_get (inp)) != -1) dump_hex_line (c, &i); } else { for (; pktlen; pktlen--) { dump_hex_line ((c = iobuf_get (inp)), &i); if (c == -1) break; } } - putc ('\n', listfp); + es_putc ('\n', listfp); return; } } iobuf_skip_rest (inp, pktlen, partial); } static void * read_rest (IOBUF inp, size_t pktlen, int partial) { byte *p; int i; if (partial) { log_error ("read_rest: can't store stream data\n"); p = NULL; } else { p = xmalloc (pktlen); for (i = 0; pktlen; pktlen--, i++) p[i] = iobuf_get (inp); } return p; } static int parse_marker (IOBUF inp, int pkttype, unsigned long pktlen) { (void) pkttype; if (pktlen != 3) goto fail; if (iobuf_get (inp) != 'P') { pktlen--; goto fail; } if (iobuf_get (inp) != 'G') { pktlen--; goto fail; } if (iobuf_get (inp) != 'P') { pktlen--; goto fail; } if (list_mode) - fputs (":marker packet: PGP\n", listfp); + es_fputs (":marker packet: PGP\n", listfp); return 0; fail: log_error ("invalid marker packet\n"); iobuf_skip_rest (inp, pktlen, 0); return G10ERR_INVALID_PACKET; } static int parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet) { PKT_symkey_enc *k; int rc = 0; int i, version, s2kmode, cipher_algo, hash_algo, seskeylen, minlen; if (pktlen < 4) { log_error ("packet(%d) too short\n", pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } version = iobuf_get_noeof (inp); pktlen--; if (version != 4) { log_error ("packet(%d) with unknown version %d\n", pkttype, version); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } if (pktlen > 200) { /* (we encode the seskeylen in a byte) */ log_error ("packet(%d) too large\n", pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } cipher_algo = iobuf_get_noeof (inp); pktlen--; s2kmode = iobuf_get_noeof (inp); pktlen--; hash_algo = iobuf_get_noeof (inp); pktlen--; switch (s2kmode) { case 0: /* Simple S2K. */ minlen = 0; break; case 1: /* Salted S2K. */ minlen = 8; break; case 3: /* Iterated+salted S2K. */ minlen = 9; break; default: log_error ("unknown S2K mode %d\n", s2kmode); goto leave; } if (minlen > pktlen) { log_error ("packet with S2K %d too short\n", s2kmode); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } seskeylen = pktlen - minlen; k = packet->pkt.symkey_enc = xmalloc_clear (sizeof *packet->pkt.symkey_enc + seskeylen - 1); k->version = version; k->cipher_algo = cipher_algo; k->s2k.mode = s2kmode; k->s2k.hash_algo = hash_algo; if (s2kmode == 1 || s2kmode == 3) { for (i = 0; i < 8 && pktlen; i++, pktlen--) k->s2k.salt[i] = iobuf_get_noeof (inp); } if (s2kmode == 3) { k->s2k.count = iobuf_get (inp); pktlen--; } k->seskeylen = seskeylen; if (k->seskeylen) { for (i = 0; i < seskeylen && pktlen; i++, pktlen--) k->seskey[i] = iobuf_get_noeof (inp); /* What we're watching out for here is a session key decryptor with no salt. The RFC says that using salt for this is a MUST. */ if (s2kmode != 1 && s2kmode != 3) log_info (_("WARNING: potentially insecure symmetrically" " encrypted session key\n")); } assert (!pktlen); if (list_mode) { - fprintf (listfp, - ":symkey enc packet: version %d, cipher %d, s2k %d, hash %d", - version, cipher_algo, s2kmode, hash_algo); + es_fprintf (listfp, + ":symkey enc packet: version %d, cipher %d, s2k %d, hash %d", + version, cipher_algo, s2kmode, hash_algo); if (seskeylen) - fprintf (listfp, ", seskey %d bits", (seskeylen - 1) * 8); - fprintf (listfp, "\n"); + es_fprintf (listfp, ", seskey %d bits", (seskeylen - 1) * 8); + es_fprintf (listfp, "\n"); if (s2kmode == 1 || s2kmode == 3) { - fprintf (listfp, "\tsalt "); - for (i = 0; i < 8; i++) - fprintf (listfp, "%02x", k->s2k.salt[i]); + es_fprintf (listfp, "\tsalt "); + es_write_hexstring (listfp, k->s2k.salt, 8, 0, NULL); if (s2kmode == 3) - fprintf (listfp, ", count %lu (%lu)", - S2K_DECODE_COUNT ((ulong) k->s2k.count), - (ulong) k->s2k.count); - fprintf (listfp, "\n"); + es_fprintf (listfp, ", count %lu (%lu)", + S2K_DECODE_COUNT ((ulong) k->s2k.count), + (ulong) k->s2k.count); + es_fprintf (listfp, "\n"); } } leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } static int parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet) { unsigned int n; int rc = 0; int i, ndata; PKT_pubkey_enc *k; k = packet->pkt.pubkey_enc = xmalloc_clear (sizeof *packet->pkt.pubkey_enc); if (pktlen < 12) { log_error ("packet(%d) too short\n", pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } k->version = iobuf_get_noeof (inp); pktlen--; if (k->version != 2 && k->version != 3) { log_error ("packet(%d) with unknown version %d\n", pkttype, k->version); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } k->keyid[0] = read_32 (inp); pktlen -= 4; k->keyid[1] = read_32 (inp); pktlen -= 4; k->pubkey_algo = iobuf_get_noeof (inp); pktlen--; k->throw_keyid = 0; /* Only used as flag for build_packet. */ if (list_mode) - fprintf (listfp, - ":pubkey enc packet: version %d, algo %d, keyid %08lX%08lX\n", - k->version, k->pubkey_algo, (ulong) k->keyid[0], - (ulong) k->keyid[1]); + es_fprintf (listfp, + ":pubkey enc packet: version %d, algo %d, keyid %08lX%08lX\n", + k->version, k->pubkey_algo, (ulong) k->keyid[0], + (ulong) k->keyid[1]); ndata = pubkey_get_nenc (k->pubkey_algo); if (!ndata) { if (list_mode) - fprintf (listfp, "\tunsupported algorithm %d\n", k->pubkey_algo); + es_fprintf (listfp, "\tunsupported algorithm %d\n", k->pubkey_algo); unknown_pubkey_warning (k->pubkey_algo); k->data[0] = NULL; /* No need to store the encrypted data. */ } else { for (i = 0; i < ndata; i++) { n = pktlen; k->data[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { - fprintf (listfp, "\tdata: "); + es_fprintf (listfp, "\tdata: "); mpi_print (listfp, k->data[i], mpi_print_mode); - putc ('\n', listfp); + es_putc ('\n', listfp); } if (!k->data[i]) rc = gpg_error (GPG_ERR_INV_PACKET); } } leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } static void dump_sig_subpkt (int hashed, int type, int critical, const byte * buffer, size_t buflen, size_t length) { const char *p = NULL; int i; /* The CERT has warning out with explains how to use GNUPG to detect * the ARRs - we print our old message here when it is a faked ARR * and add an additional notice. */ if (type == SIGSUBPKT_ARR && !hashed) { - fprintf (listfp, - "\tsubpkt %d len %u (additional recipient request)\n" - "WARNING: PGP versions > 5.0 and < 6.5.8 will automagically " - "encrypt to this key and thereby reveal the plaintext to " - "the owner of this ARR key. Detailed info follows:\n", - type, (unsigned) length); + es_fprintf (listfp, + "\tsubpkt %d len %u (additional recipient request)\n" + "WARNING: PGP versions > 5.0 and < 6.5.8 will automagically " + "encrypt to this key and thereby reveal the plaintext to " + "the owner of this ARR key. Detailed info follows:\n", + type, (unsigned) length); } buffer++; length--; - fprintf (listfp, "\t%s%ssubpkt %d len %u (", /*) */ - critical ? "critical " : "", - hashed ? "hashed " : "", type, (unsigned) length); + es_fprintf (listfp, "\t%s%ssubpkt %d len %u (", /*) */ + critical ? "critical " : "", + hashed ? "hashed " : "", type, (unsigned) length); if (length > buflen) { - fprintf (listfp, "too short: buffer is only %u)\n", (unsigned) buflen); + es_fprintf (listfp, "too short: buffer is only %u)\n", (unsigned) buflen); return; } switch (type) { case SIGSUBPKT_SIG_CREATED: if (length >= 4) - fprintf (listfp, "sig created %s", - strtimestamp (buffer_to_u32 (buffer))); + es_fprintf (listfp, "sig created %s", + strtimestamp (buffer_to_u32 (buffer))); break; case SIGSUBPKT_SIG_EXPIRE: if (length >= 4) { if (buffer_to_u32 (buffer)) - fprintf (listfp, "sig expires after %s", - strtimevalue (buffer_to_u32 (buffer))); + es_fprintf (listfp, "sig expires after %s", + strtimevalue (buffer_to_u32 (buffer))); else - fprintf (listfp, "sig does not expire"); + es_fprintf (listfp, "sig does not expire"); } break; case SIGSUBPKT_EXPORTABLE: if (length) - fprintf (listfp, "%sexportable", *buffer ? "" : "not "); + es_fprintf (listfp, "%sexportable", *buffer ? "" : "not "); break; case SIGSUBPKT_TRUST: if (length != 2) p = "[invalid trust subpacket]"; else - fprintf (listfp, "trust signature of depth %d, value %d", buffer[0], - buffer[1]); + es_fprintf (listfp, "trust signature of depth %d, value %d", buffer[0], + buffer[1]); break; case SIGSUBPKT_REGEXP: if (!length) p = "[invalid regexp subpacket]"; else - fprintf (listfp, "regular expression: \"%s\"", buffer); + es_fprintf (listfp, "regular expression: \"%s\"", buffer); break; case SIGSUBPKT_REVOCABLE: if (length) - fprintf (listfp, "%srevocable", *buffer ? "" : "not "); + es_fprintf (listfp, "%srevocable", *buffer ? "" : "not "); break; case SIGSUBPKT_KEY_EXPIRE: if (length >= 4) { if (buffer_to_u32 (buffer)) - fprintf (listfp, "key expires after %s", - strtimevalue (buffer_to_u32 (buffer))); + es_fprintf (listfp, "key expires after %s", + strtimevalue (buffer_to_u32 (buffer))); else - fprintf (listfp, "key does not expire"); + es_fprintf (listfp, "key does not expire"); } break; case SIGSUBPKT_PREF_SYM: - fputs ("pref-sym-algos:", listfp); + es_fputs ("pref-sym-algos:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %d", buffer[i]); + es_fprintf (listfp, " %d", buffer[i]); break; case SIGSUBPKT_REV_KEY: - fputs ("revocation key: ", listfp); + es_fputs ("revocation key: ", listfp); if (length < 22) p = "[too short]"; else { - fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]); + es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]); for (i = 2; i < length; i++) - fprintf (listfp, "%02X", buffer[i]); + es_fprintf (listfp, "%02X", buffer[i]); } break; case SIGSUBPKT_ISSUER: if (length >= 8) - fprintf (listfp, "issuer key ID %08lX%08lX", - (ulong) buffer_to_u32 (buffer), - (ulong) buffer_to_u32 (buffer + 4)); + es_fprintf (listfp, "issuer key ID %08lX%08lX", + (ulong) buffer_to_u32 (buffer), + (ulong) buffer_to_u32 (buffer + 4)); break; case SIGSUBPKT_NOTATION: { - fputs ("notation: ", listfp); + es_fputs ("notation: ", listfp); if (length < 8) p = "[too short]"; else { const byte *s = buffer; size_t n1, n2; n1 = (s[4] << 8) | s[5]; n2 = (s[6] << 8) | s[7]; s += 8; if (8 + n1 + n2 != length) p = "[error]"; else { - print_string (listfp, s, n1, ')'); - putc ('=', listfp); + es_write_sanitized (listfp, s, n1, ")", NULL); + es_putc ('=', listfp); if (*buffer & 0x80) - print_string (listfp, s + n1, n2, ')'); + es_write_sanitized (listfp, s + n1, n2, ")", NULL); else p = "[not human readable]"; } } } break; case SIGSUBPKT_PREF_HASH: - fputs ("pref-hash-algos:", listfp); + es_fputs ("pref-hash-algos:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %d", buffer[i]); + es_fprintf (listfp, " %d", buffer[i]); break; case SIGSUBPKT_PREF_COMPR: - fputs ("pref-zip-algos:", listfp); + es_fputs ("pref-zip-algos:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %d", buffer[i]); + es_fprintf (listfp, " %d", buffer[i]); break; case SIGSUBPKT_KS_FLAGS: - fputs ("key server preferences:", listfp); + es_fputs ("key server preferences:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %02X", buffer[i]); + es_fprintf (listfp, " %02X", buffer[i]); break; case SIGSUBPKT_PREF_KS: - fputs ("preferred key server: ", listfp); - print_string (listfp, buffer, length, ')'); + es_fputs ("preferred key server: ", listfp); + es_write_sanitized (listfp, buffer, length, ")", NULL); break; case SIGSUBPKT_PRIMARY_UID: p = "primary user ID"; break; case SIGSUBPKT_POLICY: - fputs ("policy: ", listfp); - print_string (listfp, buffer, length, ')'); + es_fputs ("policy: ", listfp); + es_write_sanitized (listfp, buffer, length, ")", NULL); break; case SIGSUBPKT_KEY_FLAGS: - fputs ("key flags:", listfp); + es_fputs ("key flags:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %02X", buffer[i]); + es_fprintf (listfp, " %02X", buffer[i]); break; case SIGSUBPKT_SIGNERS_UID: p = "signer's user ID"; break; case SIGSUBPKT_REVOC_REASON: if (length) { - fprintf (listfp, "revocation reason 0x%02x (", *buffer); - print_string (listfp, buffer + 1, length - 1, ')'); + es_fprintf (listfp, "revocation reason 0x%02x (", *buffer); + es_write_sanitized (listfp, buffer + 1, length - 1, ")", NULL); p = ")"; } break; case SIGSUBPKT_ARR: - fputs ("Big Brother's key (ignored): ", listfp); + es_fputs ("Big Brother's key (ignored): ", listfp); if (length < 22) p = "[too short]"; else { - fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]); - for (i = 2; i < length; i++) - fprintf (listfp, "%02X", buffer[i]); + es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]); + if (length > 2) + es_write_hexstring (listfp, buffer+2, length-2, 0, NULL); } break; case SIGSUBPKT_FEATURES: - fputs ("features:", listfp); + es_fputs ("features:", listfp); for (i = 0; i < length; i++) - fprintf (listfp, " %02x", buffer[i]); + es_fprintf (listfp, " %02x", buffer[i]); break; case SIGSUBPKT_SIGNATURE: - fputs ("signature: ", listfp); + es_fputs ("signature: ", listfp); if (length < 17) p = "[too short]"; else - fprintf (listfp, "v%d, class 0x%02X, algo %d, digest algo %d", - buffer[0], - buffer[0] == 3 ? buffer[2] : buffer[1], - buffer[0] == 3 ? buffer[15] : buffer[2], - buffer[0] == 3 ? buffer[16] : buffer[3]); + es_fprintf (listfp, "v%d, class 0x%02X, algo %d, digest algo %d", + buffer[0], + buffer[0] == 3 ? buffer[2] : buffer[1], + buffer[0] == 3 ? buffer[15] : buffer[2], + buffer[0] == 3 ? buffer[16] : buffer[3]); break; default: if (type >= 100 && type <= 110) p = "experimental / private subpacket"; else p = "?"; break; } - fprintf (listfp, "%s)\n", p ? p : ""); + es_fprintf (listfp, "%s)\n", p ? p : ""); } /* * Returns: >= 0 use this offset into buffer * -1 explicitly reject returning this type * -2 subpacket too short */ int parse_one_sig_subpkt (const byte * buffer, size_t n, int type) { switch (type) { case SIGSUBPKT_REV_KEY: if (n < 22) break; return 0; case SIGSUBPKT_SIG_CREATED: case SIGSUBPKT_SIG_EXPIRE: case SIGSUBPKT_KEY_EXPIRE: if (n < 4) break; return 0; case SIGSUBPKT_KEY_FLAGS: case SIGSUBPKT_KS_FLAGS: case SIGSUBPKT_PREF_SYM: case SIGSUBPKT_PREF_HASH: case SIGSUBPKT_PREF_COMPR: case SIGSUBPKT_POLICY: case SIGSUBPKT_PREF_KS: case SIGSUBPKT_FEATURES: case SIGSUBPKT_REGEXP: return 0; case SIGSUBPKT_SIGNATURE: case SIGSUBPKT_EXPORTABLE: case SIGSUBPKT_REVOCABLE: case SIGSUBPKT_REVOC_REASON: if (!n) break; return 0; case SIGSUBPKT_ISSUER: /* issuer key ID */ if (n < 8) break; return 0; case SIGSUBPKT_NOTATION: /* minimum length needed, and the subpacket must be well-formed where the name length and value length all fit inside the packet. */ if (n < 8 || 8 + ((buffer[4] << 8) | buffer[5]) + ((buffer[6] << 8) | buffer[7]) != n) break; return 0; case SIGSUBPKT_PRIMARY_UID: if (n != 1) break; return 0; case SIGSUBPKT_TRUST: if (n != 2) break; return 0; default: return 0; } return -2; } /* Return true if we understand the critical notation. */ static int can_handle_critical_notation (const byte * name, size_t len) { if (len == 32 && memcmp (name, "preferred-email-encoding@pgp.com", 32) == 0) return 1; if (len == 21 && memcmp (name, "pka-address@gnupg.org", 21) == 0) return 1; return 0; } static int can_handle_critical (const byte * buffer, size_t n, int type) { switch (type) { case SIGSUBPKT_NOTATION: if (n >= 8) return can_handle_critical_notation (buffer + 8, (buffer[4] << 8) | buffer[5]); else return 0; case SIGSUBPKT_SIGNATURE: case SIGSUBPKT_SIG_CREATED: case SIGSUBPKT_SIG_EXPIRE: case SIGSUBPKT_KEY_EXPIRE: case SIGSUBPKT_EXPORTABLE: case SIGSUBPKT_REVOCABLE: case SIGSUBPKT_REV_KEY: case SIGSUBPKT_ISSUER: /* issuer key ID */ case SIGSUBPKT_PREF_SYM: case SIGSUBPKT_PREF_HASH: case SIGSUBPKT_PREF_COMPR: case SIGSUBPKT_KEY_FLAGS: case SIGSUBPKT_PRIMARY_UID: case SIGSUBPKT_FEATURES: case SIGSUBPKT_TRUST: case SIGSUBPKT_REGEXP: /* Is it enough to show the policy or keyserver? */ case SIGSUBPKT_POLICY: case SIGSUBPKT_PREF_KS: return 1; default: return 0; } } const byte * enum_sig_subpkt (const subpktarea_t * pktbuf, sigsubpkttype_t reqtype, size_t * ret_n, int *start, int *critical) { const byte *buffer; int buflen; int type; int critical_dummy; int offset; size_t n; int seq = 0; int reqseq = start ? *start : 0; if (!critical) critical = &critical_dummy; if (!pktbuf || reqseq == -1) { /* return some value different from NULL to indicate that * there is no critical bit we do not understand. The caller * will never use the value. Yes I know, it is an ugly hack */ return reqtype == SIGSUBPKT_TEST_CRITICAL ? (const byte *) &pktbuf : NULL; } buffer = pktbuf->data; buflen = pktbuf->len; while (buflen) { n = *buffer++; buflen--; if (n == 255) /* 4 byte length header. */ { if (buflen < 4) goto too_short; n = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; buffer += 4; buflen -= 4; } else if (n >= 192) /* 4 byte special encoded length header. */ { if (buflen < 2) goto too_short; n = ((n - 192) << 8) + *buffer + 192; buffer++; buflen--; } if (buflen < n) goto too_short; type = *buffer; if (type & 0x80) { type &= 0x7f; *critical = 1; } else *critical = 0; if (!(++seq > reqseq)) ; else if (reqtype == SIGSUBPKT_TEST_CRITICAL) { if (*critical) { if (n - 1 > buflen + 1) goto too_short; if (!can_handle_critical (buffer + 1, n - 1, type)) { if (opt.verbose) log_info (_("subpacket of type %d has " "critical bit set\n"), type); if (start) *start = seq; return NULL; /* This is an error. */ } } } else if (reqtype < 0) /* List packets. */ dump_sig_subpkt (reqtype == SIGSUBPKT_LIST_HASHED, type, *critical, buffer, buflen, n); else if (type == reqtype) /* Found. */ { buffer++; n--; if (n > buflen) goto too_short; if (ret_n) *ret_n = n; offset = parse_one_sig_subpkt (buffer, n, type); switch (offset) { case -2: log_error ("subpacket of type %d too short\n", type); return NULL; case -1: return NULL; default: break; } if (start) *start = seq; return buffer + offset; } buffer += n; buflen -= n; } if (reqtype == SIGSUBPKT_TEST_CRITICAL) return buffer; /* Used as True to indicate that there is no. */ /* Critical bit we don't understand. */ if (start) *start = -1; return NULL; /* End of packets; not found. */ too_short: if (opt.verbose) log_info ("buffer shorter than subpacket\n"); if (start) *start = -1; return NULL; } const byte * parse_sig_subpkt (const subpktarea_t * buffer, sigsubpkttype_t reqtype, size_t * ret_n) { return enum_sig_subpkt (buffer, reqtype, ret_n, NULL, NULL); } const byte * parse_sig_subpkt2 (PKT_signature * sig, sigsubpkttype_t reqtype, size_t * ret_n) { const byte *p; p = parse_sig_subpkt (sig->hashed, reqtype, ret_n); if (!p) p = parse_sig_subpkt (sig->unhashed, reqtype, ret_n); return p; } /* Find all revocation keys. Look in hashed area only. */ void parse_revkeys (PKT_signature * sig) { struct revocation_key *revkey; int seq = 0; size_t len; if (sig->sig_class != 0x1F) return; while ((revkey = (struct revocation_key *) enum_sig_subpkt (sig->hashed, SIGSUBPKT_REV_KEY, &len, &seq, NULL))) { if (len == sizeof (struct revocation_key) && (revkey->class & 0x80)) /* 0x80 bit must be set. */ { sig->revkey = xrealloc (sig->revkey, sizeof (struct revocation_key *) * (sig->numrevkeys + 1)); sig->revkey[sig->numrevkeys] = revkey; sig->numrevkeys++; } } } int parse_signature (IOBUF inp, int pkttype, unsigned long pktlen, PKT_signature * sig) { int md5_len = 0; unsigned n; int is_v4 = 0; int rc = 0; int i, ndata; if (pktlen < 16) { log_error ("packet(%d) too short\n", pkttype); goto leave; } sig->version = iobuf_get_noeof (inp); pktlen--; if (sig->version == 4) is_v4 = 1; else if (sig->version != 2 && sig->version != 3) { log_error ("packet(%d) with unknown version %d\n", pkttype, sig->version); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } if (!is_v4) { md5_len = iobuf_get_noeof (inp); pktlen--; } sig->sig_class = iobuf_get_noeof (inp); pktlen--; if (!is_v4) { sig->timestamp = read_32 (inp); pktlen -= 4; sig->keyid[0] = read_32 (inp); pktlen -= 4; sig->keyid[1] = read_32 (inp); pktlen -= 4; } sig->pubkey_algo = iobuf_get_noeof (inp); pktlen--; sig->digest_algo = iobuf_get_noeof (inp); pktlen--; sig->flags.exportable = 1; sig->flags.revocable = 1; if (is_v4) /* Read subpackets. */ { n = read_16 (inp); pktlen -= 2; /* Length of hashed data. */ if (n > 10000) { log_error ("signature packet: hashed data too long\n"); rc = G10ERR_INVALID_PACKET; goto leave; } if (n) { sig->hashed = xmalloc (sizeof (*sig->hashed) + n - 1); sig->hashed->size = n; sig->hashed->len = n; if (iobuf_read (inp, sig->hashed->data, n) != n) { log_error ("premature eof while reading " "hashed signature data\n"); rc = -1; goto leave; } pktlen -= n; } n = read_16 (inp); pktlen -= 2; /* Length of unhashed data. */ if (n > 10000) { log_error ("signature packet: unhashed data too long\n"); rc = G10ERR_INVALID_PACKET; goto leave; } if (n) { sig->unhashed = xmalloc (sizeof (*sig->unhashed) + n - 1); sig->unhashed->size = n; sig->unhashed->len = n; if (iobuf_read (inp, sig->unhashed->data, n) != n) { log_error ("premature eof while reading " "unhashed signature data\n"); rc = -1; goto leave; } pktlen -= n; } } if (pktlen < 5) /* Sanity check. */ { log_error ("packet(%d) too short\n", pkttype); rc = G10ERR_INVALID_PACKET; goto leave; } sig->digest_start[0] = iobuf_get_noeof (inp); pktlen--; sig->digest_start[1] = iobuf_get_noeof (inp); pktlen--; if (is_v4 && sig->pubkey_algo) /* Extract required information. */ { const byte *p; size_t len; /* Set sig->flags.unknown_critical if there is a critical bit * set for packets which we do not understand. */ if (!parse_sig_subpkt (sig->hashed, SIGSUBPKT_TEST_CRITICAL, NULL) || !parse_sig_subpkt (sig->unhashed, SIGSUBPKT_TEST_CRITICAL, NULL)) sig->flags.unknown_critical = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_CREATED, NULL); if (p) sig->timestamp = buffer_to_u32 (p); else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110) && opt.verbose) log_info ("signature packet without timestamp\n"); p = parse_sig_subpkt2 (sig, SIGSUBPKT_ISSUER, NULL); if (p) { sig->keyid[0] = buffer_to_u32 (p); sig->keyid[1] = buffer_to_u32 (p + 4); } else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110) && opt.verbose) log_info ("signature packet without keyid\n"); p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL); if (p && buffer_to_u32 (p)) sig->expiredate = sig->timestamp + buffer_to_u32 (p); if (sig->expiredate && sig->expiredate <= make_timestamp ()) sig->flags.expired = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, NULL); if (p) sig->flags.policy_url = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, NULL); if (p) sig->flags.pref_ks = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_NOTATION, NULL); if (p) sig->flags.notation = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REVOCABLE, NULL); if (p && *p == 0) sig->flags.revocable = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_TRUST, &len); if (p && len == 2) { sig->trust_depth = p[0]; sig->trust_value = p[1]; /* Only look for a regexp if there is also a trust subpacket. */ sig->trust_regexp = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REGEXP, &len); /* If the regular expression is of 0 length, there is no regular expression. */ if (len == 0) sig->trust_regexp = NULL; } /* We accept the exportable subpacket from either the hashed or unhashed areas as older versions of gpg put it in the unhashed area. In theory, anyway, we should never see this packet off of a local keyring. */ p = parse_sig_subpkt2 (sig, SIGSUBPKT_EXPORTABLE, NULL); if (p && *p == 0) sig->flags.exportable = 0; /* Find all revocation keys. */ if (sig->sig_class == 0x1F) parse_revkeys (sig); } if (list_mode) { - fprintf (listfp, ":signature packet: algo %d, keyid %08lX%08lX\n" - "\tversion %d, created %lu, md5len %d, sigclass 0x%02x\n" - "\tdigest algo %d, begin of digest %02x %02x\n", - sig->pubkey_algo, - (ulong) sig->keyid[0], (ulong) sig->keyid[1], - sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class, - sig->digest_algo, sig->digest_start[0], sig->digest_start[1]); + es_fprintf (listfp, ":signature packet: algo %d, keyid %08lX%08lX\n" + "\tversion %d, created %lu, md5len %d, sigclass 0x%02x\n" + "\tdigest algo %d, begin of digest %02x %02x\n", + sig->pubkey_algo, + (ulong) sig->keyid[0], (ulong) sig->keyid[1], + sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class, + sig->digest_algo, sig->digest_start[0], sig->digest_start[1]); if (is_v4) { parse_sig_subpkt (sig->hashed, SIGSUBPKT_LIST_HASHED, NULL); parse_sig_subpkt (sig->unhashed, SIGSUBPKT_LIST_UNHASHED, NULL); } } ndata = pubkey_get_nsig (sig->pubkey_algo); if (!ndata) { if (list_mode) - fprintf (listfp, "\tunknown algorithm %d\n", sig->pubkey_algo); + es_fprintf (listfp, "\tunknown algorithm %d\n", sig->pubkey_algo); unknown_pubkey_warning (sig->pubkey_algo); /* We store the plain material in data[0], so that we are able * to write it back with build_packet(). */ if (pktlen > (5 * MAX_EXTERN_MPI_BITS / 8)) { /* We include a limit to avoid too trivial DoS attacks by having gpg allocate too much memory. */ log_error ("signature packet: too much data\n"); rc = G10ERR_INVALID_PACKET; } else { sig->data[0] = gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen, 0), pktlen * 8); pktlen = 0; } } else { for (i = 0; i < ndata; i++) { n = pktlen; sig->data[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { - fprintf (listfp, "\tdata: "); + es_fprintf (listfp, "\tdata: "); mpi_print (listfp, sig->data[i], mpi_print_mode); - putc ('\n', listfp); + es_putc ('\n', listfp); } if (!sig->data[i]) rc = G10ERR_INVALID_PACKET; } } leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } static int parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen, PKT_onepass_sig * ops) { int version; int rc = 0; if (pktlen < 13) { log_error ("packet(%d) too short\n", pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } version = iobuf_get_noeof (inp); pktlen--; if (version != 3) { log_error ("onepass_sig with unknown version %d\n", version); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } ops->sig_class = iobuf_get_noeof (inp); pktlen--; ops->digest_algo = iobuf_get_noeof (inp); pktlen--; ops->pubkey_algo = iobuf_get_noeof (inp); pktlen--; ops->keyid[0] = read_32 (inp); pktlen -= 4; ops->keyid[1] = read_32 (inp); pktlen -= 4; ops->last = iobuf_get_noeof (inp); pktlen--; if (list_mode) - fprintf (listfp, - ":onepass_sig packet: keyid %08lX%08lX\n" - "\tversion %d, sigclass 0x%02x, digest %d, pubkey %d, " - "last=%d\n", - (ulong) ops->keyid[0], (ulong) ops->keyid[1], - version, ops->sig_class, - ops->digest_algo, ops->pubkey_algo, ops->last); + es_fprintf (listfp, + ":onepass_sig packet: keyid %08lX%08lX\n" + "\tversion %d, sigclass 0x%02x, digest %d, pubkey %d, " + "last=%d\n", + (ulong) ops->keyid[0], (ulong) ops->keyid[1], + version, ops->sig_class, + ops->digest_algo, ops->pubkey_algo, ops->last); leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } static gcry_mpi_t read_protected_v3_mpi (IOBUF inp, unsigned long *length) { int c; unsigned int nbits, nbytes; unsigned char *buf, *p; gcry_mpi_t val; if (*length < 2) { log_error ("mpi too small\n"); return NULL; } if ((c = iobuf_get (inp)) == -1) return NULL; --*length; nbits = c << 8; if ((c = iobuf_get (inp)) == -1) return NULL; --*length; nbits |= c; if (nbits > 16384) { log_error ("mpi too large (%u bits)\n", nbits); return NULL; } nbytes = (nbits + 7) / 8; buf = p = xmalloc (2 + nbytes); *p++ = nbits >> 8; *p++ = nbits; for (; nbytes && *length; nbytes--, --*length) *p++ = iobuf_get (inp); if (nbytes) { log_error ("packet shorter than mpi\n"); xfree (buf); return NULL; } /* Convert buffer into an opaque MPI. */ val = gcry_mpi_set_opaque (NULL, buf, (p - buf) * 8); return val; } static int parse_key (IOBUF inp, int pkttype, unsigned long pktlen, byte * hdr, int hdrlen, PACKET * pkt) { int i, version, algorithm; unsigned n; unsigned long timestamp, expiredate, max_expiredate; int npkey, nskey; int is_v4 = 0; int rc = 0; u32 keyid[2]; (void) hdr; version = iobuf_get_noeof (inp); pktlen--; if (pkttype == PKT_PUBLIC_SUBKEY && version == '#') { /* Early versions of G10 used the old PGP comments packets; * luckily all those comments are started by a hash. */ if (list_mode) { - fprintf (listfp, ":rfc1991 comment packet: \""); + es_fprintf (listfp, ":rfc1991 comment packet: \""); for (; pktlen; pktlen--) { int c; c = iobuf_get_noeof (inp); if (c >= ' ' && c <= 'z') - putc (c, listfp); + es_putc (c, listfp); else - fprintf (listfp, "\\x%02x", c); + es_fprintf (listfp, "\\x%02x", c); } - fprintf (listfp, "\"\n"); + es_fprintf (listfp, "\"\n"); } iobuf_skip_rest (inp, pktlen, 0); return 0; } else if (version == 4) is_v4 = 1; else if (version != 2 && version != 3) { log_error ("packet(%d) with unknown version %d\n", pkttype, version); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } if (pktlen < 11) { log_error ("packet(%d) too short\n", pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } timestamp = read_32 (inp); pktlen -= 4; if (is_v4) { expiredate = 0; /* have to get it from the selfsignature */ max_expiredate = 0; } else { unsigned short ndays; ndays = read_16 (inp); pktlen -= 2; if (ndays) expiredate = timestamp + ndays * 86400L; else expiredate = 0; max_expiredate = expiredate; } algorithm = iobuf_get_noeof (inp); pktlen--; if (list_mode) - fprintf (listfp, ":%s key packet:\n" - "\tversion %d, algo %d, created %lu, expires %lu\n", - pkttype == PKT_PUBLIC_KEY ? "public" : - pkttype == PKT_SECRET_KEY ? "secret" : - pkttype == PKT_PUBLIC_SUBKEY ? "public sub" : - pkttype == PKT_SECRET_SUBKEY ? "secret sub" : "??", - version, algorithm, timestamp, expiredate); + es_fprintf (listfp, ":%s key packet:\n" + "\tversion %d, algo %d, created %lu, expires %lu\n", + pkttype == PKT_PUBLIC_KEY ? "public" : + pkttype == PKT_SECRET_KEY ? "secret" : + pkttype == PKT_PUBLIC_SUBKEY ? "public sub" : + pkttype == PKT_SECRET_SUBKEY ? "secret sub" : "??", + version, algorithm, timestamp, expiredate); if (pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY) { PKT_secret_key *sk = pkt->pkt.secret_key; sk->timestamp = timestamp; sk->expiredate = expiredate; sk->max_expiredate = max_expiredate; sk->hdrbytes = hdrlen; sk->version = version; sk->is_primary = pkttype == PKT_SECRET_KEY; sk->pubkey_algo = algorithm; sk->req_usage = 0; sk->pubkey_usage = 0; /* not yet used */ } else { PKT_public_key *pk = pkt->pkt.public_key; pk->timestamp = timestamp; pk->expiredate = expiredate; pk->max_expiredate = max_expiredate; pk->hdrbytes = hdrlen; pk->version = version; pk->is_primary = pkttype == PKT_PUBLIC_KEY; pk->pubkey_algo = algorithm; pk->req_usage = 0; pk->pubkey_usage = 0; /* not yet used */ pk->is_revoked = 0; pk->is_disabled = 0; pk->keyid[0] = 0; pk->keyid[1] = 0; } nskey = pubkey_get_nskey (algorithm); npkey = pubkey_get_npkey (algorithm); if (!npkey) { if (list_mode) - fprintf (listfp, "\tunknown algorithm %d\n", algorithm); + es_fprintf (listfp, "\tunknown algorithm %d\n", algorithm); unknown_pubkey_warning (algorithm); } if (pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY) { PKT_secret_key *sk = pkt->pkt.secret_key; byte temp[16]; size_t snlen = 0; if (!npkey) { sk->skey[0] = gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen, 0), pktlen * 8); pktlen = 0; goto leave; } for (i = 0; i < npkey; i++) { n = pktlen; sk->skey[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { - fprintf (listfp, "\tskey[%d]: ", i); + es_fprintf (listfp, "\tskey[%d]: ", i); mpi_print (listfp, sk->skey[i], mpi_print_mode); - putc ('\n', listfp); + es_putc ('\n', listfp); } if (!sk->skey[i]) rc = G10ERR_INVALID_PACKET; } if (rc) /* One of the MPIs were bad. */ goto leave; sk->protect.algo = iobuf_get_noeof (inp); pktlen--; sk->protect.sha1chk = 0; if (sk->protect.algo) { sk->is_protected = 1; sk->protect.s2k.count = 0; if (sk->protect.algo == 254 || sk->protect.algo == 255) { if (pktlen < 3) { rc = G10ERR_INVALID_PACKET; goto leave; } sk->protect.sha1chk = (sk->protect.algo == 254); sk->protect.algo = iobuf_get_noeof (inp); pktlen--; /* Note that a sk->protect.algo > 110 is illegal, but I'm not erroring on it here as otherwise there would be no way to delete such a key. */ sk->protect.s2k.mode = iobuf_get_noeof (inp); pktlen--; sk->protect.s2k.hash_algo = iobuf_get_noeof (inp); pktlen--; /* check for the special GNU extension */ if (is_v4 && sk->protect.s2k.mode == 101) { for (i = 0; i < 4 && pktlen; i++, pktlen--) temp[i] = iobuf_get_noeof (inp); if (i < 4 || memcmp (temp, "GNU", 3)) { if (list_mode) - fprintf (listfp, "\tunknown S2K %d\n", - sk->protect.s2k.mode); + es_fprintf (listfp, "\tunknown S2K %d\n", + sk->protect.s2k.mode); rc = G10ERR_INVALID_PACKET; goto leave; } /* Here we know that it is a GNU extension. What * follows is the GNU protection mode: All values * have special meanings and they are mapped to MODE * with a base of 1000. */ sk->protect.s2k.mode = 1000 + temp[3]; } switch (sk->protect.s2k.mode) { case 1: case 3: for (i = 0; i < 8 && pktlen; i++, pktlen--) temp[i] = iobuf_get_noeof (inp); memcpy (sk->protect.s2k.salt, temp, 8); break; } switch (sk->protect.s2k.mode) { case 0: if (list_mode) - fprintf (listfp, "\tsimple S2K"); + es_fprintf (listfp, "\tsimple S2K"); break; case 1: if (list_mode) - fprintf (listfp, "\tsalted S2K"); + es_fprintf (listfp, "\tsalted S2K"); break; case 3: if (list_mode) - fprintf (listfp, "\titer+salt S2K"); + es_fprintf (listfp, "\titer+salt S2K"); break; case 1001: if (list_mode) - fprintf (listfp, "\tgnu-dummy S2K"); + es_fprintf (listfp, "\tgnu-dummy S2K"); break; case 1002: if (list_mode) - fprintf (listfp, "\tgnu-divert-to-card S2K"); + es_fprintf (listfp, "\tgnu-divert-to-card S2K"); break; default: if (list_mode) - fprintf (listfp, "\tunknown %sS2K %d\n", - sk->protect.s2k.mode < 1000 ? "" : "GNU ", - sk->protect.s2k.mode); + es_fprintf (listfp, "\tunknown %sS2K %d\n", + sk->protect.s2k.mode < 1000 ? "" : "GNU ", + sk->protect.s2k.mode); rc = G10ERR_INVALID_PACKET; goto leave; } if (list_mode) { - fprintf (listfp, ", algo: %d,%s hash: %d", - sk->protect.algo, - sk->protect.sha1chk ? " SHA1 protection," - : " simple checksum,", sk->protect.s2k.hash_algo); + es_fprintf (listfp, ", algo: %d,%s hash: %d", + sk->protect.algo, + sk->protect.sha1chk ? " SHA1 protection," + : " simple checksum,", sk->protect.s2k.hash_algo); if (sk->protect.s2k.mode == 1 || sk->protect.s2k.mode == 3) { - fprintf (listfp, ", salt: "); - for (i = 0; i < 8; i++) - fprintf (listfp, "%02x", sk->protect.s2k.salt[i]); + es_fprintf (listfp, ", salt: "); + es_write_hexstring (listfp, sk->protect.s2k.salt, 8, + 0, NULL); } - putc ('\n', listfp); + es_putc ('\n', listfp); } if (sk->protect.s2k.mode == 3) { if (pktlen < 1) { rc = G10ERR_INVALID_PACKET; goto leave; } sk->protect.s2k.count = iobuf_get (inp); pktlen--; if (list_mode) - fprintf (listfp, "\tprotect count: %lu\n", - (ulong) sk->protect.s2k.count); + es_fprintf (listfp, "\tprotect count: %lu\n", + (ulong) sk->protect.s2k.count); } else if (sk->protect.s2k.mode == 1002) { /* Read the serial number. */ if (pktlen < 1) { rc = G10ERR_INVALID_PACKET; goto leave; } snlen = iobuf_get (inp); pktlen--; if (pktlen < snlen || snlen == -1) { rc = G10ERR_INVALID_PACKET; goto leave; } } } else /* Old version; no S2K, so we set mode to 0, hash MD5. */ { /* Note that a sk->protect.algo > 110 is illegal, but I'm not erroring on it here as otherwise there would be no way to delete such a key. */ sk->protect.s2k.mode = 0; sk->protect.s2k.hash_algo = DIGEST_ALGO_MD5; if (list_mode) - fprintf (listfp, "\tprotect algo: %d (hash algo: %d)\n", - sk->protect.algo, sk->protect.s2k.hash_algo); + es_fprintf (listfp, "\tprotect algo: %d (hash algo: %d)\n", + sk->protect.algo, sk->protect.s2k.hash_algo); } /* It is really ugly that we don't know the size * of the IV here in cases we are not aware of the algorithm. * so a * sk->protect.ivlen = cipher_get_blocksize(sk->protect.algo); * won't work. The only solution I see is to hardwire it. * NOTE: if you change the ivlen above 16, don't forget to * enlarge temp. */ sk->protect.ivlen = openpgp_cipher_blocklen (sk->protect.algo); assert (sk->protect.ivlen <= sizeof (temp)); if (sk->protect.s2k.mode == 1001) sk->protect.ivlen = 0; else if (sk->protect.s2k.mode == 1002) sk->protect.ivlen = snlen < 16 ? snlen : 16; if (pktlen < sk->protect.ivlen) { rc = G10ERR_INVALID_PACKET; goto leave; } for (i = 0; i < sk->protect.ivlen && pktlen; i++, pktlen--) temp[i] = iobuf_get_noeof (inp); if (list_mode) { - fprintf (listfp, + es_fprintf (listfp, sk->protect.s2k.mode == 1002 ? "\tserial-number: " : "\tprotect IV: "); for (i = 0; i < sk->protect.ivlen; i++) - fprintf (listfp, " %02x", temp[i]); - putc ('\n', listfp); + es_fprintf (listfp, " %02x", temp[i]); + es_putc ('\n', listfp); } memcpy (sk->protect.iv, temp, sk->protect.ivlen); } else sk->is_protected = 0; /* It does not make sense to read it into secure memory. * If the user is so careless, not to protect his secret key, * we can assume, that he operates an open system :=(. * So we put the key into secure memory when we unprotect it. */ if (sk->protect.s2k.mode == 1001 || sk->protect.s2k.mode == 1002) { /* Better set some dummy stuff here. */ sk->skey[npkey] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10 * 8); pktlen = 0; } else if (is_v4 && sk->is_protected) { /* Ugly: The length is encrypted too, so we read all stuff * up to the end of the packet into the first SKEY * element. */ sk->skey[npkey] = gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen, 0), pktlen * 8); pktlen = 0; if (list_mode) { - fprintf (listfp, "\tencrypted stuff follows\n"); + es_fprintf (listfp, "\tencrypted stuff follows\n"); } } else /* The v3 method: The mpi length is not encrypted. */ { for (i = npkey; i < nskey; i++) { if (sk->is_protected) { sk->skey[i] = read_protected_v3_mpi (inp, &pktlen); if (list_mode) - fprintf (listfp, "\tskey[%d]: [encrypted]\n", i); + es_fprintf (listfp, "\tskey[%d]: [encrypted]\n", i); } else { n = pktlen; sk->skey[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { - fprintf (listfp, "\tskey[%d]: ", i); + es_fprintf (listfp, "\tskey[%d]: ", i); mpi_print (listfp, sk->skey[i], mpi_print_mode); - putc ('\n', listfp); + es_putc ('\n', listfp); } } if (!sk->skey[i]) rc = G10ERR_INVALID_PACKET; } if (rc) goto leave; sk->csum = read_16 (inp); pktlen -= 2; if (list_mode) { - fprintf (listfp, "\tchecksum: %04hx\n", sk->csum); + es_fprintf (listfp, "\tchecksum: %04hx\n", sk->csum); } } if (list_mode) keyid_from_sk (sk, keyid); } else { PKT_public_key *pk = pkt->pkt.public_key; if (!npkey) { pk->pkey[0] = gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen, 0), pktlen * 8); pktlen = 0; goto leave; } for (i = 0; i < npkey; i++) { n = pktlen; pk->pkey[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { - fprintf (listfp, "\tpkey[%d]: ", i); + es_fprintf (listfp, "\tpkey[%d]: ", i); mpi_print (listfp, pk->pkey[i], mpi_print_mode); - putc ('\n', listfp); + es_putc ('\n', listfp); } if (!pk->pkey[i]) rc = G10ERR_INVALID_PACKET; } if (rc) goto leave; if (list_mode) keyid_from_pk (pk, keyid); } if (list_mode) - fprintf (listfp, "\tkeyid: %08lX%08lX\n", - (ulong) keyid[0], (ulong) keyid[1]); + es_fprintf (listfp, "\tkeyid: %08lX%08lX\n", + (ulong) keyid[0], (ulong) keyid[1]); leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } /* Attribute subpackets have the same format as v4 signature subpackets. This is not part of OpenPGP, but is done in several versions of PGP nevertheless. */ int parse_attribute_subpkts (PKT_user_id * uid) { size_t n; int count = 0; struct user_attribute *attribs = NULL; const byte *buffer = uid->attrib_data; int buflen = uid->attrib_len; byte type; xfree (uid->attribs); while (buflen) { n = *buffer++; buflen--; if (n == 255) /* 4 byte length header. */ { if (buflen < 4) goto too_short; n = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; buffer += 4; buflen -= 4; } else if (n >= 192) /* 2 byte special encoded length header. */ { if (buflen < 2) goto too_short; n = ((n - 192) << 8) + *buffer + 192; buffer++; buflen--; } if (buflen < n) goto too_short; attribs = xrealloc (attribs, (count + 1) * sizeof (struct user_attribute)); memset (&attribs[count], 0, sizeof (struct user_attribute)); type = *buffer; buffer++; buflen--; n--; attribs[count].type = type; attribs[count].data = buffer; attribs[count].len = n; buffer += n; buflen -= n; count++; } uid->attribs = attribs; uid->numattribs = count; return count; too_short: if (opt.verbose) log_info ("buffer shorter than attribute subpacket\n"); uid->attribs = attribs; uid->numattribs = count; return count; } static int parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet) { byte *p; /* Cap the size of a user ID at 2k: a value absurdly large enough that there is no sane user ID string (which is printable text as of RFC2440bis) that won't fit in it, but yet small enough to avoid allocation problems. A large pktlen may not be allocatable, and a very large pktlen could actually cause our allocation to wrap around in xmalloc to a small number. */ if (pktlen > 2048) { log_error ("packet(%d) too large\n", pkttype); iobuf_skip_rest (inp, pktlen, 0); return G10ERR_INVALID_PACKET; } packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id + pktlen); packet->pkt.user_id->len = pktlen; packet->pkt.user_id->ref = 1; p = packet->pkt.user_id->name; for (; pktlen; pktlen--, p++) *p = iobuf_get_noeof (inp); *p = 0; if (list_mode) { int n = packet->pkt.user_id->len; - fprintf (listfp, ":user ID packet: \""); - /* fixme: Hey why don't we replace this with print_string?? */ + es_fprintf (listfp, ":user ID packet: \""); + /* fixme: Hey why don't we replace this with es_write_sanitized?? */ for (p = packet->pkt.user_id->name; n; p++, n--) { if (*p >= ' ' && *p <= 'z') - putc (*p, listfp); + es_putc (*p, listfp); else - fprintf (listfp, "\\x%02x", *p); + es_fprintf (listfp, "\\x%02x", *p); } - fprintf (listfp, "\"\n"); + es_fprintf (listfp, "\"\n"); } return 0; } void make_attribute_uidname (PKT_user_id * uid, size_t max_namelen) { assert (max_namelen > 70); if (uid->numattribs <= 0) sprintf (uid->name, "[bad attribute packet of size %lu]", uid->attrib_len); else if (uid->numattribs > 1) sprintf (uid->name, "[%d attributes of size %lu]", uid->numattribs, uid->attrib_len); else { /* Only one attribute, so list it as the "user id" */ if (uid->attribs->type == ATTRIB_IMAGE) { u32 len; byte type; if (parse_image_header (uid->attribs, &type, &len)) sprintf (uid->name, "[%.20s image of size %lu]", image_type_to_string (type, 1), (ulong) len); else sprintf (uid->name, "[invalid image]"); } else sprintf (uid->name, "[unknown attribute of size %lu]", (ulong) uid->attribs->len); } uid->len = strlen (uid->name); } static int parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet) { byte *p; (void) pkttype; #define EXTRA_UID_NAME_SPACE 71 packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id + EXTRA_UID_NAME_SPACE); packet->pkt.user_id->ref = 1; packet->pkt.user_id->attrib_data = xmalloc (pktlen); packet->pkt.user_id->attrib_len = pktlen; p = packet->pkt.user_id->attrib_data; for (; pktlen; pktlen--, p++) *p = iobuf_get_noeof (inp); /* Now parse out the individual attribute subpackets. This is somewhat pointless since there is only one currently defined attribute type (jpeg), but it is correct by the spec. */ parse_attribute_subpkts (packet->pkt.user_id); make_attribute_uidname (packet->pkt.user_id, EXTRA_UID_NAME_SPACE); if (list_mode) { - fprintf (listfp, ":attribute packet: %s\n", packet->pkt.user_id->name); + es_fprintf (listfp, ":attribute packet: %s\n", packet->pkt.user_id->name); } return 0; } static int parse_comment (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet) { byte *p; /* Cap comment packet at a reasonable value to avoid an integer overflow in the malloc below. Comment packets are actually not anymore define my OpenPGP and we even stopped to use our private comment packet. */ if (pktlen > 65536) { log_error ("packet(%d) too large\n", pkttype); iobuf_skip_rest (inp, pktlen, 0); return G10ERR_INVALID_PACKET; } packet->pkt.comment = xmalloc (sizeof *packet->pkt.comment + pktlen - 1); packet->pkt.comment->len = pktlen; p = packet->pkt.comment->data; for (; pktlen; pktlen--, p++) *p = iobuf_get_noeof (inp); if (list_mode) { int n = packet->pkt.comment->len; - fprintf (listfp, ":%scomment packet: \"", pkttype == PKT_OLD_COMMENT ? - "OpenPGP draft " : ""); + es_fprintf (listfp, ":%scomment packet: \"", pkttype == PKT_OLD_COMMENT ? + "OpenPGP draft " : ""); for (p = packet->pkt.comment->data; n; p++, n--) { if (*p >= ' ' && *p <= 'z') - putc (*p, listfp); + es_putc (*p, listfp); else - fprintf (listfp, "\\x%02x", *p); + es_fprintf (listfp, "\\x%02x", *p); } - fprintf (listfp, "\"\n"); + es_fprintf (listfp, "\"\n"); } return 0; } static void parse_trust (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt) { int c; (void) pkttype; if (pktlen) { c = iobuf_get_noeof (inp); pktlen--; pkt->pkt.ring_trust = xmalloc (sizeof *pkt->pkt.ring_trust); pkt->pkt.ring_trust->trustval = c; pkt->pkt.ring_trust->sigcache = 0; if (!c && pktlen == 1) { c = iobuf_get_noeof (inp); pktlen--; /* We require that bit 7 of the sigcache is 0 (easier eof handling). */ if (!(c & 0x80)) pkt->pkt.ring_trust->sigcache = c; } if (list_mode) - fprintf (listfp, ":trust packet: flag=%02x sigcache=%02x\n", - pkt->pkt.ring_trust->trustval, - pkt->pkt.ring_trust->sigcache); + es_fprintf (listfp, ":trust packet: flag=%02x sigcache=%02x\n", + pkt->pkt.ring_trust->trustval, + pkt->pkt.ring_trust->sigcache); } else { if (list_mode) - fprintf (listfp, ":trust packet: empty\n"); + es_fprintf (listfp, ":trust packet: empty\n"); } iobuf_skip_rest (inp, pktlen, 0); } static int parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt, int new_ctb, int partial) { int rc = 0; int mode, namelen; PKT_plaintext *pt; byte *p; int c, i; if (!partial && pktlen < 6) { log_error ("packet(%d) too short (%lu)\n", pkttype, (ulong) pktlen); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } mode = iobuf_get_noeof (inp); if (pktlen) pktlen--; namelen = iobuf_get_noeof (inp); if (pktlen) pktlen--; /* Note that namelen will never exceed 255 bytes. */ pt = pkt->pkt.plaintext = xmalloc (sizeof *pkt->pkt.plaintext + namelen - 1); pt->new_ctb = new_ctb; pt->mode = mode; pt->namelen = namelen; pt->is_partial = partial; if (pktlen) { for (i = 0; pktlen > 4 && i < namelen; pktlen--, i++) pt->name[i] = iobuf_get_noeof (inp); } else { for (i = 0; i < namelen; i++) if ((c = iobuf_get (inp)) == -1) break; else pt->name[i] = c; } pt->timestamp = read_32 (inp); if (pktlen) pktlen -= 4; pt->len = pktlen; pt->buf = inp; pktlen = 0; if (list_mode) { - fprintf (listfp, ":literal data packet:\n" - "\tmode %c (%X), created %lu, name=\"", - mode >= ' ' && mode < 'z' ? mode : '?', mode, - (ulong) pt->timestamp); + es_fprintf (listfp, ":literal data packet:\n" + "\tmode %c (%X), created %lu, name=\"", + mode >= ' ' && mode < 'z' ? mode : '?', mode, + (ulong) pt->timestamp); for (p = pt->name, i = 0; i < namelen; p++, i++) { if (*p >= ' ' && *p <= 'z') - putc (*p, listfp); + es_putc (*p, listfp); else - fprintf (listfp, "\\x%02x", *p); + es_fprintf (listfp, "\\x%02x", *p); } - fprintf (listfp, "\",\n\traw data: "); + es_fprintf (listfp, "\",\n\traw data: "); if (partial) - fprintf (listfp, "unknown length\n"); + es_fprintf (listfp, "unknown length\n"); else - fprintf (listfp, "%lu bytes\n", (ulong) pt->len); + es_fprintf (listfp, "%lu bytes\n", (ulong) pt->len); } leave: return rc; } static int parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt, int new_ctb) { PKT_compressed *zd; /* PKTLEN is here 0, but data follows (this should be the last object in a file or the compress algorithm should know the length). */ (void) pkttype; (void) pktlen; zd = pkt->pkt.compressed = xmalloc (sizeof *pkt->pkt.compressed); zd->algorithm = iobuf_get_noeof (inp); zd->len = 0; /* not used */ zd->new_ctb = new_ctb; zd->buf = inp; if (list_mode) - fprintf (listfp, ":compressed packet: algo=%d\n", zd->algorithm); + es_fprintf (listfp, ":compressed packet: algo=%d\n", zd->algorithm); return 0; } static int parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt, int new_ctb, int partial) { int rc = 0; PKT_encrypted *ed; unsigned long orig_pktlen = pktlen; ed = pkt->pkt.encrypted = xmalloc (sizeof *pkt->pkt.encrypted); /* ed->len is set below. */ ed->extralen = 0; /* Unknown here; only used in build_packet. */ ed->buf = NULL; ed->new_ctb = new_ctb; ed->is_partial = partial; if (pkttype == PKT_ENCRYPTED_MDC) { /* Fixme: add some pktlen sanity checks. */ int version; version = iobuf_get_noeof (inp); if (orig_pktlen) pktlen--; if (version != 1) { log_error ("encrypted_mdc packet with unknown version %d\n", version); /*skip_rest(inp, pktlen); should we really do this? */ rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } ed->mdc_method = DIGEST_ALGO_SHA1; } else ed->mdc_method = 0; /* A basic sanity check. We need at least an 8 byte IV plus the 2 detection bytes. Note that we don't known the algorithm and thus we may only check against the minimum blocksize. */ if (orig_pktlen && pktlen < 10) { /* Actually this is blocksize+2. */ log_error ("packet(%d) too short\n", pkttype); rc = G10ERR_INVALID_PACKET; iobuf_skip_rest (inp, pktlen, partial); goto leave; } /* Store the remaining length of the encrypted data (i.e. without the MDC version number but with the IV etc.). This value is required during decryption. */ ed->len = pktlen; if (list_mode) { if (orig_pktlen) - fprintf (listfp, ":encrypted data packet:\n\tlength: %lu\n", - orig_pktlen); + es_fprintf (listfp, ":encrypted data packet:\n\tlength: %lu\n", + orig_pktlen); else - fprintf (listfp, ":encrypted data packet:\n\tlength: unknown\n"); + es_fprintf (listfp, ":encrypted data packet:\n\tlength: unknown\n"); if (ed->mdc_method) - fprintf (listfp, "\tmdc_method: %d\n", ed->mdc_method); + es_fprintf (listfp, "\tmdc_method: %d\n", ed->mdc_method); } ed->buf = inp; leave: return rc; } /* Note, that this code is not anymore used in real life because the MDC checking is now done right after the decryption in decrypt_data. */ static int parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt, int new_ctb) { int rc = 0; PKT_mdc *mdc; byte *p; (void) pkttype; mdc = pkt->pkt.mdc = xmalloc (sizeof *pkt->pkt.mdc); if (list_mode) - fprintf (listfp, ":mdc packet: length=%lu\n", pktlen); + es_fprintf (listfp, ":mdc packet: length=%lu\n", pktlen); if (!new_ctb || pktlen != 20) { log_error ("mdc_packet with invalid encoding\n"); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } p = mdc->hash; for (; pktlen; pktlen--, p++) *p = iobuf_get_noeof (inp); leave: return rc; } /* * This packet is internally generated by us (ibn armor.c) to transfer * some information to the lower layer. To make sure that this packet * is really a GPG faked one and not one comming from outside, we * first check that there is a unique tag in it. * * The format of such a control packet is: * n byte session marker * 1 byte control type CTRLPKT_xxxxx * m byte control data */ static int parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet, int partial) { byte *p; const byte *sesmark; size_t sesmarklen; int i; (void) pkttype; if (list_mode) - fprintf (listfp, ":packet 63: length %lu ", pktlen); + es_fprintf (listfp, ":packet 63: length %lu ", pktlen); sesmark = get_session_marker (&sesmarklen); if (pktlen < sesmarklen + 1) /* 1 is for the control bytes */ goto skipit; for (i = 0; i < sesmarklen; i++, pktlen--) { if (sesmark[i] != iobuf_get_noeof (inp)) goto skipit; } if (pktlen > 4096) goto skipit; /* Definitely too large. We skip it to avoid an overflow in the malloc. */ if (list_mode) puts ("- gpg control packet"); packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control + pktlen - 1); packet->pkt.gpg_control->control = iobuf_get_noeof (inp); pktlen--; packet->pkt.gpg_control->datalen = pktlen; p = packet->pkt.gpg_control->data; for (; pktlen; pktlen--, p++) *p = iobuf_get_noeof (inp); return 0; skipit: if (list_mode) { int c; i = 0; - fprintf (listfp, "- private (rest length %lu)\n", pktlen); + es_fprintf (listfp, "- private (rest length %lu)\n", pktlen); if (partial) { while ((c = iobuf_get (inp)) != -1) dump_hex_line (c, &i); } else { for (; pktlen; pktlen--) { dump_hex_line ((c = iobuf_get (inp)), &i); if (c == -1) break; } } - putc ('\n', listfp); + es_putc ('\n', listfp); } iobuf_skip_rest (inp, pktlen, 0); return gpg_error (GPG_ERR_INV_PACKET); } /* Create a GPG control packet to be used internally as a placeholder. */ PACKET * create_gpg_control (ctrlpkttype_t type, const byte * data, size_t datalen) { PACKET *packet; byte *p; packet = xmalloc (sizeof *packet); init_packet (packet); packet->pkttype = PKT_GPG_CONTROL; packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control + datalen - 1); packet->pkt.gpg_control->control = type; packet->pkt.gpg_control->datalen = datalen; p = packet->pkt.gpg_control->data; for (; datalen; datalen--, p++) *p = *data++; return packet; } diff --git a/g10/pkclist.c b/g10/pkclist.c index cbc76c76d..ca5624a4b 100644 --- a/g10/pkclist.c +++ b/g10/pkclist.c @@ -1,1544 +1,1543 @@ /* pkclist.c - create a list of public keys * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 2008, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "keydb.h" #include "util.h" #include "main.h" #include "trustdb.h" #include "ttyio.h" #include "status.h" #include "photoid.h" #include "i18n.h" #define CONTROL_D ('D' - 'A' + 1) static void send_status_inv_recp (int reason, const char *name) { char buf[40]; snprintf (buf, sizeof buf, "%d ", reason); write_status_text_and_buffer (STATUS_INV_RECP, buf, name, strlen (name), -1); } /**************** * Show the revocation reason as it is stored with the given signature */ static void do_show_revocation_reason( PKT_signature *sig ) { size_t n, nn; const byte *p, *pp; int seq = 0; const char *text; while( (p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON, &n, &seq, NULL )) ) { if( !n ) continue; /* invalid - just skip it */ if( *p == 0 ) text = _("No reason specified"); else if( *p == 0x01 ) text = _("Key is superseded"); else if( *p == 0x02 ) text = _("Key has been compromised"); else if( *p == 0x03 ) text = _("Key is no longer used"); else if( *p == 0x20 ) text = _("User ID is no longer valid"); else text = NULL; - log_info( _("reason for revocation: ") ); - if( text ) - fputs( text, log_get_stream() ); + log_info ( _("reason for revocation: ")); + if (text) + log_printf ("%s\n", text); else - fprintf( log_get_stream(), "code=%02x", *p ); - log_printf ("\n"); + log_printf ("code=%02x\n", *p ); n--; p++; pp = NULL; do { /* We don't want any empty lines, so skip them */ while( n && *p == '\n' ) { p++; n--; } if( n ) { pp = memchr( p, '\n', n ); nn = pp? pp - p : n; log_info ( _("revocation comment: ") ); - print_string ( log_get_stream(), p, nn, 0 ); + es_write_sanitized (log_get_stream(), p, nn, NULL, NULL); log_printf ("\n"); p += nn; n -= nn; } } while( pp ); } } /* Mode 0: try and find the revocation based on the pk (i.e. check subkeys, etc.) Mode 1: use only the revocation on the main pk */ void show_revocation_reason( PKT_public_key *pk, int mode ) { /* Hmmm, this is not so easy becuase we have to duplicate the code * used in the trustbd to calculate the keyflags. We need to find * a clean way to check revocation certificates on keys and * signatures. And there should be no duplicate code. Because we * enter this function only when the trustdb told us that we have * a revoked key, we could simply look for a revocation cert and * display this one, when there is only one. Let's try to do this * until we have a better solution. */ KBNODE node, keyblock = NULL; byte fingerprint[MAX_FINGERPRINT_LEN]; size_t fingerlen; int rc; /* get the keyblock */ fingerprint_from_pk( pk, fingerprint, &fingerlen ); rc = get_keyblock_byfprint( &keyblock, fingerprint, fingerlen ); if( rc ) { /* that should never happen */ log_debug( "failed to get the keyblock\n"); return; } for( node=keyblock; node; node = node->next ) { if( (mode && node->pkt->pkttype == PKT_PUBLIC_KEY) || ( ( node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) && !cmp_public_keys( node->pkt->pkt.public_key, pk ) ) ) break; } if( !node ) { log_debug("Oops, PK not in keyblock\n"); release_kbnode( keyblock ); return; } /* now find the revocation certificate */ for( node = node->next; node ; node = node->next ) { if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) break; if( node->pkt->pkttype == PKT_SIGNATURE && (node->pkt->pkt.signature->sig_class == 0x20 || node->pkt->pkt.signature->sig_class == 0x28 ) ) { /* FIXME: we should check the signature here */ do_show_revocation_reason ( node->pkt->pkt.signature ); break; } } /* We didn't find it, so check if the whole key is revoked */ if(!node && !mode) show_revocation_reason(pk,1); release_kbnode( keyblock ); } /**************** * mode: 0 = standard * 1 = Without key info and additional menu option 'm' * this does also add an option to set the key to ultimately trusted. * Returns: * -2 = nothing changed - caller should show some additional info * -1 = quit operation * 0 = nothing changed * 1 = new ownertrust now in new_trust */ static int do_edit_ownertrust (PKT_public_key *pk, int mode, unsigned *new_trust, int defer_help ) { char *p; u32 keyid[2]; int changed=0; int quit=0; int show=0; int min_num; int did_help=defer_help; unsigned int minimum=get_min_ownertrust(pk); switch(minimum) { default: case TRUST_UNDEFINED: min_num=1; break; case TRUST_NEVER: min_num=2; break; case TRUST_MARGINAL: min_num=3; break; case TRUST_FULLY: min_num=4; break; } keyid_from_pk (pk, keyid); for(;;) { /* A string with valid answers. Note to translators: These are the allowed answers in lower and uppercase. Below you will find the matching strings which should be translated accordingly and the letter changed to match the one in the answer string. i = please show me more information m = back to the main menu s = skip this key q = quit */ const char *ans = _("iImMqQsS"); if( !did_help ) { if( !mode ) { KBNODE keyblock, un; tty_printf(_("No trust value assigned to:\n")); tty_printf("%4u%c/%s %s\n",nbits_from_pk( pk ), pubkey_letter( pk->pubkey_algo ), keystr(keyid), datestr_from_pk( pk ) ); p=get_user_id_native(keyid); tty_printf(_(" \"%s\"\n"),p); xfree(p); keyblock = get_pubkeyblock (keyid); if (!keyblock) BUG (); for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype != PKT_USER_ID ) continue; if (un->pkt->pkt.user_id->is_revoked ) continue; if (un->pkt->pkt.user_id->is_expired ) continue; /* Only skip textual primaries */ if (un->pkt->pkt.user_id->is_primary && !un->pkt->pkt.user_id->attrib_data ) continue; if((opt.verify_options&VERIFY_SHOW_PHOTOS) && un->pkt->pkt.user_id->attrib_data) show_photos(un->pkt->pkt.user_id->attribs, un->pkt->pkt.user_id->numattribs,pk,NULL, un->pkt->pkt.user_id); p=utf8_to_native(un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len,0); tty_printf(_(" aka \"%s\"\n"),p); } print_fingerprint (pk, NULL, 2); tty_printf("\n"); release_kbnode (keyblock); } if(opt.trust_model==TM_DIRECT) { tty_printf(_("How much do you trust that this key actually " "belongs to the named user?\n")); tty_printf("\n"); } else { /* This string also used in keyedit.c:trustsig_prompt */ tty_printf(_("Please decide how far you trust this user to" " correctly verify other users' keys\n" "(by looking at passports, checking fingerprints from" " different sources, etc.)\n")); tty_printf("\n"); } if(min_num<=1) tty_printf (_(" %d = I don't know or won't say\n"), 1); if(min_num<=2) tty_printf (_(" %d = I do NOT trust\n"), 2); if(min_num<=3) tty_printf (_(" %d = I trust marginally\n"), 3); if(min_num<=4) tty_printf (_(" %d = I trust fully\n"), 4); if (mode) tty_printf (_(" %d = I trust ultimately\n"), 5); #if 0 /* not yet implemented */ tty_printf (" i = please show me more information\n"); #endif if( mode ) tty_printf(_(" m = back to the main menu\n")); else { tty_printf(_(" s = skip this key\n")); tty_printf(_(" q = quit\n")); } tty_printf("\n"); if(minimum) tty_printf(_("The minimum trust level for this key is: %s\n\n"), trust_value_to_string(minimum)); did_help = 1; } if( strlen(ans) != 8 ) BUG(); p = cpr_get("edit_ownertrust.value",_("Your decision? ")); trim_spaces(p); cpr_kill_prompt(); if( !*p ) did_help = 0; else if( *p && p[1] ) ; else if( !p[1] && ((*p >= '0'+min_num) && *p <= (mode?'5':'4')) ) { unsigned int trust; switch( *p ) { case '1': trust = TRUST_UNDEFINED; break; case '2': trust = TRUST_NEVER ; break; case '3': trust = TRUST_MARGINAL ; break; case '4': trust = TRUST_FULLY ; break; case '5': trust = TRUST_ULTIMATE ; break; default: BUG(); } if (trust == TRUST_ULTIMATE && !cpr_get_answer_is_yes ("edit_ownertrust.set_ultimate.okay", _("Do you really want to set this key" " to ultimate trust? (y/N) "))) ; /* no */ else { *new_trust = trust; changed = 1; break; } } #if 0 /* not yet implemented */ else if( *p == ans[0] || *p == ans[1] ) { tty_printf(_("Certificates leading to an ultimately trusted key:\n")); show = 1; break; } #endif else if( mode && (*p == ans[2] || *p == ans[3] || *p == CONTROL_D ) ) { break ; /* back to the menu */ } else if( !mode && (*p == ans[6] || *p == ans[7] ) ) { break; /* skip */ } else if( !mode && (*p == ans[4] || *p == ans[5] ) ) { quit = 1; break ; /* back to the menu */ } xfree(p); p = NULL; } xfree(p); return show? -2: quit? -1 : changed; } /* * Display a menu to change the ownertrust of the key PK (which should * be a primary key). * For mode values see do_edit_ownertrust () */ int edit_ownertrust (PKT_public_key *pk, int mode ) { unsigned int trust = 0; int no_help = 0; for(;;) { switch ( do_edit_ownertrust (pk, mode, &trust, no_help ) ) { case -1: /* quit */ return -1; case -2: /* show info */ no_help = 1; break; case 1: /* trust value set */ trust &= ~TRUST_FLAG_DISABLED; trust |= get_ownertrust (pk) & TRUST_FLAG_DISABLED; update_ownertrust (pk, trust ); return 1; default: return 0; } } } /**************** * Check whether we can trust this pk which has a trustlevel of TRUSTLEVEL * Returns: true if we trust. */ static int do_we_trust( PKT_public_key *pk, unsigned int trustlevel ) { /* We should not be able to get here with a revoked or expired key */ if(trustlevel & TRUST_FLAG_REVOKED || trustlevel & TRUST_FLAG_SUB_REVOKED || (trustlevel & TRUST_MASK) == TRUST_EXPIRED) BUG(); if( opt.trust_model==TM_ALWAYS ) { if( opt.verbose ) log_info("No trust check due to `--trust-model always' option\n"); return 1; } switch(trustlevel & TRUST_MASK) { default: log_error ("invalid trustlevel %u returned from validation layer\n", trustlevel); /* fall thru */ case TRUST_UNKNOWN: case TRUST_UNDEFINED: log_info(_("%s: There is no assurance this key belongs" " to the named user\n"),keystr_from_pk(pk)); return 0; /* no */ case TRUST_MARGINAL: log_info(_("%s: There is limited assurance this key belongs" " to the named user\n"),keystr_from_pk(pk)); return 1; /* yes */ case TRUST_FULLY: if( opt.verbose ) log_info(_("This key probably belongs to the named user\n")); return 1; /* yes */ case TRUST_ULTIMATE: if( opt.verbose ) log_info(_("This key belongs to us\n")); return 1; /* yes */ } return 1; /*NOTREACHED*/ } /**************** * wrapper around do_we_trust, so we can ask whether to use the * key anyway. */ static int do_we_trust_pre( PKT_public_key *pk, unsigned int trustlevel ) { int rc; rc = do_we_trust( pk, trustlevel ); if( !opt.batch && !rc ) { print_pubkey_info(NULL,pk); print_fingerprint (pk, NULL, 2); tty_printf("\n"); tty_printf( _("It is NOT certain that the key belongs to the person named\n" "in the user ID. If you *really* know what you are doing,\n" "you may answer the next question with yes.\n")); tty_printf("\n"); if (is_status_enabled ()) { u32 kid[2]; char *hint_str; keyid_from_pk (pk, kid); hint_str = get_long_user_id_string ( kid ); write_status_text ( STATUS_USERID_HINT, hint_str ); xfree (hint_str); } if( cpr_get_answer_is_yes("untrusted_key.override", _("Use this key anyway? (y/N) ")) ) rc = 1; /* Hmmm: Should we set a flag to tell the user about * his decision the next time he encrypts for this recipient? */ } return rc; } /**************** * Check whether we can trust this signature. * Returns: Error if we shall not trust this signatures. */ int check_signatures_trust( PKT_signature *sig ) { PKT_public_key *pk = xmalloc_clear( sizeof *pk ); unsigned int trustlevel; int rc=0; rc = get_pubkey( pk, sig->keyid ); if (rc) { /* this should not happen */ log_error("Ooops; the key vanished - can't check the trust\n"); rc = G10ERR_NO_PUBKEY; goto leave; } if ( opt.trust_model==TM_ALWAYS ) { if( !opt.quiet ) log_info(_("WARNING: Using untrusted key!\n")); if (opt.with_fingerprint) print_fingerprint (pk, NULL, 1); goto leave; } if(pk->maybe_revoked && !pk->is_revoked) log_info(_("WARNING: this key might be revoked (revocation key" " not present)\n")); trustlevel = get_validity (pk, NULL); if ( (trustlevel & TRUST_FLAG_REVOKED) ) { write_status( STATUS_KEYREVOKED ); if(pk->is_revoked==2) log_info(_("WARNING: This key has been revoked by its" " designated revoker!\n")); else log_info(_("WARNING: This key has been revoked by its owner!\n")); log_info(_(" This could mean that the signature is forged.\n")); show_revocation_reason( pk, 0 ); } else if ((trustlevel & TRUST_FLAG_SUB_REVOKED) ) { write_status( STATUS_KEYREVOKED ); log_info(_("WARNING: This subkey has been revoked by its owner!\n")); show_revocation_reason( pk, 0 ); } if ((trustlevel & TRUST_FLAG_DISABLED)) log_info (_("Note: This key has been disabled.\n")); /* If we have PKA information adjust the trustlevel. */ if (sig->pka_info && sig->pka_info->valid) { unsigned char fpr[MAX_FINGERPRINT_LEN]; PKT_public_key *primary_pk; size_t fprlen; int okay; primary_pk = xmalloc_clear (sizeof *primary_pk); get_pubkey (primary_pk, pk->main_keyid); fingerprint_from_pk (primary_pk, fpr, &fprlen); free_public_key (primary_pk); if ( fprlen == 20 && !memcmp (sig->pka_info->fpr, fpr, 20) ) { okay = 1; write_status_text (STATUS_PKA_TRUST_GOOD, sig->pka_info->email); log_info (_("Note: Verified signer's address is `%s'\n"), sig->pka_info->email); } else { okay = 0; write_status_text (STATUS_PKA_TRUST_BAD, sig->pka_info->email); log_info (_("Note: Signer's address `%s' " "does not match DNS entry\n"), sig->pka_info->email); } switch ( (trustlevel & TRUST_MASK) ) { case TRUST_UNKNOWN: case TRUST_UNDEFINED: case TRUST_MARGINAL: if (okay && opt.verify_options&VERIFY_PKA_TRUST_INCREASE) { trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_FULLY); log_info (_("trustlevel adjusted to FULL" " due to valid PKA info\n")); } /* (fall through) */ case TRUST_FULLY: if (!okay) { trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_NEVER); log_info (_("trustlevel adjusted to NEVER" " due to bad PKA info\n")); } break; } } /* Now let the user know what up with the trustlevel. */ switch ( (trustlevel & TRUST_MASK) ) { case TRUST_EXPIRED: log_info(_("Note: This key has expired!\n")); print_fingerprint (pk, NULL, 1); break; default: log_error ("invalid trustlevel %u returned from validation layer\n", trustlevel); /* fall thru */ case TRUST_UNKNOWN: case TRUST_UNDEFINED: write_status( STATUS_TRUST_UNDEFINED ); log_info(_("WARNING: This key is not certified with" " a trusted signature!\n")); log_info(_(" There is no indication that the " "signature belongs to the owner.\n" )); print_fingerprint (pk, NULL, 1); break; case TRUST_NEVER: /* currently we won't get that status */ write_status( STATUS_TRUST_NEVER ); log_info(_("WARNING: We do NOT trust this key!\n")); log_info(_(" The signature is probably a FORGERY.\n")); if (opt.with_fingerprint) print_fingerprint (pk, NULL, 1); rc = gpg_error (GPG_ERR_BAD_SIGNATURE); break; case TRUST_MARGINAL: write_status( STATUS_TRUST_MARGINAL ); log_info(_("WARNING: This key is not certified with" " sufficiently trusted signatures!\n")); log_info(_(" It is not certain that the" " signature belongs to the owner.\n" )); print_fingerprint (pk, NULL, 1); break; case TRUST_FULLY: write_status( STATUS_TRUST_FULLY ); if (opt.with_fingerprint) print_fingerprint (pk, NULL, 1); break; case TRUST_ULTIMATE: write_status( STATUS_TRUST_ULTIMATE ); if (opt.with_fingerprint) print_fingerprint (pk, NULL, 1); break; } leave: free_public_key( pk ); return rc; } void release_pk_list (pk_list_t pk_list) { PK_LIST pk_rover; for ( ; pk_list; pk_list = pk_rover) { pk_rover = pk_list->next; free_public_key ( pk_list->pk ); xfree ( pk_list ); } } static int key_present_in_pk_list(PK_LIST pk_list, PKT_public_key *pk) { for( ; pk_list; pk_list = pk_list->next) if (cmp_public_keys(pk_list->pk, pk) == 0) return 0; return -1; } /**************** * Return a malloced string with a default recipient if there is any */ static char * default_recipient(void) { PKT_secret_key *sk; byte fpr[MAX_FINGERPRINT_LEN+1]; size_t n; char *p; int i; if( opt.def_recipient ) return xstrdup( opt.def_recipient ); if( !opt.def_recipient_self ) return NULL; sk = xmalloc_clear( sizeof *sk ); i = get_seckey_byname( sk, NULL, 0 ); if( i ) { free_secret_key( sk ); return NULL; } n = MAX_FINGERPRINT_LEN; fingerprint_from_sk( sk, fpr, &n ); free_secret_key( sk ); p = xmalloc( 2*n+3 ); *p++ = '0'; *p++ = 'x'; for(i=0; i < n; i++ ) sprintf( p+2*i, "%02X", fpr[i] ); p -= 2; return p; } static int expand_id(const char *id,strlist_t *into,unsigned int flags) { struct groupitem *groups; int count=0; for(groups=opt.grouplist;groups;groups=groups->next) { /* need strcasecmp() here, as this should be localized */ if(strcasecmp(groups->name,id)==0) { strlist_t each,sl; /* this maintains the current utf8-ness */ for(each=groups->values;each;each=each->next) { sl=add_to_strlist(into,each->d); sl->flags=flags; count++; } break; } } return count; } /* For simplicity, and to avoid potential loops, we only expand once - you can't make an alias that points to an alias. */ static strlist_t expand_group(strlist_t input) { strlist_t sl,output=NULL,rover; for(rover=input;rover;rover=rover->next) if(expand_id(rover->d,&output,rover->flags)==0) { /* Didn't find any groups, so use the existing string */ sl=add_to_strlist(&output,rover->d); sl->flags=rover->flags; } return output; } /* Helper for build_pk_list to find and check one key. This helper is also used directly in server mode by the RECIPIENTS command. On success the new key is added to PK_LIST_ADDR. NAME is the user id of the key. USE the requested usage and a set MARK_HIDDEN will mark the key in the updated list as a hidden recipient. */ gpg_error_t find_and_check_key (const char *name, unsigned int use, int mark_hidden, pk_list_t *pk_list_addr) { int rc; PKT_public_key *pk; int trustlevel; if (!name || !*name) return gpg_error (GPG_ERR_INV_USER_ID); pk = xtrycalloc (1, sizeof *pk); if (!pk) return gpg_error_from_syserror (); pk->req_usage = use; rc = get_pubkey_byname (NULL, pk, name, NULL, NULL, 0, 0); if (rc) { /* Key not found or other error. */ log_error (_("%s: skipped: %s\n"), name, g10_errstr(rc) ); send_status_inv_recp (0, name); free_public_key (pk); return rc; } rc = openpgp_pk_test_algo2 (pk->pubkey_algo, use); if (rc) { /* Key found but not usable for us (e.g. sign-only key). */ send_status_inv_recp (0, name); log_error (_("%s: skipped: %s\n"), name, g10_errstr(rc) ); free_public_key (pk); return rc; } /* Key found and usable. Check validity. */ trustlevel = get_validity (pk, pk->user_id); if ( (trustlevel & TRUST_FLAG_DISABLED) ) { /* Key has been disabled. */ send_status_inv_recp (0, name); log_info (_("%s: skipped: public key is disabled\n"), name); free_public_key (pk); return G10ERR_UNU_PUBKEY; } if ( !do_we_trust_pre (pk, trustlevel) ) { /* We don't trust this key. */ send_status_inv_recp (10, name); free_public_key (pk); return G10ERR_UNU_PUBKEY; } /* Note: do_we_trust may have changed the trustlevel. */ /* Skip the actual key if the key is already present in the list. */ if (!key_present_in_pk_list (*pk_list_addr, pk)) { log_info (_("%s: skipped: public key already present\n"), name); free_public_key (pk); } else { pk_list_t r; r = xtrymalloc (sizeof *r); if (!r) { rc = gpg_error_from_syserror (); free_public_key (pk); return rc; } r->pk = pk; r->next = *pk_list_addr; r->flags = mark_hidden? 1:0; *pk_list_addr = r; } return 0; } /* This is the central function to collect the keys for recipients. It is thus used to prepare a public key encryption. encrypt-to keys, default keys and the keys for the actual recipients are all collected here. When not in batch mode and no recipient has been passed on the commandline, the function will also ask for recipients. RCPTS is a string list with the recipients; NULL is an allowed value but not very useful. Group expansion is done on these names; they may be in any of the user Id formats we can handle. The flags bits for each string in the string list are used for: Bit 0: This is an encrypt-to recipient. Bit 1: This is a hidden recipient. USE is the desired use for the key - usually PUBKEY_USAGE_ENC. On success a list of keys is stored at the address RET_PK_LIST; the caller must free this list. On error the value at this address is not changed. */ int build_pk_list( strlist_t rcpts, PK_LIST *ret_pk_list, unsigned int use ) { PK_LIST pk_list = NULL; PKT_public_key *pk=NULL; int rc=0; int any_recipients=0; strlist_t rov,remusr; char *def_rec = NULL; /* Try to expand groups if any have been defined. */ if (opt.grouplist) remusr = expand_group (rcpts); else remusr = rcpts; /* Check whether there are any recipients in the list and build the * list of the encrypt-to ones (we always trust them). */ for ( rov = remusr; rov; rov = rov->next ) { if ( !(rov->flags & 1) ) { /* This is a regular recipient; i.e. not an encrypt-to one. */ any_recipients = 1; /* Hidden recipients are not allowed while in PGP mode, issue a warning and switch into GnuPG mode. */ if ((rov->flags&2) && (PGP2 || PGP6 || PGP7 || PGP8)) { log_info(_("you may not use %s while in %s mode\n"), "--hidden-recipient", compliance_option_string()); compliance_failure(); } } else if ( (use & PUBKEY_USAGE_ENC) && !opt.no_encrypt_to ) { /* Encryption has been requested and --encrypt-to has not been disabled. Check this encrypt-to key. */ pk = xmalloc_clear( sizeof *pk ); pk->req_usage = use; /* We explicitly allow encrypt-to to an disabled key; thus we pass 1for the second last argument and 1 as the last argument to disable AKL. */ if ( (rc = get_pubkey_byname (NULL, pk, rov->d, NULL, NULL, 1, 1)) ) { free_public_key ( pk ); pk = NULL; log_error (_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) ); send_status_inv_recp (0, rov->d); goto fail; } else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) ) { /* Skip the actual key if the key is already present * in the list. Add it to our list if not. */ if (key_present_in_pk_list(pk_list, pk) == 0) { free_public_key (pk); pk = NULL; log_info (_("%s: skipped: public key already present\n"), rov->d); } else { PK_LIST r; r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = (rov->flags&2)?1:0; pk_list = r; /* Hidden encrypt-to recipients are not allowed while in PGP mode, issue a warning and switch into GnuPG mode. */ if ((r->flags&1) && (PGP2 || PGP6 || PGP7 || PGP8)) { log_info(_("you may not use %s while in %s mode\n"), "--hidden-encrypt-to", compliance_option_string()); compliance_failure(); } } } else { /* The public key is not usable for encryption or not available. */ free_public_key( pk ); pk = NULL; log_error(_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) ); send_status_inv_recp (0, rov->d); goto fail; } } } /* If we don't have any recipients yet and we are not in batch mode drop into interactive selection mode. */ if ( !any_recipients && !opt.batch ) { int have_def_rec; char *answer = NULL; strlist_t backlog = NULL; if (pk_list) any_recipients = 1; def_rec = default_recipient(); have_def_rec = !!def_rec; if ( !have_def_rec ) tty_printf(_("You did not specify a user ID. (you may use \"-r\")\n")); for (;;) { rc = 0; xfree(answer); if ( have_def_rec ) { /* A default recipient is taken as the first entry. */ answer = def_rec; def_rec = NULL; } else if (backlog) { /* This is part of our trick to expand and display groups. */ answer = strlist_pop (&backlog); } else { /* Show the list of already collected recipients and ask for more. */ PK_LIST iter; tty_printf("\n"); tty_printf(_("Current recipients:\n")); for (iter=pk_list;iter;iter=iter->next) { u32 keyid[2]; keyid_from_pk(iter->pk,keyid); tty_printf("%4u%c/%s %s \"", nbits_from_pk(iter->pk), pubkey_letter(iter->pk->pubkey_algo), keystr(keyid), datestr_from_pk(iter->pk)); if (iter->pk->user_id) tty_print_utf8_string(iter->pk->user_id->name, iter->pk->user_id->len); else { size_t n; char *p = get_user_id( keyid, &n ); tty_print_utf8_string( p, n ); xfree(p); } tty_printf("\"\n"); } answer = cpr_get_utf8("pklist.user_id.enter", _("\nEnter the user ID. " "End with an empty line: ")); trim_spaces(answer); cpr_kill_prompt(); } if ( !answer || !*answer ) { xfree(answer); break; /* No more recipients entered - get out of loop. */ } /* Do group expand here too. The trick here is to continue the loop if any expansion occured. The code above will then list all expanded keys. */ if (expand_id(answer,&backlog,0)) continue; /* Get and check key for the current name. */ if (pk) free_public_key (pk); pk = xmalloc_clear( sizeof *pk ); pk->req_usage = use; rc = get_pubkey_byname (NULL, pk, answer, NULL, NULL, 0, 0 ); if (rc) tty_printf(_("No such user ID.\n")); else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) ) { if ( have_def_rec ) { /* No validation for a default recipient. */ if (!key_present_in_pk_list(pk_list, pk)) { free_public_key (pk); pk = NULL; log_info (_("skipped: public key " "already set as default recipient\n") ); } else { PK_LIST r = xmalloc (sizeof *r); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing default ids. */ pk_list = r; } any_recipients = 1; continue; } else { /* Check validity of this key. */ int trustlevel; trustlevel = get_validity (pk, pk->user_id); if ( (trustlevel & TRUST_FLAG_DISABLED) ) { tty_printf (_("Public key is disabled.\n") ); } else if ( do_we_trust_pre (pk, trustlevel) ) { /* Skip the actual key if the key is already * present in the list */ if (!key_present_in_pk_list(pk_list, pk)) { free_public_key(pk); pk = NULL; log_info(_("skipped: public key already set\n") ); } else { PK_LIST r; r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing interactive ids. */ pk_list = r; } any_recipients = 1; continue; } } } xfree(def_rec); def_rec = NULL; have_def_rec = 0; } if ( pk ) { free_public_key( pk ); pk = NULL; } } else if ( !any_recipients && (def_rec = default_recipient()) ) { /* We are in batch mode and have only a default recipient. */ pk = xmalloc_clear( sizeof *pk ); pk->req_usage = use; /* The default recipient is allowed to be disabled; thus pass 1 as second last argument. We also don't want an AKL. */ rc = get_pubkey_byname (NULL, pk, def_rec, NULL, NULL, 1, 1); if (rc) log_error(_("unknown default recipient \"%s\"\n"), def_rec ); else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo, use)) ) { /* Mark any_recipients here since the default recipient would have been used if it wasn't already there. It doesn't really matter if we got this key from the default recipient or an encrypt-to. */ any_recipients = 1; if (!key_present_in_pk_list(pk_list, pk)) log_info (_("skipped: public key already set " "as default recipient\n")); else { PK_LIST r = xmalloc( sizeof *r ); r->pk = pk; pk = NULL; r->next = pk_list; r->flags = 0; /* No throwing default ids. */ pk_list = r; } } if ( pk ) { free_public_key( pk ); pk = NULL; } xfree(def_rec); def_rec = NULL; } else { /* General case: Check all keys. */ any_recipients = 0; for (; remusr; remusr = remusr->next ) { if ( (remusr->flags & 1) ) continue; /* encrypt-to keys are already handled. */ rc = find_and_check_key (remusr->d, use, !!(remusr->flags&2), &pk_list); if (rc) goto fail; any_recipients = 1; } } if ( !rc && !any_recipients ) { log_error(_("no valid addressees\n")); write_status_text (STATUS_NO_RECP, "0"); rc = G10ERR_NO_USER_ID; } fail: if ( rc ) release_pk_list( pk_list ); else *ret_pk_list = pk_list; if (opt.grouplist) free_strlist(remusr); return rc; } /* In pgp6 mode, disallow all ciphers except IDEA (1), 3DES (2), and CAST5 (3), all hashes except MD5 (1), SHA1 (2), and RIPEMD160 (3), and all compressions except none (0) and ZIP (1). pgp7 and pgp8 mode expands the cipher list to include AES128 (7), AES192 (8), AES256 (9), and TWOFISH (10). pgp8 adds the SHA-256 hash (8). For a true PGP key all of this is unneeded as they are the only items present in the preferences subpacket, but checking here covers the weird case of encrypting to a key that had preferences from a different implementation which was then used with PGP. I am not completely comfortable with this as the right thing to do, as it slightly alters the list of what the user is supposedly requesting. It is not against the RFC however, as the preference chosen will never be one that the user didn't specify somewhere ("The implementation may use any mechanism to pick an algorithm in the intersection"), and PGP has no mechanism to fix such a broken preference list, so I'm including it. -dms */ int algo_available( preftype_t preftype, int algo, const union pref_hint *hint) { if( preftype == PREFTYPE_SYM ) { if(PGP6 && (algo != CIPHER_ALGO_IDEA && algo != CIPHER_ALGO_3DES && algo != CIPHER_ALGO_CAST5)) return 0; if(PGP7 && (algo != CIPHER_ALGO_IDEA && algo != CIPHER_ALGO_3DES && algo != CIPHER_ALGO_CAST5 && algo != CIPHER_ALGO_AES && algo != CIPHER_ALGO_AES192 && algo != CIPHER_ALGO_AES256 && algo != CIPHER_ALGO_TWOFISH)) return 0; /* PGP8 supports all the ciphers we do.. */ return algo && !openpgp_cipher_test_algo ( algo ); } else if( preftype == PREFTYPE_HASH ) { if (hint && hint->digest_length) { if (hint->digest_length!=20 || opt.flags.dsa2) { /* If --enable-dsa2 is set or the hash isn't 160 bits (which implies DSA2), then we'll accept a hash that is larger than we need. Otherwise we won't accept any hash that isn't exactly the right size. */ if (hint->digest_length > gcry_md_get_algo_dlen (algo)) return 0; } else if (hint->digest_length != gcry_md_get_algo_dlen (algo)) return 0; } if((PGP6 || PGP7) && (algo != DIGEST_ALGO_MD5 && algo != DIGEST_ALGO_SHA1 && algo != DIGEST_ALGO_RMD160)) return 0; if(PGP8 && (algo != DIGEST_ALGO_MD5 && algo != DIGEST_ALGO_SHA1 && algo != DIGEST_ALGO_RMD160 && algo != DIGEST_ALGO_SHA256)) return 0; return algo && !openpgp_md_test_algo (algo); } else if( preftype == PREFTYPE_ZIP ) { if((PGP6 || PGP7) && (algo != COMPRESS_ALGO_NONE && algo != COMPRESS_ALGO_ZIP)) return 0; /* PGP8 supports all the compression algos we do */ return !check_compress_algo( algo ); } else return 0; } /**************** * Return -1 if we could not find an algorithm. */ int select_algo_from_prefs(PK_LIST pk_list, int preftype, int request, const union pref_hint *hint) { PK_LIST pkr; u32 bits[8]; const prefitem_t *prefs; int result=-1,i; unsigned int best=-1; byte scores[256]; if( !pk_list ) return -1; memset(bits,0xFF,sizeof(bits)); memset(scores,0,sizeof(scores)); for( pkr = pk_list; pkr; pkr = pkr->next ) { u32 mask[8]; int rank=1,implicit=-1; memset(mask,0,sizeof(mask)); switch(preftype) { case PREFTYPE_SYM: /* IDEA is implicitly there for v3 keys with v3 selfsigs if --pgp2 mode is on. This was a 2440 thing that was dropped from 4880 but is still relevant to GPG's 1991 support. All this doesn't mean IDEA is actually available, of course. */ if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4) implicit=CIPHER_ALGO_IDEA; else implicit=CIPHER_ALGO_3DES; break; case PREFTYPE_HASH: /* While I am including this code for completeness, note that currently --pgp2 mode locks the hash at MD5, so this code will never even be called. Even if the hash wasn't locked at MD5, we don't support sign+encrypt in --pgp2 mode, and that's the only time PREFTYPE_HASH is used anyway. -dms */ /* MD5 is there for v3 keys with v3 selfsigs when --pgp2 is on. */ if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4) implicit=DIGEST_ALGO_MD5; else implicit=DIGEST_ALGO_SHA1; break; case PREFTYPE_ZIP: /* Uncompressed is always an option. */ implicit=COMPRESS_ALGO_NONE; } if (pkr->pk->user_id) /* selected by user ID */ prefs = pkr->pk->user_id->prefs; else prefs = pkr->pk->prefs; if( prefs ) { for (i=0; prefs[i].type; i++ ) { if( prefs[i].type == preftype ) { scores[prefs[i].value]+=rank; mask[prefs[i].value/32] |= 1<<(prefs[i].value%32); rank++; /* We saw the implicit algorithm, so we don't need tack it on the end ourselves. */ if(implicit==prefs[i].value) implicit=-1; } } } if(rank==1 && preftype==PREFTYPE_ZIP) { /* If the compression preferences are not present, they are assumed to be ZIP, Uncompressed (RFC4880:13.3.1) */ scores[1]=1; /* ZIP is first choice */ scores[0]=2; /* Uncompressed is second choice */ mask[0]|=3; } /* If the key didn't have the implicit algorithm listed explicitly, add it here at the tail of the list. */ if(implicit>-1) { scores[implicit]+=rank; mask[implicit/32] |= 1<<(implicit%32); } for(i=0;i<8;i++) bits[i]&=mask[i]; } /* We've now scored all of the algorithms, and the usable ones have bits set. Let's pick the winner. */ /* The caller passed us a request. Can we use it? */ if(request>-1 && (bits[request/32] & (1<<(request%32))) && algo_available(preftype,request,hint)) result=request; if(result==-1) { /* If we have personal prefs set, use them. */ prefs=NULL; if(preftype==PREFTYPE_SYM && opt.personal_cipher_prefs) prefs=opt.personal_cipher_prefs; else if(preftype==PREFTYPE_HASH && opt.personal_digest_prefs) prefs=opt.personal_digest_prefs; else if(preftype==PREFTYPE_ZIP && opt.personal_compress_prefs) prefs=opt.personal_compress_prefs; if( prefs ) for(i=0; prefs[i].type; i++ ) { if(bits[prefs[i].value/32] & (1<<(prefs[i].value%32)) && algo_available( preftype, prefs[i].value, hint)) { result = prefs[i].value; break; } } } if(result==-1) { /* At this point, we have not selected an algorithm due to a special request or via personal prefs. Pick the highest ranked algorithm (i.e. the one with the lowest score). */ for(i=0;i<256;i++) { /* Note the '<' here. This means in case of a tie, we will favor the lower algorithm number. We have a choice between the lower number (probably an older algorithm with more time in use), or the higher number (probably a newer algorithm with less time in use). Older is probably safer here, even though the newer algorithms tend to be "stronger". */ if(scores[i] && scores[i]next) { int mdc; if (pkr->pk->user_id) /* selected by user ID */ mdc = pkr->pk->user_id->flags.mdc; else mdc = pkr->pk->mdc_feature; if (!mdc) return 0; /* At least one recipient does not support it. */ } return 1; /* Can be used. */ } /* Print a warning for all keys in PK_LIST missing the MDC feature. */ void warn_missing_mdc_from_pklist (PK_LIST pk_list) { PK_LIST pkr; for (pkr = pk_list; pkr; pkr = pkr->next) { int mdc; if (pkr->pk->user_id) /* selected by user ID */ mdc = pkr->pk->user_id->flags.mdc; else mdc = pkr->pk->mdc_feature; if (!mdc) log_info (_("Note: key %s has no %s feature\n"), keystr_from_pk (pkr->pk), "MDC"); } } void warn_missing_aes_from_pklist (PK_LIST pk_list) { PK_LIST pkr; for (pkr = pk_list; pkr; pkr = pkr->next) { const prefitem_t *prefs; int i; int gotit = 0; prefs = pkr->pk->user_id? pkr->pk->user_id->prefs : pkr->pk->prefs; if (prefs) { for (i=0; !gotit && prefs[i].type; i++ ) if (prefs[i].type == PREFTYPE_SYM && prefs[i].value == CIPHER_ALGO_AES) gotit++; } if (!gotit) log_info (_("Note: key %s has no preference for %s\n"), keystr_from_pk (pkr->pk), "AES"); } } diff --git a/g10/plaintext.c b/g10/plaintext.c index ee0d41357..0a7415c9e 100644 --- a/g10/plaintext.c +++ b/g10/plaintext.c @@ -1,720 +1,721 @@ /* plaintext.c - process plaintext packets * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, * 2006, 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_DOSISH_SYSTEM # include /* for setmode() */ #endif #include "gpg.h" #include "util.h" #include "options.h" #include "packet.h" #include "ttyio.h" #include "filter.h" #include "main.h" #include "status.h" #include "i18n.h" /* Handle a plaintext packet. If MFX is not NULL, update the MDs * Note: We should have used the filter stuff here, but we have to add * some easy mimic to set a read limit, so we calculate only the bytes * from the plaintext. */ int handle_plaintext (PKT_plaintext * pt, md_filter_context_t * mfx, int nooutput, int clearsig) { char *fname = NULL; FILE *fp = NULL; static off_t count = 0; int rc = 0; int c; int convert = (pt->mode == 't' || pt->mode == 'u'); #ifdef __riscos__ int filetype = 0xfff; #endif /* Let people know what the plaintext info is. This allows the receiving program to try and do something different based on the format code (say, recode UTF-8 to local). */ if (!nooutput && is_status_enabled ()) { char status[50]; /* Better make sure that stdout has been flushed in case the output will be written to it. This is to make sure that no not-yet-flushed stuff will be written after the plaintext status message. */ fflush (stdout); snprintf (status, sizeof status, "%X %lu ", (byte) pt->mode, (ulong) pt->timestamp); write_status_text_and_buffer (STATUS_PLAINTEXT, status, pt->name, pt->namelen, 0); if (!pt->is_partial) { sprintf (status, "%lu", (ulong) pt->len); write_status_text (STATUS_PLAINTEXT_LENGTH, status); } } /* Create the filename as C string. */ if (nooutput) ; else if (opt.outfp) { fname = xstrdup ("[FP]"); } else if (opt.outfile) { fname = xstrdup (opt.outfile); } else if (pt->namelen == 8 && !memcmp (pt->name, "_CONSOLE", 8)) { log_info (_("data not saved; use option \"--output\" to save it\n")); nooutput = 1; } else if (!opt.flags.use_embedded_filename) { fname = make_outfile_name (iobuf_get_real_fname (pt->buf)); if (!fname) fname = ask_outfile_name (pt->name, pt->namelen); if (!fname) { rc = gpg_error (GPG_ERR_GENERAL); /* Can't create file. */ goto leave; } } else fname = utf8_to_native (pt->name, pt->namelen, 0); if (nooutput) ; else if (opt.outfp) { fp = opt.outfp; #ifdef HAVE_DOSISH_SYSTEM setmode (fileno (fp), O_BINARY); #endif } else if (iobuf_is_pipe_filename (fname) || !*fname) { /* No filename or "-" given; write to stdout. */ fp = stdout; #ifdef HAVE_DOSISH_SYSTEM setmode (fileno (fp), O_BINARY); #endif } else { while (!overwrite_filep (fname)) { char *tmp = ask_outfile_name (NULL, 0); if (!tmp || !*tmp) { xfree (tmp); /* FIXME: Below used to be G10ERR_CREATE_FILE */ rc = gpg_error (GPG_ERR_GENERAL); goto leave; } xfree (fname); fname = tmp; } } #ifndef __riscos__ if (opt.outfp && is_secured_file (fileno (opt.outfp))) { rc = gpg_error (GPG_ERR_EPERM); log_error (_("error creating `%s': %s\n"), fname, gpg_strerror (rc)); goto leave; } else if (fp || nooutput) ; else if (is_secured_filename (fname)) { errno = EPERM; rc = gpg_error_from_syserror (); log_error (_("error creating `%s': %s\n"), fname, strerror (errno)); goto leave; } else if (!(fp = fopen (fname, "wb"))) { rc = gpg_error_from_syserror (); log_error (_("error creating `%s': %s\n"), fname, strerror (errno)); goto leave; } #else /* __riscos__ */ /* If no output filename was given, i.e. we constructed it, convert all '.' in fname to '/' but not vice versa as we don't create directories! */ if (!opt.outfile) for (c = 0; fname[c]; ++c) if (fname[c] == '.') fname[c] = '/'; if (fp || nooutput) ; else { fp = fopen (fname, "wb"); if (!fp) { log_error (_("error creating `%s': %s\n"), fname, strerror (errno)); rc = G10ERR_CREATE_FILE; if (errno == 106) log_info ("Do output file and input file have the same name?\n"); goto leave; } /* If there's a ,xxx extension in the embedded filename, use that, else check whether the user input (in fname) has a ,xxx appended, then use that in preference */ if ((c = riscos_get_filetype_from_string (pt->name, pt->namelen)) != -1) filetype = c; if ((c = riscos_get_filetype_from_string (fname, strlen (fname))) != -1) filetype = c; riscos_set_filetype_by_number (fname, filetype); } #endif /* __riscos__ */ if (!pt->is_partial) { /* We have an actual length (which might be zero). */ if (clearsig) { log_error ("clearsig encountered while not expected\n"); rc = G10ERR_UNEXPECTED; goto leave; } if (convert) /* Text mode. */ { for (; pt->len; pt->len--) { if ((c = iobuf_get (pt->buf)) == -1) { rc = gpg_error_from_syserror (); log_error ("problem reading source (%u bytes remaining)\n", (unsigned) pt->len); goto leave; } if (mfx->md) gcry_md_putc (mfx->md, c); #ifndef HAVE_DOSISH_SYSTEM if (c == '\r') /* convert to native line ending */ continue; /* fixme: this hack might be too simple */ #endif if (fp) { if (opt.max_output && (++count) > opt.max_output) { log_error ("error writing to `%s': %s\n", fname, "exceeded --max-output limit\n"); rc = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } else if (putc (c, fp) == EOF) { if (ferror (fp)) rc = gpg_error_from_syserror (); else rc = gpg_error (GPG_ERR_EOF); log_error ("error writing to `%s': %s\n", fname, strerror (errno)); goto leave; } } } } else /* Binary mode. */ { byte *buffer = xmalloc (32768); while (pt->len) { int len = pt->len > 32768 ? 32768 : pt->len; len = iobuf_read (pt->buf, buffer, len); if (len == -1) { rc = gpg_error_from_syserror (); log_error ("problem reading source (%u bytes remaining)\n", (unsigned) pt->len); xfree (buffer); goto leave; } if (mfx->md) gcry_md_write (mfx->md, buffer, len); if (fp) { if (opt.max_output && (count += len) > opt.max_output) { log_error ("error writing to `%s': %s\n", fname, "exceeded --max-output limit\n"); rc = gpg_error (GPG_ERR_TOO_LARGE); xfree (buffer); goto leave; } else if (fwrite (buffer, 1, len, fp) != len) { rc = gpg_error_from_syserror (); log_error ("error writing to `%s': %s\n", fname, strerror (errno)); xfree (buffer); goto leave; } } pt->len -= len; } xfree (buffer); } } else if (!clearsig) { if (convert) { /* text mode */ while ((c = iobuf_get (pt->buf)) != -1) { if (mfx->md) gcry_md_putc (mfx->md, c); #ifndef HAVE_DOSISH_SYSTEM if (convert && c == '\r') continue; /* fixme: this hack might be too simple */ #endif if (fp) { if (opt.max_output && (++count) > opt.max_output) { log_error ("Error writing to `%s': %s\n", fname, "exceeded --max-output limit\n"); rc = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } else if (putc (c, fp) == EOF) { if (ferror (fp)) rc = gpg_error_from_syserror (); else rc = gpg_error (GPG_ERR_EOF); log_error ("error writing to `%s': %s\n", fname, strerror (errno)); goto leave; } } } } else { /* binary mode */ byte *buffer = xmalloc (32768); int eof_seen = 0; while (!eof_seen) { /* Why do we check for len < 32768: * If we won't, we would practically read 2 EOFs but * the first one has already popped the block_filter * off and therefore we don't catch the boundary. * So, always assume EOF if iobuf_read returns less bytes * then requested */ int len = iobuf_read (pt->buf, buffer, 32768); if (len == -1) break; if (len < 32768) eof_seen = 1; if (mfx->md) gcry_md_write (mfx->md, buffer, len); if (fp) { if (opt.max_output && (count += len) > opt.max_output) { log_error ("error writing to `%s': %s\n", fname, "exceeded --max-output limit\n"); rc = gpg_error (GPG_ERR_TOO_LARGE); xfree (buffer); goto leave; } else if (fwrite (buffer, 1, len, fp) != len) { rc = (errno ? gpg_error_from_syserror () : gpg_error (GPG_ERR_INTERNAL)); log_error ("error writing to `%s': %s\n", fname, strerror (errno)); xfree (buffer); goto leave; } } } xfree (buffer); } pt->buf = NULL; } else /* Clear text signature - don't hash the last CR,LF. */ { int state = 0; while ((c = iobuf_get (pt->buf)) != -1) { if (fp) { if (opt.max_output && (++count) > opt.max_output) { log_error ("error writing to `%s': %s\n", fname, "exceeded --max-output limit\n"); rc = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } else if (putc (c, fp) == EOF) { rc = (errno ? gpg_error_from_syserror () : gpg_error (GPG_ERR_INTERNAL)); log_error ("error writing to `%s': %s\n", fname, strerror (errno)); goto leave; } } if (!mfx->md) continue; if (state == 2) { gcry_md_putc (mfx->md, '\r'); gcry_md_putc (mfx->md, '\n'); state = 0; } if (!state) { if (c == '\r') state = 1; else if (c == '\n') state = 2; else gcry_md_putc (mfx->md, c); } else if (state == 1) { if (c == '\n') state = 2; else { gcry_md_putc (mfx->md, '\r'); if (c == '\r') state = 1; else { state = 0; gcry_md_putc (mfx->md, c); } } } } pt->buf = NULL; } if (fp && fp != stdout && fp != opt.outfp && fclose (fp)) { rc = (errno ? gpg_error_from_syserror () : gpg_error (GPG_ERR_INTERNAL)); log_error ("error closing `%s': %s\n", fname, strerror (errno)); fp = NULL; goto leave; } fp = NULL; leave: /* Make sure that stdout gets flushed after the plaintext has been handled. This is for extra security as we do a flush anyway before checking the signature. */ fflush (stdout); if (fp && fp != stdout && fp != opt.outfp) fclose (fp); xfree (fname); return rc; } static void do_hash (gcry_md_hd_t md, gcry_md_hd_t md2, IOBUF fp, int textmode) { text_filter_context_t tfx; int c; if (textmode) { memset (&tfx, 0, sizeof tfx); iobuf_push_filter (fp, text_filter, &tfx); } if (md2) { /* work around a strange behaviour in pgp2 */ /* It seems that at least PGP5 converts a single CR to a CR,LF too */ int lc = -1; while ((c = iobuf_get (fp)) != -1) { if (c == '\n' && lc == '\r') gcry_md_putc (md2, c); else if (c == '\n') { gcry_md_putc (md2, '\r'); gcry_md_putc (md2, c); } else if (c != '\n' && lc == '\r') { gcry_md_putc (md2, '\n'); gcry_md_putc (md2, c); } else gcry_md_putc (md2, c); if (md) gcry_md_putc (md, c); lc = c; } } else { while ((c = iobuf_get (fp)) != -1) { if (md) gcry_md_putc (md, c); } } } /**************** * Ask for the detached datafile and calculate the digest from it. * INFILE is the name of the input file. */ int ask_for_detached_datafile (gcry_md_hd_t md, gcry_md_hd_t md2, const char *inname, int textmode) { progress_filter_context_t *pfx; char *answer = NULL; IOBUF fp; int rc = 0; pfx = new_progress_context (); fp = open_sigfile (inname, pfx); /* Open default file. */ if (!fp && !opt.batch) { int any = 0; tty_printf (_("Detached signature.\n")); do { char *name; xfree (answer); tty_enable_completion (NULL); name = cpr_get ("detached_signature.filename", _("Please enter name of data file: ")); tty_disable_completion (); cpr_kill_prompt (); answer = make_filename (name, (void *) NULL); xfree (name); if (any && !*answer) { rc = gpg_error (GPG_ERR_GENERAL); /*G10ERR_READ_FILE */ goto leave; } fp = iobuf_open (answer); if (fp && is_secured_file (iobuf_get_fd (fp))) { iobuf_close (fp); fp = NULL; errno = EPERM; } if (!fp && errno == ENOENT) { tty_printf ("No such file, try again or hit enter to quit.\n"); any++; } else if (!fp) { rc = gpg_error_from_syserror (); log_error (_("can't open `%s': %s\n"), answer, strerror (errno)); goto leave; } } while (!fp); } if (!fp) { if (opt.verbose) log_info (_("reading stdin ...\n")); fp = iobuf_open (NULL); assert (fp); } do_hash (md, md2, fp, textmode); iobuf_close (fp); leave: xfree (answer); release_progress_context (pfx); return rc; } /**************** * Hash the given files and append the hash to hash context md. * If FILES is NULL, hash stdin. */ int hash_datafiles (gcry_md_hd_t md, gcry_md_hd_t md2, strlist_t files, const char *sigfilename, int textmode) { progress_filter_context_t *pfx; IOBUF fp; strlist_t sl; pfx = new_progress_context (); if (!files) { /* check whether we can open the signed material */ fp = open_sigfile (sigfilename, pfx); if (fp) { do_hash (md, md2, fp, textmode); iobuf_close (fp); release_progress_context (pfx); return 0; } log_error (_("no signed data\n")); release_progress_context (pfx); return gpg_error (GPG_ERR_NO_DATA); } for (sl = files; sl; sl = sl->next) { fp = iobuf_open (sl->d); if (fp && is_secured_file (iobuf_get_fd (fp))) { iobuf_close (fp); fp = NULL; errno = EPERM; } if (!fp) { int rc = gpg_error_from_syserror (); log_error (_("can't open signed data `%s'\n"), print_fname_stdin (sl->d)); release_progress_context (pfx); return rc; } handle_progress (pfx, fp, sl->d); do_hash (md, md2, fp, textmode); iobuf_close (fp); } release_progress_context (pfx); return 0; } /* Hash the data from file descriptor DATA_FD and append the hash to hash contexts MD and MD2. */ int hash_datafile_by_fd (gcry_md_hd_t md, gcry_md_hd_t md2, int data_fd, int textmode) { progress_filter_context_t *pfx = new_progress_context (); iobuf_t fp; if (is_secured_file (data_fd)) { fp = NULL; errno = EPERM; } else fp = iobuf_fdopen_nc (data_fd, "rb"); if (!fp) { int rc = gpg_error_from_syserror (); log_error (_("can't open signed data fd=%d: %s\n"), data_fd, strerror (errno)); release_progress_context (pfx); return rc; } handle_progress (pfx, fp, NULL); do_hash (md, md2, fp, textmode); iobuf_close (fp); release_progress_context (pfx); return 0; } /* Set up a plaintext packet with the appropriate filename. If there is a --set-filename, use it (it's already UTF8). If there is a regular filename, UTF8-ize it if necessary. If there is no filenames at all, set the field empty. */ PKT_plaintext * setup_plaintext_name (const char *filename, IOBUF iobuf) { PKT_plaintext *pt; - if (filename || opt.set_filename) + if ((filename && !iobuf_is_pipe_filename (filename)) + || (opt.set_filename && !iobuf_is_pipe_filename (opt.set_filename))) { char *s; if (opt.set_filename) s = make_basename (opt.set_filename, iobuf_get_real_fname (iobuf)); else if (filename && !opt.flags.utf8_filename) { char *tmp = native_to_utf8 (filename); s = make_basename (tmp, iobuf_get_real_fname (iobuf)); xfree (tmp); } else s = make_basename (filename, iobuf_get_real_fname (iobuf)); pt = xmalloc (sizeof *pt + strlen (s) - 1); pt->namelen = strlen (s); memcpy (pt->name, s, pt->namelen); xfree (s); } else { /* no filename */ pt = xmalloc (sizeof *pt - 1); pt->namelen = 0; } return pt; } diff --git a/g10/seckey-cert.c b/g10/seckey-cert.c index 1398b181b..9995aa416 100644 --- a/g10/seckey-cert.c +++ b/g10/seckey-cert.c @@ -1,473 +1,473 @@ /* seckey-cert.c - secret key certificate packet handling * Copyright (C) 1998, 1999, 2000, 2001, 2002, * 2006, 2009 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 "gpg.h" #include "util.h" #include "packet.h" #include "keydb.h" #include "cipher.h" #include "main.h" #include "options.h" #include "i18n.h" #include "status.h" #include "pkglue.h" static int do_check( PKT_secret_key *sk, const char *tryagain_text, int mode, int *canceled ) { gpg_error_t err; byte *buffer; u16 csum=0; int i, res; size_t nbytes; if( sk->is_protected ) { /* remove the protection */ DEK *dek = NULL; u32 keyid[4]; /* 4! because we need two of them */ gcry_cipher_hd_t cipher_hd=NULL; PKT_secret_key *save_sk; if( sk->protect.s2k.mode == 1001 ) { log_info(_("secret key parts are not available\n")); return G10ERR_UNU_SECKEY; } if( sk->protect.algo == CIPHER_ALGO_NONE ) BUG(); if( openpgp_cipher_test_algo( sk->protect.algo ) ) { log_info(_("protection algorithm %d%s is not supported\n"), sk->protect.algo,sk->protect.algo==1?" (IDEA)":"" ); if (sk->protect.algo==CIPHER_ALGO_IDEA) { write_status (STATUS_RSA_OR_IDEA); idea_cipher_warn (0); } return G10ERR_CIPHER_ALGO; } if(gcry_md_test_algo (sk->protect.s2k.hash_algo)) { log_info(_("protection digest %d is not supported\n"), sk->protect.s2k.hash_algo); return G10ERR_DIGEST_ALGO; } keyid_from_sk( sk, keyid ); keyid[2] = keyid[3] = 0; if( !sk->is_primary ) { keyid[2] = sk->main_keyid[0]; keyid[3] = sk->main_keyid[1]; } dek = passphrase_to_dek( keyid, sk->pubkey_algo, sk->protect.algo, &sk->protect.s2k, mode, tryagain_text, canceled ); if (!dek && canceled && *canceled) - return G10ERR_GENERAL; + return GPG_ERR_CANCELED; err = openpgp_cipher_open (&cipher_hd, sk->protect.algo, GCRY_CIPHER_MODE_CFB, (GCRY_CIPHER_SECURE | (sk->protect.algo >= 100 ? 0 : GCRY_CIPHER_ENABLE_SYNC))); if (err) log_fatal ("cipher open failed: %s\n", gpg_strerror (err) ); err = gcry_cipher_setkey (cipher_hd, dek->key, dek->keylen); if (err) log_fatal ("set key failed: %s\n", gpg_strerror (err) ); xfree(dek); save_sk = copy_secret_key( NULL, sk ); gcry_cipher_setiv ( cipher_hd, sk->protect.iv, sk->protect.ivlen ); csum = 0; if( sk->version >= 4 ) { int ndata; unsigned int ndatabits; byte *p, *data; u16 csumc = 0; i = pubkey_get_npkey(sk->pubkey_algo); assert ( gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE )); p = gcry_mpi_get_opaque ( sk->skey[i], &ndatabits ); ndata = (ndatabits+7)/8; if ( ndata > 1 ) csumc = p[ndata-2] << 8 | p[ndata-1]; data = xmalloc_secure ( ndata ); gcry_cipher_decrypt ( cipher_hd, data, ndata, p, ndata ); gcry_mpi_release (sk->skey[i]); sk->skey[i] = NULL ; p = data; if (sk->protect.sha1chk) { /* This is the new SHA1 checksum method to detect tampering with the key as used by the Klima/Rosa attack */ sk->csum = 0; csum = 1; if( ndata < 20 ) log_error("not enough bytes for SHA-1 checksum\n"); else { gcry_md_hd_t h; if ( gcry_md_open (&h, DIGEST_ALGO_SHA1, 1)) BUG(); /* Algo not available. */ gcry_md_write (h, data, ndata - 20); gcry_md_final (h); if (!memcmp (gcry_md_read (h, DIGEST_ALGO_SHA1), data + ndata - 20, 20) ) { /* Digest does match. We have to keep the old style checksum in sk->csum, so that the test used for unprotected keys does work. This test gets used when we are adding new keys. */ sk->csum = csum = checksum (data, ndata-20); } gcry_md_close (h); } } else { if( ndata < 2 ) { log_error("not enough bytes for checksum\n"); sk->csum = 0; csum = 1; } else { csum = checksum( data, ndata-2); sk->csum = data[ndata-2] << 8 | data[ndata-1]; if ( sk->csum != csum ) { /* This is a PGP 7.0.0 workaround */ sk->csum = csumc; /* take the encrypted one */ } } } /* Must check it here otherwise the mpi_read_xx would fail because the length may have an arbitrary value */ if( sk->csum == csum ) { for( ; i < pubkey_get_nskey(sk->pubkey_algo); i++ ) { if ( gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_PGP, p, ndata, &nbytes)) { /* Checksum was okay, but not correctly decrypted. */ sk->csum = 0; csum = 1; break; } ndata -= nbytes; p += nbytes; } /* Note: at this point ndata should be 2 for a simple checksum or 20 for the sha1 digest */ } xfree(data); } else { for(i=pubkey_get_npkey(sk->pubkey_algo); i < pubkey_get_nskey(sk->pubkey_algo); i++ ) { byte *p; size_t ndata; unsigned int ndatabits; assert (gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE)); p = gcry_mpi_get_opaque (sk->skey[i], &ndatabits); ndata = (ndatabits+7)/8; assert (ndata >= 2); assert (ndata == ((p[0] << 8 | p[1]) + 7)/8 + 2); buffer = xmalloc_secure (ndata); gcry_cipher_sync (cipher_hd); buffer[0] = p[0]; buffer[1] = p[1]; gcry_cipher_decrypt (cipher_hd, buffer+2, ndata-2, p+2, ndata-2); csum += checksum (buffer, ndata); gcry_mpi_release (sk->skey[i]); err = gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_PGP, buffer, ndata, &ndata ); xfree (buffer); if (err) { /* Checksum was okay, but not correctly decrypted. */ sk->csum = 0; csum = 1; break; } /* csum += checksum_mpi (sk->skey[i]); */ } } gcry_cipher_close ( cipher_hd ); /* Now let's see whether we have used the correct passphrase. */ if( csum != sk->csum ) { copy_secret_key( sk, save_sk ); passphrase_clear_cache ( keyid, NULL, sk->pubkey_algo ); free_secret_key( save_sk ); return gpg_error (GPG_ERR_BAD_PASSPHRASE); } /* The checksum may fail, so we also check the key itself. */ res = pk_check_secret_key ( sk->pubkey_algo, sk->skey ); if( res ) { copy_secret_key( sk, save_sk ); passphrase_clear_cache ( keyid, NULL, sk->pubkey_algo ); free_secret_key( save_sk ); return gpg_error (GPG_ERR_BAD_PASSPHRASE); } free_secret_key( save_sk ); sk->is_protected = 0; } else { /* not protected, assume it is okay if the checksum is okay */ csum = 0; for(i=pubkey_get_npkey(sk->pubkey_algo); i < pubkey_get_nskey(sk->pubkey_algo); i++ ) { csum += checksum_mpi( sk->skey[i] ); } if( csum != sk->csum ) return G10ERR_CHECKSUM; } return 0; } /**************** * Check the secret key * Ask up to 3 (or n) times for a correct passphrase * If n is negative, disable the key info prompt and make n=abs(n) */ int check_secret_key( PKT_secret_key *sk, int n ) { int rc = gpg_error (GPG_ERR_BAD_PASSPHRASE); int i,mode; if (sk && sk->is_protected && sk->protect.s2k.mode == 1002) return 0; /* Let the scdaemon handle this. */ if(n<0) { n=abs(n); mode=1; } else mode=0; if( n < 1 ) n = 3; /* Use the default value */ for(i=0; i < n && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE; i++ ) { int canceled = 0; const char *tryagain = NULL; if (i) { tryagain = N_("Invalid passphrase; please try again"); log_info (_("%s ...\n"), _(tryagain)); } rc = do_check( sk, tryagain, mode, &canceled ); if ( gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && is_status_enabled () ) { u32 kid[2]; char buf[50]; keyid_from_sk( sk, kid ); sprintf(buf, "%08lX%08lX", (ulong)kid[0], (ulong)kid[1]); write_status_text( STATUS_BAD_PASSPHRASE, buf ); } if( have_static_passphrase() || canceled) break; } if( !rc ) write_status( STATUS_GOOD_PASSPHRASE ); return rc; } /**************** * check whether the secret key is protected. * Returns: 0 not protected, -1 on error or the protection algorithm * -2 indicates a card stub. * -3 indicates a not-online stub. */ int is_secret_key_protected( PKT_secret_key *sk ) { return sk->is_protected? sk->protect.s2k.mode == 1002? -2 : sk->protect.s2k.mode == 1001? -3 : sk->protect.algo : 0; } /**************** * Protect the secret key with the passphrase from DEK */ int protect_secret_key( PKT_secret_key *sk, DEK *dek ) { int i,j, rc = 0; byte *buffer; size_t nbytes; u16 csum; if( !dek ) return 0; if( !sk->is_protected ) { /* okay, apply the protection */ gcry_cipher_hd_t cipher_hd=NULL; if ( openpgp_cipher_test_algo ( sk->protect.algo ) ) { /* Unsupport protection algorithm. */ rc = gpg_error (GPG_ERR_CIPHER_ALGO); } else { print_cipher_algo_note( sk->protect.algo ); if ( openpgp_cipher_open (&cipher_hd, sk->protect.algo, GCRY_CIPHER_MODE_CFB, (GCRY_CIPHER_SECURE | (sk->protect.algo >= 100 ? 0 : GCRY_CIPHER_ENABLE_SYNC))) ) BUG(); if ( gcry_cipher_setkey ( cipher_hd, dek->key, dek->keylen ) ) log_info(_("WARNING: Weak key detected" " - please change passphrase again.\n")); sk->protect.ivlen = openpgp_cipher_get_algo_blklen (sk->protect.algo); assert( sk->protect.ivlen <= DIM(sk->protect.iv) ); if( sk->protect.ivlen != 8 && sk->protect.ivlen != 16 ) BUG(); /* yes, we are very careful */ gcry_create_nonce (sk->protect.iv, sk->protect.ivlen); gcry_cipher_setiv (cipher_hd, sk->protect.iv, sk->protect.ivlen); if( sk->version >= 4 ) { byte *bufarr[PUBKEY_MAX_NSKEY]; size_t narr[PUBKEY_MAX_NSKEY]; unsigned int nbits[PUBKEY_MAX_NSKEY]; int ndata=0; byte *p, *data; for (j=0, i = pubkey_get_npkey(sk->pubkey_algo); i < pubkey_get_nskey(sk->pubkey_algo); i++, j++ ) { assert (!gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE)); if (gcry_mpi_aprint (GCRYMPI_FMT_USG, bufarr+j, narr+j, sk->skey[i])) BUG(); nbits[j] = gcry_mpi_get_nbits (sk->skey[i]); ndata += narr[j] + 2; } for ( ; j < PUBKEY_MAX_NSKEY; j++ ) bufarr[j] = NULL; ndata += opt.simple_sk_checksum? 2 : 20; /* for checksum */ data = xmalloc_secure( ndata ); p = data; for(j=0; j < PUBKEY_MAX_NSKEY && bufarr[j]; j++ ) { p[0] = nbits[j] >> 8 ; p[1] = nbits[j]; p += 2; memcpy(p, bufarr[j], narr[j] ); p += narr[j]; xfree(bufarr[j]); } if (opt.simple_sk_checksum) { log_info (_("generating the deprecated 16-bit checksum" " for secret key protection\n")); csum = checksum( data, ndata-2); sk->csum = csum; *p++ = csum >> 8; *p++ = csum; sk->protect.sha1chk = 0; } else { gcry_md_hd_t h; if (gcry_md_open (&h, GCRY_MD_SHA1, 1)) BUG(); /* Algo not available. */ gcry_md_write (h, data, ndata - 20); gcry_md_final (h); memcpy (p, gcry_md_read (h, DIGEST_ALGO_SHA1), 20); p += 20; gcry_md_close (h); sk->csum = csum = 0; sk->protect.sha1chk = 1; } assert( p == data+ndata ); gcry_cipher_encrypt (cipher_hd, data, ndata, NULL, 0); for (i = pubkey_get_npkey(sk->pubkey_algo); i < pubkey_get_nskey(sk->pubkey_algo); i++ ) { gcry_mpi_release (sk->skey[i]); sk->skey[i] = NULL; } i = pubkey_get_npkey(sk->pubkey_algo); sk->skey[i] = gcry_mpi_set_opaque (NULL, data, ndata*8 ); } else { csum = 0; for(i=pubkey_get_npkey(sk->pubkey_algo); i < pubkey_get_nskey(sk->pubkey_algo); i++ ) { byte *data; unsigned int nbits; csum += checksum_mpi (sk->skey[i]); if (gcry_mpi_aprint (GCRYMPI_FMT_USG, &buffer, &nbytes, sk->skey[i] )) BUG(); gcry_cipher_sync (cipher_hd); assert (!gcry_mpi_get_flag (sk->skey[i], GCRYMPI_FLAG_OPAQUE)); data = xmalloc (nbytes+2); /* fixme: need xtrymalloc. */ nbits = gcry_mpi_get_nbits (sk->skey[i]); assert (nbytes == (nbits + 7)/8); data[0] = nbits >> 8; data[1] = nbits; gcry_cipher_encrypt (cipher_hd, data+2, nbytes, buffer, nbytes); xfree( buffer ); gcry_mpi_release (sk->skey[i]); sk->skey[i] = gcry_mpi_set_opaque (NULL, data, (nbytes+2)*8 ); } sk->csum = csum; } sk->is_protected = 1; gcry_cipher_close (cipher_hd); } } return rc; } diff --git a/g10/trustdb.c b/g10/trustdb.c index 2a1fc87bd..f1377aa1f 100644 --- a/g10/trustdb.c +++ b/g10/trustdb.c @@ -1,2501 +1,2502 @@ /* trustdb.c * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, * 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 . */ #include #include #include #include #include #ifndef DISABLE_REGEX #include #include #endif /* !DISABLE_REGEX */ #include "gpg.h" #include "status.h" #include "iobuf.h" #include "keydb.h" #include "util.h" #include "options.h" #include "packet.h" #include "main.h" #include "i18n.h" #include "tdbio.h" #include "trustdb.h" /* * A structure to store key identification as well as some stuff needed * for validation */ struct key_item { struct key_item *next; unsigned int ownertrust,min_ownertrust; byte trust_depth; byte trust_value; char *trust_regexp; u32 kid[2]; }; typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */ /* * Structure to keep track of keys, this is used as an array wherre * the item right after the last one has a keyblock set to NULL. * Maybe we can drop this thing and replace it by key_item */ struct key_array { KBNODE keyblock; }; /* control information for the trust DB */ static struct { int init; int level; char *dbname; } trustdb_args; /* some globals */ static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */ static struct key_item *utk_list; /* all ultimately trusted keys */ static int pending_check_trustdb; static int validate_keys (int interactive); /********************************************** ************* some helpers ******************* **********************************************/ static struct key_item * new_key_item (void) { struct key_item *k; k = xmalloc_clear (sizeof *k); return k; } static void release_key_items (struct key_item *k) { struct key_item *k2; for (; k; k = k2) { k2 = k->next; xfree (k->trust_regexp); xfree (k); } } /* * For fast keylook up we need a hash table. Each byte of a KeyIDs * should be distributed equally over the 256 possible values (except * for v3 keyIDs but we consider them as not important here). So we * can just use 10 bits to index a table of 1024 key items. * Possible optimization: Don not use key_items but other hash_table when the * duplicates lists gets too large. */ static KeyHashTable new_key_hash_table (void) { struct key_item **tbl; tbl = xmalloc_clear (1024 * sizeof *tbl); return tbl; } static void release_key_hash_table (KeyHashTable tbl) { int i; if (!tbl) return; for (i=0; i < 1024; i++) release_key_items (tbl[i]); xfree (tbl); } /* * Returns: True if the keyID is in the given hash table */ static int test_key_hash_table (KeyHashTable tbl, u32 *kid) { struct key_item *k; for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next) if (k->kid[0] == kid[0] && k->kid[1] == kid[1]) return 1; return 0; } /* * Add a new key to the hash table. The key is identified by its key ID. */ static void add_key_hash_table (KeyHashTable tbl, u32 *kid) { struct key_item *k, *kk; for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next) if (k->kid[0] == kid[0] && k->kid[1] == kid[1]) return; /* already in table */ kk = new_key_item (); kk->kid[0] = kid[0]; kk->kid[1] = kid[1]; kk->next = tbl[(kid[1] & 0x03ff)]; tbl[(kid[1] & 0x03ff)] = kk; } /* * Release a key_array */ static void release_key_array ( struct key_array *keys ) { struct key_array *k; if (keys) { for (k=keys; k->keyblock; k++) release_kbnode (k->keyblock); xfree (keys); } } /********************************************* ********** Initialization ***************** *********************************************/ /* * Used to register extra ultimately trusted keys - this has to be done * before initializing the validation module. * FIXME: Should be replaced by a function to add those keys to the trustdb. */ void register_trusted_keyid(u32 *keyid) { struct key_item *k; k = new_key_item (); k->kid[0] = keyid[0]; k->kid[1] = keyid[1]; k->next = user_utk_list; user_utk_list = k; } void register_trusted_key( const char *string ) { gpg_error_t err; KEYDB_SEARCH_DESC desc; err = classify_user_id (string, &desc); if (err || desc.mode != KEYDB_SEARCH_MODE_LONG_KID ) { log_error(_("`%s' is not a valid long keyID\n"), string ); return; } register_trusted_keyid(desc.u.kid); } /* * Helper to add a key to the global list of ultimately trusted keys. * Retruns: true = inserted, false = already in in list. */ static int add_utk (u32 *kid) { struct key_item *k; for (k = utk_list; k; k = k->next) { if (k->kid[0] == kid[0] && k->kid[1] == kid[1]) { return 0; } } k = new_key_item (); k->kid[0] = kid[0]; k->kid[1] = kid[1]; k->ownertrust = TRUST_ULTIMATE; k->next = utk_list; utk_list = k; if( opt.verbose > 1 ) log_info(_("key %s: accepted as trusted key\n"), keystr(kid)); return 1; } /**************** * Verify that all our secret keys are usable and put them into the utk_list. */ static void verify_own_keys(void) { TRUSTREC rec; ulong recnum; int rc; struct key_item *k; if (utk_list) return; /* scan the trustdb to find all ultimately trusted keys */ for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ ) { if ( rec.rectype == RECTYPE_TRUST && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE) { byte *fpr = rec.r.trust.fingerprint; int fprlen; u32 kid[2]; /* Problem: We do only use fingerprints in the trustdb but * we need the keyID here to indetify the key; we can only * use that ugly hack to distinguish between 16 and 20 * butes fpr - it does not work always so we better change * the whole validation code to only work with * fingerprints */ fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20; keyid_from_fingerprint (fpr, fprlen, kid); if (!add_utk (kid)) log_info(_("key %s occurs more than once in the trustdb\n"), keystr(kid)); } } /* Put any --trusted-key keys into the trustdb */ for (k = user_utk_list; k; k = k->next) { if ( add_utk (k->kid) ) { /* not yet in trustDB as ultimately trusted */ PKT_public_key pk; memset (&pk, 0, sizeof pk); rc = get_pubkey (&pk, k->kid); if (rc) log_info(_("key %s: no public key for trusted key - skipped\n"), keystr(k->kid)); else { update_ownertrust (&pk, ((get_ownertrust (&pk) & ~TRUST_MASK) | TRUST_ULTIMATE )); release_public_key_parts (&pk); } log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid)); } } /* release the helper table table */ release_key_items (user_utk_list); user_utk_list = NULL; return; } /********************************************* *********** TrustDB stuff ******************* *********************************************/ /* * Read a record but die if it does not exist */ static void read_record (ulong recno, TRUSTREC *rec, int rectype ) { int rc = tdbio_read_record (recno, rec, rectype); if (rc) { log_error(_("trust record %lu, req type %d: read failed: %s\n"), recno, rec->rectype, g10_errstr(rc) ); tdbio_invalid(); } if (rectype != rec->rectype) { log_error(_("trust record %lu is not of requested type %d\n"), rec->recnum, rectype); tdbio_invalid(); } } /* * Write a record and die on error */ static void write_record (TRUSTREC *rec) { int rc = tdbio_write_record (rec); if (rc) { log_error(_("trust record %lu, type %d: write failed: %s\n"), rec->recnum, rec->rectype, g10_errstr(rc) ); tdbio_invalid(); } } /* * sync the TrustDb and die on error */ static void do_sync(void) { int rc = tdbio_sync (); if(rc) { log_error (_("trustdb: sync failed: %s\n"), g10_errstr(rc) ); g10_exit(2); } } static const char * trust_model_string(void) { switch(opt.trust_model) { case TM_CLASSIC: return "classic"; case TM_PGP: return "PGP"; case TM_EXTERNAL: return "external"; case TM_ALWAYS: return "always"; case TM_DIRECT: return "direct"; default: return "unknown"; } } /**************** * Perform some checks over the trustdb * level 0: only open the db * 1: used for initial program startup */ int setup_trustdb( int level, const char *dbname ) { /* just store the args */ if( trustdb_args.init ) return 0; trustdb_args.level = level; trustdb_args.dbname = dbname? xstrdup(dbname): NULL; return 0; } void how_to_fix_the_trustdb () { const char *name = trustdb_args.dbname; if (!name) name = "trustdb.gpg"; log_info (_("You may try to re-create the trustdb using the commands:\n")); log_info (" cd %s\n", default_homedir ()); log_info (" gpg2 --export-ownertrust > otrust.tmp\n"); #ifdef HAVE_W32_SYSTEM log_info (" del %s\n", name); #else log_info (" rm %s\n", name); #endif log_info (" gpg2 --import-ownertrust < otrust.tmp\n"); log_info (_("If that does not work, please consult the manual\n")); } void init_trustdb() { int level = trustdb_args.level; const char* dbname = trustdb_args.dbname; if( trustdb_args.init ) return; trustdb_args.init = 1; if(level==0 || level==1) { int rc = tdbio_set_dbname( dbname, !!level ); if( rc ) log_fatal("can't init trustdb: %s\n", g10_errstr(rc) ); } else BUG(); if(opt.trust_model==TM_AUTO) { /* Try and set the trust model off of whatever the trustdb says it is. */ opt.trust_model=tdbio_read_model(); /* Sanity check this ;) */ if(opt.trust_model!=TM_CLASSIC && opt.trust_model!=TM_PGP && opt.trust_model!=TM_EXTERNAL) { log_info(_("unable to use unknown trust model (%d) - " "assuming %s trust model\n"),opt.trust_model,"PGP"); opt.trust_model=TM_PGP; } if(opt.verbose) log_info(_("using %s trust model\n"),trust_model_string()); } if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC) { /* Verify the list of ultimately trusted keys and move the --trusted-keys list there as well. */ if(level==1) verify_own_keys(); if(!tdbio_db_matches_options()) pending_check_trustdb=1; } } /*********************************************** ************* Print helpers **************** ***********************************************/ /**************** * This function returns a letter for a trustvalue Trust flags * are ignore. */ static int trust_letter (unsigned int value) { switch( (value & TRUST_MASK) ) { case TRUST_UNKNOWN: return '-'; case TRUST_EXPIRED: return 'e'; case TRUST_UNDEFINED: return 'q'; case TRUST_NEVER: return 'n'; case TRUST_MARGINAL: return 'm'; case TRUST_FULLY: return 'f'; case TRUST_ULTIMATE: return 'u'; default: return '?'; } } /* NOTE TO TRANSLATOR: these strings are similar to those in trust_value_to_string(), but are a fixed length. This is needed to make attractive information listings where columns line up properly. The value "10" should be the length of the strings you choose to translate to. This is the length in printable columns. It gets passed to atoi() so everything after the number is essentially a comment and need not be translated. Either key and uid are both NULL, or neither are NULL. */ const char * uid_trust_string_fixed(PKT_public_key *key,PKT_user_id *uid) { if(!key && !uid) return _("10 translator see trustdb.c:uid_trust_string_fixed"); else if(uid->is_revoked || (key && key->is_revoked)) return _("[ revoked]"); else if(uid->is_expired) return _("[ expired]"); else if(key) switch(get_validity(key,uid)&TRUST_MASK) { case TRUST_UNKNOWN: return _("[ unknown]"); case TRUST_EXPIRED: return _("[ expired]"); case TRUST_UNDEFINED: return _("[ undef ]"); case TRUST_MARGINAL: return _("[marginal]"); case TRUST_FULLY: return _("[ full ]"); case TRUST_ULTIMATE: return _("[ultimate]"); } return "err"; } /* The strings here are similar to those in pkclist.c:do_edit_ownertrust() */ const char * trust_value_to_string (unsigned int value) { switch( (value & TRUST_MASK) ) { case TRUST_UNKNOWN: return _("unknown"); case TRUST_EXPIRED: return _("expired"); case TRUST_UNDEFINED: return _("undefined"); case TRUST_NEVER: return _("never"); case TRUST_MARGINAL: return _("marginal"); case TRUST_FULLY: return _("full"); case TRUST_ULTIMATE: return _("ultimate"); default: return "err"; } } int string_to_trust_value (const char *str) { if(ascii_strcasecmp(str,"undefined")==0) return TRUST_UNDEFINED; else if(ascii_strcasecmp(str,"never")==0) return TRUST_NEVER; else if(ascii_strcasecmp(str,"marginal")==0) return TRUST_MARGINAL; else if(ascii_strcasecmp(str,"full")==0) return TRUST_FULLY; else if(ascii_strcasecmp(str,"ultimate")==0) return TRUST_ULTIMATE; else return -1; } /**************** * Recreate the WoT but do not ask for new ownertrusts. Special * feature: In batch mode and without a forced yes, this is only done * when a check is due. This can be used to run the check from a crontab */ void check_trustdb () { init_trustdb(); if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC) { if (opt.batch && !opt.answer_yes) { ulong scheduled; scheduled = tdbio_read_nextcheck (); if (!scheduled) { log_info (_("no need for a trustdb check\n")); return; } if (scheduled > make_timestamp ()) { log_info (_("next trustdb check due at %s\n"), strtimestamp (scheduled)); return; } } validate_keys (0); } else log_info (_("no need for a trustdb check with `%s' trust model\n"), trust_model_string()); } /* * Recreate the WoT. */ void update_trustdb() { init_trustdb(); if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC) validate_keys (1); else log_info (_("no need for a trustdb update with `%s' trust model\n"), trust_model_string()); } void revalidation_mark (void) { init_trustdb(); /* we simply set the time for the next check to 1 (far back in 1970) * so that a --update-trustdb will be scheduled */ if (tdbio_write_nextcheck (1)) do_sync (); pending_check_trustdb = 1; } int trustdb_pending_check(void) { return pending_check_trustdb; } /* If the trustdb is dirty, and we're interactive, update it. Otherwise, check it unless no-auto-check-trustdb is set. */ void trustdb_check_or_update(void) { if(trustdb_pending_check()) { if(opt.interactive) update_trustdb(); else if(!opt.no_auto_check_trustdb) check_trustdb(); } } void read_trust_options(byte *trust_model,ulong *created,ulong *nextcheck, byte *marginals,byte *completes,byte *cert_depth) { TRUSTREC opts; init_trustdb(); read_record(0,&opts,RECTYPE_VER); if(trust_model) *trust_model=opts.r.ver.trust_model; if(created) *created=opts.r.ver.created; if(nextcheck) *nextcheck=opts.r.ver.nextcheck; if(marginals) *marginals=opts.r.ver.marginals; if(completes) *completes=opts.r.ver.completes; if(cert_depth) *cert_depth=opts.r.ver.cert_depth; } /*********************************************** *********** Ownertrust et al. **************** ***********************************************/ static int read_trust_record (PKT_public_key *pk, TRUSTREC *rec) { int rc; init_trustdb(); rc = tdbio_search_trust_bypk (pk, rec); if (rc == -1) return -1; /* no record yet */ if (rc) { log_error ("trustdb: searching trust record failed: %s\n", g10_errstr (rc)); return rc; } if (rec->rectype != RECTYPE_TRUST) { log_error ("trustdb: record %lu is not a trust record\n", rec->recnum); return G10ERR_TRUSTDB; } return 0; } /**************** * Return the assigned ownertrust value for the given public key. * The key should be the primary key. */ unsigned int get_ownertrust ( PKT_public_key *pk) { TRUSTREC rec; int rc; rc = read_trust_record (pk, &rec); if (rc == -1) return TRUST_UNKNOWN; /* no record yet */ if (rc) { tdbio_invalid (); return rc; /* actually never reached */ } return rec.r.trust.ownertrust; } unsigned int get_min_ownertrust (PKT_public_key *pk) { TRUSTREC rec; int rc; rc = read_trust_record (pk, &rec); if (rc == -1) return TRUST_UNKNOWN; /* no record yet */ if (rc) { tdbio_invalid (); return rc; /* actually never reached */ } return rec.r.trust.min_ownertrust; } /* * Same as get_ownertrust but this takes the minimum ownertrust value * into into account, and will bump up the value as needed. */ static int get_ownertrust_with_min (PKT_public_key *pk) { unsigned int otrust,otrust_min; otrust = (get_ownertrust (pk) & TRUST_MASK); otrust_min = get_min_ownertrust (pk); if(otrustnamehash, 20) ) break; recno = vrec.r.valid.next; } if (!recno) /* insert a new validity record */ { memset (&vrec, 0, sizeof vrec); vrec.recnum = tdbio_new_recnum (); vrec.rectype = RECTYPE_VALID; memcpy (vrec.r.valid.namehash, uid->namehash, 20); vrec.r.valid.next = trec.r.trust.validlist; trec.r.trust.validlist = vrec.recnum; } vrec.r.valid.validity = validity; vrec.r.valid.full_count = uid->help_full_count; vrec.r.valid.marginal_count = uid->help_marginal_count; write_record (&vrec); trec.r.trust.depth = depth; write_record (&trec); } /*********************************************** ********* Query trustdb values ************** ***********************************************/ /* Return true if key is disabled */ int cache_disabled_value(PKT_public_key *pk) { int rc; TRUSTREC trec; int disabled=0; if(pk->is_disabled) return (pk->is_disabled==2); init_trustdb(); rc = read_trust_record (pk, &trec); if (rc && rc != -1) { tdbio_invalid (); goto leave; } if (rc == -1) /* no record found, so assume not disabled */ goto leave; if(trec.r.trust.ownertrust & TRUST_FLAG_DISABLED) disabled=1; /* Cache it for later so we don't need to look at the trustdb every time */ if(disabled) pk->is_disabled=2; else pk->is_disabled=1; leave: return disabled; } void check_trustdb_stale(void) { static int did_nextcheck=0; init_trustdb (); if (!did_nextcheck && (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)) { ulong scheduled; did_nextcheck = 1; scheduled = tdbio_read_nextcheck (); if (scheduled && scheduled <= make_timestamp ()) { if (opt.no_auto_check_trustdb) { pending_check_trustdb = 1; log_info (_("please do a --check-trustdb\n")); } else { log_info (_("checking the trustdb\n")); validate_keys (0); } } } } /* * Return the validity information for PK. If the namehash is not * NULL, the validity of the corresponsing user ID is returned, * otherwise, a reasonable value for the entire key is returned. */ unsigned int get_validity (PKT_public_key *pk, PKT_user_id *uid) { TRUSTREC trec, vrec; int rc; ulong recno; unsigned int validity; u32 kid[2]; PKT_public_key *main_pk; if(uid) namehash_from_uid(uid); init_trustdb (); check_trustdb_stale(); keyid_from_pk (pk, kid); if (pk->main_keyid[0] != kid[0] || pk->main_keyid[1] != kid[1]) { /* this is a subkey - get the mainkey */ main_pk = xmalloc_clear (sizeof *main_pk); rc = get_pubkey (main_pk, pk->main_keyid); if (rc) { char *tempkeystr=xstrdup(keystr(pk->main_keyid)); log_error ("error getting main key %s of subkey %s: %s\n", tempkeystr, keystr(kid), g10_errstr(rc)); xfree(tempkeystr); validity = TRUST_UNKNOWN; goto leave; } } else main_pk = pk; if(opt.trust_model==TM_DIRECT) { /* Note that this happens BEFORE any user ID stuff is checked. The direct trust model applies to keys as a whole. */ validity=get_ownertrust(main_pk); goto leave; } rc = read_trust_record (main_pk, &trec); if (rc && rc != -1) { tdbio_invalid (); return 0; } if (rc == -1) /* no record found */ { validity = TRUST_UNKNOWN; goto leave; } /* loop over all user IDs */ recno = trec.r.trust.validlist; validity = 0; while (recno) { read_record (recno, &vrec, RECTYPE_VALID); if(uid) { /* If a user ID is given we return the validity for that user ID ONLY. If the namehash is not found, then there is no validity at all (i.e. the user ID wasn't signed). */ if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0) { validity=(vrec.r.valid.validity & TRUST_MASK); break; } } else { /* If no namehash is given, we take the maximum validity over all user IDs */ if ( validity < (vrec.r.valid.validity & TRUST_MASK) ) validity = (vrec.r.valid.validity & TRUST_MASK); } recno = vrec.r.valid.next; } if ( (trec.r.trust.ownertrust & TRUST_FLAG_DISABLED) ) { validity |= TRUST_FLAG_DISABLED; pk->is_disabled=2; } else pk->is_disabled=1; leave: /* set some flags direct from the key */ if (main_pk->is_revoked) validity |= TRUST_FLAG_REVOKED; if (main_pk != pk && pk->is_revoked) validity |= TRUST_FLAG_SUB_REVOKED; /* Note: expiration is a trust value and not a flag - don't know why * I initially designed it that way */ if (main_pk->has_expired || pk->has_expired) validity = (validity & ~TRUST_MASK) | TRUST_EXPIRED; if (pending_check_trustdb) validity |= TRUST_FLAG_PENDING_CHECK; if (main_pk != pk) free_public_key (main_pk); return validity; } int get_validity_info (PKT_public_key *pk, PKT_user_id *uid) { int trustlevel; if (!pk) return '?'; /* Just in case a NULL PK is passed. */ trustlevel = get_validity (pk, uid); if ( (trustlevel & TRUST_FLAG_REVOKED) ) return 'r'; return trust_letter (trustlevel); } const char * get_validity_string (PKT_public_key *pk, PKT_user_id *uid) { int trustlevel; if (!pk) return "err"; /* Just in case a NULL PK is passed. */ trustlevel = get_validity (pk, uid); if( trustlevel & TRUST_FLAG_REVOKED ) return _("revoked"); return trust_value_to_string(trustlevel); } static void get_validity_counts (PKT_public_key *pk, PKT_user_id *uid) { TRUSTREC trec, vrec; ulong recno; if(pk==NULL || uid==NULL) BUG(); namehash_from_uid(uid); uid->help_marginal_count=uid->help_full_count=0; init_trustdb (); if(read_trust_record (pk, &trec)!=0) return; /* loop over all user IDs */ recno = trec.r.trust.validlist; while (recno) { read_record (recno, &vrec, RECTYPE_VALID); if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0) { uid->help_marginal_count=vrec.r.valid.marginal_count; uid->help_full_count=vrec.r.valid.full_count; /* printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */ break; } recno = vrec.r.valid.next; } } void list_trust_path( const char *username ) { (void)username; } /**************** * Enumerate all keys, which are needed to build all trust paths for * the given key. This function does not return the key itself or * the ultimate key (the last point in cerificate chain). Only * certificate chains which ends up at an ultimately trusted key * are listed. If ownertrust or validity is not NULL, the corresponding * value for the returned LID is also returned in these variable(s). * * 1) create a void pointer and initialize it to NULL * 2) pass this void pointer by reference to this function. * Set lid to the key you want to enumerate and pass it by reference. * 3) call this function as long as it does not return -1 * to indicate EOF. LID does contain the next key used to build the web * 4) Always call this function a last time with LID set to NULL, * so that it can free its context. * * Returns: -1 on EOF or the level of the returned LID */ int enum_cert_paths( void **context, ulong *lid, unsigned *ownertrust, unsigned *validity ) { (void)context; (void)lid; (void)ownertrust; (void)validity; return -1; } /**************** * Print the current path */ void enum_cert_paths_print (void **context, FILE *fp, int refresh, ulong selected_lid) { (void)context; (void)fp; (void)refresh; (void)selected_lid; } /**************************************** *********** NEW NEW NEW **************** ****************************************/ static int ask_ownertrust (u32 *kid,int minimum) { PKT_public_key *pk; int rc; int ot; pk = xmalloc_clear (sizeof *pk); rc = get_pubkey (pk, kid); if (rc) { log_error (_("public key %s not found: %s\n"), keystr(kid), g10_errstr(rc) ); return TRUST_UNKNOWN; } if(opt.force_ownertrust) { log_info("force trust for key %s to %s\n", keystr(kid),trust_value_to_string(opt.force_ownertrust)); update_ownertrust(pk,opt.force_ownertrust); ot=opt.force_ownertrust; } else { ot=edit_ownertrust(pk,0); if(ot>0) ot = get_ownertrust (pk); else if(ot==0) ot = minimum?minimum:TRUST_UNDEFINED; else ot = -1; /* quit */ } free_public_key( pk ); return ot; } static void mark_keyblock_seen (KeyHashTable tbl, KBNODE node) { for ( ;node; node = node->next ) if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { u32 aki[2]; keyid_from_pk (node->pkt->pkt.public_key, aki); add_key_hash_table (tbl, aki); } } static void dump_key_array (int depth, struct key_array *keys) { struct key_array *kar; for (kar=keys; kar->keyblock; kar++) { KBNODE node = kar->keyblock; u32 kid[2]; keyid_from_pk(node->pkt->pkt.public_key, kid); printf ("%d:%08lX%08lX:K::%c::::\n", depth, (ulong)kid[0], (ulong)kid[1], '?'); for (; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { int len = node->pkt->pkt.user_id->len; if (len > 30) len = 30; printf ("%d:%08lX%08lX:U:::%c:::", depth, (ulong)kid[0], (ulong)kid[1], (node->flag & 4)? 'f': (node->flag & 2)? 'm': (node->flag & 1)? 'q':'-'); - print_string (stdout, node->pkt->pkt.user_id->name, len, ':'); + es_write_sanitized (es_stdout, node->pkt->pkt.user_id->name, + len, ":", NULL); putchar (':'); putchar ('\n'); } } } } static void store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored) { KBNODE node; int status; int any = 0; for (node=keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = node->pkt->pkt.user_id; if (node->flag & 4) status = TRUST_FULLY; else if (node->flag & 2) status = TRUST_MARGINAL; else if (node->flag & 1) status = TRUST_UNDEFINED; else status = 0; if (status) { update_validity (keyblock->pkt->pkt.public_key, uid, depth, status); mark_keyblock_seen(stored,keyblock); any = 1; } } } if (any) do_sync (); } /* * check whether the signature sig is in the klist k */ static struct key_item * is_in_klist (struct key_item *k, PKT_signature *sig) { for (; k; k = k->next) { if (k->kid[0] == sig->keyid[0] && k->kid[1] == sig->keyid[1]) return k; } return NULL; } /* * Mark the signature of the given UID which are used to certify it. * To do this, we first revmove all signatures which are not valid and * from the remain ones we look for the latest one. If this is not a * certification revocation signature we mark the signature by setting * node flag bit 8. Revocations are marked with flag 11, and sigs * from unavailable keys are marked with flag 12. Note that flag bits * 9 and 10 are used for internal purposes. */ static void mark_usable_uid_certs (KBNODE keyblock, KBNODE uidnode, u32 *main_kid, struct key_item *klist, u32 curtime, u32 *next_expire) { KBNODE node; PKT_signature *sig; /* first check all signatures */ for (node=uidnode->next; node; node = node->next) { int rc; node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12); if (node->pkt->pkttype == PKT_USER_ID || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) break; /* ready */ if (node->pkt->pkttype != PKT_SIGNATURE) continue; sig = node->pkt->pkt.signature; if (main_kid && sig->keyid[0] == main_kid[0] && sig->keyid[1] == main_kid[1]) continue; /* ignore self-signatures if we pass in a main_kid */ if (!IS_UID_SIG(sig) && !IS_UID_REV(sig)) continue; /* we only look at these signature classes */ if(sig->sig_class>=0x11 && sig->sig_class<=0x13 && sig->sig_class-0x10flag |= 1<<12; continue; } node->flag |= 1<<9; } /* reset the remaining flags */ for (; node; node = node->next) node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12); /* kbnode flag usage: bit 9 is here set for signatures to consider, * bit 10 will be set by the loop to keep track of keyIDs already * processed, bit 8 will be set for the usable signatures, and bit * 11 will be set for usable revocations. */ /* for each cert figure out the latest valid one */ for (node=uidnode->next; node; node = node->next) { KBNODE n, signode; u32 kid[2]; u32 sigdate; if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) break; if ( !(node->flag & (1<<9)) ) continue; /* not a node to look at */ if ( (node->flag & (1<<10)) ) continue; /* signature with a keyID already processed */ node->flag |= (1<<10); /* mark this node as processed */ sig = node->pkt->pkt.signature; signode = node; sigdate = sig->timestamp; kid[0] = sig->keyid[0]; kid[1] = sig->keyid[1]; /* Now find the latest and greatest signature */ for (n=uidnode->next; n; n = n->next) { if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY) break; if ( !(n->flag & (1<<9)) ) continue; if ( (n->flag & (1<<10)) ) continue; /* shortcut already processed signatures */ sig = n->pkt->pkt.signature; if (kid[0] != sig->keyid[0] || kid[1] != sig->keyid[1]) continue; n->flag |= (1<<10); /* mark this node as processed */ /* If signode is nonrevocable and unexpired and n isn't, then take signode (skip). It doesn't matter which is older: if signode was older then we don't want to take n as signode is nonrevocable. If n was older then we're automatically fine. */ if(((IS_UID_SIG(signode->pkt->pkt.signature) && !signode->pkt->pkt.signature->flags.revocable && (signode->pkt->pkt.signature->expiredate==0 || signode->pkt->pkt.signature->expiredate>curtime))) && (!(IS_UID_SIG(n->pkt->pkt.signature) && !n->pkt->pkt.signature->flags.revocable && (n->pkt->pkt.signature->expiredate==0 || n->pkt->pkt.signature->expiredate>curtime)))) continue; /* If n is nonrevocable and unexpired and signode isn't, then take n. Again, it doesn't matter which is older: if n was older then we don't want to take signode as n is nonrevocable. If signode was older then we're automatically fine. */ if((!(IS_UID_SIG(signode->pkt->pkt.signature) && !signode->pkt->pkt.signature->flags.revocable && (signode->pkt->pkt.signature->expiredate==0 || signode->pkt->pkt.signature->expiredate>curtime))) && ((IS_UID_SIG(n->pkt->pkt.signature) && !n->pkt->pkt.signature->flags.revocable && (n->pkt->pkt.signature->expiredate==0 || n->pkt->pkt.signature->expiredate>curtime)))) { signode = n; sigdate = sig->timestamp; continue; } /* At this point, if it's newer, it goes in as the only remaining possibilities are signode and n are both either revocable or expired or both nonrevocable and unexpired. If the timestamps are equal take the later ordered packet, presuming that the key packets are hopefully in their original order. */ if (sig->timestamp >= sigdate) { signode = n; sigdate = sig->timestamp; } } sig = signode->pkt->pkt.signature; if (IS_UID_SIG (sig)) { /* this seems to be a usable one which is not revoked. * Just need to check whether there is an expiration time, * We do the expired certification after finding a suitable * certification, the assumption is that a signator does not * want that after the expiration of his certificate the * system falls back to an older certification which has a * different expiration time */ const byte *p; u32 expire; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL ); expire = p? sig->timestamp + buffer_to_u32(p) : 0; if (expire==0 || expire > curtime ) { signode->flag |= (1<<8); /* yeah, found a good cert */ if (next_expire && expire && expire < *next_expire) *next_expire = expire; } } else signode->flag |= (1<<11); } } static int clean_sigs_from_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only) { int deleted=0; KBNODE node; u32 keyid[2]; assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); keyid_from_pk(keyblock->pkt->pkt.public_key,keyid); /* Passing in a 0 for current time here means that we'll never weed out an expired sig. This is correct behavior since we want to keep the most recent expired sig in a series. */ mark_usable_uid_certs(keyblock,uidnode,NULL,NULL,0,NULL); /* What we want to do here is remove signatures that are not considered as part of the trust calculations. Thus, all invalid signatures are out, as are any signatures that aren't the last of a series of uid sigs or revocations It breaks down like this: coming out of mark_usable_uid_certs, if a sig is unflagged, it is not even a candidate. If a sig has flag 9 or 10, that means it was selected as a candidate and vetted. If a sig has flag 8 it is a usable signature. If a sig has flag 11 it is a usable revocation. If a sig has flag 12 it was issued by an unavailable key. "Usable" here means the most recent valid signature/revocation in a series from a particular signer. Delete everything that isn't a usable uid sig (which might be expired), a usable revocation, or a sig from an unavailable key. */ for(node=uidnode->next; node && node->pkt->pkttype==PKT_SIGNATURE; node=node->next) { int keep=self_only?(node->pkt->pkt.signature->keyid[0]==keyid[0] && node->pkt->pkt.signature->keyid[1]==keyid[1]):1; /* Keep usable uid sigs ... */ if((node->flag & (1<<8)) && keep) continue; /* ... and usable revocations... */ if((node->flag & (1<<11)) && keep) continue; /* ... and sigs from unavailable keys. */ /* disabled for now since more people seem to want sigs from unavailable keys removed altogether. */ /* if(node->flag & (1<<12)) continue; */ /* Everything else we delete */ /* At this point, if 12 is set, the signing key was unavailable. If 9 or 10 is set, it's superseded. Otherwise, it's invalid. */ if(noisy) log_info("removing signature from key %s on user ID \"%s\": %s\n", keystr(node->pkt->pkt.signature->keyid), uidnode->pkt->pkt.user_id->name, node->flag&(1<<12)?"key unavailable": node->flag&(1<<9)?"signature superseded":"invalid signature"); delete_kbnode(node); deleted++; } return deleted; } /* This is substantially easier than clean_sigs_from_uid since we just have to establish if the uid has a valid self-sig, is not revoked, and is not expired. Note that this does not take into account whether the uid has a trust path to it - just whether the keyholder themselves has certified the uid. Returns true if the uid was compacted. To "compact" a user ID, we simply remove ALL signatures except the self-sig that caused the user ID to be remove-worthy. We don't actually remove the user ID packet itself since it might be ressurected in a later merge. Note that this function requires that the caller has already done a merge_keys_and_selfsig(). TODO: change the import code to allow importing a uid with only a revocation if the uid already exists on the keyring. */ static int clean_uid_from_key(KBNODE keyblock,KBNODE uidnode,int noisy) { KBNODE node; PKT_user_id *uid=uidnode->pkt->pkt.user_id; int deleted=0; assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); assert(uidnode->pkt->pkttype==PKT_USER_ID); /* Skip valid user IDs, compacted user IDs, and non-self-signed user IDs if --allow-non-selfsigned-uid is set. */ if(uid->created || uid->flags.compacted || (!uid->is_expired && !uid->is_revoked && opt.allow_non_selfsigned_uid)) return 0; for(node=uidnode->next; node && node->pkt->pkttype==PKT_SIGNATURE; node=node->next) if(!node->pkt->pkt.signature->flags.chosen_selfsig) { delete_kbnode(node); deleted=1; uidnode->pkt->pkt.user_id->flags.compacted=1; } if(noisy) { const char *reason; char *user=utf8_to_native(uid->name,uid->len,0); if(uid->is_revoked) reason=_("revoked"); else if(uid->is_expired) reason=_("expired"); else reason=_("invalid"); log_info("compacting user ID \"%s\" on key %s: %s\n", user,keystr_from_pk(keyblock->pkt->pkt.public_key), reason); xfree(user); } return deleted; } /* Needs to be called after a merge_keys_and_selfsig() */ void clean_one_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only, int *uids_cleaned,int *sigs_cleaned) { int dummy; assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY); assert(uidnode->pkt->pkttype==PKT_USER_ID); if(!uids_cleaned) uids_cleaned=&dummy; if(!sigs_cleaned) sigs_cleaned=&dummy; /* Do clean_uid_from_key first since if it fires off, we don't have to bother with the other */ *uids_cleaned+=clean_uid_from_key(keyblock,uidnode,noisy); if(!uidnode->pkt->pkt.user_id->flags.compacted) *sigs_cleaned+=clean_sigs_from_uid(keyblock,uidnode,noisy,self_only); } void clean_key(KBNODE keyblock,int noisy,int self_only, int *uids_cleaned,int *sigs_cleaned) { KBNODE uidnode; merge_keys_and_selfsig(keyblock); for(uidnode=keyblock->next; uidnode && uidnode->pkt->pkttype!=PKT_PUBLIC_SUBKEY; uidnode=uidnode->next) if(uidnode->pkt->pkttype==PKT_USER_ID) clean_one_uid(keyblock,uidnode,noisy,self_only, uids_cleaned,sigs_cleaned); } /* Returns a sanitized copy of the regexp (which might be "", but not NULL). */ #ifndef DISABLE_REGEX static char * sanitize_regexp(const char *old) { size_t start=0,len=strlen(old),idx=0; int escaped=0,standard_bracket=0; char *new=xmalloc((len*2)+1); /* enough to \-escape everything if we have to */ /* There are basically two commonly-used regexps here. GPG and most versions of PGP use "<[^>]+[@.]example\.com>$" and PGP (9) command line uses "example.com" (i.e. whatever the user specfies, and we can't expect users know to use "\." instead of "."). So here are the rules: we're allowed to start with "<[^>]+[@.]" and end with ">$" or start and end with nothing. In between, the only legal regex character is ".", and everything else gets escaped. Part of the gotcha here is that some regex packages allow more than RFC-4880 requires. For example, 4880 has no "{}" operator, but GNU regex does. Commenting removes these operators from consideration. A possible future enhancement is to use commenting to effectively back off a given regex to the Henry Spencer syntax in 4880. -dshaw */ /* Are we bracketed between "<[^>]+[@.]" and ">$" ? */ if(len>=12 && strncmp(old,"<[^>]+[@.]",10)==0 && old[len-2]=='>' && old[len-1]=='$') { strcpy(new,"<[^>]+[@.]"); idx=strlen(new); standard_bracket=1; start+=10; len-=2; } /* Walk the remaining characters and ensure that everything that is left is not an operational regex character. */ for(;start$", then it was escaping the ">" and is fine. If the regexp actually ended with the bare "\", then it's an illegal regexp and regcomp should kick it out. */ if(standard_bracket) strcat(new,">$"); return new; } #endif /*!DISABLE_REGEX*/ /* Used by validate_one_keyblock to confirm a regexp within a trust signature. Returns 1 for match, and 0 for no match or regex error. */ static int check_regexp(const char *expr,const char *string) { #ifdef DISABLE_REGEX /* When DISABLE_REGEX is defined, assume all regexps do not match. */ return 0; #else int ret; char *regexp; regexp=sanitize_regexp(expr); #ifdef __riscos__ ret=riscos_check_regexp(expr, string, DBG_TRUST); #else { regex_t pat; ret=regcomp(&pat,regexp,REG_ICASE|REG_NOSUB|REG_EXTENDED); if(ret==0) { ret=regexec(&pat,string,0,NULL,0); regfree(&pat); ret=(ret==0); } } #endif if(DBG_TRUST) log_debug("regexp `%s' (`%s') on `%s': %s\n", regexp,expr,string,ret==0?"YES":"NO"); xfree(regexp); return ret; #endif } /* * Return true if the key is signed by one of the keys in the given * key ID list. User IDs with a valid signature are marked by node * flags as follows: * flag bit 0: There is at least one signature * 1: There is marginal confidence that this is a legitimate uid * 2: There is full confidence that this is a legitimate uid. * 8: Used for internal purposes. * 9: Ditto (in mark_usable_uid_certs()) * 10: Ditto (ditto) * This function assumes that all kbnode flags are cleared on entry. */ static int validate_one_keyblock (KBNODE kb, struct key_item *klist, u32 curtime, u32 *next_expire) { struct key_item *kr; KBNODE node, uidnode=NULL; PKT_user_id *uid=NULL; PKT_public_key *pk = kb->pkt->pkt.public_key; u32 main_kid[2]; int issigned=0, any_signed = 0; keyid_from_pk(pk, main_kid); for (node=kb; node; node = node->next) { /* A bit of discussion here: is it better for the web of trust to be built among only self-signed uids? On the one hand, a self-signed uid is a statement that the key owner definitely intended that uid to be there, but on the other hand, a signed (but not self-signed) uid does carry trust, of a sort, even if it is a statement being made by people other than the key owner "through" the uids on the key owner's key. I'm going with the latter. However, if the user ID was explicitly revoked, or passively allowed to expire, that should stop validity through the user ID until it is resigned. -dshaw */ if (node->pkt->pkttype == PKT_USER_ID && !node->pkt->pkt.user_id->is_revoked && !node->pkt->pkt.user_id->is_expired) { if (uidnode && issigned) { if (uid->help_full_count >= opt.completes_needed || uid->help_marginal_count >= opt.marginals_needed ) uidnode->flag |= 4; else if (uid->help_full_count || uid->help_marginal_count) uidnode->flag |= 2; uidnode->flag |= 1; any_signed = 1; } uidnode = node; uid=uidnode->pkt->pkt.user_id; /* If the selfsig is going to expire... */ if(uid->expiredate && uid->expiredate<*next_expire) *next_expire = uid->expiredate; issigned = 0; get_validity_counts(pk,uid); mark_usable_uid_certs (kb, uidnode, main_kid, klist, curtime, next_expire); } else if (node->pkt->pkttype == PKT_SIGNATURE && (node->flag & (1<<8)) && uid) { /* Note that we are only seeing unrevoked sigs here */ PKT_signature *sig = node->pkt->pkt.signature; kr = is_in_klist (klist, sig); /* If the trust_regexp does not match, it's as if the sig did not exist. This is safe for non-trust sigs as well since we don't accept a regexp on the sig unless it's a trust sig. */ if (kr && (!kr->trust_regexp || opt.trust_model != TM_PGP || (uidnode && check_regexp(kr->trust_regexp, uidnode->pkt->pkt.user_id->name)))) { /* Are we part of a trust sig chain? We always favor the latest trust sig, rather than the greater or lesser trust sig or value. I could make a decent argument for any of these cases, but this seems to be what PGP does, and I'd like to be compatible. -dms */ if (opt.trust_model == TM_PGP && sig->trust_depth && pk->trust_timestamp <= sig->timestamp) { unsigned char depth; /* If the depth on the signature is less than the chain currently has, then use the signature depth so we don't increase the depth beyond what the signer wanted. If the depth on the signature is more than the chain currently has, then use the chain depth so we use as much of the signature depth as the chain will permit. An ultimately trusted signature can restart the depth to whatever level it likes. */ if (sig->trust_depth < kr->trust_depth || kr->ownertrust == TRUST_ULTIMATE) depth = sig->trust_depth; else depth = kr->trust_depth; if (depth) { if(DBG_TRUST) log_debug ("trust sig on %s, sig depth is %d," " kr depth is %d\n", uidnode->pkt->pkt.user_id->name, sig->trust_depth, kr->trust_depth); /* If we got here, we know that: this is a trust sig. it's a newer trust sig than any previous trust sig on this key (not uid). it is legal in that it was either generated by an ultimate key, or a key that was part of a trust chain, and the depth does not violate the original trust sig. if there is a regexp attached, it matched successfully. */ if (DBG_TRUST) log_debug ("replacing trust value %d with %d and " "depth %d with %d\n", pk->trust_value,sig->trust_value, pk->trust_depth,depth); pk->trust_value = sig->trust_value; pk->trust_depth = depth-1; /* If the trust sig contains a regexp, record it on the pk for the next round. */ if (sig->trust_regexp) pk->trust_regexp = sig->trust_regexp; } } if (kr->ownertrust == TRUST_ULTIMATE) uid->help_full_count = opt.completes_needed; else if (kr->ownertrust == TRUST_FULLY) uid->help_full_count++; else if (kr->ownertrust == TRUST_MARGINAL) uid->help_marginal_count++; issigned = 1; } } } if (uidnode && issigned) { if (uid->help_full_count >= opt.completes_needed || uid->help_marginal_count >= opt.marginals_needed ) uidnode->flag |= 4; else if (uid->help_full_count || uid->help_marginal_count) uidnode->flag |= 2; uidnode->flag |= 1; any_signed = 1; } return any_signed; } static int search_skipfnc (void *opaque, u32 *kid, PKT_user_id *dummy) { (void)dummy; return test_key_hash_table ((KeyHashTable)opaque, kid); } /* * Scan all keys and return a key_array of all suitable keys from * kllist. The caller has to pass keydb handle so that we don't use * to create our own. Returns either a key_array or NULL in case of * an error. No results found are indicated by an empty array. * Caller hast to release the returned array. */ static struct key_array * validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust, struct key_item *klist, u32 curtime, u32 *next_expire) { KBNODE keyblock = NULL; struct key_array *keys = NULL; size_t nkeys, maxkeys; int rc; KEYDB_SEARCH_DESC desc; maxkeys = 1000; keys = xmalloc ((maxkeys+1) * sizeof *keys); nkeys = 0; rc = keydb_search_reset (hd); if (rc) { log_error ("keydb_search_reset failed: %s\n", g10_errstr(rc)); xfree (keys); return NULL; } memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FIRST; desc.skipfnc = search_skipfnc; desc.skipfncvalue = full_trust; rc = keydb_search (hd, &desc, 1); if (rc == -1) { keys[nkeys].keyblock = NULL; return keys; } if (rc) { log_error ("keydb_search_first failed: %s\n", g10_errstr(rc)); xfree (keys); return NULL; } desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */ do { PKT_public_key *pk; rc = keydb_get_keyblock (hd, &keyblock); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc)); xfree (keys); return NULL; } if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY) { log_debug ("ooops: invalid pkttype %d encountered\n", keyblock->pkt->pkttype); dump_kbnode (keyblock); release_kbnode(keyblock); continue; } /* prepare the keyblock for further processing */ merge_keys_and_selfsig (keyblock); clear_kbnode_flags (keyblock); pk = keyblock->pkt->pkt.public_key; if (pk->has_expired || pk->is_revoked) { /* it does not make sense to look further at those keys */ mark_keyblock_seen (full_trust, keyblock); } else if (validate_one_keyblock (keyblock, klist, curtime, next_expire)) { KBNODE node; if (pk->expiredate && pk->expiredate >= curtime && pk->expiredate < *next_expire) *next_expire = pk->expiredate; if (nkeys == maxkeys) { maxkeys += 1000; keys = xrealloc (keys, (maxkeys+1) * sizeof *keys); } keys[nkeys++].keyblock = keyblock; /* Optimization - if all uids are fully trusted, then we never need to consider this key as a candidate again. */ for (node=keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4)) break; if(node==NULL) mark_keyblock_seen (full_trust, keyblock); keyblock = NULL; } release_kbnode (keyblock); keyblock = NULL; } while ( !(rc = keydb_search (hd, &desc, 1)) ); if (rc && rc != -1) { log_error ("keydb_search_next failed: %s\n", g10_errstr(rc)); xfree (keys); return NULL; } keys[nkeys].keyblock = NULL; return keys; } /* Caller must sync */ static void reset_trust_records(void) { TRUSTREC rec; ulong recnum; int count = 0, nreset = 0; for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ ) { if(rec.rectype==RECTYPE_TRUST) { count++; if(rec.r.trust.min_ownertrust) { rec.r.trust.min_ownertrust=0; write_record(&rec); } } else if(rec.rectype==RECTYPE_VALID && ((rec.r.valid.validity&TRUST_MASK) || rec.r.valid.marginal_count || rec.r.valid.full_count)) { rec.r.valid.validity &= ~TRUST_MASK; rec.r.valid.marginal_count=rec.r.valid.full_count=0; nreset++; write_record(&rec); } } if (opt.verbose) log_info (_("%d keys processed (%d validity counts cleared)\n"), count, nreset); } /* * Run the key validation procedure. * * This works this way: * Step 1: Find all ultimately trusted keys (UTK). * mark them all as seen and put them into klist. * Step 2: loop max_cert_times * Step 3: if OWNERTRUST of any key in klist is undefined * ask user to assign ownertrust * Step 4: Loop over all keys in the keyDB which are not marked seen * Step 5: if key is revoked or expired * mark key as seen * continue loop at Step 4 * Step 6: For each user ID of that key signed by a key in klist * Calculate validity by counting trusted signatures. * Set validity of user ID * Step 7: If any signed user ID was found * mark key as seen * End Loop * Step 8: Build a new klist from all fully trusted keys from step 6 * End Loop * Ready * */ static int validate_keys (int interactive) { int rc = 0; int quit=0; struct key_item *klist = NULL; struct key_item *k; struct key_array *keys = NULL; struct key_array *kar; KEYDB_HANDLE kdb = NULL; KBNODE node; int depth; int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate; KeyHashTable stored,used,full_trust; u32 start_time, next_expire; /* Make sure we have all sigs cached. TODO: This is going to require some architectual re-thinking, as it is agonizingly slow. Perhaps combine this with reset_trust_records(), or only check the caches on keys that are actually involved in the web of trust. */ keydb_rebuild_caches(0); start_time = make_timestamp (); next_expire = 0xffffffff; /* set next expire to the year 2106 */ stored = new_key_hash_table (); used = new_key_hash_table (); full_trust = new_key_hash_table (); kdb = keydb_new (0); reset_trust_records(); /* Fixme: Instead of always building a UTK list, we could just build it * here when needed */ if (!utk_list) { if (!opt.quiet) log_info (_("no ultimately trusted keys found\n")); goto leave; } /* mark all UTKs as used and fully_trusted and set validity to ultimate */ for (k=utk_list; k; k = k->next) { KBNODE keyblock; PKT_public_key *pk; keyblock = get_pubkeyblock (k->kid); if (!keyblock) { log_error (_("public key of ultimately" " trusted key %s not found\n"), keystr(k->kid)); continue; } mark_keyblock_seen (used, keyblock); mark_keyblock_seen (stored, keyblock); mark_keyblock_seen (full_trust, keyblock); pk = keyblock->pkt->pkt.public_key; for (node=keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE); } if ( pk->expiredate && pk->expiredate >= start_time && pk->expiredate < next_expire) next_expire = pk->expiredate; release_kbnode (keyblock); do_sync (); } klist = utk_list; log_info(_("%d marginal(s) needed, %d complete(s) needed, %s trust model\n"), opt.marginals_needed,opt.completes_needed,trust_model_string()); for (depth=0; depth < opt.max_cert_depth; depth++) { int valids=0,key_count; /* See whether we should assign ownertrust values to the keys in klist. */ ot_unknown = ot_undefined = ot_never = 0; ot_marginal = ot_full = ot_ultimate = 0; for (k=klist; k; k = k->next) { int min=0; /* 120 and 60 are as per RFC2440 */ if(k->trust_value>=120) min=TRUST_FULLY; else if(k->trust_value>=60) min=TRUST_MARGINAL; if(min!=k->min_ownertrust) update_min_ownertrust(k->kid,min); if (interactive && k->ownertrust == TRUST_UNKNOWN) { k->ownertrust = ask_ownertrust (k->kid,min); if (k->ownertrust == -1) { quit=1; goto leave; } } /* This can happen during transition from an old trustdb before trust sigs. It can also happen if a user uses two different versions of GnuPG or changes the --trust-model setting. */ if(k->ownertrustkid[0],(ulong)k->kid[1], trust_value_to_string(k->ownertrust), trust_value_to_string(min)); k->ownertrust=min; } if (k->ownertrust == TRUST_UNKNOWN) ot_unknown++; else if (k->ownertrust == TRUST_UNDEFINED) ot_undefined++; else if (k->ownertrust == TRUST_NEVER) ot_never++; else if (k->ownertrust == TRUST_MARGINAL) ot_marginal++; else if (k->ownertrust == TRUST_FULLY) ot_full++; else if (k->ownertrust == TRUST_ULTIMATE) ot_ultimate++; valids++; } /* Find all keys which are signed by a key in kdlist */ keys = validate_key_list (kdb, full_trust, klist, start_time, &next_expire); if (!keys) { log_error ("validate_key_list failed\n"); rc = G10ERR_GENERAL; goto leave; } for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++) ; /* Store the calculated valididation status somewhere */ if (opt.verbose > 1) dump_key_array (depth, keys); for (kar=keys; kar->keyblock; kar++) store_validation_status (depth, kar->keyblock, stored); log_info (_("depth: %d valid: %3d signed: %3d" " trust: %d-, %dq, %dn, %dm, %df, %du\n"), depth, valids, key_count, ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate ); /* Build a new kdlist from all fully valid keys in KEYS */ if (klist != utk_list) release_key_items (klist); klist = NULL; for (kar=keys; kar->keyblock; kar++) { for (node=kar->keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4)) { u32 kid[2]; /* have we used this key already? */ keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid); if(test_key_hash_table(used,kid)==0) { /* Normally we add both the primary and subkey ids to the hash via mark_keyblock_seen, but since we aren't using this hash as a skipfnc, that doesn't matter here. */ add_key_hash_table (used,kid); k = new_key_item (); k->kid[0]=kid[0]; k->kid[1]=kid[1]; k->ownertrust = (get_ownertrust (kar->keyblock->pkt->pkt.public_key) & TRUST_MASK); k->min_ownertrust = get_min_ownertrust(kar->keyblock->pkt->pkt.public_key); k->trust_depth= kar->keyblock->pkt->pkt.public_key->trust_depth; k->trust_value= kar->keyblock->pkt->pkt.public_key->trust_value; if(kar->keyblock->pkt->pkt.public_key->trust_regexp) k->trust_regexp= xstrdup(kar->keyblock->pkt-> pkt.public_key->trust_regexp); k->next = klist; klist = k; break; } } } } release_key_array (keys); keys = NULL; if (!klist) break; /* no need to dive in deeper */ } leave: keydb_release (kdb); release_key_array (keys); release_key_items (klist); release_key_hash_table (full_trust); release_key_hash_table (used); release_key_hash_table (stored); if (!rc && !quit) /* mark trustDB as checked */ { if (next_expire == 0xffffffff || next_expire < start_time ) tdbio_write_nextcheck (0); else { tdbio_write_nextcheck (next_expire); log_info (_("next trustdb check due at %s\n"), strtimestamp (next_expire)); } if(tdbio_update_version_record()!=0) { log_error(_("unable to update trustdb version record: " "write failed: %s\n"), g10_errstr(rc)); tdbio_invalid(); } do_sync (); pending_check_trustdb = 0; } return rc; } diff --git a/sm/ChangeLog b/sm/ChangeLog index ab25af8d4..c47aa464f 100644 --- a/sm/ChangeLog +++ b/sm/ChangeLog @@ -1,2761 +1,2763 @@ 2010-03-11 Werner Koch + * verify.c (gpgsm_verify): Use gpgsm_es_print_name. + * gpgsm.c: Include "asshelp.h". (main): Remove assuan_set_assuan_log_prefix. Add assuan_set_log_cb. * server.c (gpgsm_server): Remove assuan_set_log_stream. 2010-03-10 Werner Koch * Makefile.am (common_libs): Remove libjnlib.a. Change order. * gpgsm.h: Remove "estream.h". 2010-03-08 Werner Koch * certreqgen.c (gpgsm_genkey): Change OUT_FP to an estream_t OUT_STREAM. * certreqgen-ui.c (gpgsm_gencertreq_tty): ditto. * server.c (cmd_genkey): Close IN_STREAM. * server.c (cmd_encrypt, cmd_decrypt, cmd_verify, cmd_sign): Avoid dup call by using es_fdopen_nc. (do_listkeys): Use es_fdopen_nc instead of dup and es_fdopen. (cmd_export): Ditto. (cmd_genkey): Ditto. * export.c (popen_protect_tool): Change OUTFILE to an estream_t. (export_p12): Change OUTFP and arg RETFP to an estream_t. (gpgsm_p12_export): Change DATAFP to an estream_t. (gpgsm_export): Remove arg FP. * import.c (import_one): Change CERTFP and arg FP to an estream_t. (popen_protect_tool): Ditto for OUTFILE. (parse_p12): Change CERTFP to an estream_t. * sign.c (hash_data, hash_and_copy_data): Use estream. (gpgsm_sign): Change arg OUT_FP to an estream_t. * verify.c (gpgsm_verify): Rename FP to IN_FP. Change FP and arg OUT_FP to an estream_t. (hash_data): Use estream. * base64.c (struct reader_cb_parm_s): Change FP to an estream_t. (gpgsm_create_reader): Ditto. (simple_reader_cb, base64_reader_cb): Adjust accordingly. * decrypt.c (gpgsm_decrypt): Change OUT_FP and IN_FP to an estream_t. * encrypt.c (gpgsm_encrypt): Change OUT_FP to an estream_t. Ditto for DATA_FD. (encrypt_cb): Use estream. * gpgsm.c (main) : Use estream functions. (main) : Use open_es_fwrite. 2009-12-14 Werner Koch * server.c (cmd_passwd): New. (register_commands): Register new command. 2009-12-10 Werner Koch * gpgsm.c: Add option --ignore-cert-extension. * gpgsm.h (opt): Add field IGNORED_CERT_EXTENSIONS. * certchain.c (unknown_criticals): Handle ignored extensions, 2009-12-08 Werner Koch * keydb.c (keydb_search_kid): Fix code even that it is not used. (classify_user_id): Adjust for change of u.kid type. (keydb_classify_name): Replace GPG_ERR_INV_NAME by GPG_ERR_INV_USER_ID. (keydb_classify_name): Remove. Replace all callers by classify_user_id. 2009-12-08 Marcus Brinkmann * call-dirmngr.c (start_dirmngr_ext): Convert posix fd to assuan fd. 2009-12-03 Werner Koch * gpgsm.c (set_debug): Allow for numerical debug leveles. Print active debug flags. 2009-12-02 Werner Koch * verify.c (gpgsm_verify): Add audit info on hash algorithms. * sign.c (gpgsm_sign): Add audit log calls. (hash_data): Return an error indicator. 2009-12-01 Werner Koch * decrypt.c (gpgsm_decrypt): Add audit log calls. * gpgsm.c: New option --html-audit-log. 2009-11-25 Marcus Brinkmann * server.c (gpgsm_server): Use assuan_fd_t and assuan_fdopen on fds. 2009-11-23 Werner Koch * gpgsm.c (main) : Add key "default_pubkey_algo". 2009-11-10 Marcus Brinkmann * server.c (cmd_getauditlog): Don't dup FD for es_fdopen_nc as this leaks the FD here. 2009-11-05 Marcus Brinkmann * call-dirmngr.c (start_dirmngr_ext): Update use of assuan_pipe_connect and assuan_socket_connect. 2009-11-04 Werner Koch * certreqgen.c (proc_parameters): Change fallback key length to 2048. * server.c (register_commands): Add help arg to assuan_register_command. Provide help strings for all commands. 2009-11-02 Marcus Brinkmann * server.c (reset_notify, input_notify, output_notify): Update to new assuan interface. (register_commands): Use assuan_handler_t. * call-agent.c (membuf_data_cb, default_inq_cb) (inq_ciphertext_cb, scd_serialno_status_cb) (scd_keypairinfo_status_cb, istrusted_status_cb) (learn_status_cb, learn_cb, keyinfo_status_cb): Return gpg_error_t. 2009-10-16 Werner Koch * gpgsm.c (default_include_certs): Change to -2. (DEFAULT_INCLUDE_CERTS): New. (DEFAULT_CIPHER_ALGO): New. Use instead of hardcoded "3DES". 2009-09-30 Werner Koch * gpgsm.c (main): Remove obsolete GCRYCTL_DISABLE_INTERNAL_LOCKING. 2009-09-23 Marcus Brinkmann * gpgsm.c (main): Update to new assuan API. * server.c: Include "gpgsm.h" before due to check for GPG_ERR_SOURCE_DEFAULT and assuan.h now including gpg-error.h. (option_handler, cmd_recipient, cmd_signer, cmd_encrypt) (cmd_decrypt, cmd_verify, cmd_sign, cmd_import, cmd_export) (cmd_delkeys, cmd_message, cmd_listkeys, cmd_dumpkeys) (cmd_listsecretkeys, cmd_dumpsecretkeys, cmd_genkey) (cmd_getauditlog, cmd_getinfo): Return gpg_error_t instead of int. (register_commands): Same for member HANDLER in table. (gpgsm_server): Allocate assuan context before starting server. * sm/call-dirmngr.c: * call-dirmngr.c (prepare_dirmngr): Check for CTX and error before setting LDAPSERVER. (start_dirmngr_ext): Allocate assuan context before starting server. (inq_certificate, isvalid_status_cb, lookup_cb, lookup_status_cb) (run_command_cb, run_command_inq_cb, run_command_status_cb): Return gpg_error_t instead of int. 2009-08-06 Werner Koch * sign.c (gpgsm_sign): Print INV_SNDR for a bad default key. * server.c (cmd_signer): Remove unneeded case for -1. Send INV_SGNR. Use new map function. (cmd_recipient): Use new map function. * gpgsm.c (do_add_recipient): Use new map function for INV_RECP. (main): Ditto. Also send INV_SGNR. 2009-07-30 Werner Koch * call-agent.c (learn_cb): Do not store as ephemeral. 2009-07-29 Marcus Brinkmann * keylist.c (print_capabilities): Print a trailing colon. 2009-07-23 Werner Koch * certchain.c (is_cert_still_valid): Emit AUDIT_CRL_CHECK. 2009-07-07 Werner Koch * server.c (command_has_option): New. (cmd_getinfo): Add subcommand "cmd_has_option". (cmd_import): Implement option --re-import. * import.c (gpgsm_import): Add arg reimport_mode. (reimport_one): New. * gpgsm.h: Include session-env.h. (opt): Add field SESSION_ENV. Remove obsolete fields. * server.c (option_handler): Rewrite setting of option fields. Replace strdup by xtrystrdup. * gpgsm.c (set_opt_session_env): New. (main): Use it for oDisplay, oTTYname, oTTYtype and oXauthority. * call-agent.c (start_agent): Adjust start_new_gpg_agent for changed args. * misc.c (setup_pinentry_env): Use new session_env stuff. 2009-07-02 Werner Koch * certreqgen-ui.c (gpgsm_gencertreq_tty): Allow using a key from a card. * call-agent.c (gpgsm_agent_scd_serialno) (scd_serialno_status_cb, store_serialno): New. (scd_keypairinfo_status_cb, gpgsm_agent_scd_keypairinfo): New. 2009-07-01 Werner Koch * certreqgen-ui.c (check_keygrip): New. (gpgsm_gencertreq_tty): Allow using an existing key. * gpgsm.c (open_es_fread): New. (main) : Implement --batch mode. 2009-06-24 Werner Koch * call-dirmngr.c (pattern_from_strlist): Remove dead assignment of N. * sign.c (gpgsm_sign): Remove dead assignment. * certreqgen.c (create_request): Assign GPG_ERR_BUG to RC. Reported by Fabian Keil. 2009-05-27 Werner Koch * encrypt.c (encrypt_dek): Make use of make_canon_sexp. 2009-05-18 Werner Koch * server.c (option_handler): New option "no-encrypt-to". (cmd_encrypt): Make use of it. * gpgsm.c: Remove not implemented --verify-files. 2009-04-02 Werner Koch * keylist.c (list_cert_std): Print card serial number. 2009-04-01 Werner Koch * export.c (popen_protect_tool): Add command line option --agent-program and pass flag bit 6. * import.c (popen_protect_tool): Ditto. 2009-03-26 Werner Koch * gpgsm.c (main): s/def_digest_string/forced_digest_algo/ and activate the --digest-algo option. * gpgsm.h (struct opt): s/def_digest_algo/forced_digest_algo/. * sign.c (gpgsm_sign): Implement --digest-algo. * sign.c (MAX_DIGEST_LEN): Change to 64. * call-agent.c (gpgsm_agent_marktrusted): Format the issuer name. 2009-03-25 Werner Koch * decrypt.c (gpgsm_decrypt): Print ENC_TO and NO_SECKEY stati. Fixes bug#1020. * fingerprint.c (gpgsm_get_short_fingerprint): Add arg R_HIGH and change all callers. 2009-03-23 Werner Koch * delete.c (delete_one): Also delete ephemeral certificates if specified uniquely. 2009-03-20 Werner Koch * keylist.c (list_internal_keys): Set released cert to NULL. * call-agent.c (learn_status_cb): New. (gpgsm_agent_learn): Use it. (learn_cb): Send a progress for every certificate. 2009-03-18 Werner Koch * gpgsm.h (struct opt): Move field WITH_EPHEMERAL_KEYS to struct server_control_s. * gpgsm.c (main): Change accordingly. * keylist.c (list_internal_keys): Ditto. * server.c (option_handler): Add "with-ephemeral-keys". 2009-03-12 Werner Koch * certdump.c (gpgsm_dump_time): Remove. * certdump.c, verify.c, certchain.c * gpgsm.c: s/gpgsm_dump_time/dump_isotime/. 2009-03-06 Werner Koch * call-agent.c (gpgsm_agent_keyinfo, keyinfo_status_cb): New. * keylist.c (list_cert_colon): Print card S/N. * keylist.c (list_internal_keys): Always list ephemeral keys if specified by keygrip or fingerprint. (list_cert_raw): Always show ephemeral flag. * export.c (gpgsm_export): Export ephemeral keys if specified by keygrip. 2009-02-09 Werner Koch * gpgsm.c (main): Change default cipher back to 3DES. 2009-01-12 Werner Koch * keylist.c (print_utf8_extn_raw): Cast printf precision argument. 2009-01-08 Werner Koch * fingerprint.c (gpgsm_get_keygrip_hexstring): Add error detection. 2008-12-10 Werner Koch * gpgsm.c (our_cipher_test_algo): Use the GCRY constants as we now require 1.4. (our_md_test_algo): Ditto. Add SHA224. (main) : Update default cipher algo. 2008-12-09 Werner Koch * gpgsm.c (main): Call i18n_init before init_common_subsystems. 2008-12-05 Werner Koch * certreqgen.c (create_request): Provide a custom prompt for the signing. * certdump.c (gpgsm_format_keydesc): Remove debug output. (gpgsm_format_keydesc): Remove saving of errno as xfree is supposed not to change it. Use the new percent_plus_escape function which also fixes the issue that we did not escaped a percent in the past. 2008-11-18 Werner Koch * gpgsm.c (make_libversion): New. (my_strusage): Use new function. (build_lib_list): Remove. 2008-11-13 Werner Koch * gpgsm.c: Remove all unused options. Use ARGPARSE macros. 2008-10-28 Werner Koch * certdump.c (gpgsm_format_keydesc): Use xtryasprintf and xfree. (gpgsm_es_print_name): Factor code out to ... (gpgsm_es_print_name2): New function. (gpgsm_format_name2, format_name_writer): Use estream so that it works on all platforms. (format_name_writer): Fix reallocation bug. 2008-10-23 Werner Koch * import.c (popen_protect_tool): Add arg CTRL and assure that the agent is running. Pass a value for CTRL from all caller. * export.c (popen_protect_tool): Ditto. 2008-10-21 Werner Koch * call-dirmngr.c (inq_certificate_parm_s): Add field CTRL. (gpgsm_dirmngr_isvalid): Supply a value for that field. (inq_certificate): Add inquiry ISTRUSTED. * call-agent.c (gpgsm_agent_istrusted): Add new optional arg HEXFPR. Changed all callers. 2008-10-20 Werner Koch * keydb.c (keydb_locate_writable): Mark unused arg. (keydb_search_kid): Ditto. (keydb_clear_some_cert_flags): Ditto. * server.c (cmd_encrypt): Ditto. (cmd_decrypt, cmd_verify, cmd_import, cmd_genkey): Ditto. * call-agent.c (gpgsm_scd_pksign): Ditto. * call-dirmngr.c (release_dirmngr, release_dirmngr2) (run_command_cb): Ditto. * certlist.c (gpgsm_add_cert_to_certlist): Ditto. * certchain.c (find_up_dirmngr): Ditto. * keylist.c (print_key_data): Ditto. (list_cert_raw, list_cert_std): Ditto. * qualified.c (gpgsm_is_in_qualified_list): Ditto. * gpgsm.c (set_binary) [!W32]: Mark unused arg. 2008-10-17 Werner Koch * call-dirmngr.c (start_dirmngr, start_dirmngr2): Reset the lock flag on error. (release_dirmngr, release_dirmngr2): Replace asserts by error messages. (gpgsm_dirmngr_lookup): Replace assert by fatal error message. 2008-10-13 Werner Koch * gpgsm.c: Add alias --delete-keys. 2008-09-30 Werner Koch * server.c (cmd_getinfo): New subcommand agent-check. * call-agent.c (gpgsm_agent_send_nop): New. 2008-09-29 Werner Koch * certcheck.c (MY_GCRY_PK_ECDSA): Remove. Change users to GCRY_PK_ECDSA. * gpgsm.c (MY_GCRY_PK_ECDSA): Ditto. * sign.c (MY_GCRY_MD_SHA224): Remove change users to GCRY_MD_SHA224. 2008-09-04 Werner Koch * certdump.c (gpgsm_format_keydesc): Work around a mingw32 bug. 2008-09-03 Werner Koch * sign.c (MY_GCRY_MD_SHA224): New, so that we don't need libgcrypt 1.2. 2008-08-13 Werner Koch * keylist.c (list_cert_colon): Print 'f' for validated certs. 2008-08-08 Marcus Brinkmann * gpgsm.h (struct server_control_s): Remove member dirmngr_seen. * call-dirmngr.c (dirmngr2_ctx, dirmngr_ctx_locked) (dirmngr2_ctx_locked): New global variables. (prepare_dirmngr): Don't check dirmngr_seen anymore. (start_dirmngr): Move bunch of code to ... (start_dirmngr_ext): ... this new function. (release_dirmngr, start_dirmngr2, release_dirmngr2): New functions. (gpgsm_dirmngr_isvalid): Call release_dirmngr. (gpgsm_dirmngr_lookup): Call release_dirmngr. If dirmngr_ctx is locked, use dirmngr2_locked. (gpgsm_dirmngr_run_command): Call release_dirmngr. 2008-06-25 Werner Koch * sign.c (gpgsm_sign): Revamp the hash algorithm selection. * gpgsm.h (struct certlist_s): Add field HASH_ALGO and HASH_ALGO_OID. * qualified.c (gpgsm_qualified_consent): Fix double free. * gpgsm.c (main): Change default cipher algo to AES. * keylist.c (print_utf8_extn_raw, print_utf8_extn): New. (list_cert_raw, list_cert_std): Print the TeleSec restriction extension. 2008-06-23 Werner Koch * encrypt.c (encode_session_key): Replace xmalloc by xtrymalloc. Use bin2hex instead of open coding the conversion. (encrypt_dek): Init S_DATA. 2008-06-13 Marcus Brinkmann * call-dirmngr.c (prepare_dirmngr): Fix error code to ignore. 2008-06-12 Marcus Brinkmann * gpgsm.h (struct keyserver_spec): New struct. (opt): Add member keyserver. * gpgsm.c (keyserver_list_free, parse_keyserver_line): New functions. (main): Implement --keyserver option. * call-dirmngr.c (prepare_dirmngr): Send LDAPSERVER commands. 2008-05-20 Werner Koch * gpgsm.c (main) : Pass FP and not stdout to the export function. Reported by Marc Mutz. 2008-05-06 Werner Koch * keylist.c (list_external_keys): Ignore NOT FOUND error code. This is bug#907. 2008-04-23 Werner Koch * certchain.c (find_up): Make correct C89 code. Declare variable at the top of the block. Reported by Alain Guibert. 2008-04-09 Werner Koch * verify.c (gpgsm_verify): Print the message hash values on error. 2008-03-31 Werner Koch * call-dirmngr.c (start_dirmngr): Use log_info instead of log_error when falling back to start dirmngr. 2008-03-20 Werner Koch * certlist.c (gpgsm_add_to_certlist): Always save the first subject and issuer. Initialize issuer with issuer and not with subject. (same_subject_issuer): Set issuer2 to issuer and not to subject. 2008-03-17 Werner Koch * certdump.c (my_funopen_hook_size_t): New. (format_name_writer): Use it. 2008-03-13 Werner Koch * certdump.c (gpgsm_fpr_and_name_for_status): Fix signed/unsigned char issue. (gpgsm_format_keydesc): Remove superfluous test. Add expire date to the prompt. 2008-02-18 Werner Koch * certchain.c (gpgsm_is_root_cert): Factor code out to ... (is_root_cert): New. Extend test for self-issued certificates signed by other CAs. (do_validate_chain, gpgsm_basic_cert_check) (gpgsm_walk_cert_chain): Use it here. * gpgsm.c: Add option --no-common-certs-import. * certchain.c (find_up_dirmngr, find_up, do_validate_chain) (check_cert_policy): Be more silent with --quiet. * gpgsm.c: Add option --disable-dirmngr. * gpgsm.h (opt): Add field DISABLE_DIRMNGR. * call-dirmngr.c (start_dirmngr): Implement option. 2008-02-14 Werner Koch * server.c (option_handler): Add option allow-pinentry-notify. (gpgsm_proxy_pinentry_notify): New. * call-agent.c (default_inq_cb): New. (gpgsm_agent_pksign, gpgsm_scd_pksign, gpgsm_agent_readkey) (gpgsm_agent_istrusted, gpgsm_agent_marktrusted) (gpgsm_agent_passwd, gpgsm_agent_get_confirmation): Call it. (struct cipher_parm_s, struct genkey_parm_s): Add field CTRL. (inq_ciphertext_cb): Test keyword and fallback to default_inq_cb. (inq_genkey_parms): Ditto. (start_agent): Tell agent to send us the pinentry notifications. 2008-02-13 Werner Koch * call-dirmngr.c (gpgsm_dirmngr_lookup): Add arg CACHE_ONLY. * keylist.c (list_external_keys): Pass false for new arg. * certchain.c (find_up_dirmngr): New. (find_up): Also try to read from the dirmngr cache. (find_up, find_up_external, gpgsm_walk_cert_chain) (gpgsm_basic_cert_check, allowed_ca): Add arg CTRL and changed all callers. * call-agent.c (struct learn_parm_s): Add field CTRL. (gpgsm_agent_learn): Set it. 2008-02-11 Werner Koch * server.c (cmd_getinfo): New. (gpgsm_server): Register GETINFO. 2008-01-29 Marcus Brinkmann * keylist.c (list_internal_keys): New variable lastcert. Use it to suppress duplicates which immediately follow each other. 2008-01-27 Werner Koch * import.c (popen_protect_tool): Set bit 7 in the flags for gnupg_spawn_process so that under W32 no window appears. * export.c (popen_protect_tool): Ditto. 2007-12-13 Werner Koch * gpgsm.c (main): Add option --extra-digest-algo. * gpgsm.h (struct): Add EXTRA_DIGEST_ALGO. * verify.c (gpgsm_verify): Use it. Use the hash algorithm from the signature value. 2007-12-11 Werner Koch * certchain.c (do_validate_chain): Log AUDIT_ROOT_TRUSTED. * server.c (cmd_sign, cmd_decrypt, cmd_encrypt): Start audit log. (cmd_recipient): Start audit session. * gpgsm.c (main): Revamp creation of the audit log. * gpgsm.h (struct server_control_s): Add AGENT_SEEN and DIRMNGR_SEEN. * call-agent.c (start_agent): Record an audit event. * call-dirmngr.c (start_dirmngr): Ditto. Add new arg CTRL and pass it from all callers. (prepare_dirmngr): New helper for start_dirmngr. * encrypt.c (gpgsm_encrypt): Add calls to audit_log. 2007-12-03 Werner Koch * gpgsm.c (main): Call gnupg_reopen_std. h2007-11-22 Werner Koch * server.c (cmd_getauditlog): New. (register_commands): Register GETAUDITLOG. 2007-11-19 Werner Koch * server.c (cmd_recipient, cmd_signer): Add error reason 11. * gpgsm.c (main): Print a warning if --audit-log is used. 2007-11-15 Werner Koch * gpgsm.h (struct): Add XAUTHORITY and PINENTRY_USER_DATA. * misc.c (setup_pinentry_env): Add XAUTHORITY and PINENTRY_USER_DATA. * gpgsm.c (main): New option --xauthority. * call-agent.c (start_agent): Adjust for changed start_new_gpg_agent. * server.c (option_handler): Ad the new options. 2007-11-07 Werner Koch * gpgsm.c (main): New option --audit-log. * server.c (option_handler): New option enable-audit-log. (start_audit_session): New. (cmd_verify): Create audit context. (gpgsm_server): Release the context. * gpgsm.h (struct server_control_s): Add member AUDIT, include audit.h. * certdump.c (gpgsm_format_sn_issuer): New. * verify.c (hash_data): Return an error code. (gpgsm_verify): Add calls to audit_log. * gpgsm.c (get_status_string): Remove. * gpgsm.h: Include status.h instead of errors.h. 2007-10-19 Werner Koch * qualified.c (gpgsm_qualified_consent): Use i18N-swicth functions. (gpgsm_not_qualified_warning): Ditto. * certdump.c (gpgsm_format_keydesc): Ditto. 2007-09-14 Werner Koch * gpgsm.c (build_lib_list): New. (my_strusage): Print lib info. 2007-08-24 Werner Koch * Makefile.am (common_libs): Swap libkeybox and jnlib. 2007-08-23 Werner Koch * certlist.c (gpgsm_certs_identical_p): New. (gpgsm_add_to_certlist): Ignore duplicate certificates in ambigious name detection. (gpgsm_find_cert): Ditto. * export.c (gpgsm_p12_export): Ditto. 2007-08-22 Werner Koch * certreqgen.c (create_request): Replace open coding by bin2hex. * certreqgen-ui.c (gpgsm_gencertreq_tty): Use es_fopenmem. 2007-08-21 Werner Koch * import.c (parse_p12): Use gnupg_tmpfile. * export.c (export_p12): Ditto. 2007-08-20 Werner Koch * certreqgen.c (read_parameters): Change FP to an estream_t. (gpgsm_genkey): Replace in_fd and in_stream by a estream_t. * server.c (cmd_genkey): Adjust for that. * certreqgen-ui.c (gpgsm_gencertreq_tty): Use es_open_memstream instead of a temporary file. 2007-08-14 Werner Koch * call-dirmngr.c (start_dirmngr): Use dirmngr_socket_name. change the way infostr is xstrdupped. * gpgsm.c (main) [W32]: Make --prefer-system-dirmngr a dummy under Windows. 2007-08-13 Werner Koch * gpgsm.c (do_add_recipient): Add RECP_REQUIRED and make error message depend on that. (main): Add avriable RECP_REQUIRED, set ift for encryption commands and pass it to do_add_recipient. (our_pk_test_algo, our_cipher_test_algo, our_md_test_algo): Implement. 2007-08-09 Werner Koch * gpgsm.c (main) [W32]: Enable CRL check by default. (main): Update the default control structure after reading the options. (gpgsm_parse_validation_model, parse_validation_model): New. (main): New option --validation-model. * certchain.c (gpgsm_validate_chain): Implement this option. * server.c (option_handler): Ditto. * certchain.c (is_cert_still_valid): Reformatted. Add arg FORCE_OCSP. Changed callers to set this flag when using the chain model. 2007-08-08 Werner Koch * certdump.c (gpgsm_print_serial): Fixed brown paper bag style bugs which prefixed the output with a 3A and cut it off at a 00. * keylist.c (list_cert_raw): Print the certificate ID first and rename "Serial number" to "S/N". (list_cert_std): Ditto. 2007-08-07 Werner Koch * gpgsm.c (main): Allow a string for --faked-system-time. 2007-08-06 Werner Koch Implementation of the chain model. * gpgsm.h (struct rootca_flags_s): Define new members VALID and CHAIN_MODEL. * call-agent.c (gpgsm_agent_istrusted): Mark ROOTCA_FLAGS valid. (istrusted_status_cb): Set CHAIN_MODEL. * certchain.c (gpgsm_validate_chain): Replace LM alias by LISTMODE and FP by LISTFP. (gpgsm_validate_chain): Factor some code out to ... (check_validity_period, ask_marktrusted): .. new. (check_validity_cm_basic, check_validity_cm_main): New. (do_validate_chain): New with all code from gpgsm_validate_chain. New arg ROOTCA_FLAGS. (gpgsm_validate_chain): Provide ROOTCA_FLAGS and fallback to chain model. Add RETFLAGS arg and changed all callers to pass NULL. Add CHECKTIME arg and changed all callers to pass a nil value. (has_validity_model_chain): New. * verify.c (gpgsm_verify): Check for chain model and return as part of the trust status. * gpgsm.h (VALIDATE_FLAG_NO_DIRMNGR): New. (VALIDATE_FLAG_NO_DIRMNGR): New. * call-dirmngr.c (gpgsm_dirmngr_isvalid): Use constant here. 2007-08-03 Werner Koch * keylist.c (list_cert_colon): Avoid duplicate listing of kludge uids. * verify.c (gpgsm_verify): Make STATUS_VERIFY return the hash and pk algo. * certcheck.c (gpgsm_check_cms_signature): Add arg R_PKALGO. 2007-08-02 Werner Koch * gpgsm.c (main): Factored GC_OPT_FLAGS out to gc-opt-flags.h. 2007-07-17 Werner Koch * gpgsm.c (main): Implement --default-key. (main) : Declare --default-key and --encrypt-to. 2007-07-16 Werner Koch * server.c (cmd_message): Use gnupg_fd_t to avoid dependecy on newer assuan versions. 2007-07-12 Werner Koch * gpgsm.c (check_special_filename): Use translate_sys2libc_fd_int when passing an int value. * server.c (cmd_encrypt, cmd_decrypt, cmd_verify, cmd_import) (cmd_export, cmd_message, cmd_genkey): Translate file descriptors. 2007-07-05 Werner Koch * Makefile.am (common_libs): Changed order of libs. 2007-07-04 Werner Koch * certchain.c (check_cert_policy): Remove extra checks for GPG_ERR_NO_VALUE. They are not needed since libksba 1.0.1. * keylist.c (print_capabilities, list_cert_raw, list_cert_std): Ditto. * certlist.c (cert_usage_p, cert_usage_p): Ditto. 2007-06-26 Werner Koch * gpgsm.c (main): Call gnupg_rl_initialize. * Makefile.am (gpgsm_LDADD): Add LIBREADLINE and libgpgrl.a. 2007-06-25 Werner Koch * gpgsm.c (check_special_filename): Use translate_sys2libc_fd and add new arg FOR_WRITE. Change callers to pass new arg. 2007-06-24 Werner Koch * gpgsm.c (open_es_fwrite): Avoid the dup by using the new es_fdopen_nc(). 2007-06-21 Werner Koch * certreqgen-ui.c: New. * gpgsm.c (main): Let --gen-key call it. * certreqgen.c (gpgsm_genkey): Add optional IN_STREAM arg and adjusted caller. * gpgsm.h (ctrl_t): Remove. It is now declared in ../common/util.h. * call-agent.c (start_agent): Factored almost all code out to ../common/asshelp.c. 2007-06-20 Werner Koch * call-agent.c (start_agent) [W32]: Start the agent on the fly. 2007-06-18 Marcus Brinkmann * gpgsm.c (main): Percent escape output of --gpgconf-list. 2007-06-14 Werner Koch * call-agent.c (start_agent): Use gnupg_module_name. * call-dirmngr.c (start_dirmngr): Ditto. * export.c (export_p12): Ditto. * import.c (parse_p12): Ditto. * gpgsm.c (run_protect_tool): Ditto. 2007-06-12 Werner Koch * gpgsm.c (main): Replace some calls by init_common_subsystems. (main): Use gnupg_datadir. * qualified.c (read_list): Use gnupg-datadir. 2007-06-11 Werner Koch * Makefile.am (common_libs): Use libcommaonstd macr. * gpgsm.c (main) [W32]: Call pth_init. 2007-06-06 Werner Koch * qualified.c (gpgsm_not_qualified_warning) [!ENABLE_NLS]: Do not define orig_codeset. * certdump.c (gpgsm_format_keydesc) [!ENABLE_NLS]: Do not define orig_codeset. (format_name_writer): Define only if funopen et al is available. * gpgsm.c (i18n_init): Remove. 2007-05-29 Werner Koch * export.c (gpgsm_p12_export): Print passphrase encoding info only in PEM mode. 2007-05-18 Marcus Brinkmann * qualified.c (gpgsm_qualified_consent, gpgsm_not_qualified_warning): Free ORIG_CODESET on error. * certdump.c (gpgsm_format_keydesc): Likewise. 2007-05-07 Werner Koch * certcheck.c (MY_GCRY_PK_ECDSA): New. 2007-04-20 Werner Koch * gpgsm.c (main): Parameterize failed versions check messages. 2007-04-19 Werner Koch * certcheck.c (do_encode_md): Add arg PKEY. Add support for DSA2 and all ECDSA sizes. (get_dsa_qbits): New. (pk_algo_from_sexp): A key will never contain ecdsa as algorithm, so remove that. 2007-04-18 Werner Koch * certcheck.c (do_encode_md): Support 160 bit ECDSA. 2007-04-13 Werner Koch * call-agent.c (start_agent): Don't use log_error when using the fallback hack to start the agent. This is bug 782. 2007-03-20 Werner Koch * fingerprint.c (gpgsm_get_fingerprint): Add caching. (gpgsm_get_fingerprint_string): Use bin2hexcolon(). (gpgsm_get_fingerprint_hexstring): Use bin2hex and allocate only as much memory as required. (gpgsm_get_keygrip_hexstring): Use bin2hex. * certchain.c (gpgsm_validate_chain): Keep track of the certificate chain and reset the ephemeral flags. * keydb.c (keydb_set_cert_flags): New args EPHEMERAL and MASK. Changed caller to use a mask of ~0. Return a proper error code if the certificate is not available. * gpgsm.c: Add option --p12-charset. * gpgsm.h (struct opt): Add p12_charset. * export.c (popen_protect_tool): Use new option. 2007-03-19 Werner Koch Changes to let export and key listing use estream to help systems without funopen. * keylist.c: Use estream in place of stdio functions. * gpgsm.c (open_es_fwrite): New. (main): Use it for the list commands. * server.c (data_line_cookie_functions): New. (data_line_cookie_write, data_line_cookie_close): New. (do_listkeys): Use estream. * certdump.c (gpgsm_print_serial): Changed to use estream. (gpgsm_print_time): Ditto. (pretty_es_print_sexp): New. (gpgsm_es_print_name): New. (print_dn_part): New arg STREAM. Changed all callers. (print_dn_parts): Ditto. * certchain.c (gpgsm_validate_chain): Changed FP to type estream_t. (do_list, unknown_criticals, allowed_ca, check_cert_policy) (is_cert_still_valid): Ditto. * export.c (gpgsm_export): New arg STREAM. (do_putc, do_fputs): New. (print_short_info): Allow printing to optional STREAM. * server.c (cmd_export): Use stream. * base64.c (do_putc, do_fputs): New. (base64_writer_cb, base64_finish_write): Let them cope with an alternate output function. (plain_writer_cb): New. (gpgsm_create_writer): New arg STREAM and call plain_writer_cb for binary output to an estream. Changed call callers. 2007-01-31 Werner Koch * gpgsm.c (main): Let --gen-key print a more informative error message. 2007-01-25 Werner Koch * Makefile.am (gpgsm_LDADD): Add LIBICONV. Noted by Billy Halsey. 2007-01-05 Werner Koch * certchain.c (unknown_criticals): Add subjectAltName. 2006-12-21 Werner Koch * gpgsm.c: Comment mtrace feature. 2006-12-21 Marcus Brinkmann * certchain.c (gpgsm_basic_cert_check): Release SUBJECT. * encrypt.c (encrypt_dek): Release S_CIPH. 2006-12-20 Marcus Brinkmann * server.c (gpgsm_server): Release CTRL->server_local. * base64.c: Add new members READER and WRITER in union U2. (gpgsm_create_reader): Initialise CTX->u2.reader. (gpgsm_destroy_reader): Invoke ksba_reader_release. Return early if CTX is NULL. (gpgsm_create_writer): Initialise CTX->u2.writer. (gpgsm_destroy_writer): Invoke ksba_writer_release. Return early if CTX is NULL. 2006-12-18 Marcus Brinkmann * fingerprint.c (gpgsm_get_fingerprint): Close MD. 2006-11-24 Werner Koch * certdump.c (parse_dn_part): Take '#' as a special character only at the beginning of a string. 2006-11-21 Werner Koch * certdump.c (my_funopen_hook_ret_t): New. (format_name_writer): Use it for the return value. 2006-11-14 Werner Koch * server.c (skip_options): Skip leading spaces. (has_option): Honor "--". (cmd_export): Add option --data to do an inline export. Skip all options. * certdump.c (gpgsm_fpr_and_name_for_status): New. * verify.c (gpgsm_verify): Use it to print correct status messages. 2006-11-11 Werner Koch * server.c (skip_options): New. 2006-10-24 Marcus Brinkmann * Makefile.am (AM_CFLAGS): Add $(LIBASSUAN_CFLAGS). 2006-10-23 Werner Koch * gpgsm.c (main): Remap common cipher algo names to their OIDs. (main): New command --gpgconf-test. 2006-10-20 Werner Koch * keydb.c (classify_user_id): Parse keygrip for the '&' identifier. 2006-10-18 Werner Koch * keylist.c (list_cert_raw): Also test for GPG_ERR_NO_VALUE when testing for GPG_ERR_NO_DATA. * certlist.c (cert_usage_p, gpgsm_find_cert): Ditto. * certchain.c (check_cert_policy): Ditto. * keylist.c (list_cert_std, list_cert_raw): Print "none" for no chain length available. 2006-10-17 Werner Koch * gpgsm.c: No need for pth.h. (main): or to init it. It used to be hack for W32. * sign.c (gpgsm_get_default_cert): Changed to return only certificates usable for signing. 2006-10-16 Werner Koch * certchain.c (already_asked_marktrusted) (set_already_asked_marktrusted): New. (gpgsm_validate_chain) : Keep track of certificates we already asked for. 2006-10-11 Werner Koch * certreqgen.c (proc_parameters, create_request): Allow for creation directly from a card. * call-agent.c (gpgsm_agent_readkey): New arg FROMCARD. (gpgsm_scd_pksign): New. 2006-10-06 Werner Koch * Makefile.am (AM_CFLAGS): Use PTH version of libassuan. (gpgsm_LDADD): Ditto. 2006-10-05 Werner Koch * certcheck.c (do_encode_md): Check that the has algo is valid. 2006-10-02 Marcus Brinkmann * server.c (register_commands): New commands DUMPKEYS and DUMPSECRETKEYS. (cmd_dumpkeys, cmd_dumpsecretkeys): New functions. (option_handler): Support with-key-data option. 2006-09-26 Werner Koch * certchain.c (gpgsm_validate_chain): More changes for the relax feature. Use certificate reference counting instead of the old explicit tests. Added a missing free. 2006-09-25 Werner Koch * gpgsm.h (struct rootca_flags_s): New. * call-agent.c (istrusted_status_cb): New. (gpgsm_agent_istrusted): New arg ROOTCA_FLAGS. * keylist.c (list_cert_colon): Use dummy for new arg. * certchain.c (gpgsm_validate_chain): Make use of the relax flag for root certificates. (unknown_criticals): Ignore a GPG_ERR_NO_VALUE. 2006-09-20 Werner Koch * gpgsm.c: Add alias command --dump-cert. * Makefile.am: Changes to allow parallel make runs. 2006-09-18 Werner Koch * gpgsm.c (main): Use this to import standard certificates. * keydb.c (keydb_add_resource): New arg AUTO_CREATED. 2006-09-14 Werner Koch Replaced all call gpg_error_from_errno(errno) by gpg_error_from_syserror(). 2006-09-13 Werner Koch * keylist.c (list_internal_keys): Print marker line to FP and not to stdout. * gpgsm.c (main): All list key list commands now make ose of --output. Cleaned up calls to list modes. New command --dump-chain. Renamed --list-sigs to --list-chain and added an alias for the old one. * server.c (cmd_message): Changed to use assuan_command_parse_fd. (option_handler): New option list-to-output. (do_listkeys): Use it. 2006-09-06 Werner Koch * gpgsm.h (OUT_OF_CORE): Removed and changed all callers to out_of_core. (CTRL): Removed and changed everywhere to ctrl_t. (CERTLIST): Ditto. Replaced all Assuan error codes by libgpg-error codes. Removed all map_to_assuan_status and map_assuan_err. * gpgsm.c (main): Call assuan_set_assuan_err_source to have Assuan switch to gpg-error codes. * server.c (set_error): Adjusted. 2006-08-29 Werner Koch * call-agent.c (gpgsm_agent_pkdecrypt): Allow decryption using complete S-expressions as implemented by the current gpg-agent. * gpgsm.c (main): Implement --output for encrypt, decrypt, sign and export. 2006-07-03 Werner Koch * certreqgen.c (proc_parameters): Print the component label of a faulty DN. 2006-06-26 Werner Koch * certdump.c (gpgsm_cert_log_name): New. * certchain.c (is_cert_still_valid): Log the name of the certificate. 2006-06-20 Werner Koch * gpgsm.c (gpgsm_init_default_ctrl): Take care of the command line option --include-certs. * keylist.c (list_cert_raw): Print the certid. 2006-05-23 Werner Koch * keydb.c (hextobyte): Deleted as it is now defined in jnlib. * Makefile.am (gpgsm_LDADD): Include ZLIBS. 2006-05-19 Marcus Brinkmann * keydb.c (keydb_insert_cert): Do not lock here, but only check if it is locked. (keydb_store_cert): Lock here. * keydb.h (keydb_delete): Accept new argument UNLOCK. * keydb.c (keydb_delete): Likewise. Only unlock if this is set. * delete.c (delete_one): Add new argument to invocation of keydb_delete. 2006-05-15 Werner Koch * keylist.c (print_names_raw): Sanitize URI. 2006-03-21 Werner Koch * certchain.c (get_regtp_ca_info): New. (allowed_ca): Use it. 2006-03-20 Werner Koch * qualified.c (gpgsm_is_in_qualified_list): New optional arg COUNTRY. 2006-02-17 Werner Koch * call-dirmngr.c (start_dirmngr): Print name of dirmngr to be started. 2005-11-23 Werner Koch * gpgsm.h: New member QUALSIG_APPROVAL. * sign.c (gpgsm_sign): Print a warning if a certificate is not qualified. * qualified.c (gpgsm_qualified_consent): Include a note that this is not approved software. (gpgsm_not_qualified_warning): New. * gpgsm.c (main): Prepared to print a note whether the software has been approved. 2005-11-13 Werner Koch * call-agent.c (gpgsm_agent_get_confirmation): New. * keylist.c (list_cert_std): Print qualified status. * qualified.c: New. * certchain.c (gpgsm_validate_chain): Check for qualified certificates. * certchain.c (gpgsm_basic_cert_check): Release keydb handle when no-chain-validation is used. 2005-11-11 Werner Koch * keylist.c (print_capabilities): Print is_qualified status. 2005-10-28 Werner Koch * certdump.c (pretty_print_sexp): New. (gpgsm_print_name2): Use it here. This allows proper printing of DNS names as used with server certificates. 2005-10-10 Werner Koch * keylist.c: Add pkaAdress OID as reference. 2005-10-08 Marcus Brinkmann * Makefile.am (gpgsm_LDADD): Add ../gl/libgnu.a after ../common/libcommon.a. 2005-09-13 Werner Koch * verify.c (gpgsm_verify): Print a note if the unknown algorithm is MD2. * sign.c (gpgsm_sign): Ditto. * certcheck.c (gpgsm_check_cert_sig): Ditto. 2005-09-08 Werner Koch * export.c (popen_protect_tool): Add option --have-cert. We probably lost this option with 1.9.14 due to restructuring of export.c. 2005-07-21 Werner Koch * gpgsm.c (main): New options --no-log-file and --debug-none. * certreqgen.c (get_parameter, get_parameter_value): Add SEQ arg to allow enumeration. Changed all callers. (create_request): Process DNS and URI parameters. 2005-07-20 Werner Koch * keylist.c (email_kludge): Reworked. * certdump.c (gpgsm_print_serial, gpgsm_dump_serial): Cast printf arg to unsigned. * call-dirmngr.c (gpgsm_dirmngr_run_command): Ditto 2005-07-19 Werner Koch * fingerprint.c (gpgsm_get_certid): Cast printf arg to unsigned. Bug accidently introduced while solving the #$%^& gcc signed/unsigned char* warnings. 2005-06-15 Werner Koch * delete.c (delete_one): Changed FPR to unsigned. * encrypt.c (encrypt_dek): Made ENCVAL unsigned. (gpgsm_encrypt): Ditto. * sign.c (gpgsm_sign): Made SIGVAL unsigned. * base64.c (base64_reader_cb): Need to use some casting to get around signed/unsigned char* warnings. * certcheck.c (gpgsm_check_cms_signature): Ditto. (gpgsm_create_cms_signature): Changed arg R_SIGVAL to unsigned char*. (do_encode_md): Made NFRAME a size_t. * certdump.c (gpgsm_print_serial): Fixed signed/unsigned warning. (gpgsm_dump_serial): Ditto. (gpgsm_format_serial): Ditto. (gpgsm_dump_string): Ditto. (gpgsm_dump_cert): Ditto. (parse_dn_part): Ditto. (gpgsm_print_name2): Ditto. * keylist.c (email_kludge): Ditto. * certreqgen.c (proc_parameters, create_request): Ditto. (create_request): Ditto. * call-agent.c (gpgsm_agent_pksign): Made arg R_BUF unsigned. (struct cipher_parm_s): Made CIPHERTEXT unsigned. (struct genkey_parm_s): Ditto. * server.c (strcpy_escaped_plus): Made arg S signed char*. * fingerprint.c (gpgsm_get_fingerprint): Made ARRAY unsigned. (gpgsm_get_keygrip): Ditto. * keydb.c (keydb_insert_cert): Made DIGEST unsigned. (keydb_update_cert): Ditto. (classify_user_id): Apply cast to signed/unsigned assignment. (hextobyte): Ditto. 2005-06-01 Werner Koch * misc.c: Include setenv.h. 2005-04-21 Werner Koch * gpgsm.c: New options --{enable,disable}-trusted-cert-crl-check. * certchain.c (gpgsm_validate_chain): Make use of it. * certchain.c (gpgsm_validate_chain): Check revocations even for expired certificates. This is required because on signature verification an expired key is fine whereas a revoked one is not. 2005-04-20 Werner Koch * Makefile.am (AM_CFLAGS): Add PTH_CFLAGS as noted by several folks. 2005-04-19 Werner Koch * certchain.c (check_cert_policy): Print the diagnostic for a open failure of policies.txt only in verbose mode or when it is not ENOENT. 2005-04-17 Werner Koch * call-dirmngr.c (inq_certificate): Add new inquire SENDCERT_SKI. * certlist.c (gpgsm_find_cert): Add new arg KEYID and implement this filter. Changed all callers. * certchain.c (find_up_search_by_keyid): New helper. (find_up): Also try using the AKI.keyIdentifier. (find_up_external): Ditto. 2005-04-15 Werner Koch * keylist.c (list_cert_raw): Print the subjectKeyIdentifier as well as the keyIdentifier part of the authorityKeyIdentifier. 2005-03-31 Werner Koch * call-dirmngr.c (start_dirmngr): Use PATHSEP_C instead of ':'. * call-agent.c (start_agent): Ditto. 2005-03-17 Werner Koch * certcheck.c: Fixed use of DBG_CRYPTO and DBG_X509. * certchain.c (gpgsm_basic_cert_check): Dump certificates after a failed gcry_pk_verify. (find_up): Do an external lookup also for an authorityKeyIdentifier lookup. Factored external lookup code out to .. (find_up_external): .. new. 2005-03-03 Werner Koch * Makefile.am (gpgsm_LDADD): Added PTH_LIBS. Noted by Kazu Yamamoto. 2005-01-13 Werner Koch * certreqgen.c (proc_parameters): Cast printf arg. 2004-12-22 Werner Koch * gpgsm.c (set_binary): New. (main, open_read, open_fwrite): Use it. 2004-12-21 Werner Koch * gpgsm.c (main): Use default_homedir(). (main) [W32]: Default to disabled CRL checks. 2004-12-20 Werner Koch * call-agent.c (start_agent): Before starting a pipe server start to connect to a server on the standard socket. Use PATHSEP * call-dirmngr.c (start_dirmngr): Use PATHSEP. * import.c: Include unistd.h for dup and close. 2004-12-18 Werner Koch * gpgsm.h (map_assuan_err): Define in terms of map_assuan_err_with_source. * call-agent.c (start_agent): Pass error source to send_pinentry_environment. 2004-12-17 Werner Koch * call-dirmngr.c (isvalid_status_cb, lookup_status_cb) (run_command_status_cb): Return cancel status if gpgsm_status returned an error. * server.c (gpgsm_status, gpgsm_status2) (gpgsm_status_with_err_code): Return an error code. (gpgsm_status2): Always call va_end(). 2004-12-15 Werner Koch * call-dirmngr.c (lookup_status_cb): Send progress messages upstream. (isvalid_status_cb): Ditto. (gpgsm_dirmngr_isvalid): Put CTRL into status CB parameters. (gpgsm_dirmngr_run_command, run_command_status_cb): Pass CTRL to status callback and handle PROGRESS. * misc.c (setup_pinentry_env) [W32]: Don't use it. * gpgsm.c (main) [W32]: Init Pth because we need it for the socket operations and to resolve libassuan symbols. (run_protect_tool) [W32]: Disable it. * Makefile.am (gpgsm_LDADD): Move LIBASSUAN_LIBS more to the end. 2004-12-07 Werner Koch * Makefile.am (gpgsm_LDADD): Put libassuan before jnlib because under W32 we need the w32 pth code from jnlib. * misc.c (setup_pinentry_env) [W32]: Disabled. 2004-12-06 Werner Koch * gpgsm.c (run_protect_tool) [_WIN32]: Disabled. * import.c (popen_protect_tool): Simplified by making use of gnupg_spawn_process. (parse_p12): Likewise, using gnupg_wait_process. * export.c (popen_protect_tool): Ditto. (export_p12): Ditto. * keydb.c: Don't define DIRSEP_S here. 2004-12-02 Werner Koch * certchain.c (gpgsm_basic_cert_check): Dump certs with bad signature for debugging. (gpgsm_validate_chain): Ditto. 2004-11-29 Werner Koch * gpgsm.c (set_debug): Changed to use a globals DEBUG_LEVEL and DEBUG_VALUE. (main): Made DEBUG_LEVEL global and introduced DEBUG_VALUE. This now allows to add debug flags on top of a debug-level setting. 2004-11-23 Werner Koch * gpgsm.c: New option --prefer-system-dirmngr. * call-dirmngr.c (start_dirmngr): Implement this option. 2004-10-22 Werner Koch * certreqgen.c (gpgsm_genkey): Remove the NEW from the certificate request PEM header. This is according to the Sphinx standard. 2004-10-08 Moritz Schulte * certchain.c (gpgsm_validate_chain): Do not use keydb_new() in case the no_chain_validation-return-short-cut is used (fixes memory leak). 2004-10-04 Werner Koch * misc.c (setup_pinentry_env): Try hard to set a default for GPG_TTY. 2004-09-30 Werner Koch * gpgsm.c (i18n_init): Always use LC_ALL. * certdump.c (gpgsm_format_name): Factored code out to .. (gpgsm_format_name2): .. new. (gpgsm_print_name): Factored code out to .. (gpgsm_print_name2): .. new. (print_dn_part): New arg TRANSLATE. Changed all callers. (print_dn_parts): Ditto. (gpgsm_format_keydesc): Do not translate the SUBJECT; we require it to stay UTF-8 but we still want to filter out bad control characters. * Makefile.am: Adjusted for gettext 0.14. * keylist.c (list_cert_colon): Make sure that the expired flag has a higher precedence than the invalid flag. 2004-09-29 Werner Koch * import.c (parse_p12): Write an error status line for bad passphrases. Add new arg CTRL and changed caller. * export.c (export_p12): Likewise. 2004-09-14 Werner Koch * certchain.c (gpgsm_validate_chain): Give expired certificates a higher error precedence and don't bother to check any CRL in that case. 2004-08-24 Werner Koch * certlist.c: Fixed typo in ocsp OID. 2004-08-18 Werner Koch * certlist.c (gpgsm_cert_use_ocsp_p): New. (cert_usage_p): Support it here. * call-dirmngr.c (gpgsm_dirmngr_isvalid): Use it here. 2004-08-17 Marcus Brinkmann * import.c: Fix typo in last change. 2004-08-17 Werner Koch * import.c (check_and_store): Do a full validation if --with-validation is set. * certchain.c (gpgsm_basic_cert_check): Print more detailed error messages. * certcheck.c (do_encode_md): Partly support DSA. Add new arg PKALGO. Changed all callers to pass it. (pk_algo_from_sexp): New. 2004-08-16 Werner Koch * gpgsm.c: New option --fixed-passphrase. * import.c (popen_protect_tool): Pass it to the protect-tool. * server.c (cmd_encrypt): Use DEFAULT_RECPLIST and not recplist for encrypt-to keys. 2004-08-06 Werner Koch * gpgsm.c: New option --with-ephemeral-keys. * keylist.c (list_internal_keys): Set it here. (list_cert_raw): And indicate those keys. Changed all our callers to pass the new arg HD through. 2004-07-23 Werner Koch * certreqgen.c (proc_parameters): Do not allow key length below 1024. 2004-07-22 Werner Koch * keylist.c (list_cert_raw): Print the keygrip. 2004-07-20 Werner Koch * certchain.c (gpgsm_validate_chain): The trust check didn't worked anymore, probably due to the changes at 2003-03-04. Fixed. 2004-06-06 Werner Koch * certreqgen.c (get_parameter_uint, create_request): Create an extension for key usage when requested. 2004-05-12 Werner Koch * gpgsm.c (main): Install emergency_cleanup also as an atexit handler. * verify.c (gpgsm_verify): Removed the separate error code handling for KSBA. We use shared error codes anyway. * export.c (export_p12): Removed debugging code. * encrypt.c (gpgsm_encrypt): Put the session key in to secure memory. 2004-05-11 Werner Koch * sign.c (gpgsm_sign): Include the error source in the final error message. * decrypt.c (gpgsm_decrypt): Ditto. * fingerprint.c (gpgsm_get_key_algo_info): New. * sign.c (gpgsm_sign): Don't assume RSA in the status line. * keylist.c (list_cert_colon): Really print the algorithm and key length. (list_cert_raw, list_cert_std): Ditto. (list_cert_colon): Reorganized to be able to tell whether a root certificate is trusted. * gpgsm.c: New option --debug-allow-core-dump. * gpgsm.h (opt): Add member CONFIG_FILENAME. * gpgsm.c (main): Use it here instead of the local var. * server.c (gpgsm_server): Print some additional information with the hello in verbose mode. 2004-04-30 Werner Koch * import.c (check_and_store): Do not update the stats for hidden imports of issuer certs. (popen_protect_tool): Request statusmessages from the protect-tool. (parse_p12): Detect status messages. Add new arg STATS and update them. (print_imported_summary): Include secret key stats. 2004-04-28 Werner Koch * gpgsm.c: New command --keydb-clear-some-cert-flags. * keydb.c (keydb_clear_some_cert_flags): New. (keydb_update_keyblock, keydb_set_flags): Change error code CONFLICT to NOT_LOCKED. 2004-04-26 Werner Koch * gpgsm.c (main) : Do not use /dev/null as default config filename. * call-agent.c (gpgsm_agent_pksign, gpgsm_agent_pkdecrypt) (gpgsm_agent_genkey, gpgsm_agent_istrusted) (gpgsm_agent_marktrusted, gpgsm_agent_havekey) (gpgsm_agent_passwd): Add new arg CTRL and changed all callers. (start_agent): New arg CTRL. Send progress item when starting a new agent. * sign.c (gpgsm_get_default_cert, get_default_signer): New arg CTRL to be passed down to the agent function. * decrypt.c (prepare_decryption): Ditto. * certreqgen.c (proc_parameters, read_parameters): Ditto. * certcheck.c (gpgsm_create_cms_signature): Ditto. 2004-04-23 Werner Koch * keydb.c (keydb_add_resource): Try to compress the file on init. * keylist.c (oidtranstbl): New. OIDs collected from several sources. (print_name_raw, print_names_raw, list_cert_raw): New. (gpgsm_list_keys): Check the dump mode and pass it down as necessary. 2004-04-22 Werner Koch * gpgsm.c (main): New commands --dump-keys, --dump-external-keys, --dump-secret-keys. 2004-04-13 Werner Koch * misc.c (setup_pinentry_env): New. * import.c (popen_protect_tool): Call it. * export.c (popen_protect_tool): Call it. 2004-04-08 Werner Koch * decrypt.c (gpgsm_decrypt): Return GPG_ERR_NO_DATA if it is not a encrypted message. 2004-04-07 Werner Koch * gpgsm.c: New option --force-crl-refresh. * call-dirmngr.c (gpgsm_dirmngr_isvalid): Pass option to dirmngr. 2004-04-05 Werner Koch * server.c (get_status_string): Add STATUS_NEWSIG. * verify.c (gpgsm_verify): Print STATUS_NEWSIG for each signature. * certchain.c (gpgsm_validate_chain) : Do not just warn if a cert is not suitable; bail out immediately. 2004-04-01 Werner Koch * call-dirmngr.c (isvalid_status_cb): New. (unhexify_fpr): New. Taken from ../g10/call-agent.c (gpgsm_dirmngr_isvalid): Add new arg CTRL, changed caller to pass it thru. Detect need to check the respondert cert and do that. * certchain.c (gpgsm_validate_chain): Add new arg FLAGS. Changed all callers. 2004-03-24 Werner Koch * sign.c (gpgsm_sign): Include a short list of capabilities. 2004-03-17 Werner Koch * gpgsm.c (main) : Fixed default value quoting. 2004-03-16 Werner Koch * gpgsm.c (main): Implemented --gpgconf-list. 2004-03-15 Werner Koch * keylist.c (list_cert_colon): Hack to set the expired flag. 2004-03-09 Werner Koch * gpgsm.c (main): Correctly intitialze USE_OCSP flag. * keydb.c (keydb_delete): s/GPG_ERR_CONFLICT/GPG_ERR_NOT_LOCKED/ 2004-03-04 Werner Koch * call-dirmngr.c (gpgsm_dirmngr_isvalid): New arg ISSUER_CERT. * certchain.c (is_cert_still_valid): New. Code moved from ... (gpgsm_validate_chain): ... here because we now need to check at two places and at a later stage, so that we can pass the issuer cert down to the dirmngr. 2004-03-03 Werner Koch * call-agent.c (start_agent): Replaced pinentry setup code by a call to a new common function. * certdump.c (gpgsm_format_keydesc): Make sure the string is returned as utf-8. * export.c (gpgsm_export): Make sure that we don't export more than one certificate. 2004-03-02 Werner Koch * export.c (create_duptable, destroy_duptable) (insert_duptable): New. (gpgsm_export): Avoid duplicates. 2004-02-26 Werner Koch * certchain.c (compare_certs): New. (gpgsm_validate_chain): Fixed infinite certificate checks after bad signatures. 2004-02-24 Werner Koch * keylist.c (list_cert_colon): Print the fingerprint as the cert-id for root certificates. 2004-02-21 Werner Koch * keylist.c (list_internal_keys): Return error codes. (list_external_keys, gpgsm_list_keys): Ditto. * server.c (do_listkeys): Ditto. * gpgsm.c (main): Display a key description for --passwd. * call-agent.c (gpgsm_agent_passwd): New arg DESC. 2004-02-20 Werner Koch * gpgsm.c (main): New option --debug-ignore-expiration. * certchain.c (gpgsm_validate_chain): Use it here. * certlist.c (cert_usage_p): Apply extKeyUsage. 2004-02-19 Werner Koch * export.c (export_p12, popen_protect_tool) (gpgsm_p12_export): New. * gpgsm.c (main): New command --export-secret-key-p12. 2004-02-18 Werner Koch * gpgsm.c (set_debug): Set the new --debug-level flags. (main): New option --gpgconf-list. (main): Do not setup -u and -r keys when not required. (main): Setup the used character set. * keydb.c (keydb_add_resource): Print a hint to start the gpg-agent. 2004-02-17 Werner Koch * gpgsm.c: Fixed value parsing for --with-validation. * call-agent.c (start_agent): Ignore an empty GPG_AGENT_INFO. * call-dirmngr.c (start_dirmngr): Likewise for DIRMNGR_INFO. * gpgsm.c: New option --with-md5-fingerprint. * keylist.c (list_cert_std): Print MD5 fpr. * gpgsm.c: New options --with-validation. * server.c (option_handler): New option "with-validation". * keylist.c (list_cert_std, list_internal_keys): New args CTRL and WITH_VALIDATION. Changed callers to set it. (list_external_cb, list_external_keys): Pass CTRL to the callback. (list_cert_colon): Add arg CTRL. Check validation if requested. * certchain.c (unknown_criticals, allowed_ca, check_cert_policy) (gpgsm_validate_chain): New args LISTMODE and FP. (do_list): New helper for info output. (find_up): New arg FIND_NEXT. (gpgsm_validate_chain): After a bad signature try again with other CA certificates. * import.c (print_imported_status): New arg NEW_CERT. Print additional STATUS_IMPORT_OK becuase that is what gpgme expects. (check_and_store): Always call above function after import. * server.c (get_status_string): Added STATUS_IMPORT_OK. 2004-02-13 Werner Koch * certcheck.c (gpgsm_create_cms_signature): Format a description for use by the pinentry. * decrypt.c (gpgsm_decrypt): Ditto. Free HEXKEYGRIP. * certdump.c (format_name_cookie, format_name_writer) (gpgsm_format_name): New. (gpgsm_format_serial): New. (gpgsm_format_keydesc): New. * call-agent.c (gpgsm_agent_pksign): New arg DESC. (gpgsm_agent_pkdecrypt): Ditto. * encrypt.c (init_dek): Check for too weak algorithms. * import.c (parse_p12, popen_protect_tool): New. * base64.c (gpgsm_create_reader): New arg ALLOW_MULTI_PEM. Changed all callers. (base64_reader_cb): Handle it here. (gpgsm_reader_eof_seen): New. (base64_reader_cb): Set a flag for EOF. (simple_reader_cb): Ditto. 2004-02-12 Werner Koch * gpgsm.h, gpgsm.c: New option --protect-tool-program. * gpgsm.c (run_protect_tool): Use it. 2004-02-11 Werner Koch * Makefile.am (AM_CPPFLAGS): Pass directory constants via -D; this will allow to override directory names at make time. 2004-02-02 Werner Koch * import.c (check_and_store): Import certificates even with missing issuer's cert. Fixed an "depending on the verbose setting" bug. * certchain.c (gpgsm_validate_chain): Mark revoked certs in the keybox. * keylist.c (list_cert_colon): New arg VALIDITY; use it to print a revoked flag. (list_internal_keys): Retrieve validity flag. (list_external_cb): Pass 0 as validity flag. * keydb.c (keydb_get_flags, keydb_set_flags): New. (keydb_set_cert_flags): New. (lock_all): Return a proper error code. (keydb_lock): New. (keydb_delete): Don't lock but check that it has been locked. (keydb_update_keyblock): Ditto. * delete.c (delete_one): Take a lock. 2004-01-30 Werner Koch * certchain.c (check_cert_policy): Fixed read error checking. (check_cert_policy): With no critical policies issue only a warning if the policy file does not exists. * sign.c (add_certificate_list): Decrement N for the first cert. 2004-01-29 Werner Koch * certdump.c (parse_dn_part): Map common OIDs to human readable labels. Make sure that a value won't get truncated if it includes a Nul. 2004-01-28 Werner Koch * certchain.c (gpgsm_validate_chain): Changed the message printed for an untrusted root certificate. 2004-01-27 Werner Koch * certdump.c (parse_dn_part): Pretty print the nameDistinguisher OID. (print_dn_part): Do not delimit multiple RDN by " + ". Handle multi-valued RDNs in a special way, i.e. in the order specified by the certificate. (print_dn_parts): Simplified. 2004-01-16 Werner Koch * sign.c (gpgsm_sign): Print an error message on all failures. * decrypt.c (gpgsm_decrypt): Ditto. 2003-12-17 Werner Koch * server.c (gpgsm_server): Add arg DEFAULT_RECPLIST. (cmd_encrypt): Add all enrypt-to marked certs to the list. * encrypt.c (gpgsm_encrypt): Check that real recipients are available. * gpgsm.c (main): Make the --encrypt-to and --no-encrypt-to options work. Pass the list of recients to gpgsm_server. * gpgsm.h (certlist_s): Add field IS_ENCRYPT_TO. (opt): Add NO_ENCRYPT_TO. * certlist.c (gpgsm_add_to_certlist): New arg IS_ENCRYPT_TO. Changed all callers and ignore duplicate entries. (is_cert_in_certlist): New. (gpgsm_add_cert_to_certlist): New. * certdump.c (gpgsm_print_serial): Cleaned up cast use in strtoul. (gpgsm_dump_serial): Ditto. * decrypt.c (gpgsm_decrypt): Replaced ERR by RC. 2003-12-16 Werner Koch * gpgsm.c (main): Set the prefixes for assuan logging. * sign.c (gpgsm_sign): Add validation checks for the default certificate. * gpgsm.c: Add -k as alias for --list-keys and -K for --list-secret-keys. 2003-12-15 Werner Koch * encrypt.c (init_dek): Use gry_create_nonce for the IV; there is not need for real strong random here and it even better protect the random bits used for the key. 2003-12-01 Werner Koch * gpgsm.c, gpgsm.h: New options --{enable,disable}-ocsp. (gpgsm_init_default_ctrl): Set USE_OCSP to the default value. * certchain.c (gpgsm_validate_chain): Handle USE_OCSP. * call-dirmngr.c (gpgsm_dirmngr_isvalid): Add arg USE_OCSP and proceed accordingly. 2003-11-19 Werner Koch * verify.c (gpgsm_verify): Use "0" instead of an empty string for the VALIDSIG status. 2003-11-18 Werner Koch * verify.c (gpgsm_verify): Fixed for changes API of gcry_md_info. * certchain.c (unknown_criticals): Fixed an error code test. 2003-11-12 Werner Koch Adjusted for API changes in Libksba. 2003-10-31 Werner Koch * certchain.c (gpgsm_validate_chain): Changed to use ksba_isotime_t. * verify.c (strtimestamp_r, gpgsm_verify): Ditto. * sign.c (gpgsm_sign): Ditto. * keylist.c (print_time, list_cert_std, list_cert_colon): Ditto. * certdump.c (gpgsm_print_time, gpgsm_dump_time, gpgsm_dump_cert): Ditto. 2003-10-25 Werner Koch * certreqgen.c (read_parameters): Fixed faulty of !spacep(). 2003-08-20 Marcus Brinkmann * encrypt.c (encode_session_key): Allocate enough space. Cast key byte to unsigned char to prevent sign extension. (encrypt_dek): Check return value before error. 2003-08-14 Timo Schulz * encrypt.c (encode_session_key): Use new Libgcrypt interface. 2003-07-31 Werner Koch * Makefile.am (gpgsm_LDADD): Added INTLLIBS. 2003-07-29 Werner Koch * gpgsm.c (main): Add secmem features and set the random seed file. (gpgsm_exit): Update the random seed file and enable debug output. 2003-07-27 Werner Koch Adjusted for gcry_mpi_print and gcry_mpi_scan API change. 2003-06-24 Werner Koch * server.c (gpgsm_status_with_err_code): New. * verify.c (gpgsm_verify): Use it here instead of the old tokenizing version. * verify.c (strtimestamp): Renamed to strtimestamp_r Adjusted for changes in the libgcrypt API. Some more fixes for the libgpg-error stuff. 2003-06-04 Werner Koch * call-agent.c (init_membuf,put_membuf,get_membuf): Removed. Include new membuf header and changed used type. Renamed error codes from INVALID to INV and removed _ERROR suffixes. 2003-06-03 Werner Koch Changed all error codes in all files to the new libgpg-error scheme. * gpgsm.h: Include gpg-error.h . * Makefile.am: Link with libgpg-error. 2003-04-29 Werner Koch * Makefile.am: Use libassuan. Don't override LDFLAGS anymore. * server.c (register_commands): Adjust for new Assuan semantics. 2002-12-03 Werner Koch * call-agent.c (gpgsm_agent_passwd): New. * gpgsm.c (main): New command --passwd and --call-protect-tool (run_protect_tool): New. 2002-11-25 Werner Koch * verify.c (gpgsm_verify): Handle content-type attribute. 2002-11-13 Werner Koch * call-agent.c (start_agent): Try to use $GPG_TTY instead of ttyname. Changed ttyname to test stdin becuase it can be assumed that output redirection is more common that input redirection. 2002-11-12 Werner Koch * gpgsm.c: New command --call-dirmngr. * call-dirmngr.c (gpgsm_dirmngr_run_command) (run_command_inq_cb,run_command_cb) (run_command_status_cb): New. 2002-11-11 Werner Koch * certcheck.c (gpgsm_check_cms_signature): Don't double free s_sig but free s_pkey at leave. 2002-11-10 Werner Koch * gpgsm.c: Removed duplicate --list-secret-key entry. 2002-09-19 Werner Koch * certcheck.c (gpgsm_check_cert_sig): Add cert hash debugging. * certchain.c (find_up): Print info when the cert was not found by the autorithyKeyIdentifier. 2002-09-03 Werner Koch * gpgsm.c (main): Disable the internal libgcrypt locking. 2002-08-21 Werner Koch * import.c (print_imported_summary): Cleaned up. Print new not_imported value. (check_and_store): Update non_imported counter. (print_import_problem): New. (check_and_store): Print error status message. * server.c (get_status_string): Added STATUS_IMPORT_PROBLEM. 2002-08-20 Werner Koch * gpgsm.c (main): Use the log file only in server mode. * import.c (print_imported_summary): New. (check_and_store): Update the counters, take new argument. (import_one): Factored out core of gpgsm_import. (gpgsm_import): Print counters. (gpgsm_import_files): New. * gpgsm.c (main): Use the new function for import. 2002-08-19 Werner Koch * decrypt.c (gpgsm_decrypt): Return a better error status token. * verify.c (gpgsm_verify): Don't error on messages with no signing time or no message digest. This is only the case for messages without any signed attributes. 2002-08-16 Werner Koch * certpath.c: Renamed to .. * certchain.c: this. Renamed all all other usages of "path" in the context of certificates to "chain". * call-agent.c (learn_cb): Special treatment when the issuer certificate is missing. 2002-08-10 Werner Koch * Makefile.am (INCLUDES): Add definition for localedir. * keylist.c (list_cert_colon): Print the short fingerprint in the key ID field. * fingerprint.c (gpgsm_get_short_fingerprint): New. * verify.c (gpgsm_verify): Print more verbose info for a good signature. 2002-08-09 Werner Koch * decrypt.c (prepare_decryption): Hack to detected already unpkcsedone keys. * gpgsm.c (emergency_cleanup): New. (main): Initialize the signal handler. * sign.c (gpgsm_sign): Reset the hash context for subsequent signers and release it at the end. 2002-08-05 Werner Koch * server.c (cmd_signer): New command "SIGNER" (register_commands): Register it. (cmd_sign): Pass the signer list to gpgsm_sign. * certlist.c (gpgsm_add_to_certlist): Add SECRET argument, check for secret key if set and changed all callers. * sign.c (gpgsm_sign): New argument SIGNERLIST and implemt multiple signers. * gpgsm.c (main): Support more than one -u. * server.c (cmd_recipient): Return reason code 1 for No_Public_Key which is actually what gets returned from add_to_certlist. 2002-07-26 Werner Koch * certcheck.c (gpgsm_check_cert_sig): Implement proper cleanup. (gpgsm_check_cms_signature): Ditto. 2002-07-22 Werner Koch * keydb.c (keydb_add_resource): Register a lock file. (lock_all, unlock_all): Implemented. * delete.c: New. * gpgsm.c: Made --delete-key work. * server.c (cmd_delkeys): New. (register_commands): New command DELKEYS. * decrypt.c (gpgsm_decrypt): Print a convenience note when RC2 is used and a STATUS_ERROR with the algorithm oid. 2002-07-03 Werner Koch * server.c (gpgsm_status2): Insert a blank between all optional arguments when using assuan. * server.c (cmd_recipient): No more need for extra blank in constants. * import.c (print_imported_status): Ditto. * gpgsm.c (main): Ditto. 2002-07-02 Werner Koch * verify.c (gpgsm_verify): Extend the STATUS_BADSIG line with the fingerprint. * certpath.c (check_cert_policy): Don't use log_error to print a warning. * keydb.c (keydb_store_cert): Add optional ar EXISTED and changed all callers. * call-agent.c (learn_cb): Print info message only for real imports. * import.c (gpgsm_import): Moved duplicated code to ... (check_and_store): new function. Added magic to import the entire chain. Print status only for real imports and moved printing code to .. (print_imported_status): New. * call-dirmngr.c (gpgsm_dirmngr_isvalid): print status of dirmngr call in very verbose mode. * gpgsm.c (main): Use the same error codes for STATUS_INV_RECP as with the server mode. 2002-06-29 Werner Koch * gpgsm.c: New option --auto-issuer-key-retrieve. * certpath.c (find_up): Try to retrieve an issuer key from an external source and from the ephemeral key DB. (find_up_store_certs_cb): New. * keydb.c (keydb_set_ephemeral): Does now return the old state. Call the backend only when required. * call-dirmngr.c (start_dirmngr): Use GNUPG_DEFAULT_DIRMNGR. (lookup_status_cb): Issue status only when CTRL is not NULL. (gpgsm_dirmngr_lookup): Document that CTRL is optional. * call-agent.c (start_agent): Use GNUPG_DEFAULT_AGENT. 2002-06-28 Werner Koch * server.c (cmd_recipient): Add more reason codes. 2002-06-27 Werner Koch * certpath.c (gpgsm_basic_cert_check): Use --debug-no-path-validation to also bypass this basic check. * gpgsm.c (main): Use GNUPG_DEFAULT_HOMEDIR constant. * call-agent.c (start_agent): Create and pass the list of FD to keep in the child to assuan. * call-dirmngr.c (start_dirmngr): Ditto. 2002-06-26 Werner Koch * import.c (gpgsm_import): Print an STATUS_IMPORTED. * gpgsm.c: --debug-no-path-validation does not take an argument. 2002-06-25 Werner Koch * certdump.c (print_dn_part): Always print a leading slash, removed NEED_DELIM arg and changed caller. * export.c (gpgsm_export): Print LFs to FP and not stdout. (print_short_info): Ditto. Make use of gpgsm_print_name. * server.c (cmd_export): Use output-fd instead of data lines; this was actually the specified way. 2002-06-24 Werner Koch * gpgsm.c: Removed duped help entry for --list-keys. * gpgsm.c, gpgsm.h: New option --debug-no-path-validation. * certpath.c (gpgsm_validate_path): Use it here instead of the debug flag hack. * certpath.c (check_cert_policy): Return No_Policy_Match if the policy file could not be opened. 2002-06-20 Werner Koch * certlist.c (gpgsm_add_to_certlist): Fixed locating of a certificate with the required key usage. * gpgsm.c (main): Fixed a segv when using --outfile without an argument. * keylist.c (print_capabilities): Also check for non-repudiation and data encipherment. * certlist.c (cert_usage_p): Test for signing and encryption was swapped. Add a case for certification usage, handle non-repudiation and data encipherment. (gpgsm_cert_use_cert_p): New. (gpgsm_add_to_certlist): Added a CTRL argument and changed all callers to pass it. * certpath.c (gpgsm_validate_path): Use it here to print a status message. Added a CTRL argument and changed all callers to pass it. * decrypt.c (gpgsm_decrypt): Print a status message for wrong key usage. * verify.c (gpgsm_verify): Ditto. * keydb.c (classify_user_id): Allow a colon delimited fingerprint. 2002-06-19 Werner Koch * call-agent.c (learn_cb): Use log_info instead of log_error on successful import. * keydb.c (keydb_set_ephemeral): New. (keydb_store_cert): New are ephemeral, changed all callers. * keylist.c (list_external_cb): Store cert as ephemeral. * export.c (gpgsm_export): Kludge to export epehmeral certificates. * gpgsm.c (main): New command --list-external-keys. 2002-06-17 Werner Koch * certreqgen.c (read_parameters): Improved error handling. (gpgsm_genkey): Print error message. 2002-06-13 Werner Koch * gpgsm.c (main): New option --log-file. 2002-06-12 Werner Koch * call-dirmngr.c (lookup_status_cb): New. (gpgsm_dirmngr_lookup): Use the status CB. Add new arg CTRL and changed caller to pass it. * gpgsm.c (open_fwrite): New. (main): Allow --output for --verify. * sign.c (hash_and_copy_data): New. (gpgsm_sign): Implemented normal (non-detached) signatures. * gpgsm.c (main): Ditto. * certpath.c (gpgsm_validate_path): Special error handling for no policy match. 2002-06-10 Werner Koch * server.c (get_status_string): Add STATUS_ERROR. * certpath.c (gpgsm_validate_path): Tweaked the error checking to return error codes in a more sensitive way. * verify.c (gpgsm_verify): Send status TRUST_NEVER also for a bad CA certificate and when the certificate has been revoked. Issue TRUST_FULLY even when the cert has expired. Append an error token to these status lines. Issue the new generic error status when a cert was not found and when leaving the function. 2002-06-04 Werner Koch * gpgsm.c (main): New command --list-sigs * keylist.c (list_cert_std): New. Use it whenever colon mode is not used. (list_cert_chain): New. 2002-05-31 Werner Koch * gpgsm.c (main): Don't print the "go ahead" message for an invalid command. 2002-05-23 Werner Koch * import.c (gpgsm_import): Add error messages. 2002-05-21 Werner Koch * keylist.c (list_internal_keys): Renamed from gpgsm_list_keys. (list_external_keys): New. (gpgsm_list_keys): Dispatcher for above. * call-dirmngr.c (lookup_cb,pattern_from_strlist) (gpgsm_dirmngr_lookup): New. * server.c (option_handler): Handle new option --list-mode. (do_listkeys): Handle options and actually use the mode argument. (get_status_string): New code TRUNCATED. * import.c (gpgsm_import): Try to identify the type of input and handle certs-only messages. 2002-05-14 Werner Koch * gpgsm.c: New option --faked-system-time * sign.c (gpgsm_sign): And use it here. * certpath.c (gpgsm_validate_path): Ditto. 2002-05-03 Werner Koch * certpath.c (gpgsm_validate_path): Added EXPTIME arg and changed all callers. * verify.c (gpgsm_verify): Tweaked usage of log_debug and log_error. Return EXPSIG status and add expiretime to VALIDSIG. 2002-04-26 Werner Koch * gpgsm.h (DBG_AGENT,DBG_AGENT_VALUE): Replaced by DBG_ASSUAN_*. Changed all users. * call-agent.c (start_agent): Be more silent without -v. * call-dirmngr.c (start_dirmngr): Ditto. 2002-04-25 Werner Koch * call-agent.c (start_agent): Make copies of old locales and check for setlocale. 2002-04-25 Marcus Brinkmann * call-agent.c (start_agent): Fix error handling logic so the locale is always correctly reset. 2002-04-25 Marcus Brinkmann * server.c (option_handler): Accept display, ttyname, ttytype, lc_ctype and lc_messages options. * gpgsm.c (main): Allocate memory for these options. * gpgsm.h (struct opt): Make corresponding members non-const. 2002-04-24 Marcus Brinkmann * gpgsm.h (struct opt): New members display, ttyname, ttytype, lc_ctype, lc_messages. * gpgsm.c (enum cmd_and_opt_values): New members oDisplay, oTTYname, oTTYtype, oLCctype, oLCmessages. (opts): New entries for these options. (main): Handle these new options. * call-agent.c (start_agent): Set the various display and tty parameter after resetting. 2002-04-18 Werner Koch * certreqgen.c (gpgsm_genkey): Write status output on success. 2002-04-15 Werner Koch * gpgsm.c (main): Check ksba version. * certpath.c (find_up): New to use the authorithKeyIdentifier. Use it in all other functions to locate the signing cert.. 2002-04-11 Werner Koch * certlist.c (cert_usable_p): New. (gpgsm_cert_use_sign_p,gpgsm_cert_use_encrypt_p): New. (gpgsm_cert_use_verify_p,gpgsm_cert_use_decrypt_p): New. (gpgsm_add_to_certlist): Check the key usage. * sign.c (gpgsm_sign): Ditto. * verify.c (gpgsm_verify): Print a message wehn an unsuitable certificate was used. * decrypt.c (gpgsm_decrypt): Ditto * keylist.c (print_capabilities): Determine values from the cert. 2002-03-28 Werner Koch * keylist.c (list_cert_colon): Fixed listing of crt record; the issuer is not at the right place. Print a chainingID. * certpath.c (gpgsm_walk_cert_chain): Be a bit more silent on common errors. 2002-03-21 Werner Koch * export.c: New. * gpgsm.c: Add command --export. * server.c (cmd_export): New. 2002-03-13 Werner Koch * decrypt.c (gpgsm_decrypt): Allow multiple recipients. 2002-03-12 Werner Koch * certpath.c (check_cert_policy): Print the policy list. * verify.c (gpgsm_verify): Detect certs-only message. 2002-03-11 Werner Koch * import.c (gpgsm_import): Print a notice about imported certificates when in verbose mode. * gpgsm.c (main): Print INV_RECP status. * server.c (cmd_recipient): Ditto. * server.c (gpgsm_status2): New. Allows for a list of strings. (gpgsm_status): Divert to gpgsm_status2. * encrypt.c (gpgsm_encrypt): Don't use a default key when no recipients are given. Print a NO_RECP status. 2002-03-06 Werner Koch * server.c (cmd_listkeys, cmd_listsecretkeys): Divert to (do_listkeys): new. Add pattern parsing. * keylist.c (gpgsm_list_keys): Handle selection pattern. * gpgsm.c: New command --learn-card * call-agent.c (learn_cb,gpgsm_agent_learn): New. * gpgsm.c (main): Print error messages for non-implemented commands. * base64.c (base64_reader_cb): Use case insensitive compare of the Content-Type string to detect plain base-64. 2002-03-05 Werner Koch * gpgsm.c, gpgsm.h: Add local_user. * sign.c (gpgsm_get_default_cert): New. (get_default_signer): Use the new function if local_user is not set otherwise used that value. * encrypt.c (get_default_recipient): Removed. (gpgsm_encrypt): Use gpgsm_get_default_cert. * verify.c (gpgsm_verify): Better error text for a bad signature found by comparing the hashs. 2002-02-27 Werner Koch * call-dirmngr.c, call-agent.c: Add 2 more arguments to all uses of assuan_transact. 2002-02-25 Werner Koch * server.c (option_handler): Allow to use -2 for "send all certs except the root cert". * sign.c (add_certificate_list): Implement it here. * certpath.c (gpgsm_is_root_cert): New. 2002-02-19 Werner Koch * certpath.c (check_cert_policy): New. (gpgsm_validate_path): And call it from here. * gpgsm.c (main): New options --policy-file, --disable-policy-checks and --enable-policy-checks. * gpgsm.h (opt): Added policy_file, no_policy_checks. 2002-02-18 Werner Koch * certpath.c (gpgsm_validate_path): Ask the agent to add the certificate into the trusted list. * call-agent.c (gpgsm_agent_marktrusted): New. 2002-02-07 Werner Koch * certlist.c (gpgsm_add_to_certlist): Check that the specified name identifies a certificate unambiguously. (gpgsm_find_cert): Ditto. * server.c (cmd_listkeys): Check that the data stream is available. (cmd_listsecretkeys): Ditto. (has_option): New. (cmd_sign): Fix ambiguousity in option recognition. * gpgsm.c (main): Enable --logger-fd. * encrypt.c (gpgsm_encrypt): Increased buffer size for better performance. * call-agent.c (gpgsm_agent_pksign): Check the S-Exp received from the agent. * keylist.c (list_cert_colon): Filter out control characters. 2002-02-06 Werner Koch * decrypt.c (gpgsm_decrypt): Bail out after an decryption error. * server.c (reset_notify): Close input and output FDs. (cmd_encrypt,cmd_decrypt,cmd_verify,cmd_sign.cmd_import) (cmd_genkey): Close the FDs and release the recipient list even in the error case. 2002-02-01 Marcus Brinkmann * sign.c (gpgsm_sign): Do not release certificate twice. 2002-01-29 Werner Koch * call-agent.c (gpgsm_agent_havekey): New. * keylist.c (list_cert_colon): New arg HAVE_SECRET, print "crs" when we know that the secret key is available. (gpgsm_list_keys): New arg MODE, check whether a secret key is available. Changed all callers. * gpgsm.c (main): New command --list-secret-keys. * server.c (cmd_listsecretkeys): New. (cmd_listkeys): Return secret keys with "crs" record. 2002-01-28 Werner Koch * certreqgen.c (create_request): Store the email address in the req. 2002-01-25 Werner Koch * gpgsm.c (main): Disable core dumps. * sign.c (add_certificate_list): New. (gpgsm_sign): Add the certificates to the CMS object. * certpath.c (gpgsm_walk_cert_chain): New. * gpgsm.h (server_control_s): Add included_certs. * gpgsm.c: Add option --include-certs. (gpgsm_init_default_ctrl): New. (main): Call it. * server.c (gpgsm_server): Ditto. (option_handler): Support --include-certs. 2002-01-23 Werner Koch * certpath.c (gpgsm_validate_path): Print the DN of a missing issuer. * certdump.c (gpgsm_dump_string): New. (print_dn): Replaced by above. 2002-01-22 Werner Koch * certpath.c (unknown_criticals): New. (allowed_ca): New. (gpgsm_validate_path): Check validity, CA attribute, path length and unknown critical extensions. 2002-01-21 Werner Koch * gpgsm.c: Add option --enable-crl-checks. * call-agent.c (start_agent): Implemented socket based access. * call-dirmngr.c (start_dirmngr): Ditto. 2002-01-20 Werner Koch * server.c (option_handler): New. (gpgsm_server): Register it with assuan. 2002-01-19 Werner Koch * server.c (gpgsm_server): Use assuan_deinit_server and setup assuan logging if enabled. * call-agent.c (inq_ciphertext_cb): Don't show the session key in an Assuan log file. * gpgsm.c (my_strusage): Take bugreport address from configure.ac 2002-01-15 Werner Koch * import.c (gpgsm_import): Just do a basic cert check before storing it. * certpath.c (gpgsm_basic_cert_check): New. * keydb.c (keydb_store_cert): New. * import.c (store_cert): Removed and change all caller to use the new function. * verify.c (store_cert): Ditto. * certlist.c (gpgsm_add_to_certlist): Validate the path * certpath.c (gpgsm_validate_path): Check the trust list. * call-agent.c (gpgsm_agent_istrusted): New. 2002-01-14 Werner Koch * call-dirmngr.c (inq_certificate): Changed for new interface semantic. * certlist.c (gpgsm_find_cert): New. 2002-01-13 Werner Koch * fingerprint.c (gpgsm_get_certid): Print the serial and not the hash after the dot. 2002-01-11 Werner Koch * call-dirmngr.c: New. * certpath.c (gpgsm_validate_path): Check the CRL here. * fingerprint.c (gpgsm_get_certid): New. * gpgsm.c: New options --dirmngr-program and --disable-crl-checks. 2002-01-10 Werner Koch * base64.c (gpgsm_create_writer): Allow to set the object name 2002-01-08 Werner Koch * keydb.c (spacep): Removed because it is now in util.c * server.c (cmd_genkey): New. * certreqgen.c: New. The parameter handling code has been taken from gnupg/g10/keygen.c version 1.0.6. * call-agent.c (gpgsm_agent_genkey): New. 2002-01-02 Werner Koch * server.c (rc_to_assuan_status): Removed and changed all callers to use map_to_assuan_status. 2001-12-20 Werner Koch * verify.c (gpgsm_verify): Implemented non-detached signature verification. Add OUT_FP arg, initialize a writer and changed all callers. * server.c (cmd_verify): Pass an out_fp if one has been set. * base64.c (base64_reader_cb): Try to detect an S/MIME body part. * certdump.c (print_sexp): Renamed to gpgsm_dump_serial, made global. (print_time): Renamed to gpgsm_dump_time, made global. (gpgsm_dump_serial): Take a real S-Expression as argument and print the first item. * keylist.c (list_cert_colon): Ditto. * keydb.c (keydb_search_issuer_sn): Ditto. * decrypt.c (print_integer_sexp): Removed and made callers use gpgsm_dump_serial. * verify.c (print_time): Removed, made callers use gpgsm_dump_time. 2001-12-19 Marcus Brinkmann * call-agent.c (start_agent): Add new argument to assuan_pipe_connect. 2001-12-18 Werner Koch * verify.c (print_integer_sexp): Renamed from print_integer and print the serial number according to the S-Exp rules. * decrypt.c (print_integer_sexp): Ditto. 2001-12-17 Werner Koch * keylist.c (list_cert_colon): Changed for new return value of get_serial. * keydb.c (keydb_search_issuer_sn): Ditto. * certcheck.c (gpgsm_check_cert_sig): Likewise for other S-Exp returingin functions. * fingerprint.c (gpgsm_get_keygrip): Ditto. * encrypt.c (encrypt_dek): Ditto * certcheck.c (gpgsm_check_cms_signature): Ditto * decrypt.c (prepare_decryption): Ditto. * call-agent.c (gpgsm_agent_pkdecrypt): Removed arg ciphertextlen, use KsbaSexp type and calculate the length. * certdump.c (print_sexp): Remaned from print_integer, changed caller. * Makefile.am: Use the LIBGCRYPT and LIBKSBA variables. * fingerprint.c (gpgsm_get_keygrip): Use the new gcry_pk_get_keygrip to calculate the grip - note the algorithm and therefore the grip values changed. 2001-12-15 Werner Koch * certcheck.c (gpgsm_check_cms_signature): Removed the faked-key kludge. (gpgsm_create_cms_signature): Removed the commented fake key code. This makes the function pretty simple. * gpgsm.c (main): Renamed the default key database to "keyring.kbx". * decrypt.c (gpgsm_decrypt): Write STATUS_DECRYPTION_*. * sign.c (gpgsm_sign): Write a STATUS_SIG_CREATED. 2001-12-14 Werner Koch * keylist.c (list_cert_colon): Kludge to show an email address encoded in the subject's DN. * verify.c (gpgsm_verify): Add hash debug helpers * sign.c (gpgsm_sign): Ditto. * base64.c (base64_reader_cb): Reset the linelen when we need to skip the line and adjusted test; I somehow forgot about DeMorgan. * server.c (cmd_encrypt,cmd_decrypt,cmd_sign,cmd_verify) (cmd_import): Close the FDs on success. (close_message_fd): New. (input_notify): Setting autodetect_encoding to 0 after initializing it to 0 is pretty pointless. Easy to fix. * gpgsm.c (main): New option --debug-wait n, so that it is possible to attach gdb when used in server mode. * sign.c (get_default_signer): Use keydb_classify_name here. 2001-12-14 Marcus Brinkmann * call-agent.c (LINELENGTH): Removed. (gpgsm_agent_pksign): Use ASSUAN_LINELENGTH, not LINELENGTH. (gpgsm_agent_pkdecrypt): Likewise. 2001-12-13 Werner Koch * keylist.c (list_cert_colon): Print alternative names of subject and a few other values. 2001-12-12 Werner Koch * gpgsm.c (main): New options --assume-{armor,base64,binary}. * base64.c (base64_reader_cb): Fixed non-autodetection mode. 2001-12-04 Werner Koch * call-agent.c (read_from_agent): Check for inquire responses. (request_reply): Handle them using a new callback arg, changed all callers. (gpgsm_agent_pkdecrypt): New. 2001-11-27 Werner Koch * base64.c: New. Changed all other functions to use this instead of direct creation of ksba_reader/writer. * gpgsm.c (main): Set ctrl.auto_encoding unless --no-armor is used. 2001-11-26 Werner Koch * gpgsm.c: New option --agent-program * call-agent.c (start_agent): Allow to override the default path to the agent. * keydb.c (keydb_add_resource): Create keybox * keylist.c (gpgsm_list_keys): Fixed non-server keylisting. * server.c (rc_to_assuan_status): New. Use it for all commands. Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. 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/sm/verify.c b/sm/verify.c index e7e9512f8..a2b07d884 100644 --- a/sm/verify.c +++ b/sm/verify.c @@ -1,660 +1,660 @@ /* verify.c - Verify a messages signature * Copyright (C) 2001, 2002, 2003, 2007, * 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include "gpgsm.h" #include #include #include "keydb.h" #include "i18n.h" static char * strtimestamp_r (ksba_isotime_t atime) { char *buffer = xmalloc (15); if (!atime || !*atime) strcpy (buffer, "none"); else sprintf (buffer, "%.4s-%.2s-%.2s", atime, atime+4, atime+6); return buffer; } /* Hash the data for a detached signature. Returns 0 on success. */ static gpg_error_t hash_data (int fd, gcry_md_hd_t md) { gpg_error_t err = 0; estream_t fp; char buffer[4096]; int nread; fp = es_fdopen_nc (fd, "rb"); if (!fp) { err = gpg_error_from_syserror (); log_error ("fdopen(%d) failed: %s\n", fd, gpg_strerror (err)); return err; } do { nread = es_fread (buffer, 1, DIM(buffer), fp); gcry_md_write (md, buffer, nread); } while (nread); if (es_ferror (fp)) { err = gpg_error_from_syserror (); log_error ("read error on fd %d: %s\n", fd, gpg_strerror (err)); } es_fclose (fp); return err; } /* Perform a verify operation. To verify detached signatures, DATA_FD must be different than -1. With OUT_FP given and a non-detached signature, the signed material is written to that stream. */ int gpgsm_verify (ctrl_t ctrl, int in_fd, int data_fd, estream_t out_fp) { int i, rc; Base64Context b64reader = NULL; Base64Context b64writer = NULL; ksba_reader_t reader; ksba_writer_t writer = NULL; ksba_cms_t cms = NULL; ksba_stop_reason_t stopreason; ksba_cert_t cert; KEYDB_HANDLE kh; gcry_md_hd_t data_md = NULL; int signer; const char *algoid; int algo; int is_detached; estream_t in_fp = NULL; char *p; audit_set_type (ctrl->audit, AUDIT_TYPE_VERIFY); kh = keydb_new (0); if (!kh) { log_error (_("failed to allocated keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } in_fp = es_fdopen_nc (in_fd, "rb"); if (!in_fp) { rc = gpg_error_from_syserror (); log_error ("fdopen() failed: %s\n", strerror (errno)); goto leave; } rc = gpgsm_create_reader (&b64reader, ctrl, in_fp, 0, &reader); if (rc) { log_error ("can't create reader: %s\n", gpg_strerror (rc)); goto leave; } if (out_fp) { rc = gpgsm_create_writer (&b64writer, ctrl, NULL, out_fp, &writer); if (rc) { log_error ("can't create writer: %s\n", gpg_strerror (rc)); goto leave; } } rc = ksba_cms_new (&cms); if (rc) goto leave; rc = ksba_cms_set_reader_writer (cms, reader, writer); if (rc) { log_error ("ksba_cms_set_reader_writer failed: %s\n", gpg_strerror (rc)); goto leave; } rc = gcry_md_open (&data_md, 0, 0); if (rc) { log_error ("md_open failed: %s\n", gpg_strerror (rc)); goto leave; } if (DBG_HASHING) gcry_md_start_debug (data_md, "vrfy.data"); audit_log (ctrl->audit, AUDIT_SETUP_READY); is_detached = 0; do { rc = ksba_cms_parse (cms, &stopreason); if (rc) { log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc)); goto leave; } if (stopreason == KSBA_SR_NEED_HASH) { is_detached = 1; audit_log (ctrl->audit, AUDIT_DETACHED_SIGNATURE); if (opt.verbose) log_info ("detached signature\n"); } if (stopreason == KSBA_SR_NEED_HASH || stopreason == KSBA_SR_BEGIN_DATA) { audit_log (ctrl->audit, AUDIT_GOT_DATA); /* We are now able to enable the hash algorithms */ for (i=0; (algoid=ksba_cms_get_digest_algo_list (cms, i)); i++) { algo = gcry_md_map_name (algoid); if (!algo) { log_error ("unknown hash algorithm `%s'\n", algoid? algoid:"?"); if (algoid && ( !strcmp (algoid, "1.2.840.113549.1.1.2") ||!strcmp (algoid, "1.2.840.113549.2.2"))) log_info (_("(this is the MD2 algorithm)\n")); audit_log_s (ctrl->audit, AUDIT_BAD_DATA_HASH_ALGO, algoid); } else { if (DBG_X509) log_debug ("enabling hash algorithm %d (%s)\n", algo, algoid? algoid:""); gcry_md_enable (data_md, algo); audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO, algo); } } if (opt.extra_digest_algo) { if (DBG_X509) log_debug ("enabling extra hash algorithm %d\n", opt.extra_digest_algo); gcry_md_enable (data_md, opt.extra_digest_algo); audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO, opt.extra_digest_algo); } if (is_detached) { if (data_fd == -1) { log_info ("detached signature w/o data " "- assuming certs-only\n"); audit_log (ctrl->audit, AUDIT_CERT_ONLY_SIG); } else audit_log_ok (ctrl->audit, AUDIT_DATA_HASHING, hash_data (data_fd, data_md)); } else { ksba_cms_set_hash_function (cms, HASH_FNC, data_md); } } else if (stopreason == KSBA_SR_END_DATA) { /* The data bas been hashed */ audit_log_ok (ctrl->audit, AUDIT_DATA_HASHING, 0); } } while (stopreason != KSBA_SR_READY); if (b64writer) { rc = gpgsm_finish_writer (b64writer); if (rc) { log_error ("write failed: %s\n", gpg_strerror (rc)); audit_log_ok (ctrl->audit, AUDIT_WRITE_ERROR, rc); goto leave; } } if (data_fd != -1 && !is_detached) { log_error ("data given for a non-detached signature\n"); rc = gpg_error (GPG_ERR_CONFLICT); audit_log (ctrl->audit, AUDIT_USAGE_ERROR); goto leave; } for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++) { /* Fixme: it might be better to check the validity of the certificate first before entering it into the DB. This way we would avoid cluttering the DB with invalid certificates. */ audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, keydb_store_cert (cert, 0, NULL)); ksba_cert_release (cert); } cert = NULL; for (signer=0; ; signer++) { char *issuer = NULL; ksba_sexp_t sigval = NULL; ksba_isotime_t sigtime, keyexptime; ksba_sexp_t serial; char *msgdigest = NULL; size_t msgdigestlen; char *ctattr; int sigval_hash_algo; int info_pkalgo; unsigned int verifyflags; rc = ksba_cms_get_issuer_serial (cms, signer, &issuer, &serial); if (!signer && gpg_err_code (rc) == GPG_ERR_NO_DATA && data_fd == -1 && is_detached) { log_info ("certs-only message accepted\n"); rc = 0; break; } if (rc) { if (signer && rc == -1) rc = 0; break; } gpgsm_status (ctrl, STATUS_NEWSIG, NULL); audit_log_i (ctrl->audit, AUDIT_NEW_SIG, signer); if (DBG_X509) { log_debug ("signer %d - issuer: `%s'\n", signer, issuer? issuer:"[NONE]"); log_debug ("signer %d - serial: ", signer); gpgsm_dump_serial (serial); log_printf ("\n"); } if (ctrl->audit) { char *tmpstr = gpgsm_format_sn_issuer (serial, issuer); audit_log_s (ctrl->audit, AUDIT_SIG_NAME, tmpstr); xfree (tmpstr); } rc = ksba_cms_get_signing_time (cms, signer, sigtime); if (gpg_err_code (rc) == GPG_ERR_NO_DATA) *sigtime = 0; else if (rc) { log_error ("error getting signing time: %s\n", gpg_strerror (rc)); *sigtime = 0; /* (we can't encode an error in the time string.) */ } rc = ksba_cms_get_message_digest (cms, signer, &msgdigest, &msgdigestlen); if (!rc) { size_t is_enabled; algoid = ksba_cms_get_digest_algo (cms, signer); algo = gcry_md_map_name (algoid); if (DBG_X509) log_debug ("signer %d - digest algo: %d\n", signer, algo); is_enabled = sizeof algo; if ( gcry_md_info (data_md, GCRYCTL_IS_ALGO_ENABLED, &algo, &is_enabled) || !is_enabled) { log_error ("digest algo %d (%s) has not been enabled\n", algo, algoid?algoid:""); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "unsupported"); goto next_signer; } } else if (gpg_err_code (rc) == GPG_ERR_NO_DATA) { assert (!msgdigest); rc = 0; algoid = NULL; algo = 0; } else /* real error */ { audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error"); break; } rc = ksba_cms_get_sigattr_oids (cms, signer, "1.2.840.113549.1.9.3", &ctattr); if (!rc) { const char *s; if (DBG_X509) log_debug ("signer %d - content-type attribute: %s", signer, ctattr); s = ksba_cms_get_content_oid (cms, 1); if (!s || strcmp (ctattr, s)) { log_error ("content-type attribute does not match " "actual content-type\n"); ksba_free (ctattr); ctattr = NULL; audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } ksba_free (ctattr); ctattr = NULL; } else if (rc != -1) { log_error ("error getting content-type attribute: %s\n", gpg_strerror (rc)); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } rc = 0; sigval = ksba_cms_get_sig_val (cms, signer); if (!sigval) { log_error ("no signature value available\n"); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } sigval_hash_algo = hash_algo_from_sigval (sigval); if (DBG_X509) { log_debug ("signer %d - signature available (sigval hash=%d)", signer, sigval_hash_algo); /* log_printhex ("sigval ", sigval, */ /* gcry_sexp_canon_len (sigval, 0, NULL, NULL)); */ } if (!sigval_hash_algo) sigval_hash_algo = algo; /* Fallback used e.g. with old libksba. */ /* Find the certificate of the signer */ keydb_search_reset (kh); rc = keydb_search_issuer_sn (kh, issuer, serial); if (rc) { if (rc == -1) { log_error ("certificate not found\n"); rc = gpg_error (GPG_ERR_NO_PUBKEY); } else log_error ("failed to find the certificate: %s\n", gpg_strerror(rc)); { char numbuf[50]; sprintf (numbuf, "%d", rc); gpgsm_status2 (ctrl, STATUS_ERROR, "verify.findkey", numbuf, NULL); } audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "no-cert"); goto next_signer; } rc = keydb_get_cert (kh, &cert); if (rc) { log_error ("failed to get cert: %s\n", gpg_strerror (rc)); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error"); goto next_signer; } log_info (_("Signature made ")); if (*sigtime) dump_isotime (sigtime); else log_printf (_("[date not given]")); log_printf (_(" using certificate ID 0x%08lX\n"), gpgsm_get_short_fingerprint (cert, NULL)); audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO, algo); if (msgdigest) { /* Signed attributes are available. */ gcry_md_hd_t md; unsigned char *s; /* Check that the message digest in the signed attributes matches the one we calculated on the data. */ s = gcry_md_read (data_md, algo); if ( !s || !msgdigestlen || gcry_md_get_algo_dlen (algo) != msgdigestlen || !s || memcmp (s, msgdigest, msgdigestlen) ) { char *fpr; log_error (_("invalid signature: message digest attribute " "does not match computed one\n")); if (DBG_X509) { if (msgdigest) log_printhex ("message: ", msgdigest, msgdigestlen); if (s) log_printhex ("computed: ", s, gcry_md_get_algo_dlen (algo)); } fpr = gpgsm_fpr_and_name_for_status (cert); gpgsm_status (ctrl, STATUS_BADSIG, fpr); xfree (fpr); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } audit_log_i (ctrl->audit, AUDIT_ATTR_HASH_ALGO, sigval_hash_algo); rc = gcry_md_open (&md, sigval_hash_algo, 0); if (rc) { log_error ("md_open failed: %s\n", gpg_strerror (rc)); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error"); goto next_signer; } if (DBG_HASHING) gcry_md_start_debug (md, "vrfy.attr"); ksba_cms_set_hash_function (cms, HASH_FNC, md); rc = ksba_cms_hash_signed_attrs (cms, signer); if (rc) { log_error ("hashing signed attrs failed: %s\n", gpg_strerror (rc)); gcry_md_close (md); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error"); goto next_signer; } rc = gpgsm_check_cms_signature (cert, sigval, md, sigval_hash_algo, &info_pkalgo); gcry_md_close (md); } else { rc = gpgsm_check_cms_signature (cert, sigval, data_md, algo, &info_pkalgo); } if (rc) { char *fpr; log_error ("invalid signature: %s\n", gpg_strerror (rc)); fpr = gpgsm_fpr_and_name_for_status (cert); gpgsm_status (ctrl, STATUS_BADSIG, fpr); xfree (fpr); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } rc = gpgsm_cert_use_verify_p (cert); /*(this displays an info message)*/ if (rc) { gpgsm_status_with_err_code (ctrl, STATUS_ERROR, "verify.keyusage", gpg_err_code (rc)); rc = 0; } if (DBG_X509) log_debug ("signature okay - checking certs\n"); audit_log (ctrl->audit, AUDIT_VALIDATE_CHAIN); rc = gpgsm_validate_chain (ctrl, cert, *sigtime? sigtime : "19700101T000000", keyexptime, 0, NULL, 0, &verifyflags); { char *fpr, *buf, *tstr; fpr = gpgsm_fpr_and_name_for_status (cert); if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED) { gpgsm_status (ctrl, STATUS_EXPKEYSIG, fpr); rc = 0; } else gpgsm_status (ctrl, STATUS_GOODSIG, fpr); xfree (fpr); fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); tstr = strtimestamp_r (sigtime); buf = xasprintf ("%s %s %s %s 0 0 %d %d 00", fpr, tstr, *sigtime? sigtime : "0", *keyexptime? keyexptime : "0", info_pkalgo, algo); xfree (tstr); xfree (fpr); gpgsm_status (ctrl, STATUS_VALIDSIG, buf); xfree (buf); } audit_log_ok (ctrl->audit, AUDIT_CHAIN_STATUS, rc); if (rc) /* of validate_chain */ { log_error ("invalid certification chain: %s\n", gpg_strerror (rc)); if (gpg_err_code (rc) == GPG_ERR_BAD_CERT_CHAIN || gpg_err_code (rc) == GPG_ERR_BAD_CERT || gpg_err_code (rc) == GPG_ERR_BAD_CA_CERT || gpg_err_code (rc) == GPG_ERR_CERT_REVOKED) gpgsm_status_with_err_code (ctrl, STATUS_TRUST_NEVER, NULL, gpg_err_code (rc)); else gpgsm_status_with_err_code (ctrl, STATUS_TRUST_UNDEFINED, NULL, gpg_err_code (rc)); audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad"); goto next_signer; } audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "good"); for (i=0; (p = ksba_cert_get_subject (cert, i)); i++) { log_info (!i? _("Good signature from") : _(" aka")); log_printf (" \""); - gpgsm_print_name (log_get_stream (), p); + gpgsm_es_print_name (log_get_stream (), p); log_printf ("\"\n"); ksba_free (p); } /* Print a note if this is a qualified signature. */ { size_t qualbuflen; char qualbuffer[1]; rc = ksba_cert_get_user_data (cert, "is_qualified", &qualbuffer, sizeof (qualbuffer), &qualbuflen); if (!rc && qualbuflen) { if (*qualbuffer) { log_info (_("This is a qualified signature\n")); if (!opt.qualsig_approval) log_info (_("Note, that this software is not officially approved " "to create or verify such signatures.\n")); } } else if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND) log_error ("get_user_data(is_qualified) failed: %s\n", gpg_strerror (rc)); } gpgsm_status (ctrl, STATUS_TRUST_FULLY, (verifyflags & VALIDATE_FLAG_CHAIN_MODEL)? "0 chain": "0 shell"); next_signer: rc = 0; xfree (issuer); xfree (serial); xfree (sigval); xfree (msgdigest); ksba_cert_release (cert); cert = NULL; } rc = 0; leave: ksba_cms_release (cms); gpgsm_destroy_reader (b64reader); gpgsm_destroy_writer (b64writer); keydb_release (kh); gcry_md_close (data_md); es_fclose (in_fp); if (rc) { char numbuf[50]; sprintf (numbuf, "%d", rc ); gpgsm_status2 (ctrl, STATUS_ERROR, "verify.leave", numbuf, NULL); } return rc; }