diff --git a/common/stringhelp.c b/common/stringhelp.c
index 509d327b0..3b481e862 100644
--- a/common/stringhelp.c
+++ b/common/stringhelp.c
@@ -1,1574 +1,1578 @@
/* stringhelp.c - standard string helper functions
* Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
* 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright (C) 2014 Werner Koch
* Copyright (C) 2015 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute and/or modify this
* part of GnuPG 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.
*
* 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 copies of the GNU General Public License
* and the GNU Lesser General Public License along with this program;
* if not, see .
*/
#include
#include
#include
#include
#include
#include
#ifdef HAVE_PWD_H
# include
#endif
#include
#include
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
#endif
#include
#include
#include "util.h"
#include "common-defs.h"
#include "utf8conv.h"
#include "sysutils.h"
#include "stringhelp.h"
#define tohex_lower(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'a'))
/* Sometimes we want to avoid mixing slashes and backslashes on W32
and prefer backslashes. There is usual no problem with mixing
them, however a very few W32 API calls can't grok plain slashes.
Printing filenames with mixed slashes also looks a bit strange.
This function has no effext on POSIX. */
static inline char *
change_slashes (char *name)
{
#ifdef HAVE_DOSISH_SYSTEM
char *p;
if (strchr (name, '\\'))
{
for (p=name; *p; p++)
if (*p == '/')
*p = '\\';
}
#endif /*HAVE_DOSISH_SYSTEM*/
return name;
}
/*
* Check whether STRING starts with KEYWORD. The keyword is
* delimited by end of string, a space or a tab. Returns NULL if not
* found or a pointer into STRING to the next non-space character
* after the KEYWORD (which may be end of string).
*/
char *
has_leading_keyword (const char *string, const char *keyword)
{
size_t n = strlen (keyword);
if (!strncmp (string, keyword, n)
&& (!string[n] || string[n] == ' ' || string[n] == '\t'))
{
string += n;
while (*string == ' ' || *string == '\t')
string++;
return (char*)string;
}
return NULL;
}
/*
* Look for the substring SUB in buffer and return a pointer to that
* substring in BUFFER or NULL if not found.
* Comparison is case-insensitive.
*/
const char *
memistr (const void *buffer, size_t buflen, const char *sub)
{
const unsigned char *buf = buffer;
const unsigned char *t = (const unsigned char *)buffer;
const unsigned char *s = (const unsigned char *)sub;
size_t n = buflen;
for ( ; n ; t++, n-- )
{
if ( toupper (*t) == toupper (*s) )
{
for ( buf=t++, buflen = n--, s++;
n && toupper (*t) == toupper (*s); t++, s++, n-- )
;
if (!*s)
return (const char*)buf;
t = buf;
s = (const unsigned char *)sub ;
n = buflen;
}
}
return NULL;
}
const char *
ascii_memistr ( const void *buffer, size_t buflen, const char *sub )
{
const unsigned char *buf = buffer;
const unsigned char *t = (const unsigned char *)buf;
const unsigned char *s = (const unsigned char *)sub;
size_t n = buflen;
for ( ; n ; t++, n-- )
{
if (ascii_toupper (*t) == ascii_toupper (*s) )
{
for ( buf=t++, buflen = n--, s++;
n && ascii_toupper (*t) == ascii_toupper (*s); t++, s++, n-- )
;
if (!*s)
return (const char*)buf;
t = (const unsigned char *)buf;
s = (const unsigned char *)sub ;
n = buflen;
}
}
return NULL;
}
/* This function is similar to strncpy(). However it won't copy more
than N - 1 characters and makes sure that a '\0' is appended. With
N given as 0, nothing will happen. With DEST given as NULL, memory
will be allocated using xmalloc (i.e. if it runs out of core
the function terminates). Returns DES or a pointer to the
allocated memory.
*/
char *
mem2str( char *dest , const void *src , size_t n )
{
char *d;
const char *s;
if( n ) {
if( !dest )
dest = xmalloc( n ) ;
d = dest;
s = src ;
for(n--; n && *s; n-- )
*d++ = *s++;
*d = '\0' ;
}
return dest ;
}
/****************
* remove leading and trailing white spaces
*/
char *
trim_spaces( char *str )
{
char *string, *p, *mark;
string = str;
/* find first non space character */
for( p=string; *p && isspace( *(byte*)p ) ; p++ )
;
/* move characters */
for( (mark = NULL); (*string = *p); string++, p++ )
if( isspace( *(byte*)p ) ) {
if( !mark )
mark = string ;
}
else
mark = NULL ;
if( mark )
*mark = '\0' ; /* remove trailing spaces */
return str ;
}
/****************
* remove trailing white spaces
*/
char *
trim_trailing_spaces( char *string )
{
char *p, *mark;
for( mark = NULL, p = string; *p; p++ ) {
if( isspace( *(byte*)p ) ) {
if( !mark )
mark = p;
}
else
mark = NULL;
}
if( mark )
*mark = '\0' ;
return string ;
}
unsigned
trim_trailing_chars( byte *line, unsigned len, const char *trimchars )
{
byte *p, *mark;
unsigned n;
for(mark=NULL, p=line, n=0; n < len; n++, p++ ) {
if( strchr(trimchars, *p ) ) {
if( !mark )
mark = p;
}
else
mark = NULL;
}
if( mark ) {
*mark = 0;
return mark - line;
}
return len;
}
/****************
* remove trailing white spaces and return the length of the buffer
*/
unsigned
trim_trailing_ws( byte *line, unsigned len )
{
return trim_trailing_chars( line, len, " \t\r\n" );
}
size_t
length_sans_trailing_chars (const unsigned char *line, size_t len,
const char *trimchars )
{
const unsigned char *p, *mark;
size_t n;
for( mark=NULL, p=line, n=0; n < len; n++, p++ )
{
if (strchr (trimchars, *p ))
{
if( !mark )
mark = p;
}
else
mark = NULL;
}
if (mark)
return mark - line;
return len;
}
/*
* Return the length of line ignoring trailing white-space.
*/
size_t
length_sans_trailing_ws (const unsigned char *line, size_t len)
{
return length_sans_trailing_chars (line, len, " \t\r\n");
}
/*
* Extract from a given path the filename component. This function
* terminates the process on memory shortage.
*/
char *
make_basename(const char *filepath, const char *inputpath)
{
#ifdef __riscos__
return riscos_make_basename(filepath, inputpath);
#else
char *p;
(void)inputpath; /* Only required for riscos. */
if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
if ( !(p=strrchr(filepath, ':')) )
#endif
{
return xstrdup(filepath);
}
return xstrdup(p+1);
#endif
}
/*
* Extract from a given filename the path prepended to it. If there
* isn't a path prepended to the filename, a dot is returned ('.').
* This function terminates the process on memory shortage.
*/
char *
make_dirname(const char *filepath)
{
char *dirname;
int dirname_length;
char *p;
if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
if ( !(p=strrchr(filepath, ':')) )
#endif
{
return xstrdup(".");
}
dirname_length = p-filepath;
dirname = xmalloc(dirname_length+1);
strncpy(dirname, filepath, dirname_length);
dirname[dirname_length] = 0;
return dirname;
}
static char *
get_pwdir (int xmode, const char *name)
{
char *result = NULL;
#ifdef HAVE_PWD_H
struct passwd *pwd = NULL;
if (name)
{
#ifdef HAVE_GETPWNAM
/* Fixme: We should use getpwnam_r if available. */
pwd = getpwnam (name);
#endif
}
else
{
#ifdef HAVE_GETPWUID
/* Fixme: We should use getpwuid_r if available. */
pwd = getpwuid (getuid());
#endif
}
if (pwd)
{
if (xmode)
result = xstrdup (pwd->pw_dir);
else
result = xtrystrdup (pwd->pw_dir);
}
#else /*!HAVE_PWD_H*/
/* No support at all. */
(void)xmode;
(void)name;
#endif /*HAVE_PWD_H*/
return result;
}
/* xmode 0 := Return NULL on error
1 := Terminate on error
2 := Make sure that name is absolute; return NULL on error
3 := Make sure that name is absolute; terminate on error
*/
static char *
do_make_filename (int xmode, const char *first_part, va_list arg_ptr)
{
const char *argv[32];
int argc;
size_t n;
int skip = 1;
char *home_buffer = NULL;
char *name, *home, *p;
int want_abs;
want_abs = !!(xmode & 2);
xmode &= 1;
n = strlen (first_part) + 1;
argc = 0;
while ( (argv[argc] = va_arg (arg_ptr, const char *)) )
{
n += strlen (argv[argc]) + 1;
if (argc >= DIM (argv)-1)
{
if (xmode)
BUG ();
gpg_err_set_errno (EINVAL);
return NULL;
}
argc++;
}
n++;
home = NULL;
if (*first_part == '~')
{
if (first_part[1] == '/' || !first_part[1])
{
/* This is the "~/" or "~" case. */
home = getenv("HOME");
if (!home)
home = home_buffer = get_pwdir (xmode, NULL);
if (home && *home)
n += strlen (home);
}
else
{
/* This is the "~username/" or "~username" case. */
char *user;
if (xmode)
user = xstrdup (first_part+1);
else
{
user = xtrystrdup (first_part+1);
if (!user)
return NULL;
}
p = strchr (user, '/');
if (p)
*p = 0;
skip = 1 + strlen (user);
home = home_buffer = get_pwdir (xmode, user);
xfree (user);
if (home)
n += strlen (home);
else
skip = 1;
}
}
if (xmode)
name = xmalloc (n);
else
{
name = xtrymalloc (n);
if (!name)
{
xfree (home_buffer);
return NULL;
}
}
if (home)
p = stpcpy (stpcpy (name, home), first_part + skip);
else
p = stpcpy (name, first_part);
xfree (home_buffer);
for (argc=0; argv[argc]; argc++)
{
/* Avoid a leading double slash if the first part was "/". */
if (!argc && name[0] == '/' && !name[1])
p = stpcpy (p, argv[argc]);
else
p = stpcpy (stpcpy (p, "/"), argv[argc]);
}
if (want_abs)
{
#ifdef HAVE_DRIVE_LETTERS
p = strchr (name, ':');
if (p)
p++;
else
p = name;
#else
p = name;
#endif
if (*p != '/'
#ifdef HAVE_DRIVE_LETTERS
&& *p != '\\'
#endif
)
{
home = gnupg_getcwd ();
if (!home)
{
if (xmode)
{
fprintf (stderr, "\nfatal: getcwd failed: %s\n",
strerror (errno));
exit(2);
}
xfree (name);
return NULL;
}
n = strlen (home) + 1 + strlen (name) + 1;
if (xmode)
home_buffer = xmalloc (n);
else
{
home_buffer = xtrymalloc (n);
if (!home_buffer)
{
xfree (home);
xfree (name);
return NULL;
}
}
if (p == name)
p = home_buffer;
else /* Windows case. */
{
memcpy (home_buffer, p, p - name + 1);
p = home_buffer + (p - name + 1);
}
/* Avoid a leading double slash if the cwd is "/". */
if (home[0] == '/' && !home[1])
strcpy (stpcpy (p, "/"), name);
else
strcpy (stpcpy (stpcpy (p, home), "/"), name);
xfree (home);
xfree (name);
name = home_buffer;
/* Let's do a simple compression to catch the most common
case of using "." for gpg's --homedir option. */
n = strlen (name);
if (n > 2 && name[n-2] == '/' && name[n-1] == '.')
name[n-2] = 0;
}
}
return change_slashes (name);
}
/* Construct a filename from the NULL terminated list of parts. Tilde
expansion is done for the first argument. This function terminates
the process on memory shortage. */
char *
make_filename (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (1, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct a filename from the NULL terminated list of parts. Tilde
expansion is done for the first argument. This function may return
NULL on error. */
char *
make_filename_try (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (0, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct an absolute filename from the NULL terminated list of
parts. Tilde expansion is done for the first argument. This
function terminates the process on memory shortage. */
char *
make_absfilename (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (3, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct an absolute filename from the NULL terminated list of
parts. Tilde expansion is done for the first argument. This
function may return NULL on error. */
char *
make_absfilename_try (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (2, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Compare whether the filenames are identical. This is a
special version of strcmp() taking the semantics of filenames in
account. Note that this function works only on the supplied names
without considering any context like the current directory. See
also same_file_p(). */
int
compare_filenames (const char *a, const char *b)
{
#ifdef HAVE_DOSISH_SYSTEM
for ( ; *a && *b; a++, b++ )
{
if (*a != *b
&& (toupper (*(const unsigned char*)a)
!= toupper (*(const unsigned char*)b) )
&& !((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/')))
break;
}
if ((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/'))
return 0;
else
return (toupper (*(const unsigned char*)a)
- toupper (*(const unsigned char*)b));
#else
return strcmp(a,b);
#endif
}
/* Convert a base-10 number in STRING into a 64 bit unsigned int
* value. Leading white spaces are skipped but no error checking is
* done. Thus it is similar to atoi(). */
uint64_t
string_to_u64 (const char *string)
{
uint64_t val = 0;
while (spacep (string))
string++;
for (; digitp (string); string++)
{
val *= 10;
val += *string - '0';
}
return val;
}
/* Convert 2 hex characters at S to a byte value. Return this value
or -1 if there is an error. */
int
hextobyte (const char *s)
{
int c;
if ( *s >= '0' && *s <= '9' )
c = 16 * (*s - '0');
else if ( *s >= 'A' && *s <= 'F' )
c = 16 * (10 + *s - 'A');
else if ( *s >= 'a' && *s <= 'f' )
c = 16 * (10 + *s - 'a');
else
return -1;
s++;
if ( *s >= '0' && *s <= '9' )
c += *s - '0';
else if ( *s >= 'A' && *s <= 'F' )
c += 10 + *s - 'A';
else if ( *s >= 'a' && *s <= 'f' )
c += 10 + *s - 'a';
else
return -1;
return c;
}
/* Given a string containing an UTF-8 encoded text, return the number
of characters in this string. It differs from strlen in that it
only counts complete UTF-8 characters. SIZE is the maximum length
of the string in bytes. If SIZE is -1, then a NUL character is
taken to be the end of the string. Note, that this function does
not take combined characters into account. */
size_t
utf8_charcount (const char *s, int len)
{
size_t n;
if (len == 0)
return 0;
for (n=0; *s; s++)
{
if ( (*s&0xc0) != 0x80 ) /* Exclude continuation bytes: 10xxxxxx */
n++;
if (len != -1)
{
len --;
if (len == 0)
break;
}
}
return n;
}
/****************************************************
********** W32 specific functions ****************
****************************************************/
#ifdef HAVE_W32_SYSTEM
const char *
w32_strerror (int ec)
{
static char strerr[256];
if (ec == -1)
ec = (int)GetLastError ();
#ifdef HAVE_W32CE_SYSTEM
/* There is only a wchar_t FormatMessage. It does not make much
sense to play the conversion game; we print only the code. */
snprintf (strerr, sizeof strerr, "ec=%d", (int)GetLastError ());
#else
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, ec,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
strerr, DIM (strerr)-1, NULL);
#endif
return strerr;
}
#endif /*HAVE_W32_SYSTEM*/
/****************************************************
******** Locale insensitive ctype functions ********
****************************************************/
/* FIXME: replace them by a table lookup and macros */
int
ascii_isupper (int c)
{
return c >= 'A' && c <= 'Z';
}
int
ascii_islower (int c)
{
return c >= 'a' && c <= 'z';
}
int
ascii_toupper (int c)
{
if (c >= 'a' && c <= 'z')
c &= ~0x20;
return c;
}
int
ascii_tolower (int c)
{
if (c >= 'A' && c <= 'Z')
c |= 0x20;
return c;
}
/* Lowercase all ASCII characters in S. */
char *
ascii_strlwr (char *s)
{
char *p = s;
for (p=s; *p; p++ )
if (isascii (*p) && *p >= 'A' && *p <= 'Z')
*p |= 0x20;
return s;
}
int
ascii_strcasecmp( const char *a, const char *b )
{
if (a == b)
return 0;
for (; *a && *b; a++, b++) {
if (*a != *b && ascii_toupper(*a) != ascii_toupper(*b))
break;
}
return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
}
int
ascii_strncasecmp (const char *a, const char *b, size_t n)
{
const unsigned char *p1 = (const unsigned char *)a;
const unsigned char *p2 = (const unsigned char *)b;
unsigned char c1, c2;
if (p1 == p2 || !n )
return 0;
do
{
c1 = ascii_tolower (*p1);
c2 = ascii_tolower (*p2);
if ( !--n || c1 == '\0')
break;
++p1;
++p2;
}
while (c1 == c2);
return c1 - c2;
}
int
ascii_memcasecmp (const void *a_arg, const void *b_arg, size_t n )
{
const char *a = a_arg;
const char *b = b_arg;
if (a == b)
return 0;
for ( ; n; n--, a++, b++ )
{
if( *a != *b && ascii_toupper (*a) != ascii_toupper (*b) )
return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
}
return 0;
}
int
ascii_strcmp( const char *a, const char *b )
{
if (a == b)
return 0;
for (; *a && *b; a++, b++) {
if (*a != *b )
break;
}
return *a == *b? 0 : (*(signed char *)a - *(signed char *)b);
}
void *
ascii_memcasemem (const void *haystack, size_t nhaystack,
const void *needle, size_t nneedle)
{
if (!nneedle)
return (void*)haystack; /* finding an empty needle is really easy */
if (nneedle <= nhaystack)
{
const char *a = haystack;
const char *b = a + nhaystack - nneedle;
for (; a <= b; a++)
{
if ( !ascii_memcasecmp (a, needle, nneedle) )
return (void *)a;
}
}
return NULL;
}
/*********************************************
********** missing string functions *********
*********************************************/
#ifndef HAVE_STPCPY
char *
stpcpy(char *a,const char *b)
{
while( *b )
*a++ = *b++;
*a = 0;
return (char*)a;
}
#endif
#ifndef HAVE_STRPBRK
/* Find the first occurrence in S of any character in ACCEPT.
Code taken from glibc-2.6/string/strpbrk.c (LGPLv2.1+) and modified. */
char *
strpbrk (const char *s, const char *accept)
{
while (*s != '\0')
{
const char *a = accept;
while (*a != '\0')
if (*a++ == *s)
return (char *) s;
++s;
}
return NULL;
}
#endif /*!HAVE_STRPBRK*/
#ifndef HAVE_STRSEP
/* Code taken from glibc-2.2.1/sysdeps/generic/strsep.c. */
char *
strsep (char **stringp, const char *delim)
{
char *begin, *end;
begin = *stringp;
if (begin == NULL)
return NULL;
/* A frequent case is when the delimiter string contains only one
character. Here we don't need to call the expensive 'strpbrk'
function and instead work using 'strchr'. */
if (delim[0] == '\0' || delim[1] == '\0')
{
char ch = delim[0];
if (ch == '\0')
end = NULL;
else
{
if (*begin == ch)
end = begin;
else if (*begin == '\0')
end = NULL;
else
end = strchr (begin + 1, ch);
}
}
else
/* Find the end of the token. */
end = strpbrk (begin, delim);
if (end)
{
/* Terminate the token and set *STRINGP past NUL character. */
*end++ = '\0';
*stringp = end;
}
else
/* No more delimiters; this is the last token. */
*stringp = NULL;
return begin;
}
#endif /*HAVE_STRSEP*/
#ifndef HAVE_STRLWR
char *
strlwr(char *s)
{
char *p;
for(p=s; *p; p++ )
*p = tolower(*p);
return s;
}
#endif
#ifndef HAVE_STRCASECMP
int
strcasecmp( const char *a, const char *b )
{
for( ; *a && *b; a++, b++ ) {
if( *a != *b && toupper(*a) != toupper(*b) )
break;
}
return *(const byte*)a - *(const byte*)b;
}
#endif
/****************
* mingw32/cpd has a memicmp()
*/
#ifndef HAVE_MEMICMP
int
memicmp( const char *a, const char *b, size_t n )
{
for( ; n; n--, a++, b++ )
if( *a != *b && toupper(*(const byte*)a) != toupper(*(const byte*)b) )
return *(const byte *)a - *(const byte*)b;
return 0;
}
#endif
#ifndef HAVE_MEMRCHR
void *
memrchr (const void *buffer, int c, size_t n)
{
const unsigned char *p = buffer;
for (p += n; n ; n--)
if (*--p == c)
return (void *)p;
return NULL;
}
#endif /*HAVE_MEMRCHR*/
/* Percent-escape the string STR by replacing colons with '%3a'. If
EXTRA is not NULL all characters in EXTRA are also escaped. */
static char *
do_percent_escape (const char *str, const char *extra, int die)
{
int i, j;
char *ptr;
if (!str)
return NULL;
for (i=j=0; str[i]; i++)
if (str[i] == ':' || str[i] == '%' || str[i] == '\n'
|| (extra && strchr (extra, str[i])))
j++;
if (die)
ptr = xmalloc (i + 2 * j + 1);
else
{
ptr = xtrymalloc (i + 2 * j + 1);
if (!ptr)
return NULL;
}
i = 0;
while (*str)
{
if (*str == ':')
{
ptr[i++] = '%';
ptr[i++] = '3';
ptr[i++] = 'a';
}
else if (*str == '%')
{
ptr[i++] = '%';
ptr[i++] = '2';
ptr[i++] = '5';
}
else if (*str == '\n')
{
/* The newline is problematic in a line-based format. */
ptr[i++] = '%';
ptr[i++] = '0';
ptr[i++] = 'a';
}
else if (extra && strchr (extra, *str))
{
ptr[i++] = '%';
ptr[i++] = tohex_lower ((*str>>4)&15);
ptr[i++] = tohex_lower (*str&15);
}
else
ptr[i++] = *str;
str++;
}
ptr[i] = '\0';
return ptr;
}
/* Percent-escape the string STR by replacing colons with '%3a'. If
EXTRA is not NULL all characters in EXTRA are also escaped. This
function terminates the process on memory shortage. */
char *
percent_escape (const char *str, const char *extra)
{
return do_percent_escape (str, extra, 1);
}
/* Same as percent_escape but return NULL instead of exiting on memory
error. */
char *
try_percent_escape (const char *str, const char *extra)
{
return do_percent_escape (str, extra, 0);
}
static char *
do_strconcat (const char *s1, va_list arg_ptr)
{
const char *argv[48];
size_t argc;
size_t needed;
char *buffer, *p;
argc = 0;
argv[argc++] = s1;
needed = strlen (s1);
while (((argv[argc] = va_arg (arg_ptr, const char *))))
{
needed += strlen (argv[argc]);
if (argc >= DIM (argv)-1)
{
gpg_err_set_errno (EINVAL);
return NULL;
}
argc++;
}
needed++;
buffer = xtrymalloc (needed);
if (buffer)
{
for (p = buffer, argc=0; argv[argc]; argc++)
p = stpcpy (p, argv[argc]);
}
return buffer;
}
/* Concatenate the string S1 with all the following strings up to a
NULL. Returns a malloced buffer with the new string or NULL on a
malloc error or if too many arguments are given. */
char *
strconcat (const char *s1, ...)
{
va_list arg_ptr;
char *result;
if (!s1)
result = xtrystrdup ("");
else
{
va_start (arg_ptr, s1);
result = do_strconcat (s1, arg_ptr);
va_end (arg_ptr);
}
return result;
}
/* Same as strconcat but terminate the process with an error message
if something goes wrong. */
char *
xstrconcat (const char *s1, ...)
{
va_list arg_ptr;
char *result;
if (!s1)
result = xstrdup ("");
else
{
va_start (arg_ptr, s1);
result = do_strconcat (s1, arg_ptr);
va_end (arg_ptr);
}
if (!result)
{
if (errno == EINVAL)
fputs ("\nfatal: too many args for xstrconcat\n", stderr);
else
fputs ("\nfatal: out of memory\n", stderr);
exit (2);
}
return result;
}
/* Split a string into fields at DELIM. REPLACEMENT is the character
to replace the delimiter with (normally: '\0' so that each field is
NUL terminated). The caller is responsible for freeing the result.
Note: this function modifies STRING! If you need the original
value, then you should pass a copy to this function.
If malloc fails, this function returns NULL. */
char **
strsplit (char *string, char delim, char replacement, int *count)
{
int fields = 1;
char *t;
char **result;
/* First, count the number of fields. */
for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
fields ++;
result = xtrycalloc ((fields + 1), sizeof (*result));
if (! result)
return NULL;
result[0] = string;
fields = 1;
for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
{
result[fields ++] = t + 1;
*t = replacement;
}
if (count)
*count = fields;
return result;
}
/* Tokenize STRING using the set of delimiters in DELIM. Leading
* spaces and tabs are removed from all tokens. The caller must xfree
* the result.
*
* Returns: A malloced and NULL delimited array with the tokens. On
* memory error NULL is returned and ERRNO is set.
*/
char **
strtokenize (const char *string, const char *delim)
{
const char *s;
size_t fields;
size_t bytes, n;
char *buffer;
char *p, *px, *pend;
char **result;
/* Count the number of fields. */
for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim))
fields++;
fields++; /* Add one for the terminating NULL. */
/* Allocate an array for all fields, a terminating NULL, and space
for a copy of the string. */
bytes = fields * sizeof *result;
if (bytes / sizeof *result != fields)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
n = strlen (string) + 1;
bytes += n;
if (bytes < n)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
result = xtrymalloc (bytes);
if (!result)
return NULL;
buffer = (char*)(result + fields);
/* Copy and parse the string. */
strcpy (buffer, string);
for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1)
{
*pend = 0;
while (spacep (p))
p++;
for (px = pend - 1; px >= p && spacep (px); px--)
*px = 0;
result[n++] = p;
}
while (spacep (p))
p++;
for (px = p + strlen (p) - 1; px >= p && spacep (px); px--)
*px = 0;
result[n++] = p;
result[n] = NULL;
assert ((char*)(result + n + 1) == buffer);
return result;
}
/* Split a string into space delimited fields and remove leading and
* trailing spaces from each field. A pointer to each field is stored
* in ARRAY. Stop splitting at ARRAYSIZE fields. The function
* modifies STRING. The number of parsed fields is returned.
* Example:
*
* char *fields[2];
* if (split_fields (string, fields, DIM (fields)) < 2)
* return // Not enough args.
* foo (fields[0]);
* foo (fields[1]);
*/
int
split_fields (char *string, char **array, int arraysize)
{
int n = 0;
char *p, *pend;
for (p = string; *p == ' '; p++)
;
do
{
if (n == arraysize)
break;
array[n++] = p;
pend = strchr (p, ' ');
if (!pend)
break;
*pend++ = 0;
for (p = pend; *p == ' '; p++)
;
}
while (*p);
return n;
}
/* Version number parsing. */
/* This function parses the first portion of the version number S and
stores it in *NUMBER. On success, this function returns a pointer
into S starting with the first character, which is not part of the
initial number portion; on failure, NULL is returned. */
static const char*
parse_version_number (const char *s, int *number)
{
int val = 0;
if (*s == '0' && digitp (s+1))
return NULL; /* Leading zeros are not allowed. */
for (; digitp (s); s++)
{
val *= 10;
val += *s - '0';
}
*number = val;
return val < 0 ? NULL : s;
}
/* This function breaks up the complete string-representation of the
version number S, which is of the following struture: .[.]. The major,
minor, and micro number components will be stored in *MAJOR, *MINOR
and *MICRO. If MICRO is not given 0 is used instead.
On success, the last component, the patch level, will be returned;
in failure, NULL will be returned. */
static const char *
parse_version_string (const char *s, int *major, int *minor, int *micro)
{
s = parse_version_number (s, major);
if (!s || *s != '.')
return NULL;
s++;
s = parse_version_number (s, minor);
if (!s)
return NULL;
if (*s == '.')
{
s++;
s = parse_version_number (s, micro);
if (!s)
return NULL;
}
else
*micro = 0;
return s; /* Patchlevel. */
}
/* Compare the version string MY_VERSION to the version string
* REQ_VERSION. Returns -1, 0, or 1 if MY_VERSION is found,
* respectively, to be less than, to match, or be greater than
* REQ_VERSION. This function works for three and two part version
* strings; for a two part version string the micro part is assumed to
* be 0. Patch levels are compared as strings. If a version number
* is invalid INT_MIN is returned. If REQ_VERSION is given as NULL
* the function returns 0 if MY_VERSION is parsable version string. */
int
compare_version_strings (const char *my_version, const char *req_version)
{
int my_major, my_minor, my_micro;
int rq_major, rq_minor, rq_micro;
const char *my_patch, *rq_patch;
int result;
if (!my_version)
return INT_MIN;
my_patch = parse_version_string (my_version, &my_major, &my_minor, &my_micro);
if (!my_patch)
return INT_MIN;
if (!req_version)
return 0; /* MY_VERSION can be parsed. */
rq_patch = parse_version_string (req_version, &rq_major, &rq_minor,&rq_micro);
if (!rq_patch)
return INT_MIN;
if (my_major == rq_major)
{
if (my_minor == rq_minor)
{
if (my_micro == rq_micro)
result = strcmp (my_patch, rq_patch);
else
result = my_micro - rq_micro;
}
else
result = my_minor - rq_minor;
}
else
result = my_major - rq_major;
return !result? 0 : result < 0 ? -1 : 1;
}
/* Format a string so that it fits within about TARGET_COLS columns.
- TEXT_IN is copied to a new buffer, which is returned.
- Normally, target_cols will be 72 and max_cols is 80. */
+ * TEXT_IN is copied to a new buffer, which is returned. Normally,
+ * target_cols will be 72 and max_cols is 80. On error NULL is
+ * returned and ERRNO is set. */
char *
format_text (const char *text_in, int target_cols, int max_cols)
{
- const int do_debug = 0;
+ /* const int do_debug = 0; */
/* The character under consideration. */
char *p;
/* The start of the current line. */
char *line;
/* The last space that we saw. */
char *last_space = NULL;
int last_space_cols = 0;
int copied_last_space = 0;
char *text;
- text = xstrdup (text_in);
+ text = xtrystrdup (text_in);
+ if (!text)
+ return NULL;
p = line = text;
while (1)
{
/* The number of columns including any trailing space. */
int cols;
p = p + strcspn (p, "\n ");
if (! p)
/* P now points to the NUL character. */
p = &text[strlen (text)];
if (*p == '\n')
/* Pass through any newlines. */
{
p ++;
line = p;
last_space = NULL;
last_space_cols = 0;
copied_last_space = 1;
continue;
}
/* Have a space or a NUL. Note: we don't count the trailing
space. */
cols = utf8_charcount (line, (uintptr_t) p - (uintptr_t) line);
if (cols < target_cols)
{
if (! *p)
/* Nothing left to break. */
break;
last_space = p;
last_space_cols = cols;
p ++;
/* Skip any immediately following spaces. If we break:
"... foo bar ..." between "foo" and "bar" then we want:
"... foo\nbar ...", which means that the left space has
to be the first space after foo, not the last space
before bar. */
while (*p == ' ')
p ++;
}
else
{
int cols_with_left_space;
int cols_with_right_space;
int left_penalty;
int right_penalty;
cols_with_left_space = last_space_cols;
cols_with_right_space = cols;
- if (do_debug)
- log_debug ("Breaking: '%.*s'\n",
- (int) ((uintptr_t) p - (uintptr_t) line), line);
+ /* if (do_debug) */
+ /* log_debug ("Breaking: '%.*s'\n", */
+ /* (int) ((uintptr_t) p - (uintptr_t) line), line); */
/* The number of columns away from TARGET_COLS. We prefer
to underflow than to overflow. */
left_penalty = target_cols - cols_with_left_space;
right_penalty = 2 * (cols_with_right_space - target_cols);
if (cols_with_right_space > max_cols)
/* Add a large penalty for each column that exceeds
max_cols. */
right_penalty += 4 * (cols_with_right_space - max_cols);
- if (do_debug)
- log_debug ("Left space => %d cols (penalty: %d); right space => %d cols (penalty: %d)\n",
- cols_with_left_space, left_penalty,
- cols_with_right_space, right_penalty);
+ /* if (do_debug) */
+ /* log_debug ("Left space => %d cols (penalty: %d); " */
+ /* "right space => %d cols (penalty: %d)\n", */
+ /* cols_with_left_space, left_penalty, */
+ /* cols_with_right_space, right_penalty); */
if (last_space_cols && left_penalty <= right_penalty)
- /* Prefer the left space. */
{
- if (do_debug)
- log_debug ("Breaking at left space.\n");
+ /* Prefer the left space. */
+ /* if (do_debug) */
+ /* log_debug ("Breaking at left space.\n"); */
p = last_space;
}
else
{
- if (do_debug)
- log_debug ("Breaking at right space.\n");
+ /* if (do_debug) */
+ /* log_debug ("Breaking at right space.\n"); */
}
if (! *p)
break;
*p = '\n';
p ++;
if (*p == ' ')
{
int spaces;
for (spaces = 1; p[spaces] == ' '; spaces ++)
;
memmove (p, &p[spaces], strlen (&p[spaces]) + 1);
}
line = p;
last_space = NULL;
last_space_cols = 0;
copied_last_space = 0;
}
}
/* Chop off any trailing space. */
trim_trailing_chars (text, strlen (text), " ");
/* If we inserted the trailing newline, then remove it. */
if (! copied_last_space && *text && text[strlen (text) - 1] == '\n')
text[strlen (text) - 1] = '\0';
return text;
}
diff --git a/common/t-stringhelp.c b/common/t-stringhelp.c
index 869ca56f0..189fed1f9 100644
--- a/common/t-stringhelp.c
+++ b/common/t-stringhelp.c
@@ -1,999 +1,1004 @@
/* t-stringhelp.c - Regression tests for stringhelp.c
* Copyright (C) 2007 Free Software Foundation, Inc.
* 2015 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute and/or modify this
* part of GnuPG 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.
*
* 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 copies of the GNU General Public License
* and the GNU Lesser General Public License along with this program;
* if not, see .
*/
#include
#include
#include
#include
#include
#include
#ifdef HAVE_PWD_H
# include
#endif
#include
#include
#include
#include "t-support.h"
#include "stringhelp.h"
static char *home_buffer;
const char *
gethome (void)
{
if (!home_buffer)
{
char *home = getenv("HOME");
if(home)
home_buffer = xstrdup (home);
#if defined(HAVE_GETPWUID) && defined(HAVE_PWD_H)
else
{
struct passwd *pwd;
pwd = getpwuid (getuid());
if (pwd)
home_buffer = xstrdup (pwd->pw_dir);
}
#endif
}
return home_buffer;
}
static char *
mygetcwd (void)
{
char *buffer;
size_t size = 100;
for (;;)
{
buffer = xmalloc (size+1);
#ifdef HAVE_W32CE_SYSTEM
strcpy (buffer, "/"); /* Always "/". */
return buffer;
#else
if (getcwd (buffer, size) == buffer)
return buffer;
xfree (buffer);
if (errno != ERANGE)
{
fprintf (stderr,"error getting current cwd: %s\n",
strerror (errno));
exit (2);
}
size *= 2;
#endif
}
}
static void
test_percent_escape (void)
{
char *result;
static struct {
const char *extra;
const char *value;
const char *expected;
} tests[] =
{
{ NULL, "", "" },
{ NULL, "%", "%25" },
{ NULL, "%%", "%25%25" },
{ NULL, " %", " %25" },
{ NULL, ":", "%3a" },
{ NULL, " :", " %3a" },
{ NULL, ": ", "%3a " },
{ NULL, " : ", " %3a " },
{ NULL, "::", "%3a%3a" },
{ NULL, ": :", "%3a %3a" },
{ NULL, "%:", "%25%3a" },
{ NULL, ":%", "%3a%25" },
{ "\\\n:", ":%", "%3a%25" },
{ "\\\n:", "\\:%", "%5c%3a%25" },
{ "\\\n:", "\n:%", "%0a%3a%25" },
{ "\\\n:", "\xff:%", "\xff%3a%25" },
{ "\\\n:", "\xfe:%", "\xfe%3a%25" },
{ "\\\n:", "\x01:%", "\x01%3a%25" },
{ "\x01", "\x01:%", "%01%3a%25" },
{ "\xfe", "\xfe:%", "%fe%3a%25" },
{ "\xfe", "\xff:%", "\xff%3a%25" },
{ NULL, NULL, NULL }
};
int testno;
result = percent_escape (NULL, NULL);
if (result)
fail (0);
for (testno=0; tests[testno].value; testno++)
{
result = percent_escape (tests[testno].value, tests[testno].extra);
if (!result)
fail (testno);
else if (strcmp (result, tests[testno].expected))
fail (testno);
xfree (result);
}
}
static void
test_compare_filenames (void)
{
struct {
const char *a;
const char *b;
int result;
} tests[] = {
{ "", "", 0 },
{ "", "a", -1 },
{ "a", "", 1 },
{ "a", "a", 0 },
{ "a", "aa", -1 },
{ "aa", "a", 1 },
{ "a", "b", -1 },
#ifdef HAVE_W32_SYSTEM
{ "a", "A", 0 },
{ "A", "a", 0 },
{ "foo/bar", "foo\\bar", 0 },
{ "foo\\bar", "foo/bar", 0 },
{ "foo\\", "foo/", 0 },
{ "foo/", "foo\\", 0 },
#endif /*HAVE_W32_SYSTEM*/
{ NULL, NULL, 0}
};
int testno, result;
for (testno=0; tests[testno].a; testno++)
{
result = compare_filenames (tests[testno].a, tests[testno].b);
result = result < 0? -1 : result > 0? 1 : 0;
if (result != tests[testno].result)
fail (testno);
}
}
static void
test_strconcat (void)
{
char *out;
out = strconcat ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", NULL);
if (!out)
fail (0);
else
xfree (out);
out = strconcat ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", NULL);
if (out)
fail (0);
else if (errno != EINVAL)
fail (0);
out = strconcat ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", NULL);
if (out)
fail (0);
else if (errno != EINVAL)
fail (0);
xfree (out);
#if __GNUC__ < 4 /* gcc 4.0 has a sentinel attribute. */
out = strconcat (NULL);
if (!out || *out)
fail (1);
#endif
out = strconcat (NULL, NULL);
if (!out || *out)
fail (1);
xfree (out);
out = strconcat ("", NULL);
if (!out || *out)
fail (1);
xfree (out);
out = strconcat ("", "", NULL);
if (!out || *out)
fail (2);
xfree (out);
out = strconcat ("a", "b", NULL);
if (!out || strcmp (out, "ab"))
fail (3);
xfree (out);
out = strconcat ("a", "b", "c", NULL);
if (!out || strcmp (out, "abc"))
fail (3);
xfree (out);
out = strconcat ("a", "b", "cc", NULL);
if (!out || strcmp (out, "abcc"))
fail (4);
xfree (out);
out = strconcat ("a1", "b1", "c1", NULL);
if (!out || strcmp (out, "a1b1c1"))
fail (4);
xfree (out);
out = strconcat ("", " long b ", "", "--even-longer--", NULL);
if (!out || strcmp (out, " long b --even-longer--"))
fail (5);
xfree (out);
out = strconcat ("", " long b ", "", "--even-longer--", NULL);
if (!out || strcmp (out, " long b --even-longer--"))
fail (5);
xfree (out);
}
static void
test_xstrconcat (void)
{
char *out;
out = xstrconcat ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", NULL);
if (!out)
fail (0);
xfree (out);
#if __GNUC__ < 4 /* gcc 4.0 has a sentinel attribute. */
out = xstrconcat (NULL);
if (!out)
fail (1);
#endif
out = xstrconcat (NULL, NULL);
if (!out)
fail (1);
xfree (out);
out = xstrconcat ("", NULL);
if (!out || *out)
fail (1);
xfree (out);
out = xstrconcat ("", "", NULL);
if (!out || *out)
fail (2);
xfree (out);
out = xstrconcat ("a", "b", NULL);
if (!out || strcmp (out, "ab"))
fail (3);
xfree (out);
out = xstrconcat ("a", "b", "c", NULL);
if (!out || strcmp (out, "abc"))
fail (3);
xfree (out);
out = xstrconcat ("a", "b", "cc", NULL);
if (!out || strcmp (out, "abcc"))
fail (4);
xfree (out);
out = xstrconcat ("a1", "b1", "c1", NULL);
if (!out || strcmp (out, "a1b1c1"))
fail (4);
xfree (out);
out = xstrconcat ("", " long b ", "", "--even-longer--", NULL);
if (!out || strcmp (out, " long b --even-longer--"))
fail (5);
xfree (out);
out = xstrconcat ("", " long b ", "", "--even-longer--", NULL);
if (!out || strcmp (out, " long b --even-longer--"))
fail (5);
xfree (out);
}
static void
test_make_filename_try (void)
{
char *out;
const char *home = gethome ();
size_t homelen = home? strlen (home):0;
out = make_filename_try ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", NULL);
if (out)
fail (0);
else if (errno != EINVAL)
fail (0);
xfree (out);
out = make_filename_try ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", NULL);
if (out)
fail (0);
else if (errno != EINVAL)
fail (0);
xfree (out);
out = make_filename_try ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"1", "2", NULL);
if (!out || strcmp (out,
"1/2/3/4/5/6/7/8/9/10/"
"1/2/3/4/5/6/7/8/9/10/"
"1/2/3/4/5/6/7/8/9/10/"
"1/2"))
fail (0);
xfree (out);
out = make_filename_try ("foo", "~/bar", "baz/cde", NULL);
if (!out || strcmp (out, "foo/~/bar/baz/cde"))
fail (1);
xfree (out);
out = make_filename_try ("foo", "~/bar", "baz/cde/", NULL);
if (!out || strcmp (out, "foo/~/bar/baz/cde/"))
fail (1);
xfree (out);
out = make_filename_try ("/foo", "~/bar", "baz/cde/", NULL);
if (!out || strcmp (out, "/foo/~/bar/baz/cde/"))
fail (1);
xfree (out);
out = make_filename_try ("//foo", "~/bar", "baz/cde/", NULL);
if (!out || strcmp (out, "//foo/~/bar/baz/cde/"))
fail (1);
xfree (out);
out = make_filename_try ("", "~/bar", "baz/cde", NULL);
if (!out || strcmp (out, "/~/bar/baz/cde"))
fail (1);
xfree (out);
out = make_filename_try ("~/foo", "bar", NULL);
if (!out)
fail (2);
else if (home)
{
if (strlen (out) < homelen + 7)
fail (2);
else if (strncmp (out, home, homelen))
fail (2);
else if (strcmp (out+homelen, "/foo/bar"))
fail (2);
}
else
{
if (strcmp (out, "~/foo/bar"))
fail (2);
}
xfree (out);
out = make_filename_try ("~", "bar", NULL);
if (!out)
fail (2);
else if (home)
{
if (strlen (out) < homelen + 3)
fail (2);
else if (strncmp (out, home, homelen))
fail (2);
else if (strcmp (out+homelen, "/bar"))
fail (2);
}
else
{
if (strcmp (out, "~/bar"))
fail (2);
}
xfree (out);
}
static void
test_make_absfilename_try (void)
{
char *out;
char *cwd = mygetcwd ();
size_t cwdlen = strlen (cwd);
out = make_absfilename_try ("foo", "bar", NULL);
if (!out)
fail (0);
else if (strlen (out) < cwdlen + 7)
fail (0);
else if (strncmp (out, cwd, cwdlen))
fail (0);
else if (strcmp (out+cwdlen, "/foo/bar"))
fail (0);
xfree (out);
out = make_absfilename_try ("./foo", NULL);
if (!out)
fail (1);
else if (strlen (out) < cwdlen + 5)
fail (1);
else if (strncmp (out, cwd, cwdlen))
fail (1);
else if (strcmp (out+cwdlen, "/./foo"))
fail (1);
xfree (out);
out = make_absfilename_try (".", NULL);
if (!out)
fail (2);
else if (strlen (out) < cwdlen)
fail (2);
else if (strncmp (out, cwd, cwdlen))
fail (2);
else if (strcmp (out+cwdlen, ""))
fail (2);
xfree (out);
xfree (cwd);
}
static void
test_strsplit (void)
{
struct {
const char *s;
char delim;
char replacement;
const char *fields_expected[10];
} tv[] = {
{
"a:bc:cde:fghi:jklmn::foo:", ':', '\0',
{ "a", "bc", "cde", "fghi", "jklmn", "", "foo", "", NULL }
},
{
",a,bc,,def,", ',', '!',
{ "!a!bc!!def!", "a!bc!!def!", "bc!!def!", "!def!", "def!", "", NULL }
},
{
"", ':', ',',
{ "", NULL }
}
};
int tidx;
for (tidx = 0; tidx < DIM(tv); tidx++)
{
char *s2;
int field_count;
char **fields;
int field_count_expected;
int i;
/* Count the fields. */
for (field_count_expected = 0;
tv[tidx].fields_expected[field_count_expected];
field_count_expected ++)
;
/* We need to copy s since strsplit modifies it in place. */
s2 = xstrdup (tv[tidx].s);
fields = strsplit (s2, tv[tidx].delim, tv[tidx].replacement,
&field_count);
if (field_count != field_count_expected)
fail (tidx * 1000);
for (i = 0; i < field_count_expected; i ++)
if (strcmp (tv[tidx].fields_expected[i], fields[i]) != 0)
{
printf ("For field %d, expected '%s', but got '%s'\n",
i, tv[tidx].fields_expected[i], fields[i]);
fail (tidx * 1000 + i + 1);
}
xfree (fields);
xfree (s2);
}
}
static void
test_strtokenize (void)
{
struct {
const char *s;
const char *delim;
const char *fields_expected[10];
} tv[] = {
{
"", ":",
{ "", NULL }
},
{
"a", ":",
{ "a", NULL }
},
{
":", ":",
{ "", "", NULL }
},
{
"::", ":",
{ "", "", "", NULL }
},
{
"a:b:c", ":",
{ "a", "b", "c", NULL }
},
{
"a:b:", ":",
{ "a", "b", "", NULL }
},
{
"a:b", ":",
{ "a", "b", NULL }
},
{
"aa:b:cd", ":",
{ "aa", "b", "cd", NULL }
},
{
"aa::b:cd", ":",
{ "aa", "", "b", "cd", NULL }
},
{
"::b:cd", ":",
{ "", "", "b", "cd", NULL }
},
{
"aa: : b:cd ", ":",
{ "aa", "", "b", "cd", NULL }
},
{
" aa: : b: cd ", ":",
{ "aa", "", "b", "cd", NULL }
},
{
" ", ":",
{ "", NULL }
},
{
" :", ":",
{ "", "", NULL }
},
{
" : ", ":",
{ "", "", NULL }
},
{
": ", ":",
{ "", "", NULL }
},
{
": x ", ":",
{ "", "x", NULL }
},
{
"a:bc:cde:fghi:jklmn::foo:", ":",
{ "a", "bc", "cde", "fghi", "jklmn", "", "foo", "", NULL }
},
{
",a,bc,,def,", ",",
{ "", "a", "bc", "", "def", "", NULL }
},
{
" a ", " ",
{ "", "a", "", NULL }
},
{
" ", " ",
{ "", "", NULL }
},
{
"", " ",
{ "", NULL }
}
};
int tidx;
for (tidx = 0; tidx < DIM(tv); tidx++)
{
char **fields;
int field_count;
int field_count_expected;
int i;
for (field_count_expected = 0;
tv[tidx].fields_expected[field_count_expected];
field_count_expected ++)
;
fields = strtokenize (tv[tidx].s, tv[tidx].delim);
if (!fields)
fail (tidx * 1000);
else
{
for (field_count = 0; fields[field_count]; field_count++)
;
if (field_count != field_count_expected)
fail (tidx * 1000);
else
{
for (i = 0; i < field_count_expected; i++)
if (strcmp (tv[tidx].fields_expected[i], fields[i]))
{
printf ("For field %d, expected '%s', but got '%s'\n",
i, tv[tidx].fields_expected[i], fields[i]);
fail (tidx * 1000 + i + 1);
}
}
}
xfree (fields);
}
}
static void
test_split_fields (void)
{
struct {
const char *s;
int nfields;
const char *fields_expected[10];
} tv[] = {
{
"a bc cde fghi jklmn foo ", 6,
{ "a", "bc", "cde", "fghi", "jklmn", "foo", NULL }
},
{
" a bc def ", 2,
{ "a", "bc", "def", NULL }
},
{
" a bc def ", 3,
{ "a", "bc", "def", NULL }
},
{
" a bc def ", 4,
{ "a", "bc", "def", NULL }
},
{
"", 0,
{ NULL }
}
};
int tidx;
char *fields[10];
int field_count_expected, nfields, field_count, i;
char *s2;
for (tidx = 0; tidx < DIM(tv); tidx++)
{
nfields = tv[tidx].nfields;
assert (nfields <= DIM (fields));
/* Count the fields. */
for (field_count_expected = 0;
tv[tidx].fields_expected[field_count_expected];
field_count_expected ++)
;
if (field_count_expected > nfields)
field_count_expected = nfields;
/* We need to copy s since split_fields modifies in place. */
s2 = xstrdup (tv[tidx].s);
field_count = split_fields (s2, fields, nfields);
if (field_count != field_count_expected)
{
printf ("%s: tidx %d: expected %d, got %d\n",
__func__, tidx, field_count_expected, field_count);
fail (tidx * 1000);
}
else
{
for (i = 0; i < field_count_expected; i ++)
if (strcmp (tv[tidx].fields_expected[i], fields[i]))
{
printf ("%s: tidx %d, field %d: expected '%s', got '%s'\n",
__func__,
tidx, i, tv[tidx].fields_expected[i], fields[i]);
fail (tidx * 1000 + i + 1);
}
}
xfree (s2);
}
}
static char *
stresc (char *s)
{
char *p;
int l = strlen (s) + 1;
for (p = s; *p; p ++)
if (*p == '\n')
l ++;
p = xmalloc (l);
for (l = 0; *s; s ++, l ++)
{
if (*s == ' ')
p[l] = '_';
else if (*p == '\n')
{
p[l ++] = '\\';
p[l ++] = 'n';
p[l] = '\n';
}
else
p[l] = *s;
}
p[l] = *s;
return p;
}
static void
test_format_text (void)
{
struct test
{
int target_cols, max_cols;
char *input;
char *expected;
};
struct test tests[] = {
{
10, 12,
"",
"",
},
{
10, 12,
" ",
"",
},
{
10, 12,
" ",
"",
},
{
10, 12,
" \n ",
" \n",
},
{
10, 12,
" \n \n ",
" \n \n",
},
{
10, 12,
"0123456789 0123456789 0",
"0123456789\n0123456789\n0",
},
{
10, 12,
" 0123456789 0123456789 0 ",
" 0123456789\n0123456789\n0",
},
{
10, 12,
"01 34 67 90 23 56 89 12 45 67 89 1",
"01 34 67\n90 23 56\n89 12 45\n67 89 1"
},
{
10, 12,
"01 34 67 90 23 56 89 12 45 67 89 1",
"01 34 67\n90 23 56\n89 12 45\n67 89 1"
},
{
72, 80,
"Warning: if you think you've seen more than 10 messages "
"signed by this key, then this key might be a forgery! "
"Carefully examine the email address for small variations "
"(e.g., additional white space). If the key is suspect, "
"then use 'gpg --tofu-policy bad \"FINGERPRINT\"' to mark it as being bad.\n",
"Warning: if you think you've seen more than 10 messages signed by this\n"
"key, then this key might be a forgery! Carefully examine the email\n"
"address for small variations (e.g., additional white space). If the key\n"
"is suspect, then use 'gpg --tofu-policy bad \"FINGERPRINT\"' to mark it as\n"
"being bad.\n"
},
{
72, 80,
"Normally, there is only a single key associated with an email "
"address. However, people sometimes generate a new key if "
"their key is too old or they think it might be compromised. "
"Alternatively, a new key may indicate a man-in-the-middle "
"attack! Before accepting this key, you should talk to or "
"call the person to make sure this new key is legitimate.",
"Normally, there is only a single key associated with an email "
"address.\nHowever, people sometimes generate a new key if "
"their key is too old or\nthey think it might be compromised. "
"Alternatively, a new key may indicate\na man-in-the-middle "
"attack! Before accepting this key, you should talk\nto or "
"call the person to make sure this new key is legitimate.",
}
};
int i;
int failed = 0;
for (i = 0; i < sizeof (tests) / sizeof (tests[0]); i ++)
{
struct test *test = &tests[i];
char *result =
format_text (test->input, test->target_cols, test->max_cols);
+ if (!result)
+ {
+ fail (1);
+ exit (2);
+ }
if (strcmp (result, test->expected) != 0)
{
printf ("%s: Test #%d failed.\nExpected: '%s'\nResult: '%s'\n",
__func__, i + 1, stresc (test->expected), stresc (result));
failed ++;
}
xfree (result);
}
if (failed)
fail(0);
}
static void
test_compare_version_strings (void)
{
struct { const char *a; const char *b; int okay; } tests[] = {
{ "1.0.0", "1.0.0", 0 },
{ "1.0.0-", "1.0.0", 1 },
{ "1.0.0-1", "1.0.0", 1 },
{ "1.0.0.1", "1.0.0", 1 },
{ "1.0.0", "1.0.1", -1 },
{ "1.0.0-", "1.0.1", -1 },
{ "1.0.0-1", "1.0.1", -1 },
{ "1.0.0.1", "1.0.1", -1 },
{ "1.0.0", "1.1.0", -1 },
{ "1.0.0-", "1.1.0", -1 },
{ "1.0.0-1", "1.1.0", -1 },
{ "1.0.0.1", "1.1.0", -1 },
{ "1.0.0", "1.0.0-", -1 },
{ "1.0.0", "1.0.0-1", -1 },
{ "1.0.0", "1.0.0.1", -1 },
{ "1.1.0", "1.0.0", 1 },
{ "1.1.1", "1.1.0", 1 },
{ "1.1.2", "1.1.2", 0 },
{ "1.1.2", "1.0.2", 1 },
{ "1.1.2", "0.0.2", 1 },
{ "1.1.2", "1.1.3", -1 },
{ "0.99.1", "0.9.9", 1 },
{ "0.9.1", "0.91.0", -1 },
{ "1.5.3", "1.5", 1 },
{ "1.5.0", "1.5", 0 },
{ "1.4.99", "1.5", -1 },
{ "1.5", "1.4.99", 1 },
{ "1.5", "1.5.0", 0 },
{ "1.5", "1.5.1", -1 },
{ "1.5.3-x17", "1.5-23", 1 },
{ "1.5.3a", "1.5.3", 1 },
{ "1.5.3a", "1.5.3b", -1 },
{ "3.1.4-ab", "3.1.4-ab", 0 },
{ "3.1.4-ab", "3.1.4-ac", -1 },
{ "3.1.4-ac", "3.1.4-ab", 1 },
{ "3.1.4-ab", "3.1.4-abb", -1 },
{ "3.1.4-abb", "3.1.4-ab", 1 },
{ "", "", INT_MIN },
{ NULL, "", INT_MIN },
{ "1.2.3", "", INT_MIN },
{ "1.2.3", "2", INT_MIN },
/* Test cases for validity of A. */
{ "", NULL, INT_MIN },
{ "1", NULL, INT_MIN },
{ "1.", NULL, 0 },
{ "1.0", NULL, 0 },
{ "1.0.", NULL, 0 },
{ "a1.2", NULL, INT_MIN },
{ NULL, NULL, INT_MIN }
};
int idx;
int res;
for (idx=0; idx < DIM(tests); idx++)
{
res = compare_version_strings (tests[idx].a, tests[idx].b);
/* printf ("test %d: '%s' '%s' %d -> %d\n", */
/* idx, tests[idx].a, tests[idx].b, tests[idx].okay, res); */
if (res != tests[idx].okay)
fail (idx);
}
}
int
main (int argc, char **argv)
{
(void)argc;
(void)argv;
test_percent_escape ();
test_compare_filenames ();
test_strconcat ();
test_xstrconcat ();
test_make_filename_try ();
test_make_absfilename_try ();
test_strsplit ();
test_strtokenize ();
test_split_fields ();
test_compare_version_strings ();
test_format_text ();
xfree (home_buffer);
return !!errcount;
}
diff --git a/g10/gpgcompose.c b/g10/gpgcompose.c
index 071d6bf45..4a2cb818f 100644
--- a/g10/gpgcompose.c
+++ b/g10/gpgcompose.c
@@ -1,3048 +1,3050 @@
/* gpgcompose.c - Maintainer tool to create OpenPGP messages by hand.
* Copyright (C) 2016 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include "gpg.h"
#include "packet.h"
#include "keydb.h"
#include "main.h"
#include "options.h"
static int do_debug;
#define debug(fmt, ...) \
do { if (do_debug) log_debug (fmt, ##__VA_ARGS__); } while (0)
/* --encryption, for instance, adds a filter in front of out. There
is an operator (--encryption-pop) to end this. We use the
following infrastructure to make it easy to pop the state. */
struct filter
{
void *func;
void *context;
int pkttype;
int partial_block_mode;
struct filter *next;
};
/* Hack to ass CTRL to some functions. */
static ctrl_t global_ctrl;
static struct filter *filters;
static void
filter_push (iobuf_t out, void *func, void *context,
int type, int partial_block_mode)
{
gpg_error_t err;
struct filter *f = xmalloc_clear (sizeof (*f));
f->next = filters;
f->func = func;
f->context = context;
f->pkttype = type;
f->partial_block_mode = partial_block_mode;
filters = f;
err = iobuf_push_filter (out, func, context);
if (err)
log_fatal ("Adding filter: %s\n", gpg_strerror (err));
}
static void
filter_pop (iobuf_t out, int expected_type)
{
gpg_error_t err;
struct filter *f = filters;
log_assert (f);
if (f->pkttype != expected_type)
log_fatal ("Attempted to pop a %s container, "
"but current container is a %s container.\n",
pkttype_str (f->pkttype), pkttype_str (expected_type));
if (f->pkttype == PKT_ENCRYPTED || f->pkttype == PKT_ENCRYPTED_MDC)
{
err = iobuf_pop_filter (out, f->func, f->context);
if (err)
log_fatal ("Popping encryption filter: %s\n", gpg_strerror (err));
}
else
log_fatal ("FILTERS appears to be corrupted.\n");
if (f->partial_block_mode)
iobuf_set_partial_body_length_mode (out, 0);
filters = f->next;
xfree (f);
}
/* Return if CIPHER_ID is a valid cipher. */
static int
valid_cipher (int cipher_id)
{
return (cipher_id == CIPHER_ALGO_IDEA
|| cipher_id == CIPHER_ALGO_3DES
|| cipher_id == CIPHER_ALGO_CAST5
|| cipher_id == CIPHER_ALGO_BLOWFISH
|| cipher_id == CIPHER_ALGO_AES
|| cipher_id == CIPHER_ALGO_AES192
|| cipher_id == CIPHER_ALGO_AES256
|| cipher_id == CIPHER_ALGO_TWOFISH
|| cipher_id == CIPHER_ALGO_CAMELLIA128
|| cipher_id == CIPHER_ALGO_CAMELLIA192
|| cipher_id == CIPHER_ALGO_CAMELLIA256);
}
/* Parse a session key encoded as a string of the form x:HEXDIGITS
where x is the algorithm id. (This is the format emitted by gpg
--show-session-key.) */
struct session_key
{
int algo;
int keylen;
char *key;
};
static struct session_key
parse_session_key (const char *option, char *p, int require_algo)
{
char *tail;
struct session_key sk;
memset (&sk, 0, sizeof (sk));
/* Check for the optional "cipher-id:" at the start of the
string. */
errno = 0;
sk.algo = strtol (p, &tail, 10);
if (! errno && tail && *tail == ':')
{
if (! valid_cipher (sk.algo))
log_info ("%s: %d is not a known cipher (but using anyways)\n",
option, sk.algo);
p = tail + 1;
}
else if (require_algo)
log_fatal ("%s: Session key must have the form algo:HEXCHARACTERS.\n",
option);
else
sk.algo = 0;
/* Ignore a leading 0x. */
if (p[0] == '0' && p[1] == 'x')
p += 2;
if (strlen (p) % 2 != 0)
log_fatal ("%s: session key must consist of an even number of hexadecimal characters.\n",
option);
sk.keylen = strlen (p) / 2;
sk.key = xmalloc (sk.keylen);
if (hex2bin (p, sk.key, sk.keylen) == -1)
log_fatal ("%s: Session key must only contain hexadecimal characters\n",
option);
return sk;
}
/* A callback.
OPTION_STR is the option that was matched. ARGC is the number of
arguments following the option and ARGV are those arguments.
(Thus, argv[0] is the first string following the option and
argv[-1] is the option.)
COOKIE is the opaque value passed to process_options. */
typedef int (*option_prcessor_t) (const char *option_str,
int argc, char *argv[],
void *cookie);
struct option
{
/* The option that this matches. This must start with "--" or be
the empty string. The empty string matches bare arguments. */
const char *option;
/* The function to call to process this option. */
option_prcessor_t func;
/* Documentation. */
const char *help;
};
/* Merge two lists of options. Note: this makes a shallow copy! The
caller must xfree() the result. */
static struct option *
merge_options (struct option a[], struct option b[])
{
int i, j;
struct option *c;
for (i = 0; a[i].option; i ++)
;
for (j = 0; b[j].option; j ++)
;
c = xmalloc ((i + j + 1) * sizeof (struct option));
memcpy (c, a, i * sizeof (struct option));
memcpy (&c[i], b, j * sizeof (struct option));
c[i + j].option = NULL;
if (a[i].help && b[j].help)
c[i + j].help = xasprintf ("%s\n\n%s", a[i].help, b[j].help);
else if (a[i].help)
c[i + j].help = a[i].help;
else if (b[j].help)
c[i + j].help = b[j].help;
return c;
}
/* Returns whether ARG is an option. All options start with --. */
static int
is_option (const char *arg)
{
return arg[0] == '-' && arg[1] == '-';
}
/* OPTIONS is a NULL terminated array of struct option:s. Finds the
entry that is the same as ARG. Returns -1 if no entry is found.
The empty string option matches bare arguments. */
static int
match_option (const struct option options[], const char *arg)
{
int i;
int bare_arg = ! is_option (arg);
for (i = 0; options[i].option; i ++)
if ((! bare_arg && strcmp (options[i].option, arg) == 0)
/* Non-options match the empty string. */
|| (bare_arg && options[i].option[0] == '\0'))
return i;
return -1;
}
static void
show_help (struct option options[])
{
int i;
int max_length = 0;
int space;
for (i = 0; options[i].option; i ++)
{
const char *option = options[i].option[0] ? options[i].option : "ARG";
int l = strlen (option);
if (l > max_length)
max_length = l;
}
space = 72 - (max_length + 2);
if (space < 40)
space = 40;
for (i = 0; ; i ++)
{
const char *option = options[i].option;
const char *help = options[i].help;
int l;
int j;
char *tmp;
char *formatted;
char *p;
char *newline;
if (! option && ! help)
break;
if (option)
{
const char *o = option[0] ? option : "ARG";
l = strlen (o);
fprintf (stderr, "%s", o);
}
if (! help)
{
fputc ('\n', stderr);
continue;
}
if (option)
for (j = l; j < max_length + 2; j ++)
fputc (' ', stderr);
#define BOLD_START "\033[1m"
#define NORMAL_RESTORE "\033[0m"
#define BOLD(x) BOLD_START x NORMAL_RESTORE
if (! option || options[i].func)
tmp = (char *) help;
else
tmp = xasprintf ("%s " BOLD("(Unimplemented.)"), help);
if (! option)
space = 72;
formatted = format_text (tmp, space, space + 4);
+ if (!format_text)
+ abort ();
if (tmp != help)
xfree (tmp);
if (! option)
{
fprintf (stderr, "\n%s\n", formatted);
break;
}
for (p = formatted;
p && *p;
p = (*newline == '\0') ? newline : newline + 1)
{
newline = strchr (p, '\n');
if (! newline)
newline = &p[strlen (p)];
l = (size_t) newline - (size_t) p;
if (p != formatted)
for (j = 0; j < max_length + 2; j ++)
fputc (' ', stderr);
fwrite (p, l, 1, stderr);
fputc ('\n', stderr);
}
xfree (formatted);
}
}
/* Return value is number of consumed argv elements. */
static int
process_options (const char *parent_option,
struct option break_options[],
struct option local_options[], void *lcookie,
struct option global_options[], void *gcookie,
int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i ++)
{
int j;
struct option *option;
void *cookie;
int bare_arg;
option_prcessor_t func;
int consumed;
if (break_options)
{
j = match_option (break_options, argv[i]);
if (j != -1)
/* Match. Break out. */
return i;
}
j = match_option (local_options, argv[i]);
if (j == -1)
{
if (global_options)
j = match_option (global_options, argv[i]);
if (j == -1)
{
if (strcmp (argv[i], "--help") == 0)
{
if (! global_options)
show_help (local_options);
else
{
struct option *combined
= merge_options (local_options, global_options);
show_help (combined);
xfree (combined);
}
g10_exit (0);
}
if (parent_option)
log_fatal ("%s: Unknown option: %s\n", parent_option, argv[i]);
else
log_fatal ("Unknown option: %s\n", argv[i]);
}
option = &global_options[j];
cookie = gcookie;
}
else
{
option = &local_options[j];
cookie = lcookie;
}
bare_arg = strcmp (option->option, "") == 0;
func = option->func;
if (! func)
{
if (bare_arg)
log_fatal ("Bare arguments unimplemented.\n");
else
log_fatal ("Unimplemented option: %s\n",
option->option);
}
consumed = func (bare_arg ? parent_option : argv[i],
argc - i - !bare_arg, &argv[i + !bare_arg],
cookie);
i += consumed;
if (bare_arg)
i --;
}
return i;
}
/* The keys, subkeys, user ids and user attributes in the order that
they were added. */
PACKET components[20];
/* The number of components. */
int ncomponents;
static int
add_component (int pkttype, void *component)
{
int i = ncomponents ++;
log_assert (i < sizeof (components) / sizeof (components[0]));
log_assert (pkttype == PKT_PUBLIC_KEY
|| pkttype == PKT_PUBLIC_SUBKEY
|| pkttype == PKT_SECRET_KEY
|| pkttype == PKT_SECRET_SUBKEY
|| pkttype == PKT_USER_ID
|| pkttype == PKT_ATTRIBUTE);
components[i].pkttype = pkttype;
components[i].pkt.generic = component;
return i;
}
static void
dump_component (PACKET *pkt)
{
struct kbnode_struct kbnode;
if (! do_debug)
return;
memset (&kbnode, 0, sizeof (kbnode));
kbnode.pkt = pkt;
dump_kbnode (&kbnode);
}
/* Returns the first primary key in COMPONENTS or NULL if there is
none. */
static PKT_public_key *
primary_key (void)
{
int i;
for (i = 0; i < ncomponents; i ++)
if (components[i].pkttype == PKT_PUBLIC_KEY)
return components[i].pkt.public_key;
return NULL;
}
/* The last session key (updated when adding a SK-ESK, PK-ESK or SED
packet. */
static DEK session_key;
static int user_id (const char *option, int argc, char *argv[],
void *cookie);
static int public_key (const char *option, int argc, char *argv[],
void *cookie);
static int sk_esk (const char *option, int argc, char *argv[],
void *cookie);
static int pk_esk (const char *option, int argc, char *argv[],
void *cookie);
static int encrypted (const char *option, int argc, char *argv[],
void *cookie);
static int encrypted_pop (const char *option, int argc, char *argv[],
void *cookie);
static int literal (const char *option, int argc, char *argv[],
void *cookie);
static int signature (const char *option, int argc, char *argv[],
void *cookie);
static int copy (const char *option, int argc, char *argv[],
void *cookie);
static struct option major_options[] = {
{ "--user-id", user_id, "Create a user id packet." },
{ "--public-key", public_key, "Create a public key packet." },
{ "--private-key", NULL, "Create a private key packet." },
{ "--public-subkey", public_key, "Create a subkey packet." },
{ "--private-subkey", NULL, "Create a private subkey packet." },
{ "--sk-esk", sk_esk,
"Create a symmetric-key encrypted session key packet." },
{ "--pk-esk", pk_esk,
"Create a public-key encrypted session key packet." },
{ "--encrypted", encrypted, "Create a symmetrically encrypted data packet." },
{ "--encrypted-mdc", encrypted,
"Create a symmetrically encrypted and integrity protected data packet." },
{ "--encrypted-pop", encrypted_pop,
"Pop an encryption container." },
{ "--compressed", NULL, "Create a compressed data packet." },
{ "--literal", literal, "Create a literal (plaintext) data packet." },
{ "--signature", signature, "Create a signature packet." },
{ "--onepass-sig", NULL, "Create a one-pass signature packet." },
{ "--copy", copy, "Copy the specified file." },
{ NULL, NULL,
"To get more information about a given command, use:\n\n"
" $ gpgcompose --command --help to list a command's options."},
};
static struct option global_options[] = {
{ NULL, NULL, NULL },
};
/* Make our lives easier and use a static limit for the user name.
10k is way more than enough anyways... */
const int user_id_max_len = 10 * 1024;
static int
user_id_name (const char *option, int argc, char *argv[], void *cookie)
{
PKT_user_id *uid = cookie;
int l;
if (argc == 0)
log_fatal ("Usage: %s USER_ID\n", option);
if (uid->len)
log_fatal ("Attempt to set user id multiple times.\n");
l = strlen (argv[0]);
if (l > user_id_max_len)
log_fatal ("user id too long (max: %d)\n", user_id_max_len);
memcpy (uid->name, argv[0], l);
uid->name[l] = 0;
uid->len = l;
return 1;
}
static struct option user_id_options[] = {
{ "", user_id_name,
"Set the user id. This is usually in the format "
"\"Name (comment) \"" },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --user-id \"USERID\" | " GPG_NAME " --list-packets" }
};
static int
user_id (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
gpg_error_t err;
PKT_user_id *uid = xmalloc_clear (sizeof (*uid) + user_id_max_len);
int c = add_component (PKT_USER_ID, uid);
int processed;
processed = process_options (option,
major_options,
user_id_options, uid,
global_options, NULL,
argc, argv);
if (! uid->len)
log_fatal ("%s: user id not given", option);
err = build_packet (out, &components[c]);
if (err)
log_fatal ("Serializing user id packet: %s\n", gpg_strerror (err));
debug ("Wrote user id packet:\n");
dump_component (&components[c]);
return processed;
}
static int
pk_search_terms (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
KEYDB_HANDLE hd;
KEYDB_SEARCH_DESC desc;
kbnode_t kb;
PKT_public_key *pk = cookie;
PKT_public_key *pk_ref;
int i;
if (argc == 0)
log_fatal ("Usage: %s KEYID\n", option);
if (pk->pubkey_algo)
log_fatal ("%s: multiple keys provided\n", option);
err = classify_user_id (argv[0], &desc, 0);
if (err)
log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
hd = keydb_new ();
err = keydb_search (hd, &desc, 1, NULL);
if (err)
log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err));
err = keydb_get_keyblock (hd, &kb);
if (err)
log_fatal ("retrieving keyblock for '%s': %s\n",
argv[0], gpg_strerror (err));
keydb_release (hd);
pk_ref = kb->pkt->pkt.public_key;
/* Copy the timestamp (if not already set), algo and public key
parameters. */
if (! pk->timestamp)
pk->timestamp = pk_ref->timestamp;
pk->pubkey_algo = pk_ref->pubkey_algo;
for (i = 0; i < pubkey_get_npkey (pk->pubkey_algo); i ++)
pk->pkey[i] = gcry_mpi_copy (pk_ref->pkey[i]);
release_kbnode (kb);
return 1;
}
static int
pk_timestamp (const char *option, int argc, char *argv[], void *cookie)
{
PKT_public_key *pk = cookie;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s TIMESTAMP\n", option);
errno = 0;
pk->timestamp = parse_timestamp (argv[0], &tail);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
return 1;
}
#define TIMESTAMP_HELP \
"Either as seconds since the epoch or as an ISO 8601 formatted " \
"string (yyyymmddThhmmss, where the T is a literal)."
static struct option pk_options[] = {
{ "--timestamp", pk_timestamp,
"The creation time. " TIMESTAMP_HELP },
{ "", pk_search_terms,
"The key to copy the creation time and public key parameters from." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --public-key $KEYID --user-id \"USERID\" \\\n"
" | " GPG_NAME " --list-packets" }
};
static int
public_key (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
iobuf_t out = cookie;
PKT_public_key *pk;
int c;
int processed;
int t = (strcmp (option, "--public-key") == 0
? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY);
(void) option;
pk = xmalloc_clear (sizeof (*pk));
pk->version = 4;
c = add_component (t, pk);
processed = process_options (option,
major_options,
pk_options, pk,
global_options, NULL,
argc, argv);
if (! pk->pubkey_algo)
log_fatal ("%s: key to extract public key parameters from not given",
option);
/* Clear the keyid in case we updated one of the relevant fields
after accessing it. */
pk->keyid[0] = pk->keyid[1] = 0;
err = build_packet (out, &components[c]);
if (err)
log_fatal ("serializing %s packet: %s\n",
t == PKT_PUBLIC_KEY ? "public key" : "subkey",
gpg_strerror (err));
debug ("Wrote %s packet:\n",
t == PKT_PUBLIC_KEY ? "public key" : "subkey");
dump_component (&components[c]);
return processed;
}
struct signinfo
{
/* Key with which to sign. */
kbnode_t issuer_kb;
PKT_public_key *issuer_pk;
/* Overrides the issuer's key id. */
u32 issuer_keyid[2];
/* Sets the issuer's keyid to the primary key's key id. */
int issuer_keyid_self;
/* Key to sign. */
PKT_public_key *pk;
/* Subkey to sign. */
PKT_public_key *sk;
/* User id to sign. */
PKT_user_id *uid;
int class;
int digest_algo;
u32 timestamp;
u32 key_expiration;
byte *cipher_algorithms;
int cipher_algorithms_len;
byte *digest_algorithms;
int digest_algorithms_len;
byte *compress_algorithms;
int compress_algorithms_len;
u32 expiration;
int exportable_set;
int exportable;
int revocable_set;
int revocable;
int trust_level_set;
byte trust_args[2];
char *trust_scope;
struct revocation_key *revocation_key;
int nrevocation_keys;
struct notation *notations;
byte *key_server_preferences;
int key_server_preferences_len;
char *key_server;
int primary_user_id_set;
int primary_user_id;
char *policy_uri;
byte *key_flags;
int key_flags_len;
char *signers_user_id;
byte reason_for_revocation_code;
char *reason_for_revocation;
byte *features;
int features_len;
/* Whether to corrupt the signature. */
int corrupt;
};
static int
sig_issuer (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
KEYDB_HANDLE hd;
KEYDB_SEARCH_DESC desc;
struct signinfo *si = cookie;
if (argc == 0)
log_fatal ("Usage: %s KEYID\n", option);
if (si->issuer_pk)
log_fatal ("%s: multiple keys provided\n", option);
err = classify_user_id (argv[0], &desc, 0);
if (err)
log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
hd = keydb_new ();
err = keydb_search (hd, &desc, 1, NULL);
if (err)
log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err));
err = keydb_get_keyblock (hd, &si->issuer_kb);
if (err)
log_fatal ("retrieving keyblock for '%s': %s\n",
argv[0], gpg_strerror (err));
keydb_release (hd);
si->issuer_pk = si->issuer_kb->pkt->pkt.public_key;
return 1;
}
static int
sig_issuer_keyid (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
KEYDB_SEARCH_DESC desc;
struct signinfo *si = cookie;
if (argc == 0)
log_fatal ("Usage: %s KEYID|self\n", option);
if (si->issuer_keyid[0] || si->issuer_keyid[1] || si->issuer_keyid_self)
log_fatal ("%s given multiple times.\n", option);
if (strcasecmp (argv[0], "self") == 0)
{
si->issuer_keyid_self = 1;
return 1;
}
err = classify_user_id (argv[0], &desc, 0);
if (err)
log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
if (desc.mode != KEYDB_SEARCH_MODE_LONG_KID)
log_fatal ("%s is not a valid long key id.\n", argv[0]);
keyid_copy (si->issuer_keyid, desc.u.kid);
return 1;
}
static int
sig_pk (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int i;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s COMPONENT_INDEX\n", option);
errno = 0;
i = strtoul (argv[0], &tail, 10);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
if (i >= ncomponents)
log_fatal ("%d: No such component (have %d components so far)\n",
i, ncomponents);
if (! (components[i].pkttype == PKT_PUBLIC_KEY
|| components[i].pkttype == PKT_PUBLIC_SUBKEY))
log_fatal ("Component %d is not a public key or a subkey.", i);
if (strcmp (option, "--pk") == 0)
{
if (si->pk)
log_fatal ("%s already given.\n", option);
si->pk = components[i].pkt.public_key;
}
else if (strcmp (option, "--sk") == 0)
{
if (si->sk)
log_fatal ("%s already given.\n", option);
si->sk = components[i].pkt.public_key;
}
else
log_fatal ("Cannot handle %s\n", option);
return 1;
}
static int
sig_user_id (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int i;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s COMPONENT_INDEX\n", option);
if (si->uid)
log_fatal ("%s already given.\n", option);
errno = 0;
i = strtoul (argv[0], &tail, 10);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
if (i >= ncomponents)
log_fatal ("%d: No such component (have %d components so far)\n",
i, ncomponents);
if (! (components[i].pkttype != PKT_USER_ID
|| components[i].pkttype == PKT_ATTRIBUTE))
log_fatal ("Component %d is not a public key or a subkey.", i);
si->uid = components[i].pkt.user_id;
return 1;
}
static int
sig_class (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int i;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s CLASS\n", option);
errno = 0;
i = strtoul (argv[0], &tail, 0);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
si->class = i;
return 1;
}
static int
sig_digest (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int i;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s DIGEST_ALGO\n", option);
errno = 0;
i = strtoul (argv[0], &tail, 10);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
si->digest_algo = i;
return 1;
}
static int
sig_timestamp (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s TIMESTAMP\n", option);
errno = 0;
si->timestamp = parse_timestamp (argv[0], &tail);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
return 1;
}
static int
sig_expiration (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int is_expiration = strcmp (option, "--expiration") == 0;
u32 *i = is_expiration ? &si->expiration : &si->key_expiration;
if (! is_expiration)
log_assert (strcmp (option, "--key-expiration") == 0);
if (argc == 0)
log_fatal ("Usage: %s DURATION\n", option);
*i = parse_expire_string (argv[0]);
if (*i == (u32)-1)
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
return 1;
}
static int
sig_int_list (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int nvalues = 1;
char *values = xmalloc (nvalues * sizeof (values[0]));
char *tail = argv[0];
int i;
byte **a;
int *n;
if (argc == 0)
log_fatal ("Usage: %s VALUE[,VALUE...]\n", option);
for (i = 0; tail && *tail; i ++)
{
int v;
char *old_tail = tail;
errno = 0;
v = strtol (tail, &tail, 0);
if (errno || old_tail == tail || (tail && !(*tail == ',' || *tail == 0)))
log_fatal ("Invalid value passed to %s (%s). "
"Expected a list of comma separated numbers\n",
option, argv[0]);
if (! (0 <= v && v <= 255))
log_fatal ("%s: %d is out of range (Expected: 0-255)\n", option, v);
if (i == nvalues)
{
nvalues *= 2;
values = xrealloc (values, nvalues * sizeof (values[0]));
}
values[i] = v;
if (*tail == ',')
tail ++;
else
log_assert (*tail == 0);
}
if (strcmp ("--cipher-algos", option) == 0)
{
a = &si->cipher_algorithms;
n = &si->cipher_algorithms_len;
}
else if (strcmp ("--digest-algos", option) == 0)
{
a = &si->digest_algorithms;
n = &si->digest_algorithms_len;
}
else if (strcmp ("--compress-algos", option) == 0)
{
a = &si->compress_algorithms;
n = &si->compress_algorithms_len;
}
else
log_fatal ("Cannot handle %s\n", option);
if (*a)
log_fatal ("Option %s given multiple times.\n", option);
*a = values;
*n = i;
return 1;
}
static int
sig_flag (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int range[2] = {0, 255};
char *tail;
int v;
if (strcmp (option, "--primary-user-id") == 0)
range[1] = 1;
if (argc <= 1)
{
if (range[0] == 0 && range[1] == 1)
log_fatal ("Usage: %s 0|1\n", option);
else
log_fatal ("Usage: %s %d-%d\n", option, range[0], range[1]);
}
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1]))
log_fatal ("Invalid value passed to %s (%s). Expected %d-%d\n",
option, argv[0], range[0], range[1]);
if (strcmp (option, "--exportable") == 0)
{
si->exportable_set = 1;
si->exportable = v;
}
else if (strcmp (option, "--revocable") == 0)
{
si->revocable_set = 1;
si->revocable = v;
}
else if (strcmp (option, "--primary-user-id") == 0)
{
si->primary_user_id_set = 1;
si->primary_user_id = v;
}
else
log_fatal ("Cannot handle %s\n", option);
return 1;
}
static int
sig_trust_level (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int i;
char *tail;
if (argc <= 1)
log_fatal ("Usage: %s DEPTH TRUST_AMOUNT\n", option);
for (i = 0; i < sizeof (si->trust_args) / sizeof (si->trust_args[0]); i ++)
{
int v;
errno = 0;
v = strtol (argv[i], &tail, 0);
if (errno || (tail && *tail) || !(0 <= v && v <= 255))
log_fatal ("Invalid value passed to %s (%s). Expected 0-255\n",
option, argv[i]);
si->trust_args[i] = v;
}
si->trust_level_set = 1;
return 2;
}
static int
sig_string_arg (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
char *p = argv[0];
char **s;
if (argc == 0)
log_fatal ("Usage: %s STRING\n", option);
if (strcmp (option, "--trust-scope") == 0)
s = &si->trust_scope;
else if (strcmp (option, "--key-server") == 0)
s = &si->key_server;
else if (strcmp (option, "--signers-user-id") == 0)
s = &si->signers_user_id;
else if (strcmp (option, "--policy-uri") == 0)
s = &si->policy_uri;
else
log_fatal ("Cannot handle %s\n", option);
if (*s)
log_fatal ("%s already given.\n", option);
*s = xstrdup (p);
return 1;
}
static int
sig_revocation_key (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
struct signinfo *si = cookie;
int v;
char *tail;
PKT_public_key pk;
struct revocation_key *revkey;
if (argc < 2)
log_fatal ("Usage: %s CLASS KEYID\n", option);
memset (&pk, 0, sizeof (pk));
errno = 0;
v = strtol (argv[0], &tail, 16);
if (errno || (tail && *tail) || !(0 <= v && v <= 255))
log_fatal ("%s: Invalid class value (%s). Expected 0-255\n",
option, argv[0]);
pk.req_usage = PUBKEY_USAGE_SIG;
err = get_pubkey_byname (NULL, NULL, &pk, argv[1], NULL, NULL, 1, 1);
if (err)
log_fatal ("looking up key %s: %s\n", argv[1], gpg_strerror (err));
si->nrevocation_keys ++;
si->revocation_key = xrealloc (si->revocation_key,
si->nrevocation_keys
* sizeof (*si->revocation_key));
revkey = &si->revocation_key[si->nrevocation_keys - 1];
revkey->class = v;
revkey->algid = pk.pubkey_algo;
fingerprint_from_pk (&pk, revkey->fpr, NULL);
release_public_key_parts (&pk);
return 2;
}
static int
sig_notation (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int is_blob = strcmp (option, "--notation") != 0;
struct notation *notation;
char *p = argv[0];
int p_free = 0;
char *data;
int data_size;
int data_len;
if (argc == 0)
log_fatal ("Usage: %s [!<]name=value\n", option);
if ((p[0] == '!' && p[1] == '<') || p[0] == '<')
/* Read from a file. */
{
char *filename = NULL;
iobuf_t in;
int prefix;
if (p[0] == '<')
p ++;
else
{
/* Remove the '<', which string_to_notation does not
understand, and preserve the '!'. */
p = xstrdup (&p[1]);
p_free = 1;
p[0] = '!';
}
filename = strchr (p, '=');
if (! filename)
log_fatal ("No value specified. Usage: %s [!<]name=value\n",
option);
filename ++;
prefix = (size_t) filename - (size_t) p;
errno = 0;
in = iobuf_open (filename);
if (! in)
log_fatal ("Opening '%s': %s\n",
filename, errno ? strerror (errno): "unknown error");
/* A notation can be at most about a few dozen bytes short of
64k. Since this is relatively small, we just allocate that
much instead of trying to dynamically size a buffer. */
data_size = 64 * 1024;
data = xmalloc (data_size);
log_assert (prefix <= data_size);
memcpy (data, p, prefix);
data_len = iobuf_read (in, &data[prefix], data_size - prefix - 1);
if (data_len == -1)
/* EOF => 0 bytes read. */
data_len = 0;
if (data_len == data_size - prefix - 1)
/* Technically, we should do another read and check for EOF,
but what's one byte more or less? */
log_fatal ("Notation data doesn't fit in the packet.\n");
iobuf_close (in);
/* NUL terminate it. */
data[prefix + data_len] = 0;
if (p_free)
xfree (p);
p = data;
p_free = 1;
data = &p[prefix];
if (is_blob)
p[prefix - 1] = 0;
}
else if (is_blob)
{
data = strchr (p, '=');
if (! data)
{
data = p;
data_len = 0;
}
else
{
p = xstrdup (p);
p_free = 1;
data = strchr (p, '=');
log_assert (data);
/* NUL terminate the name. */
*data = 0;
data ++;
data_len = strlen (data);
}
}
if (is_blob)
notation = blob_to_notation (p, data, data_len);
else
notation = string_to_notation (p, 1);
if (! notation)
log_fatal ("creating notation: an unknown error occurred.\n");
notation->next = si->notations;
si->notations = notation;
if (p_free)
xfree (p);
return 1;
}
static int
sig_big_endian_arg (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
char *p = argv[0];
int i;
int l;
char *bytes;
if (argc == 0)
log_fatal ("Usage: %s HEXDIGITS\n", option);
/* Skip a leading "0x". */
if (p[0] == '0' && p[1] == 'x')
p += 2;
for (i = 0; i < strlen (p); i ++)
if (!hexdigitp (&p[i]))
log_fatal ("%s: argument ('%s') must consist of hex digits.\n",
option, p);
if (strlen (p) % 2 != 0)
log_fatal ("%s: argument ('%s') must contain an even number of hex digits.\n",
option, p);
l = strlen (p) / 2;
bytes = xmalloc (l);
hex2bin (p, bytes, l);
if (strcmp (option, "--key-server-preferences") == 0)
{
if (si->key_server_preferences)
log_fatal ("%s given multiple times.\n", option);
si->key_server_preferences = bytes;
si->key_server_preferences_len = l;
}
else if (strcmp (option, "--key-flags") == 0)
{
if (si->key_flags)
log_fatal ("%s given multiple times.\n", option);
si->key_flags = bytes;
si->key_flags_len = l;
}
else if (strcmp (option, "--features") == 0)
{
if (si->features)
log_fatal ("%s given multiple times.\n", option);
si->features = bytes;
si->features_len = l;
}
else
log_fatal ("Cannot handle %s\n", option);
return 1;
}
static int
sig_reason_for_revocation (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
int v;
char *tail;
if (argc < 2)
log_fatal ("Usage: %s REASON_CODE REASON_STRING\n", option);
errno = 0;
v = strtol (argv[0], &tail, 16);
if (errno || (tail && *tail) || !(0 <= v && v <= 255))
log_fatal ("%s: Invalid reason code (%s). Expected 0-255\n",
option, argv[0]);
if (si->reason_for_revocation)
log_fatal ("%s given multiple times.\n", option);
si->reason_for_revocation_code = v;
si->reason_for_revocation = xstrdup (argv[1]);
return 2;
}
static int
sig_corrupt (const char *option, int argc, char *argv[], void *cookie)
{
struct signinfo *si = cookie;
(void) option;
(void) argc;
(void) argv;
(void) cookie;
si->corrupt = 1;
return 0;
}
static struct option sig_options[] = {
{ "--issuer", sig_issuer,
"The key to use to generate the signature."},
{ "--issuer-keyid", sig_issuer_keyid,
"Set the issuer's key id. This is useful for creating a "
"self-signature. As a special case, the value \"self\" refers "
"to the primary key's key id. "
"(RFC 4880, Section 5.2.3.5)" },
{ "--pk", sig_pk,
"The primary keyas an index into the components (keys and uids) "
"created so far where the first component has the index 0." },
{ "--sk", sig_pk,
"The subkey as an index into the components (keys and uids) created "
"so far where the first component has the index 0. Only needed for "
"0x18, 0x19, and 0x28 signatures." },
{ "--user-id", sig_user_id,
"The user id as an index into the components (keys and uids) created "
"so far where the first component has the index 0. Only needed for "
"0x10-0x13 and 0x30 signatures." },
{ "--class", sig_class,
"The signature's class. Valid values are "
"0x10-0x13 (user id and primary-key certification), "
"0x18 (subkey binding), "
"0x19 (primary key binding), "
"0x1f (direct primary key signature), "
"0x20 (key revocation), "
"0x28 (subkey revocation), and "
"0x30 (certification revocation)."
},
{ "--digest", sig_digest, "The digest algorithm" },
{ "--timestamp", sig_timestamp,
"The signature's creation time. " TIMESTAMP_HELP " 0 means now. "
"(RFC 4880, Section 5.2.3.4)" },
{ "--key-expiration", sig_expiration,
"The number of days until the associated key expires. To specify "
"seconds, prefix the value with \"seconds=\". It is also possible "
"to use 'y', 'm' and 'w' as simple multipliers. For instance, 2y "
"means 2 years, etc. "
"(RFC 4880, Section 5.2.3.6)" },
{ "--cipher-algos", sig_int_list,
"A comma separated list of the preferred cipher algorithms (identified by "
"their number, see RFC 4880, Section 9). "
"(RFC 4880, Section 5.2.3.7)" },
{ "--digest-algos", sig_int_list,
"A comma separated list of the preferred algorithms (identified by "
"their number, see RFC 4880, Section 9). "
"(RFC 4880, Section 5.2.3.8)" },
{ "--compress-algos", sig_int_list,
"A comma separated list of the preferred algorithms (identified by "
"their number, see RFC 4880, Section 9)."
"(RFC 4880, Section 5.2.3.9)" },
{ "--expiration", sig_expiration,
"The number of days until the signature expires. To specify seconds, "
"prefix the value with \"seconds=\". It is also possible to use 'y', "
"'m' and 'w' as simple multipliers. For instance, 2y means 2 years, "
"etc. "
"(RFC 4880, Section 5.2.3.10)" },
{ "--exportable", sig_flag,
"Mark this signature as exportable (1) or local (0). "
"(RFC 4880, Section 5.2.3.11)" },
{ "--revocable", sig_flag,
"Mark this signature as revocable (1, revocations are ignored) "
"or non-revocable (0). "
"(RFC 4880, Section 5.2.3.12)" },
{ "--trust-level", sig_trust_level,
"Set the trust level. This takes two integer arguments (0-255): "
"the trusted-introducer level and the degree of trust. "
"(RFC 4880, Section 5.2.3.13.)" },
{ "--trust-scope", sig_string_arg,
"A regular expression that limits the scope of --trust-level. "
"(RFC 4880, Section 5.2.3.14.)" },
{ "--revocation-key", sig_revocation_key,
"Specify a designated revoker. Takes two arguments: the class "
"(normally 0x80 or 0xC0 (sensitive)) and the key id of the "
"designatured revoker. May be given multiple times. "
"(RFC 4880, Section 5.2.3.15)" },
{ "--notation", sig_notation,
"Add a human-readable notation of the form \"[!<]name=value\" where "
"\"!\" means that the critical flag should be set and \"<\" means "
"that VALUE is a file to read the data from. "
"(RFC 4880, Section 5.2.3.16)" },
{ "--notation-binary", sig_notation,
"Add a binary notation of the form \"[!<]name=value\" where "
"\"!\" means that the critical flag should be set and \"<\" means "
"that VALUE is a file to read the data from. "
"(RFC 4880, Section 5.2.3.16)" },
{ "--key-server-preferences", sig_big_endian_arg,
"Big-endian number encoding the keyserver preferences. "
"(RFC 4880, Section 5.2.3.17)" },
{ "--key-server", sig_string_arg,
"The preferred keyserver. (RFC 4880, Section 5.2.3.18)" },
{ "--primary-user-id", sig_flag,
"Sets the primary user id flag. (RFC 4880, Section 5.2.3.19)" },
{ "--policy-uri", sig_string_arg,
"URI of a document that describes the issuer's signing policy. "
"(RFC 4880, Section 5.2.3.20)" },
{ "--key-flags", sig_big_endian_arg,
"Big-endian number encoding the key flags. "
"(RFC 4880, Section 5.2.3.21)" },
{ "--signers-user-id", sig_string_arg,
"The user id (as a string) responsible for the signing. "
"(RFC 4880, Section 5.2.3.22)" },
{ "--reason-for-revocation", sig_reason_for_revocation,
"Takes two arguments: a reason for revocation code and a "
"user-provided string. "
"(RFC 4880, Section 5.2.3.23)" },
{ "--features", sig_big_endian_arg,
"Big-endian number encoding the feature flags. "
"(RFC 4880, Section 5.2.3.24)" },
{ "--signature-target", NULL,
"Takes three arguments: the target signature's public key algorithm "
" (as an integer), the hash algorithm (as an integer) and the hash "
" (as a hexadecimal string). "
"(RFC 4880, Section 5.2.3.25)" },
{ "--embedded-signature", NULL,
"An embedded signature. This must be immediately followed by a "
"signature packet (created using --signature ...) or a filename "
"containing the packet."
"(RFC 4880, Section 5.2.3.26)" },
{ "--hashed", NULL,
"The following attributes will be placed in the hashed area of "
"the signature. (This is the default and it reset at the end of"
"each signature.)" },
{ "--unhashed", NULL,
"The following attributes will be placed in the unhashed area of "
"the signature (and thus not integrity protected)." },
{ "--corrupt", sig_corrupt,
"Corrupt the signature." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --public-key $KEYID --user-id USERID \\\n"
" --signature --class 0x10 --issuer $KEYID --issuer-keyid self \\\n"
" | " GPG_NAME " --list-packets"}
};
static int
mksubpkt_callback (PKT_signature *sig, void *cookie)
{
struct signinfo *si = cookie;
int i;
if (si->key_expiration)
{
char buf[4];
buf[0] = (si->key_expiration >> 24) & 0xff;
buf[1] = (si->key_expiration >> 16) & 0xff;
buf[2] = (si->key_expiration >> 8) & 0xff;
buf[3] = si->key_expiration & 0xff;
build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
}
if (si->cipher_algorithms)
build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM,
si->cipher_algorithms,
si->cipher_algorithms_len);
if (si->digest_algorithms)
build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH,
si->digest_algorithms,
si->digest_algorithms_len);
if (si->compress_algorithms)
build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR,
si->compress_algorithms,
si->compress_algorithms_len);
if (si->exportable_set)
{
char buf = si->exportable;
build_sig_subpkt (sig, SIGSUBPKT_EXPORTABLE, &buf, 1);
}
if (si->trust_level_set)
build_sig_subpkt (sig, SIGSUBPKT_TRUST,
si->trust_args, sizeof (si->trust_args));
if (si->trust_scope)
build_sig_subpkt (sig, SIGSUBPKT_REGEXP,
si->trust_scope, strlen (si->trust_scope));
for (i = 0; i < si->nrevocation_keys; i ++)
{
struct revocation_key *revkey = &si->revocation_key[i];
gpg_error_t err = keygen_add_revkey (sig, revkey);
if (err)
{
u32 keyid[2];
keyid_from_fingerprint (global_ctrl, revkey->fpr, 20, keyid);
log_fatal ("adding revocation key %s: %s\n",
keystr (keyid), gpg_strerror (err));
}
}
/* keygen_add_revkey sets revocable=0 so be sure to do this after
adding the rev keys. */
if (si->revocable_set)
{
char buf = si->revocable;
build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, &buf, 1);
}
keygen_add_notations (sig, si->notations);
if (si->key_server_preferences)
build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS,
si->key_server_preferences,
si->key_server_preferences_len);
if (si->key_server)
build_sig_subpkt (sig, SIGSUBPKT_PREF_KS,
si->key_server, strlen (si->key_server));
if (si->primary_user_id_set)
{
char buf = si->primary_user_id;
build_sig_subpkt (sig, SIGSUBPKT_PRIMARY_UID, &buf, 1);
}
if (si->policy_uri)
build_sig_subpkt (sig, SIGSUBPKT_POLICY,
si->policy_uri, strlen (si->policy_uri));
if (si->key_flags)
build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS,
si->key_flags, si->key_flags_len);
if (si->signers_user_id)
build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
si->signers_user_id, strlen (si->signers_user_id));
if (si->reason_for_revocation)
{
int len = 1 + strlen (si->reason_for_revocation);
char *buf;
buf = xmalloc (len);
buf[0] = si->reason_for_revocation_code;
memcpy (&buf[1], si->reason_for_revocation, len - 1);
build_sig_subpkt (sig, SIGSUBPKT_REVOC_REASON, buf, len);
xfree (buf);
}
if (si->features)
build_sig_subpkt (sig, SIGSUBPKT_FEATURES,
si->features, si->features_len);
return 0;
}
static int
signature (const char *option, int argc, char *argv[], void *cookie)
{
gpg_error_t err;
iobuf_t out = cookie;
struct signinfo si;
int processed;
PKT_public_key *pk;
PKT_signature *sig;
PACKET pkt;
u32 keyid_orig[2], keyid[2];
(void) option;
memset (&si, 0, sizeof (si));
memset (&pkt, 0, sizeof (pkt));
processed = process_options (option,
major_options,
sig_options, &si,
global_options, NULL,
argc, argv);
if (ncomponents)
{
int pkttype = components[ncomponents - 1].pkttype;
if (pkttype == PKT_PUBLIC_KEY)
{
if (! si.class)
/* Direct key sig. */
si.class = 0x1F;
}
else if (pkttype == PKT_PUBLIC_SUBKEY)
{
if (! si.sk)
si.sk = components[ncomponents - 1].pkt.public_key;
if (! si.class)
/* Subkey binding sig. */
si.class = 0x18;
}
else if (pkttype == PKT_USER_ID)
{
if (! si.uid)
si.uid = components[ncomponents - 1].pkt.user_id;
if (! si.class)
/* Certification of a user id and public key packet. */
si.class = 0x10;
}
}
pk = NULL;
if (! si.pk || ! si.issuer_pk)
/* No primary key specified. Default to the first one that we
find. */
{
int i;
for (i = 0; i < ncomponents; i ++)
if (components[i].pkttype == PKT_PUBLIC_KEY)
{
pk = components[i].pkt.public_key;
break;
}
}
if (! si.pk)
{
if (! pk)
log_fatal ("%s: no primary key given and no primary key available",
"--pk");
si.pk = pk;
}
if (! si.issuer_pk)
{
if (! pk)
log_fatal ("%s: no issuer key given and no primary key available",
"--issuer");
si.issuer_pk = pk;
}
if (si.class == 0x18 || si.class == 0x19 || si.class == 0x28)
/* Requires the primary key and a subkey. */
{
if (! si.sk)
log_fatal ("sig class 0x%x requires a subkey (--sk)\n", si.class);
}
else if (si.class == 0x10
|| si.class == 0x11
|| si.class == 0x12
|| si.class == 0x13
|| si.class == 0x30)
/* Requires the primary key and a user id. */
{
if (! si.uid)
log_fatal ("sig class 0x%x requires a uid (--uid)\n", si.class);
}
else if (si.class == 0x1F || si.class == 0x20)
/* Just requires the primary key. */
;
else
log_fatal ("Unsupported signature class: 0x%x\n", si.class);
sig = xmalloc_clear (sizeof (*sig));
/* Save SI.ISSUER_PK->KEYID. */
keyid_copy (keyid_orig, pk_keyid (si.issuer_pk));
if (si.issuer_keyid[0] || si.issuer_keyid[1])
keyid_copy (si.issuer_pk->keyid, si.issuer_keyid);
else if (si.issuer_keyid_self)
{
PKT_public_key *pripk = primary_key();
if (! pripk)
log_fatal ("--issuer-keyid self given, but no primary key available.\n");
keyid_copy (si.issuer_pk->keyid, pk_keyid (pripk));
}
/* Changing the issuer's key id is fragile. Check to make sure
make_keysig_packet didn't recompute the keyid. */
keyid_copy (keyid, si.issuer_pk->keyid);
err = make_keysig_packet (global_ctrl,
&sig, si.pk, si.uid, si.sk, si.issuer_pk,
si.class, si.digest_algo,
si.timestamp, si.expiration,
mksubpkt_callback, &si, NULL);
log_assert (keyid_cmp (keyid, si.issuer_pk->keyid) == 0);
if (err)
log_fatal ("Generating signature: %s\n", gpg_strerror (err));
/* Restore SI.PK->KEYID. */
keyid_copy (si.issuer_pk->keyid, keyid_orig);
if (si.corrupt)
{
/* Set the top 32-bits to 0xBAD0DEAD. */
int bits = gcry_mpi_get_nbits (sig->data[0]);
gcry_mpi_t x = gcry_mpi_new (0);
gcry_mpi_add_ui (x, x, 0xBAD0DEAD);
gcry_mpi_lshift (x, x, bits > 32 ? bits - 32 : bits);
gcry_mpi_clear_highbit (sig->data[0], bits > 32 ? bits - 32 : 0);
gcry_mpi_add (sig->data[0], sig->data[0], x);
gcry_mpi_release (x);
}
pkt.pkttype = PKT_SIGNATURE;
pkt.pkt.signature = sig;
err = build_packet (out, &pkt);
if (err)
log_fatal ("serializing public key packet: %s\n", gpg_strerror (err));
debug ("Wrote signature packet:\n");
dump_component (&pkt);
xfree (sig);
release_kbnode (si.issuer_kb);
xfree (si.revocation_key);
return processed;
}
struct sk_esk_info
{
/* The cipher used for encrypting the session key (when a session
key is used). */
int cipher;
/* The cipher used for encryping the SED packet. */
int sed_cipher;
/* S2K related data. */
int hash;
int mode;
int mode_set;
byte salt[8];
int salt_set;
int iterations;
/* If applying the S2K function to the passphrase is the session key
or if it is the decryption key for the session key. */
int s2k_is_session_key;
/* Generate a new, random session key. */
int new_session_key;
/* The unencrypted session key. */
int session_key_len;
char *session_key;
char *password;
};
static int
sk_esk_cipher (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "integer|IDEA|3DES|CAST5|BLOWFISH|AES|AES192|AES256|CAMELLIA128|CAMELLIA192|CAMELLIA256";
int cipher;
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (strcasecmp (argv[0], "IDEA") == 0)
cipher = CIPHER_ALGO_IDEA;
else if (strcasecmp (argv[0], "3DES") == 0)
cipher = CIPHER_ALGO_3DES;
else if (strcasecmp (argv[0], "CAST5") == 0)
cipher = CIPHER_ALGO_CAST5;
else if (strcasecmp (argv[0], "BLOWFISH") == 0)
cipher = CIPHER_ALGO_BLOWFISH;
else if (strcasecmp (argv[0], "AES") == 0)
cipher = CIPHER_ALGO_AES;
else if (strcasecmp (argv[0], "AES192") == 0)
cipher = CIPHER_ALGO_AES192;
else if (strcasecmp (argv[0], "TWOFISH") == 0)
cipher = CIPHER_ALGO_TWOFISH;
else if (strcasecmp (argv[0], "CAMELLIA128") == 0)
cipher = CIPHER_ALGO_CAMELLIA128;
else if (strcasecmp (argv[0], "CAMELLIA192") == 0)
cipher = CIPHER_ALGO_CAMELLIA192;
else if (strcasecmp (argv[0], "CAMELLIA256") == 0)
cipher = CIPHER_ALGO_CAMELLIA256;
else
{
char *tail;
int v;
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail) || ! valid_cipher (v))
log_fatal ("Invalid or unsupported value. Usage: %s %s\n",
option, usage);
cipher = v;
}
if (strcmp (option, "--cipher") == 0)
{
if (si->cipher)
log_fatal ("%s given multiple times.", option);
si->cipher = cipher;
}
else if (strcmp (option, "--sed-cipher") == 0)
{
if (si->sed_cipher)
log_fatal ("%s given multiple times.", option);
si->sed_cipher = cipher;
}
return 1;
}
static int
sk_esk_mode (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "integer|simple|salted|iterated";
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (si->mode)
log_fatal ("%s given multiple times.", option);
if (strcasecmp (argv[0], "simple") == 0)
si->mode = 0;
else if (strcasecmp (argv[0], "salted") == 0)
si->mode = 1;
else if (strcasecmp (argv[0], "iterated") == 0)
si->mode = 3;
else
{
char *tail;
int v;
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail) || ! (v == 0 || v == 1 || v == 3))
log_fatal ("Invalid or unsupported value. Usage: %s %s\n",
option, usage);
si->mode = v;
}
si->mode_set = 1;
return 1;
}
static int
sk_esk_hash_algorithm (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "integer|MD5|SHA1|RMD160|SHA256|SHA384|SHA512|SHA224";
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (si->hash)
log_fatal ("%s given multiple times.", option);
if (strcasecmp (argv[0], "MD5") == 0)
si->hash = DIGEST_ALGO_MD5;
else if (strcasecmp (argv[0], "SHA1") == 0)
si->hash = DIGEST_ALGO_SHA1;
else if (strcasecmp (argv[0], "RMD160") == 0)
si->hash = DIGEST_ALGO_RMD160;
else if (strcasecmp (argv[0], "SHA256") == 0)
si->hash = DIGEST_ALGO_SHA256;
else if (strcasecmp (argv[0], "SHA384") == 0)
si->hash = DIGEST_ALGO_SHA384;
else if (strcasecmp (argv[0], "SHA512") == 0)
si->hash = DIGEST_ALGO_SHA512;
else if (strcasecmp (argv[0], "SHA224") == 0)
si->hash = DIGEST_ALGO_SHA224;
else
{
char *tail;
int v;
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail)
|| ! (v == DIGEST_ALGO_MD5
|| v == DIGEST_ALGO_SHA1
|| v == DIGEST_ALGO_RMD160
|| v == DIGEST_ALGO_SHA256
|| v == DIGEST_ALGO_SHA384
|| v == DIGEST_ALGO_SHA512
|| v == DIGEST_ALGO_SHA224))
log_fatal ("Invalid or unsupported value. Usage: %s %s\n",
option, usage);
si->hash = v;
}
return 1;
}
static int
sk_esk_salt (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "16-HEX-CHARACTERS";
char *p = argv[0];
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (si->salt_set)
log_fatal ("%s given multiple times.", option);
if (p[0] == '0' && p[1] == 'x')
p += 2;
if (strlen (p) != 16)
log_fatal ("%s: Salt must be exactly 16 hexadecimal characters (have: %zd)\n",
option, strlen (p));
if (hex2bin (p, si->salt, sizeof (si->salt)) == -1)
log_fatal ("%s: Salt must only contain hexadecimal characters\n",
option);
si->salt_set = 1;
return 1;
}
static int
sk_esk_iterations (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "ITERATION-COUNT";
char *tail;
int v;
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail) || v < 0)
log_fatal ("%s: Non-negative integer expected.\n", option);
si->iterations = v;
return 1;
}
static int
sk_esk_session_key (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "HEX-CHARACTERS|auto|none";
char *p = argv[0];
struct session_key sk;
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (si->session_key || si->s2k_is_session_key
|| si->new_session_key)
log_fatal ("%s given multiple times.", option);
if (strcasecmp (p, "none") == 0)
{
si->s2k_is_session_key = 1;
return 1;
}
if (strcasecmp (p, "new") == 0)
{
si->new_session_key = 1;
return 1;
}
if (strcasecmp (p, "auto") == 0)
return 1;
sk = parse_session_key (option, p, 0);
if (si->session_key)
log_fatal ("%s given multiple times.", option);
if (sk.algo)
si->sed_cipher = sk.algo;
si->session_key_len = sk.keylen;
si->session_key = sk.key;
return 1;
}
static int
sk_esk_password (const char *option, int argc, char *argv[], void *cookie)
{
struct sk_esk_info *si = cookie;
char *usage = "PASSWORD";
if (argc == 0)
log_fatal ("Usage: --sk-esk %s\n", usage);
if (si->password)
log_fatal ("%s given multiple times.", option);
si->password = xstrdup (argv[0]);
return 1;
}
static struct option sk_esk_options[] = {
{ "--cipher", sk_esk_cipher,
"The encryption algorithm for encrypting the session key. "
"One of IDEA, 3DES, CAST5, BLOWFISH, AES (default), AES192, "
"AES256, TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." },
{ "--sed-cipher", sk_esk_cipher,
"The encryption algorithm for encrypting the SED packet. "
"One of IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, "
"AES256 (default), TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." },
{ "--mode", sk_esk_mode,
"The S2K mode. Either one of the strings \"simple\", \"salted\" "
"or \"iterated\" or an integer." },
{ "--hash", sk_esk_hash_algorithm,
"The hash algorithm to used to derive the key. One of "
"MD5, SHA1 (default), RMD160, SHA256, SHA384, SHA512, or SHA224." },
{ "--salt", sk_esk_salt,
"The S2K salt encoded as 16 hexadecimal characters. One needed "
"if the S2K function is in salted or iterated mode." },
{ "--iterations", sk_esk_iterations,
"The iteration count. If not provided, a reasonable value is chosen. "
"Note: due to the encoding scheme, not every value is valid. For "
"convenience, the provided value will be rounded appropriately. "
"Only needed if the S2K function is in iterated mode." },
{ "--session-key", sk_esk_session_key,
"The session key to be encrypted by the S2K function as a hexadecimal "
"string. If this is \"new\", then a new session key is generated."
"If this is \"auto\", then either the last session key is "
"used, if the was none, one is generated. If this is \"none\", then "
"the session key is the result of applying the S2K algorithms to the "
"password. The session key may be prefaced with an integer and a colon "
"to indicate the cipher to use for the SED packet (making --sed-cipher "
"unnecessary and allowing the direct use of the result of "
"\"" GPG_NAME " --show-session-key\")." },
{ "", sk_esk_password, "The password." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --sk-esk foobar --encrypted \\\n"
" --literal --value foo | " GPG_NAME " --list-packets" }
};
static int
sk_esk (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
gpg_error_t err;
int processed;
struct sk_esk_info si;
DEK sesdek;
DEK s2kdek;
PKT_symkey_enc *ske;
PACKET pkt;
memset (&si, 0, sizeof (si));
processed = process_options (option,
major_options,
sk_esk_options, &si,
global_options, NULL,
argc, argv);
if (! si.password)
log_fatal ("%s: missing password. Usage: %s PASSWORD", option, option);
/* Fill in defaults, if appropriate. */
if (! si.cipher)
si.cipher = CIPHER_ALGO_AES;
if (! si.sed_cipher)
si.sed_cipher = CIPHER_ALGO_AES256;
if (! si.hash)
si.hash = DIGEST_ALGO_SHA1;
if (! si.mode_set)
/* Salted and iterated. */
si.mode = 3;
if (si.mode != 0 && ! si.salt_set)
/* Generate a salt. */
gcry_randomize (si.salt, 8, GCRY_STRONG_RANDOM);
if (si.mode == 0)
{
if (si.iterations)
log_info ("%s: --iterations provided, but not used for mode=0\n",
option);
si.iterations = 0;
}
else if (! si.iterations)
si.iterations = 10000;
memset (&sesdek, 0, sizeof (sesdek));
/* The session key is used to encrypt the SED packet. */
sesdek.algo = si.sed_cipher;
if (si.session_key)
/* Copy the unencrypted session key into SESDEK. */
{
sesdek.keylen = openpgp_cipher_get_algo_keylen (sesdek.algo);
if (sesdek.keylen != si.session_key_len)
log_fatal ("%s: Cipher algorithm requires a %d byte session key, but provided session key is %d bytes.",
option, sesdek.keylen, si.session_key_len);
log_assert (sesdek.keylen <= sizeof (sesdek.key));
memcpy (sesdek.key, si.session_key, sesdek.keylen);
}
else if (! si.s2k_is_session_key || si.new_session_key)
/* We need a session key, but one wasn't provided. Generate it. */
make_session_key (&sesdek);
/* The encrypted session key needs 1 + SESDEK.KEYLEN bytes of
space. */
ske = xmalloc_clear (sizeof (*ske) + sesdek.keylen);
ske->version = 4;
ske->cipher_algo = si.cipher;
ske->s2k.mode = si.mode;
ske->s2k.hash_algo = si.hash;
log_assert (sizeof (si.salt) == sizeof (ske->s2k.salt));
memcpy (ske->s2k.salt, si.salt, sizeof (ske->s2k.salt));
if (! si.s2k_is_session_key)
/* 0 means get the default. */
ske->s2k.count = encode_s2k_iterations (si.iterations);
/* Derive the symmetric key that is either the session key or the
key used to encrypt the session key. */
memset (&s2kdek, 0, sizeof (s2kdek));
s2kdek.algo = si.cipher;
s2kdek.keylen = openpgp_cipher_get_algo_keylen (s2kdek.algo);
err = gcry_kdf_derive (si.password, strlen (si.password),
ske->s2k.mode == 3 ? GCRY_KDF_ITERSALTED_S2K
: ske->s2k.mode == 1 ? GCRY_KDF_SALTED_S2K
: GCRY_KDF_SIMPLE_S2K,
ske->s2k.hash_algo, ske->s2k.salt, 8,
S2K_DECODE_COUNT (ske->s2k.count),
/* The size of the desired key and its
buffer. */
s2kdek.keylen, s2kdek.key);
if (err)
log_fatal ("gcry_kdf_derive failed: %s", gpg_strerror (err));
if (si.s2k_is_session_key)
{
ske->seskeylen = 0;
session_key = s2kdek;
}
else
/* Encrypt the session key using the s2k specifier. */
{
DEK *sesdekp = &sesdek;
/* Now encrypt the session key (or rather, the algorithm used to
encrypt the SED plus the session key) using ENCKEY. */
ske->seskeylen = 1 + sesdek.keylen;
encrypt_seskey (&s2kdek, &sesdekp, ske->seskey);
/* Save the session key for later. */
session_key = sesdek;
}
pkt.pkttype = PKT_SYMKEY_ENC;
pkt.pkt.symkey_enc = ske;
err = build_packet (out, &pkt);
if (err)
log_fatal ("Serializing sym-key encrypted packet: %s\n",
gpg_strerror (err));
debug ("Wrote sym-key encrypted packet:\n");
dump_component (&pkt);
xfree (si.session_key);
xfree (si.password);
xfree (ske);
return processed;
}
struct pk_esk_info
{
int session_key_set;
int new_session_key;
int sed_cipher;
int session_key_len;
char *session_key;
int throw_keyid;
char *keyid;
};
static int
pk_esk_session_key (const char *option, int argc, char *argv[], void *cookie)
{
struct pk_esk_info *pi = cookie;
char *usage = "HEX-CHARACTERS|auto|none";
char *p = argv[0];
struct session_key sk;
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (pi->session_key_set)
log_fatal ("%s given multiple times.", option);
pi->session_key_set = 1;
if (strcasecmp (p, "new") == 0)
{
pi->new_session_key = 1;
return 1;
}
if (strcasecmp (p, "auto") == 0)
return 1;
sk = parse_session_key (option, p, 0);
if (pi->session_key)
log_fatal ("%s given multiple times.", option);
if (sk.algo)
pi->sed_cipher = sk.algo;
pi->session_key_len = sk.keylen;
pi->session_key = sk.key;
return 1;
}
static int
pk_esk_throw_keyid (const char *option, int argc, char *argv[], void *cookie)
{
struct pk_esk_info *pi = cookie;
(void) option;
(void) argc;
(void) argv;
pi->throw_keyid = 1;
return 0;
}
static int
pk_esk_keyid (const char *option, int argc, char *argv[], void *cookie)
{
struct pk_esk_info *pi = cookie;
char *usage = "KEYID";
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (pi->keyid)
log_fatal ("Multiple key ids given, but only one is allowed.");
pi->keyid = xstrdup (argv[0]);
return 1;
}
static struct option pk_esk_options[] = {
{ "--session-key", pk_esk_session_key,
"The session key to be encrypted by the S2K function as a hexadecimal "
"string. If this is not given or is \"auto\", then the current "
"session key is used. If there is no session key or this is \"new\", "
"then a new session key is generated. The session key may be "
"prefaced with an integer and a colon to indicate the cipher to use "
"for the SED packet (making --sed-cipher unnecessary and allowing the "
"direct use of the result of \"" GPG_NAME " --show-session-key\")." },
{ "--throw-keyid", pk_esk_throw_keyid,
"Throw the keyid." },
{ "", pk_esk_keyid, "The key id." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --pk-esk $KEYID --encrypted --literal --value foo \\\n"
" | " GPG_NAME " --list-packets"}
};
static int
pk_esk (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
gpg_error_t err;
int processed;
struct pk_esk_info pi;
PKT_public_key pk;
memset (&pi, 0, sizeof (pi));
processed = process_options (option,
major_options,
pk_esk_options, &pi,
global_options, NULL,
argc, argv);
if (! pi.keyid)
log_fatal ("%s: missing keyid. Usage: %s KEYID", option, option);
memset (&pk, 0, sizeof (pk));
pk.req_usage = PUBKEY_USAGE_ENC;
err = get_pubkey_byname (NULL, NULL, &pk, pi.keyid, NULL, NULL, 1, 1);
if (err)
log_fatal ("%s: looking up key %s: %s\n",
option, pi.keyid, gpg_strerror (err));
if (pi.sed_cipher)
/* Have a session key. */
{
session_key.algo = pi.sed_cipher;
session_key.keylen = pi.session_key_len;
log_assert (session_key.keylen <= sizeof (session_key.key));
memcpy (session_key.key, pi.session_key, session_key.keylen);
}
if (pi.new_session_key || ! session_key.algo)
{
if (! pi.new_session_key)
/* Default to AES256. */
session_key.algo = CIPHER_ALGO_AES256;
make_session_key (&session_key);
}
err = write_pubkey_enc (global_ctrl, &pk, pi.throw_keyid, &session_key, out);
if (err)
log_fatal ("%s: writing pk_esk packet for %s: %s\n",
option, pi.keyid, gpg_strerror (err));
debug ("Wrote pk_esk packet for %s\n", pi.keyid);
xfree (pi.keyid);
xfree (pi.session_key);
return processed;
}
struct encinfo
{
int saw_session_key;
};
static int
encrypted_session_key (const char *option, int argc, char *argv[], void *cookie)
{
struct encinfo *ei = cookie;
char *usage = "HEX-CHARACTERS|auto";
char *p = argv[0];
struct session_key sk;
if (argc == 0)
log_fatal ("Usage: %s %s\n", option, usage);
if (ei->saw_session_key)
log_fatal ("%s given multiple times.", option);
ei->saw_session_key = 1;
if (strcasecmp (p, "auto") == 0)
return 1;
sk = parse_session_key (option, p, 1);
session_key.algo = sk.algo;
log_assert (sk.keylen <= sizeof (session_key.key));
memcpy (session_key.key, sk.key, sk.keylen);
xfree (sk.key);
return 1;
}
static struct option encrypted_options[] = {
{ "--session-key", encrypted_session_key,
"The session key to be encrypted by the S2K function as a hexadecimal "
"string. If this is not given or is \"auto\", then the last session key "
"is used. If there was none, then an error is raised. The session key "
"must be prefaced with an integer and a colon to indicate the cipher "
"to use (this is format used by \"" GPG_NAME " --show-session-key\")." },
{ NULL, NULL,
"After creating the packet, this command clears the current "
"session key.\n\n"
"Example: nested encryption packets:\n\n"
" $ gpgcompose --sk-esk foo --encrypted-mdc \\\n"
" --sk-esk bar --encrypted-mdc \\\n"
" --literal --value 123 --encrypted-pop --encrypted-pop | " GPG_NAME" -d" }
};
static int
encrypted (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
int processed;
struct encinfo ei;
PKT_encrypted e;
cipher_filter_context_t *cfx;
memset (&ei, 0, sizeof (ei));
processed = process_options (option,
major_options,
encrypted_options, &ei,
global_options, NULL,
argc, argv);
if (! session_key.algo)
log_fatal ("%s: no session key configured.\n", option);
memset (&e, 0, sizeof (e));
/* We only need to set E->LEN, E->EXTRALEN (if E->LEN is not
0), and E->NEW_CTB. */
e.len = 0;
e.new_ctb = 1;
/* Register the cipher filter. */
cfx = xmalloc_clear (sizeof (*cfx));
/* Copy the session key. */
cfx->dek = xmalloc (sizeof (*cfx->dek));
*cfx->dek = session_key;
if (do_debug)
{
char *buf;
buf = xmalloc (2 * session_key.keylen + 1);
debug ("session key: algo: %d; keylen: %d; key: %s\n",
session_key.algo, session_key.keylen,
bin2hex (session_key.key, session_key.keylen, buf));
xfree (buf);
}
if (strcmp (option, "--encrypted-mdc") == 0)
cfx->dek->use_mdc = 1;
else if (strcmp (option, "--encrypted") == 0)
cfx->dek->use_mdc = 0;
else
log_fatal ("%s: option not handled by this function!\n", option);
cfx->datalen = 0;
filter_push (out, cipher_filter, cfx, PKT_ENCRYPTED, cfx->datalen == 0);
debug ("Wrote encrypted packet:\n");
/* Clear the current session key. */
memset (&session_key, 0, sizeof (session_key));
return processed;
}
static int
encrypted_pop (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
(void) argc;
(void) argv;
if (strcmp (option, "--encrypted-pop") == 0)
filter_pop (out, PKT_ENCRYPTED);
else if (strcmp (option, "--encrypted-mdc-pop") == 0)
filter_pop (out, PKT_ENCRYPTED_MDC);
else
log_fatal ("%s: option not handled by this function!\n", option);
debug ("Popped encryption container.\n");
return 0;
}
struct data
{
int file;
union
{
char *data;
char *filename;
};
struct data *next;
};
/* This must be the first member of the struct to be able to use
add_value! */
struct datahead
{
struct data *head;
struct data **last_next;
};
static int
add_value (const char *option, int argc, char *argv[], void *cookie)
{
struct datahead *dh = cookie;
struct data *d = xmalloc_clear (sizeof (struct data));
d->file = strcmp ("--file", option) == 0;
if (! d->file)
log_assert (strcmp ("--value", option) == 0);
if (argc == 0)
{
if (d->file)
log_fatal ("Usage: %s FILENAME\n", option);
else
log_fatal ("Usage: %s STRING\n", option);
}
if (! dh->last_next)
/* First time through. Initialize DH->LAST_NEXT. */
{
log_assert (! dh->head);
dh->last_next = &dh->head;
}
if (d->file)
d->filename = argv[0];
else
d->data = argv[0];
/* Append it. */
*dh->last_next = d;
dh->last_next = &d->next;
return 1;
}
struct litinfo
{
/* This must be the first element for add_value to work! */
struct datahead data;
int timestamp_set;
u32 timestamp;
char mode;
int partial_body_length_encoding;
char *name;
};
static int
literal_timestamp (const char *option, int argc, char *argv[], void *cookie)
{
struct litinfo *li = cookie;
char *tail = NULL;
if (argc == 0)
log_fatal ("Usage: %s TIMESTAMP\n", option);
errno = 0;
li->timestamp = parse_timestamp (argv[0], &tail);
if (errno || (tail && *tail))
log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
li->timestamp_set = 1;
return 1;
}
static int
literal_mode (const char *option, int argc, char *argv[], void *cookie)
{
struct litinfo *li = cookie;
if (argc == 0
|| ! (strcmp (argv[0], "b") == 0
|| strcmp (argv[0], "t") == 0
|| strcmp (argv[0], "u") == 0))
log_fatal ("Usage: %s [btu]\n", option);
li->mode = argv[0][0];
return 1;
}
static int
literal_partial_body_length (const char *option, int argc, char *argv[],
void *cookie)
{
struct litinfo *li = cookie;
char *tail;
int v;
int range[2] = {0, 1};
if (argc <= 1)
log_fatal ("Usage: %s [0|1]\n", option);
errno = 0;
v = strtol (argv[0], &tail, 0);
if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1]))
log_fatal ("Invalid value passed to %s (%s). Expected %d-%d\n",
option, argv[0], range[0], range[1]);
li->partial_body_length_encoding = v;
return 1;
}
static int
literal_name (const char *option, int argc, char *argv[], void *cookie)
{
struct litinfo *li = cookie;
if (argc <= 1)
log_fatal ("Usage: %s NAME\n", option);
if (strlen (argv[0]) > 255)
log_fatal ("%s: name is too long (%zd > 255 characters).\n",
option, strlen (argv[0]));
li->name = argv[0];
return 1;
}
static struct option literal_options[] = {
{ "--value", add_value,
"A string to store in the literal packet." },
{ "--file", add_value,
"A file to copy into the literal packet." },
{ "--timestamp", literal_timestamp,
"The literal packet's time stamp. This defaults to the current time." },
{ "--mode", literal_mode,
"The content's mode (normally 'b' (default), 't' or 'u')." },
{ "--partial-body-length", literal_partial_body_length,
"Force partial body length encoding." },
{ "--name", literal_name,
"The literal's name." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --literal --value foobar | " GPG_NAME " -d"}
};
static int
literal (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
gpg_error_t err;
int processed;
struct litinfo li;
PKT_plaintext *pt;
PACKET pkt;
struct data *data;
memset (&li, 0, sizeof (li));
processed = process_options (option,
major_options,
literal_options, &li,
global_options, NULL,
argc, argv);
if (! li.data.head)
log_fatal ("%s: no data provided (use --value or --file)", option);
pt = xmalloc_clear (sizeof (*pt) + (li.name ? strlen (li.name) : 0));
pt->new_ctb = 1;
if (li.timestamp_set)
pt->timestamp = li.timestamp;
else
/* Default to the current time. */
pt->timestamp = make_timestamp ();
pt->mode = li.mode;
if (! pt->mode)
/* Default to binary. */
pt->mode = 'b';
if (li.name)
{
strcpy (pt->name, li.name);
pt->namelen = strlen (pt->name);
}
pkt.pkttype = PKT_PLAINTEXT;
pkt.pkt.plaintext = pt;
if (! li.partial_body_length_encoding)
/* Compute the amount of data. */
{
pt->len = 0;
for (data = li.data.head; data; data = data->next)
{
if (data->file)
{
iobuf_t in;
int overflow;
off_t off;
in = iobuf_open (data->filename);
if (! in)
/* An error opening the file. We do error handling
below so just break here. */
{
pt->len = 0;
break;
}
off = iobuf_get_filelength (in, &overflow);
iobuf_close (in);
if (overflow || off == 0)
/* Length is unknown or there was an error
(unfortunately, iobuf_get_filelength doesn't
distinguish between 0 length files and an error!).
Fall back to partial body mode. */
{
pt->len = 0;
break;
}
pt->len += off;
}
else
pt->len += strlen (data->data);
}
}
err = build_packet (out, &pkt);
if (err)
log_fatal ("Serializing literal packet: %s\n", gpg_strerror (err));
/* Write out the data. */
for (data = li.data.head; data; data = data->next)
{
if (data->file)
{
iobuf_t in;
errno = 0;
in = iobuf_open (data->filename);
if (! in)
log_fatal ("Opening '%s': %s\n",
data->filename,
errno ? strerror (errno): "unknown error");
iobuf_copy (out, in);
if (iobuf_error (in))
log_fatal ("Reading from %s: %s\n",
data->filename,
gpg_strerror (iobuf_error (in)));
if (iobuf_error (out))
log_fatal ("Writing literal data from %s: %s\n",
data->filename,
gpg_strerror (iobuf_error (out)));
iobuf_close (in);
}
else
{
err = iobuf_write (out, data->data, strlen (data->data));
if (err)
log_fatal ("Writing literal data: %s\n", gpg_strerror (err));
}
}
if (! pt->len)
{
/* Disable partial body length mode. */
log_assert (pt->new_ctb == 1);
iobuf_set_partial_body_length_mode (out, 0);
}
debug ("Wrote literal packet:\n");
dump_component (&pkt);
while (li.data.head)
{
data = li.data.head->next;
xfree (li.data.head);
li.data.head = data;
}
xfree (pt);
return processed;
}
static int
copy_file (const char *option, int argc, char *argv[], void *cookie)
{
char **filep = cookie;
if (argc == 0)
log_fatal ("Usage: %s FILENAME\n", option);
*filep = argv[0];
return 1;
}
static struct option copy_options[] = {
{ "", copy_file, "Copy the specified file to stdout." },
{ NULL, NULL,
"Example:\n\n"
" $ gpgcompose --copy /etc/hostname\n\n"
"This is particularly useful when combined with gpgsplit." }
};
static int
copy (const char *option, int argc, char *argv[], void *cookie)
{
iobuf_t out = cookie;
char *file = NULL;
iobuf_t in;
int processed;
processed = process_options (option,
major_options,
copy_options, &file,
global_options, NULL,
argc, argv);
if (! file)
log_fatal ("Usage: %s FILE\n", option);
errno = 0;
in = iobuf_open (file);
if (! in)
log_fatal ("Error opening %s: %s.\n",
file, errno ? strerror (errno): "unknown error");
iobuf_copy (out, in);
if (iobuf_error (out))
log_fatal ("Copying data to destination: %s\n",
gpg_strerror (iobuf_error (out)));
if (iobuf_error (in))
log_fatal ("Reading data from %s: %s\n",
argv[0], gpg_strerror (iobuf_error (in)));
iobuf_close (in);
return processed;
}
int
main (int argc, char *argv[])
{
const char *filename = "-";
iobuf_t out;
int preprocessed = 1;
int processed;
ctrl_t ctrl;
opt.ignore_time_conflict = 1;
/* Allow notations in the IETF space, for instance. */
opt.expert = 1;
global_ctrl = ctrl = xcalloc (1, sizeof *ctrl);
keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
KEYDB_RESOURCE_FLAG_DEFAULT);
if (argc == 1)
/* Nothing to do. */
return 0;
if (strcmp (argv[1], "--output") == 0
|| strcmp (argv[1], "-o") == 0)
{
filename = argv[2];
log_info ("Writing to %s\n", filename);
preprocessed += 2;
}
out = iobuf_create (filename, 0);
if (! out)
log_fatal ("Failed to open stdout for writing\n");
processed = process_options (NULL, NULL,
major_options, out,
global_options, NULL,
argc - preprocessed, &argv[preprocessed]);
if (processed != argc - preprocessed)
log_fatal ("Didn't process %d options.\n", argc - preprocessed - processed);
iobuf_close (out);
return 0;
}
/* Stubs duplicated from gpg.c. */
int g10_errors_seen = 0;
/* Note: This function is used by signal handlers!. */
static void
emergency_cleanup (void)
{
gcry_control (GCRYCTL_TERM_SECMEM );
}
void
g10_exit( int rc )
{
gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
emergency_cleanup ();
rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
exit (rc);
}
void
keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr,
strlist_t commands, int quiet, int seckey_check)
{
(void) ctrl;
(void) username;
(void) locusr;
(void) commands;
(void) quiet;
(void) seckey_check;
}
void
show_basic_key_info (ctrl_t ctrl, KBNODE keyblock)
{
(void)ctrl;
(void) keyblock;
}
diff --git a/g10/tofu.c b/g10/tofu.c
index 1437a50b9..1c1c3967f 100644
--- a/g10/tofu.c
+++ b/g10/tofu.c
@@ -1,4001 +1,4011 @@
/* tofu.c - TOFU trust model.
* Copyright (C) 2015, 2016 g10 Code GmbH
*
* 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 .
*/
/* TODO:
- Format the fingerprints nicely when printing (similar to gpg
--list-keys)
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "../common/types.h"
#include "../common/logging.h"
#include "../common/stringhelp.h"
#include "options.h"
#include "../common/mbox-util.h"
#include "../common/i18n.h"
#include "../common/ttyio.h"
#include "trustdb.h"
#include "../common/mkdir_p.h"
#include "gpgsql.h"
#include "../common/status.h"
#include "sqrtu32.h"
#include "tofu.h"
#define CONTROL_L ('L' - 'A' + 1)
/* Number of days with signed / ecnrypted messages required to
* indicate that enough history is available for basic trust. */
#define BASIC_TRUST_THRESHOLD 4
/* Number of days with signed / encrypted messages required to
* indicate that a lot of history is available. */
#define FULL_TRUST_THRESHOLD 21
/* A struct with data pertaining to the tofu DB. There is one such
struct per session and it is cached in session's ctrl structure.
To initialize this or get the current singleton, call opendbs().
There is no need to explicitly release it; cleanup is done when the
CTRL object is released. */
struct tofu_dbs_s
{
sqlite3 *db;
char *want_lock_file;
time_t want_lock_file_ctime;
struct
{
sqlite3_stmt *savepoint_batch;
sqlite3_stmt *savepoint_batch_commit;
sqlite3_stmt *record_binding_get_old_policy;
sqlite3_stmt *record_binding_update;
sqlite3_stmt *get_policy_select_policy_and_conflict;
sqlite3_stmt *get_trust_bindings_with_this_email;
sqlite3_stmt *get_trust_gather_other_user_ids;
sqlite3_stmt *get_trust_gather_signature_stats;
sqlite3_stmt *get_trust_gather_encryption_stats;
sqlite3_stmt *register_already_seen;
sqlite3_stmt *register_signature;
sqlite3_stmt *register_encryption;
} s;
int in_batch_transaction;
int in_transaction;
time_t batch_update_started;
};
#define STRINGIFY(s) STRINGIFY2(s)
#define STRINGIFY2(s) #s
/* The grouping parameters when collecting signature statistics. */
/* If a message is signed a couple of hours in the future, just assume
some clock skew. */
#define TIME_AGO_FUTURE_IGNORE (2 * 60 * 60)
/* Days. */
#define TIME_AGO_UNIT_SMALL (24 * 60 * 60)
#define TIME_AGO_SMALL_THRESHOLD (7 * TIME_AGO_UNIT_SMALL)
/* Months. */
#define TIME_AGO_UNIT_MEDIUM (30 * 24 * 60 * 60)
#define TIME_AGO_MEDIUM_THRESHOLD (2 * TIME_AGO_UNIT_MEDIUM)
/* Years. */
#define TIME_AGO_UNIT_LARGE (365 * 24 * 60 * 60)
#define TIME_AGO_LARGE_THRESHOLD (2 * TIME_AGO_UNIT_LARGE)
/* Local prototypes. */
static gpg_error_t end_transaction (ctrl_t ctrl, int only_batch);
static char *email_from_user_id (const char *user_id);
static int show_statistics (tofu_dbs_t dbs,
const char *fingerprint, const char *email,
enum tofu_policy policy,
estream_t outfp, int only_status_fd, time_t now);
const char *
tofu_policy_str (enum tofu_policy policy)
{
switch (policy)
{
case TOFU_POLICY_NONE: return "none";
case TOFU_POLICY_AUTO: return "auto";
case TOFU_POLICY_GOOD: return "good";
case TOFU_POLICY_UNKNOWN: return "unknown";
case TOFU_POLICY_BAD: return "bad";
case TOFU_POLICY_ASK: return "ask";
default: return "???";
}
}
/* Convert a binding policy (e.g., TOFU_POLICY_BAD) to a trust level
(e.g., TRUST_BAD) in light of the current configuration. */
int
tofu_policy_to_trust_level (enum tofu_policy policy)
{
if (policy == TOFU_POLICY_AUTO)
/* If POLICY is AUTO, fallback to OPT.TOFU_DEFAULT_POLICY. */
policy = opt.tofu_default_policy;
switch (policy)
{
case TOFU_POLICY_AUTO:
/* If POLICY and OPT.TOFU_DEFAULT_POLICY are both AUTO, default
to marginal trust. */
return TRUST_MARGINAL;
case TOFU_POLICY_GOOD:
return TRUST_FULLY;
case TOFU_POLICY_UNKNOWN:
return TRUST_UNKNOWN;
case TOFU_POLICY_BAD:
return TRUST_NEVER;
case TOFU_POLICY_ASK:
return TRUST_UNKNOWN;
default:
log_bug ("Bad value for trust policy: %d\n",
opt.tofu_default_policy);
return 0;
}
}
/* Start a transaction on DB. If ONLY_BATCH is set, then this will
start a batch transaction if we haven't started a batch transaction
and one has been requested. */
static gpg_error_t
begin_transaction (ctrl_t ctrl, int only_batch)
{
tofu_dbs_t dbs = ctrl->tofu.dbs;
int rc;
char *err = NULL;
log_assert (dbs);
/* If we've been in batch update mode for a while (on average, more
* than 500 ms), to prevent starving other gpg processes, we drop
* and retake the batch lock.
*
* Note: gnupg_get_time has a one second resolution, if we wanted a
* higher resolution, we could use npth_clock_gettime. */
if (/* No real transactions. */
dbs->in_transaction == 0
/* There is an open batch transaction. */
&& dbs->in_batch_transaction
/* And some time has gone by since it was started. */
&& dbs->batch_update_started != gnupg_get_time ())
{
struct stat statbuf;
/* If we are in a batch update, then batch updates better have
been enabled. */
log_assert (ctrl->tofu.batch_updated_wanted);
/* Check if another process wants to run. (We just ignore any
* stat failure. A waiter might have to wait a bit longer, but
* otherwise there should be no impact.) */
if (stat (dbs->want_lock_file, &statbuf) == 0
&& statbuf.st_ctime != dbs->want_lock_file_ctime)
{
end_transaction (ctrl, 2);
/* Yield to allow another process a chance to run. Note:
* testing suggests that anything less than a 100ms tends to
* not result in the other process getting the lock. */
gnupg_usleep (100000);
}
else
dbs->batch_update_started = gnupg_get_time ();
}
if (/* We don't have an open batch transaction. */
!dbs->in_batch_transaction
&& (/* Batch mode is enabled or we are starting a new transaction. */
ctrl->tofu.batch_updated_wanted || dbs->in_transaction == 0))
{
struct stat statbuf;
/* We are in batch mode, but we don't have an open batch
* transaction. Since the batch save point must be the outer
* save point, it must be taken before the inner save point. */
log_assert (dbs->in_transaction == 0);
rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch,
NULL, NULL, &err,
"begin immediate transaction;", GPGSQL_ARG_END);
if (rc)
{
log_error (_("error beginning transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return gpg_error (GPG_ERR_GENERAL);
}
dbs->in_batch_transaction = 1;
dbs->batch_update_started = gnupg_get_time ();
if (stat (dbs->want_lock_file, &statbuf) == 0)
dbs->want_lock_file_ctime = statbuf.st_ctime;
}
if (only_batch)
return 0;
log_assert (dbs->in_transaction >= 0);
dbs->in_transaction ++;
rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
"savepoint inner%d;",
dbs->in_transaction);
if (rc)
{
log_error (_("error beginning transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return gpg_error (GPG_ERR_GENERAL);
}
return 0;
}
/* Commit a transaction. If ONLY_BATCH is 1, then this only ends the
* batch transaction if we have left batch mode. If ONLY_BATCH is 2,
* this commits any open batch transaction even if we are still in
* batch mode. */
static gpg_error_t
end_transaction (ctrl_t ctrl, int only_batch)
{
tofu_dbs_t dbs = ctrl->tofu.dbs;
int rc;
char *err = NULL;
if (only_batch || (! only_batch && dbs->in_transaction == 1))
{
if (!dbs)
return 0; /* Shortcut to allow for easier cleanup code. */
/* If we are releasing the batch transaction, then we better not
be in a normal transaction. */
if (only_batch)
log_assert (dbs->in_transaction == 0);
if (/* Batch mode disabled? */
(!ctrl->tofu.batch_updated_wanted || only_batch == 2)
/* But, we still have an open batch transaction? */
&& dbs->in_batch_transaction)
{
/* The batch transaction is still in open, but we've left
* batch mode. */
dbs->in_batch_transaction = 0;
dbs->in_transaction = 0;
rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch_commit,
NULL, NULL, &err,
"commit transaction;", GPGSQL_ARG_END);
if (rc)
{
log_error (_("error committing transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return gpg_error (GPG_ERR_GENERAL);
}
return 0;
}
if (only_batch)
return 0;
}
log_assert (dbs);
log_assert (dbs->in_transaction > 0);
rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
"release inner%d;", dbs->in_transaction);
dbs->in_transaction --;
if (rc)
{
log_error (_("error committing transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return gpg_error (GPG_ERR_GENERAL);
}
return 0;
}
static gpg_error_t
rollback_transaction (ctrl_t ctrl)
{
tofu_dbs_t dbs = ctrl->tofu.dbs;
int rc;
char *err = NULL;
log_assert (dbs);
log_assert (dbs->in_transaction > 0);
/* Be careful to not undo any progress made by closed transactions in
batch mode. */
rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
"rollback to inner%d;",
dbs->in_transaction);
dbs->in_transaction --;
if (rc)
{
log_error (_("error rolling back transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return gpg_error (GPG_ERR_GENERAL);
}
return 0;
}
void
tofu_begin_batch_update (ctrl_t ctrl)
{
ctrl->tofu.batch_updated_wanted ++;
}
void
tofu_end_batch_update (ctrl_t ctrl)
{
log_assert (ctrl->tofu.batch_updated_wanted > 0);
ctrl->tofu.batch_updated_wanted --;
end_transaction (ctrl, 1);
}
/* Suspend any extant batch transaction (it is safe to call this even
no batch transaction has been started). Note: you cannot suspend a
batch transaction if you are in a normal transaction. The batch
transaction can be resumed explicitly by calling
tofu_resume_batch_transaction or implicitly by starting a normal
transaction. */
static void
tofu_suspend_batch_transaction (ctrl_t ctrl)
{
end_transaction (ctrl, 2);
}
/* Resume a batch transaction if there is no extant batch transaction
and one has been requested using tofu_begin_batch_transaction. */
static void
tofu_resume_batch_transaction (ctrl_t ctrl)
{
begin_transaction (ctrl, 1);
}
/* Wrapper around strtol which prints a warning in case of a
* conversion error. On success the converted value is stored at
* R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
* and an error code is returned. */
static gpg_error_t
string_to_long (long *r_value, const char *string, long fallback, int line)
{
gpg_error_t err;
char *tail = NULL;
gpg_err_set_errno (0);
*r_value = strtol (string, &tail, 0);
if (errno || !(!strcmp (tail, ".0") || !*tail))
{
err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
log_debug ("%s:%d: strtol failed for TOFU DB data; returned string"
" (string='%.10s%s'; tail='%.10s%s'): %s\n",
__FILE__, line,
string, string && strlen(string) > 10 ? "..." : "",
tail, tail && strlen(tail) > 10 ? "..." : "",
gpg_strerror (err));
*r_value = fallback;
}
else
err = 0;
return err;
}
/* Wrapper around strtoul which prints a warning in case of a
* conversion error. On success the converted value is stored at
* R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
* and an error code is returned. */
static gpg_error_t
string_to_ulong (unsigned long *r_value, const char *string,
unsigned long fallback, int line)
{
gpg_error_t err;
char *tail = NULL;
gpg_err_set_errno (0);
*r_value = strtoul (string, &tail, 0);
if (errno || !(!strcmp (tail, ".0") || !*tail))
{
err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
log_debug ("%s:%d: strtoul failed for TOFU DB data; returned string"
" (string='%.10s%s'; tail='%.10s%s'): %s\n",
__FILE__, line,
string, string && strlen(string) > 10 ? "..." : "",
tail, tail && strlen(tail) > 10 ? "..." : "",
gpg_strerror (err));
*r_value = fallback;
}
else
err = 0;
return err;
}
/* Collect results of a select count (*) ...; style query. Aborts if
the argument is not a valid integer (or real of the form X.0). */
static int
get_single_unsigned_long_cb (void *cookie, int argc, char **argv,
char **azColName)
{
unsigned long int *count = cookie;
(void) azColName;
log_assert (argc == 1);
if (string_to_ulong (count, argv[0], 0, __LINE__))
return 1; /* Abort. */
return 0;
}
static int
get_single_unsigned_long_cb2 (void *cookie, int argc, char **argv,
char **azColName, sqlite3_stmt *stmt)
{
(void) stmt;
return get_single_unsigned_long_cb (cookie, argc, argv, azColName);
}
/* We expect a single integer column whose name is "version". COOKIE
must point to an int. This function always aborts. On error or a
if the version is bad, sets *VERSION to -1. */
static int
version_check_cb (void *cookie, int argc, char **argv, char **azColName)
{
int *version = cookie;
if (argc != 1 || strcmp (azColName[0], "version") != 0)
{
*version = -1;
return 1;
}
if (strcmp (argv[0], "1") == 0)
*version = 1;
else
{
log_error (_("unsupported TOFU database version: %s\n"), argv[0]);
*version = -1;
}
/* Don't run again. */
return 1;
}
static int
check_utks (sqlite3 *db)
{
int rc;
char *err = NULL;
struct key_item *utks;
struct key_item *ki;
int utk_count;
char *utks_string = NULL;
char keyid_str[16+1];
long utks_unchanged = 0;
/* An early version of the v1 format did not include the list of
* known ultimately trusted keys.
*
* This list is used to detect when the set of ultimately trusted
* keys changes. We need to detect this to invalidate the effective
* policy, which can change if an ultimately trusted key is added or
* removed. */
rc = sqlite3_exec (db,
"create table if not exists ultimately_trusted_keys"
" (keyid);\n",
NULL, NULL, &err);
if (rc)
{
log_error (_("error creating 'ultimately_trusted_keys' TOFU table: %s\n"),
err);
sqlite3_free (err);
goto out;
}
utks = tdb_utks ();
for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
;
if (utk_count)
{
/* Build a list of keyids of the form "XXX","YYY","ZZZ". */
int len = (1 + 16 + 1 + 1) * utk_count;
int o = 0;
utks_string = xmalloc (len);
*utks_string = 0;
for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
{
utks_string[o ++] = '\'';
format_keyid (ki->kid, KF_LONG,
keyid_str, sizeof (keyid_str));
memcpy (&utks_string[o], keyid_str, 16);
o += 16;
utks_string[o ++] = '\'';
utks_string[o ++] = ',';
}
utks_string[o - 1] = 0;
log_assert (o == len);
}
rc = gpgsql_exec_printf
(db, get_single_unsigned_long_cb, &utks_unchanged, &err,
"select"
/* Removed UTKs? (Known UTKs in current UTKs.) */
" ((select count(*) from ultimately_trusted_keys"
" where (keyid in (%s))) == %d)"
" and"
/* New UTKs? */
" ((select count(*) from ultimately_trusted_keys"
" where keyid not in (%s)) == 0);",
utks_string ? utks_string : "",
utk_count,
utks_string ? utks_string : "");
xfree (utks_string);
if (rc)
{
log_error (_("TOFU DB error"));
print_further_info ("checking if ultimately trusted keys changed: %s",
err);
sqlite3_free (err);
goto out;
}
if (utks_unchanged)
goto out;
if (DBG_TRUST)
log_debug ("TOFU: ultimately trusted keys changed.\n");
/* Given that the set of ultimately trusted keys
* changed, clear any cached policies. */
rc = gpgsql_exec_printf
(db, NULL, NULL, &err,
"update bindings set effective_policy = %d;",
TOFU_POLICY_NONE);
if (rc)
{
log_error (_("TOFU DB error"));
print_further_info ("clearing cached policies: %s", err);
sqlite3_free (err);
goto out;
}
/* Now, update the UTK table. */
rc = sqlite3_exec (db,
"drop table ultimately_trusted_keys;",
NULL, NULL, &err);
if (rc)
{
log_error (_("TOFU DB error"));
print_further_info ("dropping ultimately_trusted_keys: %s", err);
sqlite3_free (err);
goto out;
}
rc = sqlite3_exec (db,
"create table if not exists"
" ultimately_trusted_keys (keyid);\n",
NULL, NULL, &err);
if (rc)
{
log_error (_("TOFU DB error"));
print_further_info ("creating ultimately_trusted_keys: %s", err);
sqlite3_free (err);
goto out;
}
for (ki = utks; ki; ki = ki->next)
{
format_keyid (ki->kid, KF_LONG,
keyid_str, sizeof (keyid_str));
rc = gpgsql_exec_printf
(db, NULL, NULL, &err,
"insert into ultimately_trusted_keys values ('%s');",
keyid_str);
if (rc)
{
log_error (_("TOFU DB error"));
print_further_info ("updating ultimately_trusted_keys: %s",
err);
sqlite3_free (err);
goto out;
}
}
out:
return rc;
}
/* If the DB is new, initialize it. Otherwise, check the DB's
version.
Return 0 if the database is okay and 1 otherwise. */
static int
initdb (sqlite3 *db)
{
char *err = NULL;
int rc;
unsigned long int count;
int version = -1;
rc = sqlite3_exec (db, "begin transaction;", NULL, NULL, &err);
if (rc)
{
log_error (_("error beginning transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return 1;
}
/* If the DB has no tables, then assume this is a new DB that needs
to be initialized. */
rc = sqlite3_exec (db,
"select count(*) from sqlite_master where type='table';",
get_single_unsigned_long_cb, &count, &err);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("query available tables");
sqlite3_free (err);
goto out;
}
else if (count != 0)
/* Assume that the DB is already initialized. Make sure the
version is okay. */
{
rc = sqlite3_exec (db, "select version from version;", version_check_cb,
&version, &err);
if (rc == SQLITE_ABORT && version == 1)
/* Happy, happy, joy, joy. */
{
sqlite3_free (err);
rc = 0;
goto out;
}
else if (rc == SQLITE_ABORT && version == -1)
/* Unsupported version. */
{
/* An error message was already displayed. */
sqlite3_free (err);
goto out;
}
else if (rc)
/* Some error. */
{
log_error (_("error determining TOFU database's version: %s\n"), err);
sqlite3_free (err);
goto out;
}
else
{
/* Unexpected success. This can only happen if there are no
rows. (select returned 0, but expected ABORT.) */
log_error (_("error determining TOFU database's version: %s\n"),
gpg_strerror (GPG_ERR_NO_DATA));
rc = 1;
goto out;
}
}
/* Create the version table. */
rc = sqlite3_exec (db,
"create table version (version INTEGER);",
NULL, NULL, &err);
if (rc)
{
log_error (_("error initializing TOFU database: %s\n"), err);
print_further_info ("create version");
sqlite3_free (err);
goto out;
}
/* Initialize the version table, which contains a single integer
value. */
rc = sqlite3_exec (db,
"insert into version values (1);",
NULL, NULL, &err);
if (rc)
{
log_error (_("error initializing TOFU database: %s\n"), err);
print_further_info ("insert version");
sqlite3_free (err);
goto out;
}
/* The list of bindings and auxiliary data.
*
* OID is a unique ID identifying this binding (and used by the
* signatures table, see below). Note: OIDs will never be
* reused.
*
* FINGERPRINT: The key's fingerprint.
*
* EMAIL: The normalized email address.
*
* USER_ID: The unmodified user id from which EMAIL was extracted.
*
* TIME: The time this binding was first observed.
*
* POLICY: The trust policy (TOFU_POLICY_BAD, etc. as an integer).
*
* CONFLICT is either NULL or a fingerprint. Assume that we have
* a binding <0xdeadbeef, foo@example.com> and then we observe
* <0xbaddecaf, foo@example.com>. There two bindings conflict
* (they have the same email address). When we observe the
* latter binding, we warn the user about the conflict and ask
* for a policy decision about the new binding. We also change
* the old binding's policy to ask if it was auto. So that we
* know why this occurred, we also set conflict to 0xbaddecaf.
*/
rc = gpgsql_exec_printf
(db, NULL, NULL, &err,
"create table bindings\n"
" (oid INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" fingerprint TEXT, email TEXT, user_id TEXT, time INTEGER,\n"
" policy INTEGER CHECK (policy in (%d, %d, %d, %d, %d)),\n"
" conflict STRING,\n"
" unique (fingerprint, email));\n"
"create index bindings_fingerprint_email\n"
" on bindings (fingerprint, email);\n"
"create index bindings_email on bindings (email);\n",
TOFU_POLICY_AUTO, TOFU_POLICY_GOOD, TOFU_POLICY_UNKNOWN,
TOFU_POLICY_BAD, TOFU_POLICY_ASK);
if (rc)
{
log_error (_("error initializing TOFU database: %s\n"), err);
print_further_info ("create bindings");
sqlite3_free (err);
goto out;
}
/* The signatures that we have observed.
*
* BINDING refers to a record in the bindings table, which
* describes the binding (i.e., this is a foreign key that
* references bindings.oid).
*
* SIG_DIGEST is the digest stored in the signature.
*
* SIG_TIME is the timestamp stored in the signature.
*
* ORIGIN is a free-form string that describes who fed this
* signature to GnuPG (e.g., email:claws).
*
* TIME is the time this signature was registered. */
rc = sqlite3_exec (db,
"create table signatures "
" (binding INTEGER NOT NULL, sig_digest TEXT,"
" origin TEXT, sig_time INTEGER, time INTEGER,"
" primary key (binding, sig_digest, origin));",
NULL, NULL, &err);
if (rc)
{
log_error (_("error initializing TOFU database: %s\n"), err);
print_further_info ("create signatures");
sqlite3_free (err);
goto out;
}
out:
if (! rc)
{
/* Early version of the v1 format did not include the encryption
table. Add it. */
rc = sqlite3_exec (db,
"create table if not exists encryptions"
" (binding INTEGER NOT NULL,"
" time INTEGER);"
"create index if not exists encryptions_binding"
" on encryptions (binding);\n",
NULL, NULL, &err);
if (rc)
{
log_error (_("error creating 'encryptions' TOFU table: %s\n"),
err);
sqlite3_free (err);
}
}
if (! rc)
{
/* The effective policy for a binding. If a key is ultimately
* trusted, then the effective policy of all of its bindings is
* good. Likewise if a key is signed by an ultimately trusted
* key, etc. If the effective policy is NONE, then we need to
* recompute the effective policy. Otherwise, the effective
* policy is considered to be up to date, i.e., effective_policy
* is a cache of the computed policy. */
rc = gpgsql_exec_printf
(db, NULL, NULL, &err,
"alter table bindings"
" add column effective_policy INTEGER"
" DEFAULT %d"
" CHECK (effective_policy in (%d, %d, %d, %d, %d, %d));",
TOFU_POLICY_NONE,
TOFU_POLICY_NONE, TOFU_POLICY_AUTO, TOFU_POLICY_GOOD,
TOFU_POLICY_UNKNOWN, TOFU_POLICY_BAD, TOFU_POLICY_ASK);
if (rc)
{
if (rc == SQLITE_ERROR)
/* Almost certainly "duplicate column name", which we can
* safely ignore. */
rc = 0;
else
log_error (_("adding column effective_policy to bindings DB: %s\n"),
err);
sqlite3_free (err);
}
}
if (! rc)
rc = check_utks (db);
if (rc)
{
rc = sqlite3_exec (db, "rollback;", NULL, NULL, &err);
if (rc)
{
log_error (_("error rolling back transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
}
return 1;
}
else
{
rc = sqlite3_exec (db, "end transaction;", NULL, NULL, &err);
if (rc)
{
log_error (_("error committing transaction on TOFU database: %s\n"),
err);
sqlite3_free (err);
return 1;
}
return 0;
}
}
static int
busy_handler (void *cookie, int call_count)
{
ctrl_t ctrl = cookie;
tofu_dbs_t dbs = ctrl->tofu.dbs;
(void) call_count;
/* Update the want-lock-file time stamp (specifically, the ctime) so
* that the current owner knows that we (well, someone) want the
* lock. */
if (dbs)
{
/* Note: we don't fail if we can't create the lock file: this
* process will have to wait a bit longer, but otherwise nothing
* horrible should happen. */
estream_t fp;
fp = es_fopen (dbs->want_lock_file, "w");
if (! fp)
log_debug ("TOFU: Error opening '%s': %s\n",
dbs->want_lock_file, strerror (errno));
else
es_fclose (fp);
}
/* Call again. */
return 1;
}
/* Create a new DB handle. Returns NULL on error. */
/* FIXME: Change to return an error code for better reporting by the
caller. */
static tofu_dbs_t
opendbs (ctrl_t ctrl)
{
char *filename;
sqlite3 *db;
int rc;
if (!ctrl->tofu.dbs)
{
filename = make_filename (gnupg_homedir (), "tofu.db", NULL);
rc = sqlite3_open (filename, &db);
if (rc)
{
log_error (_("error opening TOFU database '%s': %s\n"),
filename, sqlite3_errmsg (db));
/* Even if an error occurs, DB is guaranteed to be valid. */
sqlite3_close (db);
db = NULL;
}
/* If a DB is locked wait up to 5 seconds for the lock to be cleared
before failing. */
if (db)
{
sqlite3_busy_timeout (db, 5 * 1000);
sqlite3_busy_handler (db, busy_handler, ctrl);
}
if (db && initdb (db))
{
sqlite3_close (db);
db = NULL;
}
if (db)
{
ctrl->tofu.dbs = xmalloc_clear (sizeof *ctrl->tofu.dbs);
ctrl->tofu.dbs->db = db;
ctrl->tofu.dbs->want_lock_file = xasprintf ("%s-want-lock", filename);
}
xfree (filename);
}
else
log_assert (ctrl->tofu.dbs->db);
return ctrl->tofu.dbs;
}
/* Release all of the resources associated with the DB handle. */
void
tofu_closedbs (ctrl_t ctrl)
{
tofu_dbs_t dbs;
sqlite3_stmt **statements;
dbs = ctrl->tofu.dbs;
if (!dbs)
return; /* Not initialized. */
log_assert (dbs->in_transaction == 0);
end_transaction (ctrl, 2);
/* Arghh, that is a surprising use of the struct. */
for (statements = (void *) &dbs->s;
(void *) statements < (void *) &(&dbs->s)[1];
statements ++)
sqlite3_finalize (*statements);
sqlite3_close (dbs->db);
xfree (dbs->want_lock_file);
xfree (dbs);
ctrl->tofu.dbs = NULL;
}
/* Collect results of a select min (foo) ...; style query. Aborts if
the argument is not a valid integer (or real of the form X.0). */
static int
get_single_long_cb (void *cookie, int argc, char **argv, char **azColName)
{
long *count = cookie;
(void) azColName;
log_assert (argc == 1);
if (string_to_long (count, argv[0], 0, __LINE__))
return 1; /* Abort. */
return 0;
}
static int
get_single_long_cb2 (void *cookie, int argc, char **argv, char **azColName,
sqlite3_stmt *stmt)
{
(void) stmt;
return get_single_long_cb (cookie, argc, argv, azColName);
}
/* Record (or update) a trust policy about a (possibly new)
binding.
If SHOW_OLD is set, the binding's old policy is displayed. */
static gpg_error_t
record_binding (tofu_dbs_t dbs, const char *fingerprint, const char *email,
const char *user_id,
enum tofu_policy policy, enum tofu_policy effective_policy,
const char *conflict, int set_conflict,
int show_old, time_t now)
{
char *fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
gpg_error_t rc;
char *err = NULL;
if (! (policy == TOFU_POLICY_AUTO
|| policy == TOFU_POLICY_GOOD
|| policy == TOFU_POLICY_UNKNOWN
|| policy == TOFU_POLICY_BAD
|| policy == TOFU_POLICY_ASK))
log_bug ("%s: Bad value for policy (%d)!\n", __func__, policy);
if (DBG_TRUST || show_old)
{
/* Get the old policy. Since this is just for informational
* purposes, there is no need to start a transaction or to die
* if there is a failure. */
/* policy_old needs to be a long and not an enum tofu_policy,
because we pass it by reference to get_single_long_cb2, which
expects a long. */
long policy_old = TOFU_POLICY_NONE;
rc = gpgsql_stepx
(dbs->db, &dbs->s.record_binding_get_old_policy,
get_single_long_cb2, &policy_old, &err,
"select policy from bindings where fingerprint = ? and email = ?",
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_END);
if (rc)
{
log_debug ("TOFU: Error reading from binding database"
" (reading policy for ): %s\n",
fingerprint, email, err);
sqlite3_free (err);
}
if (policy_old != TOFU_POLICY_NONE)
(show_old ? log_info : log_debug)
("Changing TOFU trust policy for binding"
" from %s to %s.\n",
fingerprint, show_old ? user_id : email,
tofu_policy_str (policy_old),
tofu_policy_str (policy));
else
(show_old ? log_info : log_debug)
("Setting TOFU trust policy for new binding"
" to %s.\n",
fingerprint, show_old ? user_id : email,
tofu_policy_str (policy));
}
if (opt.dry_run)
{
log_info ("TOFU database update skipped due to --dry-run\n");
rc = 0;
goto leave;
}
rc = gpgsql_stepx
(dbs->db, &dbs->s.record_binding_update, NULL, NULL, &err,
"insert or replace into bindings\n"
" (oid, fingerprint, email, user_id, time,"
" policy, conflict, effective_policy)\n"
" values (\n"
/* If we don't explicitly reuse the OID, then SQLite will
* reallocate a new one. We just need to search for the OID
* based on the fingerprint and email since they are unique. */
" (select oid from bindings where fingerprint = ? and email = ?),\n"
" ?, ?, ?, ?, ?,"
/* If SET_CONFLICT is 0, then preserve conflict's current value. */
" case ?"
" when 0 then"
" (select conflict from bindings where fingerprint = ? and email = ?)"
" else ?"
" end,"
" ?);",
/* oid subquery. */
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
/* values 2 through 6. */
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, user_id,
GPGSQL_ARG_LONG_LONG, (long long) now,
GPGSQL_ARG_INT, (int) policy,
/* conflict subquery. */
GPGSQL_ARG_INT, set_conflict ? 1 : 0,
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, conflict ? conflict : "",
GPGSQL_ARG_INT, (int) effective_policy,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error updating TOFU database: %s\n"), err);
print_further_info (" insert bindings = %s",
fingerprint, email, tofu_policy_str (policy));
sqlite3_free (err);
goto leave;
}
leave:
xfree (fingerprint_pp);
return rc;
}
/* Collect the strings returned by a query in a simple string list.
Any NULL values are converted to the empty string.
If a result has 3 rows and each row contains two columns, then the
results are added to the list as follows (the value is parentheses
is the 1-based index in the final list):
row 1, col 2 (6)
row 1, col 1 (5)
row 2, col 2 (4)
row 2, col 1 (3)
row 3, col 2 (2)
row 3, col 1 (1)
This is because add_to_strlist pushes the results onto the front of
the list. The end result is that the rows are backwards, but the
columns are in the expected order. */
static int
strings_collect_cb (void *cookie, int argc, char **argv, char **azColName)
{
int i;
strlist_t *strlist = cookie;
(void) azColName;
for (i = argc - 1; i >= 0; i --)
add_to_strlist (strlist, argv[i] ? argv[i] : "");
return 0;
}
static int
strings_collect_cb2 (void *cookie, int argc, char **argv, char **azColName,
sqlite3_stmt *stmt)
{
(void) stmt;
return strings_collect_cb (cookie, argc, argv, azColName);
}
/* Auxiliary data structure to collect statistics about
signatures. */
struct signature_stats
{
struct signature_stats *next;
/* The user-assigned policy for this binding. */
enum tofu_policy policy;
/* How long ago the signature was created (rounded to a multiple of
TIME_AGO_UNIT_SMALL, etc.). */
long time_ago;
/* Number of signatures during this time. */
unsigned long count;
/* If the corresponding key/user id has been expired / revoked. */
int is_expired;
int is_revoked;
/* The key that generated this signature. */
char fingerprint[1];
};
static void
signature_stats_free (struct signature_stats *stats)
{
while (stats)
{
struct signature_stats *next = stats->next;
xfree (stats);
stats = next;
}
}
static void
signature_stats_prepend (struct signature_stats **statsp,
const char *fingerprint,
enum tofu_policy policy,
long time_ago,
unsigned long count)
{
struct signature_stats *stats =
xmalloc_clear (sizeof (*stats) + strlen (fingerprint));
stats->next = *statsp;
*statsp = stats;
strcpy (stats->fingerprint, fingerprint);
stats->policy = policy;
stats->time_ago = time_ago;
stats->count = count;
}
/* Process rows that contain the four columns:
. */
static int
signature_stats_collect_cb (void *cookie, int argc, char **argv,
char **azColName, sqlite3_stmt *stmt)
{
struct signature_stats **statsp = cookie;
int i = 0;
enum tofu_policy policy;
long time_ago;
unsigned long count;
long along;
(void) azColName;
(void) stmt;
i ++;
if (string_to_long (&along, argv[i], 0, __LINE__))
return 1; /* Abort */
policy = along;
i ++;
if (! argv[i])
time_ago = 0;
else
{
if (string_to_long (&time_ago, argv[i], 0, __LINE__))
return 1; /* Abort. */
}
i ++;
/* If time_ago is NULL, then we had no messages, but we still have a
single row, which count(*) turns into 1. */
if (! argv[i - 1])
count = 0;
else
{
if (string_to_ulong (&count, argv[i], 0, __LINE__))
return 1; /* Abort */
}
i ++;
log_assert (argc == i);
signature_stats_prepend (statsp, argv[0], policy, time_ago, count);
return 0;
}
/* Format the first part of a conflict message and return that as a
- * malloced string. */
+ * malloced string. Returns NULL on error. */
static char *
format_conflict_msg_part1 (int policy, strlist_t conflict_set,
const char *email)
{
estream_t fp;
char *fingerprint;
char *tmpstr, *text;
log_assert (conflict_set);
fingerprint = conflict_set->d;
fp = es_fopenmem (0, "rw,samethread");
if (!fp)
log_fatal ("error creating memory stream: %s\n",
gpg_strerror (gpg_error_from_syserror()));
if (policy == TOFU_POLICY_NONE)
{
es_fprintf (fp,
_("This is the first time the email address \"%s\" is "
"being used with key %s."),
email, fingerprint);
es_fputs (" ", fp);
}
else if (policy == TOFU_POLICY_ASK && conflict_set->next)
{
int conflicts = strlist_length (conflict_set);
es_fprintf
(fp, ngettext("The email address \"%s\" is associated with %d key!",
"The email address \"%s\" is associated with %d keys!",
conflicts),
email, conflicts);
if (opt.verbose)
es_fprintf (fp,
_(" Since this binding's policy was 'auto', it has been "
"changed to 'ask'."));
es_fputs (" ", fp);
}
es_fprintf (fp,
_("Please indicate whether this email address should"
" be associated with key %s or whether you think someone"
" is impersonating \"%s\"."),
fingerprint, email);
es_fputc ('\n', fp);
es_fputc (0, fp);
if (es_fclose_snatch (fp, (void **)&tmpstr, NULL))
log_fatal ("error snatching memory stream\n");
text = format_text (tmpstr, 72, 80);
es_free (tmpstr);
return text;
}
/* Return 1 if A signed B and B signed A. */
static int
cross_sigs (const char *email, kbnode_t a, kbnode_t b)
{
int i;
PKT_public_key *a_pk = a->pkt->pkt.public_key;
PKT_public_key *b_pk = b->pkt->pkt.public_key;
char a_keyid[33];
char b_keyid[33];
if (DBG_TRUST)
{
format_keyid (pk_main_keyid (a_pk),
KF_LONG, a_keyid, sizeof (a_keyid));
format_keyid (pk_main_keyid (b_pk),
KF_LONG, b_keyid, sizeof (b_keyid));
}
for (i = 0; i < 2; i ++)
{
/* See if SIGNER signed SIGNEE. */
kbnode_t signer = i == 0 ? a : b;
kbnode_t signee = i == 0 ? b : a;
PKT_public_key *signer_pk = signer->pkt->pkt.public_key;
u32 *signer_kid = pk_main_keyid (signer_pk);
kbnode_t n;
int saw_email = 0;
/* Iterate over SIGNEE's keyblock and see if there is a valid
signature from SIGNER. */
for (n = signee; n; n = n->next)
{
PKT_signature *sig;
if (n->pkt->pkttype == PKT_USER_ID)
{
if (saw_email)
/* We're done: we've processed all signatures on the
user id. */
break;
else
{
/* See if this is the matching user id. */
PKT_user_id *user_id = n->pkt->pkt.user_id;
char *email2 = email_from_user_id (user_id->name);
if (strcmp (email, email2) == 0)
saw_email = 1;
xfree (email2);
}
}
if (! saw_email)
continue;
if (n->pkt->pkttype != PKT_SIGNATURE)
continue;
sig = n->pkt->pkt.signature;
if (! (sig->sig_class == 0x10
|| sig->sig_class == 0x11
|| sig->sig_class == 0x12
|| sig->sig_class == 0x13))
/* Not a signature over a user id. */
continue;
/* SIG is on SIGNEE's keyblock. If SIG was generated by the
signer, then it's a match. */
if (keyid_cmp (sig->keyid, signer_kid) == 0)
/* Match! */
break;
}
if (! n)
/* We didn't find a signature from signer over signee. */
{
if (DBG_TRUST)
log_debug ("No cross sig between %s and %s\n",
a_keyid, b_keyid);
return 0;
}
}
/* A signed B and B signed A. */
if (DBG_TRUST)
log_debug ("Cross sig between %s and %s\n",
a_keyid, b_keyid);
return 1;
}
/* Return whether the key was signed by an ultimately trusted key. */
static int
signed_by_utk (const char *email, kbnode_t a)
{
kbnode_t n;
int saw_email = 0;
for (n = a; n; n = n->next)
{
PKT_signature *sig;
if (n->pkt->pkttype == PKT_USER_ID)
{
if (saw_email)
/* We're done: we've processed all signatures on the
user id. */
break;
else
{
/* See if this is the matching user id. */
PKT_user_id *user_id = n->pkt->pkt.user_id;
char *email2 = email_from_user_id (user_id->name);
if (strcmp (email, email2) == 0)
saw_email = 1;
xfree (email2);
}
}
if (! saw_email)
continue;
if (n->pkt->pkttype != PKT_SIGNATURE)
continue;
sig = n->pkt->pkt.signature;
if (! (sig->sig_class == 0x10
|| sig->sig_class == 0x11
|| sig->sig_class == 0x12
|| sig->sig_class == 0x13))
/* Not a signature over a user id. */
continue;
/* SIG is on SIGNEE's keyblock. If SIG was generated by the
signer, then it's a match. */
if (tdb_keyid_is_utk (sig->keyid))
{
/* Match! */
if (DBG_TRUST)
log_debug ("TOFU: %s is signed by an ultimately trusted key.\n",
pk_keyid_str (a->pkt->pkt.public_key));
return 1;
}
}
if (DBG_TRUST)
log_debug ("TOFU: %s is NOT signed by an ultimately trusted key.\n",
pk_keyid_str (a->pkt->pkt.public_key));
return 0;
}
enum
{
BINDING_NEW = 1 << 0,
BINDING_CONFLICT = 1 << 1,
BINDING_EXPIRED = 1 << 2,
BINDING_REVOKED = 1 << 3
};
/* Ask the user about the binding. There are three ways we could end
* up here:
*
* - This is a new binding and there is a conflict
* (policy == TOFU_POLICY_NONE && conflict_set_count > 1),
*
* - This is a new binding and opt.tofu_default_policy is set to
* ask. (policy == TOFU_POLICY_NONE && opt.tofu_default_policy ==
* TOFU_POLICY_ASK), or,
*
* - The policy is ask (the user deferred last time) (policy ==
* TOFU_POLICY_ASK).
*
* Note: this function must not be called while in a transaction!
*
* CONFLICT_SET includes all of the conflicting bindings
* with FINGERPRINT first. FLAGS is a bit-wise or of
* BINDING_NEW, etc.
*/
static void
ask_about_binding (ctrl_t ctrl,
enum tofu_policy *policy,
int *trust_level,
strlist_t conflict_set,
const char *fingerprint,
const char *email,
const char *user_id,
time_t now)
{
tofu_dbs_t dbs;
strlist_t iter;
int conflict_set_count = strlist_length (conflict_set);
char *sqerr = NULL;
int rc;
estream_t fp;
strlist_t other_user_ids = NULL;
struct signature_stats *stats = NULL;
struct signature_stats *stats_iter = NULL;
char *prompt = NULL;
const char *choices;
dbs = ctrl->tofu.dbs;
log_assert (dbs);
log_assert (dbs->in_transaction == 0);
fp = es_fopenmem (0, "rw,samethread");
if (!fp)
log_fatal ("error creating memory stream: %s\n",
gpg_strerror (gpg_error_from_syserror()));
{
char *text = format_conflict_msg_part1 (*policy, conflict_set, email);
+ if (!text) /* FIXME: Return the error all the way up. */
+ log_fatal ("format failed: %s\n",
+ gpg_strerror (gpg_error_from_syserror()));
+
es_fputs (text, fp);
es_fputc ('\n', fp);
xfree (text);
}
begin_transaction (ctrl, 0);
/* Find other user ids associated with this key and whether the
* bindings are marked as good or bad. */
rc = gpgsql_stepx
(dbs->db, &dbs->s.get_trust_gather_other_user_ids,
strings_collect_cb2, &other_user_ids, &sqerr,
"select user_id, policy from bindings where fingerprint = ?;",
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_END);
if (rc)
{
log_error (_("error gathering other user IDs: %s\n"), sqerr);
sqlite3_free (sqerr);
sqerr = NULL;
rc = gpg_error (GPG_ERR_GENERAL);
}
if (other_user_ids)
{
strlist_t strlist_iter;
es_fprintf (fp, _("This key's user IDs:\n"));
for (strlist_iter = other_user_ids;
strlist_iter;
strlist_iter = strlist_iter->next)
{
char *other_user_id = strlist_iter->d;
char *other_thing;
enum tofu_policy other_policy;
log_assert (strlist_iter->next);
strlist_iter = strlist_iter->next;
other_thing = strlist_iter->d;
other_policy = atoi (other_thing);
es_fprintf (fp, " %s (", other_user_id);
es_fprintf (fp, _("policy: %s"), tofu_policy_str (other_policy));
es_fprintf (fp, ")\n");
}
es_fprintf (fp, "\n");
free_strlist (other_user_ids);
}
/* Get the stats for all the keys in CONFLICT_SET. */
strlist_rev (&conflict_set);
for (iter = conflict_set; iter && ! rc; iter = iter->next)
{
#define STATS_SQL(table, time, sign) \
"select fingerprint, policy, time_ago, count(*)\n" \
" from\n" \
" (select bindings.*,\n" \
" "sign" case\n" \
" when delta ISNULL then 1\n" \
/* From the future (but if its just a couple of hours in the \
* future don't turn it into a warning)? Or should we use \
* small, medium or large units? (Note: whatever we do, we \
* keep the value in seconds. Then when we group, everything \
* that rounds to the same number of seconds is grouped.) */ \
" when delta < -("STRINGIFY (TIME_AGO_FUTURE_IGNORE)") then 2\n" \
" when delta < ("STRINGIFY (TIME_AGO_SMALL_THRESHOLD)")\n" \
" then 3\n" \
" when delta < ("STRINGIFY (TIME_AGO_MEDIUM_THRESHOLD)")\n" \
" then 4\n" \
" when delta < ("STRINGIFY (TIME_AGO_LARGE_THRESHOLD)")\n" \
" then 5\n" \
" else 6\n" \
" end time_ago,\n" \
" delta time_ago_raw\n" \
" from bindings\n" \
" left join\n" \
" (select *,\n" \
" cast(? - " time " as real) delta\n" \
" from " table ") ss\n" \
" on ss.binding = bindings.oid)\n" \
" where email = ? and fingerprint = ?\n" \
" group by time_ago\n" \
/* Make sure the current key is first. */ \
" order by time_ago desc;\n"
/* Use the time when we saw the signature, not when the
signature was created as that can be forged. */
rc = gpgsql_stepx
(dbs->db, &dbs->s.get_trust_gather_signature_stats,
signature_stats_collect_cb, &stats, &sqerr,
STATS_SQL ("signatures", "time", ""),
GPGSQL_ARG_LONG_LONG, (long long) now,
GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, iter->d,
GPGSQL_ARG_END);
if (rc)
{
rc = gpg_error (GPG_ERR_GENERAL);
break;
}
if (!stats || strcmp (iter->d, stats->fingerprint) != 0)
/* No stats for this binding. Add a dummy entry. */
signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, 1, 1);
rc = gpgsql_stepx
(dbs->db, &dbs->s.get_trust_gather_encryption_stats,
signature_stats_collect_cb, &stats, &sqerr,
STATS_SQL ("encryptions", "time", "-"),
GPGSQL_ARG_LONG_LONG, (long long) now,
GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, iter->d,
GPGSQL_ARG_END);
if (rc)
{
rc = gpg_error (GPG_ERR_GENERAL);
break;
}
#undef STATS_SQL
if (!stats || strcmp (iter->d, stats->fingerprint) != 0
|| stats->time_ago > 0)
/* No stats for this binding. Add a dummy entry. */
signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, -1, 1);
}
end_transaction (ctrl, 0);
strlist_rev (&conflict_set);
if (rc)
{
strlist_t strlist_iter;
log_error (_("error gathering signature stats: %s\n"), sqerr);
sqlite3_free (sqerr);
sqerr = NULL;
es_fprintf (fp, ngettext("The email address \"%s\" is"
" associated with %d key:\n",
"The email address \"%s\" is"
" associated with %d keys:\n",
conflict_set_count),
email, conflict_set_count);
for (strlist_iter = conflict_set;
strlist_iter;
strlist_iter = strlist_iter->next)
es_fprintf (fp, " %s\n", strlist_iter->d);
}
else
{
char *key = NULL;
strlist_t binding;
int seen_in_past = 0;
int encrypted = 1;
es_fprintf (fp, _("Statistics for keys"
" with the email address \"%s\":\n"),
email);
for (stats_iter = stats; stats_iter; stats_iter = stats_iter->next)
{
#if 0
log_debug ("%s: time_ago: %ld; count: %ld\n",
stats_iter->fingerprint,
stats_iter->time_ago,
stats_iter->count);
#endif
if (stats_iter->time_ago > 0 && encrypted)
{
/* We've change from the encrypted stats to the verified
* stats. Reset SEEN_IN_PAST. */
encrypted = 0;
seen_in_past = 0;
}
if (! key || strcmp (key, stats_iter->fingerprint))
{
int this_key;
char *key_pp;
key = stats_iter->fingerprint;
this_key = strcmp (key, fingerprint) == 0;
key_pp = format_hexfingerprint (key, NULL, 0);
es_fprintf (fp, " %s (", key_pp);
/* Find the associated binding. */
for (binding = conflict_set;
binding;
binding = binding->next)
if (strcmp (key, binding->d) == 0)
break;
log_assert (binding);
if ((binding->flags & BINDING_REVOKED))
{
es_fprintf (fp, _("revoked"));
es_fprintf (fp, _(", "));
}
else if ((binding->flags & BINDING_EXPIRED))
{
es_fprintf (fp, _("expired"));
es_fprintf (fp, _(", "));
}
if (this_key)
es_fprintf (fp, _("this key"));
else
es_fprintf (fp, _("policy: %s"),
tofu_policy_str (stats_iter->policy));
es_fputs ("):\n", fp);
xfree (key_pp);
seen_in_past = 0;
show_statistics (dbs, stats_iter->fingerprint, email,
TOFU_POLICY_ASK, NULL, 1, now);
}
if (labs(stats_iter->time_ago) == 1)
{
/* The 1 in this case is the NULL entry. */
log_assert (stats_iter->count == 1);
stats_iter->count = 0;
}
seen_in_past += stats_iter->count;
es_fputs (" ", fp);
if (!stats_iter->count)
{
if (stats_iter->time_ago > 0)
es_fprintf (fp, ngettext("Verified %d message.",
"Verified %d messages.",
seen_in_past), seen_in_past);
else
es_fprintf (fp, ngettext("Encrypted %d message.",
"Encrypted %d messages.",
seen_in_past), seen_in_past);
}
else if (labs(stats_iter->time_ago) == 2)
{
if (stats_iter->time_ago > 0)
es_fprintf (fp, ngettext("Verified %d message in the future.",
"Verified %d messages in the future.",
seen_in_past), seen_in_past);
else
es_fprintf (fp, ngettext("Encrypted %d message in the future.",
"Encrypted %d messages in the future.",
seen_in_past), seen_in_past);
/* Reset it. */
seen_in_past = 0;
}
else
{
if (labs(stats_iter->time_ago) == 3)
{
int days = 1 + stats_iter->time_ago / TIME_AGO_UNIT_SMALL;
if (stats_iter->time_ago > 0)
es_fprintf
(fp,
ngettext("Messages verified over the past %d day: %d.",
"Messages verified over the past %d days: %d.",
days), days, seen_in_past);
else
es_fprintf
(fp,
ngettext("Messages encrypted over the past %d day: %d.",
"Messages encrypted over the past %d days: %d.",
days), days, seen_in_past);
}
else if (labs(stats_iter->time_ago) == 4)
{
int months = 1 + stats_iter->time_ago / TIME_AGO_UNIT_MEDIUM;
if (stats_iter->time_ago > 0)
es_fprintf
(fp,
ngettext("Messages verified over the past %d month: %d.",
"Messages verified over the past %d months: %d.",
months), months, seen_in_past);
else
es_fprintf
(fp,
ngettext("Messages encrypted over the past %d month: %d.",
"Messages encrypted over the past %d months: %d.",
months), months, seen_in_past);
}
else if (labs(stats_iter->time_ago) == 5)
{
int years = 1 + stats_iter->time_ago / TIME_AGO_UNIT_LARGE;
if (stats_iter->time_ago > 0)
es_fprintf
(fp,
ngettext("Messages verified over the past %d year: %d.",
"Messages verified over the past %d years: %d.",
years), years, seen_in_past);
else
es_fprintf
(fp,
ngettext("Messages encrypted over the past %d year: %d.",
"Messages encrypted over the past %d years: %d.",
years), years, seen_in_past);
}
else if (labs(stats_iter->time_ago) == 6)
{
if (stats_iter->time_ago > 0)
es_fprintf
(fp, _("Messages verified in the past: %d."),
seen_in_past);
else
es_fprintf
(fp, _("Messages encrypted in the past: %d."),
seen_in_past);
}
else
log_assert (! "Broken SQL.\n");
}
es_fputs ("\n", fp);
}
}
if (conflict_set_count > 1 || (conflict_set->flags & BINDING_CONFLICT))
{
/* This is a conflict. */
/* TRANSLATORS: Please translate the text found in the source
* file below. We don't directly internationalize that text so
* that we can tweak it without breaking translations. */
const char *text = _("TOFU detected a binding conflict");
char *textbuf;
if (!strcmp (text, "TOFU detected a binding conflict"))
{
/* No translation. Use the English text. */
text =
"Normally, an email address is associated with a single key. "
"However, people sometimes generate a new key if "
"their key is too old or they think it might be compromised. "
"Alternatively, a new key may indicate a man-in-the-middle "
"attack! Before accepting this association, you should talk to or "
"call the person to make sure this new key is legitimate.";
}
textbuf = format_text (text, 72, 80);
- es_fprintf (fp, "\n%s\n", textbuf);
+ es_fprintf (fp, "\n%s\n", textbuf? textbuf : "[OUT OF CORE!]");
xfree (textbuf);
}
es_fputc ('\n', fp);
/* Add a NUL terminator. */
es_fputc (0, fp);
if (es_fclose_snatch (fp, (void **) &prompt, NULL))
log_fatal ("error snatching memory stream\n");
/* I think showing the large message once is sufficient. If we
* would move it right before the cpr_get many lines will scroll
* away and the user might not realize that he merely entered a
* wrong choice (because he does not see that either). As a small
* benefit we allow C-L to redisplay everything. */
tty_printf ("%s", prompt);
/* Suspend any transaction: it could take a while until the user
responds. */
tofu_suspend_batch_transaction (ctrl);
while (1)
{
char *response;
/* TRANSLATORS: Two letters (normally the lower and upper case
* version of the hotkey) for each of the five choices. If
* there is only one choice in your language, repeat it. */
choices = _("gG" "aA" "uU" "rR" "bB");
if (strlen (choices) != 10)
log_bug ("Bad TOFU conflict translation! Please report.");
response = cpr_get
("tofu.conflict",
_("(G)ood, (A)ccept once, (U)nknown, (R)eject once, (B)ad? "));
trim_spaces (response);
cpr_kill_prompt ();
if (*response == CONTROL_L)
tty_printf ("%s", prompt);
else if (!response[0])
/* Default to unknown. Don't save it. */
{
tty_printf (_("Defaulting to unknown.\n"));
*policy = TOFU_POLICY_UNKNOWN;
break;
}
else if (!response[1])
{
char *choice = strchr (choices, *response);
if (choice)
{
int c = ((size_t) choice - (size_t) choices) / 2;
switch (c)
{
case 0: /* Good. */
*policy = TOFU_POLICY_GOOD;
*trust_level = tofu_policy_to_trust_level (*policy);
break;
case 1: /* Accept once. */
*policy = TOFU_POLICY_ASK;
*trust_level = tofu_policy_to_trust_level (TOFU_POLICY_GOOD);
break;
case 2: /* Unknown. */
*policy = TOFU_POLICY_UNKNOWN;
*trust_level = tofu_policy_to_trust_level (*policy);
break;
case 3: /* Reject once. */
*policy = TOFU_POLICY_ASK;
*trust_level = tofu_policy_to_trust_level (TOFU_POLICY_BAD);
break;
case 4: /* Bad. */
*policy = TOFU_POLICY_BAD;
*trust_level = tofu_policy_to_trust_level (*policy);
break;
default:
log_bug ("c should be between 0 and 4 but it is %d!", c);
}
if (record_binding (dbs, fingerprint, email, user_id,
*policy, TOFU_POLICY_NONE, NULL, 0, 0, now))
{
/* If there's an error registering the
* binding, don't save the signature. */
*trust_level = _tofu_GET_TRUST_ERROR;
}
break;
}
}
xfree (response);
}
tofu_resume_batch_transaction (ctrl);
xfree (prompt);
signature_stats_free (stats);
}
/* Return the set of keys that conflict with the binding (including the binding itself, which will be first in the
list). For each returned key also sets BINDING_NEW, etc. */
static strlist_t
build_conflict_set (ctrl_t ctrl, tofu_dbs_t dbs,
PKT_public_key *pk, const char *fingerprint,
const char *email)
{
gpg_error_t rc;
char *sqerr;
strlist_t conflict_set = NULL;
int conflict_set_count;
strlist_t iter;
kbnode_t *kb_all;
KEYDB_HANDLE hd;
int i;
/* Get the fingerprints of any bindings that share the email address
* and whether the bindings have a known conflict.
*
* Note: if the binding in question is in the DB, it will also be
* returned. Thus, if the result set is empty, then is a new binding. */
rc = gpgsql_stepx
(dbs->db, &dbs->s.get_trust_bindings_with_this_email,
strings_collect_cb2, &conflict_set, &sqerr,
"select"
/* A binding should only appear once, but try not to break in the
* case of corruption. */
" fingerprint || case sum(conflict NOTNULL) when 0 then '' else '!' end"
" from bindings where email = ?"
" group by fingerprint"
/* Make sure the current key comes first in the result list (if
it is present). */
" order by fingerprint = ? asc, fingerprint desc;",
GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, fingerprint,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), sqerr);
print_further_info ("listing fingerprints");
sqlite3_free (sqerr);
rc = gpg_error (GPG_ERR_GENERAL);
return NULL;
}
/* Set BINDING_CONFLICT if the binding has a known conflict. This
* allows us to distinguish between bindings where the user
* explicitly set the policy to ask and bindings where we set the
* policy to ask due to a conflict. */
for (iter = conflict_set; iter; iter = iter->next)
{
int l = strlen (iter->d);
if (!(l == 2 * MAX_FINGERPRINT_LEN
|| l == 2 * MAX_FINGERPRINT_LEN + 1))
{
log_error (_("TOFU db corruption detected.\n"));
print_further_info ("fingerprint '%s' is not %d characters long",
iter->d, 2 * MAX_FINGERPRINT_LEN);
}
if (l >= 1 && iter->d[l - 1] == '!')
{
iter->flags |= BINDING_CONFLICT;
/* Remove the !. */
iter->d[l - 1] = 0;
}
}
/* If the current binding has not yet been recorded, add it to the
* list. (The order by above ensures that if it is present, it will
* be first.) */
if (! (conflict_set && strcmp (conflict_set->d, fingerprint) == 0))
{
add_to_strlist (&conflict_set, fingerprint);
conflict_set->flags |= BINDING_NEW;
}
conflict_set_count = strlist_length (conflict_set);
/* Eliminate false conflicts. */
if (conflict_set_count == 1)
/* We only have a single key. There are no false conflicts to
eliminate. But, we do need to set the flags. */
{
if (pk->has_expired)
conflict_set->flags |= BINDING_EXPIRED;
if (pk->flags.revoked)
conflict_set->flags |= BINDING_REVOKED;
return conflict_set;
}
/* If two keys have cross signatures, then they are controlled by
* the same person and thus are not in conflict. */
kb_all = xcalloc (sizeof (kb_all[0]), conflict_set_count);
hd = keydb_new ();
for (i = 0, iter = conflict_set;
i < conflict_set_count;
i ++, iter = iter->next)
{
char *fp = iter->d;
KEYDB_SEARCH_DESC desc;
kbnode_t kb;
PKT_public_key *binding_pk;
kbnode_t n;
int found_user_id;
rc = keydb_search_reset (hd);
if (rc)
{
log_error (_("resetting keydb: %s\n"),
gpg_strerror (rc));
continue;
}
rc = classify_user_id (fp, &desc, 0);
if (rc)
{
log_error (_("error parsing key specification '%s': %s\n"),
fp, gpg_strerror (rc));
continue;
}
rc = keydb_search (hd, &desc, 1, NULL);
if (rc)
{
/* Note: it is entirely possible that we don't have the key
corresponding to an entry in the TOFU DB. This can
happen if we merge two TOFU DBs, but not the key
rings. */
log_info (_("key \"%s\" not found: %s\n"),
fp, gpg_strerror (rc));
continue;
}
rc = keydb_get_keyblock (hd, &kb);
if (rc)
{
log_error (_("error reading keyblock: %s\n"),
gpg_strerror (rc));
print_further_info ("fingerprint: %s", fp);
continue;
}
merge_keys_and_selfsig (ctrl, kb);
log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
kb_all[i] = kb;
/* Since we have the key block, use this opportunity to figure
* out if the binding is expired or revoked. */
binding_pk = kb->pkt->pkt.public_key;
/* The binding is always expired/revoked if the key is
* expired/revoked. */
if (binding_pk->has_expired)
iter->flags |= BINDING_EXPIRED;
if (binding_pk->flags.revoked)
iter->flags |= BINDING_REVOKED;
/* The binding is also expired/revoked if the user id is
* expired/revoked. */
n = kb;
found_user_id = 0;
while ((n = find_next_kbnode (n, PKT_USER_ID)) && ! found_user_id)
{
PKT_user_id *user_id2 = n->pkt->pkt.user_id;
char *email2;
if (user_id2->attrib_data)
continue;
email2 = email_from_user_id (user_id2->name);
if (strcmp (email, email2) == 0)
{
found_user_id = 1;
if (user_id2->flags.revoked)
iter->flags |= BINDING_REVOKED;
if (user_id2->flags.expired)
iter->flags |= BINDING_EXPIRED;
}
xfree (email2);
}
if (! found_user_id)
{
log_info (_("TOFU db corruption detected.\n"));
print_further_info ("user id '%s' not on key block '%s'",
email, fingerprint);
}
}
keydb_release (hd);
/* Now that we have the key blocks, check for cross sigs. */
{
int j;
strlist_t *prevp;
strlist_t iter_next;
int *die;
log_assert (conflict_set_count > 0);
die = xtrycalloc (conflict_set_count, sizeof *die);
if (!die)
{
/*err = gpg_error_from_syserror ();*/
xoutofcore (); /* Fixme: Let the function return an error. */
}
for (i = 0; i < conflict_set_count; i ++)
{
/* Look for cross sigs between this key (i == 0) or a key
* that has cross sigs with i == 0 (i.e., transitively) */
if (! (i == 0 || die[i]))
continue;
for (j = i + 1; j < conflict_set_count; j ++)
/* Be careful: we might not have a key block for a key. */
if (kb_all[i] && kb_all[j] && cross_sigs (email, kb_all[i], kb_all[j]))
die[j] = 1;
}
/* Free unconflicting bindings (and all of the key blocks). */
for (iter = conflict_set, prevp = &conflict_set, i = 0;
iter;
iter = iter_next, i ++)
{
iter_next = iter->next;
release_kbnode (kb_all[i]);
if (die[i])
{
*prevp = iter_next;
iter->next = NULL;
free_strlist (iter);
conflict_set_count --;
}
else
{
prevp = &iter->next;
}
}
/* We shouldn't have removed the head. */
log_assert (conflict_set);
log_assert (conflict_set_count >= 1);
xfree (die);
}
xfree (kb_all);
if (DBG_TRUST)
{
log_debug ("binding conflicts:\n",
fingerprint, email);
for (iter = conflict_set; iter; iter = iter->next)
{
log_debug (" %s:%s%s%s%s\n",
iter->d,
(iter->flags & BINDING_NEW) ? " new" : "",
(iter->flags & BINDING_CONFLICT) ? " known_conflict" : "",
(iter->flags & BINDING_EXPIRED) ? " expired" : "",
(iter->flags & BINDING_REVOKED) ? " revoked" : "");
}
}
return conflict_set;
}
/* Return the effective policy for the binding
* (email has already been normalized). Returns
* _tofu_GET_POLICY_ERROR if an error occurs. Returns any conflict
* information in *CONFLICT_SETP if CONFLICT_SETP is not NULL and the
* returned policy is TOFU_POLICY_ASK (consequently, if there is a
* conflict, but the user set the policy to good *CONFLICT_SETP will
* empty). Note: as per build_conflict_set, which is used to build
* the conflict information, the conflict information includes the
* current user id as the first element of the linked list.
*
* This function registers the binding in the bindings table if it has
* not yet been registered.
*/
static enum tofu_policy
get_policy (ctrl_t ctrl, tofu_dbs_t dbs, PKT_public_key *pk,
const char *fingerprint, const char *user_id, const char *email,
strlist_t *conflict_setp, time_t now)
{
int rc;
char *err = NULL;
strlist_t results = NULL;
enum tofu_policy policy = _tofu_GET_POLICY_ERROR;
enum tofu_policy effective_policy_orig = TOFU_POLICY_NONE;
enum tofu_policy effective_policy = _tofu_GET_POLICY_ERROR;
long along;
char *conflict_orig = NULL;
char *conflict = NULL;
strlist_t conflict_set = NULL;
int conflict_set_count;
/* Check if the binding is known
(TOFU_POLICY_NONE cannot appear in the DB. Thus, if POLICY is
still TOFU_POLICY_NONE after executing the query, then the
result set was empty.) */
rc = gpgsql_stepx (dbs->db, &dbs->s.get_policy_select_policy_and_conflict,
strings_collect_cb2, &results, &err,
"select policy, conflict, effective_policy from bindings\n"
" where fingerprint = ? and email = ?",
GPGSQL_ARG_STRING, fingerprint,
GPGSQL_ARG_STRING, email,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("reading the policy");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
goto out;
}
if (strlist_length (results) == 0)
{
/* No results. Use the defaults. */
policy = TOFU_POLICY_NONE;
effective_policy = TOFU_POLICY_NONE;
}
else if (strlist_length (results) == 3)
{
/* Parse and sanity check the results. */
if (string_to_long (&along, results->d, 0, __LINE__))
{
log_error (_("error reading TOFU database: %s\n"),
gpg_strerror (GPG_ERR_BAD_DATA));
print_further_info ("bad value for policy: %s", results->d);
goto out;
}
policy = along;
if (! (policy == TOFU_POLICY_AUTO
|| policy == TOFU_POLICY_GOOD
|| policy == TOFU_POLICY_UNKNOWN
|| policy == TOFU_POLICY_BAD
|| policy == TOFU_POLICY_ASK))
{
log_error (_("error reading TOFU database: %s\n"),
gpg_strerror (GPG_ERR_DB_CORRUPTED));
print_further_info ("invalid value for policy (%d)", policy);
effective_policy = _tofu_GET_POLICY_ERROR;
goto out;
}
if (*results->next->d)
conflict = xstrdup (results->next->d);
if (string_to_long (&along, results->next->next->d, 0, __LINE__))
{
log_error (_("error reading TOFU database: %s\n"),
gpg_strerror (GPG_ERR_BAD_DATA));
print_further_info ("bad value for effective policy: %s",
results->next->next->d);
goto out;
}
effective_policy = along;
if (! (effective_policy == TOFU_POLICY_NONE
|| effective_policy == TOFU_POLICY_AUTO
|| effective_policy == TOFU_POLICY_GOOD
|| effective_policy == TOFU_POLICY_UNKNOWN
|| effective_policy == TOFU_POLICY_BAD
|| effective_policy == TOFU_POLICY_ASK))
{
log_error (_("error reading TOFU database: %s\n"),
gpg_strerror (GPG_ERR_DB_CORRUPTED));
print_further_info ("invalid value for effective_policy (%d)",
effective_policy);
effective_policy = _tofu_GET_POLICY_ERROR;
goto out;
}
}
else
{
/* The result has the wrong form. */
log_error (_("error reading TOFU database: %s\n"),
gpg_strerror (GPG_ERR_BAD_DATA));
print_further_info ("reading policy: expected 3 columns, got %d\n",
strlist_length (results));
goto out;
}
/* Save the effective policy and conflict so we know if we changed
* them. */
effective_policy_orig = effective_policy;
conflict_orig = conflict;
/* Unless there is a conflict, if the effective policy is cached,
* just return it. The reason we don't do this when there is a
* conflict is because of the following scenario: assume A and B
* conflict and B has signed A's key. Now, later we import A's
* signature on B. We need to recheck A, but the signature was on
* B, i.e., when B changes, we invalidate B's effective policy, but
* we also need to invalidate A's effective policy. Instead, we
* assume that conflicts are rare and don't optimize for them, which
* would complicate the code. */
if (effective_policy != TOFU_POLICY_NONE && !conflict)
goto out;
/* If the user explicitly set the policy, then respect that. */
if (policy != TOFU_POLICY_AUTO && policy != TOFU_POLICY_NONE)
{
effective_policy = policy;
goto out;
}
/* Unless proven wrong, assume the effective policy is 'auto'. */
effective_policy = TOFU_POLICY_AUTO;
/* See if the key is ultimately trusted. */
{
u32 kid[2];
keyid_from_pk (pk, kid);
if (tdb_keyid_is_utk (kid))
{
effective_policy = TOFU_POLICY_GOOD;
goto out;
}
}
/* See if the key is signed by an ultimately trusted key. */
{
int fingerprint_raw_len = strlen (fingerprint) / 2;
char fingerprint_raw[20];
int len = 0;
if (fingerprint_raw_len != sizeof fingerprint_raw
|| ((len = hex2bin (fingerprint,
fingerprint_raw, fingerprint_raw_len))
!= strlen (fingerprint)))
{
if (DBG_TRUST)
log_debug ("TOFU: Bad fingerprint: %s (len: %zu, parsed: %d)\n",
fingerprint, strlen (fingerprint), len);
}
else
{
int lookup_err;
kbnode_t kb;
lookup_err = get_pubkey_byfprint (ctrl, NULL, &kb,
fingerprint_raw,
fingerprint_raw_len);
if (lookup_err)
{
if (DBG_TRUST)
log_debug ("TOFU: Looking up %s: %s\n",
fingerprint, gpg_strerror (lookup_err));
}
else
{
int is_signed_by_utk = signed_by_utk (email, kb);
release_kbnode (kb);
if (is_signed_by_utk)
{
effective_policy = TOFU_POLICY_GOOD;
goto out;
}
}
}
}
/* Check for any conflicts / see if a previously discovered conflict
* disappeared. The latter can happen if the conflicting bindings
* are now cross signed, for instance. */
conflict_set = build_conflict_set (ctrl, dbs, pk, fingerprint, email);
conflict_set_count = strlist_length (conflict_set);
if (conflict_set_count == 0)
{
/* build_conflict_set should always at least return the current
binding. Something went wrong. */
effective_policy = _tofu_GET_POLICY_ERROR;
goto out;
}
if (conflict_set_count == 1
&& (conflict_set->flags & BINDING_NEW))
{
/* We've never observed a binding with this email address and we
* have a default policy, which is not to ask the user. */
/* If we've seen this binding, then we've seen this email and
* policy couldn't possibly be TOFU_POLICY_NONE. */
log_assert (policy == TOFU_POLICY_NONE);
if (DBG_TRUST)
log_debug ("TOFU: New binding , no conflict.\n",
fingerprint, email);
effective_policy = TOFU_POLICY_AUTO;
goto out;
}
if (conflict_set_count == 1
&& (conflict_set->flags & BINDING_CONFLICT))
{
/* No known conflicts now, but there was a conflict. This means
* at some point, there was a conflict and we changed this
* binding's policy to ask and set the conflicting key. The
* conflict can go away if there is not a cross sig between the
* two keys. In this case, just silently clear the conflict and
* reset the policy to auto. */
if (DBG_TRUST)
log_debug ("TOFU: binding had a conflict, but it's been resolved (probably via cross sig).\n",
fingerprint, email);
effective_policy = TOFU_POLICY_AUTO;
conflict = NULL;
goto out;
}
if (conflict_set_count == 1)
{
/* No conflicts and never marked as conflicting. */
log_assert (!conflict);
effective_policy = TOFU_POLICY_AUTO;
goto out;
}
/* There is a conflicting key. */
log_assert (conflict_set_count > 1);
effective_policy = TOFU_POLICY_ASK;
conflict = xstrdup (conflict_set->next->d);
out:
log_assert (policy == _tofu_GET_POLICY_ERROR
|| policy == TOFU_POLICY_NONE
|| policy == TOFU_POLICY_AUTO
|| policy == TOFU_POLICY_GOOD
|| policy == TOFU_POLICY_UNKNOWN
|| policy == TOFU_POLICY_BAD
|| policy == TOFU_POLICY_ASK);
/* Everything but NONE. */
log_assert (effective_policy == _tofu_GET_POLICY_ERROR
|| effective_policy == TOFU_POLICY_AUTO
|| effective_policy == TOFU_POLICY_GOOD
|| effective_policy == TOFU_POLICY_UNKNOWN
|| effective_policy == TOFU_POLICY_BAD
|| effective_policy == TOFU_POLICY_ASK);
if (effective_policy != TOFU_POLICY_ASK && conflict)
conflict = NULL;
/* If we don't have a record of this binding, its effective policy
* changed, or conflict changed, update the DB. */
if (effective_policy != _tofu_GET_POLICY_ERROR
&& (/* New binding. */
policy == TOFU_POLICY_NONE
/* effective_policy changed. */
|| effective_policy != effective_policy_orig
/* conflict changed. */
|| (conflict != conflict_orig
&& (!conflict || !conflict_orig
|| strcmp (conflict, conflict_orig) != 0))))
{
if (record_binding (dbs, fingerprint, email, user_id,
policy == TOFU_POLICY_NONE ? TOFU_POLICY_AUTO : policy,
effective_policy, conflict, 1, 0, now) != 0)
log_error (_("error setting TOFU binding's policy"
" to %s\n"), tofu_policy_str (policy));
}
/* If the caller wants the set of conflicts, return it. */
if (effective_policy == TOFU_POLICY_ASK && conflict_setp)
{
if (! conflict_set)
conflict_set = build_conflict_set (ctrl, dbs, pk, fingerprint, email);
*conflict_setp = conflict_set;
}
else
{
free_strlist (conflict_set);
if (conflict_setp)
*conflict_setp = NULL;
}
xfree (conflict_orig);
if (conflict != conflict_orig)
xfree (conflict);
free_strlist (results);
return effective_policy;
}
/* Return the trust level (TRUST_NEVER, etc.) for the binding
* (email is already normalized). If no policy
* is registered, returns TOFU_POLICY_NONE. If an error occurs,
* returns _tofu_GET_TRUST_ERROR.
*
* PK is the public key object for FINGERPRINT.
*
* USER_ID is the unadulterated user id.
*
* If MAY_ASK is set, then we may interact with the user. This is
* necessary if there is a conflict or the binding's policy is
* TOFU_POLICY_ASK. In the case of a conflict, we set the new
* conflicting binding's policy to TOFU_POLICY_ASK. In either case,
* we return TRUST_UNDEFINED. Note: if MAY_ASK is set, then this
* function must not be called while in a transaction! */
static enum tofu_policy
get_trust (ctrl_t ctrl, PKT_public_key *pk,
const char *fingerprint, const char *email,
const char *user_id, int may_ask,
enum tofu_policy *policyp, strlist_t *conflict_setp,
time_t now)
{
tofu_dbs_t dbs = ctrl->tofu.dbs;
int in_transaction = 0;
enum tofu_policy policy;
int rc;
char *sqerr = NULL;
strlist_t conflict_set = NULL;
int trust_level = TRUST_UNKNOWN;
strlist_t iter;
log_assert (dbs);
if (may_ask)
log_assert (dbs->in_transaction == 0);
if (opt.batch)
may_ask = 0;
log_assert (pk_is_primary (pk));
/* Make sure _tofu_GET_TRUST_ERROR isn't equal to any of the trust
levels. */
log_assert (_tofu_GET_TRUST_ERROR != TRUST_UNKNOWN
&& _tofu_GET_TRUST_ERROR != TRUST_EXPIRED
&& _tofu_GET_TRUST_ERROR != TRUST_UNDEFINED
&& _tofu_GET_TRUST_ERROR != TRUST_NEVER
&& _tofu_GET_TRUST_ERROR != TRUST_MARGINAL
&& _tofu_GET_TRUST_ERROR != TRUST_FULLY
&& _tofu_GET_TRUST_ERROR != TRUST_ULTIMATE);
begin_transaction (ctrl, 0);
in_transaction = 1;
/* We need to call get_policy even if the key is ultimately trusted
* to make sure the binding has been registered. */
policy = get_policy (ctrl, dbs, pk, fingerprint, user_id, email,
&conflict_set, now);
if (policy == TOFU_POLICY_ASK)
/* The conflict set should always contain at least one element:
* the current key. */
log_assert (conflict_set);
else
/* If the policy is not TOFU_POLICY_ASK, then conflict_set will be
* NULL. */
log_assert (! conflict_set);
/* If the key is ultimately trusted, there is nothing to do. */
{
u32 kid[2];
keyid_from_pk (pk, kid);
if (tdb_keyid_is_utk (kid))
{
trust_level = TRUST_ULTIMATE;
policy = TOFU_POLICY_GOOD;
goto out;
}
}
if (policy == TOFU_POLICY_AUTO)
{
policy = opt.tofu_default_policy;
if (DBG_TRUST)
log_debug ("TOFU: binding 's policy is"
" auto (default: %s).\n",
fingerprint, email,
tofu_policy_str (opt.tofu_default_policy));
if (policy == TOFU_POLICY_ASK)
/* The default policy is ASK, but there is no conflict (policy
* was 'auto'). In this case, we need to make sure the
* conflict set includes at least the current user id. */
{
add_to_strlist (&conflict_set, fingerprint);
}
}
switch (policy)
{
case TOFU_POLICY_AUTO:
case TOFU_POLICY_GOOD:
case TOFU_POLICY_UNKNOWN:
case TOFU_POLICY_BAD:
/* The saved judgement is auto -> auto, good, unknown or bad.
* We don't need to ask the user anything. */
if (DBG_TRUST)
log_debug ("TOFU: Known binding 's policy: %s\n",
fingerprint, email, tofu_policy_str (policy));
trust_level = tofu_policy_to_trust_level (policy);
goto out;
case TOFU_POLICY_ASK:
/* We need to ask the user what to do. */
break;
case _tofu_GET_POLICY_ERROR:
trust_level = _tofu_GET_TRUST_ERROR;
goto out;
default:
log_bug ("%s: Impossible value for policy (%d)\n", __func__, policy);
}
/* We get here if:
*
* 1. The saved policy is auto and the default policy is ask
* (get_policy() == TOFU_POLICY_AUTO
* && opt.tofu_default_policy == TOFU_POLICY_ASK)
*
* 2. The saved policy is ask (either last time the user selected
* accept once or reject once or there was a conflict and this
* binding's policy was changed from auto to ask)
* (policy == TOFU_POLICY_ASK).
*/
log_assert (policy == TOFU_POLICY_ASK);
if (may_ask)
{
/* We can't be in a normal transaction in ask_about_binding. */
end_transaction (ctrl, 0);
in_transaction = 0;
/* If we get here, we need to ask the user about the binding. */
ask_about_binding (ctrl,
&policy,
&trust_level,
conflict_set,
fingerprint,
email,
user_id,
now);
}
else
{
trust_level = TRUST_UNDEFINED;
}
/* Mark any conflicting bindings that have an automatic policy as
* now requiring confirmation. Note: we do this after we ask for
* confirmation so that when the current policy is printed, it is
* correct. */
if (! in_transaction)
{
begin_transaction (ctrl, 0);
in_transaction = 1;
}
/* The conflict set should always contain at least one element:
* the current key. */
log_assert (conflict_set);
for (iter = conflict_set->next; iter; iter = iter->next)
{
/* We don't immediately set the effective policy to 'ask,
because */
rc = gpgsql_exec_printf
(dbs->db, NULL, NULL, &sqerr,
"update bindings set effective_policy = %d, conflict = %Q"
" where email = %Q and fingerprint = %Q and effective_policy != %d;",
TOFU_POLICY_NONE, fingerprint,
email, iter->d, TOFU_POLICY_ASK);
if (rc)
{
log_error (_("error changing TOFU policy: %s\n"), sqerr);
print_further_info ("binding: ",
fingerprint, user_id);
sqlite3_free (sqerr);
sqerr = NULL;
rc = gpg_error (GPG_ERR_GENERAL);
}
else if (DBG_TRUST)
log_debug ("Set %s to conflict with %s\n",
iter->d, fingerprint);
}
out:
if (in_transaction)
end_transaction (ctrl, 0);
if (policyp)
*policyp = policy;
if (conflict_setp)
*conflict_setp = conflict_set;
else
free_strlist (conflict_set);
return trust_level;
}
/* Return a malloced string of the form
* "7~months"
* The caller should replace all '~' in the returned string by a space
* and also free the returned string.
*
* This is actually a bad hack which may not work correctly with all
* languages.
*/
static char *
time_ago_str (long long int t)
{
/* It would be nice to use a macro to do this, but gettext
works on the unpreprocessed code. */
#define MIN_SECS (60)
#define HOUR_SECS (60 * MIN_SECS)
#define DAY_SECS (24 * HOUR_SECS)
#define WEEK_SECS (7 * DAY_SECS)
#define MONTH_SECS (30 * DAY_SECS)
#define YEAR_SECS (365 * DAY_SECS)
if (t > 2 * YEAR_SECS)
{
long long int c = t / YEAR_SECS;
return xtryasprintf (ngettext("%lld~year", "%lld~years", c), c);
}
if (t > 2 * MONTH_SECS)
{
long long int c = t / MONTH_SECS;
return xtryasprintf (ngettext("%lld~month", "%lld~months", c), c);
}
if (t > 2 * WEEK_SECS)
{
long long int c = t / WEEK_SECS;
return xtryasprintf (ngettext("%lld~week", "%lld~weeks", c), c);
}
if (t > 2 * DAY_SECS)
{
long long int c = t / DAY_SECS;
return xtryasprintf (ngettext("%lld~day", "%lld~days", c), c);
}
if (t > 2 * HOUR_SECS)
{
long long int c = t / HOUR_SECS;
return xtryasprintf (ngettext("%lld~hour", "%lld~hours", c), c);
}
if (t > 2 * MIN_SECS)
{
long long int c = t / MIN_SECS;
return xtryasprintf (ngettext("%lld~minute", "%lld~minutes", c), c);
}
return xtryasprintf (ngettext("%lld~second", "%lld~seconds", t), t);
}
/* If FP is NULL, write TOFU_STATS status line. If FP is not NULL
* write a "tfs" record to that stream. */
static void
write_stats_status (estream_t fp,
enum tofu_policy policy,
unsigned long signature_count,
unsigned long signature_first_seen,
unsigned long signature_most_recent,
unsigned long signature_days,
unsigned long encryption_count,
unsigned long encryption_first_done,
unsigned long encryption_most_recent,
unsigned long encryption_days)
{
int summary;
int validity;
unsigned long days;
/* Use the euclidean distance (m = sqrt(a^2 + b^2)) rather then the
sum of the magnitudes (m = a + b) to ensure a balance between
verified signatures and encrypted messages. */
days = sqrtu32 (signature_days * signature_days
+ encryption_days * encryption_days);
if (days < 1)
validity = 1; /* Key without history. */
else if (days < 2 * BASIC_TRUST_THRESHOLD)
validity = 2; /* Key with too little history. */
else if (days < 2 * FULL_TRUST_THRESHOLD)
validity = 3; /* Key with enough history for basic trust. */
else
validity = 4; /* Key with a lot of history. */
if (policy == TOFU_POLICY_ASK)
summary = 0; /* Key requires attention. */
else
summary = validity;
if (fp)
{
es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:%lu:%lu:\n",
summary, signature_count, encryption_count,
tofu_policy_str (policy),
signature_first_seen, signature_most_recent,
encryption_first_done, encryption_most_recent,
validity, signature_days, encryption_days);
}
else
{
write_status_printf (STATUS_TOFU_STATS,
"%d %lu %lu %s %lu %lu %lu %lu %d %lu %lu",
summary,
signature_count,
encryption_count,
tofu_policy_str (policy),
signature_first_seen,
signature_most_recent,
encryption_first_done,
encryption_most_recent,
validity,
signature_days, encryption_days);
}
}
/* Note: If OUTFP is not NULL, this function merely prints a "tfs" record
* to OUTFP.
*
* POLICY is the key's policy (as returned by get_policy).
*
* Returns 0 if ONLY_STATUS_FD is set. Otherwise, returns whether
* the caller should call show_warning after iterating over all user
* ids.
*/
static int
show_statistics (tofu_dbs_t dbs,
const char *fingerprint, const char *email,
enum tofu_policy policy,
estream_t outfp, int only_status_fd, time_t now)
{
char *fingerprint_pp;
int rc;
strlist_t strlist = NULL;
char *err = NULL;
unsigned long signature_first_seen = 0;
unsigned long signature_most_recent = 0;
unsigned long signature_count = 0;
unsigned long signature_days = 0;
unsigned long encryption_first_done = 0;
unsigned long encryption_most_recent = 0;
unsigned long encryption_count = 0;
unsigned long encryption_days = 0;
int show_warning = 0;
if (only_status_fd && ! is_status_enabled ())
return 0;
fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
/* Get the signature stats. */
rc = gpgsql_exec_printf
(dbs->db, strings_collect_cb, &strlist, &err,
"select count (*), coalesce (min (signatures.time), 0),\n"
" coalesce (max (signatures.time), 0)\n"
" from signatures\n"
" left join bindings on signatures.binding = bindings.oid\n"
" where fingerprint = %Q and email = %Q;",
fingerprint, email);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("getting signature statistics");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
goto out;
}
rc = gpgsql_exec_printf
(dbs->db, strings_collect_cb, &strlist, &err,
"select count (*) from\n"
" (select round(signatures.time / (24 * 60 * 60)) day\n"
" from signatures\n"
" left join bindings on signatures.binding = bindings.oid\n"
" where fingerprint = %Q and email = %Q\n"
" group by day);",
fingerprint, email);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("getting signature statistics (by day)");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
goto out;
}
if (strlist)
{
/* We expect exactly 4 elements. */
log_assert (strlist->next);
log_assert (strlist->next->next);
log_assert (strlist->next->next->next);
log_assert (! strlist->next->next->next->next);
string_to_ulong (&signature_days, strlist->d, -1, __LINE__);
string_to_ulong (&signature_count, strlist->next->d, -1, __LINE__);
string_to_ulong (&signature_first_seen,
strlist->next->next->d, -1, __LINE__);
string_to_ulong (&signature_most_recent,
strlist->next->next->next->d, -1, __LINE__);
free_strlist (strlist);
strlist = NULL;
}
/* Get the encryption stats. */
rc = gpgsql_exec_printf
(dbs->db, strings_collect_cb, &strlist, &err,
"select count (*), coalesce (min (encryptions.time), 0),\n"
" coalesce (max (encryptions.time), 0)\n"
" from encryptions\n"
" left join bindings on encryptions.binding = bindings.oid\n"
" where fingerprint = %Q and email = %Q;",
fingerprint, email);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("getting encryption statistics");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
goto out;
}
rc = gpgsql_exec_printf
(dbs->db, strings_collect_cb, &strlist, &err,
"select count (*) from\n"
" (select round(encryptions.time / (24 * 60 * 60)) day\n"
" from encryptions\n"
" left join bindings on encryptions.binding = bindings.oid\n"
" where fingerprint = %Q and email = %Q\n"
" group by day);",
fingerprint, email);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("getting encryption statistics (by day)");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
goto out;
}
if (strlist)
{
/* We expect exactly 4 elements. */
log_assert (strlist->next);
log_assert (strlist->next->next);
log_assert (strlist->next->next->next);
log_assert (! strlist->next->next->next->next);
string_to_ulong (&encryption_days, strlist->d, -1, __LINE__);
string_to_ulong (&encryption_count, strlist->next->d, -1, __LINE__);
string_to_ulong (&encryption_first_done,
strlist->next->next->d, -1, __LINE__);
string_to_ulong (&encryption_most_recent,
strlist->next->next->next->d, -1, __LINE__);
free_strlist (strlist);
strlist = NULL;
}
if (!outfp)
write_status_text_and_buffer (STATUS_TOFU_USER, fingerprint,
email, strlen (email), 0);
write_stats_status (outfp, policy,
signature_count,
signature_first_seen,
signature_most_recent,
signature_days,
encryption_count,
encryption_first_done,
encryption_most_recent,
encryption_days);
if (!outfp && !only_status_fd)
{
estream_t fp;
char *msg;
fp = es_fopenmem (0, "rw,samethread");
if (! fp)
log_fatal ("error creating memory stream: %s\n",
gpg_strerror (gpg_error_from_syserror()));
if (signature_count == 0 && encryption_count == 0)
{
es_fprintf (fp,
_("%s: Verified 0~signatures and encrypted 0~messages."),
email);
}
else
{
if (signature_count == 0)
es_fprintf (fp, _("%s: Verified 0 signatures."), email);
else
{
/* TRANSLATORS: The final %s is replaced by a string like
"7~months". */
char *ago_str = time_ago_str (now - signature_first_seen);
es_fprintf
(fp,
ngettext("%s: Verified %ld~signature in the past %s.",
"%s: Verified %ld~signatures in the past %s.",
signature_count),
email, signature_count, ago_str);
xfree (ago_str);
}
es_fputs (" ", fp);
if (encryption_count == 0)
es_fprintf (fp, _("Encrypted 0 messages."));
else
{
char *ago_str = time_ago_str (now - encryption_first_done);
/* TRANSLATORS: The final %s is replaced by a string like
"7~months". */
es_fprintf (fp,
ngettext("Encrypted %ld~message in the past %s.",
"Encrypted %ld~messages in the past %s.",
encryption_count),
encryption_count, ago_str);
xfree (ago_str);
}
}
if (opt.verbose)
{
es_fputs (" ", fp);
es_fprintf (fp, _("(policy: %s)"), tofu_policy_str (policy));
}
es_fputs ("\n", fp);
{
char *tmpmsg, *p;
es_fputc (0, fp);
if (es_fclose_snatch (fp, (void **) &tmpmsg, NULL))
log_fatal ("error snatching memory stream\n");
msg = format_text (tmpmsg, 72, 80);
+ if (!msg) /* FIXME: Return the error all the way up. */
+ log_fatal ("format failed: %s\n",
+ gpg_strerror (gpg_error_from_syserror()));
es_free (tmpmsg);
/* Print a status line but suppress the trailing LF.
* Spaces are not percent escaped. */
if (*msg)
write_status_buffer (STATUS_TOFU_STATS_LONG,
msg, strlen (msg)-1, -1);
/* Remove the non-breaking space markers. */
for (p=msg; *p; p++)
if (*p == '~')
*p = ' ';
}
log_string (GPGRT_LOG_INFO, msg);
xfree (msg);
if (policy == TOFU_POLICY_AUTO)
{
if (signature_count == 0)
log_info (_("Warning: we have yet to see"
" a message signed using this key and user id!\n"));
else if (signature_count == 1)
log_info (_("Warning: we've only seen one message"
" signed using this key and user id!\n"));
if (encryption_count == 0)
log_info (_("Warning: you have yet to encrypt"
" a message to this key!\n"));
else if (encryption_count == 1)
log_info (_("Warning: you have only encrypted"
" one message to this key!\n"));
/* Cf. write_stats_status */
if (sqrtu32 (encryption_count * encryption_count
+ signature_count * signature_count)
< 2 * BASIC_TRUST_THRESHOLD)
show_warning = 1;
}
}
out:
xfree (fingerprint_pp);
return show_warning;
}
static void
show_warning (const char *fingerprint, strlist_t user_id_list)
{
char *set_policy_command;
char *text;
char *tmpmsg;
set_policy_command =
xasprintf ("gpg --tofu-policy bad %s", fingerprint);
tmpmsg = xasprintf
(ngettext
("Warning: if you think you've seen more signatures "
"by this key and user id, then this key might be a "
"forgery! Carefully examine the email address for small "
"variations. If the key is suspect, then use\n"
" %s\n"
"to mark it as being bad.\n",
"Warning: if you think you've seen more signatures "
"by this key and these user ids, then this key might be a "
"forgery! Carefully examine the email addresses for small "
"variations. If the key is suspect, then use\n"
" %s\n"
"to mark it as being bad.\n",
strlist_length (user_id_list)),
set_policy_command);
text = format_text (tmpmsg, 72, 80);
+ if (!text) /* FIXME: Return the error all the way up. */
+ log_fatal ("format failed: %s\n",
+ gpg_strerror (gpg_error_from_syserror()));
xfree (tmpmsg);
log_string (GPGRT_LOG_INFO, text);
xfree (text);
es_free (set_policy_command);
}
/* Extract the email address from a user id and normalize it. If the
user id doesn't contain an email address, then we use the whole
user_id and normalize that. The returned string must be freed. */
static char *
email_from_user_id (const char *user_id)
{
char *email = mailbox_from_userid (user_id);
if (! email)
{
/* Hmm, no email address was provided or we are out of core. Just
take the lower-case version of the whole user id. It could be
a hostname, for instance. */
email = ascii_strlwr (xstrdup (user_id));
}
return email;
}
/* Register the signature with the bindings ,
for each USER_ID in USER_ID_LIST. The fingerprint is taken from
the primary key packet PK.
SIG_DIGEST_BIN is the binary representation of the message's
digest. SIG_DIGEST_BIN_LEN is its length.
SIG_TIME is the time that the signature was generated.
ORIGIN is a free-formed string describing the origin of the
signature. If this was from an email and the Claws MUA was used,
then this should be something like: "email:claws". If this is
NULL, the default is simply "unknown".
If MAY_ASK is 1, then this function may interact with the user.
This is necessary if there is a conflict or the binding's policy is
TOFU_POLICY_ASK.
This function returns 0 on success and an error code if an error
occurred. */
gpg_error_t
tofu_register_signature (ctrl_t ctrl,
PKT_public_key *pk, strlist_t user_id_list,
const byte *sig_digest_bin, int sig_digest_bin_len,
time_t sig_time, const char *origin)
{
time_t now = gnupg_get_time ();
gpg_error_t rc;
tofu_dbs_t dbs;
char *fingerprint = NULL;
strlist_t user_id;
char *email = NULL;
char *err = NULL;
char *sig_digest;
unsigned long c;
dbs = opendbs (ctrl);
if (! dbs)
{
rc = gpg_error (GPG_ERR_GENERAL);
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (rc));
return rc;
}
/* We do a query and then an insert. Make sure they are atomic
by wrapping them in a transaction. */
rc = begin_transaction (ctrl, 0);
if (rc)
return rc;
log_assert (pk_is_primary (pk));
sig_digest = make_radix64_string (sig_digest_bin, sig_digest_bin_len);
fingerprint = hexfingerprint (pk, NULL, 0);
if (! origin)
/* The default origin is simply "unknown". */
origin = "unknown";
for (user_id = user_id_list; user_id; user_id = user_id->next)
{
email = email_from_user_id (user_id->d);
if (DBG_TRUST)
log_debug ("TOFU: Registering signature %s with binding"
" \n",
sig_digest, fingerprint, email);
/* Make sure the binding exists and record any TOFU
conflicts. */
if (get_trust (ctrl, pk, fingerprint, email, user_id->d,
0, NULL, NULL, now)
== _tofu_GET_TRUST_ERROR)
{
rc = gpg_error (GPG_ERR_GENERAL);
xfree (email);
break;
}
/* If we've already seen this signature before, then don't add
it again. */
rc = gpgsql_stepx
(dbs->db, &dbs->s.register_already_seen,
get_single_unsigned_long_cb2, &c, &err,
"select count (*)\n"
" from signatures left join bindings\n"
" on signatures.binding = bindings.oid\n"
" where fingerprint = ? and email = ? and sig_time = ?\n"
" and sig_digest = ?",
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_LONG_LONG, (long long) sig_time,
GPGSQL_ARG_STRING, sig_digest,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error reading TOFU database: %s\n"), err);
print_further_info ("checking existence");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
}
else if (c > 1)
/* Duplicates! This should not happen. In particular,
because is the
primary key! */
log_debug ("SIGNATURES DB contains duplicate records"
" ."
" Please report.\n",
fingerprint, email, (unsigned long) sig_time,
sig_digest, origin);
else if (c == 1)
{
if (DBG_TRUST)
log_debug ("Already observed the signature and binding"
" \n",
fingerprint, email, (unsigned long) sig_time,
sig_digest, origin);
}
else if (opt.dry_run)
{
log_info ("TOFU database update skipped due to --dry-run\n");
}
else
/* This is the first time that we've seen this signature and
binding. Record it. */
{
if (DBG_TRUST)
log_debug ("TOFU: Saving signature"
" \n",
fingerprint, email, sig_digest);
log_assert (c == 0);
rc = gpgsql_stepx
(dbs->db, &dbs->s.register_signature, NULL, NULL, &err,
"insert into signatures\n"
" (binding, sig_digest, origin, sig_time, time)\n"
" values\n"
" ((select oid from bindings\n"
" where fingerprint = ? and email = ?),\n"
" ?, ?, ?, ?);",
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_STRING, sig_digest, GPGSQL_ARG_STRING, origin,
GPGSQL_ARG_LONG_LONG, (long long) sig_time,
GPGSQL_ARG_LONG_LONG, (long long) now,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error updating TOFU database: %s\n"), err);
print_further_info ("insert signatures");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
}
}
xfree (email);
if (rc)
break;
}
if (rc)
rollback_transaction (ctrl);
else
rc = end_transaction (ctrl, 0);
xfree (fingerprint);
xfree (sig_digest);
return rc;
}
gpg_error_t
tofu_register_encryption (ctrl_t ctrl,
PKT_public_key *pk, strlist_t user_id_list,
int may_ask)
{
time_t now = gnupg_get_time ();
gpg_error_t rc = 0;
tofu_dbs_t dbs;
kbnode_t kb = NULL;
int free_user_id_list = 0;
char *fingerprint = NULL;
strlist_t user_id;
char *err = NULL;
dbs = opendbs (ctrl);
if (! dbs)
{
rc = gpg_error (GPG_ERR_GENERAL);
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (rc));
return rc;
}
if (/* We need the key block to find the primary key. */
! pk_is_primary (pk)
/* We need the key block to find all user ids. */
|| ! user_id_list)
kb = get_pubkeyblock (ctrl, pk->keyid);
/* Make sure PK is a primary key. */
if (! pk_is_primary (pk))
pk = kb->pkt->pkt.public_key;
if (! user_id_list)
{
/* Use all non-revoked user ids. Do use expired user ids. */
kbnode_t n = kb;
while ((n = find_next_kbnode (n, PKT_USER_ID)))
{
PKT_user_id *uid = n->pkt->pkt.user_id;
if (uid->flags.revoked)
continue;
add_to_strlist (&user_id_list, uid->name);
}
free_user_id_list = 1;
if (! user_id_list)
log_info (_("WARNING: Encrypting to %s, which has no "
"non-revoked user ids\n"),
keystr (pk->keyid));
}
fingerprint = hexfingerprint (pk, NULL, 0);
tofu_begin_batch_update (ctrl);
tofu_resume_batch_transaction (ctrl);
for (user_id = user_id_list; user_id; user_id = user_id->next)
{
char *email = email_from_user_id (user_id->d);
strlist_t conflict_set = NULL;
enum tofu_policy policy;
/* Make sure the binding exists and that we recognize any
conflicts. */
int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
may_ask, &policy, &conflict_set, now);
if (tl == _tofu_GET_TRUST_ERROR)
{
/* An error. */
rc = gpg_error (GPG_ERR_GENERAL);
xfree (email);
goto die;
}
/* If there is a conflict and MAY_ASK is true, we need to show
* the TOFU statistics for the current binding and the
* conflicting bindings. But, if we are not in batch mode, then
* they have already been printed (this is required to make sure
* the information is available to the caller before cpr_get is
* called). */
if (policy == TOFU_POLICY_ASK && may_ask && opt.batch)
{
strlist_t iter;
/* The conflict set should contain at least the current
* key. */
log_assert (conflict_set);
for (iter = conflict_set; iter; iter = iter->next)
show_statistics (dbs, iter->d, email,
TOFU_POLICY_ASK, NULL, 1, now);
}
free_strlist (conflict_set);
rc = gpgsql_stepx
(dbs->db, &dbs->s.register_encryption, NULL, NULL, &err,
"insert into encryptions\n"
" (binding, time)\n"
" values\n"
" ((select oid from bindings\n"
" where fingerprint = ? and email = ?),\n"
" ?);",
GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
GPGSQL_ARG_LONG_LONG, (long long) now,
GPGSQL_ARG_END);
if (rc)
{
log_error (_("error updating TOFU database: %s\n"), err);
print_further_info ("insert encryption");
sqlite3_free (err);
rc = gpg_error (GPG_ERR_GENERAL);
}
xfree (email);
}
die:
tofu_end_batch_update (ctrl);
if (kb)
release_kbnode (kb);
if (free_user_id_list)
free_strlist (user_id_list);
xfree (fingerprint);
return rc;
}
/* Combine a trust level returned from the TOFU trust model with a
trust level returned by the PGP trust model. This is primarily of
interest when the trust model is tofu+pgp (TM_TOFU_PGP).
This function ors together the upper bits (the values not covered
by TRUST_MASK, i.e., TRUST_FLAG_REVOKED, etc.). */
int
tofu_wot_trust_combine (int tofu_base, int wot_base)
{
int tofu = tofu_base & TRUST_MASK;
int wot = wot_base & TRUST_MASK;
int upper = (tofu_base & ~TRUST_MASK) | (wot_base & ~TRUST_MASK);
log_assert (tofu == TRUST_UNKNOWN
|| tofu == TRUST_EXPIRED
|| tofu == TRUST_UNDEFINED
|| tofu == TRUST_NEVER
|| tofu == TRUST_MARGINAL
|| tofu == TRUST_FULLY
|| tofu == TRUST_ULTIMATE);
log_assert (wot == TRUST_UNKNOWN
|| wot == TRUST_EXPIRED
|| wot == TRUST_UNDEFINED
|| wot == TRUST_NEVER
|| wot == TRUST_MARGINAL
|| wot == TRUST_FULLY
|| wot == TRUST_ULTIMATE);
/* We first consider negative trust policys. These trump positive
trust policies. */
if (tofu == TRUST_NEVER || wot == TRUST_NEVER)
/* TRUST_NEVER trumps everything else. */
return upper | TRUST_NEVER;
if (tofu == TRUST_EXPIRED || wot == TRUST_EXPIRED)
/* TRUST_EXPIRED trumps everything but TRUST_NEVER. */
return upper | TRUST_EXPIRED;
/* Now we only have positive or neutral trust policies. We take
the max. */
if (tofu == TRUST_ULTIMATE)
return upper | TRUST_ULTIMATE | TRUST_FLAG_TOFU_BASED;
if (wot == TRUST_ULTIMATE)
return upper | TRUST_ULTIMATE;
if (tofu == TRUST_FULLY)
return upper | TRUST_FULLY | TRUST_FLAG_TOFU_BASED;
if (wot == TRUST_FULLY)
return upper | TRUST_FULLY;
if (tofu == TRUST_MARGINAL)
return upper | TRUST_MARGINAL | TRUST_FLAG_TOFU_BASED;
if (wot == TRUST_MARGINAL)
return upper | TRUST_MARGINAL;
if (tofu == TRUST_UNDEFINED)
return upper | TRUST_UNDEFINED | TRUST_FLAG_TOFU_BASED;
if (wot == TRUST_UNDEFINED)
return upper | TRUST_UNDEFINED;
return upper | TRUST_UNKNOWN;
}
/* Write a "tfs" record for a --with-colons listing. */
gpg_error_t
tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
PKT_public_key *pk, const char *user_id)
{
time_t now = gnupg_get_time ();
gpg_error_t err;
tofu_dbs_t dbs;
char *fingerprint;
char *email;
enum tofu_policy policy;
if (!*user_id)
return 0; /* No TOFU stats possible for an empty ID. */
dbs = opendbs (ctrl);
if (!dbs)
{
err = gpg_error (GPG_ERR_GENERAL);
log_error (_("error opening TOFU database: %s\n"), gpg_strerror (err));
return err;
}
fingerprint = hexfingerprint (pk, NULL, 0);
email = email_from_user_id (user_id);
policy = get_policy (ctrl, dbs, pk, fingerprint, user_id, email, NULL, now);
show_statistics (dbs, fingerprint, email, policy, fp, 0, now);
xfree (email);
xfree (fingerprint);
return 0;
}
/* Return the validity (TRUST_NEVER, etc.) of the bindings
, for each USER_ID in USER_ID_LIST. If
USER_ID_LIST->FLAG is set, then the id is considered to be expired.
PK is the primary key packet.
If MAY_ASK is 1 and the policy is TOFU_POLICY_ASK, then the user
will be prompted to choose a policy. If MAY_ASK is 0 and the
policy is TOFU_POLICY_ASK, then TRUST_UNKNOWN is returned.
Returns TRUST_UNDEFINED if an error occurs. */
int
tofu_get_validity (ctrl_t ctrl, PKT_public_key *pk, strlist_t user_id_list,
int may_ask)
{
time_t now = gnupg_get_time ();
tofu_dbs_t dbs;
char *fingerprint = NULL;
strlist_t user_id;
int trust_level = TRUST_UNKNOWN;
int bindings = 0;
int bindings_valid = 0;
int need_warning = 0;
int had_conflict = 0;
dbs = opendbs (ctrl);
if (! dbs)
{
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (GPG_ERR_GENERAL));
return TRUST_UNDEFINED;
}
fingerprint = hexfingerprint (pk, NULL, 0);
tofu_begin_batch_update (ctrl);
/* Start the batch transaction now. */
tofu_resume_batch_transaction (ctrl);
for (user_id = user_id_list; user_id; user_id = user_id->next, bindings ++)
{
char *email = email_from_user_id (user_id->d);
strlist_t conflict_set = NULL;
enum tofu_policy policy;
/* Always call get_trust to make sure the binding is
registered. */
int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
may_ask, &policy, &conflict_set, now);
if (tl == _tofu_GET_TRUST_ERROR)
{
/* An error. */
trust_level = TRUST_UNDEFINED;
xfree (email);
goto die;
}
if (DBG_TRUST)
log_debug ("TOFU: validity for : %s%s.\n",
fingerprint, email,
trust_value_to_string (tl),
user_id->flags ? " (but expired)" : "");
if (user_id->flags)
tl = TRUST_EXPIRED;
if (tl != TRUST_EXPIRED)
bindings_valid ++;
if (may_ask && tl != TRUST_ULTIMATE && tl != TRUST_EXPIRED)
{
/* If policy is ask, then we already printed out the
* conflict information in ask_about_binding or will do so
* in a moment. */
if (policy != TOFU_POLICY_ASK)
need_warning |=
show_statistics (dbs, fingerprint, email, policy, NULL, 0, now);
/* If there is a conflict and MAY_ASK is true, we need to
* show the TOFU statistics for the current binding and the
* conflicting bindings. But, if we are not in batch mode,
* then they have already been printed (this is required to
* make sure the information is available to the caller
* before cpr_get is called). */
if (policy == TOFU_POLICY_ASK && opt.batch)
{
strlist_t iter;
/* The conflict set should contain at least the current
* key. */
log_assert (conflict_set);
had_conflict = 1;
for (iter = conflict_set; iter; iter = iter->next)
show_statistics (dbs, iter->d, email,
TOFU_POLICY_ASK, NULL, 1, now);
}
}
free_strlist (conflict_set);
if (tl == TRUST_NEVER)
trust_level = TRUST_NEVER;
else if (tl == TRUST_EXPIRED)
/* Ignore expired bindings in the trust calculation. */
;
else if (tl > trust_level)
{
/* The expected values: */
log_assert (tl == TRUST_UNKNOWN || tl == TRUST_UNDEFINED
|| tl == TRUST_MARGINAL || tl == TRUST_FULLY
|| tl == TRUST_ULTIMATE);
/* We assume the following ordering: */
log_assert (TRUST_UNKNOWN < TRUST_UNDEFINED);
log_assert (TRUST_UNDEFINED < TRUST_MARGINAL);
log_assert (TRUST_MARGINAL < TRUST_FULLY);
log_assert (TRUST_FULLY < TRUST_ULTIMATE);
trust_level = tl;
}
xfree (email);
}
if (need_warning && ! had_conflict)
show_warning (fingerprint, user_id_list);
die:
tofu_end_batch_update (ctrl);
xfree (fingerprint);
if (bindings_valid == 0)
{
if (DBG_TRUST)
log_debug ("no (of %d) valid bindings."
" Can't get TOFU validity for this set of user ids.\n",
bindings);
return TRUST_NEVER;
}
return trust_level;
}
/* Set the policy for all non-revoked user ids in the keyblock KB to
POLICY.
If no key is available with the specified key id, then this
function returns GPG_ERR_NO_PUBKEY.
Returns 0 on success and an error code otherwise. */
gpg_error_t
tofu_set_policy (ctrl_t ctrl, kbnode_t kb, enum tofu_policy policy)
{
gpg_error_t err = 0;
time_t now = gnupg_get_time ();
tofu_dbs_t dbs;
PKT_public_key *pk;
char *fingerprint = NULL;
log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
pk = kb->pkt->pkt.public_key;
dbs = opendbs (ctrl);
if (! dbs)
{
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (GPG_ERR_GENERAL));
return gpg_error (GPG_ERR_GENERAL);
}
if (DBG_TRUST)
log_debug ("Setting TOFU policy for %s to %s\n",
keystr (pk->keyid), tofu_policy_str (policy));
if (! pk_is_primary (pk))
log_bug ("%s: Passed a subkey, but expecting a primary key.\n", __func__);
fingerprint = hexfingerprint (pk, NULL, 0);
begin_transaction (ctrl, 0);
for (; kb; kb = kb->next)
{
PKT_user_id *user_id;
char *email;
if (kb->pkt->pkttype != PKT_USER_ID)
continue;
user_id = kb->pkt->pkt.user_id;
if (user_id->flags.revoked)
/* Skip revoked user ids. (Don't skip expired user ids, the
expiry can be changed.) */
continue;
email = email_from_user_id (user_id->name);
err = record_binding (dbs, fingerprint, email, user_id->name,
policy, TOFU_POLICY_NONE, NULL, 0, 1, now);
if (err)
{
log_error (_("error setting policy for key %s, user id \"%s\": %s"),
fingerprint, email, gpg_strerror (err));
xfree (email);
break;
}
xfree (email);
}
if (err)
rollback_transaction (ctrl);
else
end_transaction (ctrl, 0);
xfree (fingerprint);
return err;
}
/* Return the TOFU policy for the specified binding in *POLICY. If no
policy has been set for the binding, sets *POLICY to
TOFU_POLICY_NONE.
PK is a primary public key and USER_ID is a user id.
Returns 0 on success and an error code otherwise. */
gpg_error_t
tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id,
enum tofu_policy *policy)
{
time_t now = gnupg_get_time ();
tofu_dbs_t dbs;
char *fingerprint;
char *email;
/* Make sure PK is a primary key. */
log_assert (pk_is_primary (pk));
dbs = opendbs (ctrl);
if (! dbs)
{
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (GPG_ERR_GENERAL));
return gpg_error (GPG_ERR_GENERAL);
}
fingerprint = hexfingerprint (pk, NULL, 0);
email = email_from_user_id (user_id->name);
*policy = get_policy (ctrl, dbs, pk, fingerprint,
user_id->name, email, NULL, now);
xfree (email);
xfree (fingerprint);
if (*policy == _tofu_GET_POLICY_ERROR)
return gpg_error (GPG_ERR_GENERAL);
return 0;
}
gpg_error_t
tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb)
{
tofu_dbs_t dbs;
PKT_public_key *pk;
char *fingerprint;
char *sqlerr = NULL;
int rc;
/* Make sure PK is a primary key. */
setup_main_keyids (kb);
pk = kb->pkt->pkt.public_key;
log_assert (pk_is_primary (pk));
dbs = opendbs (ctrl);
if (! dbs)
{
log_error (_("error opening TOFU database: %s\n"),
gpg_strerror (GPG_ERR_GENERAL));
return gpg_error (GPG_ERR_GENERAL);
}
fingerprint = hexfingerprint (pk, NULL, 0);
rc = gpgsql_stepx (dbs->db, NULL, NULL, NULL, &sqlerr,
"update bindings set effective_policy = ?"
" where fingerprint = ?;",
GPGSQL_ARG_INT, (int) TOFU_POLICY_NONE,
GPGSQL_ARG_STRING, fingerprint,
GPGSQL_ARG_END);
xfree (fingerprint);
if (rc == _tofu_GET_POLICY_ERROR)
return gpg_error (GPG_ERR_GENERAL);
return 0;
}