diff --git a/doc/specify-user-id.texi b/doc/specify-user-id.texi index b363c2ace..64e354bdf 100644 --- a/doc/specify-user-id.texi +++ b/doc/specify-user-id.texi @@ -1,176 +1,173 @@ @c Include file to allow for different placements in man pages and the manual There are different ways to specify a user ID to GnuPG. Some of them are only valid for @command{gpg} others are only good for @command{gpgsm}. Here is the entire list of ways to specify a key: @itemize @bullet @item By key Id. This format is deduced from the length of the string and its content or @code{0x} prefix. The key Id of an X.509 certificate are the low 64 bits of its SHA-1 fingerprint. The use of key Ids is just a shortcut, for all automated processing the fingerprint should be used. When using @command{gpg} an exclamation mark (!) may be appended to force using the specified primary or secondary key and not to try and calculate which primary or secondary key to use. The last four lines of the example give the key ID in their long form as internally used by the OpenPGP protocol. You can see the long key ID using the option @option{--with-colons}. @cartouche @example 234567C4 0F34E556E 01347A56A 0xAB123456 234AABBCC34567C4 0F323456784E56EAB 01AB3FED1347A5612 0x234AABBCC34567C4 @end example @end cartouche @item By fingerprint. This format is deduced from the length of the string and its content or the @code{0x} prefix. Note, that only the 20 byte version fingerprint is available with @command{gpgsm} (i.e. the SHA-1 hash of the certificate). When using @command{gpg} an exclamation mark (!) may be appended to force using the specified primary or secondary key and not to try and calculate which primary or secondary key to use. The best way to specify a key Id is by using the fingerprint. This avoids any ambiguities in case that there are duplicated key IDs. @cartouche @example 1234343434343434C434343434343434 123434343434343C3434343434343734349A3434 0E12343434343434343434EAB3484343434343434 0xE12343434343434343434EAB3484343434343434 @end example @end cartouche @noindent @command{gpgsm} also accepts colons between each pair of hexadecimal digits because this is the de-facto standard on how to present X.509 fingerprints. @command{gpg} also allows the use of the space separated SHA-1 fingerprint as printed by the key listing commands. @item By exact match on OpenPGP user ID. This is denoted by a leading equal sign. It does not make sense for X.509 certificates. @cartouche @example =Heinrich Heine @end example @end cartouche @item By exact match on an email address. This is indicated by enclosing the email address in the usual way with left and right angles. @cartouche @example @end example @end cartouche @item By partial match on an email address. This is indicated by prefixing the search string with an @code{@@}. This uses a substring search but considers only the mail address (i.e. inside the angle brackets). @cartouche @example @@heinrichh @end example @end cartouche @item By exact match on the subject's DN. This is indicated by a leading slash, directly followed by the RFC-2253 encoded DN of the subject. Note that you can't use the string printed by @code{gpgsm --list-keys} because that one has been reordered and modified for better readability; use @option{--with-colons} to print the raw (but standard escaped) RFC-2253 string. @cartouche @example /CN=Heinrich Heine,O=Poets,L=Paris,C=FR @end example @end cartouche @item By exact match on the issuer's DN. This is indicated by a leading hash mark, directly followed by a slash and then directly followed by the RFC-2253 encoded DN of the issuer. This should return the Root cert of the issuer. See note above. @cartouche @example #/CN=Root Cert,O=Poets,L=Paris,C=FR @end example @end cartouche @item By exact match on serial number and issuer's DN. This is indicated by a hash mark, followed by the hexadecimal representation of the serial number, then followed by a slash and the RFC-2253 encoded DN of the issuer. See note above. @cartouche @example #4F03/CN=Root Cert,O=Poets,L=Paris,C=FR @end example @end cartouche @item By keygrip. This is indicated by an ampersand followed by the 40 hex digits of a keygrip. @command{gpgsm} prints the keygrip when using the command -@option{--dump-cert}. It does not yet work for OpenPGP keys. +@option{--dump-cert}. @cartouche @example &D75F22C3F86E355877348498CDC92BD21010A480 @end example @end cartouche @item By substring match. This is the default mode but applications may want to explicitly indicate this by putting the asterisk in front. Match is not case sensitive. @cartouche @example Heine *Heine @end example @end cartouche @item . and + prefixes These prefixes are reserved for looking up mails anchored at the end and for a word search mode. They are not yet implemented and using them is undefined. @end itemize Please note that we have reused the hash mark identifier which was used in old GnuPG versions to indicate the so called local-id. It is not anymore used and there should be no conflict when used with X.509 stuff. Using the RFC-2253 format of DNs has the drawback that it is not possible to map them back to the original encoding, however we don't have to do this because our key database stores this encoding as meta data. - - - diff --git a/kbx/kbxutil.c b/kbx/kbxutil.c index 07774f2d9..f156122e2 100644 --- a/kbx/kbxutil.c +++ b/kbx/kbxutil.c @@ -1,623 +1,641 @@ /* kbxutil.c - The Keybox utility * Copyright (C) 2000, 2001, 2004, 2007, 2011 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include #include #include "../common/logging.h" #include "../common/argparse.h" #include "../common/stringhelp.h" #include "../common/utf8conv.h" #include "../common/i18n.h" #include "keybox-defs.h" #include "../common/init.h" #include enum cmd_and_opt_values { aNull = 0, oArmor = 'a', oDryRun = 'n', oOutput = 'o', oQuiet = 'q', oVerbose = 'v', aNoSuchCmd = 500, /* force other values not to be a letter */ aFindByFpr, aFindByKid, aFindByUid, aStats, aImportOpenPGP, aFindDups, aCut, oDebug, oDebugAll, oNoArmor, oFrom, oTo, aTest }; static ARGPARSE_OPTS opts[] = { { 300, NULL, 0, N_("@Commands:\n ") }, /* { aFindByFpr, "find-by-fpr", 0, "|FPR| find key using it's fingerprnt" }, */ /* { aFindByKid, "find-by-kid", 0, "|KID| find key using it's keyid" }, */ /* { aFindByUid, "find-by-uid", 0, "|NAME| find key by user name" }, */ { aStats, "stats", 0, "show key statistics" }, { aImportOpenPGP, "import-openpgp", 0, "import OpenPGP keyblocks"}, { aFindDups, "find-dups", 0, "find duplicates" }, { aCut, "cut", 0, "export records" }, { 301, NULL, 0, N_("@\nOptions:\n ") }, { oFrom, "from", 4, "|N|first record to export" }, { oTo, "to", 4, "|N|last record to export" }, /* { oArmor, "armor", 0, N_("create ascii armored output")}, */ /* { oArmor, "armour", 0, "@" }, */ /* { oOutput, "output", 2, N_("use as output file")}, */ { oVerbose, "verbose", 0, N_("verbose") }, { oQuiet, "quiet", 0, N_("be somewhat more quiet") }, { oDryRun, "dry-run", 0, N_("do not make any changes") }, { oDebug, "debug" ,4|16, N_("set debugging flags")}, { oDebugAll, "debug-all" ,0, N_("enable full debugging")}, ARGPARSE_end () /* end of list */ }; void myexit (int rc); int keybox_errors_seen = 0; static const char * my_strusage( int level ) { const char *p; switch( level ) { case 11: p = "kbxutil (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: kbxutil [options] [files] (-h for help)"); break; case 41: p = _("Syntax: kbxutil [options] [files]\n" "List, export, import Keybox data\n"); break; default: p = NULL; } return p; } /* Used by gcry for logging */ static void my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr) { (void)dummy; /* Map the log levels. */ switch (level) { case GCRY_LOG_CONT: level = GPGRT_LOG_CONT; break; case GCRY_LOG_INFO: level = GPGRT_LOG_INFO; break; case GCRY_LOG_WARN: level = GPGRT_LOG_WARN; break; case GCRY_LOG_ERROR:level = GPGRT_LOG_ERROR; break; case GCRY_LOG_FATAL:level = GPGRT_LOG_FATAL; break; case GCRY_LOG_BUG: level = GPGRT_LOG_BUG; break; case GCRY_LOG_DEBUG:level = GPGRT_LOG_DEBUG; break; default: level = GPGRT_LOG_ERROR; break; } log_logv (level, fmt, arg_ptr); } /* static void */ /* wrong_args( const char *text ) */ /* { */ /* log_error("usage: kbxutil %s\n", text); */ /* myexit ( 1 ); */ /* } */ #if 0 static int hextobyte( const byte *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; } #endif #if 0 static char * format_fingerprint ( const char *s ) { int i, c; byte fpr[20]; for (i=0; i < 20 && *s; ) { if ( *s == ' ' || *s == '\t' ) { s++; continue; } c = hextobyte(s); if (c == -1) { return NULL; } fpr[i++] = c; s += 2; } return gcry_xstrdup ( fpr ); } #endif #if 0 static int format_keyid ( const char *s, u32 *kid ) { char helpbuf[9]; switch ( strlen ( s ) ) { case 8: kid[0] = 0; kid[1] = strtoul( s, NULL, 16 ); return 10; case 16: mem2str( helpbuf, s, 9 ); kid[0] = strtoul( helpbuf, NULL, 16 ); kid[1] = strtoul( s+8, NULL, 16 ); return 11; } return 0; /* error */ } #endif static char * read_file (const char *fname, size_t *r_length) { FILE *fp; char *buf; size_t buflen; if (!strcmp (fname, "-")) { size_t nread, bufsize = 0; fp = stdin; buf = NULL; buflen = 0; #define NCHUNK 8192 do { bufsize += NCHUNK; if (!buf) buf = xtrymalloc (bufsize); else buf = xtryrealloc (buf, bufsize); if (!buf) log_fatal ("can't allocate buffer: %s\n", strerror (errno)); nread = fread (buf+buflen, 1, NCHUNK, fp); if (nread < NCHUNK && ferror (fp)) { log_error ("error reading '[stdin]': %s\n", strerror (errno)); xfree (buf); return NULL; } buflen += nread; } while (nread == NCHUNK); #undef NCHUNK } else { struct stat st; fp = fopen (fname, "rb"); if (!fp) { log_error ("can't open '%s': %s\n", fname, strerror (errno)); return NULL; } if (fstat (fileno(fp), &st)) { log_error ("can't stat '%s': %s\n", fname, strerror (errno)); fclose (fp); return NULL; } buflen = st.st_size; buf = xtrymalloc (buflen+1); if (!buf) log_fatal ("can't allocate buffer: %s\n", strerror (errno)); if (fread (buf, buflen, 1, fp) != 1) { log_error ("error reading '%s': %s\n", fname, strerror (errno)); fclose (fp); xfree (buf); return NULL; } fclose (fp); } *r_length = buflen; return buf; } static void dump_fpr (const unsigned char *buffer, size_t len) { int i; for (i=0; i < len; i++, buffer++) { if (len == 20) { if (i == 10) putchar (' '); printf (" %02X%02X", buffer[0], buffer[1]); i++; buffer++; } else { if (i && !(i % 8)) putchar (' '); printf (" %02X", buffer[0]); } } } +static void +dump_grip (const unsigned char *buffer, size_t len) +{ + int i; + + for (i=0; i < len; i++, buffer++) + { + printf ("%02X", buffer[0]); + } +} + + static void dump_openpgp_key (keybox_openpgp_info_t info, const unsigned char *image) { printf ("pub %2d %02X%02X%02X%02X", info->primary.algo, info->primary.keyid[4], info->primary.keyid[5], info->primary.keyid[6], info->primary.keyid[7] ); dump_fpr (info->primary.fpr, info->primary.fprlen); putchar ('\n'); + fputs ("grp ", stdout); + dump_grip (info->primary.grip, 20); + putchar ('\n'); if (info->nsubkeys) { struct _keybox_openpgp_key_info *k; k = &info->subkeys; do { printf ("sub %2d %02X%02X%02X%02X", k->algo, k->keyid[4], k->keyid[5], k->keyid[6], k->keyid[7] ); dump_fpr (k->fpr, k->fprlen); putchar ('\n'); + fputs ("grp ", stdout); + dump_grip (k->grip, 20); + putchar ('\n'); k = k->next; } while (k); } if (info->nuids) { struct _keybox_openpgp_uid_info *u; u = &info->uids; do { printf ("uid\t\t%.*s\n", (int)u->len, image + u->off); u = u->next; } while (u); } } static void import_openpgp (const char *filename, int dryrun) { gpg_error_t err; char *buffer; size_t buflen, nparsed; unsigned char *p; struct _keybox_openpgp_info info; KEYBOXBLOB blob; buffer = read_file (filename, &buflen); if (!buffer) return; p = (unsigned char *)buffer; for (;;) { err = _keybox_parse_openpgp (p, buflen, &nparsed, &info); assert (nparsed <= buflen); if (err) { if (gpg_err_code (err) == GPG_ERR_NO_DATA) break; if (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM) { /* This is likely a v3 key packet with a non-RSA algorithm. These are keys from very early versions of GnuPG (pre-OpenPGP). */ } else { fflush (stdout); log_info ("%s: failed to parse OpenPGP keyblock: %s\n", filename, gpg_strerror (err)); } } else { if (dryrun) dump_openpgp_key (&info, p); else { err = _keybox_create_openpgp_blob (&blob, &info, p, nparsed, 0); if (err) { fflush (stdout); log_error ("%s: failed to create OpenPGP keyblock: %s\n", filename, gpg_strerror (err)); } else { err = _keybox_write_blob (blob, stdout); _keybox_release_blob (blob); if (err) { fflush (stdout); log_error ("%s: failed to write OpenPGP keyblock: %s\n", filename, gpg_strerror (err)); } } } _keybox_destroy_openpgp_info (&info); } p += nparsed; buflen -= nparsed; } xfree (buffer); } int main( int argc, char **argv ) { ARGPARSE_ARGS pargs; enum cmd_and_opt_values cmd = 0; unsigned long from = 0, to = ULONG_MAX; int dry_run = 0; early_system_init (); set_strusage( my_strusage ); gcry_control (GCRYCTL_DISABLE_SECMEM); log_set_prefix ("kbxutil", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); gcry_set_log_handler (my_gcry_logger, NULL); /*create_dotlock(NULL); register locking cleanup */ /* We need to use the gcry malloc function because jnlib uses them. */ ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ while (arg_parse( &pargs, opts) ) { switch (pargs.r_opt) { case oVerbose: /*opt.verbose++;*/ /*gcry_control( GCRYCTL_SET_VERBOSITY, (int)opt.verbose );*/ break; case oDebug: /*opt.debug |= pargs.r.ret_ulong; */ break; case oDebugAll: /*opt.debug = ~0;*/ break; case aFindByFpr: case aFindByKid: case aFindByUid: case aStats: case aImportOpenPGP: case aFindDups: case aCut: cmd = pargs.r_opt; break; case oFrom: from = pargs.r.ret_ulong; break; case oTo: to = pargs.r.ret_ulong; break; case oDryRun: dry_run = 1; break; default: pargs.err = 2; break; } } if (to < from) log_error ("record number of \"--to\" is lower than \"--from\" one\n"); if (log_get_errorcount(0) ) myexit(2); if (!cmd) { /* Default is to list a KBX file */ if (!argc) _keybox_dump_file (NULL, 0, stdout); else { for (; argc; argc--, argv++) _keybox_dump_file (*argv, 0, stdout); } } else if (cmd == aStats ) { if (!argc) _keybox_dump_file (NULL, 1, stdout); else { for (; argc; argc--, argv++) _keybox_dump_file (*argv, 1, stdout); } } else if (cmd == aFindDups ) { if (!argc) _keybox_dump_find_dups (NULL, 0, stdout); else { for (; argc; argc--, argv++) _keybox_dump_find_dups (*argv, 0, stdout); } } else if (cmd == aCut ) { if (!argc) _keybox_dump_cut_records (NULL, from, to, stdout); else { for (; argc; argc--, argv++) _keybox_dump_cut_records (*argv, from, to, stdout); } } else if (cmd == aImportOpenPGP) { if (!argc) import_openpgp ("-", dry_run); else { for (; argc; argc--, argv++) import_openpgp (*argv, dry_run); } } #if 0 else if ( cmd == aFindByFpr ) { char *fpr; if ( argc != 2 ) wrong_args ("kbxfile foingerprint"); fpr = format_fingerprint ( argv[1] ); if ( !fpr ) log_error ("invalid formatted fingerprint\n"); else { kbxfile_search_by_fpr ( argv[0], fpr ); gcry_free ( fpr ); } } else if ( cmd == aFindByKid ) { u32 kid[2]; int mode; if ( argc != 2 ) wrong_args ("kbxfile short-or-long-keyid"); mode = format_keyid ( argv[1], kid ); if ( !mode ) log_error ("invalid formatted keyID\n"); else { kbxfile_search_by_kid ( argv[0], kid, mode ); } } else if ( cmd == aFindByUid ) { if ( argc != 2 ) wrong_args ("kbxfile userID"); kbxfile_search_by_uid ( argv[0], argv[1] ); } #endif else log_error ("unsupported action\n"); myexit(0); return 8; /*NEVER REACHED*/ } void myexit( int rc ) { /* if( opt.debug & DBG_MEMSTAT_VALUE ) {*/ /* gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); */ /* gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); */ /* }*/ /* if( opt.debug ) */ /* gcry_control( GCRYCTL_DUMP_SECMEM_STATS ); */ rc = rc? rc : log_get_errorcount(0)? 2 : keybox_errors_seen? 1 : 0; exit(rc ); } diff --git a/kbx/keybox-defs.h b/kbx/keybox-defs.h index be2dd721f..d2b79baf2 100644 --- a/kbx/keybox-defs.h +++ b/kbx/keybox-defs.h @@ -1,209 +1,210 @@ /* keybox-defs.h - internal Keybox definitions * Copyright (C) 2001, 2004 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef KEYBOX_DEFS_H #define KEYBOX_DEFS_H 1 #ifdef GPG_ERR_SOURCE_DEFAULT # if GPG_ERR_SOURCE_DEFAULT != GPG_ERR_SOURCE_KEYBOX # error GPG_ERR_SOURCE_DEFAULT already defined # endif #else # define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_KEYBOX #endif #include #define map_assuan_err(a) \ map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a)) #include /* off_t */ #include "../common/util.h" #include "keybox.h" typedef struct keyboxblob *KEYBOXBLOB; typedef struct keybox_name *KB_NAME; struct keybox_name { /* Link to the next resources, so that we can walk all resources. */ KB_NAME next; /* True if this is a keybox with secret keys. */ int secret; /* A table with all the handles accessing this resources. HANDLE_TABLE_SIZE gives the allocated length of this table unused entrues are set to NULL. HANDLE_TABLE may be NULL. */ KEYBOX_HANDLE *handle_table; size_t handle_table_size; /* The lock handle or NULL it not yet initialized. */ dotlock_t lockhd; /* Not yet used. */ int is_locked; /* Not yet used. */ int did_full_scan; /* The name of the resource file. */ char fname[1]; }; struct keybox_found_s { KEYBOXBLOB blob; size_t pk_no; size_t uid_no; }; struct keybox_handle { KB_NAME kb; int secret; /* this is for a secret keybox */ FILE *fp; int eof; int error; int ephemeral; int for_openpgp; /* Used by gpg. */ struct keybox_found_s found; struct keybox_found_s saved_found; struct { char *name; char *pattern; } word_match; }; -/* Openpgp helper structures. */ +/* OpenPGP helper structures. */ struct _keybox_openpgp_key_info { struct _keybox_openpgp_key_info *next; int algo; + unsigned char grip[20]; unsigned char keyid[8]; int fprlen; /* Either 16 or 20 */ unsigned char fpr[20]; }; struct _keybox_openpgp_uid_info { struct _keybox_openpgp_uid_info *next; size_t off; size_t len; }; struct _keybox_openpgp_info { int is_secret; /* True if this is a secret key. */ unsigned int nsubkeys;/* Total number of subkeys. */ unsigned int nuids; /* Total number of user IDs in the keyblock. */ unsigned int nsigs; /* Total number of signatures in the keyblock. */ /* Note, we use 2 structs here to better cope with the most common use of having one primary and one subkey - this allows us to statically allocate this structure and only malloc stuff for more than one subkey. */ struct _keybox_openpgp_key_info primary; struct _keybox_openpgp_key_info subkeys; struct _keybox_openpgp_uid_info uids; }; typedef struct _keybox_openpgp_info *keybox_openpgp_info_t; /* Don't know whether this is needed: */ /* static struct { */ /* int dry_run; */ /* int quiet; */ /* int verbose; */ /* int preserve_permissions; */ /* } keybox_opt; */ /*-- keybox-init.c --*/ void _keybox_close_file (KEYBOX_HANDLE hd); /*-- keybox-blob.c --*/ gpg_error_t _keybox_create_openpgp_blob (KEYBOXBLOB *r_blob, keybox_openpgp_info_t info, const unsigned char *image, size_t imagelen, int as_ephemeral); #ifdef KEYBOX_WITH_X509 int _keybox_create_x509_blob (KEYBOXBLOB *r_blob, ksba_cert_t cert, unsigned char *sha1_digest, int as_ephemeral); #endif /*KEYBOX_WITH_X509*/ int _keybox_new_blob (KEYBOXBLOB *r_blob, unsigned char *image, size_t imagelen, off_t off); void _keybox_release_blob (KEYBOXBLOB blob); const unsigned char *_keybox_get_blob_image (KEYBOXBLOB blob, size_t *n); off_t _keybox_get_blob_fileoffset (KEYBOXBLOB blob); void _keybox_update_header_blob (KEYBOXBLOB blob, int for_openpgp); /*-- keybox-openpgp.c --*/ gpg_error_t _keybox_parse_openpgp (const unsigned char *image, size_t imagelen, size_t *nparsed, keybox_openpgp_info_t info); void _keybox_destroy_openpgp_info (keybox_openpgp_info_t info); /*-- keybox-file.c --*/ int _keybox_read_blob (KEYBOXBLOB *r_blob, FILE *fp, int *skipped_deleted); int _keybox_write_blob (KEYBOXBLOB blob, FILE *fp); /*-- keybox-search.c --*/ gpg_err_code_t _keybox_get_flag_location (const unsigned char *buffer, size_t length, int what, size_t *flag_off, size_t *flag_size); static inline int blob_get_type (KEYBOXBLOB blob) { const unsigned char *buffer; size_t length; buffer = _keybox_get_blob_image (blob, &length); if (length < 32) return -1; /* blob too short */ return buffer[4]; } /*-- keybox-dump.c --*/ int _keybox_dump_blob (KEYBOXBLOB blob, FILE *fp); int _keybox_dump_file (const char *filename, int stats_only, FILE *outfp); int _keybox_dump_find_dups (const char *filename, int print_them, FILE *outfp); int _keybox_dump_cut_records (const char *filename, unsigned long from, unsigned long to, FILE *outfp); /*-- keybox-util.c --*/ /* * A couple of handy macros */ #endif /*KEYBOX_DEFS_H*/ diff --git a/kbx/keybox-openpgp.c b/kbx/keybox-openpgp.c index 0ba0b9ae8..6d6ed77dc 100644 --- a/kbx/keybox-openpgp.c +++ b/kbx/keybox-openpgp.c @@ -1,522 +1,635 @@ /* keybox-openpgp.c - OpenPGP key parsing * Copyright (C) 2001, 2003, 2011 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ /* This is a simple OpenPGP parser suitable for all OpenPGP key material. It just provides the functionality required to build and parse an KBX OpenPGP key blob. Thus it is not a complete parser. However it is self-contained and optimized for fast in-memory parsing. Note that we don't support old ElGamal v3 keys anymore. */ #include #include #include #include #include #include #include "keybox-defs.h" #include #include "../common/openpgpdefs.h" #include "../common/host2net.h" +struct keyparm_s +{ + const char *mpi; + int len; /* int to avoid a cast in gcry_sexp_build. */ +}; + + /* Assume a valid OpenPGP packet at the address pointed to by BUFBTR which has a maximum length as stored at BUFLEN. Return the header information of that packet and advance the pointer stored at BUFPTR to the next packet; also adjust the length stored at BUFLEN to match the remaining bytes. If there are no more packets, store NULL at BUFPTR. Return an non-zero error code on failure or the following data on success: R_DATAPKT = Pointer to the begin of the packet data. R_DATALEN = Length of this data. This has already been checked to fit into the buffer. R_PKTTYPE = The packet type. R_NTOTAL = The total number of bytes of this packet Note that these values are only updated on success. */ static gpg_error_t next_packet (unsigned char const **bufptr, size_t *buflen, unsigned char const **r_data, size_t *r_datalen, int *r_pkttype, size_t *r_ntotal) { const unsigned char *buf = *bufptr; size_t len = *buflen; int c, ctb, pkttype; unsigned long pktlen; if (!len) return gpg_error (GPG_ERR_NO_DATA); ctb = *buf++; len--; if ( !(ctb & 0x80) ) return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */ if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */ { pkttype = (ctb & 0x3f); if (!len) return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */ c = *buf++; len--; if (pkttype == PKT_COMPRESSED) return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */ if ( c < 192 ) pktlen = c; else if ( c < 224 ) { pktlen = (c - 192) * 256; if (!len) return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */ c = *buf++; len--; pktlen += c + 192; } else if (c == 255) { if (len <4 ) return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */ pktlen = buf32_to_ulong (buf); buf += 4; len -= 4; } else /* Partial length encoding is not allowed for key packets. */ return gpg_error (GPG_ERR_UNEXPECTED); } else /* Old style CTB. */ { int lenbytes; pktlen = 0; pkttype = (ctb>>2)&0xf; lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3)); if (!lenbytes) /* Not allowed in key packets. */ return gpg_error (GPG_ERR_UNEXPECTED); if (len < lenbytes) return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */ for (; lenbytes; lenbytes--) { pktlen <<= 8; pktlen |= *buf++; len--; } } /* Do some basic sanity check. */ switch (pkttype) { case PKT_SIGNATURE: case PKT_SECRET_KEY: case PKT_PUBLIC_KEY: case PKT_SECRET_SUBKEY: case PKT_MARKER: case PKT_RING_TRUST: case PKT_USER_ID: case PKT_PUBLIC_SUBKEY: case PKT_OLD_COMMENT: case PKT_ATTRIBUTE: case PKT_COMMENT: case PKT_GPG_CONTROL: break; /* Okay these are allowed packets. */ default: return gpg_error (GPG_ERR_UNEXPECTED); } if (pkttype == 63 && pktlen == 0xFFFFFFFF) /* Sometimes the decompressing layer enters an error state in which it simply outputs 0xff for every byte read. If we have a stream of 0xff bytes, then it will be detected as a new format packet with type 63 and a 4-byte encoded length that is 4G-1. Since packets with type 63 are private and we use them as a control packet, which won't be 4 GB, we reject such packets as invalid. */ return gpg_error (GPG_ERR_INV_PACKET); if (pktlen > len) return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */ *r_data = buf; *r_datalen = pktlen; *r_pkttype = pkttype; *r_ntotal = (buf - *bufptr) + pktlen; *bufptr = buf + pktlen; *buflen = len - pktlen; if (!*buflen) *bufptr = NULL; return 0; } +/* Take a list of key parameters KP for the OpenPGP ALGO and compute + * the keygrip which will be stored at GRIP. GRIP needs to be a + * buffer of 20 bytes. */ +static gpg_error_t +keygrip_from_keyparm (int algo, struct keyparm_s *kp, unsigned char *grip) +{ + gpg_error_t err; + gcry_sexp_t s_pkey = NULL; + + switch (algo) + { + case PUBKEY_ALGO_DSA: + err = gcry_sexp_build (&s_pkey, NULL, + "(public-key(dsa(p%b)(q%b)(g%b)(y%b)))", + kp[0].len, kp[0].mpi, + kp[1].len, kp[1].mpi, + kp[2].len, kp[2].mpi, + kp[3].len, kp[3].mpi); + break; + + case PUBKEY_ALGO_ELGAMAL: + case PUBKEY_ALGO_ELGAMAL_E: + err = gcry_sexp_build (&s_pkey, NULL, + "(public-key(elg(p%b)(g%b)(y%b)))", + kp[0].len, kp[0].mpi, + kp[1].len, kp[1].mpi, + kp[2].len, kp[2].mpi); + break; + + case PUBKEY_ALGO_RSA: + case PUBKEY_ALGO_RSA_S: + case PUBKEY_ALGO_RSA_E: + err = gcry_sexp_build (&s_pkey, NULL, + "(public-key(rsa(n%b)(e%b)))", + kp[0].len, kp[0].mpi, + kp[1].len, kp[1].mpi); + break; + + case PUBKEY_ALGO_EDDSA: + case PUBKEY_ALGO_ECDSA: + case PUBKEY_ALGO_ECDH: + { + char *curve = openpgp_oidbuf_to_str (kp[0].mpi, kp[0].len); + if (!curve) + err = gpg_error_from_syserror (); + else + { + err = gcry_sexp_build + (&s_pkey, NULL, + (algo == PUBKEY_ALGO_EDDSA)? + "(public-key(ecc(curve%s)(flags eddsa)(q%b)))": + (algo == PUBKEY_ALGO_ECDH + && openpgp_oidbuf_is_cv25519 (kp[0].mpi, kp[0].len))? + "(public-key(ecc(curve%s)(flags djb-tweak)(q%b)))": + "(public-key(ecc(curve%s)(q%b)))", + curve, kp[1].len, kp[1].mpi); + xfree (curve); + } + } + break; + + default: + err = gpg_error (GPG_ERR_PUBKEY_ALGO); + break; + } + + if (!err && !gcry_pk_get_keygrip (s_pkey, grip)) + { + log_info ("kbx: error computing keygrip\n"); + err = gpg_error (GPG_ERR_GENERAL); + } + + gcry_sexp_release (s_pkey); + + if (err) + memset (grip, 0, 20); + return err; +} + + /* Parse a key packet and store the information in KI. */ static gpg_error_t parse_key (const unsigned char *data, size_t datalen, struct _keybox_openpgp_key_info *ki) { gpg_error_t err; const unsigned char *data_start = data; int i, version, algorithm; size_t n; int npkey; unsigned char hashbuffer[768]; - const unsigned char *mpi_n = NULL; - size_t mpi_n_len = 0, mpi_e_len = 0; gcry_md_hd_t md; int is_ecc = 0; + struct keyparm_s keyparm[OPENPGP_MAX_NPKEY]; + unsigned char *helpmpibuf[OPENPGP_MAX_NPKEY] = { NULL }; if (datalen < 5) return gpg_error (GPG_ERR_INV_PACKET); version = *data++; datalen--; if (version < 2 || version > 4 ) return gpg_error (GPG_ERR_INV_PACKET); /* Invalid version. */ /*timestamp = ((data[0]<<24)|(data[1]<<16)|(data[2]<<8)|(data[3]));*/ data +=4; datalen -=4; if (version < 4) { if (datalen < 2) return gpg_error (GPG_ERR_INV_PACKET); data +=2; datalen -= 2; } if (!datalen) return gpg_error (GPG_ERR_INV_PACKET); algorithm = *data++; datalen--; switch (algorithm) { case PUBKEY_ALGO_RSA: case PUBKEY_ALGO_RSA_E: case PUBKEY_ALGO_RSA_S: npkey = 2; break; case PUBKEY_ALGO_ELGAMAL_E: case PUBKEY_ALGO_ELGAMAL: npkey = 3; break; case PUBKEY_ALGO_DSA: npkey = 4; break; case PUBKEY_ALGO_ECDH: npkey = 3; is_ecc = 1; break; case PUBKEY_ALGO_ECDSA: case PUBKEY_ALGO_EDDSA: npkey = 2; is_ecc = 1; break; default: /* Unknown algorithm. */ return gpg_error (GPG_ERR_UNKNOWN_ALGORITHM); } ki->algo = algorithm; for (i=0; i < npkey; i++ ) { unsigned int nbits, nbytes; if (datalen < 2) return gpg_error (GPG_ERR_INV_PACKET); if (is_ecc && (i == 0 || i == 2)) { nbytes = data[0]; if (nbytes < 2 || nbytes > 254) return gpg_error (GPG_ERR_INV_PACKET); nbytes++; /* The size byte itself. */ if (datalen < nbytes) return gpg_error (GPG_ERR_INV_PACKET); + + keyparm[i].mpi = data; + keyparm[i].len = nbytes; } else { nbits = ((data[0]<<8)|(data[1])); data += 2; datalen -= 2; nbytes = (nbits+7) / 8; if (datalen < nbytes) return gpg_error (GPG_ERR_INV_PACKET); - /* For use by v3 fingerprint calculation we need to know the RSA - modulus and exponent. */ - if (i==0) - { - mpi_n = data; - mpi_n_len = nbytes; - } - else if (i==1) - mpi_e_len = nbytes; + + keyparm[i].mpi = data; + keyparm[i].len = nbytes; } data += nbytes; datalen -= nbytes; } n = data - data_start; + + /* Note: Starting here we need to jump to leave on error. */ + + /* Make sure the MPIs are unsigned. */ + for (i=0; i < npkey; i++) + { + if (!keyparm[i].len || (keyparm[i].mpi[0] & 0x80)) + { + helpmpibuf[i] = xtrymalloc (1+keyparm[i].len); + if (!helpmpibuf[i]) + { + err = gpg_error_from_syserror (); + goto leave; + } + helpmpibuf[i][0] = 0; + memcpy (helpmpibuf[i]+1, keyparm[i].mpi, keyparm[i].len); + keyparm[i].mpi = helpmpibuf[i]; + keyparm[i].len++; + } + } + + err = keygrip_from_keyparm (algorithm, keyparm, ki->grip); + if (err) + goto leave; + if (version < 4) { /* We do not support any other algorithm than RSA in v3 packets. */ if (algorithm < 1 || algorithm > 3) return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); err = gcry_md_open (&md, GCRY_MD_MD5, 0); if (err) return err; /* Oops */ - gcry_md_write (md, mpi_n, mpi_n_len); - gcry_md_write (md, mpi_n+mpi_n_len+2, mpi_e_len); + gcry_md_write (md, keyparm[0].mpi, keyparm[0].len); + gcry_md_write (md, keyparm[1].mpi, keyparm[1].len); memcpy (ki->fpr, gcry_md_read (md, 0), 16); gcry_md_close (md); ki->fprlen = 16; - if (mpi_n_len < 8) + if (keyparm[0].len < 8) { /* Moduli less than 64 bit are out of the specs scope. Zero them out because this is what gpg does too. */ memset (ki->keyid, 0, 8); } else - memcpy (ki->keyid, mpi_n + mpi_n_len - 8, 8); + memcpy (ki->keyid, keyparm[0].mpi + keyparm[0].len - 8, 8); } else { /* Its a pity that we need to prefix the buffer with the tag and a length header: We can't simply pass it to the fast hashing function for that reason. It might be a good idea to have a scatter-gather enabled hash function. What we do here is to use a static buffer if this one is large enough and only use the regular hash functions if this buffer is not large enough. */ if ( 3 + n < sizeof hashbuffer ) { hashbuffer[0] = 0x99; /* CTB */ hashbuffer[1] = (n >> 8); /* 2 byte length header. */ hashbuffer[2] = n; memcpy (hashbuffer + 3, data_start, n); gcry_md_hash_buffer (GCRY_MD_SHA1, ki->fpr, hashbuffer, 3 + n); } else { err = gcry_md_open (&md, GCRY_MD_SHA1, 0); if (err) return err; /* Oops */ gcry_md_putc (md, 0x99 ); /* CTB */ gcry_md_putc (md, (n >> 8) ); /* 2 byte length header. */ gcry_md_putc (md, n ); gcry_md_write (md, data_start, n); memcpy (ki->fpr, gcry_md_read (md, 0), 20); gcry_md_close (md); } ki->fprlen = 20; memcpy (ki->keyid, ki->fpr+12, 8); } - return 0; + leave: + for (i=0; i < npkey; i++) + xfree (helpmpibuf[i]); + + return err; } /* The caller must pass the address of an INFO structure which will get filled on success with information pertaining to the OpenPGP keyblock IMAGE of length IMAGELEN. Note that a caller does only need to release this INFO structure if the function returns success. If NPARSED is not NULL the actual number of bytes parsed will be stored at this address. */ gpg_error_t _keybox_parse_openpgp (const unsigned char *image, size_t imagelen, size_t *nparsed, keybox_openpgp_info_t info) { gpg_error_t err = 0; const unsigned char *image_start, *data; size_t n, datalen; int pkttype; int first = 1; int read_error = 0; struct _keybox_openpgp_key_info *k, **ktail = NULL; struct _keybox_openpgp_uid_info *u, **utail = NULL; memset (info, 0, sizeof *info); if (nparsed) *nparsed = 0; image_start = image; while (image) { err = next_packet (&image, &imagelen, &data, &datalen, &pkttype, &n); if (err) { read_error = 1; break; } if (first) { if (pkttype == PKT_PUBLIC_KEY) ; else if (pkttype == PKT_SECRET_KEY) info->is_secret = 1; else { err = gpg_error (GPG_ERR_UNEXPECTED); if (nparsed) *nparsed += n; break; } first = 0; } else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY) break; /* Next keyblock encountered - ready. */ if (nparsed) *nparsed += n; if (pkttype == PKT_SIGNATURE) { /* For now we only count the total number of signatures. */ info->nsigs++; } else if (pkttype == PKT_USER_ID) { info->nuids++; if (info->nuids == 1) { info->uids.off = data - image_start; info->uids.len = datalen; utail = &info->uids.next; } else { u = xtrycalloc (1, sizeof *u); if (!u) { err = gpg_error_from_syserror (); break; } u->off = data - image_start; u->len = datalen; *utail = u; utail = &u->next; } } else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY) { err = parse_key (data, datalen, &info->primary); if (err) break; } else if( pkttype == PKT_PUBLIC_SUBKEY && datalen && *data == '#' ) { /* Early versions of GnuPG used old PGP comment packets; * luckily all those comments are prefixed by a hash * sign - ignore these packets. */ } else if (pkttype == PKT_PUBLIC_SUBKEY || pkttype == PKT_SECRET_SUBKEY) { info->nsubkeys++; if (info->nsubkeys == 1) { err = parse_key (data, datalen, &info->subkeys); if (err) { info->nsubkeys--; /* We ignore subkeys with unknown algorithms. */ if (gpg_err_code (err) == GPG_ERR_UNKNOWN_ALGORITHM || gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM) err = 0; if (err) break; } else ktail = &info->subkeys.next; } else { k = xtrycalloc (1, sizeof *k); if (!k) { err = gpg_error_from_syserror (); break; } err = parse_key (data, datalen, k); if (err) { xfree (k); info->nsubkeys--; /* We ignore subkeys with unknown algorithms. */ if (gpg_err_code (err) == GPG_ERR_UNKNOWN_ALGORITHM || gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM) err = 0; if (err) break; } else { *ktail = k; ktail = &k->next; } } } } if (err) { _keybox_destroy_openpgp_info (info); if (!read_error) { /* Packet parsing worked, thus we should be able to skip the rest of the keyblock. */ while (image) { if (next_packet (&image, &imagelen, &data, &datalen, &pkttype, &n) ) break; /* Another error - stop here. */ if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY) break; /* Next keyblock encountered - ready. */ if (nparsed) *nparsed += n; } } } return err; } /* Release any malloced data in INFO but not INFO itself! */ void _keybox_destroy_openpgp_info (keybox_openpgp_info_t info) { struct _keybox_openpgp_key_info *k, *k2; struct _keybox_openpgp_uid_info *u, *u2; assert (!info->primary.next); for (k=info->subkeys.next; k; k = k2) { k2 = k->next; xfree (k); } for (u=info->uids.next; u; u = u2) { u2 = u->next; xfree (u); } } diff --git a/kbx/keybox-search.c b/kbx/keybox-search.c index e309cce98..1f5dbdf97 100644 --- a/kbx/keybox-search.c +++ b/kbx/keybox-search.c @@ -1,1234 +1,1285 @@ /* keybox-search.c - Search operations * Copyright (C) 2001, 2002, 2003, 2004, 2012, * 2013 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "keybox-defs.h" #include #include "../common/host2net.h" #include "../common/mbox-util.h" #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) struct sn_array_s { int snlen; unsigned char *sn; }; #define get32(a) buf32_to_ulong ((a)) #define get16(a) buf16_to_ulong ((a)) static inline unsigned int blob_get_blob_flags (KEYBOXBLOB blob) { const unsigned char *buffer; size_t length; buffer = _keybox_get_blob_image (blob, &length); if (length < 8) return 0; /* oops */ return get16 (buffer + 6); } /* Return the first keyid from the blob. Returns true if available. */ static int blob_get_first_keyid (KEYBOXBLOB blob, u32 *kid) { const unsigned char *buffer; size_t length, nkeys, keyinfolen; buffer = _keybox_get_blob_image (blob, &length); if (length < 48) return 0; /* blob too short */ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18); if (!nkeys || keyinfolen < 28) return 0; /* invalid blob */ kid[0] = get32 (buffer + 32); kid[1] = get32 (buffer + 36); return 1; } /* Return information on the flag WHAT within the blob BUFFER,LENGTH. Return the offset and the length (in bytes) of the flag in FLAGOFF,FLAG_SIZE. */ gpg_err_code_t _keybox_get_flag_location (const unsigned char *buffer, size_t length, int what, size_t *flag_off, size_t *flag_size) { size_t pos; size_t nkeys, keyinfolen; size_t nuids, uidinfolen; size_t nserial; size_t nsigs, siginfolen, siginfooff; switch (what) { case KEYBOX_FLAG_BLOB: if (length < 8) return GPG_ERR_INV_OBJ; *flag_off = 6; *flag_size = 2; break; case KEYBOX_FLAG_OWNERTRUST: case KEYBOX_FLAG_VALIDITY: case KEYBOX_FLAG_CREATED_AT: case KEYBOX_FLAG_SIG_INFO: if (length < 20) return GPG_ERR_INV_OBJ; /* Key info. */ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return GPG_ERR_INV_OBJ; pos = 20 + keyinfolen*nkeys; if (pos+2 > length) return GPG_ERR_INV_OBJ; /* Out of bounds. */ /* Serial number. */ nserial = get16 (buffer+pos); pos += 2 + nserial; if (pos+4 > length) return GPG_ERR_INV_OBJ; /* Out of bounds. */ /* User IDs. */ nuids = get16 (buffer + pos); pos += 2; uidinfolen = get16 (buffer + pos); pos += 2; if (uidinfolen < 12 ) return GPG_ERR_INV_OBJ; pos += uidinfolen*nuids; if (pos+4 > length) return GPG_ERR_INV_OBJ ; /* Out of bounds. */ /* Signature info. */ siginfooff = pos; nsigs = get16 (buffer + pos); pos += 2; siginfolen = get16 (buffer + pos); pos += 2; if (siginfolen < 4 ) return GPG_ERR_INV_OBJ; pos += siginfolen*nsigs; if (pos+1+1+2+4+4+4+4 > length) return GPG_ERR_INV_OBJ ; /* Out of bounds. */ *flag_size = 1; *flag_off = pos; switch (what) { case KEYBOX_FLAG_VALIDITY: *flag_off += 1; break; case KEYBOX_FLAG_CREATED_AT: *flag_size = 4; *flag_off += 1+2+4+4+4; break; case KEYBOX_FLAG_SIG_INFO: *flag_size = siginfolen * nsigs; *flag_off = siginfooff; break; default: break; } break; default: return GPG_ERR_INV_FLAG; } return 0; } /* Return one of the flags WHAT in VALUE from the blob BUFFER of LENGTH bytes. Return 0 on success or an raw error code. */ static gpg_err_code_t get_flag_from_image (const unsigned char *buffer, size_t length, int what, unsigned int *value) { gpg_err_code_t ec; size_t pos, size; *value = 0; ec = _keybox_get_flag_location (buffer, length, what, &pos, &size); if (!ec) switch (size) { case 1: *value = buffer[pos]; break; case 2: *value = get16 (buffer + pos); break; case 4: *value = get32 (buffer + pos); break; default: ec = GPG_ERR_BUG; break; } return ec; } static int blob_cmp_sn (KEYBOXBLOB blob, const unsigned char *sn, int snlen) { const unsigned char *buffer; size_t length; size_t pos, off; size_t nkeys, keyinfolen; size_t nserial; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return 0; /* invalid blob */ pos = 20 + keyinfolen*nkeys; if (pos+2 > length) return 0; /* out of bounds */ /*serial*/ nserial = get16 (buffer+pos); off = pos + 2; if (off+nserial > length) return 0; /* out of bounds */ return nserial == snlen && !memcmp (buffer+off, sn, snlen); } /* Returns 0 if not found or the number of the key which was found. For X.509 this is always 1, for OpenPGP this is 1 for the primary key and 2 and more for the subkeys. */ static int blob_cmp_fpr (KEYBOXBLOB blob, const unsigned char *fpr) { const unsigned char *buffer; size_t length; size_t pos, off; size_t nkeys, keyinfolen; int idx; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return 0; /* invalid blob */ pos = 20; if (pos + (uint64_t)keyinfolen*nkeys > (uint64_t)length) return 0; /* out of bounds */ for (idx=0; idx < nkeys; idx++) { off = pos + idx*keyinfolen; if (!memcmp (buffer + off, fpr, 20)) return idx+1; /* found */ } return 0; /* not found */ } static int blob_cmp_fpr_part (KEYBOXBLOB blob, const unsigned char *fpr, int fproff, int fprlen) { const unsigned char *buffer; size_t length; size_t pos, off; size_t nkeys, keyinfolen; int idx; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return 0; /* invalid blob */ pos = 20; if (pos + (uint64_t)keyinfolen*nkeys > (uint64_t)length) return 0; /* out of bounds */ for (idx=0; idx < nkeys; idx++) { off = pos + idx*keyinfolen; if (!memcmp (buffer + off + fproff, fpr, fprlen)) return idx+1; /* found */ } return 0; /* not found */ } static int blob_cmp_name (KEYBOXBLOB blob, int idx, const char *name, size_t namelen, int substr, int x509) { const unsigned char *buffer; size_t length; size_t pos, off, len; size_t nkeys, keyinfolen; size_t nuids, uidinfolen; size_t nserial; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return 0; /* invalid blob */ pos = 20 + keyinfolen*nkeys; if ((uint64_t)pos+2 > (uint64_t)length) return 0; /* out of bounds */ /*serial*/ nserial = get16 (buffer+pos); pos += 2 + nserial; if (pos+4 > length) return 0; /* out of bounds */ /* user ids*/ nuids = get16 (buffer + pos); pos += 2; uidinfolen = get16 (buffer + pos); pos += 2; if (uidinfolen < 12 /* should add a: || nuidinfolen > MAX_UIDINFOLEN */) return 0; /* invalid blob */ if (pos + uidinfolen*nuids > length) return 0; /* out of bounds */ if (idx < 0) { /* Compare all names. Note that for X.509 we start with index 1 so to skip the issuer at index 0. */ for (idx = !!x509; idx < nuids; idx++) { size_t mypos = pos; mypos += idx*uidinfolen; off = get32 (buffer+mypos); len = get32 (buffer+mypos+4); if ((uint64_t)off+(uint64_t)len > (uint64_t)length) return 0; /* error: better stop here out of bounds */ if (len < 1) continue; /* empty name */ if (substr) { if (ascii_memcasemem (buffer+off, len, name, namelen)) return idx+1; /* found */ } else { if (len == namelen && !memcmp (buffer+off, name, len)) return idx+1; /* found */ } } } else { if (idx > nuids) return 0; /* no user ID with that idx */ pos += idx*uidinfolen; off = get32 (buffer+pos); len = get32 (buffer+pos+4); if (off+len > length) return 0; /* out of bounds */ if (len < 1) return 0; /* empty name */ if (substr) { if (ascii_memcasemem (buffer+off, len, name, namelen)) return idx+1; /* found */ } else { if (len == namelen && !memcmp (buffer+off, name, len)) return idx+1; /* found */ } } return 0; /* not found */ } /* Compare all email addresses of the subject. With SUBSTR given as True a substring search is done in the mail address. The X509 flag indicated whether the search is done on an X.509 blob. */ static int blob_cmp_mail (KEYBOXBLOB blob, const char *name, size_t namelen, int substr, int x509) { const unsigned char *buffer; size_t length; size_t pos, off, len; size_t nkeys, keyinfolen; size_t nuids, uidinfolen; size_t nserial; int idx; /* fixme: this code is common to blob_cmp_mail */ buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < 28) return 0; /* invalid blob */ pos = 20 + keyinfolen*nkeys; if (pos+2 > length) return 0; /* out of bounds */ /*serial*/ nserial = get16 (buffer+pos); pos += 2 + nserial; if (pos+4 > length) return 0; /* out of bounds */ /* user ids*/ nuids = get16 (buffer + pos); pos += 2; uidinfolen = get16 (buffer + pos); pos += 2; if (uidinfolen < 12 /* should add a: || nuidinfolen > MAX_UIDINFOLEN */) return 0; /* invalid blob */ if (pos + uidinfolen*nuids > length) return 0; /* out of bounds */ if (namelen < 1) return 0; /* Note that for X.509 we start at index 1 because index 0 is used for the issuer name. */ for (idx=!!x509 ;idx < nuids; idx++) { size_t mypos = pos; size_t mylen; mypos += idx*uidinfolen; off = get32 (buffer+mypos); len = get32 (buffer+mypos+4); if ((uint64_t)off+(uint64_t)len > (uint64_t)length) return 0; /* error: better stop here - out of bounds */ if (x509) { if (len < 2 || buffer[off] != '<') continue; /* empty name or trailing 0 not stored */ len--; /* one back */ if ( len < 3 || buffer[off+len] != '>') continue; /* not a proper email address */ off++; len--; } else /* OpenPGP. */ { /* We need to forward to the mailbox part. */ mypos = off; mylen = len; for ( ; len && buffer[off] != '<'; len--, off++) ; if (len < 2 || buffer[off] != '<') { /* Mailbox not explicitly given or too short. Restore OFF and LEN and check whether the entire string resembles a mailbox without the angle brackets. */ off = mypos; len = mylen; if (!is_valid_mailbox_mem (buffer+off, len)) continue; /* Not a mail address. */ } else /* Seems to be standard user id with mail address. */ { off++; /* Point to first char of the mail address. */ len--; /* Search closing '>'. */ for (mypos=off; len && buffer[mypos] != '>'; len--, mypos++) ; if (!len || buffer[mypos] != '>' || off == mypos) continue; /* Not a proper mail address. */ len = mypos - off; } } if (substr) { if (ascii_memcasemem (buffer+off, len, name, namelen)) return idx+1; /* found */ } else { if (len == namelen && !ascii_memcasecmp (buffer+off, name, len)) return idx+1; /* found */ } } return 0; /* not found */ } +/* Return true if the key in BLOB matches the 20 bytes keygrip GRIP. + * We don't have the keygrips as meta data, thus we need to parse the + * certificate. Fixme: We might want to return proper error codes + * instead of failing a search for invalid certificates etc. */ +static int +blob_openpgp_has_grip (KEYBOXBLOB blob, const unsigned char *grip) +{ + int rc = 0; + const unsigned char *buffer; + size_t length; + size_t cert_off, cert_len; + struct _keybox_openpgp_info info; + struct _keybox_openpgp_key_info *k; + + buffer = _keybox_get_blob_image (blob, &length); + if (length < 40) + return 0; /* Too short. */ + cert_off = get32 (buffer+8); + cert_len = get32 (buffer+12); + if ((uint64_t)cert_off+(uint64_t)cert_len > (uint64_t)length) + return 0; /* Too short. */ + + if (_keybox_parse_openpgp (buffer + cert_off, cert_len, NULL, &info)) + return 0; /* Parse error. */ + + if (!memcmp (info.primary.grip, grip, 20)) + { + rc = 1; + goto leave; + } + + if (info.nsubkeys) + { + k = &info.subkeys; + do + { + if (!memcmp (k->grip, grip, 20)) + { + rc = 1; + goto leave; + } + k = k->next; + } + while (k); + } + + leave: + _keybox_destroy_openpgp_info (&info); + return rc; +} + + #ifdef KEYBOX_WITH_X509 /* Return true if the key in BLOB matches the 20 bytes keygrip GRIP. We don't have the keygrips as meta data, thus we need to parse the certificate. Fixme: We might want to return proper error codes instead of failing a search for invalid certificates etc. */ static int blob_x509_has_grip (KEYBOXBLOB blob, const unsigned char *grip) { int rc; const unsigned char *buffer; size_t length; size_t cert_off, cert_len; ksba_reader_t reader = NULL; ksba_cert_t cert = NULL; ksba_sexp_t p = NULL; gcry_sexp_t s_pkey; unsigned char array[20]; unsigned char *rcp; size_t n; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* Too short. */ cert_off = get32 (buffer+8); cert_len = get32 (buffer+12); if ((uint64_t)cert_off+(uint64_t)cert_len > (uint64_t)length) return 0; /* Too short. */ rc = ksba_reader_new (&reader); if (rc) return 0; /* Problem with ksba. */ rc = ksba_reader_set_mem (reader, buffer+cert_off, cert_len); if (rc) goto failed; rc = ksba_cert_new (&cert); if (rc) goto failed; rc = ksba_cert_read_der (cert, reader); if (rc) goto failed; p = ksba_cert_get_public_key (cert); if (!p) goto failed; n = gcry_sexp_canon_len (p, 0, NULL, NULL); if (!n) goto failed; rc = gcry_sexp_sscan (&s_pkey, NULL, (char*)p, n); if (rc) { gcry_sexp_release (s_pkey); goto failed; } rcp = gcry_pk_get_keygrip (s_pkey, array); gcry_sexp_release (s_pkey); if (!rcp) goto failed; /* Can't calculate keygrip. */ xfree (p); ksba_cert_release (cert); ksba_reader_release (reader); return !memcmp (array, grip, 20); failed: xfree (p); ksba_cert_release (cert); ksba_reader_release (reader); return 0; } #endif /*KEYBOX_WITH_X509*/ /* The has_foo functions are used as helpers for search */ static inline int has_short_kid (KEYBOXBLOB blob, u32 lkid) { unsigned char buf[4]; buf[0] = lkid >> 24; buf[1] = lkid >> 16; buf[2] = lkid >> 8; buf[3] = lkid; return blob_cmp_fpr_part (blob, buf, 16, 4); } static inline int has_long_kid (KEYBOXBLOB blob, u32 mkid, u32 lkid) { unsigned char buf[8]; buf[0] = mkid >> 24; buf[1] = mkid >> 16; buf[2] = mkid >> 8; buf[3] = mkid; buf[4] = lkid >> 24; buf[5] = lkid >> 16; buf[6] = lkid >> 8; buf[7] = lkid; return blob_cmp_fpr_part (blob, buf, 12, 8); } static inline int has_fingerprint (KEYBOXBLOB blob, const unsigned char *fpr) { return blob_cmp_fpr (blob, fpr); } static inline int has_keygrip (KEYBOXBLOB blob, const unsigned char *grip) { + if (blob_get_type (blob) == KEYBOX_BLOBTYPE_PGP) + return blob_openpgp_has_grip (blob, grip); #ifdef KEYBOX_WITH_X509 if (blob_get_type (blob) == KEYBOX_BLOBTYPE_X509) return blob_x509_has_grip (blob, grip); -#else - (void)blob; - (void)grip; #endif return 0; } static inline int has_issuer (KEYBOXBLOB blob, const char *name) { size_t namelen; return_val_if_fail (name, 0); if (blob_get_type (blob) != KEYBOX_BLOBTYPE_X509) return 0; namelen = strlen (name); return blob_cmp_name (blob, 0 /* issuer */, name, namelen, 0, 1); } static inline int has_issuer_sn (KEYBOXBLOB blob, const char *name, const unsigned char *sn, int snlen) { size_t namelen; return_val_if_fail (name, 0); return_val_if_fail (sn, 0); if (blob_get_type (blob) != KEYBOX_BLOBTYPE_X509) return 0; namelen = strlen (name); return (blob_cmp_sn (blob, sn, snlen) && blob_cmp_name (blob, 0 /* issuer */, name, namelen, 0, 1)); } static inline int has_sn (KEYBOXBLOB blob, const unsigned char *sn, int snlen) { return_val_if_fail (sn, 0); if (blob_get_type (blob) != KEYBOX_BLOBTYPE_X509) return 0; return blob_cmp_sn (blob, sn, snlen); } static inline int has_subject (KEYBOXBLOB blob, const char *name) { size_t namelen; return_val_if_fail (name, 0); if (blob_get_type (blob) != KEYBOX_BLOBTYPE_X509) return 0; namelen = strlen (name); return blob_cmp_name (blob, 1 /* subject */, name, namelen, 0, 1); } static inline int has_username (KEYBOXBLOB blob, const char *name, int substr) { size_t namelen; int btype; return_val_if_fail (name, 0); btype = blob_get_type (blob); if (btype != KEYBOX_BLOBTYPE_PGP && btype != KEYBOX_BLOBTYPE_X509) return 0; namelen = strlen (name); return blob_cmp_name (blob, -1 /* all subject/user names */, name, namelen, substr, (btype == KEYBOX_BLOBTYPE_X509)); } static inline int has_mail (KEYBOXBLOB blob, const char *name, int substr) { size_t namelen; int btype; return_val_if_fail (name, 0); btype = blob_get_type (blob); if (btype != KEYBOX_BLOBTYPE_PGP && btype != KEYBOX_BLOBTYPE_X509) return 0; if (btype == KEYBOX_BLOBTYPE_PGP && *name == '<') name++; /* Hack to remove the leading '<' for gpg. */ namelen = strlen (name); if (namelen && name[namelen-1] == '>') namelen--; return blob_cmp_mail (blob, name, namelen, substr, (btype == KEYBOX_BLOBTYPE_X509)); } static void release_sn_array (struct sn_array_s *array, size_t size) { size_t n; for (n=0; n < size; n++) xfree (array[n].sn); xfree (array); } /* Helper to open the file. */ static gpg_error_t open_file (KEYBOX_HANDLE hd) { hd->fp = fopen (hd->kb->fname, "rb"); if (!hd->fp) { hd->error = gpg_error_from_syserror (); return hd->error; } return 0; } /* The search API */ gpg_error_t keybox_search_reset (KEYBOX_HANDLE hd) { if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (hd->found.blob) { _keybox_release_blob (hd->found.blob); hd->found.blob = NULL; } if (hd->fp) { if (fseeko (hd->fp, 0, SEEK_SET)) { /* Ooops. Seek did not work. Close so that the search will * open the file again. */ fclose (hd->fp); hd->fp = NULL; } } hd->error = 0; hd->eof = 0; return 0; } /* Note: When in ephemeral mode the search function does visit all blobs but in standard mode, blobs flagged as ephemeral are ignored. If WANT_BLOBTYPE is not 0 only blobs of this type are considered. The value at R_SKIPPED is updated by the number of skipped long records (counts PGP and X.509). */ gpg_error_t keybox_search (KEYBOX_HANDLE hd, KEYBOX_SEARCH_DESC *desc, size_t ndesc, keybox_blobtype_t want_blobtype, size_t *r_descindex, unsigned long *r_skipped) { gpg_error_t rc; size_t n; int need_words, any_skip; KEYBOXBLOB blob = NULL; struct sn_array_s *sn_array = NULL; int pk_no, uid_no; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); /* clear last found result */ if (hd->found.blob) { _keybox_release_blob (hd->found.blob); hd->found.blob = NULL; } if (hd->error) return hd->error; /* still in error state */ if (hd->eof) return -1; /* still EOF */ /* figure out what information we need */ need_words = any_skip = 0; for (n=0; n < ndesc; n++) { switch (desc[n].mode) { case KEYDB_SEARCH_MODE_WORDS: need_words = 1; break; case KEYDB_SEARCH_MODE_FIRST: /* always restart the search in this mode */ keybox_search_reset (hd); break; default: break; } if (desc[n].skipfnc) any_skip = 1; if (desc[n].snlen == -1 && !sn_array) { sn_array = xtrycalloc (ndesc, sizeof *sn_array); if (!sn_array) return (hd->error = gpg_error_from_syserror ()); } } (void)need_words; /* Not yet implemented. */ if (!hd->fp) { rc = open_file (hd); if (rc) { xfree (sn_array); return rc; } } /* Kludge: We need to convert an SN given as hexstring to its binary representation - in some cases we are not able to store it in the search descriptor, because due to the way we use it, it is not possible to free allocated memory. */ if (sn_array) { const unsigned char *s; int i, odd; size_t snlen; for (n=0; n < ndesc; n++) { if (!desc[n].sn) ; else if (desc[n].snlen == -1) { unsigned char *sn; s = desc[n].sn; for (i=0; *s && *s != '/'; s++, i++) ; odd = (i & 1); snlen = (i+1)/2; sn_array[n].sn = xtrymalloc (snlen); if (!sn_array[n].sn) { hd->error = gpg_error_from_syserror (); release_sn_array (sn_array, n); return hd->error; } sn_array[n].snlen = snlen; sn = sn_array[n].sn; s = desc[n].sn; if (odd) { *sn++ = xtoi_1 (s); s++; } for (; *s && *s != '/'; s += 2) *sn++ = xtoi_2 (s); } else { const unsigned char *sn; sn = desc[n].sn; snlen = desc[n].snlen; sn_array[n].sn = xtrymalloc (snlen); if (!sn_array[n].sn) { hd->error = gpg_error_from_syserror (); release_sn_array (sn_array, n); return hd->error; } sn_array[n].snlen = snlen; memcpy (sn_array[n].sn, sn, snlen); } } } pk_no = uid_no = 0; for (;;) { unsigned int blobflags; int blobtype; _keybox_release_blob (blob); blob = NULL; rc = _keybox_read_blob (&blob, hd->fp, NULL); if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX) { ++*r_skipped; continue; /* Skip too large records. */ } if (rc) break; blobtype = blob_get_type (blob); if (blobtype == KEYBOX_BLOBTYPE_HEADER) continue; if (want_blobtype && blobtype != want_blobtype) continue; blobflags = blob_get_blob_flags (blob); if (!hd->ephemeral && (blobflags & 2)) continue; /* Not in ephemeral mode but blob is flagged ephemeral. */ for (n=0; n < ndesc; n++) { switch (desc[n].mode) { case KEYDB_SEARCH_MODE_NONE: never_reached (); break; case KEYDB_SEARCH_MODE_EXACT: uid_no = has_username (blob, desc[n].u.name, 0); if (uid_no) goto found; break; case KEYDB_SEARCH_MODE_MAIL: uid_no = has_mail (blob, desc[n].u.name, 0); if (uid_no) goto found; break; case KEYDB_SEARCH_MODE_MAILSUB: uid_no = has_mail (blob, desc[n].u.name, 1); if (uid_no) goto found; break; case KEYDB_SEARCH_MODE_SUBSTR: uid_no = has_username (blob, desc[n].u.name, 1); if (uid_no) goto found; break; case KEYDB_SEARCH_MODE_MAILEND: case KEYDB_SEARCH_MODE_WORDS: /* not yet implemented */ break; case KEYDB_SEARCH_MODE_ISSUER: if (has_issuer (blob, desc[n].u.name)) goto found; break; case KEYDB_SEARCH_MODE_ISSUER_SN: if (has_issuer_sn (blob, desc[n].u.name, sn_array? sn_array[n].sn : desc[n].sn, sn_array? sn_array[n].snlen : desc[n].snlen)) goto found; break; case KEYDB_SEARCH_MODE_SN: if (has_sn (blob, sn_array? sn_array[n].sn : desc[n].sn, sn_array? sn_array[n].snlen : desc[n].snlen)) goto found; break; case KEYDB_SEARCH_MODE_SUBJECT: if (has_subject (blob, desc[n].u.name)) goto found; break; case KEYDB_SEARCH_MODE_SHORT_KID: pk_no = has_short_kid (blob, desc[n].u.kid[1]); if (pk_no) goto found; break; case KEYDB_SEARCH_MODE_LONG_KID: pk_no = has_long_kid (blob, desc[n].u.kid[0], desc[n].u.kid[1]); if (pk_no) goto found; break; case KEYDB_SEARCH_MODE_FPR: case KEYDB_SEARCH_MODE_FPR20: pk_no = has_fingerprint (blob, desc[n].u.fpr); if (pk_no) goto found; break; case KEYDB_SEARCH_MODE_KEYGRIP: if (has_keygrip (blob, desc[n].u.grip)) goto found; break; case KEYDB_SEARCH_MODE_FIRST: goto found; break; case KEYDB_SEARCH_MODE_NEXT: goto found; break; default: rc = gpg_error (GPG_ERR_INV_VALUE); goto found; } } continue; found: /* Record which DESC we matched on. Note this value is only meaningful if this function returns with no errors. */ if(r_descindex) *r_descindex = n; for (n=any_skip?0:ndesc; n < ndesc; n++) { u32 kid[2]; if (desc[n].skipfnc && blob_get_first_keyid (blob, kid) && desc[n].skipfnc (desc[n].skipfncvalue, kid, uid_no)) break; } if (n == ndesc) break; /* got it */ } if (!rc) { hd->found.blob = blob; hd->found.pk_no = pk_no; hd->found.uid_no = uid_no; } else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF) { _keybox_release_blob (blob); hd->eof = 1; } else { _keybox_release_blob (blob); hd->error = rc; } if (sn_array) release_sn_array (sn_array, ndesc); return rc; } /* Functions to return a certificate or a keyblock. To be used after a successful search operation. */ /* Return the last found keyblock. Returns 0 on success and stores a * new iobuf at R_IOBUF. R_UID_NO and R_PK_NO are used to retun the * number of the key or user id which was matched the search criteria; * if not known they are set to 0. */ gpg_error_t keybox_get_keyblock (KEYBOX_HANDLE hd, iobuf_t *r_iobuf, int *r_pk_no, int *r_uid_no) { gpg_error_t err; const unsigned char *buffer; size_t length; size_t image_off, image_len; size_t siginfo_off, siginfo_len; *r_iobuf = NULL; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); if (blob_get_type (hd->found.blob) != KEYBOX_BLOBTYPE_PGP) return gpg_error (GPG_ERR_WRONG_BLOB_TYPE); buffer = _keybox_get_blob_image (hd->found.blob, &length); if (length < 40) return gpg_error (GPG_ERR_TOO_SHORT); image_off = get32 (buffer+8); image_len = get32 (buffer+12); if ((uint64_t)image_off+(uint64_t)image_len > (uint64_t)length) return gpg_error (GPG_ERR_TOO_SHORT); err = _keybox_get_flag_location (buffer, length, KEYBOX_FLAG_SIG_INFO, &siginfo_off, &siginfo_len); if (err) return err; *r_pk_no = hd->found.pk_no; *r_uid_no = hd->found.uid_no; *r_iobuf = iobuf_temp_with_content (buffer+image_off, image_len); return 0; } #ifdef KEYBOX_WITH_X509 /* Return the last found cert. Caller must free it. */ int keybox_get_cert (KEYBOX_HANDLE hd, ksba_cert_t *r_cert) { const unsigned char *buffer; size_t length; size_t cert_off, cert_len; ksba_reader_t reader = NULL; ksba_cert_t cert = NULL; int rc; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); if (blob_get_type (hd->found.blob) != KEYBOX_BLOBTYPE_X509) return gpg_error (GPG_ERR_WRONG_BLOB_TYPE); buffer = _keybox_get_blob_image (hd->found.blob, &length); if (length < 40) return gpg_error (GPG_ERR_TOO_SHORT); cert_off = get32 (buffer+8); cert_len = get32 (buffer+12); if ((uint64_t)cert_off+(uint64_t)cert_len > (uint64_t)length) return gpg_error (GPG_ERR_TOO_SHORT); rc = ksba_reader_new (&reader); if (rc) return rc; rc = ksba_reader_set_mem (reader, buffer+cert_off, cert_len); if (rc) { ksba_reader_release (reader); /* fixme: need to map the error codes */ return gpg_error (GPG_ERR_GENERAL); } rc = ksba_cert_new (&cert); if (rc) { ksba_reader_release (reader); return rc; } rc = ksba_cert_read_der (cert, reader); if (rc) { ksba_cert_release (cert); ksba_reader_release (reader); /* fixme: need to map the error codes */ return gpg_error (GPG_ERR_GENERAL); } *r_cert = cert; ksba_reader_release (reader); return 0; } #endif /*KEYBOX_WITH_X509*/ /* Return the flags named WHAT at the address of VALUE. IDX is used only for certain flags and should be 0 if not required. */ int keybox_get_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int *value) { const unsigned char *buffer; size_t length; gpg_err_code_t ec; (void)idx; /* Not yet used. */ if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); buffer = _keybox_get_blob_image (hd->found.blob, &length); ec = get_flag_from_image (buffer, length, what, value); return ec? gpg_error (ec):0; } off_t keybox_offset (KEYBOX_HANDLE hd) { if (!hd->fp) return 0; return ftello (hd->fp); } gpg_error_t keybox_seek (KEYBOX_HANDLE hd, off_t offset) { gpg_error_t err; if (hd->error) return hd->error; /* still in error state */ if (! hd->fp) { if (!offset) { /* No need to open the file. An unopened file is effectively at offset 0. */ return 0; } err = open_file (hd); if (err) return err; } err = fseeko (hd->fp, offset, SEEK_SET); hd->error = gpg_error_from_errno (err); return hd->error; }