diff --git a/agent/command-ssh.c b/agent/command-ssh.c index 9081f6f89..ee9270491 100644 --- a/agent/command-ssh.c +++ b/agent/command-ssh.c @@ -1,3769 +1,3769 @@ /* 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 #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); struct peer_info_s { unsigned long pid; int uid; }; /* 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; log_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 both 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 & 1) && *data == 0x40) { /* 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. */ /* For now, it's only Ed25519. In future, Ed448 will come. */ curve_name = "Ed25519"; 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; } err = sexp_key_construct (&key, spec, secret, curve_name, mpi_list, comment? comment:""); if (!err) { 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; } /* Check whether a key of KEYGRIP on 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, const struct card_key_info_s *keyinfo, gcry_sexp_t *r_pk, char **cardsn) { gpg_error_t err; unsigned char *pkbuf; size_t pkbuflen; gcry_sexp_t s_pk; unsigned char grip[20]; *r_pk = NULL; if (cardsn) *cardsn = NULL; /* Read the public key. */ err = agent_card_readkey (ctrl, keyinfo->keygrip, &pkbuf, NULL); if (err) { if (opt.verbose) log_info (_("no suitable card key found: %s\n"), gpg_strerror (err)); 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); return err; } hex2bin (keyinfo->keygrip, grip, sizeof (grip)); if ( agent_key_available (grip) ) { /* (Shadow)-key is not available in our key storage. */ err = agent_write_shadow_key (grip, keyinfo->serialno, keyinfo->idstr, pkbuf, 0); if (err) { xfree (pkbuf); gcry_sexp_release (s_pk); 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, keyinfo->keygrip)) { *cardsn = xtryasprintf ("cardno:%s", dispsn); xfree (dispsn); } else *cardsn = xtryasprintf ("cardno:%s", keyinfo->serialno); if (!*cardsn) { err = gpg_error_from_syserror (); xfree (pkbuf); gcry_sexp_release (s_pk); return err; } } xfree (pkbuf); *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_daemon[DAEMON_SCD]) { char *serialno; struct card_key_info_s *keyinfo_list; struct card_key_info_s *keyinfo; /* Scan device(s), and get list of KEYGRIP. */ err = agent_card_serialno (ctrl, &serialno, NULL); if (!err) { xfree (serialno); err = agent_card_keyinfo (ctrl, NULL, GCRY_PK_USAGE_AUTH, &keyinfo_list); } if (err) { if (opt.verbose) log_info (_("error getting list of cards: %s\n"), gpg_strerror (err)); goto scd_out; } for (keyinfo = keyinfo_list; keyinfo; keyinfo = keyinfo->next) { char *cardsn; if (card_key_available (ctrl, keyinfo, &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) { agent_card_free_keyinfo (keyinfo_list); goto out; } key_counter++; } agent_card_free_keyinfo (keyinfo_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; log_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 release 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; xfree (ctrl->digest.data); ctrl->digest.data = NULL; ctrl->digest.is_pss = 0; 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, NULL, NULL, 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 void get_client_info (int fd, struct peer_info_s *out) { pid_t client_pid = (pid_t)(-1); int client_uid = -1; #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; client_uid = (int)cr.uid; #elif defined (HAVE_STRUCT_UCRED_CR_PID) client_pid = cr.cr_pid; client_uid = (int)cr.cr_uid; #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); #if defined (LOCAL_PEERCRED) { struct xucred cr; len = sizeof (struct xucred); if (!getsockopt (fd, SOL_LOCAL, LOCAL_PEERCRED, &cr, &len)) client_uid = (int)cr.cr_uid; } #endif } #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; client_uid = (int)unp.unp_euid; } } #elif defined (HAVE_GETPEERUCRED) { ucred_t *ucred = NULL; if (getpeerucred (fd, &ucred) != -1) { client_pid = ucred_getpid (ucred); client_uid = (int)ucred_geteuid (ucred); ucred_free (ucred); } } #else (void)fd; #endif out->pid = (client_pid == (pid_t)(-1)? 0 : (unsigned long)client_pid); out->uid = client_uid; } /* 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; struct peer_info_s peer_info; err = agent_copy_startup_env (ctrl); if (err) goto out; get_client_info (FD2INT(sock_client), &peer_info); ctrl->client_pid = peer_info.pid; ctrl->client_uid = peer_info.uid; /* 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 daemon in case it has been used. */ agent_reset_daemon (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 daemon in case it has been used. */ agent_reset_daemon (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/common/sysutils.c b/common/sysutils.c index 99bc021f5..6738da108 100644 --- a/common/sysutils.c +++ b/common/sysutils.c @@ -1,1464 +1,1466 @@ /* sysutils.c - system helpers * Copyright (C) 1991-2001, 2003-2004, * 2006-2008 Free Software Foundation, Inc. * Copyright (C) 2013-2016 Werner Koch * * 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 #ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth. */ # undef HAVE_NPTH # undef USE_NPTH #endif #include #include #include #include #include #include #include #include #ifdef HAVE_STAT # include #endif #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2 # include # include #endif #include #ifdef HAVE_SETRLIMIT # include # include #endif #ifdef HAVE_PWD_H # include # include #endif /*HAVE_PWD_H*/ #ifdef HAVE_W32_SYSTEM # if WINVER < 0x0500 # define WINVER 0x0500 /* Required for AllowSetForegroundWindow. */ # endif # ifdef HAVE_WINSOCK2_H # include # endif # include #else /*!HAVE_W32_SYSTEM*/ # include # include #endif #ifdef HAVE_INOTIFY_INIT # include #endif /*HAVE_INOTIFY_INIT*/ #ifdef HAVE_NPTH # include #endif #include #include #include "util.h" #include "i18n.h" #include "sysutils.h" #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) /* Flag to tell whether special file names are enabled. See gpg.c for * an explanation of these file names. */ static int allow_special_filenames; #ifdef HAVE_W32_SYSTEM /* State of gnupg_inhibit_set_foregound_window. */ static int inhibit_set_foregound_window; #endif static GPGRT_INLINE gpg_error_t my_error_from_syserror (void) { return gpg_err_make (default_errsource, gpg_err_code_from_syserror ()); } static GPGRT_INLINE gpg_error_t my_error (int e) { return gpg_err_make (default_errsource, (e)); } #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2 #warning using trap_unaligned static int setsysinfo(unsigned long op, void *buffer, unsigned long size, int *start, void *arg, unsigned long flag) { return syscall(__NR_osf_setsysinfo, op, buffer, size, start, arg, flag); } void trap_unaligned(void) { unsigned int buf[2]; buf[0] = SSIN_UACPROC; buf[1] = UAC_SIGBUS | UAC_NOPRINT; setsysinfo(SSI_NVPAIRS, buf, 1, 0, 0, 0); } #else void trap_unaligned(void) { /* dummy */ } #endif int disable_core_dumps (void) { #ifdef HAVE_DOSISH_SYSTEM return 0; #else # ifdef HAVE_SETRLIMIT struct rlimit limit; /* We only set the current limit unless we were not able to retrieve the old value. */ if (getrlimit (RLIMIT_CORE, &limit)) limit.rlim_max = 0; limit.rlim_cur = 0; if( !setrlimit (RLIMIT_CORE, &limit) ) return 0; if( errno != EINVAL && errno != ENOSYS ) log_fatal (_("can't disable core dumps: %s\n"), strerror(errno) ); #endif return 1; #endif } int enable_core_dumps (void) { #ifdef HAVE_DOSISH_SYSTEM return 0; #else # ifdef HAVE_SETRLIMIT struct rlimit limit; if (getrlimit (RLIMIT_CORE, &limit)) return 1; limit.rlim_cur = limit.rlim_max; setrlimit (RLIMIT_CORE, &limit); return 1; /* We always return true because this function is merely a debugging aid. */ # endif return 1; #endif } /* Allow the use of special "-&nnn" style file names. */ void enable_special_filenames (void) { allow_special_filenames = 1; } /* Return a string which is used as a kind of process ID. */ const byte * get_session_marker (size_t *rlen) { static byte marker[SIZEOF_UNSIGNED_LONG*2]; static int initialized; if (!initialized) { gcry_create_nonce (marker, sizeof marker); initialized = 1; } *rlen = sizeof (marker); return marker; } /* Return a random number in an unsigned int. */ unsigned int get_uint_nonce (void) { unsigned int value; gcry_create_nonce (&value, sizeof value); return value; } #if 0 /* not yet needed - Note that this will require inclusion of cmacros.am in Makefile.am */ int check_permissions(const char *path,int extension,int checkonly) { #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM) char *tmppath; struct stat statbuf; int ret=1; int isdir=0; if(opt.no_perm_warn) return 0; if(extension && path[0]!=DIRSEP_C) { if(strchr(path,DIRSEP_C)) tmppath=make_filename(path,NULL); else tmppath=make_filename(GNUPG_LIBDIR,path,NULL); } else tmppath=m_strdup(path); /* It's okay if the file doesn't exist */ if(stat(tmppath,&statbuf)!=0) { ret=0; goto end; } isdir=S_ISDIR(statbuf.st_mode); /* Per-user files must be owned by the user. Extensions must be owned by the user or root. */ if((!extension && statbuf.st_uid != getuid()) || (extension && statbuf.st_uid!=0 && statbuf.st_uid!=getuid())) { if(!checkonly) log_info(_("Warning: unsafe ownership on %s \"%s\"\n"), isdir?"directory":extension?"extension":"file",path); goto end; } /* This works for both directories and files - basically, we don't care what the owner permissions are, so long as the group and other permissions are 0 for per-user files, and non-writable for extensions. */ if((extension && (statbuf.st_mode & (S_IWGRP|S_IWOTH)) !=0) || (!extension && (statbuf.st_mode & (S_IRWXG|S_IRWXO)) != 0)) { char *dir; /* However, if the directory the directory/file is in is owned by the user and is 700, then this is not a problem. Theoretically, we could walk this test up to the root directory /, but for the sake of sanity, I'm stopping at one level down. */ dir= make_dirname (tmppath); if(stat(dir,&statbuf)==0 && statbuf.st_uid==getuid() && S_ISDIR(statbuf.st_mode) && (statbuf.st_mode & (S_IRWXG|S_IRWXO))==0) { xfree (dir); ret=0; goto end; } m_free(dir); if(!checkonly) log_info(_("Warning: unsafe permissions on %s \"%s\"\n"), isdir?"directory":extension?"extension":"file",path); goto end; } ret=0; end: m_free(tmppath); return ret; #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */ return 0; } #endif /* Wrapper around the usual sleep function. This one won't wake up before the sleep time has really elapsed. When build with Pth it merely calls pth_sleep and thus suspends only the current thread. */ void gnupg_sleep (unsigned int seconds) { #ifdef USE_NPTH npth_sleep (seconds); #else /* Fixme: make sure that a sleep won't wake up to early. */ # ifdef HAVE_W32_SYSTEM Sleep (seconds*1000); # else sleep (seconds); # endif #endif } /* Wrapper around the platforms usleep function. This one won't wake * up before the sleep time has really elapsed. When build with nPth * it merely calls npth_usleep and thus suspends only the current * thread. */ void gnupg_usleep (unsigned int usecs) { #if defined(USE_NPTH) npth_usleep (usecs); #elif defined(HAVE_W32_SYSTEM) Sleep ((usecs + 999) / 1000); #elif defined(HAVE_NANOSLEEP) if (usecs) { struct timespec req; struct timespec rem; req.tv_sec = usecs / 1000000; req.tv_nsec = (usecs % 1000000) * 1000; while (nanosleep (&req, &rem) < 0 && errno == EINTR) req = rem; } #else /*Standard Unix*/ if (usecs) { struct timeval tv; tv.tv_sec = usecs / 1000000; tv.tv_usec = usecs % 1000000; select (0, NULL, NULL, NULL, &tv); } #endif } /* This function is a NOP for POSIX systems but required under Windows as the file handles as returned by OS calls (like CreateFile) are different from the libc file descriptors (like open). This function translates system file handles to libc file handles. FOR_WRITE gives the direction of the handle. */ int translate_sys2libc_fd (gnupg_fd_t fd, int for_write) { #if defined(HAVE_W32CE_SYSTEM) (void)for_write; return (int) fd; #elif defined(HAVE_W32_SYSTEM) int x; if (fd == GNUPG_INVALID_FD) return -1; /* Note that _open_osfhandle is currently defined to take and return a long. */ x = _open_osfhandle ((intptr_t)fd, for_write ? 1 : 0); if (x == -1) log_error ("failed to translate osfhandle %p\n", (void *) fd); return x; #else /*!HAVE_W32_SYSTEM */ (void)for_write; return fd; #endif } /* This is the same as translate_sys2libc_fd but takes an integer which is assumed to be such an system handle. On WindowsCE the passed FD is a rendezvous ID and the function finishes the pipe creation. */ int translate_sys2libc_fd_int (int fd, int for_write) { #if HAVE_W32CE_SYSTEM fd = (int) _assuan_w32ce_finish_pipe (fd, for_write); return translate_sys2libc_fd ((void*)fd, for_write); #elif HAVE_W32_SYSTEM if (fd <= 2) return fd; /* Do not do this for error, stdin, stdout, stderr. */ return translate_sys2libc_fd ((void*)fd, for_write); #else (void)for_write; return fd; #endif } /* Check whether FNAME has the form "-&nnnn", where N is a non-zero * number. Returns this number or -1 if it is not the case. If the * caller wants to use the file descriptor for writing FOR_WRITE shall * be set to 1. If NOTRANSLATE is set the Windows specific mapping is * not done. */ int check_special_filename (const char *fname, int for_write, int notranslate) { if (allow_special_filenames && fname && *fname == '-' && fname[1] == '&') { int i; fname += 2; for (i=0; digitp (fname+i); i++ ) ; if (!fname[i]) return notranslate? atoi (fname) /**/ : translate_sys2libc_fd_int (atoi (fname), for_write); } return -1; } /* Replacement for tmpfile(). This is required because the tmpfile function of Windows' runtime library is broken, insecure, ignores TMPDIR and so on. In addition we create a file with an inheritable handle. */ FILE * gnupg_tmpfile (void) { #ifdef HAVE_W32_SYSTEM int attempts, n; #ifdef HAVE_W32CE_SYSTEM wchar_t buffer[MAX_PATH+7+12+1]; # define mystrlen(a) wcslen (a) wchar_t *name, *p; #else char buffer[MAX_PATH+7+12+1]; # define mystrlen(a) strlen (a) char *name, *p; #endif HANDLE file; int pid = GetCurrentProcessId (); unsigned int value; int i; SECURITY_ATTRIBUTES sec_attr; memset (&sec_attr, 0, sizeof sec_attr ); sec_attr.nLength = sizeof sec_attr; sec_attr.bInheritHandle = TRUE; n = GetTempPath (MAX_PATH+1, buffer); if (!n || n > MAX_PATH || mystrlen (buffer) > MAX_PATH) { gpg_err_set_errno (ENOENT); return NULL; } p = buffer + mystrlen (buffer); #ifdef HAVE_W32CE_SYSTEM wcscpy (p, L"_gnupg"); p += 7; #else p = stpcpy (p, "_gnupg"); #endif /* We try to create the directory but don't care about an error as it may already exist and the CreateFile would throw an error anyway. */ CreateDirectory (buffer, NULL); *p++ = '\\'; name = p; for (attempts=0; attempts < 10; attempts++) { p = name; value = (GetTickCount () ^ ((pid<<16) & 0xffff0000)); for (i=0; i < 8; i++) { *p++ = tohex (((value >> 28) & 0x0f)); value <<= 4; } #ifdef HAVE_W32CE_SYSTEM wcscpy (p, L".tmp"); #else strcpy (p, ".tmp"); #endif file = CreateFile (buffer, GENERIC_READ | GENERIC_WRITE, 0, &sec_attr, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (file != INVALID_HANDLE_VALUE) { FILE *fp; #ifdef HAVE_W32CE_SYSTEM int fd = (int)file; fp = _wfdopen (fd, L"w+b"); #else int fd = _open_osfhandle ((intptr_t)file, 0); if (fd == -1) { CloseHandle (file); return NULL; } fp = fdopen (fd, "w+b"); #endif if (!fp) { int save = errno; close (fd); gpg_err_set_errno (save); return NULL; } return fp; } Sleep (1); /* One ms as this is the granularity of GetTickCount. */ } gpg_err_set_errno (ENOENT); return NULL; #undef mystrlen #else /*!HAVE_W32_SYSTEM*/ return tmpfile (); #endif /*!HAVE_W32_SYSTEM*/ } /* Make sure that the standard file descriptors are opened. Obviously some folks close them before an exec and the next file we open will get one of them assigned and thus any output (i.e. diagnostics) end up in that file (e.g. the trustdb). Not actually a gpg problem as this will happen with almost all utilities when called in a wrong way. However we try to minimize the damage here and raise awareness of the problem. Must be called before we open any files! */ void gnupg_reopen_std (const char *pgmname) { #ifdef F_GETFD int did_stdin = 0; int did_stdout = 0; int did_stderr = 0; FILE *complain; if (fcntl (STDIN_FILENO, F_GETFD) == -1 && errno ==EBADF) { if (open ("/dev/null",O_RDONLY) == STDIN_FILENO) did_stdin = 1; else did_stdin = 2; } if (fcntl (STDOUT_FILENO, F_GETFD) == -1 && errno == EBADF) { if (open ("/dev/null",O_WRONLY) == STDOUT_FILENO) did_stdout = 1; else did_stdout = 2; } if (fcntl (STDERR_FILENO, F_GETFD)==-1 && errno==EBADF) { if (open ("/dev/null", O_WRONLY) == STDERR_FILENO) did_stderr = 1; else did_stderr = 2; } /* It's hard to log this sort of thing since the filehandle we would complain to may be closed... */ if (!did_stderr) complain = stderr; else if (!did_stdout) complain = stdout; else complain = NULL; if (complain) { if (did_stdin == 1) fprintf (complain, "%s: WARNING: standard input reopened\n", pgmname); if (did_stdout == 1) fprintf (complain, "%s: WARNING: standard output reopened\n", pgmname); if (did_stderr == 1) fprintf (complain, "%s: WARNING: standard error reopened\n", pgmname); if (did_stdin == 2 || did_stdout == 2 || did_stderr == 2) fprintf(complain,"%s: fatal: unable to reopen standard input," " output, or error\n", pgmname); } if (did_stdin == 2 || did_stdout == 2 || did_stderr == 2) exit (3); #else /* !F_GETFD */ (void)pgmname; #endif } /* Inhibit calls to AllowSetForegroundWindow on Windows. Calling this * with YES set to true calls to gnupg_allow_set_foregound_window are * shunted. */ void gnupg_inhibit_set_foregound_window (int yes) { #ifdef HAVE_W32_SYSTEM inhibit_set_foregound_window = yes; #else (void)yes; #endif } /* Hack required for Windows. */ void gnupg_allow_set_foregound_window (pid_t pid) { if (!pid) log_info ("%s called with invalid pid %lu\n", "gnupg_allow_set_foregound_window", (unsigned long)pid); #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM) else if (inhibit_set_foregound_window) ; else if (!AllowSetForegroundWindow ((pid_t)pid == (pid_t)(-1)?ASFW_ANY:pid)) log_info ("AllowSetForegroundWindow(%lu) failed: %s\n", (unsigned long)pid, w32_strerror (-1)); #endif } int gnupg_remove (const char *fname) { #ifdef HAVE_W32CE_SYSTEM int rc; wchar_t *wfname; wfname = utf8_to_wchar (fname); if (!wfname) rc = 0; else { rc = DeleteFile (wfname); xfree (wfname); } if (!rc) return -1; /* ERRNO is automagically provided by gpg-error.h. */ return 0; #else return remove (fname); #endif } /* Wrapper for rename(2) to handle Windows peculiarities. If * BLOCK_SIGNALS is not NULL and points to a variable set to true, all * signals will be blocked by calling gnupg_block_all_signals; the * caller needs to call gnupg_unblock_all_signals if that variable is * still set to true on return. */ gpg_error_t gnupg_rename_file (const char *oldname, const char *newname, int *block_signals) { gpg_error_t err = 0; if (block_signals && *block_signals) gnupg_block_all_signals (); #ifdef HAVE_DOSISH_SYSTEM { int wtime = 0; gnupg_remove (newname); again: if (rename (oldname, newname)) { if (GetLastError () == ERROR_SHARING_VIOLATION) { /* Another process has the file open. We do not use a * lock for read but instead we wait until the other * process has closed the file. This may take long but * that would also be the case with a dotlock approach for * read and write. Note that we don't need this on Unix * due to the inode concept. * * So let's wait until the rename has worked. The retry * intervals are 50, 100, 200, 400, 800, 50ms, ... */ if (!wtime || wtime >= 800) wtime = 50; else wtime *= 2; if (wtime >= 800) log_info (_("waiting for file '%s' to become accessible ...\n"), oldname); Sleep (wtime); goto again; } err = my_error_from_syserror (); } } #else /* Unix */ { #ifdef __riscos__ gnupg_remove (newname); #endif if (rename (oldname, newname) ) err = my_error_from_syserror (); } #endif /* Unix */ if (block_signals && *block_signals && err) { gnupg_unblock_all_signals (); *block_signals = 0; } if (err) log_error (_("renaming '%s' to '%s' failed: %s\n"), oldname, newname, gpg_strerror (err)); return err; } #ifndef HAVE_W32_SYSTEM static mode_t modestr_to_mode (const char *modestr, mode_t oldmode) { static struct { char letter; mode_t value; } table[] = { { '-', 0 }, { 'r', S_IRUSR }, { 'w', S_IWUSR }, { 'x', S_IXUSR }, { 'r', S_IRGRP }, { 'w', S_IWGRP }, { 'x', S_IXGRP }, { 'r', S_IROTH }, { 'w', S_IWOTH }, { 'x', S_IXOTH } }; int idx; mode_t mode = 0; /* For now we only support a string as used by ls(1) and no octal * numbers. The first character must be a dash. */ for (idx=0; idx < 10 && *modestr; idx++, modestr++) { if (*modestr == table[idx].letter) mode |= table[idx].value; else if (*modestr == '.') { if (!idx) ; /* Skip the dummy. */ else if ((oldmode & table[idx].value)) mode |= (oldmode & table[idx].value); else mode &= ~(oldmode & table[idx].value); } else if (*modestr != '-') break; } return mode; } #endif /* A wrapper around mkdir which takes a string for the mode argument. This makes it easier to handle the mode argument which is not defined on all systems. The format of the modestring is "-rwxrwxrwx" '-' is a don't care or not set. 'r', 'w', 'x' are read allowed, write allowed, execution allowed with the first group for the user, the second for the group and the third for all others. If the string is shorter than above the missing mode characters are meant to be not set. */ int gnupg_mkdir (const char *name, const char *modestr) { /* Note that gpgrt_mkdir also sets ERRNO in addition to returing an * gpg-error style error code. */ return gpgrt_mkdir (name, modestr); } /* A simple wrapper around chdir. NAME is expected to be utf8 * encoded. */ int gnupg_chdir (const char *name) { /* Note that gpgrt_chdir also sets ERRNO in addition to returning an * gpg-error style error code. */ return gpgrt_chdir (name); } /* A wrapper around chmod which takes a string for the mode argument. This makes it easier to handle the mode argument which is not defined on all systems. The format of the modestring is the same as for gnupg_mkdir with extra feature that a '.' keeps the original mode bit. */ int gnupg_chmod (const char *name, const char *modestr) { #ifdef HAVE_W32_SYSTEM (void)name; (void)modestr; return 0; #else mode_t oldmode; if (strchr (modestr, '.')) { /* Get the old mode so that a '.' can copy that bit. */ struct stat st; if (stat (name, &st)) return -1; oldmode = st.st_mode; } else oldmode = 0; return chmod (name, modestr_to_mode (modestr, oldmode)); #endif } /* Our version of mkdtemp. The API is identical to POSIX.1-2008 version. We do not use a system provided mkdtemp because we have a good RNG instantly available and this way we don't have diverging versions. */ char * gnupg_mkdtemp (char *tmpl) { /* A lower bound on the number of temporary files to attempt to generate. The maximum total number of temporary file names that can exist for a given template is 62**6 (5*36**3 for Windows). It should never be necessary to try all these combinations. Instead if a reasonable number of names is tried (we define reasonable as 62**3 or 5*36**3) fail to give the system administrator the chance to remove the problems. */ #ifdef HAVE_W32_SYSTEM static const char letters[] = "abcdefghijklmnopqrstuvwxyz0123456789"; # define NUMBER_OF_LETTERS 36 # define ATTEMPTS_MIN (5 * 36 * 36 * 36) #else static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; # define NUMBER_OF_LETTERS 62 # define ATTEMPTS_MIN (62 * 62 * 62) #endif int len; char *XXXXXX; uint64_t value; unsigned int count; int save_errno = errno; /* The number of times to attempt to generate a temporary file. To conform to POSIX, this must be no smaller than TMP_MAX. */ #if ATTEMPTS_MIN < TMP_MAX unsigned int attempts = TMP_MAX; #else unsigned int attempts = ATTEMPTS_MIN; #endif len = strlen (tmpl); if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX")) { gpg_err_set_errno (EINVAL); return NULL; } /* This is where the Xs start. */ XXXXXX = &tmpl[len - 6]; /* Get a random start value. */ gcry_create_nonce (&value, sizeof value); /* Loop until a directory was created. */ for (count = 0; count < attempts; value += 7777, ++count) { uint64_t v = value; /* Fill in the random bits. */ XXXXXX[0] = letters[v % NUMBER_OF_LETTERS]; v /= NUMBER_OF_LETTERS; XXXXXX[1] = letters[v % NUMBER_OF_LETTERS]; v /= NUMBER_OF_LETTERS; XXXXXX[2] = letters[v % NUMBER_OF_LETTERS]; v /= NUMBER_OF_LETTERS; XXXXXX[3] = letters[v % NUMBER_OF_LETTERS]; v /= NUMBER_OF_LETTERS; XXXXXX[4] = letters[v % NUMBER_OF_LETTERS]; v /= NUMBER_OF_LETTERS; XXXXXX[5] = letters[v % NUMBER_OF_LETTERS]; if (!gnupg_mkdir (tmpl, "-rwx")) { gpg_err_set_errno (save_errno); return tmpl; } if (errno != EEXIST) return NULL; } /* We got out of the loop because we ran out of combinations to try. */ gpg_err_set_errno (EEXIST); return NULL; } int gnupg_setenv (const char *name, const char *value, int overwrite) { #ifdef HAVE_W32CE_SYSTEM (void)name; (void)value; (void)overwrite; return 0; #else /*!W32CE*/ # ifdef HAVE_W32_SYSTEM /* Windows maintains (at least) two sets of environment variables. One set can be accessed by GetEnvironmentVariable and SetEnvironmentVariable. This set is inherited by the children. The other set is maintained in the C runtime, and is accessed using getenv and putenv. We try to keep them in sync by modifying both sets. */ { int exists; char tmpbuf[10]; exists = GetEnvironmentVariable (name, tmpbuf, sizeof tmpbuf); if ((! exists || overwrite) && !SetEnvironmentVariable (name, value)) { gpg_err_set_errno (EINVAL); /* (Might also be ENOMEM.) */ return -1; } } # endif /*W32*/ # ifdef HAVE_SETENV return setenv (name, value, overwrite); # else /*!HAVE_SETENV*/ if (! getenv (name) || overwrite) { char *buf; (void)overwrite; if (!name || !value) { gpg_err_set_errno (EINVAL); return -1; } buf = strconcat (name, "=", value, NULL); if (!buf) return -1; # if __GNUC__ # warning no setenv - using putenv but leaking memory. # endif return putenv (buf); } return 0; # endif /*!HAVE_SETENV*/ #endif /*!W32CE*/ } int gnupg_unsetenv (const char *name) { #ifdef HAVE_W32CE_SYSTEM (void)name; return 0; #else /*!W32CE*/ # ifdef HAVE_W32_SYSTEM /* Windows maintains (at least) two sets of environment variables. One set can be accessed by GetEnvironmentVariable and SetEnvironmentVariable. This set is inherited by the children. The other set is maintained in the C runtime, and is accessed using getenv and putenv. We try to keep them in sync by modifying both sets. */ if (!SetEnvironmentVariable (name, NULL)) { gpg_err_set_errno (EINVAL); /* (Might also be ENOMEM.) */ return -1; } # endif /*W32*/ # ifdef HAVE_UNSETENV return unsetenv (name); # else /*!HAVE_UNSETENV*/ { char *buf; if (!name) { gpg_err_set_errno (EINVAL); return -1; } buf = xtrystrdup (name); if (!buf) return -1; # if __GNUC__ # warning no unsetenv - trying putenv but leaking memory. # endif return putenv (buf); } # endif /*!HAVE_UNSETENV*/ #endif /*!W32CE*/ } /* Return the current working directory as a malloced string. Return NULL and sets ERRNO on error. */ char * gnupg_getcwd (void) { return gpgrt_getcwd (); } /* A simple wrapper around access. NAME is expected to be utf8 * encoded. This function returns an error code and sets ERRNO. */ gpg_err_code_t gnupg_access (const char *name, int mode) { #if GPGRT_VERSION_NUMBER < 0x012800 /* 1.39 */ # ifdef HAVE_W32_SYSTEM wchar_t *wfname; wfname = utf8_to_wchar (fname); if (!wfname) ec = gpg_err_code_from_syserror (); else { ec = _waccess (wfname, mode)? gpg_err_code_from_syserror () : 0; xfree (wfname); } # else return access (name, mode)? gpg_err_code_from_syserror () : 0; # endif #else return gpgrt_access (name, mode); #endif } /* Try to set an envvar. Print only a notice on error. */ +#ifndef HAVE_W32_SYSTEM static void try_set_envvar (const char *name, const char *value, int silent) { if (gnupg_setenv (name, value, 1)) if (!silent) log_info ("error setting envvar %s to '%s': %s\n", name, value, gpg_strerror (my_error_from_syserror ())); } +#endif /*!HAVE_W32_SYSTEM*/ /* Switch to USER which is either a name or an UID. This is a nop * under Windows. Note that in general it is only possible to switch * to another user id if the process is running under root. if silent * is set no diagnostics are printed. */ gpg_error_t gnupg_chuid (const char *user, int silent) { #ifdef HAVE_W32_SYSTEM (void)user; /* Not implemented for Windows - ignore. */ (void)silent; return 0; #elif HAVE_PWD_H /* A proper Unix */ unsigned long ul; struct passwd *pw; struct stat st; char *endp; gpg_error_t err; gpg_err_set_errno (0); ul = strtoul (user, &endp, 10); if (errno || endp == user || *endp) pw = getpwnam (user); /* Not a number; assume USER is a name. */ else pw = getpwuid ((uid_t)ul); if (!pw) { if (!silent) log_error ("user '%s' not found\n", user); return my_error (GPG_ERR_NOT_FOUND); } /* Try to set some envvars even if we are already that user. */ if (!stat (pw->pw_dir, &st)) try_set_envvar ("HOME", pw->pw_dir, silent); try_set_envvar ("USER", pw->pw_name, silent); try_set_envvar ("LOGNAME", pw->pw_name, silent); #ifdef _AIX try_set_envvar ("LOGIN", pw->pw_name, silent); #endif if (getuid () == pw->pw_uid) return 0; /* We are already this user. */ /* If we need to switch set PATH to a standard value and make sure * GNUPGHOME is not set. */ try_set_envvar ("PATH", "/usr/local/bin:/usr/bin:/bin", silent); if (gnupg_unsetenv ("GNUPGHOME")) if (!silent) log_info ("error unsetting envvar %s: %s\n", "GNUPGHOME", gpg_strerror (gpg_error_from_syserror ())); if (initgroups (pw->pw_name, pw->pw_gid)) { err = my_error_from_syserror (); if (!silent) log_error ("error setting supplementary groups for '%s': %s\n", pw->pw_name, gpg_strerror (err)); return err; } if (setuid (pw->pw_uid)) { err = my_error_from_syserror (); log_error ("error switching to user '%s': %s\n", pw->pw_name, gpg_strerror (err)); return err; } return 0; #else /*!HAVE_PWD_H */ if (!silent) log_info ("system is missing passwd querying functions\n"); return my_error (GPG_ERR_NOT_IMPLEMENTED); #endif } #ifdef HAVE_W32CE_SYSTEM /* There is a isatty function declaration in cegcc but it does not make sense, thus we redefine it. */ int _gnupg_isatty (int fd) { (void)fd; return 0; } #endif #ifdef HAVE_W32CE_SYSTEM /* Replacement for getenv which takes care of the our use of getenv. The code is not thread safe but we expect it to work in all cases because it is called for the first time early enough. */ char * _gnupg_getenv (const char *name) { static int initialized; static char *assuan_debug; if (!initialized) { assuan_debug = read_w32_registry_string (NULL, "\\Software\\GNU\\libassuan", "debug"); initialized = 1; } if (!strcmp (name, "ASSUAN_DEBUG")) return assuan_debug; else return NULL; } #endif /*HAVE_W32CE_SYSTEM*/ #ifdef HAVE_W32_SYSTEM /* Return the user's security identifier from the current process. */ PSID w32_get_user_sid (void) { int okay = 0; HANDLE proc = NULL; HANDLE token = NULL; TOKEN_USER *user = NULL; PSID sid = NULL; DWORD tokenlen, sidlen; proc = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId()); if (!proc) goto leave; if (!OpenProcessToken (proc, TOKEN_QUERY, &token)) goto leave; if (!GetTokenInformation (token, TokenUser, NULL, 0, &tokenlen) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) goto leave; user = xtrymalloc (tokenlen); if (!user) goto leave; if (!GetTokenInformation (token, TokenUser, user, tokenlen, &tokenlen)) goto leave; if (!IsValidSid (user->User.Sid)) goto leave; sidlen = GetLengthSid (user->User.Sid); sid = xtrymalloc (sidlen); if (!sid) goto leave; if (!CopySid (sidlen, sid, user->User.Sid)) goto leave; okay = 1; leave: xfree (user); if (token) CloseHandle (token); if (proc) CloseHandle (proc); if (!okay) { xfree (sid); sid = NULL; } return sid; } #endif /*HAVE_W32_SYSTEM*/ /* Support for inotify under Linux. */ /* Store a new inotify file handle for FNAME at R_FD or return an * error code. This file descriptor watch the removal of FNAME. */ gpg_error_t gnupg_inotify_watch_delete_self (int *r_fd, const char *fname) { #if HAVE_INOTIFY_INIT gpg_error_t err; int fd; *r_fd = -1; if (!fname) return my_error (GPG_ERR_INV_VALUE); fd = inotify_init (); if (fd == -1) return my_error_from_syserror (); if (inotify_add_watch (fd, fname, IN_DELETE_SELF) == -1) { err = my_error_from_syserror (); close (fd); return err; } *r_fd = fd; return 0; #else /*!HAVE_INOTIFY_INIT*/ (void)fname; *r_fd = -1; return my_error (GPG_ERR_NOT_SUPPORTED); #endif /*!HAVE_INOTIFY_INIT*/ } /* Store a new inotify file handle for SOCKET_NAME at R_FD or return * an error code. */ gpg_error_t gnupg_inotify_watch_socket (int *r_fd, const char *socket_name) { #if HAVE_INOTIFY_INIT gpg_error_t err; char *fname; int fd; char *p; *r_fd = -1; if (!socket_name) return my_error (GPG_ERR_INV_VALUE); fname = xtrystrdup (socket_name); if (!fname) return my_error_from_syserror (); fd = inotify_init (); if (fd == -1) { err = my_error_from_syserror (); xfree (fname); return err; } /* We need to watch the directory for the file because there won't * be an IN_DELETE_SELF for a socket file. To handle a removal of * the directory we also watch the directory itself. */ p = strrchr (fname, '/'); if (p) *p = 0; if (inotify_add_watch (fd, fname, (IN_DELETE|IN_DELETE_SELF|IN_EXCL_UNLINK)) == -1) { err = my_error_from_syserror (); close (fd); xfree (fname); return err; } xfree (fname); *r_fd = fd; return 0; #else /*!HAVE_INOTIFY_INIT*/ (void)socket_name; *r_fd = -1; return my_error (GPG_ERR_NOT_SUPPORTED); #endif /*!HAVE_INOTIFY_INIT*/ } /* Read an inotify event and return true if it matches NAME or if it * sees an IN_DELETE_SELF event for the directory of NAME. */ int gnupg_inotify_has_name (int fd, const char *name) { #if USE_NPTH && HAVE_INOTIFY_INIT #define BUFSIZE_FOR_INOTIFY (sizeof (struct inotify_event) + 255 + 1) union { struct inotify_event ev; char _buf[sizeof (struct inotify_event) + 255 + 1]; } buf; struct inotify_event *evp; int n; n = npth_read (fd, &buf, sizeof buf); /* log_debug ("notify read: n=%d\n", n); */ evp = &buf.ev; while (n >= sizeof (struct inotify_event)) { /* log_debug (" mask=%x len=%u name=(%s)\n", */ /* evp->mask, (unsigned int)evp->len, evp->len? evp->name:""); */ if ((evp->mask & IN_UNMOUNT)) { /* log_debug (" found (dir unmounted)\n"); */ return 3; /* Directory was unmounted. */ } if ((evp->mask & IN_DELETE_SELF)) { /* log_debug (" found (dir removed)\n"); */ return 2; /* Directory was removed. */ } if ((evp->mask & IN_DELETE)) { if (evp->len >= strlen (name) && !strcmp (evp->name, name)) { /* log_debug (" found (file removed)\n"); */ return 1; /* File was removed. */ } } n -= sizeof (*evp) + evp->len; evp = (struct inotify_event *)(void *) ((char *)evp + sizeof (*evp) + evp->len); } #else /*!(USE_NPTH && HAVE_INOTIFY_INIT)*/ (void)fd; (void)name; #endif /*!(USE_NPTH && HAVE_INOTIFY_INIT)*/ return 0; /* Not found. */ } /* Return a malloc'ed string that is the path to the passed * unix-domain socket (or return NULL if this is not a valid * unix-domain socket). We use a plain int here because it is only * used on Linux. * * FIXME: This function needs to be moved to libassuan. */ #ifndef HAVE_W32_SYSTEM char * gnupg_get_socket_name (int fd) { struct sockaddr_un un; socklen_t len = sizeof(un); char *name = NULL; if (getsockname (fd, (struct sockaddr*)&un, &len) != 0) log_error ("could not getsockname(%d): %s\n", fd, gpg_strerror (my_error_from_syserror ())); else if (un.sun_family != AF_UNIX) log_error ("file descriptor %d is not a unix-domain socket\n", fd); else if (len <= offsetof (struct sockaddr_un, sun_path)) log_error ("socket name not present for file descriptor %d\n", fd); else if (len > sizeof(un)) log_error ("socket name for file descriptor %d was truncated " "(passed %zu bytes, wanted %u)\n", fd, sizeof(un), len); else { size_t namelen = len - offsetof (struct sockaddr_un, sun_path); /* log_debug ("file descriptor %d has path %s (%zu octets)\n", fd, */ /* un.sun_path, namelen); */ name = xtrymalloc (namelen + 1); if (!name) log_error ("failed to allocate memory for name of fd %d: %s\n", fd, gpg_strerror (my_error_from_syserror ())); else { memcpy (name, un.sun_path, namelen); name[namelen] = 0; } } return name; } #endif /*!HAVE_W32_SYSTEM*/ /* Check whether FD is valid. */ int gnupg_fd_valid (int fd) { int d = dup (fd); if (d < 0) return 0; close (d); return 1; } diff --git a/g10/keydb.c b/g10/keydb.c index ddbab7300..f32eab055 100644 --- a/g10/keydb.c +++ b/g10/keydb.c @@ -1,1953 +1,1953 @@ /* keydb.c - key database dispatcher * Copyright (C) 2001-2013 Free Software Foundation, Inc. * Copyright (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" #include "keydb-private.h" /* For struct keydb_handle_s */ static int active_handles; 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; /* 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_s *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, NULL, 1); - fclose (fp); + rc = _keybox_write_header_blob (fp, 1); + 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]; #if MAX_FINGERPRINT_LEN < UBID_LEN || MAX_FINGERPRINT_LEN < KEYGRIP_LEN #error MAX_FINGERPRINT_LEN is shorter than KEYGRIP or UBID length. #endif 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_FPR: bin2hex (desc->u.fpr, desc->fprlen, fpr); return xasprintf ("FPR%02d: '%s'", desc->fprlen, 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/%s'", (int)desc->snlen,desc->sn, desc->u.name); case KEYDB_SEARCH_MODE_SN: return xasprintf ("SN: '%.*s'", (int)desc->snlen, desc->sn); case KEYDB_SEARCH_MODE_SUBJECT: return xasprintf ("SUBJECT: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_KEYGRIP: bin2hex (desc[0].u.grip, KEYGRIP_LEN, fpr); return xasprintf ("KEYGRIP: %s", fpr); case KEYDB_SEARCH_MODE_UBID: bin2hex (desc[0].u.ubid, UBID_LEN, fpr); return xasprintf ("UBID: %s", fpr); 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); } /* keydb_new diverts to here in non-keyboxd mode. HD is just the * calloced structure with the handle type initialized. */ gpg_error_t internal_keydb_init (KEYDB_HANDLE hd) { gpg_error_t err = 0; int i, j; int die = 0; int reterrno; log_assert (!hd->use_keyboxd); 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) err = gpg_error_from_errno (reterrno); return err; } /* Free all non-keyboxd resources owned by the database handle. * keydb_release diverts to here. */ void internal_keydb_deinit (KEYDB_HANDLE hd) { int i; log_assert (!hd->use_keyboxd); 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); } /* Take a lock on the files immediately and not only during insert or * update. This lock is released with keydb_release. */ gpg_error_t internal_keydb_lock (KEYDB_HANDLE hd) { gpg_error_t err; log_assert (!hd->use_keyboxd); 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->use_keyboxd) 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->use_keyboxd) return "[keyboxd]"; 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. */ /* FIXME(keyboxd): This function is used only at one place - see how * we can avoid it. */ 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. */ /* FIXME(keyboxd): This function is used only at one place - see how * we can avoid it. */ 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; } } /* Parse the keyblock in IOBUF and return at R_KEYBLOCK. */ gpg_error_t keydb_parse_keyblock (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; } 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. * keydb_get_keyblock divert to here in the non-keyboxd mode. * * 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 internal_keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb) { gpg_error_t err = 0; log_assert (!hd->use_keyboxd); 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 = keydb_parse_keyblock (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 ("%s leave (cached mode)", __func__); 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 = keydb_parse_keyblock (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++; return err; } /* Update the keyblock KB (i.e., extract the fingerprint and find the * corresponding keyblock in the keyring). * keydb_update_keyblock diverts to here in the non-keyboxd mode. * * 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 internal_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 (!hd->use_keyboxd); pk = kb->pkt->pkt.public_key; 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 || len == 32) { desc.mode = KEYDB_SEARCH_MODE_FPR; desc.fprlen = len; } 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) { keydb_stats.build_keyblocks++; 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. * keydb_insert_keyblock diverts to here in the non-keyboxd mode. * * 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 internal_keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb) { gpg_error_t err; int idx; log_assert (!hd->use_keyboxd); 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) { keydb_stats.build_keyblocks++; 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 internal_keydb_delete_keyblock (KEYDB_HANDLE hd) { gpg_error_t rc; log_assert (!hd->use_keyboxd); 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; if (hd->use_keyboxd) return 0; /* No need for this here. */ 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; if (opt.use_keyboxd) return; /* No need for this here. */ 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 too large to read from a keybox) since the last search reset. */ unsigned long keydb_get_skipped_counter (KEYDB_HANDLE hd) { /*FIXME(keyboxd): Do we need this? */ return hd && !hd->use_keyboxd? 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). * keydb_search_reset diverts to here in the non-keyboxd mode. * * 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 internal_keydb_search_reset (KEYDB_HANDLE hd) { gpg_error_t rc = 0; int i; log_assert (!hd->use_keyboxd); keyblock_cache_clear (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. * keydb_search diverts to here in the non-keyboxd mode. * * 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 internal_keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc, size_t *descindex) { 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; int fprlen; log_assert (!hd->use_keyboxd); if (!any_registered) { write_status_error ("keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN)); return gpg_error (GPG_ERR_NOT_FOUND); } 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 ("%s leave (not found, cached)", __func__); 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 (desc[0].mode == KEYDB_SEARCH_MODE_FPR) fprlen = desc[0].fprlen; else fprlen = 0; if (!hd->no_caching && ndesc == 1 && fprlen && hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED && hd->keyblock_cache.fprlen == fprlen && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, fprlen) /* 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 ("%s leave (cached)", __func__); 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 (rc == GPG_ERR_LEGACY_KEY); 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 && fprlen && 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, fprlen); hd->keyblock_cache.fprlen = fprlen; } 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 (!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, size_t fprlen) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_FPR; memcpy (desc.u.fpr, fpr, fprlen); desc.fprlen = fprlen; 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/photoid.c b/g10/photoid.c index f7ada2729..8a4436b8b 100644 --- a/g10/photoid.c +++ b/g10/photoid.c @@ -1,708 +1,708 @@ /* photoid.c - photo ID handling code * Copyright (C) 2001, 2002, 2005, 2006, 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 #ifdef _WIN32 # ifdef HAVE_WINSOCK2_H # include # endif # include # ifndef VER_PLATFORM_WIN32_WINDOWS # define VER_PLATFORM_WIN32_WINDOWS 1 # endif #endif #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/status.h" #include "exec.h" #include "keydb.h" #include "../common/i18n.h" #include "../common/iobuf.h" #include "options.h" #include "main.h" #include "photoid.h" #include "../common/ttyio.h" #include "trustdb.h" /* Generate a new photo id packet, or return NULL if canceled. FIXME: Should we add a duplicates check similar to generate_user_id? */ PKT_user_id * generate_photo_id (ctrl_t ctrl, PKT_public_key *pk,const char *photo_name) { PKT_user_id *uid; int error=1,i; unsigned int len; char *filename; byte *photo=NULL; byte header[16]; IOBUF file; int overflow; header[0]=0x10; /* little side of photo header length */ header[1]=0; /* big side of photo header length */ header[2]=1; /* 1 == version of photo header */ header[3]=1; /* 1 == JPEG */ for(i=4;i<16;i++) /* The reserved bytes */ header[i]=0; #define EXTRA_UID_NAME_SPACE 71 uid=xmalloc_clear(sizeof(*uid)+71); if(photo_name && *photo_name) filename=make_filename(photo_name,(void *)NULL); else { tty_printf(_("\nPick an image to use for your photo ID." " The image must be a JPEG file.\n" "Remember that the image is stored within your public key." " If you use a\n" "very large picture, your key will become very large" " as well!\n" "Keeping the image close to 240x288 is a good size" " to use.\n")); filename=NULL; } while(photo==NULL) { if(filename==NULL) { char *tempname; tty_printf("\n"); tty_enable_completion(NULL); tempname=cpr_get("photoid.jpeg.add", _("Enter JPEG filename for photo ID: ")); tty_disable_completion(); filename=make_filename(tempname,(void *)NULL); xfree(tempname); if(strlen(filename)==0) goto scram; } file=iobuf_open(filename); if (file && is_secured_file (iobuf_get_fd (file))) { iobuf_close (file); file = NULL; gpg_err_set_errno (EPERM); } if(!file) { log_error(_("unable to open JPEG file '%s': %s\n"), filename,strerror(errno)); xfree(filename); filename=NULL; continue; } len=iobuf_get_filelength(file, &overflow); if(len>6144 || overflow) { tty_printf( _("This JPEG is really large (%d bytes) !\n"),len); if(!cpr_get_answer_is_yes("photoid.jpeg.size", _("Are you sure you want to use it? (y/N) "))) { iobuf_close(file); xfree(filename); filename=NULL; continue; } } photo=xmalloc(len); iobuf_read(file,photo,len); iobuf_close(file); /* Is it a JPEG? */ if(photo[0]!=0xFF || photo[1]!=0xD8) { log_error(_("'%s' is not a JPEG file\n"),filename); xfree(photo); photo=NULL; xfree(filename); filename=NULL; continue; } /* Build the packet */ build_attribute_subpkt(uid,1,photo,len,header,16); parse_attribute_subpkts(uid); make_attribute_uidname(uid, EXTRA_UID_NAME_SPACE); /* Showing the photo is not safe when noninteractive since the "user" may not be able to dismiss a viewer window! */ if(opt.command_fd==-1) { show_photos (ctrl, uid->attribs, uid->numattribs, pk, uid); switch(cpr_get_answer_yes_no_quit("photoid.jpeg.okay", _("Is this photo correct (y/N/q)? "))) { case -1: goto scram; case 0: free_attributes(uid); xfree(photo); photo=NULL; xfree(filename); filename=NULL; continue; } } } error=0; uid->ref=1; scram: xfree(filename); xfree(photo); if(error) { free_attributes(uid); xfree(uid); return NULL; } return uid; } /* Returns 0 for error, 1 for valid */ int parse_image_header(const struct user_attribute *attr,byte *type,u32 *len) { u16 headerlen; if(attr->len<3) return 0; /* For historical reasons (i.e. "oops!"), the header length is little endian. */ headerlen=(attr->data[1]<<8) | attr->data[0]; if(headerlen>attr->len) return 0; if(type && attr->len>=4) { if(attr->data[2]==1) /* header version 1 */ *type=attr->data[3]; else *type=0; } *len=attr->len-headerlen; if(*len==0) return 0; return 1; } /* style==0 for extension, 1 for name, 2 for MIME type. Remember that the "name" style string could be used in a user ID name field, so make sure it is not too big (see parse-packet.c:parse_attribute). Extensions should be 3 characters long for the best cross-platform compatibility. */ const char * image_type_to_string(byte type,int style) { const char *string; switch(type) { case 1: /* jpeg */ if(style==0) string="jpg"; else if(style==1) string="jpeg"; else string="image/jpeg"; break; default: if(style==0) string="bin"; else if(style==1) string="unknown"; else string="image/x-unknown"; break; } return string; } #if !defined(FIXED_PHOTO_VIEWER) && !defined(DISABLE_PHOTO_VIEWER) static const char * get_default_photo_command(void) { #if defined(_WIN32) OSVERSIONINFO osvi; memset(&osvi,0,sizeof(osvi)); osvi.dwOSVersionInfoSize=sizeof(osvi); GetVersionEx(&osvi); if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS) return "start /w %i"; else return "!ShellExecute 400 %i"; #elif defined(__APPLE__) /* OS X. This really needs more than just __APPLE__. */ return "open %I"; #else if (!path_access ("xloadimage", X_OK)) return "xloadimage -fork -quiet -title 'KeyID 0x%k' stdin"; else if (!path_access ("display",X_OK)) return "display -title 'KeyID 0x%k' %i"; else if (getuid () && !path_access ("xdg-open", X_OK)) return "xdg-open %i"; else return "/bin/true"; #endif } #endif #ifndef DISABLE_PHOTO_VIEWER struct spawn_info { unsigned int keep_temp_file; char *command; char *tempdir; char *tempfile; }; #ifdef NO_EXEC static void show_photo (const char *command, const char *name, const void *image, u32 len) { log_error(_("no remote program execution supported\n")); return GPG_ERR_GENERAL; } #else /* ! NO_EXEC */ #include "../common/membuf.h" #include "../common/exechelp.h" /* Makes a temp directory and filenames */ static int setup_input_file (struct spawn_info *info, const char *name) { char *tmp = opt.temp_dir; int len; #define TEMPLATE "gpg-XXXXXX" /* Initialize by the length of last part in the path + 1 */ len = strlen (DIRSEP_S) + strlen (TEMPLATE) + 1; /* Make up the temp dir and file in case we need them */ if (tmp) { len += strlen (tmp); info->tempdir = xmalloc (len); } else { #if defined (_WIN32) int ret; tmp = xmalloc (MAX_PATH+1); if (!tmp) return -1; ret = GetTempPath (MAX_PATH-len, tmp); if (ret == 0 || ret >= MAX_PATH-len) strcpy (tmp, "c:\\windows\\temp"); else { /* GetTempPath may return with \ on the end */ while (ret > 0 && tmp[ret-1] == '\\') { tmp[ret-1]='\0'; ret--; } } len += ret; info->tempdir = tmp; #else /* More unixish systems */ if (!(tmp = getenv ("TMPDIR")) && !(tmp = getenv ("TMP"))) tmp = "/tmp"; len += strlen (tmp); info->tempdir = xmalloc (len); #endif } if (info->tempdir == NULL) return -1; sprintf (info->tempdir, "%s" DIRSEP_S TEMPLATE, tmp); if (gnupg_mkdtemp (info->tempdir) == NULL) { log_error (_("can't create directory '%s': %s\n"), info->tempdir, strerror (errno)); return -1; } info->tempfile = xmalloc (strlen (info->tempdir) + strlen (DIRSEP_S) + strlen (name) + 1); if (info->tempfile == NULL) { xfree (info->tempdir); info->tempdir = NULL; return -1; } sprintf (info->tempfile, "%s" DIRSEP_S "%s", info->tempdir, name); return 0; } /* Expands %i or %I in the args to the full temp file within the temp directory. */ static int expand_args (struct spawn_info *info, const char *args_in, const char *name) { const char *ch = args_in; membuf_t command; info->keep_temp_file = 0; if (DBG_EXTPROG) log_debug ("expanding string \"%s\"\n", args_in); init_membuf (&command, 100); while (*ch != '\0') { if (*ch == '%') { const char *append = NULL; ch++; switch (*ch) { case 'I': info->keep_temp_file = 1; /* fall through */ case 'i': /* in */ if (info->tempfile == NULL) { if (setup_input_file (info, name) < 0) goto fail; } append = info->tempfile; break; case '%': append = "%"; break; } if (append) put_membuf_str (&command, append); } else put_membuf (&command, ch, 1); ch++; } put_membuf (&command, "", 1); /* Terminate string. */ info->command = get_membuf (&command, NULL); if (!info->command) return -1; if(DBG_EXTPROG) log_debug("args expanded to \"%s\", use %s, keep %u\n", info->command, info->tempfile, info->keep_temp_file); return 0; fail: xfree (get_membuf (&command, NULL)); return -1; } #ifndef EXEC_TEMPFILE_ONLY static void fill_command_argv (const char *argv[4], const char *command) { argv[0] = getenv ("SHELL"); if (argv[0] == NULL) argv[0] = "/bin/sh"; argv[1] = "-c"; argv[2] = command; argv[3] = NULL; } #endif static void run_with_pipe (struct spawn_info *info, const void *image, u32 len) { #ifdef EXEC_TEMPFILE_ONLY (void)info; (void)image; (void)len; log_error (_("this platform requires temporary files when calling" " external programs\n")); return; #else /* !EXEC_TEMPFILE_ONLY */ int to[2]; pid_t pid; gpg_error_t err; const char *argv[4]; err = gnupg_create_pipe (to); if (err) return; fill_command_argv (argv, info->command); err = gnupg_spawn_process_fd (argv[0], argv+1, to[0], -1, -1, &pid); close (to[0]); if (err) { log_error (_("unable to execute shell '%s': %s\n"), argv[0], gpg_strerror (err)); close (to[1]); } else { write (to[1], image, len); close (to[1]); err = gnupg_wait_process (argv[0], pid, 1, NULL); if (err) log_error (_("unnatural exit of external program\n")); } #endif /* !EXEC_TEMPFILE_ONLY */ } static int create_temp_file (struct spawn_info *info, const void *ptr, u32 len) { if (DBG_EXTPROG) log_debug ("using temp file '%s'\n", info->tempfile); /* It's not fork/exec/pipe, so create a temp file */ if ( is_secured_filename (info->tempfile) ) { log_error (_("can't create '%s': %s\n"), info->tempfile, strerror (EPERM)); gpg_err_set_errno (EPERM); return -1; } else { - FILE *fp = fopen (info->tempfile, "wb"); + estream_t fp = es_fopen (info->tempfile, "wb"); if (fp) { - fwrite (ptr, len, 1, fp); - fclose (fp); + es_fwrite (ptr, len, 1, fp); + es_fclose (fp); return 0; } else { int save = errno; log_error (_("can't create '%s': %s\n"), info->tempfile, strerror(errno)); gpg_err_set_errno (save); return -1; } } } static void show_photo (const char *command, const char *name, const void *image, u32 len) { struct spawn_info *spawn; spawn = xmalloc_clear (sizeof (struct spawn_info)); if (!spawn) return; /* Expand the args */ if (expand_args (spawn, command, name) < 0) { xfree (spawn); return; } if (DBG_EXTPROG) log_debug ("running command: %s\n", spawn->command); if (spawn->tempfile == NULL) run_with_pipe (spawn, image, len); else if (create_temp_file (spawn, image, len) == 0) { #if defined (_WIN32) if (w32_system (spawn->command) < 0) log_error (_("system error while calling external program: %s\n"), strerror (errno)); #else pid_t pid; gpg_error_t err; const char *argv[4]; fill_command_argv (argv, spawn->command); err = gnupg_spawn_process_fd (argv[0], argv+1, -1, -1, -1, &pid); if (!err) err = gnupg_wait_process (argv[0], pid, 1, NULL); if (err) log_error (_("unnatural exit of external program\n")); #endif if (!spawn->keep_temp_file) { if (unlink (spawn->tempfile) < 0) log_info (_("WARNING: unable to remove tempfile (%s) '%s': %s\n"), "in", spawn->tempfile, strerror(errno)); if (rmdir (spawn->tempdir) < 0) log_info (_("WARNING: unable to remove temp directory '%s': %s\n"), spawn->tempdir, strerror(errno)); } } xfree(spawn->command); xfree(spawn->tempdir); xfree(spawn->tempfile); xfree(spawn); } #endif #endif void show_photos (ctrl_t ctrl, const struct user_attribute *attrs, int count, PKT_public_key *pk, PKT_user_id *uid) { #ifdef DISABLE_PHOTO_VIEWER (void)attrs; (void)count; (void)pk; (void)uid; #else /*!DISABLE_PHOTO_VIEWER*/ int i; struct expando_args args; u32 len; u32 kid[2]={0,0}; if (opt.exec_disable && !opt.no_perm_warn) { log_info (_("external program calls are disabled due to unsafe " "options file permissions\n")); return; } #if defined(HAVE_GETUID) && defined(HAVE_GETEUID) /* There should be no way to get to this spot while still carrying setuid privs. Just in case, bomb out if we are. */ if ( getuid () != geteuid ()) BUG (); #endif memset (&args, 0, sizeof(args)); args.pk = pk; args.validity_info = get_validity_info (ctrl, NULL, pk, uid); args.validity_string = get_validity_string (ctrl, pk, uid); namehash_from_uid (uid); args.namehash = uid->namehash; if (pk) keyid_from_pk (pk, kid); es_fflush (es_stdout); #ifdef FIXED_PHOTO_VIEWER opt.photo_viewer = FIXED_PHOTO_VIEWER; #else if (!opt.photo_viewer) opt.photo_viewer = get_default_photo_command (); #endif for (i=0; i. */ #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 because * dotlock does not implement 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 active. * 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 record 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[20]; fpr20_from_pk (pk, fingerprint); 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/backend-kbx.c b/kbx/backend-kbx.c index ca72169a0..eff64cfa3 100644 --- a/kbx/backend-kbx.c +++ b/kbx/backend-kbx.c @@ -1,457 +1,457 @@ /* backend-kbx.c - Keybox format backend for keyboxd * Copyright (C) 2019 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 . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include "keyboxd.h" #include "../common/i18n.h" #include "backend.h" #include "keybox.h" /* Our definition of the backend handle. */ struct backend_handle_s { enum database_types db_type; /* Always DB_TYPE_KBX. */ unsigned int backend_id; /* Always the id of the backend. */ void *token; /* Used to create a new KEYBOX_HANDLE. */ char filename[1]; }; /* Check that the file FILENAME is a valid keybox file which can be * used here. Common return codes: * * 0 := Valid keybox file * GPG_ERR_ENOENT := No such file * GPG_ERR_NO_OBJ := File exists with size zero. * GPG_ERR_INV_OBJ:= File exists but is not a keybox file. */ static gpg_error_t check_kbx_file_magic (const char *filename) { gpg_error_t err; u32 magic; unsigned char verbuf[4]; estream_t fp; fp = es_fopen (filename, "rb"); if (!fp) return gpg_error_from_syserror (); err = gpg_error (GPG_ERR_INV_OBJ); if (es_fread (&magic, 4, 1, fp) == 1 ) { if (es_fread (&verbuf, 4, 1, fp) == 1 && verbuf[0] == 1 && es_fread (&magic, 4, 1, fp) == 1 && !memcmp (&magic, "KBXf", 4)) { err = 0; } } else /* Maybe empty: Let's create it. */ err = gpg_error (GPG_ERR_NO_OBJ); es_fclose (fp); return err; } /* Create new keybox file. This can also be used if the keybox * already exists but has a length of zero. Do not use it in any * other cases. */ static gpg_error_t create_keybox (const char *filename) { gpg_error_t err; dotlock_t lockhd = NULL; estream_t fp; /* To avoid races with other temporary instances of keyboxd trying * to create or update the keybox, we do the next stuff in a locked * state. */ lockhd = dotlock_create (filename, 0); if (!lockhd) { err = 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 keybox is not really useful at all. */ if (opt.verbose) log_info ("can't allocate lock for '%s': %s\n", filename, gpg_strerror (err)); return err; } if ( dotlock_take (lockhd, -1) ) { err = gpg_error_from_syserror (); /* This is something bad. Probably a stale lockfile. */ log_info ("can't lock '%s': %s\n", filename, gpg_strerror (err)); goto leave; } /* 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. * We always set the OpenPGP blobs maybe available flag. */ fp = es_fopen (filename, "w+b,mode=-rw-------"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (err)); goto leave; } - err = _keybox_write_header_blob (NULL, fp, 1); + err = _keybox_write_header_blob (fp, 1); es_fclose (fp); if (err) { log_error (_("error creating keybox '%s': %s\n"), filename, gpg_strerror (err)); goto leave; } if (!opt.quiet) log_info (_("keybox '%s' created\n"), filename); err = 0; leave: if (lockhd) { dotlock_release (lockhd); dotlock_destroy (lockhd); } return err; } /* Install a new resource and return a handle for that backend. */ gpg_error_t be_kbx_add_resource (ctrl_t ctrl, backend_handle_t *r_hd, const char *filename, int readonly) { gpg_error_t err; backend_handle_t hd; void *token; (void)ctrl; *r_hd = NULL; hd = xtrycalloc (1, sizeof *hd + strlen (filename)); if (!hd) return gpg_error_from_syserror (); hd->db_type = DB_TYPE_KBX; strcpy (hd->filename, filename); err = check_kbx_file_magic (filename); switch (gpg_err_code (err)) { case 0: break; case GPG_ERR_ENOENT: case GPG_ERR_NO_OBJ: if (readonly) { err = gpg_error (GPG_ERR_ENOENT); goto leave; } err = create_keybox (filename); if (err) goto leave; break; default: goto leave; } err = keybox_register_file (filename, 0, &token); if (err) goto leave; hd->backend_id = be_new_backend_id (); hd->token = token; *r_hd = hd; hd = NULL; leave: xfree (hd); return err; } /* Release the backend handle HD and all its resources. HD is not * valid after a call to this function. */ void be_kbx_release_resource (ctrl_t ctrl, backend_handle_t hd) { (void)ctrl; if (!hd) return; hd->db_type = DB_TYPE_NONE; xfree (hd); } void be_kbx_release_kbx_hd (KEYBOX_HANDLE kbx_hd) { keybox_release (kbx_hd); } /* Helper for be_find_request_part to initialize a kbx request part. */ gpg_error_t be_kbx_init_request_part (backend_handle_t backend_hd, db_request_part_t part) { part->kbx_hd = keybox_new_openpgp (backend_hd->token, 0); if (!part->kbx_hd) return gpg_error_from_syserror (); return 0; } /* Search for the keys described by (DESC,NDESC) and return them to * the caller. BACKEND_HD is the handle for this backend and REQUEST * is the current database request object. */ gpg_error_t be_kbx_search (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request, KEYDB_SEARCH_DESC *desc, unsigned int ndesc) { gpg_error_t err; db_request_part_t part; size_t descindex; unsigned long skipped_long_blobs; log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX); log_assert (request); /* Find the specific request part or allocate it. */ err = be_find_request_part (backend_hd, request, &part); if (err) goto leave; if (!desc) err = keybox_search_reset (part->kbx_hd); else err = keybox_search (part->kbx_hd, desc, ndesc, KEYBOX_BLOBTYPE_PGP, &descindex, &skipped_long_blobs); if (err == -1) err = gpg_error (GPG_ERR_EOF); if (desc && !err) { /* Successful search operation. */ void *buffer; size_t buflen; enum pubkey_types pubkey_type; unsigned char ubid[UBID_LEN]; err = keybox_get_data (part->kbx_hd, &buffer, &buflen, &pubkey_type, ubid); if (err) goto leave; /* FIXME: Return the ephemeral flag. */ err = be_return_pubkey (ctrl, buffer, buflen, pubkey_type, ubid, 0, 0, 0, 0); if (!err) be_cache_pubkey (ctrl, ubid, buffer, buflen, pubkey_type); xfree (buffer); } leave: return err; } /* Seek in the keybox to the given UBID (if UBID is not NULL) or to * the primary fingerprint specified by (FPR,FPRLEN). BACKEND_HD is * the handle for this backend and REQUEST is the current database * request object. This does a dummy read so that the next search * operation starts right after that UBID. */ gpg_error_t be_kbx_seek (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request, const unsigned char *ubid) { gpg_error_t err; db_request_part_t part; size_t descindex; unsigned long skipped_long_blobs; KEYDB_SEARCH_DESC desc; (void)ctrl; log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX); log_assert (request); memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_UBID; memcpy (desc.u.ubid, ubid, UBID_LEN); /* Find the specific request part or allocate it. */ err = be_find_request_part (backend_hd, request, &part); if (err) goto leave; err = keybox_search_reset (part->kbx_hd); if (!err) err = keybox_search (part->kbx_hd, &desc, 1, 0, &descindex, &skipped_long_blobs); if (err == -1) err = gpg_error (GPG_ERR_EOF); leave: return err; } /* Insert (BLOB,BLOBLEN) into the keybox. BACKEND_HD is the handle * for this backend and REQUEST is the current database request * object. */ gpg_error_t be_kbx_insert (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request, enum pubkey_types pktype, const void *blob, size_t bloblen) { gpg_error_t err; db_request_part_t part; ksba_cert_t cert = NULL; (void)ctrl; log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX); log_assert (request); /* Find the specific request part or allocate it. */ err = be_find_request_part (backend_hd, request, &part); if (err) goto leave; if (pktype == PUBKEY_TYPE_OPGP) err = keybox_insert_keyblock (part->kbx_hd, blob, bloblen); else if (pktype == PUBKEY_TYPE_X509) { unsigned char sha1[20]; err = ksba_cert_new (&cert); if (err) goto leave; err = ksba_cert_init_from_mem (cert, blob, bloblen); if (err) goto leave; gcry_md_hash_buffer (GCRY_MD_SHA1, sha1, blob, bloblen); err = keybox_insert_cert (part->kbx_hd, cert, sha1); } else err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE); leave: ksba_cert_release (cert); return err; } /* Update (BLOB,BLOBLEN) in the keybox. BACKEND_HD is the handle for * this backend and REQUEST is the current database request object. */ gpg_error_t be_kbx_update (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request, enum pubkey_types pktype, const void *blob, size_t bloblen) { gpg_error_t err; db_request_part_t part; ksba_cert_t cert = NULL; (void)ctrl; log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX); log_assert (request); /* Find the specific request part or allocate it. */ err = be_find_request_part (backend_hd, request, &part); if (err) goto leave; /* FIXME: We make use of the fact that we know that the caller * already did a keybox search. This needs to be made more * explicit. */ if (pktype == PUBKEY_TYPE_OPGP) { err = keybox_update_keyblock (part->kbx_hd, blob, bloblen); } else if (pktype == PUBKEY_TYPE_X509) { unsigned char sha1[20]; err = ksba_cert_new (&cert); if (err) goto leave; err = ksba_cert_init_from_mem (cert, blob, bloblen); if (err) goto leave; gcry_md_hash_buffer (GCRY_MD_SHA1, sha1, blob, bloblen); err = keybox_update_cert (part->kbx_hd, cert, sha1); } else err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE); leave: ksba_cert_release (cert); return err; } /* Delete the blob from the keybox. BACKEND_HD is the handle for * this backend and REQUEST is the current database request object. */ gpg_error_t be_kbx_delete (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request) { gpg_error_t err; db_request_part_t part; (void)ctrl; log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX); log_assert (request); /* Find the specific request part or allocate it. */ err = be_find_request_part (backend_hd, request, &part); if (err) goto leave; /* FIXME: We make use of the fact that we know that the caller * already did a keybox search. This needs to be made more * explicit. */ err = keybox_delete (part->kbx_hd); leave: return err; } diff --git a/kbx/kbxutil.c b/kbx/kbxutil.c index 45f23d23b..c76809bc4 100644 --- a/kbx/kbxutil.c +++ b/kbx/kbxutil.c @@ -1,647 +1,647 @@ /* 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 . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include #include #include #include "../common/logging.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 gpgrt_opt_t 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 9: p = "GPL-3.0-or-later"; break; case 11: p = "kbxutil (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: 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_LOGLVL_CONT; break; case GCRY_LOG_INFO: level = GPGRT_LOGLVL_INFO; break; case GCRY_LOG_WARN: level = GPGRT_LOGLVL_WARN; break; case GCRY_LOG_ERROR:level = GPGRT_LOGLVL_ERROR; break; case GCRY_LOG_FATAL:level = GPGRT_LOGLVL_FATAL; break; case GCRY_LOG_BUG: level = GPGRT_LOGLVL_BUG; break; case GCRY_LOG_DEBUG:level = GPGRT_LOGLVL_DEBUG; break; default: level = GPGRT_LOGLVL_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) { gpgrt_argparse_t pargs; enum cmd_and_opt_values cmd = 0; unsigned long from = 0, to = ULONG_MAX; int dry_run = 0; early_system_init (); gpgrt_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= ARGPARSE_FLAG_KEEP; while (gpgrt_argparse (NULL,&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; } } gpgrt_argparse (NULL, &pargs, NULL); 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 da23289d3..0af3aafb3 100644 --- a/kbx/keybox-defs.h +++ b/kbx/keybox-defs.h @@ -1,213 +1,213 @@ /* 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; int version; unsigned char grip[20]; unsigned char keyid[8]; int fprlen; /* Either 16, 20 or 32 */ unsigned char fpr[32]; }; 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); char *_keybox_x509_email_kludge (const char *name); #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 7a1b43aa7..f20001dc2 100644 --- a/kbx/keybox-file.c +++ b/kbx/keybox-file.c @@ -1,188 +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. Either FP or STREAM must be used. */ +/* Write a fresh header type blob. */ gpg_error_t -_keybox_write_header_blob (FILE *fp, estream_t stream, 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 (fp) - { - if (fwrite (image, 32, 1, fp) != 1) - return gpg_error_from_syserror (); - } - else - { - if (es_fwrite (image, 32, 1, stream) != 1) - return gpg_error_from_syserror (); - } + 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 248a0a543..48af5c7a1 100644 --- a/kbx/keybox-init.c +++ b/kbx/keybox-init.c @@ -1,331 +1,331 @@ /* 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. 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 c07cd48c9..5ff9111fa 100644 --- a/kbx/keybox-search.c +++ b/kbx/keybox-search.c @@ -1,1494 +1,1494 @@ /* 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; int fpr32; buffer = _keybox_get_blob_image (blob, &length); if (length < 48) return 0; /* blob too short */ fpr32 = buffer[5] == 2; if (fpr32 && length < 56) return 0; /* blob to short */ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18); if (!nkeys || keyinfolen < (fpr32?56:28)) return 0; /* invalid blob */ if (fpr32 && (get16 (buffer + 20 + 32) & 0x80)) { /* 32 byte fingerprint. */ kid[0] = get32 (buffer + 20); kid[1] = get32 (buffer + 20 + 4); } else /* 20 byte fingerprint. */ { kid[0] = get32 (buffer + 20 + 12); kid[1] = get32 (buffer + 20 + 16); } 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, unsigned int fprlen) { const unsigned char *buffer; size_t length; size_t pos, off; size_t nkeys, keyinfolen; int idx, fpr32, storedfprlen; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ fpr32 = buffer[5] == 2; /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < (fpr32?56: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 (fpr32) storedfprlen = (get16 (buffer + off + 32) & 0x80)? 32:20; else storedfprlen = 20; if (storedfprlen == fprlen && !memcmp (buffer + off, fpr, storedfprlen)) return idx+1; /* found */ } return 0; /* not found */ } /* Helper for has_short_kid and has_long_kid. */ 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, fpr32, storedfprlen; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ fpr32 = buffer[5] == 2; /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (keyinfolen < (fpr32?56:28)) return 0; /* invalid blob */ pos = 20; if (pos + (uint64_t)keyinfolen*nkeys > (uint64_t)length) return 0; /* out of bounds */ if (fpr32) fproff = 0; /* keyid are the high-order bits. */ for (idx=0; idx < nkeys; idx++) { off = pos + idx*keyinfolen; if (fpr32) storedfprlen = (get16 (buffer + off + 32) & 0x80)? 32:20; else storedfprlen = 20; if ((fpr32 || storedfprlen == fproff + fprlen) && !memcmp (buffer + off + fproff, fpr, fprlen)) return idx+1; /* found */ } return 0; /* not found */ } /* Returns true if found. */ static int blob_cmp_ubid (KEYBOXBLOB blob, const unsigned char *ubid) { const unsigned char *buffer; size_t length; size_t pos; size_t nkeys, keyinfolen; int fpr32; buffer = _keybox_get_blob_image (blob, &length); if (length < 40) return 0; /* blob too short */ fpr32 = buffer[5] == 2; /*keys*/ nkeys = get16 (buffer + 16); keyinfolen = get16 (buffer + 18 ); if (!nkeys || keyinfolen < (fpr32?56:28)) return 0; /* invalid blob */ pos = 20; if (pos + (uint64_t)keyinfolen*nkeys > (uint64_t)length) return 0; /* out of bounds */ if (!memcmp (buffer + pos, ubid, UBID_LEN)) return 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) { const unsigned char *buffer; size_t length; int fpr32; unsigned char buf[4]; buffer = _keybox_get_blob_image (blob, &length); if (length < 48) return 0; /* blob too short */ fpr32 = buffer[5] == 2; if (fpr32 && length < 56) return 0; /* blob to short */ buf[0] = lkid >> 24; buf[1] = lkid >> 16; buf[2] = lkid >> 8; buf[3] = lkid; if (fpr32) return blob_cmp_fpr_part (blob, buf, 0, 4); else return blob_cmp_fpr_part (blob, buf, 16, 4); } static inline int has_long_kid (KEYBOXBLOB blob, u32 mkid, u32 lkid) { const unsigned char *buffer; size_t length; int fpr32; unsigned char buf[8]; buffer = _keybox_get_blob_image (blob, &length); if (length < 48) return 0; /* blob too short */ fpr32 = buffer[5] == 2; if (fpr32 && length < 56) return 0; /* blob to short */ 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; if (fpr32) return blob_cmp_fpr_part (blob, buf, 0, 8); else return blob_cmp_fpr_part (blob, buf, 12, 8); } static inline int has_fingerprint (KEYBOXBLOB blob, const unsigned char *fpr, unsigned int fprlen) { return blob_cmp_fpr (blob, fpr, fprlen); } 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; } /* The UBID is the primary fingerprint. For OpenPGP v5 keys only the * leftmost 20 bytes (UBID_LEN) are used. */ static inline int has_ubid (KEYBOXBLOB blob, const unsigned char *ubid) { return blob_cmp_ubid (blob, ubid); } 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 record 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].snhex && !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].snhex) { unsigned char *sn; s = desc[n].sn; for (i=0; *s && *s != '/' && i < desc[n].snlen; 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: pk_no = has_fingerprint (blob, desc[n].u.fpr, desc[n].fprlen); 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_UBID: if (has_ubid (blob, desc[n].u.ubid)) 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 raw data from the last found blob. Caller must release * the value stored at R_BUFFER. If called with NULL for R_BUFFER * only the needed length for the buffer and the public key type is * returned. R_PUBKEY_TYPE and R_UBID can be used to return these * attributes. */ gpg_error_t keybox_get_data (KEYBOX_HANDLE hd, void **r_buffer, size_t *r_length, enum pubkey_types *r_pubkey_type, unsigned char *r_ubid) { const unsigned char *buffer; size_t length; size_t image_off, image_len; if (r_buffer) *r_buffer = NULL; if (r_length) *r_length = 0; if (r_pubkey_type) *r_pubkey_type = PUBKEY_TYPE_UNKNOWN; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->found.blob) return gpg_error (GPG_ERR_NOTHING_FOUND); switch (blob_get_type (hd->found.blob)) { case KEYBOX_BLOBTYPE_PGP: if (r_pubkey_type) *r_pubkey_type = PUBKEY_TYPE_OPGP; break; case KEYBOX_BLOBTYPE_X509: if (r_pubkey_type) *r_pubkey_type = PUBKEY_TYPE_X509; break; default: 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); if (r_ubid) { size_t keyinfolen; /* We do a quick but sufficient consistency check. For the full * check see blob_cmp_ubid. */ if (!get16 (buffer + 16) /* No keys. */ || (keyinfolen = get16 (buffer + 18)) < 28 || (20 + (uint64_t)keyinfolen) > (uint64_t)length) return gpg_error (GPG_ERR_TOO_SHORT); memcpy (r_ubid, buffer + 20, UBID_LEN); } if (r_length) *r_length = image_len; if (r_buffer) { *r_buffer = xtrymalloc (image_len); if (!*r_buffer) return gpg_error_from_syserror (); memcpy (*r_buffer, buffer + image_off, image_len); } return 0; } /* 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 return the * index of the key or user id which 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 e263bc3d6..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, NULL, for_openpgp); + 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, NULL, hd->for_openpgp); + 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 6e5a51c63..9bff271ea 100644 --- a/kbx/keybox.h +++ b/kbx/keybox.h @@ -1,142 +1,141 @@ /* 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. */ -gpg_error_t _keybox_write_header_blob (FILE *fp, estream_t stream, - int openpgp_flag); +gpg_error_t _keybox_write_header_blob (estream_t fp, int openpgp_flag); /*-- keybox-search.c --*/ gpg_error_t keybox_get_data (KEYBOX_HANDLE hd, void **r_buffer, size_t *r_length, enum pubkey_types *r_pubkey_type, unsigned char *r_ubid); gpg_error_t keybox_get_keyblock (KEYBOX_HANDLE hd, iobuf_t *r_iobuf, int *r_pk_no, int *r_uid_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 f772510c3..d02c0ef91 100644 --- a/scd/app.c +++ b/scd/app.c @@ -1,2367 +1,2367 @@ /* 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 "iso7816.h" #include "apdu.h" #include "../common/tlv.h" #include "../common/membuf.h" /* Forward declaration of internal function. */ static gpg_error_t select_additional_application_internal (card_t card, apptype_t req_apptype); static gpg_error_t send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl); static gpg_error_t run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev); /* Lock to protect the list of cards and its associated * applications. */ static npth_mutex_t card_list_lock; /* Notification to threads which keep watching the status change. */ static npth_cond_t notify_cond; /* A list of card contexts. A card is a collection of applications * (described by app_t) on the same physical token. */ static card_t card_top; /* The list of application names and their select function. If no * specific application is selected the first available application on * a card is selected. */ struct app_priority_list_s { apptype_t apptype; char const *name; gpg_error_t (*select_func)(app_t); }; static struct app_priority_list_s app_priority_list[] = {{ APPTYPE_OPENPGP , "openpgp", app_select_openpgp }, { APPTYPE_PIV , "piv", app_select_piv }, { APPTYPE_NKS , "nks", app_select_nks }, { APPTYPE_P15 , "p15", app_select_p15 }, { APPTYPE_GELDKARTE, "geldkarte", app_select_geldkarte }, { APPTYPE_DINSIG , "dinsig", app_select_dinsig }, { APPTYPE_SC_HSM , "sc-hsm", app_select_sc_hsm }, { APPTYPE_NONE , NULL, NULL } /* APPTYPE_UNDEFINED is special and not listed here. */ }; /* Map a cardtype to a string. Never returns NULL. */ const char * strcardtype (cardtype_t t) { switch (t) { case CARDTYPE_GENERIC: return "generic"; case CARDTYPE_GNUK: return "gnuk"; case CARDTYPE_YUBIKEY: return "yubikey"; case CARDTYPE_ZEITCONTROL: return "zeitcontrol"; } return "?"; } /* Map an application type to a string. Never returns NULL. */ const char * strapptype (apptype_t t) { int i; for (i=0; app_priority_list[i].apptype; i++) if (app_priority_list[i].apptype == t) return app_priority_list[i].name; return t == APPTYPE_UNDEFINED? "undefined" : t? "?" : "none"; } const char * xstrapptype (app_t app) { return app? strapptype (app->apptype) : "[no_app]"; } /* Return the apptype for NAME. */ static apptype_t apptype_from_name (const char *name) { int i; if (!name) return APPTYPE_NONE; for (i=0; app_priority_list[i].apptype; i++) if (!ascii_strcasecmp (app_priority_list[i].name, name)) return app_priority_list[i].apptype; if (!ascii_strcasecmp ("undefined", name)) return APPTYPE_UNDEFINED; return APPTYPE_NONE; } /* Return the apptype for KEYREF. This is the first part of the * KEYREF up to the dot. */ static apptype_t apptype_from_keyref (const char *keyref) { int i; unsigned int n; const char *s; if (!keyref) return APPTYPE_NONE; s = strchr (keyref, '.'); if (!s || s == keyref || !s[1]) return APPTYPE_NONE; /* Not a valid keyref. */ n = s - keyref; for (i=0; app_priority_list[i].apptype; i++) if (strlen (app_priority_list[i].name) == n && !ascii_strncasecmp (app_priority_list[i].name, keyref, n)) return app_priority_list[i].apptype; return APPTYPE_NONE; } /* Initialization function to change the default app_priority_list. * LIST is a list of comma or space separated strings with application * names. Unknown names will only result in warning message. * Application not mentioned in LIST are used in their original order * after the given once. */ void app_update_priority_list (const char *arg) { struct app_priority_list_s save; char **names; int i, j, idx; names = strtokenize (arg, ", "); if (!names) log_fatal ("strtokenize failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); idx = 0; for (i=0; names[i]; i++) { ascii_strlwr (names[i]); for (j=0; j < i; j++) if (!strcmp (names[j], names[i])) break; if (j < i) { log_info ("warning: duplicate application '%s' in priority list\n", names[i]); continue; } for (j=idx; app_priority_list[j].name; j++) if (!strcmp (names[i], app_priority_list[j].name)) break; if (!app_priority_list[j].name) { log_info ("warning: unknown application '%s' in priority list\n", names[i]); continue; } save = app_priority_list[idx]; app_priority_list[idx] = app_priority_list[j]; app_priority_list[j] = save; idx++; } log_assert (idx < DIM (app_priority_list)); xfree (names); for (i=0; app_priority_list[i].name; i++) log_info ("app priority %d: %s\n", i, app_priority_list[i].name); } 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 CARD. 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 card is not actually used. * This allows an actual connection to assume that it never shares a * card (while performing one command). Returns 0 on success; only * then the unlock_reader function must be called after returning from * the handler. Right now we assume a that a reader has just one * card; this may eventually need refinement. */ static gpg_error_t lock_card (card_t card, ctrl_t ctrl) { if (npth_mutex_lock (&card->lock)) { gpg_error_t err = gpg_error_from_syserror (); log_error ("failed to acquire CARD lock for %p: %s\n", card, gpg_strerror (err)); return err; } apdu_set_progress_cb (card->slot, print_progress_line, ctrl); apdu_set_prompt_cb (card->slot, popup_prompt, ctrl); return 0; } /* Release a lock on a card. See lock_reader(). */ static void unlock_card (card_t card) { apdu_set_progress_cb (card->slot, NULL, NULL); apdu_set_prompt_cb (card->slot, NULL, NULL); if (npth_mutex_unlock (&card->lock)) { gpg_error_t err = gpg_error_from_syserror (); log_error ("failed to release CARD lock for %p: %s\n", card, 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) { card_t c; app_t a; npth_mutex_lock (&card_list_lock); for (c = card_top; c; c = c->next) { log_info ("app_dump_state: card=%p slot=%d type=%s\n", c, c->slot, strcardtype (c->cardtype)); /* FIXME The use of log_info risks a race! */ for (a=c->app; a; a = a->next) log_info ("app_dump_state: app=%p type='%s'\n", a, strapptype (a->apptype)); } npth_mutex_unlock (&card_list_lock); } gpg_error_t app_send_devinfo (ctrl_t ctrl) { card_t c; app_t a; int no_device; send_status_direct (ctrl, "DEVINFO_START", ""); npth_mutex_lock (&card_list_lock); no_device = (card_top == NULL); for (c = card_top; c; c = c->next) { char *serialno; char card_info[80]; serialno = card_get_serialno (c); snprintf (card_info, sizeof card_info, "DEVICE %s %s", strcardtype (c->cardtype), serialno); xfree (serialno); for (a = c->app; a; a = a->next) send_status_direct (ctrl, card_info, strapptype (a->apptype)); } npth_mutex_unlock (&card_list_lock); send_status_direct (ctrl, "DEVINFO_END", ""); return no_device ? gpg_error (GPG_ERR_NOT_FOUND): 0; } /* 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 */ } /* This function is mainly 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. Return values are: * 0 - No conflict * GPG_ERR_FALSE - Another application is in use but it is possible * to switch to the requested application. * Other code - Switching is not possible. * * If SERIALNO_BIN is not NULL a conflict is only asserted if the * serialno of the card matches. */ gpg_error_t check_application_conflict (card_t card, const char *name, const unsigned char *serialno_bin, size_t serialno_bin_len) { apptype_t apptype; if (!card || !name) return 0; if (!card->app) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); /* Should not happen. */ if (serialno_bin && card->serialno) { if (serialno_bin_len != card->serialnolen || memcmp (serialno_bin, card->serialno, card->serialnolen)) return 0; /* The card does not match the requested S/N. */ } apptype = apptype_from_name (name); if (card->app->apptype == apptype) return 0; if (card->app->apptype == APPTYPE_UNDEFINED) return 0; if (card->cardtype == CARDTYPE_YUBIKEY) { if (card->app->apptype == APPTYPE_OPENPGP) { /* Current app is OpenPGP. */ if (!ascii_strcasecmp (name, "piv")) return gpg_error (GPG_ERR_FALSE); /* Switching allowed. */ } else if (card->app->apptype == APPTYPE_PIV) { /* Current app is PIV. */ if (!ascii_strcasecmp (name, "openpgp")) return gpg_error (GPG_ERR_FALSE); /* Switching allowed. */ } } log_info ("application '%s' in use - can't switch\n", strapptype (card->app->apptype)); return gpg_error (GPG_ERR_CONFLICT); } gpg_error_t card_reset (card_t card, ctrl_t ctrl, int send_reset) { gpg_error_t err = 0; if (send_reset) { int sw; lock_card (card, ctrl); sw = apdu_reset (card->slot); if (sw) err = gpg_error (GPG_ERR_CARD_RESET); card->reset_requested = 1; unlock_card (card); scd_kick_the_loop (); gnupg_sleep (1); } else { ctrl->card_ctx = NULL; ctrl->current_apptype = APPTYPE_NONE; card_unref (card); } 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; card_t card = NULL; app_t app = NULL; unsigned char *result = NULL; size_t resultlen; int want_undefined; int i; /* Need to allocate a new card object */ card = xtrycalloc (1, sizeof *card); if (!card) { err = gpg_error_from_syserror (); log_info ("error allocating context: %s\n", gpg_strerror (err)); return err; } card->slot = slot; card->card_status = (unsigned int)-1; if (npth_mutex_init (&card->lock, NULL)) { err = gpg_error_from_syserror (); log_error ("error initializing mutex: %s\n", gpg_strerror (err)); xfree (card); return err; } err = lock_card (card, ctrl); if (err) { xfree (card); 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 (gpg_err_code (err) == GPG_ERR_CARD) { /* Might be SW==0x7D00. Let's test whether it is a Yubikey * by selecting its manager application and then reading the * config. */ static char const yk_aid[] = { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17 }; /*MGR*/ static char const otp_aid[] = { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01 }; /*OTP*/ unsigned char *buf; size_t buflen; const unsigned char *s0; unsigned char formfactor; size_t n; if (!iso7816_select_application (slot, yk_aid, sizeof yk_aid, 0x0001) && !iso7816_apdu_direct (slot, "\x00\x1d\x00\x00\x00", 5, 0, NULL, &buf, &buflen)) { card->cardtype = CARDTYPE_YUBIKEY; if (opt.verbose) { log_info ("Yubico: config="); log_printhex (buf, buflen, ""); } /* We skip the first byte which seems to be the total * length of the config data. */ if (buflen > 1) { s0 = find_tlv (buf+1, buflen-1, 0x04, &n); /* Form factor */ formfactor = (s0 && n == 1)? *s0 : 0; s0 = find_tlv (buf+1, buflen-1, 0x02, &n); /* Serial */ if (s0 && n >= 4) { card->serialno = xtrymalloc (3 + 1 + n); if (card->serialno) { card->serialnolen = 3 + 1 + n; card->serialno[0] = 0xff; card->serialno[1] = 0x02; card->serialno[2] = 0x0; card->serialno[3] = formfactor; memcpy (card->serialno + 4, s0, n); /* Note that we do not clear the error * so that no further serial number * testing is done. After all we just * set the serial number. */ } } s0 = find_tlv (buf+1, buflen-1, 0x05, &n); /* version */ if (s0 && n == 3) card->cardversion = ((s0[0]<<16)|(s0[1]<<8)|s0[2]); else if (!s0) { /* No version - this is not a Yubikey 5. We now * switch to the OTP app and take the first * three bytes of the response as version * number. */ xfree (buf); buf = NULL; if (!iso7816_select_application_ext (slot, otp_aid, sizeof otp_aid, 1, &buf, &buflen) && buflen > 3) card->cardversion = ((buf[0]<<16)|(buf[1]<<8)|buf[2]); } } xfree (buf); } } else { unsigned char *atr; size_t atrlen; /* This is heuristics to identify different implementations. */ atr = apdu_get_atr (slot, &atrlen); if (atr) { if (atrlen == 21 && atr[2] == 0x11) card->cardtype = CARDTYPE_GNUK; else if (atrlen == 21 && atr[7] == 0x75) card->cardtype = CARDTYPE_ZEITCONTROL; xfree (atr); } } 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 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); card->serialno = result; card->serialnolen = n; err = app_munge_serialno (card); if (err) goto leave; } else xfree (result); result = NULL; } } /* Allocate a new app object. */ app = xtrycalloc (1, sizeof *app); if (!app) { err = gpg_error_from_syserror (); log_info ("error allocating app context: %s\n", gpg_strerror (err)); goto leave; } card->app = app; app->card = card; /* Figure out the application to use. */ if (want_undefined) { /* We switch to the "undefined" application only if explicitly requested. */ app->apptype = APPTYPE_UNDEFINED; /* Clear the error so that we don't run through the application * selection chain. */ err = 0; } else { /* 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; /* Set a default error so that we run through the application * selection chain. */ err = gpg_error (GPG_ERR_NOT_FOUND); } /* Find the first available app if NAME is NULL or the matching * NAME but only if that application is also enabled. */ for (i=0; err && app_priority_list[i].name; i++) { if (is_app_allowed (app_priority_list[i].name) && (!name || !strcmp (name, app_priority_list[i].name))) err = app_priority_list[i].select_func (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_card (card); xfree (app); xfree (card); return err; } card->periodical_check_needed = periodical_check_needed; card->next = card_top; card_top = card; unlock_card (card); return 0; } /* If called with NAME as NULL, select the best fitting application * and return its card context; otherwise select the application with * NAME and return its card context. Returns an error code and stores * NULL at R_CARD if no application was found or no card is present. */ gpg_error_t select_application (ctrl_t ctrl, const char *name, card_t *r_card, int scan, const unsigned char *serialno_bin, size_t serialno_bin_len) { gpg_error_t err = 0; card_t card, card_prev = NULL; *r_card = NULL; npth_mutex_lock (&card_list_lock); if (scan || !card_top) { struct dev_list *l; int new_card = 0; /* Scan the devices to find new device(s). */ err = apdu_dev_list_start (opt.reader_port, &l); if (err) { npth_mutex_unlock (&card_list_lock); return err; } while (1) { int slot; int periodical_check_needed_this; slot = apdu_open_reader (l); 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_card++; } if (err) { pincache_put (ctrl, slot, NULL, NULL, NULL, 0); apdu_close_reader (slot); } } apdu_dev_list_finish (l); /* If new device(s), kick the scdaemon loop. */ if (new_card) scd_kick_the_loop (); } for (card = card_top; card; card = card->next) { lock_card (card, ctrl); if (serialno_bin == NULL) break; if (card->serialnolen == serialno_bin_len && !memcmp (card->serialno, serialno_bin, card->serialnolen)) break; unlock_card (card); card_prev = card; } if (card) { err = check_application_conflict (card, name, NULL, 0); if (!err) ctrl->current_apptype = card->app ? card->app->apptype : APPTYPE_NONE; else if (gpg_err_code (err) == GPG_ERR_FALSE) { apptype_t req_apptype = apptype_from_name (name); if (!req_apptype) err = gpg_error (GPG_ERR_NOT_FOUND); else { err = select_additional_application_internal (card, req_apptype); if (!err) ctrl->current_apptype = req_apptype; } } if (!err) { /* Note: We do not use card_ref as we are already locked. */ card->ref_count++; *r_card = card; if (card_prev) { card_prev->next = card->next; card->next = card_top; card_top = card; } } unlock_card (card); } else err = gpg_error (GPG_ERR_ENODEV); npth_mutex_unlock (&card_list_lock); return err; } /* Switch the current card for the session CTRL and print a SERIALNO * status line on success. (SERIALNO, SERIALNOLEN) is the binary s/n * of the card to switch to. */ gpg_error_t app_switch_current_card (ctrl_t ctrl, const unsigned char *serialno, size_t serialnolen) { gpg_error_t err; card_t card, cardtmp; npth_mutex_lock (&card_list_lock); if (!ctrl->card_ctx) { err = gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); goto leave; } if (serialno && serialnolen) { for (card = card_top; card; card = card->next) { if (card->serialnolen == serialnolen && !memcmp (card->serialno, serialno, card->serialnolen)) break; } if (!card) { err = gpg_error (GPG_ERR_NOT_FOUND); goto leave; } /* Note: We do not use card_ref here because we only swap the * context of the current session and there is no chance of a * context switch. This also works if the card stays the same. */ cardtmp = ctrl->card_ctx; ctrl->card_ctx = card; card->ref_count++; card_unref_locked (cardtmp); } /* Print the status line. */ err = send_serialno_and_app_status (ctrl->card_ctx, 0, ctrl); leave: npth_mutex_unlock (&card_list_lock); return err; } static gpg_error_t select_additional_application_internal (card_t card, apptype_t req_apptype) { gpg_error_t err = 0; app_t app; int i; /* Check that the requested app has not yet been put onto the list. */ for (app = card->app; app; app = app->next) if (app->apptype == req_apptype) { /* We already got this one. Note that in this case we don't * make it the current one but it doesn't matter because * maybe_switch_app will do that anyway. */ err = 0; app = NULL; goto leave; } /* Allocate a new app object. */ app = xtrycalloc (1, sizeof *app); if (!app) { err = gpg_error_from_syserror (); log_info ("error allocating app context: %s\n", gpg_strerror (err)); goto leave; } app->card = card; /* Find the app and run the select. */ for (i=0; app_priority_list[i].apptype; i++) { if (app_priority_list[i].apptype == req_apptype && is_app_allowed (app_priority_list[i].name)) { err = app_priority_list[i].select_func (app); break; } } if (!app_priority_list[i].apptype || (err && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE)) err = gpg_error (GPG_ERR_NOT_SUPPORTED); if (err) goto leave; /* Add this app. We make it the current one to avoid an extra * reselect by maybe_switch_app after the select we just did. */ app->next = card->app; card->app = app; log_info ("added app '%s' to the card context and switched\n", strapptype (app->apptype)); leave: if (err) xfree (app); return err; } /* Add all possible additional applications to the card context but do * not change the current one. This currently works only for Yubikeys. */ static gpg_error_t select_all_additional_applications_internal (ctrl_t ctrl, card_t card) { gpg_error_t err = 0; apptype_t candidates[3]; int i, j; int any_new = 0; if (card->cardtype == CARDTYPE_YUBIKEY) { candidates[0] = APPTYPE_OPENPGP; candidates[1] = APPTYPE_PIV; candidates[2] = APPTYPE_NONE; } else { candidates[0] = APPTYPE_NONE; } /* Find the app and run the select. */ for (i=0; app_priority_list[i].apptype; i++) { app_t app, app_r, app_prev; for (j=0; candidates[j]; j++) if (candidates[j] == app_priority_list[i].apptype && is_app_allowed (app_priority_list[i].name)) break; if (!candidates[j]) continue; for (app = card->app; app; app = app->next) if (app->apptype == candidates[j]) break; if (app) continue; /* Already on the list of apps. */ app = xtrycalloc (1, sizeof *app); if (!app) { err = gpg_error_from_syserror (); log_info ("error allocating app context: %s\n", gpg_strerror (err)); goto leave; } app->card = card; err = app_priority_list[i].select_func (app); if (err) { log_error ("error selecting additional app '%s': %s - skipped\n", strapptype (candidates[j]), gpg_strerror (err)); err = 0; xfree (app); } else { /* Append to the list of apps. */ app_prev = card->app; for (app_r=app_prev->next; app_r; app_prev=app_r, app_r=app_r->next) ; app_prev->next = app; log_info ("added app '%s' to the card context\n", strapptype (app->apptype)); any_new = 1; } } /* If we found a new application we need to reselect the original * application so that we are in a well defined state. */ if (!err && any_new && card->app && card->app->fnc.reselect) err = run_reselect (ctrl, card, card->app, NULL); leave: return err; } /* This function needs to be called with the NAME of the new * application to be selected on CARD. On success the application is * added to the list of the card's active applications as currently * active application. On error no new application is allocated. * Selecting an already selected application has no effect. */ gpg_error_t select_additional_application (ctrl_t ctrl, const char *name) { gpg_error_t err = 0; apptype_t req_apptype; card_t card; if (!name) req_apptype = 0; else { req_apptype = apptype_from_name (name); if (!req_apptype) return gpg_error (GPG_ERR_NOT_FOUND); } card = ctrl->card_ctx; if (!card) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); err = lock_card (card, ctrl); if (err) return err; if (req_apptype) { err = select_additional_application_internal (card, req_apptype); if (!err) { ctrl->current_apptype = req_apptype; log_debug ("current_apptype is set to %s\n", name); } } else { err = select_all_additional_applications_internal (ctrl, card); } unlock_card (card); return err; } char * get_supported_applications (void) { int idx; size_t nbytes; char *buffer, *p; const char *s; for (nbytes=1, idx=0; (s=app_priority_list[idx].name); idx++) nbytes += strlen (s) + 1 + 1; buffer = xtrymalloc (nbytes); if (!buffer) return NULL; for (p=buffer, idx=0; (s=app_priority_list[idx].name); idx++) if (is_app_allowed (s)) p = stpcpy (stpcpy (p, s), ":\n"); *p = 0; return buffer; } /* Deallocate the application. */ static void deallocate_card (card_t card) { card_t c, c_prev = NULL; app_t a, anext; for (c = card_top; c; c = c->next) if (c == card) { if (c_prev == NULL) card_top = c->next; else c_prev->next = c->next; break; } else c_prev = c; if (card->ref_count) log_error ("releasing still used card context (%d)\n", card->ref_count); for (a = card->app; a; a = anext) { if (a->fnc.deinit) { a->fnc.deinit (a); a->fnc.deinit = NULL; } anext = a->next; xfree (a); } xfree (card->serialno); unlock_card (card); xfree (card); } /* Increment the reference counter of CARD. Returns CARD. */ card_t card_ref (card_t card) { lock_card (card, NULL); ++card->ref_count; unlock_card (card); return card; } /* Decrement the reference counter for CARD. Note that we are using * reference counting to track the users of the card's application and * are deferring the actual deallocation to allow for a later reuse by * a new connection. Using NULL for CARD is a no-op. */ void card_unref (card_t card) { if (!card) return; /* We don't deallocate CARD 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. */ lock_card (card, NULL); card_unref_locked (card); unlock_card (card); } /* This is the same as card_unref but assumes that CARD is already * locked. */ void card_unref_locked (card_t card) { if (!card) return; if (!card->ref_count) log_bug ("tried to release an already released card context\n"); --card->ref_count; } /* 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 02 00 = Serial number from Yubikey config FF 7F 00 = No serialno. All other serial numbers not starting with FF are used as they are. */ gpg_error_t app_munge_serialno (card_t card) { if (card->serialnolen && card->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 (card->serialnolen + 3); if (!p) return gpg_error_from_syserror (); memcpy (p, "\xff\0", 3); memcpy (p+3, card->serialno, card->serialnolen); card->serialnolen += 3; xfree (card->serialno); card->serialno = p; } else if (!card->serialnolen) { unsigned char *p = xtrymalloc (3); if (!p) return gpg_error_from_syserror (); memcpy (p, "\xff\x7f", 3); card->serialnolen = 3; xfree (card->serialno); card->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 * card_get_serialno (card_t card) { char *serial; if (!card) return NULL; if (!card->serialnolen) serial = xtrystrdup ("FF7F00"); else serial = bin2hex (card->serialno, card->serialnolen, NULL); return serial; } /* Same as card_get_serialno but takes an APP object. */ char * app_get_serialno (app_t app) { if (!app || !app->card) return NULL; return card_get_serialno (app->card); } /* Helper to run the reselect function. */ static gpg_error_t run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev) { gpg_error_t err; if (!a->fnc.reselect) { log_info ("slot %d, app %s: re-select not implemented\n", c->slot, xstrapptype (a)); return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); } /* Give the current app a chance to save some state before another * app is selected. We ignore errors here because that state saving * (e.g. putting PINs into a cache) is a convenience feature and not * required to always work. */ if (a_prev && a_prev->fnc.prep_reselect) { err = a_prev->fnc.prep_reselect (a_prev, ctrl); if (err) log_error ("slot %d, app %s: preparing re-select from %s failed: %s\n", c->slot, xstrapptype (a), xstrapptype (a_prev), gpg_strerror (err)); } err = a->fnc.reselect (a, ctrl); if (err) { log_error ("slot %d, app %s: error re-selecting: %s\n", c->slot, xstrapptype (a), gpg_strerror (err)); return err; } if (DBG_APP) log_debug ("slot %d, app %s: re-selected\n", c->slot, xstrapptype (a)); return 0; } /* Check that the card has been initialized and whether we need to * switch to another application on the same card. Switching means * that the new active app will be moved to the head of the list at * CARD->app. This function must be called with the card lock held. */ static gpg_error_t maybe_switch_app (ctrl_t ctrl, card_t card, const char *keyref) { gpg_error_t err; app_t app; app_t app_prev = NULL; apptype_t apptype; if (!card->ref_count || !card->app) return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); if (!ctrl->current_apptype) { /* For whatever reasons the current apptype has not been set - * fix that and use the current app. */ ctrl->current_apptype = card->app->apptype; return 0; } if (DBG_APP) log_debug ("slot %d: have=%s want=%s keyref=%s\n", card->slot, strapptype (card->app->apptype), strapptype (ctrl->current_apptype), keyref? keyref:"[none]"); app = NULL; if (keyref) { /* Switch based on the requested KEYREF. */ apptype = apptype_from_keyref (keyref); if (apptype) { for (app = card->app; app; app_prev = app, app = app->next) if (app->apptype == apptype) break; if (!app_prev && ctrl->current_apptype == card->app->apptype) return 0; /* Already the first app - no need to switch. */ } else if (strlen (keyref) == 40) { /* This looks like a keygrip. Iterate over all apps to find * the corresponding app. */ for (app = card->app; app; app_prev = app, app = app->next) if (app->fnc.with_keygrip && !app->fnc.with_keygrip (app, ctrl, KEYGRIP_ACTION_LOOKUP, keyref, 0)) break; if (!app_prev && ctrl->current_apptype == card->app->apptype) return 0; /* Already the first app - no need to switch. */ } } if (!app) { /* Switch based on the current application of this connection or * if a keyref based switch didn't worked. */ if (ctrl->current_apptype == card->app->apptype) return 0; /* No need to switch. */ app_prev = card->app; for (app = app_prev->next; app; app_prev = app, app = app->next) if (app->apptype == ctrl->current_apptype) break; } if (!app) return gpg_error (GPG_ERR_WRONG_CARD); err = run_reselect (ctrl, card, app, app_prev); if (err) return err; /* Swap APP with the head of the app list if needed. Note that APP * is not the head of the list. */ if (app_prev) { app_prev->next = app->next; app->next = card->app; card->app = app; } if (opt.verbose) log_info ("slot %d, app %s: %s\n", card->slot, xstrapptype (app), app_prev? "switched":"re-selected"); ctrl->current_apptype = app->apptype; return 0; } /* Helper for app_write_learn_status. */ static gpg_error_t write_learn_status_core (card_t card, app_t app, ctrl_t ctrl, unsigned int flags) { /* We do not send CARD and APPTYPE if only keypairinfo is requested. */ if (!(flags & APP_LEARN_FLAG_KEYPAIRINFO)) { if (card && card->cardtype) send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype)); if (card && card->cardversion) send_status_printf (ctrl, "CARDVERSION", "%X", card->cardversion); if (app->apptype) send_status_direct (ctrl, "APPTYPE", strapptype (app->apptype)); if (app->appversion) send_status_printf (ctrl, "APPVERSION", "%X", app->appversion); } return app->fnc.learn_status (app, ctrl, flags); } /* Write out the application specific status lines for the LEARN command. */ gpg_error_t app_write_learn_status (card_t card, ctrl_t ctrl, unsigned int flags) { gpg_error_t err, err2, tmperr; app_t app, last_app; int any_reselect = 0; if (!card) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; /* Always make sure that the current app for this connection has * been selected and is at the top of the list. */ if ((err = maybe_switch_app (ctrl, card, NULL))) ; else if (!card->app->fnc.learn_status) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { err = write_learn_status_core (card, card->app, ctrl, flags); if (!err && card->app->fnc.reselect && (flags & APP_LEARN_FLAG_MULTI)) { /* The current app has the reselect feature so that we can * loop over all other apps which are capable of a reselect * and finally reselect the first app again. Note that we * did the learn for the currently selected card above. */ app = last_app = card->app; for (app = app->next; app && !err; app = app->next) if (app->fnc.reselect) { if (last_app && last_app->fnc.prep_reselect) { tmperr = last_app->fnc.prep_reselect (last_app, ctrl); if (tmperr) log_info ("slot %d, app %s:" " preparing re-select from %s failed: %s\n", card->slot, xstrapptype (app), xstrapptype (last_app), gpg_strerror (tmperr)); } any_reselect = 1; err = app->fnc.reselect (app, ctrl); if (!err) { last_app = app; err = write_learn_status_core (NULL, app, ctrl, flags); } } app = card->app; if (any_reselect) { if (last_app && last_app->fnc.prep_reselect) { tmperr = last_app->fnc.prep_reselect (last_app, ctrl); if (tmperr) log_info ("slot %d, app %s:" " preparing re-select from %s failed: %s\n", card->slot, xstrapptype (app), xstrapptype (last_app), gpg_strerror (tmperr)); } err2 = app->fnc.reselect (app, ctrl); if (err2) { log_error ("error re-selecting '%s': %s\n", strapptype(app->apptype), gpg_strerror (err2)); if (!err) err = err2; } } } } unlock_card (card); 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 (card_t card, ctrl_t ctrl, const char *certid, unsigned char **cert, size_t *certlen) { gpg_error_t err; if (!card) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, certid))) ; else if (!card->app->fnc.readcert) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling readcert(%s)\n", card->slot, xstrapptype (card->app), certid); err = card->app->fnc.readcert (card->app, certid, cert, certlen); } unlock_card (card); 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. If the key is not required NULL may be passed for * PK; this makes sense if the APP_READKEY_FLAG_INFO has also been set. * * This function might not be supported by all applications. */ gpg_error_t app_readkey (card_t card, ctrl_t ctrl, const char *keyid, unsigned int flags, unsigned char **pk, size_t *pklen) { gpg_error_t err; if (pk) *pk = NULL; if (pklen) *pklen = 0; if (!card || !keyid) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keyid))) ; else if (!card->app->fnc.readkey) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling readkey(%s)\n", card->slot, xstrapptype (card->app), keyid); err = card->app->fnc.readkey (card->app, ctrl, keyid, flags, pk, pklen); } unlock_card (card); return err; } /* Perform a GETATTR operation. */ gpg_error_t app_getattr (card_t card, ctrl_t ctrl, const char *name) { gpg_error_t err; if (!card || !name || !*name) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, NULL))) ; else if (name && !strcmp (name, "CARDTYPE")) { send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype)); } else if (name && !strcmp (name, "APPTYPE")) { send_status_direct (ctrl, "APPTYPE", strapptype (card->app->apptype)); } else if (name && !strcmp (name, "SERIALNO")) { char *serial; serial = card_get_serialno (card); if (!serial) err = gpg_error (GPG_ERR_INV_VALUE); else { send_status_direct (ctrl, "SERIALNO", serial); xfree (serial); } } else if (!card->app->fnc.getattr) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling getattr(%s)\n", card->slot, xstrapptype (card->app), name); err = card->app->fnc.getattr (card->app, ctrl, name); } unlock_card (card); return err; } /* Perform a SETATTR operation. */ gpg_error_t app_setattr (card_t card, 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 (!card || !name || !*name || !value) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, NULL))) ; else if (!card->app->fnc.setattr) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling setattr(%s)\n", card->slot, xstrapptype (card->app), name); err = card->app->fnc.setattr (card->app, ctrl, name, pincb, pincb_arg, value, valuelen); } unlock_card (card); 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 (card_t card, 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 (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keyidstr))) ; else if (!card->app->fnc.sign) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling sign(%s)\n", card->slot, xstrapptype (card->app), keyidstr); err = card->app->fnc.sign (card->app, ctrl, keyidstr, hashalgo, pincb, pincb_arg, indata, indatalen, outdata, outdatalen); } unlock_card (card); 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 (card_t card, 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 (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keyidstr))) ; else if (!card->app->fnc.auth) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling auth(%s)\n", card->slot, xstrapptype (card->app), keyidstr); err = card->app->fnc.auth (card->app, ctrl, keyidstr, pincb, pincb_arg, indata, indatalen, outdata, outdatalen); } unlock_card (card); 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 (card_t card, 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 (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keyidstr))) ; else if (!card->app->fnc.decipher) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling decipher(%s)\n", card->slot, xstrapptype (card->app), keyidstr); err = card->app->fnc.decipher (card->app, ctrl, keyidstr, pincb, pincb_arg, indata, indatalen, outdata, outdatalen, r_info); } unlock_card (card); if (opt.verbose) log_info ("operation decipher result: %s\n", gpg_strerror (err)); return err; } /* Perform the WRITECERT operation. */ gpg_error_t app_writecert (card_t card, 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 (!card || !certidstr || !*certidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, certidstr))) ; else if (!card->app->fnc.writecert) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling writecert(%s)\n", card->slot, xstrapptype (card->app), certidstr); err = card->app->fnc.writecert (card->app, ctrl, certidstr, pincb, pincb_arg, data, datalen); } unlock_card (card); if (opt.verbose) log_info ("operation writecert result: %s\n", gpg_strerror (err)); return err; } /* Perform the WRITEKEY operation. */ gpg_error_t app_writekey (card_t card, 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 (!card || !keyidstr || !*keyidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keyidstr))) ; else if (!card->app->fnc.writekey) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling writekey(%s)\n", card->slot, xstrapptype (card->app), keyidstr); err = card->app->fnc.writekey (card->app, ctrl, keyidstr, flags, pincb, pincb_arg, keydata, keydatalen); } unlock_card (card); if (opt.verbose) log_info ("operation writekey result: %s\n", gpg_strerror (err)); return err; } /* Perform a GENKEY operation. */ gpg_error_t app_genkey (card_t card, 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 (!card || !keynostr || !*keynostr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, keynostr))) ; else if (!card->app->fnc.genkey) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling genkey(%s)\n", card->slot, xstrapptype (card->app), keynostr); err = card->app->fnc.genkey (card->app, ctrl, keynostr, keytype, flags, createtime, pincb, pincb_arg); } unlock_card (card); 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 (card_t card, ctrl_t ctrl, size_t nbytes, unsigned char *buffer) { gpg_error_t err; if (!card || !nbytes || !buffer) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if (!card->ref_count) err = gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); else err = iso7816_get_challenge (card->slot, nbytes, buffer); unlock_card (card); return err; } /* Perform a CHANGE REFERENCE DATA or RESET RETRY COUNTER operation. */ gpg_error_t app_change_pin (card_t card, 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 (!card || !chvnostr || !*chvnostr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, NULL))) ; else if (!card->app->fnc.change_pin) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling change_pin(%s)\n", card->slot, xstrapptype (card->app), chvnostr); err = card->app->fnc.change_pin (card->app, ctrl, chvnostr, flags, pincb, pincb_arg); } unlock_card (card); 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 (card_t card, ctrl_t ctrl, const char *keyidstr, gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg) { gpg_error_t err; if (!card || !keyidstr || !*keyidstr || !pincb) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; if ((err = maybe_switch_app (ctrl, card, NULL))) ; else if (!card->app->fnc.check_pin) err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION); else { if (DBG_APP) log_debug ("slot %d app %s: calling check_pin(%s)\n", card->slot, xstrapptype (card->app), keyidstr); err = card->app->fnc.check_pin (card->app, ctrl, keyidstr, pincb, pincb_arg); } unlock_card (card); 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) { card_t card, card_next; int periodical_check_needed = 0; int reported = 0; npth_mutex_lock (&card_list_lock); for (card = card_top; card; card = card_next) { int sw; unsigned int status; lock_card (card, NULL); card_next = card->next; if (card->reset_requested) status = 0; else { sw = apdu_get_status (card->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 (card->periodical_check_needed) periodical_check_needed = 1; unlock_card (card); continue; } } if (card->card_status != status) { report_change (card->slot, card->card_status, status); send_client_notifications (card, status == 0); reported++; if (status == 0) { log_debug ("Removal of a card: %d\n", card->slot); pincache_put (NULL, card->slot, NULL, NULL, NULL, 0); apdu_close_reader (card->slot); deallocate_card (card); } else { card->card_status = status; if (card->periodical_check_needed) periodical_check_needed = 1; unlock_card (card); } } else { if (card->periodical_check_needed) periodical_check_needed = 1; unlock_card (card); } } if (reported) npth_cond_broadcast (¬ify_cond); npth_mutex_unlock (&card_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 (&card_list_lock, NULL)) { err = gpg_error_from_syserror (); log_error ("app: error initializing mutex: %s\n", gpg_strerror (err)); return err; } err = npth_cond_init (¬ify_cond, NULL); if (err) { err = gpg_error_from_syserror (); log_error ("npth_cond_init failed: %s\n", gpg_strerror (err)); return err; } return apdu_init (); } /* Sort helper for app_send_card_list. */ static int compare_card_list_items (const void *arg_a, const void *arg_b) { const card_t a = *(const card_t *)arg_a; const card_t b = *(const card_t *)arg_b; return a->slot - b->slot; } /* Helper for send_card_and_app_list and app_switch_active_app. */ static gpg_error_t send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl) { gpg_error_t err; app_t a; char buf[65]; char *p; membuf_t mb; int any = 0; if (DIM (buf) < 2 * card->serialnolen + 1) return 0; /* Oops. */ bin2hex (card->serialno, card->serialnolen, buf); if (with_apps) { /* Note that in case the additional applications have not yet been * added to the card context (which is commonly done by means of * "SERIALNO --all", we do that here. */ err = select_all_additional_applications_internal (ctrl, card); if (err) return err; init_membuf (&mb, 256); put_membuf_str (&mb, buf); for (a = card->app; a; a = a->next) { if (!a->fnc.with_keygrip) continue; any = 1; put_membuf (&mb, " ", 1); put_membuf_str (&mb, xstrapptype (a)); } if (!any && card->app) { /* No card app supports the with_keygrip function. Use the * main app as fallback. */ put_membuf (&mb, " ", 1); put_membuf_str (&mb, xstrapptype (card->app)); } put_membuf (&mb, "", 1); p = get_membuf (&mb, NULL); if (!p) return gpg_error_from_syserror (); send_status_direct (ctrl, "SERIALNO", p); xfree (p); } else send_status_direct (ctrl, "SERIALNO", buf); return 0; } /* Common code for app_send_card_list and app_send_active_apps. */ static gpg_error_t send_card_and_app_list (ctrl_t ctrl, card_t wantcard, int with_apps) { gpg_error_t err; card_t c; card_t *cardlist = NULL; int n, ncardlist; npth_mutex_lock (&card_list_lock); for (n=0, c = card_top; c; c = c->next) n++; if (!n) { err = gpg_error (GPG_ERR_CARD_NOT_PRESENT); goto leave; } cardlist = xtrycalloc (n, sizeof *cardlist); if (!cardlist) { err = gpg_error_from_syserror (); goto leave; } for (ncardlist=0, c = card_top; c; c = c->next) cardlist[ncardlist++] = c; qsort (cardlist, ncardlist, sizeof *cardlist, compare_card_list_items); for (n=0; n < ncardlist; n++) { if (wantcard && wantcard != cardlist[n]) continue; err = send_serialno_and_app_status (cardlist[n], with_apps, ctrl); if (err) goto leave; } err = 0; leave: npth_mutex_unlock (&card_list_lock); xfree (cardlist); return err; } /* Send status lines with the serialno of all inserted cards. */ gpg_error_t app_send_card_list (ctrl_t ctrl) { return send_card_and_app_list (ctrl, NULL, 0); } /* Send status lines with the serialno and appname of the current card * or of all cards if CARD is NULL. */ gpg_error_t app_send_active_apps (card_t card, ctrl_t ctrl) { return send_card_and_app_list (ctrl, card, 1); } /* Switch to APPNAME and print a respective status line with that app * listed first. If APPNAME is NULL or the empty string no switching * is done but the status line is printed anyway. */ gpg_error_t app_switch_active_app (card_t card, ctrl_t ctrl, const char *appname) { gpg_error_t err; apptype_t apptype; if (!card) return gpg_error (GPG_ERR_INV_VALUE); err = lock_card (card, ctrl); if (err) return err; /* Note that in case the additional applications have not yet been * added to the card context (which is commonly done by means of * "SERIALNO --all", we do that here. */ err = select_all_additional_applications_internal (ctrl, card); if (err) goto leave; if (appname && *appname) { apptype = apptype_from_name (appname); if (!apptype) { err = gpg_error (GPG_ERR_NOT_FOUND); goto leave; } ctrl->current_apptype = apptype; err = maybe_switch_app (ctrl, card, NULL); if (err) goto leave; } /* Print the status line. */ err = send_serialno_and_app_status (card, 1, ctrl); leave: unlock_card (card); return err; } /* Execute an action for each app. ACTION can be one of: * * - KEYGRIP_ACTION_SEND_DATA * * If KEYGRIP_STR matches a public key of any active application * send information as LF terminated data lines about the public * key. The format of these lines is * T * If a match was found a pointer to the matching application is * returned. With the KEYGRIP_STR given as NULL, lines for all * keys (with CAPABILITY) will be send and the return value is * GPG_ERR_TRUE. * * - KEYGRIP_ACTION_WRITE_STATUS * * Same as KEYGRIP_ACTION_SEND_DATA but uses status lines instead * of data lines. * * - KEYGRIP_ACTION_LOOKUP * * Returns a pointer to the application matching KEYGRIP_STR but * does not emit any status or data lines. If no key with that * keygrip is available or KEYGRIP_STR is NULL, GPG_ERR_NOT_FOUND * is returned. */ card_t app_do_with_keygrip (ctrl_t ctrl, int action, const char *keygrip_str, int capability) { int locked = 0; card_t c; app_t a, a_prev; npth_mutex_lock (&card_list_lock); for (c = card_top; c; c = c->next) { if (lock_card (c, ctrl)) { c = NULL; goto leave_the_loop; } locked = 1; a_prev = NULL; for (a = c->app; a; a = a->next) { if (!a->fnc.with_keygrip) continue; /* Note that we need to do a re-select even for the current * app because the last selected application (e.g. after * init) might be a different one and we do not run * maybe_switch_app here. Of course we we do this only iff * we have an additional app. */ if (c->app->next) { if (run_reselect (ctrl, c, a, a_prev)) continue; } a_prev = a; if (DBG_APP) log_debug ("slot %d, app %s: calling with_keygrip(%s)\n", c->slot, xstrapptype (a), action == KEYGRIP_ACTION_SEND_DATA? "send_data": action == KEYGRIP_ACTION_WRITE_STATUS? "status": action == KEYGRIP_ACTION_LOOKUP? "lookup":"?"); if (!a->fnc.with_keygrip (a, ctrl, action, keygrip_str, capability)) goto leave_the_loop; /* ACTION_LOOKUP succeeded. */ } /* Select the first app again. */ if (c->app->next) run_reselect (ctrl, c, c->app, a_prev); unlock_card (c); locked = 0; } leave_the_loop: /* Force switching of the app if the selected one is not the current * one. Changing the current apptype is sufficient to do this. */ if (c && c->app && c->app->apptype != a->apptype) ctrl->current_apptype = a->apptype; if (locked && c) { unlock_card (c); locked = 0; } npth_mutex_unlock (&card_list_lock); return c; } void app_wait (void) { npth_mutex_lock (&card_list_lock); npth_cond_wait (¬ify_cond, &card_list_lock); npth_mutex_unlock (&card_list_lock); } diff --git a/sm/certchain.c b/sm/certchain.c index d4047fd53..7aa7c1af3 100644 --- a/sm/certchain.c +++ b/sm/certchain.c @@ -1,2382 +1,2382 @@ /* 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 "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_LOGLVL_ERROR: GPGRT_LOGLVL_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 GPG_ERR_NOT_FOUND 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 = gpg_error (GPG_ERR_NOT_FOUND); 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 = gpg_error (GPG_ERR_NOT_FOUND); 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 = gpg_error (GPG_ERR_NOT_FOUND); 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 = gpg_error (GPG_ERR_NOT_FOUND); goto leave; } /* Ready. The NE_FOUND_CERT is available via keydb_get_cert. */ } leave: ksba_cert_release (found_cert); ksba_cert_release (ne_found_cert); ksba_cert_release (cert); xfree (subj); return rc? gpg_error (GPG_ERR_NOT_FOUND) : 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 = gpg_error (GPG_ERR_NOT_FOUND); } else if (!find_up_store_certs_parm.count) rc = gpg_err_code (rc) == GPG_ERR_NOT_FOUND; 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 : gpg_error (GPG_ERR_NOT_FOUND)); } /* 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, GPG_ERR_NOT_FOUND if not found or another 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 certificate 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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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) /* Need to make sure to have this error code. */ rc = gpg_error (GPG_ERR_NOT_FOUND); } if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && 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) /* Need to make sure to have this error code. */ rc = gpg_error (GPG_ERR_NOT_FOUND); } /* If we still didn't found it, try to find it via the subject from the dirmngr-cache. */ if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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) /* Need to make sure to have this error code. */ rc = gpg_error (GPG_ERR_NOT_FOUND); 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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && opt.quiet) ; else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) { 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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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 (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && !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 GPG_ERR_NOT_FOUND when there are no more certificates. */ gpg_error_t 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 (ctrl); *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 = gpg_error (GPG_ERR_NOT_FOUND); /* 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 (gpg_err_code (rc) != GPG_ERR_NOT_FOUND && 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 certificate (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 extra constraint 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 consistency 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 (ctrl); 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 certificate 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 (ctrl); 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 (gpg_err_code (rc) != GPG_ERR_NOT_FOUND || !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 af8bf8629..875189ea6 100644 --- a/sm/keydb.c +++ b/sm/keydb.c @@ -1,2154 +1,2156 @@ /* keydb.c - key database dispatcher * Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc. * Copyright (C) 2014, 2020 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 "gpgsm.h" #include #include "../kbx/keybox.h" #include "keydb.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../kbx/kbx-client-util.h" 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; }; /* Data used to keep track of keybox daemon sessions. This allows us * to use several sessions with the keyboxd and also to re-use already * established sessions. Note that gpgdm.h defines the type * keydb_local_t for this structure. */ struct keydb_local_s { /* Link to other keyboxd contexts which are used simultaneously. */ struct keydb_local_s *next; /* The active Assuan context. */ assuan_context_t ctx; /* The client data helper context. */ kbx_client_data_t kcd; /* I/O buffer with the last search result or NULL. Used if * D-lines are used to convey the keyblocks. */ struct { char *buf; size_t len; } search_result; /* This flag set while an operation is running on this context. */ unsigned int is_active : 1; /* Flag indicating that a search reset is required. */ unsigned int need_search_reset : 1; }; static struct resource_item all_resources[MAX_KEYDB_RESOURCES]; static int used_resources; /* Whether we have successfully registered any resource. */ static int any_registered; /* Number of active handles. */ static int active_handles; struct keydb_handle { /* CTRL object passed to keydb_new. */ ctrl_t ctrl; /* If set the keyboxdd is used instead of the local files. */ int use_keyboxd; /* BEGIN USE_KEYBOXD */ /* (These fields are only valid if USE_KEYBOXD is set.) */ /* Connection info which also keeps the local state. (This points * into the CTRL->keybox_local list.) */ keydb_local_t kbl; /* Various flags. */ unsigned int last_ubid_valid:1; unsigned int last_is_ephemeral; /* Last found key is ephemeral. */ /* The UBID of the last returned keyblock. */ unsigned char last_ubid[UBID_LEN]; /* END USE_KEYBOXD */ /* BEGIN !USE_KEYBOXD */ /* (The remaining fields are only valid if USE_KEYBOXD is cleared.) */ /* If this flag is set the resources is locked. */ int locked; /* If this flag is set a lock will only be released by * keydb_release. */ int keep_lock; int found; int saved_found; int current; int is_ephemeral; int used; /* items in active */ struct resource_item active[MAX_KEYDB_RESOURCES]; /* END !USE_KEYBOXD */ }; static int lock_all (KEYDB_HANDLE hd); static void unlock_all (KEYDB_HANDLE hd); /* Deinitialize all session resources pertaining to the keyboxd. */ void gpgsm_keydb_deinit_session_data (ctrl_t ctrl) { keydb_local_t kbl; while ((kbl = ctrl->keydb_local)) { ctrl->keydb_local = kbl->next; if (kbl->is_active) log_error ("oops: trying to cleanup an active keydb context\n"); else { kbx_client_data_release (kbl->kcd); kbl->kcd = NULL; assuan_release (kbl->ctx); kbl->ctx = NULL; } xfree (kbl); } } 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 account 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, NULL, 0); + 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 { KEYBOX_HANDLE kbxhd; all_resources[used_resources].type = rt; all_resources[used_resources].u.kr = NULL; /* Not used here */ all_resources[used_resources].token = token; /* Do a compress run if needed and the keybox is not locked. */ kbxhd = keybox_new_x509 (token, 0); if (kbxhd) { if (!keybox_lock (kbxhd, 1, 0)) { keybox_compress (kbxhd); keybox_lock (kbxhd, 0, 0); } keybox_release (kbxhd); } 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; } /* Print a warning if the server's version number is less than our version number. Returns an error code on a connection problem. */ static gpg_error_t warn_version_mismatch (ctrl_t ctrl, assuan_context_t ctx, const char *servername) { return warn_server_version_mismatch (ctx, servername, 0, gpgsm_status2, ctrl, !opt.quiet); } /* Connect to the keybox daemon and launch it if necessary. Handle * the server's initial greeting and set global options. Returns a * new assuan context or an error. */ static gpg_error_t create_new_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; assuan_context_t ctx; *r_ctx = NULL; err = start_new_keyboxd (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.keyboxd_program, opt.autostart, opt.verbose, DBG_IPC, NULL, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_KEYBOXD) { static int shown; if (!shown) { shown = 1; log_info (_("no keyboxd running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (ctrl, ctx, KEYBOXD_NAME))) { /* Place to emit global options. */ } if (err) assuan_release (ctx); else *r_ctx = ctx; return err; } /* Get a context for accessing keyboxd. If no context is available a * new one is created and if necessary keyboxd is started. R_KBL * receives a pointer to the local context object. */ static gpg_error_t open_context (ctrl_t ctrl, keydb_local_t *r_kbl) { gpg_error_t err; keydb_local_t kbl; *r_kbl = NULL; for (;;) { for (kbl = ctrl->keydb_local; kbl && kbl->is_active; kbl = kbl->next) ; if (kbl) { /* Found an inactive keyboxd session - return that. */ log_assert (!kbl->is_active); kbl->is_active = 1; kbl->need_search_reset = 1; *r_kbl = kbl; return 0; } /* None found. Create a new session and retry. */ kbl = xtrycalloc (1, sizeof *kbl); if (!kbl) return gpg_error_from_syserror (); err = create_new_context (ctrl, &kbl->ctx); if (err) { xfree (kbl); return err; } err = kbx_client_data_new (&kbl->kcd, kbl->ctx, 1); if (err) { assuan_release (kbl->ctx); xfree (kbl); return err; } /* For thread-saftey we add it to the list and retry; this is * easier than to employ a lock. */ kbl->next = ctrl->keydb_local; ctrl->keydb_local = kbl; } /*NOTREACHED*/ } KEYDB_HANDLE keydb_new (ctrl_t ctrl) { gpg_error_t err; KEYDB_HANDLE hd; int rc, i, j; if (DBG_CLOCK) log_clock ("%s: enter\n", __func__); hd = xcalloc (1, sizeof *hd); hd->found = -1; hd->saved_found = -1; hd->use_keyboxd = opt.use_keyboxd; hd->ctrl = ctrl; if (hd->use_keyboxd) { err = open_context (ctrl, &hd->kbl); if (err) { log_error (_("error opening key DB: %s\n"), gpg_strerror (err)); xfree (hd); hd = NULL; if (!(rc = gpg_err_code_to_errno (err))) rc = gpg_err_code_to_errno (GPG_ERR_EIO); gpg_err_set_errno (rc); goto leave; } } else /* Use the local keybox. */ { log_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].u.kr = keybox_new_x509 (all_resources[i].token, 0); if (!hd->active[j].u.kr) { xfree (hd); return NULL; /* fixme: free all previously allocated handles*/ } j++; break; } } hd->used = j; } active_handles++; leave: if (DBG_CLOCK) log_clock ("%s: leave (hd=%p)\n", __func__, hd); return hd; } void keydb_release (KEYDB_HANDLE hd) { keydb_local_t kbl; int i; if (!hd) return; if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); log_assert (active_handles > 0); active_handles--; if (hd->use_keyboxd) { kbl = hd->kbl; if (DBG_CLOCK) log_clock ("close_context (found)"); if (!kbl->is_active) log_fatal ("closing inactive keyboxd context %p\n", kbl); kbl->is_active = 0; hd->kbl = NULL; } else { 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_KEYBOX: keybox_release (hd->active[i].u.kr); break; } } } xfree (hd); if (DBG_CLOCK) log_clock ("%s: leave\n", __func__); } /* 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->use_keyboxd) return "[keyboxd]"; 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; if (hd->use_keyboxd) return 0; /* FIXME: No support yet. */ 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 kept until a keydb_release so * that internal unlock_all calls have no effect. */ gpg_error_t keydb_lock (KEYDB_HANDLE hd) { gpg_error_t err; if (!hd) return gpg_error (GPG_ERR_INV_HANDLE); if (hd->use_keyboxd) return 0; if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); err = lock_all (hd); if (!err) hd->keep_lock = 1; if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; } static int lock_all (KEYDB_HANDLE hd) { int i, rc = 0; if (hd->use_keyboxd) return 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: rc = keybox_lock (hd->active[i].u.kr, 1, -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: keybox_lock (hd->active[i].u.kr, 0, 0); break; } } } else hd->locked = 1; return rc; } static void unlock_all (KEYDB_HANDLE hd) { int i; if (hd->use_keyboxd) return; 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_KEYBOX: keybox_lock (hd->active[i].u.kr, 0, 0); break; } } hd->locked = 0; } /* Push the last found state if any. */ void keydb_push_found_state (KEYDB_HANDLE hd) { if (!hd) return; if (hd->use_keyboxd) return; /* FIXME: Do we need this? */ 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; if (DBG_CLOCK) log_clock ("%s: done (hd=%p)\n", __func__, hd); } /* Pop the last found state. */ void keydb_pop_found_state (KEYDB_HANDLE hd) { if (!hd) return; if (hd->use_keyboxd) return; /* FIXME: Do we need this? */ 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; } if (DBG_CLOCK) log_clock ("%s: done (hd=%p)\n", __func__, hd); } /* Return the last found certificate. Caller must free it. */ int keydb_get_cert (KEYDB_HANDLE hd, ksba_cert_t *r_cert) { int err = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { ksba_cert_t cert; /* Fixme: We should clear that also in non-keyboxd mode but we * did not in the past and thus all code should be checked * whether this is okay. If we run into error in keyboxd mode, * this is a not as severe because keyboxd is currently * experimental. */ *r_cert = NULL; if (!hd->kbl->search_result.buf || !hd->kbl->search_result.len) { err = gpg_error (GPG_ERR_VALUE_NOT_FOUND); goto leave; } err = ksba_cert_new (&cert); if (err) goto leave; err = ksba_cert_init_from_mem (cert, hd->kbl->search_result.buf, hd->kbl->search_result.len); if (err) { ksba_cert_release (cert); goto leave; } xfree (hd->kbl->search_result.buf); hd->kbl->search_result.buf = NULL; hd->kbl->search_result.len = 0; *r_cert = cert; goto leave; } if ( hd->found < 0 || hd->found >= hd->used) { /* Fixme: It would be better to use GPG_ERR_VALUE_NOT_FOUND here * but for now we use NOT_FOUND because that is our standard * replacement for the formerly used (-1). */ err = gpg_error (GPG_ERR_NOT_FOUND); /* nothing found */ goto leave; } err = GPG_ERR_BUG; 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_cert (hd->active[hd->found].u.kr, r_cert); break; } leave: if (DBG_CLOCK) log_clock ("%s: leave (rc=%d)\n", __func__, err); return err; } /* 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) { gpg_error_t err; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { /* FIXME */ *value = 0; err = 0; goto leave; } if ( hd->found < 0 || hd->found >= hd->used) { err = gpg_error (GPG_ERR_NOTHING_FOUND); goto leave; } err = gpg_error (GPG_ERR_BUG); 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; } leave: if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); 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) { gpg_error_t err = 0; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { /* FIXME */ goto leave; } if ( hd->found < 0 || hd->found >= hd->used) { err = gpg_error (GPG_ERR_NOTHING_FOUND); goto leave; } if (!hd->locked) { err = gpg_error (GPG_ERR_NOT_LOCKED); goto leave; } 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; } leave: if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; } /* Communication object for Keyboxd STORE commands. */ struct store_parm_s { assuan_context_t ctx; const void *data; /* The certificate in X.509 binary format. */ size_t datalen; /* The length of DATA. */ }; /* Handle the inquiries from the STORE command. */ static gpg_error_t store_inq_cb (void *opaque, const char *line) { struct store_parm_s *parm = opaque; gpg_error_t err = 0; if (has_leading_keyword (line, "BLOB")) { if (parm->data) err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); return err; } /* * Insert a new Certificate into one of the resources. */ gpg_error_t keydb_insert_cert (KEYDB_HANDLE hd, ksba_cert_t cert) { gpg_error_t err; int idx; unsigned char digest[20]; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (opt.dry_run) return 0; if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { struct store_parm_s parm; parm.ctx = hd->kbl->ctx; parm.data = ksba_cert_get_image (cert, &parm.datalen); if (!parm.data) { log_debug ("broken ksba cert object\n"); err = gpg_error (GPG_ERR_GENERAL); goto leave; } err = assuan_transact (hd->kbl->ctx, "STORE --insert", NULL, NULL, store_inq_cb, &parm, NULL, NULL); goto leave; } if ( hd->found >= 0 && hd->found < hd->used) idx = hd->found; else if ( hd->current >= 0 && hd->current < hd->used) idx = hd->current; else { err = gpg_error (GPG_ERR_GENERAL); goto leave; } if (!hd->locked) { err = gpg_error (GPG_ERR_NOT_LOCKED); goto leave; } gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/ err = gpg_error (GPG_ERR_BUG); switch (hd->active[idx].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); break; case KEYDB_RESOURCE_TYPE_KEYBOX: err = keybox_insert_cert (hd->active[idx].u.kr, cert, digest); break; } unlock_all (hd); leave: if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; } /* Update the current keyblock with KB. */ /* Note: This function is currently not called. */ gpg_error_t keydb_update_cert (KEYDB_HANDLE hd, ksba_cert_t cert) { (void)hd; (void)cert; return GPG_ERR_BUG; #if 0 gpg_error_t err; unsigned char digest[20]; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if ( hd->found < 0 || hd->found >= hd->used) return gpg_error (GPG_ERR_NOT_FOUND); if (opt.dry_run) return 0; if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { /* FIXME */ goto leave; } err = lock_all (hd); if (err) goto leave; gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/ err = gpg_error (GPG_ERR_BUG); 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_update_cert (hd->active[hd->found].u.kr, cert, digest); break; } unlock_all (hd); leave: if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; #endif /*0*/ } /* * The current keyblock or cert will be deleted. */ gpg_error_t keydb_delete (KEYDB_HANDLE hd) { gpg_error_t err; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!hd->use_keyboxd && (hd->found < 0 || hd->found >= hd->used)) return gpg_error (GPG_ERR_NOT_FOUND); if (opt.dry_run) return 0; if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (hd->use_keyboxd) { unsigned char hexubid[UBID_LEN * 2 + 1]; char line[ASSUAN_LINELENGTH]; if (!hd->last_ubid_valid) { err = gpg_error (GPG_ERR_VALUE_NOT_FOUND); goto leave; } bin2hex (hd->last_ubid, UBID_LEN, hexubid); snprintf (line, sizeof line, "DELETE %s", hexubid); err = assuan_transact (hd->kbl->ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); goto leave; } if (!hd->locked) { err = gpg_error (GPG_ERR_NOT_LOCKED); goto leave; } err = gpg_error (GPG_ERR_BUG); switch (hd->active[hd->found].type) { case KEYDB_RESOURCE_TYPE_NONE: err = gpg_error (GPG_ERR_GENERAL); break; case KEYDB_RESOURCE_TYPE_KEYBOX: err = keybox_delete (hd->active[hd->found].u.kr); break; } unlock_all (hd); leave: if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; } /* * Locate the default writable key resource, so that the next * operation (which is only relevant for inserts) will be done on this * resource. */ static gpg_error_t keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved) { int rc; (void)reserved; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (hd->use_keyboxd) return 0; /* Not required. */ 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 gpg_error (GPG_ERR_NOT_FOUND); } /* * Rebuild the caches of all key resources. */ void keydb_rebuild_caches (void) { int i; /* This function does nothing and thus we don't need to handle keyboxd in a * special way. */ 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) { gpg_error_t err = 0; int i; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); hd->current = 0; hd->found = -1; if (hd->use_keyboxd) { /* All we need is to tell search that a reset is pending. Note that * keydb_new sets this flag as well. To comply with the * specification of keydb_delete_keyblock we also need to clear the * ubid flag so that after a reset a delete can't be performed. */ hd->kbl->need_search_reset = 1; hd->last_ubid_valid = 0; } else { /* Reset all resources */ for (i=0; !err && i < hd->used; i++) { switch (hd->active[i].type) { case KEYDB_RESOURCE_TYPE_NONE: break; case KEYDB_RESOURCE_TYPE_KEYBOX: err = keybox_search_reset (hd->active[i].u.kr); break; } } } if (DBG_CLOCK) log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err)); return err; } char * keydb_search_desc_dump (struct keydb_search_desc *desc) { char *fpr; char *result; 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: '%08lX'", (ulong)desc->u.kid[1]); case KEYDB_SEARCH_MODE_LONG_KID: return xasprintf ("LONG_KID: '%08lX%08lX'", (ulong)desc->u.kid[0], (ulong)desc->u.kid[1]); case KEYDB_SEARCH_MODE_FPR: fpr = bin2hexcolon (desc->u.fpr, desc->fprlen, NULL); result = xasprintf ("FPR%02d: '%s'", desc->fprlen, fpr); xfree (fpr); return result; case KEYDB_SEARCH_MODE_ISSUER: return xasprintf ("ISSUER: '%s'", desc->u.name); case KEYDB_SEARCH_MODE_ISSUER_SN: return xasprintf ("ISSUER_SN: '#%.*s/%s'", (int)desc->snlen,desc->sn, desc->u.name); case KEYDB_SEARCH_MODE_SN: return xasprintf ("SN: '%.*s'", (int)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); } } /* Status callback for SEARCH and NEXT operaions. */ static gpg_error_t search_status_cb (void *opaque, const char *line) { KEYDB_HANDLE hd = opaque; gpg_error_t err = 0; const char *s; unsigned int n; if ((s = has_leading_keyword (line, "PUBKEY_INFO"))) { if (atoi (s) != PUBKEY_TYPE_X509) err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE); else { hd->last_ubid_valid = 0; while (*s && !spacep (s)) s++; if (!(n=hex2fixedbuf (s, hd->last_ubid, sizeof hd->last_ubid))) err = gpg_error (GPG_ERR_INV_VALUE); else { hd->last_ubid_valid = 1; s += n; hd->last_is_ephemeral = (*s == 'e'); } } } return err; } /* Search through all keydb resources, starting at the current * position, for a keyblock which contains one of the keys described * in the DESC array. In keyboxd mode the search is instead delegated * to the keyboxd. * * 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, the error code * GPG_ERR_NOT_FOUND is retruned. If there was a match, 0 is * returned. If an error occurred, that error code is returned. * * The returned key is considered to be selected and the certificate * can be detched via keydb_get_cert. */ gpg_error_t keydb_search (ctrl_t ctrl, KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc) { gpg_error_t err = gpg_error (GPG_ERR_EOF); unsigned long skipped; int i; if (!hd) return gpg_error (GPG_ERR_INV_VALUE); if (!any_registered && !hd->use_keyboxd) { gpgsm_status_with_error (ctrl, STATUS_ERROR, "keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN)); return gpg_error (GPG_ERR_NOT_FOUND); } if (DBG_CLOCK) log_clock ("%s: enter (hd=%p)\n", __func__, hd); if (DBG_LOOKUP) { log_debug ("%s: %zd search description(s):\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 (hd->use_keyboxd) { char line[ASSUAN_LINELENGTH]; /* Clear the result objects. */ if (hd->kbl->search_result.buf) { xfree (hd->kbl->search_result.buf); hd->kbl->search_result.buf = NULL; hd->kbl->search_result.len = 0; } /* Check whether this is a NEXT search. */ if (!hd->kbl->need_search_reset) { /* A reset was not requested thus continue the search. The * keyboxd keeps the context of the search and thus the NEXT * operates on the last search pattern. This is the way how * we always used the keydb functions. In theory we were * able to modify the search pattern between searches but * that is not anymore supported by keyboxd and a cursory * check does not show that we actually made use of that * misfeature. */ snprintf (line, sizeof line, "NEXT --x509"); goto do_search; } hd->kbl->need_search_reset = 0; if (!ndesc) { err = gpg_error (GPG_ERR_INV_ARG); goto leave; } /* FIXME: Implement --multi */ switch (desc->mode) { case KEYDB_SEARCH_MODE_EXACT: snprintf (line, sizeof line, "SEARCH --x509 =%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SUBSTR: snprintf (line, sizeof line, "SEARCH --x509 *%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAIL: snprintf (line, sizeof line, "SEARCH --x509 <%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAILSUB: snprintf (line, sizeof line, "SEARCH --x509 @%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_MAILEND: snprintf (line, sizeof line, "SEARCH --x509 .%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_WORDS: snprintf (line, sizeof line, "SEARCH --x509 +%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SHORT_KID: snprintf (line, sizeof line, "SEARCH --x509 0x%08lX", (ulong)desc->u.kid[1]); break; case KEYDB_SEARCH_MODE_LONG_KID: snprintf (line, sizeof line, "SEARCH --x509 0x%08lX%08lX", (ulong)desc->u.kid[0], (ulong)desc->u.kid[1]); break; case KEYDB_SEARCH_MODE_FPR: { unsigned char hexfpr[MAX_FINGERPRINT_LEN * 2 + 1]; log_assert (desc[0].fprlen <= MAX_FINGERPRINT_LEN); bin2hex (desc[0].u.fpr, desc[0].fprlen, hexfpr); snprintf (line, sizeof line, "SEARCH --x509 0x%s", hexfpr); } break; case KEYDB_SEARCH_MODE_ISSUER: snprintf (line, sizeof line, "SEARCH --x509 #/%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_ISSUER_SN: if (desc[0].snhex) snprintf (line, sizeof line, "SEARCH --x509 #%.*s/%s", (int)desc[0].snlen, desc[0].sn, desc[0].u.name); else { char *hexsn = bin2hex (desc[0].sn, desc[0].snlen, NULL); if (!hexsn) { err = gpg_error_from_syserror (); goto leave; } snprintf (line, sizeof line, "SEARCH --x509 #%s/%s", hexsn, desc[0].u.name); xfree (hexsn); } break; case KEYDB_SEARCH_MODE_SN: snprintf (line, sizeof line, "SEARCH --x509 #%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_SUBJECT: snprintf (line, sizeof line, "SEARCH --x509 /%s", desc[0].u.name); break; case KEYDB_SEARCH_MODE_KEYGRIP: { unsigned char hexgrip[KEYGRIP_LEN * 2 + 1]; bin2hex (desc[0].u.grip, KEYGRIP_LEN, hexgrip); snprintf (line, sizeof line, "SEARCH --x509 &%s", hexgrip); } break; case KEYDB_SEARCH_MODE_UBID: { unsigned char hexubid[UBID_LEN * 2 + 1]; bin2hex (desc[0].u.ubid, UBID_LEN, hexubid); snprintf (line, sizeof line, "SEARCH --x509 ^%s", hexubid); } break; case KEYDB_SEARCH_MODE_FIRST: snprintf (line, sizeof line, "SEARCH --x509"); break; case KEYDB_SEARCH_MODE_NEXT: log_debug ("%s: mode next - we should not get to here!\n", __func__); snprintf (line, sizeof line, "NEXT --x509"); break; default: err = gpg_error (GPG_ERR_INV_ARG); goto leave; } do_search: hd->last_ubid_valid = 0; /* To avoid silent truncation we error out on a too long line. */ if (strlen (line) + 5 >= sizeof line) err = gpg_error (GPG_ERR_ASS_LINE_TOO_LONG); else err = kbx_client_data_cmd (hd->kbl->kcd, line, search_status_cb, hd); if (!err && !(err = kbx_client_data_wait (hd->kbl->kcd, &hd->kbl->search_result.buf, &hd->kbl->search_result.len))) { /* if (hd->last_ubid_valid) */ /* log_printhex (hd->last_ubid, 20, "found UBID%s:", */ /* hd->last_is_ephemeral? "(ephemeral)":""); */ } } else /* Local keyring search. */ { while (gpg_err_code (err) == GPG_ERR_EOF && 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: err = keybox_search (hd->active[hd->current].u.kr, desc, ndesc, KEYBOX_BLOBTYPE_X509, NULL, &skipped); if (err == -1) /* Map legacy code. */ err = gpg_error (GPG_ERR_EOF); break; } if (DBG_LOOKUP) log_debug ("%s: searched %s (resource %d of %d) => %s\n", __func__, hd->active[hd->current].type==KEYDB_RESOURCE_TYPE_KEYBOX ? "keybox" : "unknown type", hd->current, hd->used, gpg_strerror (err)); if (gpg_err_code (err) == GPG_ERR_EOF) { /* EOF -> switch to next resource */ hd->current++; } else if (!err) hd->found = hd->current; } } leave: /* The NOTHING_FOUND error is triggered by a NEXT command. */ if (gpg_err_code (err) == GPG_ERR_EOF || gpg_err_code (err) == GPG_ERR_NOTHING_FOUND) err = gpg_error (GPG_ERR_NOT_FOUND); if (DBG_CLOCK) log_clock ("%s: leave (%s)\n", __func__, gpg_strerror (err)); return err; } 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); desc.fprlen = 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 (ctrl); 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); if (!kh->use_keyboxd) { rc = lock_all (kh); if (rc) return rc; } rc = keydb_search_fpr (ctrl, kh, fpr); if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND) { 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 (ctrl); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); return gpg_error (GPG_ERR_ENOMEM);; } if (ephemeral) keydb_set_ephemeral (kh, 1); if (!kh->use_keyboxd) { 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 (gpg_err_code (err) != gpg_error (GPG_ERR_NOT_FOUND)) 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 (ctrl); 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++; } } if (!hd->use_keyboxd) { 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 && gpg_err_code (rc) != GPG_ERR_NOT_FOUND) 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 a1d6fe9bf..4d8dfccab 100644 --- a/sm/qualified.c +++ b/sm/qualified.c @@ -1,324 +1,324 @@ /* 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 "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_sysconfdir (), "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); } log_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 with a 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 b3e1d5268..d798dbe2e 100644 --- a/tools/gpg-check-pattern.c +++ b/tools/gpg-check-pattern.c @@ -1,497 +1,495 @@ /* 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 . * SPDX-License-Identifier: GPL-3.0-or-later */ #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 gpgrt_opt_t 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 regular 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 9: p = "GPL-3.0-or-later"; break; case 11: p = "gpg-check-pattern (@GnuPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: gpg-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 ) { gpgrt_argparse_t pargs; char *raw_pattern; size_t raw_pattern_length; pattern_t *patternarray; early_system_init (); gpgrt_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= ARGPARSE_FLAG_KEEP; while (gpgrt_argparse (NULL, &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; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount(0)) exit (2); if (argc != 1) gpgrt_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 guaranteed 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 6ec08c538..142f69143 100644 --- a/tools/gpg-connect-agent.c +++ b/tools/gpg-connect-agent.c @@ -1,2330 +1,2331 @@ /* gpg-connect-agent.c - Tool to connect to the agent. * Copyright (C) 2005, 2007, 2008, 2010 Free Software Foundation, Inc. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include #include "../common/i18n.h" #include "../common/util.h" #include "../common/asshelp.h" #include "../common/sysutils.h" #include "../common/membuf.h" #include "../common/ttyio.h" #ifdef HAVE_W32_SYSTEM # include "../common/exechelp.h" #endif #include "../common/init.h" #define CONTROL_D ('D' - 'A' + 1) #define octdigitp(p) (*(p) >= '0' && *(p) <= '7') #define HISTORYNAME ".gpg-connect_history" /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oRawSocket = 'S', oTcpSocket = 'T', oExec = 'E', oRun = 'r', oSubst = 's', oNoVerbose = 500, oHomedir, oAgentProgram, oDirmngrProgram, oKeyboxdProgram, oHex, oDecode, oNoExtConnect, oDirmngr, oKeyboxd, oUIServer, oNoHistory, oNoAutostart, oChUid, oNoop }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("quiet")), ARGPARSE_s_n (oHex, "hex", N_("print data out hex encoded")), ARGPARSE_s_n (oDecode,"decode", N_("decode received data lines")), ARGPARSE_s_n (oDirmngr,"dirmngr", N_("connect to the dirmngr")), ARGPARSE_s_n (oKeyboxd,"keyboxd", N_("connect to the keyboxd")), ARGPARSE_s_n (oUIServer, "uiserver", "@"), ARGPARSE_s_s (oRawSocket, "raw-socket", N_("|NAME|connect to Assuan socket NAME")), ARGPARSE_s_s (oTcpSocket, "tcp-socket", N_("|ADDR|connect to Assuan server at ADDR")), ARGPARSE_s_n (oExec, "exec", N_("run the Assuan server given on the command line")), ARGPARSE_s_n (oNoExtConnect, "no-ext-connect", N_("do not use extended connect mode")), ARGPARSE_s_s (oRun, "run", N_("|FILE|run commands from FILE on startup")), ARGPARSE_s_n (oSubst, "subst", N_("run /subst on startup")), ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"), ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"), ARGPARSE_s_n (oNoHistory,"no-history", "do not use the command history file"), ARGPARSE_s_s (oHomedir, "homedir", "@" ), ARGPARSE_s_s (oAgentProgram, "agent-program", "@"), ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"), ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"), ARGPARSE_s_s (oChUid, "chuid", "@"), ARGPARSE_end () }; /* We keep all global options in the structure OPT. */ struct { int verbose; /* Verbosity level. */ int quiet; /* Be extra quiet. */ int autostart; /* Start the server if not running. */ const char *homedir; /* Configuration directory name */ const char *agent_program; /* Value of --agent-program. */ const char *dirmngr_program; /* Value of --dirmngr-program. */ const char *keyboxd_program; /* Value of --keyboxd-program. */ int hex; /* Print data lines in hex format. */ int decode; /* Decode received data lines. */ int use_dirmngr; /* Use the dirmngr and not gpg-agent. */ int use_keyboxd; /* Use the keyboxd and not gpg-agent. */ int use_uiserver; /* Use the standard UI server. */ const char *raw_socket; /* Name of socket to connect in raw mode. */ const char *tcp_socket; /* Name of server to connect in tcp mode. */ int exec; /* Run the pgm given on the command line. */ unsigned int connect_flags; /* Flags used for connecting. */ int enable_varsubst; /* Set if variable substitution is enabled. */ int trim_leading_spaces; int no_history; } opt; /* Definitions for /definq commands and a global linked list with all the definitions. */ struct definq_s { struct definq_s *next; char *name; /* Name of inquiry or NULL for any name. */ int is_var; /* True if FILE is a variable name. */ int is_prog; /* True if FILE is a program to run. */ char file[1]; /* Name of file or program. */ }; typedef struct definq_s *definq_t; static definq_t definq_list; static definq_t *definq_list_tail = &definq_list; /* Variable definitions and glovbal table. */ struct variable_s { struct variable_s *next; char *value; /* Malloced value - always a string. */ char name[1]; /* Name of the variable. */ }; typedef struct variable_s *variable_t; static variable_t variable_table; /* To implement loops we store entire lines in a linked list. */ struct loopline_s { struct loopline_s *next; char line[1]; }; typedef struct loopline_s *loopline_t; /* This is used to store the pid of the server. */ static pid_t server_pid = (pid_t)(-1); /* The current datasink file or NULL. */ -static FILE *current_datasink; +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 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPG@-connect-agent (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: @GPG@-connect-agent [options] (-h for help)"); break; case 41: p = _("Syntax: @GPG@-connect-agent [options]\n" "Connect to a running agent and send commands\n"); break; case 31: p = "\nHome: "; break; case 32: p = gnupg_homedir (); break; case 33: p = "\n"; break; default: p = NULL; break; } return p; } /* Unescape STRING and returned the malloced result. The surrounding quotes must already be removed from STRING. */ static char * unescape_string (const char *string) { const unsigned char *s; int esc; size_t n; char *buffer; unsigned char *d; n = 0; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': case 't': case 'v': case 'n': case 'f': case 'r': case '"': case '\'': case '\\': n++; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) n++; break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) n++; break; } esc = 0; } else if (*s == '\\') esc = 1; else n++; } buffer = xmalloc (n+1); d = (unsigned char*)buffer; for (s = (const unsigned char*)string, esc=0; *s; s++) { if (esc) { switch (*s) { case 'b': *d++ = '\b'; break; case 't': *d++ = '\t'; break; case 'v': *d++ = '\v'; break; case 'n': *d++ = '\n'; break; case 'f': *d++ = '\f'; break; case 'r': *d++ = '\r'; break; case '"': *d++ = '\"'; break; case '\'': *d++ = '\''; break; case '\\': *d++ = '\\'; break; case 'x': if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2)) { s++; *d++ = xtoi_2 (s); s++; } break; default: if (s[1] && s[2] && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) { *d++ = (atoi_1 (s)*64) + (atoi_1 (s+1)*8) + atoi_1 (s+2); s += 2; } break; } esc = 0; } else if (*s == '\\') esc = 1; else *d++ = *s; } *d = 0; return buffer; } /* Do the percent unescaping and return a newly malloced string. If WITH_PLUS is set '+' characters will be changed to space. */ static char * unpercent_string (const char *string, int with_plus) { const unsigned char *s; unsigned char *buffer, *p; size_t n; n = 0; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; n++; s++; } else if (with_plus && *s == '+') n++; else n++; } buffer = xmalloc (n+1); p = buffer; for (s=(const unsigned char *)string; *s; s++) { if (*s == '%' && s[1] && s[2]) { s++; *p++ = xtoi_2 (s); s++; } else if (with_plus && *s == '+') *p++ = ' '; else *p++ = *s; } *p = 0; return (char*)buffer; } static const char * set_var (const char *name, const char *value) { variable_t var; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var) { var = xmalloc (sizeof *var + strlen (name)); var->value = NULL; strcpy (var->name, name); var->next = variable_table; variable_table = var; } xfree (var->value); var->value = value? xstrdup (value) : NULL; return var->value; } static void set_int_var (const char *name, int value) { char numbuf[35]; snprintf (numbuf, sizeof numbuf, "%d", value); set_var (name, numbuf); } /* Return the value of a variable. That value is valid until a variable of the name is changed. Return NULL if not found. Note that envvars are copied to our variable list at the first access and not at oprogram start. */ static const char * get_var (const char *name) { variable_t var; const char *s; if (!*name) return ""; for (var = variable_table; var; var = var->next) if (!strcmp (var->name, name)) break; if (!var && (s = getenv (name))) return set_var (name, s); if (!var || !var->value) return NULL; return var->value; } /* Perform some simple arithmetic operations. Caller must release the return value. On error the return value is NULL. */ static char * arithmetic_op (int operator, const char *operands) { long result, value; char numbuf[35]; while ( spacep (operands) ) operands++; if (!*operands) return NULL; result = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; if (operator == '!') result = !result; while (*operands) { while ( spacep (operands) ) operands++; if (!*operands) break; value = strtol (operands, NULL, 0); while (*operands && !spacep (operands) ) operands++; switch (operator) { case '+': result += value; break; case '-': result -= value; break; case '*': result *= value; break; case '/': if (!value) return NULL; result /= value; break; case '%': if (!value) return NULL; result %= value; break; case '!': result = !value; break; case '|': result = result || value; break; case '&': result = result && value; break; default: log_error ("unknown arithmetic operator '%c'\n", operator); return NULL; } } snprintf (numbuf, sizeof numbuf, "%ld", result); return xstrdup (numbuf); } /* Extended version of get_var. This returns a malloced string and understand the function syntax: "func args". Defined functions are get - Return a value described by the next argument: cwd - The current working directory. homedir - The gnupg homedir. sysconfdir - GnuPG's system configuration directory. bindir - GnuPG's binary directory. libdir - GnuPG's library directory. libexecdir - GnuPG's library directory for executable files. datadir - GnuPG's data directory. serverpid - The PID of the current server. unescape ARGS Remove C-style escapes from string. Note that "\0" and "\x00" terminate the string implicitly. Use "\x7d" to represent the closing brace. The args start right after the first space after the function name. unpercent ARGS unpercent+ ARGS Remove percent style ecaping from string. Note that "%00 terminates the string implicitly. Use "%7d" to represetn the closing brace. The args start right after the first space after the function name. "unpercent+" also maps '+' to space. percent ARGS percent+ ARGS Escape the args using the percent style. Tabs, formfeeds, linefeeds, carriage return, and the plus sign are also escaped. "percent+" also maps spaces to plus characters. errcode ARG Assuming ARG is an integer, return the gpg-error code. errsource ARG Assuming ARG is an integer, return the gpg-error source. errstring ARG Assuming ARG is an integer return a formatted fpf error string. Example: get_var_ext ("get sysconfdir") -> "/etc/gnupg" */ static char * get_var_ext (const char *name) { static int recursion_count; const char *s; char *result; char *p; char *free_me = NULL; int intvalue; if (recursion_count > 50) { log_error ("variables nested too deeply\n"); return NULL; } recursion_count++; free_me = opt.enable_varsubst? substitute_line_copy (name) : NULL; if (free_me) name = free_me; for (s=name; *s && !spacep (s); s++) ; if (!*s) { s = get_var (name); result = s? xstrdup (s): NULL; } else if ( (s - name) == 3 && !strncmp (name, "get", 3)) { while ( spacep (s) ) s++; if (!strcmp (s, "cwd")) { result = gnupg_getcwd (); if (!result) log_error ("getcwd failed: %s\n", strerror (errno)); } else if (!strcmp (s, "homedir")) result = xstrdup (gnupg_homedir ()); else if (!strcmp (s, "sysconfdir")) result = xstrdup (gnupg_sysconfdir ()); else if (!strcmp (s, "bindir")) result = xstrdup (gnupg_bindir ()); else if (!strcmp (s, "libdir")) result = xstrdup (gnupg_libdir ()); else if (!strcmp (s, "libexecdir")) result = xstrdup (gnupg_libexecdir ()); else if (!strcmp (s, "datadir")) result = xstrdup (gnupg_datadir ()); else if (!strcmp (s, "serverpid")) result = xasprintf ("%d", (int)server_pid); else { log_error ("invalid argument '%s' for variable function 'get'\n", s); log_info ("valid are: cwd, " "{home,bin,lib,libexec,data}dir, serverpid\n"); result = NULL; } } else if ( (s - name) == 8 && !strncmp (name, "unescape", 8)) { s++; result = unescape_string (s); } else if ( (s - name) == 9 && !strncmp (name, "unpercent", 9)) { s++; result = unpercent_string (s, 0); } else if ( (s - name) == 10 && !strncmp (name, "unpercent+", 10)) { s++; result = unpercent_string (s, 1); } else if ( (s - name) == 7 && !strncmp (name, "percent", 7)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); } else if ( (s - name) == 8 && !strncmp (name, "percent+", 8)) { s++; result = percent_escape (s, "+\t\r\n\f\v"); for (p=result; *p; p++) if (*p == ' ') *p = '+'; } else if ( (s - name) == 7 && !strncmp (name, "errcode", 7)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_code (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errsource", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%d", gpg_err_source (intvalue)); } else if ( (s - name) == 9 && !strncmp (name, "errstring", 9)) { s++; intvalue = (int)strtol (s, NULL, 0); result = xasprintf ("%s <%s>", gpg_strerror (intvalue), gpg_strsource (intvalue)); } else if ( (s - name) == 1 && strchr ("+-*/%!|&", *name)) { result = arithmetic_op (*name, s+1); } else { log_error ("unknown variable function '%.*s'\n", (int)(s-name), name); result = NULL; } xfree (free_me); recursion_count--; return result; } /* Substitute variables in LINE and return a new allocated buffer if required. The function might modify LINE if the expanded version fits into it. */ static char * substitute_line (char *buffer) { char *line = buffer; char *p, *pend; const char *value; size_t valuelen, n; char *result = NULL; char *freeme = NULL; while (*line) { p = strchr (line, '$'); if (!p) return result; /* No more variables. */ if (p[1] == '$') /* Escaped dollar sign. */ { memmove (p, p+1, strlen (p+1)+1); line = p + 1; continue; } if (p[1] == '{') { int count = 0; for (pend=p+2; *pend; pend++) { if (*pend == '{') count++; else if (*pend == '}') { if (--count < 0) break; } } if (!*pend) return result; /* Unclosed - don't substitute. */ } else { for (pend=p+1; *pend && !spacep (pend) && *pend != '$' ; pend++) ; } if (p[1] == '{' && *pend == '}') { int save = *pend; *pend = 0; freeme = get_var_ext (p+2); value = freeme; *pend++ = save; } else if (*pend) { int save = *pend; *pend = 0; value = get_var (p+1); *pend = save; } else value = get_var (p+1); if (!value) value = ""; valuelen = strlen (value); if (valuelen <= pend - p) { memcpy (p, value, valuelen); p += valuelen; n = pend - p; if (n) memmove (p, p+n, strlen (p+n)+1); line = p; } else { char *src = result? result : buffer; char *dst; dst = xmalloc (strlen (src) + valuelen + 1); n = p - src; memcpy (dst, src, n); memcpy (dst + n, value, valuelen); n += valuelen; strcpy (dst + n, pend); line = dst + n; xfree (result); result = dst; } xfree (freeme); freeme = NULL; } return result; } /* Same as substitute_line but do not modify BUFFER. */ static char * substitute_line_copy (const char *buffer) { char *result, *p; p = xstrdup (buffer?buffer:""); result = substitute_line (p); if (!result) result = p; else xfree (p); return result; } static void assign_variable (char *line, int syslet) { char *name, *p, *tmp, *free_me, *buffer; /* Get the name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!*p) set_var (name, NULL); /* Remove variable. */ else if (syslet) { free_me = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (free_me) p = free_me; buffer = xmalloc (4 + strlen (p) + 1); strcpy (stpcpy (buffer, "get "), p); tmp = get_var_ext (buffer); xfree (buffer); set_var (name, tmp); xfree (tmp); xfree (free_me); } else { tmp = opt.enable_varsubst? substitute_line_copy (p) : NULL; if (tmp) { set_var (name, tmp); xfree (tmp); } else set_var (name, p); } } static void show_variables (void) { variable_t var; for (var = variable_table; var; var = var->next) if (var->value) printf ("%-20s %s\n", var->name, var->value); } /* Store an inquire response pattern. Note, that this function may change the content of LINE. We assume that leading white spaces are already removed. */ static void add_definq (char *line, int is_var, int is_prog) { definq_t d; char *name, *p; /* Get name. */ name = line; for (p=name; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; d = xmalloc (sizeof *d + strlen (p) ); strcpy (d->file, p); d->is_var = is_var; d->is_prog = is_prog; if ( !strcmp (name, "*")) d->name = NULL; else d->name = xstrdup (name); d->next = NULL; *definq_list_tail = d; definq_list_tail = &d->next; } /* Show all inquiry definitions. */ static void show_definq (void) { definq_t d; for (d=definq_list; d; d = d->next) if (d->name) printf ("%-20s %c %s\n", d->name, d->is_var? 'v' : d->is_prog? 'p':'f', d->file); for (d=definq_list; d; d = d->next) if (!d->name) printf ("%-20s %c %s\n", "*", d->is_var? 'v': d->is_prog? 'p':'f', d->file); } /* Clear all inquiry definitions. */ static void clear_definq (void) { while (definq_list) { definq_t tmp = definq_list->next; xfree (definq_list->name); xfree (definq_list); definq_list = tmp; } definq_list_tail = &definq_list; } static void do_sendfd (assuan_context_t ctx, char *line) { - FILE *fp; + 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) { gpgrt_argparse_t pargs; int no_more_options = 0; assuan_context_t ctx; char *line, *p; char *tmpline; size_t linesize; int rc; int cmderr; const char *opt_run = NULL; gpgrt_stream_t script_fp = NULL; int use_tty, keep_line; struct { int collecting; loopline_t head; loopline_t *tail; loopline_t current; unsigned int nestlevel; int oneshot; char *condition; } loopstack[20]; int loopidx; char **cmdline_commands = NULL; char *historyname = NULL; static const char *changeuser; early_system_init (); gnupg_rl_initialize (); gpgrt_set_strusage (my_strusage); log_set_prefix ("gpg-connect-agent", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); assuan_set_gpg_err_source (0); gnupg_init_signals (0, NULL); opt.autostart = 1; opt.connect_flags = 1; /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = ARGPARSE_FLAG_KEEP; while (!no_more_options && gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oAgentProgram: opt.agent_program = pargs.r.ret_str; break; case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break; case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str; break; case oNoAutostart: opt.autostart = 0; break; case oNoHistory: opt.no_history = 1; break; case oHex: opt.hex = 1; break; case oDecode: opt.decode = 1; break; case oDirmngr: opt.use_dirmngr = 1; break; case oKeyboxd: opt.use_keyboxd = 1; break; case oUIServer: opt.use_uiserver = 1; break; case oRawSocket: opt.raw_socket = pargs.r.ret_str; break; case oTcpSocket: opt.tcp_socket = pargs.r.ret_str; break; case oExec: opt.exec = 1; break; case oNoExtConnect: opt.connect_flags &= ~(1); break; case oRun: opt_run = pargs.r.ret_str; break; case oSubst: opt.enable_varsubst = 1; opt.trim_leading_spaces = 1; break; case oChUid: changeuser = pargs.r.ret_str; break; default: pargs.err = 2; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (changeuser && gnupg_chuid (changeuser, 0)) log_inc_errorcount (); /* Force later termination. */ if (log_get_errorcount (0)) exit (2); /* --uiserver is a shortcut for a specific raw socket. This comes in particular handy on Windows. */ if (opt.use_uiserver) { opt.raw_socket = make_absfilename (gnupg_homedir (), "S.uiserver", NULL); } /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } use_tty = (gnupg_isatty (fileno (stdin)) && gnupg_isatty (fileno (stdout))); if (opt.exec) { if (!argc) { log_error (_("option \"%s\" requires a program " "and optional arguments\n"), "--exec" ); exit (1); } } else if (argc) cmdline_commands = argv; if (opt.exec && opt.raw_socket) { opt.raw_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--raw-socket", "--exec"); } if (opt.exec && opt.tcp_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--exec"); } if (opt.tcp_socket && opt.raw_socket) { opt.tcp_socket = NULL; log_info (_("option \"%s\" ignored due to \"%s\"\n"), "--tcp-socket", "--raw-socket"); } if (opt_run && !(script_fp = gpgrt_fopen (opt_run, "r"))) { log_error ("cannot open run file '%s': %s\n", opt_run, strerror (errno)); exit (1); } if (opt.exec) { assuan_fd_t no_close[3]; no_close[0] = assuan_fd_from_posix_fd (es_fileno (es_stderr)); no_close[1] = assuan_fd_from_posix_fd (log_get_fd ()); no_close[2] = ASSUAN_INVALID_FD; rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_pipe_connect (ctx, *argv, (const char **)argv, no_close, NULL, NULL, (opt.connect_flags & 1) ? ASSUAN_PIPE_CONNECT_FDPASSING : 0); if (rc) { log_error ("assuan_pipe_connect_ext failed: %s\n", gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("server '%s' started\n", *argv); } else if (opt.raw_socket) { rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.raw_socket, 0, (opt.connect_flags & 1) ? ASSUAN_SOCKET_CONNECT_FDPASSING : 0); if (rc) { log_error ("can't connect to socket '%s': %s\n", opt.raw_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", opt.raw_socket); } else if (opt.tcp_socket) { char *url; url = xstrconcat ("assuan://", opt.tcp_socket, NULL); rc = assuan_new (&ctx); if (rc) { log_error ("assuan_new failed: %s\n", gpg_strerror (rc)); exit (1); } rc = assuan_socket_connect (ctx, opt.tcp_socket, 0, 0); if (rc) { log_error ("can't connect to server '%s': %s\n", opt.tcp_socket, gpg_strerror (rc)); exit (1); } if (opt.verbose) log_info ("connection to socket '%s' established\n", url); xfree (url); } else ctx = start_agent (); /* See whether there is a line pending from the server (in case assuan did not run the initial handshaking). */ if (assuan_pending_line (ctx)) { rc = read_and_print_response (ctx, 0, &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); } for (loopidx=0; loopidx < DIM (loopstack); loopidx++) loopstack[loopidx].collecting = 0; loopidx = -1; line = NULL; linesize = 0; keep_line = 1; for (;;) { int n; size_t maxlength = 2048; assert (loopidx < (int)DIM (loopstack)); if (loopidx >= 0 && loopstack[loopidx].current) { keep_line = 0; xfree (line); line = xstrdup (loopstack[loopidx].current->line); n = strlen (line); /* Never go beyond of the final /end. */ if (loopstack[loopidx].current->next) loopstack[loopidx].current = loopstack[loopidx].current->next; else if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) ; else log_fatal ("/end command vanished\n"); } else if (cmdline_commands && *cmdline_commands && !script_fp) { keep_line = 0; xfree (line); line = xstrdup (*cmdline_commands); cmdline_commands++; n = strlen (line); if (n >= maxlength) maxlength = 0; } else if (use_tty && !script_fp) { keep_line = 0; xfree (line); if (!historyname && !opt.no_history) { historyname = make_filename (gnupg_homedir (), HISTORYNAME, NULL); if (tty_read_history (historyname, 500)) log_info ("error reading '%s': %s\n", historyname, gpg_strerror (gpg_error_from_syserror ())); } line = tty_get ("> "); n = strlen (line); if (n==1 && *line == CONTROL_D) n = 0; if (n >= maxlength) maxlength = 0; } else { if (!keep_line) { xfree (line); line = NULL; linesize = 0; keep_line = 1; } n = gpgrt_read_line (script_fp ? script_fp : gpgrt_stdin, &line, &linesize, &maxlength); } if (n < 0) { log_error (_("error reading input: %s\n"), strerror (errno)); if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; log_error ("stopping script execution\n"); continue; } exit (1); } if (!n) { /* EOF */ if (script_fp) { gpgrt_fclose (script_fp); script_fp = NULL; if (opt.verbose) log_info ("end of script\n"); continue; } break; } if (!maxlength) { log_error (_("line too long - skipped\n")); continue; } if (memchr (line, 0, n)) log_info (_("line shortened due to embedded Nul character\n")); if (line[n-1] == '\n') line[n-1] = 0; if (opt.trim_leading_spaces) { const char *s = line; while (spacep (s)) s++; if (s != line) { for (p=line; *s;) *p++ = *s++; *p = 0; n = p - line; } } if (loopidx+1 >= 0 && loopstack[loopidx+1].collecting) { loopline_t ll; ll = xmalloc (sizeof *ll + strlen (line)); ll->next = NULL; strcpy (ll->line, line); *loopstack[loopidx+1].tail = ll; loopstack[loopidx+1].tail = &ll->next; if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4))) loopstack[loopidx+1].nestlevel--; else if (!strncmp (line, "/while", 6) && (!line[6]||spacep(line+6))) loopstack[loopidx+1].nestlevel++; if (loopstack[loopidx+1].nestlevel) continue; /* We reached the corresponding /end. */ loopstack[loopidx+1].collecting = 0; loopidx++; } if (*line == '/') { /* Handle control commands. */ char *cmd = line+1; for (p=cmd; *p && !spacep (p); p++) ; if (*p) *p++ = 0; while (spacep (p)) p++; if (!strcmp (cmd, "let")) { assign_variable (p, 0); } else if (!strcmp (cmd, "slet")) { /* Deprecated - never used in a released version. */ assign_variable (p, 1); } else if (!strcmp (cmd, "showvar")) { show_variables (); } else if (!strcmp (cmd, "definq")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 1, 0); xfree (tmpline); } else add_definq (p, 1, 0); } else if (!strcmp (cmd, "definqfile")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 0); xfree (tmpline); } else add_definq (p, 0, 0); } else if (!strcmp (cmd, "definqprog")) { tmpline = opt.enable_varsubst? substitute_line (p) : NULL; if (tmpline) { add_definq (tmpline, 0, 1); xfree (tmpline); } else add_definq (p, 0, 1); } else if (!strcmp (cmd, "datafile")) { const char *fname; if (current_datasink) { - if (current_datasink != stdout) - fclose (current_datasink); + 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") || !strcmp (cmd, "quit")) { break; } else if (!strcmp (cmd, "sleep")) { gnupg_sleep (1); } else if (!strcmp (cmd, "history")) { if (!strcmp (p, "--clear")) { tty_read_history (NULL, 0); } else log_error ("Only \"/history --clear\" is supported\n"); } else if (!strcmp (cmd, "help")) { puts ( "Available commands:\n" "/echo ARGS Echo ARGS.\n" "/let NAME VALUE Set variable NAME to VALUE.\n" "/showvar Show all variables.\n" "/definq NAME VAR Use content of VAR for inquiries with NAME.\n" "/definqfile NAME FILE Use content of FILE for inquiries with NAME.\n" "/definqprog NAME PGM Run PGM for inquiries with NAME.\n" "/datafile [NAME] Write all D line content to file NAME.\n" "/showdef Print all definitions.\n" "/cleardef Delete all definitions.\n" "/sendfd FILE MODE Open FILE and pass descriptor to server.\n" "/recvfd Receive FD from server and print.\n" "/open VAR FILE MODE Open FILE and assign the file descriptor to VAR.\n" "/close FD Close file with descriptor FD.\n" "/showopen Show descriptors of all open files.\n" "/serverpid Retrieve the pid of the server.\n" "/[no]hex Enable hex dumping of received data lines.\n" "/[no]decode Enable decoding of received data lines.\n" "/[no]subst Enable variable substitution.\n" "/run FILE Run commands from FILE.\n" "/if VAR Begin conditional block controlled by VAR.\n" "/while VAR Begin loop controlled by VAR.\n" "/end End loop or condition\n" "/history Manage the history\n" "/bye Terminate gpg-connect-agent.\n" "/help Print this help."); } else log_error (_("unknown command '%s'\n"), cmd ); continue; } if (opt.verbose && script_fp) puts (line); tmpline = opt.enable_varsubst? substitute_line (line) : NULL; if (tmpline) { rc = assuan_write_line (ctx, tmpline); xfree (tmpline); } else rc = assuan_write_line (ctx, line); if (rc) { log_info (_("sending line failed: %s\n"), gpg_strerror (rc) ); break; } if (*line == '#' || !*line) continue; /* Don't expect a response for a comment line. */ rc = read_and_print_response (ctx, help_cmd_p (line), &cmderr); if (rc) log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) ); if ((rc || cmderr) && script_fp) { log_error ("stopping script execution\n"); gpgrt_fclose (script_fp); script_fp = NULL; } /* FIXME: If the last command was BYE or the server died for some other reason, we won't notice until we get the next input command. Probing the connection with a non-blocking read could help to notice termination or other problems early. */ } if (opt.verbose) log_info ("closing connection to %s\n", opt.use_dirmngr? "dirmngr" : opt.use_keyboxd? "keyboxd" : "agent"); if (historyname && tty_write_history (historyname)) log_info ("error writing '%s': %s\n", historyname, gpg_strerror (gpg_error_from_syserror ())); /* XXX: We would like to release the context here, but libassuan nicely says good bye to the server, which results in a SIGPIPE if the server died. Unfortunately, libassuan does not ignore SIGPIPE when used with UNIX sockets, hence we simply leak the context here. */ if (0) assuan_release (ctx); else gpgrt_annotate_leaked_object (ctx); xfree (historyname); xfree (line); return 0; } /* Handle an Inquire from the server. Return False if it could not be handled; in this case the caller shll complete the operation. LINE is the complete line as received from the server. This function may change the content of LINE. */ static int handle_inquire (assuan_context_t ctx, char *line) { const char *name; definq_t d; + /* 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 if (opt.use_keyboxd) err = start_new_keyboxd (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.keyboxd_program, opt.autostart, !opt.quiet, 0, NULL, NULL); else err = start_new_gpg_agent (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.agent_program, NULL, NULL, session_env, opt.autostart, !opt.quiet, 0, NULL, NULL); session_env_release (session_env); if (err) { if (!opt.autostart && (gpg_err_code (err) == (opt.use_dirmngr? GPG_ERR_NO_DIRMNGR : opt.use_keyboxd? GPG_ERR_NO_KEYBOXD : GPG_ERR_NO_AGENT))) { /* In the no-autostart case we don't make gpg-connect-agent fail on a missing server. */ log_info (opt.use_dirmngr? _("no dirmngr running in this session\n"): opt.use_keyboxd? _("no keybox daemon running in this session\n"): _("no gpg-agent running in this session\n")); exit (0); } else { log_error (_("error sending standard options: %s\n"), gpg_strerror (err)); exit (1); } } return ctx; } diff --git a/tools/wks-util.c b/tools/wks-util.c index 1706c694a..621be7920 100644 --- a/tools/wks-util.c +++ b/tools/wks-util.c @@ -1,1231 +1,1231 @@ /* 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 output 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, 0); 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, 0); 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; const 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, 0); 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) { /* 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; }