diff --git a/common/common-defs.h b/common/common-defs.h index b1928e611..cad5405d0 100644 --- a/common/common-defs.h +++ b/common/common-defs.h @@ -1,54 +1,55 @@ /* common-defs.h - Private declarations for common/ * Copyright (C) 2006 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - 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. * * or * * - 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. * * or both in parallel, as here. * * This file 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_COMMON_DEFS_H #define GNUPG_COMMON_COMMON_DEFS_H /* Dummy replacement for getenv. */ #ifndef HAVE_GETENV #define getenv(a) (NULL) #endif #ifdef HAVE_W32CE_SYSTEM #define getpid() GetCurrentProcessId () #endif /*-- ttyio.c --*/ 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*)); + void (*add_history_fun) (const char*), + int (*rw_history_fun)(const char *, int, int)); #endif /*GNUPG_COMMON_COMMON_DEFS_H*/ diff --git a/common/gpgrlhelp.c b/common/gpgrlhelp.c index 680d9998b..fd3a48f8a 100644 --- a/common/gpgrlhelp.c +++ b/common/gpgrlhelp.c @@ -1,97 +1,164 @@ /* gpgrlhelp.c - A readline wrapper. * Copyright (C) 2006 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - 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. * * or * * - 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. * * or both in parallel, as here. * * This file 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 . */ /* This module may by used by applications to initializes readline support. It is required so that we can have hooks in other parts of libcommon without actually requiring to link against libreadline. It works along with ttyio.c which is a proper part of libcommon. */ #include #include #include #ifdef HAVE_LIBREADLINE #define GNUPG_LIBREADLINE_H_INCLUDED #include #include #include #endif #include "util.h" #include "common-defs.h" #ifdef HAVE_LIBREADLINE static void set_completer (rl_completion_func_t *completer) { rl_attempted_completion_function = completer; rl_inhibit_completion = 0; } static void inhibit_completion (int value) { rl_inhibit_completion = value; } static void cleanup_after_signal (void) { rl_free_line_state (); rl_cleanup_after_signal (); } static void init_stream (FILE *fp) { rl_catch_signals = 0; rl_instream = rl_outstream = fp; rl_inhibit_completion = 1; } + +/* Read or write the history to or from the file FILENAME. The + * behaviour depends on the flag WRITE_MODE: + * + * In read mode (WRITE_MODE is false) these semantics are used: + * + * If NLINES is positive only this number of lines are read from the + * history and the history is always limited to that number of + * lines. A negative value for NLINES is undefined. + * + * If FILENAME is NULL the current history is cleared. If NLINES is + * positive the number of lines stored in the history is limited to + * that number. A negative value for NLINES is undefined. + * + * If WRITE_MODE is true these semantics are used: + * + * If NLINES is negative the history and the history file are + * cleared; if it is zero the entire history is written to the file; + * if it is positive the history is written to the file and the file + * is truncated to this number of lines. + * + * If FILENAME is NULL no file operations are done but if NLINES is + * negative the entire history is cleared. + * + * On success 0 is returned; on error -1 is returned and ERRNO is set. + */ +static int +read_write_history (const char *filename, int write_mode, int nlines) +{ + int rc; + + if (write_mode) + { + if (nlines < 0) + clear_history (); + rc = filename? write_history (filename) : 0; + if (!rc && filename && nlines > 0) + rc = history_truncate_file (filename, nlines); + if (rc) + { + gpg_err_set_errno (rc); + return -1; + } + } + else + { + clear_history (); + if (filename) + { + if (nlines) + rc = read_history_range (filename, 0, nlines); + else + rc = read_history (filename); + if (rc) + { + gpg_err_set_errno (rc); + return -1; + } + } + if (nlines > 0) + stifle_history (nlines); + } + + return 0; +} + #endif /*HAVE_LIBREADLINE*/ /* Initialize our readline code. This should be called as early as - possible as it is actually a constructur. */ + * possible as it is actually a constructor. */ void gnupg_rl_initialize (void) { #ifdef HAVE_LIBREADLINE tty_private_set_rl_hooks (init_stream, set_completer, inhibit_completion, cleanup_after_signal, readline, - add_history); + add_history, + read_write_history); rl_readline_name = GNUPG_NAME; #endif } diff --git a/common/ttyio.c b/common/ttyio.c index 4c095bc03..a27c095cf 100644 --- a/common/ttyio.c +++ b/common/ttyio.c @@ -1,756 +1,791 @@ /* ttyio.c - tty i/O functions * Copyright (C) 1998,1999,2000,2001,2002,2003,2004,2006,2007, * 2009, 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - 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. * * or * * - 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. * * or both in parallel, as here. * * This file 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(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) # define USE_W32_CONSOLE 1 #endif #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 USE_W32_CONSOLE # ifdef HAVE_WINSOCK2_H # include # endif # 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 USE_W32_CONSOLE 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*); - +static int (*my_rl_rw_history)(const char *, int, int); /* 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 there is no ctermid. */ 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(USE_W32_CONSOLE) { 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); #elif defined (HAVE_W32CE_SYSTEM) ttyfp = stderr; #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 USE_W32_CONSOLE { 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 (estream_t fp, const char *fmt, ... ) { va_list arg_ptr; if (fp) { va_start (arg_ptr, fmt) ; es_vfprintf (fp, fmt, arg_ptr ); va_end (arg_ptr); return; } if (no_terminal) return; if (!initialized) init_ttyfp (); va_start (arg_ptr, fmt); #ifdef USE_W32_CONSOLE { 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); } /* Print a string, but filter all control characters out. If FP is * not NULL print to that stream instead to the tty. */ static void do_print_string (estream_t fp, const byte *p, size_t n ) { if (no_terminal && !fp) return; if (!initialized && !fp) init_ttyfp(); if (fp) { print_utf8_buffer (fp, p, n); return; } #ifdef USE_W32_CONSOLE /* 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 (estream_t fp, const byte *p, size_t n, size_t max_n) { size_t i; char *buf; if (no_terminal && !fp) 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_fprintf (fp, "%s", buf); xfree (buf); } else { if( max_n && (n > max_n) ) { n = max_n; } do_print_string (fp, p, n ); } } void tty_print_utf8_string( const byte *p, size_t n ) { tty_print_utf8_string2 (NULL, 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 USE_W32_CONSOLE 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 >= 0 && c <= 0x1f) || c == 0x7f) continue; if (!(i < n-1)) { n += 50; buf = xrealloc (buf, n); } buf[i++] = c; } if (hidden) SetConsoleMode(con.in, DEF_INPMODE ); #elif defined(__riscos__) || defined(HAVE_W32CE_SYSTEM) do { #ifdef HAVE_W32CE_SYSTEM /* Using getchar is not a correct solution but for now it doesn't matter because we have no real console at all. We should rework this as soon as we have switched this entire module to estream. */ c = getchar(); #else c = riscos_getchar(); #endif 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 /* Other systems. */ 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 detected\n"); if (c == '\t') /* Map tab to a space. */ c = ' '; else if ( (c >= 0 && c <= 0x1f) || c == 0x7f) continue; /* Skip all other ASCII control characters. */ 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; } /* Note: This function never returns NULL. */ 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 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 (gpgrt_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 USE_W32_CONSOLE 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*)) + void (*add_history_fun) (const char*), + int (*rw_history_fun)(const char *, int, int)) { 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; + my_rl_rw_history = rw_history_fun; +} + + +/* Read the history from FILENAME or limit the size of the history. + * If FILENAME is NULL and NLINES is zero the current history is + * cleared. Returns 0 on success or -1 on error and sets ERRNO. No + * error is return if readline support is not available. */ +int +tty_read_history (const char *filename, int nlines) +{ + int rc; + + if (!my_rl_rw_history) + return 0; + + rc = my_rl_rw_history (filename, 0, nlines); + if (rc && gpg_err_code_from_syserror () == GPG_ERR_ENOENT) + rc = 0; + + return rc; +} + + +/* Write the current history to the file FILENAME. Returns 0 on + * success or -1 on error and sets ERRNO. No error is return if + * readline support is not available. */ +int +tty_write_history (const char *filename) +{ + if (!my_rl_rw_history) + return 0; + + return my_rl_rw_history (filename, 1, 0); } #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 5bff82fbb..46bcc2ffc 100644 --- a/common/ttyio.h +++ b/common/ttyio.h @@ -1,73 +1,75 @@ /* ttyio.h * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2006, * 2009 Free Software Foundation, Inc. * * This file is part of GNUPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - 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. * * or * * - 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. * * or both in parallel, as here. * * This file 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 (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 (estream_t fp, const char *fmt, ... ); char *tty_getf (const char *promptfmt, ... ); #endif void tty_print_utf8_string (const unsigned char *p, size_t n); void tty_print_utf8_string2 (estream_t fp, 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 +int tty_read_history (const char *filename, int nlines); +int tty_write_history (const char *filename); void tty_cleanup_after_signal (void); void tty_cleanup_rl_after_signal (void); #endif /*GNUPG_COMMON_TTYIO_H*/ diff --git a/doc/gpg-card.texi b/doc/gpg-card.texi index 0865798d2..be19704cc 100644 --- a/doc/gpg-card.texi +++ b/doc/gpg-card.texi @@ -1,652 +1,658 @@ @c card-tool.texi - man page for gpg-card-tool @c Copyright (C) 2019 g10 Code GmbH @c This is part of the GnuPG manual. @c For copying conditions, see the file GnuPG.texi. @include defs.inc @node Smart Card Tool @chapter Smart Card Tool GnuPG comes with a tool to administrate smart cards and USB tokens. This tool is an enhanced version of the @option{--edit-key} command available with @command{gpg}. @menu * gpg-card:: Administrate smart cards. @end menu @c @c GPG-CARD-TOOL @c @manpage gpg-card.1 @node gpg-card @section Administrate smart cards. @ifset manverb .B gpg-card \- Administrate Smart Cards @end ifset @mansect synopsis @ifset manverb .B gpg-card .RI [ options ] .br .B gpg-card .RI [ options ] .I command .RI { .B -- .I command .RI } @end ifset @mansect description The @command{gpg-card} is used to administrate smart cards and USB tokens. It provides a superset of features from @command{gpg --card-edit} an can be considered a frontend to @command{scdaemon} which is a daemon started by @command{gpg-agent} to handle smart cards. If @command{gpg-card} is invoked without commands an interactive mode is used. If @command{gpg-card} is invoked with one or more commands the same commands as available in the interactive mode are run from the command line. These commands need to be delimited with a double-dash. If a double-dash or a shell specific character is required as part of a command the entire command needs to be put in quotes. If one of those commands returns an error the remaining commands are not anymore run unless the command was prefixed with a single dash. A list of commands is available by using the command @code{help} and a detailed description of each command is printed by using @code{help COMMAND}. See the NOTES sections for instructions pertaining to specific cards or card applications. @mansect options @noindent @command{gpg-card} understands these options: @table @gnupgtabopt @item --with-colons @opindex with-colons This option has currently no effect. @item --status-fd @var{n} @opindex status-fd Write special status strings to the file descriptor @var{n}. This program returns only the status messages SUCCESS or FAILURE which are helpful when the caller uses a double fork approach and can't easily get the return code of the process. @item --verbose @opindex verbose Enable extra informational output. @item --quiet @opindex quiet Disable almost all informational output. @item --version @opindex version Print version of the program and exit. @item --help @opindex help Display a brief help page and exit. @item --no-autostart @opindex no-autostart Do not start the gpg-agent if it has not yet been started and its service is required. This option is mostly useful on machines where the connection to gpg-agent has been redirected to another machines. +@item --no-history +@opindex --no-history +In interactive mode the command line history is usually saved and +restored to and from a file below the GnuPG home directory. This +option inhibits the use of that file. + @item --agent-program @var{file} @opindex agent-program Specify the agent program to be started if none is running. The default value is determined by running @command{gpgconf} with the option @option{--list-dirs}. @item --gpg-program @var{file} @opindex gpg-program Specify a non-default gpg binary to be used by certain commands. @item --gpgsm-program @var{file} @opindex gpgsm-program Specify a non-default gpgsm binary to be used by certain commands. @end table @mansect notes (OpenPGP) The support for OpenPGP cards in @command{gpg-card} is not yet complete. For missing features, please continue to use @code{gpg --card-edit}. @mansect notes (PIV) @noindent GnuPG has support for PIV cards (``Personal Identity Verification'' as specified by NIST Special Publication 800-73-4). This section describes how to initialize (personalize) a fresh Yubikey token featuring the PIV application (requires Yubikey-5). We assume that the credentials have not yet been changed and thus are: @table @asis @item Authentication key This is a 24 byte key described by the hex string @* @code{010203040506070801020304050607080102030405060708}. @item PIV Application PIN This is the string @code{123456}. @item PIN Unblocking Key This is the string @code{12345678}. @end table See the example section on how to change these defaults. For production use it is important to use secure values for them. Note that the Authentication Key is not queried via the usual Pinentry dialog but needs to be entered manually or read from a file. The use of a dedicated machine to personalize tokens is strongly suggested. To see what is on the card, the command @code{list} can be given. We will use the interactive mode in the following (the string @emph{gpg/card>} is the prompt). An example output for a fresh card is: @example gpg/card> list Reader ...........: 1050:0407:X:0 Card type ........: yubikey Card firmware ....: 5.1.2 Serial number ....: D2760001240102010006090746250000 Application type .: OpenPGP Version ..........: 2.1 [...] @end example It can be seen by the ``Application type'' line that GnuPG selected the OpenPGP application of the Yubikey. This is because GnuPG assigns the highest priority to the OpenPGP application. To use the PIV application of the Yubikey several methods can be used: With a Yubikey 5 or later the OpenPGP application on the Yubikey can be disabled: @example gpg/card> yubikey disable all opgp gpg/card> yubikey list Application USB NFC ----------------------- OTP yes yes U2F yes yes OPGP no no PIV yes no OATH yes yes FIDO2 yes yes gpg/card> reset @end example The @code{reset} is required so that the GnuPG system rereads the card. Note that disabled applications keep all their data and can at any time be re-enabled (use @kbd{help yubikey}). Another option, which works for all Yubikey versions, is to disable the support for OpenPGP cards in scdaemon. This is done by adding the line @smallexample disable-application openpgp @end smallexample to @file{~/.gnupg/scdaemon.conf} and by restarting scdaemon, either by killing the process or by using @kbd{gpgconf --kill scdaemon}. Finally the default order in which card applications are tried by scdaemon can be changed. For example to prefer PIV over OpenPGP it is sufficient to add @smallexample application-priority piv @end smallexample to @file{~/.gnupg/scdaemon.conf} and to restart @command{scdaemon}. This has an effect only on tokens which support both, PIV and OpenPGP, but does not hamper the use of OpenPGP only tokens. With one of these methods employed the @code{list} command of @command{gpg-card} shows this: @example gpg/card> list Reader ...........: 1050:0407:X:0 Card type ........: yubikey Card firmware ....: 5.1.2 Serial number ....: FF020001008A77C1 Application type .: PIV Version ..........: 1.0 Displayed s/n ....: yk-9074625 PIN usage policy .: app-pin PIN retry counter : - 3 - PIV authentication: [none] keyref .....: PIV.9A Card authenticat. : [none] keyref .....: PIV.9E Digital signature : [none] keyref .....: PIV.9C Key management ...: [none] keyref .....: PIV.9D @end example In case several tokens are plugged into the computer, gpg-card will show only one. To show another token the number of the token (0, 1, 2, ...) can be given as an argument to the @code{list} command. The command @kbd{list --cards} prints a list of all inserted tokens. Note that the ``Displayed s/n'' is printed on the token and also shown in Pinentry prompts asking for the PIN. The four standard key slots are always shown, if other key slots are initialized they are shown as well. The @emph{PIV authentication} key (internal reference @emph{PIV.9A}) is used to authenticate the card and the card holder. The use of the associated private key is protected by the Application PIN which needs to be provided once and the key can the be used until the card is reset or removed from the reader or USB port. GnuPG uses this key with its @emph{Secure Shell} support. The @emph{Card authentication} key (@emph{PIV.9E}) is also known as the CAK and used to support physical access applications. The private key is not protected by a PIN and can thus immediately be used. The @emph{Digital signature} key (@emph{PIV.9C}) is used to digitally sign documents. The use of the associated private key is protected by the Application PIN which needs to be provided for each signing operation. The @emph{Key management} key (@emph{PIV.9D}) is used for encryption. The use of the associated private key is protected by the Application PIN which needs to be provided only once so that decryption operations can then be done until the card is reset or removed from the reader or USB port. We now generate three of the four keys. Note that GnuPG does currently not use the the @emph{Card authentication} key; however, that key is mandatory by the PIV standard and thus we create it too. Key generation requires that we authenticate to the card. This can be done either on the command line (which would reveal the key): @example gpg/card> auth 010203040506070801020304050607080102030405060708 @end example or by reading the key from a file. That file needs to consist of one LF terminated line with the hex encoded key (as above): @example gpg/card> auth < myauth.key @end example As usual @samp{help auth} gives help for this command. An error message is printed if a non-matching key is used. The authentication is valid until a reset of the card or until the card is removed from the reader or the USB port. Note that that in non-interactive mode the @samp{<} needs to be quoted so that the shell does not interpret it as a its own redirection symbol. @noindent Here are the actual commands to generate the keys: @example gpg/card> generate --algo=nistp384 PIV.9A PIV card no. yk-9074625 detected gpg/card> generate --algo=nistp256 PIV.9E PIV card no. yk-9074625 detected gpg/card> generate --algo=rsa2048 PIV.9C PIV card no. yk-9074625 detected @end example If a key has already been created for one of the slots an error will be printed; to create a new key anyway the option @samp{--force} can be used. Note that only the private and public keys have been created but no certificates are stored in the key slots. In fact, GnuPG uses its own non-standard method to store just the public key in place of the the certificate. Other application will not be able to make use these keys until @command{gpgsm} or another tool has been used to create and store the respective certificates. Let us see what the list command now shows: @example gpg/card> list Reader ...........: 1050:0407:X:0 Card type ........: yubikey Card firmware ....: 5.1.2 Serial number ....: FF020001008A77C1 Application type .: PIV Version ..........: 1.0 Displayed s/n ....: yk-9074625 PIN usage policy .: app-pin PIN retry counter : - 3 - PIV authentication: 213D1825FDE0F8240CB4E4229F01AF90AC658C2E keyref .....: PIV.9A (auth) algorithm ..: nistp384 Card authenticat. : 7A53E6CFFE7220A0E646B4632EE29E5A7104499C keyref .....: PIV.9E (auth) algorithm ..: nistp256 Digital signature : 32A6C6FAFCB8421878608AAB452D5470DD3223ED keyref .....: PIV.9C (sign,cert) algorithm ..: rsa2048 Key management ...: [none] keyref .....: PIV.9D @end example The primary information for each key is the @emph{keygrip}, a 40 byte hex-string identifying the key. This keygrip is a unique identifier for the specific parameters of a key. It is used by @command{gpg-agent} and other parts of GnuPG to associate a private key to its protocol specific certificate format (X.509, OpenPGP, or SecureShell). Below the keygrip the key reference along with the key usage capabilities are show. Finally the algorithm is printed in the format used by @command {gpg}. At that point no other information is shown because for these new keys gpg won't be able to find matching certificates. Although we could have created the @emph{Key management} key also with the generate command, we will create that key off-card so that a backup exists. To accomplish this a key needs to be created with either @command{gpg} or @command{gpgsm} or imported in one of these tools. In our example we create a self-signed X.509 certificate (exit the gpg-card tool, first): @example $ gpgsm --gen-key -o encr.crt (1) RSA (2) Existing key (3) Existing key from card Your selection? 1 What keysize do you want? (3072) 2048 Requested keysize is 2048 bits Possible actions for a RSA key: (1) sign, encrypt (2) sign (3) encrypt Your selection? 3 Enter the X.509 subject name: CN=Encryption key for yk-9074625,O=example,C=DE Enter email addresses (end with an empty line): > otto@@example.net > Enter DNS names (optional; end with an empty line): > Enter URIs (optional; end with an empty line): > Create self-signed certificate? (y/N) y These parameters are used: Key-Type: RSA Key-Length: 2048 Key-Usage: encrypt Serial: random Name-DN: CN=Encryption key for yk-9074625,O=example,C=DE Name-Email: otto@@example.net Proceed with creation? (y/N) Now creating self-signed certificate. This may take a while ... gpgsm: about to sign the certificate for key: &34798AAFE0A7565088101CC4AE31C5C8C74461CB gpgsm: certificate created Ready. $ gpgsm --import encr.crt gpgsm: certificate imported gpgsm: total number processed: 1 gpgsm: imported: 1 @end example Note the last step which imported the created certificate. If you you instead created a certificate signing request (CSR) instead of a self-signed certificate and sent this off to a CA you would do the same import step with the certificate received from the CA. Take note of the keygrip (prefixed with an ampersand) as shown during the certificate creation or listed it again using @samp{gpgsm --with-keygrip -k otto@@example.net}. Now to move the key and certificate to the card start @command{gpg-card} again and enter: @example gpg/card> writekey PIV.9D 34798AAFE0A7565088101CC4AE31C5C8C74461CB gpg/card> writecert PIV.9D < encr.crt @end example If you entered a passphrase to protect the private key, you will be asked for it via the Pinentry prompt. On success the key and the certificate has been written to the card and a @code{list} command shows: @example [...] Key management ...: 34798AAFE0A7565088101CC4AE31C5C8C74461CB keyref .....: PIV.9D (encr) algorithm ..: rsa2048 used for ...: X.509 user id ..: CN=Encryption key for yk-9074625,O=example,C=DE user id ..: @end example In case the same key (identified by the keygrip) has been used for several certificates you will see several ``used for'' parts. With this the encryption key is now fully functional and can be used to decrypt messages encrypted to this certificate. @sc{Take care:} the original key is still stored on-disk and should be moved to a backup medium. This can simply be done by copying the file @file{34798AAFE0A7565088101CC4AE31C5C8C74461CB.key} from the directory @file{~/.gnupg/private-keys-v1.d/} to the backup medium and deleting the file at its original place. The final example is to create a self-signed certificate for digital signatures. Leave @command{gpg-card} using @code{quit} or by pressing Control-D and use gpgsm: @example $ gpgsm --learn $ gpgsm --gen-key -o sign.crt Please select what kind of key you want: (1) RSA (2) Existing key (3) Existing key from card Your selection? 3 Serial number of the card: FF020001008A77C1 Available keys: (1) 213D1825FDE0F8240CB4E4229F01AF90AC658C2E PIV.9A nistp384 (2) 7A53E6CFFE7220A0E646B4632EE29E5A7104499C PIV.9E nistp256 (3) 32A6C6FAFCB8421878608AAB452D5470DD3223ED PIV.9C rsa2048 (4) 34798AAFE0A7565088101CC4AE31C5C8C74461CB PIV.9D rsa2048 Your selection? 3 Possible actions for a RSA key: (1) sign, encrypt (2) sign (3) encrypt Your selection? 2 Enter the X.509 subject name: CN=Signing key for yk-9074625,O=example,C=DE Enter email addresses (end with an empty line): > otto@@example.net > Enter DNS names (optional; end with an empty line): > Enter URIs (optional; end with an empty line): > Create self-signed certificate? (y/N) These parameters are used: Key-Type: card:PIV.9C Key-Length: 1024 Key-Usage: sign Serial: random Name-DN: CN=Signing key for yk-9074625,O=example,C=DE Name-Email: otto@@example.net Proceed with creation? (y/N) y Now creating self-signed certificate. This may take a while ... gpgsm: about to sign the certificate for key: &32A6C6FAFCB8421878608AAB452D5470DD3223ED gpgsm: certificate created Ready. $ gpgsm --import sign.crt gpgsm: certificate imported gpgsm: total number processed: 1 gpgsm: imported: 1 @end example The use of @samp{gpgsm --learn} is currently necessary so that gpg-agent knows what keys are available on the card. The need for this command will eventually be removed. The remaining commands are similar to the creation of an on-disk key. However, here we select the @samp{Digital signature} key. During the creation process you will be asked for the Application PIN of the card. The final step is to write the certificate to the card using @command{gpg-card}: @example gpg/card> writecert PIV.9C < sign.crt @end example By running list again we will see the fully initialized card: @example Reader ...........: 1050:0407:X:0 Card type ........: yubikey Card firmware ....: 5.1.2 Serial number ....: FF020001008A77C1 Application type .: PIV Version ..........: 1.0 Displayed s/n ....: yk-9074625 PIN usage policy .: app-pin PIN retry counter : - [verified] - PIV authentication: 213D1825FDE0F8240CB4E4229F01AF90AC658C2E keyref .....: PIV.9A (auth) algorithm ..: nistp384 Card authenticat. : 7A53E6CFFE7220A0E646B4632EE29E5A7104499C keyref .....: PIV.9E (auth) algorithm ..: nistp256 Digital signature : 32A6C6FAFCB8421878608AAB452D5470DD3223ED keyref .....: PIV.9C (sign,cert) algorithm ..: rsa2048 used for ...: X.509 user id ..: CN=Signing key for yk-9074625,O=example,C=DE user id ..: Key management ...: 34798AAFE0A7565088101CC4AE31C5C8C74461CB keyref .....: PIV.9D (encr) algorithm ..: rsa2048 used for ...: X.509 user id ..: CN=Encryption key for yk-9074625,O=example,C=DE user id ..: @end example It is now possible to sign and to encrypt with this card using gpgsm and to use the @samp{PIV authentication} key with ssh: @example $ ssh-add -l 384 SHA256:0qnJ0Y0ehWxKcx2frLfEljf6GCdlO55OZed5HqGHsaU cardno:yk-9074625 (ECDSA) @end example As usual use ssh-add with the uppercase @samp{-L} to list the public ssh key. To use the certificates with Thunderbird or Mozilla, please consult the Scute manual for details. If you want to use the same PIV keys also for OpenPGP (for example on a Yubikey to avoid switching between OpenPGP and PIV), this is also possible: @example $ gpgsm --learn $ gpg --full-gen-key Please select what kind of key you want: (1) RSA and RSA (default) (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only) (14) Existing key from card Your selection? 14 Serial number of the card: FF020001008A77C1 Available keys: (1) 213D1825FDE0F8240CB4E4229F01AF90AC658C2E PIV.9A nistp384 (auth) (2) 7A53E6CFFE7220A0E646B4632EE29E5A7104499C PIV.9E nistp256 (auth) (3) 32A6C6FAFCB8421878608AAB452D5470DD3223ED PIV.9C rsa2048 (cert,sign) (4) 34798AAFE0A7565088101CC4AE31C5C8C74461CB PIV.9D rsa2048 (encr) Your selection? 3 Please specify how long the key should be valid. 0 = key does not expire = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years Key is valid for? (0) Key does not expire at all Is this correct? (y/N) y GnuPG needs to construct a user ID to identify your key. Real name: Email address: otto@@example.net Comment: You selected this USER-ID: "otto@@example.net" Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o gpg: key C3AFA9ED971BB365 marked as ultimately trusted gpg: revocation certificate stored as '[...]D971BB365.rev' public and secret key created and signed. Note that this key cannot be used for encryption. You may want to use the command "--edit-key" to generate a subkey for this purpose. pub rsa2048 2019-04-04 [SC] 7F899AE2FB73159DD68A1B20C3AFA9ED971BB365 uid otto@@example.net @end example Note that you will be asked two times to enter the PIN of your PIV card. If you run @command{gpg} in @option{--expert} mode you will also ge given the option to change the usage flags of the key. The next typescript shows how to add the encryption subkey: @example $ gpg --edit-key 7F899AE2FB73159DD68A1B20C3AFA9ED971BB365 Secret key is available. sec rsa2048/C3AFA9ED971BB365 created: 2019-04-04 expires: never usage: SC card-no: FF020001008A77C1 trust: ultimate validity: ultimate [ultimate] (1). otto@@example.net gpg> addkey Secret parts of primary key are stored on-card. Please select what kind of key you want: (3) DSA (sign only) (4) RSA (sign only) (5) Elgamal (encrypt only) (6) RSA (encrypt only) (14) Existing key from card Your selection? 14 Serial number of the card: FF020001008A77C1 Available keys: (1) 213D1825FDE0F8240CB4E4229F01AF90AC658C2E PIV.9A nistp384 (auth) (2) 7A53E6CFFE7220A0E646B4632EE29E5A7104499C PIV.9E nistp256 (auth) (3) 32A6C6FAFCB8421878608AAB452D5470DD3223ED PIV.9C rsa2048 (cert,sign) (4) 34798AAFE0A7565088101CC4AE31C5C8C74461CB PIV.9D rsa2048 (encr) Your selection? 4 Please specify how long the key should be valid. 0 = key does not expire = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years Key is valid for? (0) Key does not expire at all Is this correct? (y/N) y Really create? (y/N) y sec rsa2048/C3AFA9ED971BB365 created: 2019-04-04 expires: never usage: SC card-no: FF020001008A77C1 trust: ultimate validity: ultimate ssb rsa2048/7067860A98FCE6E1 created: 2019-04-04 expires: never usage: E card-no: FF020001008A77C1 [ultimate] (1). otto@@example.net gpg> save @end example Now you can use your PIV card also with @command{gpg}. @c @mansect examples @mansect see also @ifset isman @command{scdaemon}(1) @end ifset diff --git a/doc/tools.texi b/doc/tools.texi index 985c0a75c..537c3c72a 100644 --- a/doc/tools.texi +++ b/doc/tools.texi @@ -1,2190 +1,2199 @@ @c Copyright (C) 2004, 2008 Free Software Foundation, Inc. @c This is part of the GnuPG manual. @c For copying conditions, see the file GnuPG.texi. @include defs.inc @node Helper Tools @chapter Helper Tools GnuPG comes with a couple of smaller tools: @menu * watchgnupg:: Read logs from a socket. * gpgv:: Verify OpenPGP signatures. * addgnupghome:: Create .gnupg home directories. * gpgconf:: Modify .gnupg home directories. * applygnupgdefaults:: Run gpgconf for all users. * gpg-preset-passphrase:: Put a passphrase into the cache. * gpg-connect-agent:: Communicate with a running agent. * dirmngr-client:: How to use the Dirmngr client tool. * gpgparsemail:: Parse a mail message into an annotated format * symcryptrun:: Call a simple symmetric encryption tool. * gpgtar:: Encrypt or sign files into an archive. * gpg-check-pattern:: Check a passphrase on stdin against the patternfile. @end menu @c @c WATCHGNUPG @c @manpage watchgnupg.1 @node watchgnupg @section Read logs from a socket @ifset manverb .B watchgnupg \- Read and print logs from a socket @end ifset @mansect synopsis @ifset manverb .B watchgnupg .RB [ \-\-force ] .RB [ \-\-verbose ] .I socketname @end ifset @mansect description Most of the main utilities are able to write their log files to a Unix Domain socket if configured that way. @command{watchgnupg} is a simple listener for such a socket. It ameliorates the output with a time stamp and makes sure that long lines are not interspersed with log output from other utilities. This tool is not available for Windows. @noindent @command{watchgnupg} is commonly invoked as @example watchgnupg @end example which is a shorthand for @example watchgnupg --force $(gpgconf --list-dirs socketdir)/S.log @end example To watch GnuPG running with a different home directory, use @example watchgnupg --homedir DIR @end example @manpause @noindent This starts it on the current terminal for listening on the standard logging socket (this is commonly @file{/var/run/user/UID/gnupg/S.log} or if no such user directory hierarchy exists @file{~/.gnupg/S.log}). @mansect options @noindent @command{watchgnupg} understands these options: @table @gnupgtabopt @item --force @opindex force Delete an already existing socket file. This option is implicitly used if no socket name has been given on the command line. @item --homedir @var{DIR} If no socket name is given on the command line, pass @var{DIR} to gpgconf so that the socket for a GnuPG running with DIR has its home directory is used. Note that the environment variable @var{GNUPGHOME} is ignored by watchgnupg. @anchor{option watchgnupg --tcp} @item --tcp @var{n} Instead of reading from a local socket, listen for connects on TCP port @var{n}. A Unix domain socket can optionally also be given as a second source. This option does not use a default socket name. @item --time-only @opindex time-only Do not print the date part of the timestamp. @item --verbose @opindex verbose Enable extra informational output. @item --version @opindex version Print version of the program and exit. @item --help @opindex help Display a brief help page and exit. @end table @noindent @mansect examples @chapheading Examples @example $ watchgnupg --time-only @end example This waits for connections on the local socket (e.g. @file{/var/run/user/1234/gnupg/S.log}) and shows all log entries. To make this work the option @option{log-file} needs to be used with all modules which logs are to be shown. The suggested entry for the configuration files is: @example log-file socket:// @end example If the default socket as given above and returned by "echo $(gpgconf --list-dirs socketdir)/S.log" is not desired an arbitrary socket name can be specified, for example @file{socket:///home/foo/bar/mysocket}. For debugging purposes it is also possible to do remote logging. Take care if you use this feature because the information is send in the clear over the network. Use this syntax in the conf files: @example log-file tcp://192.168.1.1:4711 @end example You may use any port and not just 4711 as shown above; only IP addresses are supported (v4 and v6) and no host names. You need to start @command{watchgnupg} with the @option{tcp} option. Note that under Windows the registry entry @var{HKCU\Software\GNU\GnuPG:DefaultLogFile} can be used to change the default log output from @code{stderr} to whatever is given by that entry. However the only useful entry is a TCP name for remote debugging. @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1) @end ifset @include see-also-note.texi @c @c GPGV @c @include gpgv.texi @c @c ADDGNUPGHOME @c @manpage addgnupghome.8 @node addgnupghome @section Create .gnupg home directories @ifset manverb .B addgnupghome \- Create .gnupg home directories @end ifset @mansect synopsis @ifset manverb .B addgnupghome .I account_1 .IR account_2 ... account_n @end ifset @mansect description If GnuPG is installed on a system with existing user accounts, it is sometimes required to populate the GnuPG home directory with existing files. Especially a @file{trustlist.txt} and a keybox with some initial certificates are often desired. This script helps to do this by copying all files from @file{/etc/skel/.gnupg} to the home directories of the accounts given on the command line. It takes care not to overwrite existing GnuPG home directories. @noindent @command{addgnupghome} is invoked by root as: @example addgnupghome account1 account2 ... accountn @end example @c @c GPGCONF @c @manpage gpgconf.1 @node gpgconf @section Modify .gnupg home directories @ifset manverb .B gpgconf \- Modify .gnupg home directories @end ifset @mansect synopsis @ifset manverb .B gpgconf .RI [ options ] .B \-\-list-components .br .B gpgconf .RI [ options ] .B \-\-list-options .I component .br .B gpgconf .RI [ options ] .B \-\-change-options .I component @end ifset @mansect description The @command{gpgconf} is a utility to automatically and reasonable safely query and modify configuration files in the @file{.gnupg} home directory. It is designed not to be invoked manually by the user, but automatically by graphical user interfaces (GUI).@footnote{Please note that currently no locking is done, so concurrent access should be avoided. There are some precautions to avoid corruption with concurrent usage, but results may be inconsistent and some changes may get lost. The stateless design makes it difficult to provide more guarantees.} @command{gpgconf} provides access to the configuration of one or more components of the GnuPG system. These components correspond more or less to the programs that exist in the GnuPG framework, like GPG, GPGSM, DirMngr, etc. But this is not a strict one-to-one relationship. Not all configuration options are available through @command{gpgconf}. @command{gpgconf} provides a generic and abstract method to access the most important configuration options that can feasibly be controlled via such a mechanism. @command{gpgconf} can be used to gather and change the options available in each component, and can also provide their default values. @command{gpgconf} will give detailed type information that can be used to restrict the user's input without making an attempt to commit the changes. @command{gpgconf} provides the backend of a configuration editor. The configuration editor would usually be a graphical user interface program that displays the current options, their default values, and allows the user to make changes to the options. These changes can then be made active with @command{gpgconf} again. Such a program that uses @command{gpgconf} in this way will be called GUI throughout this section. @menu * Invoking gpgconf:: List of all commands and options. * Format conventions:: Formatting conventions relevant for all commands. * Listing components:: List all gpgconf components. * Checking programs:: Check all programs known to gpgconf. * Listing options:: List all options of a component. * Changing options:: Changing options of a component. * Listing global options:: List all global options. * Querying versions:: Get and compare software versions. * Files used by gpgconf:: What files are used by gpgconf. @end menu @manpause @node Invoking gpgconf @subsection Invoking gpgconf @mansect commands One of the following commands must be given: @table @gnupgtabopt @item --list-components List all components. This is the default command used if none is specified. @item --check-programs List all available backend programs and test whether they are runnable. @item --list-options @var{component} List all options of the component @var{component}. @item --change-options @var{component} Change the options of the component @var{component}. @item --check-options @var{component} Check the options for the component @var{component}. @item --apply-profile @var{file} Apply the configuration settings listed in @var{file} to the configuration files. If @var{file} has no suffix and no slashes the command first tries to read a file with the suffix @code{.prf} from the data directory (@code{gpgconf --list-dirs datadir}) before it reads the file verbatim. A profile is divided into sections using the bracketed component name. Each section then lists the option which shall go into the respective configuration file. @item --apply-defaults Update all configuration files with values taken from the global configuration file (usually @file{/etc/gnupg/gpgconf.conf}). @item --list-dirs [@var{names}] Lists the directories used by @command{gpgconf}. One directory is listed per line, and each line consists of a colon-separated list where the first field names the directory type (for example @code{sysconfdir}) and the second field contains the percent-escaped directory. Although they are not directories, the socket file names used by @command{gpg-agent} and @command{dirmngr} are printed as well. Note that the socket file names and the @code{homedir} lines are the default names and they may be overridden by command line switches. If @var{names} are given only the directories or file names specified by the list names are printed without any escaping. @item --list-config [@var{filename}] List the global configuration file in a colon separated format. If @var{filename} is given, check that file instead. @item --check-config [@var{filename}] Run a syntax check on the global configuration file. If @var{filename} is given, check that file instead. @item --query-swdb @var{package_name} [@var{version_string}] Returns the current version for @var{package_name} and if @var{version_string} is given also an indicator on whether an update is available. The actual file with the software version is automatically downloaded and checked by @command{dirmngr}. @command{dirmngr} uses a thresholds to avoid download the file too often and it does this by default only if it can be done via Tor. To force an update of that file this command can be used: @example gpg-connect-agent --dirmngr 'loadswdb --force' /bye @end example @item --reload [@var{component}] @opindex reload Reload all or the given component. This is basically the same as sending a SIGHUP to the component. Components which don't support reloading are ignored. Without @var{component} or by using "all" for @var{component} all components which are daemons are reloaded. @item --launch [@var{component}] @opindex launch If the @var{component} is not already running, start it. @command{component} must be a daemon. This is in general not required because the system starts these daemons as needed. However, external software making direct use of @command{gpg-agent} or @command{dirmngr} may use this command to ensure that they are started. Using "all" for @var{component} launches all components which are daemons. @item --kill [@var{component}] @opindex kill Kill the given component that runs as a daemon, including @command{gpg-agent}, @command{dirmngr}, and @command{scdaemon}. A @command{component} which does not run as a daemon will be ignored. Using "all" for @var{component} kills all components running as daemons. Note that as of now reload and kill have the same effect for @command{scdaemon}. @item --create-socketdir @opindex create-socketdir Create a directory for sockets below /run/user or /var/run/user. This is command is only required if a non default home directory is used and the /run based sockets shall be used. For the default home directory GnUPG creates a directory on the fly. @item --remove-socketdir @opindex remove-socketdir Remove a directory created with command @option{--create-socketdir}. @end table @mansect options The following options may be used: @table @gnupgtabopt @item -o @var{file} @itemx --output @var{file} Write output to @var{file}. Default is to write to stdout. @item -v @itemx --verbose Outputs additional information while running. Specifically, this extends numerical field values by human-readable descriptions. @item -q @itemx --quiet @opindex quiet Try to be as quiet as possible. @include opt-homedir.texi @item -n @itemx --dry-run Do not actually change anything. This is currently only implemented for @code{--change-options} and can be used for testing purposes. @item -r @itemx --runtime Only used together with @code{--change-options}. If one of the modified options can be changed in a running daemon process, signal the running daemon to ask it to reparse its configuration file after changing. This means that the changes will take effect at run-time, as far as this is possible. Otherwise, they will take effect at the next start of the respective backend programs. @item --status-fd @var{n} @opindex status-fd Write special status strings to the file descriptor @var{n}. This program returns the status messages SUCCESS or FAILURE which are helpful when the caller uses a double fork approach and can't easily get the return code of the process. @manpause @end table @node Format conventions @subsection Format conventions Some lines in the output of @command{gpgconf} contain a list of colon-separated fields. The following conventions apply: @itemize @bullet @item The GUI program is required to strip off trailing newline and/or carriage return characters from the output. @item @command{gpgconf} will never leave out fields. If a certain version provides a certain field, this field will always be present in all @command{gpgconf} versions from that time on. @item Future versions of @command{gpgconf} might append fields to the list. New fields will always be separated from the previously last field by a colon separator. The GUI should be prepared to parse the last field it knows about up until a colon or end of line. @item Not all fields are defined under all conditions. You are required to ignore the content of undefined fields. @end itemize There are several standard types for the content of a field: @table @asis @item verbatim Some fields contain strings that are not escaped in any way. Such fields are described to be used @emph{verbatim}. These fields will never contain a colon character (for obvious reasons). No de-escaping or other formatting is required to use the field content. This is for easy parsing of the output, when it is known that the content can never contain any special characters. @item percent-escaped Some fields contain strings that are described to be @emph{percent-escaped}. Such strings need to be de-escaped before their content can be presented to the user. A percent-escaped string is de-escaped by replacing all occurrences of @code{%XY} by the byte that has the hexadecimal value @code{XY}. @code{X} and @code{Y} are from the set @code{0-9a-f}. @item localized Some fields contain strings that are described to be @emph{localized}. Such strings are translated to the active language and formatted in the active character set. @item @w{unsigned number} Some fields contain an @emph{unsigned number}. This number will always fit into a 32-bit unsigned integer variable. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number. @item @w{signed number} Some fields contain a @emph{signed number}. This number will always fit into a 32-bit signed integer variable. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number. @item @w{boolean value} Some fields contain a @emph{boolean value}. This is a number with either the value 0 or 1. The number may be followed by a space, followed by a human readable description of that value (if the verbose option is used). You should ignore everything in the field that follows the number; checking just the first character is sufficient in this case. @item option Some fields contain an @emph{option} argument. The format of an option argument depends on the type of the option and on some flags: @table @asis @item no argument The simplest case is that the option does not take an argument at all (@var{type} @code{0}). Then the option argument is an unsigned number that specifies how often the option occurs. If the @code{list} flag is not set, then the only valid number is @code{1}. Options that do not take an argument never have the @code{default} or @code{optional arg} flag set. @item number If the option takes a number argument (@var{alt-type} is @code{2} or @code{3}), and it can only occur once (@code{list} flag is not set), then the option argument is either empty (only allowed if the argument is optional), or it is a number. A number is a string that begins with an optional minus character, followed by one or more digits. The number must fit into an integer variable (unsigned or signed, depending on @var{alt-type}). @item number list If the option takes a number argument and it can occur more than once, then the option argument is either empty, or it is a comma-separated list of numbers as described above. @item string If the option takes a string argument (@var{alt-type} is 1), and it can only occur once (@code{list} flag is not set) then the option argument is either empty (only allowed if the argument is optional), or it starts with a double quote character (@code{"}) followed by a percent-escaped string that is the argument value. Note that there is only a leading double quote character, no trailing one. The double quote character is only needed to be able to differentiate between no value and the empty string as value. @item string list If the option takes a string argument and it can occur more than once, then the option argument is either empty, or it is a comma-separated list of string arguments as described above. @end table @end table The active language and character set are currently determined from the locale environment of the @command{gpgconf} program. @c FIXME: Document the active language and active character set. Allow @c to change it via the command line? @mansect usage @node Listing components @subsection Listing components The command @code{--list-components} will list all components that can be configured with @command{gpgconf}. Usually, one component will correspond to one GnuPG-related program and contain the options of that program's configuration file that can be modified using @command{gpgconf}. However, this is not necessarily the case. A component might also be a group of selected options from several programs, or contain entirely virtual options that have a special effect rather than changing exactly one option in one configuration file. A component is a set of configuration options that semantically belong together. Furthermore, several changes to a component can be made in an atomic way with a single operation. The GUI could for example provide a menu with one entry for each component, or a window with one tabulator sheet per component. The command @code{--list-components} lists all available components, one per line. The format of each line is: @code{@var{name}:@var{description}:@var{pgmname}:} @table @var @item name This field contains a name tag of the component. The name tag is used to specify the component in all communication with @command{gpgconf}. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. @item description The @emph{string} in this field contains a human-readable description of the component. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item pgmname The @emph{string} in this field contains the absolute name of the program's file. It can be used to unambiguously invoke that program. It is @emph{percent-escaped}. @end table Example: @example $ gpgconf --list-components gpg:GPG for OpenPGP:/usr/local/bin/gpg2: gpg-agent:GPG Agent:/usr/local/bin/gpg-agent: scdaemon:Smartcard Daemon:/usr/local/bin/scdaemon: gpgsm:GPG for S/MIME:/usr/local/bin/gpgsm: dirmngr:Directory Manager:/usr/local/bin/dirmngr: @end example @node Checking programs @subsection Checking programs The command @code{--check-programs} is similar to @code{--list-components} but works on backend programs and not on components. It runs each program to test whether it is installed and runnable. This also includes a syntax check of all config file options of the program. The command @code{--check-programs} lists all available programs, one per line. The format of each line is: @code{@var{name}:@var{description}:@var{pgmname}:@var{avail}:@var{okay}:@var{cfgfile}:@var{line}:@var{error}:} @table @var @item name This field contains a name tag of the program which is identical to the name of the component. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. This field may be empty to indicate a continuation of error descriptions for the last name. The description and pgmname fields are then also empty. @item description The @emph{string} in this field contains a human-readable description of the component. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item pgmname The @emph{string} in this field contains the absolute name of the program's file. It can be used to unambiguously invoke that program. It is @emph{percent-escaped}. @item avail The @emph{boolean value} in this field indicates whether the program is installed and runnable. @item okay The @emph{boolean value} in this field indicates whether the program's config file is syntactically okay. @item cfgfile If an error occurred in the configuration file (as indicated by a false value in the field @code{okay}), this field has the name of the failing configuration file. It is @emph{percent-escaped}. @item line If an error occurred in the configuration file, this field has the line number of the failing statement in the configuration file. It is an @emph{unsigned number}. @item error If an error occurred in the configuration file, this field has the error text of the failing statement in the configuration file. It is @emph{percent-escaped} and @emph{localized}. @end table @noindent In the following example the @command{dirmngr} is not runnable and the configuration file of @command{scdaemon} is not okay. @example $ gpgconf --check-programs gpg:GPG for OpenPGP:/usr/local/bin/gpg2:1:1: gpg-agent:GPG Agent:/usr/local/bin/gpg-agent:1:1: scdaemon:Smartcard Daemon:/usr/local/bin/scdaemon:1:0: gpgsm:GPG for S/MIME:/usr/local/bin/gpgsm:1:1: dirmngr:Directory Manager:/usr/local/bin/dirmngr:0:0: @end example @noindent The command @w{@code{--check-options @var{component}}} will verify the configuration file in the same manner as @code{--check-programs}, but only for the component @var{component}. @node Listing options @subsection Listing options Every component contains one or more options. Options may be gathered into option groups to allow the GUI to give visual hints to the user about which options are related. The command @code{@w{--list-options @var{component}}} lists all options (and the groups they belong to) in the component @var{component}, one per line. @var{component} must be the string in the field @var{name} in the output of the @code{--list-components} command. There is one line for each option and each group. First come all options that are not in any group. Then comes a line describing a group. Then come all options that belong into each group. Then comes the next group and so on. There does not need to be any group (and in this case the output will stop after the last non-grouped option). The format of each line is: @code{@var{name}:@var{flags}:@var{level}:@var{description}:@var{type}:@var{alt-type}:@var{argname}:@var{default}:@var{argdef}:@var{value}} @table @var @item name This field contains a name tag for the group or option. The name tag is used to specify the group or option in all communication with @command{gpgconf}. The name tag is to be used @emph{verbatim}. It is thus not in any escaped format. @item flags The flags field contains an @emph{unsigned number}. Its value is the OR-wise combination of the following flag values: @table @code @item group (1) If this flag is set, this is a line describing a group and not an option. @end table The following flag values are only defined for options (that is, if the @code{group} flag is not used). @table @code @item optional arg (2) If this flag is set, the argument is optional. This is never set for @var{type} @code{0} (none) options. @item list (4) If this flag is set, the option can be given multiple times. @item runtime (8) If this flag is set, the option can be changed at runtime. @item default (16) If this flag is set, a default value is available. @item default desc (32) If this flag is set, a (runtime) default is available. This and the @code{default} flag are mutually exclusive. @item no arg desc (64) If this flag is set, and the @code{optional arg} flag is set, then the option has a special meaning if no argument is given. @item no change (128) If this flag is set, @command{gpgconf} ignores requests to change the value. GUI frontends should grey out this option. Note, that manual changes of the configuration files are still possible. @end table @item level This field is defined for options and for groups. It contains an @emph{unsigned number} that specifies the expert level under which this group or option should be displayed. The following expert levels are defined for options (they have analogous meaning for groups): @table @code @item basic (0) This option should always be offered to the user. @item advanced (1) This option may be offered to advanced users. @item expert (2) This option should only be offered to expert users. @item invisible (3) This option should normally never be displayed, not even to expert users. @item internal (4) This option is for internal use only. Ignore it. @end table The level of a group will always be the lowest level of all options it contains. @item description This field is defined for options and groups. The @emph{string} in this field contains a human-readable description of the option or group. It can be displayed to the user of the GUI for informational purposes. It is @emph{percent-escaped} and @emph{localized}. @item type This field is only defined for options. It contains an @emph{unsigned number} that specifies the type of the option's argument, if any. The following types are defined: Basic types: @table @code @item none (0) No argument allowed. @item string (1) An @emph{unformatted string}. @item int32 (2) A @emph{signed number}. @item uint32 (3) An @emph{unsigned number}. @end table Complex types: @table @code @item pathname (32) A @emph{string} that describes the pathname of a file. The file does not necessarily need to exist. @item ldap server (33) A @emph{string} that describes an LDAP server in the format: @code{@var{hostname}:@var{port}:@var{username}:@var{password}:@var{base_dn}} @item key fingerprint (34) A @emph{string} with a 40 digit fingerprint specifying a certificate. @item pub key (35) A @emph{string} that describes a certificate by user ID, key ID or fingerprint. @item sec key (36) A @emph{string} that describes a certificate with a key by user ID, key ID or fingerprint. @item alias list (37) A @emph{string} that describes an alias list, like the one used with gpg's group option. The list consists of a key, an equal sign and space separated values. @end table More types will be added in the future. Please see the @var{alt-type} field for information on how to cope with unknown types. @item alt-type This field is identical to @var{type}, except that only the types @code{0} to @code{31} are allowed. The GUI is expected to present the user the option in the format specified by @var{type}. But if the argument type @var{type} is not supported by the GUI, it can still display the option in the more generic basic type @var{alt-type}. The GUI must support all the defined basic types to be able to display all options. More basic types may be added in future versions. If the GUI encounters a basic type it doesn't support, it should report an error and abort the operation. @item argname This field is only defined for options with an argument type @var{type} that is not @code{0}. In this case it may contain a @emph{percent-escaped} and @emph{localized string} that gives a short name for the argument. The field may also be empty, though, in which case a short name is not known. @item default This field is defined only for options for which the @code{default} or @code{default desc} flag is set. If the @code{default} flag is set, its format is that of an @emph{option argument} (@pxref{Format conventions}, for details). If the default value is empty, then no default is known. Otherwise, the value specifies the default value for this option. If the @code{default desc} flag is set, the field is either empty or contains a description of the effect if the option is not given. @item argdef This field is defined only for options for which the @code{optional arg} flag is set. If the @code{no arg desc} flag is not set, its format is that of an @emph{option argument} (@pxref{Format conventions}, for details). If the default value is empty, then no default is known. Otherwise, the value specifies the default argument for this option. If the @code{no arg desc} flag is set, the field is either empty or contains a description of the effect of this option if no argument is given. @item value This field is defined only for options. Its format is that of an @emph{option argument}. If it is empty, then the option is not explicitly set in the current configuration, and the default applies (if any). Otherwise, it contains the current value of the option. Note that this field is also meaningful if the option itself does not take a real argument (in this case, it contains the number of times the option appears). @end table @node Changing options @subsection Changing options The command @w{@code{--change-options @var{component}}} will attempt to change the options of the component @var{component} to the specified values. @var{component} must be the string in the field @var{name} in the output of the @code{--list-components} command. You have to provide the options that shall be changed in the following format on standard input: @code{@var{name}:@var{flags}:@var{new-value}} @table @var @item name This is the name of the option to change. @var{name} must be the string in the field @var{name} in the output of the @code{--list-options} command. @item flags The flags field contains an @emph{unsigned number}. Its value is the OR-wise combination of the following flag values: @table @code @item default (16) If this flag is set, the option is deleted and the default value is used instead (if applicable). @end table @item new-value The new value for the option. This field is only defined if the @code{default} flag is not set. The format is that of an @emph{option argument}. If it is empty (or the field is omitted), the default argument is used (only allowed if the argument is optional for this option). Otherwise, the option will be set to the specified value. @end table @noindent The output of the command is the same as that of @code{--check-options} for the modified configuration file. Examples: To set the force option, which is of basic type @code{none (0)}: @example $ echo 'force:0:1' | gpgconf --change-options dirmngr @end example To delete the force option: @example $ echo 'force:16:' | gpgconf --change-options dirmngr @end example The @code{--runtime} option can influence when the changes take effect. @node Listing global options @subsection Listing global options Sometimes it is useful for applications to look at the global options file @file{gpgconf.conf}. The colon separated listing format is record oriented and uses the first field to identify the record type: @table @code @item k This describes a key record to start the definition of a new ruleset for a user/group. The format of a key record is: @code{k:@var{user}:@var{group}:} @table @var @item user This is the user field of the key. It is percent escaped. See the definition of the gpgconf.conf format for details. @item group This is the group field of the key. It is percent escaped. @end table @item r This describes a rule record. All rule records up to the next key record make up a rule set for that key. The format of a rule record is: @code{r:::@var{component}:@var{option}:@var{flag}:@var{value}:} @table @var @item component This is the component part of a rule. It is a plain string. @item option This is the option part of a rule. It is a plain string. @item flag This is the flags part of a rule. There may be only one flag per rule but by using the same component and option, several flags may be assigned to an option. It is a plain string. @item value This is the optional value for the option. It is a percent escaped string with a single quotation mark to indicate a string. The quotation mark is only required to distinguish between no value specified and an empty string. @end table @end table @noindent Unknown record types should be ignored. Note that there is intentionally no feature to change the global option file through @command{gpgconf}. @node Querying versions @subsection Get and compare software versions. The GnuPG Project operates a server to query the current versions of software packages related to GnuPG. @command{gpgconf} can be used to access this online database. To allow for offline operations, this feature works by having @command{dirmngr} download a file from @code{https://versions.gnupg.org}, checking the signature of that file and storing the file in the GnuPG home directory. If @command{gpgconf} is used and @command{dirmngr} is running, it may ask @command{dirmngr} to refresh that file before itself uses the file. The command @option{--query-swdb} returns information for the given package in a colon delimited format: @table @var @item name This is the name of the package as requested. Note that "gnupg" is a special name which is replaced by the actual package implementing this version of GnuPG. For this name it is also not required to specify a version because @command{gpgconf} takes its own version in this case. @item iversion The currently installed version or an empty string. The value is taken from the command line argument but may be provided by gpg if not given. @item status The status of the software package according to this table: @table @code @item - No information available. This is either because no current version has been specified or due to an error. @item ? The given name is not known in the online database. @item u An update of the software is available. @item c The installed version of the software is current. @item n The installed version is already newer than the released version. @end table @item urgency If the value (the empty string should be considered as zero) is greater than zero an important update is available. @item error This returns an @command{gpg-error} error code to distinguish between various failure modes. @item filedate This gives the date of the file with the version numbers in standard ISO format (@code{yyyymmddThhmmss}). The date has been extracted by @command{dirmngr} from the signature of the file. @item verified This gives the date in ISO format the file was downloaded. This value can be used to evaluate the freshness of the information. @item version This returns the version string for the requested software from the file. @item reldate This returns the release date in ISO format. @item size This returns the size of the package as decimal number of bytes. @item hash This returns a hexified SHA-2 hash of the package. @end table @noindent More fields may be added in future to the output. @mansect files @node Files used by gpgconf @subsection Files used by gpgconf @table @file @item /etc/gnupg/gpgconf.conf @cindex gpgconf.conf If this file exists, it is processed as a global configuration file. A commented example can be found in the @file{examples} directory of the distribution. @item @var{GNUPGHOME}/swdb.lst @cindex swdb.lst A file with current software versions. @command{dirmngr} creates this file on demand from an online resource. @end table @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1), @command{dirmngr}(1) @end ifset @include see-also-note.texi @c @c APPLYGNUPGDEFAULTS @c @manpage applygnupgdefaults.8 @node applygnupgdefaults @section Run gpgconf for all users @ifset manverb .B applygnupgdefaults \- Run gpgconf --apply-defaults for all users. @end ifset @mansect synopsis @ifset manverb .B applygnupgdefaults @end ifset @mansect description This script is a wrapper around @command{gpgconf} to run it with the command @code{--apply-defaults} for all real users with an existing GnuPG home directory. Admins might want to use this script to update he GnuPG configuration files for all users after @file{/etc/gnupg/gpgconf.conf} has been changed. This allows enforcing certain policies for all users. Note, that this is not a bulletproof way to force a user to use certain options. A user may always directly edit the configuration files and bypass gpgconf. @noindent @command{applygnupgdefaults} is invoked by root as: @example applygnupgdefaults @end example @c @c GPG-PRESET-PASSPHRASE @c @node gpg-preset-passphrase @section Put a passphrase into the cache @manpage gpg-preset-passphrase.1 @ifset manverb .B gpg-preset-passphrase \- Put a passphrase into gpg-agent's cache @end ifset @mansect synopsis @ifset manverb .B gpg-preset-passphrase .RI [ options ] .RI [ command ] .I cache-id @end ifset @mansect description The @command{gpg-preset-passphrase} is a utility to seed the internal cache of a running @command{gpg-agent} with passphrases. It is mainly useful for unattended machines, where the usual @command{pinentry} tool may not be used and the passphrases for the to be used keys are given at machine startup. This program works with GnuPG 2 and later. GnuPG 1.x is not supported. Passphrases set with this utility don't expire unless the @option{--forget} option is used to explicitly clear them from the cache --- or @command{gpg-agent} is either restarted or reloaded (by sending a SIGHUP to it). Note that the maximum cache time as set with @option{--max-cache-ttl} is still honored. It is necessary to allow this passphrase presetting by starting @command{gpg-agent} with the @option{--allow-preset-passphrase}. @menu * Invoking gpg-preset-passphrase:: List of all commands and options. @end menu @manpause @node Invoking gpg-preset-passphrase @subsection List of all commands and options @mancont @noindent @command{gpg-preset-passphrase} is invoked this way: @example gpg-preset-passphrase [options] [command] @var{cacheid} @end example @var{cacheid} is either a 40 character keygrip of hexadecimal characters identifying the key for which the passphrase should be set or cleared. The keygrip is listed along with the key when running the command: @code{gpgsm --with-keygrip --list-secret-keys}. Alternatively an arbitrary string may be used to identify a passphrase; it is suggested that such a string is prefixed with the name of the application (e.g @code{foo:12346}). Scripts should always use the option @option{--with-colons}, which provides the keygrip in a "grp" line (cf. @file{doc/DETAILS})/ @noindent One of the following command options must be given: @table @gnupgtabopt @item --preset @opindex preset Preset a passphrase. This is what you usually will use. @command{gpg-preset-passphrase} will then read the passphrase from @code{stdin}. @item --forget @opindex forget Flush the passphrase for the given cache ID from the cache. @end table @noindent The following additional options may be used: @table @gnupgtabopt @item -v @itemx --verbose @opindex verbose Output additional information while running. @item -P @var{string} @itemx --passphrase @var{string} @opindex passphrase Instead of reading the passphrase from @code{stdin}, use the supplied @var{string} as passphrase. Note that this makes the passphrase visible for other users. @end table @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @command{scdaemon}(1) @end ifset @include see-also-note.texi @c @c GPG-CONNECT-AGENT @c @node gpg-connect-agent @section Communicate with a running agent @manpage gpg-connect-agent.1 @ifset manverb .B gpg-connect-agent \- Communicate with a running agent @end ifset @mansect synopsis @ifset manverb .B gpg-connect-agent .RI [ options ] [commands] @end ifset @mansect description The @command{gpg-connect-agent} is a utility to communicate with a running @command{gpg-agent}. It is useful to check out the commands @command{gpg-agent} provides using the Assuan interface. It might also be useful for scripting simple applications. Input is expected at stdin and output gets printed to stdout. It is very similar to running @command{gpg-agent} in server mode; but here we connect to a running instance. @menu * Invoking gpg-connect-agent:: List of all options. * Controlling gpg-connect-agent:: Control commands. @end menu @manpause @node Invoking gpg-connect-agent @subsection List of all options @noindent @command{gpg-connect-agent} is invoked this way: @example gpg-connect-agent [options] [commands] @end example @mancont @noindent The following options may be used: @table @gnupgtabopt @item -v @itemx --verbose @opindex verbose Output additional information while running. @item -q @item --quiet @opindex q @opindex quiet Try to be as quiet as possible. @include opt-homedir.texi @item --agent-program @var{file} @opindex agent-program Specify the agent program to be started if none is running. The default value is determined by running @command{gpgconf} with the option @option{--list-dirs}. Note that the pipe symbol (@code{|}) is used for a regression test suite hack and may thus not be used in the file name. @item --dirmngr-program @var{file} @opindex dirmngr-program Specify the directory manager (keyserver client) program to be started if none is running. This has only an effect if used together with the option @option{--dirmngr}. @item --keyboxd-program @var{file} @opindex keyboxd-program Specify the keybox daemon program to be started if none is running. This has only an effect if used together with the option @option{--keyboxd}. @item --dirmngr @opindex dirmngr Connect to a running directory manager (keyserver client) instead of to the gpg-agent. If a dirmngr is not running, start it. @item --keyboxd @opindex keyboxd Connect to a running keybox daemon instead of to the gpg-agent. If a keyboxd is not running, start it. @item -S @itemx --raw-socket @var{name} @opindex raw-socket Connect to socket @var{name} assuming this is an Assuan style server. Do not run any special initializations or environment checks. This may be used to directly connect to any Assuan style socket server. @item -E @itemx --exec @opindex exec Take the rest of the command line as a program and it's arguments and execute it as an Assuan server. Here is how you would run @command{gpgsm}: @smallexample gpg-connect-agent --exec gpgsm --server @end smallexample Note that you may not use options on the command line in this case. @item --no-ext-connect @opindex no-ext-connect When using @option{-S} or @option{--exec}, @command{gpg-connect-agent} connects to the Assuan server in extended mode to allow descriptor passing. This option makes it use the old mode. @item --no-autostart @opindex no-autostart Do not start the gpg-agent or the dirmngr if it has not yet been started. +@item --no-history +@opindex --no-history +In interactive mode the command line history is usually saved and +restored to and from a file below the GnuPG home directory. This +option inhibits the use of that file. + @item -r @var{file} @itemx --run @var{file} @opindex run Run the commands from @var{file} at startup and then continue with the regular input method. Note, that commands given on the command line are executed after this file. @item -s @itemx --subst @opindex subst Run the command @code{/subst} at startup. @item --hex @opindex hex Print data lines in a hex format and the ASCII representation of non-control characters. @item --decode @opindex decode Decode data lines. That is to remove percent escapes but make sure that a new line always starts with a D and a space. @end table @mansect control commands @node Controlling gpg-connect-agent @subsection Control commands While reading Assuan commands, gpg-agent also allows a few special commands to control its operation. These control commands all start with a slash (@code{/}). @table @code @item /echo @var{args} Just print @var{args}. @item /let @var{name} @var{value} Set the variable @var{name} to @var{value}. Variables are only substituted on the input if the @command{/subst} has been used. Variables are referenced by prefixing the name with a dollar sign and optionally include the name in curly braces. The rules for a valid name are identically to those of the standard bourne shell. This is not yet enforced but may be in the future. When used with curly braces no leading or trailing white space is allowed. If a variable is not found, it is searched in the environment and if found copied to the table of variables. Variable functions are available: The name of the function must be followed by at least one space and the at least one argument. The following functions are available: @table @code @item get Return a value described by the argument. Available arguments are: @table @code @item cwd The current working directory. @item homedir The gnupg homedir. @item sysconfdir GnuPG's system configuration directory. @item bindir GnuPG's binary directory. @item libdir GnuPG's library directory. @item libexecdir GnuPG's library directory for executable files. @item datadir GnuPG's data directory. @item serverpid The PID of the current server. Command @command{/serverpid} must have been given to return a useful value. @end table @item unescape @var{args} Remove C-style escapes from @var{args}. Note that @code{\0} and @code{\x00} terminate the returned string implicitly. The string to be converted are the entire arguments right behind the delimiting space of the function name. @item unpercent @var{args} @itemx unpercent+ @var{args} Remove percent style escaping from @var{args}. Note that @code{%00} terminates the string implicitly. The string to be converted are the entire arguments right behind the delimiting space of the function name. @code{unpercent+} also maps plus signs to a spaces. @item percent @var{args} @itemx percent+ @var{args} Escape the @var{args} using percent style escaping. Tabs, formfeeds, linefeeds, carriage returns and colons are escaped. @code{percent+} also maps spaces to plus signs. @item errcode @var{arg} @itemx errsource @var{arg} @itemx errstring @var{arg} Assume @var{arg} is an integer and evaluate it using @code{strtol}. Return the gpg-error error code, error source or a formatted string with the error code and error source. @item + @itemx - @itemx * @itemx / @itemx % Evaluate all arguments as long integers using @code{strtol} and apply this operator. A division by zero yields an empty string. @item ! @itemx | @itemx & Evaluate all arguments as long integers using @code{strtol} and apply the logical operators NOT, OR or AND. The NOT operator works on the last argument only. @end table @item /definq @var{name} @var{var} Use content of the variable @var{var} for inquiries with @var{name}. @var{name} may be an asterisk (@code{*}) to match any inquiry. @item /definqfile @var{name} @var{file} Use content of @var{file} for inquiries with @var{name}. @var{name} may be an asterisk (@code{*}) to match any inquiry. @item /definqprog @var{name} @var{prog} Run @var{prog} for inquiries matching @var{name} and pass the entire line to it as command line arguments. @item /datafile @var{name} Write all data lines from the server to the file @var{name}. The file is opened for writing and created if it does not exists. An existing file is first truncated to 0. The data written to the file fully decoded. Using a single dash for @var{name} writes to stdout. The file is kept open until a new file is set using this command or this command is used without an argument. @item /showdef Print all definitions @item /cleardef Delete all definitions @item /sendfd @var{file} @var{mode} Open @var{file} in @var{mode} (which needs to be a valid @code{fopen} mode string) and send the file descriptor to the server. This is usually followed by a command like @code{INPUT FD} to set the input source for other commands. @item /recvfd Not yet implemented. @item /open @var{var} @var{file} [@var{mode}] Open @var{file} and assign the file descriptor to @var{var}. Warning: This command is experimental and might change in future versions. @item /close @var{fd} Close the file descriptor @var{fd}. Warning: This command is experimental and might change in future versions. @item /showopen Show a list of open files. @item /serverpid Send the Assuan command @command{GETINFO pid} to the server and store the returned PID for internal purposes. @item /sleep Sleep for a second. @item /hex @itemx /nohex Same as the command line option @option{--hex}. @item /decode @itemx /nodecode Same as the command line option @option{--decode}. @item /subst @itemx /nosubst Enable and disable variable substitution. It defaults to disabled unless the command line option @option{--subst} has been used. If /subst as been enabled once, leading whitespace is removed from input lines which makes scripts easier to read. @item /while @var{condition} @itemx /end These commands provide a way for executing loops. All lines between the @code{while} and the corresponding @code{end} are executed as long as the evaluation of @var{condition} yields a non-zero value or is the string @code{true} or @code{yes}. The evaluation is done by passing @var{condition} to the @code{strtol} function. Example: @smallexample /subst /let i 3 /while $i /echo loop counter is $i /let i $@{- $i 1@} /end @end smallexample @item /if @var{condition} @itemx /end These commands provide a way for conditional execution. All lines between the @code{if} and the corresponding @code{end} are executed only if the evaluation of @var{condition} yields a non-zero value or is the string @code{true} or @code{yes}. The evaluation is done by passing @var{condition} to the @code{strtol} function. @item /run @var{file} Run commands from @var{file}. +@item /history --clear +Clear the command history. + @item /bye Terminate the connection and the program. @item /help Print a list of available control commands. @end table @ifset isman @mansect see also @command{gpg-agent}(1), @command{scdaemon}(1) @include see-also-note.texi @end ifset @c @c DIRMNGR-CLIENT @c @node dirmngr-client @section The Dirmngr Client Tool @manpage dirmngr-client.1 @ifset manverb .B dirmngr-client \- Tool to access the Dirmngr services @end ifset @mansect synopsis @ifset manverb .B dirmngr-client .RI [ options ] .RI [ certfile | pattern ] @end ifset @mansect description The @command{dirmngr-client} is a simple tool to contact a running dirmngr and test whether a certificate has been revoked --- either by being listed in the corresponding CRL or by running the OCSP protocol. If no dirmngr is running, a new instances will be started but this is in general not a good idea due to the huge performance overhead. @noindent The usual way to run this tool is either: @example dirmngr-client @var{acert} @end example @noindent or @example dirmngr-client <@var{acert} @end example Where @var{acert} is one DER encoded (binary) X.509 certificates to be tested. @ifclear isman The return value of this command is @end ifclear @mansect return value @ifset isman @command{dirmngr-client} returns these values: @end ifset @table @code @item 0 The certificate under question is valid; i.e. there is a valid CRL available and it is not listed there or the OCSP request returned that that certificate is valid. @item 1 The certificate has been revoked @item 2 (and other values) There was a problem checking the revocation state of the certificate. A message to stderr has given more detailed information. Most likely this is due to a missing or expired CRL or due to a network problem. @end table @mansect options @noindent @command{dirmngr-client} may be called with the following options: @table @gnupgtabopt @item --version @opindex version Print the program version and licensing information. Note that you cannot abbreviate this command. @item --help, -h @opindex help Print a usage message summarizing the most useful command-line options. Note that you cannot abbreviate this command. @item --quiet, -q @opindex quiet Make the output extra brief by suppressing any informational messages. @item -v @item --verbose @opindex v @opindex verbose Outputs additional information while running. You can increase the verbosity by giving several verbose commands to @sc{dirmngr}, such as @samp{-vv}. @item --pem @opindex pem Assume that the given certificate is in PEM (armored) format. @item --ocsp @opindex ocsp Do the check using the OCSP protocol and ignore any CRLs. @item --force-default-responder @opindex force-default-responder When checking using the OCSP protocol, force the use of the default OCSP responder. That is not to use the Reponder as given by the certificate. @item --ping @opindex ping Check whether the dirmngr daemon is up and running. @item --cache-cert @opindex cache-cert Put the given certificate into the cache of a running dirmngr. This is mainly useful for debugging. @item --validate @opindex validate Validate the given certificate using dirmngr's internal validation code. This is mainly useful for debugging. @item --load-crl @opindex load-crl This command expects a list of filenames with DER encoded CRL files. With the option @option{--url} URLs are expected in place of filenames and they are loaded directly from the given location. All CRLs will be validated and then loaded into dirmngr's cache. @item --lookup @opindex lookup Take the remaining arguments and run a lookup command on each of them. The results are Base-64 encoded outputs (without header lines). This may be used to retrieve certificates from a server. However the output format is not very well suited if more than one certificate is returned. @item --url @itemx -u @opindex url Modify the @command{lookup} and @command{load-crl} commands to take an URL. @item --local @itemx -l @opindex url Let the @command{lookup} command only search the local cache. @item --squid-mode @opindex squid-mode Run @sc{dirmngr-client} in a mode suitable as a helper program for Squid's @option{external_acl_type} option. @end table @ifset isman @mansect see also @command{dirmngr}(8), @command{gpgsm}(1) @include see-also-note.texi @end ifset @c @c GPGPARSEMAIL @c @node gpgparsemail @section Parse a mail message into an annotated format @manpage gpgparsemail.1 @ifset manverb .B gpgparsemail \- Parse a mail message into an annotated format @end ifset @mansect synopsis @ifset manverb .B gpgparsemail .RI [ options ] .RI [ file ] @end ifset @mansect description The @command{gpgparsemail} is a utility currently only useful for debugging. Run it with @code{--help} for usage information. @c @c SYMCRYPTRUN @c @node symcryptrun @section Call a simple symmetric encryption tool @manpage symcryptrun.1 @ifset manverb .B symcryptrun \- Call a simple symmetric encryption tool @end ifset @mansect synopsis @ifset manverb .B symcryptrun .B \-\-class .I class .B \-\-program .I program .B \-\-keyfile .I keyfile .RB [ --decrypt | --encrypt ] .RI [ inputfile ] @end ifset @mansect description Sometimes simple encryption tools are already in use for a long time and there might be a desire to integrate them into the GnuPG framework. The protocols and encryption methods might be non-standard or not even properly documented, so that a full-fledged encryption tool with an interface like @command{gpg} is not doable. @command{symcryptrun} provides a solution: It operates by calling the external encryption/decryption module and provides a passphrase for a key using the standard @command{pinentry} based mechanism through @command{gpg-agent}. Note, that @command{symcryptrun} is only available if GnuPG has been configured with @samp{--enable-symcryptrun} at build time. @menu * Invoking symcryptrun:: List of all commands and options. @end menu @manpause @node Invoking symcryptrun @subsection List of all commands and options @noindent @command{symcryptrun} is invoked this way: @example symcryptrun --class CLASS --program PROGRAM --keyfile KEYFILE [--decrypt | --encrypt] [inputfile] @end example @mancont For encryption, the plain text must be provided on STDIN or as the argument @var{inputfile}, and the ciphertext will be output to STDOUT. For decryption vice versa. @var{CLASS} describes the calling conventions of the external tool. Currently it must be given as @samp{confucius}. @var{PROGRAM} is the full filename of that external tool. For the class @samp{confucius} the option @option{--keyfile} is required; @var{keyfile} is the name of a file containing the secret key, which may be protected by a passphrase. For detailed calling conventions, see the source code. @noindent Note, that @command{gpg-agent} must be running before starting @command{symcryptrun}. @noindent The following additional options may be used: @table @gnupgtabopt @item -v @itemx --verbose @opindex verbose Output additional information while running. @item -q @item --quiet @opindex q @opindex quiet Try to be as quiet as possible. @include opt-homedir.texi @item --log-file @var{file} @opindex log-file Append all logging output to @var{file}. Use @file{socket://} to log to socket. Default is to write logging information to STDERR. @end table @noindent The possible exit status codes of @command{symcryptrun} are: @table @code @item 0 Success. @item 1 Some error occurred. @item 2 No valid passphrase was provided. @item 3 The operation was canceled by the user. @end table @mansect see also @ifset isman @command{gpg}(1), @command{gpgsm}(1), @command{gpg-agent}(1), @end ifset @include see-also-note.texi @c @c GPGTAR @c @manpage gpgtar.1 @node gpgtar @section Encrypt or sign files into an archive @ifset manverb .B gpgtar \- Encrypt or sign files into an archive @end ifset @mansect synopsis @ifset manverb .B gpgtar .RI [ options ] .I filename1 .I [ filename2, ... ] .I directory1 .I [ directory2, ... ] @end ifset @mansect description @command{gpgtar} encrypts or signs files into an archive. It is an gpg-ized tar using the same format as used by PGP's PGP Zip. @manpause @noindent @command{gpgtar} is invoked this way: @example gpgtar [options] @var{filename1} [@var{filename2}, ...] @var{directory} [@var{directory2}, ...] @end example @mansect options @noindent @command{gpgtar} understands these options: @table @gnupgtabopt @item --create @opindex create Put given files and directories into a vanilla ``ustar'' archive. @item --extract @opindex extract Extract all files from a vanilla ``ustar'' archive. @item --encrypt @itemx -e @opindex encrypt Encrypt given files and directories into an archive. This option may be combined with option @option{--symmetric} for an archive that may be decrypted via a secret key or a passphrase. @item --decrypt @itemx -d @opindex decrypt Extract all files from an encrypted archive. @item --sign @itemx -s Make a signed archive from the given files and directories. This can be combined with option @option{--encrypt} to create a signed and then encrypted archive. @item --list-archive @itemx -t @opindex list-archive List the contents of the specified archive. @item --symmetric @itemx -c Encrypt with a symmetric cipher using a passphrase. The default symmetric cipher used is @value{GPGSYMENCALGO}, but may be chosen with the @option{--cipher-algo} option to @command{gpg}. @item --recipient @var{user} @itemx -r @var{user} @opindex recipient Encrypt for user id @var{user}. For details see @command{gpg}. @item --local-user @var{user} @itemx -u @var{user} @opindex local-user Use @var{user} as the key to sign with. For details see @command{gpg}. @item --output @var{file} @itemx -o @var{file} @opindex output Write the archive to the specified file @var{file}. @item --verbose @itemx -v @opindex verbose Enable extra informational output. @item --quiet @itemx -q @opindex quiet Try to be as quiet as possible. @item --skip-crypto @opindex skip-crypto Skip all crypto operations and create or extract vanilla ``ustar'' archives. @item --dry-run @opindex dry-run Do not actually output the extracted files. @item --directory @var{dir} @itemx -C @var{dir} @opindex directory Extract the files into the directory @var{dir}. The default is to take the directory name from the input filename. If no input filename is known a directory named @file{GPGARCH} is used. For tarball creation, switch to directory @var{dir} before performing any operations. @item --files-from @var{file} @itemx -T @var{file} Take the file names to work from the file @var{file}; one file per line. @item --null @opindex null Modify option @option{--files-from} to use a binary nul instead of a linefeed to separate file names. @item --openpgp @opindex openpgp This option has no effect because OpenPGP encryption and signing is the default. @item --cms @opindex cms This option is reserved and shall not be used. It will eventually be used to encrypt or sign using the CMS protocol; but that is not yet implemented. @item --set-filename @var{file} @opindex set-filename Use the last component of @var{file} as the output directory. The default is to take the directory name from the input filename. If no input filename is known a directory named @file{GPGARCH} is used. This option is deprecated in favor of option @option{--directory}. @item --gpg @var{gpgcmd} @opindex gpg Use the specified command @var{gpgcmd} instead of @command{gpg}. @item --gpg-args @var{args} @opindex gpg-args Pass the specified extra options to @command{gpg}. @item --tar-args @var{args} @opindex tar-args Assume @var{args} are standard options of the command @command{tar} and parse them. The only supported tar options are "--directory", "--files-from", and "--null" This is an obsolete options because those supported tar options can also be given directly. @item --version @opindex version Print version of the program and exit. @item --help @opindex help Display a brief help page and exit. @end table @mansect diagnostics @noindent The program returns 0 if everything was fine, 1 otherwise. @mansect examples @ifclear isman @noindent Some examples: @end ifclear @noindent Encrypt the contents of directory @file{mydocs} for user Bob to file @file{test1}: @example gpgtar --encrypt --output test1 -r Bob mydocs @end example @noindent List the contents of archive @file{test1}: @example gpgtar --list-archive test1 @end example @mansect see also @ifset isman @command{gpg}(1), @command{tar}(1), @end ifset @include see-also-note.texi @c @c GPG-CHECK-PATTERN @c @manpage gpg-check-pattern.1 @node gpg-check-pattern @section Check a passphrase on stdin against the patternfile @ifset manverb .B gpg-check-pattern \- Check a passphrase on stdin against the patternfile @end ifset @mansect synopsis @ifset manverb .B gpg\-check\-pattern .RI [ options ] .I patternfile @end ifset @mansect description @command{gpg-check-pattern} checks a passphrase given on stdin against a specified pattern file. @mansect options @noindent @table @gnupgtabopt @item --verbose @opindex verbose Enable extra informational output. @item --check @opindex check Run only a syntax check on the patternfile. @item --null @opindex null Input is expected to be null delimited. @end table @mansect see also @ifset isman @command{gpg}(1), @end ifset @include see-also-note.texi diff --git a/tools/gpg-card.c b/tools/gpg-card.c index 96b2bcf44..2fcc120fb 100644 --- a/tools/gpg-card.c +++ b/tools/gpg-card.c @@ -1,4015 +1,4067 @@ /* gpg-card.c - An interactive tool to work with cards. * Copyright (C) 2019, 2020 g10 Code GmbH * * This file is part of GnuPG. * * This file 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. * * This file 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 General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #ifdef HAVE_LIBREADLINE # define GNUPG_LIBREADLINE_H_INCLUDED # include #endif /*HAVE_LIBREADLINE*/ #define INCLUDED_BY_MAIN_MODULE 1 #include "../common/util.h" #include "../common/status.h" #include "../common/i18n.h" #include "../common/init.h" #include "../common/sysutils.h" #include "../common/asshelp.h" #include "../common/userids.h" #include "../common/ccparray.h" #include "../common/exectool.h" #include "../common/ttyio.h" #include "../common/server-help.h" #include "../common/openpgpdefs.h" #include "../common/tlv.h" #include "gpg-card.h" #define CONTROL_D ('D' - 'A' + 1) +#define HISTORYNAME ".gpg-card_history" + /* Constants to identify the commands and options. */ enum opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oDebug = 500, oGpgProgram, oGpgsmProgram, oStatusFD, oWithColons, oNoAutostart, oAgentProgram, oDisplay, oTTYname, oTTYtype, oXauthority, oLCctype, oLCmessages, oNoKeyLookup, + oNoHistory, oDummy }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (301, ("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", ("verbose")), ARGPARSE_s_n (oQuiet, "quiet", ("be somewhat more quiet")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oGpgProgram, "gpg", "@"), ARGPARSE_s_s (oGpgsmProgram, "gpgsm", "@"), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), ARGPARSE_s_n (oWithColons, "with-colons", "@"), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDisplay, "display", "@"), ARGPARSE_s_s (oTTYname, "ttyname", "@"), ARGPARSE_s_s (oTTYtype, "ttytype", "@"), ARGPARSE_s_s (oXauthority, "xauthority", "@"), ARGPARSE_s_s (oLCctype, "lc-ctype", "@"), ARGPARSE_s_s (oLCmessages, "lc-messages","@"), ARGPARSE_s_n (oNoKeyLookup,"no-key-lookup", "use --no-key-lookup for \"list\""), + ARGPARSE_s_n (oNoHistory,"no-history", + "do not use the command history file"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_IPC_VALUE , "ipc" }, { DBG_EXTPROG_VALUE, "extprog" }, { 0, NULL } }; /* An object to create lists of labels and keyrefs. */ struct keyinfolabel_s { const char *label; const char *keyref; }; typedef struct keyinfolabel_s *keyinfolabel_t; /* Limit of size of data we read from a file for certain commands. */ #define MAX_GET_DATA_FROM_FILE 16384 /* Constants for OpenPGP cards. */ #define OPENPGP_USER_PIN_DEFAULT "123456" #define OPENPGP_ADMIN_PIN_DEFAULT "12345678" #define OPENPGP_KDF_DATA_LENGTH_MIN 90 #define OPENPGP_KDF_DATA_LENGTH_MAX 110 /* Local prototypes. */ static void show_keysize_warning (void); static gpg_error_t dispatch_command (card_info_t info, const char *command); static void interactive_loop (void); #ifdef HAVE_LIBREADLINE static char **command_completion (const char *text, int start, int end); #endif /*HAVE_LIBREADLINE*/ /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "gpg-card"; break; case 12: p = "@GNUPG@"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = ("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = ("Usage: gpg-card" " [options] [{[--] command [args]}] (-h for help)"); break; case 41: p = ("Syntax: gpg-card" " [options] [command [args] {-- command [args]}]\n\n" "Tool to manage cards and tokens. With a command an interactive\n" "mode is used. Use command \"help\" to list all commands."); break; default: p = NULL; break; } 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)); } /* Command line parsing. */ static void parse_arguments (gpgrt_argparse_t *pargs, gpgrt_opt_t *popts) { while (gpgrt_argparse (NULL, pargs, popts)) { switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: if (parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags)) { pargs->r_opt = ARGPARSE_INVALID_ARG; pargs->err = ARGPARSE_PRINT_ERROR; } break; case oGpgProgram: opt.gpg_program = pargs->r.ret_str; break; case oGpgsmProgram: opt.gpgsm_program = pargs->r.ret_str; break; case oAgentProgram: opt.agent_program = pargs->r.ret_str; break; case oStatusFD: gnupg_set_status_fd (translate_sys2libc_fd_int (pargs->r.ret_int, 1)); break; case oWithColons: opt.with_colons = 1; break; case oNoAutostart: opt.autostart = 0; 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 oNoKeyLookup: opt.no_key_lookup = 1; break; + case oNoHistory: opt.no_history = 1; break; default: pargs->err = 2; break; } } } /* gpg-card main. */ int main (int argc, char **argv) { gpg_error_t err; gpgrt_argparse_t pargs; char **command_list = NULL; int cmdidx; char *command; gnupg_reopen_std ("gpg-card"); gpgrt_set_strusage (my_strusage); gnupg_rl_initialize (); log_set_prefix ("gpg-card", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); setup_libassuan_logging (&opt.debug, NULL); /* Setup default options. */ opt.autostart = 1; opt.session_env = session_env_new (); if (!opt.session_env) log_fatal ("error allocating session environment block: %s\n", gpg_strerror (gpg_error_from_syserror ())); /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = ARGPARSE_FLAG_KEEP; parse_arguments (&pargs, opts); gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount (0)) exit (2); /* Set defaults for non given options. */ if (!opt.gpg_program) opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG); if (!opt.gpgsm_program) opt.gpgsm_program = gnupg_module_name (GNUPG_MODULE_NAME_GPGSM); /* Now build the list of commands. We guess the size of the array * by assuming each item is a complete command. Obviously this will * be rarely the case, but it is less code to allocate a possible * too large array. */ command_list = xcalloc (argc+1, sizeof *command_list); cmdidx = 0; command = NULL; while (argc) { for ( ; argc && strcmp (*argv, "--"); argc--, argv++) { if (!command) command = xstrdup (*argv); else { char *tmp = xstrconcat (command, " ", *argv, NULL); xfree (command); command = tmp; } } if (argc) { /* Skip the double dash. */ argc--; argv++; } if (command) { command_list[cmdidx++] = command; command = NULL; } } opt.interactive = !cmdidx; + if (!opt.interactive) + opt.no_history = 1; + if (opt.interactive) { interactive_loop (); err = 0; } else { struct card_info_s info_buffer = { 0 }; card_info_t info = &info_buffer; err = 0; for (cmdidx=0; (command = command_list[cmdidx]); cmdidx++) { err = dispatch_command (info, command); if (err) break; } if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; /* This was a "quit". */ else if (command && !opt.quiet) log_info ("stopped at command '%s'\n", command); } flush_keyblock_cache (); if (command_list) { for (cmdidx=0; command_list[cmdidx]; cmdidx++) xfree (command_list[cmdidx]); xfree (command_list); } if (err) gnupg_status_printf (STATUS_FAILURE, "- %u", err); else if (log_get_errorcount (0)) gnupg_status_printf (STATUS_FAILURE, "- %u", GPG_ERR_GENERAL); else gnupg_status_printf (STATUS_SUCCESS, NULL); return log_get_errorcount (0)? 1:0; } /* Read data from file FNAME up to MAX_GET_DATA_FROM_FILE characters. * On error return an error code and stores NULL at R_BUFFER; on * success returns 0 and stores the number of bytes read at R_BUFLEN * and the address of a newly allocated buffer at R_BUFFER. A * complementary nul byte is always appended to the data but not * counted; this allows to pass NULL for R-BUFFER and consider the * returned data as a string. */ static gpg_error_t get_data_from_file (const char *fname, char **r_buffer, size_t *r_buflen) { gpg_error_t err; estream_t fp; char *data; int n; *r_buffer = NULL; if (r_buflen) *r_buflen = 0; fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); return err; } data = xtrymalloc (MAX_GET_DATA_FROM_FILE); if (!data) { err = gpg_error_from_syserror (); log_error (_("error allocating enough memory: %s\n"), gpg_strerror (err)); es_fclose (fp); return err; } n = es_fread (data, 1, MAX_GET_DATA_FROM_FILE - 1, fp); es_fclose (fp); if (n < 0) { err = gpg_error_from_syserror (); tty_printf (_("error reading '%s': %s\n"), fname, gpg_strerror (err)); xfree (data); return err; } data[n] = 0; *r_buffer = data; if (r_buflen) *r_buflen = n; return 0; } /* Fixup the ENODEV error from scdaemon which we may see after * removing a card due to scdaemon scanning for readers with cards. * We also map the CAERD REMOVED error to the more useful CARD_NOT * PRESENT. */ static gpg_error_t fixup_scd_errors (gpg_error_t err) { if ((gpg_err_code (err) == GPG_ERR_ENODEV || gpg_err_code (err) == GPG_ERR_CARD_REMOVED) && gpg_err_source (err) == GPG_ERR_SOURCE_SCD) err = gpg_error (GPG_ERR_CARD_NOT_PRESENT); return err; } /* Set the card removed flag from INFO depending on ERR. This does * not clear the flag. */ static gpg_error_t maybe_set_card_removed (card_info_t info, gpg_error_t err) { if ((gpg_err_code (err) == GPG_ERR_ENODEV || gpg_err_code (err) == GPG_ERR_CARD_REMOVED) && gpg_err_source (err) == GPG_ERR_SOURCE_SCD) info->card_removed = 1; return err; } /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on * success. */ static gpg_error_t put_data_to_file (const char *fname, const void *buffer, size_t length) { gpg_error_t err; estream_t fp; fp = es_fopen (fname, "wb"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't create '%s': %s\n"), fname, gpg_strerror (err)); return err; } if (length && es_fwrite (buffer, length, 1, fp) != 1) { err = gpg_error_from_syserror (); log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err)); es_fclose (fp); return err; } if (es_fclose (fp)) { err = gpg_error_from_syserror (); log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err)); return err; } return 0; } /* Return a malloced string with the number opf the menu PROMPT. * Control-D is mapped to "Q". */ static char * get_selection (const char *prompt) { char *answer; tty_printf ("\n"); tty_printf ("%s", prompt); tty_printf ("\n"); answer = tty_get (_("Your selection? ")); tty_kill_prompt (); if (*answer == CONTROL_D) strcpy (answer, "q"); return answer; } /* Simply prints TEXT to the output. Returns 0 as a convenience. * This is a separate function so that it can be extended to run * less(1) or so. The extra arguments are int values terminated by a * 0 to indicate card application types supported with this command. * If none are given (just the final 0), this is a general * command. */ static gpg_error_t print_help (const char *text, ...) { estream_t fp; va_list arg_ptr; int value; int any = 0; fp = opt.interactive? NULL : es_stdout; tty_fprintf (fp, "%s\n", text); va_start (arg_ptr, text); while ((value = va_arg (arg_ptr, int))) { if (!any) tty_fprintf (fp, "[Supported by: "); tty_fprintf (fp, "%s%s", any?", ":"", app_type_string (value)); any = 1; } if (any) tty_fprintf (fp, "]\n"); va_end (arg_ptr); return 0; } /* Print an (OpenPGP) fingerprint. */ static void print_shax_fpr (estream_t fp, const unsigned char *fpr, unsigned int fprlen) { int i; if (fpr) { for (i=0; i < fprlen ; i++, fpr++) tty_fprintf (fp, "%02X", *fpr); } else tty_fprintf (fp, " [none]"); tty_fprintf (fp, "\n"); } /* Print the keygrip GRP. */ static void print_keygrip (estream_t fp, const unsigned char *grp) { int i; for (i=0; i < 20 ; i++, grp++) tty_fprintf (fp, "%02X", *grp); tty_fprintf (fp, "\n"); } /* Print a string but avoid printing control characters. */ static void print_string (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_buffer2 (fp, name, strlen (name), '\n'); else tty_print_utf8_string2 (NULL, name, strlen (name), 0); } else tty_fprintf (fp, _("[not set]")); tty_fprintf (fp, "\n"); } /* Print an ISO formatted name or "[not set]". */ static void print_isoname (estream_t fp, const char *name) { if (name && *name) { char *p, *given, *buf; buf = xstrdup (name); given = strstr (buf, "<<"); for (p=buf; *p; p++) if (*p == '<') *p = ' '; if (given && given[2]) { *given = 0; given += 2; if (fp) print_utf8_buffer2 (fp, given, strlen (given), '\n'); else tty_print_utf8_string2 (NULL, given, strlen (given), 0); if (*buf) tty_fprintf (fp, " "); } if (fp) print_utf8_buffer2 (fp, buf, strlen (buf), '\n'); else tty_print_utf8_string2 (NULL, buf, strlen (buf), 0); xfree (buf); } else { tty_fprintf (fp, _("[not set]")); } tty_fprintf (fp, "\n"); } /* Return true if the buffer MEM of length memlen consists only of zeroes. */ static int mem_is_zero (const char *mem, unsigned int memlen) { int i; for (i=0; i < memlen && !mem[i]; i++) ; return (i == memlen); } /* Helper to list a single keyref. LABEL_KEYREF is a fallback key * reference if no info is available; it may be NULL. */ static void list_one_kinfo (card_info_t info, key_info_t kinfo, const char *label_keyref, estream_t fp, int no_key_lookup) { gpg_error_t err; key_info_t firstkinfo = info->kinfo; keyblock_t keyblock = NULL; keyblock_t kb; pubkey_t pubkey; userid_t uid; key_info_t ki; const char *s; gcry_sexp_t s_pkey; int any; if (firstkinfo && kinfo) { tty_fprintf (fp, " "); if (mem_is_zero (kinfo->grip, sizeof kinfo->grip)) { tty_fprintf (fp, "[none]\n"); tty_fprintf (fp, " keyref .....: %s\n", kinfo->keyref); tty_fprintf (fp, " algorithm ..: %s\n", kinfo->keyalgo); goto leave; } print_keygrip (fp, kinfo->grip); tty_fprintf (fp, " keyref .....: %s", kinfo->keyref); if (kinfo->usage) { any = 0; tty_fprintf (fp, " ("); if ((kinfo->usage & GCRY_PK_USAGE_SIGN)) { tty_fprintf (fp, "sign"); any=1; } if ((kinfo->usage & GCRY_PK_USAGE_CERT)) { tty_fprintf (fp, "%scert", any?",":""); any=1; } if ((kinfo->usage & GCRY_PK_USAGE_AUTH)) { tty_fprintf (fp, "%sauth", any?",":""); any=1; } if ((kinfo->usage & GCRY_PK_USAGE_ENCR)) { tty_fprintf (fp, "%sencr", any?",":""); any=1; } tty_fprintf (fp, ")"); } tty_fprintf (fp, "\n"); if (!(err = scd_readkey (kinfo->keyref, &s_pkey))) { char *tmp = pubkey_algo_string (s_pkey, NULL); tty_fprintf (fp, " algorithm ..: %s\n", tmp); xfree (tmp); gcry_sexp_release (s_pkey); s_pkey = NULL; } else { maybe_set_card_removed (info, err); tty_fprintf (fp, " algorithm ..: %s\n", kinfo->keyalgo); } if (kinfo->fprlen && kinfo->created) { tty_fprintf (fp, " stored fpr .: "); print_shax_fpr (fp, kinfo->fpr, kinfo->fprlen); tty_fprintf (fp, " created ....: %s\n", isotimestamp (kinfo->created)); } if (no_key_lookup) err = 0; else err = get_matching_keys (kinfo->grip, (GNUPG_PROTOCOL_OPENPGP | GNUPG_PROTOCOL_CMS), &keyblock); if (err) { if (gpg_err_code (err) != GPG_ERR_NO_PUBKEY) tty_fprintf (fp, " error ......: %s\n", gpg_strerror (err)); goto leave; } for (kb = keyblock; kb; kb = kb->next) { tty_fprintf (fp, " used for ...: %s\n", kb->protocol == GNUPG_PROTOCOL_OPENPGP? "OpenPGP" : kb->protocol == GNUPG_PROTOCOL_CMS? "X.509" : "?"); pubkey = kb->keys; if (kb->protocol == GNUPG_PROTOCOL_OPENPGP) { /* If this is not the primary key print the primary * key's fingerprint or a reference to it. */ tty_fprintf (fp, " main key .: "); for (ki=firstkinfo; ki; ki = ki->next) if (pubkey->grip_valid && !memcmp (ki->grip, pubkey->grip, KEYGRIP_LEN)) break; if (ki) { /* Fixme: Replace mapping by a table lookup. */ if (!memcmp (kinfo->grip, pubkey->grip, KEYGRIP_LEN)) s = "this"; else if (!strcmp (ki->keyref, "OPENPGP.1")) s = "Signature key"; else if (!strcmp (ki->keyref, "OPENPGP.2")) s = "Encryption key"; else if (!strcmp (ki->keyref, "OPENPGP.3")) s = "Authentication key"; else s = NULL; if (s) tty_fprintf (fp, "<%s>\n", s); else tty_fprintf (fp, "\n", ki->keyref); } else /* Print the primary key as fallback. */ print_shax_fpr (fp, pubkey->fpr, pubkey->fprlen); /* Find the primary or subkey of that key. */ for (; pubkey; pubkey = pubkey->next) if (pubkey->grip_valid && !memcmp (kinfo->grip, pubkey->grip, KEYGRIP_LEN)) break; if (pubkey) { tty_fprintf (fp, " fpr ......: "); print_shax_fpr (fp, pubkey->fpr, pubkey->fprlen); tty_fprintf (fp, " created ..: %s\n", isotimestamp (pubkey->created)); } } for (uid = kb->uids; uid; uid = uid->next) { print_string (fp, " user id ..: ", uid->value); } } } else { tty_fprintf (fp, " [none]\n"); if (label_keyref) tty_fprintf (fp, " keyref .....: %s\n", label_keyref); if (kinfo) tty_fprintf (fp, " algorithm ..: %s\n", kinfo->keyalgo); } leave: release_keyblock (keyblock); } /* List all keyinfo in INFO using the list of LABELS. */ static void list_all_kinfo (card_info_t info, keyinfolabel_t labels, estream_t fp, int no_key_lookup) { key_info_t kinfo; int idx, i, j; /* Print the keyinfo. We first print those we known and then all * remaining item. */ for (kinfo = info->kinfo; kinfo; kinfo = kinfo->next) kinfo->xflag = 0; if (labels) { for (idx=0; labels[idx].label; idx++) { tty_fprintf (fp, "%s", labels[idx].label); kinfo = find_kinfo (info, labels[idx].keyref); list_one_kinfo (info, kinfo, labels[idx].keyref, fp, no_key_lookup); if (kinfo) kinfo->xflag = 1; } } for (kinfo = info->kinfo; kinfo; kinfo = kinfo->next) { if (kinfo->xflag) continue; tty_fprintf (fp, "Key %s", kinfo->keyref); for (i=4+strlen (kinfo->keyref), j=0; i < 18; i++, j=1) tty_fprintf (fp, j? ".":" "); tty_fprintf (fp, ":"); list_one_kinfo (info, kinfo, NULL, fp, no_key_lookup); } } /* List OpenPGP card specific data. */ static void list_openpgp (card_info_t info, estream_t fp, int no_key_lookup) { static struct keyinfolabel_s keyinfolabels[] = { { "Signature key ....:", "OPENPGP.1" }, { "Encryption key....:", "OPENPGP.2" }, { "Authentication key:", "OPENPGP.3" }, { NULL, NULL } }; if (!info->serialno || strncmp (info->serialno, "D27600012401", 12) || strlen (info->serialno) != 32 ) { tty_fprintf (fp, "invalid OpenPGP card\n"); return; } tty_fprintf (fp, "Name of cardholder: "); print_isoname (fp, info->disp_name); print_string (fp, "Language prefs ...: ", info->disp_lang); tty_fprintf (fp, "Salutation .......: %s\n", info->disp_sex == 1? _("Mr."): info->disp_sex == 2? _("Ms.") : ""); print_string (fp, "URL of public key : ", info->pubkey_url); print_string (fp, "Login data .......: ", info->login_data); if (info->private_do[0]) print_string (fp, "Private DO 1 .....: ", info->private_do[0]); if (info->private_do[1]) print_string (fp, "Private DO 2 .....: ", info->private_do[1]); if (info->private_do[2]) print_string (fp, "Private DO 3 .....: ", info->private_do[2]); if (info->private_do[3]) print_string (fp, "Private DO 4 .....: ", info->private_do[3]); if (info->cafpr1len) { tty_fprintf (fp, "CA fingerprint %d .:", 1); print_shax_fpr (fp, info->cafpr1, info->cafpr1len); } if (info->cafpr2len) { tty_fprintf (fp, "CA fingerprint %d .:", 2); print_shax_fpr (fp, info->cafpr2, info->cafpr2len); } if (info->cafpr3len) { tty_fprintf (fp, "CA fingerprint %d .:", 3); print_shax_fpr (fp, info->cafpr3, info->cafpr3len); } tty_fprintf (fp, "Signature PIN ....: %s\n", info->chv1_cached? _("not forced"): _("forced")); 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->chvinfo[0], info->chvinfo[1], info->chvinfo[2]); tty_fprintf (fp, "Signature counter : %lu\n", info->sig_counter); tty_fprintf (fp, "Capabilities .....:"); if (info->extcap.ki) tty_fprintf (fp, " key-import"); if (info->extcap.aac) tty_fprintf (fp, " algo-change"); if (info->extcap.bt) tty_fprintf (fp, " button"); if (info->extcap.sm) tty_fprintf (fp, " sm(%s)", gcry_cipher_algo_name (info->extcap.smalgo)); if (info->extcap.private_dos) tty_fprintf (fp, " priv-data"); tty_fprintf (fp, "\n"); if (info->extcap.kdf) { tty_fprintf (fp, "KDF setting ......: %s\n", info->kdf_do_enabled ? "on" : "off"); } if (info->extcap.bt) { tty_fprintf (fp, "UIF setting ......: Sign=%s Decrypt=%s Auth=%s\n", info->uif[0] ? (info->uif[0]==2? "permanent": "on") : "off", info->uif[1] ? (info->uif[0]==2? "permanent": "on") : "off", info->uif[2] ? (info->uif[0]==2? "permanent": "on") : "off"); } list_all_kinfo (info, keyinfolabels, fp, no_key_lookup); } /* List PIV card specific data. */ static void list_piv (card_info_t info, estream_t fp, int no_key_lookup) { static struct keyinfolabel_s keyinfolabels[] = { { "PIV authentication:", "PIV.9A" }, { "Card authenticat. :", "PIV.9E" }, { "Digital signature :", "PIV.9C" }, { "Key management ...:", "PIV.9D" }, { NULL, NULL } }; const char *s; int i; if (info->chvusage[0] || info->chvusage[1]) { tty_fprintf (fp, "PIN usage policy .:"); if ((info->chvusage[0] & 0x40)) tty_fprintf (fp, " app-pin"); if ((info->chvusage[0] & 0x20)) tty_fprintf (fp, " global-pin"); if ((info->chvusage[0] & 0x10)) tty_fprintf (fp, " occ"); if ((info->chvusage[0] & 0x08)) tty_fprintf (fp, " vci"); if ((info->chvusage[0] & 0x08) && !(info->chvusage[0] & 0x04)) tty_fprintf (fp, " pairing"); if (info->chvusage[1] == 0x10) tty_fprintf (fp, " primary:card"); else if (info->chvusage[1] == 0x20) tty_fprintf (fp, " primary:global"); tty_fprintf (fp, "\n"); } tty_fprintf (fp, "PIN retry counter :"); for (i=0; i < DIM (info->chvinfo); i++) { if (info->chvinfo[i] > 0) tty_fprintf (fp, " %d", info->chvinfo[i]); else { switch (info->chvinfo[i]) { case -1: s = "[error]"; break; case -2: s = "-"; break; /* No such PIN or info not available. */ case -3: s = "[blocked]"; break; case -5: s = "[verified]"; break; default: s = "[?]"; break; } tty_fprintf (fp, " %s", s); } } tty_fprintf (fp, "\n"); list_all_kinfo (info, keyinfolabels, fp, no_key_lookup); } /* List Netkey card specific data. */ static void list_nks (card_info_t info, estream_t fp, int no_key_lookup) { static struct keyinfolabel_s keyinfolabels[] = { { NULL, NULL } }; const char *s; int i; tty_fprintf (fp, "PIN retry counter :"); for (i=0; i < DIM (info->chvinfo); i++) { if (info->chvinfo[i] >= 0) tty_fprintf (fp, " %d", info->chvinfo[i]); else { switch (info->chvinfo[i]) { case -1: s = "[error]"; break; case -2: s = "-"; break; /* No such PIN or info not available. */ case -3: s = "[blocked]"; break; case -4: s = "[nullpin]"; break; case -5: s = "[verified]"; break; default: s = "[?]"; break; } tty_fprintf (fp, " %s", s); } } tty_fprintf (fp, "\n"); list_all_kinfo (info, keyinfolabels, fp, no_key_lookup); } static void print_a_version (estream_t fp, const char *prefix, unsigned int value) { unsigned int a, b, c, d; a = ((value >> 24) & 0xff); b = ((value >> 16) & 0xff); c = ((value >> 8) & 0xff); d = ((value ) & 0xff); if (a) tty_fprintf (fp, "%s %u.%u.%u.%u\n", prefix, a, b, c, d); else if (b) tty_fprintf (fp, "%s %u.%u.%u\n", prefix, b, c, d); else if (c) tty_fprintf (fp, "%s %u.%u\n", prefix, c, d); else tty_fprintf (fp, "%s %u\n", prefix, d); } /* Print all available information about the current card. With * NO_KEY_LOOKUP the sometimes expensive listing of all matching * OpenPGP and X.509 keys is not done */ static void list_card (card_info_t info, int no_key_lookup) { estream_t fp = opt.interactive? NULL : es_stdout; tty_fprintf (fp, "Reader ...........: %s\n", info->reader? info->reader : "[none]"); if (info->cardtype) tty_fprintf (fp, "Card type ........: %s\n", info->cardtype); if (info->cardversion) print_a_version (fp, "Card firmware ....:", info->cardversion); tty_fprintf (fp, "Serial number ....: %s\n", info->serialno? info->serialno : "[none]"); tty_fprintf (fp, "Application type .: %s%s%s%s\n", app_type_string (info->apptype), info->apptype == APP_TYPE_UNKNOWN && info->apptypestr? "(":"", info->apptype == APP_TYPE_UNKNOWN && info->apptypestr ? info->apptypestr:"", info->apptype == APP_TYPE_UNKNOWN && info->apptypestr? ")":""); if (info->appversion) print_a_version (fp, "Version ..........:", info->appversion); if (info->serialno && info->dispserialno && strcmp (info->serialno, info->dispserialno)) tty_fprintf (fp, "Displayed s/n ....: %s\n", info->dispserialno); if (info->manufacturer_name && info->manufacturer_id) tty_fprintf (fp, "Manufacturer .....: %s (%x)\n", info->manufacturer_name, info->manufacturer_id); else if (info->manufacturer_name && !info->manufacturer_id) tty_fprintf (fp, "Manufacturer .....: %s\n", info->manufacturer_name); else if (info->manufacturer_id) tty_fprintf (fp, "Manufacturer .....: (%x)\n", info->manufacturer_id); switch (info->apptype) { case APP_TYPE_OPENPGP: list_openpgp (info, fp, no_key_lookup); break; case APP_TYPE_PIV: list_piv (info, fp, no_key_lookup); break; case APP_TYPE_NKS: list_nks (info, fp, no_key_lookup); break; default: break; } } /* Helper for cmd_list. */ static void print_card_list (estream_t fp, card_info_t info, strlist_t cards, int only_current) { int count; strlist_t sl; size_t snlen; int star; const char *s; for (count = 0, sl = cards; sl; sl = sl->next, count++) { if (info && info->serialno) { s = strchr (sl->d, ' '); if (s) snlen = s - sl->d; else snlen = strlen (sl->d); star = (strlen (info->serialno) == snlen && !memcmp (info->serialno, sl->d, snlen)); } else star = 0; if (!only_current || star) tty_fprintf (fp, "%d%c %s\n", count, star? '*':' ', sl->d); } } /* The LIST command. This also updates INFO if needed. */ static gpg_error_t cmd_list (card_info_t info, char *argstr) { gpg_error_t err; int opt_cards, opt_apps, opt_info, opt_no_key_lookup; strlist_t cards = NULL; strlist_t sl; estream_t fp = opt.interactive? NULL : es_stdout; const char *cardsn = NULL; char *appstr = NULL; int count; int need_learn = 0; if (!info) return print_help ("LIST [--cards] [--apps] [--info] [--no-key-lookup] [N] [APP]\n\n" "Show the content of the current card.\n" "With N given select and list the N-th card;\n" "with APP also given select that application.\n" "To select an APP on the current card use '-' for N.\n" "The S/N of the card may be used instead of N.\n" " --cards lists available cards\n" " --apps lists additional card applications\n" " --info selects a card and prints its s/n\n" " --no-key-lookup does not list matching OpenPGP or X.509 keys\n" , 0); opt_cards = has_leading_option (argstr, "--cards"); opt_apps = has_leading_option (argstr, "--apps"); opt_info = has_leading_option (argstr, "--info"); opt_no_key_lookup = has_leading_option (argstr, "--no-key-lookup"); argstr = skip_options (argstr); if (opt.no_key_lookup) opt_no_key_lookup = 1; if (hexdigitp (argstr) || (*argstr == '-' && spacep (argstr+1))) { if (*argstr == '-' && (argstr[1] || spacep (argstr+1))) argstr++; /* Keep current card. */ else { cardsn = argstr; while (hexdigitp (argstr)) argstr++; if (*argstr && !spacep (argstr)) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } if (*argstr) *argstr++ = 0; } while (spacep (argstr)) argstr++; if (*argstr) { appstr = argstr; while (*argstr && !spacep (argstr)) argstr++; while (spacep (argstr)) argstr++; if (*argstr) { /* Extra arguments found. */ err = gpg_error (GPG_ERR_INV_ARG); goto leave; } } } else if (*argstr) { /* First argument needs to be a digit. */ err = gpg_error (GPG_ERR_INV_ARG); goto leave; } if (!info->serialno || info->need_sn_cmd) { /* This is probably the first call or was explictly requested. * We need to send a SERIALNO command to scdaemon so that our * session knows all cards. */ err = scd_serialno (NULL, NULL); if (err) goto leave; info->need_sn_cmd = 0; need_learn = 1; } if (opt_cards || opt_apps) { /* Note that with option --apps CARDS is here the list of all * apps. Format is "SERIALNO APPNAME {APPNAME}". We print the * card number in the first column. */ if (opt_apps) err = scd_applist (&cards, opt_cards); else err = scd_cardlist (&cards); if (err) goto leave; print_card_list (fp, info, cards, 0); } else { if (cardsn) { int i, cardno; err = scd_cardlist (&cards); if (err) goto leave; /* Switch to the requested card. */ for (i=0; digitp (cardsn+i); i++) ; if (i && i < 4 && !cardsn[i]) { /* Looks like an index into the card list. */ cardno = atoi (cardsn); for (count = 0, sl = cards; sl; sl = sl->next, count++) if (count == cardno) break; if (!sl) { err = gpg_error (GPG_ERR_INV_INDEX); goto leave; } } else /* S/N of card specified. */ { for (sl = cards; sl; sl = sl->next) if (!ascii_strcasecmp (sl->d, cardsn)) break; if (!sl) { err = gpg_error (GPG_ERR_INV_INDEX); goto leave; } } err = scd_switchcard (sl->d); need_learn = 1; } else /* show app list. */ { err = scd_applist (&cards, 1); if (err) goto leave; } if (appstr && *appstr) { /* Switch to the requested app. */ err = scd_switchapp (appstr); if (err) goto leave; need_learn = 1; } if (need_learn) err = scd_learn (info); else err = 0; if (err) ; else if (opt_info) print_card_list (fp, info, cards, 1); else { size_t snlen; const char *s; /* First get the list of active cards and check whether the * current card is still in the list. If not the card has * been removed. Note that during the listing the card * remove state might also be detected but only if an access * to the scdaemon is required; it is anyway better to test * that before starting a listing. */ free_strlist (cards); err = scd_cardlist (&cards); if (err) goto leave; for (sl = cards; sl; sl = sl->next) { if (info && info->serialno) { s = strchr (sl->d, ' '); if (s) snlen = s - sl->d; else snlen = strlen (sl->d); if (strlen (info->serialno) == snlen && !memcmp (info->serialno, sl->d, snlen)) break; } } if (!sl) { info->need_sn_cmd = 1; err = gpg_error (GPG_ERR_CARD_REMOVED); goto leave; } list_card (info, opt_no_key_lookup); } } leave: free_strlist (cards); return err; } /* The VERIFY command. */ static gpg_error_t cmd_verify (card_info_t info, char *argstr) { gpg_error_t err; const char *pinref; if (!info) return print_help ("verify [chvid]", 0); if (*argstr) pinref = argstr; else if (info->apptype == APP_TYPE_OPENPGP) pinref = info->serialno; else if (info->apptype == APP_TYPE_PIV) pinref = "PIV.80"; else return gpg_error (GPG_ERR_MISSING_VALUE); err = scd_checkpin (pinref); if (err) log_error ("verify failed: %s <%s>\n", gpg_strerror (err), gpg_strsource (err)); return err; } static gpg_error_t cmd_authenticate (card_info_t info, char *argstr) { gpg_error_t err; int opt_setkey; int opt_raw; char *string = NULL; char *key = NULL; size_t keylen; if (!info) return print_help ("AUTHENTICATE [--setkey] [--raw] [< FILE]|KEY\n\n" "Perform a mutual authentication either by reading the key\n" "from FILE or by taking it from the command line. Without\n" "the option --raw the key is expected to be hex encoded.\n" "To install a new administration key --setkey is used; this\n" "requires a prior authentication with the old key.", APP_TYPE_PIV, 0); if (info->apptype != APP_TYPE_PIV) { log_info ("Note: This is a PIV only command.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } opt_setkey = has_leading_option (argstr, "--setkey"); opt_raw = has_leading_option (argstr, "--raw"); argstr = skip_options (argstr); if (*argstr == '<') /* Read key from a file. */ { for (argstr++; spacep (argstr); argstr++) ; err = get_data_from_file (argstr, &string, NULL); if (err) goto leave; } if (opt_raw) { key = string? string : xstrdup (argstr); string = NULL; keylen = strlen (key); } else { key = hex_to_buffer (string? string: argstr, &keylen); if (!key) { err = gpg_error_from_syserror (); goto leave; } } err = scd_setattr (opt_setkey? "SET-ADM-KEY":"AUTH-ADM-KEY", key, keylen); leave: if (key) { wipememory (key, keylen); xfree (key); } xfree (string); return err; } /* Helper for cmd_name to qyery a part of name. */ static char * ask_one_name (const char *prompt) { char *name; int i; for (;;) { name = tty_get (prompt); trim_spaces (name); tty_kill_prompt (); if (!*name || *name == CONTROL_D) { if (*name == CONTROL_D) tty_fprintf (NULL, "\n"); xfree (name); return NULL; } 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); } } /* The NAME command. */ static gpg_error_t cmd_name (card_info_t info, const char *argstr) { gpg_error_t err; char *surname, *givenname; char *isoname, *p; if (!info) return print_help ("name [--clear]\n\n" "Set the name field of an OpenPGP card. With --clear the stored\n" "name is cleared off the card.", APP_TYPE_OPENPGP, APP_TYPE_NKS, 0); if (info->apptype != APP_TYPE_OPENPGP) { log_info ("Note: This is an OpenPGP only command.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } again: if (!strcmp (argstr, "--clear")) isoname = xstrdup (" "); /* No real way to clear; set to space instead. */ else { surname = ask_one_name (_("Cardholder's surname: ")); givenname = ask_one_name (_("Cardholder's given name: ")); if (!surname || !givenname || (!*surname && !*givenname)) { xfree (surname); xfree (givenname); return gpg_error (GPG_ERR_CANCELED); } isoname = xstrconcat (surname, "<<", givenname, NULL); xfree (surname); xfree (givenname); for (p=isoname; *p; p++) if (*p == ' ') *p = '<'; if (strlen (isoname) > 39 ) { log_info (_("Error: Combined name too long " "(limit is %d characters).\n"), 39); xfree (isoname); goto again; } } err = scd_setattr ("DISP-NAME", isoname, strlen (isoname)); xfree (isoname); return err; } static gpg_error_t cmd_url (card_info_t info, const char *argstr) { gpg_error_t err; char *url; if (!info) return print_help ("URL [--clear]\n\n" "Set the URL data object. That data object can be used by\n" "the FETCH command to retrieve the full public key. The\n" "option --clear deletes the content of that data object.", APP_TYPE_OPENPGP, 0); if (info->apptype != APP_TYPE_OPENPGP) { log_info ("Note: This is an OpenPGP only command.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } if (!strcmp (argstr, "--clear")) url = xstrdup (" "); /* No real way to clear; set to space instead. */ else { url = tty_get (_("URL to retrieve public key: ")); trim_spaces (url); tty_kill_prompt (); if (!*url || *url == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } } err = scd_setattr ("PUBKEY-URL", url, strlen (url)); leave: xfree (url); return err; } /* Fetch the key from the URL given on the card or try to get it from * the default keyserver. */ static gpg_error_t cmd_fetch (card_info_t info) { gpg_error_t err; key_info_t kinfo; if (!info) return print_help ("FETCH\n\n" "Retrieve a key using the URL data object or if that is missing\n" "using the fingerprint.", APP_TYPE_OPENPGP, 0); if (info->pubkey_url && *info->pubkey_url) { /* strlist_t sl = NULL; */ /* add_to_strlist (&sl, info.pubkey_url); */ /* err = keyserver_fetch (ctrl, sl, KEYORG_URL); */ /* free_strlist (sl); */ err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); /* FIXME */ } else if ((kinfo = find_kinfo (info, "OPENPGP.1")) && kinfo->fprlen) { /* rc = keyserver_import_fprint (ctrl, info.fpr1, info.fpr1len, */ /* opt.keyserver, 0); */ err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); /* FIXME */ } else err = gpg_error (GPG_ERR_NO_DATA); return err; } static gpg_error_t cmd_login (card_info_t info, char *argstr) { gpg_error_t err; char *data; size_t datalen; if (!info) return print_help ("LOGIN [--clear] [< FILE]\n\n" "Set the login data object. If FILE is given the data is\n" "is read from that file. This allows for binary data.\n" "The option --clear deletes the login data.", APP_TYPE_OPENPGP, 0); if (!strcmp (argstr, "--clear")) { data = xstrdup (" "); /* kludge. */ datalen = 1; } else if (*argstr == '<') /* Read it from a file */ { for (argstr++; spacep (argstr); argstr++) ; err = get_data_from_file (argstr, &data, &datalen); if (err) goto leave; } else { data = tty_get (_("Login data (account name): ")); trim_spaces (data); tty_kill_prompt (); if (!*data || *data == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } datalen = strlen (data); } err = scd_setattr ("LOGIN-DATA", data, datalen); leave: xfree (data); return err; } static gpg_error_t cmd_lang (card_info_t info, const char *argstr) { gpg_error_t err; char *data, *p; if (!info) return print_help ("LANG [--clear]\n\n" "Change the language info for the card. This info can be used\n" "by applications for a personalized greeting. Up to 4 two-digit\n" "language identifiers can be entered as a preference. The option\n" "--clear removes all identifiers. GnuPG does not use this info.", APP_TYPE_OPENPGP, 0); if (!strcmp (argstr, "--clear")) data = xstrdup (" "); /* Note that we need two spaces here. */ else { again: data = tty_get (_("Language preferences: ")); trim_spaces (data); tty_kill_prompt (); if (!*data || *data == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } if (strlen (data) > 8 || (strlen (data) & 1)) { log_info (_("Error: invalid length of preference string.\n")); xfree (data); goto again; } for (p=data; *p && *p >= 'a' && *p <= 'z'; p++) ; if (*p) { log_info (_("Error: invalid characters in preference string.\n")); xfree (data); goto again; } } err = scd_setattr ("DISP-LANG", data, strlen (data)); leave: xfree (data); return err; } static gpg_error_t cmd_salut (card_info_t info, const char *argstr) { gpg_error_t err; char *data = NULL; const char *str; if (!info) return print_help ("SALUT [--clear]\n\n" "Change the salutation info for the card. This info can be used\n" "by applications for a personalized greeting. The option --clear\n" "removes this data object. GnuPG does not use this info.", APP_TYPE_OPENPGP, 0); again: if (!strcmp (argstr, "--clear")) str = "9"; else { data = tty_get (_("Salutation (M = Mr., F = Ms., or space): ")); trim_spaces (data); tty_kill_prompt (); if (*data == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } 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); goto again; } } err = scd_setattr ("DISP-SEX", str, 1); leave: xfree (data); return err; } static gpg_error_t cmd_cafpr (card_info_t info, char *argstr) { gpg_error_t err; char *data = NULL; const char *s; int i, c; unsigned char fpr[32]; int fprlen; int fprno; int opt_clear = 0; if (!info) return print_help ("CAFPR [--clear] N\n\n" "Change the CA fingerprint number N. N must be in the\n" "range 1 to 3. The option --clear clears the specified\n" "CA fingerprint N or all of them if N is 0 or not given.", APP_TYPE_OPENPGP, 0); opt_clear = has_leading_option (argstr, "--clear"); argstr = skip_options (argstr); if (digitp (argstr)) { fprno = atoi (argstr); while (digitp (argstr)) argstr++; while (spacep (argstr)) argstr++; } else fprno = 0; if (opt_clear && !fprno) ; /* Okay: clear all fprs. */ else if (fprno < 1 || fprno > 3) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } again: if (opt_clear) { memset (fpr, 0, 20); fprlen = 20; } else { xfree (data); data = tty_get (_("CA fingerprint: ")); trim_spaces (data); tty_kill_prompt (); if (!*data || *data == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } for (i=0, s=data; i < sizeof fpr && *s; ) { while (spacep(s)) s++; if (*s == ':') s++; while (spacep(s)) s++; c = hextobyte (s); if (c == -1) break; fpr[i++] = c; s += 2; } fprlen = i; if ((fprlen != 20 && fprlen != 32) || *s) { log_error (_("Error: invalid formatted fingerprint.\n")); goto again; } } if (!fprno) { log_assert (opt_clear); err = scd_setattr ("CA-FPR-1", fpr, fprlen); if (!err) err = scd_setattr ("CA-FPR-2", fpr, fprlen); if (!err) err = scd_setattr ("CA-FPR-3", fpr, fprlen); } else err = scd_setattr (fprno==1?"CA-FPR-1": fprno==2?"CA-FPR-2": fprno==3?"CA-FPR-3":"x", fpr, fprlen); leave: xfree (data); return err; } static gpg_error_t cmd_privatedo (card_info_t info, char *argstr) { gpg_error_t err; int opt_clear; char *do_name = NULL; char *data = NULL; size_t datalen; int do_no; if (!info) return print_help ("PRIVATEDO [--clear] N [< FILE]\n\n" "Change the private data object N. N must be in the\n" "range 1 to 4. If FILE is given the data is is read\n" "from that file. The option --clear clears the data.", APP_TYPE_OPENPGP, 0); opt_clear = has_leading_option (argstr, "--clear"); argstr = skip_options (argstr); if (digitp (argstr)) { do_no = atoi (argstr); while (digitp (argstr)) argstr++; while (spacep (argstr)) argstr++; } else do_no = 0; if (do_no < 1 || do_no > 4) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } do_name = xasprintf ("PRIVATE-DO-%d", do_no); if (opt_clear) { data = xstrdup (" "); datalen = 1; } else if (*argstr == '<') /* Read it from a file */ { for (argstr++; spacep (argstr); argstr++) ; err = get_data_from_file (argstr, &data, &datalen); if (err) goto leave; } else if (*argstr) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } else { data = tty_get (_("Private DO data: ")); trim_spaces (data); tty_kill_prompt (); datalen = strlen (data); if (!*data || *data == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } } err = scd_setattr (do_name, data, datalen); leave: xfree (do_name); xfree (data); return err; } static gpg_error_t cmd_writecert (card_info_t info, char *argstr) { gpg_error_t err; int opt_clear; int opt_openpgp; char *certref_buffer = NULL; char *certref; char *data = NULL; size_t datalen; estream_t key = NULL; if (!info) return print_help ("WRITECERT CERTREF '<' FILE\n" "WRITECERT --openpgp CERTREF ['<' FILE|FPR]\n" "WRITECERT --clear CERTREF\n\n" "Write a certificate for key 3. The option --clear removes\n" "the certificate from the card. The option --openpgp expects\n" "a keyblock and stores it encapsulated in a CMS container; the\n" "keyblock is taken from FILE or directly from the key with FPR", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); opt_clear = has_leading_option (argstr, "--clear"); opt_openpgp = has_leading_option (argstr, "--openpgp"); argstr = skip_options (argstr); certref = argstr; if ((argstr = strchr (certref, ' '))) { *argstr++ = 0; trim_spaces (certref); trim_spaces (argstr); } else /* Let argstr point to an empty string. */ argstr = certref + strlen (certref); if (info->apptype == APP_TYPE_OPENPGP) { if (ascii_strcasecmp (certref, "OPENPGP.3") && strcmp (certref, "3")) { err = gpg_error (GPG_ERR_INV_ID); log_error ("Error: CERTREF must be \"3\" or \"OPENPGP.3\"\n"); goto leave; } certref = certref_buffer = xstrdup ("OPENPGP.3"); } else /* Upcase the certref; prepend cardtype if needed. */ { if (!strchr (certref, '.')) certref_buffer = xstrconcat (app_type_string (info->apptype), ".", certref, NULL); else certref_buffer = xstrdup (certref); ascii_strupr (certref_buffer); certref = certref_buffer; } if (opt_clear) { data = xstrdup (" "); datalen = 1; } else if (*argstr == '<') /* Read it from a file */ { for (argstr++; spacep (argstr); argstr++) ; err = get_data_from_file (argstr, &data, &datalen); if (err) goto leave; if (ascii_memistr (data, datalen, "-----BEGIN CERTIFICATE-----") && ascii_memistr (data, datalen, "-----END CERTIFICATE-----") && !memchr (data, 0, datalen) && !memchr (data, 1, datalen)) { struct b64state b64; err = b64dec_start (&b64, ""); if (!err) err = b64dec_proc (&b64, data, datalen, &datalen); if (!err) err = b64dec_finish (&b64); if (err) goto leave; } } else if (opt_openpgp && *argstr) { err = get_minimal_openpgp_key (&key, argstr); if (err) goto leave; if (es_fclose_snatch (key, (void*)&data, &datalen)) { err = gpg_error_from_syserror (); goto leave; } key = NULL; } else { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } if (opt_openpgp && !opt_clear) { tlv_builder_t tb; void *tmpder; size_t tmpderlen; tb = tlv_builder_new (0); if (!tb) { err = gpg_error_from_syserror (); goto leave; } tlv_builder_add_tag (tb, 0, TAG_SEQUENCE); tlv_builder_add_ptr (tb, 0, TAG_OBJECT_ID, "\x2B\x06\x01\x04\x01\xDA\x47\x02\x03\x01", 10); tlv_builder_add_tag (tb, CLASS_CONTEXT, 0); tlv_builder_add_ptr (tb, 0, TAG_OCTET_STRING, data, datalen); tlv_builder_add_end (tb); tlv_builder_add_end (tb); err = tlv_builder_finalize (tb, &tmpder, &tmpderlen); if (err) goto leave; xfree (data); data = tmpder; datalen = tmpderlen; } err = scd_writecert (certref, data, datalen); leave: es_fclose (key); xfree (data); xfree (certref_buffer); return err; } static gpg_error_t cmd_readcert (card_info_t info, char *argstr) { gpg_error_t err; char *certref_buffer = NULL; char *certref; void *data = NULL; size_t datalen, dataoff; const char *fname; int opt_openpgp; if (!info) return print_help ("READCERT [--openpgp] CERTREF > FILE\n\n" "Read the certificate for key CERTREF and store it in FILE.\n" "With option \"--openpgp\" an OpenPGP keyblock is expected\n" "and stored in FILE.\n", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); opt_openpgp = has_leading_option (argstr, "--openpgp"); argstr = skip_options (argstr); certref = argstr; if ((argstr = strchr (certref, ' '))) { *argstr++ = 0; trim_spaces (certref); trim_spaces (argstr); } else /* Let argstr point to an empty string. */ argstr = certref + strlen (certref); if (info->apptype == APP_TYPE_OPENPGP) { if (ascii_strcasecmp (certref, "OPENPGP.3") && strcmp (certref, "3")) { err = gpg_error (GPG_ERR_INV_ID); log_error ("Error: CERTREF must be \"3\" or \"OPENPGP.3\"\n"); goto leave; } certref = certref_buffer = xstrdup ("OPENPGP.3"); } if (*argstr == '>') /* Write it to a file */ { for (argstr++; spacep (argstr); argstr++) ; fname = argstr; } else { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } dataoff = 0; err = scd_readcert (certref, &data, &datalen); if (err) goto leave; if (opt_openpgp) { /* Check whether DATA contains an OpenPGP keyblock and put only * this into FILE. If the data is something different, return * an error. */ const unsigned char *p; size_t n, objlen, hdrlen; int class, tag, cons, ndef; p = data; n = datalen; if (parse_ber_header (&p,&n,&class,&tag,&cons,&ndef,&objlen,&hdrlen)) goto not_openpgp; if (!(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && cons)) goto not_openpgp; /* Does not start with a sequence. */ if (parse_ber_header (&p,&n,&class,&tag,&cons,&ndef,&objlen,&hdrlen)) goto not_openpgp; if (!(class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !cons)) goto not_openpgp; /* No Object ID. */ if (objlen > n) goto not_openpgp; /* Inconsistent lengths. */ if (objlen != 10 || memcmp (p, "\x2B\x06\x01\x04\x01\xDA\x47\x02\x03\x01", objlen)) goto not_openpgp; /* Wrong Object ID. */ p += objlen; n -= objlen; if (parse_ber_header (&p,&n,&class,&tag,&cons,&ndef,&objlen,&hdrlen)) goto not_openpgp; if (!(class == CLASS_CONTEXT && tag == 0 && cons)) goto not_openpgp; /* Not a [0] context tag. */ if (parse_ber_header (&p,&n,&class,&tag,&cons,&ndef,&objlen,&hdrlen)) goto not_openpgp; if (!(class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING && !cons)) goto not_openpgp; /* Not an octet string. */ if (objlen > n) goto not_openpgp; /* Inconsistent lengths. */ dataoff = p - (const unsigned char*)data; datalen = objlen; } err = put_data_to_file (fname, (unsigned char*)data+dataoff, datalen); goto leave; not_openpgp: err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE); leave: xfree (data); xfree (certref_buffer); return err; } static gpg_error_t cmd_writekey (card_info_t info, char *argstr) { gpg_error_t err; int opt_force; char *argv[2]; int argc; char *keyref_buffer = NULL; char *keyref; char *keygrip; if (!info) return print_help ("WRITEKEY [--force] KEYREF KEYGRIP\n\n" "Write a private key object identified by KEYGRIP to slot KEYREF.\n" "Use --force to overwrite an existing key.", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); opt_force = has_leading_option (argstr, "--force"); argstr = skip_options (argstr); argc = split_fields (argstr, argv, DIM (argv)); if (argc < 2) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } /* Upcase the keyref; prepend cardtype if needed. */ keyref = argv[0]; if (!strchr (keyref, '.')) keyref_buffer = xstrconcat (app_type_string (info->apptype), ".", keyref, NULL); else keyref_buffer = xstrdup (keyref); ascii_strupr (keyref_buffer); keyref = keyref_buffer; /* Get the keygrip. */ keygrip = argv[1]; if (strlen (keygrip) != 40 && !(keygrip[0] == '&' && strlen (keygrip+1) == 40)) { log_error (_("Not a valid keygrip (expecting 40 hex digits)\n")); err = gpg_error (GPG_ERR_INV_ARG); goto leave; } err = scd_writekey (keyref, opt_force, keygrip); leave: xfree (keyref_buffer); return err; } static gpg_error_t cmd_forcesig (card_info_t info) { gpg_error_t err; int newstate; if (!info) return print_help ("FORCESIG\n\n" "Toggle the forcesig flag of an OpenPGP card.", APP_TYPE_OPENPGP, 0); if (info->apptype != APP_TYPE_OPENPGP) { log_info ("Note: This is an OpenPGP only command.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } newstate = !info->chv1_cached; err = scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1); if (err) goto leave; /* Read it back to be sure we have the right toggle state the next * time. */ err = scd_getattr ("CHV-STATUS", info); leave: return err; } /* Helper for cmd_generate_openpgp. Note that either 0 or 1 is stored at * FORCED_CHV1. */ static gpg_error_t check_pin_for_key_operation (card_info_t info, int *forced_chv1) { gpg_error_t err = 0; *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. */ err = scd_setattr ("CHV-STATUS-1", "\x01", 1); if (err) { log_error ("error clearing forced signature PIN flag: %s\n", gpg_strerror (err)); *forced_chv1 = -1; /* Not changed. */ goto leave; } } /* Check the PIN now, so that we won't get asked later for each * binding signature. */ err = scd_checkpin (info->serialno); if (err) log_error ("error checking the PIN: %s\n", gpg_strerror (err)); leave: return err; } /* Helper for cmd_generate_openpgp. */ static void restore_forced_chv1 (int *forced_chv1) { gpg_error_t err; /* Note the possible values stored at FORCED_CHV1: * 0 - forcesig was not enabled. * 1 - forcesig was enabled - enable it again. * -1 - We have not changed anything. */ if (*forced_chv1 == 1) { /* Switch back to forced state. */ err = scd_setattr ("CHV-STATUS-1", "", 1); if (err) log_error ("error setting forced signature PIN flag: %s\n", gpg_strerror (err)); *forced_chv1 = 0; } } /* Ask whether existing keys shall be overwritten. With NULL used for * KINFO it will ask for all keys, other wise for the given key. */ static gpg_error_t ask_replace_keys (key_info_t kinfo) { gpg_error_t err; char *answer; tty_printf ("\n"); if (kinfo) log_info (_("Note: key %s is already stored on the card!\n"), kinfo->keyref); else log_info (_("Note: Keys are already stored on the card!\n")); tty_printf ("\n"); if (kinfo) answer = tty_getf (_("Replace existing key %s ? (y/N) "), kinfo->keyref); else answer = tty_get (_("Replace existing keys? (y/N) ")); tty_kill_prompt (); if (*answer == CONTROL_D) err = gpg_error (GPG_ERR_CANCELED); else if (!answer_is_yes_no_default (answer, 0/*(default to No)*/)) err = gpg_error (GPG_ERR_CANCELED); else err = 0; xfree (answer); return err; } /* Implementation of cmd_generate for OpenPGP cards to generate all * standard keys at once. */ static gpg_error_t generate_all_openpgp_card_keys (card_info_t info, char **algos) { gpg_error_t err; int forced_chv1 = -1; int want_backup; char *answer = NULL; key_info_t kinfo1, kinfo2, kinfo3; if (info->extcap.ki) { xfree (answer); answer = tty_get (_("Make off-card backup of encryption key? (Y/n) ")); want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/); tty_kill_prompt (); if (*answer == CONTROL_D) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } } else want_backup = 0; kinfo1 = find_kinfo (info, "OPENPGP.1"); kinfo2 = find_kinfo (info, "OPENPGP.2"); kinfo3 = find_kinfo (info, "OPENPGP.3"); if ((kinfo1 && kinfo1->fprlen && !mem_is_zero (kinfo1->fpr,kinfo1->fprlen)) || (kinfo2 && kinfo2->fprlen && !mem_is_zero (kinfo2->fpr,kinfo2->fprlen)) || (kinfo3 && kinfo3->fprlen && !mem_is_zero (kinfo3->fpr,kinfo3->fprlen)) ) { err = ask_replace_keys (NULL); if (err) goto leave; } /* 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"), OPENPGP_USER_PIN_DEFAULT, OPENPGP_ADMIN_PIN_DEFAULT); tty_printf ("\n"); } err = check_pin_for_key_operation (info, &forced_chv1); if (err) goto leave; (void)algos; /* FIXME: If we have ALGOS, we need to change the key attr. */ /* FIXME: We need to divert to a function which spawns gpg which * will then create the key. This also requires new features in * gpg. We might also first create the keys on the card and then * tell gpg to use them to create the OpenPGP keyblock. */ /* generate_keypair (ctrl, 1, NULL, info.serialno, want_backup); */ (void)want_backup; err = scd_genkey ("OPENPGP.1", 1, NULL, NULL); leave: restore_forced_chv1 (&forced_chv1); xfree (answer); return err; } /* Create a single key. This is a helper for cmd_generate. */ static gpg_error_t generate_key (card_info_t info, const char *keyref, int force, const char *algo) { gpg_error_t err; key_info_t kinfo; if (info->apptype == APP_TYPE_OPENPGP) { kinfo = find_kinfo (info, keyref); if (!kinfo) { err = gpg_error (GPG_ERR_INV_ID); goto leave; } if (!force && kinfo->fprlen && !mem_is_zero (kinfo->fpr, kinfo->fprlen)) { err = ask_replace_keys (NULL); if (err) goto leave; force = 1; } } err = scd_genkey (keyref, force, algo, NULL); leave: return err; } static gpg_error_t cmd_generate (card_info_t info, char *argstr) { static char * const valid_algos[] = { "rsa2048", "rsa3072", "rsa4096", "", "nistp256", "nistp384", "nistp521", "", "brainpoolP256r1", "brainpoolP384r1", "brainpoolP512r1", "", "ed25519", "cv25519", NULL }; gpg_error_t err; int opt_force; char *p; char **opt_algo = NULL; /* Malloced. */ char *keyref_buffer = NULL; /* Malloced. */ char *keyref; /* Points into argstr or keyref_buffer. */ int i, j; if (!info) return print_help ("GENERATE [--force] [--algo=ALGO{+ALGO2}] KEYREF\n\n" "Create a new key on a card.\n" "Use --force to overwrite an existing key.\n" "Use \"help\" for ALGO to get a list of known algorithms.\n" "For OpenPGP cards several algos may be given.\n" "Note that the OpenPGP key generation is done interactively\n" "unless a single ALGO or KEYREF are given.", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); if (opt.interactive || opt.verbose) log_info (_("%s card no. %s detected\n"), app_type_string (info->apptype), info->dispserialno? info->dispserialno : info->serialno); opt_force = has_leading_option (argstr, "--force"); err = get_option_value (argstr, "--algo", &p); if (err) goto leave; if (p) { opt_algo = strtokenize (p, "+"); if (!opt_algo) { err = gpg_error_from_syserror (); xfree (p); goto leave; } xfree (p); } argstr = skip_options (argstr); keyref = argstr; if ((argstr = strchr (keyref, ' '))) { *argstr++ = 0; trim_spaces (keyref); trim_spaces (argstr); } else /* Let argstr point to an empty string. */ argstr = keyref + strlen (keyref); if (!*keyref) keyref = NULL; if (*argstr) { /* Extra arguments found. */ err = gpg_error (GPG_ERR_INV_ARG); goto leave; } if (opt_algo) { /* opt_algo is an array of algos. */ for (i=0; opt_algo[i]; i++) { for (j=0; valid_algos[j]; j++) if (*valid_algos[j] && !strcmp (valid_algos[j], opt_algo[i])) break; if (!valid_algos[j]) { int lf = 1; if (!ascii_strcasecmp (opt_algo[i], "help")) log_info ("Known algorithms:\n"); else { log_info ("Invalid algorithm '%s' given. Use one of:\n", opt_algo[i]); err = gpg_error (GPG_ERR_PUBKEY_ALGO); } for (i=0; valid_algos[i]; i++) { if (!*valid_algos[i]) lf = 1; else if (lf) { lf = 0; log_info (" %s%s", valid_algos[i], valid_algos[i+1]?",":"."); } else log_printf (" %s%s", valid_algos[i], valid_algos[i+1]?",":"."); } log_printf ("\n"); show_keysize_warning (); goto leave; } } } /* Upcase the keyref; if it misses the cardtype, prepend it. */ if (keyref) { if (!strchr (keyref, '.')) keyref_buffer = xstrconcat (app_type_string (info->apptype), ".", keyref, NULL); else keyref_buffer = xstrdup (keyref); ascii_strupr (keyref_buffer); keyref = keyref_buffer; } /* Special checks. */ if ((info->cardtype && !strcmp (info->cardtype, "yubikey")) && info->cardversion >= 0x040200 && info->cardversion < 0x040305) { log_error ("On-chip key generation on this YubiKey has been blocked.\n"); log_info ("Please see for details\n"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } /* Divert to dedicated functions. */ if (info->apptype == APP_TYPE_OPENPGP && !keyref && (!opt_algo || (opt_algo[0] && opt_algo[1]))) { /* With no algo requested or more than one algo requested and no * keyref given we create all keys. */ if (opt_force || keyref) log_info ("Note: OpenPGP key generation is interactive.\n"); err = generate_all_openpgp_card_keys (info, opt_algo); } else if (!keyref) err = gpg_error (GPG_ERR_INV_ID); else if (opt_algo && opt_algo[0] && opt_algo[1]) { log_error ("only one algorithm expected as value for --algo.\n"); err = gpg_error (GPG_ERR_INV_ARG); } else err = generate_key (info, keyref, opt_force, opt_algo? opt_algo[0]:NULL); if (!err) { err = scd_learn (info); if (err) log_error ("Error re-reading card: %s\n", gpg_strerror (err)); } leave: xfree (opt_algo); xfree (keyref_buffer); return err; } /* Change a PIN. */ static gpg_error_t cmd_passwd (card_info_t info, char *argstr) { gpg_error_t err = 0; char *answer = NULL; const char *pinref = NULL; int reset_mode = 0; int nullpin = 0; int menu_used = 0; if (!info) return print_help ("PASSWD [--reset|--nullpin] [PINREF]\n\n" "Change or unblock the PINs. Note that in interactive mode\n" "and without a PINREF a menu is presented for certain cards;\n" "in non-interactive and without a PINREF a default value is\n" "used for these cards. The option --reset is used with TCOS\n" "cards to reset the PIN using the PUK or vice versa; --nullpin\n" "is used for these cards to set the intial PIN.", 0); if (opt.interactive || opt.verbose) log_info (_("%s card no. %s detected\n"), app_type_string (info->apptype), info->dispserialno? info->dispserialno : info->serialno); if (has_option (argstr, "--reset")) reset_mode = 1; else if (has_option (argstr, "--nullpin")) nullpin = 1; argstr = skip_options (argstr); /* If --reset or --nullpin has been given we force non-interactive mode. */ if (*argstr || reset_mode || nullpin) { pinref = argstr; if (!*pinref) { err = gpg_error (GPG_ERR_MISSING_VALUE); goto leave; } } else if (opt.interactive && info->apptype == APP_TYPE_OPENPGP) { menu_used = 1; while (!pinref) { xfree (answer); answer = get_selection ("1 - change the PIN\n" "2 - unblock and set new a PIN\n" "3 - change the Admin PIN\n" "4 - set the Reset Code\n" "Q - quit\n"); if (strlen (answer) != 1) continue; else if (*answer == 'q' || *answer == 'Q') goto leave; else if (*answer == '1') pinref = "OPENPGP.1"; else if (*answer == '2') { pinref = "OPENPGP.1"; reset_mode = 1; } else if (*answer == '3') pinref = "OPENPGP.3"; else if (*answer == '4') { pinref = "OPENPGP.2"; reset_mode = 1; } } } else if (info->apptype == APP_TYPE_OPENPGP) pinref = "OPENPGP.1"; else if (opt.interactive && info->apptype == APP_TYPE_PIV) { menu_used = 1; while (!pinref) { xfree (answer); answer = get_selection ("1 - change the PIN\n" "2 - change the PUK\n" "3 - change the Global PIN\n" "Q - quit\n"); if (strlen (answer) != 1) ; else if (*answer == 'q' || *answer == 'Q') goto leave; else if (*answer == '1') pinref = "PIV.80"; else if (*answer == '2') pinref = "PIV.81"; else if (*answer == '3') pinref = "PIV.00"; } } else if (opt.interactive && info->apptype == APP_TYPE_NKS) { int for_qualified = 0; menu_used = 1; for (;;) { xfree (answer); answer = get_selection (" 1 - Standard PIN/PUK\n" " 2 - PIN/PUK for qualified signature\n" " Q - quit\n"); if (!ascii_strcasecmp (answer, "q")) goto leave; else if (!strcmp (answer, "1")) break; else if (!strcmp (answer, "2")) { for_qualified = 1; break; } } log_assert (DIM (info->chvinfo) >= 4); if (info->chvinfo[for_qualified? 2 : 0] == -4) { while (!pinref) { xfree (answer); answer = get_selection ("The NullPIN is still active on this card.\n" "You need to choose and set a PIN first.\n" "\n" " 1 - Set your PIN\n" " Q - quit\n"); if (!ascii_strcasecmp (answer, "q")) goto leave; else if (!strcmp (answer, "1")) { pinref = for_qualified? "PW1.CH.SIG" : "PW1.CH"; nullpin = 1; } } } else { while (!pinref) { xfree (answer); answer = get_selection (" 1 - change PIN\n" " 2 - reset PIN\n" " 3 - change PUK\n" " 4 - reset PUK\n" " Q - quit\n"); if (!ascii_strcasecmp (answer, "q")) goto leave; else if (!strcmp (answer, "1")) { pinref = for_qualified? "PW1.CH.SIG" : "PW1.CH"; } else if (!strcmp (answer, "2")) { pinref = for_qualified? "PW1.CH.SIG" : "PW1.CH"; reset_mode = 1; } else if (!strcmp (answer, "3")) { pinref = for_qualified? "PW2.CH.SIG" : "PW2.CH"; } else if (!strcmp (answer, "4")) { pinref = for_qualified? "PW2.CH.SIG" : "PW2.CH"; reset_mode = 1; } } } } else if (info->apptype == APP_TYPE_PIV) pinref = "PIV.80"; else { err = gpg_error (GPG_ERR_MISSING_VALUE); goto leave; } err = scd_change_pin (pinref, reset_mode, nullpin); if (err) { if (!opt.interactive && !menu_used && !opt.verbose) ; else if (!ascii_strcasecmp (pinref, "PIV.81")) log_error ("Error changing the PUK.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.1") && reset_mode) log_error ("Error unblocking the PIN.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.2") && reset_mode) log_error ("Error setting the Reset Code.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.3")) log_error ("Error changing the Admin PIN.\n"); else if (reset_mode) log_error ("Error resetting the PIN.\n"); else log_error ("Error changing the PIN.\n"); } else { if (!opt.interactive && !opt.verbose) ; else if (!ascii_strcasecmp (pinref, "PIV.81")) log_info ("PUK changed.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.1") && reset_mode) log_info ("PIN unblocked and new PIN set.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.2") && reset_mode) log_info ("Reset Code set.\n"); else if (!ascii_strcasecmp (pinref, "OPENPGP.3")) log_info ("Admin PIN changed.\n"); else if (reset_mode) log_info ("PIN resetted.\n"); else log_info ("PIN changed.\n"); /* Update the CHV status. */ err = scd_getattr ("CHV-STATUS", info); } leave: xfree (answer); return err; } static gpg_error_t cmd_unblock (card_info_t info) { gpg_error_t err = 0; if (!info) return print_help ("UNBLOCK\n\n" "Unblock a PIN using a PUK or Reset Code. Note that OpenPGP\n" "cards prior to version 2 can't use this; instead the PASSWD\n" "command can be used to set a new PIN.", 0); if (opt.interactive || opt.verbose) log_info (_("%s card no. %s detected\n"), app_type_string (info->apptype), info->dispserialno? info->dispserialno : info->serialno); if (info->apptype == APP_TYPE_OPENPGP) { if (!info->is_v2) { log_error (_("This command is only available for version 2 cards\n")); err = gpg_error (GPG_ERR_NOT_SUPPORTED); } else if (!info->chvinfo[1]) { log_error (_("Reset Code not or not anymore available\n")); err = gpg_error (GPG_ERR_PIN_BLOCKED); } else { err = scd_change_pin ("OPENPGP.2", 0, 0); if (!err) log_info ("PIN changed.\n"); } } else if (info->apptype == APP_TYPE_PIV) { /* Unblock the Application PIN. */ err = scd_change_pin ("PIV.80", 1, 0); if (!err) log_info ("PIN unblocked and changed.\n"); } else { log_info ("Unblocking not supported for '%s'.\n", app_type_string (info->apptype)); err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); } return err; } /* Note: On successful execution a redisplay should be scheduled. If * this function fails the card may be in an unknown state. */ static gpg_error_t cmd_factoryreset (card_info_t info) { gpg_error_t err; char *answer = NULL; int termstate = 0; int any_apdu = 0; int is_yubikey = 0; int i; if (!info) return print_help ("FACTORY-RESET\n\n" "Do a complete reset of some OpenPGP and PIV cards. This\n" "deletes all data and keys and resets the PINs to their default.\n" "This is mainly used by developers with scratch cards. Don't\n" "worry, you need to confirm before the command proceeds.", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); /* We support the factory reset for most OpenPGP cards and Yubikeys * with the PIV application. */ if (info->apptype == APP_TYPE_OPENPGP) ; else if (info->apptype == APP_TYPE_PIV && info->cardtype && !strcmp (info->cardtype, "yubikey")) is_yubikey = 1; else return gpg_error (GPG_ERR_NOT_SUPPORTED); /* For an OpenPGP card the code below basically does the same what * this gpg-connect-agent script does: * * scd reset * scd serialno undefined * scd apdu 00 A4 04 00 06 D2 76 00 01 24 01 * scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 * scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40 * scd apdu 00 e6 00 00 * scd apdu 00 44 00 00 * scd reset * /echo Card has been reset to factory defaults * * For a PIV application on a Yubikey it merely issues the Yubikey * specific resset command. */ err = scd_learn (info); if (gpg_err_code (err) == GPG_ERR_OBJ_TERM_STATE && gpg_err_source (err) == GPG_ERR_SOURCE_SCD) termstate = 1; else if (err) { log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err)); goto leave; } if (opt.interactive || opt.verbose) log_info (_("%s card no. %s detected\n"), app_type_string (info->apptype), info->dispserialno? info->dispserialno : info->serialno); if (!termstate || is_yubikey) { if (!is_yubikey) { if (!(info->status_indicator == 3 || info->status_indicator == 5)) { /* Note: We won't see status-indicator 3 here because it * is not possible to select a card application in * termination state. */ log_error (_("This command is not supported by this card\n")); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } } tty_printf ("\n"); log_info (_("Note: This command destroys all keys stored on the card!\n")); tty_printf ("\n"); xfree (answer); answer = tty_get (_("Continue? (y/N) ")); tty_kill_prompt (); trim_spaces (answer); if (*answer == CONTROL_D || !answer_is_yes_no_default (answer, 0/*(default to no)*/)) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } xfree (answer); answer = tty_get (_("Really do a factory reset? (enter \"yes\") ")); tty_kill_prompt (); trim_spaces (answer); if (strcmp (answer, "yes") && strcmp (answer,_("yes"))) { err = gpg_error (GPG_ERR_CANCELED); goto leave; } if (is_yubikey) { /* The PIV application si already selected, we only need to * send the special reset APDU after having blocked PIN and * PUK. Note that blocking the PUK is done using the * unblock PIN command. */ any_apdu = 1; for (i=0; i < 5; i++) send_apdu ("0020008008FFFFFFFFFFFFFFFF", "VERIFY", 0xffff, NULL, NULL); for (i=0; i < 5; i++) send_apdu ("002C008010FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "RESET RETRY COUNTER", 0xffff, NULL, NULL); err = send_apdu ("00FB000001FF", "YUBIKEY RESET", 0, NULL, NULL); if (err) goto leave; } else /* OpenPGP card. */ { any_apdu = 1; /* We need to select a card application before we can send APDUs * to the card without scdaemon doing anything on its own. */ err = send_apdu (NULL, "RESET", 0, NULL, NULL); if (err) goto leave; err = send_apdu ("undefined", "dummy select ", 0, NULL, NULL); if (err) goto leave; /* Select the OpenPGP application. */ err = send_apdu ("00A4040006D27600012401", "SELECT AID", 0, NULL, NULL); if (err) goto leave; /* Do some dummy verifies with wrong PINs to set the retry * counter to zero. We can't easily use the card version 2.1 * feature of presenting the admin PIN to allow the terminate * command because there is no machinery in scdaemon to catch * the verify command and ask for the PIN when the "APDU" * command is used. * Here, the length of dummy wrong PIN is 32-byte, also * supporting authentication with KDF DO. */ for (i=0; i < 4; i++) send_apdu ("0020008120" "40404040404040404040404040404040" "40404040404040404040404040404040", "VERIFY", 0xffff, NULL, NULL); for (i=0; i < 4; i++) send_apdu ("0020008320" "40404040404040404040404040404040" "40404040404040404040404040404040", "VERIFY", 0xffff, NULL, NULL); /* Send terminate datafile command. */ err = send_apdu ("00e60000", "TERMINATE DF", 0x6985, NULL, NULL); if (err) goto leave; } } if (!is_yubikey) { any_apdu = 1; /* Send activate datafile command. This is used without * confirmation if the card is already in termination state. */ err = send_apdu ("00440000", "ACTIVATE DF", 0, NULL, NULL); if (err) goto leave; } /* Finally we reset the card reader once more. */ err = send_apdu (NULL, "RESET", 0, NULL, NULL); if (err) goto leave; /* Then, connect the card again. */ err = scd_serialno (NULL, NULL); if (!err) info->need_sn_cmd = 0; leave: if (err && any_apdu && !is_yubikey) { log_info ("Due to an error the card might be in an inconsistent state\n" "You should run the LIST command to check this.\n"); /* FIXME: We need a better solution in the case that the card is * in a termination state, i.e. the card was removed before the * activate was sent. The best solution I found with v2.1 * Zeitcontrol card was to kill scdaemon and the issue this * sequence with gpg-connect-agent: * scd reset * scd serialno undefined * scd apdu 00A4040006D27600012401 (returns error) * scd apdu 00440000 * Then kill scdaemon again and issue: * scd reset * scd serialno openpgp */ } xfree (answer); return err; } /* Generate KDF data. This is a helper for cmd_kdfsetup. */ static gpg_error_t gen_kdf_data (unsigned char *data, int single_salt) { gpg_error_t err; const unsigned char h0[] = { 0x81, 0x01, 0x03, 0x82, 0x01, 0x08, 0x83, 0x04 }; const unsigned char h1[] = { 0x84, 0x08 }; const unsigned char h2[] = { 0x85, 0x08 }; const unsigned char h3[] = { 0x86, 0x08 }; const unsigned char h4[] = { 0x87, 0x20 }; const unsigned char h5[] = { 0x88, 0x20 }; unsigned char *p, *salt_user, *salt_admin; unsigned char s2k_char; unsigned int iterations; unsigned char count_4byte[4]; p = data; s2k_char = encode_s2k_iterations (agent_get_s2k_count ()); iterations = S2K_DECODE_COUNT (s2k_char); count_4byte[0] = (iterations >> 24) & 0xff; count_4byte[1] = (iterations >> 16) & 0xff; count_4byte[2] = (iterations >> 8) & 0xff; count_4byte[3] = (iterations & 0xff); memcpy (p, h0, sizeof h0); p += sizeof h0; memcpy (p, count_4byte, sizeof count_4byte); p += sizeof count_4byte; memcpy (p, h1, sizeof h1); salt_user = (p += sizeof h1); gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; if (single_salt) salt_admin = salt_user; else { memcpy (p, h2, sizeof h2); p += sizeof h2; gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; memcpy (p, h3, sizeof h3); salt_admin = (p += sizeof h3); gcry_randomize (p, 8, GCRY_STRONG_RANDOM); p += 8; } memcpy (p, h4, sizeof h4); p += sizeof h4; err = gcry_kdf_derive (OPENPGP_USER_PIN_DEFAULT, strlen (OPENPGP_USER_PIN_DEFAULT), GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA256, salt_user, 8, iterations, 32, p); p += 32; if (!err) { memcpy (p, h5, sizeof h5); p += sizeof h5; err = gcry_kdf_derive (OPENPGP_ADMIN_PIN_DEFAULT, strlen (OPENPGP_ADMIN_PIN_DEFAULT), GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA256, salt_admin, 8, iterations, 32, p); } return err; } static gpg_error_t cmd_kdfsetup (card_info_t info, char *argstr) { gpg_error_t err; unsigned char kdf_data[OPENPGP_KDF_DATA_LENGTH_MAX]; int single = (*argstr != 0); if (!info) return print_help ("KDF-SETUP\n\n" "Prepare the OpenPGP card KDF feature for this card.", APP_TYPE_OPENPGP, 0); if (info->apptype != APP_TYPE_OPENPGP) { log_info ("Note: This is an OpenPGP only command.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } if (!info->extcap.kdf) { log_error (_("This command is not supported by this card\n")); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } err = gen_kdf_data (kdf_data, single); if (err) goto leave; err = scd_setattr ("KDF", kdf_data, single ? OPENPGP_KDF_DATA_LENGTH_MIN /* */ : OPENPGP_KDF_DATA_LENGTH_MAX); if (err) goto leave; err = scd_getattr ("KDF", info); leave: return err; } 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\n" " key type or size. If the key generation does not succeed,\n" " please check the documentation of your card to see which\n" " key types and sizes are supported.\n") ); } static gpg_error_t cmd_uif (card_info_t info, char *argstr) { gpg_error_t err; int keyno; char name[50]; unsigned char data[2]; char *answer = NULL; int opt_yes; if (!info) return print_help ("UIF N [on|off|permanent]\n\n" "Change the User Interaction Flag. N must in the range 1 to 3.", APP_TYPE_OPENPGP, APP_TYPE_PIV, 0); if (!info->extcap.bt) { log_error (_("This command is not supported by this card\n")); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } opt_yes = has_leading_option (argstr, "--yes"); argstr = skip_options (argstr); if (digitp (argstr)) { keyno = atoi (argstr); while (digitp (argstr)) argstr++; while (spacep (argstr)) argstr++; } else keyno = 0; if (keyno < 1 || keyno > 3) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } if ( !strcmp (argstr, "off") ) data[0] = 0x00; else if ( !strcmp (argstr, "on") ) data[0] = 0x01; else if ( !strcmp (argstr, "permanent") ) data[0] = 0x02; else { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } data[1] = 0x20; log_assert (keyno - 1 < DIM(info->uif)); if (info->uif[keyno-1] == 2) { log_info (_("User Interaction Flag is set to \"%s\" - can't change\n"), "permanent"); err = gpg_error (GPG_ERR_INV_STATE); goto leave; } if (data[0] == 0x02) { if (opt.interactive) { tty_printf (_("Warning: Setting the User Interaction Flag to \"%s\"\n" " can only be reverted using a factory reset!\n" ), "permanent"); answer = tty_get (_("Continue? (y/N) ")); tty_kill_prompt (); if (*answer == CONTROL_D) err = gpg_error (GPG_ERR_CANCELED); else if (!answer_is_yes_no_default (answer, 0/*(default to No)*/)) err = gpg_error (GPG_ERR_CANCELED); else err = 0; } else if (!opt_yes) { log_info (_("Warning: Setting the User Interaction Flag to \"%s\"\n" " can only be reverted using a factory reset!\n" ), "permanent"); log_info (_("Please use \"uif --yes %d %s\"\n"), keyno, "permanent"); err = gpg_error (GPG_ERR_CANCELED); } else err = 0; if (err) goto leave; } snprintf (name, sizeof name, "UIF-%d", keyno); err = scd_setattr (name, data, 2); if (!err) /* Read all UIF attributes again. */ err = scd_getattr ("UIF", info); leave: xfree (answer); return err; } static gpg_error_t cmd_yubikey (card_info_t info, char *argstr) { gpg_error_t err, err2; estream_t fp = opt.interactive? NULL : es_stdout; char *words[20]; int nwords; if (!info) return print_help ("YUBIKEY args\n\n" "Various commands pertaining to Yubikey tokens with being:\n" "\n" " LIST \n" "\n" "List supported and enabled applications.\n" "\n" " ENABLE usb|nfc|all [otp|u2f|opgp|piv|oath|fido2|all]\n" " DISABLE usb|nfc|all [otp|u2f|opgp|piv|oath|fido2|all]\n" "\n" "Enable or disable the specified or all applications on the\n" "given interface.", 0); argstr = skip_options (argstr); if (!info->cardtype || strcmp (info->cardtype, "yubikey")) { log_info ("This command can only be used with Yubikeys.\n"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } nwords = split_fields (argstr, words, DIM (words)); if (nwords < 1) { err = gpg_error (GPG_ERR_SYNTAX); goto leave; } /* Note that we always do a learn to get a chance to the card back * into a usable state. */ err = yubikey_commands (info, fp, nwords, words); err2 = scd_learn (info); if (err2) log_error ("Error re-reading card: %s\n", gpg_strerror (err)); leave: return err; } static gpg_error_t cmd_apdu (card_info_t info, char *argstr) { gpg_error_t err; estream_t fp = opt.interactive? NULL : es_stdout; int with_atr; int handle_more; const char *s; const char *exlenstr; int exlenstrlen; char *options = NULL; unsigned int sw; unsigned char *result = NULL; size_t i, j, resultlen; if (!info) return print_help ("APDU [--more] [--exlen[=N]] \n" "\n" "Send an APDU to the current card. This command bypasses the high\n" "level functions and sends the data directly to the card. HEXSTRING\n" "is expected to be a proper APDU.\n" "\n" "Using the option \"--more\" handles the card status word MORE_DATA\n" "(61xx) and concatenates all responses to one block.\n" "\n" "Using the option \"--exlen\" the returned APDU may use extended\n" "length up to N bytes. If N is not given a default value is used.\n", 0); if (has_option (argstr, "--dump-atr")) with_atr = 2; else with_atr = has_option (argstr, "--atr"); handle_more = has_option (argstr, "--more"); exlenstr = has_option_name (argstr, "--exlen"); exlenstrlen = 0; if (exlenstr) { for (s=exlenstr; *s && !spacep (s); s++) exlenstrlen++; } argstr = skip_options (argstr); if (with_atr || handle_more || exlenstr) options = xasprintf ("%s%s%s%.*s", with_atr == 2? " --dump-atr": with_atr? " --atr":"", handle_more?" --more":"", exlenstr?" ":"", exlenstrlen, exlenstr?exlenstr:""); err = scd_apdu (argstr, options, &sw, &result, &resultlen); if (err) goto leave; log_info ("Statusword: 0x%04x\n", sw); for (i=0; i < resultlen; ) { size_t save_i = i; tty_fprintf (fp, "D[%04X] ", (unsigned int)i); for (j=0; j < 16 ; j++, i++) { if (j == 8) tty_fprintf (fp, " "); if (i < resultlen) tty_fprintf (fp, " %02X", result[i]); else tty_fprintf (fp, " "); } tty_fprintf (fp, " "); i = save_i; for (j=0; j < 16; j++, i++) { unsigned int c = result[i]; if ( i >= resultlen ) tty_fprintf (fp, " "); else if (isascii (c) && isprint (c) && !iscntrl (c)) tty_fprintf (fp, "%c", c); else tty_fprintf (fp, "."); } tty_fprintf (fp, "\n"); } leave: xfree (result); xfree (options); return err; } +static gpg_error_t +cmd_history (card_info_t info, char *argstr) +{ + int opt_list, opt_clear; + + opt_list = has_option (argstr, "--list"); + opt_clear = has_option (argstr, "--clear"); + + if (!info || !(opt_list || opt_clear)) + return print_help + ("HISTORY --list\n" + " List the command history\n" + "HISTORY --clear\n" + " Clear the command history", + 0); + + if (opt_list) + tty_printf ("Sorry, history listing not yet possible\n"); + + if (opt_clear) + tty_read_history (NULL, 0); + + return 0; +} + + /* 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, cmdHELP, cmdLIST, cmdRESET, cmdVERIFY, cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSALUT, cmdCAFPR, cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT, cmdREADCERT, cmdWRITEKEY, cmdUNBLOCK, cmdFACTRST, cmdKDFSETUP, - cmdUIF, cmdAUTH, cmdYUBIKEY, cmdAPDU, + cmdUIF, cmdAUTH, cmdYUBIKEY, cmdAPDU, cmdHISTORY, cmdINVCMD }; static struct { const char *name; enum cmdids id; const char *desc; } cmds[] = { { "quit" , cmdQUIT, N_("quit this menu")}, { "q" , cmdQUIT, NULL }, { "bye" , cmdQUIT, NULL }, { "help" , cmdHELP, N_("show this help")}, { "?" , cmdHELP, NULL }, { "list" , cmdLIST, N_("list all available data")}, { "l" , cmdLIST, NULL }, { "name" , cmdNAME, N_("change card holder's name")}, { "url" , cmdURL, N_("change URL to retrieve key")}, { "fetch" , cmdFETCH, N_("fetch the key specified in the card URL")}, { "login" , cmdLOGIN, N_("change the login name")}, { "lang" , cmdLANG, N_("change the language preferences")}, { "salutation",cmdSALUT, N_("change card holder's salutation")}, { "salut" , cmdSALUT, NULL }, { "cafpr" , cmdCAFPR , N_("change a CA fingerprint")}, { "forcesig", cmdFORCESIG, N_("toggle the signature force PIN flag")}, { "generate", cmdGENERATE, N_("generate new keys")}, { "passwd" , cmdPASSWD, N_("menu to change or unblock the PIN")}, { "verify" , cmdVERIFY, N_("verify the PIN and list all data")}, { "unblock" , cmdUNBLOCK, N_("unblock the PIN using a Reset Code")}, { "authenticate",cmdAUTH, N_("authenticate to the card")}, { "auth" , cmdAUTH, NULL }, { "reset" , cmdRESET, N_("send a reset to the card daemon")}, { "factory-reset",cmdFACTRST, N_("destroy all keys and data")}, { "kdf-setup", cmdKDFSETUP, N_("setup KDF for PIN authentication")}, { "uif", cmdUIF, N_("change the User Interaction Flag")}, { "privatedo", cmdPRIVATEDO, N_("change a private data object")}, { "readcert", cmdREADCERT, N_("read a certificate from a data object")}, { "writecert", cmdWRITECERT, N_("store a certificate to a data object")}, { "writekey", cmdWRITEKEY, N_("store a private key to a data object")}, { "yubikey", cmdYUBIKEY, N_("Yubikey management commands")}, { "apdu", cmdAPDU, NULL}, + { "history", cmdHISTORY, N_("manage the command history")}, { NULL, cmdINVCMD, NULL } }; /* The command line command dispatcher. */ static gpg_error_t dispatch_command (card_info_t info, const char *orig_command) { gpg_error_t err = 0; enum cmdids cmd; /* The command. */ char *command; /* A malloced copy of ORIG_COMMAND. */ char *argstr; /* The argument as a string. */ int i; int ignore_error; if ((ignore_error = *orig_command == '-')) orig_command++; command = xstrdup (orig_command); argstr = NULL; if ((argstr = strchr (command, ' '))) { *argstr++ = 0; trim_spaces (command); trim_spaces (argstr); } for (i=0; cmds[i].name; i++ ) if (!ascii_strcasecmp (command, cmds[i].name )) break; cmd = cmds[i].id; /* (If not found this will be cmdINVCMD). */ /* Make sure we have valid strings for the args. They are allowed * to be modified and must thus point to a buffer. */ if (!argstr) argstr = command + strlen (command); /* For most commands we need to make sure that we have a card. */ if (!info) ; /* Help mode */ else if (!(cmd == cmdNOP || cmd == cmdQUIT || cmd == cmdHELP || cmd == cmdINVCMD) && !info->initialized) { err = scd_learn (info); if (err) { err = fixup_scd_errors (err); log_error ("Error reading card: %s\n", gpg_strerror (err)); goto leave; } } if (info) info->card_removed = 0; switch (cmd) { case cmdNOP: if (!info) print_help ("NOP\n\n" "Dummy command.", 0); break; case cmdQUIT: if (!info) print_help ("QUIT\n\n" "Stop processing.", 0); else { err = gpg_error (GPG_ERR_EOF); goto leave; } break; case cmdHELP: if (!info) print_help ("HELP [command]\n\n" "Show all commands. With an argument show help\n" "for that command.", 0); else if (*argstr) dispatch_command (NULL, argstr); else { es_printf ("List of commands (\"help \" for details):\n"); for (i=0; cmds[i].name; i++ ) if(cmds[i].desc) es_printf("%-14s %s\n", cmds[i].name, _(cmds[i].desc) ); es_printf ("Prefix a command with a dash to ignore its error.\n"); } break; case cmdRESET: if (!info) print_help ("RESET\n\n" "Send a RESET to the card daemon.", 0); else { flush_keyblock_cache (); err = scd_apdu (NULL, NULL, NULL, NULL, NULL); if (!err) info->need_sn_cmd = 1; } break; case cmdLIST: err = cmd_list (info, argstr); break; case cmdVERIFY: err = cmd_verify (info, argstr); break; case cmdAUTH: err = cmd_authenticate (info, argstr); break; case cmdNAME: err = cmd_name (info, argstr); break; case cmdURL: err = cmd_url (info, argstr); break; case cmdFETCH: err = cmd_fetch (info); break; case cmdLOGIN: err = cmd_login (info, argstr); break; case cmdLANG: err = cmd_lang (info, argstr); break; case cmdSALUT: err = cmd_salut (info, argstr); break; case cmdCAFPR: err = cmd_cafpr (info, argstr); break; case cmdPRIVATEDO: err = cmd_privatedo (info, argstr); break; case cmdWRITECERT: err = cmd_writecert (info, argstr); break; case cmdREADCERT: err = cmd_readcert (info, argstr); break; case cmdWRITEKEY: err = cmd_writekey (info, argstr); break; case cmdFORCESIG: err = cmd_forcesig (info); break; case cmdGENERATE: err = cmd_generate (info, argstr); break; case cmdPASSWD: err = cmd_passwd (info, argstr); break; case cmdUNBLOCK: err = cmd_unblock (info); break; case cmdFACTRST: err = cmd_factoryreset (info); break; case cmdKDFSETUP: err = cmd_kdfsetup (info, argstr); break; case cmdUIF: err = cmd_uif (info, argstr); break; case cmdYUBIKEY: err = cmd_yubikey (info, argstr); break; case cmdAPDU: err = cmd_apdu (info, argstr); break; + case cmdHISTORY: err = 0; break; /* Only used in interactive mode. */ case cmdINVCMD: default: log_error (_("Invalid command (try \"help\")\n")); break; } /* End command switch. */ leave: /* Return GPG_ERR_EOF only if its origin was "quit". */ es_fflush (es_stdout); if (gpg_err_code (err) == GPG_ERR_EOF && cmd != cmdQUIT) err = gpg_error (GPG_ERR_GENERAL); if (!err && info && info->card_removed) { info->card_removed = 0; info->need_sn_cmd = 1; err = gpg_error (GPG_ERR_CARD_REMOVED); } if (err && gpg_err_code (err) != GPG_ERR_EOF) { err = fixup_scd_errors (err); if (ignore_error) { log_info ("Command '%s' failed: %s\n", command, gpg_strerror (err)); err = 0; } else { log_error ("Command '%s' failed: %s\n", command, gpg_strerror (err)); if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT) info->need_sn_cmd = 1; } } xfree (command); return err; } /* The interactive main loop. */ static void interactive_loop (void) { gpg_error_t err; char *answer = NULL; /* The input line. */ enum cmdids cmd = cmdNOP; /* The command. */ char *argstr; /* The argument as a string. */ int redisplay = 1; /* Whether to redisplay the main info. */ char *help_arg = NULL; /* Argument of the HELP command. */ struct card_info_s info_buffer = { 0 }; card_info_t info = &info_buffer; char *p; int i; + const char *historyname = NULL; /* In the interactive mode we do not want to print the program prefix. */ log_set_prefix (NULL, 0); + if (!opt.no_history) + { + historyname = make_filename (gnupg_homedir (), HISTORYNAME, NULL); + if (tty_read_history (historyname, 500)) + log_info ("error reading '%s': %s\n", + historyname, gpg_strerror (gpg_error_from_syserror ())); + } + for (;;) { if (help_arg) { /* Clear info to indicate helpmode */ info = NULL; } else if (!info) { /* Get out of help. */ info = &info_buffer; help_arg = NULL; redisplay = 0; } else if (redisplay) { err = cmd_list (info, ""); if (err) { err = fixup_scd_errors (err); log_error ("Error reading card: %s\n", gpg_strerror (err)); } else { tty_printf("\n"); redisplay = 0; } } if (!info) { /* Copy the pending help arg into our answer. Note that * help_arg points into answer. */ p = xstrdup (help_arg); help_arg = NULL; xfree (answer); answer = p; } else { do { xfree (answer); tty_enable_completion (command_completion); answer = tty_get (_("gpg/card> ")); tty_kill_prompt(); tty_disable_completion (); trim_spaces(answer); } while ( *answer == '#' ); } argstr = NULL; if (!*answer) cmd = cmdLIST; /* We default to the list command */ else if (*answer == CONTROL_D) cmd = cmdQUIT; else { if ((argstr = strchr (answer,' '))) { *argstr++ = 0; trim_spaces (answer); trim_spaces (argstr); } for (i=0; cmds[i].name; i++ ) if (!ascii_strcasecmp (answer, cmds[i].name )) break; cmd = cmds[i].id; } /* Make sure we have valid strings for the args. They are * allowed to be modified and must thus point to a buffer. */ if (!argstr) argstr = answer + strlen (answer); if (!(cmd == cmdNOP || cmd == cmdQUIT || cmd == cmdHELP - || cmd == cmdINVCMD)) + || cmd == cmdHISTORY || cmd == cmdINVCMD)) { /* If redisplay is set we know that there was an error reading * the card. In this case we force a LIST command to retry. */ if (!info) ; /* In help mode. */ else if (redisplay) { cmd = cmdLIST; } else if (!info->serialno) { /* Without a serial number most commands won't work. * Catch it here. */ if (cmd == cmdRESET || cmd == cmdLIST) info->need_sn_cmd = 1; else { tty_printf ("\n"); tty_printf ("Serial number missing\n"); continue; } } } if (info) info->card_removed = 0; err = 0; switch (cmd) { case cmdNOP: if (!info) print_help ("NOP\n\n" "Dummy command.", 0); break; case cmdQUIT: if (!info) print_help ("QUIT\n\n" "Leave this tool.", 0); else { tty_printf ("\n"); goto leave; } break; case cmdHELP: if (!info) print_help ("HELP [command]\n\n" "Show all commands. With an argument show help\n" "for that command.", 0); else if (*argstr) help_arg = argstr; /* Trigger help for a command. */ else { tty_printf ("List of commands (\"help \" for details):\n"); for (i=0; cmds[i].name; i++ ) if(cmds[i].desc) tty_printf("%-14s %s\n", cmds[i].name, _(cmds[i].desc) ); } break; case cmdRESET: if (!info) print_help ("RESET\n\n" "Send a RESET to the card daemon.", 0); else { flush_keyblock_cache (); err = scd_apdu (NULL, NULL, NULL, NULL, NULL); if (!err) info->need_sn_cmd = 1; } break; case cmdLIST: err = cmd_list (info, argstr); break; case cmdVERIFY: err = cmd_verify (info, argstr); if (!err) redisplay = 1; break; case cmdAUTH: err = cmd_authenticate (info, argstr); break; case cmdNAME: err = cmd_name (info, argstr); break; case cmdURL: err = cmd_url (info, argstr); break; case cmdFETCH: err = cmd_fetch (info); break; case cmdLOGIN: err = cmd_login (info, argstr); break; case cmdLANG: err = cmd_lang (info, argstr); break; case cmdSALUT: err = cmd_salut (info, argstr); break; case cmdCAFPR: err = cmd_cafpr (info, argstr); break; case cmdPRIVATEDO: err = cmd_privatedo (info, argstr); break; case cmdWRITECERT: err = cmd_writecert (info, argstr); break; case cmdREADCERT: err = cmd_readcert (info, argstr); break; case cmdWRITEKEY: err = cmd_writekey (info, argstr); break; case cmdFORCESIG: err = cmd_forcesig (info); break; case cmdGENERATE: err = cmd_generate (info, argstr); break; case cmdPASSWD: err = cmd_passwd (info, argstr); break; case cmdUNBLOCK: err = cmd_unblock (info); break; case cmdFACTRST: err = cmd_factoryreset (info); if (!err) redisplay = 1; break; case cmdKDFSETUP: err = cmd_kdfsetup (info, argstr); break; case cmdUIF: err = cmd_uif (info, argstr); break; case cmdYUBIKEY: err = cmd_yubikey (info, argstr); break; case cmdAPDU: err = cmd_apdu (info, argstr); break; + case cmdHISTORY: err = cmd_history (info, argstr); break; case cmdINVCMD: default: tty_printf ("\n"); tty_printf (_("Invalid command (try \"help\")\n")); break; } /* End command switch. */ if (!err && info && info->card_removed) { info->card_removed = 0; info->need_sn_cmd = 1; err = gpg_error (GPG_ERR_CARD_REMOVED); } if (gpg_err_code (err) == GPG_ERR_CANCELED) tty_fprintf (NULL, "\n"); else if (err) { const char *s = "?"; for (i=0; cmds[i].name; i++ ) if (cmd == cmds[i].id) { s = cmds[i].name; break; } err = fixup_scd_errors (err); log_error ("Command '%s' failed: %s\n", s, gpg_strerror (err)); if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT) info->need_sn_cmd = 1; } } /* End of main menu loop. */ leave: + if (historyname && tty_write_history (historyname)) + log_info ("error writing '%s': %s\n", + historyname, gpg_strerror (gpg_error_from_syserror ())); + release_card_info (info); + xfree (historyname); xfree (answer); } #ifdef HAVE_LIBREADLINE /* Helper function for readline's 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)) return strdup(name); } return NULL; } /* Second helper function for readline's command completion. */ static char ** command_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. The support for help completion * needs to be more smarter. */ if (!start) return rl_completion_matches (text, command_generator); else if (start == 5 && !ascii_strncasecmp (rl_line_buffer, "help ", 5)) return rl_completion_matches (text, command_generator); rl_attempted_completion_over = 1; return NULL; } #endif /*HAVE_LIBREADLINE*/ diff --git a/tools/gpg-card.h b/tools/gpg-card.h index 56e117bf3..067720d6c 100644 --- a/tools/gpg-card.h +++ b/tools/gpg-card.h @@ -1,246 +1,248 @@ /* gpg-card.h - Common definitions for the gpg-card-tool * Copyright (C) 2019, 2020 g10 Code GmbH * * This file is part of GnuPG. * * This file 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. * * This file 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 General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #ifndef GNUPG_GPG_CARD_H #define GNUPG_GPG_CARD_H #include "../common/session-env.h" /* We keep all global options in the structure OPT. */ EXTERN_UNLESS_MAIN_MODULE struct { int interactive; int verbose; unsigned int debug; int quiet; int with_colons; const char *gpg_program; const char *gpgsm_program; const char *agent_program; int autostart; int no_key_lookup; /* Assume --no-key-lookup for "list". */ + int no_history; /* Do not use the command line history. */ + /* Options passed to the gpg-agent: */ session_env_t session_env; char *lc_ctype; char *lc_messages; } opt; /* Debug values and macros. */ #define DBG_IPC_VALUE 1024 /* Debug assuan communication. */ #define DBG_EXTPROG_VALUE 16384 /* Debug external program calls */ #define DBG_IPC (opt.debug & DBG_IPC_VALUE) #define DBG_EXTPROG (opt.debug & DBG_EXTPROG_VALUE) /* The maximum length of a binary fingerprint. */ #define MAX_FINGERPRINT_LEN 32 /* * Data structures to store keyblocks (aka certificates). */ struct pubkey_s { struct pubkey_s *next; /* The next key. */ unsigned char grip[KEYGRIP_LEN]; unsigned char fpr[MAX_FINGERPRINT_LEN]; unsigned char fprlen; /* The used length of a FPR. */ time_t created; /* The creation date of the key. */ unsigned int grip_valid:1;/* The grip is valid. */ unsigned int requested: 1;/* This is the requested grip. */ }; typedef struct pubkey_s *pubkey_t; struct userid_s { struct userid_s *next; char *value; /* Malloced. */ }; typedef struct userid_s *userid_t; struct keyblock_s { struct keyblock_s *next; /* Allow to link several keyblocks. */ int protocol; /* GPGME_PROTOCOL_OPENPGP or _CMS. */ pubkey_t keys; /* The key. For OpenPGP primary + list of subkeys. */ userid_t uids; /* The list of user ids. */ }; typedef struct keyblock_s *keyblock_t; /* Enumeration of the known card application types. */ typedef enum { APP_TYPE_NONE, /* Not yet known or for direct APDU sending. */ APP_TYPE_OPENPGP, APP_TYPE_NKS, APP_TYPE_DINSIG, APP_TYPE_P15, APP_TYPE_GELDKARTE, APP_TYPE_SC_HSM, APP_TYPE_PIV, APP_TYPE_UNKNOWN /* Unknown by this tool. */ } app_type_t; /* An object to store information pertaining to a key pair as stored * on a card. This is commonly used as a linked list with all keys * known for the current card. */ struct key_info_s { struct key_info_s *next; unsigned char grip[20];/* The keygrip. */ unsigned char xflag; /* Temporary flag to help processing a list. */ /* OpenPGP card and possible other cards keyalgo string (an atom) * and the id of the algorithm. */ const char *keyalgo; enum gcry_pk_algos keyalgo_id; /* The three next items are mostly useful for OpenPGP cards. */ unsigned char fprlen; /* Use length of the next item. */ unsigned char fpr[32]; /* The binary fingerprint of length FPRLEN. */ u32 created; /* The time the key was created. */ unsigned int usage; /* Usage flags. (GCRY_PK_USAGE_*) */ char keyref[1]; /* String with the keyref (e.g. OPENPGP.1). */ }; typedef struct key_info_s *key_info_t; /* * The object used to store information about a card. */ struct card_info_s { int initialized; /* True if a learn command was successful. */ int need_sn_cmd; /* The SERIALNO command needs to be issued. */ int card_removed; /* Helper flag set by some listing functions. */ int error; /* private. */ char *reader; /* Reader information. */ char *cardtype; /* NULL or type of the card. */ unsigned int cardversion; /* Firmware version of the card. */ char *apptypestr; /* Malloced application type string. */ app_type_t apptype;/* Translated from APPTYPESTR. */ unsigned int appversion; /* Version of the application. */ unsigned int manufacturer_id; char *manufacturer_name; /* malloced. */ char *serialno; /* malloced hex string. */ char *dispserialno;/* malloced string. */ char *disp_name; /* malloced. */ char *disp_lang; /* malloced. */ int disp_sex; /* 0 = unspecified, 1 = male, 2 = female */ char *pubkey_url; /* malloced. */ char *login_data; /* malloced. */ char *private_do[4]; /* malloced. */ char cafpr1len; /* Length of the CA-fingerprint or 0 if invalid. */ char cafpr2len; char cafpr3len; char cafpr1[20]; char cafpr2[20]; char cafpr3[20]; key_info_t kinfo; /* Linked list with all keypair related data. */ unsigned long sig_counter; int chv1_cached; /* For openpgp this is true if a PIN is not required for each signing. Note that the gpg-agent might cache it anyway. */ int is_v2; /* True if this is a v2 openpgp card. */ int chvmaxlen[4]; /* Maximum allowed length of a CHV. */ int chvinfo[4]; /* Allowed retries for the CHV; 0 = blocked. */ unsigned char chvusage[2]; /* Data object 5F2F */ struct { unsigned int ki:1; /* Key import available. */ unsigned int aac:1; /* Algorithm attributes are changeable. */ unsigned int kdf:1; /* KDF object to support PIN hashing available. */ unsigned int bt:1; /* Button for confirmation available. */ unsigned int sm:1; /* Secure messaging available. */ unsigned int smalgo:15;/* Secure messaging cipher algorithm. */ unsigned int private_dos:1;/* Support fpr private use DOs. */ unsigned int mcl3:16; /* Max. length for a OpenPGP card cert.3 */ } extcap; unsigned int status_indicator; int kdf_do_enabled; /* True if card has a KDF object. */ int uif[3]; /* True if User Interaction Flag is on. */ /* 1 = on, 2 = permanent on. */ }; typedef struct card_info_s *card_info_t; /*-- card-keys.c --*/ void release_keyblock (keyblock_t keyblock); void flush_keyblock_cache (void); gpg_error_t get_matching_keys (const unsigned char *keygrip, int protocol, keyblock_t *r_keyblock); gpg_error_t test_get_matching_keys (const char *hexgrip); gpg_error_t get_minimal_openpgp_key (estream_t *r_key, const char *fingerprint); /*-- card-misc.c --*/ key_info_t find_kinfo (card_info_t info, const char *keyref); void *hex_to_buffer (const char *string, size_t *r_length); gpg_error_t send_apdu (const char *hexapdu, const char *desc, unsigned int ignore, unsigned char **r_data, size_t *r_datalen); /*-- card-call-scd.c --*/ void release_card_info (card_info_t info); const char *app_type_string (app_type_t app_type); gpg_error_t scd_apdu (const char *hexapdu, const char *options, unsigned int *r_sw, unsigned char **r_data, size_t *r_datalen); gpg_error_t scd_switchcard (const char *serialno); gpg_error_t scd_switchapp (const char *appname); gpg_error_t scd_learn (card_info_t info); gpg_error_t scd_getattr (const char *name, struct card_info_s *info); gpg_error_t scd_setattr (const char *name, const unsigned char *value, size_t valuelen); gpg_error_t scd_writecert (const char *certidstr, const unsigned char *certdata, size_t certdatalen); gpg_error_t scd_writekey (const char *keyref, int force, const char *keygrip); gpg_error_t scd_genkey (const char *keyref, int force, const char *algo, u32 *createtime); gpg_error_t scd_serialno (char **r_serialno, const char *demand); gpg_error_t scd_readcert (const char *certidstr, void **r_buf, size_t *r_buflen); gpg_error_t scd_readkey (const char *keyrefstr, gcry_sexp_t *r_result); gpg_error_t scd_cardlist (strlist_t *result); gpg_error_t scd_applist (strlist_t *result, int all); gpg_error_t scd_change_pin (const char *pinref, int reset_mode, int nullpin); gpg_error_t scd_checkpin (const char *serialno); unsigned long agent_get_s2k_count (void); /*-- card-yubikey.c --*/ gpg_error_t yubikey_commands (card_info_t info, estream_t fp, int argc, char *argv[]); #endif /*GNUPG_GPG_CARD_H*/ diff --git a/tools/gpg-connect-agent.c b/tools/gpg-connect-agent.c index 746ac7daf..cde086770 100644 --- a/tools/gpg-connect-agent.c +++ b/tools/gpg-connect-agent.c @@ -1,2284 +1,2319 @@ /* gpg-connect-agent.c - Tool to connect to the agent. * Copyright (C) 2005, 2007, 2008, 2010 Free Software Foundation, Inc. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include #include "../common/i18n.h" #include "../common/util.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "../common/membuf.h" #include "../common/ttyio.h" #ifdef HAVE_W32_SYSTEM # include "../common/exechelp.h" #endif #include "../common/init.h" #define CONTROL_D ('D' - 'A' + 1) #define octdigitp(p) (*(p) >= '0' && *(p) <= '7') +#define HISTORYNAME ".gpg-connect_history" + + /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oRawSocket = 'S', oTcpSocket = 'T', oExec = 'E', oRun = 'r', oSubst = 's', oNoVerbose = 500, oHomedir, oAgentProgram, oDirmngrProgram, oKeyboxdProgram, oHex, oDecode, oNoExtConnect, oDirmngr, oKeyboxd, oUIServer, + oNoHistory, oNoAutostart }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("quiet")), ARGPARSE_s_n (oHex, "hex", N_("print data out hex encoded")), ARGPARSE_s_n (oDecode,"decode", N_("decode received data lines")), ARGPARSE_s_n (oDirmngr,"dirmngr", N_("connect to the dirmngr")), ARGPARSE_s_n (oKeyboxd,"keyboxd", N_("connect to the keyboxd")), ARGPARSE_s_n (oUIServer, "uiserver", "@"), ARGPARSE_s_s (oRawSocket, "raw-socket", N_("|NAME|connect to Assuan socket NAME")), ARGPARSE_s_s (oTcpSocket, "tcp-socket", N_("|ADDR|connect to Assuan server at ADDR")), ARGPARSE_s_n (oExec, "exec", N_("run the Assuan server given on the command line")), ARGPARSE_s_n (oNoExtConnect, "no-ext-connect", N_("do not use extended connect mode")), ARGPARSE_s_s (oRun, "run", N_("|FILE|run commands from FILE on startup")), ARGPARSE_s_n (oSubst, "subst", N_("run /subst on startup")), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), + ARGPARSE_s_n (oNoHistory,"no-history", + "do not use the command history file"), ARGPARSE_s_s (oHomedir, "homedir", "@" ), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"), ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"), ARGPARSE_end () }; /* We keep all global options in the structure OPT. */ struct { int verbose; /* Verbosity level. */ int quiet; /* Be extra quiet. */ int autostart; /* Start the server if not running. */ const char *homedir; /* Configuration directory name */ const char *agent_program; /* Value of --agent-program. */ const char *dirmngr_program; /* Value of --dirmngr-program. */ const char *keyboxd_program; /* Value of --keyboxd-program. */ int hex; /* Print data lines in hex format. */ int decode; /* Decode received data lines. */ int use_dirmngr; /* Use the dirmngr and not gpg-agent. */ int use_keyboxd; /* Use the keyboxd and not gpg-agent. */ int use_uiserver; /* Use the standard UI server. */ const char *raw_socket; /* Name of socket to connect in raw mode. */ const char *tcp_socket; /* Name of server to connect in tcp mode. */ int exec; /* Run the pgm given on the command line. */ unsigned int connect_flags; /* Flags used for connecting. */ int enable_varsubst; /* Set if variable substitution is enabled. */ int trim_leading_spaces; + int no_history; } opt; /* Definitions for /definq commands and a global linked list with all the definitions. */ struct definq_s { struct definq_s *next; char *name; /* Name of inquiry or NULL for any name. */ int is_var; /* True if FILE is a variable name. */ int is_prog; /* True if FILE is a program to run. */ char file[1]; /* Name of file or program. */ }; typedef struct definq_s *definq_t; static definq_t definq_list; static definq_t *definq_list_tail = &definq_list; /* Variable definitions and glovbal table. */ struct variable_s { struct variable_s *next; char *value; /* Malloced value - always a string. */ char name[1]; /* Name of the variable. */ }; typedef struct variable_s *variable_t; static variable_t variable_table; /* To implement loops we store entire lines in a linked list. */ struct loopline_s { struct loopline_s *next; char line[1]; }; typedef struct loopline_s *loopline_t; /* This is used to store the pid of the server. */ static pid_t server_pid = (pid_t)(-1); /* The current datasink file or NULL. */ static FILE *current_datasink; /* A list of open file descriptors. */ static struct { int inuse; #ifdef HAVE_W32_SYSTEM HANDLE handle; #endif } open_fd_table[256]; /*-- local prototypes --*/ static char *substitute_line_copy (const char *buffer); static int read_and_print_response (assuan_context_t ctx, int withhash, int *r_goterr); static assuan_context_t start_agent (void); /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPG@-connect-agent (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: @GPG@-connect-agent [options] (-h for help)"); break; case 41: p = _("Syntax: @GPG@-connect-agent [options]\n" "Connect to a running agent and send commands\n"); break; case 31: p = "\nHome: "; break; case 32: p = gnupg_homedir (); break; case 33: p = "\n"; break; default: p = NULL; break; } return p; } /* Unescape STRING and returned the malloced result. The surrounding quotes must already be removed from STRING. */ static char * unescape_string (const char *string) { const unsigned char *s; int esc; size_t n; char *buffer; unsigned char *d; n = 0; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': case 't': case 'v': case 'n': case 'f': case 'r': case '"': case '\'': case '\\': n++; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) n++; break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) n++; break; } esc = 0; } else if (*s == '\\') esc = 1; else n++; } buffer = xmalloc (n+1); d = (unsigned char*)buffer; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': *d++ = '\b'; break; case 't': *d++ = '\t'; break; case 'v': *d++ = '\v'; break; case 'n': *d++ = '\n'; break; case 'f': *d++ = '\f'; break; case 'r': *d++ = '\r'; break; case '"': *d++ = '\"'; break; case '\'': *d++ = '\''; break; case '\\': *d++ = '\\'; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) { s++; *d++ = xtoi_2 (s); s++; } break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) { *d++ = (atoi_1 (s)*64) + (atoi_1 (s+1)*8) + atoi_1 (s+2); s += 2; } break; } esc = 0; } else if (*s == '\\') esc = 1; else *d++ = *s; } *d = 0; return buffer; } /* Do the percent unescaping and return a newly malloced string. If WITH_PLUS is set '+' characters will be changed to space. */ static char * unpercent_string (const char *string, int with_plus) { const unsigned char *s; unsigned char *buffer, *p; size_t n; n = 0; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; n++; s++; } else if (with_plus && *s == '+') n++; else n++; } buffer = xmalloc (n+1); p = buffer; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; *p++ = xtoi_2 (s); s++; } else if (with_plus && *s == '+') *p++ = ' '; else *p++ = *s; } *p = 0; return (char*)buffer; } static const char * set_var (const char *name, const char *value) { variable_t var; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var) { var = xmalloc (sizeof *var + strlen (name)); var->value = NULL; strcpy (var->name, name); var->next = variable_table; variable_table = var; } xfree (var->value); var->value = value? xstrdup (value) : NULL; return var->value; } static void set_int_var (const char *name, int value) { char numbuf[35]; snprintf (numbuf, sizeof numbuf, "%d", value); set_var (name, numbuf); } /* Return the value of a variable. That value is valid until a variable of the name is changed. Return NULL if not found. Note that envvars are copied to our variable list at the first access and not at oprogram start. */ static const char * get_var (const char *name) { variable_t var; const char *s; if (!*name) return ""; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var && (s = getenv (name))) return set_var (name, s); if (!var || !var->value) return NULL; return var->value; } /* Perform some simple arithmetic operations. Caller must release the return value. On error the return value is NULL. */ static char * arithmetic_op (int operator, const char *operands) { long result, value; char numbuf[35]; while ( spacep (operands) ) operands++; if (!*operands) return NULL; result = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; if (operator == '!') result = !result; while (*operands) { while ( spacep (operands) ) operands++; if (!*operands) break; value = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; switch (operator) { case '+': result += value; break; case '-': result -= value; break; case '*': result *= value; break; case '/': if (!value) return NULL; result /= value; break; case '%': if (!value) return NULL; result %= value; break; case '!': result = !value; break; case '|': result = result || value; break; case '&': result = result && value; break; default: log_error ("unknown arithmetic operator '%c'\n", operator); return NULL; } } snprintf (numbuf, sizeof numbuf, "%ld", result); return xstrdup (numbuf); } /* Extended version of get_var. This returns a malloced string and understand the function syntax: "func args". Defined functions are get - Return a value described by the next argument: cwd - The current working directory. homedir - The gnupg homedir. sysconfdir - GnuPG's system configuration directory. bindir - GnuPG's binary directory. libdir - GnuPG's library directory. libexecdir - GnuPG's library directory for executable files. datadir - GnuPG's data directory. serverpid - The PID of the current server. unescape ARGS Remove C-style escapes from string. Note that "\0" and "\x00" terminate the string implicitly. Use "\x7d" to represent the closing brace. The args start right after the first space after the function name. unpercent ARGS unpercent+ ARGS Remove percent style ecaping from string. Note that "%00 terminates the string implicitly. Use "%7d" to represetn the closing brace. The args start right after the first space after the function name. "unpercent+" also maps '+' to space. percent ARGS percent+ ARGS Escape the args using the percent style. Tabs, formfeeds, linefeeds, carriage return, and the plus sign are also escaped. "percent+" also maps spaces to plus characters. errcode ARG Assuming ARG is an integer, return the gpg-error code. errsource ARG Assuming ARG is an integer, return the gpg-error source. errstring ARG Assuming ARG is an integer return a formatted fpf error string. Example: get_var_ext ("get sysconfdir") -> "/etc/gnupg" */ static char * get_var_ext (const char *name) { static int recursion_count; const char *s; char *result; char *p; char *free_me = NULL; int intvalue; if (recursion_count > 50) { log_error ("variables nested too deeply\n"); return NULL; } recursion_count++; free_me = opt.enable_varsubst? substitute_line_copy (name) : NULL; if (free_me) name = free_me; for (s=name; *s && !spacep (s); s++) ; if (!*s) { s = get_var (name); result = s? xstrdup (s): NULL; } else if ( (s - name) == 3 && !strncmp (name, "get", 3)) { while ( spacep (s) ) s++; if (!strcmp (s, "cwd")) { result = gnupg_getcwd (); if (!result) log_error ("getcwd failed: %s\n", strerror (errno)); } else if (!strcmp (s, "homedir")) result = xstrdup (gnupg_homedir ()); else if (!strcmp (s, "sysconfdir")) result = xstrdup (gnupg_sysconfdir ()); else if (!strcmp (s, "bindir")) result = xstrdup (gnupg_bindir ()); else if (!strcmp (s, "libdir")) result = xstrdup (gnupg_libdir ()); else if (!strcmp (s, "libexecdir")) result = xstrdup (gnupg_libexecdir ()); else if (!strcmp (s, "datadir")) result = xstrdup (gnupg_datadir ()); else if (!strcmp (s, "serverpid")) result = xasprintf ("%d", (int)server_pid); else { log_error ("invalid argument '%s' for variable function 'get'\n", s); log_info ("valid are: cwd, " "{home,bin,lib,libexec,data}dir, serverpid\n"); result = NULL; } } else if ( (s - name) == 8 && !strncmp (name, "unescape", 8)) { s++; result = unescape_string (s); } else if ( (s - name) == 9 && !strncmp (name, "unpercent", 9)) { s++; result = unpercent_string (s, 0); } else if ( (s - name) == 10 && !strncmp (name, "unpercent+", 10)) { s++; result = unpercent_string (s, 1); } else if ( (s - name) == 7 && !strncmp (name, "percent", 7)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); } else if ( (s - name) == 8 && !strncmp (name, "percent+", 8)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); for (p=result; *p; p++) if (*p == ' ') *p = '+'; } else if ( (s - name) == 7 && !strncmp (name, "errcode", 7)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_code (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errsource", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_source (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errstring", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%s <%s>", gpg_strerror (intvalue), gpg_strsource (intvalue)); } else if ( (s - name) == 1 && strchr ("+-*/%!|&", *name)) { result = arithmetic_op (*name, s+1); } else { log_error ("unknown variable function '%.*s'\n", (int)(s-name), name); result = NULL; } xfree (free_me); recursion_count--; return result; } /* Substitute variables in LINE and return a new allocated buffer if required. The function might modify LINE if the expanded version fits into it. */ static char * substitute_line (char *buffer) { char *line = buffer; char *p, *pend; const char *value; size_t valuelen, n; char *result = NULL; char *freeme = NULL; while (*line) { p = strchr (line, '$'); if (!p) return result; /* No more variables. */ if (p[1] == '$') /* Escaped dollar sign. */ { memmove (p, p+1, strlen (p+1)+1); line = p + 1; continue; } if (p[1] == '{') { int count = 0; for (pend=p+2; *pend; pend++) { if (*pend == '{') count++; else if (*pend == '}') { if (--count < 0) break; } } if (!*pend) return result; /* Unclosed - don't substitute. */ } else { for (pend=p+1; *pend && !spacep (pend) && *pend != '$' ; pend++) ; } if (p[1] == '{' && *pend == '}') { int save = *pend; *pend = 0; freeme = get_var_ext (p+2); value = freeme; *pend++ = save; } else if (*pend) { int save = *pend; *pend = 0; value = get_var (p+1); *pend = save; } else value = get_var (p+1); if (!value) value = ""; valuelen = strlen (value); if (valuelen <= pend - p) { memcpy (p, value, valuelen); p += valuelen; n = pend - p; if (n) memmove (p, p+n, strlen (p+n)+1); line = p; } else { char *src = result? result : buffer; char *dst; dst = xmalloc (strlen (src) + valuelen + 1); n = p - src; memcpy (dst, src, n); memcpy (dst + n, value, valuelen); n += valuelen; strcpy (dst + n, pend); line = dst + n; xfree (result); result = dst; } xfree (freeme); freeme = NULL; } return result; } /* Same as substitute_line but do not modify BUFFER. */ static char * substitute_line_copy (const char *buffer) { char *result, *p; p = xstrdup (buffer?buffer:""); result = substitute_line (p); if (!result) result = p; else xfree (p); return result; } static void assign_variable (char *line, int syslet) { char *name, *p, *tmp, *free_me, *buffer; /* Get the name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!*p) set_var (name, NULL); /* Remove variable. */ else if (syslet) { free_me = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (free_me) p = free_me; buffer = xmalloc (4 + strlen (p) + 1); strcpy (stpcpy (buffer, "get "), p); tmp = get_var_ext (buffer); xfree (buffer); set_var (name, tmp); xfree (tmp); xfree (free_me); } else { tmp = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (tmp) { set_var (name, tmp); xfree (tmp); } else set_var (name, p); } } static void show_variables (void) { variable_t var; for (var = variable_table; var; var = var->next) if (var->value) printf ("%-20s %s\n", var->name, var->value); } /* Store an inquire response pattern. Note, that this function may change the content of LINE. We assume that leading white spaces are already removed. */ static void add_definq (char *line, int is_var, int is_prog) { definq_t d; char *name, *p; /* Get name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; d = xmalloc (sizeof *d + strlen (p) ); strcpy (d->file, p); d->is_var = is_var; d->is_prog = is_prog; if ( !strcmp (name, "*")) d->name = NULL; else d->name = xstrdup (name); d->next = NULL; *definq_list_tail = d; definq_list_tail = &d->next; } /* Show all inquiry definitions. */ static void show_definq (void) { definq_t d; for (d=definq_list; d; d = d->next) if (d->name) printf ("%-20s %c %s\n", d->name, d->is_var? 'v' : d->is_prog? 'p':'f', d->file); for (d=definq_list; d; d = d->next) if (!d->name) printf ("%-20s %c %s\n", "*", d->is_var? 'v': d->is_prog? 'p':'f', d->file); } /* Clear all inquiry definitions. */ static void clear_definq (void) { while (definq_list) { definq_t tmp = definq_list->next; xfree (definq_list->name); xfree (definq_list); definq_list = tmp; } definq_list_tail = &definq_list; } static void do_sendfd (assuan_context_t ctx, char *line) { FILE *fp; char *name, *mode, *p; int rc, fd; /* Get file name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get mode. */ mode = p; if (!*mode) mode = "r"; else { for (p=mode; *p && !spacep (p); p++) ; if (*p) *p++ = 0; } /* Open and send. */ fp = fopen (name, mode); if (!fp) { log_error ("can't open '%s' in \"%s\" mode: %s\n", name, mode, strerror (errno)); return; } fd = fileno (fp); if (opt.verbose) log_error ("file '%s' opened in \"%s\" mode, fd=%d\n", name, mode, fd); rc = assuan_sendfd (ctx, INT2FD (fd) ); if (rc) log_error ("sending descriptor %d failed: %s\n", fd, gpg_strerror (rc)); fclose (fp); } static void do_recvfd (assuan_context_t ctx, char *line) { (void)ctx; (void)line; log_info ("This command has not yet been implemented\n"); } static void do_open (char *line) { FILE *fp; char *varname, *name, *mode, *p; int fd; #ifdef HAVE_W32_SYSTEM if (server_pid == (pid_t)(-1)) { log_error ("the pid of the server is unknown\n"); log_info ("use command \"/serverpid\" first\n"); return; } #endif /* Get variable name. */ varname = line; for (p=varname; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get file name. */ name = p; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get mode. */ mode = p; if (!*mode) mode = "r"; else { for (p=mode; *p && !spacep (p); p++) ; if (*p) *p++ = 0; } /* Open and send. */ fp = fopen (name, mode); if (!fp) { log_error ("can't open '%s' in \"%s\" mode: %s\n", name, mode, strerror (errno)); return; } fd = dup (fileno (fp)); if (fd >= 0 && fd < DIM (open_fd_table)) { open_fd_table[fd].inuse = 1; #ifdef HAVE_W32CE_SYSTEM # warning fixme: implement our pipe emulation. #endif #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) { HANDLE prochandle, handle, newhandle; handle = (void*)_get_osfhandle (fd); prochandle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, server_pid); if (!prochandle) { log_error ("failed to open the server process\n"); close (fd); return; } if (!DuplicateHandle (GetCurrentProcess(), handle, prochandle, &newhandle, 0, TRUE, DUPLICATE_SAME_ACCESS )) { log_error ("failed to duplicate the handle\n"); close (fd); CloseHandle (prochandle); return; } CloseHandle (prochandle); open_fd_table[fd].handle = newhandle; } if (opt.verbose) log_info ("file '%s' opened in \"%s\" mode, fd=%d (libc=%d)\n", name, mode, (int)open_fd_table[fd].handle, fd); set_int_var (varname, (int)open_fd_table[fd].handle); #else if (opt.verbose) log_info ("file '%s' opened in \"%s\" mode, fd=%d\n", name, mode, fd); set_int_var (varname, fd); #endif } else { log_error ("can't put fd %d into table\n", fd); if (fd != -1) close (fd); /* Table was full. */ } fclose (fp); } static void do_close (char *line) { int fd = atoi (line); #ifdef HAVE_W32_SYSTEM int i; for (i=0; i < DIM (open_fd_table); i++) if ( open_fd_table[i].inuse && open_fd_table[i].handle == (void*)fd) break; if (i < DIM (open_fd_table)) fd = i; else { log_error ("given fd (system handle) has not been opened\n"); return; } #endif if (fd < 0 || fd >= DIM (open_fd_table)) { log_error ("invalid fd\n"); return; } if (!open_fd_table[fd].inuse) { log_error ("given fd has not been opened\n"); return; } #ifdef HAVE_W32_SYSTEM CloseHandle (open_fd_table[fd].handle); /* Close duped handle. */ #endif close (fd); open_fd_table[fd].inuse = 0; } static void do_showopen (void) { int i; for (i=0; i < DIM (open_fd_table); i++) if (open_fd_table[i].inuse) { #ifdef HAVE_W32_SYSTEM printf ("%-15d (libc=%d)\n", (int)open_fd_table[i].handle, i); #else printf ("%-15d\n", i); #endif } } static gpg_error_t getinfo_pid_cb (void *opaque, const void *buffer, size_t length) { membuf_t *mb = opaque; put_membuf (mb, buffer, length); return 0; } /* Get the pid of the server and store it locally. */ static void do_serverpid (assuan_context_t ctx) { int rc; membuf_t mb; char *buffer; init_membuf (&mb, 100); rc = assuan_transact (ctx, "GETINFO pid", getinfo_pid_cb, &mb, NULL, NULL, NULL, NULL); put_membuf (&mb, "", 1); buffer = get_membuf (&mb, NULL); if (rc || !buffer) log_error ("command \"%s\" failed: %s\n", "GETINFO pid", gpg_strerror (rc)); else { server_pid = (pid_t)strtoul (buffer, NULL, 10); if (opt.verbose) log_info ("server's PID is %lu\n", (unsigned long)server_pid); } xfree (buffer); } /* Return true if the command is either "HELP" or "SCD HELP". */ static int help_cmd_p (const char *line) { if (!ascii_strncasecmp (line, "SCD", 3) && (spacep (line+3) || !line[3])) { for (line += 3; spacep (line); line++) ; } return (!ascii_strncasecmp (line, "HELP", 4) && (spacep (line+4) || !line[4])); } /* gpg-connect-agent's entry point. */ int main (int argc, char **argv) { gpgrt_argparse_t pargs; int no_more_options = 0; assuan_context_t ctx; char *line, *p; char *tmpline; size_t linesize; int rc; int cmderr; const char *opt_run = NULL; gpgrt_stream_t script_fp = NULL; int use_tty, keep_line; struct { int collecting; loopline_t head; loopline_t *tail; loopline_t current; unsigned int nestlevel; int oneshot; char *condition; } loopstack[20]; int loopidx; char **cmdline_commands = NULL; + char *historyname = NULL; early_system_init (); gnupg_rl_initialize (); gpgrt_set_strusage (my_strusage); log_set_prefix ("gpg-connect-agent", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); assuan_set_gpg_err_source (0); opt.autostart = 1; opt.connect_flags = 1; /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = ARGPARSE_FLAG_KEEP; while (!no_more_options && gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break; case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str; break; case oNoAutostart: opt.autostart = 0; break; + case oNoHistory: opt.no_history = 1; break; case oHex: opt.hex = 1; break; case oDecode: opt.decode = 1; break; case oDirmngr: opt.use_dirmngr = 1; break; case oKeyboxd: opt.use_keyboxd = 1; break; case oUIServer: opt.use_uiserver = 1; break; case oRawSocket: opt.raw_socket = pargs.r.ret_str; break; case oTcpSocket: opt.tcp_socket = pargs.r.ret_str; break; case oExec: opt.exec = 1; break; case oNoExtConnect: opt.connect_flags &= ~(1); break; case oRun: opt_run = pargs.r.ret_str; break; case oSubst: opt.enable_varsubst = 1; opt.trim_leading_spaces = 1; break; default: pargs.err = 2; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount (0)) exit (2); /* --uiserver is a shortcut for a specific raw socket. This comes in particular handy on Windows. */ if (opt.use_uiserver) { opt.raw_socket = make_absfilename (gnupg_homedir (), "S.uiserver", NULL); } /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } use_tty = (gnupg_isatty (fileno (stdin)) && gnupg_isatty (fileno (stdout))); if (opt.exec) { if (!argc) { log_error (_("option \"%s\" requires a program " "and optional arguments\n"), "--exec" ); exit (1); } } else if (argc) cmdline_commands = argv; if (opt.exec && opt.raw_socket) { opt.raw_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--raw-socket", "--exec"); } if (opt.exec && opt.tcp_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--exec"); } if (opt.tcp_socket && opt.raw_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--raw-socket"); } if (opt_run && !(script_fp = gpgrt_fopen (opt_run, "r"))) { log_error ("cannot open run file '%s': %s\n", opt_run, strerror (errno)); exit (1); } if (opt.exec) { assuan_fd_t no_close[3]; no_close[0] = assuan_fd_from_posix_fd (es_fileno (es_stderr)); no_close[1] = assuan_fd_from_posix_fd (log_get_fd ()); no_close[2] = ASSUAN_INVALID_FD; rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_pipe_connect (ctx, *argv, (const char **)argv, no_close, NULL, NULL, (opt.connect_flags & 1) ? ASSUAN_PIPE_CONNECT_FDPASSING : 0); if (rc) { log_error ("assuan_pipe_connect_ext failed: %s\n", gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("server '%s' started\n", *argv); } else if (opt.raw_socket) { rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.raw_socket, 0, (opt.connect_flags & 1) ? ASSUAN_SOCKET_CONNECT_FDPASSING : 0); if (rc) { log_error ("can't connect to socket '%s': %s\n", opt.raw_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", opt.raw_socket); } else if (opt.tcp_socket) { char *url; url = xstrconcat ("assuan://", opt.tcp_socket, NULL); rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.tcp_socket, 0, 0); if (rc) { log_error ("can't connect to server '%s': %s\n", opt.tcp_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", url); xfree (url); } else ctx = start_agent (); /* See whether there is a line pending from the server (in case assuan did not run the initial handshaking). */ if (assuan_pending_line (ctx)) { rc = read_and_print_response (ctx, 0, &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); } for (loopidx=0; loopidx < DIM (loopstack); loopidx++) loopstack[loopidx].collecting = 0; loopidx = -1; line = NULL; linesize = 0; keep_line = 1; for (;;) { int n; size_t maxlength = 2048; assert (loopidx < (int)DIM (loopstack)); if (loopidx >= 0 && loopstack[loopidx].current) { keep_line = 0; xfree (line); line = xstrdup (loopstack[loopidx].current->line); n = strlen (line); /* Never go beyond of the final /end. */ if (loopstack[loopidx].current->next) loopstack[loopidx].current = loopstack[loopidx].current->next; else if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) ; else log_fatal ("/end command vanished\n"); } else if (cmdline_commands && *cmdline_commands && !script_fp) { keep_line = 0; xfree (line); line = xstrdup (*cmdline_commands); cmdline_commands++; n = strlen (line); if (n >= maxlength) maxlength = 0; } else if (use_tty && !script_fp) { keep_line = 0; xfree (line); + if (!historyname && !opt.no_history) + { + historyname = make_filename (gnupg_homedir (), HISTORYNAME, NULL); + if (tty_read_history (historyname, 500)) + log_info ("error reading '%s': %s\n", + historyname, + gpg_strerror (gpg_error_from_syserror ())); + } + line = tty_get ("> "); n = strlen (line); if (n==1 && *line == CONTROL_D) n = 0; if (n >= maxlength) maxlength = 0; } else { if (!keep_line) { xfree (line); line = NULL; linesize = 0; keep_line = 1; } n = gpgrt_read_line (script_fp ? script_fp : gpgrt_stdin, &line, &linesize, &maxlength); } if (n < 0) { log_error (_("error reading input: %s\n"), strerror (errno)); if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; log_error ("stopping script execution\n"); continue; } exit (1); } if (!n) { /* EOF */ if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; if (opt.verbose) log_info ("end of script\n"); continue; } break; } if (!maxlength) { log_error (_("line too long - skipped\n")); continue; } if (memchr (line, 0, n)) log_info (_("line shortened due to embedded Nul character\n")); if (line[n-1] == '\n') line[n-1] = 0; if (opt.trim_leading_spaces) { const char *s = line; while (spacep (s)) s++; if (s != line) { for (p=line; *s;) *p++ = *s++; *p = 0; n = p - line; } } if (loopidx+1 >= 0 && loopstack[loopidx+1].collecting) { loopline_t ll; ll = xmalloc (sizeof *ll + strlen (line)); ll->next = NULL; strcpy (ll->line, line); *loopstack[loopidx+1].tail = ll; loopstack[loopidx+1].tail = &ll->next; if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) loopstack[loopidx+1].nestlevel--; else if (!strncmp (line, "/while", 6) && (!line[6]||spacep(line+6))) loopstack[loopidx+1].nestlevel++; if (loopstack[loopidx+1].nestlevel) continue; /* We reached the corresponding /end. */ loopstack[loopidx+1].collecting = 0; loopidx++; } if (*line == '/') { /* Handle control commands. */ char *cmd = line+1; for (p=cmd; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!strcmp (cmd, "let")) { assign_variable (p, 0); } else if (!strcmp (cmd, "slet")) { /* Deprecated - never used in a released version. */ assign_variable (p, 1); } else if (!strcmp (cmd, "showvar")) { show_variables (); } else if (!strcmp (cmd, "definq")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 1, 0); xfree (tmpline); } else add_definq (p, 1, 0); } else if (!strcmp (cmd, "definqfile")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 0); xfree (tmpline); } else add_definq (p, 0, 0); } else if (!strcmp (cmd, "definqprog")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 1); xfree (tmpline); } else add_definq (p, 0, 1); } else if (!strcmp (cmd, "datafile")) { const char *fname; if (current_datasink) { if (current_datasink != stdout) fclose (current_datasink); current_datasink = NULL; } tmpline = opt.enable_varsubst? substitute_line (p) : NULL; fname = tmpline? tmpline : p; if (fname && !strcmp (fname, "-")) current_datasink = stdout; else if (fname && *fname) { current_datasink = fopen (fname, "wb"); if (!current_datasink) log_error ("can't open '%s': %s\n", fname, strerror (errno)); } xfree (tmpline); } else if (!strcmp (cmd, "showdef")) { show_definq (); } else if (!strcmp (cmd, "cleardef")) { clear_definq (); } else if (!strcmp (cmd, "echo")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { puts (tmpline); xfree (tmpline); } else puts (p); } else if (!strcmp (cmd, "sendfd")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_sendfd (ctx, tmpline); xfree (tmpline); } else do_sendfd (ctx, p); continue; } else if (!strcmp (cmd, "recvfd")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_recvfd (ctx, tmpline); xfree (tmpline); } else do_recvfd (ctx, p); continue; } else if (!strcmp (cmd, "open")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_open (tmpline); xfree (tmpline); } else do_open (p); } else if (!strcmp (cmd, "close")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_close (tmpline); xfree (tmpline); } else do_close (p); } else if (!strcmp (cmd, "showopen")) { do_showopen (); } else if (!strcmp (cmd, "serverpid")) { do_serverpid (ctx); } else if (!strcmp (cmd, "hex")) opt.hex = 1; else if (!strcmp (cmd, "nohex")) opt.hex = 0; else if (!strcmp (cmd, "decode")) opt.decode = 1; else if (!strcmp (cmd, "nodecode")) opt.decode = 0; else if (!strcmp (cmd, "subst")) { opt.enable_varsubst = 1; opt.trim_leading_spaces = 1; } else if (!strcmp (cmd, "nosubst")) opt.enable_varsubst = 0; else if (!strcmp (cmd, "run")) { char *p2; for (p2=p; *p2 && !spacep (p2); p2++) ; if (*p2) *p2++ = 0; while (spacep (p2)) p++; if (*p2) { log_error ("syntax error in run command\n"); if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; } } else if (script_fp) { log_error ("cannot nest run commands - stop\n"); gpgrt_fclose (script_fp); script_fp = NULL; } else if (!(script_fp = gpgrt_fopen (p, "r"))) { log_error ("cannot open run file '%s': %s\n", p, strerror (errno)); } else if (opt.verbose) log_info ("running commands from '%s'\n", p); } else if (!strcmp (cmd, "while")) { if (loopidx+2 >= (int)DIM(loopstack)) { log_error ("blocks are nested too deep\n"); /* We should better die or break all loop in this case as recovering from this error won't be easy. */ } else { loopstack[loopidx+1].head = NULL; loopstack[loopidx+1].tail = &loopstack[loopidx+1].head; loopstack[loopidx+1].current = NULL; loopstack[loopidx+1].nestlevel = 1; loopstack[loopidx+1].oneshot = 0; loopstack[loopidx+1].condition = xstrdup (p); loopstack[loopidx+1].collecting = 1; } } else if (!strcmp (cmd, "if")) { if (loopidx+2 >= (int)DIM(loopstack)) { log_error ("blocks are nested too deep\n"); } else { /* Note that we need to evaluate the condition right away and not just at the end of the block as we do with a WHILE. */ loopstack[loopidx+1].head = NULL; loopstack[loopidx+1].tail = &loopstack[loopidx+1].head; loopstack[loopidx+1].current = NULL; loopstack[loopidx+1].nestlevel = 1; loopstack[loopidx+1].oneshot = 1; loopstack[loopidx+1].condition = substitute_line_copy (p); loopstack[loopidx+1].collecting = 1; } } else if (!strcmp (cmd, "end")) { if (loopidx < 0) log_error ("stray /end command encountered - ignored\n"); else { char *tmpcond; const char *value; long condition; /* Evaluate the condition. */ tmpcond = xstrdup (loopstack[loopidx].condition); if (loopstack[loopidx].oneshot) { xfree (loopstack[loopidx].condition); loopstack[loopidx].condition = xstrdup ("0"); } tmpline = substitute_line (tmpcond); value = tmpline? tmpline : tmpcond; /* "true" or "yes" are commonly used to mean TRUE; all other strings will evaluate to FALSE due to the strtoul. */ if (!ascii_strcasecmp (value, "true") || !ascii_strcasecmp (value, "yes")) condition = 1; else condition = strtol (value, NULL, 0); xfree (tmpline); xfree (tmpcond); if (condition) { /* Run loop. */ loopstack[loopidx].current = loopstack[loopidx].head; } else { /* Cleanup. */ while (loopstack[loopidx].head) { loopline_t tmp = loopstack[loopidx].head->next; xfree (loopstack[loopidx].head); loopstack[loopidx].head = tmp; } loopstack[loopidx].tail = NULL; loopstack[loopidx].current = NULL; loopstack[loopidx].nestlevel = 0; loopstack[loopidx].collecting = 0; loopstack[loopidx].oneshot = 0; xfree (loopstack[loopidx].condition); loopstack[loopidx].condition = NULL; loopidx--; } } } else if (!strcmp (cmd, "bye") || !strcmp (cmd, "quit")) { break; } else if (!strcmp (cmd, "sleep")) { gnupg_sleep (1); } + else if (!strcmp (cmd, "history")) + { + if (!strcmp (p, "--clear")) + { + tty_read_history (NULL, 0); + } + else + log_error ("Only \"/history --clear\" is supported\n"); + } else if (!strcmp (cmd, "help")) { puts ( "Available commands:\n" "/echo ARGS Echo ARGS.\n" "/let NAME VALUE Set variable NAME to VALUE.\n" "/showvar Show all variables.\n" "/definq NAME VAR Use content of VAR for inquiries with NAME.\n" "/definqfile NAME FILE Use content of FILE for inquiries with NAME.\n" "/definqprog NAME PGM Run PGM for inquiries with NAME.\n" "/datafile [NAME] Write all D line content to file NAME.\n" "/showdef Print all definitions.\n" "/cleardef Delete all definitions.\n" "/sendfd FILE MODE Open FILE and pass descriptor to server.\n" "/recvfd Receive FD from server and print.\n" "/open VAR FILE MODE Open FILE and assign the file descriptor to VAR.\n" "/close FD Close file with descriptor FD.\n" "/showopen Show descriptors of all open files.\n" "/serverpid Retrieve the pid of the server.\n" "/[no]hex Enable hex dumping of received data lines.\n" "/[no]decode Enable decoding of received data lines.\n" "/[no]subst Enable variable substitution.\n" "/run FILE Run commands from FILE.\n" "/if VAR Begin conditional block controlled by VAR.\n" "/while VAR Begin loop controlled by VAR.\n" "/end End loop or condition\n" +"/history Manage the history\n" "/bye Terminate gpg-connect-agent.\n" "/help Print this help."); } else log_error (_("unknown command '%s'\n"), cmd ); continue; } if (opt.verbose && script_fp) puts (line); tmpline = opt.enable_varsubst? substitute_line (line) : NULL; if (tmpline) { rc = assuan_write_line (ctx, tmpline); xfree (tmpline); } else rc = assuan_write_line (ctx, line); if (rc) { log_info (_("sending line failed: %s\n"), gpg_strerror (rc) ); break; } if (*line == '#' || !*line) continue; /* Don't expect a response for a comment line. */ rc = read_and_print_response (ctx, help_cmd_p (line), &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); if ((rc || cmderr) && script_fp) { log_error ("stopping script execution\n"); gpgrt_fclose (script_fp); script_fp = NULL; } /* FIXME: If the last command was BYE or the server died for some other reason, we won't notice until we get the next input command. Probing the connection with a non-blocking read could help to notice termination or other problems early. */ } if (opt.verbose) log_info ("closing connection to %s\n", opt.use_dirmngr? "dirmngr" : opt.use_keyboxd? "keyboxd" : "agent"); + + if (historyname && tty_write_history (historyname)) + log_info ("error writing '%s': %s\n", + historyname, gpg_strerror (gpg_error_from_syserror ())); + + /* XXX: We would like to release the context here, but libassuan nicely says good bye to the server, which results in a SIGPIPE if the server died. Unfortunately, libassuan does not ignore SIGPIPE when used with UNIX sockets, hence we simply leak the context here. */ if (0) assuan_release (ctx); else gpgrt_annotate_leaked_object (ctx); + xfree (historyname); xfree (line); return 0; } /* Handle an Inquire from the server. Return False if it could not be handled; in this case the caller shll complete the operation. LINE is the complete line as received from the server. This function may change the content of LINE. */ static int handle_inquire (assuan_context_t ctx, char *line) { const char *name; definq_t d; FILE *fp = NULL; char buffer[1024]; int rc, n; /* Skip the command and trailing spaces. */ for (; *line && !spacep (line); line++) ; while (spacep (line)) line++; /* Get the name. */ name = line; for (; *line && !spacep (line); line++) ; if (*line) *line++ = 0; /* Now match it against our list. The second loop is there to detect the match-all entry. */ for (d=definq_list; d; d = d->next) if (d->name && !strcmp (d->name, name)) break; if (!d) for (d=definq_list; d; d = d->next) if (!d->name) break; if (!d) { if (opt.verbose) log_info ("no handler for inquiry '%s' found\n", name); return 0; } if (d->is_var) { char *tmpvalue = get_var_ext (d->file); if (tmpvalue) rc = assuan_send_data (ctx, tmpvalue, strlen (tmpvalue)); else rc = assuan_send_data (ctx, "", 0); xfree (tmpvalue); if (rc) log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); } else { if (d->is_prog) { #ifdef HAVE_W32CE_SYSTEM fp = NULL; #else fp = popen (d->file, "r"); #endif if (!fp) log_error ("error executing '%s': %s\n", d->file, strerror (errno)); else if (opt.verbose) log_error ("handling inquiry '%s' by running '%s'\n", name, d->file); } else { fp = fopen (d->file, "rb"); if (!fp) log_error ("error opening '%s': %s\n", d->file, strerror (errno)); else if (opt.verbose) log_error ("handling inquiry '%s' by returning content of '%s'\n", name, d->file); } if (!fp) return 0; while ( (n = fread (buffer, 1, sizeof buffer, fp)) ) { rc = assuan_send_data (ctx, buffer, n); if (rc) { log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); break; } } if (ferror (fp)) log_error ("error reading from '%s': %s\n", d->file, strerror (errno)); } rc = assuan_send_data (ctx, NULL, 0); if (rc) log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); if (d->is_var) ; else if (d->is_prog) { #ifndef HAVE_W32CE_SYSTEM if (pclose (fp)) log_error ("error running '%s': %s\n", d->file, strerror (errno)); #endif } else fclose (fp); return 1; } /* Read all response lines from server and print them. Returns 0 on success or an assuan error code. If WITHHASH istrue, comment lines are printed. Sets R_GOTERR to true if the command did not returned OK. */ static int read_and_print_response (assuan_context_t ctx, int withhash, int *r_goterr) { char *line; size_t linelen; gpg_error_t rc; int i, j; int need_lf = 0; *r_goterr = 0; for (;;) { do { rc = assuan_read_line (ctx, &line, &linelen); if (rc) return rc; if ((withhash || opt.verbose > 1) && *line == '#') { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } while (*line == '#' || !linelen); if (linelen >= 1 && line[0] == 'D' && line[1] == ' ') { if (current_datasink) { const unsigned char *s; int c = 0; for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ ) { if (*s == '%' && j+2 < linelen) { s++; j++; c = xtoi_2 ( s ); s++; j++; } else c = *s; putc (c, current_datasink); } } else if (opt.hex) { for (i=2; i < linelen; ) { int save_i = i; printf ("D[%04X] ", i-2); for (j=0; j < 16 ; j++, i++) { if (j == 8) putchar (' '); if (i < linelen) printf (" %02X", ((unsigned char*)line)[i]); else fputs (" ", stdout); } fputs (" ", stdout); i= save_i; for (j=0; j < 16; j++, i++) { unsigned int c = ((unsigned char*)line)[i]; if ( i >= linelen ) putchar (' '); else if (isascii (c) && isprint (c) && !iscntrl (c)) putchar (c); else putchar ('.'); } putchar ('\n'); } } else if (opt.decode) { const unsigned char *s; int need_d = 1; int c = 0; for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ ) { if (need_d) { fputs ("D ", stdout); need_d = 0; } if (*s == '%' && j+2 < linelen) { s++; j++; c = xtoi_2 ( s ); s++; j++; } else c = *s; if (c == '\n') need_d = 1; putchar (c); } need_lf = (c != '\n'); } else { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } else { if (need_lf) { if (!current_datasink || current_datasink != stdout) putchar ('\n'); need_lf = 0; } if (linelen >= 1 && line[0] == 'S' && (line[1] == '\0' || line[1] == ' ')) { if (!current_datasink || current_datasink != stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } else if (linelen >= 2 && line[0] == 'O' && line[1] == 'K' && (line[2] == '\0' || line[2] == ' ')) { if (!current_datasink || current_datasink != stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } set_int_var ("?", 0); return 0; } else if (linelen >= 3 && line[0] == 'E' && line[1] == 'R' && line[2] == 'R' && (line[3] == '\0' || line[3] == ' ')) { int errval; errval = strtol (line+3, NULL, 10); if (!errval) errval = -1; set_int_var ("?", errval); if (!current_datasink || current_datasink != stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } *r_goterr = 1; return 0; } else if (linelen >= 7 && line[0] == 'I' && line[1] == 'N' && line[2] == 'Q' && line[3] == 'U' && line[4] == 'I' && line[5] == 'R' && line[6] == 'E' && (line[7] == '\0' || line[7] == ' ')) { if (!current_datasink || current_datasink != stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } if (!handle_inquire (ctx, line)) assuan_write_line (ctx, "CANCEL"); } else if (linelen >= 3 && line[0] == 'E' && line[1] == 'N' && line[2] == 'D' && (line[3] == '\0' || line[3] == ' ')) { if (!current_datasink || current_datasink != stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } /* Received from server, thus more responses are expected. */ } else return gpg_error (GPG_ERR_ASS_INV_RESPONSE); } } } /* Connect to the agent and send the standard options. */ static assuan_context_t start_agent (void) { gpg_error_t err; assuan_context_t ctx; session_env_t session_env; session_env = session_env_new (); if (!session_env) log_fatal ("error allocating session environment block: %s\n", strerror (errno)); if (opt.use_dirmngr) err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, !opt.quiet, 0, NULL, NULL); else if (opt.use_keyboxd) err = start_new_keyboxd (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.keyboxd_program, opt.autostart, !opt.quiet, 0, NULL, NULL); else err = start_new_gpg_agent (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, NULL, NULL, session_env, opt.autostart, !opt.quiet, 0, NULL, NULL); session_env_release (session_env); if (err) { if (!opt.autostart && (gpg_err_code (err) == (opt.use_dirmngr? GPG_ERR_NO_DIRMNGR : opt.use_keyboxd? GPG_ERR_NO_KEYBOXD : GPG_ERR_NO_AGENT))) { /* In the no-autostart case we don't make gpg-connect-agent fail on a missing server. */ log_info (opt.use_dirmngr? _("no dirmngr running in this session\n"): opt.use_keyboxd? _("no keybox daemon running in this session\n"): _("no gpg-agent running in this session\n")); exit (0); } else { log_error (_("error sending standard options: %s\n"), gpg_strerror (err)); exit (1); } } return ctx; }