diff --git a/configure.ac b/configure.ac index 9b0f4fd..e36f56d 100644 --- a/configure.ac +++ b/configure.ac @@ -1,486 +1,480 @@ # configure.ac: Configure script for Scute. # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2015 g10 Code GmbH # # This file is part of Scute. # # Scute is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of # the License, or (at your option) any later version. # # Scute is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . # SPDX-License-Identifier: LGPL-2.1-or-later # Process this file with autoconf to produce a configure script. AC_PREREQ(2.61) min_automake_version="1.14" # To build a release you need to create a tag with the version number # (git tag -s scute-1.n.m) and run "./autogen.sh --force". Please # bump the version number immediately *after* the release and do # another commit and push so that the git magic is able to work. m4_define([mym4_package],[scute]) m4_define([mym4_major], [1]) m4_define([mym4_minor], [6]) m4_define([mym4_micro], [0]) # To start a new development series, i.e a new major or minor number # you need to mark an arbitrary commit before the first beta release # with an annotated tag. For example the 1.5 branch starts off with # the tag "scute-1.5-base". This is used as the base for counting # beta numbers before the first release of a series. # Below is m4 magic to extract and compute the git revision number, # the decimalized short revision number, a beta version string and a # flag indicating a development version (mym4_isbeta). Note that the # m4 processing is done by autoconf and not during the configure run. m4_define([mym4_verslist], m4_split(m4_esyscmd([./autogen.sh --find-version] \ mym4_package mym4_major mym4_minor mym4_micro),[:])) m4_define([mym4_isbeta], m4_argn(2, mym4_verslist)) m4_define([mym4_version], m4_argn(4, mym4_verslist)) m4_define([mym4_revision], m4_argn(7, mym4_verslist)) m4_define([mym4_revision_dec], m4_argn(8, mym4_verslist)) m4_esyscmd([echo ]mym4_version[>VERSION]) AC_INIT([mym4_package],[mym4_version], [https://bugs.gnupg.org]) # LT Version numbers, remember to change them just *before* a release. # (Code changed: REVISION++) # (Interfaces added/removed/changed: CURRENT++, REVISION=0) # (Interfaces added: AGE++) # (Interfaces removed/changed: AGE=0) # LIBSCUTE_LT_CURRENT=0 LIBSCUTE_LT_AGE=0 LIBSCUTE_LT_REVISION=3 # Version numbers reported by the PKCS #11 module to its users. VERSION_MAJOR=1 VERSION_MINOR=0 NEED_GPG_ERROR_VERSION=1.24 NEED_LIBASSUAN_VERSION=2.5.0 NEED_GPGSM_VERSION=2.2.0 # Some status variables to give feedback at the end of a configure run. have_gpg_error=no have_libassuan=no # # Provide information about the build. # BUILD_REVISION="mym4_revision" BUILD_REVISION_DEC="mym4_revision_dec" PACKAGE=$PACKAGE_NAME VERSION=$PACKAGE_VERSION AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_SRCDIR([src/cryptoki.h]) AC_CONFIG_HEADER([config.h]) AC_CONFIG_MACRO_DIR(m4) AM_INIT_AUTOMAKE AM_MAINTAINER_MODE AC_CANONICAL_HOST # Autobuilder support. AB_INIT # Enable GNU extensions on systems that have them. AC_GNU_SOURCE AH_VERBATIM([_REENTRANT], [/* To allow the use of scute in multithreaded programs we have to use special features from the library. */ #ifndef _REENTRANT # define _REENTRANT 1 #endif]) # Checks for programs. AC_PROG_CC # Note: A suitable gitlog-to-changelog script can be found in GnuPG master. AC_CHECK_PROGS(GITLOG_TO_CHANGELOG, gitlog-to-changelog, [gitlog-to-changelog]) # # Setup gcc specific options # AC_MSG_NOTICE([checking for cc features]) if test "$GCC" = yes; then mycflags= mycflags_save=$CFLAGS # Check whether gcc does not emit a diagnositc for unknow -Wno-* # options. This is the case for gcc >= 4.6 AC_MSG_CHECKING([if gcc ignores unknown -Wno-* options]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6 ) #kickerror #endif]],[])],[_gcc_silent_wno=yes],[_gcc_silent_wno=no]) AC_MSG_RESULT($_gcc_silent_wno) # Note that it is okay to use CFLAGS here because these are just # warning options and the user should have a chance of overriding # them. if test "$USE_MAINTAINER_MODE" = "yes"; then mycflags="$mycflags -O3 -Wall -Wcast-align -Wshadow -Wstrict-prototypes" mycflags="$mycflags -Wformat -Wno-format-y2k -Wformat-security" if test x"$_gcc_silent_wno" = xyes ; then _gcc_wopt=yes else AC_MSG_CHECKING([if gcc supports -Wno-missing-field-initializers]) CFLAGS="-Wno-missing-field-initializers" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [_gcc_wopt=yes],[_gcc_wopt=no]) AC_MSG_RESULT($_gcc_wopt) fi if test x"$_gcc_wopt" = xyes ; then mycflags="$mycflags -W -Wno-sign-compare" mycflags="$mycflags -Wno-missing-field-initializers" fi AC_MSG_CHECKING([if gcc supports -Wdeclaration-after-statement]) CFLAGS="-Wdeclaration-after-statement" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],_gcc_wopt=yes,_gcc_wopt=no) AC_MSG_RESULT($_gcc_wopt) if test x"$_gcc_wopt" = xyes ; then mycflags="$mycflags -Wdeclaration-after-statement" fi else mycflags="$mycflags -Wall" fi if test x"$_gcc_silent_wno" = xyes ; then _gcc_psign=yes else AC_MSG_CHECKING([if gcc supports -Wno-pointer-sign]) CFLAGS="-Wno-pointer-sign" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [_gcc_psign=yes],[_gcc_psign=no]) AC_MSG_RESULT($_gcc_psign) fi if test x"$_gcc_psign" = xyes ; then mycflags="$mycflags -Wno-pointer-sign" fi AC_MSG_CHECKING([if gcc supports -Wpointer-arith]) CFLAGS="-Wpointer-arith" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],_gcc_psign=yes,_gcc_psign=no) AC_MSG_RESULT($_gcc_psign) if test x"$_gcc_psign" = xyes ; then mycflags="$mycflags -Wpointer-arith" fi CFLAGS="$mycflags $mycflags_save" fi 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]) AC_SUBST(LIBSCUTE_LT_CURRENT) AC_SUBST(LIBSCUTE_LT_AGE) AC_SUBST(LIBSCUTE_LT_REVISION) AC_DEFINE_UNQUOTED(NEED_GPGSM_VERSION, "$NEED_GPGSM_VERSION", [Min. needed GPGSM version.]) AC_SUBST(PACKAGE) AC_SUBST(VERSION) AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package]) AC_DEFINE_UNQUOTED(VERSION_MAJOR, $VERSION_MAJOR, [Major version number]) AC_DEFINE_UNQUOTED(VERSION_MINOR, $VERSION_MINOR, [Minor version number]) # Don't default to build static libs. # FIXME: Caution: Evil hack ahead. Libtool does not support linking a # static library to a shared library. But for libassuan, we need this. # Instead adding a lot of junk to Makefile.am to get this, we just override # all safety checks here. We are driving without seat belts now! # http://lists.cairographics.org/archives/cairo/2009-April/016962.html lt_cv_deplibs_check_method=pass_all LT_PREREQ([2.2.6]) LT_INIT([win32-dll disable-static]) LT_LANG([Windows Resource]) # For now we hardcode the use of version scripts. It would be better # to write a test for this or even implement this within libtool. have_ld_version_script=no case "${host}" in *-*-linux*) have_ld_version_script=yes ;; *-*-gnu*) have_ld_version_script=yes ;; *-apple-darwin*) AC_DEFINE(_DARWIN_C_SOURCE, 900000L, Expose all libc features (__DARWIN_C_FULL).) AC_DEFINE(_XOPEN_SOURCE, 500, Activate POSIX interface on MacOS X) ;; esac AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes") GPGSM_DEFAULT=no GPG_CONNECT_AGENT_DEFAULT=no have_w32_system=no case "${host}" in *-mingw32*) # special stuff for Windoze NT GPGSM_DEFAULT='c:\\gnupg\\gpgsm.exe' GPG_CONNECT_AGENT_DEFAULT='c:\\gnupg\\gpg-connect-agent.exe' have_w32_system=yes ;; *) ;; esac if test "$have_w32_system" = yes; then AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system]) fi AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes) # Generate values for the DLL version info if test "$have_w32_system" = yes; then BUILD_TIMESTAMP=`date --iso-8601=minutes` changequote(,)dnl BUILD_FILEVERSION=`echo "$VERSION" | sed 's/\([0-9.]*\).*/\1./;s/\./,/g'` changequote([,])dnl BUILD_FILEVERSION="${BUILD_FILEVERSION}${BUILD_REVISION_DEC}" fi AC_SUBST(BUILD_REVISION) AC_SUBST(BUILD_REVISION_DEC) AC_SUBST(BUILD_TIMESTAMP) AC_SUBST(BUILD_FILEVERSION) -# Checks for libraries. - -AC_CHECK_FUNCS([ttyname localtime_r timegm stpcpy]) - -# Run the checks needed for estream-printf.c -estream_PRINTF_INIT - # The error code library. Error codes are sent over the IPC layer and # have to be interpreted. AM_PATH_GPG_ERROR("$NEED_GPG_ERROR_VERSION", have_gpg_error=yes, have_gpg_error=no) # The IPC library. AM_PATH_LIBASSUAN("$NEED_LIBASSUAN_VERSION", have_libassuan=yes, have_libassuan=no) # GPGSM NO_OVERRIDE=no AC_ARG_WITH(gpgsm, AC_HELP_STRING([--with-gpgsm=PATH], [use GpgSM binary at PATH]), GPGSM=$withval, NO_OVERRIDE=yes) if test "$NO_OVERRIDE" = "yes" || test "$GPGSM" = "yes"; then GPGSM= NO_OVERRIDE=yes if test "$cross_compiling" != "yes"; then AC_PATH_PROG(GPGSM, gpgsm) fi if test -z "$GPGSM"; then GPGSM="$GPGSM_DEFAULT" fi fi if test "$GPGSM" = no; then if test "$NO_OVERRIDE" = "yes"; then if test "$cross_compiling" != "yes"; then AC_MSG_ERROR([ *** *** Could not find GpgSM, install GpgSM or use --with-gpgsm=PATH to enable it ***]) else AC_MSG_ERROR([ *** *** Can not determine path to GpgSM when cross-compiling, use --with-gpgsm=PATH ***]) fi fi else AC_DEFINE_UNQUOTED(GPGSM_PATH, "$GPGSM", [Path to the GPGSM binary.]) AC_DEFINE(ENABLE_GPGSM,1,[Whether GPGSM support is enabled]) fi AM_CONDITIONAL(HAVE_GPGSM, test "$GPGSM" != "no") dnl Check for GPGSM version requirement. GPGSM_VERSION=unknown ok=maybe if test -z "$GPGSM" -o "x$GPGSM" = "xno"; then ok=no else if test "$cross_compiling" = "yes"; then AC_MSG_WARN([GPGSM version can not be checked when cross compiling]) ok=no else if test ! -x "$GPGSM"; then AC_MSG_WARN([GPGSM not executable, version check disabled]) ok=no fi fi fi if test "$ok" = "maybe"; then AC_MSG_CHECKING(for GPGSM >= $NEED_GPGSM_VERSION) req_major=`echo $NEED_GPGSM_VERSION | \ sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\1/'` req_minor=`echo $NEED_GPGSM_VERSION | \ sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\2/'` req_micro=`echo $NEED_GPGSM_VERSION | \ sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\3/'` gpgsm_version=`$GPGSM --version | grep ^gpgsm` major=`echo $gpgsm_version | \ sed 's/^gpgsm (GnuPG) \([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\1/'` minor=`echo $gpgsm_version | \ sed 's/^gpgsm (GnuPG) \([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\2/'` micro=`echo $gpgsm_version | \ sed 's/^gpgsm (GnuPG) \([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\3/'` GPGSM_VERSION=`echo $gpgsm_version | sed 's/^gpgsm (GnuPG) //'` if test "$major" -gt "$req_major"; then ok=yes else if test "$major" -eq "$req_major"; then if test "$minor" -gt "$req_minor"; then ok=yes else if test "$minor" -eq "$req_minor"; then if test "$micro" -ge "$req_micro"; then ok=yes fi fi fi fi fi if test "$ok" = "yes"; then AC_MSG_RESULT(yes) else AC_MSG_RESULT(no) AC_MSG_WARN([GPGSM must be at least version $NEED_GPGSM_VERSION]) fi fi gpgsm_ok="$ok" # GPG_CONNECT_AGENT NO_OVERRIDE=no AC_ARG_WITH(gpg-connect-agent, AC_HELP_STRING([--with-gpg-connect-agent=PATH], [use gpg-connect-agent binary at PATH]), GPG_CONNECT_AGENT=$withval, NO_OVERRIDE=yes) if test "$NO_OVERRIDE" = "yes" || test "$GPG_CONNECT_AGENT" = "yes"; then GPG_CONNECT_AGENT= NO_OVERRIDE=yes if test "$cross_compiling" != "yes"; then AC_CHECK_PROG(GPG_CONNECT_AGENT, gpg-connect-agent, gpg-connect-agent) fi if test -z "$GPG_CONNECT_AGENT"; then GPG_CONNECT_AGENT="$GPG_CONNECT_AGENT_DEFAULT" fi fi if test "$GPG_CONNECT_AGENT" = no; then if test "$NO_OVERRIDE" = "yes"; then if test "$cross_compiling" != "yes"; then AC_MSG_ERROR([ *** *** Could not find gpg-connect-agent, use --with-gpg-connect-agent=PATH to enable it ***]) else AC_MSG_ERROR([ *** *** Can not determine path to gpg-connect-agent when cross-compiling, use --with-gpg-connect-agent=PATH ***]) fi fi else AC_DEFINE_UNQUOTED(GPG_CONNECT_AGENT_PATH, "$GPG_CONNECT_AGENT", [Path to the GPG_CONNECT_AGENT binary.]) fi # Checks for header files. AC_HEADER_STDC AC_CHECK_HEADERS([stdlib.h string.h]) # Checks for typedefs, structures, and compiler characteristics. AC_HEADER_STDBOOL AC_C_INLINE # Checks for library functions. +AC_CHECK_FUNCS([ttyname localtime_r timegm stpcpy]) # Check for programs needed for the manual. AC_CHECK_PROG(CONVERT, convert, convert) AC_CHECK_PROG(EPSTOPDF, epstopdf, epstopdf) # Test if tests can be run ok=yes AM_CONDITIONAL(RUN_TESTS, test "$ok" = "yes") AH_BOTTOM([ /* Prefix all estream functions. */ #define _ESTREAM_EXT_SYM_PREFIX _scute_ ]) # 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/pub/gcrypt/libgpg-error *** (at least version $NEED_GPG_ERROR_VERSION 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/pub/gcrypt/alpha/libassuan/ *** (at least version $NEED_LIBASSUAN_VERSION is required). ***]]) 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([Makefile m4/Makefile src/Makefile tests/Makefile doc/manual/Makefile doc/Makefile src/versioninfo.rc]) AC_OUTPUT echo " Scute v${VERSION} has been configured as follows: Revision: mym4_revision (mym4_revision_dec) Platform: $host GpgSM: ${GPGSM} Gpg-connect-agent: ${GPG_CONNECT_AGENT} " diff --git a/m4/Makefile.am b/m4/Makefile.am index bff7b15..cbcd9a8 100644 --- a/m4/Makefile.am +++ b/m4/Makefile.am @@ -1,2 +1,2 @@ -EXTRA_DIST = estream.m4 autobuild.m4 gpg-error.m4 libassuan.m4 libtool.m4 \ +EXTRA_DIST = autobuild.m4 gpg-error.m4 libassuan.m4 libtool.m4 \ ltoptions.m4 ltsugar.m4 ltversion.m4 lt~obsolete.m4 diff --git a/m4/estream.m4 b/m4/estream.m4 deleted file mode 100644 index 4b6c745..0000000 --- a/m4/estream.m4 +++ /dev/null @@ -1,48 +0,0 @@ -dnl Autoconf macros for libestream -dnl Copyright (C) 2007 g10 Code GmbH -dnl -dnl This file is free software; as a special exception the author gives -dnl unlimited permission to copy and/or distribute it, with or without -dnl modifications, as long as this notice is preserved. -dnl -dnl This file is distributed in the hope that it will be useful, but -dnl WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -dnl implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - -dnl estream_PRINTF_INIT -dnl Prepare build of source included estream-printf.c -dnl -AC_DEFUN([estream_PRINTF_INIT], -[ - AC_MSG_NOTICE([checking system features for estream-printf]) - AC_TYPE_LONG_LONG_INT - AC_TYPE_LONG_DOUBLE - AC_TYPE_INTMAX_T - AC_TYPE_UINTMAX_T - AC_CHECK_TYPES([ptrdiff_t]) - AC_CHECK_SIZEOF([unsigned long]) - AC_CHECK_SIZEOF([void *]) - AC_CACHE_CHECK([for nl_langinfo and THOUSANDS_SEP], - estream_cv_langinfo_thousands_sep, - [AC_TRY_LINK([#include ], - [char* cs = nl_langinfo(THOUSANDS_SEP); return !cs;], - estream_cv_langinfo_thousands_sep=yes, - estream_cv_langinfo_thousands_sep=no) - ]) - if test $estream_cv_langinfo_thousands_sep = yes; then - AC_DEFINE(HAVE_LANGINFO_THOUSANDS_SEP, 1, - [Define if you have and nl_langinfo(THOUSANDS_SEP).]) - fi -]) - - -dnl estream_INIT -dnl Prepare build of source included estream.c -dnl -AC_DEFUN([estream_INIT], -[ - AC_REQUIRE([estream_PRINTF_INIT]) - AC_MSG_NOTICE([checking system features for estream]) - -]) diff --git a/src/agent.c b/src/agent.c index df9cdc1..6228af9 100644 --- a/src/agent.c +++ b/src/agent.c @@ -1,1217 +1,1218 @@ /* agent.c - Talking to gpg-agent. * Copyright (C) 2006, 2007, 2008, 2015 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM -#define PATHSEP_C ';' -#define WINVER 0x0500 /* Required for AllowSetForegroundWindow. */ -#include +# define PATHSEP_C ';' +# define WINVER 0x0500 /* Required for AllowSetForegroundWindow. */ +# include +# include #else -#define PATHSEP_C ':' +# define PATHSEP_C ':' #endif #include #include #include "debug.h" #include "support.h" #include "sexp-parse.h" #include "cert.h" #include "agent.h" /* The global agent context. */ static assuan_context_t agent_ctx = NULL; /* The version number of the agent. */ static int agent_version_major; static int agent_version_minor; /* Hack required for Windows. */ void gnupg_allow_set_foregound_window (pid_t pid) { if (!pid || pid == (pid_t)(-1)) return; #ifdef HAVE_W32_SYSTEM else if (!AllowSetForegroundWindow (pid)) - DEBUG (DBG_CRIT, "AllowSetForegroundWindow(%lu) failed: %i\n", - (unsigned long)pid, GetLastError ()); + DEBUG (DBG_CRIT, "AllowSetForegroundWindow(%lu) failed: %u\n", + (unsigned long)pid, (unsigned int)GetLastError ()); #endif } /* Establish a connection to a running GPG agent. */ static gpg_error_t agent_connect (assuan_context_t *ctx_r) { gpg_error_t err = 0; assuan_context_t ctx = NULL; char buffer[255]; FILE *p; /* Use gpg-connect-agent to obtain the socket name * directly from the agent itself. */ snprintf (buffer, sizeof buffer, "%s 'GETINFO socket_name' /bye", get_gpg_connect_agent_path ()); #ifdef HAVE_W32_SYSTEM p = _popen (buffer, "r"); #else p = popen (buffer, "r"); #endif if (p) { int ret; ret = fscanf (p, "D %254s\nOK\n", buffer); if (ret == EOF) /* I/O error? */ err = gpg_error_from_errno (errno); else if (ret != 1) /* Unexpected reply */ err = gpg_error (GPG_ERR_NO_AGENT); pclose (p); } else err = gpg_error_from_errno (errno); /* Then connect to the socket we got. */ if (!err) { err = assuan_new (&ctx); if (!err) { err = assuan_socket_connect (ctx, buffer, 0, 0); if (!err) { *ctx_r = ctx; if (_scute_debug_flags & DBG_ASSUAN) assuan_set_log_stream (*ctx_r, _scute_debug_stream); } else assuan_release (ctx); } } /* We do not try any harder. If gpg-connect-agent somehow failed * to give us a suitable socket, we probably cannot do better. */ if (err) DEBUG (DBG_CRIT, "cannot connect to GPG agent: %s", gpg_strerror (err)); return err; } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { (void)opaque; if (!strncmp (line, "PINENTRY_LAUNCHED", 17) && (line[17]==' '||!line[17])) { gnupg_allow_set_foregound_window ((pid_t)strtoul (line+17, NULL, 10)); /* We do not pass errors to avoid breaking other code. */ } else DEBUG (DBG_CRIT, "ignoring gpg-agent inquiry `%s'\n", line); return 0; } /* Send a simple command to the agent. */ static gpg_error_t agent_simple_cmd (assuan_context_t ctx, const char *fmt, ...) { gpg_error_t err; char *optstr; va_list arg; int res; va_start (arg, fmt); res = vasprintf (&optstr, fmt, arg); va_end (arg); if (res < 0) return gpg_error_from_errno (errno); err = assuan_transact (ctx, optstr, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err) DEBUG (DBG_CRIT, "gpg-agent command '%s' failed: %s", optstr, gpg_strerror (err)); free (optstr); return err; } /* Read and stroe the agent's version number. */ static gpg_error_t read_version_cb (void *opaque, const void *buffer, size_t length) { char version[20]; const char *s; (void) opaque; if (length > sizeof (version) -1) length = sizeof (version) - 1; strncpy (version, buffer, length); version[length] = 0; agent_version_major = atoi (version); s = strchr (version, '.'); agent_version_minor = s? atoi (s+1) : 0; return 0; } /* Configure the GPG agent at connection CTX. */ static gpg_error_t agent_configure (assuan_context_t ctx) { gpg_error_t err = 0; char *dft_display = NULL; char *dft_ttyname = NULL; char *dft_ttytype = NULL; #if defined(HAVE_SETLOCALE) && (defined(LC_CTYPE) || defined(LC_MESSAGES)) char *old_lc = NULL; char *dft_lc = NULL; #endif char *dft_xauthority = NULL; char *dft_pinentry_user_data = NULL; err = agent_simple_cmd (ctx, "RESET"); if (err) return err; /* Set up display, terminal and locale options. */ dft_display = getenv ("DISPLAY"); if (dft_display) err = agent_simple_cmd (ctx, "OPTION display=%s", dft_display); if (err) return err; dft_ttyname = getenv ("GPG_TTY"); if ((!dft_ttyname || !*dft_ttyname) && ttyname (0)) dft_ttyname = ttyname (0); if (dft_ttyname) { err = agent_simple_cmd (ctx, "OPTION ttyname=%s", dft_ttyname); if (err) return err; } dft_ttytype = getenv ("TERM"); if (dft_ttytype) err = agent_simple_cmd (ctx, "OPTION ttytype=%s", dft_ttytype); if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) old_lc = setlocale (LC_CTYPE, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) return gpg_error_from_errno (errno); } dft_lc = setlocale (LC_CTYPE, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-ctype=%s", dft_lc); if (old_lc) { setlocale (LC_CTYPE, old_lc); free (old_lc); } #endif if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) old_lc = setlocale (LC_MESSAGES, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) err = gpg_error_from_errno (errno); } dft_lc = setlocale (LC_MESSAGES, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-messages=%s", dft_lc); if (old_lc) { setlocale (LC_MESSAGES, old_lc); free (old_lc); } #endif dft_xauthority = getenv ("XAUTHORITY"); if (dft_xauthority) err = agent_simple_cmd (ctx, "OPTION xauthority=%s", dft_xauthority); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; else if (err) return err; dft_pinentry_user_data = getenv ("PINENTRY_USER_DATA"); if (dft_pinentry_user_data) err = agent_simple_cmd (ctx, "OPTION pinentry_user_data=%s", dft_pinentry_user_data); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; err = agent_simple_cmd (ctx, "OPTION allow-pinentry-notify"); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; err = assuan_transact (ctx, "GETINFO version", read_version_cb, NULL, NULL, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; else if (err) return err; return err; } /* Try to connect to the agent via socket. Handle the server's initial greeting. */ gpg_error_t scute_agent_initialize (void) { gpg_error_t err = 0; if (agent_ctx) { DEBUG (DBG_CRIT, "GPG Agent connection already established"); return 0; } DEBUG (DBG_INFO, "Establishing connection to gpg-agent"); err = agent_connect (&agent_ctx); if (err) return err; err = agent_configure (agent_ctx); if (err) scute_agent_finalize (); return err; } int scute_agent_get_agent_version (int *minor) { *minor = agent_version_minor; return agent_version_major; } /* Return a new malloced string by unescaping the string S. Escaping is percent escaping and '+'/space mapping. A binary nul will silently be replaced by a 0xFF. Function returns NULL to indicate an out of memory status. */ static char * unescape_status_string (const unsigned char *src) { char *buffer; char *dst; buffer = malloc (strlen (src) + 1); if (!buffer) return NULL; dst = buffer; while (*src) { if (*src == '%' && src[1] && src[2]) { src++; *dst = xtoi_2 (src); if (*dst == '\0') *dst = '\xff'; dst++; src += 2; } else if (*src == '+') { *(dst++) = ' '; src++; } else *(dst++) = *(src++); } *dst = 0; return buffer; } /* Take a 20 byte hexencoded string and put it into the provided 20 byte buffer FPR in binary format. Returns true if successful, and false otherwise. */ static int unhexify_fpr (const char *hexstr, unsigned char *fpr) { const char *src; int cnt; /* Check for invalid or wrong length. */ for (src = hexstr, cnt = 0; hexdigitp (src); src++, cnt++) ; if ((*src && !spacep (src)) || (cnt != 40)) return 0; for (src = hexstr, cnt = 0; *src && !spacep (src); src += 2, cnt++) fpr[cnt] = xtoi_2 (src); return 1; } /* Return true if HEXSTR is a valid keygrip. */ static unsigned int hexgrip_valid_p (const char *hexstr) { const char *s; int n; for (s=hexstr, n=0; hexdigitp (s); s++, n++) ; if ((*s && *s != ' ') || n != 40) return 0; /* Bad keygrip */ else return 1; /* Valid. */ } /* Take the serial number from LINE and return it verbatim in a newly allocated string. We make sure that only hex characters are returned. */ static char * store_serialno (const char *line) { const char *src; char *ptr; for (src = line; hexdigitp (src); src++) ; ptr = malloc (src + 1 - line); if (ptr) { memcpy (ptr, line, src - line); ptr[src - line] = 0; } return ptr; } /* Release the card info structure INFO. */ void scute_agent_release_card_info (struct agent_card_info_s *info) { if (!info) return; free (info->serialno); free (info->dispserialno); free (info->cardtype); free (info->disp_name); free (info->disp_lang); free (info->pubkey_url); free (info->login_data); while (info->kinfo) { key_info_t ki = info->kinfo->next; free (info->kinfo); info->kinfo = ki; } memset (info, 0, sizeof (*info)); } /* Return the key info object for the key KEYREF. If it is not found * NULL is returned. */ key_info_t scute_find_kinfo (agent_card_info_t info, const char *keyref) { key_info_t kinfo; for (kinfo = info->kinfo; kinfo; kinfo = kinfo->next) if (!strcmp (kinfo->keyref, keyref)) return kinfo; return NULL; } /* Create a new key info object with KEYREF. All fields but the * keyref are zeroed out. The created object is appended to the list * at INFO. */ static key_info_t create_kinfo (agent_card_info_t info, const char *keyref) { key_info_t kinfo, ki; kinfo = calloc (1, sizeof *kinfo + strlen (keyref)); if (!kinfo) return NULL; strcpy (kinfo->keyref, keyref); if (!info->kinfo) info->kinfo = kinfo; else { for (ki=info->kinfo; ki->next; ki = ki->next) ; ki->next = kinfo; } return kinfo; } /* FIXME: We are not returning out of memory errors. */ static gpg_error_t learn_status_cb (void *opaque, const char *line) { agent_card_info_t parm = opaque; const char *keyword = line; int keywordlen; key_info_t kinfo; const char *keyref; int i; for (keywordlen = 0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen)) { free (parm->serialno); parm->serialno = store_serialno (line); } else if (keywordlen == 13 && !memcmp (keyword, "$DISPSERIALNO", keywordlen)) { free (parm->dispserialno); parm->dispserialno = unescape_status_string (line); } else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen)) { parm->is_piv = !strcmp (line, "PIV"); } else if (keywordlen == 8 && !memcmp (keyword, "CARDTYPE", keywordlen)) { free (parm->cardtype); parm->cardtype = unescape_status_string (line); } else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen)) { if (parm->disp_name) free (parm->disp_name); parm->disp_name = unescape_status_string (line); } else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen)) { if (parm->disp_lang) free (parm->disp_lang); parm->disp_lang = unescape_status_string (line); } else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen)) { parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0; } else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen)) { if (parm->pubkey_url) free (parm->pubkey_url); parm->pubkey_url = unescape_status_string (line); } else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen)) { if (parm->login_data) free (parm->login_data); parm->login_data = unescape_status_string (line); } else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen)) { parm->sig_counter = strtoul (line, NULL, 0); } else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen)) { char *p, *buf; buf = p = unescape_status_string (line); if (buf) { while (spacep (p)) p++; parm->chv1_cached = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; for (i = 0; *p && i < 3; i++) { parm->chvmaxlen[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } for (i=0; *p && i < 3; i++) { parm->chvretry[i] = atoi (p); while (*p && !spacep (p)) p++; while (spacep (p)) p++; } free (buf); } } else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->fpr1valid = unhexify_fpr (line, parm->fpr1); else if (no == 2) parm->fpr2valid = unhexify_fpr (line, parm->fpr2); else if (no == 3) parm->fpr3valid = unhexify_fpr (line, parm->fpr3); } else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen)) { int no = atoi (line); while (*line && !spacep (line)) line++; while (spacep (line)) line++; if (no == 1) parm->cafpr1valid = unhexify_fpr (line, parm->cafpr1); else if (no == 2) parm->cafpr2valid = unhexify_fpr (line, parm->cafpr2); else if (no == 3) parm->cafpr3valid = unhexify_fpr (line, parm->cafpr3); } else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen)) { /* The format of such a line is: * KEYPARINFO */ const char *hexgrip = line; while (*line && !spacep (line)) line++; while (spacep (line)) line++; keyref = line; if (hexgrip_valid_p (hexgrip)) { /* Check whether we already have an item for the keyref. */ kinfo = scute_find_kinfo (parm, keyref); if (!kinfo) /* New entry. */ { kinfo = create_kinfo (parm, keyref); if (!kinfo) goto no_core; } else /* Existing entry - clear the grip. */ *kinfo->grip = 0; strncpy (kinfo->grip, hexgrip, sizeof kinfo->grip); kinfo->grip[sizeof kinfo->grip -1] = 0; } } else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen)) { char *p, *p2, *buf; int abool; buf = p = unescape_status_string (line); if (buf) { for (p = strtok (buf, " "); p; p = strtok (NULL, " ")) { p2 = strchr (p, '='); if (p2) { *p2++ = 0; abool = (*p2 == '1'); if (!strcmp (p, "gc")) parm->rng_available = abool; /* We're currently not interested in the * other capabilities. */ } } free (buf); } } return 0; no_core: return gpg_error_from_syserror (); } /* Call the agent to learn about a smartcard. */ gpg_error_t scute_agent_learn (struct agent_card_info_s *info) { gpg_error_t err; memset (info, 0, sizeof (*info)); err = assuan_transact (agent_ctx, "LEARN --sendinfo", NULL, NULL, default_inq_cb, NULL, learn_status_cb, info); if (gpg_err_source(err) == GPG_ERR_SOURCE_SCD && gpg_err_code (err) == GPG_ERR_CARD_REMOVED) { /* SCD session is in card removed state. clear that state. */ err = assuan_transact (agent_ctx, "SCD SERIALNO", NULL, NULL, NULL, NULL, NULL, NULL); if (!err) { memset (info, 0, sizeof (*info)); err = assuan_transact (agent_ctx, "LEARN --sendinfo", NULL, NULL, default_inq_cb, NULL, learn_status_cb, info); } } if (!err) { /* Also try to get the human readabale serial number. */ err = assuan_transact (agent_ctx, "SCD GETATTR $DISPSERIALNO", NULL, NULL, default_inq_cb, NULL, learn_status_cb, info); if (gpg_err_code (err) == GPG_ERR_INV_NAME || gpg_err_code (err) == GPG_ERR_UNSUPPORTED_OPERATION) err = 0; /* Not implemented or GETATTR not supported. */ } return err; } static gpg_error_t geteventcounter_status_cb (void *opaque, const char *line) { int *result = opaque; const char *keyword = line; int keywordlen; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 12 && !memcmp (keyword, "EVENTCOUNTER", keywordlen)) { static int any_count; static unsigned int last_count; unsigned int count; if (sscanf (line, "%*u %*u %u ", &count) == 1) { if (any_count && last_count != count) *result = 1; any_count = 1; last_count = count; } } return 0; } static gpg_error_t read_status_cb (void *opaque, const void *buffer, size_t length) { char *flag = opaque; if (length == 0) *flag = 'r'; else *flag = *((char *) buffer); return 0; } /* Check the agent status. This returns 0 if a token is present, GPG_ERR_CARD_REMOVED if no token is present, and an error code otherwise. */ gpg_error_t scute_agent_check_status (void) { static char last_flag; gpg_error_t err; int any = 0; char flag = '-'; /* First we look at the eventcounter to see if anything happened at all. This is a low overhead function which won't even clutter a gpg-agent log file. There is no need for error checking here. */ if (last_flag) assuan_transact (agent_ctx, "GETEVENTCOUNTER", NULL, NULL, NULL, NULL, geteventcounter_status_cb, &any); if (any || !last_flag) { err = assuan_transact (agent_ctx, "SCD GETINFO status", read_status_cb, &flag, default_inq_cb, NULL, NULL, NULL); if (err) return err; last_flag = flag; } else flag = last_flag; if (flag == 'r') return gpg_error (GPG_ERR_CARD_REMOVED); return 0; } /* We only support RSA signatures up to 4096 bits. */ #define MAX_SIGNATURE_BITS 4096 /* Enough space to hold a 4096 bit RSA signature in an S-expression. */ #define MAX_SIGNATURE_LEN 640 /* FIXME: magic value */ struct signature { unsigned char data[MAX_SIGNATURE_LEN]; int len; }; static gpg_error_t pksign_cb (void *opaque, const void *buffer, size_t length) { struct signature *sig = opaque; if (sig->len + length > MAX_SIGNATURE_LEN) { DEBUG (DBG_INFO, "maximum signature length exceeded"); return gpg_error (GPG_ERR_BAD_DATA); } memcpy (&sig->data[sig->len], buffer, length); sig->len += length; return 0; } /* Parse the result of an pksign operation which is a s-expression in canonical form that looks like (7:sig-val(3:rsa(1:s:))). The raw result is stored in RESULT of size *LEN, and *LEN is adjusted to the actual size. */ static gpg_error_t pksign_parse_result (const struct signature *sig, unsigned char *result, unsigned int *len) { gpg_error_t err; const unsigned char *s = sig->data; size_t n; int depth; if (*s++ != '(') gpg_error (GPG_ERR_INV_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "sig-val")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "rsa")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "s")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); /* Remove a possible prepended zero byte. */ if (!*s && n > 1) { n -= 1; s += 1; } if (*len < (unsigned int) n) return gpg_error (GPG_ERR_INV_LENGTH); *len = (unsigned int) n; memcpy (result, s, n); s += n; depth = 3; err = sskip (&s, &depth); if (err) return err; if (s - sig->data != sig->len || depth != 0) return gpg_error (GPG_ERR_INV_SEXP); return 0; } /* Decodes the hash DATA of size LEN (if necessary). Returns a pointer to the raw hash data in R_DATA, the size in R_LEN, and the name of the hash function in R_HASH. Prior to TLSv1.2, the hash function was the concatenation of MD5 and SHA1 applied to the data respectively, and no encoding was applied. From TLSv1.2 on, the hash value is prefixed with an hash identifier and encoded using ASN1. FIXME: Reference. */ static gpg_error_t decode_hash (const unsigned char *data, int len, const unsigned char **r_data, size_t *r_len, const char **r_hash) { static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */ { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C }; static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */ { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 }; static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */ { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 }; static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */ { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 }; #define HANDLE(hash,hashlen) \ if (len == sizeof hash ## _prefix + (hashlen) \ && !memcmp (data, hash ## _prefix, sizeof hash ## _prefix)) \ { \ *r_data = data + sizeof hash ## _prefix; \ *r_len = hashlen; \ *r_hash = #hash; \ } if (len == 36) { /* Prior to TLSv1.2, a combination of MD5 and SHA1 was used. */ *r_data = data; *r_len = 36; *r_hash = "tls-md5sha1"; } /* TLSv1.2 encodes the hash value using ASN1. */ else HANDLE (sha1, 20) else HANDLE (rmd160, 20) else HANDLE (sha224, 28) else HANDLE (sha256, 32) else HANDLE (sha384, 48) else HANDLE (sha512, 64) else return gpg_error (GPG_ERR_INV_ARG); #undef HANDLE return 0; } /* Call the agent to sign (DATA,LEN) using the key described by * HEXGRIP. Stores the signature in SIG_RESULT and its lengtn at * SIG_LEN; SIGLEN must initially point to the allocated size of * SIG_RESULT. */ gpg_error_t scute_agent_sign (const char *hexgrip, unsigned char *data, int len, unsigned char *sig_result, unsigned int *sig_len) { char cmd[150]; gpg_error_t err; const char *hash; const unsigned char *raw_data; size_t raw_len; #define MAX_DATA_LEN 64 /* Size of an SHA512 sum. */ unsigned char pretty_data[2 * MAX_DATA_LEN + 1]; int i; struct signature sig; sig.len = 0; if (sig_len == NULL) return gpg_error (GPG_ERR_INV_ARG); err = decode_hash (data, len, &raw_data, &raw_len, &hash); if (err) return err; if (sig_result == NULL) { *sig_len = raw_len; return 0; } if (!hexgrip || !sig_result) return gpg_error (GPG_ERR_INV_ARG); snprintf (cmd, sizeof (cmd), "SIGKEY %s", hexgrip); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err) return err; for (i = 0; i < raw_len; i++) snprintf (&pretty_data[2 * i], 3, "%02X", raw_data[i]); pretty_data[2 * raw_len] = '\0'; snprintf (cmd, sizeof (cmd), "SETHASH --hash=%s %s", hash, pretty_data); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err) return err; err = assuan_transact (agent_ctx, "PKSIGN", pksign_cb, &sig, default_inq_cb, NULL, NULL, NULL); if (err) return err; err = pksign_parse_result (&sig, sig_result, sig_len); return err; } /* Determine if FPR is trusted. */ gpg_error_t scute_agent_is_trusted (const char *fpr, bool *is_trusted) { gpg_error_t err; bool trusted = false; char cmd[150]; snprintf (cmd, sizeof (cmd), "ISTRUSTED %s", fpr); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err && gpg_err_code (err) != GPG_ERR_NOT_TRUSTED) return err; else if (!err) trusted = true; *is_trusted = trusted; return 0; } #define GET_CERT_INIT_SIZE 2048 struct get_cert_s { unsigned char *cert_der; int cert_der_len; int cert_der_size; }; gpg_error_t get_cert_data_cb (void *opaque, const void *data, size_t data_len) { struct get_cert_s *cert_s = opaque; int needed_size; needed_size = cert_s->cert_der_len + data_len; if (needed_size > cert_s->cert_der_size) { unsigned char *new_cert_der; int new_cert_der_size = cert_s->cert_der_size; if (new_cert_der_size == 0) new_cert_der_size = GET_CERT_INIT_SIZE; while (new_cert_der_size < needed_size) new_cert_der_size *= 2; if (cert_s->cert_der == NULL) new_cert_der = malloc (new_cert_der_size); else new_cert_der = realloc (cert_s->cert_der, new_cert_der_size); if (new_cert_der == NULL) return gpg_error_from_syserror (); cert_s->cert_der = new_cert_der; cert_s->cert_der_size = new_cert_der_size; } memcpy (cert_s->cert_der + cert_s->cert_der_len, data, data_len); cert_s->cert_der_len += data_len; return 0; } /* Try to get certificate for CERTREF. */ gpg_error_t scute_agent_get_cert (const char *certref, struct cert *cert) { gpg_error_t err; char cmd[150]; struct get_cert_s cert_s; cert_s.cert_der = NULL; cert_s.cert_der_len = 0; cert_s.cert_der_size = 0; snprintf (cmd, sizeof (cmd), "SCD READCERT %s", certref); err = assuan_transact (agent_ctx, cmd, get_cert_data_cb, &cert_s, NULL, NULL, NULL, NULL); /* Just to be safe... */ if (!err && (cert_s.cert_der_len <= 16 || cert_s.cert_der[0] != 0x30)) { DEBUG (DBG_INFO, "bad card certificate rejected"); err = gpg_error (GPG_ERR_BAD_CERT); } if (err) { if (cert_s.cert_der) free (cert_s.cert_der); return err; } DEBUG (DBG_INFO, "got certificate from card with length %i", cert_s.cert_der_len); cert->cert_der = cert_s.cert_der; cert->cert_der_len = cert_s.cert_der_len; strncpy (cert->certref, certref, sizeof cert->certref -1); cert->certref[sizeof cert->certref - 1] = 0; return 0; } struct random_request { unsigned char *buffer; size_t len; }; gpg_error_t get_challenge_data_cb (void *opaque, const void *line, size_t len) { struct random_request *request = opaque; if (len != request->len) return gpg_error (GPG_ERR_INV_LENGTH); memcpy (request->buffer, line, len); return 0; } gpg_error_t scute_agent_get_random (unsigned char *data, size_t len) { char command[16]; gpg_error_t err; struct random_request request; snprintf (command, sizeof(command), "SCD RANDOM %zu", len); request.buffer = data; request.len = len; err = assuan_transact (agent_ctx, command, get_challenge_data_cb, &request, NULL, NULL, NULL, NULL); return err; } void scute_agent_finalize (void) { if (!agent_ctx) { DEBUG (DBG_CRIT, "no GPG Agent connection established"); return; } DEBUG (DBG_INFO, "releasing agent context"); assuan_release (agent_ctx); agent_ctx = NULL; } diff --git a/src/get-path.c b/src/get-path.c index 521c727..58491fe 100644 --- a/src/get-path.c +++ b/src/get-path.c @@ -1,302 +1,320 @@ /* agent.c - Talking to gpg-agent. * Copyright (C) 2008 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #ifdef HAVE_W32_SYSTEM -#include -#include -#include +# include +# include +# include #endif #include "support.h" +#ifndef HAVE_STPCPY +static char * +my_stpcpy (char *a, const char *b) +{ + while( *b ) + *a++ = *b++; + *a = 0; + + return (char*)a; +} +# undef stpcpy +# define stpcpy(a,b) my_stpcpy ((a), (b)) +#endif /* !HAVE_STPCPY */ + + + + #ifdef HAVE_W32_SYSTEM #define RTLD_LAZY 0 static __inline__ void * dlopen (const char * name, int flag) { void * hd = LoadLibrary (name); + (void)flag; return hd; } static __inline__ void * dlsym (void * hd, const char * sym) { if (hd && sym) { void * fnc = GetProcAddress (hd, sym); if (!fnc) return NULL; return fnc; } return NULL; } static __inline__ int dlclose (void * hd) { if (hd) { FreeLibrary (hd); return 0; } return -1; } /* Return a string from the W32 Registry or NULL in case of error. Caller must release the return value. A NULL for root is an alias for HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE in turn. */ static char * read_w32_registry_string (const char *root, const char *dir, const char *name) { HKEY root_key, key_handle; DWORD n1, nbytes, type; char *result = NULL; if ( !root ) root_key = HKEY_CURRENT_USER; else if ( !strcmp( root, "HKEY_CLASSES_ROOT" ) ) root_key = HKEY_CLASSES_ROOT; else if ( !strcmp( root, "HKEY_CURRENT_USER" ) ) root_key = HKEY_CURRENT_USER; else if ( !strcmp( root, "HKEY_LOCAL_MACHINE" ) ) root_key = HKEY_LOCAL_MACHINE; else if ( !strcmp( root, "HKEY_USERS" ) ) root_key = HKEY_USERS; else if ( !strcmp( root, "HKEY_PERFORMANCE_DATA" ) ) root_key = HKEY_PERFORMANCE_DATA; else if ( !strcmp( root, "HKEY_CURRENT_CONFIG" ) ) root_key = HKEY_CURRENT_CONFIG; else return NULL; if ( RegOpenKeyEx ( root_key, dir, 0, KEY_READ, &key_handle ) ) { if (root) return NULL; /* no need for a RegClose, so return direct */ /* It seems to be common practise to fall back to HKLM. */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, dir, 0, KEY_READ, &key_handle) ) return NULL; /* still no need for a RegClose, so return direct */ } nbytes = 1; if ( RegQueryValueEx( key_handle, name, 0, NULL, NULL, &nbytes ) ) { if (root) goto leave; /* Try to fallback to HKLM also vor a missing value. */ RegCloseKey (key_handle); if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, dir, 0, KEY_READ, &key_handle) ) return NULL; /* Nope. */ if (RegQueryValueEx ( key_handle, name, 0, NULL, NULL, &nbytes)) goto leave; } result = malloc ( (n1=nbytes+1) ); if ( !result ) goto leave; if ( RegQueryValueEx ( key_handle, name, 0, &type, result, &n1 ) ) { free(result); result = NULL; goto leave; } result[nbytes] = 0; /* Make sure it is really a string. */ if (type == REG_EXPAND_SZ && strchr (result, '%')) { char *tmp; n1 += 1000; tmp = malloc (n1+1); if (!tmp) goto leave; nbytes = ExpandEnvironmentStrings (result, tmp, n1); if (nbytes && nbytes > n1) { free (tmp); n1 = nbytes; tmp = malloc (n1 + 1); if (!tmp) goto leave; nbytes = ExpandEnvironmentStrings (result, tmp, n1); if (nbytes && nbytes > n1) { free (tmp); /* Oops - truncated, better don't expand at all. */ goto leave; } tmp[nbytes] = 0; free (result); result = tmp; } else if (nbytes) /* Okay, reduce the length. */ { tmp[nbytes] = 0; free (result); result = malloc (strlen (tmp)+1); if (!result) result = tmp; else { strcpy (result, tmp); free (tmp); } } else /* Error - don't expand. */ { free (tmp); } } leave: RegCloseKey( key_handle ); return result; } /* This is a helper function to load and run a Windows function from either of one DLLs. */ static HRESULT w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e) { static int initialized; static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR); if (!initialized) { static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL }; void *handle; int i; initialized = 1; for (i=0, handle = NULL; !handle && dllnames[i]; i++) { handle = dlopen (dllnames[i], RTLD_LAZY); if (handle) { func = dlsym (handle, "SHGetFolderPathA"); if (!func) { dlclose (handle); handle = NULL; } } } } if (func) return func (a,b,c,d,e); else return -1; } static char * find_program_in_inst_dir (const char *name) { char *result = NULL; char *tmp; tmp = read_w32_registry_string ("HKEY_LOCAL_MACHINE", "Software\\GNU\\GnuPG", "Install Directory"); if (!tmp) return NULL; result = malloc (strlen (tmp) + 1 + strlen (name) + 1); if (!result) { free (tmp); return NULL; } strcpy (stpcpy (stpcpy (result, tmp), "\\"), name); free (tmp); if (access (result, F_OK)) { free (result); return NULL; } return result; } static char * find_program_at_standard_place (const char *name) { char path[MAX_PATH]; char *result = NULL; if (w32_shgetfolderpath (NULL, CSIDL_PROGRAM_FILES, NULL, 0, path) >= 0) { result = malloc (strlen (path) + 1 + strlen (name) + 1); if (result) { strcpy (stpcpy (stpcpy (result, path), "\\"), name); if (access (result, F_OK)) { free (result); result = NULL; } } } return result; } #endif const char * get_gpgsm_path (void) { static const char *pgmname; #ifdef HAVE_W32_SYSTEM if (!pgmname) pgmname = find_program_in_inst_dir ("gpgsm.exe"); if (!pgmname) pgmname = find_program_at_standard_place ("GNU\\GnuPG\\gpgsm.exe"); #endif if (!pgmname) pgmname = GPGSM_PATH; return pgmname; } const char * get_gpg_connect_agent_path (void) { static const char *pgmname; #ifdef HAVE_W32_SYSTEM if (!pgmname) pgmname = find_program_in_inst_dir ("gpg-connect-agent.exe"); if (!pgmname) pgmname = find_program_at_standard_place ("GNU\\GnuPG\\gpg-connect-agent.exe"); #endif if (!pgmname) pgmname = GPG_CONNECT_AGENT_PATH; return pgmname; } diff --git a/src/p11-finalize.c b/src/p11-finalize.c index 7dbd00b..834046a 100644 --- a/src/p11-finalize.c +++ b/src/p11-finalize.c @@ -1,54 +1,54 @@ /* p11-finalize.c - Cryptoki implementation. * Copyright (C) 2006 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #ifdef HAVE_W32_SYSTEM -#define __USE_W32_SOCKETS 1 -#include +# include +# include #endif #include "cryptoki.h" #include "slots.h" #include "agent.h" #include "locking.h" CK_RV CK_SPEC C_Finalize (CK_VOID_PTR pReserved) { /* This is one of the few functions which do not need to take the global lock. */ if (pReserved != NULL_PTR) return CKR_ARGUMENTS_BAD; scute_slots_finalize (); scute_agent_finalize (); scute_locking_finalize (); #ifdef HAVE_W32_SYSTEM WSACleanup (); #endif return CKR_OK; } diff --git a/src/p11-initialize.c b/src/p11-initialize.c index 386df0e..6202cb5 100644 --- a/src/p11-initialize.c +++ b/src/p11-initialize.c @@ -1,120 +1,121 @@ /* p11-initialize.c - Cryptoki implementation. * Copyright (C) 2006 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #ifdef HAVE_W32_SYSTEM #define __USE_W32_SOCKETS 1 -#include +# include +# include #endif #include #include #include "cryptoki.h" #include "settings.h" #include "locking.h" #include "agent.h" #include "error-mapping.h" #include "slots.h" #include "debug.h" CK_RV CK_SPEC C_Initialize (CK_VOID_PTR pInitArgs) { CK_RV err; #ifdef HAVE_W32_SYSTEM WSADATA wsadat; WSAStartup (0x202, &wsadat); #endif /* This is one of the few functions which do not need to take the global lock. */ assuan_set_gpg_err_source (GPG_ERR_SOURCE_ANY); _scute_debug_init (); /* Check the threading configuration. */ if (pInitArgs != NULL_PTR) { CK_C_INITIALIZE_ARGS_PTR args = pInitArgs; bool callbacks; if (args->pReserved != NULL_PTR) return CKR_ARGUMENTS_BAD; if (NEED_TO_CREATE_THREADS && (args->flags & CKF_LIBRARY_CANT_CREATE_OS_THREADS)) return CKR_NEED_TO_CREATE_THREADS; /* Either all pointers are provided, or none are. */ if (args->CreateMutex == NULL_PTR) { if (args->DestroyMutex != NULL_PTR || args->LockMutex != NULL_PTR || args->UnlockMutex != NULL_PTR) return CKR_ARGUMENTS_BAD; callbacks = false; } else { if (args->DestroyMutex == NULL_PTR || args->LockMutex == NULL_PTR || args->UnlockMutex == NULL_PTR) return CKR_ARGUMENTS_BAD; callbacks = true; } /* FIXME: At this point, we do not support using the native thread package. */ if (!callbacks && (args->flags & CKF_OS_LOCKING_OK)) return CKR_CANT_LOCK; } err = scute_locking_initialize (pInitArgs); if (err) return err; err = scute_agent_initialize (); if (err) { scute_locking_finalize (); return scute_gpg_err_to_ck (err); } err = scute_slots_initialize (); if (err) { scute_agent_finalize (); scute_locking_finalize (); return err; } return err; } diff --git a/src/support.h b/src/support.h index 34f67d2..b51f3ac 100644 --- a/src/support.h +++ b/src/support.h @@ -1,91 +1,79 @@ /* support.h - Cryptoki implementation support functions. Copyright (C) 2006 g10 Code GmbH This file is part of Scute. Scute is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Scute is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Scute; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, g10 Code GmbH gives permission to link this library: with the Mozilla Foundation's code for Mozilla (or with modified versions of it that use the same license as the "Mozilla" code), and distribute the linked executables. You must obey the GNU General Public License in all respects for all of the code used other than "Mozilla". If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef SUPPORT_H #define SUPPORT_H 1 #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')) #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 DIM(x) (sizeof (x) / sizeof (x[0])) /* Copy a string into its location, with blank character padding. */ static inline void scute_copy_string (char *dest, const char *src, int max_len) { int i; for (i = 0; (i < max_len) && (*src != '\0'); i++) *(dest++) = *(src++); while (i++ < max_len) *(dest++) = ' '; } /* Use gpg-errors printf functions for better portability. We also replace the standard snprintf with our implementation due to a bug in some mingw32 versions related to the 'l' format modifier. */ #define asprintf gpgrt_asprintf #define vasprintf gpgrt_vasprintf #define snprintf gpgrt_snprintf /*-- 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 */ -#ifndef HAVE_STPCPY -static inline char * -stpcpy (char *a, const char *b) -{ - while( *b ) - *a++ = *b++; - *a = 0; - - return (char*)a; -} -#endif /* !HAVE_STPCPY */ - - const char *get_gpgsm_path (void); const char *get_gpg_connect_agent_path (void); #endif /* !SUPPORT_H */ diff --git a/tests/t-getslotinfo.c b/tests/t-getslotinfo.c index 7633e82..caf02c7 100644 --- a/tests/t-getslotinfo.c +++ b/tests/t-getslotinfo.c @@ -1,157 +1,157 @@ /* t-getslotinfo.c - Regression test. * Copyright (C) 2006, 2008 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #define PGM "t-getslotinfo" #include "t-support.h" int main (int argc, char *argv[]) { int last_argc = -1; CK_RV err; int loop = 0; int token = 0; CK_SLOT_ID_PTR slots; CK_ULONG slots_count; unsigned int i; if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--")) { argc--; argv++; break; } else if (!strcmp (*argv, "--help")) { fputs ("usage: " PGM " [options]\n" "Options:\n" " --loop N Run N times with a 2 second delay.\n" " --token Only present tokens\n", stdout); exit (0); } else if (!strcmp (*argv, "--loop")) { argc--; argv++; if (argc) { loop = atoi (*argv); argc--; argv++; } } else if (!strcmp (*argv, "--token")) { argc--; argv++; token = 1; } else if (!strncmp (*argv, "--", 2)) { fprintf (stderr, "unknown option '%s'\n", *argv); exit (1); } } init_cryptoki (); err = C_GetSlotList (token, NULL, &slots_count); fail_if_err (err); printf ("Number of slots%s: %lu\n", token ? " (with tokens)" : "", slots_count); if (!slots_count) return 0; /* Nothing to do. */ slots = malloc (sizeof (CK_SLOT_ID) * slots_count); if (!slots) fail_if_err (CKR_HOST_MEMORY); err = C_GetSlotList (token, slots, &slots_count); fail_if_err (err); again: for (i = 0; i < slots_count; i++) { CK_SLOT_INFO info; err = C_GetSlotInfo (slots[i], &info); fail_if_err (err); printf ("%2i. Slot ID %lu\n", i, slots[i]); printf (" %.64s\n", info.slotDescription); printf (" Manufacturer ID: %.32s\n", info.manufacturerID); printf (" Flags: %#lx", info.flags); if (info.flags) { int any = 0; CK_FLAGS xflags; xflags = info.flags & ~(CKF_TOKEN_PRESENT | CKF_REMOVABLE_DEVICE | CKF_HW_SLOT); printf (" == "); if (info.flags & CKF_TOKEN_PRESENT) { printf ("TOKEN_PRESENT"); any = 1; } if (info.flags & CKF_REMOVABLE_DEVICE) { printf ("%sREMOVABLE_DEVICE", any ? " | " : ""); any = 1; } if (info.flags & CKF_HW_SLOT) { printf ("%sHW_SLOT", any ? " | " : ""); any = 1; } if (xflags) printf ("%s%#lx", any ? " | " : "", xflags); } printf ("\n"); printf (" Hardware version: %i.%i\n", info.hardwareVersion.major, info.hardwareVersion.minor); printf (" Firmware version: %i.%i\n", info.firmwareVersion.major, info.firmwareVersion.minor); } if (loop > 0) loop--; if (loop) { #ifdef WIN32 - _sleep (2); + Sleep (2*1000); #else sleep (2); /* Why? */ #endif goto again; } return 0; }