diff --git a/agent/command-ssh.c b/agent/command-ssh.c index a26d60417..bcc78bd15 100644 --- a/agent/command-ssh.c +++ b/agent/command-ssh.c @@ -1,3848 +1,3848 @@ /* command-ssh.c - gpg-agent's implementation of the ssh-agent protocol. * Copyright (C) 2004-2006, 2009, 2012 Free Software Foundation, Inc. * Copyright (C) 2004-2006, 2009, 2012-2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ /* Only v2 of the ssh-agent protocol is implemented. Relevant RFCs are: RFC-4250 - Protocol Assigned Numbers RFC-4251 - Protocol Architecture RFC-4252 - Authentication Protocol RFC-4253 - Transport Layer Protocol RFC-5656 - ECC support The protocol for the agent is defined in: https://tools.ietf.org/html/draft-miller-ssh-agent */ #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #include #endif /*!HAVE_W32_SYSTEM*/ #ifdef HAVE_SYS_UCRED_H #include #endif #ifdef HAVE_UCRED_H #include #endif #include "agent.h" #include "../common/i18n.h" #include "../common/util.h" #include "../common/ssh-utils.h" /* Request types. */ #define SSH_REQUEST_REQUEST_IDENTITIES 11 #define SSH_REQUEST_SIGN_REQUEST 13 #define SSH_REQUEST_ADD_IDENTITY 17 #define SSH_REQUEST_REMOVE_IDENTITY 18 #define SSH_REQUEST_REMOVE_ALL_IDENTITIES 19 #define SSH_REQUEST_LOCK 22 #define SSH_REQUEST_UNLOCK 23 #define SSH_REQUEST_ADD_ID_CONSTRAINED 25 /* Options. */ #define SSH_OPT_CONSTRAIN_LIFETIME 1 #define SSH_OPT_CONSTRAIN_CONFIRM 2 /* Response types. */ #define SSH_RESPONSE_SUCCESS 6 #define SSH_RESPONSE_FAILURE 5 #define SSH_RESPONSE_IDENTITIES_ANSWER 12 #define SSH_RESPONSE_SIGN_RESPONSE 14 /* Other constants. */ #define SSH_DSA_SIGNATURE_PADDING 20 #define SSH_DSA_SIGNATURE_ELEMS 2 #define SSH_AGENT_RSA_SHA2_256 0x02 #define SSH_AGENT_RSA_SHA2_512 0x04 #define SPEC_FLAG_USE_PKCS1V2 (1 << 0) #define SPEC_FLAG_IS_ECDSA (1 << 1) #define SPEC_FLAG_IS_EdDSA (1 << 2) /*(lowercase 'd' on purpose.)*/ #define SPEC_FLAG_WITH_CERT (1 << 7) /* The name of the control file. */ #define SSH_CONTROL_FILE_NAME "sshcontrol" /* The blurb we put into the header of a newly created control file. */ static const char sshcontrolblurb[] = "# List of allowed ssh keys. Only keys present in this file are used\n" "# in the SSH protocol. The ssh-add tool may add new entries to this\n" "# file to enable them; you may also add them manually. Comment\n" "# lines, like this one, as well as empty lines are ignored. Lines do\n" "# have a certain length limit but this is not serious limitation as\n" "# the format of the entries is fixed and checked by gpg-agent. A\n" "# non-comment line starts with optional white spaces, followed by the\n" "# keygrip of the key given as 40 hex digits, optionally followed by a\n" "# caching TTL in seconds, and another optional field for arbitrary\n" "# flags. Prepend the keygrip with an '!' mark to disable it.\n" "\n"; /* Macros. */ /* Return a new uint32 with b0 being the most significant byte and b3 being the least significant byte. */ #define uint32_construct(b0, b1, b2, b3) \ ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) /* * Basic types. */ /* Type for a request handler. */ typedef gpg_error_t (*ssh_request_handler_t) (ctrl_t ctrl, estream_t request, estream_t response); struct ssh_key_type_spec; typedef struct ssh_key_type_spec ssh_key_type_spec_t; /* Type, which is used for associating request handlers with the appropriate request IDs. */ typedef struct ssh_request_spec { unsigned char type; ssh_request_handler_t handler; const char *identifier; unsigned int secret_input; } ssh_request_spec_t; /* Type for "key modifier functions", which are necessary since OpenSSH and GnuPG treat key material slightly different. A key modifier is called right after a new key identity has been received in order to "sanitize" the material. */ typedef gpg_error_t (*ssh_key_modifier_t) (const char *elems, gcry_mpi_t *mpis); /* The encoding of a generated signature is dependent on the algorithm; therefore algorithm specific signature encoding functions are necessary. */ typedef gpg_error_t (*ssh_signature_encoder_t) (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t sig); /* Type, which is used for boundling all the algorithm specific information together in a single object. */ struct ssh_key_type_spec { /* Algorithm identifier as used by OpenSSH. */ const char *ssh_identifier; /* Human readable name of the algorithm. */ const char *name; /* Algorithm identifier as used by GnuPG. */ int algo; /* List of MPI names for secret keys; order matches the one of the agent protocol. */ const char *elems_key_secret; /* List of MPI names for public keys; order matches the one of the agent protocol. */ const char *elems_key_public; /* List of MPI names for signature data. */ const char *elems_signature; /* List of MPI names for secret keys; order matches the one, which is required by gpg-agent's key access layer. */ const char *elems_sexp_order; /* Key modifier function. Key modifier functions are necessary in order to fix any inconsistencies between the representation of keys on the SSH and on the GnuPG side. */ ssh_key_modifier_t key_modifier; /* Signature encoder function. Signature encoder functions are necessary since the encoding of signatures depends on the used algorithm. */ ssh_signature_encoder_t signature_encoder; /* The name of the ECC curve or NULL for non-ECC algos. This is the * canonical name for the curve as specified by RFC-5656. */ const char *curve_name; /* An alias for curve_name or NULL. Actually this is Libcgrypt's * primary name of the curve. */ const char *alt_curve_name; /* The hash algorithm to be used with this key. 0 for using the default. */ int hash_algo; /* Misc flags. */ unsigned int flags; }; /* Definition of an object to access the sshcontrol file. */ struct ssh_control_file_s { char *fname; /* Name of the file. */ - FILE *fp; /* This is never NULL. */ + estream_t fp; /* This is never NULL. */ int lnr; /* The current line number. */ struct { int valid; /* True if the data of this structure is valid. */ int disabled; /* The item is disabled. */ int ttl; /* The TTL of the item. */ int confirm; /* The confirm flag is set. */ char hexgrip[40+1]; /* The hexgrip of the item (uppercase). */ } item; }; /* Prototypes. */ static gpg_error_t ssh_handler_request_identities (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_sign_request (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_add_identity (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_remove_identity (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_remove_all_identities (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_lock (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_handler_unlock (ctrl_t ctrl, estream_t request, estream_t response); static gpg_error_t ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis); static gpg_error_t ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t signature); static gpg_error_t ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t signature); static gpg_error_t ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t signature); static gpg_error_t ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t signature); static gpg_error_t ssh_key_extract_comment (gcry_sexp_t key, char **comment); /* Global variables. */ /* Associating request types with the corresponding request handlers. */ static const ssh_request_spec_t request_specs[] = { #define REQUEST_SPEC_DEFINE(id, name, secret_input) \ { SSH_REQUEST_##id, ssh_handler_##name, #name, secret_input } REQUEST_SPEC_DEFINE (REQUEST_IDENTITIES, request_identities, 1), REQUEST_SPEC_DEFINE (SIGN_REQUEST, sign_request, 0), REQUEST_SPEC_DEFINE (ADD_IDENTITY, add_identity, 1), REQUEST_SPEC_DEFINE (ADD_ID_CONSTRAINED, add_identity, 1), REQUEST_SPEC_DEFINE (REMOVE_IDENTITY, remove_identity, 0), REQUEST_SPEC_DEFINE (REMOVE_ALL_IDENTITIES, remove_all_identities, 0), REQUEST_SPEC_DEFINE (LOCK, lock, 0), REQUEST_SPEC_DEFINE (UNLOCK, unlock, 0) #undef REQUEST_SPEC_DEFINE }; /* Table holding key type specifications. */ static const ssh_key_type_spec_t ssh_key_types[] = { { "ssh-ed25519", "Ed25519", GCRY_PK_EDDSA, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_eddsa, "Ed25519", NULL, 0, SPEC_FLAG_IS_EdDSA }, { "ssh-rsa", "RSA", GCRY_PK_RSA, "nedupq", "en", "s", "nedpqu", ssh_key_modifier_rsa, ssh_signature_encoder_rsa, NULL, NULL, 0, SPEC_FLAG_USE_PKCS1V2 }, { "ssh-dss", "DSA", GCRY_PK_DSA, "pqgyx", "pqgy", "rs", "pqgyx", NULL, ssh_signature_encoder_dsa, NULL, NULL, 0, 0 }, { "ecdsa-sha2-nistp256", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp256", "NIST P-256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA }, { "ecdsa-sha2-nistp384", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp384", "NIST P-384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA }, { "ecdsa-sha2-nistp521", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp521", "NIST P-521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA }, { "ssh-ed25519-cert-v01@openssh.com", "Ed25519", GCRY_PK_EDDSA, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_eddsa, "Ed25519", NULL, 0, SPEC_FLAG_IS_EdDSA | SPEC_FLAG_WITH_CERT }, { "ssh-rsa-cert-v01@openssh.com", "RSA", GCRY_PK_RSA, "nedupq", "en", "s", "nedpqu", ssh_key_modifier_rsa, ssh_signature_encoder_rsa, NULL, NULL, 0, SPEC_FLAG_USE_PKCS1V2 | SPEC_FLAG_WITH_CERT }, { "ssh-dss-cert-v01@openssh.com", "DSA", GCRY_PK_DSA, "pqgyx", "pqgy", "rs", "pqgyx", NULL, ssh_signature_encoder_dsa, NULL, NULL, 0, SPEC_FLAG_WITH_CERT | SPEC_FLAG_WITH_CERT }, { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp256", "NIST P-256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT }, { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp384", "NIST P-384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT }, { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd", NULL, ssh_signature_encoder_ecdsa, "nistp521", "NIST P-521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT } }; /* General utility functions. */ /* A secure realloc, i.e. it makes sure to allocate secure memory if A is NULL. This is required because the standard gcry_realloc does not know whether to allocate secure or normal if NULL is passed as existing buffer. */ static void * realloc_secure (void *a, size_t n) { void *p; if (a) p = gcry_realloc (a, n); else p = gcry_malloc_secure (n); return p; } /* Lookup the ssh-identifier for the ECC curve CURVE_NAME. Returns * NULL if not found. If found the ssh indetifier is returned and a * pointer to the canonical curve name as specified for ssh is stored * at R_CANON_NAME. */ static const char * ssh_identifier_from_curve_name (const char *curve_name, const char **r_canon_name) { int i; for (i = 0; i < DIM (ssh_key_types); i++) if (ssh_key_types[i].curve_name && (!strcmp (ssh_key_types[i].curve_name, curve_name) || (ssh_key_types[i].alt_curve_name && !strcmp (ssh_key_types[i].alt_curve_name, curve_name)))) { *r_canon_name = ssh_key_types[i].curve_name; return ssh_key_types[i].ssh_identifier; } return NULL; } /* Primitive I/O functions. */ /* Read a byte from STREAM, store it in B. */ static gpg_error_t stream_read_byte (estream_t stream, unsigned char *b) { gpg_error_t err; int ret; ret = es_fgetc (stream); if (ret == EOF) { if (es_ferror (stream)) err = gpg_error_from_syserror (); else err = gpg_error (GPG_ERR_EOF); *b = 0; } else { *b = ret & 0xFF; err = 0; } return err; } /* Write the byte contained in B to STREAM. */ static gpg_error_t stream_write_byte (estream_t stream, unsigned char b) { gpg_error_t err; int ret; ret = es_fputc (b, stream); if (ret == EOF) err = gpg_error_from_syserror (); else err = 0; return err; } /* Read a uint32 from STREAM, store it in UINT32. */ static gpg_error_t stream_read_uint32 (estream_t stream, u32 *uint32) { unsigned char buffer[4]; size_t bytes_read; gpg_error_t err; int ret; ret = es_read (stream, buffer, sizeof (buffer), &bytes_read); if (ret) err = gpg_error_from_syserror (); else { if (bytes_read != sizeof (buffer)) err = gpg_error (GPG_ERR_EOF); else { u32 n; n = uint32_construct (buffer[0], buffer[1], buffer[2], buffer[3]); *uint32 = n; err = 0; } } return err; } /* Write the uint32 contained in UINT32 to STREAM. */ static gpg_error_t stream_write_uint32 (estream_t stream, u32 uint32) { unsigned char buffer[4]; gpg_error_t err; int ret; buffer[0] = uint32 >> 24; buffer[1] = uint32 >> 16; buffer[2] = uint32 >> 8; buffer[3] = uint32 >> 0; ret = es_write (stream, buffer, sizeof (buffer), NULL); if (ret) err = gpg_error_from_syserror (); else err = 0; return err; } /* Read SIZE bytes from STREAM into BUFFER. */ static gpg_error_t stream_read_data (estream_t stream, unsigned char *buffer, size_t size) { gpg_error_t err; size_t bytes_read; int ret; ret = es_read (stream, buffer, size, &bytes_read); if (ret) err = gpg_error_from_syserror (); else { if (bytes_read != size) err = gpg_error (GPG_ERR_EOF); else err = 0; } return err; } /* Skip over SIZE bytes from STREAM. */ static gpg_error_t stream_read_skip (estream_t stream, size_t size) { char buffer[128]; size_t bytes_to_read, bytes_read; int ret; do { bytes_to_read = size; if (bytes_to_read > sizeof buffer) bytes_to_read = sizeof buffer; ret = es_read (stream, buffer, bytes_to_read, &bytes_read); if (ret) return gpg_error_from_syserror (); else if (bytes_read != bytes_to_read) return gpg_error (GPG_ERR_EOF); else size -= bytes_to_read; } while (size); return 0; } /* Write SIZE bytes from BUFFER to STREAM. */ static gpg_error_t stream_write_data (estream_t stream, const unsigned char *buffer, size_t size) { gpg_error_t err; int ret; ret = es_write (stream, buffer, size, NULL); if (ret) err = gpg_error_from_syserror (); else err = 0; return err; } /* Read a binary string from STREAM into STRING, store size of string in STRING_SIZE. Append a hidden nul so that the result may directly be used as a C string. Depending on SECURE use secure memory for STRING. If STRING is NULL do only a dummy read. */ static gpg_error_t stream_read_string (estream_t stream, unsigned int secure, unsigned char **string, u32 *string_size) { gpg_error_t err; unsigned char *buffer = NULL; u32 length = 0; if (string_size) *string_size = 0; /* Read string length. */ err = stream_read_uint32 (stream, &length); if (err) goto out; if (string) { /* Allocate space. */ if (secure) buffer = xtrymalloc_secure (length + 1); else buffer = xtrymalloc (length + 1); if (! buffer) { err = gpg_error_from_syserror (); goto out; } /* Read data. */ err = stream_read_data (stream, buffer, length); if (err) goto out; /* Finalize string object. */ buffer[length] = 0; *string = buffer; } else /* Dummy read requested. */ { err = stream_read_skip (stream, length); if (err) goto out; } if (string_size) *string_size = length; out: if (err) xfree (buffer); return err; } /* Read a binary string from STREAM and store it as an opaque MPI at R_MPI, adding 0x40 (this is the prefix for EdDSA key in OpenPGP). Depending on SECURE use secure memory. If the string is too large for key material return an error. */ static gpg_error_t stream_read_blob (estream_t stream, unsigned int secure, gcry_mpi_t *r_mpi) { gpg_error_t err; unsigned char *buffer = NULL; u32 length = 0; *r_mpi = NULL; /* Read string length. */ err = stream_read_uint32 (stream, &length); if (err) goto leave; /* To avoid excessive use of secure memory we check that an MPI is not too large. */ if (length > (4096/8) + 8) { log_error (_("ssh keys greater than %d bits are not supported\n"), 4096); err = GPG_ERR_TOO_LARGE; goto leave; } /* Allocate space. */ if (secure) buffer = xtrymalloc_secure (length+1); else buffer = xtrymalloc (length+1); if (!buffer) { err = gpg_error_from_syserror (); goto leave; } /* Read data. */ err = stream_read_data (stream, buffer + 1, length); if (err) goto leave; buffer[0] = 0x40; *r_mpi = gcry_mpi_set_opaque (NULL, buffer, 8*(length+1)); buffer = NULL; leave: xfree (buffer); return err; } /* Read a C-string from STREAM, store copy in STRING. */ static gpg_error_t stream_read_cstring (estream_t stream, char **string) { return stream_read_string (stream, 0, (unsigned char **)string, NULL); } /* Write a binary string from STRING of size STRING_N to STREAM. */ static gpg_error_t stream_write_string (estream_t stream, const unsigned char *string, u32 string_n) { gpg_error_t err; err = stream_write_uint32 (stream, string_n); if (err) goto out; err = stream_write_data (stream, string, string_n); out: return err; } /* Write a C-string from STRING to STREAM. */ static gpg_error_t stream_write_cstring (estream_t stream, const char *string) { gpg_error_t err; err = stream_write_string (stream, (const unsigned char *) string, strlen (string)); return err; } /* Read an MPI from STREAM, store it in MPINT. Depending on SECURE use secure memory. */ static gpg_error_t stream_read_mpi (estream_t stream, unsigned int secure, gcry_mpi_t *mpint) { unsigned char *mpi_data; u32 mpi_data_size; gpg_error_t err; gcry_mpi_t mpi; mpi_data = NULL; err = stream_read_string (stream, secure, &mpi_data, &mpi_data_size); if (err) goto out; /* To avoid excessive use of secure memory we check that an MPI is not too large. */ if (mpi_data_size > 520) { log_error (_("ssh keys greater than %d bits are not supported\n"), 4096); err = GPG_ERR_TOO_LARGE; goto out; } err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_STD, mpi_data, mpi_data_size, NULL); if (err) goto out; *mpint = mpi; out: xfree (mpi_data); return err; } /* Write the MPI contained in MPINT to STREAM. */ static gpg_error_t stream_write_mpi (estream_t stream, gcry_mpi_t mpint) { unsigned char *mpi_buffer; size_t mpi_buffer_n; gpg_error_t err; mpi_buffer = NULL; err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &mpi_buffer, &mpi_buffer_n, mpint); if (err) goto out; err = stream_write_string (stream, mpi_buffer, mpi_buffer_n); out: xfree (mpi_buffer); return err; } /* Copy data from SRC to DST until EOF is reached. */ static gpg_error_t stream_copy (estream_t dst, estream_t src) { char buffer[BUFSIZ]; size_t bytes_read; gpg_error_t err; int ret; err = 0; while (1) { ret = es_read (src, buffer, sizeof (buffer), &bytes_read); if (ret || (! bytes_read)) { if (ret) err = gpg_error_from_syserror (); break; } ret = es_write (dst, buffer, bytes_read, NULL); if (ret) { err = gpg_error_from_syserror (); break; } } return err; } /* Open the ssh control file and create it if not available. With APPEND passed as true the file will be opened in append mode, otherwise in read only mode. On success 0 is returned and a new control file object stored at R_CF. On error an error code is returned and NULL is stored at R_CF. */ static gpg_error_t open_control_file (ssh_control_file_t *r_cf, int append) { gpg_error_t err; ssh_control_file_t cf; cf = xtrycalloc (1, sizeof *cf); if (!cf) { err = gpg_error_from_syserror (); goto leave; } /* Note: As soon as we start to use non blocking functions here (i.e. where Pth might switch threads) we need to employ a mutex. */ cf->fname = make_filename_try (gnupg_homedir (), SSH_CONTROL_FILE_NAME, NULL); if (!cf->fname) { err = gpg_error_from_syserror (); goto leave; } /* FIXME: With "a+" we are not able to check whether this will be created and thus the blurb needs to be written first. */ - cf->fp = fopen (cf->fname, append? "a+":"r"); + cf->fp = es_fopen (cf->fname, append? "a+":"r"); if (!cf->fp && errno == ENOENT) { estream_t stream = es_fopen (cf->fname, "wx,mode=-rw-r"); if (!stream) { err = gpg_error_from_syserror (); log_error (_("can't create '%s': %s\n"), cf->fname, gpg_strerror (err)); goto leave; } es_fputs (sshcontrolblurb, stream); es_fclose (stream); - cf->fp = fopen (cf->fname, append? "a+":"r"); + cf->fp = es_fopen (cf->fname, append? "a+":"r"); } if (!cf->fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), cf->fname, gpg_strerror (err)); goto leave; } err = 0; leave: if (err && cf) { if (cf->fp) - fclose (cf->fp); + es_fclose (cf->fp); xfree (cf->fname); xfree (cf); } else *r_cf = cf; return err; } static void rewind_control_file (ssh_control_file_t cf) { - fseek (cf->fp, 0, SEEK_SET); + es_fseek (cf->fp, 0, SEEK_SET); cf->lnr = 0; - clearerr (cf->fp); + es_clearerr (cf->fp); } static void close_control_file (ssh_control_file_t cf) { if (!cf) return; - fclose (cf->fp); + es_fclose (cf->fp); xfree (cf->fname); xfree (cf); } /* Read the next line from the control file and store the data in CF. Returns 0 on success, GPG_ERR_EOF on EOF, or other error codes. */ static gpg_error_t read_control_file_item (ssh_control_file_t cf) { int c, i, n; char *p, *pend, line[256]; long ttl = 0; cf->item.valid = 0; - clearerr (cf->fp); + es_clearerr (cf->fp); do { - if (!fgets (line, DIM(line)-1, cf->fp) ) + if (!es_fgets (line, DIM(line)-1, cf->fp) ) { - if (feof (cf->fp)) + if (es_feof (cf->fp)) return gpg_error (GPG_ERR_EOF); return gpg_error_from_syserror (); } cf->lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line */ - while ( (c=getc (cf->fp)) != EOF && c != '\n') + while ((c = es_getc (cf->fp)) != EOF && c != '\n') ; return gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; } while (!*p || *p == '\n' || *p == '#'); cf->item.disabled = 0; if (*p == '!') { cf->item.disabled = 1; for (p++; spacep (p); p++) ; } for (i=0; hexdigitp (p) && i < 40; p++, i++) cf->item.hexgrip[i] = (*p >= 'a'? (*p & 0xdf): *p); cf->item.hexgrip[i] = 0; if (i != 40 || !(spacep (p) || *p == '\n')) { log_error ("%s:%d: invalid formatted line\n", cf->fname, cf->lnr); return gpg_error (GPG_ERR_BAD_DATA); } ttl = strtol (p, &pend, 10); p = pend; if (!(spacep (p) || *p == '\n') || (int)ttl < -1) { log_error ("%s:%d: invalid TTL value; assuming 0\n", cf->fname, cf->lnr); cf->item.ttl = 0; } cf->item.ttl = ttl; /* Now check for key-value pairs of the form NAME[=VALUE]. */ cf->item.confirm = 0; while (*p) { for (; spacep (p) && *p != '\n'; p++) ; if (!*p || *p == '\n') break; n = strcspn (p, "= \t\n"); if (p[n] == '=') { log_error ("%s:%d: assigning a value to a flag is not yet supported; " "flag ignored\n", cf->fname, cf->lnr); p++; } else if (n == 7 && !memcmp (p, "confirm", 7)) { cf->item.confirm = 1; } else log_error ("%s:%d: invalid flag '%.*s'; ignored\n", cf->fname, cf->lnr, n, p); p += n; } /* log_debug ("%s:%d: grip=%s ttl=%d%s%s\n", */ /* cf->fname, cf->lnr, */ /* cf->item.hexgrip, cf->item.ttl, */ /* cf->item.disabled? " disabled":"", */ /* cf->item.confirm? " confirm":""); */ cf->item.valid = 1; return 0; /* Okay: valid entry found. */ } /* Search the control file CF from the beginning until a matching HEXGRIP is found; return success in this case and store true at DISABLED if the found key has been disabled. If R_TTL is not NULL a specified TTL for that key is stored there. If R_CONFIRM is not NULL it is set to 1 if the key has the confirm flag set. */ static gpg_error_t search_control_file (ssh_control_file_t cf, const char *hexgrip, int *r_disabled, int *r_ttl, int *r_confirm) { gpg_error_t err; assert (strlen (hexgrip) == 40 ); if (r_disabled) *r_disabled = 0; if (r_ttl) *r_ttl = 0; if (r_confirm) *r_confirm = 0; rewind_control_file (cf); while (!(err=read_control_file_item (cf))) { if (!cf->item.valid) continue; /* Should not happen. */ if (!strcmp (hexgrip, cf->item.hexgrip)) break; } if (!err) { if (r_disabled) *r_disabled = cf->item.disabled; if (r_ttl) *r_ttl = cf->item.ttl; if (r_confirm) *r_confirm = cf->item.confirm; } return err; } /* Add an entry to the control file to mark the key with the keygrip HEXGRIP as usable for SSH; i.e. it will be returned when ssh asks for it. FMTFPR is the fingerprint string. This function is in general used to add a key received through the ssh-add function. We can assume that the user wants to allow ssh using this key. */ static gpg_error_t add_control_entry (ctrl_t ctrl, ssh_key_type_spec_t *spec, const char *hexgrip, gcry_sexp_t key, int ttl, int confirm) { gpg_error_t err; ssh_control_file_t cf; int disabled; char *fpr_md5 = NULL; char *fpr_sha256 = NULL; (void)ctrl; err = open_control_file (&cf, 1); if (err) return err; err = search_control_file (cf, hexgrip, &disabled, NULL, NULL); if (err && gpg_err_code(err) == GPG_ERR_EOF) { struct tm *tp; time_t atime = time (NULL); err = ssh_get_fingerprint_string (key, GCRY_MD_MD5, &fpr_md5); if (err) goto out; err = ssh_get_fingerprint_string (key, GCRY_MD_SHA256, &fpr_sha256); if (err) goto out; /* Not yet in the file - add it. Because the file has been opened in append mode, we simply need to write to it. */ tp = localtime (&atime); - fprintf (cf->fp, + es_fprintf (cf->fp, ("# %s key added on: %04d-%02d-%02d %02d:%02d:%02d\n" "# Fingerprints: %s\n" "# %s\n" "%s %d%s\n"), spec->name, 1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec, fpr_md5, fpr_sha256, hexgrip, ttl, confirm? " confirm":""); } out: xfree (fpr_md5); xfree (fpr_sha256); close_control_file (cf); return 0; } /* Scan the sshcontrol file and return the TTL. */ static int ttl_from_sshcontrol (const char *hexgrip) { ssh_control_file_t cf; int disabled, ttl; if (!hexgrip || strlen (hexgrip) != 40) return 0; /* Wrong input: Use global default. */ if (open_control_file (&cf, 0)) return 0; /* Error: Use the global default TTL. */ if (search_control_file (cf, hexgrip, &disabled, &ttl, NULL) || disabled) ttl = 0; /* Use the global default if not found or disabled. */ close_control_file (cf); return ttl; } /* Scan the sshcontrol file and return the confirm flag. */ static int confirm_flag_from_sshcontrol (const char *hexgrip) { ssh_control_file_t cf; int disabled, confirm; if (!hexgrip || strlen (hexgrip) != 40) return 1; /* Wrong input: Better ask for confirmation. */ if (open_control_file (&cf, 0)) return 1; /* Error: Better ask for confirmation. */ if (search_control_file (cf, hexgrip, &disabled, NULL, &confirm) || disabled) confirm = 0; /* If not found or disabled, there is no reason to ask for confirmation. */ close_control_file (cf); return confirm; } /* Open the ssh control file for reading. This is a public version of open_control_file. The caller must use ssh_close_control_file to release the returned handle. */ ssh_control_file_t ssh_open_control_file (void) { ssh_control_file_t cf; /* Then look at all the registered and non-disabled keys. */ if (open_control_file (&cf, 0)) return NULL; return cf; } /* Close an ssh control file handle. This is the public version of close_control_file. CF may be NULL. */ void ssh_close_control_file (ssh_control_file_t cf) { close_control_file (cf); } /* Read the next item from the ssh control file. The function returns 0 if a item was read, GPG_ERR_EOF on eof or another error value. R_HEXGRIP shall either be null or a BUFFER of at least 41 byte. R_DISABLED, R_TTLm and R_CONFIRM return flags from the control file; they are only set on success. */ gpg_error_t ssh_read_control_file (ssh_control_file_t cf, char *r_hexgrip, int *r_disabled, int *r_ttl, int *r_confirm) { gpg_error_t err; do err = read_control_file_item (cf); while (!err && !cf->item.valid); if (!err) { if (r_hexgrip) strcpy (r_hexgrip, cf->item.hexgrip); if (r_disabled) *r_disabled = cf->item.disabled; if (r_ttl) *r_ttl = cf->item.ttl; if (r_confirm) *r_confirm = cf->item.confirm; } return err; } /* Search for a key with HEXGRIP in sshcontrol and return all info. */ gpg_error_t ssh_search_control_file (ssh_control_file_t cf, const char *hexgrip, int *r_disabled, int *r_ttl, int *r_confirm) { gpg_error_t err; int i; const char *s; char uphexgrip[41]; /* We need to make sure that HEXGRIP is all uppercase. The easiest way to do this and also check its length is by copying to a second buffer. */ for (i=0, s=hexgrip; i < 40 && *s; s++, i++) uphexgrip[i] = *s >= 'a'? (*s & 0xdf): *s; uphexgrip[i] = 0; if (i != 40) err = gpg_error (GPG_ERR_INV_LENGTH); else err = search_control_file (cf, uphexgrip, r_disabled, r_ttl, r_confirm); if (gpg_err_code (err) == GPG_ERR_EOF) err = gpg_error (GPG_ERR_NOT_FOUND); return err; } /* MPI lists. */ /* Free the list of MPIs MPI_LIST. */ static void mpint_list_free (gcry_mpi_t *mpi_list) { if (mpi_list) { unsigned int i; for (i = 0; mpi_list[i]; i++) gcry_mpi_release (mpi_list[i]); xfree (mpi_list); } } /* Receive key material MPIs from STREAM according to KEY_SPEC; depending on SECRET expect a public key or secret key. CERT is the certificate blob used if KEY_SPEC indicates the certificate format; it needs to be positioned to the end of the nonce. The newly allocated list of MPIs is stored in MPI_LIST. Returns usual error code. */ static gpg_error_t ssh_receive_mpint_list (estream_t stream, int secret, ssh_key_type_spec_t *spec, estream_t cert, gcry_mpi_t **mpi_list) { const char *elems_public; unsigned int elems_n; const char *elems; int elem_is_secret; gcry_mpi_t *mpis = NULL; gpg_error_t err = 0; unsigned int i; if (secret) elems = spec->elems_key_secret; else elems = spec->elems_key_public; elems_n = strlen (elems); elems_public = spec->elems_key_public; /* Check that either both, CERT and the WITH_CERT flag, are given or none of them. */ if (!(!!(spec->flags & SPEC_FLAG_WITH_CERT) ^ !cert)) { err = gpg_error (GPG_ERR_INV_CERT_OBJ); goto out; } mpis = xtrycalloc (elems_n + 1, sizeof *mpis ); if (!mpis) { err = gpg_error_from_syserror (); goto out; } elem_is_secret = 0; for (i = 0; i < elems_n; i++) { if (secret) elem_is_secret = !strchr (elems_public, elems[i]); if (cert && !elem_is_secret) err = stream_read_mpi (cert, elem_is_secret, &mpis[i]); else err = stream_read_mpi (stream, elem_is_secret, &mpis[i]); if (err) goto out; } *mpi_list = mpis; mpis = NULL; out: if (err) mpint_list_free (mpis); return err; } /* Key modifier function for RSA. */ static gpg_error_t ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis) { gcry_mpi_t p; gcry_mpi_t q; gcry_mpi_t u; if (strcmp (elems, "nedupq")) /* Modifying only necessary for secret keys. */ goto out; u = mpis[3]; p = mpis[4]; q = mpis[5]; if (gcry_mpi_cmp (p, q) > 0) { /* P shall be smaller then Q! Swap primes. iqmp becomes u. */ gcry_mpi_t tmp; tmp = mpis[4]; mpis[4] = mpis[5]; mpis[5] = tmp; } else /* U needs to be recomputed. */ gcry_mpi_invm (u, p, q); out: return 0; } /* Signature encoder function for RSA. */ static gpg_error_t ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t s_signature) { gpg_error_t err = 0; gcry_sexp_t valuelist = NULL; gcry_sexp_t sublist = NULL; gcry_mpi_t sig_value = NULL; gcry_mpi_t *mpis = NULL; const char *elems; size_t elems_n; int i; unsigned char *data; size_t data_n; gcry_mpi_t s; valuelist = gcry_sexp_nth (s_signature, 1); if (!valuelist) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } elems = spec->elems_signature; elems_n = strlen (elems); mpis = xtrycalloc (elems_n + 1, sizeof *mpis); if (!mpis) { err = gpg_error_from_syserror (); goto out; } for (i = 0; i < elems_n; i++) { sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1); if (!sublist) { err = gpg_error (GPG_ERR_INV_SEXP); break; } sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG); if (!sig_value) { err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */ break; } gcry_sexp_release (sublist); sublist = NULL; mpis[i] = sig_value; } if (err) goto out; /* RSA specific */ s = mpis[0]; err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, s); if (err) goto out; err = stream_write_string (signature_blob, data, data_n); xfree (data); out: gcry_sexp_release (valuelist); gcry_sexp_release (sublist); mpint_list_free (mpis); return err; } /* Signature encoder function for DSA. */ static gpg_error_t ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec, estream_t signature_blob, gcry_sexp_t s_signature) { gpg_error_t err = 0; gcry_sexp_t valuelist = NULL; gcry_sexp_t sublist = NULL; gcry_mpi_t sig_value = NULL; gcry_mpi_t *mpis = NULL; const char *elems; size_t elems_n; int i; unsigned char buffer[SSH_DSA_SIGNATURE_PADDING * SSH_DSA_SIGNATURE_ELEMS]; unsigned char *data = NULL; size_t data_n; valuelist = gcry_sexp_nth (s_signature, 1); if (!valuelist) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } elems = spec->elems_signature; elems_n = strlen (elems); mpis = xtrycalloc (elems_n + 1, sizeof *mpis); if (!mpis) { err = gpg_error_from_syserror (); goto out; } for (i = 0; i < elems_n; i++) { sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1); if (!sublist) { err = gpg_error (GPG_ERR_INV_SEXP); break; } sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG); if (!sig_value) { err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */ break; } gcry_sexp_release (sublist); sublist = NULL; mpis[i] = sig_value; } if (err) goto out; /* DSA specific code. */ /* FIXME: Why this complicated code? Why collecting boths mpis in a buffer instead of writing them out one after the other? */ for (i = 0; i < 2; i++) { err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, mpis[i]); if (err) break; if (data_n > SSH_DSA_SIGNATURE_PADDING) { err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */ break; } memset (buffer + (i * SSH_DSA_SIGNATURE_PADDING), 0, SSH_DSA_SIGNATURE_PADDING - data_n); memcpy (buffer + (i * SSH_DSA_SIGNATURE_PADDING) + (SSH_DSA_SIGNATURE_PADDING - data_n), data, data_n); xfree (data); data = NULL; } if (err) goto out; err = stream_write_string (signature_blob, buffer, sizeof (buffer)); out: xfree (data); gcry_sexp_release (valuelist); gcry_sexp_release (sublist); mpint_list_free (mpis); return err; } /* Signature encoder function for ECDSA. */ static gpg_error_t ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec, estream_t stream, gcry_sexp_t s_signature) { gpg_error_t err = 0; gcry_sexp_t valuelist = NULL; gcry_sexp_t sublist = NULL; gcry_mpi_t sig_value = NULL; gcry_mpi_t *mpis = NULL; const char *elems; size_t elems_n; int i; unsigned char *data[2] = {NULL, NULL}; size_t data_n[2]; size_t innerlen; valuelist = gcry_sexp_nth (s_signature, 1); if (!valuelist) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } elems = spec->elems_signature; elems_n = strlen (elems); mpis = xtrycalloc (elems_n + 1, sizeof *mpis); if (!mpis) { err = gpg_error_from_syserror (); goto out; } for (i = 0; i < elems_n; i++) { sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1); if (!sublist) { err = gpg_error (GPG_ERR_INV_SEXP); break; } sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG); if (!sig_value) { err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */ break; } gcry_sexp_release (sublist); sublist = NULL; mpis[i] = sig_value; } if (err) goto out; /* ECDSA specific */ innerlen = 0; for (i = 0; i < DIM(data); i++) { err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &data[i], &data_n[i], mpis[i]); if (err) goto out; innerlen += 4 + data_n[i]; } err = stream_write_uint32 (stream, innerlen); if (err) goto out; for (i = 0; i < DIM(data); i++) { err = stream_write_string (stream, data[i], data_n[i]); if (err) goto out; } out: for (i = 0; i < DIM(data); i++) xfree (data[i]); gcry_sexp_release (valuelist); gcry_sexp_release (sublist); mpint_list_free (mpis); return err; } /* Signature encoder function for EdDSA. */ static gpg_error_t ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec, estream_t stream, gcry_sexp_t s_signature) { gpg_error_t err = 0; gcry_sexp_t valuelist = NULL; gcry_sexp_t sublist = NULL; const char *elems; size_t elems_n; int i; unsigned char *data[2] = {NULL, NULL}; size_t data_n[2]; size_t totallen = 0; valuelist = gcry_sexp_nth (s_signature, 1); if (!valuelist) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } elems = spec->elems_signature; elems_n = strlen (elems); if (elems_n != DIM(data)) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } for (i = 0; i < DIM(data); i++) { sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1); if (!sublist) { err = gpg_error (GPG_ERR_INV_SEXP); break; } data[i] = gcry_sexp_nth_buffer (sublist, 1, &data_n[i]); if (!data[i]) { err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */ break; } totallen += data_n[i]; gcry_sexp_release (sublist); sublist = NULL; } if (err) goto out; err = stream_write_uint32 (stream, totallen); if (err) goto out; for (i = 0; i < DIM(data); i++) { err = stream_write_data (stream, data[i], data_n[i]); if (err) goto out; } out: for (i = 0; i < DIM(data); i++) xfree (data[i]); gcry_sexp_release (valuelist); gcry_sexp_release (sublist); return err; } /* S-Expressions. */ /* This function constructs a new S-Expression for the key identified by the KEY_SPEC, SECRET, CURVE_NAME, MPIS, and COMMENT, which is to be stored at R_SEXP. Returns an error code. */ static gpg_error_t sexp_key_construct (gcry_sexp_t *r_sexp, ssh_key_type_spec_t key_spec, int secret, const char *curve_name, gcry_mpi_t *mpis, const char *comment) { gpg_error_t err; gcry_sexp_t sexp_new = NULL; void *formatbuf = NULL; void **arg_list = NULL; estream_t format = NULL; char *algo_name = NULL; if ((key_spec.flags & SPEC_FLAG_IS_EdDSA)) { /* It is much easier and more readable to use a separate code path for EdDSA. */ if (!curve_name) err = gpg_error (GPG_ERR_INV_CURVE); else if (!mpis[0] || !gcry_mpi_get_flag (mpis[0], GCRYMPI_FLAG_OPAQUE)) err = gpg_error (GPG_ERR_BAD_PUBKEY); else if (secret && (!mpis[1] || !gcry_mpi_get_flag (mpis[1], GCRYMPI_FLAG_OPAQUE))) err = gpg_error (GPG_ERR_BAD_SECKEY); else if (secret) err = gcry_sexp_build (&sexp_new, NULL, "(private-key(ecc(curve %s)" "(flags eddsa)(q %m)(d %m))" "(comment%s))", curve_name, mpis[0], mpis[1], comment? comment:""); else err = gcry_sexp_build (&sexp_new, NULL, "(public-key(ecc(curve %s)" "(flags eddsa)(q %m))" "(comment%s))", curve_name, mpis[0], comment? comment:""); } else { const char *key_identifier[] = { "public-key", "private-key" }; int arg_idx; const char *elems; size_t elems_n; unsigned int i, j; if (secret) elems = key_spec.elems_sexp_order; else elems = key_spec.elems_key_public; elems_n = strlen (elems); format = es_fopenmem (0, "a+b"); if (!format) { err = gpg_error_from_syserror (); goto out; } /* Key identifier, algorithm identifier, mpis, comment, and a NULL as a safeguard. */ arg_list = xtrymalloc (sizeof (*arg_list) * (2 + 1 + elems_n + 1 + 1)); if (!arg_list) { err = gpg_error_from_syserror (); goto out; } arg_idx = 0; es_fputs ("(%s(%s", format); arg_list[arg_idx++] = &key_identifier[secret]; algo_name = xtrystrdup (gcry_pk_algo_name (key_spec.algo)); if (!algo_name) { err = gpg_error_from_syserror (); goto out; } strlwr (algo_name); arg_list[arg_idx++] = &algo_name; if (curve_name) { es_fputs ("(curve%s)", format); arg_list[arg_idx++] = &curve_name; } for (i = 0; i < elems_n; i++) { es_fprintf (format, "(%c%%m)", elems[i]); if (secret) { for (j = 0; j < elems_n; j++) if (key_spec.elems_key_secret[j] == elems[i]) break; } else j = i; arg_list[arg_idx++] = &mpis[j]; } es_fputs (")(comment%s))", format); arg_list[arg_idx++] = &comment; arg_list[arg_idx] = NULL; es_putc (0, format); if (es_ferror (format)) { err = gpg_error_from_syserror (); goto out; } if (es_fclose_snatch (format, &formatbuf, NULL)) { err = gpg_error_from_syserror (); goto out; } format = NULL; err = gcry_sexp_build_array (&sexp_new, NULL, formatbuf, arg_list); } if (!err) *r_sexp = sexp_new; out: es_fclose (format); xfree (arg_list); xfree (formatbuf); xfree (algo_name); return err; } /* This function extracts the key from the s-expression SEXP according to KEY_SPEC and stores it in ssh format at (R_BLOB, R_BLOBLEN). If WITH_SECRET is true, the secret key parts are also extracted if possible. Returns 0 on success or an error code. Note that data stored at R_BLOB must be freed using es_free! */ static gpg_error_t ssh_key_to_blob (gcry_sexp_t sexp, int with_secret, ssh_key_type_spec_t key_spec, void **r_blob, size_t *r_blob_size) { gpg_error_t err = 0; gcry_sexp_t value_list = NULL; gcry_sexp_t value_pair = NULL; estream_t stream = NULL; void *blob = NULL; size_t blob_size; const char *elems, *p_elems; const char *data; size_t datalen; *r_blob = NULL; *r_blob_size = 0; stream = es_fopenmem (0, "r+b"); if (!stream) { err = gpg_error_from_syserror (); goto out; } /* Get the type of the key expression. */ data = gcry_sexp_nth_data (sexp, 0, &datalen); if (!data) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } if ((datalen == 10 && !strncmp (data, "public-key", 10)) || (datalen == 21 && !strncmp (data, "protected-private-key", 21)) || (datalen == 20 && !strncmp (data, "shadowed-private-key", 20))) elems = key_spec.elems_key_public; else if (datalen == 11 && !strncmp (data, "private-key", 11)) elems = with_secret? key_spec.elems_key_secret : key_spec.elems_key_public; else { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } /* Get key value list. */ value_list = gcry_sexp_cadr (sexp); if (!value_list) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } /* Write the ssh algorithm identifier. */ if ((key_spec.flags & SPEC_FLAG_IS_ECDSA)) { /* Map the curve name to the ssh name. */ const char *name, *sshname, *canon_name; name = gcry_pk_get_curve (sexp, 0, NULL); if (!name) { err = gpg_error (GPG_ERR_INV_CURVE); goto out; } sshname = ssh_identifier_from_curve_name (name, &canon_name); if (!sshname) { err = gpg_error (GPG_ERR_UNKNOWN_CURVE); goto out; } err = stream_write_cstring (stream, sshname); if (err) goto out; err = stream_write_cstring (stream, canon_name); if (err) goto out; } else { /* Note: This is also used for EdDSA. */ err = stream_write_cstring (stream, key_spec.ssh_identifier); if (err) goto out; } /* Write the parameters. */ for (p_elems = elems; *p_elems; p_elems++) { gcry_sexp_release (value_pair); value_pair = gcry_sexp_find_token (value_list, p_elems, 1); if (!value_pair) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } if ((key_spec.flags & SPEC_FLAG_IS_EdDSA)) { data = gcry_sexp_nth_data (value_pair, 1, &datalen); if (!data) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } if (*p_elems == 'q' && datalen) { /* Remove the prefix 0x40. */ data++; datalen--; } err = stream_write_string (stream, data, datalen); if (err) goto out; } else { gcry_mpi_t mpi; /* Note that we need to use STD format; i.e. prepend a 0x00 to indicate a positive number if the high bit is set. */ mpi = gcry_sexp_nth_mpi (value_pair, 1, GCRYMPI_FMT_STD); if (!mpi) { err = gpg_error (GPG_ERR_INV_SEXP); goto out; } err = stream_write_mpi (stream, mpi); gcry_mpi_release (mpi); if (err) goto out; } } if (es_fclose_snatch (stream, &blob, &blob_size)) { err = gpg_error_from_syserror (); goto out; } stream = NULL; *r_blob = blob; blob = NULL; *r_blob_size = blob_size; out: gcry_sexp_release (value_list); gcry_sexp_release (value_pair); es_fclose (stream); es_free (blob); return err; } /* Key I/O. */ /* Search for a key specification entry. If SSH_NAME is not NULL, search for an entry whose "ssh_name" is equal to SSH_NAME; otherwise, search for an entry whose algorithm is equal to ALGO. Store found entry in SPEC on success, return error otherwise. */ static gpg_error_t ssh_key_type_lookup (const char *ssh_name, int algo, ssh_key_type_spec_t *spec) { gpg_error_t err; unsigned int i; for (i = 0; i < DIM (ssh_key_types); i++) if ((ssh_name && (! strcmp (ssh_name, ssh_key_types[i].ssh_identifier))) || algo == ssh_key_types[i].algo) break; if (i == DIM (ssh_key_types)) err = gpg_error (GPG_ERR_NOT_FOUND); else { *spec = ssh_key_types[i]; err = 0; } return err; } /* Receive a key from STREAM, according to the key specification given as KEY_SPEC. Depending on SECRET, receive a secret or a public key. If READ_COMMENT is true, receive a comment string as well. Constructs a new S-Expression from received data and stores it in KEY_NEW. Returns zero on success or an error code. */ static gpg_error_t ssh_receive_key (estream_t stream, gcry_sexp_t *key_new, int secret, int read_comment, ssh_key_type_spec_t *key_spec) { gpg_error_t err; char *key_type = NULL; char *comment = NULL; estream_t cert = NULL; gcry_sexp_t key = NULL; ssh_key_type_spec_t spec; gcry_mpi_t *mpi_list = NULL; const char *elems; const char *curve_name = NULL; err = stream_read_cstring (stream, &key_type); if (err) goto out; err = ssh_key_type_lookup (key_type, 0, &spec); if (err) goto out; if ((spec.flags & SPEC_FLAG_WITH_CERT)) { /* This is an OpenSSH certificate+private key. The certificate is an SSH string and which we store in an estream object. */ unsigned char *buffer; u32 buflen; char *cert_key_type; err = stream_read_string (stream, 0, &buffer, &buflen); if (err) goto out; cert = es_fopenmem_init (0, "rb", buffer, buflen); xfree (buffer); if (!cert) { err = gpg_error_from_syserror (); goto out; } /* Check that the key type matches. */ err = stream_read_cstring (cert, &cert_key_type); if (err) goto out; if (strcmp (cert_key_type, key_type) ) { xfree (cert_key_type); log_error ("key types in received ssh certificate do not match\n"); err = gpg_error (GPG_ERR_INV_CERT_OBJ); goto out; } xfree (cert_key_type); /* Skip the nonce. */ err = stream_read_string (cert, 0, NULL, NULL); if (err) goto out; } if ((spec.flags & SPEC_FLAG_IS_EdDSA)) { /* The format of an EdDSA key is: * string key_type ("ssh-ed25519") * string public_key * string private_key * * Note that the private key is the concatenation of the private * key with the public key. Thus there's are 64 bytes; however * we only want the real 32 byte private key - Libgcrypt expects * this. */ mpi_list = xtrycalloc (3, sizeof *mpi_list); if (!mpi_list) { err = gpg_error_from_syserror (); goto out; } err = stream_read_blob (cert? cert : stream, 0, &mpi_list[0]); if (err) goto out; if (secret) { u32 len = 0; unsigned char *buffer; /* Read string length. */ err = stream_read_uint32 (stream, &len); if (err) goto out; if (len != 32 && len != 64) { err = gpg_error (GPG_ERR_BAD_SECKEY); goto out; } buffer = xtrymalloc_secure (32); if (!buffer) { err = gpg_error_from_syserror (); goto out; } err = stream_read_data (stream, buffer, 32); if (err) { xfree (buffer); goto out; } mpi_list[1] = gcry_mpi_set_opaque (NULL, buffer, 8*32); buffer = NULL; if (len == 64) { err = stream_read_skip (stream, 32); if (err) goto out; } } } else if ((spec.flags & SPEC_FLAG_IS_ECDSA)) { /* The format of an ECDSA key is: * string key_type ("ecdsa-sha2-nistp256" | * "ecdsa-sha2-nistp384" | * "ecdsa-sha2-nistp521" ) * string ecdsa_curve_name * string ecdsa_public_key * mpint ecdsa_private * * Note that we use the mpint reader instead of the string * reader for ecsa_public_key. For the certificate variante * ecdsa_curve_name+ecdsa_public_key are replaced by the * certificate. */ unsigned char *buffer; err = stream_read_string (cert? cert : stream, 0, &buffer, NULL); if (err) goto out; /* Get the canonical name. Should be the same as the read * string but we use this mapping to validate that name. */ if (!ssh_identifier_from_curve_name (buffer, &curve_name)) { err = gpg_error (GPG_ERR_UNKNOWN_CURVE); xfree (buffer); goto out; } xfree (buffer); err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list); if (err) goto out; } else { err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list); if (err) goto out; } if (read_comment) { err = stream_read_cstring (stream, &comment); if (err) goto out; } if (secret) elems = spec.elems_key_secret; else elems = spec.elems_key_public; if (spec.key_modifier) { err = (*spec.key_modifier) (elems, mpi_list); if (err) goto out; } if ((spec.flags & SPEC_FLAG_IS_EdDSA)) { if (secret) { err = gcry_sexp_build (&key, NULL, "(private-key(ecc(curve \"Ed25519\")" "(flags eddsa)(q %m)(d %m))" "(comment%s))", mpi_list[0], mpi_list[1], comment? comment:""); } else { err = gcry_sexp_build (&key, NULL, "(public-key(ecc(curve \"Ed25519\")" "(flags eddsa)(q %m))" "(comment%s))", mpi_list[0], comment? comment:""); } } else { err = sexp_key_construct (&key, spec, secret, curve_name, mpi_list, comment? comment:""); if (err) goto out; } if (key_spec) *key_spec = spec; *key_new = key; out: es_fclose (cert); mpint_list_free (mpi_list); xfree (key_type); xfree (comment); return err; } /* Write the public key from KEY to STREAM in SSH key format. If OVERRIDE_COMMENT is not NULL, it will be used instead of the comment stored in the key. */ static gpg_error_t ssh_send_key_public (estream_t stream, gcry_sexp_t key, const char *override_comment) { ssh_key_type_spec_t spec; int algo; char *comment = NULL; void *blob = NULL; size_t bloblen; gpg_error_t err = 0; algo = get_pk_algo_from_key (key); if (algo == 0) goto out; err = ssh_key_type_lookup (NULL, algo, &spec); if (err) goto out; err = ssh_key_to_blob (key, 0, spec, &blob, &bloblen); if (err) goto out; err = stream_write_string (stream, blob, bloblen); if (err) goto out; if (override_comment) err = stream_write_cstring (stream, override_comment); else { err = ssh_key_extract_comment (key, &comment); if (err) err = stream_write_cstring (stream, "(none)"); else err = stream_write_cstring (stream, comment); } if (err) goto out; out: xfree (comment); es_free (blob); return err; } /* Read a public key out of BLOB/BLOB_SIZE according to the key specification given as KEY_SPEC, storing the new key in KEY_PUBLIC. Returns zero on success or an error code. */ static gpg_error_t ssh_read_key_public_from_blob (unsigned char *blob, size_t blob_size, gcry_sexp_t *key_public, ssh_key_type_spec_t *key_spec) { gpg_error_t err; estream_t blob_stream; blob_stream = es_fopenmem (0, "r+b"); if (!blob_stream) { err = gpg_error_from_syserror (); goto out; } err = stream_write_data (blob_stream, blob, blob_size); if (err) goto out; err = es_fseek (blob_stream, 0, SEEK_SET); if (err) goto out; err = ssh_receive_key (blob_stream, key_public, 0, 0, key_spec); out: es_fclose (blob_stream); return err; } /* This function calculates the key grip for the key contained in the S-Expression KEY and writes it to BUFFER, which must be large enough to hold it. Returns usual error code. */ static gpg_error_t ssh_key_grip (gcry_sexp_t key, unsigned char *buffer) { if (!gcry_pk_get_keygrip (key, buffer)) { gpg_error_t err = gcry_pk_testkey (key); return err? err : gpg_error (GPG_ERR_INTERNAL); } return 0; } static gpg_error_t card_key_list (ctrl_t ctrl, char **r_serialno, strlist_t *result) { gpg_error_t err; *r_serialno = NULL; *result = NULL; err = agent_card_serialno (ctrl, r_serialno, NULL); if (err) { if (gpg_err_code (err) != GPG_ERR_ENODEV && opt.verbose) log_info (_("error getting serial number of card: %s\n"), gpg_strerror (err)); /* Nothing available. */ return 0; } err = agent_card_cardlist (ctrl, result); if (err) { xfree (*r_serialno); *r_serialno = NULL; } return err; } /* Check whether a smartcard is available and whether it has a usable key. Store a copy of that key at R_PK and return 0. If no key is available store NULL at R_PK and return an error code. If CARDSN is not NULL, a string with the serial number of the card will be a malloced and stored there. */ static gpg_error_t card_key_available (ctrl_t ctrl, gcry_sexp_t *r_pk, char **cardsn) { gpg_error_t err; char *authkeyid; char *serialno = NULL; unsigned char *pkbuf; size_t pkbuflen; gcry_sexp_t s_pk; unsigned char grip[20]; *r_pk = NULL; if (cardsn) *cardsn = NULL; /* First see whether a card is available and whether the application is supported. */ err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid); if ( gpg_err_code (err) == GPG_ERR_CARD_REMOVED ) { /* Ask for the serial number to reset the card. */ err = agent_card_serialno (ctrl, &serialno, NULL); if (err) { if (opt.verbose) log_info (_("error getting serial number of card: %s\n"), gpg_strerror (err)); return err; } log_info (_("detected card with S/N: %s\n"), serialno); err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid); } if (err) { log_error (_("no authentication key for ssh on card: %s\n"), gpg_strerror (err)); xfree (serialno); return err; } /* Get the S/N if we don't have it yet. Use the fast getattr method. */ if (!serialno && (err = agent_card_getattr (ctrl, "SERIALNO", &serialno)) ) { log_error (_("error getting serial number of card: %s\n"), gpg_strerror (err)); xfree (authkeyid); return err; } /* Read the public key. */ err = agent_card_readkey (ctrl, authkeyid, &pkbuf); if (err) { if (opt.verbose) log_info (_("no suitable card key found: %s\n"), gpg_strerror (err)); xfree (serialno); xfree (authkeyid); return err; } pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL); err = gcry_sexp_sscan (&s_pk, NULL, (char*)pkbuf, pkbuflen); if (err) { log_error ("failed to build S-Exp from received card key: %s\n", gpg_strerror (err)); xfree (pkbuf); xfree (serialno); xfree (authkeyid); return err; } err = ssh_key_grip (s_pk, grip); if (err) { log_debug ("error computing keygrip from received card key: %s\n", gcry_strerror (err)); xfree (pkbuf); gcry_sexp_release (s_pk); xfree (serialno); xfree (authkeyid); return err; } if ( agent_key_available (grip) ) { /* (Shadow)-key is not available in our key storage. */ err = agent_write_shadow_key (grip, serialno, authkeyid, pkbuf, 0); if (err) { xfree (pkbuf); gcry_sexp_release (s_pk); xfree (serialno); xfree (authkeyid); return err; } } if (cardsn) { char *dispsn; /* If the card handler is able to return a short serialnumber, use that one, else use the complete serialno. */ if (!agent_card_getattr (ctrl, "$DISPSERIALNO", &dispsn)) { *cardsn = xtryasprintf ("cardno:%s", dispsn); xfree (dispsn); } else *cardsn = xtryasprintf ("cardno:%s", serialno); if (!*cardsn) { err = gpg_error_from_syserror (); xfree (pkbuf); gcry_sexp_release (s_pk); xfree (serialno); xfree (authkeyid); return err; } } xfree (pkbuf); xfree (serialno); xfree (authkeyid); *r_pk = s_pk; return 0; } /* Request handler. Each handler is provided with a CTRL context, a REQUEST object and a RESPONSE object. The actual request is to be read from REQUEST, the response needs to be written to RESPONSE. */ /* Handler for the "request_identities" command. */ static gpg_error_t ssh_handler_request_identities (ctrl_t ctrl, estream_t request, estream_t response) { u32 key_counter; estream_t key_blobs; gcry_sexp_t key_public; gpg_error_t err; int ret; ssh_control_file_t cf = NULL; gpg_error_t ret_err; (void)request; /* Prepare buffer stream. */ key_public = NULL; key_counter = 0; key_blobs = es_fopenmem (0, "r+b"); if (! key_blobs) { err = gpg_error_from_syserror (); goto out; } /* First check whether a key is currently available in the card reader - this should be allowed even without being listed in sshcontrol. */ if (!opt.disable_scdaemon) { char *serialno; strlist_t card_list, sl; err = card_key_list (ctrl, &serialno, &card_list); if (err) { if (opt.verbose) log_info (_("error getting list of cards: %s\n"), gpg_strerror (err)); goto scd_out; } for (sl = card_list; sl; sl = sl->next) { char *serialno0; char *cardsn; err = agent_card_serialno (ctrl, &serialno0, sl->d); if (err) { if (opt.verbose) log_info (_("error getting serial number of card: %s\n"), gpg_strerror (err)); continue; } xfree (serialno0); if (card_key_available (ctrl, &key_public, &cardsn)) continue; err = ssh_send_key_public (key_blobs, key_public, cardsn); if (err && opt.verbose) gcry_log_debugsxp ("pubkey", key_public); gcry_sexp_release (key_public); key_public = NULL; xfree (cardsn); if (err) { xfree (serialno); free_strlist (card_list); goto out; } key_counter++; } xfree (serialno); free_strlist (card_list); } scd_out: /* Then look at all the registered and non-disabled keys. */ err = open_control_file (&cf, 0); if (err) goto out; while (!read_control_file_item (cf)) { unsigned char grip[20]; if (!cf->item.valid) continue; /* Should not happen. */ if (cf->item.disabled) continue; assert (strlen (cf->item.hexgrip) == 40); hex2bin (cf->item.hexgrip, grip, sizeof (grip)); err = agent_public_key_from_file (ctrl, grip, &key_public); if (err) { log_error ("%s:%d: key '%s' skipped: %s\n", cf->fname, cf->lnr, cf->item.hexgrip, gpg_strerror (err)); continue; } err = ssh_send_key_public (key_blobs, key_public, NULL); if (err) goto out; gcry_sexp_release (key_public); key_public = NULL; key_counter++; } err = 0; ret = es_fseek (key_blobs, 0, SEEK_SET); if (ret) { err = gpg_error_from_syserror (); goto out; } out: /* Send response. */ gcry_sexp_release (key_public); if (!err) { ret_err = stream_write_byte (response, SSH_RESPONSE_IDENTITIES_ANSWER); if (!ret_err) ret_err = stream_write_uint32 (response, key_counter); if (!ret_err) ret_err = stream_copy (response, key_blobs); } else { log_error ("ssh request identities failed: %s <%s>\n", gpg_strerror (err), gpg_strsource (err)); ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); } es_fclose (key_blobs); close_control_file (cf); return ret_err; } /* This function hashes the data contained in DATA of size DATA_N according to the message digest algorithm specified by MD_ALGORITHM and writes the message digest to HASH, which needs to large enough for the digest. */ static gpg_error_t data_hash (unsigned char *data, size_t data_n, int md_algorithm, unsigned char *hash) { gcry_md_hash_buffer (md_algorithm, hash, data, data_n); return 0; } /* This function signs the data described by CTRL. If HASH is not NULL, (HASH,HASHLEN) overrides the hash stored in CTRL. This is to allow the use of signature algorithms that implement the hashing internally (e.g. Ed25519). On success the created signature is stored in ssh format at R_SIG and it's size at R_SIGLEN; the caller must use es_free to releaase this memory. */ static gpg_error_t data_sign (ctrl_t ctrl, ssh_key_type_spec_t *spec, const void *hash, size_t hashlen, unsigned char **r_sig, size_t *r_siglen) { gpg_error_t err; gcry_sexp_t signature_sexp = NULL; estream_t stream = NULL; void *blob = NULL; size_t bloblen; char hexgrip[40+1]; *r_sig = NULL; *r_siglen = 0; /* Quick check to see whether we have a valid keygrip and convert it to hex. */ if (!ctrl->have_keygrip) { err = gpg_error (GPG_ERR_NO_SECKEY); goto out; } bin2hex (ctrl->keygrip, 20, hexgrip); /* Ask for confirmation if needed. */ if (confirm_flag_from_sshcontrol (hexgrip)) { gcry_sexp_t key; char *fpr, *prompt; char *comment = NULL; err = agent_raw_key_from_file (ctrl, ctrl->keygrip, &key); if (err) goto out; err = ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest, &fpr); if (!err) { gcry_sexp_t tmpsxp = gcry_sexp_find_token (key, "comment", 0); if (tmpsxp) comment = gcry_sexp_nth_string (tmpsxp, 1); gcry_sexp_release (tmpsxp); } gcry_sexp_release (key); if (err) goto out; prompt = xtryasprintf (L_("An ssh process requested the use of key%%0A" " %s%%0A" " (%s)%%0A" "Do you want to allow this?"), fpr, comment? comment:""); xfree (fpr); gcry_free (comment); err = agent_get_confirmation (ctrl, prompt, L_("Allow"), L_("Deny"), 0); xfree (prompt); if (err) goto out; } /* Create signature. */ ctrl->use_auth_call = 1; err = agent_pksign_do (ctrl, NULL, L_("Please enter the passphrase " "for the ssh key%%0A %F%%0A (%c)"), &signature_sexp, CACHE_MODE_SSH, ttl_from_sshcontrol, hash, hashlen); ctrl->use_auth_call = 0; if (err) goto out; stream = es_fopenmem (0, "r+b"); if (!stream) { err = gpg_error_from_syserror (); goto out; } err = stream_write_cstring (stream, spec->ssh_identifier); if (err) goto out; err = spec->signature_encoder (spec, stream, signature_sexp); if (err) goto out; err = es_fclose_snatch (stream, &blob, &bloblen); if (err) goto out; stream = NULL; *r_sig = blob; blob = NULL; *r_siglen = bloblen; out: xfree (blob); es_fclose (stream); gcry_sexp_release (signature_sexp); return err; } /* Handler for the "sign_request" command. */ static gpg_error_t ssh_handler_sign_request (ctrl_t ctrl, estream_t request, estream_t response) { gcry_sexp_t key = NULL; ssh_key_type_spec_t spec; unsigned char hash[MAX_DIGEST_LEN]; unsigned int hash_n; unsigned char key_grip[20]; unsigned char *key_blob = NULL; u32 key_blob_size; unsigned char *data = NULL; unsigned char *sig = NULL; size_t sig_n; u32 data_size; gpg_error_t err; gpg_error_t ret_err; int hash_algo; /* Receive key. */ err = stream_read_string (request, 0, &key_blob, &key_blob_size); if (err) goto out; err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, &spec); if (err) goto out; /* Receive data to sign. */ err = stream_read_string (request, 0, &data, &data_size); if (err) goto out; /* Flag processing. */ { u32 flags; err = stream_read_uint32 (request, &flags); if (err) goto out; if (spec.algo == GCRY_PK_RSA) { if ((flags & SSH_AGENT_RSA_SHA2_512)) { flags &= ~SSH_AGENT_RSA_SHA2_512; spec.ssh_identifier = "rsa-sha2-512"; spec.hash_algo = GCRY_MD_SHA512; } if ((flags & SSH_AGENT_RSA_SHA2_256)) { /* Note: We prefer SHA256 over SHA512. */ flags &= ~SSH_AGENT_RSA_SHA2_256; spec.ssh_identifier = "rsa-sha2-256"; spec.hash_algo = GCRY_MD_SHA256; } } /* Some flag is present that we do not know about. Note that * processed or known flags have been cleared at this point. */ if (flags) { err = gpg_error (GPG_ERR_UNKNOWN_OPTION); goto out; } } hash_algo = spec.hash_algo; if (!hash_algo) hash_algo = GCRY_MD_SHA1; /* Use the default. */ ctrl->digest.algo = hash_algo; if ((spec.flags & SPEC_FLAG_USE_PKCS1V2)) ctrl->digest.raw_value = 0; else ctrl->digest.raw_value = 1; /* Calculate key grip. */ err = ssh_key_grip (key, key_grip); if (err) goto out; ctrl->have_keygrip = 1; memcpy (ctrl->keygrip, key_grip, 20); /* Hash data unless we use EdDSA. */ if ((spec.flags & SPEC_FLAG_IS_EdDSA)) { ctrl->digest.valuelen = 0; } else { hash_n = gcry_md_get_algo_dlen (hash_algo); if (!hash_n) { err = gpg_error (GPG_ERR_INTERNAL); goto out; } err = data_hash (data, data_size, hash_algo, hash); if (err) goto out; memcpy (ctrl->digest.value, hash, hash_n); ctrl->digest.valuelen = hash_n; } /* Sign data. */ if ((spec.flags & SPEC_FLAG_IS_EdDSA)) err = data_sign (ctrl, &spec, data, data_size, &sig, &sig_n); else err = data_sign (ctrl, &spec, NULL, 0, &sig, &sig_n); out: /* Done. */ if (!err) { ret_err = stream_write_byte (response, SSH_RESPONSE_SIGN_RESPONSE); if (ret_err) goto leave; ret_err = stream_write_string (response, sig, sig_n); if (ret_err) goto leave; } else { log_error ("ssh sign request failed: %s <%s>\n", gpg_strerror (err), gpg_strsource (err)); ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); if (ret_err) goto leave; } leave: gcry_sexp_release (key); xfree (key_blob); xfree (data); es_free (sig); return ret_err; } /* This function extracts the comment contained in the key s-expression KEY and stores a copy in COMMENT. Returns usual error code. */ static gpg_error_t ssh_key_extract_comment (gcry_sexp_t key, char **r_comment) { gcry_sexp_t comment_list; *r_comment = NULL; comment_list = gcry_sexp_find_token (key, "comment", 0); if (!comment_list) return gpg_error (GPG_ERR_INV_SEXP); *r_comment = gcry_sexp_nth_string (comment_list, 1); gcry_sexp_release (comment_list); if (!*r_comment) return gpg_error (GPG_ERR_INV_SEXP); return 0; } /* This function converts the key contained in the S-Expression KEY into a buffer, which is protected by the passphrase PASSPHRASE. If PASSPHRASE is the empty passphrase, the key is not protected. Returns usual error code. */ static gpg_error_t ssh_key_to_protected_buffer (gcry_sexp_t key, const char *passphrase, unsigned char **buffer, size_t *buffer_n) { unsigned char *buffer_new; unsigned int buffer_new_n; gpg_error_t err; buffer_new_n = gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, NULL, 0); buffer_new = xtrymalloc_secure (buffer_new_n); if (! buffer_new) { err = gpg_error_from_syserror (); goto out; } buffer_new_n = gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, buffer_new, buffer_new_n); if (*passphrase) err = agent_protect (buffer_new, passphrase, buffer, buffer_n, 0, -1); else { /* The key derivation function does not support zero length * strings. Store key unprotected if the user wishes so. */ *buffer = buffer_new; *buffer_n = buffer_new_n; buffer_new = NULL; err = 0; } out: xfree (buffer_new); return err; } /* Callback function to compare the first entered PIN with the one currently being entered. */ static gpg_error_t reenter_compare_cb (struct pin_entry_info_s *pi) { const char *pin1 = pi->check_cb_arg; if (!strcmp (pin1, pi->pin)) return 0; /* okay */ return gpg_error (GPG_ERR_BAD_PASSPHRASE); } /* Store the ssh KEY into our local key storage and protect it after asking for a passphrase. Cache that passphrase. TTL is the maximum caching time for that key. If the key already exists in our key storage, don't do anything. When entering a key also add an entry to the sshcontrol file. */ static gpg_error_t ssh_identity_register (ctrl_t ctrl, ssh_key_type_spec_t *spec, gcry_sexp_t key, int ttl, int confirm) { gpg_error_t err; unsigned char key_grip_raw[20]; char key_grip[41]; unsigned char *buffer = NULL; size_t buffer_n; char *description = NULL; const char *description2 = L_("Please re-enter this passphrase"); char *comment = NULL; char *key_fpr = NULL; const char *initial_errtext = NULL; struct pin_entry_info_s *pi = NULL; struct pin_entry_info_s *pi2 = NULL; err = ssh_key_grip (key, key_grip_raw); if (err) goto out; bin2hex (key_grip_raw, 20, key_grip); err = ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest, &key_fpr); if (err) goto out; /* Check whether the key is already in our key storage. Don't do anything then besides (re-)adding it to sshcontrol. */ if ( !agent_key_available (key_grip_raw) ) goto key_exists; /* Yes, key is available. */ err = ssh_key_extract_comment (key, &comment); if (err) goto out; if ( asprintf (&description, L_("Please enter a passphrase to protect" " the received secret key%%0A" " %s%%0A" " %s%%0A" "within gpg-agent's key storage"), key_fpr, comment ? comment : "") < 0) { err = gpg_error_from_syserror (); goto out; } pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1); if (!pi) { err = gpg_error_from_syserror (); goto out; } pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1); if (!pi2) { err = gpg_error_from_syserror (); goto out; } pi->max_length = MAX_PASSPHRASE_LEN + 1; pi->max_tries = 1; pi->with_repeat = 1; pi2->max_length = MAX_PASSPHRASE_LEN + 1; pi2->max_tries = 1; pi2->check_cb = reenter_compare_cb; pi2->check_cb_arg = pi->pin; next_try: err = agent_askpin (ctrl, description, NULL, initial_errtext, pi, NULL, 0); initial_errtext = NULL; if (err) goto out; /* Unless the passphrase is empty or the pinentry told us that it already did the repetition check, ask to confirm it. */ if (*pi->pin && !pi->repeat_okay) { err = agent_askpin (ctrl, description2, NULL, NULL, pi2, NULL, 0); if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE) { /* The re-entered one did not match and the user did not hit cancel. */ initial_errtext = L_("does not match - try again"); goto next_try; } } err = ssh_key_to_protected_buffer (key, pi->pin, &buffer, &buffer_n); if (err) goto out; /* Store this key to our key storage. We do not store a creation * timestamp because we simply do not know. */ err = agent_write_private_key (key_grip_raw, buffer, buffer_n, 0, 0); if (err) goto out; /* Cache this passphrase. */ err = agent_put_cache (ctrl, key_grip, CACHE_MODE_SSH, pi->pin, ttl); if (err) goto out; key_exists: /* And add an entry to the sshcontrol file. */ err = add_control_entry (ctrl, spec, key_grip, key, ttl, confirm); out: if (pi2 && pi2->max_length) wipememory (pi2->pin, pi2->max_length); xfree (pi2); if (pi && pi->max_length) wipememory (pi->pin, pi->max_length); xfree (pi); xfree (buffer); xfree (comment); xfree (key_fpr); xfree (description); return err; } /* This function removes the key contained in the S-Expression KEY from the local key storage, in case it exists there. Returns usual error code. FIXME: this function is a stub. */ static gpg_error_t ssh_identity_drop (gcry_sexp_t key) { unsigned char key_grip[21] = { 0 }; gpg_error_t err; err = ssh_key_grip (key, key_grip); if (err) goto out; key_grip[sizeof (key_grip) - 1] = 0; /* FIXME: What to do here - forgetting the passphrase or deleting the key from key cache? */ out: return err; } /* Handler for the "add_identity" command. */ static gpg_error_t ssh_handler_add_identity (ctrl_t ctrl, estream_t request, estream_t response) { gpg_error_t ret_err; ssh_key_type_spec_t spec; gpg_error_t err; gcry_sexp_t key; unsigned char b; int confirm; int ttl; confirm = 0; key = NULL; ttl = 0; /* FIXME? */ err = ssh_receive_key (request, &key, 1, 1, &spec); if (err) goto out; while (1) { err = stream_read_byte (request, &b); if (err) { if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; break; } switch (b) { case SSH_OPT_CONSTRAIN_LIFETIME: { u32 n = 0; err = stream_read_uint32 (request, &n); if (! err) ttl = n; break; } case SSH_OPT_CONSTRAIN_CONFIRM: { confirm = 1; break; } default: /* FIXME: log/bad? */ break; } } if (err) goto out; err = ssh_identity_register (ctrl, &spec, key, ttl, confirm); out: gcry_sexp_release (key); if (! err) ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS); else ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); return ret_err; } /* Handler for the "remove_identity" command. */ static gpg_error_t ssh_handler_remove_identity (ctrl_t ctrl, estream_t request, estream_t response) { unsigned char *key_blob; u32 key_blob_size; gcry_sexp_t key; gpg_error_t ret_err; gpg_error_t err; (void)ctrl; /* Receive key. */ key_blob = NULL; key = NULL; err = stream_read_string (request, 0, &key_blob, &key_blob_size); if (err) goto out; err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, NULL); if (err) goto out; err = ssh_identity_drop (key); out: xfree (key_blob); gcry_sexp_release (key); if (! err) ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS); else ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); return ret_err; } /* FIXME: stub function. Actually useful? */ static gpg_error_t ssh_identities_remove_all (void) { gpg_error_t err; err = 0; /* FIXME: shall we remove _all_ cache entries or only those registered through the ssh-agent protocol? */ return err; } /* Handler for the "remove_all_identities" command. */ static gpg_error_t ssh_handler_remove_all_identities (ctrl_t ctrl, estream_t request, estream_t response) { gpg_error_t ret_err; gpg_error_t err; (void)ctrl; (void)request; err = ssh_identities_remove_all (); if (! err) ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS); else ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); return ret_err; } /* Lock agent? FIXME: stub function. */ static gpg_error_t ssh_lock (void) { gpg_error_t err; /* FIXME */ log_error ("ssh-agent's lock command is not implemented\n"); err = 0; return err; } /* Unock agent? FIXME: stub function. */ static gpg_error_t ssh_unlock (void) { gpg_error_t err; log_error ("ssh-agent's unlock command is not implemented\n"); err = 0; return err; } /* Handler for the "lock" command. */ static gpg_error_t ssh_handler_lock (ctrl_t ctrl, estream_t request, estream_t response) { gpg_error_t ret_err; gpg_error_t err; (void)ctrl; (void)request; err = ssh_lock (); if (! err) ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS); else ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); return ret_err; } /* Handler for the "unlock" command. */ static gpg_error_t ssh_handler_unlock (ctrl_t ctrl, estream_t request, estream_t response) { gpg_error_t ret_err; gpg_error_t err; (void)ctrl; (void)request; err = ssh_unlock (); if (! err) ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS); else ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE); return ret_err; } /* Return the request specification for the request identified by TYPE or NULL in case the requested request specification could not be found. */ static const ssh_request_spec_t * request_spec_lookup (int type) { const ssh_request_spec_t *spec; unsigned int i; for (i = 0; i < DIM (request_specs); i++) if (request_specs[i].type == type) break; if (i == DIM (request_specs)) { if (opt.verbose) log_info ("ssh request %u is not supported\n", type); spec = NULL; } else spec = request_specs + i; return spec; } /* Process a single request. The request is read from and the response is written to STREAM_SOCK. Uses CTRL as context. Returns zero in case of success, non zero in case of failure. */ static int ssh_request_process (ctrl_t ctrl, estream_t stream_sock) { const ssh_request_spec_t *spec; estream_t response = NULL; estream_t request = NULL; unsigned char request_type; gpg_error_t err; int send_err = 0; int ret; unsigned char *request_data = NULL; u32 request_data_size; u32 response_size; /* Create memory streams for request/response data. The entire request will be stored in secure memory, since it might contain secret key material. The response does not have to be stored in secure memory, since we never give out secret keys. Note: we only have little secure memory, but there is NO possibility of DoS here; only trusted clients are allowed to connect to the agent. What could happen is that the agent returns out-of-secure-memory errors on requests in case the agent's owner floods his own agent with many large messages. -moritz */ /* Retrieve request. */ err = stream_read_string (stream_sock, 1, &request_data, &request_data_size); if (err) goto out; if (opt.verbose > 1) log_info ("received ssh request of length %u\n", (unsigned int)request_data_size); if (! request_data_size) { send_err = 1; goto out; /* Broken request; FIXME. */ } request_type = request_data[0]; spec = request_spec_lookup (request_type); if (! spec) { send_err = 1; goto out; /* Unknown request; FIXME. */ } if (spec->secret_input) request = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+b"); else request = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+b"); if (! request) { err = gpg_error_from_syserror (); goto out; } ret = es_setvbuf (request, NULL, _IONBF, 0); if (ret) { err = gpg_error_from_syserror (); goto out; } err = stream_write_data (request, request_data + 1, request_data_size - 1); if (err) goto out; es_rewind (request); response = es_fopenmem (0, "r+b"); if (! response) { err = gpg_error_from_syserror (); goto out; } if (opt.verbose) log_info ("ssh request handler for %s (%u) started\n", spec->identifier, spec->type); err = (*spec->handler) (ctrl, request, response); if (opt.verbose) { if (err) log_info ("ssh request handler for %s (%u) failed: %s\n", spec->identifier, spec->type, gpg_strerror (err)); else log_info ("ssh request handler for %s (%u) ready\n", spec->identifier, spec->type); } if (err) { send_err = 1; goto out; } response_size = es_ftell (response); if (opt.verbose > 1) log_info ("sending ssh response of length %u\n", (unsigned int)response_size); err = es_fseek (response, 0, SEEK_SET); if (err) { send_err = 1; goto out; } err = stream_write_uint32 (stream_sock, response_size); if (err) { send_err = 1; goto out; } err = stream_copy (stream_sock, response); if (err) goto out; err = es_fflush (stream_sock); if (err) goto out; out: if (err && es_feof (stream_sock)) log_error ("error occurred while processing request: %s\n", gpg_strerror (err)); if (send_err) { if (opt.verbose > 1) log_info ("sending ssh error response\n"); err = stream_write_uint32 (stream_sock, 1); if (err) goto leave; err = stream_write_byte (stream_sock, SSH_RESPONSE_FAILURE); if (err) goto leave; } leave: es_fclose (request); es_fclose (response); xfree (request_data); return !!err; } /* Return the peer's pid. */ static unsigned long get_client_pid (int fd) { pid_t client_pid = (pid_t)0; #ifdef SO_PEERCRED { #ifdef HAVE_STRUCT_SOCKPEERCRED_PID struct sockpeercred cr; #else struct ucred cr; #endif socklen_t cl = sizeof cr; if (!getsockopt (fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl)) { #if defined (HAVE_STRUCT_SOCKPEERCRED_PID) || defined (HAVE_STRUCT_UCRED_PID) client_pid = cr.pid; #elif defined (HAVE_STRUCT_UCRED_CR_PID) client_pid = cr.cr_pid; #else #error "Unknown SO_PEERCRED struct" #endif } } #elif defined (LOCAL_PEERPID) { socklen_t len = sizeof (pid_t); getsockopt (fd, SOL_LOCAL, LOCAL_PEERPID, &client_pid, &len); } #elif defined (LOCAL_PEEREID) { struct unpcbid unp; socklen_t unpl = sizeof unp; if (getsockopt (fd, 0, LOCAL_PEEREID, &unp, &unpl) != -1) client_pid = unp.unp_pid; } #elif defined (HAVE_GETPEERUCRED) { ucred_t *ucred = NULL; if (getpeerucred (fd, &ucred) != -1) { client_pid= ucred_getpid (ucred); ucred_free (ucred); } } #else (void)fd; #endif return (unsigned long)client_pid; } /* Start serving client on SOCK_CLIENT. */ void start_command_handler_ssh (ctrl_t ctrl, gnupg_fd_t sock_client) { estream_t stream_sock = NULL; gpg_error_t err; int ret; err = agent_copy_startup_env (ctrl); if (err) goto out; ctrl->client_pid = get_client_pid (FD2INT(sock_client)); /* Create stream from socket. */ stream_sock = es_fdopen (FD2INT(sock_client), "r+"); if (!stream_sock) { err = gpg_error_from_syserror (); log_error (_("failed to create stream from socket: %s\n"), gpg_strerror (err)); goto out; } /* We have to disable the estream buffering, because the estream core doesn't know about secure memory. */ ret = es_setvbuf (stream_sock, NULL, _IONBF, 0); if (ret) { err = gpg_error_from_syserror (); log_error ("failed to disable buffering " "on socket stream: %s\n", gpg_strerror (err)); goto out; } /* Main processing loop. */ while ( !ssh_request_process (ctrl, stream_sock) ) { /* Check whether we have reached EOF before trying to read another request. */ int c; c = es_fgetc (stream_sock); if (c == EOF) break; es_ungetc (c, stream_sock); } /* Reset the SCD in case it has been used. */ agent_reset_scd (ctrl); out: if (stream_sock) es_fclose (stream_sock); } #ifdef HAVE_W32_SYSTEM /* Serve one ssh-agent request. This is used for the Putty support. REQUEST is the mmapped memory which may be accessed up to a length of MAXREQLEN. Returns 0 on success which also indicates that a valid SSH response message is now in REQUEST. */ int serve_mmapped_ssh_request (ctrl_t ctrl, unsigned char *request, size_t maxreqlen) { gpg_error_t err; int send_err = 0; int valid_response = 0; const ssh_request_spec_t *spec; u32 msglen; estream_t request_stream, response_stream; if (agent_copy_startup_env (ctrl)) goto leave; /* Error setting up the environment. */ if (maxreqlen < 5) goto leave; /* Caller error. */ msglen = uint32_construct (request[0], request[1], request[2], request[3]); if (msglen < 1 || msglen > maxreqlen - 4) { log_error ("ssh message len (%u) out of range", (unsigned int)msglen); goto leave; } spec = request_spec_lookup (request[4]); if (!spec) { send_err = 1; /* Unknown request type. */ goto leave; } /* Create a stream object with the data part of the request. */ if (spec->secret_input) request_stream = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+"); else request_stream = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+"); if (!request_stream) { err = gpg_error_from_syserror (); goto leave; } /* We have to disable the estream buffering, because the estream core doesn't know about secure memory. */ if (es_setvbuf (request_stream, NULL, _IONBF, 0)) { err = gpg_error_from_syserror (); goto leave; } /* Copy the request to the stream but omit the request type. */ err = stream_write_data (request_stream, request + 5, msglen - 1); if (err) goto leave; es_rewind (request_stream); response_stream = es_fopenmem (0, "r+b"); if (!response_stream) { err = gpg_error_from_syserror (); goto leave; } if (opt.verbose) log_info ("ssh request handler for %s (%u) started\n", spec->identifier, spec->type); err = (*spec->handler) (ctrl, request_stream, response_stream); if (opt.verbose) { if (err) log_info ("ssh request handler for %s (%u) failed: %s\n", spec->identifier, spec->type, gpg_strerror (err)); else log_info ("ssh request handler for %s (%u) ready\n", spec->identifier, spec->type); } es_fclose (request_stream); request_stream = NULL; if (err) { send_err = 1; goto leave; } /* Put the response back into the mmapped buffer. */ { void *response_data; size_t response_size; /* NB: In contrast to the request-stream, the response stream includes the message type byte. */ if (es_fclose_snatch (response_stream, &response_data, &response_size)) { log_error ("snatching ssh response failed: %s", gpg_strerror (gpg_error_from_syserror ())); send_err = 1; /* Ooops. */ goto leave; } if (opt.verbose > 1) log_info ("sending ssh response of length %u\n", (unsigned int)response_size); if (response_size > maxreqlen - 4) { log_error ("invalid length of the ssh response: %s", gpg_strerror (GPG_ERR_INTERNAL)); es_free (response_data); send_err = 1; goto leave; } request[0] = response_size >> 24; request[1] = response_size >> 16; request[2] = response_size >> 8; request[3] = response_size >> 0; memcpy (request+4, response_data, response_size); es_free (response_data); valid_response = 1; } leave: if (send_err) { request[0] = 0; request[1] = 0; request[2] = 0; request[3] = 1; request[4] = SSH_RESPONSE_FAILURE; valid_response = 1; } /* Reset the SCD in case it has been used. */ agent_reset_scd (ctrl); return valid_response? 0 : -1; } #endif /*HAVE_W32_SYSTEM*/ diff --git a/common/helpfile.c b/common/helpfile.c index 7cb01a443..7a7a2358a 100644 --- a/common/helpfile.c +++ b/common/helpfile.c @@ -1,272 +1,272 @@ /* helpfile.c - GnuPG's helpfile feature * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include "util.h" #include "i18n.h" #include "membuf.h" /* Try to find KEY in the file FNAME. */ static char * findkey_fname (const char *key, const char *fname) { gpg_error_t err = 0; - FILE *fp; + estream_t fp; int lnr = 0; int c; char *p, line[256]; int in_item = 0; membuf_t mb = MEMBUF_ZERO; - fp = fopen (fname, "r"); + fp = es_fopen (fname, "r"); if (!fp) { if (errno != ENOENT) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); } return NULL; } - while (fgets (line, DIM(line)-1, fp)) + while (es_fgets (line, DIM(line)-1, fp)) { lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ - while ( (c=getc (fp)) != EOF && c != '\n') + while ((c = es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); log_error (_("file '%s', line %d: %s\n"), fname, lnr, gpg_strerror (err)); } else line[strlen(line)-1] = 0; /* Chop the LF. */ again: if (!in_item) { /* Allow for empty lines and spaces while not in an item. */ for (p=line; spacep (p); p++) ; if (!*p || *p == '#') continue; if (*line != '.' || spacep(line+1)) { log_info (_("file '%s', line %d: %s\n"), fname, lnr, _("ignoring garbage line")); continue; } trim_trailing_spaces (line); in_item = 1; if (!strcmp (line+1, key)) { /* Found. Start collecting. */ init_membuf (&mb, 1024); } continue; } /* If in an item only allow for comments in the first column and provide ". " as an escape sequence to allow for leading dots and hash marks in the actual text. */ if (*line == '#') continue; if (*line == '.') { if (spacep(line+1)) p = line + 2; else { trim_trailing_spaces (line); in_item = 0; if (is_membuf_ready (&mb)) break; /* Yep, found and collected the item. */ if (!line[1]) continue; /* Just an end of text dot. */ goto again; /* A new key line. */ } } else p = line; if (is_membuf_ready (&mb)) { put_membuf_str (&mb, p); put_membuf (&mb, "\n", 1); } } - if ( !err && ferror (fp) ) + if ( !err && es_ferror (fp) ) { err = gpg_error_from_syserror (); log_error (_("error reading '%s', line %d: %s\n"), fname, lnr, gpg_strerror (err)); } - fclose (fp); + es_fclose (fp); if (is_membuf_ready (&mb)) { /* We have collected something. */ if (err) { xfree (get_membuf (&mb, NULL)); return NULL; } else { put_membuf (&mb, "", 1); /* Terminate string. */ return get_membuf (&mb, NULL); } } else return NULL; } /* Try the help files depending on the locale. */ static char * findkey_locale (const char *key, const char *locname, int only_current_locale, const char *dirname) { const char *s; char *fname, *ext, *p; char *result; fname = xtrymalloc (strlen (dirname) + 6 + strlen (locname) + 4 + 1); if (!fname) return NULL; ext = stpcpy (stpcpy (fname, dirname), "/help."); /* Search with locale name and territory. ("help.LL_TT.txt") */ if (strchr (locname, '_')) { strcpy (stpcpy (ext, locname), ".txt"); result = findkey_fname (key, fname); } else result = NULL; /* No territory. */ if (!result) { /* Search with just the locale name - if any. ("help.LL.txt") */ if (*locname) { for (p=ext, s=locname; *s && *s != '_';) *p++ = *s++; strcpy (p, ".txt"); result = findkey_fname (key, fname); } else result = NULL; } if (!result && (!only_current_locale || !*locname) ) { /* Last try: Search in file without any locale info. ("help.txt") */ strcpy (ext, "txt"); result = findkey_fname (key, fname); } xfree (fname); return result; } /* Return a malloced help text as identified by KEY. The system takes the string from an UTF-8 encoded file to be created by an administrator or as distributed with GnuPG. On a GNU or Unix system the entry is searched in these files: /etc/gnupg/help.LL.txt /etc/gnupg/help.txt /usr/share/gnupg/help.LL.txt /usr/share/gnupg/help.txt Here LL denotes the two digit language code of the current locale. If ONLY_CURRENT_LOCALE is set, the function won't fallback to the english valiant ("help.txt") unless that locale has been requested. The help file needs to be encoded in UTF-8, lines with a '#' in the first column are comment lines and entirely ignored. Help keys are identified by a key consisting of a single word with a single dot as the first character. All key lines listed without any intervening lines (except for comment lines) lead to the same help text. Lines following the key lines make up the actual hep texts. */ char * gnupg_get_help_string (const char *key, int only_current_locale) { static const char *locname; char *result; if (!locname) { char *buffer, *p; int count = 0; const char *s = gnupg_messages_locale_name (); buffer = xtrystrdup (s); if (!buffer) locname = ""; else { for (p = buffer; *p; p++) if (*p == '.' || *p == '@' || *p == '/' /*(safeguard)*/) *p = 0; else if (*p == '_') { if (count++) *p = 0; /* Also cut at a underscore in the territory. */ } locname = buffer; } } if (!key || !*key) return NULL; result = findkey_locale (key, locname, only_current_locale, gnupg_sysconfdir ()); if (!result) result = findkey_locale (key, locname, only_current_locale, gnupg_datadir ()); if (result) trim_trailing_spaces (result); return result; } diff --git a/g10/keydb.c b/g10/keydb.c index 934002498..7b411dbfe 100644 --- a/g10/keydb.c +++ b/g10/keydb.c @@ -1,2116 +1,2116 @@ /* keydb.c - key database dispatcher * Copyright (C) 2001-2013 Free Software Foundation, Inc. * Coyrright (C) 2001-2015 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include "gpg.h" #include "../common/util.h" #include "../common/sysutils.h" #include "options.h" #include "main.h" /*try_make_homedir ()*/ #include "packet.h" #include "keyring.h" #include "../kbx/keybox.h" #include "keydb.h" #include "../common/i18n.h" static int active_handles; typedef enum { KEYDB_RESOURCE_TYPE_NONE = 0, KEYDB_RESOURCE_TYPE_KEYRING, KEYDB_RESOURCE_TYPE_KEYBOX } KeydbResourceType; #define MAX_KEYDB_RESOURCES 40 struct resource_item { KeydbResourceType type; union { KEYRING_HANDLE kr; KEYBOX_HANDLE kb; } u; void *token; }; static struct resource_item all_resources[MAX_KEYDB_RESOURCES]; static int used_resources; /* A pointer used to check for the primary key database by comparing to the struct resource_item's TOKEN. */ static void *primary_keydb; /* Whether we have successfully registered any resource. */ static int any_registered; /* This is a simple cache used to return the last result of a successful fingerprint search. This works only for keybox resources because (due to lack of a copy_keyblock function) we need to store an image of the keyblock which is fortunately instantly available for keyboxes. */ enum keyblock_cache_states { KEYBLOCK_CACHE_EMPTY, KEYBLOCK_CACHE_PREPARED, KEYBLOCK_CACHE_FILLED }; struct keyblock_cache { enum keyblock_cache_states state; byte fpr[MAX_FINGERPRINT_LEN]; iobuf_t iobuf; /* Image of the keyblock. */ int pk_no; int uid_no; /* Offset of the record in the keybox. */ int resource; off_t offset; }; struct keydb_handle { /* When we locked all of the resources in ACTIVE (using keyring_lock / keybox_lock, as appropriate). */ int locked; /* If this flag is set a lock will only be released by * keydb_release. */ int keep_lock; /* The index into ACTIVE of the resources in which the last search result was found. Initially -1. */ int found; /* Initially -1 (invalid). This is used to save a search result and later restore it as the selected result. */ int saved_found; /* The number of skipped long blobs since the last search (keydb_search_reset). */ unsigned long skipped_long_blobs; /* If set, this disables the use of the keyblock cache. */ int no_caching; /* Whether the next search will be from the beginning of the database (and thus consider all records). */ int is_reset; /* The "file position." In our case, this is index of the current resource in ACTIVE. */ int current; /* The number of resources in ACTIVE. */ int used; /* Cache of the last found and parsed key block (only used for keyboxes, not keyrings). */ struct keyblock_cache keyblock_cache; /* Copy of ALL_RESOURCES when keydb_new is called. */ struct resource_item active[MAX_KEYDB_RESOURCES]; }; /* Looking up keys is expensive. To hide the cost, we cache whether keys exist in the key database. Then, if we know a key does not exist, we don't have to spend time looking it up. This particularly helps the --list-sigs and --check-sigs commands. The cache stores the results in a hash using separate chaining. Concretely: we use the LSB of the keyid to index the hash table and each bucket consists of a linked list of entries. An entry consists of the 64-bit key id. If a key id is not in the cache, then we don't know whether it is in the DB or not. To simplify the cache consistency protocol, we simply flush the whole cache whenever a key is inserted or updated. */ #define KID_NOT_FOUND_CACHE_BUCKETS 256 static struct kid_not_found_cache_bucket * kid_not_found_cache[KID_NOT_FOUND_CACHE_BUCKETS]; struct kid_not_found_cache_bucket { struct kid_not_found_cache_bucket *next; u32 kid[2]; }; struct { unsigned int count; /* The current number of entries in the hash table. */ unsigned int peak; /* The peak of COUNT. */ unsigned int flushes; /* The number of flushes. */ } kid_not_found_stats; struct { unsigned int handles; /* Number of handles created. */ unsigned int locks; /* Number of locks taken. */ unsigned int parse_keyblocks; /* Number of parse_keyblock_image calls. */ unsigned int get_keyblocks; /* Number of keydb_get_keyblock calls. */ unsigned int build_keyblocks; /* Number of build_keyblock_image calls. */ unsigned int update_keyblocks;/* Number of update_keyblock calls. */ unsigned int insert_keyblocks;/* Number of update_keyblock calls. */ unsigned int delete_keyblocks;/* Number of delete_keyblock calls. */ unsigned int search_resets; /* Number of keydb_search_reset calls. */ unsigned int found; /* Number of successful keydb_search calls. */ unsigned int found_cached; /* Ditto but from the cache. */ unsigned int notfound; /* Number of failed keydb_search calls. */ unsigned int notfound_cached; /* Ditto but from the cache. */ } keydb_stats; static int lock_all (KEYDB_HANDLE hd); static void unlock_all (KEYDB_HANDLE hd); /* Check whether the keyid KID is in key id is definitely not in the database. Returns: 0 - Indeterminate: the key id is not in the cache; we don't know whether the key is in the database or not. If you want a definitive answer, you'll need to perform a lookup. 1 - There is definitely no key with this key id in the database. We searched for a key with this key id previously, but we didn't find it in the database. */ static int kid_not_found_p (u32 *kid) { struct kid_not_found_cache_bucket *k; for (k = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; k; k = k->next) if (k->kid[0] == kid[0] && k->kid[1] == kid[1]) { if (DBG_CACHE) log_debug ("keydb: kid_not_found_p (%08lx%08lx) => not in DB\n", (ulong)kid[0], (ulong)kid[1]); return 1; } if (DBG_CACHE) log_debug ("keydb: kid_not_found_p (%08lx%08lx) => indeterminate\n", (ulong)kid[0], (ulong)kid[1]); return 0; } /* Insert the keyid KID into the kid_not_found_cache. FOUND is whether the key is in the key database or not. Note this function does not check whether the key id is already in the cache. As such, kid_not_found_p() should be called first. */ static void kid_not_found_insert (u32 *kid) { struct kid_not_found_cache_bucket *k; if (DBG_CACHE) log_debug ("keydb: kid_not_found_insert (%08lx%08lx)\n", (ulong)kid[0], (ulong)kid[1]); k = xmalloc (sizeof *k); k->kid[0] = kid[0]; k->kid[1] = kid[1]; k->next = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS] = k; kid_not_found_stats.count++; } /* Flush the kid not found cache. */ static void kid_not_found_flush (void) { struct kid_not_found_cache_bucket *k, *knext; int i; if (DBG_CACHE) log_debug ("keydb: kid_not_found_flush\n"); if (!kid_not_found_stats.count) return; for (i=0; i < DIM(kid_not_found_cache); i++) { for (k = kid_not_found_cache[i]; k; k = knext) { knext = k->next; xfree (k); } kid_not_found_cache[i] = NULL; } if (kid_not_found_stats.count > kid_not_found_stats.peak) kid_not_found_stats.peak = kid_not_found_stats.count; kid_not_found_stats.count = 0; kid_not_found_stats.flushes++; } static void keyblock_cache_clear (struct keydb_handle *hd) { hd->keyblock_cache.state = KEYBLOCK_CACHE_EMPTY; iobuf_close (hd->keyblock_cache.iobuf); hd->keyblock_cache.iobuf = NULL; hd->keyblock_cache.resource = -1; hd->keyblock_cache.offset = -1; } /* Handle the creation of a keyring or a keybox if it does not yet exist. Take into account that other processes might have the keyring/keybox already locked. This lock check does not work if the directory itself is not yet available. If IS_BOX is true the filename is expected to refer to a keybox. If FORCE_CREATE is true the keyring or keybox will be created. Return 0 if it is okay to access the specified file. */ static gpg_error_t maybe_create_keyring_or_box (char *filename, int is_box, int force_create) { gpg_err_code_t ec; dotlock_t lockhd = NULL; IOBUF iobuf; int rc; mode_t oldmask; char *last_slash_in_filename; char *bak_fname = NULL; char *tmp_fname = NULL; int save_slash; /* A quick test whether the filename already exists. */ if (!gnupg_access (filename, F_OK)) return !gnupg_access (filename, R_OK)? 0 : gpg_error (GPG_ERR_EACCES); /* If we don't want to create a new file at all, there is no need to go any further - bail out right here. */ if (!force_create) return gpg_error (GPG_ERR_ENOENT); /* First of all we try to create the home directory. Note, that we don't do any locking here because any sane application of gpg would create the home directory by itself and not rely on gpg's tricky auto-creation which is anyway only done for certain home directory name pattern. */ last_slash_in_filename = strrchr (filename, DIRSEP_C); #if HAVE_W32_SYSTEM { /* Windows may either have a slash or a backslash. Take care of it. */ char *p = strrchr (filename, '/'); if (!last_slash_in_filename || p > last_slash_in_filename) last_slash_in_filename = p; } #endif /*HAVE_W32_SYSTEM*/ if (!last_slash_in_filename) return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should not happen though. */ save_slash = *last_slash_in_filename; *last_slash_in_filename = 0; if (access(filename, F_OK)) { static int tried; if (!tried) { tried = 1; try_make_homedir (filename); } if ((ec = gnupg_access (filename, F_OK))) { rc = gpg_error (ec); *last_slash_in_filename = save_slash; goto leave; } } *last_slash_in_filename = save_slash; /* To avoid races with other instances of gpg trying to create or update the keyring (it is removed during an update for a short time), we do the next stuff in a locked state. */ lockhd = dotlock_create (filename, 0); if (!lockhd) { rc = gpg_error_from_syserror (); /* A reason for this to fail is that the directory is not writable. However, this whole locking stuff does not make sense if this is the case. An empty non-writable directory with no keyring is not really useful at all. */ if (opt.verbose) log_info ("can't allocate lock for '%s': %s\n", filename, gpg_strerror (rc)); if (!force_create) return gpg_error (GPG_ERR_ENOENT); /* Won't happen. */ else return rc; } if ( dotlock_take (lockhd, -1) ) { rc = gpg_error_from_syserror (); /* This is something bad. Probably a stale lockfile. */ log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc)); goto leave; } /* Now the real test while we are locked. */ /* Gpg either uses pubring.gpg or pubring.kbx and thus different * lock files. Now, when one gpg process is updating a pubring.gpg * and thus holding the corresponding lock, a second gpg process may * get to here at the time between the two rename operation used by * the first process to update pubring.gpg. The lock taken above * may not protect the second process if it tries to create a * pubring.kbx file which would be protected by a different lock * file. * * We can detect this case by checking that the two temporary files * used by the update code exist at the same time. In that case we * do not create a new file but act as if FORCE_CREATE has not been * given. Obviously there is a race between our two checks but the * worst thing is that we won't create a new file, which is better * than to accidentally creating one. */ rc = keybox_tmp_names (filename, is_box, &bak_fname, &tmp_fname); if (rc) goto leave; if (!gnupg_access (filename, F_OK)) { rc = 0; /* Okay, we may access the file now. */ goto leave; } if (!gnupg_access (bak_fname, F_OK) && !gnupg_access (tmp_fname, F_OK)) { /* Very likely another process is updating a pubring.gpg and we should not create a pubring.kbx. */ rc = gpg_error (GPG_ERR_ENOENT); goto leave; } /* The file does not yet exist, create it now. */ oldmask = umask (077); if (is_secured_filename (filename)) { iobuf = NULL; gpg_err_set_errno (EPERM); } else iobuf = iobuf_create (filename, 0); umask (oldmask); if (!iobuf) { rc = gpg_error_from_syserror (); if (is_box) log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (rc)); else log_error (_("error creating keyring '%s': %s\n"), filename, gpg_strerror (rc)); goto leave; } iobuf_close (iobuf); /* Must invalidate that ugly cache */ iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename); /* Make sure that at least one record is in a new keybox file, so that the detection magic will work the next time it is used. */ if (is_box) { - FILE *fp = fopen (filename, "wb"); + estream_t fp = es_fopen (filename, "wb"); if (!fp) rc = gpg_error_from_syserror (); else { rc = _keybox_write_header_blob (fp, 1); - fclose (fp); + es_fclose (fp); } if (rc) { if (is_box) log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (rc)); else log_error (_("error creating keyring '%s': %s\n"), filename, gpg_strerror (rc)); goto leave; } } if (!opt.quiet) { if (is_box) log_info (_("keybox '%s' created\n"), filename); else log_info (_("keyring '%s' created\n"), filename); } rc = 0; leave: if (lockhd) { dotlock_release (lockhd); dotlock_destroy (lockhd); } xfree (bak_fname); xfree (tmp_fname); return rc; } /* Helper for keydb_add_resource. Opens FILENAME to figure out the resource type. Returns the specified file's likely type. If the file does not exist, returns KEYDB_RESOURCE_TYPE_NONE and sets *R_FOUND to 0. Otherwise, tries to figure out the file's type. This is either KEYDB_RESOURCE_TYPE_KEYBOX, KEYDB_RESOURCE_TYPE_KEYRING or KEYDB_RESOURCE_TYPE_KEYNONE. If the file is a keybox and it has the OpenPGP flag set, then R_OPENPGP is also set. */ static KeydbResourceType rt_from_file (const char *filename, int *r_found, int *r_openpgp) { u32 magic; unsigned char verbuf[4]; FILE *fp; KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE; *r_found = *r_openpgp = 0; fp = fopen (filename, "rb"); if (fp) { *r_found = 1; if (fread (&magic, 4, 1, fp) == 1 ) { if (magic == 0x13579ace || magic == 0xce9a5713) ; /* GDBM magic - not anymore supported. */ else if (fread (&verbuf, 4, 1, fp) == 1 && verbuf[0] == 1 && fread (&magic, 4, 1, fp) == 1 && !memcmp (&magic, "KBXf", 4)) { if ((verbuf[3] & 0x02)) *r_openpgp = 1; rt = KEYDB_RESOURCE_TYPE_KEYBOX; } else rt = KEYDB_RESOURCE_TYPE_KEYRING; } else /* Maybe empty: assume keyring. */ rt = KEYDB_RESOURCE_TYPE_KEYRING; fclose (fp); } return rt; } char * keydb_search_desc_dump (struct keydb_search_desc *desc) { char b[MAX_FORMATTED_FINGERPRINT_LEN + 1]; char fpr[2 * MAX_FINGERPRINT_LEN + 1]; switch (desc->mode) { case KEYDB_SEARCH_MODE_EXACT: return xasprintf ("EXACT: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_SUBSTR: return xasprintf ("SUBSTR: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_MAIL: return xasprintf ("MAIL: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_MAILSUB: return xasprintf ("MAILSUB: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_MAILEND: return xasprintf ("MAILEND: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_WORDS: return xasprintf ("WORDS: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_SHORT_KID: return xasprintf ("SHORT_KID: '%s'", format_keyid (desc->u.kid, KF_SHORT, b, sizeof (b))); case KEYDB_SEARCH_MODE_LONG_KID: return xasprintf ("LONG_KID: '%s'", format_keyid (desc->u.kid, KF_LONG, b, sizeof (b))); case KEYDB_SEARCH_MODE_FPR16: bin2hex (desc->u.fpr, 16, fpr); return xasprintf ("FPR16: '%s'", format_hexfingerprint (fpr, b, sizeof (b))); case KEYDB_SEARCH_MODE_FPR20: bin2hex (desc->u.fpr, 20, fpr); return xasprintf ("FPR20: '%s'", format_hexfingerprint (fpr, b, sizeof (b))); case KEYDB_SEARCH_MODE_FPR: bin2hex (desc->u.fpr, 20, fpr); return xasprintf ("FPR: '%s'", format_hexfingerprint (fpr, b, sizeof (b))); case KEYDB_SEARCH_MODE_ISSUER: return xasprintf ("ISSUER: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_ISSUER_SN: return xasprintf ("ISSUER_SN: '%*s'", (int) (desc->snlen == -1 ? strlen (desc->sn) : desc->snlen), desc->sn); case KEYDB_SEARCH_MODE_SN: return xasprintf ("SN: '%*s'", (int) (desc->snlen == -1 ? strlen (desc->sn) : desc->snlen), desc->sn); case KEYDB_SEARCH_MODE_SUBJECT: return xasprintf ("SUBJECT: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_KEYGRIP: return xasprintf ("KEYGRIP: %s", desc->u.grip); case KEYDB_SEARCH_MODE_FIRST: return xasprintf ("FIRST"); case KEYDB_SEARCH_MODE_NEXT: return xasprintf ("NEXT"); default: return xasprintf ("Bad search mode (%d)", desc->mode); } } /* Register a resource (keyring or keybox). The first keyring or * keybox that is added using this function is created if it does not * already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set. * * FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants. * * URL must have the following form: * * gnupg-ring:filename = plain keyring * gnupg-kbx:filename = keybox file * filename = check file's type (create as a plain keyring) * * Note: on systems with drive letters (Windows) invalid URLs (i.e., * those with an unrecognized part before the ':' such as "c:\...") * will silently be treated as bare filenames. On other systems, such * URLs will cause this function to return GPG_ERR_GENERAL. * * If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring * and the file ends in ".gpg", then this function also checks if a * file with the same name, but the extension ".kbx" exists, is a * keybox and the OpenPGP flag is set. If so, this function opens * that resource instead. * * If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and * the URL ends in ".kbx", then this function will try opening the * same URL, but with the extension ".gpg". If that file is a keybox * with the OpenPGP flag set or it is a keyring, then we use that * instead. * * If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the * file should be created and the file's extension is ".gpg" then we * replace the extension with ".kbx". * * If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a * keyring (not a keybox), then this resource is considered the * primary resource. This is used by keydb_locate_writable(). If * another primary keyring is set, then that keyring is considered the * primary. * * If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a * keyring (not a keybox), then the keyring is marked as read only and * operations just as keyring_insert_keyblock will return * GPG_ERR_ACCESS. */ gpg_error_t keydb_add_resource (const char *url, unsigned int flags) { /* The file named by the URL (i.e., without the prototype). */ const char *resname = url; char *filename = NULL; int create; int read_only = !!(flags&KEYDB_RESOURCE_FLAG_READONLY); int is_default = !!(flags&KEYDB_RESOURCE_FLAG_DEFAULT); int is_gpgvdef = !!(flags&KEYDB_RESOURCE_FLAG_GPGVDEF); gpg_error_t err = 0; KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE; void *token; /* Create the resource if it is the first registered one. */ create = (!read_only && !any_registered); if (strlen (resname) > 11 && !strncmp( resname, "gnupg-ring:", 11) ) { rt = KEYDB_RESOURCE_TYPE_KEYRING; resname += 11; } else if (strlen (resname) > 10 && !strncmp (resname, "gnupg-kbx:", 10) ) { rt = KEYDB_RESOURCE_TYPE_KEYBOX; resname += 10; } #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__) else if (strchr (resname, ':')) { log_error ("invalid key resource URL '%s'\n", url ); err = gpg_error (GPG_ERR_GENERAL); goto leave; } #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */ if (*resname != DIRSEP_C #ifdef HAVE_W32_SYSTEM && *resname != '/' /* Fixme: does not handle drive letters. */ #endif ) { /* Do tilde expansion etc. */ if (strchr (resname, DIRSEP_C) #ifdef HAVE_W32_SYSTEM || strchr (resname, '/') /* Windows also accepts this. */ #endif ) filename = make_filename (resname, NULL); else filename = make_filename (gnupg_homedir (), resname, NULL); } else filename = xstrdup (resname); /* See whether we can determine the filetype. */ if (rt == KEYDB_RESOURCE_TYPE_NONE) { int found, openpgp_flag; int pass = 0; size_t filenamelen; check_again: filenamelen = strlen (filename); rt = rt_from_file (filename, &found, &openpgp_flag); if (found) { /* The file exists and we have the resource type in RT. Now let us check whether in addition to the "pubring.gpg" a "pubring.kbx with openpgp keys exists. This is so that GPG 2.1 will use an existing "pubring.kbx" by default iff that file has been created or used by 2.1. This check is needed because after creation or use of the kbx file with 2.1 an older version of gpg may have created a new pubring.gpg for its own use. */ if (!pass && is_default && rt == KEYDB_RESOURCE_TYPE_KEYRING && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg")) { strcpy (filename+filenamelen-4, ".kbx"); if ((rt_from_file (filename, &found, &openpgp_flag) == KEYDB_RESOURCE_TYPE_KEYBOX) && found && openpgp_flag) rt = KEYDB_RESOURCE_TYPE_KEYBOX; else /* Restore filename */ strcpy (filename+filenamelen-4, ".gpg"); } } else if (!pass && is_gpgvdef && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".kbx")) { /* Not found but gpgv's default "trustedkeys.kbx" file has been requested. We did not found it so now check whether a "trustedkeys.gpg" file exists and use that instead. */ KeydbResourceType rttmp; strcpy (filename+filenamelen-4, ".gpg"); rttmp = rt_from_file (filename, &found, &openpgp_flag); if (found && ((rttmp == KEYDB_RESOURCE_TYPE_KEYBOX && openpgp_flag) || (rttmp == KEYDB_RESOURCE_TYPE_KEYRING))) rt = rttmp; else /* Restore filename */ strcpy (filename+filenamelen-4, ".kbx"); } else if (!pass && is_default && create && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg")) { /* The file does not exist, the default resource has been requested, the file shall be created, and the file has a ".gpg" suffix. Change the suffix to ".kbx" and try once more. This way we achieve that we open an existing ".gpg" keyring, but create a new keybox file with an ".kbx" suffix. */ strcpy (filename+filenamelen-4, ".kbx"); pass++; goto check_again; } else /* No file yet: create keybox. */ rt = KEYDB_RESOURCE_TYPE_KEYBOX; } switch (rt) { case KEYDB_RESOURCE_TYPE_NONE: log_error ("unknown type of key resource '%s'\n", url ); err = gpg_error (GPG_ERR_GENERAL); goto leave; case KEYDB_RESOURCE_TYPE_KEYRING: err = maybe_create_keyring_or_box (filename, 0, create); if (err) goto leave; if (keyring_register_filename (filename, read_only, &token)) { if (used_resources >= MAX_KEYDB_RESOURCES) err = gpg_error (GPG_ERR_RESOURCE_LIMIT); else { if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) primary_keydb = token; all_resources[used_resources].type = rt; all_resources[used_resources].u.kr = NULL; /* Not used here */ all_resources[used_resources].token = token; used_resources++; } } else { /* This keyring was already registered, so ignore it. However, we can still mark it as primary even if it was already registered. */ if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) primary_keydb = token; } break; case KEYDB_RESOURCE_TYPE_KEYBOX: { err = maybe_create_keyring_or_box (filename, 1, create); if (err) goto leave; err = keybox_register_file (filename, 0, &token); if (!err) { if (used_resources >= MAX_KEYDB_RESOURCES) err = gpg_error (GPG_ERR_RESOURCE_LIMIT); else { KEYBOX_HANDLE kbxhd; if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) primary_keydb = token; all_resources[used_resources].type = rt; all_resources[used_resources].u.kb = NULL; /* Not used here */ all_resources[used_resources].token = token; /* Do a compress run if needed and no other user is * currently using the keybox. */ kbxhd = keybox_new_openpgp (token, 0); if (kbxhd) { if (!keybox_lock (kbxhd, 1, 0)) { keybox_compress (kbxhd); keybox_lock (kbxhd, 0, 0); } keybox_release (kbxhd); } used_resources++; } } else if (gpg_err_code (err) == GPG_ERR_EEXIST) { /* Already registered. We will mark it as the primary key if requested. */ if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) primary_keydb = token; } } break; default: log_error ("resource type of '%s' not supported\n", url); err = gpg_error (GPG_ERR_GENERAL); goto leave; } /* fixme: check directory permissions and print a warning */ leave: if (err) { log_error (_("keyblock resource '%s': %s\n"), filename, gpg_strerror (err)); write_status_error ("add_keyblock_resource", err); } else any_registered = 1; xfree (filename); return err; } void keydb_dump_stats (void) { log_info ("keydb: handles=%u locks=%u parse=%u get=%u\n", keydb_stats.handles, keydb_stats.locks, keydb_stats.parse_keyblocks, keydb_stats.get_keyblocks); log_info (" build=%u update=%u insert=%u delete=%u\n", keydb_stats.build_keyblocks, keydb_stats.update_keyblocks, keydb_stats.insert_keyblocks, keydb_stats.delete_keyblocks); log_info (" reset=%u found=%u not=%u cache=%u not=%u\n", keydb_stats.search_resets, keydb_stats.found, keydb_stats.notfound, keydb_stats.found_cached, keydb_stats.notfound_cached); log_info ("kid_not_found_cache: count=%u peak=%u flushes=%u\n", kid_not_found_stats.count, kid_not_found_stats.peak, kid_not_found_stats.flushes); } /* Create a new database handle. A database handle is similar to a file handle: it contains a local file position. This is used when searching: subsequent searches resume where the previous search left off. To rewind the position, use keydb_search_reset(). This function returns NULL on error, sets ERRNO, and prints an error diagnostic. */ KEYDB_HANDLE keydb_new (void) { KEYDB_HANDLE hd; int i, j; int die = 0; int reterrno; if (DBG_CLOCK) log_clock ("keydb_new"); hd = xtrycalloc (1, sizeof *hd); if (!hd) goto leave; hd->found = -1; hd->saved_found = -1; hd->is_reset = 1; log_assert (used_resources <= MAX_KEYDB_RESOURCES); for (i=j=0; ! die && i < used_resources; i++) { switch (all_resources[i].type) { case KEYDB_RESOURCE_TYPE_NONE: /* ignore */ break; case KEYDB_RESOURCE_TYPE_KEYRING: hd->active[j].type = all_resources[i].type; hd->active[j].token = all_resources[i].token; hd->active[j].u.kr = keyring_new (all_resources[i].token); if (!hd->active[j].u.kr) { reterrno = errno; die = 1; } j++; break; case KEYDB_RESOURCE_TYPE_KEYBOX: hd->active[j].type = all_resources[i].type; hd->active[j].token = all_resources[i].token; hd->active[j].u.kb = keybox_new_openpgp (all_resources[i].token, 0); if (!hd->active[j].u.kb) { reterrno = errno; die = 1; } j++; break; } } hd->used = j; active_handles++; keydb_stats.handles++; if (die) { keydb_release (hd); gpg_err_set_errno (reterrno); hd = NULL; } leave: if (!hd) log_error (_("error opening key DB: %s\n"), gpg_strerror (gpg_error_from_syserror())); return hd; } void keydb_release (KEYDB_HANDLE hd) { int i; if (!hd) return; log_assert (active_handles > 0); active_handles--; hd->keep_lock = 0; unlock_all (hd); for (i=0; i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: keyring_release (hd->active[i].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_release (hd->active[i].u.kb); break; } } keyblock_cache_clear (hd); xfree (hd); } /* Take a lock on the files immediately and not only during insert or * update. This lock is released with keydb_release. */ gpg_error_t keydb_lock (KEYDB_HANDLE hd) { gpg_error_t err; if (!hd) return gpg_error (GPG_ERR_INV_ARG); err = lock_all (hd); if (!err) hd->keep_lock = 1; return err; } /* Set a flag on the handle to suppress use of cached results. This * is required for updating a keyring and for key listings. Fixme: * Using a new parameter for keydb_new might be a better solution. */ void keydb_disable_caching (KEYDB_HANDLE hd) { if (hd) hd->no_caching = 1; } /* Return the file name of the resource in which the current search * result was found or, if there is no search result, the filename of * the current resource (i.e., the resource that the file position * points to). Note: the filename is not necessarily the URL used to * open it! * * This function only returns NULL if no handle is specified, in all * other error cases an empty string is returned. */ const char * keydb_get_resource_name (KEYDB_HANDLE hd) { int idx; const char *s = NULL; if (!hd) return NULL; if ( hd->found >= 0 && hd->found < hd->used) idx = hd->found; else if ( hd->current >= 0 && hd->current < hd->used) idx = hd->current; else idx = 0; switch (hd->active[idx].type) { case KEYDB_RESOURCE_TYPE_NONE: s = NULL; break; case KEYDB_RESOURCE_TYPE_KEYRING: s = keyring_get_resource_name (hd->active[idx].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: s = keybox_get_resource_name (hd->active[idx].u.kb); break; } return s? s: ""; } static int lock_all (KEYDB_HANDLE hd) { int i, rc = 0; /* Fixme: This locking scheme may lead to a deadlock if the resources are not added in the same order by all processes. We are currently only allowing one resource so it is not a problem. [Oops: Who claimed the latter] To fix this we need to use a lock file to protect lock_all. */ for (i=0; !rc && i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: rc = keyring_lock (hd->active[i].u.kr, 1); break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_lock (hd->active[i].u.kb, 1, -1); break; } } if (rc) { /* Revert the already taken locks. */ for (i--; i >= 0; i--) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: keyring_lock (hd->active[i].u.kr, 0); break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_lock (hd->active[i].u.kb, 0, 0); break; } } } else { hd->locked = 1; keydb_stats.locks++; } return rc; } static void unlock_all (KEYDB_HANDLE hd) { int i; if (!hd->locked || hd->keep_lock) return; for (i=hd->used-1; i >= 0; i--) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: keyring_lock (hd->active[i].u.kr, 0); break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_lock (hd->active[i].u.kb, 0, 0); break; } } hd->locked = 0; } /* Save the last found state and invalidate the current selection * (i.e., the entry selected by keydb_search() is invalidated and * something like keydb_get_keyblock() will return an error). This * does not change the file position. This makes it possible to do * something like: * * keydb_search (hd, ...); // Result 1. * keydb_push_found_state (hd); * keydb_search_reset (hd); * keydb_search (hd, ...); // Result 2. * keydb_pop_found_state (hd); * keydb_get_keyblock (hd, ...); // -> Result 1. * * Note: it is only possible to save a single save state at a time. * In other words, the save stack only has room for a single * instance of the state. */ void keydb_push_found_state (KEYDB_HANDLE hd) { if (!hd) return; if (hd->found < 0 || hd->found >= hd->used) { hd->saved_found = -1; return; } switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: keyring_push_found_state (hd->active[hd->found].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_push_found_state (hd->active[hd->found].u.kb); break; } hd->saved_found = hd->found; hd->found = -1; } /* Restore the previous save state. If the saved state is NULL or invalid, this is a NOP. */ void keydb_pop_found_state (KEYDB_HANDLE hd) { if (!hd) return; hd->found = hd->saved_found; hd->saved_found = -1; if (hd->found < 0 || hd->found >= hd->used) return; switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: keyring_pop_found_state (hd->active[hd->found].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_pop_found_state (hd->active[hd->found].u.kb); break; } } static gpg_error_t parse_keyblock_image (iobuf_t iobuf, int pk_no, int uid_no, kbnode_t *r_keyblock) { gpg_error_t err; struct parse_packet_ctx_s parsectx; PACKET *pkt; kbnode_t keyblock = NULL; kbnode_t node, *tail; int in_cert, save_mode; int pk_count, uid_count; *r_keyblock = NULL; pkt = xtrymalloc (sizeof *pkt); if (!pkt) return gpg_error_from_syserror (); init_packet (pkt); init_parse_packet (&parsectx, iobuf); save_mode = set_packet_list_mode (0); in_cert = 0; tail = NULL; pk_count = uid_count = 0; while ((err = parse_packet (&parsectx, pkt)) != -1) { if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET) { free_packet (pkt, &parsectx); init_packet (pkt); continue; } if (err) { es_fflush (es_stdout); log_error ("parse_keyblock_image: read error: %s\n", gpg_strerror (err)); if (gpg_err_code (err) == GPG_ERR_INV_PACKET) { free_packet (pkt, &parsectx); init_packet (pkt); continue; } /* Unknown version maybe due to v5 keys - we treat this * error different. */ if (gpg_err_code (err) != GPG_ERR_UNKNOWN_VERSION) err = gpg_error (GPG_ERR_INV_KEYRING); break; } /* Filter allowed packets. */ switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: case PKT_USER_ID: case PKT_ATTRIBUTE: case PKT_SIGNATURE: case PKT_RING_TRUST: break; /* Allowed per RFC. */ default: log_info ("skipped packet of type %d in keybox\n", (int)pkt->pkttype); free_packet(pkt, &parsectx); init_packet(pkt); continue; } /* Other sanity checks. */ if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY) { log_error ("parse_keyblock_image: first packet in a keybox blob " "is not a public key packet\n"); err = gpg_error (GPG_ERR_INV_KEYRING); break; } if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY || pkt->pkttype == PKT_SECRET_KEY)) { log_error ("parse_keyblock_image: " "multiple keyblocks in a keybox blob\n"); err = gpg_error (GPG_ERR_INV_KEYRING); break; } in_cert = 1; node = new_kbnode (pkt); switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: if (++pk_count == pk_no) node->flag |= 1; break; case PKT_USER_ID: if (++uid_count == uid_no) node->flag |= 2; break; default: break; } if (!keyblock) keyblock = node; else *tail = node; tail = &node->next; pkt = xtrymalloc (sizeof *pkt); if (!pkt) { err = gpg_error_from_syserror (); break; } init_packet (pkt); } set_packet_list_mode (save_mode); if (err == -1 && keyblock) err = 0; /* Got the entire keyblock. */ if (err) release_kbnode (keyblock); else { *r_keyblock = keyblock; keydb_stats.parse_keyblocks++; } free_packet (pkt, &parsectx); deinit_parse_packet (&parsectx); xfree (pkt); return err; } /* Return the keyblock last found by keydb_search() in *RET_KB. * * On success, the function returns 0 and the caller must free *RET_KB * using release_kbnode(). Otherwise, the function returns an error * code. * * The returned keyblock has the kbnode flag bit 0 set for the node * with the public key used to locate the keyblock or flag bit 1 set * for the user ID node. */ gpg_error_t keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb) { gpg_error_t err = 0; *ret_kb = NULL; if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (DBG_CLOCK) log_clock ("keydb_get_keybock enter"); if (hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED) { err = iobuf_seek (hd->keyblock_cache.iobuf, 0); if (err) { log_error ("keydb_get_keyblock: failed to rewind iobuf for cache\n"); keyblock_cache_clear (hd); } else { err = parse_keyblock_image (hd->keyblock_cache.iobuf, hd->keyblock_cache.pk_no, hd->keyblock_cache.uid_no, ret_kb); if (err) keyblock_cache_clear (hd); if (DBG_CLOCK) log_clock (err? "keydb_get_keyblock leave (cached, failed)" : "keydb_get_keyblock leave (cached)"); return err; } } if (hd->found < 0 || hd->found >= hd->used) return gpg_error (GPG_ERR_VALUE_NOT_FOUND); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYRING: err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb); break; case KEYDB_RESOURCE_TYPE_KEYBOX: { iobuf_t iobuf; int pk_no, uid_no; err = keybox_get_keyblock (hd->active[hd->found].u.kb, &iobuf, &pk_no, &uid_no); if (!err) { err = parse_keyblock_image (iobuf, pk_no, uid_no, ret_kb); if (!err && hd->keyblock_cache.state == KEYBLOCK_CACHE_PREPARED) { hd->keyblock_cache.state = KEYBLOCK_CACHE_FILLED; hd->keyblock_cache.iobuf = iobuf; hd->keyblock_cache.pk_no = pk_no; hd->keyblock_cache.uid_no = uid_no; } else { iobuf_close (iobuf); } } } break; } if (hd->keyblock_cache.state != KEYBLOCK_CACHE_FILLED) keyblock_cache_clear (hd); if (!err) keydb_stats.get_keyblocks++; if (DBG_CLOCK) log_clock (err? "keydb_get_keyblock leave (failed)" : "keydb_get_keyblock leave"); return err; } /* Build a keyblock image from KEYBLOCK. Returns 0 on success and * only then stores a new iobuf object at R_IOBUF. */ static gpg_error_t build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf) { gpg_error_t err; iobuf_t iobuf; kbnode_t kbctx, node; *r_iobuf = NULL; iobuf = iobuf_temp (); for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));) { /* Make sure to use only packets valid on a keyblock. */ switch (node->pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SIGNATURE: case PKT_USER_ID: case PKT_ATTRIBUTE: case PKT_RING_TRUST: break; default: continue; } err = build_packet_and_meta (iobuf, node->pkt); if (err) { iobuf_close (iobuf); return err; } } keydb_stats.build_keyblocks++; *r_iobuf = iobuf; return 0; } /* Update the keyblock KB (i.e., extract the fingerprint and find the * corresponding keyblock in the keyring). * * This doesn't do anything if --dry-run was specified. * * Returns 0 on success. Otherwise, it returns an error code. Note: * if there isn't a keyblock in the keyring corresponding to KB, then * this function returns GPG_ERR_VALUE_NOT_FOUND. * * This function selects the matching record and modifies the current * file position to point to the record just after the selected entry. * Thus, if you do a subsequent search using HD, you should first do a * keydb_search_reset. Further, if the selected record is important, * you should use keydb_push_found_state and keydb_pop_found_state to * save and restore it. */ gpg_error_t keydb_update_keyblock (ctrl_t ctrl, KEYDB_HANDLE hd, kbnode_t kb) { gpg_error_t err; PKT_public_key *pk; KEYDB_SEARCH_DESC desc; size_t len; log_assert (kb); log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY); pk = kb->pkt->pkt.public_key; if (!hd) return gpg_error (GPG_ERR_INV_ARG); kid_not_found_flush (); keyblock_cache_clear (hd); if (opt.dry_run) return 0; err = lock_all (hd); if (err) return err; #ifdef USE_TOFU tofu_notice_key_changed (ctrl, kb); #endif memset (&desc, 0, sizeof (desc)); fingerprint_from_pk (pk, desc.u.fpr, &len); if (len == 20) desc.mode = KEYDB_SEARCH_MODE_FPR20; else log_bug ("%s: Unsupported key length: %zu\n", __func__, len); keydb_search_reset (hd); err = keydb_search (hd, &desc, 1, NULL); if (err) return gpg_error (GPG_ERR_VALUE_NOT_FOUND); log_assert (hd->found >= 0 && hd->found < hd->used); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYRING: err = keyring_update_keyblock (hd->active[hd->found].u.kr, kb); break; case KEYDB_RESOURCE_TYPE_KEYBOX: { iobuf_t iobuf; err = build_keyblock_image (kb, &iobuf); if (!err) { err = keybox_update_keyblock (hd->active[hd->found].u.kb, iobuf_get_temp_buffer (iobuf), iobuf_get_temp_length (iobuf)); iobuf_close (iobuf); } } break; } unlock_all (hd); if (!err) keydb_stats.update_keyblocks++; return err; } /* Insert a keyblock into one of the underlying keyrings or keyboxes. * * Be default, the keyring / keybox from which the last search result * came is used. If there was no previous search result (or * keydb_search_reset was called), then the keyring / keybox where the * next search would start is used (i.e., the current file position). * * Note: this doesn't do anything if --dry-run was specified. * * Returns 0 on success. Otherwise, it returns an error code. */ gpg_error_t keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb) { gpg_error_t err; int idx; if (!hd) return gpg_error (GPG_ERR_INV_ARG); kid_not_found_flush (); keyblock_cache_clear (hd); if (opt.dry_run) return 0; if (hd->found >= 0 && hd->found < hd->used) idx = hd->found; else if (hd->current >= 0 && hd->current < hd->used) idx = hd->current; else return gpg_error (GPG_ERR_GENERAL); err = lock_all (hd); if (err) return err; switch (hd->active[idx].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYRING: err = keyring_insert_keyblock (hd->active[idx].u.kr, kb); break; case KEYDB_RESOURCE_TYPE_KEYBOX: { /* We need to turn our kbnode_t list of packets into a proper keyblock first. This is required by the OpenPGP key parser included in the keybox code. Eventually we can change this kludge to have the caller pass the image. */ iobuf_t iobuf; err = build_keyblock_image (kb, &iobuf); if (!err) { err = keybox_insert_keyblock (hd->active[idx].u.kb, iobuf_get_temp_buffer (iobuf), iobuf_get_temp_length (iobuf)); iobuf_close (iobuf); } } break; } unlock_all (hd); if (!err) keydb_stats.insert_keyblocks++; return err; } /* Delete the currently selected keyblock. If you haven't done a * search yet on this database handle (or called keydb_search_reset), * then this will return an error. * * Returns 0 on success or an error code, if an error occurs. */ gpg_error_t keydb_delete_keyblock (KEYDB_HANDLE hd) { gpg_error_t rc; if (!hd) return gpg_error (GPG_ERR_INV_ARG); kid_not_found_flush (); keyblock_cache_clear (hd); if (hd->found < 0 || hd->found >= hd->used) return gpg_error (GPG_ERR_VALUE_NOT_FOUND); if (opt.dry_run) return 0; rc = lock_all (hd); if (rc) return rc; switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: rc = gpg_error (GPG_ERR_GENERAL); break; case KEYDB_RESOURCE_TYPE_KEYRING: rc = keyring_delete_keyblock (hd->active[hd->found].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_delete (hd->active[hd->found].u.kb); break; } unlock_all (hd); if (!rc) keydb_stats.delete_keyblocks++; return rc; } /* A database may consists of multiple keyrings / key boxes. This * sets the "file position" to the start of the first keyring / key * box that is writable (i.e., doesn't have the read-only flag set). * * This first tries the primary keyring (the last keyring (not * keybox!) added using keydb_add_resource() and with * KEYDB_RESOURCE_FLAG_PRIMARY set). If that is not writable, then it * tries the keyrings / keyboxes in the order in which they were * added. */ gpg_error_t keydb_locate_writable (KEYDB_HANDLE hd) { gpg_error_t rc; if (!hd) return GPG_ERR_INV_ARG; rc = keydb_search_reset (hd); /* this does reset hd->current */ if (rc) return rc; /* If we have a primary set, try that one first */ if (primary_keydb) { for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++) { if(hd->active[hd->current].token == primary_keydb) { if(keyring_is_writable (hd->active[hd->current].token)) return 0; else break; } } rc = keydb_search_reset (hd); /* this does reset hd->current */ if (rc) return rc; } for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++) { switch (hd->active[hd->current].type) { case KEYDB_RESOURCE_TYPE_NONE: BUG(); break; case KEYDB_RESOURCE_TYPE_KEYRING: if (keyring_is_writable (hd->active[hd->current].token)) return 0; /* found (hd->current is set to it) */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: if (keybox_is_writable (hd->active[hd->current].token)) return 0; /* found (hd->current is set to it) */ break; } } return gpg_error (GPG_ERR_NOT_FOUND); } /* Rebuild the on-disk caches of all key resources. */ void keydb_rebuild_caches (ctrl_t ctrl, int noisy) { int i, rc; for (i=0; i < used_resources; i++) { if (!keyring_is_writable (all_resources[i].token)) continue; switch (all_resources[i].type) { case KEYDB_RESOURCE_TYPE_NONE: /* ignore */ break; case KEYDB_RESOURCE_TYPE_KEYRING: rc = keyring_rebuild_cache (ctrl, all_resources[i].token,noisy); if (rc) log_error (_("failed to rebuild keyring cache: %s\n"), gpg_strerror (rc)); break; case KEYDB_RESOURCE_TYPE_KEYBOX: /* N/A. */ break; } } } /* Return the number of skipped blocks (because they were to large to read from a keybox) since the last search reset. */ unsigned long keydb_get_skipped_counter (KEYDB_HANDLE hd) { return hd ? hd->skipped_long_blobs : 0; } /* Clears the current search result and resets the handle's position * so that the next search starts at the beginning of the database * (the start of the first resource). * * Returns 0 on success and an error code if an error occurred. * (Currently, this function always returns 0 if HD is valid.) */ gpg_error_t keydb_search_reset (KEYDB_HANDLE hd) { gpg_error_t rc = 0; int i; if (!hd) return gpg_error (GPG_ERR_INV_ARG); keyblock_cache_clear (hd); if (DBG_CLOCK) log_clock ("keydb_search_reset"); if (DBG_CACHE) log_debug ("keydb_search: reset (hd=%p)", hd); hd->skipped_long_blobs = 0; hd->current = 0; hd->found = -1; /* Now reset all resources. */ for (i=0; !rc && i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYRING: rc = keyring_search_reset (hd->active[i].u.kr); break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_search_reset (hd->active[i].u.kb); break; } } hd->is_reset = 1; if (!rc) keydb_stats.search_resets++; return rc; } /* Search the database for keys matching the search description. If * the DB contains any legacy keys, these are silently ignored. * * DESC is an array of search terms with NDESC entries. The search * terms are or'd together. That is, the next entry in the DB that * matches any of the descriptions will be returned. * * Note: this function resumes searching where the last search left * off (i.e., at the current file position). If you want to search * from the start of the database, then you need to first call * keydb_search_reset(). * * If no key matches the search description, returns * GPG_ERR_NOT_FOUND. If there was a match, returns 0. If an error * occurred, returns an error code. * * The returned key is considered to be selected and the raw data can, * for instance, be returned by calling keydb_get_keyblock(). */ gpg_error_t keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc, size_t *descindex) { int i; gpg_error_t rc; int was_reset = hd->is_reset; /* If an entry is already in the cache, then don't add it again. */ int already_in_cache = 0; if (descindex) *descindex = 0; /* Make sure it is always set on return. */ if (!hd) return gpg_error (GPG_ERR_INV_ARG); if (!any_registered) { write_status_error ("keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN)); return gpg_error (GPG_ERR_NOT_FOUND); } if (DBG_CLOCK) log_clock ("keydb_search enter"); if (DBG_LOOKUP) { log_debug ("%s: %zd search descriptions:\n", __func__, ndesc); for (i = 0; i < ndesc; i ++) { char *t = keydb_search_desc_dump (&desc[i]); log_debug ("%s %d: %s\n", __func__, i, t); xfree (t); } } if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && (already_in_cache = kid_not_found_p (desc[0].u.kid)) == 1 ) { if (DBG_CLOCK) log_clock ("keydb_search leave (not found, cached)"); keydb_stats.notfound_cached++; return gpg_error (GPG_ERR_NOT_FOUND); } /* NB: If one of the exact search modes below is used in a loop to walk over all keys (with the same fingerprint) the caching must have been disabled for the handle. */ if (!hd->no_caching && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20 || desc[0].mode == KEYDB_SEARCH_MODE_FPR) && hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, 20) /* Make sure the current file position occurs before the cached result to avoid an infinite loop. */ && (hd->current < hd->keyblock_cache.resource || (hd->current == hd->keyblock_cache.resource && (keybox_offset (hd->active[hd->current].u.kb) <= hd->keyblock_cache.offset)))) { /* (DESCINDEX is already set). */ if (DBG_CLOCK) log_clock ("keydb_search leave (cached)"); hd->current = hd->keyblock_cache.resource; /* HD->KEYBLOCK_CACHE.OFFSET is the last byte in the record. Seek just beyond that. */ keybox_seek (hd->active[hd->current].u.kb, hd->keyblock_cache.offset + 1); keydb_stats.found_cached++; return 0; } rc = -1; while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF) && hd->current >= 0 && hd->current < hd->used) { if (DBG_LOOKUP) log_debug ("%s: searching %s (resource %d of %d)\n", __func__, hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING ? "keyring" : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX ? "keybox" : "unknown type"), hd->current, hd->used); switch (hd->active[hd->current].type) { case KEYDB_RESOURCE_TYPE_NONE: BUG(); /* we should never see it here */ break; case KEYDB_RESOURCE_TYPE_KEYRING: rc = keyring_search (hd->active[hd->current].u.kr, desc, ndesc, descindex, 1); break; case KEYDB_RESOURCE_TYPE_KEYBOX: do rc = keybox_search (hd->active[hd->current].u.kb, desc, ndesc, KEYBOX_BLOBTYPE_PGP, descindex, &hd->skipped_long_blobs); while (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY || gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION) ; break; } if (DBG_LOOKUP) log_debug ("%s: searched %s (resource %d of %d) => %s\n", __func__, hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING ? "keyring" : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX ? "keybox" : "unknown type"), hd->current, hd->used, rc == -1 ? "EOF" : gpg_strerror (rc)); if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF) { /* EOF -> switch to next resource */ hd->current++; } else if (!rc) hd->found = hd->current; } hd->is_reset = 0; rc = ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF) ? gpg_error (GPG_ERR_NOT_FOUND) : rc); keyblock_cache_clear (hd); if (!hd->no_caching && !rc && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20 || desc[0].mode == KEYDB_SEARCH_MODE_FPR) && hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX) { hd->keyblock_cache.state = KEYBLOCK_CACHE_PREPARED; hd->keyblock_cache.resource = hd->current; /* The current offset is at the start of the next record. Since a record is at least 1 byte, we just use offset - 1, which is within the record. */ hd->keyblock_cache.offset = keybox_offset (hd->active[hd->current].u.kb) - 1; memcpy (hd->keyblock_cache.fpr, desc[0].u.fpr, 20); } if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && was_reset && !already_in_cache) kid_not_found_insert (desc[0].u.kid); if (DBG_CLOCK) log_clock (rc? "keydb_search leave (not found)" : "keydb_search leave (found)"); if (!rc) keydb_stats.found++; else keydb_stats.notfound++; return rc; } /* Return the first non-legacy key in the database. * * If you want the very first key in the database, you can directly * call keydb_search with the search description * KEYDB_SEARCH_MODE_FIRST. */ gpg_error_t keydb_search_first (KEYDB_HANDLE hd) { gpg_error_t err; KEYDB_SEARCH_DESC desc; err = keydb_search_reset (hd); if (err) return err; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FIRST; return keydb_search (hd, &desc, 1, NULL); } /* Return the next key (not the next matching key!). * * Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this * function silently skips legacy keys. */ gpg_error_t keydb_search_next (KEYDB_HANDLE hd) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_NEXT; return keydb_search (hd, &desc, 1, NULL); } /* This is a convenience function for searching for keys with a long * key id. * * Note: this function resumes searching where the last search left * off. If you want to search the whole database, then you need to * first call keydb_search_reset(). */ gpg_error_t keydb_search_kid (KEYDB_HANDLE hd, u32 *kid) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0] = kid[0]; desc.u.kid[1] = kid[1]; return keydb_search (hd, &desc, 1, NULL); } /* This is a convenience function for searching for keys with a long * (20 byte) fingerprint. * * Note: this function resumes searching where the last search left * off. If you want to search the whole database, then you need to * first call keydb_search_reset(). */ gpg_error_t keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FPR; memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN); return keydb_search (hd, &desc, 1, NULL); } diff --git a/g10/migrate.c b/g10/migrate.c index 9045ae66e..38fb7bd68 100644 --- a/g10/migrate.c +++ b/g10/migrate.c @@ -1,118 +1,118 @@ /* migrate.c - Migrate from earlier GnupG versions. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "options.h" #include "keydb.h" #include "../common/util.h" #include "main.h" #include "call-agent.h" #ifdef HAVE_DOSISH_SYSTEM # define V21_MIGRATION_FNAME "gpg-v21-migrated" #else # define V21_MIGRATION_FNAME ".gpg-v21-migrated" #endif /* Check whether a default secring.gpg from GnuPG < 2.1 exists and import it if not yet done. */ void migrate_secring (ctrl_t ctrl) { dotlock_t lockhd = NULL; char *secring = NULL; char *flagfile = NULL; char *agent_version = NULL; secring = make_filename (gnupg_homedir (), "secring" EXTSEP_S "gpg", NULL); if (gnupg_access (secring, F_OK)) goto leave; /* Does not exist or is not readable. */ flagfile = make_filename (gnupg_homedir (), V21_MIGRATION_FNAME, NULL); if (!gnupg_access (flagfile, F_OK)) goto leave; /* Does exist - fine. */ log_info ("starting migration from earlier GnuPG versions\n"); lockhd = dotlock_create (flagfile, 0); if (!lockhd) { log_error ("can't allocate lock for '%s': %s\n", flagfile, gpg_strerror (gpg_error_from_syserror ())); goto leave; } if (dotlock_take (lockhd, -1)) { log_error ("can't lock '%s': %s\n", flagfile, gpg_strerror (gpg_error_from_syserror ())); dotlock_destroy (lockhd); lockhd = NULL; goto leave; } if (!agent_get_version (ctrl, &agent_version)) { if (!gnupg_compare_version (agent_version, "2.1.0")) { log_error ("error: GnuPG agent version \"%s\" is too old. ", agent_version); log_info ("Please make sure that a recent gpg-agent is running.\n"); log_info ("(restarting the user session may achieve this.)\n"); log_info ("migration aborted\n"); xfree (agent_version); goto leave; } xfree (agent_version); } else { log_error ("error: GnuPG agent unusable. " "Please check that a GnuPG agent can be started.\n"); log_error ("migration aborted\n"); goto leave; } log_info ("porting secret keys from '%s' to gpg-agent\n", secring); if (!import_old_secring (ctrl, secring)) { - FILE *fp = fopen (flagfile, "w"); - if (!fp || fclose (fp)) + estream_t fp = es_fopen (flagfile, "w"); + if (!fp || es_fclose (fp)) log_error ("error creating flag file '%s': %s\n", flagfile, gpg_strerror (gpg_error_from_syserror ())); else log_info ("migration succeeded\n"); } leave: if (lockhd) { dotlock_release (lockhd); dotlock_destroy (lockhd); } xfree (flagfile); xfree (secring); } diff --git a/g10/tdbio.c b/g10/tdbio.c index 9c77bc4b2..947dbb36d 100644 --- a/g10/tdbio.c +++ b/g10/tdbio.c @@ -1,1933 +1,1933 @@ /* tdbio.c - trust database I/O operations * Copyright (C) 1998-2002, 2012 Free Software Foundation, Inc. * Copyright (C) 1998-2015 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include "gpg.h" #include "../common/status.h" #include "../common/iobuf.h" #include "../common/util.h" #include "options.h" #include "main.h" #include "../common/i18n.h" #include "trustdb.h" #include "tdbio.h" #if defined(HAVE_DOSISH_SYSTEM) && !defined(ftruncate) #define ftruncate chsize #endif #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__) #define MY_O_BINARY O_BINARY #else #define MY_O_BINARY 0 #endif /* We use ERRNO despite that the cegcc provided open/read/write functions don't set ERRNO - at least show that ERRNO does not make sense. */ #ifdef HAVE_W32CE_SYSTEM #undef strerror #define strerror(a) ("[errno not available]") #endif /* * Yes, this is a very simple implementation. We should really * use a page aligned buffer and read complete pages. * To implement a simple trannsaction system, this is sufficient. */ typedef struct cache_ctrl_struct *CACHE_CTRL; struct cache_ctrl_struct { CACHE_CTRL next; struct { unsigned used:1; unsigned dirty:1; } flags; ulong recno; char data[TRUST_RECORD_LEN]; }; /* Size of the cache. The SOFT value is the general one. While in a transaction this may not be sufficient and thus we may increase it then up to the HARD limit. */ #define MAX_CACHE_ENTRIES_SOFT 200 #define MAX_CACHE_ENTRIES_HARD 10000 /* The cache is controlled by these variables. */ static CACHE_CTRL cache_list; static int cache_entries; static int cache_is_dirty; /* An object to pass information to cmp_krec_fpr. */ struct cmp_krec_fpr_struct { int pubkey_algo; const char *fpr; int fprlen; }; /* An object used to pass information to cmp_[s]dir. */ struct cmp_xdir_struct { int pubkey_algo; u32 keyid[2]; }; /* The name of the trustdb file. */ static char *db_name; /* The handle for locking the trustdb file and a counter to record how * often this lock has been taken. That counter is required becuase * dotlock does not implemen recursive locks. */ static dotlock_t lockhandle; static unsigned int is_locked; /* The file descriptor of the trustdb. */ static int db_fd = -1; /* A flag indicating that a transaction is active. */ /* static int in_transaction; Not yet used. */ static void open_db (void); static void create_hashtable (ctrl_t ctrl, TRUSTREC *vr, int type); /* * Take a lock on the trustdb file name. I a lock file can't be * created the function terminates the process. Except for a * different return code the function does nothing if the lock has * already been taken. * * Returns: True if lock already exists, False if the lock has * actually been taken. */ static int take_write_lock (void) { int rc; if (!lockhandle) lockhandle = dotlock_create (db_name, 0); if (!lockhandle) log_fatal ( _("can't create lock for '%s'\n"), db_name ); if (!is_locked) { if (dotlock_take (lockhandle, -1) ) log_fatal ( _("can't lock '%s'\n"), db_name ); rc = 0; } else rc = 1; if (opt.lock_once) is_locked = 1; else is_locked++; return rc; } /* * Release a lock from the trustdb file unless the global option * --lock-once has been used. */ static void release_write_lock (void) { if (opt.lock_once) return; /* Don't care; here IS_LOCKED is fixed to 1. */ if (!is_locked) { log_error ("Ooops, tdbio:release_write_lock with no lock held\n"); return; } if (--is_locked) return; if (dotlock_release (lockhandle)) log_error ("Oops, tdbio:release_write_locked failed\n"); } /************************************* ************* record cache ********** *************************************/ /* * Get the data from the record cache and return a pointer into that * cache. Caller should copy the returned data. NULL is returned on * a cache miss. */ static const char * get_record_from_cache (ulong recno) { CACHE_CTRL r; for (r = cache_list; r; r = r->next) { if (r->flags.used && r->recno == recno) return r->data; } return NULL; } /* * Write a cached item back to the trustdb file. * * Returns: 0 on success or an error code. */ static int write_cache_item (CACHE_CTRL r) { gpg_error_t err; int n; if (lseek (db_fd, r->recno * TRUST_RECORD_LEN, SEEK_SET) == -1) { err = gpg_error_from_syserror (); log_error (_("trustdb rec %lu: lseek failed: %s\n"), r->recno, strerror (errno)); return err; } n = write (db_fd, r->data, TRUST_RECORD_LEN); if (n != TRUST_RECORD_LEN) { err = gpg_error_from_syserror (); log_error (_("trustdb rec %lu: write failed (n=%d): %s\n"), r->recno, n, strerror (errno) ); return err; } r->flags.dirty = 0; return 0; } /* * Put data into the cache. This function may flush * some cache entries if the cache is filled up. * * Returns: 0 on success or an error code. */ static int put_record_into_cache (ulong recno, const char *data) { CACHE_CTRL r, unused; int dirty_count = 0; int clean_count = 0; /* See whether we already cached this one. */ for (unused = NULL, r = cache_list; r; r = r->next) { if (!r->flags.used) { if (!unused) unused = r; } else if (r->recno == recno) { if (!r->flags.dirty) { /* Hmmm: should we use a copy and compare? */ if (memcmp (r->data, data, TRUST_RECORD_LEN)) { r->flags.dirty = 1; cache_is_dirty = 1; } } memcpy (r->data, data, TRUST_RECORD_LEN); return 0; } if (r->flags.used) { if (r->flags.dirty) dirty_count++; else clean_count++; } } /* Not in the cache: add a new entry. */ if (unused) { /* Reuse this entry. */ r = unused; r->flags.used = 1; r->recno = recno; memcpy (r->data, data, TRUST_RECORD_LEN); r->flags.dirty = 1; cache_is_dirty = 1; cache_entries++; return 0; } /* See whether we reached the limit. */ if (cache_entries < MAX_CACHE_ENTRIES_SOFT) { /* No: Put into cache. */ r = xmalloc (sizeof *r); r->flags.used = 1; r->recno = recno; memcpy (r->data, data, TRUST_RECORD_LEN); r->flags.dirty = 1; r->next = cache_list; cache_list = r; cache_is_dirty = 1; cache_entries++; return 0; } /* Cache is full: discard some clean entries. */ if (clean_count) { int n; /* We discard a third of the clean entries. */ n = clean_count / 3; if (!n) n = 1; for (unused = NULL, r = cache_list; r; r = r->next) { if (r->flags.used && !r->flags.dirty) { if (!unused) unused = r; r->flags.used = 0; cache_entries--; if (!--n) break; } } /* Now put into the cache. */ log_assert (unused); r = unused; r->flags.used = 1; r->recno = recno; memcpy (r->data, data, TRUST_RECORD_LEN); r->flags.dirty = 1; cache_is_dirty = 1; cache_entries++; return 0; } /* No clean entries: We have to flush some dirty entries. */ #if 0 /* Transactions are not yet used. */ if (in_transaction) { /* But we can't do this while in a transaction. Thus we * increase the cache size instead. */ if (cache_entries < MAX_CACHE_ENTRIES_HARD) { if (opt.debug && !(cache_entries % 100)) log_debug ("increasing tdbio cache size\n"); r = xmalloc (sizeof *r); r->flags.used = 1; r->recno = recno; memcpy (r->data, data, TRUST_RECORD_LEN); r->flags.dirty = 1; r->next = cache_list; cache_list = r; cache_is_dirty = 1; cache_entries++; return 0; } /* Hard limit for the cache size reached. */ log_info (_("trustdb transaction too large\n")); return GPG_ERR_RESOURCE_LIMIT; } #endif if (dirty_count) { int n; /* Discard some dirty entries. */ n = dirty_count / 5; if (!n) n = 1; take_write_lock (); for (unused = NULL, r = cache_list; r; r = r->next) { if (r->flags.used && r->flags.dirty) { int rc; rc = write_cache_item (r); if (rc) return rc; if (!unused) unused = r; r->flags.used = 0; cache_entries--; if (!--n) break; } } release_write_lock (); /* Now put into the cache. */ log_assert (unused); r = unused; r->flags.used = 1; r->recno = recno; memcpy (r->data, data, TRUST_RECORD_LEN); r->flags.dirty = 1; cache_is_dirty = 1; cache_entries++; return 0; } /* We should never reach this. */ BUG(); } /* Return true if the cache is dirty. */ int tdbio_is_dirty() { return cache_is_dirty; } /* * Flush the cache. This cannot be used while in a transaction. */ int tdbio_sync() { CACHE_CTRL r; int did_lock = 0; if( db_fd == -1 ) open_db(); #if 0 /* Transactions are not yet used. */ if( in_transaction ) log_bug("tdbio: syncing while in transaction\n"); #endif if( !cache_is_dirty ) return 0; if (!take_write_lock ()) did_lock = 1; for( r = cache_list; r; r = r->next ) { if( r->flags.used && r->flags.dirty ) { int rc = write_cache_item( r ); if( rc ) return rc; } } cache_is_dirty = 0; if (did_lock) release_write_lock (); return 0; } #if 0 /* Not yet used. */ /* * Simple transactions system: * Everything between begin_transaction and end/cancel_transaction * is not immediately written but at the time of end_transaction. * * NOTE: The transaction code is disabled in the 1.2 branch, as it is * not yet used. */ int tdbio_begin_transaction () /* Not yet used. */ { int rc; if (in_transaction) log_bug ("tdbio: nested transactions\n"); /* Flush everything out. */ rc = tdbio_sync(); if (rc) return rc; in_transaction = 1; return 0; } int tdbio_end_transaction () /* Not yet used. */ { int rc; if (!in_transaction) log_bug ("tdbio: no active transaction\n"); take_write_lock (); gnupg_block_all_signals (); in_transaction = 0; rc = tdbio_sync(); gnupg_unblock_all_signals(); release_write_lock (); return rc; } int tdbio_cancel_transaction () /* Not yet used. */ { CACHE_CTRL r; if (!in_transaction) log_bug ("tdbio: no active transaction\n"); /* Remove all dirty marked entries, so that the original ones are * read back the next time. */ if (cache_is_dirty) { for (r = cache_list; r; r = r->next) { if (r->flags.used && r->flags.dirty) { r->flags.used = 0; cache_entries--; } } cache_is_dirty = 0; } in_transaction = 0; return 0; } #endif /* Not yet used. */ /******************************************************** **************** cached I/O functions ****************** ********************************************************/ /* The cleanup handler for this module. */ static void cleanup (void) { if (is_locked) { if (!dotlock_release (lockhandle)) is_locked = 0; } } /* * Update an existing trustdb record. The caller must call * tdbio_sync. * * Returns: 0 on success or an error code. */ int tdbio_update_version_record (ctrl_t ctrl) { TRUSTREC rec; int rc; int opt_tm; /* Never store a TOFU trust model in the trustdb. Use PGP instead. */ opt_tm = opt.trust_model; if (opt_tm == TM_TOFU || opt_tm == TM_TOFU_PGP) opt_tm = TM_PGP; memset (&rec, 0, sizeof rec); rc = tdbio_read_record (0, &rec, RECTYPE_VER); if (!rc) { rec.r.ver.created = make_timestamp(); rec.r.ver.marginals = opt.marginals_needed; rec.r.ver.completes = opt.completes_needed; rec.r.ver.cert_depth = opt.max_cert_depth; rec.r.ver.trust_model = opt_tm; rec.r.ver.min_cert_level = opt.min_cert_level; rc = tdbio_write_record (ctrl, &rec); } return rc; } /* * Create and write the trustdb version record. * This is called with the writelock activ. * Returns: 0 on success or an error code. */ static int create_version_record (ctrl_t ctrl) { TRUSTREC rec; int rc; int opt_tm; /* Never store a TOFU trust model in the trustdb. Use PGP instead. */ opt_tm = opt.trust_model; if (opt_tm == TM_TOFU || opt_tm == TM_TOFU_PGP) opt_tm = TM_PGP; memset (&rec, 0, sizeof rec); rec.r.ver.version = 3; rec.r.ver.created = make_timestamp (); rec.r.ver.marginals = opt.marginals_needed; rec.r.ver.completes = opt.completes_needed; rec.r.ver.cert_depth = opt.max_cert_depth; if (opt_tm == TM_PGP || opt_tm == TM_CLASSIC) rec.r.ver.trust_model = opt_tm; else rec.r.ver.trust_model = TM_PGP; rec.r.ver.min_cert_level = opt.min_cert_level; rec.rectype = RECTYPE_VER; rec.recnum = 0; rc = tdbio_write_record (ctrl, &rec); if (!rc) tdbio_sync (); if (!rc) create_hashtable (ctrl, &rec, 0); return rc; } /* * Set the file name for the trustdb to NEW_DBNAME and if CREATE is * true create that file. If NEW_DBNAME is NULL a default name is * used, if the it does not contain a path component separator ('/') * the global GnuPG home directory is used. * * Returns: 0 on success or an error code. * * On the first call this function registers an atexit handler. * */ int tdbio_set_dbname (ctrl_t ctrl, const char *new_dbname, int create, int *r_nofile) { char *fname, *p; struct stat statbuf; static int initialized = 0; int save_slash; if (!initialized) { atexit (cleanup); initialized = 1; } *r_nofile = 0; if (!new_dbname) { fname = make_filename (gnupg_homedir (), "trustdb" EXTSEP_S GPGEXT_GPG, NULL); } else if (*new_dbname != DIRSEP_C ) { if (strchr (new_dbname, DIRSEP_C)) fname = make_filename (new_dbname, NULL); else fname = make_filename (gnupg_homedir (), new_dbname, NULL); } else { fname = xstrdup (new_dbname); } xfree (db_name); db_name = fname; /* Quick check for (likely) case where there already is a * trustdb.gpg. This check is not required in theory, but it helps * in practice avoiding costly operations of preparing and taking * the lock. */ if (!stat (fname, &statbuf) && statbuf.st_size > 0) { /* OK, we have the valid trustdb.gpg already. */ return 0; } else if (!create) { *r_nofile = 1; return 0; } /* Here comes: No valid trustdb.gpg AND CREATE==1 */ /* * Make sure the directory exists. This should be done before * acquiring the lock, which assumes the existence of the directory. */ p = strrchr (fname, DIRSEP_C); #if HAVE_W32_SYSTEM { /* Windows may either have a slash or a backslash. Take care of it. */ char *pp = strrchr (fname, '/'); if (!p || pp > p) p = pp; } #endif /*HAVE_W32_SYSTEM*/ log_assert (p); save_slash = *p; *p = 0; if (gnupg_access (fname, F_OK)) { try_make_homedir (fname); if (gnupg_access (fname, F_OK)) log_fatal (_("%s: directory does not exist!\n"), fname); } *p = save_slash; take_write_lock (); if (gnupg_access (fname, R_OK) || stat (fname, &statbuf) || statbuf.st_size == 0) { - FILE *fp; + estream_t fp; TRUSTREC rec; int rc; mode_t oldmask; #ifdef HAVE_W32CE_SYSTEM /* We know how the cegcc implementation of access works ;-). */ if (GetLastError () == ERROR_FILE_NOT_FOUND) gpg_err_set_errno (ENOENT); else gpg_err_set_errno (EIO); #endif /*HAVE_W32CE_SYSTEM*/ if (errno && errno != ENOENT) log_fatal ( _("can't access '%s': %s\n"), fname, strerror (errno)); oldmask = umask (077); if (is_secured_filename (fname)) { fp = NULL; gpg_err_set_errno (EPERM); } else - fp = fopen (fname, "wb"); + fp = es_fopen (fname, "wb"); umask(oldmask); if (!fp) log_fatal (_("can't create '%s': %s\n"), fname, strerror (errno)); - fclose (fp); + es_fclose (fp); db_fd = open (db_name, O_RDWR | MY_O_BINARY); if (db_fd == -1) log_fatal (_("can't open '%s': %s\n"), db_name, strerror (errno)); rc = create_version_record (ctrl); if (rc) log_fatal (_("%s: failed to create version record: %s"), fname, gpg_strerror (rc)); /* Read again to check that we are okay. */ if (tdbio_read_record (0, &rec, RECTYPE_VER)) log_fatal (_("%s: invalid trustdb created\n"), db_name); if (!opt.quiet) log_info (_("%s: trustdb created\n"), db_name); } release_write_lock (); return 0; } /* * Return the full name of the trustdb. */ const char * tdbio_get_dbname () { return db_name; } /* * Open the trustdb. This may only be called if it has not yet been * opened and after a successful call to tdbio_set_dbname. On return * the trustdb handle (DB_FD) is guaranteed to be open. */ static void open_db () { TRUSTREC rec; log_assert( db_fd == -1 ); #ifdef HAVE_W32CE_SYSTEM { DWORD prevrc = 0; wchar_t *wname = utf8_to_wchar (db_name); if (wname) { db_fd = (int)CreateFile (wname, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); xfree (wname); } if (db_fd == -1) log_fatal ("can't open '%s': %d, %d\n", db_name, (int)prevrc, (int)GetLastError ()); } #else /*!HAVE_W32CE_SYSTEM*/ db_fd = open (db_name, O_RDWR | MY_O_BINARY ); if (db_fd == -1 && (errno == EACCES #ifdef EROFS || errno == EROFS #endif ) ) { /* Take care of read-only trustdbs. */ db_fd = open (db_name, O_RDONLY | MY_O_BINARY ); if (db_fd != -1 && !opt.quiet) log_info (_("Note: trustdb not writable\n")); } if ( db_fd == -1 ) log_fatal( _("can't open '%s': %s\n"), db_name, strerror(errno) ); #endif /*!HAVE_W32CE_SYSTEM*/ register_secured_file (db_name); /* Read the version record. */ if (tdbio_read_record (0, &rec, RECTYPE_VER ) ) log_fatal( _("%s: invalid trustdb\n"), db_name ); } /* * Append a new empty hashtable to the trustdb. TYPE gives the type * of the hash table. The only defined type is 0 for a trust hash. * On return the hashtable has been created, written, the version * record update, and the data flushed to the disk. On a fatal error * the function terminates the process. */ static void create_hashtable (ctrl_t ctrl, TRUSTREC *vr, int type) { TRUSTREC rec; off_t offset; ulong recnum; int i, n, rc; offset = lseek (db_fd, 0, SEEK_END); if (offset == -1) log_fatal ("trustdb: lseek to end failed: %s\n", strerror(errno)); recnum = offset / TRUST_RECORD_LEN; log_assert (recnum); /* This is will never be the first record. */ if (!type) vr->r.ver.trusthashtbl = recnum; /* Now write the records making up the hash table. */ n = (256+ITEMS_PER_HTBL_RECORD-1) / ITEMS_PER_HTBL_RECORD; for (i=0; i < n; i++, recnum++) { memset (&rec, 0, sizeof rec); rec.rectype = RECTYPE_HTBL; rec.recnum = recnum; rc = tdbio_write_record (ctrl, &rec); if (rc) log_fatal (_("%s: failed to create hashtable: %s\n"), db_name, gpg_strerror (rc)); } /* Update the version record and flush. */ rc = tdbio_write_record (ctrl, vr); if (!rc) rc = tdbio_sync (); if (rc) log_fatal (_("%s: error updating version record: %s\n"), db_name, gpg_strerror (rc)); } /* * Check whether open trustdb matches the global trust options given * for this process. On a read problem the process is terminated. * * Return: 1 for yes, 0 for no. */ int tdbio_db_matches_options() { static int yes_no = -1; if (yes_no == -1) { TRUSTREC vr; int rc; int opt_tm, tm; rc = tdbio_read_record (0, &vr, RECTYPE_VER); if( rc ) log_fatal( _("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc) ); /* Consider tofu and pgp the same. */ tm = vr.r.ver.trust_model; if (tm == TM_TOFU || tm == TM_TOFU_PGP) tm = TM_PGP; opt_tm = opt.trust_model; if (opt_tm == TM_TOFU || opt_tm == TM_TOFU_PGP) opt_tm = TM_PGP; yes_no = vr.r.ver.marginals == opt.marginals_needed && vr.r.ver.completes == opt.completes_needed && vr.r.ver.cert_depth == opt.max_cert_depth && tm == opt_tm && vr.r.ver.min_cert_level == opt.min_cert_level; } return yes_no; } /* * Read and return the trust model identifier from the trustdb. On a * read problem the process is terminated. */ byte tdbio_read_model (void) { TRUSTREC vr; int rc; rc = tdbio_read_record (0, &vr, RECTYPE_VER ); if (rc) log_fatal (_("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc) ); return vr.r.ver.trust_model; } /* * Read and return the nextstamp value from the trustdb. On a read * problem the process is terminated. */ ulong tdbio_read_nextcheck () { TRUSTREC vr; int rc; rc = tdbio_read_record (0, &vr, RECTYPE_VER); if (rc) log_fatal (_("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc)); return vr.r.ver.nextcheck; } /* * Write the STAMP nextstamp timestamp to the trustdb. On a read or * write problem the process is terminated. * * Return: True if the stamp actually changed. */ int tdbio_write_nextcheck (ctrl_t ctrl, ulong stamp) { TRUSTREC vr; int rc; rc = tdbio_read_record (0, &vr, RECTYPE_VER); if (rc) log_fatal (_("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc)); if (vr.r.ver.nextcheck == stamp) return 0; vr.r.ver.nextcheck = stamp; rc = tdbio_write_record (ctrl, &vr); if (rc) log_fatal (_("%s: error writing version record: %s\n"), db_name, gpg_strerror (rc)); return 1; } /* * Return the record number of the trusthash table or create one if it * does not yet exist. On a read or write problem the process is * terminated. * * Return: record number */ static ulong get_trusthashrec (ctrl_t ctrl) { static ulong trusthashtbl; /* Record number of the trust hashtable. */ (void)ctrl; if (!trusthashtbl) { TRUSTREC vr; int rc; rc = tdbio_read_record (0, &vr, RECTYPE_VER ); if (rc) log_fatal (_("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc) ); if (!vr.r.ver.trusthashtbl) { /* Oops: the trustdb is corrupt because the hashtable is * always created along with the version record. However, * if something went initially wrong it may happen that * there is just the version record. We try to fix it here. * If we can't do that we return 0 - this is the version * record and thus the actual read will detect the mismatch * and bail out. Note that create_hashtable updates VR. */ take_write_lock (); if (lseek (db_fd, 0, SEEK_END) == TRUST_RECORD_LEN) create_hashtable (ctrl, &vr, 0); release_write_lock (); } trusthashtbl = vr.r.ver.trusthashtbl; } return trusthashtbl; } /* * Update a hashtable in the trustdb. TABLE gives the start of the * table, KEY and KEYLEN are the key, NEWRECNUM is the record number * to insert into the table. * * Return: 0 on success or an error code. */ static int upd_hashtable (ctrl_t ctrl, ulong table, byte *key, int keylen, ulong newrecnum) { TRUSTREC lastrec, rec; ulong hashrec, item; int msb; int level = 0; int rc, i; hashrec = table; next_level: msb = key[level]; hashrec += msb / ITEMS_PER_HTBL_RECORD; rc = tdbio_read_record (hashrec, &rec, RECTYPE_HTBL); if (rc) { log_error ("upd_hashtable: read failed: %s\n", gpg_strerror (rc)); return rc; } item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD]; if (!item) /* Insert a new item into the hash table. */ { rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = newrecnum; rc = tdbio_write_record (ctrl, &rec); if (rc) { log_error ("upd_hashtable: write htbl failed: %s\n", gpg_strerror (rc)); return rc; } } else if (item != newrecnum) /* Must do an update. */ { lastrec = rec; rc = tdbio_read_record (item, &rec, 0); if (rc) { log_error ("upd_hashtable: read item failed: %s\n", gpg_strerror (rc)); return rc; } if (rec.rectype == RECTYPE_HTBL) { hashrec = item; level++; if (level >= keylen) { log_error ("hashtable has invalid indirections.\n"); return GPG_ERR_TRUSTDB; } goto next_level; } else if (rec.rectype == RECTYPE_HLST) /* Extend the list. */ { /* Check whether the key is already in this list. */ for (;;) { for (i=0; i < ITEMS_PER_HLST_RECORD; i++) { if (rec.r.hlst.rnum[i] == newrecnum) { return 0; /* Okay, already in the list. */ } } if (rec.r.hlst.next) { rc = tdbio_read_record (rec.r.hlst.next, &rec, RECTYPE_HLST); if (rc) { log_error ("upd_hashtable: read hlst failed: %s\n", gpg_strerror (rc) ); return rc; } } else break; /* key is not in the list */ } /* Find the next free entry and put it in. */ for (;;) { for (i=0; i < ITEMS_PER_HLST_RECORD; i++) { if (!rec.r.hlst.rnum[i]) { /* Empty slot found. */ rec.r.hlst.rnum[i] = newrecnum; rc = tdbio_write_record (ctrl, &rec); if (rc) log_error ("upd_hashtable: write hlst failed: %s\n", gpg_strerror (rc)); return rc; /* Done. */ } } if (rec.r.hlst.next) { /* read the next reord of the list. */ rc = tdbio_read_record (rec.r.hlst.next, &rec, RECTYPE_HLST); if (rc) { log_error ("upd_hashtable: read hlst failed: %s\n", gpg_strerror (rc)); return rc; } } else { /* Append a new record to the list. */ rec.r.hlst.next = item = tdbio_new_recnum (ctrl); rc = tdbio_write_record (ctrl, &rec); if (rc) { log_error ("upd_hashtable: write hlst failed: %s\n", gpg_strerror (rc)); return rc; } memset (&rec, 0, sizeof rec); rec.rectype = RECTYPE_HLST; rec.recnum = item; rec.r.hlst.rnum[0] = newrecnum; rc = tdbio_write_record (ctrl, &rec); if (rc) log_error ("upd_hashtable: write ext hlst failed: %s\n", gpg_strerror (rc)); return rc; /* Done. */ } } /* end loop over list slots */ } else if (rec.rectype == RECTYPE_TRUST) /* Insert a list record. */ { if (rec.recnum == newrecnum) { return 0; } item = rec.recnum; /* Save number of key record. */ memset (&rec, 0, sizeof rec); rec.rectype = RECTYPE_HLST; rec.recnum = tdbio_new_recnum (ctrl); rec.r.hlst.rnum[0] = item; /* Old key record */ rec.r.hlst.rnum[1] = newrecnum; /* and new key record */ rc = tdbio_write_record (ctrl, &rec); if (rc) { log_error( "upd_hashtable: write new hlst failed: %s\n", gpg_strerror (rc) ); return rc; } /* Update the hashtable record. */ lastrec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = rec.recnum; rc = tdbio_write_record (ctrl, &lastrec); if (rc) log_error ("upd_hashtable: update htbl failed: %s\n", gpg_strerror (rc)); return rc; /* Ready. */ } else { log_error ("hashtbl %lu: %lu/%d points to an invalid record %lu\n", table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item); if (opt.verbose > 1) list_trustdb (ctrl, es_stderr, NULL); return GPG_ERR_TRUSTDB; } } return 0; } /* * Drop an entry from a hashtable. TABLE gives the start of the * table, KEY and KEYLEN are the key. * * Return: 0 on success or an error code. */ static int drop_from_hashtable (ctrl_t ctrl, ulong table, byte *key, int keylen, ulong recnum) { TRUSTREC rec; ulong hashrec, item; int msb; int level = 0; int rc, i; hashrec = table; next_level: msb = key[level]; hashrec += msb / ITEMS_PER_HTBL_RECORD; rc = tdbio_read_record (hashrec, &rec, RECTYPE_HTBL ); if (rc) { log_error ("drop_from_hashtable: read failed: %s\n", gpg_strerror (rc)); return rc; } item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD]; if (!item) return 0; /* Not found - forget about it. */ if (item == recnum) /* Table points direct to the record. */ { rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = 0; rc = tdbio_write_record (ctrl, &rec); if (rc) log_error ("drop_from_hashtable: write htbl failed: %s\n", gpg_strerror (rc)); return rc; } rc = tdbio_read_record (item, &rec, 0); if (rc) { log_error ("drop_from_hashtable: read item failed: %s\n", gpg_strerror (rc)); return rc; } if (rec.rectype == RECTYPE_HTBL) { hashrec = item; level++; if (level >= keylen) { log_error ("hashtable has invalid indirections.\n"); return GPG_ERR_TRUSTDB; } goto next_level; } if (rec.rectype == RECTYPE_HLST) { for (;;) { for (i=0; i < ITEMS_PER_HLST_RECORD; i++) { if (rec.r.hlst.rnum[i] == recnum) { rec.r.hlst.rnum[i] = 0; /* Mark as free. */ rc = tdbio_write_record (ctrl, &rec); if (rc) log_error("drop_from_hashtable: write htbl failed: %s\n", gpg_strerror (rc)); return rc; } } if (rec.r.hlst.next) { rc = tdbio_read_record (rec.r.hlst.next, &rec, RECTYPE_HLST); if (rc) { log_error ("drop_from_hashtable: read hlst failed: %s\n", gpg_strerror (rc)); return rc; } } else return 0; /* Key not in table. */ } } log_error ("hashtbl %lu: %lu/%d points to wrong record %lu\n", table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item); return GPG_ERR_TRUSTDB; } /* * Lookup a record via the hashtable TABLE by (KEY,KEYLEN) and return * the result in REC. The return value of CMP() should be True if the * record is the desired one. * * Return: 0 if found, GPG_ERR_NOT_FOUND, or another error code. */ static gpg_error_t lookup_hashtable (ulong table, const byte *key, size_t keylen, int (*cmpfnc)(const void*, const TRUSTREC *), const void *cmpdata, TRUSTREC *rec ) { int rc; ulong hashrec, item; int msb; int level = 0; if (!table) { rc = gpg_error (GPG_ERR_INV_RECORD); log_error("lookup_hashtable failed: %s\n", "request for record 0"); return rc; } hashrec = table; next_level: msb = key[level]; hashrec += msb / ITEMS_PER_HTBL_RECORD; rc = tdbio_read_record (hashrec, rec, RECTYPE_HTBL); if (rc) { log_error("lookup_hashtable failed: %s\n", gpg_strerror (rc) ); return rc; } item = rec->r.htbl.item[msb % ITEMS_PER_HTBL_RECORD]; if (!item) return gpg_error (GPG_ERR_NOT_FOUND); rc = tdbio_read_record (item, rec, 0); if (rc) { log_error( "hashtable read failed: %s\n", gpg_strerror (rc) ); return rc; } if (rec->rectype == RECTYPE_HTBL) { hashrec = item; level++; if (level >= keylen) { log_error ("hashtable has invalid indirections\n"); return GPG_ERR_TRUSTDB; } goto next_level; } else if (rec->rectype == RECTYPE_HLST) { for (;;) { int i; for (i=0; i < ITEMS_PER_HLST_RECORD; i++) { if (rec->r.hlst.rnum[i]) { TRUSTREC tmp; rc = tdbio_read_record (rec->r.hlst.rnum[i], &tmp, 0); if (rc) { log_error ("lookup_hashtable: read item failed: %s\n", gpg_strerror (rc)); return rc; } if ((*cmpfnc)(cmpdata, &tmp)) { *rec = tmp; return 0; } } } if (rec->r.hlst.next) { rc = tdbio_read_record (rec->r.hlst.next, rec, RECTYPE_HLST); if (rc) { log_error ("lookup_hashtable: read hlst failed: %s\n", gpg_strerror (rc) ); return rc; } } else return gpg_error (GPG_ERR_NOT_FOUND); } } if ((*cmpfnc)(cmpdata, rec)) return 0; /* really found */ return gpg_error (GPG_ERR_NOT_FOUND); /* no: not found */ } /* * Update the trust hash table TR or create the table if it does not * exist. * * Return: 0 on success or an error code. */ static int update_trusthashtbl (ctrl_t ctrl, TRUSTREC *tr) { return upd_hashtable (ctrl, get_trusthashrec (ctrl), tr->r.trust.fingerprint, 20, tr->recnum); } /* * Dump the trustdb record REC to stream FP. */ void tdbio_dump_record (TRUSTREC *rec, estream_t fp) { int i; ulong rnum = rec->recnum; es_fprintf (fp, "rec %5lu, ", rnum); switch (rec->rectype) { case 0: es_fprintf (fp, "blank\n"); break; case RECTYPE_VER: es_fprintf (fp, "version, td=%lu, f=%lu, m/c/d=%d/%d/%d tm=%d mcl=%d nc=%lu (%s)\n", rec->r.ver.trusthashtbl, rec->r.ver.firstfree, rec->r.ver.marginals, rec->r.ver.completes, rec->r.ver.cert_depth, rec->r.ver.trust_model, rec->r.ver.min_cert_level, rec->r.ver.nextcheck, strtimestamp(rec->r.ver.nextcheck) ); break; case RECTYPE_FREE: es_fprintf (fp, "free, next=%lu\n", rec->r.free.next); break; case RECTYPE_HTBL: es_fprintf (fp, "htbl,"); for (i=0; i < ITEMS_PER_HTBL_RECORD; i++) es_fprintf (fp, " %lu", rec->r.htbl.item[i]); es_putc ('\n', fp); break; case RECTYPE_HLST: es_fprintf (fp, "hlst, next=%lu,", rec->r.hlst.next); for (i=0; i < ITEMS_PER_HLST_RECORD; i++) es_fprintf (fp, " %lu", rec->r.hlst.rnum[i]); es_putc ('\n', fp); break; case RECTYPE_TRUST: es_fprintf (fp, "trust "); for (i=0; i < 20; i++) es_fprintf (fp, "%02X", rec->r.trust.fingerprint[i]); es_fprintf (fp, ", ot=%d, d=%d, vl=%lu\n", rec->r.trust.ownertrust, rec->r.trust.depth, rec->r.trust.validlist); break; case RECTYPE_VALID: es_fprintf (fp, "valid "); for (i=0; i < 20; i++) es_fprintf(fp, "%02X", rec->r.valid.namehash[i]); es_fprintf (fp, ", v=%d, next=%lu\n", rec->r.valid.validity, rec->r.valid.next); break; default: es_fprintf (fp, "unknown type %d\n", rec->rectype ); break; } } /* * Read the record with number RECNUM into the structure REC. If * EXPECTED is not 0 reading any other record type will return an * error. * * Return: 0 on success or an error code. */ int tdbio_read_record (ulong recnum, TRUSTREC *rec, int expected) { byte readbuf[TRUST_RECORD_LEN]; const byte *buf, *p; gpg_error_t err = 0; int n, i; if (db_fd == -1) open_db (); buf = get_record_from_cache( recnum ); if (!buf) { if (lseek (db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET) == -1) { err = gpg_error_from_syserror (); log_error (_("trustdb: lseek failed: %s\n"), strerror (errno)); return err; } n = read (db_fd, readbuf, TRUST_RECORD_LEN); if (!n) { return gpg_error (GPG_ERR_EOF); } else if (n != TRUST_RECORD_LEN) { err = gpg_error_from_syserror (); log_error (_("trustdb: read failed (n=%d): %s\n"), n, strerror(errno)); return err; } buf = readbuf; } rec->recnum = recnum; rec->dirty = 0; p = buf; rec->rectype = *p++; if (expected && rec->rectype != expected) { log_error ("%lu: read expected rec type %d, got %d\n", recnum, expected, rec->rectype); return gpg_error (GPG_ERR_TRUSTDB); } p++; /* Skip reserved byte. */ switch (rec->rectype) { case 0: /* unused (free) record */ break; case RECTYPE_VER: /* version record */ if (memcmp(buf+1, GPGEXT_GPG, 3)) { log_error (_("%s: not a trustdb file\n"), db_name ); err = gpg_error (GPG_ERR_TRUSTDB); } else { p += 2; /* skip "gpg" */ rec->r.ver.version = *p++; rec->r.ver.marginals = *p++; rec->r.ver.completes = *p++; rec->r.ver.cert_depth = *p++; rec->r.ver.trust_model = *p++; rec->r.ver.min_cert_level = *p++; p += 2; rec->r.ver.created = buf32_to_ulong(p); p += 4; rec->r.ver.nextcheck = buf32_to_ulong(p); p += 4; p += 4; p += 4; rec->r.ver.firstfree = buf32_to_ulong(p); p += 4; p += 4; rec->r.ver.trusthashtbl = buf32_to_ulong(p); if (recnum) { log_error( _("%s: version record with recnum %lu\n"), db_name, (ulong)recnum ); err = gpg_error (GPG_ERR_TRUSTDB); } else if (rec->r.ver.version != 3) { log_error( _("%s: invalid file version %d\n"), db_name, rec->r.ver.version ); err = gpg_error (GPG_ERR_TRUSTDB); } } break; case RECTYPE_FREE: rec->r.free.next = buf32_to_ulong(p); break; case RECTYPE_HTBL: for (i=0; i < ITEMS_PER_HTBL_RECORD; i++) { rec->r.htbl.item[i] = buf32_to_ulong(p); p += 4; } break; case RECTYPE_HLST: rec->r.hlst.next = buf32_to_ulong(p); p += 4; for (i=0; i < ITEMS_PER_HLST_RECORD; i++) { rec->r.hlst.rnum[i] = buf32_to_ulong(p); p += 4; } break; case RECTYPE_TRUST: memcpy (rec->r.trust.fingerprint, p, 20); p+=20; rec->r.trust.ownertrust = *p++; rec->r.trust.depth = *p++; rec->r.trust.min_ownertrust = *p++; p++; rec->r.trust.validlist = buf32_to_ulong(p); break; case RECTYPE_VALID: memcpy (rec->r.valid.namehash, p, 20); p+=20; rec->r.valid.validity = *p++; rec->r.valid.next = buf32_to_ulong(p); p += 4; rec->r.valid.full_count = *p++; rec->r.valid.marginal_count = *p++; break; default: log_error ("%s: invalid record type %d at recnum %lu\n", db_name, rec->rectype, (ulong)recnum); err = gpg_error (GPG_ERR_TRUSTDB); break; } return err; } /* * Write the record from the struct REC. * * Return: 0 on success or an error code. */ int tdbio_write_record (ctrl_t ctrl, TRUSTREC *rec) { byte buf[TRUST_RECORD_LEN]; byte *p; int rc = 0; int i; ulong recnum = rec->recnum; if (db_fd == -1) open_db (); memset (buf, 0, TRUST_RECORD_LEN); p = buf; *p++ = rec->rectype; p++; switch (rec->rectype) { case 0: /* unused record */ break; case RECTYPE_VER: /* version record */ if (recnum) BUG (); memcpy(p-1, GPGEXT_GPG, 3 ); p += 2; *p++ = rec->r.ver.version; *p++ = rec->r.ver.marginals; *p++ = rec->r.ver.completes; *p++ = rec->r.ver.cert_depth; *p++ = rec->r.ver.trust_model; *p++ = rec->r.ver.min_cert_level; p += 2; ulongtobuf(p, rec->r.ver.created); p += 4; ulongtobuf(p, rec->r.ver.nextcheck); p += 4; p += 4; p += 4; ulongtobuf(p, rec->r.ver.firstfree ); p += 4; p += 4; ulongtobuf(p, rec->r.ver.trusthashtbl ); p += 4; break; case RECTYPE_FREE: ulongtobuf(p, rec->r.free.next); p += 4; break; case RECTYPE_HTBL: for (i=0; i < ITEMS_PER_HTBL_RECORD; i++) { ulongtobuf( p, rec->r.htbl.item[i]); p += 4; } break; case RECTYPE_HLST: ulongtobuf( p, rec->r.hlst.next); p += 4; for (i=0; i < ITEMS_PER_HLST_RECORD; i++ ) { ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4; } break; case RECTYPE_TRUST: memcpy (p, rec->r.trust.fingerprint, 20); p += 20; *p++ = rec->r.trust.ownertrust; *p++ = rec->r.trust.depth; *p++ = rec->r.trust.min_ownertrust; p++; ulongtobuf( p, rec->r.trust.validlist); p += 4; break; case RECTYPE_VALID: memcpy (p, rec->r.valid.namehash, 20); p += 20; *p++ = rec->r.valid.validity; ulongtobuf( p, rec->r.valid.next); p += 4; *p++ = rec->r.valid.full_count; *p++ = rec->r.valid.marginal_count; break; default: BUG(); } rc = put_record_into_cache (recnum, buf); if (rc) ; else if (rec->rectype == RECTYPE_TRUST) rc = update_trusthashtbl (ctrl, rec); return rc; } /* * Delete the record at record number RECNUm from the trustdb. * * Return: 0 on success or an error code. */ int tdbio_delete_record (ctrl_t ctrl, ulong recnum) { TRUSTREC vr, rec; int rc; /* Must read the record fist, so we can drop it from the hash tables */ rc = tdbio_read_record (recnum, &rec, 0); if (rc) ; else if (rec.rectype == RECTYPE_TRUST) { rc = drop_from_hashtable (ctrl, get_trusthashrec (ctrl), rec.r.trust.fingerprint, 20, rec.recnum); } if (rc) return rc; /* Now we can change it to a free record. */ rc = tdbio_read_record (0, &vr, RECTYPE_VER); if (rc) log_fatal (_("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc)); rec.recnum = recnum; rec.rectype = RECTYPE_FREE; rec.r.free.next = vr.r.ver.firstfree; vr.r.ver.firstfree = recnum; rc = tdbio_write_record (ctrl, &rec); if (!rc) rc = tdbio_write_record (ctrl, &vr); return rc; } /* * Create a new record and return its record number. */ ulong tdbio_new_recnum (ctrl_t ctrl) { off_t offset; ulong recnum; TRUSTREC vr, rec; int rc; /* Look for unused records. */ rc = tdbio_read_record (0, &vr, RECTYPE_VER); if (rc) log_fatal( _("%s: error reading version record: %s\n"), db_name, gpg_strerror (rc)); if (vr.r.ver.firstfree) { recnum = vr.r.ver.firstfree; rc = tdbio_read_record (recnum, &rec, RECTYPE_FREE); if (rc) log_fatal (_("%s: error reading free record: %s\n"), db_name, gpg_strerror (rc)); /* Update dir record. */ vr.r.ver.firstfree = rec.r.free.next; rc = tdbio_write_record (ctrl, &vr); if (rc) log_fatal (_("%s: error writing dir record: %s\n"), db_name, gpg_strerror (rc)); /* Zero out the new record. */ memset (&rec, 0, sizeof rec); rec.rectype = 0; /* Mark as unused record (actually already done my the memset). */ rec.recnum = recnum; rc = tdbio_write_record (ctrl, &rec); if (rc) log_fatal (_("%s: failed to zero a record: %s\n"), db_name, gpg_strerror (rc)); } else /* Not found - append a new record. */ { offset = lseek (db_fd, 0, SEEK_END); if (offset == (off_t)(-1)) log_fatal ("trustdb: lseek to end failed: %s\n", strerror (errno)); recnum = offset / TRUST_RECORD_LEN; log_assert (recnum); /* This will never be the first record */ /* We must write a record, so that the next call to this * function returns another recnum. */ memset (&rec, 0, sizeof rec); rec.rectype = 0; /* unused record */ rec.recnum = recnum; rc = 0; if (lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET) == -1) { rc = gpg_error_from_syserror (); log_error (_("trustdb rec %lu: lseek failed: %s\n"), recnum, strerror (errno)); } else { int n; n = write (db_fd, &rec, TRUST_RECORD_LEN); if (n != TRUST_RECORD_LEN) { rc = gpg_error_from_syserror (); log_error (_("trustdb rec %lu: write failed (n=%d): %s\n"), recnum, n, gpg_strerror (rc)); } } if (rc) log_fatal (_("%s: failed to append a record: %s\n"), db_name, gpg_strerror (rc)); } return recnum ; } /* Helper function for tdbio_search_trust_byfpr. */ static int cmp_trec_fpr ( const void *fpr, const TRUSTREC *rec ) { return (rec->rectype == RECTYPE_TRUST && !memcmp (rec->r.trust.fingerprint, fpr, 20)); } /* * Given a 20 byte FINGERPRINT search its trust record and return * that at REC. * * Return: 0 if found, GPG_ERR_NOT_FOUND, or another error code. */ gpg_error_t tdbio_search_trust_byfpr (ctrl_t ctrl, const byte *fingerprint, TRUSTREC *rec) { int rc; /* Locate the trust record using the hash table */ rc = lookup_hashtable (get_trusthashrec (ctrl), fingerprint, 20, cmp_trec_fpr, fingerprint, rec ); return rc; } /* * Given a primary public key object PK search its trust record and * return that at REC. * * Return: 0 if found, GPG_ERR_NOT_FOUND, or another error code. */ gpg_error_t tdbio_search_trust_bypk (ctrl_t ctrl, PKT_public_key *pk, TRUSTREC *rec) { byte fingerprint[MAX_FINGERPRINT_LEN]; size_t fingerlen; fingerprint_from_pk( pk, fingerprint, &fingerlen ); for (; fingerlen < 20; fingerlen++) fingerprint[fingerlen] = 0; return tdbio_search_trust_byfpr (ctrl, fingerprint, rec); } /* * Terminate the process with a message about a corrupted trustdb. */ void tdbio_invalid (void) { log_error (_("Error: The trustdb is corrupted.\n")); how_to_fix_the_trustdb (); g10_exit (2); } diff --git a/kbx/kbxutil.c b/kbx/kbxutil.c index f156122e2..6fb05ff6c 100644 --- a/kbx/kbxutil.c +++ b/kbx/kbxutil.c @@ -1,641 +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); + es_fflush (es_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); + es_fflush (es_stdout); log_error ("%s: failed to create OpenPGP keyblock: %s\n", filename, gpg_strerror (err)); } else { - err = _keybox_write_blob (blob, stdout); + err = _keybox_write_blob (blob, es_stdout, NULL); _keybox_release_blob (blob); if (err) { - fflush (stdout); + es_fflush (es_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 d2b79baf2..2751b4bd8 100644 --- a/kbx/keybox-defs.h +++ b/kbx/keybox-defs.h @@ -1,210 +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; + estream_t 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. */ 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); +int _keybox_read_blob (KEYBOXBLOB *r_blob, estream_t fp, int *skipped_deleted); +int _keybox_write_blob (KEYBOXBLOB blob, estream_t fp, FILE *outfp); /*-- 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-dump.c b/kbx/keybox-dump.c index a12d683ea..3e66b72a1 100644 --- a/kbx/keybox-dump.c +++ b/kbx/keybox-dump.c @@ -1,915 +1,915 @@ /* keybox-dump.c - Debug helpers * Copyright (C) 2001, 2003 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 "keybox-defs.h" #include #include "../common/host2net.h" /* Argg, we can't include ../common/util.h */ char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf); #define get32(a) buf32_to_ulong ((a)) #define get16(a) buf16_to_ulong ((a)) void print_string (FILE *fp, const byte *p, size_t n, int delim) { for ( ; n; n--, p++ ) { if (*p < 0x20 || (*p >= 0x7f && *p < 0xa0) || *p == delim) { putc('\\', fp); if( *p == '\n' ) putc('n', fp); else if( *p == '\r' ) putc('r', fp); else if( *p == '\f' ) putc('f', fp); else if( *p == '\v' ) putc('v', fp); else if( *p == '\b' ) putc('b', fp); else if( !*p ) putc('0', fp); else fprintf(fp, "x%02x", *p ); } else putc(*p, fp); } } static int print_checksum (const byte *buffer, size_t length, size_t unhashed, FILE *fp) { const byte *p; int i; int hashlen; unsigned char digest[20]; fprintf (fp, "Checksum: "); if (unhashed && unhashed < 20) { fputs ("[specified unhashed sized too short]\n", fp); return 0; } if (!unhashed) { unhashed = 16; hashlen = 16; } else hashlen = 20; if (length < 5+unhashed) { fputs ("[blob too short for a checksum]\n", fp); return 0; } p = buffer + length - hashlen; for (i=0; i < hashlen; p++, i++) fprintf (fp, "%02x", *p); if (hashlen == 16) /* Compatibility method. */ { gcry_md_hash_buffer (GCRY_MD_MD5, digest, buffer, length - 16); if (!memcmp (buffer + length - 16, digest, 16)) fputs (" [valid]\n", fp); else fputs (" [bad]\n", fp); } else { gcry_md_hash_buffer (GCRY_MD_SHA1, digest, buffer, length - unhashed); if (!memcmp (buffer + length - hashlen, digest, hashlen)) fputs (" [valid]\n", fp); else fputs (" [bad]\n", fp); } return 0; } static int dump_header_blob (const byte *buffer, size_t length, FILE *fp) { unsigned long n; if (length < 32) { fprintf (fp, "[blob too short]\n"); return -1; } fprintf (fp, "Version: %d\n", buffer[5]); n = get16 (buffer + 6); fprintf( fp, "Flags: %04lX", n); if (n) { int any = 0; fputs (" (", fp); if ((n & 2)) { if (any) putc (',', fp); fputs ("openpgp", fp); any++; } putc (')', fp); } putc ('\n', fp); if ( memcmp (buffer+8, "KBXf", 4)) fprintf (fp, "[Error: invalid magic number]\n"); n = get32 (buffer+16); fprintf( fp, "created-at: %lu\n", n ); n = get32 (buffer+20); fprintf( fp, "last-maint: %lu\n", n ); return 0; } /* Dump one block to FP */ int _keybox_dump_blob (KEYBOXBLOB blob, FILE *fp) { const byte *buffer; size_t length; int type, i; ulong n, nkeys, keyinfolen; ulong nuids, uidinfolen; ulong nsigs, siginfolen; ulong rawdata_off, rawdata_len; ulong nserial; ulong unhashed; const byte *p; const byte *pend; int is_fpr32; /* blob version 2 */ buffer = _keybox_get_blob_image (blob, &length); if (length < 32) { fprintf (fp, "[blob too short]\n"); return -1; } n = get32( buffer ); if (n > length) fprintf (fp, "[blob larger than length - output truncated]\n"); else length = n; /* ignore the rest */ fprintf (fp, "Length: %lu\n", n ); type = buffer[4]; switch (type) { case KEYBOX_BLOBTYPE_EMPTY: fprintf (fp, "Type: Empty\n"); return 0; case KEYBOX_BLOBTYPE_HEADER: fprintf (fp, "Type: Header\n"); return dump_header_blob (buffer, length, fp); case KEYBOX_BLOBTYPE_PGP: fprintf (fp, "Type: OpenPGP\n"); break; case KEYBOX_BLOBTYPE_X509: fprintf (fp, "Type: X.509\n"); break; default: fprintf (fp, "Type: %d\n", type); fprintf (fp, "[can't dump this blob type]\n"); return 0; } /* Here we have either BLOGTYPE_X509 or BLOBTYPE_OPENPGP */ fprintf (fp, "Version: %d\n", buffer[5]); is_fpr32 = buffer[5] == 2; if (length < 40) { fprintf (fp, "[blob too short]\n"); return -1; } n = get16 (buffer + 6); fprintf( fp, "Blob-Flags: %04lX", n); if (n) { int any = 0; fputs (" (", fp); if ((n & 1)) { fputs ("secret", fp); any++; } if ((n & 2)) { if (any) putc (',', fp); fputs ("ephemeral", fp); any++; } putc (')', fp); } putc ('\n', fp); rawdata_off = get32 (buffer + 8); rawdata_len = get32 (buffer + 12); fprintf( fp, "Data-Offset: %lu\n", rawdata_off ); fprintf( fp, "Data-Length: %lu\n", rawdata_len ); if (rawdata_off > length || rawdata_len > length || rawdata_off+rawdata_len > length || rawdata_len + 4 > length || rawdata_off+rawdata_len + 4 > length) { fprintf (fp, "[Error: raw data larger than blob]\n"); return -1; } if (rawdata_off > length || rawdata_len > length || rawdata_off + rawdata_len > length) { fprintf (fp, "[Error: unhashed data larger than blob]\n"); return -1; } unhashed = length - rawdata_off - rawdata_len; fprintf (fp, "Unhashed: %lu\n", unhashed); nkeys = get16 (buffer + 16); fprintf (fp, "Key-Count: %lu\n", nkeys ); if (!nkeys) fprintf (fp, "[Error: no keys]\n"); if (nkeys > 1 && type == KEYBOX_BLOBTYPE_X509) fprintf (fp, "[Error: only one key allowed for X509]\n"); keyinfolen = get16 (buffer + 18 ); fprintf (fp, "Key-Info-Length: %lu\n", keyinfolen); p = buffer + 20; pend = buffer + length; for (n=0; n < nkeys; n++, p += keyinfolen) { ulong kidoff, kflags; if (p + keyinfolen >= pend) { fprintf (fp, "[Error: key data larger than blob]\n"); return -1; } fprintf (fp, "Key-Fpr[%lu]: ", n ); if (is_fpr32) { if (p + 32 + 2 >= pend) { fprintf (fp, "[Error: fingerprint data larger than blob]\n"); return -1; } kflags = get16 (p + 32 ); for (i=0; i < ((kflags & 0x80)?32:20); i++ ) fprintf (fp, "%02X", p[i]); } else { if (p + 20 + 4 >= pend) { fprintf (fp, "[Error: fingerprint data larger than blob]\n"); return -1; } for (i=0; i < 20; i++ ) fprintf (fp, "%02X", p[i]); kidoff = get32 (p + 20); fprintf (fp, "\nKey-Kid-Off[%lu]: %lu\n", n, kidoff ); fprintf (fp, "Key-Kid[%lu]: ", n ); if (p + kidoff + 8 >= pend) { fprintf (fp, "[Error: fingerprint data larger than blob]\n"); return -1; } for (i=0; i < 8; i++ ) fprintf (fp, "%02X", buffer[kidoff+i] ); if (p + 24 >= pend) { fprintf (fp, "[Error: fingerprint data larger than blob]\n"); return -1; } kflags = get16 (p + 24); } fprintf( fp, "\nKey-Flags[%lu]: %04lX\n", n, kflags); } /* serial number */ if (p + 2 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } fputs ("Serial-No: ", fp); nserial = get16 (p); p += 2; if (!nserial) fputs ("none", fp); else { if (p + nserial >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } for (; nserial; nserial--, p++) fprintf (fp, "%02X", *p); } putc ('\n', fp); /* user IDs */ if (p + 4 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } nuids = get16 (p); fprintf (fp, "Uid-Count: %lu\n", nuids ); uidinfolen = get16 (p + 2); fprintf (fp, "Uid-Info-Length: %lu\n", uidinfolen); p += 4; for (n=0; n < nuids; n++, p += uidinfolen) { ulong uidoff, uidlen, uflags; if (p + uidinfolen >= pend || uidinfolen < 8) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } uidoff = get32( p ); uidlen = get32( p+4 ); if (type == KEYBOX_BLOBTYPE_X509 && !n) { fprintf (fp, "Issuer-Off: %lu\n", uidoff ); fprintf (fp, "Issuer-Len: %lu\n", uidlen ); fprintf (fp, "Issuer: \""); } else if (type == KEYBOX_BLOBTYPE_X509 && n == 1) { fprintf (fp, "Subject-Off: %lu\n", uidoff ); fprintf (fp, "Subject-Len: %lu\n", uidlen ); fprintf (fp, "Subject: \""); } else { fprintf (fp, "Uid-Off[%lu]: %lu\n", n, uidoff ); fprintf (fp, "Uid-Len[%lu]: %lu\n", n, uidlen ); fprintf (fp, "Uid[%lu]: \"", n ); } if (uidoff + uidlen > length || uidoff + uidlen < uidoff || uidoff + uidlen < uidlen) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } print_string (fp, buffer+uidoff, uidlen, '\"'); fputs ("\"\n", fp); if (p + 8 + 2 + 1 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } uflags = get16 (p + 8); if (type == KEYBOX_BLOBTYPE_X509 && !n) { fprintf (fp, "Issuer-Flags: %04lX\n", uflags ); fprintf (fp, "Issuer-Validity: %d\n", p[10] ); } else if (type == KEYBOX_BLOBTYPE_X509 && n == 1) { fprintf (fp, "Subject-Flags: %04lX\n", uflags ); fprintf (fp, "Subject-Validity: %d\n", p[10] ); } else { fprintf (fp, "Uid-Flags[%lu]: %04lX\n", n, uflags ); fprintf (fp, "Uid-Validity[%lu]: %d\n", n, p[10] ); } } if (p + 2 + 2 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } nsigs = get16 (p); fprintf (fp, "Sig-Count: %lu\n", nsigs ); siginfolen = get16 (p + 2); fprintf (fp, "Sig-Info-Length: %lu\n", siginfolen ); p += 4; { int in_range = 0; ulong first = 0; for (n=0; n < nsigs; n++, p += siginfolen) { ulong sflags; if (p + siginfolen >= pend || siginfolen < 4) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } sflags = get32 (p); if (!in_range && !sflags) { in_range = 1; first = n; continue; } if (in_range && !sflags) continue; if (in_range) { fprintf (fp, "Sig-Expire[%lu-%lu]: [not checked]\n", first, n-1); in_range = 0; } fprintf (fp, "Sig-Expire[%lu]: ", n ); if (!sflags) fputs ("[not checked]", fp); else if (sflags == 1 ) fputs ("[missing key]", fp); else if (sflags == 2 ) fputs ("[bad signature]", fp); else if (sflags < 0x10000000) fprintf (fp, "[bad flag %0lx]", sflags); else if (sflags == (ulong)(-1)) fputs ("[good - does not expire]", fp ); else fprintf (fp, "[good - expires at %lu]", sflags); putc ('\n', fp ); } if (in_range) fprintf (fp, "Sig-Expire[%lu-%lu]: [not checked]\n", first, n-1); } if (p + 16 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } fprintf (fp, "Ownertrust: %d\n", p[0] ); fprintf (fp, "All-Validity: %d\n", p[1] ); p += 4; n = get32 (p); p += 4; fprintf (fp, "Recheck-After: %lu\n", n ); n = get32 (p ); p += 4; fprintf( fp, "Latest-Timestamp: %lu\n", n ); n = get32 (p ); p += 4; fprintf (fp, "Created-At: %lu\n", n ); if (p + 4 >= pend) { fprintf (fp, "[Error: data larger than blob]\n"); return -1; } n = get32 (p ); fprintf (fp, "Reserved-Space: %lu\n", n ); if (n >= 4 && unhashed >= 24) { n = get32 ( buffer + length - unhashed); fprintf (fp, "Storage-Flags: %08lx\n", n ); } print_checksum (buffer, length, unhashed, fp); return 0; } /* Compute the SHA-1 checksum of the rawdata in BLOB and put it into DIGEST. */ static int hash_blob_rawdata (KEYBOXBLOB blob, unsigned char *digest) { const unsigned char *buffer; size_t n, length; int type; ulong rawdata_off, rawdata_len; buffer = _keybox_get_blob_image (blob, &length); if (length < 32) return -1; n = get32 (buffer); if (n < length) length = n; /* Blob larger than length in header - ignore the rest. */ type = buffer[4]; switch (type) { case KEYBOX_BLOBTYPE_PGP: case KEYBOX_BLOBTYPE_X509: break; case KEYBOX_BLOBTYPE_EMPTY: case KEYBOX_BLOBTYPE_HEADER: default: memset (digest, 0, 20); return 0; } if (length < 40) return -1; rawdata_off = get32 (buffer + 8); rawdata_len = get32 (buffer + 12); if (rawdata_off > length || rawdata_len > length || rawdata_off+rawdata_off > length) return -1; /* Out of bounds. */ gcry_md_hash_buffer (GCRY_MD_SHA1, digest, buffer+rawdata_off, rawdata_len); return 0; } struct file_stats_s { unsigned long too_short_blobs; unsigned long too_large_blobs; unsigned long total_blob_count; unsigned long empty_blob_count; unsigned long header_blob_count; unsigned long pgp_blob_count; unsigned long x509_blob_count; unsigned long unknown_blob_count; unsigned long non_flagged; unsigned long secret_flagged; unsigned long ephemeral_flagged; unsigned long skipped_long_blobs; }; static int update_stats (KEYBOXBLOB blob, struct file_stats_s *s) { const unsigned char *buffer; size_t length; int type; unsigned long n; buffer = _keybox_get_blob_image (blob, &length); if (length < 32) { s->too_short_blobs++; return -1; } n = get32( buffer ); if (n > length) s->too_large_blobs++; else length = n; /* ignore the rest */ s->total_blob_count++; type = buffer[4]; switch (type) { case KEYBOX_BLOBTYPE_EMPTY: s->empty_blob_count++; return 0; case KEYBOX_BLOBTYPE_HEADER: s->header_blob_count++; return 0; case KEYBOX_BLOBTYPE_PGP: s->pgp_blob_count++; break; case KEYBOX_BLOBTYPE_X509: s->x509_blob_count++; break; default: s->unknown_blob_count++; return 0; } if (length < 40) { s->too_short_blobs++; return -1; } n = get16 (buffer + 6); if (n) { if ((n & 1)) s->secret_flagged++; if ((n & 2)) s->ephemeral_flagged++; } else s->non_flagged++; return 0; } -static FILE * +static estream_t open_file (const char **filename, FILE *outfp) { - FILE *fp; + estream_t fp; if (!*filename) { *filename = "-"; - fp = stdin; + fp = es_stdin; } else - fp = fopen (*filename, "rb"); + fp = es_fopen (*filename, "rb"); if (!fp) { int save_errno = errno; fprintf (outfp, "can't open '%s': %s\n", *filename, strerror(errno)); gpg_err_set_errno (save_errno); } return fp; } int _keybox_dump_file (const char *filename, int stats_only, FILE *outfp) { - FILE *fp; + estream_t fp; KEYBOXBLOB blob; int rc; unsigned long count = 0; struct file_stats_s stats; int skipped_deleted; memset (&stats, 0, sizeof stats); if (!(fp = open_file (&filename, outfp))) return gpg_error_from_syserror (); for (;;) { rc = _keybox_read_blob (&blob, fp, &skipped_deleted); if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX) { if (stats_only) stats.skipped_long_blobs++; else { fprintf (outfp, "BEGIN-RECORD: %lu\n", count ); fprintf (outfp, "# Record too large\nEND-RECORD\n"); } count++; continue; } if (rc) break; count += skipped_deleted; if (stats_only) { stats.total_blob_count += skipped_deleted; stats.empty_blob_count += skipped_deleted; update_stats (blob, &stats); } else { fprintf (outfp, "BEGIN-RECORD: %lu\n", count ); _keybox_dump_blob (blob, outfp); fprintf (outfp, "END-RECORD\n"); } _keybox_release_blob (blob); count++; } if (rc == -1) rc = 0; if (rc) fprintf (outfp, "# error reading '%s': %s\n", filename, gpg_strerror (rc)); - if (fp != stdin) - fclose (fp); + if (fp != es_stdin) + es_fclose (fp); if (stats_only) { fprintf (outfp, "Total number of blobs: %8lu\n" " header: %8lu\n" " empty: %8lu\n" " openpgp: %8lu\n" " x509: %8lu\n" " non flagged: %8lu\n" " secret flagged: %8lu\n" " ephemeral flagged: %8lu\n", stats.total_blob_count, stats.header_blob_count, stats.empty_blob_count, stats.pgp_blob_count, stats.x509_blob_count, stats.non_flagged, stats.secret_flagged, stats.ephemeral_flagged); if (stats.skipped_long_blobs) fprintf (outfp, " skipped long blobs: %8lu\n", stats.skipped_long_blobs); if (stats.unknown_blob_count) fprintf (outfp, " unknown blob types: %8lu\n", stats.unknown_blob_count); if (stats.too_short_blobs) fprintf (outfp, " too short blobs: %8lu (error)\n", stats.too_short_blobs); if (stats.too_large_blobs) fprintf (outfp, " too large blobs: %8lu (error)\n", stats.too_large_blobs); } return rc; } struct dupitem_s { unsigned long recno; unsigned char digest[20]; }; static int cmp_dupitems (const void *arg_a, const void *arg_b) { struct dupitem_s *a = (struct dupitem_s *)arg_a; struct dupitem_s *b = (struct dupitem_s *)arg_b; return memcmp (a->digest, b->digest, 20); } int _keybox_dump_find_dups (const char *filename, int print_them, FILE *outfp) { - FILE *fp; + estream_t fp; KEYBOXBLOB blob; int rc; unsigned long recno = 0; unsigned char zerodigest[20]; struct dupitem_s *dupitems; size_t dupitems_size, dupitems_count, lastn, n; char fprbuf[3*20+1]; (void)print_them; memset (zerodigest, 0, sizeof zerodigest); if (!(fp = open_file (&filename, outfp))) return gpg_error_from_syserror (); dupitems_size = 1000; dupitems = malloc (dupitems_size * sizeof *dupitems); if (!dupitems) { gpg_error_t tmperr = gpg_error_from_syserror (); fprintf (outfp, "error allocating array for '%s': %s\n", filename, strerror(errno)); return tmperr; } dupitems_count = 0; while ( !(rc = _keybox_read_blob (&blob, fp, NULL)) ) { unsigned char digest[20]; if (hash_blob_rawdata (blob, digest)) fprintf (outfp, "error in blob %ld of '%s'\n", recno, filename); else if (memcmp (digest, zerodigest, 20)) { if (dupitems_count >= dupitems_size) { struct dupitem_s *tmp; dupitems_size += 1000; tmp = realloc (dupitems, dupitems_size * sizeof *dupitems); if (!tmp) { gpg_error_t tmperr = gpg_error_from_syserror (); fprintf (outfp, "error reallocating array for '%s': %s\n", filename, strerror(errno)); free (dupitems); return tmperr; } dupitems = tmp; } dupitems[dupitems_count].recno = recno; memcpy (dupitems[dupitems_count].digest, digest, 20); dupitems_count++; } _keybox_release_blob (blob); recno++; } if (rc == -1) rc = 0; if (rc) fprintf (outfp, "error reading '%s': %s\n", filename, gpg_strerror (rc)); - if (fp != stdin) - fclose (fp); + if (fp != es_stdin) + es_fclose (fp); qsort (dupitems, dupitems_count, sizeof *dupitems, cmp_dupitems); for (lastn=0, n=1; n < dupitems_count; lastn=n, n++) { if (!memcmp (dupitems[lastn].digest, dupitems[n].digest, 20)) { bin2hexcolon (dupitems[lastn].digest, 20, fprbuf); fprintf (outfp, "fpr=%s recno=%lu", fprbuf, dupitems[lastn].recno); do fprintf (outfp, " %lu", dupitems[n].recno); while (++n < dupitems_count && !memcmp (dupitems[lastn].digest, dupitems[n].digest, 20)); putc ('\n', outfp); n--; } } free (dupitems); return rc; } /* Print records with record numbers FROM to TO to OUTFP. */ int _keybox_dump_cut_records (const char *filename, unsigned long from, unsigned long to, FILE *outfp) { - FILE *fp; + estream_t fp; KEYBOXBLOB blob; int rc; unsigned long recno = 0; if (!(fp = open_file (&filename, stderr))) return gpg_error_from_syserror (); while ( !(rc = _keybox_read_blob (&blob, fp, NULL)) ) { if (recno > to) break; /* Ready. */ if (recno >= from) { - if ((rc = _keybox_write_blob (blob, outfp))) + if ((rc = _keybox_write_blob (blob, NULL, outfp))) { fprintf (stderr, "error writing output: %s\n", gpg_strerror (rc)); goto leave; } } _keybox_release_blob (blob); recno++; } if (rc == -1) rc = 0; if (rc) fprintf (stderr, "error reading '%s': %s\n", filename, gpg_strerror (rc)); leave: - if (fp != stdin) - fclose (fp); + if (fp != es_stdin) + es_fclose (fp); return rc; } diff --git a/kbx/keybox-file.c b/kbx/keybox-file.c index 046e32123..c36f5beee 100644 --- a/kbx/keybox-file.c +++ b/kbx/keybox-file.c @@ -1,180 +1,190 @@ /* keybox-file.c - File operations * Copyright (C) 2001, 2003 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" #define IMAGELEN_LIMIT (5*1024*1024) #if !defined(HAVE_FTELLO) && !defined(ftello) static off_t ftello (FILE *stream) { long int off; off = ftell (stream); if (off == -1) return (off_t)-1; return off; } #endif /* !defined(HAVE_FTELLO) && !defined(ftello) */ /* Read a block at the current position and return it in R_BLOB. R_BLOB may be NULL to simply skip the current block. */ int -_keybox_read_blob (KEYBOXBLOB *r_blob, FILE *fp, int *skipped_deleted) +_keybox_read_blob (KEYBOXBLOB *r_blob, estream_t fp, int *skipped_deleted) { unsigned char *image; size_t imagelen = 0; int c1, c2, c3, c4, type; int rc; off_t off; if (skipped_deleted) *skipped_deleted = 0; again: if (r_blob) *r_blob = NULL; - off = ftello (fp); + off = es_ftello (fp); if (off == (off_t)-1) return gpg_error_from_syserror (); - if ((c1 = getc (fp)) == EOF - || (c2 = getc (fp)) == EOF - || (c3 = getc (fp)) == EOF - || (c4 = getc (fp)) == EOF - || (type = getc (fp)) == EOF) + if ((c1 = es_getc (fp)) == EOF + || (c2 = es_getc (fp)) == EOF + || (c3 = es_getc (fp)) == EOF + || (c4 = es_getc (fp)) == EOF + || (type = es_getc (fp)) == EOF) { - if ( c1 == EOF && !ferror (fp) ) + if ( c1 == EOF && !es_ferror (fp) ) return -1; /* eof */ - if (!ferror (fp)) + if (!es_ferror (fp)) return gpg_error (GPG_ERR_TOO_SHORT); return gpg_error_from_syserror (); } imagelen = ((unsigned int) c1 << 24) | (c2 << 16) | (c3 << 8 ) | c4; if (imagelen < 5) return gpg_error (GPG_ERR_TOO_SHORT); if (!type) { /* Special treatment for empty blobs. */ - if (fseek (fp, imagelen-5, SEEK_CUR)) + if (es_fseek (fp, imagelen-5, SEEK_CUR)) return gpg_error_from_syserror (); if (skipped_deleted) *skipped_deleted = 1; goto again; } if (imagelen > IMAGELEN_LIMIT) /* Sanity check. */ { /* Seek forward so that the caller may choose to ignore this record. */ - if (fseek (fp, imagelen-5, SEEK_CUR)) + if (es_fseek (fp, imagelen-5, SEEK_CUR)) return gpg_error_from_syserror (); return gpg_error (GPG_ERR_TOO_LARGE); } if (!r_blob) { /* This blob shall be skipped. */ - if (fseek (fp, imagelen-5, SEEK_CUR)) + if (es_fseek (fp, imagelen-5, SEEK_CUR)) return gpg_error_from_syserror (); return 0; } image = xtrymalloc (imagelen); if (!image) return gpg_error_from_syserror (); image[0] = c1; image[1] = c2; image[2] = c3; image[3] = c4; image[4] = type; - if (fread (image+5, imagelen-5, 1, fp) != 1) + if (es_fread (image+5, imagelen-5, 1, fp) != 1) { gpg_error_t tmperr = gpg_error_from_syserror (); xfree (image); return tmperr; } rc = _keybox_new_blob (r_blob, image, imagelen, off); if (rc) xfree (image); return rc; } /* Write the block to the current file position */ int -_keybox_write_blob (KEYBOXBLOB blob, FILE *fp) +_keybox_write_blob (KEYBOXBLOB blob, estream_t fp, FILE *outfp) { const unsigned char *image; size_t length; image = _keybox_get_blob_image (blob, &length); if (length > IMAGELEN_LIMIT) return gpg_error (GPG_ERR_TOO_LARGE); - if (fwrite (image, length, 1, fp) != 1) - return gpg_error_from_syserror (); + if (fp) + { + if (es_fwrite (image, length, 1, fp) != 1) + return gpg_error_from_syserror (); + } + else + { + if (fwrite (image, length, 1, outfp) != 1) + return gpg_error_from_syserror (); + } + return 0; } /* Write a fresh header type blob. */ int -_keybox_write_header_blob (FILE *fp, int for_openpgp) +_keybox_write_header_blob (estream_t fp, int for_openpgp) { unsigned char image[32]; u32 val; memset (image, 0, sizeof image); /* Length of this blob. */ image[3] = 32; image[4] = KEYBOX_BLOBTYPE_HEADER; image[5] = 1; /* Version */ if (for_openpgp) image[7] = 0x02; /* OpenPGP data may be available. */ memcpy (image+8, "KBXf", 4); val = time (NULL); /* created_at and last maintenance run. */ image[16] = (val >> 24); image[16+1] = (val >> 16); image[16+2] = (val >> 8); image[16+3] = (val ); image[20] = (val >> 24); image[20+1] = (val >> 16); image[20+2] = (val >> 8); image[20+3] = (val ); - if (fwrite (image, 32, 1, fp) != 1) + if (es_fwrite (image, 32, 1, fp) != 1) return gpg_error_from_syserror (); + return 0; } diff --git a/kbx/keybox-init.c b/kbx/keybox-init.c index c05ef52e6..6cabaea73 100644 --- a/kbx/keybox-init.c +++ b/kbx/keybox-init.c @@ -1,332 +1,332 @@ /* keybox-init.c - Initialization of the library * Copyright (C) 2001 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 "../common/sysutils.h" #include "../common/mischelp.h" static KB_NAME kb_names; /* Register a filename for plain keybox files. Returns 0 on success, * GPG_ERR_EEXIST if it has already been registered, or another error * code. On success or with error code GPG_ERR_EEXIST a token usable * to access the keybox handle is stored at R_TOKEN, NULL is stored * for all other errors. */ gpg_error_t keybox_register_file (const char *fname, int secret, void **r_token) { KB_NAME kr; *r_token = NULL; for (kr=kb_names; kr; kr = kr->next) { if (same_file_p (kr->fname, fname) ) { *r_token = kr; return gpg_error (GPG_ERR_EEXIST); /* Already registered. */ } } kr = xtrymalloc (sizeof *kr + strlen (fname)); if (!kr) return gpg_error_from_syserror (); strcpy (kr->fname, fname); kr->secret = !!secret; kr->handle_table = NULL; kr->handle_table_size = 0; kr->lockhd = NULL; kr->is_locked = 0; kr->did_full_scan = 0; /* keep a list of all issued pointers */ kr->next = kb_names; kb_names = kr; /* create the offset table the first time a function here is used */ /* if (!kb_offtbl) */ /* kb_offtbl = new_offset_hash_table (); */ *r_token = kr; return 0; } int keybox_is_writable (void *token) { KB_NAME r = token; return r? !gnupg_access (r->fname, W_OK) : 0; } static KEYBOX_HANDLE do_keybox_new (KB_NAME resource, int secret, int for_openpgp) { KEYBOX_HANDLE hd; int idx; assert (resource && !resource->secret == !secret); hd = xtrycalloc (1, sizeof *hd); if (hd) { hd->kb = resource; hd->secret = !!secret; hd->for_openpgp = for_openpgp; if (!resource->handle_table) { resource->handle_table_size = 3; resource->handle_table = xtrycalloc (resource->handle_table_size, sizeof *resource->handle_table); if (!resource->handle_table) { resource->handle_table_size = 0; xfree (hd); return NULL; } } for (idx=0; idx < resource->handle_table_size; idx++) if (!resource->handle_table[idx]) { resource->handle_table[idx] = hd; break; } if (!(idx < resource->handle_table_size)) { KEYBOX_HANDLE *tmptbl; size_t newsize; newsize = resource->handle_table_size + 5; tmptbl = xtryrealloc (resource->handle_table, newsize * sizeof (*tmptbl)); if (!tmptbl) { xfree (hd); return NULL; } resource->handle_table = tmptbl; resource->handle_table_size = newsize; resource->handle_table[idx] = hd; for (idx++; idx < resource->handle_table_size; idx++) resource->handle_table[idx] = NULL; } } return hd; } /* Create a new handle for the resource associated with TOKEN. SECRET is just a cross-check. This is the OpenPGP version. The returned handle must be released using keybox_release. */ KEYBOX_HANDLE keybox_new_openpgp (void *token, int secret) { KB_NAME resource = token; return do_keybox_new (resource, secret, 1); } /* Create a new handle for the resource associated with TOKEN. SECRET is just a cross-check. This is the X.509 version. The returned handle must be released using keybox_release. */ KEYBOX_HANDLE keybox_new_x509 (void *token, int secret) { KB_NAME resource = token; return do_keybox_new (resource, secret, 0); } void keybox_release (KEYBOX_HANDLE hd) { if (!hd) return; if (hd->kb->handle_table) { int idx; for (idx=0; idx < hd->kb->handle_table_size; idx++) if (hd->kb->handle_table[idx] == hd) hd->kb->handle_table[idx] = NULL; } _keybox_release_blob (hd->found.blob); _keybox_release_blob (hd->saved_found.blob); if (hd->fp) { - fclose (hd->fp); + es_fclose (hd->fp); hd->fp = NULL; } xfree (hd->word_match.name); xfree (hd->word_match.pattern); xfree (hd); } /* Save the current found state in HD for later retrieval by keybox_restore_found_state. Only one state may be saved. */ void keybox_push_found_state (KEYBOX_HANDLE hd) { if (hd->saved_found.blob) { _keybox_release_blob (hd->saved_found.blob); hd->saved_found.blob = NULL; } hd->saved_found = hd->found; hd->found.blob = NULL; } /* Restore the saved found state in HD. */ void keybox_pop_found_state (KEYBOX_HANDLE hd) { if (hd->found.blob) { _keybox_release_blob (hd->found.blob); hd->found.blob = NULL; } hd->found = hd->saved_found; hd->saved_found.blob = NULL; } const char * keybox_get_resource_name (KEYBOX_HANDLE hd) { if (!hd || !hd->kb) return NULL; return hd->kb->fname; } int keybox_set_ephemeral (KEYBOX_HANDLE hd, int yes) { if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); hd->ephemeral = yes; return 0; } /* Close the file of the resource identified by HD. For consistent results this function closes the files of all handles pointing to the resource identified by HD. */ void _keybox_close_file (KEYBOX_HANDLE hd) { int idx; KEYBOX_HANDLE roverhd; if (!hd || !hd->kb || !hd->kb->handle_table) return; for (idx=0; idx < hd->kb->handle_table_size; idx++) if ((roverhd = hd->kb->handle_table[idx])) { if (roverhd->fp) { - fclose (roverhd->fp); + es_fclose (roverhd->fp); roverhd->fp = NULL; } } - assert (!hd->fp); + log_assert (!hd->fp); } /* * Lock the keybox at handle HD, or unlock if YES is false. * Lock the keybox at handle HD, or unlock if YES is false. TIMEOUT * is the value used for dotlock_take. In general -1 should be used * when taking a lock; use 0 when releasing a lock. */ gpg_error_t keybox_lock (KEYBOX_HANDLE hd, int yes, long timeout) { gpg_error_t err = 0; KB_NAME kb = hd->kb; if (!keybox_is_writable (kb)) return 0; /* Make sure the lock handle has been created. */ if (!kb->lockhd) { kb->lockhd = dotlock_create (kb->fname, 0); if (!kb->lockhd) { err = gpg_error_from_syserror (); log_info ("can't allocate lock for '%s'\n", kb->fname ); return err; } } if (yes) /* Take the lock. */ { if (!kb->is_locked) { #ifdef HAVE_W32_SYSTEM /* Under Windows we need to close the file before we try * to lock it. This is because another process might have * taken the lock and is using keybox_file_rename to * rename the base file. Now if our dotlock_take below is * waiting for the lock but we have the base file still * open, keybox_file_rename will never succeed as we are * in a deadlock. */ _keybox_close_file (hd); #endif /*HAVE_W32_SYSTEM*/ if (dotlock_take (kb->lockhd, timeout)) { err = gpg_error_from_syserror (); if (!timeout && gpg_err_code (err) == GPG_ERR_EACCES) ; /* No diagnostic if we only tried to lock. */ else log_info ("can't lock '%s'\n", kb->fname ); } else kb->is_locked = 1; } } else /* Release the lock. */ { if (kb->is_locked) { if (dotlock_release (kb->lockhd)) { err = gpg_error_from_syserror (); log_info ("can't unlock '%s'\n", kb->fname ); } else kb->is_locked = 0; } } return err; } diff --git a/kbx/keybox-search.c b/kbx/keybox-search.c index c07fe81eb..53ed66b67 100644 --- a/kbx/keybox-search.c +++ b/kbx/keybox-search.c @@ -1,1317 +1,1317 @@ /* 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); #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"); + hd->fp = es_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)) + if (es_fseeko (hd->fp, 0, SEEK_SET)) { /* Ooops. Seek did not work. Close so that the search will * open the file again. */ - fclose (hd->fp); + es_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; off_t lastfoundoff; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); /* Clear last found result but reord the offset of the last found * blob which we may need later. */ if (hd->found.blob) { lastfoundoff = _keybox_get_blob_fileoffset (hd->found.blob); _keybox_release_blob (hd->found.blob); hd->found.blob = NULL; } else lastfoundoff = 0; 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); lastfoundoff = 0; 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; } /* log_debug ("%s: re-opened file\n", __func__); */ if (ndesc && desc[0].mode != KEYDB_SEARCH_MODE_FIRST && lastfoundoff) { /* Search mode is not first and the last search operation * returned a blob which also was not the first one. We now * need to skip over that blob and hope that the file has * not changed. */ - if (fseeko (hd->fp, lastfoundoff, SEEK_SET)) + if (es_fseeko (hd->fp, lastfoundoff, SEEK_SET)) { rc = gpg_error_from_syserror (); log_debug ("%s: seeking to last found offset failed: %s\n", __func__, gpg_strerror (rc)); xfree (sn_array); return gpg_error (GPG_ERR_NOTHING_FOUND); } /* log_debug ("%s: re-opened file and sought to last offset\n", */ /* __func__); */ rc = _keybox_read_blob (NULL, hd->fp, NULL); if (rc) { log_debug ("%s: skipping last found blob failed: %s\n", __func__, gpg_strerror (rc)); xfree (sn_array); return gpg_error (GPG_ERR_NOTHING_FOUND); } } } /* 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); + return es_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); + err = es_fseeko (hd->fp, offset, SEEK_SET); hd->error = gpg_error_from_errno (err); return hd->error; } diff --git a/kbx/keybox-update.c b/kbx/keybox-update.c index c797f3ba5..ddda52ac1 100644 --- a/kbx/keybox-update.c +++ b/kbx/keybox-update.c @@ -1,799 +1,799 @@ /* keybox-update.c - keybox update operations * Copyright (C) 2001, 2003, 2004, 2012 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 "keybox-defs.h" #include "../common/sysutils.h" #include "../common/host2net.h" #include "../common/utilproto.h" #define EXTSEP_S "." #define FILECOPY_INSERT 1 #define FILECOPY_DELETE 2 #define FILECOPY_UPDATE 3 #if !defined(HAVE_FSEEKO) && !defined(fseeko) #ifdef HAVE_LIMITS_H # include #endif #ifndef LONG_MAX # define LONG_MAX ((long) ((unsigned long) -1 >> 1)) #endif #ifndef LONG_MIN # define LONG_MIN (-1 - LONG_MAX) #endif /**************** * A substitute for fseeko, for hosts that don't have it. */ static int fseeko (FILE * stream, off_t newpos, int whence) { while (newpos != (long) newpos) { long pos = newpos < 0 ? LONG_MIN : LONG_MAX; if (fseek (stream, pos, whence) != 0) return -1; newpos -= pos; whence = SEEK_CUR; } return fseek (stream, (long) newpos, whence); } #endif /* !defined(HAVE_FSEEKO) && !defined(fseeko) */ static int create_tmp_file (const char *template, - char **r_bakfname, char **r_tmpfname, FILE **r_fp) + char **r_bakfname, char **r_tmpfname, estream_t *r_fp) { gpg_error_t err; err = keybox_tmp_names (template, 0, r_bakfname, r_tmpfname); if (!err) { - *r_fp = fopen (*r_tmpfname, "wb"); + *r_fp = es_fopen (*r_tmpfname, "wb"); if (!*r_fp) { err = gpg_error_from_syserror (); xfree (*r_tmpfname); *r_tmpfname = NULL; xfree (*r_bakfname); *r_bakfname = NULL; } } return err; } static int rename_tmp_file (const char *bakfname, const char *tmpfname, const char *fname, int secret ) { int rc=0; int block = 0; /* restrict the permissions for secret keyboxs */ #ifndef HAVE_DOSISH_SYSTEM /* if (secret && !opt.preserve_permissions) */ /* { */ /* if (chmod (tmpfname, S_IRUSR | S_IWUSR) ) */ /* { */ /* log_debug ("chmod of '%s' failed: %s\n", */ /* tmpfname, strerror(errno) ); */ /* return KEYBOX_Write_File; */ /* } */ /* } */ #endif /* fixme: invalidate close caches (not used with stdio)*/ /* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)tmpfname ); */ /* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)bakfname ); */ /* iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname ); */ /* First make a backup file except for secret keyboxes. */ if (!secret) { block = 1; rc = gnupg_rename_file (fname, bakfname, &block); if (rc) goto leave; } /* Then rename the file. */ rc = gnupg_rename_file (tmpfname, fname, NULL); if (block) { gnupg_unblock_all_signals (); block = 0; } /* if (rc) */ /* { */ /* if (secret) */ /* { */ /* log_info ("WARNING: 2 files with confidential" */ /* " information exists.\n"); */ /* log_info ("%s is the unchanged one\n", fname ); */ /* log_info ("%s is the new one\n", tmpfname ); */ /* log_info ("Please fix this possible security flaw\n"); */ /* } */ /* } */ leave: if (block) gnupg_unblock_all_signals (); return rc; } /* Perform insert/delete/update operation. MODE is one of FILECOPY_INSERT, FILECOPY_DELETE, FILECOPY_UPDATE. FOR_OPENPGP indicates that this is called due to an OpenPGP keyblock change. */ static int blob_filecopy (int mode, const char *fname, KEYBOXBLOB blob, int secret, int for_openpgp, off_t start_offset) { gpg_err_code_t ec; - FILE *fp, *newfp; - int rc=0; + estream_t fp, newfp; + int rc = 0; char *bakfname = NULL; char *tmpfname = NULL; char buffer[4096]; /* (Must be at least 32 bytes) */ int nread, nbytes; /* Open the source file. Because we do a rename, we have to check the permissions of the file */ if ((ec = gnupg_access (fname, W_OK))) return gpg_error (ec); - fp = fopen (fname, "rb"); + fp = es_fopen (fname, "rb"); if (mode == FILECOPY_INSERT && !fp && errno == ENOENT) { /* Insert mode but file does not exist: Create a new keybox file. */ - newfp = fopen (fname, "wb"); + newfp = es_fopen (fname, "wb"); if (!newfp ) return gpg_error_from_syserror (); rc = _keybox_write_header_blob (newfp, for_openpgp); if (rc) { - fclose (newfp); + es_fclose (newfp); return rc; } - rc = _keybox_write_blob (blob, newfp); + rc = _keybox_write_blob (blob, newfp, NULL); if (rc) { - fclose (newfp); + es_fclose (newfp); return rc; } - if ( fclose (newfp) ) + if ( es_fclose (newfp) ) return gpg_error_from_syserror (); /* if (chmod( fname, S_IRUSR | S_IWUSR )) */ /* { */ /* log_debug ("%s: chmod failed: %s\n", fname, strerror(errno) ); */ /* return KEYBOX_File_Error; */ /* } */ return 0; /* Ready. */ } if (!fp) { rc = gpg_error_from_syserror (); goto leave; } /* Create the new file. On success NEWFP is initialized. */ rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp); if (rc) { - fclose (fp); + es_fclose (fp); goto leave; } /* prepare for insert */ if (mode == FILECOPY_INSERT) { int first_record = 1; /* Copy everything to the new file. If this is for OpenPGP, we make sure that the openpgp flag is set in the header. (We failsafe the blob type.) */ - while ( (nread = fread (buffer, 1, DIM(buffer), fp)) > 0 ) + while ( (nread = es_fread (buffer, 1, DIM(buffer), fp)) > 0 ) { if (first_record && for_openpgp && buffer[4] == KEYBOX_BLOBTYPE_HEADER) { first_record = 0; buffer[7] |= 0x02; /* OpenPGP data may be available. */ } - if (fwrite (buffer, nread, 1, newfp) != 1) + if (es_fwrite (buffer, nread, 1, newfp) != 1) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } } - if (ferror (fp)) + if (es_ferror (fp)) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } } /* Prepare for delete or update. */ if ( mode == FILECOPY_DELETE || mode == FILECOPY_UPDATE ) { off_t current = 0; /* Copy first part to the new file. */ while ( current < start_offset ) { nbytes = DIM(buffer); if (current + nbytes > start_offset) nbytes = start_offset - current; - nread = fread (buffer, 1, nbytes, fp); + nread = es_fread (buffer, 1, nbytes, fp); if (!nread) break; current += nread; - if (fwrite (buffer, nread, 1, newfp) != 1) + if (es_fwrite (buffer, nread, 1, newfp) != 1) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } } - if (ferror (fp)) + if (es_ferror (fp)) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } /* Skip this blob. */ rc = _keybox_read_blob (NULL, fp, NULL); if (rc) { - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); return rc; } } /* Do an insert or update. */ if ( mode == FILECOPY_INSERT || mode == FILECOPY_UPDATE ) { - rc = _keybox_write_blob (blob, newfp); + rc = _keybox_write_blob (blob, newfp, NULL); if (rc) { - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); return rc; } } /* Copy the rest of the packet for an delete or update. */ if (mode == FILECOPY_DELETE || mode == FILECOPY_UPDATE) { - while ( (nread = fread (buffer, 1, DIM(buffer), fp)) > 0 ) + while ( (nread = es_fread (buffer, 1, DIM(buffer), fp)) > 0 ) { - if (fwrite (buffer, nread, 1, newfp) != 1) + if (es_fwrite (buffer, nread, 1, newfp) != 1) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } } - if (ferror (fp)) + if (es_ferror (fp)) { rc = gpg_error_from_syserror (); - fclose (fp); - fclose (newfp); + es_fclose (fp); + es_fclose (newfp); goto leave; } } /* Close both files. */ - if (fclose(fp)) + if (es_fclose(fp)) { rc = gpg_error_from_syserror (); - fclose (newfp); + es_fclose (newfp); goto leave; } - if (fclose(newfp)) + if (es_fclose(newfp)) { rc = gpg_error_from_syserror (); goto leave; } rc = rename_tmp_file (bakfname, tmpfname, fname, secret); leave: xfree(bakfname); xfree(tmpfname); return rc; } /* Insert the OpenPGP keyblock {IMAGE,IMAGELEN} into HD. */ gpg_error_t keybox_insert_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen) { gpg_error_t err; const char *fname; KEYBOXBLOB blob; size_t nparsed; struct _keybox_openpgp_info info; if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); if (!hd->kb) return gpg_error (GPG_ERR_INV_HANDLE); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); /* Close this one otherwise we will mess up the position for a next search. Fixme: it would be better to adjust the position after the write operation. */ _keybox_close_file (hd); err = _keybox_parse_openpgp (image, imagelen, &nparsed, &info); if (err) return err; assert (nparsed <= imagelen); err = _keybox_create_openpgp_blob (&blob, &info, image, imagelen, hd->ephemeral); _keybox_destroy_openpgp_info (&info); if (!err) { err = blob_filecopy (FILECOPY_INSERT, fname, blob, hd->secret, 1, 0); _keybox_release_blob (blob); /* if (!rc && !hd->secret && kb_offtbl) */ /* { */ /* update_offset_hash_table_from_kb (kb_offtbl, kb, 0); */ /* } */ } return err; } /* Update the current key at HD with the given OpenPGP keyblock in {IMAGE,IMAGELEN}. */ gpg_error_t keybox_update_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen) { gpg_error_t err; const char *fname; off_t off; KEYBOXBLOB blob; size_t nparsed; struct _keybox_openpgp_info info; if (!hd || !image || !imagelen) 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); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); off = _keybox_get_blob_fileoffset (hd->found.blob); if (off == (off_t)-1) return gpg_error (GPG_ERR_GENERAL); /* Close the file so that we do no mess up the position for a next search. */ _keybox_close_file (hd); /* Build a new blob. */ err = _keybox_parse_openpgp (image, imagelen, &nparsed, &info); if (err) return err; assert (nparsed <= imagelen); err = _keybox_create_openpgp_blob (&blob, &info, image, imagelen, hd->ephemeral); _keybox_destroy_openpgp_info (&info); /* Update the keyblock. */ if (!err) { err = blob_filecopy (FILECOPY_UPDATE, fname, blob, hd->secret, 1, off); _keybox_release_blob (blob); } return err; } #ifdef KEYBOX_WITH_X509 int keybox_insert_cert (KEYBOX_HANDLE hd, ksba_cert_t cert, unsigned char *sha1_digest) { int rc; const char *fname; KEYBOXBLOB blob; if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); if (!hd->kb) return gpg_error (GPG_ERR_INV_HANDLE); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); /* Close this one otherwise we will mess up the position for a next search. Fixme: it would be better to adjust the position after the write operation. */ _keybox_close_file (hd); rc = _keybox_create_x509_blob (&blob, cert, sha1_digest, hd->ephemeral); if (!rc) { rc = blob_filecopy (FILECOPY_INSERT, fname, blob, hd->secret, 0, 0); _keybox_release_blob (blob); /* if (!rc && !hd->secret && kb_offtbl) */ /* { */ /* update_offset_hash_table_from_kb (kb_offtbl, kb, 0); */ /* } */ } return rc; } int keybox_update_cert (KEYBOX_HANDLE hd, ksba_cert_t cert, unsigned char *sha1_digest) { (void)hd; (void)cert; (void)sha1_digest; return -1; } #endif /*KEYBOX_WITH_X509*/ /* Note: We assume that the keybox has been locked before the current search was executed. This is needed so that we can depend on the offset information of the flags. */ int keybox_set_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int value) { off_t off; const char *fname; - FILE *fp; + estream_t fp; gpg_err_code_t ec; size_t flag_pos, flag_size; const unsigned char *buffer; size_t length; (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); if (!hd->kb) return gpg_error (GPG_ERR_INV_HANDLE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); off = _keybox_get_blob_fileoffset (hd->found.blob); if (off == (off_t)-1) return gpg_error (GPG_ERR_GENERAL); buffer = _keybox_get_blob_image (hd->found.blob, &length); ec = _keybox_get_flag_location (buffer, length, what, &flag_pos, &flag_size); if (ec) return gpg_error (ec); off += flag_pos; _keybox_close_file (hd); - fp = fopen (hd->kb->fname, "r+b"); + fp = es_fopen (hd->kb->fname, "r+b"); if (!fp) return gpg_error_from_syserror (); ec = 0; - if (fseeko (fp, off, SEEK_SET)) + if (es_fseeko (fp, off, SEEK_SET)) ec = gpg_err_code_from_syserror (); else { unsigned char tmp[4]; tmp[0] = value >> 24; tmp[1] = value >> 16; tmp[2] = value >> 8; tmp[3] = value; switch (flag_size) { case 1: case 2: case 4: - if (fwrite (tmp+4-flag_size, flag_size, 1, fp) != 1) + if (es_fwrite (tmp+4-flag_size, flag_size, 1, fp) != 1) ec = gpg_err_code_from_syserror (); break; default: ec = GPG_ERR_BUG; break; } } - if (fclose (fp)) + if (es_fclose (fp)) { if (!ec) ec = gpg_err_code_from_syserror (); } return gpg_error (ec); } int keybox_delete (KEYBOX_HANDLE hd) { off_t off; const char *fname; - FILE *fp; + estream_t fp; int rc; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); if (!hd->kb) return gpg_error (GPG_ERR_INV_HANDLE); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); off = _keybox_get_blob_fileoffset (hd->found.blob); if (off == (off_t)-1) return gpg_error (GPG_ERR_GENERAL); off += 4; _keybox_close_file (hd); - fp = fopen (hd->kb->fname, "r+b"); + fp = es_fopen (hd->kb->fname, "r+b"); if (!fp) return gpg_error_from_syserror (); - if (fseeko (fp, off, SEEK_SET)) + if (es_fseeko (fp, off, SEEK_SET)) rc = gpg_error_from_syserror (); - else if (putc (0, fp) == EOF) + else if (es_fputc (0, fp) == EOF) rc = gpg_error_from_syserror (); else rc = 0; - if (fclose (fp)) + if (es_fclose (fp)) { if (!rc) rc = gpg_error_from_syserror (); } return rc; } /* Compress the keybox file. This should be run with the file locked. */ int keybox_compress (KEYBOX_HANDLE hd) { gpg_err_code_t ec; int read_rc, rc; const char *fname; - FILE *fp, *newfp; + estream_t fp, newfp; char *bakfname = NULL; char *tmpfname = NULL; int first_blob; KEYBOXBLOB blob = NULL; u32 cut_time; int any_changes = 0; int skipped_deleted; if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); if (!hd->kb) return gpg_error (GPG_ERR_INV_HANDLE); if (hd->secret) return gpg_error (GPG_ERR_NOT_IMPLEMENTED); fname = hd->kb->fname; if (!fname) return gpg_error (GPG_ERR_INV_HANDLE); _keybox_close_file (hd); /* Open the source file. Because we do a rename, we have to check the permissions of the file */ if ((ec = gnupg_access (fname, W_OK))) return gpg_error (ec); - fp = fopen (fname, "rb"); + fp = es_fopen (fname, "rb"); if (!fp && errno == ENOENT) return 0; /* Ready. File has been deleted right after the access above. */ if (!fp) { rc = gpg_error_from_syserror (); return rc; } /* A quick test to see if we need to compress the file at all. We schedule a compress run after 3 hours. */ if ( !_keybox_read_blob (&blob, fp, NULL) ) { const unsigned char *buffer; size_t length; buffer = _keybox_get_blob_image (blob, &length); if (length > 4 && buffer[4] == KEYBOX_BLOBTYPE_HEADER) { u32 last_maint = buf32_to_u32 (buffer+20); if ( (last_maint + 3*3600) > make_timestamp () ) { - fclose (fp); + es_fclose (fp); _keybox_release_blob (blob); return 0; /* Compress run not yet needed. */ } } _keybox_release_blob (blob); - fseek (fp, 0, SEEK_SET); - clearerr (fp); + es_fseek (fp, 0, SEEK_SET); + es_clearerr (fp); } /* Create the new file. */ rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp); if (rc) { - fclose (fp); + es_fclose (fp); return rc;; } /* Processing loop. By reading using _keybox_read_blob we automagically skip any blobs flagged as deleted. Thus what we only have to do is to check all ephemeral flagged blocks whether their time has come and write out all other blobs. */ cut_time = make_timestamp () - 86400; first_blob = 1; skipped_deleted = 0; for (rc=0; !(read_rc = _keybox_read_blob (&blob, fp, &skipped_deleted)); _keybox_release_blob (blob), blob = NULL ) { unsigned int blobflags; const unsigned char *buffer; size_t length, pos, size; u32 created_at; if (skipped_deleted) any_changes = 1; buffer = _keybox_get_blob_image (blob, &length); if (first_blob) { first_blob = 0; if (length > 4 && buffer[4] == KEYBOX_BLOBTYPE_HEADER) { /* Write out the blob with an updated maintenance time stamp and if needed (ie. used by gpg) set the openpgp flag. */ _keybox_update_header_blob (blob, hd->for_openpgp); - rc = _keybox_write_blob (blob, newfp); + rc = _keybox_write_blob (blob, newfp, NULL); if (rc) break; continue; } /* The header blob is missing. Insert it. */ rc = _keybox_write_header_blob (newfp, hd->for_openpgp); if (rc) break; any_changes = 1; } else if (length > 4 && buffer[4] == KEYBOX_BLOBTYPE_HEADER) { /* Oops: There is another header record - remove it. */ any_changes = 1; continue; } if (_keybox_get_flag_location (buffer, length, KEYBOX_FLAG_BLOB, &pos, &size) || size != 2) { rc = gpg_error (GPG_ERR_BUG); break; } blobflags = buf16_to_uint (buffer+pos); if ((blobflags & KEYBOX_FLAG_BLOB_EPHEMERAL)) { /* This is an ephemeral blob. */ if (_keybox_get_flag_location (buffer, length, KEYBOX_FLAG_CREATED_AT, &pos, &size) || size != 4) created_at = 0; /* oops. */ else created_at = buf32_to_u32 (buffer+pos); if (created_at && created_at < cut_time) { any_changes = 1; continue; /* Skip this blob. */ } } - rc = _keybox_write_blob (blob, newfp); + rc = _keybox_write_blob (blob, newfp, NULL); if (rc) break; } if (skipped_deleted) any_changes = 1; _keybox_release_blob (blob); blob = NULL; if (!rc && read_rc == -1) rc = 0; else if (!rc) rc = read_rc; /* Close both files. */ - if (fclose(fp) && !rc) + if (es_fclose(fp) && !rc) rc = gpg_error_from_syserror (); - if (fclose(newfp) && !rc) + if (es_fclose(newfp) && !rc) rc = gpg_error_from_syserror (); /* Rename or remove the temporary file. */ if (rc || !any_changes) gnupg_remove (tmpfname); else rc = rename_tmp_file (bakfname, tmpfname, fname, hd->secret); xfree(bakfname); xfree(tmpfname); return rc; } diff --git a/kbx/keybox.h b/kbx/keybox.h index 4d941571e..c5f9b571e 100644 --- a/kbx/keybox.h +++ b/kbx/keybox.h @@ -1,137 +1,137 @@ /* keybox.h - Keybox operations * Copyright (C) 2001, 2003, 2012 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_H #define KEYBOX_H 1 #ifdef __cplusplus extern "C" { #if 0 } #endif #endif #include "../common/iobuf.h" #include "keybox-search-desc.h" #ifdef KEYBOX_WITH_X509 # include #endif typedef struct keybox_handle *KEYBOX_HANDLE; typedef enum { KEYBOX_FLAG_BLOB, /* The blob flags. */ KEYBOX_FLAG_VALIDITY, /* The validity of the entire key. */ KEYBOX_FLAG_OWNERTRUST, /* The assigned ownertrust. */ KEYBOX_FLAG_KEY, /* The key flags; requires a key index. */ KEYBOX_FLAG_UID, /* The user ID flags; requires an uid index. */ KEYBOX_FLAG_UID_VALIDITY,/* The validity of a specific uid, requires an uid index. */ KEYBOX_FLAG_CREATED_AT, /* The date the block was created. */ KEYBOX_FLAG_SIG_INFO, /* The signature info block. */ } keybox_flag_t; /* Flag values used with KEYBOX_FLAG_BLOB. */ #define KEYBOX_FLAG_BLOB_SECRET 1 #define KEYBOX_FLAG_BLOB_EPHEMERAL 2 /* The keybox blob types. */ typedef enum { KEYBOX_BLOBTYPE_EMPTY = 0, KEYBOX_BLOBTYPE_HEADER = 1, KEYBOX_BLOBTYPE_PGP = 2, KEYBOX_BLOBTYPE_X509 = 3 } keybox_blobtype_t; /*-- keybox-init.c --*/ gpg_error_t keybox_register_file (const char *fname, int secret, void **r_token); int keybox_is_writable (void *token); KEYBOX_HANDLE keybox_new_openpgp (void *token, int secret); KEYBOX_HANDLE keybox_new_x509 (void *token, int secret); void keybox_release (KEYBOX_HANDLE hd); void keybox_push_found_state (KEYBOX_HANDLE hd); void keybox_pop_found_state (KEYBOX_HANDLE hd); const char *keybox_get_resource_name (KEYBOX_HANDLE hd); int keybox_set_ephemeral (KEYBOX_HANDLE hd, int yes); gpg_error_t keybox_lock (KEYBOX_HANDLE hd, int yes, long timeout); /*-- keybox-file.c --*/ /* Fixme: This function does not belong here: Provide a better interface to create a new keybox file. */ -int _keybox_write_header_blob (FILE *fp, int openpgp_flag); +int _keybox_write_header_blob (estream_t fp, int openpgp_flag); /*-- keybox-search.c --*/ gpg_error_t keybox_get_keyblock (KEYBOX_HANDLE hd, iobuf_t *r_iobuf, int *r_uid_no, int *r_pk_no); #ifdef KEYBOX_WITH_X509 int keybox_get_cert (KEYBOX_HANDLE hd, ksba_cert_t *ret_cert); #endif /*KEYBOX_WITH_X509*/ int keybox_get_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int *value); gpg_error_t keybox_search_reset (KEYBOX_HANDLE hd); 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); off_t keybox_offset (KEYBOX_HANDLE hd); gpg_error_t keybox_seek (KEYBOX_HANDLE hd, off_t offset); /*-- keybox-update.c --*/ gpg_error_t keybox_insert_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen); gpg_error_t keybox_update_keyblock (KEYBOX_HANDLE hd, const void *image, size_t imagelen); #ifdef KEYBOX_WITH_X509 int keybox_insert_cert (KEYBOX_HANDLE hd, ksba_cert_t cert, unsigned char *sha1_digest); int keybox_update_cert (KEYBOX_HANDLE hd, ksba_cert_t cert, unsigned char *sha1_digest); #endif /*KEYBOX_WITH_X509*/ int keybox_set_flags (KEYBOX_HANDLE hd, int what, int idx, unsigned int value); int keybox_delete (KEYBOX_HANDLE hd); int keybox_compress (KEYBOX_HANDLE hd); /*-- --*/ #if 0 int keybox_locate_writable (KEYBOX_HANDLE hd); int keybox_rebuild_cache (void *); #endif /*-- keybox-util.c --*/ gpg_error_t keybox_tmp_names (const char *filename, int for_keyring, char **r_bakname, char **r_tmpname); #ifdef __cplusplus } #endif #endif /*KEYBOX_H*/ diff --git a/scd/app.c b/scd/app.c index bb33a56c3..957345e1e 100644 --- a/scd/app.c +++ b/scd/app.c @@ -1,1130 +1,1130 @@ /* app.c - Application selection. * Copyright (C) 2003, 2004, 2005 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 "scdaemon.h" #include "../common/exechelp.h" #include "app-common.h" #include "iso7816.h" #include "apdu.h" #include "../common/tlv.h" static npth_mutex_t app_list_lock; static app_t app_top; static void print_progress_line (void *opaque, const char *what, int pc, int cur, int tot) { ctrl_t ctrl = opaque; char line[100]; if (ctrl) { snprintf (line, sizeof line, "%s %c %d %d", what, pc, cur, tot); send_status_direct (ctrl, "PROGRESS", line); } } /* Lock the reader SLOT. This function shall be used right before calling any of the actual application functions to serialize access to the reader. We do this always even if the reader is not actually used. This allows an actual connection to assume that it never shares a reader (while performing one command). Returns 0 on success; only then the unlock_reader function must be called after returning from the handler. */ static gpg_error_t lock_app (app_t app, ctrl_t ctrl) { if (npth_mutex_lock (&app->lock)) { gpg_error_t err = gpg_error_from_syserror (); log_error ("failed to acquire APP lock for %p: %s\n", app, gpg_strerror (err)); return err; } apdu_set_progress_cb (app->slot, print_progress_line, ctrl); apdu_set_prompt_cb (app->slot, popup_prompt, ctrl); return 0; } /* Release a lock on the reader. See lock_reader(). */ static void unlock_app (app_t app) { apdu_set_progress_cb (app->slot, NULL, NULL); apdu_set_prompt_cb (app->slot, NULL, NULL); if (npth_mutex_unlock (&app->lock)) { gpg_error_t err = gpg_error_from_syserror (); log_error ("failed to release APP lock for %p: %s\n", app, gpg_strerror (err)); } } /* This function may be called to print information pertaining to the current state of this module to the log. */ void app_dump_state (void) { app_t a; npth_mutex_lock (&app_list_lock); for (a = app_top; a; a = a->next) log_info ("app_dump_state: app=%p type='%s'\n", a, a->apptype); npth_mutex_unlock (&app_list_lock); } /* Check whether the application NAME is allowed. This does not mean we have support for it though. */ static int is_app_allowed (const char *name) { strlist_t l; for (l=opt.disabled_applications; l; l = l->next) if (!strcmp (l->d, name)) return 0; /* no */ return 1; /* yes */ } static gpg_error_t check_conflict (app_t app, const char *name) { if (!app || !name || (app->apptype && !ascii_strcasecmp (app->apptype, name))) return 0; if (app->apptype && !strcmp (app->apptype, "UNDEFINED")) return 0; log_info ("application '%s' in use - can't switch\n", app->apptype? app->apptype : ""); return gpg_error (GPG_ERR_CONFLICT); } /* This function is used by the serialno command to check for an application conflict which may appear if the serialno command is used to request a specific application and the connection has already done a select_application. */ gpg_error_t check_application_conflict (const char *name, app_t app) { return check_conflict (app, name); } gpg_error_t app_reset (app_t app, ctrl_t ctrl, int send_reset) { gpg_error_t err = 0; if (send_reset) { int sw; lock_app (app, ctrl); sw = apdu_reset (app->slot); if (sw) err = gpg_error (GPG_ERR_CARD_RESET); app->reset_requested = 1; unlock_app (app); scd_kick_the_loop (); gnupg_sleep (1); } else { ctrl->app_ctx = NULL; release_application (app, 0); } return err; } static gpg_error_t app_new_register (int slot, ctrl_t ctrl, const char *name, int periodical_check_needed) { gpg_error_t err = 0; app_t app = NULL; unsigned char *result = NULL; size_t resultlen; int want_undefined; /* Need to allocate a new one. */ app = xtrycalloc (1, sizeof *app); if (!app) { err = gpg_error_from_syserror (); log_info ("error allocating context: %s\n", gpg_strerror (err)); return err; } app->slot = slot; app->card_status = (unsigned int)-1; if (npth_mutex_init (&app->lock, NULL)) { err = gpg_error_from_syserror (); log_error ("error initializing mutex: %s\n", gpg_strerror (err)); xfree (app); return err; } err = lock_app (app, ctrl); if (err) { xfree (app); return err; } want_undefined = (name && !strcmp (name, "undefined")); /* Try to read the GDO file first to get a default serial number. We skip this if the undefined application has been requested. */ if (!want_undefined) { err = iso7816_select_file (slot, 0x3F00, 1); if (!err) err = iso7816_select_file (slot, 0x2F02, 0); if (!err) err = iso7816_read_binary (slot, 0, 0, &result, &resultlen); if (!err) { size_t n; const unsigned char *p; p = find_tlv_unchecked (result, resultlen, 0x5A, &n); if (p) resultlen -= (p-result); if (p && n > resultlen && n == 0x0d && resultlen+1 == n) { /* The object it does not fit into the buffer. This is an invalid encoding (or the buffer is too short. However, I have some test cards with such an invalid encoding and therefore I use this ugly workaround to return something I can further experiment with. */ log_info ("enabling BMI testcard workaround\n"); n--; } if (p && n <= resultlen) { /* The GDO file is pretty short, thus we simply reuse it for storing the serial number. */ memmove (result, p, n); app->serialno = result; app->serialnolen = n; err = app_munge_serialno (app); if (err) goto leave; } else xfree (result); result = NULL; } } /* For certain error codes, there is no need to try more. */ if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT || gpg_err_code (err) == GPG_ERR_ENODEV) goto leave; /* Figure out the application to use. */ if (want_undefined) { /* We switch to the "undefined" application only if explicitly requested. */ app->apptype = "UNDEFINED"; err = 0; } else err = gpg_error (GPG_ERR_NOT_FOUND); if (err && is_app_allowed ("openpgp") && (!name || !strcmp (name, "openpgp"))) err = app_select_openpgp (app); if (err && is_app_allowed ("nks") && (!name || !strcmp (name, "nks"))) err = app_select_nks (app); if (err && is_app_allowed ("p15") && (!name || !strcmp (name, "p15"))) err = app_select_p15 (app); if (err && is_app_allowed ("geldkarte") && (!name || !strcmp (name, "geldkarte"))) err = app_select_geldkarte (app); if (err && is_app_allowed ("dinsig") && (!name || !strcmp (name, "dinsig"))) err = app_select_dinsig (app); if (err && is_app_allowed ("sc-hsm") && (!name || !strcmp (name, "sc-hsm"))) err = app_select_sc_hsm (app); if (err && name && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE) err = gpg_error (GPG_ERR_NOT_SUPPORTED); leave: if (err) { if (name) log_info ("can't select application '%s': %s\n", name, gpg_strerror (err)); else log_info ("no supported card application found: %s\n", gpg_strerror (err)); unlock_app (app); xfree (app); return err; } app->periodical_check_needed = periodical_check_needed; npth_mutex_lock (&app_list_lock); app->next = app_top; app_top = app; npth_mutex_unlock (&app_list_lock); unlock_app (app); return 0; } /* If called with NAME as NULL, select the best fitting application and return a context; otherwise select the application with NAME and return a context. Returns an error code and stores NULL at R_APP if no application was found or no card is present. */ gpg_error_t select_application (ctrl_t ctrl, const char *name, app_t *r_app, int scan, const unsigned char *serialno_bin, size_t serialno_bin_len) { gpg_error_t err = 0; app_t a, a_prev = NULL; *r_app = NULL; if (scan || !app_top) { struct dev_list *l; int new_app = 0; /* Scan the devices to find new device(s). */ err = apdu_dev_list_start (opt.reader_port, &l); if (err) return err; while (1) { int slot; int periodical_check_needed_this; slot = apdu_open_reader (l, !app_top); if (slot < 0) break; periodical_check_needed_this = apdu_connect (slot); if (periodical_check_needed_this < 0) { /* We close a reader with no card. */ err = gpg_error (GPG_ERR_ENODEV); } else { err = app_new_register (slot, ctrl, name, periodical_check_needed_this); new_app++; } if (err) apdu_close_reader (slot); } apdu_dev_list_finish (l); /* If new device(s), kick the scdaemon loop. */ if (new_app) scd_kick_the_loop (); } npth_mutex_lock (&app_list_lock); for (a = app_top; a; a = a->next) { lock_app (a, ctrl); if (serialno_bin == NULL) break; if (a->serialnolen == serialno_bin_len && !memcmp (a->serialno, serialno_bin, a->serialnolen)) break; unlock_app (a); a_prev = a; } if (a) { err = check_conflict (a, name); if (!err) { a->ref_count++; *r_app = a; if (a_prev) { a_prev->next = a->next; a->next = app_top; app_top = a; } } unlock_app (a); } else err = gpg_error (GPG_ERR_ENODEV); npth_mutex_unlock (&app_list_lock); return err; } char * get_supported_applications (void) { const char *list[] = { "openpgp", "nks", "p15", "geldkarte", "dinsig", "sc-hsm", /* Note: "undefined" is not listed here because it needs special treatment by the client. */ NULL }; int idx; size_t nbytes; char *buffer, *p; for (nbytes=1, idx=0; list[idx]; idx++) nbytes += strlen (list[idx]) + 1 + 1; buffer = xtrymalloc (nbytes); if (!buffer) return NULL; for (p=buffer, idx=0; list[idx]; idx++) if (is_app_allowed (list[idx])) p = stpcpy (stpcpy (p, list[idx]), ":\n"); *p = 0; return buffer; } /* Deallocate the application. */ static void deallocate_app (app_t app) { app_t a, a_prev = NULL; for (a = app_top; a; a = a->next) if (a == app) { if (a_prev == NULL) app_top = a->next; else a_prev->next = a->next; break; } else a_prev = a; if (app->ref_count) log_error ("trying to release context used yet (%d)\n", app->ref_count); if (app->fnc.deinit) { app->fnc.deinit (app); app->fnc.deinit = NULL; } xfree (app->serialno); unlock_app (app); xfree (app); } /* Free the resources associated with the application APP. APP is allowed to be NULL in which case this is a no-op. Note that we are using reference counting to track the users of the application and actually deferring the deallocation to allow for a later reuse by a new connection. */ void release_application (app_t app, int locked_already) { if (!app) return; /* We don't deallocate app here. Instead, we keep it. This is useful so that a card does not get reset even if only one session is using the card - this way the PIN cache and other cached data are preserved. */ if (!locked_already) lock_app (app, NULL); if (!app->ref_count) log_bug ("trying to release an already released context\n"); --app->ref_count; if (!locked_already) unlock_app (app); } /* The serial number may need some cosmetics. Do it here. This function shall only be called once after a new serial number has been put into APP->serialno. Prefixes we use: FF 00 00 = For serial numbers starting with an FF FF 01 00 = Some german p15 cards return an empty serial number so the serial number from the EF(TokenInfo) is used instead. FF 7F 00 = No serialno. All other serial number not starting with FF are used as they are. */ gpg_error_t app_munge_serialno (app_t app) { if (app->serialnolen && app->serialno[0] == 0xff) { /* The serial number starts with our special prefix. This requires that we put our default prefix "FF0000" in front. */ unsigned char *p = xtrymalloc (app->serialnolen + 3); if (!p) return gpg_error_from_syserror (); memcpy (p, "\xff\0", 3); memcpy (p+3, app->serialno, app->serialnolen); app->serialnolen += 3; xfree (app->serialno); app->serialno = p; } else if (!app->serialnolen) { unsigned char *p = xtrymalloc (3); if (!p) return gpg_error_from_syserror (); memcpy (p, "\xff\x7f", 3); app->serialnolen = 3; xfree (app->serialno); app->serialno = p; } return 0; } /* Retrieve the serial number of the card. The serial number is returned as a malloced string (hex encoded) in SERIAL. Caller must free SERIAL unless the function returns an error. */ char * app_get_serialno (app_t app) { char *serial; if (!app) return NULL; if (!app->serialnolen) serial = xtrystrdup ("FF7F00"); else serial = bin2hex (app->serialno, app->serialnolen, NULL); return serial; } /* Write out the application specifig status lines for the LEARN command. */ gpg_error_t app_write_learn_status (app_t app, ctrl_t ctrl, unsigned int flags) { gpg_error_t err; if (!app) return gpg_error (GPG_ERR_INV_VALUE); if (!app->fnc.learn_status) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); /* We do not send APPTYPE if only keypairinfo is requested. */ if (app->apptype && !(flags & 1)) send_status_direct (ctrl, "APPTYPE", app->apptype); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.learn_status (app, ctrl, flags); unlock_app (app); return err; } /* Read the certificate with id CERTID (as returned by learn_status in the CERTINFO status lines) and return it in the freshly allocated buffer put into CERT and the length of the certificate put into CERTLEN. */ gpg_error_t app_readcert (app_t app, ctrl_t ctrl, const char *certid, unsigned char **cert, size_t *certlen) { gpg_error_t err; if (!app) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.readcert) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.readcert (app, certid, cert, certlen); unlock_app (app); return err; } /* Read the key with ID KEYID. On success a canonical encoded S-expression with the public key will get stored at PK and its length (for assertions) at PKLEN; the caller must release that buffer. On error NULL will be stored at PK and PKLEN and an error code returned. This function might not be supported by all applications. */ gpg_error_t app_readkey (app_t app, ctrl_t ctrl, int advanced, const char *keyid, unsigned char **pk, size_t *pklen) { gpg_error_t err; if (pk) *pk = NULL; if (pklen) *pklen = 0; if (!app || !keyid || !pk || !pklen) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.readkey) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err= app->fnc.readkey (app, advanced, keyid, pk, pklen); unlock_app (app); return err; } /* Perform a GETATTR operation. */ gpg_error_t app_getattr (app_t app, ctrl_t ctrl, const char *name) { gpg_error_t err; if (!app || !name || !*name) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (app->apptype && name && !strcmp (name, "APPTYPE")) { send_status_direct (ctrl, "APPTYPE", app->apptype); return 0; } if (name && !strcmp (name, "SERIALNO")) { char *serial; serial = app_get_serialno (app); if (!serial) return gpg_error (GPG_ERR_INV_VALUE); send_status_direct (ctrl, "SERIALNO", serial); xfree (serial); return 0; } if (!app->fnc.getattr) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.getattr (app, ctrl, name); unlock_app (app); return err; } /* Perform a SETATTR operation. */ gpg_error_t app_setattr (app_t app, ctrl_t ctrl, const char *name, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *value, size_t valuelen) { gpg_error_t err; if (!app || !name || !*name || !value) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.setattr) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.setattr (app, name, pincb, pincb_arg, value, valuelen); unlock_app (app); return err; } /* Create the signature and return the allocated result in OUTDATA. If a PIN is required the PINCB will be used to ask for the PIN; it should return the PIN in an allocated buffer and put it into PIN. */ gpg_error_t app_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen ) { gpg_error_t err; if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.sign) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.sign (app, keyidstr, hashalgo, pincb, pincb_arg, indata, indatalen, outdata, outdatalen); unlock_app (app); if (opt.verbose) log_info ("operation sign result: %s\n", gpg_strerror (err)); return err; } /* Create the signature using the INTERNAL AUTHENTICATE command and return the allocated result in OUTDATA. If a PIN is required the PINCB will be used to ask for the PIN; it should return the PIN in an allocated buffer and put it into PIN. */ gpg_error_t app_auth (app_t app, ctrl_t ctrl, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen ) { gpg_error_t err; if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.auth) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.auth (app, keyidstr, pincb, pincb_arg, indata, indatalen, outdata, outdatalen); unlock_app (app); if (opt.verbose) log_info ("operation auth result: %s\n", gpg_strerror (err)); return err; } /* Decrypt the data in INDATA and return the allocated result in OUTDATA. If a PIN is required the PINCB will be used to ask for the PIN; it should return the PIN in an allocated buffer and put it into PIN. */ gpg_error_t app_decipher (app_t app, ctrl_t ctrl, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const void *indata, size_t indatalen, unsigned char **outdata, size_t *outdatalen, unsigned int *r_info) { gpg_error_t err; *r_info = 0; if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.decipher) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.decipher (app, keyidstr, pincb, pincb_arg, indata, indatalen, outdata, outdatalen, r_info); unlock_app (app); if (opt.verbose) log_info ("operation decipher result: %s\n", gpg_strerror (err)); return err; } /* Perform the WRITECERT operation. */ gpg_error_t app_writecert (app_t app, ctrl_t ctrl, const char *certidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *data, size_t datalen) { gpg_error_t err; if (!app || !certidstr || !*certidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.writecert) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.writecert (app, ctrl, certidstr, pincb, pincb_arg, data, datalen); unlock_app (app); if (opt.verbose) log_info ("operation writecert result: %s\n", gpg_strerror (err)); return err; } /* Perform the WRITEKEY operation. */ gpg_error_t app_writekey (app_t app, ctrl_t ctrl, const char *keyidstr, unsigned int flags, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg, const unsigned char *keydata, size_t keydatalen) { gpg_error_t err; if (!app || !keyidstr || !*keyidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.writekey) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.writekey (app, ctrl, keyidstr, flags, pincb, pincb_arg, keydata, keydatalen); unlock_app (app); if (opt.verbose) log_info ("operation writekey result: %s\n", gpg_strerror (err)); return err; } /* Perform a SETATTR operation. */ gpg_error_t app_genkey (app_t app, ctrl_t ctrl, const char *keynostr, const char *keytype, unsigned int flags, time_t createtime, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; if (!app || !keynostr || !*keynostr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.genkey) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.genkey (app, ctrl, keynostr, keytype, flags, createtime, pincb, pincb_arg); unlock_app (app); if (opt.verbose) log_info ("operation genkey result: %s\n", gpg_strerror (err)); return err; } /* Perform a GET CHALLENGE operation. This function is special as it directly accesses the card without any application specific wrapper. */ gpg_error_t app_get_challenge (app_t app, ctrl_t ctrl, size_t nbytes, unsigned char *buffer) { gpg_error_t err; if (!app || !nbytes || !buffer) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); err = lock_app (app, ctrl); if (err) return err; err = iso7816_get_challenge (app->slot, nbytes, buffer); unlock_app (app); return err; } /* Perform a CHANGE REFERENCE DATA or RESET RETRY COUNTER operation. */ gpg_error_t app_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, unsigned int flags, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; if (!app || !chvnostr || !*chvnostr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.change_pin) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.change_pin (app, ctrl, chvnostr, flags, pincb, pincb_arg); unlock_app (app); if (opt.verbose) log_info ("operation change_pin result: %s\n", gpg_strerror (err)); return err; } /* Perform a VERIFY operation without doing anything else. This may be used to initialize a the PIN cache for long lasting other operations. Its use is highly application dependent. */ gpg_error_t app_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; if (!app || !keyidstr || !*keyidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); if (!app->ref_count) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!app->fnc.check_pin) return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); err = lock_app (app, ctrl); if (err) return err; err = app->fnc.check_pin (app, keyidstr, pincb, pincb_arg); unlock_app (app); if (opt.verbose) log_info ("operation check_pin result: %s\n", gpg_strerror (err)); return err; } static void report_change (int slot, int old_status, int cur_status) { char *homestr, *envstr; char *fname; char templ[50]; - FILE *fp; + estream_t fp; snprintf (templ, sizeof templ, "reader_%d.status", slot); fname = make_filename (gnupg_homedir (), templ, NULL ); - fp = fopen (fname, "w"); + fp = es_fopen (fname, "w"); if (fp) { - fprintf (fp, "%s\n", + es_fprintf (fp, "%s\n", (cur_status & 1)? "USABLE": (cur_status & 4)? "ACTIVE": (cur_status & 2)? "PRESENT": "NOCARD"); - fclose (fp); + es_fclose (fp); } xfree (fname); homestr = make_filename (gnupg_homedir (), NULL); if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0) log_error ("out of core while building environment\n"); else { gpg_error_t err; const char *args[9], *envs[2]; char numbuf1[30], numbuf2[30], numbuf3[30]; envs[0] = envstr; envs[1] = NULL; sprintf (numbuf1, "%d", slot); sprintf (numbuf2, "0x%04X", old_status); sprintf (numbuf3, "0x%04X", cur_status); args[0] = "--reader-port"; args[1] = numbuf1; args[2] = "--old-code"; args[3] = numbuf2; args[4] = "--new-code"; args[5] = numbuf3; args[6] = "--status"; args[7] = ((cur_status & 1)? "USABLE": (cur_status & 4)? "ACTIVE": (cur_status & 2)? "PRESENT": "NOCARD"); args[8] = NULL; fname = make_filename (gnupg_homedir (), "scd-event", NULL); err = gnupg_spawn_process_detached (fname, args, envs); if (err && gpg_err_code (err) != GPG_ERR_ENOENT) log_error ("failed to run event handler '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); xfree (envstr); } xfree (homestr); } int scd_update_reader_status_file (void) { app_t a, app_next; int periodical_check_needed = 0; npth_mutex_lock (&app_list_lock); for (a = app_top; a; a = app_next) { int sw; unsigned int status; lock_app (a, NULL); app_next = a->next; if (a->reset_requested) status = 0; else { sw = apdu_get_status (a->slot, 0, &status); if (sw == SW_HOST_NO_READER) { /* Most likely the _reader_ has been unplugged. */ status = 0; } else if (sw) { /* Get status failed. Ignore that. */ if (a->periodical_check_needed) periodical_check_needed = 1; unlock_app (a); continue; } } if (a->card_status != status) { report_change (a->slot, a->card_status, status); send_client_notifications (a, status == 0); if (status == 0) { log_debug ("Removal of a card: %d\n", a->slot); apdu_close_reader (a->slot); deallocate_app (a); } else { a->card_status = status; if (a->periodical_check_needed) periodical_check_needed = 1; unlock_app (a); } } else { if (a->periodical_check_needed) periodical_check_needed = 1; unlock_app (a); } } npth_mutex_unlock (&app_list_lock); return periodical_check_needed; } /* This function must be called once to initialize this module. This has to be done before a second thread is spawned. We can't do the static initialization because Pth emulation code might not be able to do a static init; in particular, it is not possible for W32. */ gpg_error_t initialize_module_command (void) { gpg_error_t err; if (npth_mutex_init (&app_list_lock, NULL)) { err = gpg_error_from_syserror (); log_error ("app: error initializing mutex: %s\n", gpg_strerror (err)); return err; } return apdu_init (); } void app_send_card_list (ctrl_t ctrl) { app_t a; char buf[65]; npth_mutex_lock (&app_list_lock); for (a = app_top; a; a = a->next) { if (DIM (buf) < 2 * a->serialnolen + 1) continue; bin2hex (a->serialno, a->serialnolen, buf); send_status_direct (ctrl, "SERIALNO", buf); } npth_mutex_unlock (&app_list_lock); } diff --git a/sm/certchain.c b/sm/certchain.c index 5f8320231..d2a180062 100644 --- a/sm/certchain.c +++ b/sm/certchain.c @@ -1,2380 +1,2380 @@ /* certchain.c - certificate chain validation * Copyright (C) 2001, 2002, 2003, 2004, 2005, * 2006, 2007, 2008, 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 "gpgsm.h" #include #include #include "keydb.h" #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */ #include "../common/i18n.h" #include "../common/tlv.h" /* The OID for the authorityInfoAccess's caIssuers. */ static const char oidstr_caIssuers[] = "1.3.6.1.5.5.7.48.2"; /* Object to keep track of certain root certificates. */ struct marktrusted_info_s { struct marktrusted_info_s *next; unsigned char fpr[20]; }; static struct marktrusted_info_s *marktrusted_info; /* While running the validation function we want to keep track of the certificates in the chain. This type is used for that. */ struct chain_item_s { struct chain_item_s *next; ksba_cert_t cert; /* The certificate. */ int is_root; /* The certificate is the root certificate. */ }; typedef struct chain_item_s *chain_item_t; static int is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn); static int get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen); /* This function returns true if we already asked during this session whether the root certificate CERT shall be marked as trusted. */ static int already_asked_marktrusted (ksba_cert_t cert) { unsigned char fpr[20]; struct marktrusted_info_s *r; gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL); /* No context switches in the loop! */ for (r=marktrusted_info; r; r= r->next) if (!memcmp (r->fpr, fpr, 20)) return 1; return 0; } /* Flag certificate CERT as already asked whether it shall be marked as trusted. */ static void set_already_asked_marktrusted (ksba_cert_t cert) { unsigned char fpr[20]; struct marktrusted_info_s *r; gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL); for (r=marktrusted_info; r; r= r->next) if (!memcmp (r->fpr, fpr, 20)) return; /* Already marked. */ r = xtrycalloc (1, sizeof *r); if (!r) return; memcpy (r->fpr, fpr, 20); r->next = marktrusted_info; marktrusted_info = r; } /* If LISTMODE is true, print FORMAT using LISTMODE to FP. If LISTMODE is false, use the string to print an log_info or, if IS_ERROR is true, and log_error. */ static void do_list (int is_error, int listmode, estream_t fp, const char *format, ...) { va_list arg_ptr; va_start (arg_ptr, format) ; if (listmode) { if (fp) { es_fputs (" [", fp); es_vfprintf (fp, format, arg_ptr); es_fputs ("]\n", fp); } } else { log_logv (is_error? GPGRT_LOG_ERROR: GPGRT_LOG_INFO, format, arg_ptr); log_printf ("\n"); } va_end (arg_ptr); } /* Return 0 if A and B are equal. */ static int compare_certs (ksba_cert_t a, ksba_cert_t b) { const unsigned char *img_a, *img_b; size_t len_a, len_b; img_a = ksba_cert_get_image (a, &len_a); if (!img_a) return 1; img_b = ksba_cert_get_image (b, &len_b); if (!img_b) return 1; return !(len_a == len_b && !memcmp (img_a, img_b, len_a)); } /* Return true if CERT has the validityModel extensions and defines the use of the chain model. */ static int has_validation_model_chain (ksba_cert_t cert, int listmode, estream_t listfp) { gpg_error_t err; int idx, yes; const char *oid; size_t off, derlen, objlen, hdrlen; const unsigned char *der; int class, tag, constructed, ndef; char *oidbuf; for (idx=0; !(err=ksba_cert_get_extension (cert, idx, &oid, NULL, &off, &derlen));idx++) if (!strcmp (oid, "1.3.6.1.4.1.8301.3.5") ) break; if (err) return 0; /* Not found. */ der = ksba_cert_get_image (cert, NULL); if (!der) { err = gpg_error (GPG_ERR_INV_OBJ); /* Oops */ goto leave; } der += off; err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, &ndef, &objlen, &hdrlen); if (!err && (objlen > derlen || tag != TAG_SEQUENCE)) err = gpg_error (GPG_ERR_INV_OBJ); if (err) goto leave; derlen = objlen; err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, &ndef, &objlen, &hdrlen); if (!err && (objlen > derlen || tag != TAG_OBJECT_ID)) err = gpg_error (GPG_ERR_INV_OBJ); if (err) goto leave; oidbuf = ksba_oid_to_str (der, objlen); if (!oidbuf) { err = gpg_error_from_syserror (); goto leave; } if (opt.verbose) do_list (0, listmode, listfp, _("validation model requested by certificate: %s"), !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1")? _("chain") : !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.2")? _("shell") : /* */ oidbuf); yes = !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1"); ksba_free (oidbuf); return yes; leave: log_error ("error parsing validityModel: %s\n", gpg_strerror (err)); return 0; } static int unknown_criticals (ksba_cert_t cert, int listmode, estream_t fp) { static const char *known[] = { "2.5.29.15", /* keyUsage */ "2.5.29.17", /* subjectAltName Japanese DoCoMo certs mark them as critical. PKIX only requires them as critical if subjectName is empty. I don't know whether our code gracefully handles such empry subjectNames but that is another story. */ "2.5.29.19", /* basic Constraints */ "2.5.29.32", /* certificatePolicies */ "2.5.29.37", /* extendedKeyUsage - handled by certlist.c */ "1.3.6.1.4.1.8301.3.5", /* validityModel - handled here. */ NULL }; int rc = 0, i, idx, crit; const char *oid; gpg_error_t err; int unsupported; strlist_t sl; for (idx=0; !(err=ksba_cert_get_extension (cert, idx, &oid, &crit, NULL, NULL));idx++) { if (!crit) continue; for (i=0; known[i] && strcmp (known[i],oid); i++) ; unsupported = !known[i]; /* If this critical extension is not supported. Check the list of to be ignored extensions to see whether we claim that it is supported. */ if (unsupported && opt.ignored_cert_extensions) { for (sl=opt.ignored_cert_extensions; sl && strcmp (sl->d, oid); sl = sl->next) ; if (sl) unsupported = 0; } if (unsupported) { do_list (1, listmode, fp, _("critical certificate extension %s is not supported"), oid); rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT); } } /* We ignore the error codes EOF as well as no-value. The later will occur for certificates with no extensions at all. */ if (err && gpg_err_code (err) != GPG_ERR_EOF && gpg_err_code (err) != GPG_ERR_NO_VALUE) rc = err; return rc; } /* Check whether CERT is an allowed certificate. This requires that CERT matches all requirements for such a CA, i.e. the BasicConstraints extension. The function returns 0 on success and the allowed length of the chain at CHAINLEN. */ static int allowed_ca (ctrl_t ctrl, ksba_cert_t cert, int *chainlen, int listmode, estream_t fp) { gpg_error_t err; int flag; err = ksba_cert_is_ca (cert, &flag, chainlen); if (err) return err; if (!flag) { if (get_regtp_ca_info (ctrl, cert, chainlen)) { /* Note that dirmngr takes a different way to cope with such certs. */ return 0; /* RegTP issued certificate. */ } do_list (1, listmode, fp,_("issuer certificate is not marked as a CA")); return gpg_error (GPG_ERR_BAD_CA_CERT); } return 0; } static int check_cert_policy (ksba_cert_t cert, int listmode, estream_t fplist) { gpg_error_t err; char *policies; - FILE *fp; + estream_t fp; int any_critical; err = ksba_cert_get_cert_policies (cert, &policies); if (gpg_err_code (err) == GPG_ERR_NO_DATA) return 0; /* No policy given. */ if (err) return err; /* STRING is a line delimited list of certificate policies as stored in the certificate. The line itself is colon delimited where the first field is the OID of the policy and the second field either N or C for normal or critical extension */ if (opt.verbose > 1 && !listmode) log_info ("certificate's policy list: %s\n", policies); /* The check is very minimal but won't give false positives */ any_critical = !!strstr (policies, ":C"); if (!opt.policy_file) { xfree (policies); if (any_critical) { do_list (1, listmode, fplist, _("critical marked policy without configured policies")); return gpg_error (GPG_ERR_NO_POLICY_MATCH); } return 0; } - fp = fopen (opt.policy_file, "r"); + fp = es_fopen (opt.policy_file, "r"); if (!fp) { if (opt.verbose || errno != ENOENT) log_info (_("failed to open '%s': %s\n"), opt.policy_file, strerror (errno)); xfree (policies); /* With no critical policies this is only a warning */ if (!any_critical) { if (!opt.quiet) do_list (0, listmode, fplist, _("Note: non-critical certificate policy not allowed")); return 0; } do_list (1, listmode, fplist, _("certificate policy not allowed")); return gpg_error (GPG_ERR_NO_POLICY_MATCH); } for (;;) { int c; char *p, line[256]; char *haystack, *allowed; /* read line */ do { - if (!fgets (line, DIM(line)-1, fp) ) + if (!es_fgets (line, DIM(line)-1, fp) ) { - gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno)); + gpg_error_t tmperr = gpg_error_from_syserror (); xfree (policies); - if (feof (fp)) + if (es_feof (fp)) { - fclose (fp); + es_fclose (fp); /* With no critical policies this is only a warning */ if (!any_critical) { do_list (0, listmode, fplist, _("Note: non-critical certificate policy not allowed")); return 0; } do_list (1, listmode, fplist, _("certificate policy not allowed")); return gpg_error (GPG_ERR_NO_POLICY_MATCH); } - fclose (fp); + es_fclose (fp); return tmperr; } if (!*line || line[strlen(line)-1] != '\n') { /* eat until end of line */ - while ( (c=getc (fp)) != EOF && c != '\n') + while ((c = es_getc (fp)) != EOF && c != '\n') ; - fclose (fp); + es_fclose (fp); xfree (policies); return gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; } while (!*p || *p == '\n' || *p == '#'); /* Parse line. Note that the line has always a LF and spacep does not consider a LF a space. Thus strpbrk will always succeed. */ for (allowed=line; spacep (allowed); allowed++) ; p = strpbrk (allowed, " :\n"); if (!*p || p == allowed) { - fclose (fp); + es_fclose (fp); xfree (policies); return gpg_error (GPG_ERR_CONFIGURATION); } *p = 0; /* strip the rest of the line */ /* See whether we find ALLOWED (which is an OID) in POLICIES */ for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1) { if ( !(p == policies || p[-1] == '\n') ) continue; /* Does not match the begin of a line. */ if (p[strlen (allowed)] != ':') continue; /* The length does not match. */ /* Yep - it does match so return okay. */ - fclose (fp); + es_fclose (fp); xfree (policies); return 0; } } } /* Helper function for find_up. This resets the key handle and search for an issuer ISSUER with a subjectKeyIdentifier of KEYID. Returns 0 on success or -1 when not found. */ static int find_up_search_by_keyid (ctrl_t ctrl, KEYDB_HANDLE kh, const char *issuer, ksba_sexp_t keyid) { int rc; ksba_cert_t cert = NULL; ksba_sexp_t subj = NULL; ksba_isotime_t not_before, not_after, last_not_before, ne_last_not_before; ksba_cert_t found_cert = NULL; ksba_cert_t ne_found_cert = NULL; keydb_search_reset (kh); while (!(rc = keydb_search_subject (ctrl, kh, issuer))) { ksba_cert_release (cert); cert = NULL; rc = keydb_get_cert (kh, &cert); if (rc) { log_error ("keydb_get_cert() failed: rc=%d\n", rc); rc = -1; goto leave; } xfree (subj); if (!ksba_cert_get_subj_key_id (cert, NULL, &subj)) { if (!cmp_simple_canon_sexp (keyid, subj)) { /* Found matching cert. */ rc = ksba_cert_get_validity (cert, 0, not_before); if (!rc) rc = ksba_cert_get_validity (cert, 1, not_after); if (rc) { log_error ("keydb_get_validity() failed: rc=%d\n", rc); rc = -1; goto leave; } if (!found_cert || strcmp (last_not_before, not_before) < 0) { /* This certificate is the first one found or newer * than the previous one. This copes with * re-issuing CA certificates while keeping the same * key information. */ gnupg_copy_time (last_not_before, not_before); ksba_cert_release (found_cert); ksba_cert_ref ((found_cert = cert)); keydb_push_found_state (kh); } if (*not_after && strcmp (ctrl->current_time, not_after) > 0 ) ; /* CERT has expired - don't consider it. */ else if (!ne_found_cert || strcmp (ne_last_not_before, not_before) < 0) { /* This certificate is the first non-expired one * found or newer than the previous non-expired one. */ gnupg_copy_time (ne_last_not_before, not_before); ksba_cert_release (ne_found_cert); ksba_cert_ref ((ne_found_cert = cert)); } } } } if (!found_cert) goto leave; /* Take the last saved one. Note that push/pop_found_state are * misnomers because there is no stack of states. Renaming them to * save/restore_found_state would be better. */ keydb_pop_found_state (kh); rc = 0; /* Ignore EOF or other error after the first cert. */ /* We need to consider some corner cases. It is possible that we * have a long term certificate (e.g. valid from 2008 to 2033) as * well as a re-issued (i.e. using the same key material) short term * certificate (say from 2016 to 2019). Using the short term * certificate is the proper solution. But we need to take care if * there is no re-issued new short term certificate (e.g. from 2020 * to 2023) available. In that case it is better to use the long * term certificate which is still valid. The code may run into * minor problems in the case of the chain validation mode. Given * that this corner case is due to non-diligent PKI management we * ignore this problem. */ /* The most common case is that the found certificate is not expired * and thus identical to the one found from the list of non-expired * certs. We can stop here. */ if (found_cert == ne_found_cert) goto leave; /* If we do not have a non expired certificate the actual cert is * expired and we can also stop here. */ if (!ne_found_cert) goto leave; /* Now we need to see whether the found certificate is expired and * only in this case we return the certificate found in the list of * non-expired certs. */ rc = ksba_cert_get_validity (found_cert, 1, not_after); if (rc) { log_error ("keydb_get_validity() failed: rc=%d\n", rc); rc = -1; goto leave; } if (*not_after && strcmp (ctrl->current_time, not_after) > 0 ) { /* CERT has expired. Use the NE_FOUND_CERT. Because we have no * found state for this we need to search for it again. */ unsigned char fpr[20]; gpgsm_get_fingerprint (ne_found_cert, GCRY_MD_SHA1, fpr, NULL); keydb_search_reset (kh); rc = keydb_search_fpr (ctrl, kh, fpr); if (rc) { log_error ("keydb_search_fpr() failed: rc=%d\n", rc); rc = -1; goto leave; } /* Ready. The NE_FOUND_CERT is availabale via keydb_get_cert. */ } leave: ksba_cert_release (found_cert); ksba_cert_release (ne_found_cert); ksba_cert_release (cert); xfree (subj); return rc? -1:0; } struct find_up_store_certs_s { ctrl_t ctrl; int count; unsigned int want_fpr:1; unsigned int got_fpr:1; unsigned char fpr[20]; }; static void find_up_store_certs_cb (void *cb_value, ksba_cert_t cert) { struct find_up_store_certs_s *parm = cb_value; if (keydb_store_cert (parm->ctrl, cert, 1, NULL)) log_error ("error storing issuer certificate as ephemeral\n"); else if (parm->want_fpr && !parm->got_fpr) { if (!gpgsm_get_fingerprint (cert, 0, parm->fpr, NULL)) log_error (_("failed to get the fingerprint\n")); else parm->got_fpr = 1; } parm->count++; } /* Helper for find_up(). Locate the certificate for ISSUER using an external lookup. KH is the keydb context we are currently using. On success 0 is returned and the certificate may be retrieved from the keydb using keydb_get_cert(). KEYID is the keyIdentifier from the AKI or NULL. */ static int find_up_external (ctrl_t ctrl, KEYDB_HANDLE kh, const char *issuer, ksba_sexp_t keyid) { int rc; strlist_t names = NULL; struct find_up_store_certs_s find_up_store_certs_parm; char *pattern; const char *s; find_up_store_certs_parm.ctrl = ctrl; find_up_store_certs_parm.want_fpr = 0; find_up_store_certs_parm.got_fpr = 0; find_up_store_certs_parm.count = 0; if (opt.verbose) log_info (_("looking up issuer at external location\n")); /* The Dirmngr process is confused about unknown attributes. As a quick and ugly hack we locate the CN and use the issuer string starting at this attribite. Fixme: we should have far better parsing for external lookups in the Dirmngr. */ s = strstr (issuer, "CN="); if (!s || s == issuer || s[-1] != ',') s = issuer; pattern = xtrymalloc (strlen (s)+2); if (!pattern) return gpg_error_from_syserror (); strcpy (stpcpy (pattern, "/"), s); add_to_strlist (&names, pattern); xfree (pattern); rc = gpgsm_dirmngr_lookup (ctrl, names, NULL, 0, find_up_store_certs_cb, &find_up_store_certs_parm); free_strlist (names); if (opt.verbose) log_info (_("number of issuers matching: %d\n"), find_up_store_certs_parm.count); if (rc) { log_error ("external key lookup failed: %s\n", gpg_strerror (rc)); rc = -1; } else if (!find_up_store_certs_parm.count) rc = -1; else { int old; /* The issuers are currently stored in the ephemeral key DB, so we temporary switch to ephemeral mode. */ old = keydb_set_ephemeral (kh, 1); if (keyid) rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid); else { keydb_search_reset (kh); rc = keydb_search_subject (ctrl, kh, issuer); } keydb_set_ephemeral (kh, old); } return rc; } /* Helper for find_up(). Locate the certificate for CERT using the * caIssuer from the authorityInfoAccess. KH is the keydb context we * are currently using. On success 0 is returned and the certificate * may be retrieved from the keydb using keydb_get_cert(). If no * suitable authorityInfoAccess is encoded in the certificate * GPG_ERR_NOT_FOUND is returned. */ static gpg_error_t find_up_via_auth_info_access (ctrl_t ctrl, KEYDB_HANDLE kh, ksba_cert_t cert) { gpg_error_t err; struct find_up_store_certs_s find_up_store_certs_parm; char *url, *ldapurl; int idx, i; char *oid; ksba_name_t name; find_up_store_certs_parm.ctrl = ctrl; find_up_store_certs_parm.want_fpr = 1; find_up_store_certs_parm.got_fpr = 0; find_up_store_certs_parm.count = 0; /* Find suitable URLs; if there is a http scheme we prefer that. */ url = ldapurl = NULL; for (idx=0; !url && !(err = ksba_cert_get_authority_info_access (cert, idx, &oid, &name)); idx++) { if (!strcmp (oid, oidstr_caIssuers)) { for (i=0; !url && ksba_name_enum (name, i); i++) { char *p = ksba_name_get_uri (name, i); if (p) { if (!strncmp (p, "http:", 5) || !strncmp (p, "https:", 6)) url = p; else if (ldapurl) xfree (p); /* We already got one. */ else if (!strncmp (p, "ldap:",5) || !strncmp (p, "ldaps:",6)) ldapurl = p; } else xfree (p); } } ksba_name_release (name); ksba_free (oid); } if (err && gpg_err_code (err) != GPG_ERR_EOF) { log_error (_("can't get authorityInfoAccess: %s\n"), gpg_strerror (err)); return err; } if (!url && ldapurl) { /* No HTTP scheme; fallback to LDAP if available. */ url = ldapurl; ldapurl = NULL; } xfree (ldapurl); if (!url) return gpg_error (GPG_ERR_NOT_FOUND); if (opt.verbose) log_info ("looking up issuer via authorityInfoAccess.caIssuers\n"); err = gpgsm_dirmngr_lookup (ctrl, NULL, url, 0, find_up_store_certs_cb, &find_up_store_certs_parm); /* Although we might receive several certificates we use only the * first one. Or more exacty the first one for which we retrieved * the fingerprint. */ if (opt.verbose) log_info ("number of caIssuers found: %d\n", find_up_store_certs_parm.count); if (err) { log_error ("external URL lookup failed: %s\n", gpg_strerror (err)); err = gpg_error (GPG_ERR_NOT_FOUND); } else if (!find_up_store_certs_parm.got_fpr) err = gpg_error (GPG_ERR_NOT_FOUND); else { int old; /* The retrieved certificates are currently stored in the * ephemeral key DB, so we temporary switch to ephemeral * mode. */ old = keydb_set_ephemeral (kh, 1); keydb_search_reset (kh); err = keydb_search_fpr (ctrl, kh, find_up_store_certs_parm.fpr); keydb_set_ephemeral (kh, old); } return err; } /* Helper for find_up(). Ask the dirmngr for the certificate for ISSUER with optional SERIALNO. KH is the keydb context we are currently using. With SUBJECT_MODE set, ISSUER is searched as the subject. On success 0 is returned and the certificate is available in the ephemeral DB. */ static int find_up_dirmngr (ctrl_t ctrl, KEYDB_HANDLE kh, ksba_sexp_t serialno, const char *issuer, int subject_mode) { int rc; strlist_t names = NULL; struct find_up_store_certs_s find_up_store_certs_parm; char *pattern; (void)kh; find_up_store_certs_parm.ctrl = ctrl; find_up_store_certs_parm.count = 0; if (opt.verbose) log_info (_("looking up issuer from the Dirmngr cache\n")); if (subject_mode) { pattern = xtrymalloc (strlen (issuer)+2); if (pattern) strcpy (stpcpy (pattern, "/"), issuer); } else if (serialno) pattern = gpgsm_format_sn_issuer (serialno, issuer); else { pattern = xtrymalloc (strlen (issuer)+3); if (pattern) strcpy (stpcpy (pattern, "#/"), issuer); } if (!pattern) return gpg_error_from_syserror (); add_to_strlist (&names, pattern); xfree (pattern); rc = gpgsm_dirmngr_lookup (ctrl, names, NULL, 1, find_up_store_certs_cb, &find_up_store_certs_parm); free_strlist (names); if (opt.verbose) log_info (_("number of matching certificates: %d\n"), find_up_store_certs_parm.count); if (rc && !opt.quiet) log_info (_("dirmngr cache-only key lookup failed: %s\n"), gpg_strerror (rc)); return (!rc && find_up_store_certs_parm.count)? 0 : -1; } /* Locate issuing certificate for CERT. ISSUER is the name of the issuer used as a fallback if the other methods don't work. If FIND_NEXT is true, the function shall return the next possible issuer. The certificate itself is not directly returned but a keydb_get_cert on the keydb context KH will return it. Returns 0 on success, -1 if not found or an error code. */ static int find_up (ctrl_t ctrl, KEYDB_HANDLE kh, ksba_cert_t cert, const char *issuer, int find_next) { ksba_name_t authid; ksba_sexp_t authidno; ksba_sexp_t keyid; int rc = -1; if (DBG_X509) log_debug ("looking for parent certificate\n"); if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno)) { const char *s = ksba_name_enum (authid, 0); if (s && *authidno) { rc = keydb_search_issuer_sn (ctrl, kh, s, authidno); if (rc) keydb_search_reset (kh); if (!rc && DBG_X509) log_debug (" found via authid and sn+issuer\n"); /* In case of an error, try to get the certificate from the dirmngr. That is done by trying to put that certifcate into the ephemeral DB and let the code below do the actual retrieve. Thus there is no error checking. Skipped in find_next mode as usual. */ if (rc == -1 && !find_next) find_up_dirmngr (ctrl, kh, authidno, s, 0); /* In case of an error try the ephemeral DB. We can't do that in find_next mode because we can't keep the search state then. */ if (rc == -1 && !find_next) { int old = keydb_set_ephemeral (kh, 1); if (!old) { rc = keydb_search_issuer_sn (ctrl, kh, s, authidno); if (rc) keydb_search_reset (kh); if (!rc && DBG_X509) log_debug (" found via authid and sn+issuer (ephem)\n"); } keydb_set_ephemeral (kh, old); } if (rc) rc = -1; /* Need to make sure to have this error code. */ } if (rc == -1 && keyid && !find_next) { /* Not found by AKI.issuer_sn. Lets try the AKI.ki instead. Loop over all certificates with that issuer as subject and stop for the one with a matching subjectKeyIdentifier. */ /* Fixme: Should we also search in the dirmngr? */ rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid); if (!rc && DBG_X509) log_debug (" found via authid and keyid\n"); if (rc) { int old = keydb_set_ephemeral (kh, 1); if (!old) rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid); if (!rc && DBG_X509) log_debug (" found via authid and keyid (ephem)\n"); keydb_set_ephemeral (kh, old); } if (rc) rc = -1; /* Need to make sure to have this error code. */ } /* If we still didn't found it, try to find it via the subject from the dirmngr-cache. */ if (rc == -1 && !find_next) { if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1)) { int old = keydb_set_ephemeral (kh, 1); if (keyid) rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid); else { keydb_search_reset (kh); rc = keydb_search_subject (ctrl, kh, issuer); } keydb_set_ephemeral (kh, old); } if (rc) rc = -1; /* Need to make sure to have this error code. */ if (!rc && DBG_X509) log_debug (" found via authid and issuer from dirmngr cache\n"); } /* If we still didn't found it, try an external lookup. */ if (rc == -1 && !find_next && !ctrl->offline) { /* We allow AIA also if CRLs are enabled; both can be used * as a web bug so it does not make sense to not use AIA if * CRL checks are enabled. */ if ((opt.auto_issuer_key_retrieve || !opt.no_crl_check) && !find_up_via_auth_info_access (ctrl, kh, cert)) { if (DBG_X509) log_debug (" found via authorityInfoAccess.caIssuers\n"); rc = 0; } else if (opt.auto_issuer_key_retrieve) { rc = find_up_external (ctrl, kh, issuer, keyid); if (!rc && DBG_X509) log_debug (" found via authid and external lookup\n"); } } /* Print a note so that the user does not feel too helpless when an issuer certificate was found and gpgsm prints BAD signature because it is not the correct one. */ if (rc == -1 && opt.quiet) ; else if (rc == -1) { log_info ("%sissuer certificate ", find_next?"next ":""); if (keyid) { log_printf ("{"); gpgsm_dump_serial (keyid); log_printf ("} "); } if (authidno) { log_printf ("(#"); gpgsm_dump_serial (authidno); log_printf ("/"); gpgsm_dump_string (s); log_printf (") "); } log_printf ("not found using authorityKeyIdentifier\n"); } else if (rc) log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc); xfree (keyid); ksba_name_release (authid); xfree (authidno); } if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */ rc = keydb_search_subject (ctrl, kh, issuer); if (rc == -1 && !find_next) { int old; /* Also try to get it from the Dirmngr cache. The function merely puts it into the ephemeral database. */ find_up_dirmngr (ctrl, kh, NULL, issuer, 0); /* Not found, let us see whether we have one in the ephemeral key DB. */ old = keydb_set_ephemeral (kh, 1); if (!old) { keydb_search_reset (kh); rc = keydb_search_subject (ctrl, kh, issuer); } keydb_set_ephemeral (kh, old); if (!rc && DBG_X509) log_debug (" found via issuer\n"); } /* Still not found. If enabled, try an external lookup. */ if (rc == -1 && !find_next && !ctrl->offline) { if ((opt.auto_issuer_key_retrieve || !opt.no_crl_check) && !find_up_via_auth_info_access (ctrl, kh, cert)) { if (DBG_X509) log_debug (" found via authorityInfoAccess.caIssuers\n"); rc = 0; } else if (opt.auto_issuer_key_retrieve) { rc = find_up_external (ctrl, kh, issuer, NULL); if (!rc && DBG_X509) log_debug (" found via issuer and external lookup\n"); } } return rc; } /* Return the next certificate up in the chain starting at START. Returns -1 when there are no more certificates. */ int gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next) { int rc = 0; char *issuer = NULL; char *subject = NULL; KEYDB_HANDLE kh = keydb_new (); *r_next = NULL; if (!kh) { log_error (_("failed to allocate keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } issuer = ksba_cert_get_issuer (start, 0); subject = ksba_cert_get_subject (start, 0); if (!issuer) { log_error ("no issuer found in certificate\n"); rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } if (!subject) { log_error ("no subject found in certificate\n"); rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } if (is_root_cert (start, issuer, subject)) { rc = -1; /* we are at the root */ goto leave; } rc = find_up (ctrl, kh, start, issuer, 0); if (rc) { /* It is quite common not to have a certificate, so better don't print an error here. */ if (rc != -1 && opt.verbose > 1) log_error ("failed to find issuer's certificate: rc=%d\n", rc); rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT); goto leave; } rc = keydb_get_cert (kh, r_next); if (rc) { log_error ("keydb_get_cert() failed: rc=%d\n", rc); rc = gpg_error (GPG_ERR_GENERAL); } leave: xfree (issuer); xfree (subject); keydb_release (kh); return rc; } /* Helper for gpgsm_is_root_cert. This one is used if the subject and issuer DNs are already known. */ static int is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn) { gpg_error_t err; int result = 0; ksba_sexp_t serialno; ksba_sexp_t ak_keyid; ksba_name_t ak_name; ksba_sexp_t ak_sn; const char *ak_name_str; ksba_sexp_t subj_keyid = NULL; if (!issuerdn || !subjectdn) return 0; /* No. */ if (strcmp (issuerdn, subjectdn)) return 0; /* No. */ err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn); if (err) { if (gpg_err_code (err) == GPG_ERR_NO_DATA) return 1; /* Yes. Without a authorityKeyIdentifier this needs to be the Root certifcate (our trust anchor). */ log_error ("error getting authorityKeyIdentifier: %s\n", gpg_strerror (err)); return 0; /* Well, it is broken anyway. Return No. */ } serialno = ksba_cert_get_serial (cert); if (!serialno) { log_error ("error getting serialno: %s\n", gpg_strerror (err)); goto leave; } /* Check whether the auth name's matches the issuer name+sn. If that is the case this is a root certificate. */ ak_name_str = ksba_name_enum (ak_name, 0); if (ak_name_str && !strcmp (ak_name_str, issuerdn) && !cmp_simple_canon_sexp (ak_sn, serialno)) { result = 1; /* Right, CERT is self-signed. */ goto leave; } /* Similar for the ak_keyid. */ if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid) && !cmp_simple_canon_sexp (ak_keyid, subj_keyid)) { result = 1; /* Right, CERT is self-signed. */ goto leave; } leave: ksba_free (subj_keyid); ksba_free (ak_keyid); ksba_name_release (ak_name); ksba_free (ak_sn); ksba_free (serialno); return result; } /* Check whether the CERT is a root certificate. Returns True if this is the case. */ int gpgsm_is_root_cert (ksba_cert_t cert) { char *issuer; char *subject; int yes; issuer = ksba_cert_get_issuer (cert, 0); subject = ksba_cert_get_subject (cert, 0); yes = is_root_cert (cert, issuer, subject); xfree (issuer); xfree (subject); return yes; } /* This is a helper for gpgsm_validate_chain. */ static gpg_error_t is_cert_still_valid (ctrl_t ctrl, int force_ocsp, int lm, estream_t fp, ksba_cert_t subject_cert, ksba_cert_t issuer_cert, int *any_revoked, int *any_no_crl, int *any_crl_too_old) { gpg_error_t err; if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp)) { audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, gpg_error (GPG_ERR_NOT_ENABLED)); return 0; } if (!(force_ocsp || ctrl->use_ocsp) && !opt.enable_issuer_based_crl_check) { err = ksba_cert_get_crl_dist_point (subject_cert, 0, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_EOF) { /* No DP specified in the certificate. Thus the CA does not * consider a CRL useful and the user of the certificate * also does not consider this to be a critical thing. In * this case we can conclude that the certificate shall not * be revocable. Note that we reach this point here only if * no OCSP responder shall be used. */ audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, gpg_error (GPG_ERR_TRUE)); return 0; } } err = gpgsm_dirmngr_isvalid (ctrl, subject_cert, issuer_cert, force_ocsp? 2 : !!ctrl->use_ocsp); audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, err); if (err) { if (!lm) gpgsm_cert_log_name (NULL, subject_cert); switch (gpg_err_code (err)) { case GPG_ERR_CERT_REVOKED: do_list (1, lm, fp, _("certificate has been revoked")); *any_revoked = 1; /* Store that in the keybox so that key listings are able to return the revoked flag. We don't care about error, though. */ keydb_set_cert_flags (ctrl, subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0, ~0, VALIDITY_REVOKED); break; case GPG_ERR_NO_CRL_KNOWN: do_list (1, lm, fp, _("no CRL found for certificate")); *any_no_crl = 1; break; case GPG_ERR_NO_DATA: do_list (1, lm, fp, _("the status of the certificate is unknown")); *any_no_crl = 1; break; case GPG_ERR_CRL_TOO_OLD: do_list (1, lm, fp, _("the available CRL is too old")); if (!lm) log_info (_("please make sure that the " "\"dirmngr\" is properly installed\n")); *any_crl_too_old = 1; break; default: do_list (1, lm, fp, _("checking the CRL failed: %s"), gpg_strerror (err)); return err; } } return 0; } /* Helper for gpgsm_validate_chain to check the validity period of SUBJECT_CERT. The caller needs to pass EXPTIME which will be updated to the nearest expiration time seen. A DEPTH of 0 indicates the target certificate, -1 the final root certificate and other values intermediate certificates. */ static gpg_error_t check_validity_period (ksba_isotime_t current_time, ksba_cert_t subject_cert, ksba_isotime_t exptime, int listmode, estream_t listfp, int depth) { gpg_error_t err; ksba_isotime_t not_before, not_after; err = ksba_cert_get_validity (subject_cert, 0, not_before); if (!err) err = ksba_cert_get_validity (subject_cert, 1, not_after); if (err) { do_list (1, listmode, listfp, _("certificate with invalid validity: %s"), gpg_strerror (err)); return gpg_error (GPG_ERR_BAD_CERT); } if (*not_after) { if (!*exptime) gnupg_copy_time (exptime, not_after); else if (strcmp (not_after, exptime) < 0 ) gnupg_copy_time (exptime, not_after); } if (*not_before && strcmp (current_time, not_before) < 0 ) { do_list (1, listmode, listfp, depth == 0 ? _("certificate not yet valid") : depth == -1 ? _("root certificate not yet valid") : /* other */ _("intermediate certificate not yet valid")); if (!listmode) { log_info (" (valid from "); dump_isotime (not_before); log_printf (")\n"); } return gpg_error (GPG_ERR_CERT_TOO_YOUNG); } if (*not_after && strcmp (current_time, not_after) > 0 ) { do_list (opt.ignore_expiration?0:1, listmode, listfp, depth == 0 ? _("certificate has expired") : depth == -1 ? _("root certificate has expired") : /* other */ _("intermediate certificate has expired")); if (!listmode) { log_info (" (expired at "); dump_isotime (not_after); log_printf (")\n"); } if (opt.ignore_expiration) log_info ("WARNING: ignoring expiration\n"); else return gpg_error (GPG_ERR_CERT_EXPIRED); } return 0; } /* This is a variant of check_validity_period used with the chain model. The dextra contraint here is that notBefore and notAfter must exists and if the additional argument CHECK_TIME is given this time is used to check the validity period of SUBJECT_CERT. */ static gpg_error_t check_validity_period_cm (ksba_isotime_t current_time, ksba_isotime_t check_time, ksba_cert_t subject_cert, ksba_isotime_t exptime, int listmode, estream_t listfp, int depth) { gpg_error_t err; ksba_isotime_t not_before, not_after; err = ksba_cert_get_validity (subject_cert, 0, not_before); if (!err) err = ksba_cert_get_validity (subject_cert, 1, not_after); if (err) { do_list (1, listmode, listfp, _("certificate with invalid validity: %s"), gpg_strerror (err)); return gpg_error (GPG_ERR_BAD_CERT); } if (!*not_before || !*not_after) { do_list (1, listmode, listfp, _("required certificate attributes missing: %s%s%s"), !*not_before? "notBefore":"", (!*not_before && !*not_after)? ", ":"", !*not_before? "notAfter":""); return gpg_error (GPG_ERR_BAD_CERT); } if (strcmp (not_before, not_after) > 0 ) { do_list (1, listmode, listfp, _("certificate with invalid validity")); log_info (" (valid from "); dump_isotime (not_before); log_printf (" expired at "); dump_isotime (not_after); log_printf (")\n"); return gpg_error (GPG_ERR_BAD_CERT); } if (!*exptime) gnupg_copy_time (exptime, not_after); else if (strcmp (not_after, exptime) < 0 ) gnupg_copy_time (exptime, not_after); if (strcmp (current_time, not_before) < 0 ) { do_list (1, listmode, listfp, depth == 0 ? _("certificate not yet valid") : depth == -1 ? _("root certificate not yet valid") : /* other */ _("intermediate certificate not yet valid")); if (!listmode) { log_info (" (valid from "); dump_isotime (not_before); log_printf (")\n"); } return gpg_error (GPG_ERR_CERT_TOO_YOUNG); } if (*check_time && (strcmp (check_time, not_before) < 0 || strcmp (check_time, not_after) > 0)) { /* Note that we don't need a case for the root certificate because its own consitency has already been checked. */ do_list(opt.ignore_expiration?0:1, listmode, listfp, depth == 0 ? _("signature not created during lifetime of certificate") : depth == 1 ? _("certificate not created during lifetime of issuer") : _("intermediate certificate not created during lifetime " "of issuer")); if (!listmode) { log_info (depth== 0? _(" ( signature created at ") : /* */ _(" (certificate created at ") ); dump_isotime (check_time); log_printf (")\n"); log_info (depth==0? _(" (certificate valid from ") : /* */ _(" ( issuer valid from ") ); dump_isotime (not_before); log_info (" to "); dump_isotime (not_after); log_printf (")\n"); } if (opt.ignore_expiration) log_info ("WARNING: ignoring expiration\n"); else return gpg_error (GPG_ERR_CERT_EXPIRED); } return 0; } /* Ask the user whether he wants to mark the certificate CERT trusted. Returns true if the CERT is the trusted. We also check whether the agent is at all enabled to allow marktrusted and don't call it in this session again if it is not. */ static int ask_marktrusted (ctrl_t ctrl, ksba_cert_t cert, int listmode) { static int no_more_questions; int rc; char *fpr; int success = 0; fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1); log_info (_("fingerprint=%s\n"), fpr? fpr : "?"); xfree (fpr); if (no_more_questions) rc = gpg_error (GPG_ERR_NOT_SUPPORTED); else rc = gpgsm_agent_marktrusted (ctrl, cert); if (!rc) { log_info (_("root certificate has now been marked as trusted\n")); success = 1; } else if (!listmode) { gpgsm_dump_cert ("issuer", cert); log_info ("after checking the fingerprint, you may want " "to add it manually to the list of trusted certificates.\n"); } if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED) { if (!no_more_questions) log_info (_("interactive marking as trusted " "not enabled in gpg-agent\n")); no_more_questions = 1; } else if (gpg_err_code (rc) == GPG_ERR_CANCELED) { log_info (_("interactive marking as trusted " "disabled for this session\n")); no_more_questions = 1; } else set_already_asked_marktrusted (cert); return success; } /* Validate a chain and optionally return the nearest expiration time in R_EXPTIME. With LISTMODE set to 1 a special listmode is activated where only information about the certificate is printed to LISTFP and no output is send to the usual log stream. If CHECKTIME_ARG is set, it is used only in the chain model instead of the current time. Defined flag bits VALIDATE_FLAG_NO_DIRMNGR - Do not do any dirmngr isvalid checks. VALIDATE_FLAG_CHAIN_MODEL - Check according to chain model. VALIDATE_FLAG_STEED - Check according to the STEED model. */ static int do_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime_arg, ksba_isotime_t r_exptime, int listmode, estream_t listfp, unsigned int flags, struct rootca_flags_s *rootca_flags) { int rc = 0, depth, maxdepth; char *issuer = NULL; char *subject = NULL; KEYDB_HANDLE kh = NULL; ksba_cert_t subject_cert = NULL, issuer_cert = NULL; ksba_isotime_t current_time; ksba_isotime_t check_time; ksba_isotime_t exptime; int any_expired = 0; int any_revoked = 0; int any_no_crl = 0; int any_crl_too_old = 0; int any_no_policy_match = 0; int is_qualified = -1; /* Indicates whether the certificate stems from a qualified root certificate. -1 = unknown, 0 = no, 1 = yes. */ chain_item_t chain = NULL; /* A list of all certificates in the chain. */ gnupg_get_isotime (current_time); gnupg_copy_time (ctrl->current_time, current_time); if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) ) { if (!strcmp (checktime_arg, "19700101T000000")) { do_list (1, listmode, listfp, _("WARNING: creation time of signature not known - " "assuming current time")); gnupg_copy_time (check_time, current_time); } else gnupg_copy_time (check_time, checktime_arg); } else *check_time = 0; if (r_exptime) *r_exptime = 0; *exptime = 0; if (opt.no_chain_validation && !listmode) { log_info ("WARNING: bypassing certificate chain validation\n"); return 0; } kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } if (DBG_X509 && !listmode) gpgsm_dump_cert ("target", cert); subject_cert = cert; ksba_cert_ref (subject_cert); maxdepth = 50; depth = 0; for (;;) { int is_root; gpg_error_t istrusted_rc = -1; /* Put the certificate on our list. */ { chain_item_t ci; ci = xtrycalloc (1, sizeof *ci); if (!ci) { rc = gpg_error_from_syserror (); goto leave; } ksba_cert_ref (subject_cert); ci->cert = subject_cert; ci->next = chain; chain = ci; } xfree (issuer); xfree (subject); issuer = ksba_cert_get_issuer (subject_cert, 0); subject = ksba_cert_get_subject (subject_cert, 0); if (!issuer) { do_list (1, listmode, listfp, _("no issuer found in certificate")); rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } /* Is this a self-issued certificate (i.e. the root certificate)? */ is_root = is_root_cert (subject_cert, issuer, subject); if (is_root) { chain->is_root = 1; /* Check early whether the certificate is listed as trusted. We used to do this only later but changed it to call the check right here so that we can access special flags associated with that specific root certificate. */ if (gpgsm_cert_has_well_known_private_key (subject_cert)) { memset (rootca_flags, 0, sizeof *rootca_flags); istrusted_rc = ((flags & VALIDATE_FLAG_STEED) ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED)); } else istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert, NULL, rootca_flags); audit_log_cert (ctrl->audit, AUDIT_ROOT_TRUSTED, subject_cert, istrusted_rc); /* If the chain model extended attribute is used, make sure that our chain model flag is set. */ if (!(flags & VALIDATE_FLAG_STEED) && has_validation_model_chain (subject_cert, listmode, listfp)) rootca_flags->chain_model = 1; } /* Check the validity period. */ if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) ) rc = check_validity_period_cm (current_time, check_time, subject_cert, exptime, listmode, listfp, (depth && is_root)? -1: depth); else rc = check_validity_period (current_time, subject_cert, exptime, listmode, listfp, (depth && is_root)? -1: depth); if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED) any_expired = 1; else if (rc) goto leave; /* Assert that we understand all critical extensions. */ rc = unknown_criticals (subject_cert, listmode, listfp); if (rc) goto leave; /* Do a policy check. */ if (!opt.no_policy_check) { rc = check_cert_policy (subject_cert, listmode, listfp); if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH) { any_no_policy_match = 1; rc = 1; /* Be on the safe side and set RC. */ } else if (rc) goto leave; } /* If this is the root certificate we are at the end of the chain. */ if (is_root) { if (!istrusted_rc) ; /* No need to check the certificate for a trusted one. */ else if (gpgsm_check_cert_sig (subject_cert, subject_cert) ) { /* We only check the signature if the certificate is not trusted for better diagnostics. */ do_list (1, listmode, listfp, _("self-signed certificate has a BAD signature")); if (DBG_X509) { gpgsm_dump_cert ("self-signing cert", subject_cert); } rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN : GPG_ERR_BAD_CERT); goto leave; } if (!rootca_flags->relax) { rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp); if (rc) goto leave; } /* Set the flag for qualified signatures. This flag is deduced from a list of root certificates allowed for qualified signatures. */ if (is_qualified == -1 && !(flags & VALIDATE_FLAG_STEED)) { gpg_error_t err; size_t buflen; char buf[1]; if (!ksba_cert_get_user_data (cert, "is_qualified", &buf, sizeof (buf), &buflen) && buflen) { /* We already checked this for this certificate, thus we simply take it from the user data. */ is_qualified = !!*buf; } else { /* Need to consult the list of root certificates for qualified signatures. */ err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL); if (!err) is_qualified = 1; else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND) is_qualified = 0; else log_error ("checking the list of qualified " "root certificates failed: %s\n", gpg_strerror (err)); if ( is_qualified != -1 ) { /* Cache the result but don't care too much about an error. */ buf[0] = !!is_qualified; err = ksba_cert_set_user_data (subject_cert, "is_qualified", buf, 1); if (err) log_error ("set_user_data(is_qualified) failed: %s\n", gpg_strerror (err)); } } } /* Act on the check for a trusted root certificates. */ rc = istrusted_rc; if (!rc) ; else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED) { do_list (0, listmode, listfp, _("root certificate is not marked trusted")); /* If we already figured out that the certificate is expired it does not make much sense to ask the user whether they want to trust the root certificate. We should do this only if the certificate under question will then be usable. If the certificate has a well known private key asking the user does not make any sense. */ if ( !any_expired && !gpgsm_cert_has_well_known_private_key (subject_cert) && (!listmode || !already_asked_marktrusted (subject_cert)) && ask_marktrusted (ctrl, subject_cert, listmode) ) rc = 0; } else { log_error (_("checking the trust list failed: %s\n"), gpg_strerror (rc)); } if (rc) goto leave; /* Check for revocations etc. */ if ((flags & VALIDATE_FLAG_NO_DIRMNGR)) ; else if ((flags & VALIDATE_FLAG_STEED)) ; /* Fixme: check revocations via DNS. */ else if (opt.no_trusted_cert_crl_check || rootca_flags->relax) ; else rc = is_cert_still_valid (ctrl, (flags & VALIDATE_FLAG_CHAIN_MODEL), listmode, listfp, subject_cert, subject_cert, &any_revoked, &any_no_crl, &any_crl_too_old); if (rc) goto leave; break; /* Okay: a self-signed certicate is an end-point. */ } /* End is_root. */ /* Take care that the chain does not get too long. */ if ((depth+1) > maxdepth) { do_list (1, listmode, listfp, _("certificate chain too long\n")); rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN); goto leave; } /* Find the next cert up the tree. */ keydb_search_reset (kh); rc = find_up (ctrl, kh, subject_cert, issuer, 0); if (rc) { if (rc == -1) { do_list (0, listmode, listfp, _("issuer certificate not found")); if (!listmode) { log_info ("issuer certificate: #/"); gpgsm_dump_string (issuer); log_printf ("\n"); } } else log_error ("failed to find issuer's certificate: rc=%d\n", rc); rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT); goto leave; } ksba_cert_release (issuer_cert); issuer_cert = NULL; rc = keydb_get_cert (kh, &issuer_cert); if (rc) { log_error ("keydb_get_cert() failed: rc=%d\n", rc); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } try_another_cert: if (DBG_X509) { log_debug ("got issuer's certificate:\n"); gpgsm_dump_cert ("issuer", issuer_cert); } rc = gpgsm_check_cert_sig (issuer_cert, subject_cert); if (rc) { do_list (0, listmode, listfp, _("certificate has a BAD signature")); if (DBG_X509) { gpgsm_dump_cert ("signing issuer", issuer_cert); gpgsm_dump_cert ("signed subject", subject_cert); } if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE) { /* We now try to find other issuer certificates which might have been used. This is required because some CAs are reusing the issuer and subject DN for new root certificates. */ /* FIXME: Do this only if we don't have an AKI.keyIdentifier */ rc = find_up (ctrl, kh, subject_cert, issuer, 1); if (!rc) { ksba_cert_t tmp_cert; rc = keydb_get_cert (kh, &tmp_cert); if (rc || !compare_certs (issuer_cert, tmp_cert)) { /* The find next did not work or returned an identical certificate. We better stop here to avoid infinite checks. */ /* No need to set RC because it is not used: rc = gpg_error (GPG_ERR_BAD_SIGNATURE); */ ksba_cert_release (tmp_cert); } else { do_list (0, listmode, listfp, _("found another possible matching " "CA certificate - trying again")); ksba_cert_release (issuer_cert); issuer_cert = tmp_cert; goto try_another_cert; } } } /* We give a more descriptive error code than the one returned from the signature checking. */ rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN); goto leave; } is_root = gpgsm_is_root_cert (issuer_cert); istrusted_rc = -1; /* Check that a CA is allowed to issue certificates. */ { int chainlen; rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp); if (rc) { /* Not allowed. Check whether this is a trusted root certificate and whether we allow special exceptions. We could carry the result of the test over to the regular root check at the top of the loop but for clarity we won't do that. Given that the majority of certificates carry proper BasicContraints our way of overriding an error in the way is justified for performance reasons. */ if (is_root) { if (gpgsm_cert_has_well_known_private_key (issuer_cert)) { memset (rootca_flags, 0, sizeof *rootca_flags); istrusted_rc = ((flags & VALIDATE_FLAG_STEED) ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED)); } else istrusted_rc = gpgsm_agent_istrusted (ctrl, issuer_cert, NULL, rootca_flags); if (!istrusted_rc && rootca_flags->relax) { /* Ignore the error due to the relax flag. */ rc = 0; chainlen = -1; } } } if (rc) goto leave; if (chainlen >= 0 && depth > chainlen) { do_list (1, listmode, listfp, _("certificate chain longer than allowed by CA (%d)"), chainlen); rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN); goto leave; } } /* Is the certificate allowed to sign other certificates. */ if (!listmode) { rc = gpgsm_cert_use_cert_p (issuer_cert); if (rc) { char numbuf[50]; sprintf (numbuf, "%d", rc); gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage", numbuf, NULL); goto leave; } } /* Check for revocations etc. Note that for a root certificate this test is done a second time later. This should eventually be fixed. */ if ((flags & VALIDATE_FLAG_NO_DIRMNGR)) rc = 0; else if ((flags & VALIDATE_FLAG_STEED)) rc = 0; /* Fixme: XXX */ else if (is_root && (opt.no_trusted_cert_crl_check || (!istrusted_rc && rootca_flags->relax))) rc = 0; else rc = is_cert_still_valid (ctrl, (flags & VALIDATE_FLAG_CHAIN_MODEL), listmode, listfp, subject_cert, issuer_cert, &any_revoked, &any_no_crl, &any_crl_too_old); if (rc) goto leave; if (opt.verbose && !listmode) log_info (depth == 0 ? _("certificate is good\n") : !is_root ? _("intermediate certificate is good\n") : /* other */ _("root certificate is good\n")); /* Under the chain model the next check time is the creation time of the subject certificate. */ if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) ) { rc = ksba_cert_get_validity (subject_cert, 0, check_time); if (rc) { /* That will never happen as we have already checked this above. */ BUG (); } } /* For the next round the current issuer becomes the new subject. */ keydb_search_reset (kh); ksba_cert_release (subject_cert); subject_cert = issuer_cert; issuer_cert = NULL; depth++; } /* End chain traversal. */ if (!listmode && !opt.quiet) { if (opt.no_policy_check) log_info ("policies not checked due to %s option\n", "--disable-policy-checks"); if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp)) log_info ("CRLs not checked due to %s option\n", ctrl->offline ? "offline" : "--disable-crl-checks"); } if (!rc) { /* If we encountered an error somewhere during the checks, set the error code to the most critical one */ if (any_revoked) rc = gpg_error (GPG_ERR_CERT_REVOKED); else if (any_expired) rc = gpg_error (GPG_ERR_CERT_EXPIRED); else if (any_no_crl) rc = gpg_error (GPG_ERR_NO_CRL_KNOWN); else if (any_crl_too_old) rc = gpg_error (GPG_ERR_CRL_TOO_OLD); else if (any_no_policy_match) rc = gpg_error (GPG_ERR_NO_POLICY_MATCH); } leave: /* If we have traversed a complete chain up to the root we will reset the ephemeral flag for all these certificates. This is done regardless of any error because those errors may only be transient. */ if (chain && chain->is_root) { gpg_error_t err; chain_item_t ci; for (ci = chain; ci; ci = ci->next) { /* Note that it is possible for the last certificate in the chain (i.e. our target certificate) that it has not yet been stored in the keybox and thus the flag can't be set. We ignore this error because it will later be stored anyway. */ err = keydb_set_cert_flags (ctrl, ci->cert, 1, KEYBOX_FLAG_BLOB, 0, KEYBOX_FLAG_BLOB_EPHEMERAL, 0); if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND) ; else if (err) log_error ("clearing ephemeral flag failed: %s\n", gpg_strerror (err)); } } /* If we have figured something about the qualified signature capability of the certificate under question, store the result as user data in all certificates of the chain. We do this even if the validation itself failed. */ if (is_qualified != -1 && !(flags & VALIDATE_FLAG_STEED)) { gpg_error_t err; chain_item_t ci; char buf[1]; buf[0] = !!is_qualified; for (ci = chain; ci; ci = ci->next) { err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1); if (err) { log_error ("set_user_data(is_qualified) failed: %s\n", gpg_strerror (err)); if (!rc) rc = err; } } } /* If auditing has been enabled, record what is in the chain. */ if (ctrl->audit) { chain_item_t ci; audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN); for (ci = chain; ci; ci = ci->next) { audit_log_cert (ctrl->audit, ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT, ci->cert, 0); } audit_log (ctrl->audit, AUDIT_CHAIN_END); } if (r_exptime) gnupg_copy_time (r_exptime, exptime); xfree (issuer); xfree (subject); keydb_release (kh); while (chain) { chain_item_t ci_next = chain->next; ksba_cert_release (chain->cert); xfree (chain); chain = ci_next; } ksba_cert_release (issuer_cert); ksba_cert_release (subject_cert); return rc; } /* Validate a certificate chain. For a description see do_validate_chain. This function is a wrapper to handle a root certificate with the chain_model flag set. If RETFLAGS is not NULL, flags indicating now the verification was done are stored there. The only defined vits for RETFLAGS are VALIDATE_FLAG_CHAIN_MODEL and VALIDATE_FLAG_STEED. If you are verifying a signature you should set CHECKTIME to the creation time of the signature. If your are verifying a certificate, set it nil (i.e. the empty string). If the creation date of the signature is not known use the special date "19700101T000000" which is treated in a special way here. */ int gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime, ksba_isotime_t r_exptime, int listmode, estream_t listfp, unsigned int flags, unsigned int *retflags) { int rc; struct rootca_flags_s rootca_flags; unsigned int dummy_retflags; if (!retflags) retflags = &dummy_retflags; /* If the session requested a certain validation mode make sure the corresponding flags are set. */ if (ctrl->validation_model == 1) flags |= VALIDATE_FLAG_CHAIN_MODEL; else if (ctrl->validation_model == 2) flags |= VALIDATE_FLAG_STEED; /* If the chain model was forced, set this immediately into RETFLAGS. */ *retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL); memset (&rootca_flags, 0, sizeof rootca_flags); rc = do_validate_chain (ctrl, cert, checktime, r_exptime, listmode, listfp, flags, &rootca_flags); if (!rc && (flags & VALIDATE_FLAG_STEED)) { *retflags |= VALIDATE_FLAG_STEED; } else if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED && !(flags & VALIDATE_FLAG_CHAIN_MODEL) && (rootca_flags.valid && rootca_flags.chain_model)) { do_list (0, listmode, listfp, _("switching to chain model")); rc = do_validate_chain (ctrl, cert, checktime, r_exptime, listmode, listfp, (flags |= VALIDATE_FLAG_CHAIN_MODEL), &rootca_flags); *retflags |= VALIDATE_FLAG_CHAIN_MODEL; } if (opt.verbose) do_list (0, listmode, listfp, _("validation model used: %s"), (*retflags & VALIDATE_FLAG_STEED)? "steed" : (*retflags & VALIDATE_FLAG_CHAIN_MODEL)? _("chain"):_("shell")); return rc; } /* Check that the given certificate is valid but DO NOT check any constraints. We assume that the issuers certificate is already in the DB and that this one is valid; which it should be because it has been checked using this function. */ int gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert) { int rc = 0; char *issuer = NULL; char *subject = NULL; KEYDB_HANDLE kh; ksba_cert_t issuer_cert = NULL; if (opt.no_chain_validation) { log_info ("WARNING: bypassing basic certificate checks\n"); return 0; } kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } issuer = ksba_cert_get_issuer (cert, 0); subject = ksba_cert_get_subject (cert, 0); if (!issuer) { log_error ("no issuer found in certificate\n"); rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } if (is_root_cert (cert, issuer, subject)) { rc = gpgsm_check_cert_sig (cert, cert); if (rc) { log_error ("self-signed certificate has a BAD signature: %s\n", gpg_strerror (rc)); if (DBG_X509) { gpgsm_dump_cert ("self-signing cert", cert); } rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } } else { /* Find the next cert up the tree. */ keydb_search_reset (kh); rc = find_up (ctrl, kh, cert, issuer, 0); if (rc) { if (rc == -1) { log_info ("issuer certificate (#/"); gpgsm_dump_string (issuer); log_printf (") not found\n"); } else log_error ("failed to find issuer's certificate: rc=%d\n", rc); rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT); goto leave; } ksba_cert_release (issuer_cert); issuer_cert = NULL; rc = keydb_get_cert (kh, &issuer_cert); if (rc) { log_error ("keydb_get_cert() failed: rc=%d\n", rc); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } rc = gpgsm_check_cert_sig (issuer_cert, cert); if (rc) { log_error ("certificate has a BAD signature: %s\n", gpg_strerror (rc)); if (DBG_X509) { gpgsm_dump_cert ("signing issuer", issuer_cert); gpgsm_dump_cert ("signed subject", cert); } rc = gpg_error (GPG_ERR_BAD_CERT); goto leave; } if (opt.verbose) log_info (_("certificate is good\n")); } leave: xfree (issuer); xfree (subject); keydb_release (kh); ksba_cert_release (issuer_cert); return rc; } /* Check whether the certificate CERT has been issued by the German authority for qualified signature. They do not set the basicConstraints and thus we need this workaround. It works by looking up the root certificate and checking whether that one is listed as a qualified certificate for Germany. We also try to cache this data but as long as don't keep a reference to the certificate this won't be used. Returns: True if CERT is a RegTP issued CA cert (i.e. the root certificate itself or one of the CAs). In that case CHAINLEN will receive the length of the chain which is either 0 or 1. */ static int get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen) { gpg_error_t err; ksba_cert_t next; int rc = 0; int i, depth; char country[3]; ksba_cert_t array[4]; char buf[2]; size_t buflen; int dummy_chainlen; if (!chainlen) chainlen = &dummy_chainlen; *chainlen = 0; err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen", &buf, sizeof (buf), &buflen); if (!err) { /* Got info. */ if (buflen < 2 || !*buf) return 0; /* Nothing found. */ *chainlen = buf[1]; return 1; /* This is a regtp CA. */ } else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND) { log_error ("ksba_cert_get_user_data(%s) failed: %s\n", "regtp_ca_chainlen", gpg_strerror (err)); return 0; /* Nothing found. */ } /* Need to gather the info. This requires to walk up the chain until we have found the root. Because we are only interested in German Bundesnetzagentur (former RegTP) derived certificates 3 levels are enough. (The German signature law demands a 3 tier hierarchy; thus there is only one CA between the EE and the Root CA.) */ memset (&array, 0, sizeof array); depth = 0; ksba_cert_ref (cert); array[depth++] = cert; ksba_cert_ref (cert); while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next))) { ksba_cert_release (cert); ksba_cert_ref (next); array[depth++] = next; cert = next; } ksba_cert_release (cert); if (rc != -1 || !depth || depth == DIM(array) ) { /* We did not reached the root. */ goto leave; } /* If this is a German signature law issued certificate, we store additional information. */ if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country) && !strcmp (country, "de")) { /* Setting the pathlen for the root CA and the CA flag for the next one is all what we need to do. */ err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen", "\x01\x01", 2); if (!err && depth > 1) err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen", "\x01\x00", 2); if (err) log_error ("ksba_set_user_data(%s) failed: %s\n", "regtp_ca_chainlen", gpg_strerror (err)); for (i=0; i < depth; i++) ksba_cert_release (array[i]); *chainlen = (depth>1? 0:1); return 1; } leave: /* Nothing special with this certificate. Mark the target certificate anyway to avoid duplicate lookups. */ err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1); if (err) log_error ("ksba_set_user_data(%s) failed: %s\n", "regtp_ca_chainlen", gpg_strerror (err)); for (i=0; i < depth; i++) ksba_cert_release (array[i]); return 0; } diff --git a/sm/keydb.c b/sm/keydb.c index 45e932aa3..4d3f40990 100644 --- a/sm/keydb.c +++ b/sm/keydb.c @@ -1,1362 +1,1364 @@ /* keydb.c - key database dispatcher * Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc. * Copyright (C) 2014 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 #include #include #include #include #include #include #include "gpgsm.h" #include "../kbx/keybox.h" #include "keydb.h" #include "../common/i18n.h" static int active_handles; typedef enum { KEYDB_RESOURCE_TYPE_NONE = 0, KEYDB_RESOURCE_TYPE_KEYBOX } KeydbResourceType; #define MAX_KEYDB_RESOURCES 20 struct resource_item { KeydbResourceType type; union { KEYBOX_HANDLE kr; } u; void *token; dotlock_t lockhandle; }; static struct resource_item all_resources[MAX_KEYDB_RESOURCES]; static int used_resources; /* Whether we have successfully registered any resource. */ static int any_registered; struct keydb_handle { int locked; int found; int saved_found; int current; int is_ephemeral; int used; /* items in active */ struct resource_item active[MAX_KEYDB_RESOURCES]; }; static int lock_all (KEYDB_HANDLE hd); static void unlock_all (KEYDB_HANDLE hd); static void try_make_homedir (const char *fname) { const char *defhome = standard_homedir (); /* Create the directory only if the supplied directory name is the same as the default one. This way we avoid to create arbitrary directories when a non-default home directory is used. To cope with HOME, we do compare only the suffix if we see that the default homedir does start with a tilde. */ if ( opt.dry_run || opt.no_homedir_creation ) return; if ( #ifdef HAVE_W32_SYSTEM ( !compare_filenames (fname, defhome) ) #else ( *defhome == '~' && (strlen(fname) >= strlen (defhome+1) && !strcmp(fname+strlen(fname)-strlen(defhome+1), defhome+1 ) )) || (*defhome != '~' && !compare_filenames( fname, defhome ) ) #endif ) { if (gnupg_mkdir (fname, "-rwx")) log_info (_("can't create directory '%s': %s\n"), fname, strerror(errno) ); else if (!opt.quiet ) log_info (_("directory '%s' created\n"), fname); } } /* Handle the creation of a keybox if it does not yet exist. Take into acount that other processes might have the keybox already locked. This lock check does not work if the directory itself is not yet available. If R_CREATED is not NULL it will be set to true if the function created a new keybox. */ static gpg_error_t maybe_create_keybox (char *filename, int force, int *r_created) { gpg_err_code_t ec; dotlock_t lockhd = NULL; - FILE *fp; + estream_t fp; int rc; mode_t oldmask; char *last_slash_in_filename; int save_slash; if (r_created) *r_created = 0; /* A quick test whether the filename already exists. */ if (!gnupg_access (filename, F_OK)) return !gnupg_access (filename, R_OK)? 0 : gpg_error (GPG_ERR_EACCES); /* If we don't want to create a new file at all, there is no need to go any further - bail out right here. */ if (!force) return gpg_error (GPG_ERR_ENOENT); /* First of all we try to create the home directory. Note, that we don't do any locking here because any sane application of gpg would create the home directory by itself and not rely on gpg's tricky auto-creation which is anyway only done for some home directory name patterns. */ last_slash_in_filename = strrchr (filename, DIRSEP_C); #if HAVE_W32_SYSTEM { /* Windows may either have a slash or a backslash. Take care of it. */ char *p = strrchr (filename, '/'); if (!last_slash_in_filename || p > last_slash_in_filename) last_slash_in_filename = p; } #endif /*HAVE_W32_SYSTEM*/ if (!last_slash_in_filename) return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should not happen though. */ save_slash = *last_slash_in_filename; *last_slash_in_filename = 0; if (access(filename, F_OK)) { static int tried; if (!tried) { tried = 1; try_make_homedir (filename); } if ((ec = gnupg_access (filename, F_OK))) { rc = gpg_error (ec); *last_slash_in_filename = save_slash; goto leave; } } *last_slash_in_filename = save_slash; /* To avoid races with other instances of gpg trying to create or update the keybox (it is removed during an update for a short time), we do the next stuff in a locked state. */ lockhd = dotlock_create (filename, 0); if (!lockhd) { /* A reason for this to fail is that the directory is not writable. However, this whole locking stuff does not make sense if this is the case. An empty non-writable directory with no keyring is not really useful at all. */ if (opt.verbose) log_info ("can't allocate lock for '%s'\n", filename ); if (!force) return gpg_error (GPG_ERR_ENOENT); else return gpg_error (GPG_ERR_GENERAL); } if ( dotlock_take (lockhd, -1) ) { /* This is something bad. Probably a stale lockfile. */ log_info ("can't lock '%s'\n", filename); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } /* Now the real test while we are locked. */ if (!access(filename, F_OK)) { rc = 0; /* Okay, we may access the file now. */ goto leave; } /* The file does not yet exist, create it now. */ oldmask = umask (077); - fp = fopen (filename, "wb"); + fp = es_fopen (filename, "wb"); if (!fp) { rc = gpg_error_from_syserror (); umask (oldmask); log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (rc)); goto leave; } umask (oldmask); /* Make sure that at least one record is in a new keybox file, so that the detection magic for OpenPGP keyboxes works the next time it is used. */ rc = _keybox_write_header_blob (fp, 0); if (rc) { - fclose (fp); + es_fclose (fp); log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (rc)); goto leave; } if (!opt.quiet) log_info (_("keybox '%s' created\n"), filename); if (r_created) *r_created = 1; - fclose (fp); + es_fclose (fp); rc = 0; leave: if (lockhd) { dotlock_release (lockhd); dotlock_destroy (lockhd); } return rc; } /* * Register a resource (which currently may only be a keybox file). * The first keybox which is added by this function is created if it * does not exist. If AUTO_CREATED is not NULL it will be set to true * if the function has created a new keybox. */ gpg_error_t keydb_add_resource (ctrl_t ctrl, const char *url, int force, int *auto_created) { const char *resname = url; char *filename = NULL; gpg_error_t err = 0; KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE; if (auto_created) *auto_created = 0; /* Do we have an URL? gnupg-kbx:filename := this is a plain keybox filename := See what it is, but create as plain keybox. */ if (strlen (resname) > 10) { if (!strncmp (resname, "gnupg-kbx:", 10) ) { rt = KEYDB_RESOURCE_TYPE_KEYBOX; resname += 10; } #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__) else if (strchr (resname, ':')) { log_error ("invalid key resource URL '%s'\n", url ); err = gpg_error (GPG_ERR_GENERAL); goto leave; } #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */ } if (*resname != DIRSEP_C ) { /* do tilde expansion etc */ if (strchr(resname, DIRSEP_C) ) filename = make_filename (resname, NULL); else filename = make_filename (gnupg_homedir (), resname, NULL); } else filename = xstrdup (resname); if (!force) force = !any_registered; /* see whether we can determine the filetype */ if (rt == KEYDB_RESOURCE_TYPE_NONE) { - FILE *fp = fopen( filename, "rb" ); + estream_t fp; + fp = es_fopen( filename, "rb" ); if (fp) { u32 magic; /* FIXME: check for the keybox magic */ - if (fread (&magic, 4, 1, fp) == 1 ) + if (es_fread (&magic, 4, 1, fp) == 1 ) { if (magic == 0x13579ace || magic == 0xce9a5713) ; /* GDBM magic - no more support */ else rt = KEYDB_RESOURCE_TYPE_KEYBOX; } else /* maybe empty: assume keybox */ rt = KEYDB_RESOURCE_TYPE_KEYBOX; - fclose (fp); + + es_fclose (fp); } else /* no file yet: create keybox */ rt = KEYDB_RESOURCE_TYPE_KEYBOX; } switch (rt) { case KEYDB_RESOURCE_TYPE_NONE: log_error ("unknown type of key resource '%s'\n", url ); err = gpg_error (GPG_ERR_GENERAL); goto leave; case KEYDB_RESOURCE_TYPE_KEYBOX: err = maybe_create_keybox (filename, force, auto_created); if (err) goto leave; /* Now register the file */ { void *token; err = keybox_register_file (filename, 0, &token); if (gpg_err_code (err) == GPG_ERR_EEXIST) ; /* Already registered - ignore. */ else if (err) ; /* Other error. */ else if (used_resources >= MAX_KEYDB_RESOURCES) err = gpg_error (GPG_ERR_RESOURCE_LIMIT); else { all_resources[used_resources].type = rt; all_resources[used_resources].u.kr = NULL; /* Not used here */ all_resources[used_resources].token = token; all_resources[used_resources].lockhandle = dotlock_create (filename, 0); if (!all_resources[used_resources].lockhandle) log_fatal ( _("can't create lock for '%s'\n"), filename); /* Do a compress run if needed and the file is not locked. */ if (!dotlock_take (all_resources[used_resources].lockhandle, 0)) { KEYBOX_HANDLE kbxhd = keybox_new_x509 (token, 0); if (kbxhd) { keybox_compress (kbxhd); keybox_release (kbxhd); } dotlock_release (all_resources[used_resources].lockhandle); } used_resources++; } } break; default: log_error ("resource type of '%s' not supported\n", url); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto leave; } /* fixme: check directory permissions and print a warning */ leave: if (err) { log_error ("keyblock resource '%s': %s\n", filename, gpg_strerror (err)); gpgsm_status_with_error (ctrl, STATUS_ERROR, "add_keyblock_resource", err); } else any_registered = 1; xfree (filename); return err; } KEYDB_HANDLE keydb_new (void) { KEYDB_HANDLE hd; int i, j; hd = xcalloc (1, sizeof *hd); hd->found = -1; hd->saved_found = -1; assert (used_resources <= MAX_KEYDB_RESOURCES); for (i=j=0; i < used_resources; i++) { switch (all_resources[i].type) { case KEYDB_RESOURCE_TYPE_NONE: /* ignore */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: hd->active[j].type = all_resources[i].type; hd->active[j].token = all_resources[i].token; hd->active[j].lockhandle = all_resources[i].lockhandle; hd->active[j].u.kr = keybox_new_x509 (all_resources[i].token, 0); if (!hd->active[j].u.kr) { xfree (hd); return NULL; /* fixme: release all previously allocated handles*/ } j++; break; } } hd->used = j; active_handles++; return hd; } void keydb_release (KEYDB_HANDLE hd) { int i; if (!hd) return; assert (active_handles > 0); active_handles--; unlock_all (hd); for (i=0; i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_release (hd->active[i].u.kr); break; } } xfree (hd); } /* Return the name of the current resource. This is function first looks for the last found found, then for the current search position, and last returns the first available resource. The returned string is only valid as long as the handle exists. This function does only return NULL if no handle is specified, in all other error cases an empty string is returned. */ const char * keydb_get_resource_name (KEYDB_HANDLE hd) { int idx; const char *s = NULL; if (!hd) return NULL; if ( hd->found >= 0 && hd->found < hd->used) idx = hd->found; else if ( hd->current >= 0 && hd->current < hd->used) idx = hd->current; else idx = 0; switch (hd->active[idx].type) { case KEYDB_RESOURCE_TYPE_NONE: s = NULL; break; case KEYDB_RESOURCE_TYPE_KEYBOX: s = keybox_get_resource_name (hd->active[idx].u.kr); break; } return s? s: ""; } /* Switch the handle into ephemeral mode and return the original value. */ int keydb_set_ephemeral (KEYDB_HANDLE hd, int yes) { int i; if (!hd) return 0; yes = !!yes; if (hd->is_ephemeral != yes) { for (i=0; i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_set_ephemeral (hd->active[i].u.kr, yes); break; } } } i = hd->is_ephemeral; hd->is_ephemeral = yes; return i; } /* If the keyring has not yet been locked, lock it now. This operation is required before any update operation; it is optional for an insert operation. The lock is released with keydb_released. */ gpg_error_t keydb_lock (KEYDB_HANDLE hd) { if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); if (hd->locked) return 0; /* Already locked. */ return lock_all (hd); } static int lock_all (KEYDB_HANDLE hd) { int i, rc = 0; /* Fixme: This locking scheme may lead to deadlock if the resources are not added in the same order by all processes. We are currently only allowing one resource so it is not a problem. */ for (i=0; i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: if (hd->active[i].lockhandle) rc = dotlock_take (hd->active[i].lockhandle, -1); break; } if (rc) break; } if (rc) { /* revert the already set locks */ for (i--; i >= 0; i--) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: if (hd->active[i].lockhandle) dotlock_release (hd->active[i].lockhandle); break; } } } else hd->locked = 1; /* make_dotlock () does not yet guarantee that errno is set, thus we can't rely on the error reason and will simply use EACCES. */ return rc? gpg_error (GPG_ERR_EACCES) : 0; } static void unlock_all (KEYDB_HANDLE hd) { int i; if (!hd->locked) return; for (i=hd->used-1; i >= 0; i--) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: if (hd->active[i].lockhandle) dotlock_release (hd->active[i].lockhandle); break; } } hd->locked = 0; } /* Push the last found state if any. */ void keydb_push_found_state (KEYDB_HANDLE hd) { if (!hd) return; if (hd->found < 0 || hd->found >= hd->used) { hd->saved_found = -1; return; } switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_push_found_state (hd->active[hd->found].u.kr); break; } hd->saved_found = hd->found; hd->found = -1; } /* Pop the last found state. */ void keydb_pop_found_state (KEYDB_HANDLE hd) { if (!hd) return; hd->found = hd->saved_found; hd->saved_found = -1; if (hd->found < 0 || hd->found >= hd->used) return; switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: keybox_pop_found_state (hd->active[hd->found].u.kr); break; } } /* Return the last found object. Caller must free it. The returned keyblock has the kbode flag bit 0 set for the node with the public key used to locate the keyblock or flag bit 1 set for the user ID node. */ int keydb_get_cert (KEYDB_HANDLE hd, ksba_cert_t *r_cert) { int rc = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return -1; /* nothing found */ switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: rc = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_get_cert (hd->active[hd->found].u.kr, r_cert); break; } return rc; } /* Return a flag of the last found object. WHICH is the flag requested; it should be one of the KEYBOX_FLAG_ values. If the operation is successful, the flag value will be stored at the address given by VALUE. Return 0 on success or an error code. */ gpg_error_t keydb_get_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int *value) { int err = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return gpg_error (GPG_ERR_NOTHING_FOUND); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: err = keybox_get_flags (hd->active[hd->found].u.kr, which, idx, value); break; } return err; } /* Set a flag of the last found object. WHICH is the flag to be set; it should be one of the KEYBOX_FLAG_ values. If the operation is successful, the flag value will be stored in the keybox. Note, that some flag values can't be updated and thus may return an error, some other flag values may be masked out before an update. Returns 0 on success or an error code. */ gpg_error_t keydb_set_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int value) { int err = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return gpg_error (GPG_ERR_NOTHING_FOUND); if (!hd->locked) return gpg_error (GPG_ERR_NOT_LOCKED); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: err = keybox_set_flags (hd->active[hd->found].u.kr, which, idx, value); break; } return err; } /* * Insert a new Certificate into one of the resources. */ int keydb_insert_cert (KEYDB_HANDLE hd, ksba_cert_t cert) { int rc = -1; int idx; unsigned char digest[20]; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (opt.dry_run) return 0; if ( hd->found >= 0 && hd->found < hd->used) idx = hd->found; else if ( hd->current >= 0 && hd->current < hd->used) idx = hd->current; else return gpg_error (GPG_ERR_GENERAL); if (!hd->locked) return gpg_error (GPG_ERR_NOT_LOCKED); gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/ switch (hd->active[idx].type) { case KEYDB_RESOURCE_TYPE_NONE: rc = gpg_error (GPG_ERR_GENERAL); break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_insert_cert (hd->active[idx].u.kr, cert, digest); break; } unlock_all (hd); return rc; } /* Update the current keyblock with KB. */ int keydb_update_cert (KEYDB_HANDLE hd, ksba_cert_t cert) { int rc = 0; unsigned char digest[20]; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return -1; /* nothing found */ if (opt.dry_run) return 0; rc = lock_all (hd); if (rc) return rc; gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/ switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: rc = gpg_error (GPG_ERR_GENERAL); /* oops */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_update_cert (hd->active[hd->found].u.kr, cert, digest); break; } unlock_all (hd); return rc; } /* * The current keyblock or cert will be deleted. */ int keydb_delete (KEYDB_HANDLE hd, int unlock) { int rc = -1; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return -1; /* nothing found */ if( opt.dry_run ) return 0; if (!hd->locked) return gpg_error (GPG_ERR_NOT_LOCKED); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: rc = gpg_error (GPG_ERR_GENERAL); break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_delete (hd->active[hd->found].u.kr); break; } if (unlock) unlock_all (hd); return rc; } /* * Locate the default writable key resource, so that the next * operation (which is only relevant for inserts) will be done on this * resource. */ int keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved) { int rc; (void)reserved; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); rc = keydb_search_reset (hd); /* this does reset hd->current */ if (rc) return rc; for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++) { switch (hd->active[hd->current].type) { case KEYDB_RESOURCE_TYPE_NONE: BUG(); break; case KEYDB_RESOURCE_TYPE_KEYBOX: if (keybox_is_writable (hd->active[hd->current].token)) return 0; /* found (hd->current is set to it) */ break; } } return -1; } /* * Rebuild the caches of all key resources. */ void keydb_rebuild_caches (void) { int i; for (i=0; i < used_resources; i++) { switch (all_resources[i].type) { case KEYDB_RESOURCE_TYPE_NONE: /* ignore */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: /* rc = keybox_rebuild_cache (all_resources[i].token); */ /* if (rc) */ /* log_error (_("failed to rebuild keybox cache: %s\n"), */ /* g10_errstr (rc)); */ break; } } } /* * Start the next search on this handle right at the beginning */ gpg_error_t keydb_search_reset (KEYDB_HANDLE hd) { int i; gpg_error_t rc = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); hd->current = 0; hd->found = -1; /* and reset all resources */ for (i=0; !rc && i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_search_reset (hd->active[i].u.kr); break; } } return rc; } /* * Search through all keydb resources, starting at the current position, * for a keyblock which contains one of the keys described in the DESC array. */ int keydb_search (ctrl_t ctrl, KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc) { int rc = -1; unsigned long skipped; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!any_registered) { gpgsm_status_with_error (ctrl, STATUS_ERROR, "keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN)); return gpg_error (GPG_ERR_NOT_FOUND); } while (rc == -1 && hd->current >= 0 && hd->current < hd->used) { switch (hd->active[hd->current].type) { case KEYDB_RESOURCE_TYPE_NONE: BUG(); /* we should never see it here */ break; case KEYDB_RESOURCE_TYPE_KEYBOX: rc = keybox_search (hd->active[hd->current].u.kr, desc, ndesc, KEYBOX_BLOBTYPE_X509, NULL, &skipped); break; } if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF) { /* EOF -> switch to next resource */ hd->current++; } else if (!rc) hd->found = hd->current; } return rc; } int keydb_search_first (ctrl_t ctrl, KEYDB_HANDLE hd) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FIRST; return keydb_search (ctrl, hd, &desc, 1); } int keydb_search_next (ctrl_t ctrl, KEYDB_HANDLE hd) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_NEXT; return keydb_search (ctrl, hd, &desc, 1); } int keydb_search_kid (ctrl_t ctrl, KEYDB_HANDLE hd, u32 *kid) { KEYDB_SEARCH_DESC desc; (void)kid; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0] = kid[0]; desc.u.kid[1] = kid[1]; return keydb_search (ctrl, hd, &desc, 1); } int keydb_search_fpr (ctrl_t ctrl, KEYDB_HANDLE hd, const byte *fpr) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FPR; memcpy (desc.u.fpr, fpr, 20); return keydb_search (ctrl, hd, &desc, 1); } int keydb_search_issuer (ctrl_t ctrl, KEYDB_HANDLE hd, const char *issuer) { KEYDB_SEARCH_DESC desc; int rc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_ISSUER; desc.u.name = issuer; rc = keydb_search (ctrl, hd, &desc, 1); return rc; } int keydb_search_issuer_sn (ctrl_t ctrl, KEYDB_HANDLE hd, const char *issuer, ksba_const_sexp_t serial) { KEYDB_SEARCH_DESC desc; int rc; const unsigned char *s; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_ISSUER_SN; s = serial; if (*s !='(') return gpg_error (GPG_ERR_INV_VALUE); s++; for (desc.snlen = 0; digitp (s); s++) desc.snlen = 10*desc.snlen + atoi_1 (s); if (*s !=':') return gpg_error (GPG_ERR_INV_VALUE); desc.sn = s+1; desc.u.name = issuer; rc = keydb_search (ctrl, hd, &desc, 1); return rc; } int keydb_search_subject (ctrl_t ctrl, KEYDB_HANDLE hd, const char *name) { KEYDB_SEARCH_DESC desc; int rc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_SUBJECT; desc.u.name = name; rc = keydb_search (ctrl, hd, &desc, 1); return rc; } /* Store the certificate in the key DB but make sure that it does not already exists. We do this simply by comparing the fingerprint. If EXISTED is not NULL it will be set to true if the certificate was already in the DB. */ int keydb_store_cert (ctrl_t ctrl, ksba_cert_t cert, int ephemeral, int *existed) { KEYDB_HANDLE kh; int rc; unsigned char fpr[20]; if (existed) *existed = 0; if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL)) { log_error (_("failed to get the fingerprint\n")); return gpg_error (GPG_ERR_GENERAL); } kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); return gpg_error (GPG_ERR_ENOMEM);; } /* Set the ephemeral flag so that the search looks at all records. */ keydb_set_ephemeral (kh, 1); rc = lock_all (kh); if (rc) return rc; rc = keydb_search_fpr (ctrl, kh, fpr); if (rc != -1) { keydb_release (kh); if (!rc) { if (existed) *existed = 1; if (!ephemeral) { /* Remove ephemeral flags from existing certificate to "store" it permanently. */ rc = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0, KEYBOX_FLAG_BLOB_EPHEMERAL, 0); if (rc) { log_error ("clearing ephemeral flag failed: %s\n", gpg_strerror (rc)); return rc; } } return 0; /* okay */ } log_error (_("problem looking for existing certificate: %s\n"), gpg_strerror (rc)); return rc; } /* Reset the ephemeral flag if not requested. */ if (!ephemeral) keydb_set_ephemeral (kh, 0); rc = keydb_locate_writable (kh, 0); if (rc) { log_error (_("error finding writable keyDB: %s\n"), gpg_strerror (rc)); keydb_release (kh); return rc; } rc = keydb_insert_cert (kh, cert); if (rc) { log_error (_("error storing certificate: %s\n"), gpg_strerror (rc)); keydb_release (kh); return rc; } keydb_release (kh); return 0; } /* This is basically keydb_set_flags but it implements a complete transaction by locating the certificate in the DB and updating the flags. */ gpg_error_t keydb_set_cert_flags (ctrl_t ctrl, ksba_cert_t cert, int ephemeral, int which, int idx, unsigned int mask, unsigned int value) { KEYDB_HANDLE kh; gpg_error_t err; unsigned char fpr[20]; unsigned int old_value; if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL)) { log_error (_("failed to get the fingerprint\n")); return gpg_error (GPG_ERR_GENERAL); } kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); return gpg_error (GPG_ERR_ENOMEM);; } if (ephemeral) keydb_set_ephemeral (kh, 1); err = keydb_lock (kh); if (err) { log_error (_("error locking keybox: %s\n"), gpg_strerror (err)); keydb_release (kh); return err; } err = keydb_search_fpr (ctrl, kh, fpr); if (err) { if (err == -1) err = gpg_error (GPG_ERR_NOT_FOUND); else log_error (_("problem re-searching certificate: %s\n"), gpg_strerror (err)); keydb_release (kh); return err; } err = keydb_get_flags (kh, which, idx, &old_value); if (err) { log_error (_("error getting stored flags: %s\n"), gpg_strerror (err)); keydb_release (kh); return err; } value = ((old_value & ~mask) | (value & mask)); if (value != old_value) { err = keydb_set_flags (kh, which, idx, value); if (err) { log_error (_("error storing flags: %s\n"), gpg_strerror (err)); keydb_release (kh); return err; } } keydb_release (kh); return 0; } /* Reset all the certificate flags we have stored with the certificates for performance reasons. */ void keydb_clear_some_cert_flags (ctrl_t ctrl, strlist_t names) { gpg_error_t err; KEYDB_HANDLE hd = NULL; KEYDB_SEARCH_DESC *desc = NULL; int ndesc; strlist_t sl; int rc=0; unsigned int old_value, value; (void)ctrl; hd = keydb_new (); if (!hd) { log_error ("keydb_new failed\n"); goto leave; } if (!names) ndesc = 1; else { for (sl=names, ndesc=0; sl; sl = sl->next, ndesc++) ; } desc = xtrycalloc (ndesc, sizeof *desc); if (!ndesc) { log_error ("allocating memory failed: %s\n", gpg_strerror (out_of_core ())); goto leave; } if (!names) desc[0].mode = KEYDB_SEARCH_MODE_FIRST; else { for (ndesc=0, sl=names; sl; sl = sl->next) { rc = classify_user_id (sl->d, desc+ndesc, 0); if (rc) log_error ("key '%s' not found: %s\n", sl->d, gpg_strerror (rc)); else ndesc++; } } err = keydb_lock (hd); if (err) { log_error (_("error locking keybox: %s\n"), gpg_strerror (err)); goto leave; } while (!(rc = keydb_search (ctrl, hd, desc, ndesc))) { if (!names) desc[0].mode = KEYDB_SEARCH_MODE_NEXT; err = keydb_get_flags (hd, KEYBOX_FLAG_VALIDITY, 0, &old_value); if (err) { log_error (_("error getting stored flags: %s\n"), gpg_strerror (err)); goto leave; } value = (old_value & ~VALIDITY_REVOKED); if (value != old_value) { err = keydb_set_flags (hd, KEYBOX_FLAG_VALIDITY, 0, value); if (err) { log_error (_("error storing flags: %s\n"), gpg_strerror (err)); goto leave; } } } if (rc && rc != -1) log_error ("keydb_search failed: %s\n", gpg_strerror (rc)); leave: xfree (desc); keydb_release (hd); } diff --git a/sm/qualified.c b/sm/qualified.c index 564e77929..b43371756 100644 --- a/sm/qualified.c +++ b/sm/qualified.c @@ -1,325 +1,325 @@ /* qualified.c - Routines related to qualified signatures * Copyright (C) 2005, 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include "gpgsm.h" #include "../common/i18n.h" #include /* We open the file only once and keep the open file pointer as well as the name of the file here. Note that, a listname not equal to NULL indicates that this module has been initialized and if the LISTFP is also NULL, no list of qualified signatures exists. */ static char *listname; -static FILE *listfp; +static estream_t listfp; /* Read the trustlist and return entry by entry. KEY must point to a buffer of at least 41 characters. COUNTRY shall be a buffer of at least 3 characters to receive the country code of that qualified signature (i.e. "de" for German and "be" for Belgium). Reading a valid entry returns 0, EOF is indicated by GPG_ERR_EOF and any other error condition is indicated by the appropriate error code. */ static gpg_error_t read_list (char *key, char *country, int *lnr) { gpg_error_t err; int c, i, j; char *p, line[256]; *key = 0; *country = 0; if (!listname) { listname = make_filename (gnupg_datadir (), "qualified.txt", NULL); - listfp = fopen (listname, "r"); + listfp = es_fopen (listname, "r"); if (!listfp && errno != ENOENT) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), listname, gpg_strerror (err)); return err; } } if (!listfp) return gpg_error (GPG_ERR_EOF); do { - if (!fgets (line, DIM(line)-1, listfp) ) + if (!es_fgets (line, DIM(line)-1, listfp) ) { - if (feof (listfp)) + if (es_feof (listfp)) return gpg_error (GPG_ERR_EOF); return gpg_error_from_syserror (); } if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ - while ( (c=getc (listfp)) != EOF && c != '\n') + while ((c = es_getc (listfp)) != EOF && c != '\n') ; return gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); } ++*lnr; /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; } while (!*p || *p == '\n' || *p == '#'); for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++) if ( p[i] != ':' ) key[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i]; key[j] = 0; if (j != 40 || !(spacep (p+i) || p[i] == '\n')) { log_error (_("invalid formatted fingerprint in '%s', line %d\n"), listname, *lnr); return gpg_error (GPG_ERR_BAD_DATA); } assert (p[i]); i++; while (spacep (p+i)) i++; if ( p[i] >= 'a' && p[i] <= 'z' && p[i+1] >= 'a' && p[i+1] <= 'z' && (spacep (p+i+2) || p[i+2] == '\n')) { country[0] = p[i]; country[1] = p[i+1]; country[2] = 0; } else { log_error (_("invalid country code in '%s', line %d\n"), listname, *lnr); return gpg_error (GPG_ERR_BAD_DATA); } return 0; } /* Check whether the certificate CERT is included in the list of qualified certificates. This list is similar to the "trustlist.txt" as maintained by gpg-agent and includes fingerprints of root certificates to be used for qualified (legally binding like handwritten) signatures. We keep this list system wide and not per user because it is not a decision of the user. Returns: 0 if the certificate is included. GPG_ERR_NOT_FOUND if it is not in the list or any other error (e.g. if no list of qualified signatures is available. If COUNTRY has not been passed as NULL a string witha maximum length of 2 will be copied into it; thus the caller needs to provide a buffer of length 3. */ gpg_error_t gpgsm_is_in_qualified_list (ctrl_t ctrl, ksba_cert_t cert, char *country) { gpg_error_t err; char *fpr; char key[41]; char mycountry[3]; int lnr = 0; (void)ctrl; if (country) *country = 0; fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); if (!fpr) return gpg_error (GPG_ERR_GENERAL); if (listfp) { /* W32ce has no rewind, thus we use the equivalent code. */ - fseek (listfp, 0, SEEK_SET); - clearerr (listfp); + es_fseek (listfp, 0, SEEK_SET); + es_clearerr (listfp); } while (!(err = read_list (key, mycountry, &lnr))) { if (!strcmp (key, fpr)) break; } if (gpg_err_code (err) == GPG_ERR_EOF) err = gpg_error (GPG_ERR_NOT_FOUND); if (!err && country) strcpy (country, mycountry); xfree (fpr); return err; } /* We know that CERT is a qualified certificate. Ask the user for consent to actually create a signature using this certificate. Returns: 0 for yes, GPG_ERR_CANCEL for no or any other error code. */ gpg_error_t gpgsm_qualified_consent (ctrl_t ctrl, ksba_cert_t cert) { gpg_error_t err; char *name, *subject, *buffer, *p; const char *s; char *orig_codeset = NULL; name = ksba_cert_get_subject (cert, 0); if (!name) return gpg_error (GPG_ERR_GENERAL); subject = gpgsm_format_name2 (name, 0); ksba_free (name); name = NULL; orig_codeset = i18n_switchto_utf8 (); if (asprintf (&name, _("You are about to create a signature using your " "certificate:\n" "\"%s\"\n" "This will create a qualified signature by law " "equated to a handwritten signature.\n\n%s%s" "Are you really sure that you want to do this?"), subject? subject:"?", opt.qualsig_approval? "": _("Note, that this software is not officially approved " "to create or verify such signatures.\n"), opt.qualsig_approval? "":"\n" ) < 0 ) err = gpg_error_from_syserror (); else err = 0; i18n_switchback (orig_codeset); xfree (subject); if (err) return err; buffer = p = xtrymalloc (strlen (name) * 3 + 1); if (!buffer) { err = gpg_error_from_syserror (); free (name); return err; } for (s=name; *s; s++) { if (*s < ' ' || *s == '+') { sprintf (p, "%%%02X", *(unsigned char *)s); p += 3; } else if (*s == ' ') *p++ = '+'; else *p++ = *s; } *p = 0; free (name); err = gpgsm_agent_get_confirmation (ctrl, buffer); xfree (buffer); return err; } /* Popup a prompt to inform the user that the signature created is not a qualified one. This is of course only done if we know that we have been approved. */ gpg_error_t gpgsm_not_qualified_warning (ctrl_t ctrl, ksba_cert_t cert) { gpg_error_t err; char *name, *subject, *buffer, *p; const char *s; char *orig_codeset; if (!opt.qualsig_approval) return 0; name = ksba_cert_get_subject (cert, 0); if (!name) return gpg_error (GPG_ERR_GENERAL); subject = gpgsm_format_name2 (name, 0); ksba_free (name); name = NULL; orig_codeset = i18n_switchto_utf8 (); if (asprintf (&name, _("You are about to create a signature using your " "certificate:\n" "\"%s\"\n" "Note, that this certificate will NOT create a " "qualified signature!"), subject? subject:"?") < 0 ) err = gpg_error_from_syserror (); else err = 0; i18n_switchback (orig_codeset); xfree (subject); if (err) return err; buffer = p = xtrymalloc (strlen (name) * 3 + 1); if (!buffer) { err = gpg_error_from_syserror (); free (name); return err; } for (s=name; *s; s++) { if (*s < ' ' || *s == '+') { sprintf (p, "%%%02X", *(unsigned char *)s); p += 3; } else if (*s == ' ') *p++ = '+'; else *p++ = *s; } *p = 0; free (name); err = gpgsm_agent_get_confirmation (ctrl, buffer); xfree (buffer); return err; } diff --git a/tools/gpg-check-pattern.c b/tools/gpg-check-pattern.c index e4906d26c..46b9e589d 100644 --- a/tools/gpg-check-pattern.c +++ b/tools/gpg-check-pattern.c @@ -1,494 +1,492 @@ /* gpg-check-pattern.c - A tool to check passphrases against pattern. * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #ifdef HAVE_LANGINFO_CODESET # include #endif #ifdef HAVE_DOSISH_SYSTEM # include /* for setmode() */ #endif #include #include #include #include "../common/util.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/init.h" #include "../regexp/jimregexp.h" enum cmd_and_opt_values { aNull = 0, oVerbose = 'v', oArmor = 'a', oPassphrase = 'P', oProtect = 'p', oUnprotect = 'u', oNull = '0', oNoVerbose = 500, oCheck, oHomedir }; /* The list of commands and options. */ static ARGPARSE_OPTS opts[] = { { 301, NULL, 0, N_("@Options:\n ") }, { oVerbose, "verbose", 0, "verbose" }, { oHomedir, "homedir", 2, "@" }, { oCheck, "check", 0, "run only a syntax check on the patternfile" }, { oNull, "null", 0, "input is expected to be null delimited" }, ARGPARSE_end () }; /* Global options are accessed through the usual OPT structure. */ static struct { int verbose; const char *homedir; int checkonly; int null; } opt; enum { PAT_NULL, /* Indicates end of the array. */ PAT_STRING, /* The pattern is a simple string. */ PAT_REGEX /* The pattern is an extended regualr expression. */ }; /* An object to decibe an item of our pattern table. */ struct pattern_s { int type; unsigned int lineno; /* Line number of the pattern file. */ union { struct { const char *string; /* Pointer to the actual string (nul termnated). */ size_t length; /* The length of this string (strlen). */ } s; /*PAT_STRING*/ struct { /* We allocate the regex_t because this type is larger than what we need for PAT_STRING and we expect only a few regex in a patternfile. It would be a waste of core to have so many unused stuff in the table. */ regex_t *regex; } r; /*PAT_REGEX*/ } u; }; typedef struct pattern_s pattern_t; /*** Local prototypes ***/ static char *read_file (const char *fname, size_t *r_length); static pattern_t *parse_pattern_file (char *data, size_t datalen); static void process (FILE *fp, pattern_t *patarray); /* Info function for usage(). */ static const char * my_strusage (int level) { const char *p; switch (level) { case 11: p = "gpg-check-pattern (@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: gpg-check-pattern [options] patternfile (-h for help)\n"); break; case 41: p = _("Syntax: gpg-check-pattern [options] patternfile\n" "Check a passphrase given on stdin against the patternfile\n"); break; default: p = NULL; } return p; } int main (int argc, char **argv ) { ARGPARSE_ARGS pargs; char *raw_pattern; size_t raw_pattern_length; pattern_t *patternarray; early_system_init (); set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); log_set_prefix ("gpg-check-pattern", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); setup_libgcrypt_logging (); gcry_control (GCRYCTL_INIT_SECMEM, 4096, 0); 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++; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oCheck: opt.checkonly = 1; break; case oNull: opt.null = 1; break; default : pargs.err = 2; break; } } if (log_get_errorcount(0)) exit (2); if (argc != 1) usage (1); /* We read the entire pattern file into our memory and parse it using a separate function. This allows us to eventual do the reading while running setuid so that the pattern file can be hidden from regular users. I am not sure whether this makes sense, but lets be prepared for it. */ raw_pattern = read_file (*argv, &raw_pattern_length); if (!raw_pattern) exit (2); patternarray = parse_pattern_file (raw_pattern, raw_pattern_length); if (!patternarray) exit (1); if (opt.checkonly) return 0; #ifdef HAVE_DOSISH_SYSTEM setmode (fileno (stdin) , O_BINARY ); #endif process (stdin, patternarray); return log_get_errorcount(0)? 1 : 0; } /* Read a file FNAME into a buffer and return that malloced buffer. Caller must free the buffer. On error NULL is returned, on success the valid length of the buffer is stored at R_LENGTH. The returned buffer is guarnteed to be nul terminated. */ static char * read_file (const char *fname, size_t *r_length) { - FILE *fp; + estream_t fp; char *buf; size_t buflen; if (!strcmp (fname, "-")) { size_t nread, bufsize = 0; - fp = stdin; -#ifdef HAVE_DOSISH_SYSTEM - setmode ( fileno(fp) , O_BINARY ); -#endif + fp = es_stdin; + es_set_binary (fp); buf = NULL; buflen = 0; #define NCHUNK 8192 do { bufsize += NCHUNK; if (!buf) buf = xmalloc (bufsize+1); else buf = xrealloc (buf, bufsize+1); - nread = fread (buf+buflen, 1, NCHUNK, fp); - if (nread < NCHUNK && ferror (fp)) + nread = es_fread (buf+buflen, 1, NCHUNK, fp); + if (nread < NCHUNK && es_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"); + fp = es_fopen (fname, "rb"); if (!fp) { log_error ("can't open '%s': %s\n", fname, strerror (errno)); return NULL; } - if (fstat (fileno(fp), &st)) + if (fstat (es_fileno (fp), &st)) { log_error ("can't stat '%s': %s\n", fname, strerror (errno)); - fclose (fp); + es_fclose (fp); return NULL; } buflen = st.st_size; buf = xmalloc (buflen+1); - if (fread (buf, buflen, 1, fp) != 1) + if (es_fread (buf, buflen, 1, fp) != 1) { log_error ("error reading '%s': %s\n", fname, strerror (errno)); - fclose (fp); + es_fclose (fp); xfree (buf); return NULL; } - fclose (fp); + es_fclose (fp); } buf[buflen] = 0; *r_length = buflen; return buf; } static char * get_regerror (int errcode, regex_t *compiled) { size_t length = regerror (errcode, compiled, NULL, 0); char *buffer = xmalloc (length); regerror (errcode, compiled, buffer, length); return buffer; } /* Parse the pattern given in the memory aread DATA/DATALEN and return a new pattern array. The end of the array is indicated by a NULL entry. On error an error message is printed and the function returns NULL. Note that the function modifies DATA and assumes that data is nul terminated (even if this is one byte past DATALEN). */ static pattern_t * parse_pattern_file (char *data, size_t datalen) { char *p, *p2; size_t n; pattern_t *array; size_t arraysize, arrayidx; unsigned int lineno = 0; /* Estimate the number of entries by counting the non-comment lines. */ arraysize = 0; p = data; for (n = datalen; n && (p2 = memchr (p, '\n', n)); p2++, n -= p2 - p, p = p2) if (*p != '#') arraysize++; arraysize += 2; /* For the terminating NULL and a last line w/o a LF. */ array = xcalloc (arraysize, sizeof *array); arrayidx = 0; /* Loop over all lines. */ while (datalen && data) { lineno++; p = data; p2 = data = memchr (p, '\n', datalen); if (p2) { *data++ = 0; datalen -= data - p; } else p2 = p + datalen; assert (!*p2); p2--; while (isascii (*p) && isspace (*p)) p++; if (*p == '#') continue; while (p2 > p && isascii (*p2) && isspace (*p2)) *p2-- = 0; if (!*p) continue; assert (arrayidx < arraysize); array[arrayidx].lineno = lineno; if (*p == '/') { int rerr; p++; array[arrayidx].type = PAT_REGEX; if (*p && p[strlen(p)-1] == '/') p[strlen(p)-1] = 0; /* Remove optional delimiter. */ array[arrayidx].u.r.regex = xcalloc (1, sizeof (regex_t)); rerr = regcomp (array[arrayidx].u.r.regex, p, REG_ICASE|REG_EXTENDED); if (rerr) { char *rerrbuf = get_regerror (rerr, array[arrayidx].u.r.regex); log_error ("invalid r.e. at line %u: %s\n", lineno, rerrbuf); xfree (rerrbuf); if (!opt.checkonly) exit (1); } } else { array[arrayidx].type = PAT_STRING; array[arrayidx].u.s.string = p; array[arrayidx].u.s.length = strlen (p); } arrayidx++; } assert (arrayidx < arraysize); array[arrayidx].type = PAT_NULL; return array; } /* Check whether string macthes any of the pattern in PATARRAY and returns the matching pattern item or NULL. */ static pattern_t * match_p (const char *string, pattern_t *patarray) { pattern_t *pat; if (!*string) { if (opt.verbose) log_info ("zero length input line - ignored\n"); return NULL; } for (pat = patarray; pat->type != PAT_NULL; pat++) { if (pat->type == PAT_STRING) { if (!strcasecmp (pat->u.s.string, string)) return pat; } else if (pat->type == PAT_REGEX) { int rerr; rerr = regexec (pat->u.r.regex, string, 0, NULL, 0); if (!rerr) return pat; else if (rerr != REG_NOMATCH) { char *rerrbuf = get_regerror (rerr, pat->u.r.regex); log_error ("matching r.e. failed: %s\n", rerrbuf); xfree (rerrbuf); return pat; /* Better indicate a match on error. */ } } else BUG (); } return NULL; } /* Actual processing of the input. This function does not return an error code but exits as soon as a match has been found. */ static void process (FILE *fp, pattern_t *patarray) { char buffer[2048]; size_t idx; int c; unsigned long lineno = 0; pattern_t *pat; idx = 0; c = 0; while (idx < sizeof buffer -1 && c != EOF ) { if ((c = getc (fp)) != EOF) buffer[idx] = c; if ((c == '\n' && !opt.null) || (!c && opt.null) || c == EOF) { lineno++; if (!opt.null) { while (idx && isascii (buffer[idx-1]) && isspace (buffer[idx-1])) idx--; } buffer[idx] = 0; pat = match_p (buffer, patarray); if (pat) { if (opt.verbose) log_error ("input line %lu matches pattern at line %u" " - rejected\n", lineno, pat->lineno); exit (1); } idx = 0; } else idx++; } if (c != EOF) { log_error ("input line %lu too long - rejected\n", lineno+1); exit (1); } if (ferror (fp)) { log_error ("input read error at line %lu: %s - rejected\n", lineno+1, strerror (errno)); exit (1); } if (opt.verbose) log_info ("no input line matches the pattern - accepted\n"); } diff --git a/tools/gpg-connect-agent.c b/tools/gpg-connect-agent.c index bf32a74de..a06d6fd2c 100644 --- a/tools/gpg-connect-agent.c +++ b/tools/gpg-connect-agent.c @@ -1,2261 +1,2262 @@ /* gpg-connect-agent.c - Tool to connect to the agent. * Copyright (C) 2005, 2007, 2008, 2010 Free Software Foundation, Inc. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #include #include "../common/i18n.h" #include "../common/util.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "../common/membuf.h" #include "../common/ttyio.h" #ifdef HAVE_W32_SYSTEM # include "../common/exechelp.h" #endif #include "../common/init.h" #define CONTROL_D ('D' - 'A' + 1) #define octdigitp(p) (*(p) >= '0' && *(p) <= '7') /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oRawSocket = 'S', oTcpSocket = 'T', oExec = 'E', oRun = 'r', oSubst = 's', oNoVerbose = 500, oHomedir, oAgentProgram, oDirmngrProgram, oHex, oDecode, oNoExtConnect, oDirmngr, oUIServer, oNoAutostart, }; /* The list of commands and options. */ static ARGPARSE_OPTS opts[] = { ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("quiet")), ARGPARSE_s_n (oHex, "hex", N_("print data out hex encoded")), ARGPARSE_s_n (oDecode,"decode", N_("decode received data lines")), ARGPARSE_s_n (oDirmngr,"dirmngr", N_("connect to the dirmngr")), ARGPARSE_s_n (oUIServer, "uiserver", "@"), ARGPARSE_s_s (oRawSocket, "raw-socket", N_("|NAME|connect to Assuan socket NAME")), ARGPARSE_s_s (oTcpSocket, "tcp-socket", N_("|ADDR|connect to Assuan server at ADDR")), ARGPARSE_s_n (oExec, "exec", N_("run the Assuan server given on the command line")), ARGPARSE_s_n (oNoExtConnect, "no-ext-connect", N_("do not use extended connect mode")), ARGPARSE_s_s (oRun, "run", N_("|FILE|run commands from FILE on startup")), ARGPARSE_s_n (oSubst, "subst", N_("run /subst on startup")), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@" ), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"), ARGPARSE_end () }; /* We keep all global options in the structure OPT. */ struct { int verbose; /* Verbosity level. */ int quiet; /* Be extra quiet. */ int autostart; /* Start the server if not running. */ const char *homedir; /* Configuration directory name */ const char *agent_program; /* Value of --agent-program. */ const char *dirmngr_program; /* Value of --dirmngr-program. */ int hex; /* Print data lines in hex format. */ int decode; /* Decode received data lines. */ int use_dirmngr; /* Use the dirmngr and not gpg-agent. */ int use_uiserver; /* Use the standard UI server. */ const char *raw_socket; /* Name of socket to connect in raw mode. */ const char *tcp_socket; /* Name of server to connect in tcp mode. */ int exec; /* Run the pgm given on the command line. */ unsigned int connect_flags; /* Flags used for connecting. */ int enable_varsubst; /* Set if variable substitution is enabled. */ int trim_leading_spaces; } opt; /* Definitions for /definq commands and a global linked list with all the definitions. */ struct definq_s { struct definq_s *next; char *name; /* Name of inquiry or NULL for any name. */ int is_var; /* True if FILE is a variable name. */ int is_prog; /* True if FILE is a program to run. */ char file[1]; /* Name of file or program. */ }; typedef struct definq_s *definq_t; static definq_t definq_list; static definq_t *definq_list_tail = &definq_list; /* Variable definitions and glovbal table. */ struct variable_s { struct variable_s *next; char *value; /* Malloced value - always a string. */ char name[1]; /* Name of the variable. */ }; typedef struct variable_s *variable_t; static variable_t variable_table; /* To implement loops we store entire lines in a linked list. */ struct loopline_s { struct loopline_s *next; char line[1]; }; typedef struct loopline_s *loopline_t; /* This is used to store the pid of the server. */ static pid_t server_pid = (pid_t)(-1); /* The current datasink file or NULL. */ -static FILE *current_datasink; +static estream_t current_datasink; /* A list of open file descriptors. */ static struct { int inuse; #ifdef HAVE_W32_SYSTEM HANDLE handle; #endif } open_fd_table[256]; /*-- local prototypes --*/ static char *substitute_line_copy (const char *buffer); static int read_and_print_response (assuan_context_t ctx, int withhash, int *r_goterr); static assuan_context_t start_agent (void); /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 11: p = "@GPG@-connect-agent (@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: @GPG@-connect-agent [options] (-h for help)"); break; case 41: p = _("Syntax: @GPG@-connect-agent [options]\n" "Connect to a running agent and send commands\n"); break; case 31: p = "\nHome: "; break; case 32: p = gnupg_homedir (); break; case 33: p = "\n"; break; default: p = NULL; break; } return p; } /* Unescape STRING and returned the malloced result. The surrounding quotes must already be removed from STRING. */ static char * unescape_string (const char *string) { const unsigned char *s; int esc; size_t n; char *buffer; unsigned char *d; n = 0; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': case 't': case 'v': case 'n': case 'f': case 'r': case '"': case '\'': case '\\': n++; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) n++; break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) n++; break; } esc = 0; } else if (*s == '\\') esc = 1; else n++; } buffer = xmalloc (n+1); d = (unsigned char*)buffer; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': *d++ = '\b'; break; case 't': *d++ = '\t'; break; case 'v': *d++ = '\v'; break; case 'n': *d++ = '\n'; break; case 'f': *d++ = '\f'; break; case 'r': *d++ = '\r'; break; case '"': *d++ = '\"'; break; case '\'': *d++ = '\''; break; case '\\': *d++ = '\\'; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) { s++; *d++ = xtoi_2 (s); s++; } break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) { *d++ = (atoi_1 (s)*64) + (atoi_1 (s+1)*8) + atoi_1 (s+2); s += 2; } break; } esc = 0; } else if (*s == '\\') esc = 1; else *d++ = *s; } *d = 0; return buffer; } /* Do the percent unescaping and return a newly malloced string. If WITH_PLUS is set '+' characters will be changed to space. */ static char * unpercent_string (const char *string, int with_plus) { const unsigned char *s; unsigned char *buffer, *p; size_t n; n = 0; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; n++; s++; } else if (with_plus && *s == '+') n++; else n++; } buffer = xmalloc (n+1); p = buffer; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; *p++ = xtoi_2 (s); s++; } else if (with_plus && *s == '+') *p++ = ' '; else *p++ = *s; } *p = 0; return (char*)buffer; } static const char * set_var (const char *name, const char *value) { variable_t var; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var) { var = xmalloc (sizeof *var + strlen (name)); var->value = NULL; strcpy (var->name, name); var->next = variable_table; variable_table = var; } xfree (var->value); var->value = value? xstrdup (value) : NULL; return var->value; } static void set_int_var (const char *name, int value) { char numbuf[35]; snprintf (numbuf, sizeof numbuf, "%d", value); set_var (name, numbuf); } /* Return the value of a variable. That value is valid until a variable of the name is changed. Return NULL if not found. Note that envvars are copied to our variable list at the first access and not at oprogram start. */ static const char * get_var (const char *name) { variable_t var; const char *s; if (!*name) return ""; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var && (s = getenv (name))) return set_var (name, s); if (!var || !var->value) return NULL; return var->value; } /* Perform some simple arithmetic operations. Caller must release the return value. On error the return value is NULL. */ static char * arithmetic_op (int operator, const char *operands) { long result, value; char numbuf[35]; while ( spacep (operands) ) operands++; if (!*operands) return NULL; result = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; if (operator == '!') result = !result; while (*operands) { while ( spacep (operands) ) operands++; if (!*operands) break; value = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; switch (operator) { case '+': result += value; break; case '-': result -= value; break; case '*': result *= value; break; case '/': if (!value) return NULL; result /= value; break; case '%': if (!value) return NULL; result %= value; break; case '!': result = !value; break; case '|': result = result || value; break; case '&': result = result && value; break; default: log_error ("unknown arithmetic operator '%c'\n", operator); return NULL; } } snprintf (numbuf, sizeof numbuf, "%ld", result); return xstrdup (numbuf); } /* Extended version of get_var. This returns a malloced string and understand the function syntax: "func args". Defined functions are get - Return a value described by the next argument: cwd - The current working directory. homedir - The gnupg homedir. sysconfdir - GnuPG's system configuration directory. bindir - GnuPG's binary directory. libdir - GnuPG's library directory. libexecdir - GnuPG's library directory for executable files. datadir - GnuPG's data directory. serverpid - The PID of the current server. unescape ARGS Remove C-style escapes from string. Note that "\0" and "\x00" terminate the string implictly. Use "\x7d" to represent the closing brace. The args start right after the first space after the function name. unpercent ARGS unpercent+ ARGS Remove percent style ecaping from string. Note that "%00 terminates the string implicitly. Use "%7d" to represetn the closing brace. The args start right after the first space after the function name. "unpercent+" also maps '+' to space. percent ARGS percent+ ARGS Escape the args using the percent style. Tabs, formfeeds, linefeeds, carriage return, and the plus sign are also escaped. "percent+" also maps spaces to plus characters. errcode ARG Assuming ARG is an integer, return the gpg-error code. errsource ARG Assuming ARG is an integer, return the gpg-error source. errstring ARG Assuming ARG is an integer return a formatted fpf error string. Example: get_var_ext ("get sysconfdir") -> "/etc/gnupg" */ static char * get_var_ext (const char *name) { static int recursion_count; const char *s; char *result; char *p; char *free_me = NULL; int intvalue; if (recursion_count > 50) { log_error ("variables nested too deeply\n"); return NULL; } recursion_count++; free_me = opt.enable_varsubst? substitute_line_copy (name) : NULL; if (free_me) name = free_me; for (s=name; *s && !spacep (s); s++) ; if (!*s) { s = get_var (name); result = s? xstrdup (s): NULL; } else if ( (s - name) == 3 && !strncmp (name, "get", 3)) { while ( spacep (s) ) s++; if (!strcmp (s, "cwd")) { result = gnupg_getcwd (); if (!result) log_error ("getcwd failed: %s\n", strerror (errno)); } else if (!strcmp (s, "homedir")) result = xstrdup (gnupg_homedir ()); else if (!strcmp (s, "sysconfdir")) result = xstrdup (gnupg_sysconfdir ()); else if (!strcmp (s, "bindir")) result = xstrdup (gnupg_bindir ()); else if (!strcmp (s, "libdir")) result = xstrdup (gnupg_libdir ()); else if (!strcmp (s, "libexecdir")) result = xstrdup (gnupg_libexecdir ()); else if (!strcmp (s, "datadir")) result = xstrdup (gnupg_datadir ()); else if (!strcmp (s, "serverpid")) result = xasprintf ("%d", (int)server_pid); else { log_error ("invalid argument '%s' for variable function 'get'\n", s); log_info ("valid are: cwd, " "{home,bin,lib,libexec,data}dir, serverpid\n"); result = NULL; } } else if ( (s - name) == 8 && !strncmp (name, "unescape", 8)) { s++; result = unescape_string (s); } else if ( (s - name) == 9 && !strncmp (name, "unpercent", 9)) { s++; result = unpercent_string (s, 0); } else if ( (s - name) == 10 && !strncmp (name, "unpercent+", 10)) { s++; result = unpercent_string (s, 1); } else if ( (s - name) == 7 && !strncmp (name, "percent", 7)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); } else if ( (s - name) == 8 && !strncmp (name, "percent+", 8)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); for (p=result; *p; p++) if (*p == ' ') *p = '+'; } else if ( (s - name) == 7 && !strncmp (name, "errcode", 7)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_code (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errsource", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_source (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errstring", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%s <%s>", gpg_strerror (intvalue), gpg_strsource (intvalue)); } else if ( (s - name) == 1 && strchr ("+-*/%!|&", *name)) { result = arithmetic_op (*name, s+1); } else { log_error ("unknown variable function '%.*s'\n", (int)(s-name), name); result = NULL; } xfree (free_me); recursion_count--; return result; } /* Substitute variables in LINE and return a new allocated buffer if required. The function might modify LINE if the expanded version fits into it. */ static char * substitute_line (char *buffer) { char *line = buffer; char *p, *pend; const char *value; size_t valuelen, n; char *result = NULL; char *freeme = NULL; while (*line) { p = strchr (line, '$'); if (!p) return result; /* No more variables. */ if (p[1] == '$') /* Escaped dollar sign. */ { memmove (p, p+1, strlen (p+1)+1); line = p + 1; continue; } if (p[1] == '{') { int count = 0; for (pend=p+2; *pend; pend++) { if (*pend == '{') count++; else if (*pend == '}') { if (--count < 0) break; } } if (!*pend) return result; /* Unclosed - don't substitute. */ } else { for (pend=p+1; *pend && !spacep (pend) && *pend != '$' ; pend++) ; } if (p[1] == '{' && *pend == '}') { int save = *pend; *pend = 0; freeme = get_var_ext (p+2); value = freeme; *pend++ = save; } else if (*pend) { int save = *pend; *pend = 0; value = get_var (p+1); *pend = save; } else value = get_var (p+1); if (!value) value = ""; valuelen = strlen (value); if (valuelen <= pend - p) { memcpy (p, value, valuelen); p += valuelen; n = pend - p; if (n) memmove (p, p+n, strlen (p+n)+1); line = p; } else { char *src = result? result : buffer; char *dst; dst = xmalloc (strlen (src) + valuelen + 1); n = p - src; memcpy (dst, src, n); memcpy (dst + n, value, valuelen); n += valuelen; strcpy (dst + n, pend); line = dst + n; xfree (result); result = dst; } xfree (freeme); freeme = NULL; } return result; } /* Same as substitute_line but do not modify BUFFER. */ static char * substitute_line_copy (const char *buffer) { char *result, *p; p = xstrdup (buffer?buffer:""); result = substitute_line (p); if (!result) result = p; else xfree (p); return result; } static void assign_variable (char *line, int syslet) { char *name, *p, *tmp, *free_me, *buffer; /* Get the name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!*p) set_var (name, NULL); /* Remove variable. */ else if (syslet) { free_me = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (free_me) p = free_me; buffer = xmalloc (4 + strlen (p) + 1); strcpy (stpcpy (buffer, "get "), p); tmp = get_var_ext (buffer); xfree (buffer); set_var (name, tmp); xfree (tmp); xfree (free_me); } else { tmp = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (tmp) { set_var (name, tmp); xfree (tmp); } else set_var (name, p); } } static void show_variables (void) { variable_t var; for (var = variable_table; var; var = var->next) if (var->value) printf ("%-20s %s\n", var->name, var->value); } /* Store an inquire response pattern. Note, that this function may change the content of LINE. We assume that leading white spaces are already removed. */ static void add_definq (char *line, int is_var, int is_prog) { definq_t d; char *name, *p; /* Get name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; d = xmalloc (sizeof *d + strlen (p) ); strcpy (d->file, p); d->is_var = is_var; d->is_prog = is_prog; if ( !strcmp (name, "*")) d->name = NULL; else d->name = xstrdup (name); d->next = NULL; *definq_list_tail = d; definq_list_tail = &d->next; } /* Show all inquiry definitions. */ static void show_definq (void) { definq_t d; for (d=definq_list; d; d = d->next) if (d->name) printf ("%-20s %c %s\n", d->name, d->is_var? 'v' : d->is_prog? 'p':'f', d->file); for (d=definq_list; d; d = d->next) if (!d->name) printf ("%-20s %c %s\n", "*", d->is_var? 'v': d->is_prog? 'p':'f', d->file); } /* Clear all inquiry definitions. */ static void clear_definq (void) { while (definq_list) { definq_t tmp = definq_list->next; xfree (definq_list->name); xfree (definq_list); definq_list = tmp; } definq_list_tail = &definq_list; } static void do_sendfd (assuan_context_t ctx, char *line) { - FILE *fp; + estream_t fp; char *name, *mode, *p; int rc, fd; /* Get file name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get mode. */ mode = p; if (!*mode) mode = "r"; else { for (p=mode; *p && !spacep (p); p++) ; if (*p) *p++ = 0; } /* Open and send. */ - fp = fopen (name, mode); + fp = es_fopen (name, mode); if (!fp) { log_error ("can't open '%s' in \"%s\" mode: %s\n", name, mode, strerror (errno)); return; } - fd = fileno (fp); + fd = es_fileno (fp); if (opt.verbose) log_error ("file '%s' opened in \"%s\" mode, fd=%d\n", name, mode, fd); rc = assuan_sendfd (ctx, INT2FD (fd) ); if (rc) log_error ("sending descriptor %d failed: %s\n", fd, gpg_strerror (rc)); - fclose (fp); + es_fclose (fp); } static void do_recvfd (assuan_context_t ctx, char *line) { (void)ctx; (void)line; log_info ("This command has not yet been implemented\n"); } static void do_open (char *line) { - FILE *fp; + estream_t fp; char *varname, *name, *mode, *p; int fd; #ifdef HAVE_W32_SYSTEM if (server_pid == (pid_t)(-1)) { log_error ("the pid of the server is unknown\n"); log_info ("use command \"/serverpid\" first\n"); return; } #endif /* Get variable name. */ varname = line; for (p=varname; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get file name. */ name = p; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; /* Get mode. */ mode = p; if (!*mode) mode = "r"; else { for (p=mode; *p && !spacep (p); p++) ; if (*p) *p++ = 0; } /* Open and send. */ - fp = fopen (name, mode); + fp = es_fopen (name, mode); if (!fp) { log_error ("can't open '%s' in \"%s\" mode: %s\n", name, mode, strerror (errno)); return; } - fd = dup (fileno (fp)); + fd = dup (es_fileno (fp)); if (fd >= 0 && fd < DIM (open_fd_table)) { open_fd_table[fd].inuse = 1; #ifdef HAVE_W32CE_SYSTEM # warning fixme: implement our pipe emulation. #endif #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) { HANDLE prochandle, handle, newhandle; handle = (void*)_get_osfhandle (fd); prochandle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, server_pid); if (!prochandle) { log_error ("failed to open the server process\n"); close (fd); return; } if (!DuplicateHandle (GetCurrentProcess(), handle, prochandle, &newhandle, 0, TRUE, DUPLICATE_SAME_ACCESS )) { log_error ("failed to duplicate the handle\n"); close (fd); CloseHandle (prochandle); return; } CloseHandle (prochandle); open_fd_table[fd].handle = newhandle; } if (opt.verbose) log_info ("file '%s' opened in \"%s\" mode, fd=%d (libc=%d)\n", name, mode, (int)open_fd_table[fd].handle, fd); set_int_var (varname, (int)open_fd_table[fd].handle); #else if (opt.verbose) log_info ("file '%s' opened in \"%s\" mode, fd=%d\n", name, mode, fd); set_int_var (varname, fd); #endif } else { log_error ("can't put fd %d into table\n", fd); if (fd != -1) close (fd); /* Table was full. */ } - fclose (fp); + es_fclose (fp); } static void do_close (char *line) { int fd = atoi (line); #ifdef HAVE_W32_SYSTEM int i; for (i=0; i < DIM (open_fd_table); i++) if ( open_fd_table[i].inuse && open_fd_table[i].handle == (void*)fd) break; if (i < DIM (open_fd_table)) fd = i; else { log_error ("given fd (system handle) has not been opened\n"); return; } #endif if (fd < 0 || fd >= DIM (open_fd_table)) { log_error ("invalid fd\n"); return; } if (!open_fd_table[fd].inuse) { log_error ("given fd has not been opened\n"); return; } #ifdef HAVE_W32_SYSTEM CloseHandle (open_fd_table[fd].handle); /* Close duped handle. */ #endif close (fd); open_fd_table[fd].inuse = 0; } static void do_showopen (void) { int i; for (i=0; i < DIM (open_fd_table); i++) if (open_fd_table[i].inuse) { #ifdef HAVE_W32_SYSTEM printf ("%-15d (libc=%d)\n", (int)open_fd_table[i].handle, i); #else printf ("%-15d\n", i); #endif } } static gpg_error_t getinfo_pid_cb (void *opaque, const void *buffer, size_t length) { membuf_t *mb = opaque; put_membuf (mb, buffer, length); return 0; } /* Get the pid of the server and store it locally. */ static void do_serverpid (assuan_context_t ctx) { int rc; membuf_t mb; char *buffer; init_membuf (&mb, 100); rc = assuan_transact (ctx, "GETINFO pid", getinfo_pid_cb, &mb, NULL, NULL, NULL, NULL); put_membuf (&mb, "", 1); buffer = get_membuf (&mb, NULL); if (rc || !buffer) log_error ("command \"%s\" failed: %s\n", "GETINFO pid", gpg_strerror (rc)); else { server_pid = (pid_t)strtoul (buffer, NULL, 10); if (opt.verbose) log_info ("server's PID is %lu\n", (unsigned long)server_pid); } xfree (buffer); } /* Return true if the command is either "HELP" or "SCD HELP". */ static int help_cmd_p (const char *line) { if (!ascii_strncasecmp (line, "SCD", 3) && (spacep (line+3) || !line[3])) { for (line += 3; spacep (line); line++) ; } return (!ascii_strncasecmp (line, "HELP", 4) && (spacep (line+4) || !line[4])); } /* gpg-connect-agent's entry point. */ int main (int argc, char **argv) { ARGPARSE_ARGS pargs; int no_more_options = 0; assuan_context_t ctx; char *line, *p; char *tmpline; size_t linesize; int rc; int cmderr; const char *opt_run = NULL; gpgrt_stream_t script_fp = NULL; int use_tty, keep_line; struct { int collecting; loopline_t head; loopline_t *tail; loopline_t current; unsigned int nestlevel; int oneshot; char *condition; } loopstack[20]; int loopidx; char **cmdline_commands = NULL; early_system_init (); gnupg_rl_initialize (); set_strusage (my_strusage); log_set_prefix ("gpg-connect-agent", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); assuan_set_gpg_err_source (0); gnupg_init_signals (0, NULL); opt.autostart = 1; opt.connect_flags = 1; /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = 1; /* Do not remove the args. */ while (!no_more_options && optfile_parse (NULL, NULL, NULL, &pargs, opts)) { switch (pargs.r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break; case oNoAutostart: opt.autostart = 0; break; case oHex: opt.hex = 1; break; case oDecode: opt.decode = 1; break; case oDirmngr: opt.use_dirmngr = 1; break; case oUIServer: opt.use_uiserver = 1; break; case oRawSocket: opt.raw_socket = pargs.r.ret_str; break; case oTcpSocket: opt.tcp_socket = pargs.r.ret_str; break; case oExec: opt.exec = 1; break; case oNoExtConnect: opt.connect_flags &= ~(1); break; case oRun: opt_run = pargs.r.ret_str; break; case oSubst: opt.enable_varsubst = 1; opt.trim_leading_spaces = 1; break; default: pargs.err = 2; break; } } if (log_get_errorcount (0)) exit (2); /* --uiserver is a shortcut for a specific raw socket. This comes in particular handy on Windows. */ if (opt.use_uiserver) { opt.raw_socket = make_absfilename (gnupg_homedir (), "S.uiserver", NULL); } /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } use_tty = (gnupg_isatty (fileno (stdin)) && gnupg_isatty (fileno (stdout))); if (opt.exec) { if (!argc) { log_error (_("option \"%s\" requires a program " "and optional arguments\n"), "--exec" ); exit (1); } } else if (argc) cmdline_commands = argv; if (opt.exec && opt.raw_socket) { opt.raw_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--raw-socket", "--exec"); } if (opt.exec && opt.tcp_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--exec"); } if (opt.tcp_socket && opt.raw_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--raw-socket"); } if (opt_run && !(script_fp = gpgrt_fopen (opt_run, "r"))) { log_error ("cannot open run file '%s': %s\n", opt_run, strerror (errno)); exit (1); } if (opt.exec) { assuan_fd_t no_close[3]; no_close[0] = assuan_fd_from_posix_fd (es_fileno (es_stderr)); no_close[1] = assuan_fd_from_posix_fd (log_get_fd ()); no_close[2] = ASSUAN_INVALID_FD; rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_pipe_connect (ctx, *argv, (const char **)argv, no_close, NULL, NULL, (opt.connect_flags & 1) ? ASSUAN_PIPE_CONNECT_FDPASSING : 0); if (rc) { log_error ("assuan_pipe_connect_ext failed: %s\n", gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("server '%s' started\n", *argv); } else if (opt.raw_socket) { rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.raw_socket, 0, (opt.connect_flags & 1) ? ASSUAN_SOCKET_CONNECT_FDPASSING : 0); if (rc) { log_error ("can't connect to socket '%s': %s\n", opt.raw_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", opt.raw_socket); } else if (opt.tcp_socket) { char *url; url = xstrconcat ("assuan://", opt.tcp_socket, NULL); rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.tcp_socket, 0, 0); if (rc) { log_error ("can't connect to server '%s': %s\n", opt.tcp_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", url); xfree (url); } else ctx = start_agent (); /* See whether there is a line pending from the server (in case assuan did not run the initial handshaking). */ if (assuan_pending_line (ctx)) { rc = read_and_print_response (ctx, 0, &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); } for (loopidx=0; loopidx < DIM (loopstack); loopidx++) loopstack[loopidx].collecting = 0; loopidx = -1; line = NULL; linesize = 0; keep_line = 1; for (;;) { int n; size_t maxlength = 2048; assert (loopidx < (int)DIM (loopstack)); if (loopidx >= 0 && loopstack[loopidx].current) { keep_line = 0; xfree (line); line = xstrdup (loopstack[loopidx].current->line); n = strlen (line); /* Never go beyond of the final /end. */ if (loopstack[loopidx].current->next) loopstack[loopidx].current = loopstack[loopidx].current->next; else if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) ; else log_fatal ("/end command vanished\n"); } else if (cmdline_commands && *cmdline_commands && !script_fp) { keep_line = 0; xfree (line); line = xstrdup (*cmdline_commands); cmdline_commands++; n = strlen (line); if (n >= maxlength) maxlength = 0; } else if (use_tty && !script_fp) { keep_line = 0; xfree (line); line = tty_get ("> "); n = strlen (line); if (n==1 && *line == CONTROL_D) n = 0; if (n >= maxlength) maxlength = 0; } else { if (!keep_line) { xfree (line); line = NULL; linesize = 0; keep_line = 1; } n = gpgrt_read_line (script_fp ? script_fp : gpgrt_stdin, &line, &linesize, &maxlength); } if (n < 0) { log_error (_("error reading input: %s\n"), strerror (errno)); if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; log_error ("stopping script execution\n"); continue; } exit (1); } if (!n) { /* EOF */ if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; if (opt.verbose) log_info ("end of script\n"); continue; } break; } if (!maxlength) { log_error (_("line too long - skipped\n")); continue; } if (memchr (line, 0, n)) log_info (_("line shortened due to embedded Nul character\n")); if (line[n-1] == '\n') line[n-1] = 0; if (opt.trim_leading_spaces) { const char *s = line; while (spacep (s)) s++; if (s != line) { for (p=line; *s;) *p++ = *s++; *p = 0; n = p - line; } } if (loopidx+1 >= 0 && loopstack[loopidx+1].collecting) { loopline_t ll; ll = xmalloc (sizeof *ll + strlen (line)); ll->next = NULL; strcpy (ll->line, line); *loopstack[loopidx+1].tail = ll; loopstack[loopidx+1].tail = &ll->next; if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) loopstack[loopidx+1].nestlevel--; else if (!strncmp (line, "/while", 6) && (!line[6]||spacep(line+6))) loopstack[loopidx+1].nestlevel++; if (loopstack[loopidx+1].nestlevel) continue; /* We reached the corresponding /end. */ loopstack[loopidx+1].collecting = 0; loopidx++; } if (*line == '/') { /* Handle control commands. */ char *cmd = line+1; for (p=cmd; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!strcmp (cmd, "let")) { assign_variable (p, 0); } else if (!strcmp (cmd, "slet")) { /* Deprecated - never used in a released version. */ assign_variable (p, 1); } else if (!strcmp (cmd, "showvar")) { show_variables (); } else if (!strcmp (cmd, "definq")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 1, 0); xfree (tmpline); } else add_definq (p, 1, 0); } else if (!strcmp (cmd, "definqfile")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 0); xfree (tmpline); } else add_definq (p, 0, 0); } else if (!strcmp (cmd, "definqprog")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 1); xfree (tmpline); } else add_definq (p, 0, 1); } else if (!strcmp (cmd, "datafile")) { const char *fname; if (current_datasink) { - if (current_datasink != stdout) - fclose (current_datasink); + if (current_datasink != es_stdout) + es_fclose (current_datasink); current_datasink = NULL; } tmpline = opt.enable_varsubst? substitute_line (p) : NULL; fname = tmpline? tmpline : p; if (fname && !strcmp (fname, "-")) - current_datasink = stdout; + current_datasink = es_stdout; else if (fname && *fname) { - current_datasink = fopen (fname, "wb"); + current_datasink = es_fopen (fname, "wb"); if (!current_datasink) log_error ("can't open '%s': %s\n", fname, strerror (errno)); } xfree (tmpline); } else if (!strcmp (cmd, "showdef")) { show_definq (); } else if (!strcmp (cmd, "cleardef")) { clear_definq (); } else if (!strcmp (cmd, "echo")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { puts (tmpline); xfree (tmpline); } else puts (p); } else if (!strcmp (cmd, "sendfd")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_sendfd (ctx, tmpline); xfree (tmpline); } else do_sendfd (ctx, p); continue; } else if (!strcmp (cmd, "recvfd")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_recvfd (ctx, tmpline); xfree (tmpline); } else do_recvfd (ctx, p); continue; } else if (!strcmp (cmd, "open")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_open (tmpline); xfree (tmpline); } else do_open (p); } else if (!strcmp (cmd, "close")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { do_close (tmpline); xfree (tmpline); } else do_close (p); } else if (!strcmp (cmd, "showopen")) { do_showopen (); } else if (!strcmp (cmd, "serverpid")) { do_serverpid (ctx); } else if (!strcmp (cmd, "hex")) opt.hex = 1; else if (!strcmp (cmd, "nohex")) opt.hex = 0; else if (!strcmp (cmd, "decode")) opt.decode = 1; else if (!strcmp (cmd, "nodecode")) opt.decode = 0; else if (!strcmp (cmd, "subst")) { opt.enable_varsubst = 1; opt.trim_leading_spaces = 1; } else if (!strcmp (cmd, "nosubst")) opt.enable_varsubst = 0; else if (!strcmp (cmd, "run")) { char *p2; for (p2=p; *p2 && !spacep (p2); p2++) ; if (*p2) *p2++ = 0; while (spacep (p2)) p++; if (*p2) { log_error ("syntax error in run command\n"); if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; } } else if (script_fp) { log_error ("cannot nest run commands - stop\n"); gpgrt_fclose (script_fp); script_fp = NULL; } else if (!(script_fp = gpgrt_fopen (p, "r"))) { log_error ("cannot open run file '%s': %s\n", p, strerror (errno)); } else if (opt.verbose) log_info ("running commands from '%s'\n", p); } else if (!strcmp (cmd, "while")) { if (loopidx+2 >= (int)DIM(loopstack)) { log_error ("blocks are nested too deep\n"); /* We should better die or break all loop in this case as recovering from this error won't be easy. */ } else { loopstack[loopidx+1].head = NULL; loopstack[loopidx+1].tail = &loopstack[loopidx+1].head; loopstack[loopidx+1].current = NULL; loopstack[loopidx+1].nestlevel = 1; loopstack[loopidx+1].oneshot = 0; loopstack[loopidx+1].condition = xstrdup (p); loopstack[loopidx+1].collecting = 1; } } else if (!strcmp (cmd, "if")) { if (loopidx+2 >= (int)DIM(loopstack)) { log_error ("blocks are nested too deep\n"); } else { /* Note that we need to evaluate the condition right away and not just at the end of the block as we do with a WHILE. */ loopstack[loopidx+1].head = NULL; loopstack[loopidx+1].tail = &loopstack[loopidx+1].head; loopstack[loopidx+1].current = NULL; loopstack[loopidx+1].nestlevel = 1; loopstack[loopidx+1].oneshot = 1; loopstack[loopidx+1].condition = substitute_line_copy (p); loopstack[loopidx+1].collecting = 1; } } else if (!strcmp (cmd, "end")) { if (loopidx < 0) log_error ("stray /end command encountered - ignored\n"); else { char *tmpcond; const char *value; long condition; /* Evaluate the condition. */ tmpcond = xstrdup (loopstack[loopidx].condition); if (loopstack[loopidx].oneshot) { xfree (loopstack[loopidx].condition); loopstack[loopidx].condition = xstrdup ("0"); } tmpline = substitute_line (tmpcond); value = tmpline? tmpline : tmpcond; /* "true" or "yes" are commonly used to mean TRUE; all other strings will evaluate to FALSE due to the strtoul. */ if (!ascii_strcasecmp (value, "true") || !ascii_strcasecmp (value, "yes")) condition = 1; else condition = strtol (value, NULL, 0); xfree (tmpline); xfree (tmpcond); if (condition) { /* Run loop. */ loopstack[loopidx].current = loopstack[loopidx].head; } else { /* Cleanup. */ while (loopstack[loopidx].head) { loopline_t tmp = loopstack[loopidx].head->next; xfree (loopstack[loopidx].head); loopstack[loopidx].head = tmp; } loopstack[loopidx].tail = NULL; loopstack[loopidx].current = NULL; loopstack[loopidx].nestlevel = 0; loopstack[loopidx].collecting = 0; loopstack[loopidx].oneshot = 0; xfree (loopstack[loopidx].condition); loopstack[loopidx].condition = NULL; loopidx--; } } } else if (!strcmp (cmd, "bye")) { break; } else if (!strcmp (cmd, "sleep")) { gnupg_sleep (1); } else if (!strcmp (cmd, "help")) { puts ( "Available commands:\n" "/echo ARGS Echo ARGS.\n" "/let NAME VALUE Set variable NAME to VALUE.\n" "/showvar Show all variables.\n" "/definq NAME VAR Use content of VAR for inquiries with NAME.\n" "/definqfile NAME FILE Use content of FILE for inquiries with NAME.\n" "/definqprog NAME PGM Run PGM for inquiries with NAME.\n" "/datafile [NAME] Write all D line content to file NAME.\n" "/showdef Print all definitions.\n" "/cleardef Delete all definitions.\n" "/sendfd FILE MODE Open FILE and pass descriptor to server.\n" "/recvfd Receive FD from server and print.\n" "/open VAR FILE MODE Open FILE and assign the file descriptor to VAR.\n" "/close FD Close file with descriptor FD.\n" "/showopen Show descriptors of all open files.\n" "/serverpid Retrieve the pid of the server.\n" "/[no]hex Enable hex dumping of received data lines.\n" "/[no]decode Enable decoding of received data lines.\n" "/[no]subst Enable variable substitution.\n" "/run FILE Run commands from FILE.\n" "/if VAR Begin conditional block controlled by VAR.\n" "/while VAR Begin loop controlled by VAR.\n" "/end End loop or condition\n" "/bye Terminate gpg-connect-agent.\n" "/help Print this help."); } else log_error (_("unknown command '%s'\n"), cmd ); continue; } if (opt.verbose && script_fp) puts (line); tmpline = opt.enable_varsubst? substitute_line (line) : NULL; if (tmpline) { rc = assuan_write_line (ctx, tmpline); xfree (tmpline); } else rc = assuan_write_line (ctx, line); if (rc) { log_info (_("sending line failed: %s\n"), gpg_strerror (rc) ); break; } if (*line == '#' || !*line) continue; /* Don't expect a response for a comment line. */ rc = read_and_print_response (ctx, help_cmd_p (line), &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); if ((rc || cmderr) && script_fp) { log_error ("stopping script execution\n"); gpgrt_fclose (script_fp); script_fp = NULL; } /* FIXME: If the last command was BYE or the server died for some other reason, we won't notice until we get the next input command. Probing the connection with a non-blocking read could help to notice termination or other problems early. */ } if (opt.verbose) log_info ("closing connection to agent\n"); /* XXX: We would like to release the context here, but libassuan nicely says good bye to the server, which results in a SIGPIPE if the server died. Unfortunately, libassuan does not ignore SIGPIPE when used with UNIX sockets, hence we simply leak the context here. */ if (0) assuan_release (ctx); else gpgrt_annotate_leaked_object (ctx); xfree (line); return 0; } /* Handle an Inquire from the server. Return False if it could not be handled; in this case the caller shll complete the operation. LINE is the complete line as received from the server. This function may change the content of LINE. */ static int handle_inquire (assuan_context_t ctx, char *line) { const char *name; definq_t d; + /* FIXME: Due to the use of popen we can't easily switch to estream. */ FILE *fp = NULL; char buffer[1024]; int rc, n; /* Skip the command and trailing spaces. */ for (; *line && !spacep (line); line++) ; while (spacep (line)) line++; /* Get the name. */ name = line; for (; *line && !spacep (line); line++) ; if (*line) *line++ = 0; /* Now match it against our list. The second loop is there to detect the match-all entry. */ for (d=definq_list; d; d = d->next) if (d->name && !strcmp (d->name, name)) break; if (!d) for (d=definq_list; d; d = d->next) if (!d->name) break; if (!d) { if (opt.verbose) log_info ("no handler for inquiry '%s' found\n", name); return 0; } if (d->is_var) { char *tmpvalue = get_var_ext (d->file); if (tmpvalue) rc = assuan_send_data (ctx, tmpvalue, strlen (tmpvalue)); else rc = assuan_send_data (ctx, "", 0); xfree (tmpvalue); if (rc) log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); } else { if (d->is_prog) { #ifdef HAVE_W32CE_SYSTEM fp = NULL; #else fp = popen (d->file, "r"); #endif if (!fp) log_error ("error executing '%s': %s\n", d->file, strerror (errno)); else if (opt.verbose) log_error ("handling inquiry '%s' by running '%s'\n", name, d->file); } else { fp = fopen (d->file, "rb"); if (!fp) log_error ("error opening '%s': %s\n", d->file, strerror (errno)); else if (opt.verbose) log_error ("handling inquiry '%s' by returning content of '%s'\n", name, d->file); } if (!fp) return 0; while ( (n = fread (buffer, 1, sizeof buffer, fp)) ) { rc = assuan_send_data (ctx, buffer, n); if (rc) { log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); break; } } if (ferror (fp)) log_error ("error reading from '%s': %s\n", d->file, strerror (errno)); } rc = assuan_send_data (ctx, NULL, 0); if (rc) log_error ("sending data back failed: %s\n", gpg_strerror (rc) ); if (d->is_var) ; else if (d->is_prog) { #ifndef HAVE_W32CE_SYSTEM if (pclose (fp)) log_error ("error running '%s': %s\n", d->file, strerror (errno)); #endif } else fclose (fp); return 1; } /* Read all response lines from server and print them. Returns 0 on success or an assuan error code. If WITHHASH istrue, comment lines are printed. Sets R_GOTERR to true if the command did not returned OK. */ static int read_and_print_response (assuan_context_t ctx, int withhash, int *r_goterr) { char *line; size_t linelen; gpg_error_t rc; int i, j; int need_lf = 0; *r_goterr = 0; for (;;) { do { rc = assuan_read_line (ctx, &line, &linelen); if (rc) return rc; if ((withhash || opt.verbose > 1) && *line == '#') { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } while (*line == '#' || !linelen); if (linelen >= 1 && line[0] == 'D' && line[1] == ' ') { if (current_datasink) { const unsigned char *s; int c = 0; for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ ) { if (*s == '%' && j+2 < linelen) { s++; j++; c = xtoi_2 ( s ); s++; j++; } else c = *s; - putc (c, current_datasink); + es_putc (c, current_datasink); } } else if (opt.hex) { for (i=2; i < linelen; ) { int save_i = i; printf ("D[%04X] ", i-2); for (j=0; j < 16 ; j++, i++) { if (j == 8) putchar (' '); if (i < linelen) printf (" %02X", ((unsigned char*)line)[i]); else fputs (" ", stdout); } fputs (" ", stdout); i= save_i; for (j=0; j < 16; j++, i++) { unsigned int c = ((unsigned char*)line)[i]; if ( i >= linelen ) putchar (' '); else if (isascii (c) && isprint (c) && !iscntrl (c)) putchar (c); else putchar ('.'); } putchar ('\n'); } } else if (opt.decode) { const unsigned char *s; int need_d = 1; int c = 0; for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ ) { if (need_d) { fputs ("D ", stdout); need_d = 0; } if (*s == '%' && j+2 < linelen) { s++; j++; c = xtoi_2 ( s ); s++; j++; } else c = *s; if (c == '\n') need_d = 1; putchar (c); } need_lf = (c != '\n'); } else { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } else { if (need_lf) { - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) putchar ('\n'); need_lf = 0; } if (linelen >= 1 && line[0] == 'S' && (line[1] == '\0' || line[1] == ' ')) { - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } } else if (linelen >= 2 && line[0] == 'O' && line[1] == 'K' && (line[2] == '\0' || line[2] == ' ')) { - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } set_int_var ("?", 0); return 0; } else if (linelen >= 3 && line[0] == 'E' && line[1] == 'R' && line[2] == 'R' && (line[3] == '\0' || line[3] == ' ')) { int errval; errval = strtol (line+3, NULL, 10); if (!errval) errval = -1; set_int_var ("?", errval); - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } *r_goterr = 1; return 0; } else if (linelen >= 7 && line[0] == 'I' && line[1] == 'N' && line[2] == 'Q' && line[3] == 'U' && line[4] == 'I' && line[5] == 'R' && line[6] == 'E' && (line[7] == '\0' || line[7] == ' ')) { - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } if (!handle_inquire (ctx, line)) assuan_write_line (ctx, "CANCEL"); } else if (linelen >= 3 && line[0] == 'E' && line[1] == 'N' && line[2] == 'D' && (line[3] == '\0' || line[3] == ' ')) { - if (!current_datasink || current_datasink != stdout) + if (!current_datasink || current_datasink != es_stdout) { fwrite (line, linelen, 1, stdout); putchar ('\n'); } /* Received from server, thus more responses are expected. */ } else return gpg_error (GPG_ERR_ASS_INV_RESPONSE); } } } /* Connect to the agent and send the standard options. */ static assuan_context_t start_agent (void) { gpg_error_t err; assuan_context_t ctx; session_env_t session_env; session_env = session_env_new (); if (!session_env) log_fatal ("error allocating session environment block: %s\n", strerror (errno)); if (opt.use_dirmngr) err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, !opt.quiet, 0, NULL, NULL); else err = start_new_gpg_agent (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, NULL, NULL, session_env, opt.autostart, !opt.quiet, 0, NULL, NULL); session_env_release (session_env); if (err) { if (!opt.autostart && (gpg_err_code (err) == (opt.use_dirmngr? GPG_ERR_NO_DIRMNGR : GPG_ERR_NO_AGENT))) { /* In the no-autostart case we don't make gpg-connect-agent fail on a missing server. */ log_info (opt.use_dirmngr? _("no dirmngr running in this session\n"): _("no gpg-agent running in this session\n")); exit (0); } else { log_error (_("error sending standard options: %s\n"), gpg_strerror (err)); exit (1); } } return ctx; } diff --git a/tools/wks-util.c b/tools/wks-util.c index 9aaa7aaf5..cb1ecdaa2 100644 --- a/tools/wks-util.c +++ b/tools/wks-util.c @@ -1,1232 +1,1232 @@ /* wks-utils.c - Common helper functions for wks tools * Copyright (C) 2016 g10 Code GmbH * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. */ #include #include #include #include #include #include #include #include "../common/util.h" #include "../common/status.h" #include "../common/ccparray.h" #include "../common/exectool.h" #include "../common/zb32.h" #include "../common/userids.h" #include "../common/mbox-util.h" #include "../common/sysutils.h" #include "mime-maker.h" #include "send-mail.h" #include "gpg-wks.h" /* The stream to output the status information. Output is disabled if this is NULL. */ static estream_t statusfp; /* Set the status FD. */ void wks_set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (statusfp && statusfp != es_stdout && statusfp != es_stderr) es_fclose (statusfp); statusfp = NULL; if (fd == -1) return; if (fd == 1) statusfp = es_stdout; else if (fd == 2) statusfp = es_stderr; else statusfp = es_fdopen (fd, "w"); if (!statusfp) { log_fatal ("can't open fd %d for status output: %s\n", fd, gpg_strerror (gpg_error_from_syserror ())); } last_fd = fd; } /* Write a status line with code NO followed by the outout of the * printf style FORMAT. The caller needs to make sure that LFs and * CRs are not printed. */ void wks_write_status (int no, const char *format, ...) { va_list arg_ptr; if (!statusfp) return; /* Not enabled. */ es_fputs ("[GNUPG:] ", statusfp); es_fputs (get_status_string (no), statusfp); if (format) { es_putc (' ', statusfp); va_start (arg_ptr, format); es_vfprintf (statusfp, format, arg_ptr); va_end (arg_ptr); } es_putc ('\n', statusfp); } /* Append UID to LIST and return the new item. On success LIST is * updated. On error ERRNO is set and NULL returned. */ static uidinfo_list_t append_to_uidinfo_list (uidinfo_list_t *list, const char *uid, time_t created) { uidinfo_list_t r, sl; sl = xtrymalloc (sizeof *sl + strlen (uid)); if (!sl) return NULL; strcpy (sl->uid, uid); sl->created = created; sl->mbox = mailbox_from_userid (uid); sl->next = NULL; if (!*list) *list = sl; else { for (r = *list; r->next; r = r->next ) ; r->next = sl; } return sl; } /* Free the list of uid infos at LIST. */ void free_uidinfo_list (uidinfo_list_t list) { while (list) { uidinfo_list_t tmp = list->next; xfree (list->mbox); xfree (list); list = tmp; } } struct get_key_status_parm_s { const char *fpr; int found; int count; }; static void get_key_status_cb (void *opaque, const char *keyword, char *args) { struct get_key_status_parm_s *parm = opaque; /*log_debug ("%s: %s\n", keyword, args);*/ if (!strcmp (keyword, "EXPORTED")) { parm->count++; if (!ascii_strcasecmp (args, parm->fpr)) parm->found = 1; } } /* Get a key by fingerprint from gpg's keyring and make sure that the * mail address ADDRSPEC is included in the key. If EXACT is set the * returned user id must match Addrspec exactly and not just in the * addr-spec (mailbox) part. The key is returned as a new memory * stream at R_KEY. */ gpg_error_t wks_get_key (estream_t *r_key, const char *fingerprint, const char *addrspec, int exact) { gpg_error_t err; ccparray_t ccp; const char **argv = NULL; estream_t key = NULL; struct get_key_status_parm_s parm; char *filterexp = NULL; memset (&parm, 0, sizeof parm); *r_key = NULL; key = es_fopenmem (0, "w+b"); if (!key) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } /* Prefix the key with the MIME content type. */ es_fputs ("Content-Type: application/pgp-keys\n" "\n", key); filterexp = es_bsprintf ("keep-uid=%s= %s", exact? "uid":"mbox", addrspec); if (!filterexp) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } ccparray_init (&ccp, 0); ccparray_put (&ccp, "--no-options"); if (!opt.verbose) ccparray_put (&ccp, "--quiet"); else if (opt.verbose > 1) ccparray_put (&ccp, "--verbose"); ccparray_put (&ccp, "--batch"); ccparray_put (&ccp, "--status-fd=2"); ccparray_put (&ccp, "--always-trust"); ccparray_put (&ccp, "--armor"); ccparray_put (&ccp, "--export-options=export-minimal"); ccparray_put (&ccp, "--export-filter"); ccparray_put (&ccp, filterexp); ccparray_put (&ccp, "--export"); ccparray_put (&ccp, "--"); ccparray_put (&ccp, fingerprint); ccparray_put (&ccp, NULL); argv = ccparray_get (&ccp, NULL); if (!argv) { err = gpg_error_from_syserror (); goto leave; } parm.fpr = fingerprint; err = gnupg_exec_tool_stream (opt.gpg_program, argv, NULL, NULL, key, get_key_status_cb, &parm); if (!err && parm.count > 1) err = gpg_error (GPG_ERR_TOO_MANY); else if (!err && !parm.found) err = gpg_error (GPG_ERR_NOT_FOUND); if (err) { log_error ("export failed: %s\n", gpg_strerror (err)); goto leave; } es_rewind (key); *r_key = key; key = NULL; leave: es_fclose (key); xfree (argv); xfree (filterexp); return err; } /* Helper for wks_list_key and wks_filter_uid. */ static void key_status_cb (void *opaque, const char *keyword, char *args) { (void)opaque; if (DBG_CRYPTO) log_debug ("gpg status: %s %s\n", keyword, args); } /* Run gpg on KEY and store the primary fingerprint at R_FPR and the * list of mailboxes at R_MBOXES. Returns 0 on success; on error NULL * is stored at R_FPR and R_MBOXES and an error code is returned. * R_FPR may be NULL if the fingerprint is not needed. */ gpg_error_t wks_list_key (estream_t key, char **r_fpr, uidinfo_list_t *r_mboxes) { gpg_error_t err; ccparray_t ccp; const char **argv; estream_t listing; char *line = NULL; size_t length_of_line = 0; size_t maxlen; ssize_t len; char **fields = NULL; int nfields; int lnr; char *fpr = NULL; uidinfo_list_t mboxes = NULL; if (r_fpr) *r_fpr = NULL; *r_mboxes = NULL; /* Open a memory stream. */ listing = es_fopenmem (0, "w+b"); if (!listing) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); return err; } ccparray_init (&ccp, 0); ccparray_put (&ccp, "--no-options"); if (!opt.verbose) ccparray_put (&ccp, "--quiet"); else if (opt.verbose > 1) ccparray_put (&ccp, "--verbose"); ccparray_put (&ccp, "--batch"); ccparray_put (&ccp, "--status-fd=2"); ccparray_put (&ccp, "--always-trust"); ccparray_put (&ccp, "--with-colons"); ccparray_put (&ccp, "--dry-run"); ccparray_put (&ccp, "--import-options=import-minimal,import-show"); ccparray_put (&ccp, "--import"); ccparray_put (&ccp, NULL); argv = ccparray_get (&ccp, NULL); if (!argv) { err = gpg_error_from_syserror (); goto leave; } err = gnupg_exec_tool_stream (opt.gpg_program, argv, key, NULL, listing, key_status_cb, NULL); if (err) { log_error ("import failed: %s\n", gpg_strerror (err)); goto leave; } es_rewind (listing); lnr = 0; maxlen = 2048; /* Set limit. */ while ((len = es_read_line (listing, &line, &length_of_line, &maxlen)) > 0) { lnr++; if (!maxlen) { log_error ("received line too long\n"); err = gpg_error (GPG_ERR_LINE_TOO_LONG); goto leave; } /* Strip newline and carriage return, if present. */ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; /* log_debug ("line '%s'\n", line); */ xfree (fields); fields = strtokenize (line, ":"); if (!fields) { err = gpg_error_from_syserror (); log_error ("strtokenize failed: %s\n", gpg_strerror (err)); goto leave; } for (nfields = 0; fields[nfields]; nfields++) ; if (!nfields) { err = gpg_error (GPG_ERR_INV_ENGINE); goto leave; } if (!strcmp (fields[0], "sec")) { /* gpg may return "sec" as the first record - but we do not * accept secret keys. */ err = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } if (lnr == 1 && strcmp (fields[0], "pub")) { /* First record is not a public key. */ err = gpg_error (GPG_ERR_INV_ENGINE); goto leave; } if (lnr > 1 && !strcmp (fields[0], "pub")) { /* More than one public key. */ err = gpg_error (GPG_ERR_TOO_MANY); goto leave; } if (!strcmp (fields[0], "sub") || !strcmp (fields[0], "ssb")) break; /* We can stop parsing here. */ if (!strcmp (fields[0], "fpr") && nfields > 9 && !fpr) { fpr = xtrystrdup (fields[9]); if (!fpr) { err = gpg_error_from_syserror (); goto leave; } } else if (!strcmp (fields[0], "uid") && nfields > 9) { /* Fixme: Unescape fields[9] */ if (!append_to_uidinfo_list (&mboxes, fields[9], parse_timestamp (fields[5], NULL))) { err = gpg_error_from_syserror (); goto leave; } } } if (len < 0 || es_ferror (listing)) { err = gpg_error_from_syserror (); log_error ("error reading memory stream\n"); goto leave; } if (!fpr) { err = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } if (r_fpr) { *r_fpr = fpr; fpr = NULL; } *r_mboxes = mboxes; mboxes = NULL; leave: xfree (fpr); free_uidinfo_list (mboxes); xfree (fields); es_free (line); xfree (argv); es_fclose (listing); return err; } /* Run gpg as a filter on KEY and write the output to a new stream * stored at R_NEWKEY. The new key will contain only the user id UID. * Returns 0 on success. Only one key is expected in KEY. If BINARY * is set the resulting key is returned as a binary (non-armored) * keyblock. */ gpg_error_t wks_filter_uid (estream_t *r_newkey, estream_t key, const char *uid, int binary) { gpg_error_t err; ccparray_t ccp; const char **argv = NULL; estream_t newkey; char *filterexp = NULL; *r_newkey = NULL; /* Open a memory stream. */ newkey = es_fopenmem (0, "w+b"); if (!newkey) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); return err; } /* Prefix the key with the MIME content type. */ if (!binary) es_fputs ("Content-Type: application/pgp-keys\n" "\n", newkey); filterexp = es_bsprintf ("keep-uid=uid= %s", uid); if (!filterexp) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } ccparray_init (&ccp, 0); ccparray_put (&ccp, "--no-options"); if (!opt.verbose) ccparray_put (&ccp, "--quiet"); else if (opt.verbose > 1) ccparray_put (&ccp, "--verbose"); ccparray_put (&ccp, "--batch"); ccparray_put (&ccp, "--status-fd=2"); ccparray_put (&ccp, "--always-trust"); if (!binary) ccparray_put (&ccp, "--armor"); ccparray_put (&ccp, "--import-options=import-export"); ccparray_put (&ccp, "--import-filter"); ccparray_put (&ccp, filterexp); ccparray_put (&ccp, "--import"); ccparray_put (&ccp, NULL); argv = ccparray_get (&ccp, NULL); if (!argv) { err = gpg_error_from_syserror (); goto leave; } err = gnupg_exec_tool_stream (opt.gpg_program, argv, key, NULL, newkey, key_status_cb, NULL); if (err) { log_error ("import/export failed: %s\n", gpg_strerror (err)); goto leave; } es_rewind (newkey); *r_newkey = newkey; newkey = NULL; leave: xfree (filterexp); xfree (argv); es_fclose (newkey); return err; } /* Helper to write mail to the output(s). */ gpg_error_t wks_send_mime (mime_maker_t mime) { gpg_error_t err; estream_t mail; /* Without any option we take a short path. */ if (!opt.use_sendmail && !opt.output) { es_set_binary (es_stdout); return mime_maker_make (mime, es_stdout); } mail = es_fopenmem (0, "w+b"); if (!mail) { err = gpg_error_from_syserror (); return err; } err = mime_maker_make (mime, mail); if (!err && opt.output) { es_rewind (mail); err = send_mail_to_file (mail, opt.output); } if (!err && opt.use_sendmail) { es_rewind (mail); err = send_mail (mail); } es_fclose (mail); return err; } /* Parse the policy flags by reading them from STREAM and storing them * into FLAGS. If IGNORE_UNKNOWN is set unknown keywords are * ignored. */ gpg_error_t wks_parse_policy (policy_flags_t flags, estream_t stream, int ignore_unknown) { enum tokens { TOK_SUBMISSION_ADDRESS, TOK_MAILBOX_ONLY, TOK_DANE_ONLY, TOK_AUTH_SUBMIT, TOK_MAX_PENDING, TOK_PROTOCOL_VERSION }; static struct { const char *name; enum tokens token; } keywords[] = { { "submission-address", TOK_SUBMISSION_ADDRESS }, { "mailbox-only", TOK_MAILBOX_ONLY }, { "dane-only", TOK_DANE_ONLY }, { "auth-submit", TOK_AUTH_SUBMIT }, { "max-pending", TOK_MAX_PENDING }, { "protocol-version", TOK_PROTOCOL_VERSION } }; gpg_error_t err = 0; int lnr = 0; char line[1024]; char *p, *keyword, *value; int i, n; memset (flags, 0, sizeof *flags); while (es_fgets (line, DIM(line)-1, stream) ) { lnr++; n = strlen (line); if (!n || line[n-1] != '\n') { err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG : GPG_ERR_INCOMPLETE_LINE); break; } trim_trailing_spaces (line); /* Skip empty and comment lines. */ for (p=line; spacep (p); p++) ; if (!*p || *p == '#') continue; if (*p == ':') { err = gpg_error (GPG_ERR_SYNTAX); break; } keyword = p; value = NULL; if ((p = strchr (p, ':'))) { /* Colon found: Keyword with value. */ *p++ = 0; for (; spacep (p); p++) ; if (!*p) { err = gpg_error (GPG_ERR_MISSING_VALUE); break; } value = p; } for (i=0; i < DIM (keywords); i++) if (!ascii_strcasecmp (keywords[i].name, keyword)) break; if (!(i < DIM (keywords))) { if (ignore_unknown) continue; err = gpg_error (GPG_ERR_INV_NAME); break; } switch (keywords[i].token) { case TOK_SUBMISSION_ADDRESS: if (!value || !*value) { err = gpg_error (GPG_ERR_SYNTAX); goto leave; } xfree (flags->submission_address); flags->submission_address = xtrystrdup (value); if (!flags->submission_address) { err = gpg_error_from_syserror (); goto leave; } break; case TOK_MAILBOX_ONLY: flags->mailbox_only = 1; break; case TOK_DANE_ONLY: flags->dane_only = 1; break; case TOK_AUTH_SUBMIT: flags->auth_submit = 1; break; case TOK_MAX_PENDING: if (!value) { err = gpg_error (GPG_ERR_SYNTAX); goto leave; } /* FIXME: Define whether these are seconds, hours, or days * and decide whether to allow other units. */ flags->max_pending = atoi (value); break; case TOK_PROTOCOL_VERSION: if (!value) { err = gpg_error (GPG_ERR_SYNTAX); goto leave; } flags->protocol_version = atoi (value); break; } } if (!err && !es_feof (stream)) err = gpg_error_from_syserror (); leave: if (err) log_error ("error reading '%s', line %d: %s\n", es_fname_get (stream), lnr, gpg_strerror (err)); return err; } void wks_free_policy (policy_flags_t policy) { if (policy) { xfree (policy->submission_address); memset (policy, 0, sizeof *policy); } } /* Write the content of SRC to the new file FNAME. */ static gpg_error_t write_to_file (estream_t src, const char *fname) { gpg_error_t err; estream_t dst; char buffer[4096]; size_t nread, written; dst = es_fopen (fname, "wb"); if (!dst) return gpg_error_from_syserror (); do { nread = es_fread (buffer, 1, sizeof buffer, src); if (!nread) break; written = es_fwrite (buffer, 1, nread, dst); if (written != nread) break; } while (!es_feof (src) && !es_ferror (src) && !es_ferror (dst)); if (!es_feof (src) || es_ferror (src) || es_ferror (dst)) { err = gpg_error_from_syserror (); es_fclose (dst); gnupg_remove (fname); return err; } if (es_fclose (dst)) { err = gpg_error_from_syserror (); log_error ("error closing '%s': %s\n", fname, gpg_strerror (err)); return err; } return 0; } /* Return the filename and optionally the addrspec for USERID at * R_FNAME and R_ADDRSPEC. R_ADDRSPEC might also be set on error. If * HASH_ONLY is set only the has is returned at R_FNAME and no file is * created. */ gpg_error_t wks_fname_from_userid (const char *userid, int hash_only, char **r_fname, char **r_addrspec) { gpg_error_t err; char *addrspec = NULL; const char *domain; char *hash = NULL; const char *s; char shaxbuf[32]; /* Used for SHA-1 and SHA-256 */ *r_fname = NULL; if (r_addrspec) *r_addrspec = NULL; addrspec = mailbox_from_userid (userid); if (!addrspec) { if (opt.verbose || hash_only) log_info ("\"%s\" is not a proper mail address\n", userid); err = gpg_error (GPG_ERR_INV_USER_ID); goto leave; } domain = strchr (addrspec, '@'); log_assert (domain); domain++; /* Hash user ID and create filename. */ s = strchr (addrspec, '@'); log_assert (s); gcry_md_hash_buffer (GCRY_MD_SHA1, shaxbuf, addrspec, s - addrspec); hash = zb32_encode (shaxbuf, 8*20); if (!hash) { err = gpg_error_from_syserror (); goto leave; } if (hash_only) { *r_fname = hash; hash = NULL; err = 0; } else { *r_fname = make_filename_try (opt.directory, domain, "hu", hash, NULL); if (!*r_fname) err = gpg_error_from_syserror (); else err = 0; } leave: if (r_addrspec && addrspec) *r_addrspec = addrspec; else xfree (addrspec); xfree (hash); return err; } /* Compute the the full file name for the key with ADDRSPEC and return * it at R_FNAME. */ gpg_error_t wks_compute_hu_fname (char **r_fname, const char *addrspec) { gpg_error_t err; char *hash; const char *domain; char sha1buf[20]; char *fname; struct stat sb; *r_fname = NULL; domain = strchr (addrspec, '@'); if (!domain || !domain[1] || domain == addrspec) return gpg_error (GPG_ERR_INV_ARG); domain++; gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, addrspec, domain - addrspec - 1); hash = zb32_encode (sha1buf, 8*20); if (!hash) return gpg_error_from_syserror (); /* Try to create missing directories below opt.directory. */ fname = make_filename_try (opt.directory, domain, NULL); if (fname && stat (fname, &sb) && gpg_err_code_from_syserror () == GPG_ERR_ENOENT) if (!gnupg_mkdir (fname, "-rwxr--r--") && opt.verbose) log_info ("directory '%s' created\n", fname); xfree (fname); fname = make_filename_try (opt.directory, domain, "hu", NULL); if (fname && stat (fname, &sb) && gpg_err_code_from_syserror () == GPG_ERR_ENOENT) if (!gnupg_mkdir (fname, "-rwxr--r--") && opt.verbose) log_info ("directory '%s' created\n", fname); xfree (fname); /* Create the filename. */ fname = make_filename_try (opt.directory, domain, "hu", hash, NULL); err = fname? 0 : gpg_error_from_syserror (); if (err) xfree (fname); else *r_fname = fname; /* Okay. */ xfree (hash); return err; } /* Make sure that a policy file exists for addrspec. Directories must * already exist. */ static gpg_error_t ensure_policy_file (const char *addrspec) { gpg_err_code_t ec; gpg_error_t err; const char *domain; char *fname; estream_t fp; domain = strchr (addrspec, '@'); if (!domain || !domain[1] || domain == addrspec) return gpg_error (GPG_ERR_INV_ARG); domain++; /* Create the filename. */ fname = make_filename_try (opt.directory, domain, "policy", NULL); err = fname? 0 : gpg_error_from_syserror (); if (err) goto leave; /* First a quick check whether it already exists. */ if (!(ec = gnupg_access (fname, F_OK))) { err = 0; /* File already exists. */ goto leave; } err = gpg_error (ec); if (gpg_err_code (err) == GPG_ERR_ENOENT) err = 0; else { log_error ("domain %s: problem with '%s': %s\n", domain, fname, gpg_strerror (err)); goto leave; } /* Now create the file. */ fp = es_fopen (fname, "wxb"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_EEXIST) - err = 0; /* Was created between the access() and fopen(). */ + err = 0; /* Was created between the gnupg_access() and es_fopen(). */ else log_error ("domain %s: error creating '%s': %s\n", domain, fname, gpg_strerror (err)); goto leave; } es_fprintf (fp, "# Policy flags for domain %s\n", domain); if (es_ferror (fp) || es_fclose (fp)) { err = gpg_error_from_syserror (); log_error ("error writing '%s': %s\n", fname, gpg_strerror (err)); goto leave; } if (opt.verbose) log_info ("policy file '%s' created\n", fname); /* Make sure the policy file world readable. */ if (gnupg_chmod (fname, "-rw-rw-r--")) { err = gpg_error_from_syserror (); log_error ("can't set permissions of '%s': %s\n", fname, gpg_strerror (err)); goto leave; } leave: xfree (fname); return err; } /* Helper form wks_cmd_install_key. */ static gpg_error_t install_key_from_spec_file (const char *fname) { gpg_error_t err; estream_t fp; char *line = NULL; size_t linelen = 0; size_t maxlen = 2048; char *fields[2]; unsigned int lnr = 0; if (!fname || !strcmp (fname, "")) fp = es_stdin; else fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } while (es_read_line (fp, &line, &linelen, &maxlen) > 0) { if (!maxlen) { err = gpg_error (GPG_ERR_LINE_TOO_LONG); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } lnr++; trim_spaces (line); if (!*line || *line == '#') continue; if (split_fields (line, fields, DIM(fields)) < 2) { log_error ("error reading '%s': syntax error at line %u\n", fname, lnr); continue; } err = wks_cmd_install_key (fields[0], fields[1]); if (err) goto leave; } if (es_ferror (fp)) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } leave: if (fp != es_stdin) es_fclose (fp); es_free (line); return err; } /* Install a single key into the WKD by reading FNAME and extracting * USERID. If USERID is NULL FNAME is expected to be a list of fpr * mbox lines and for each line the respective key will be * installed. */ gpg_error_t wks_cmd_install_key (const char *fname, const char *userid) { gpg_error_t err; KEYDB_SEARCH_DESC desc; estream_t fp = NULL; char *addrspec = NULL; char *fpr = NULL; uidinfo_list_t uidlist = NULL; uidinfo_list_t uid, thisuid; time_t thistime; char *huname = NULL; int any; if (!userid) return install_key_from_spec_file (fname); addrspec = mailbox_from_userid (userid); if (!addrspec) { log_error ("\"%s\" is not a proper mail address\n", userid); err = gpg_error (GPG_ERR_INV_USER_ID); goto leave; } if (!classify_user_id (fname, &desc, 1) && (desc.mode == KEYDB_SEARCH_MODE_FPR || desc.mode == KEYDB_SEARCH_MODE_FPR20)) { /* FNAME looks like a fingerprint. Get the key from the * standard keyring. */ err = wks_get_key (&fp, fname, addrspec, 0); if (err) { log_error ("error getting key '%s' (uid='%s'): %s\n", fname, addrspec, gpg_strerror (err)); goto leave; } } else /* Take it from the file */ { fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } } /* List the key so that we can figure out the newest UID with the * requested addrspec. */ err = wks_list_key (fp, &fpr, &uidlist); if (err) { log_error ("error parsing key: %s\n", gpg_strerror (err)); err = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } thistime = 0; thisuid = NULL; any = 0; for (uid = uidlist; uid; uid = uid->next) { if (!uid->mbox) continue; /* Should not happen anyway. */ if (ascii_strcasecmp (uid->mbox, addrspec)) continue; /* Not the requested addrspec. */ any = 1; if (uid->created > thistime) { thistime = uid->created; thisuid = uid; } } if (!thisuid) thisuid = uidlist; /* This is the case for a missing timestamp. */ if (!any) { log_error ("public key in '%s' has no mail address '%s'\n", fname, addrspec); err = gpg_error (GPG_ERR_INV_USER_ID); goto leave; } if (opt.verbose) log_info ("using key with user id '%s'\n", thisuid->uid); { estream_t fp2; es_rewind (fp); err = wks_filter_uid (&fp2, fp, thisuid->uid, 1); if (err) { log_error ("error filtering key: %s\n", gpg_strerror (err)); err = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } es_fclose (fp); fp = fp2; } /* Hash user ID and create filename. */ err = wks_compute_hu_fname (&huname, addrspec); if (err) goto leave; /* Now that wks_compute_hu_fname has created missing directories we * can create a policy file if it does not exist. */ err = ensure_policy_file (addrspec); if (err) goto leave; /* Publish. */ err = write_to_file (fp, huname); if (err) { log_error ("copying key to '%s' failed: %s\n", huname,gpg_strerror (err)); goto leave; } /* Make sure it is world readable. */ if (gnupg_chmod (huname, "-rwxr--r--")) log_error ("can't set permissions of '%s': %s\n", huname, gpg_strerror (gpg_err_code_from_syserror())); if (!opt.quiet) log_info ("key %s published for '%s'\n", fpr, addrspec); leave: xfree (huname); free_uidinfo_list (uidlist); xfree (fpr); xfree (addrspec); es_fclose (fp); return err; } /* Remove the key with mail address in USERID. */ gpg_error_t wks_cmd_remove_key (const char *userid) { gpg_error_t err; char *addrspec = NULL; char *fname = NULL; err = wks_fname_from_userid (userid, 0, &fname, &addrspec); if (err) goto leave; if (gnupg_remove (fname)) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOENT) { if (!opt.quiet) log_info ("key for '%s' is not installed\n", addrspec); log_inc_errorcount (); err = 0; } else log_error ("error removing '%s': %s\n", fname, gpg_strerror (err)); goto leave; } if (opt.verbose) log_info ("key for '%s' removed\n", addrspec); err = 0; leave: xfree (fname); xfree (addrspec); return err; } /* Print the WKD hash for the user id to stdout. */ gpg_error_t wks_cmd_print_wkd_hash (const char *userid) { gpg_error_t err; char *addrspec, *fname; err = wks_fname_from_userid (userid, 1, &fname, &addrspec); if (err) return err; es_printf ("%s %s\n", fname, addrspec); xfree (fname); xfree (addrspec); return err; } /* Print the WKD URL for the user id to stdout. */ gpg_error_t wks_cmd_print_wkd_url (const char *userid) { gpg_error_t err; char *addrspec, *fname; char *domain; err = wks_fname_from_userid (userid, 1, &fname, &addrspec); if (err) return err; domain = strchr (addrspec, '@'); if (domain) *domain++ = 0; es_printf ("https://openpgpkey.%s/.well-known/openpgpkey/%s/hu/%s?l=%s\n", domain, domain, fname, addrspec); xfree (fname); xfree (addrspec); return err; }