diff --git a/agent/command.c b/agent/command.c index 160979dae..e21dcdac4 100644 --- a/agent/command.c +++ b/agent/command.c @@ -1,4013 +1,4012 @@ /* command.c - gpg-agent command handler * Copyright (C) 2001-2011 Free Software Foundation, Inc. * Copyright (C) 2001-2013 Werner Koch * Copyright (C) 2015 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 . */ /* FIXME: we should not use the default assuan buffering but setup some buffering in secure mempory to protect session keys etc. */ #include #include #include #include #include #include #include #include #include #include #include "agent.h" #include #include "../common/i18n.h" #include "cvt-openpgp.h" #include "../common/ssh-utils.h" #include "../common/asshelp.h" #include "../common/server-help.h" /* Maximum allowed size of the inquired ciphertext. */ #define MAXLEN_CIPHERTEXT 4096 /* Maximum allowed size of the key parameters. */ #define MAXLEN_KEYPARAM 1024 /* Maximum allowed size of key data as used in inquiries (bytes). */ #define MAXLEN_KEYDATA 8192 /* Maximum length of a secret to store under one key. */ #define MAXLEN_PUT_SECRET 4096 /* The size of the import/export KEK key (in bytes). */ #define KEYWRAP_KEYSIZE (128/8) /* A shortcut to call assuan_set_error using an gpg_err_code_t and a text string. */ #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t)) /* Check that the maximum digest length we support has at least the length of the keygrip. */ #if MAX_DIGEST_LEN < 20 #error MAX_DIGEST_LEN shorter than keygrip #endif /* Data used to associate an Assuan context with local server data. This is this modules local part of the server_control_s struct. */ struct server_local_s { /* Our Assuan context. */ assuan_context_t assuan_ctx; /* If this flag is true, the passphrase cache is used for signing operations. It defaults to true but may be set on a per connection base. The global option opt.ignore_cache_for_signing takes precedence over this flag. */ unsigned int use_cache_for_signing : 1; /* Flag to suppress I/O logging during a command. */ unsigned int pause_io_logging : 1; /* Flag indicating that the connection is from ourselves. */ unsigned int connect_from_self : 1; /* Helper flag for io_monitor to allow suppressing of our own * greeting in some cases. See io_monitor for details. */ unsigned int greeting_seen : 1; /* If this flag is set to true the agent will be terminated after the end of the current session. */ unsigned int stopme : 1; /* Flag indicating whether pinentry notifications shall be done. */ unsigned int allow_pinentry_notify : 1; /* An allocated description for the next key operation. This is used if a pinnetry needs to be popped up. */ char *keydesc; /* Malloced KEK (Key-Encryption-Key) for the import_key command. */ void *import_key; /* Malloced KEK for the export_key command. */ void *export_key; /* Client is aware of the error code GPG_ERR_FULLY_CANCELED. */ int allow_fully_canceled; /* Last CACHE_NONCE sent as status (malloced). */ char *last_cache_nonce; /* Last PASSWD_NONCE sent as status (malloced). */ char *last_passwd_nonce; /* Per connection cache of the keyinfo from the cards. The * eventcounters for cards at the time the info was fetched is * stored here as a freshness indicator. */ struct { struct card_key_info_s *ki; unsigned int eventno; unsigned int maybe_key_change; } last_card_keyinfo; }; /* An entry for the getval/putval commands. */ struct putval_item_s { struct putval_item_s *next; size_t off; /* Offset to the value into DATA. */ size_t len; /* Length of the value. */ char d[1]; /* Key | Nul | value. */ }; /* A list of key value pairs fpr the getval/putval commands. */ static struct putval_item_s *putval_list; /* To help polling clients, we keep track of the number of certain events. This structure keeps those counters. The counters are integers and there should be no problem if they are overflowing as callers need to check only whether a counter changed. The actual values are not meaningful. */ struct { /* Incremented if any of the other counters below changed. */ unsigned int any; /* Incremented if a key is added or removed from the internal privat key database. */ unsigned int key; /* Incremented if a change of the card readers stati has been detected. */ unsigned int card; /* Internal counter to track possible changes to a key. * FIXME: This should be replaced by generic notifications from scd. */ unsigned int maybe_key_change; } eventcounter; /* Local prototypes. */ static int command_has_option (const char *cmd, const char *cmdopt); /* Release the memory buffer MB but first wipe out the used memory. */ static void clear_outbuf (membuf_t *mb) { void *p; size_t n; p = get_membuf (mb, &n); if (p) { wipememory (p, n); xfree (p); } } /* Write the content of memory buffer MB as assuan data to CTX and wipe the buffer out afterwards. */ static gpg_error_t write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb) { gpg_error_t ae; void *p; size_t n; p = get_membuf (mb, &n); if (!p) return out_of_core (); ae = assuan_send_data (ctx, p, n); memset (p, 0, n); xfree (p); return ae; } /* Clear the nonces used to enable the passphrase cache for certain multi-command command sequences. */ static void clear_nonce_cache (ctrl_t ctrl) { if (ctrl->server_local->last_cache_nonce) { agent_put_cache (ctrl, ctrl->server_local->last_cache_nonce, CACHE_MODE_NONCE, NULL, 0); xfree (ctrl->server_local->last_cache_nonce); ctrl->server_local->last_cache_nonce = NULL; } if (ctrl->server_local->last_passwd_nonce) { agent_put_cache (ctrl, ctrl->server_local->last_passwd_nonce, CACHE_MODE_NONCE, NULL, 0); xfree (ctrl->server_local->last_passwd_nonce); ctrl->server_local->last_passwd_nonce = NULL; } } /* This function is called by Libassuan whenever the client sends a reset. It has been registered similar to the other Assuan commands. */ static gpg_error_t reset_notify (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void) line; memset (ctrl->keygrip, 0, 20); ctrl->have_keygrip = 0; ctrl->digest.valuelen = 0; xfree (ctrl->digest.data); ctrl->digest.data = NULL; xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; clear_nonce_cache (ctrl); return 0; } /* Replace all '+' by a blank in the string S. */ static void plus_to_blank (char *s) { for (; *s; s++) { if (*s == '+') *s = ' '; } } /* Parse a hex string. Return an Assuan error code or 0 on success and the length of the parsed string in LEN. */ static int parse_hexstring (assuan_context_t ctx, const char *string, size_t *len) { const char *p; size_t n; /* parse the hash value */ for (p=string, n=0; hexdigitp (p); p++, n++) ; if (*p != ' ' && *p != '\t' && *p) return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring"); if ((n&1)) return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits"); *len = n; return 0; } /* Parse the keygrip in STRING into the provided buffer BUF. BUF must provide space for 20 bytes. BUF is not changed if the function returns an error. */ static int parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf) { int rc; size_t n = 0; rc = parse_hexstring (ctx, string, &n); if (rc) return rc; n /= 2; if (n != 20) return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of keygrip"); if (hex2bin (string, buf, 20) < 0) return set_error (GPG_ERR_BUG, "hex2bin"); return 0; } /* Parse the TTL from STRING. Leading and trailing spaces are * skipped. The value is constrained to -1 .. MAXINT. On error 0 is * returned, else the number of bytes scanned. */ static size_t parse_ttl (const char *string, int *r_ttl) { const char *string_orig = string; long ttl; char *pend; ttl = strtol (string, &pend, 10); string = pend; if (string == string_orig || !(spacep (string) || !*string) || ttl < -1L || (int)ttl != (long)ttl) { *r_ttl = 0; return 0; } while (spacep (string) || *string== '\n') string++; *r_ttl = (int)ttl; return string - string_orig; } /* Write an Assuan status line. KEYWORD is the first item on the * status line. The following arguments are all separated by a space * in the output. The last argument must be a NULL. Linefeeds and * carriage returns characters (which are not allowed in an Assuan * status line) are silently quoted in C-style. */ gpg_error_t agent_write_status (ctrl_t ctrl, const char *keyword, ...) { gpg_error_t err; va_list arg_ptr; assuan_context_t ctx = ctrl->server_local->assuan_ctx; va_start (arg_ptr, keyword); err = vprint_assuan_status_strings (ctx, keyword, arg_ptr); va_end (arg_ptr); return err; } /* This function is similar to print_assuan_status but takes a CTRL arg instead of an assuan context as first argument. */ gpg_error_t agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...) { gpg_error_t err; va_list arg_ptr; assuan_context_t ctx = ctrl->server_local->assuan_ctx; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, keyword, format, arg_ptr); va_end (arg_ptr); return err; } /* Helper to notify the client about a launched Pinentry. Because that might disturb some older clients, this is only done if enabled via an option. Returns an gpg error code. */ gpg_error_t agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid, const char *extra) { char line[256]; if (!ctrl || !ctrl->server_local || !ctrl->server_local->allow_pinentry_notify) return 0; snprintf (line, DIM(line), "PINENTRY_LAUNCHED %lu%s%s", pid, extra?" ":"", extra? extra:""); return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0); } /* An agent progress callback for Libgcrypt. This has been registered * to be called via the progress dispatcher mechanism from * gpg-agent.c */ static void progress_cb (ctrl_t ctrl, const char *what, int printchar, int current, int total) { if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) ; else if (printchar == '\n' && what && !strcmp (what, "primegen")) agent_print_status (ctrl, "PROGRESS", "%.20s X 100 100", what); else agent_print_status (ctrl, "PROGRESS", "%.20s %c %d %d", what, printchar=='\n'?'X':printchar, current, total); } /* Helper to print a message while leaving a command. Note that this * function does not call assuan_set_error; the caller may do this * prior to calling us. */ static gpg_error_t leave_cmd (assuan_context_t ctx, gpg_error_t err) { if (err) { const char *name = assuan_get_command_name (ctx); if (!name) name = "?"; /* Not all users of gpg-agent know about the fully canceled error code; map it back if needed. */ if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED) { ctrl_t ctrl = assuan_get_pointer (ctx); if (!ctrl->server_local->allow_fully_canceled) err = gpg_err_make (gpg_err_source (err), GPG_ERR_CANCELED); } /* Most code from common/ does not know the error source, thus we fix this here. */ if (gpg_err_source (err) == GPG_ERR_SOURCE_UNKNOWN) err = gpg_err_make (GPG_ERR_SOURCE_DEFAULT, gpg_err_code (err)); if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT) log_error ("command '%s' failed: %s\n", name, gpg_strerror (err)); else log_error ("command '%s' failed: %s <%s>\n", name, gpg_strerror (err), gpg_strsource (err)); } return err; } static const char hlp_geteventcounter[] = "GETEVENTCOUNTER\n" "\n" "Return a status line named EVENTCOUNTER with the current values\n" "of all event counters. The values are decimal numbers in the range\n" "0 to UINT_MAX and wrapping around to 0. The actual values should\n" "not be relied upon, they shall only be used to detect a change.\n" "\n" "The currently defined counters are:\n" "\n" "ANY - Incremented with any change of any of the other counters.\n" "KEY - Incremented for added or removed private keys.\n" "CARD - Incremented for changes of the card readers stati."; static gpg_error_t cmd_geteventcounter (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)line; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); return agent_print_status (ctrl, "EVENTCOUNTER", "%u %u %u", eventcounter.any, eventcounter.key, eventcounter.card); } /* This function should be called once for all key removals or additions. This function is assured not to do any context switches. */ void bump_key_eventcounter (void) { eventcounter.key++; eventcounter.any++; } /* This function should be called for all card reader status changes. This function is assured not to do any context switches. */ void bump_card_eventcounter (void) { eventcounter.card++; eventcounter.any++; } static const char hlp_istrusted[] = "ISTRUSTED \n" "\n" "Return OK when we have an entry with this fingerprint in our\n" "trustlist"; static gpg_error_t cmd_istrusted (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc, n, i; char *p; char fpr[41]; /* Parse the fingerprint value. */ for (p=line,n=0; hexdigitp (p); p++, n++) ; if (*p || !(n == 40 || n == 32)) return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint"); i = 0; if (n==32) { strcpy (fpr, "00000000"); i += 8; } for (p=line; i < 40; p++, i++) fpr[i] = *p >= 'a'? (*p & 0xdf): *p; fpr[i] = 0; rc = agent_istrusted (ctrl, fpr, NULL); if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED) return rc; else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF ) return gpg_error (GPG_ERR_NOT_TRUSTED); else return leave_cmd (ctx, rc); } static const char hlp_listtrusted[] = "LISTTRUSTED\n" "\n" "List all entries from the trustlist."; static gpg_error_t cmd_listtrusted (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; (void)line; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); rc = agent_listtrusted (ctx); return leave_cmd (ctx, rc); } static const char hlp_martrusted[] = "MARKTRUSTED \n" "\n" "Store a new key in into the trustlist."; static gpg_error_t cmd_marktrusted (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc, n, i; char *p; char fpr[41]; int flag; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); /* parse the fingerprint value */ for (p=line,n=0; hexdigitp (p); p++, n++) ; if (!spacep (p) || !(n == 40 || n == 32)) return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint"); i = 0; if (n==32) { strcpy (fpr, "00000000"); i += 8; } for (p=line; i < 40; p++, i++) fpr[i] = *p >= 'a'? (*p & 0xdf): *p; fpr[i] = 0; while (spacep (p)) p++; flag = *p++; if ( (flag != 'S' && flag != 'P') || !spacep (p) ) return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S"); while (spacep (p)) p++; rc = agent_marktrusted (ctrl, p, fpr, flag); return leave_cmd (ctx, rc); } static const char hlp_havekey[] = "HAVEKEY \n" "\n" "Return success if at least one of the secret keys with the given\n" "keygrips is available."; static gpg_error_t cmd_havekey (assuan_context_t ctx, char *line) { gpg_error_t err; unsigned char buf[20]; do { err = parse_keygrip (ctx, line, buf); if (err) return err; if (!agent_key_available (buf)) return 0; /* Found. */ while (*line && *line != ' ' && *line != '\t') line++; while (*line == ' ' || *line == '\t') line++; } while (*line); /* No leave_cmd() here because errors are expected and would clutter the log. */ return gpg_error (GPG_ERR_NO_SECKEY); } static const char hlp_sigkey[] = "SIGKEY \n" "SETKEY \n" "\n" "Set the key used for a sign or decrypt operation."; static gpg_error_t cmd_sigkey (assuan_context_t ctx, char *line) { int rc; ctrl_t ctrl = assuan_get_pointer (ctx); rc = parse_keygrip (ctx, line, ctrl->keygrip); if (rc) return rc; ctrl->have_keygrip = 1; return 0; } static const char hlp_setkeydesc[] = "SETKEYDESC plus_percent_escaped_string\n" "\n" "Set a description to be used for the next PKSIGN, PKDECRYPT, IMPORT_KEY\n" "or EXPORT_KEY operation if this operation requires a passphrase. If\n" "this command is not used a default text will be used. Note, that\n" "this description implicitly selects the label used for the entry\n" "box; if the string contains the string PIN (which in general will\n" "not be translated), \"PIN\" is used, otherwise the translation of\n" "\"passphrase\" is used. The description string should not contain\n" "blanks unless they are percent or '+' escaped.\n" "\n" "The description is only valid for the next PKSIGN, PKDECRYPT,\n" "IMPORT_KEY, EXPORT_KEY, or DELETE_KEY operation."; static gpg_error_t cmd_setkeydesc (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); char *desc, *p; for (p=line; *p == ' '; p++) ; desc = p; p = strchr (desc, ' '); if (p) *p = 0; /* We ignore any garbage; we might late use it for other args. */ if (!*desc) return set_error (GPG_ERR_ASS_PARAMETER, "no description given"); /* Note, that we only need to replace the + characters and should leave the other escaping in place because the escaped string is send verbatim to the pinentry which does the unescaping (but not the + replacing) */ plus_to_blank (desc); xfree (ctrl->server_local->keydesc); if (ctrl->restricted) { ctrl->server_local->keydesc = strconcat ((ctrl->restricted == 2 ? _("Note: Request from the web browser.") : _("Note: Request from a remote site.") ), "%0A%0A", desc, NULL); } else ctrl->server_local->keydesc = xtrystrdup (desc); if (!ctrl->server_local->keydesc) return out_of_core (); return 0; } static const char hlp_sethash[] = "SETHASH (--hash=)|() ]\n" "SETHASH [--pss] --inquire\n" "\n" "The client can use this command to tell the server about the data\n" "(which usually is a hash) to be signed. The option --inquire is\n" "used to ask back for to-be-signed data in case of PureEdDSA or\n" "with --pss for pre-formatted rsaPSS."; static gpg_error_t cmd_sethash (assuan_context_t ctx, char *line) { gpg_error_t err; size_t n; char *p; ctrl_t ctrl = assuan_get_pointer (ctx); unsigned char *buf; char *endp; int algo; int opt_inquire, opt_pss; /* Parse the alternative hash options which may be used instead of the algo number. */ if (has_option_name (line, "--hash")) { if (has_option (line, "--hash=sha1")) algo = GCRY_MD_SHA1; else if (has_option (line, "--hash=sha224")) algo = GCRY_MD_SHA224; else if (has_option (line, "--hash=sha256")) algo = GCRY_MD_SHA256; else if (has_option (line, "--hash=sha384")) algo = GCRY_MD_SHA384; else if (has_option (line, "--hash=sha512")) algo = GCRY_MD_SHA512; else if (has_option (line, "--hash=rmd160")) algo = GCRY_MD_RMD160; else if (has_option (line, "--hash=md5")) algo = GCRY_MD_MD5; else if (has_option (line, "--hash=tls-md5sha1")) algo = MD_USER_TLS_MD5SHA1; else if (has_option (line, "--hash=none")) algo = 0; else { err = set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm"); goto leave; } } else algo = 0; opt_pss = has_option (line, "--pss"); opt_inquire = has_option (line, "--inquire"); line = skip_options (line); if (!algo && !opt_inquire) { /* No hash option has been given: require an algo number instead */ algo = (int)strtoul (line, &endp, 10); for (line = endp; *line == ' ' || *line == '\t'; line++) ; if (!algo || gcry_md_test_algo (algo)) { err = set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL); goto leave; } } xfree (ctrl->digest.data); ctrl->digest.data = NULL; ctrl->digest.algo = algo; ctrl->digest.raw_value = 0; ctrl->digest.is_pss = opt_pss; if (opt_inquire) { /* We limit the to-be-signed data to some reasonable size which * may eventually allow us to pass that even to smartcards. */ size_t maxlen = 2048; if (algo) { err = set_error (GPG_ERR_ASS_PARAMETER, "both --inquire and an algo are specified"); goto leave; } err = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen); if (!err) err = assuan_inquire (ctx, "TBSDATA", &buf, &n, maxlen); if (err) goto leave; ctrl->digest.data = buf; ctrl->digest.valuelen = n; } else { /* Parse the hash value. */ n = 0; err = parse_hexstring (ctx, line, &n); if (err) goto leave; n /= 2; if (algo == MD_USER_TLS_MD5SHA1 && n == 36) ; else if (n != 16 && n != 20 && n != 24 && n != 28 && n != 32 && n != 48 && n != 64) { err = set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash"); goto leave; } if (n > MAX_DIGEST_LEN) { err = set_error (GPG_ERR_ASS_PARAMETER, "hash value to long"); goto leave; } buf = ctrl->digest.value; ctrl->digest.valuelen = n; for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++) buf[n] = xtoi_2 (p); for (; n < ctrl->digest.valuelen; n++) buf[n] = 0; } leave: return leave_cmd (ctx, err); } static const char hlp_pksign[] = "PKSIGN [] []\n" "\n" "Perform the actual sign operation. Neither input nor output are\n" "sensitive to eavesdropping."; static gpg_error_t cmd_pksign (assuan_context_t ctx, char *line) { gpg_error_t err; cache_mode_t cache_mode = CACHE_MODE_NORMAL; ctrl_t ctrl = assuan_get_pointer (ctx); membuf_t outbuf; char *cache_nonce = NULL; char *p; line = skip_options (line); for (p=line; *p && *p != ' ' && *p != '\t'; p++) ; *p = '\0'; if (*line) cache_nonce = xtrystrdup (line); if (opt.ignore_cache_for_signing) cache_mode = CACHE_MODE_IGNORE; else if (!ctrl->server_local->use_cache_for_signing) cache_mode = CACHE_MODE_IGNORE; init_membuf (&outbuf, 512); err = agent_pksign (ctrl, cache_nonce, ctrl->server_local->keydesc, &outbuf, cache_mode); if (err) clear_outbuf (&outbuf); else err = write_and_clear_outbuf (ctx, &outbuf); xfree (cache_nonce); xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; return leave_cmd (ctx, err); } static const char hlp_pkdecrypt[] = "PKDECRYPT []\n" "\n" "Perform the actual decrypt operation. Input is not\n" "sensitive to eavesdropping."; static gpg_error_t cmd_pkdecrypt (assuan_context_t ctx, char *line) { int rc; ctrl_t ctrl = assuan_get_pointer (ctx); unsigned char *value; size_t valuelen; membuf_t outbuf; int padding; (void)line; /* First inquire the data to decrypt */ rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_CIPHERTEXT); if (!rc) rc = assuan_inquire (ctx, "CIPHERTEXT", &value, &valuelen, MAXLEN_CIPHERTEXT); if (rc) return rc; init_membuf (&outbuf, 512); rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc, value, valuelen, &outbuf, &padding); xfree (value); if (rc) clear_outbuf (&outbuf); else { if (padding != -1) rc = print_assuan_status (ctx, "PADDING", "%d", padding); else rc = 0; if (!rc) rc = write_and_clear_outbuf (ctx, &outbuf); } xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; return leave_cmd (ctx, rc); } static const char hlp_genkey[] = "GENKEY [--no-protection] [--preset] [--timestamp=]\n" " [--inq-passwd] [--passwd-nonce=] []\n" "\n" "Generate a new key, store the secret part and return the public\n" "part. Here is an example transaction:\n" "\n" " C: GENKEY\n" " S: INQUIRE KEYPARAM\n" " C: D (genkey (rsa (nbits 3072)))\n" " C: END\n" " S: D (public-key\n" " S: D (rsa (n 326487324683264) (e 10001)))\n" " S: OK key created\n" "\n" "If the --preset option is used the passphrase for the generated\n" "key will be added to the cache. If --inq-passwd is used an inquire\n" "with the keyword NEWPASSWD is used to request the passphrase for the\n" "new key. If a --passwd-nonce is used, the corresponding cached\n" "passphrase is used to protect the new key. If --timestamp is given\n" "its value is recorded as the key's creation time; the value is\n" "expected in ISO format (e.g. \"20030316T120000\")."; static gpg_error_t cmd_genkey (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; int no_protection; unsigned char *value = NULL; size_t valuelen; unsigned char *newpasswd = NULL; membuf_t outbuf; char *cache_nonce = NULL; char *passwd_nonce = NULL; int opt_preset; int opt_inq_passwd; size_t n; char *p, *pend; const char *s; time_t opt_timestamp; int c; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); no_protection = has_option (line, "--no-protection"); opt_preset = has_option (line, "--preset"); opt_inq_passwd = has_option (line, "--inq-passwd"); passwd_nonce = option_value (line, "--passwd-nonce"); if (passwd_nonce) { for (pend = passwd_nonce; *pend && !spacep (pend); pend++) ; c = *pend; *pend = '\0'; passwd_nonce = xtrystrdup (passwd_nonce); *pend = c; if (!passwd_nonce) { rc = gpg_error_from_syserror (); goto leave; } } if ((s=has_option_name (line, "--timestamp"))) { if (*s != '=') { rc = set_error (GPG_ERR_ASS_PARAMETER, "missing value for option"); goto leave; } opt_timestamp = isotime2epoch (s+1); if (opt_timestamp < 1) { rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid time value"); goto leave; } } else opt_timestamp = 0; line = skip_options (line); for (p=line; *p && *p != ' ' && *p != '\t'; p++) ; *p = '\0'; if (*line) cache_nonce = xtrystrdup (line); eventcounter.maybe_key_change++; /* First inquire the parameters */ rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_KEYPARAM); if (!rc) rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM); if (rc) return rc; init_membuf (&outbuf, 512); /* If requested, ask for the password to be used for the key. If this is not used the regular Pinentry mechanism is used. */ if (opt_inq_passwd && !no_protection) { /* (N is used as a dummy) */ assuan_begin_confidential (ctx); rc = assuan_inquire (ctx, "NEWPASSWD", &newpasswd, &n, 256); assuan_end_confidential (ctx); if (rc) goto leave; if (!*newpasswd) { /* Empty password given - switch to no-protection mode. */ xfree (newpasswd); newpasswd = NULL; no_protection = 1; } } else if (passwd_nonce) newpasswd = agent_get_cache (ctrl, passwd_nonce, CACHE_MODE_NONCE); rc = agent_genkey (ctrl, cache_nonce, opt_timestamp, (char*)value, valuelen, no_protection, newpasswd, opt_preset, &outbuf); leave: if (newpasswd) { /* Assuan_inquire does not allow us to read into secure memory thus we need to wipe it ourself. */ wipememory (newpasswd, strlen (newpasswd)); xfree (newpasswd); } xfree (value); if (rc) clear_outbuf (&outbuf); else rc = write_and_clear_outbuf (ctx, &outbuf); xfree (cache_nonce); xfree (passwd_nonce); return leave_cmd (ctx, rc); } static const char hlp_readkey[] = "READKEY \n" " --card \n" "\n" "Return the public key for the given keygrip or keyid.\n" "With --card, private key file with card information will be created."; static gpg_error_t cmd_readkey (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; unsigned char grip[20]; gcry_sexp_t s_pkey = NULL; unsigned char *pkbuf = NULL; char *serialno = NULL; size_t pkbuflen; const char *opt_card; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); opt_card = has_option_name (line, "--card"); line = skip_options (line); if (opt_card) { const char *keyid = opt_card; rc = agent_card_getattr (ctrl, "SERIALNO", &serialno, NULL); if (rc) { log_error (_("error getting serial number of card: %s\n"), gpg_strerror (rc)); goto leave; } rc = agent_card_readkey (ctrl, keyid, &pkbuf, NULL); if (rc) goto leave; pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL); rc = gcry_sexp_sscan (&s_pkey, NULL, (char*)pkbuf, pkbuflen); if (rc) goto leave; if (!gcry_pk_get_keygrip (s_pkey, grip)) { rc = gcry_pk_testkey (s_pkey); if (rc == 0) rc = gpg_error (GPG_ERR_INTERNAL); goto leave; } rc = agent_write_shadow_key (grip, serialno, keyid, pkbuf, 0); if (rc) goto leave; rc = assuan_send_data (ctx, pkbuf, pkbuflen); } else { rc = parse_keygrip (ctx, line, grip); if (rc) goto leave; rc = agent_public_key_from_file (ctrl, grip, &s_pkey); if (!rc) { pkbuflen = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0); log_assert (pkbuflen); pkbuf = xtrymalloc (pkbuflen); if (!pkbuf) rc = gpg_error_from_syserror (); else { pkbuflen = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, pkbuf, pkbuflen); rc = assuan_send_data (ctx, pkbuf, pkbuflen); } } } leave: xfree (serialno); xfree (pkbuf); gcry_sexp_release (s_pkey); return leave_cmd (ctx, rc); } static const char hlp_keyinfo[] = "KEYINFO [--[ssh-]list] [--data] [--ssh-fpr[=algo]] [--with-ssh] \n" "\n" "Return information about the key specified by the KEYGRIP. If the\n" "key is not available GPG_ERR_NOT_FOUND is returned. If the option\n" "--list is given the keygrip is ignored and information about all\n" "available keys are returned. If --ssh-list is given information\n" "about all keys listed in the sshcontrol are returned. With --with-ssh\n" "information from sshcontrol is always added to the info. Unless --data\n" "is given, the information is returned as a status line using the format:\n" "\n" " KEYINFO \n" "\n" "KEYGRIP is the keygrip.\n" "\n" "TYPE is describes the type of the key:\n" " 'D' - Regular key stored on disk,\n" " 'T' - Key is stored on a smartcard (token),\n" " 'X' - Unknown type,\n" " '-' - Key is missing.\n" "\n" "SERIALNO is an ASCII string with the serial number of the\n" " smartcard. If the serial number is not known a single\n" " dash '-' is used instead.\n" "\n" "IDSTR is the IDSTR used to distinguish keys on a smartcard. If it\n" " is not known a dash is used instead.\n" "\n" "CACHED is 1 if the passphrase for the key was found in the key cache.\n" " If not, a '-' is used instead.\n" "\n" "PROTECTION describes the key protection type:\n" " 'P' - The key is protected with a passphrase,\n" " 'C' - The key is not protected,\n" " '-' - Unknown protection.\n" "\n" "FPR returns the formatted ssh-style fingerprint of the key. It is only\n" " printed if the option --ssh-fpr has been used. If ALGO is not given\n" " to that option the default ssh fingerprint algo is used. Without the\n" " option a '-' is printed.\n" "\n" "TTL is the TTL in seconds for that key or '-' if n/a.\n" "\n" "FLAGS is a word consisting of one-letter flags:\n" " 'D' - The key has been disabled,\n" " 'S' - The key is listed in sshcontrol (requires --with-ssh),\n" " 'c' - Use of the key needs to be confirmed,\n" " 'A' - The key is available on card,\n" " '-' - No flags given.\n" "\n" "More information may be added in the future."; static gpg_error_t do_one_keyinfo (ctrl_t ctrl, const unsigned char *grip, assuan_context_t ctx, int data, int with_ssh_fpr, int in_ssh, int ttl, int disabled, int confirm, int on_card) { gpg_error_t err; char hexgrip[40+1]; char *fpr = NULL; int keytype; unsigned char *shadow_info = NULL; unsigned char *shadow_info_type = NULL; char *serialno = NULL; char *idstr = NULL; const char *keytypestr; const char *cached; const char *protectionstr; char *pw; int missing_key = 0; char ttlbuf[20]; char flagsbuf[5]; err = agent_key_info_from_file (ctrl, grip, &keytype, &shadow_info, &shadow_info_type); if (err) { if (in_ssh && gpg_err_code (err) == GPG_ERR_NOT_FOUND) missing_key = 1; else goto leave; } /* Reformat the grip so that we use uppercase as good style. */ bin2hex (grip, 20, hexgrip); if (ttl > 0) snprintf (ttlbuf, sizeof ttlbuf, "%d", ttl); else strcpy (ttlbuf, "-"); *flagsbuf = 0; if (disabled) strcat (flagsbuf, "D"); if (in_ssh) strcat (flagsbuf, "S"); if (confirm) strcat (flagsbuf, "c"); if (on_card) strcat (flagsbuf, "A"); if (!*flagsbuf) strcpy (flagsbuf, "-"); if (missing_key) { protectionstr = "-"; keytypestr = "-"; } else { switch (keytype) { case PRIVATE_KEY_CLEAR: case PRIVATE_KEY_OPENPGP_NONE: protectionstr = "C"; keytypestr = "D"; break; case PRIVATE_KEY_PROTECTED: protectionstr = "P"; keytypestr = "D"; break; case PRIVATE_KEY_SHADOWED: protectionstr = "-"; keytypestr = "T"; break; default: protectionstr = "-"; keytypestr = "X"; break; } } /* Compute the ssh fingerprint if requested. */ if (with_ssh_fpr) { gcry_sexp_t key; if (!agent_raw_key_from_file (ctrl, grip, &key)) { ssh_get_fingerprint_string (key, with_ssh_fpr, &fpr); gcry_sexp_release (key); } } /* Here we have a little race by doing the cache check separately from the retrieval function. Given that the cache flag is only a hint, it should not really matter. */ pw = agent_get_cache (ctrl, hexgrip, CACHE_MODE_NORMAL); cached = pw ? "1" : "-"; xfree (pw); if (shadow_info) { if (strcmp (shadow_info_type, "t1-v1") == 0) { err = parse_shadow_info (shadow_info, &serialno, &idstr, NULL); if (err) goto leave; } else { log_error ("unrecognised shadow key type %s\n", shadow_info_type); err = GPG_ERR_BAD_KEY; goto leave; } } if (!data) err = agent_write_status (ctrl, "KEYINFO", hexgrip, keytypestr, serialno? serialno : "-", idstr? idstr : "-", cached, protectionstr, fpr? fpr : "-", ttlbuf, flagsbuf, NULL); else { char *string; string = xtryasprintf ("%s %s %s %s %s %s %s %s %s\n", hexgrip, keytypestr, serialno? serialno : "-", idstr? idstr : "-", cached, protectionstr, fpr? fpr : "-", ttlbuf, flagsbuf); if (!string) err = gpg_error_from_syserror (); else err = assuan_send_data (ctx, string, strlen(string)); xfree (string); } leave: xfree (fpr); xfree (shadow_info_type); xfree (shadow_info); xfree (serialno); xfree (idstr); return err; } /* Entry into the command KEYINFO. This function handles the * command option processing. For details see hlp_keyinfo above. */ static gpg_error_t cmd_keyinfo (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int err; unsigned char grip[20]; - DIR *dir = NULL; + gnupg_dir_t dir = NULL; int list_mode; int opt_data, opt_ssh_fpr, opt_with_ssh; ssh_control_file_t cf = NULL; char hexgrip[41]; int disabled, ttl, confirm, is_ssh; struct card_key_info_s *keyinfo_on_cards; struct card_key_info_s *l; int on_card; if (has_option (line, "--ssh-list")) list_mode = 2; else list_mode = has_option (line, "--list"); opt_data = has_option (line, "--data"); if (has_option_name (line, "--ssh-fpr")) { if (has_option (line, "--ssh-fpr=md5")) opt_ssh_fpr = GCRY_MD_MD5; else if (has_option (line, "--ssh-fpr=sha1")) opt_ssh_fpr = GCRY_MD_SHA1; else if (has_option (line, "--ssh-fpr=sha256")) opt_ssh_fpr = GCRY_MD_SHA256; else opt_ssh_fpr = opt.ssh_fingerprint_digest; } else opt_ssh_fpr = 0; opt_with_ssh = has_option (line, "--with-ssh"); line = skip_options (line); if (opt_with_ssh || list_mode == 2) cf = ssh_open_control_file (); /* Take the keyinfo for cards from our local cache. Actually this * cache could be a global one but then we would need to employ * reference counting. */ if (ctrl->server_local->last_card_keyinfo.ki && ctrl->server_local->last_card_keyinfo.eventno == eventcounter.card && (ctrl->server_local->last_card_keyinfo.maybe_key_change == eventcounter.maybe_key_change)) { keyinfo_on_cards = ctrl->server_local->last_card_keyinfo.ki; } else if (!agent_card_keyinfo (ctrl, NULL, 0, &keyinfo_on_cards)) { agent_card_free_keyinfo (ctrl->server_local->last_card_keyinfo.ki); ctrl->server_local->last_card_keyinfo.ki = keyinfo_on_cards; ctrl->server_local->last_card_keyinfo.eventno = eventcounter.card; ctrl->server_local->last_card_keyinfo.maybe_key_change = eventcounter.maybe_key_change; } if (list_mode == 2) { if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); if (cf) { while (!ssh_read_control_file (cf, hexgrip, &disabled, &ttl, &confirm)) { if (hex2bin (hexgrip, grip, 20) < 0 ) continue; /* Bad hex string. */ on_card = 0; for (l = keyinfo_on_cards; l; l = l->next) if (!memcmp (l->keygrip, hexgrip, 40)) on_card = 1; err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, 1, ttl, disabled, confirm, on_card); if (err) goto leave; } } err = 0; } else if (list_mode) { char *dirname; - struct dirent *dir_entry; + gnupg_dirent_t dir_entry; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); dirname = make_filename_try (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR, NULL); if (!dirname) { err = gpg_error_from_syserror (); goto leave; } - dir = opendir (dirname); + dir = gnupg_opendir (dirname); if (!dir) { err = gpg_error_from_syserror (); xfree (dirname); goto leave; } xfree (dirname); - while ( (dir_entry = readdir (dir)) ) + while ( (dir_entry = gnupg_readdir (dir)) ) { if (strlen (dir_entry->d_name) != 44 || strcmp (dir_entry->d_name + 40, ".key")) continue; strncpy (hexgrip, dir_entry->d_name, 40); hexgrip[40] = 0; if ( hex2bin (hexgrip, grip, 20) < 0 ) continue; /* Bad hex string. */ disabled = ttl = confirm = is_ssh = 0; if (opt_with_ssh) { err = ssh_search_control_file (cf, hexgrip, &disabled, &ttl, &confirm); if (!err) is_ssh = 1; else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND) goto leave; } on_card = 0; for (l = keyinfo_on_cards; l; l = l->next) if (!memcmp (l->keygrip, hexgrip, 40)) on_card = 1; err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh, ttl, disabled, confirm, on_card); if (err) goto leave; } err = 0; } else { err = parse_keygrip (ctx, line, grip); if (err) goto leave; disabled = ttl = confirm = is_ssh = 0; if (opt_with_ssh) { err = ssh_search_control_file (cf, line, &disabled, &ttl, &confirm); if (!err) is_ssh = 1; else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND) goto leave; } on_card = 0; for (l = keyinfo_on_cards; l; l = l->next) if (!memcmp (l->keygrip, line, 40)) on_card = 1; err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh, ttl, disabled, confirm, on_card); } leave: ssh_close_control_file (cf); - if (dir) - closedir (dir); + gnupg_closedir (dir); if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND) leave_cmd (ctx, err); return err; } /* Helper for cmd_get_passphrase. */ static int send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw) { size_t n; int rc; assuan_begin_confidential (ctx); n = strlen (pw); if (via_data) rc = assuan_send_data (ctx, pw, n); else { char *p = xtrymalloc_secure (n*2+1); if (!p) rc = gpg_error_from_syserror (); else { bin2hex (pw, n, p); rc = assuan_set_okay_line (ctx, p); xfree (p); } } return rc; } /* Callback function to compare the first entered PIN with the one currently being entered. */ static gpg_error_t reenter_passphrase_cmp_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); } static const char hlp_get_passphrase[] = "GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]]\n" " [--qualitybar] [--newsymkey] \n" " [ ]\n" "\n" "This function is usually used to ask for a passphrase to be used\n" "for conventional encryption, but may also be used by programs which\n" "need specal handling of passphrases. This command uses a syntax\n" "which helps clients to use the agent with minimum effort. The\n" "agent either returns with an error or with a OK followed by the hex\n" "encoded passphrase. Note that the length of the strings is\n" "implicitly limited by the maximum length of a command.\n" "\n" "If the option \"--data\" is used the passphrase is returned by usual\n" "data lines and not on the okay line.\n" "\n" "If the option \"--check\" is used the passphrase constraints checks as\n" "implemented by gpg-agent are applied. A check is not done if the\n" "passphrase has been found in the cache.\n" "\n" "If the option \"--no-ask\" is used and the passphrase is not in the\n" "cache the user will not be asked to enter a passphrase but the error\n" "code GPG_ERR_NO_DATA is returned. \n" "\n" "If the option\"--newsymkey\" is used the agent asks for a new passphrase\n" "to be used in symmetric-only encryption. This must not be empty.\n" "\n" "If the option \"--qualitybar\" is used a visual indication of the\n" "entered passphrase quality is shown. (Unless no minimum passphrase\n" "length has been configured.)"; static gpg_error_t cmd_get_passphrase (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; char *pw; char *response = NULL; char *response2 = NULL; char *cacheid = NULL; /* May point into LINE. */ char *desc = NULL; /* Ditto */ char *prompt = NULL; /* Ditto */ char *errtext = NULL; /* Ditto */ const char *desc2 = _("Please re-enter this passphrase"); char *p; int opt_data, opt_check, opt_no_ask, opt_qualbar, opt_newsymkey; int opt_repeat = 0; char *entry_errtext = NULL; struct pin_entry_info_s *pi = NULL; struct pin_entry_info_s *pi2 = NULL; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); opt_data = has_option (line, "--data"); opt_check = has_option (line, "--check"); opt_no_ask = has_option (line, "--no-ask"); if (has_option_name (line, "--repeat")) { p = option_value (line, "--repeat"); if (p) opt_repeat = atoi (p); else opt_repeat = 1; } opt_qualbar = has_option (line, "--qualitybar"); opt_newsymkey = has_option (line, "--newsymkey"); line = skip_options (line); cacheid = line; p = strchr (cacheid, ' '); if (p) { *p++ = 0; while (*p == ' ') p++; errtext = p; p = strchr (errtext, ' '); if (p) { *p++ = 0; while (*p == ' ') p++; prompt = p; p = strchr (prompt, ' '); if (p) { *p++ = 0; while (*p == ' ') p++; desc = p; p = strchr (desc, ' '); if (p) *p = 0; /* Ignore trailing garbage. */ } } } if (!*cacheid || strlen (cacheid) > 50) return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID"); if (!desc) return set_error (GPG_ERR_ASS_PARAMETER, "no description given"); if (!strcmp (cacheid, "X")) cacheid = NULL; if (!strcmp (errtext, "X")) errtext = NULL; if (!strcmp (prompt, "X")) prompt = NULL; if (!strcmp (desc, "X")) desc = NULL; pw = cacheid ? agent_get_cache (ctrl, cacheid, CACHE_MODE_USER) : NULL; if (pw) { rc = send_back_passphrase (ctx, opt_data, pw); xfree (pw); goto leave; } else if (opt_no_ask) { rc = gpg_error (GPG_ERR_NO_DATA); goto leave; } /* Note, that we only need to replace the + characters and should * leave the other escaping in place because the escaped string is * send verbatim to the pinentry which does the unescaping (but not * the + replacing) */ if (errtext) plus_to_blank (errtext); if (prompt) plus_to_blank (prompt); if (desc) plus_to_blank (desc); /* If opt_repeat is 2 or higher we can't use our pin_entry_info_s * based method but fallback to the old simple method. It is * anyway questionable whether this extra repeat count makes any * real sense. */ if (opt_newsymkey && opt_repeat < 2) { /* We do not want to break any existing usage of this command * and thus we introduced the option --newsymkey to make this * command more useful to query the passphrase for symmetric * encryption. */ pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1); if (!pi) { rc = gpg_error_from_syserror (); goto leave; } pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1); if (!pi2) { rc = gpg_error_from_syserror (); goto leave; } pi->max_length = MAX_PASSPHRASE_LEN + 1; pi->max_tries = 3; pi->with_qualitybar = opt_qualbar; pi->with_repeat = opt_repeat; pi2->max_length = MAX_PASSPHRASE_LEN + 1; pi2->max_tries = 3; pi2->check_cb = reenter_passphrase_cmp_cb; pi2->check_cb_arg = pi->pin; for (;;) /* (degenerated for-loop) */ { xfree (response); response = NULL; rc = agent_get_passphrase (ctrl, &response, desc, prompt, entry_errtext? entry_errtext:errtext, opt_qualbar, cacheid, CACHE_MODE_USER, pi); if (rc) goto leave; xfree (entry_errtext); entry_errtext = NULL; /* We don't allow an empty passpharse in this mode. */ if (check_passphrase_constraints (ctrl, pi->pin, 1, &entry_errtext)) { pi->failed_tries = 0; pi2->failed_tries = 0; continue; } if (*pi->pin && !pi->repeat_okay && ctrl->pinentry_mode != PINENTRY_MODE_LOOPBACK && opt_repeat) { /* The passphrase is empty and the pinentry did not * already run the repetition check, do it here. This * is only called when using an old and simple pinentry. * It is neither called in loopback mode because the * caller does any passphrase repetition by herself nor if * no repetition was requested. */ xfree (response); response = NULL; rc = agent_get_passphrase (ctrl, &response, L_("Please re-enter this passphrase"), prompt, entry_errtext? entry_errtext:errtext, opt_qualbar, cacheid, CACHE_MODE_USER, pi2); if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE) { /* The re-entered passphrase one did not match and * the user did not hit cancel. */ entry_errtext = xtrystrdup (L_("does not match - try again")); if (!entry_errtext) { rc = gpg_error_from_syserror (); goto leave; } continue; } } break; } if (!rc && *pi->pin) { /* Return the passphrase. */ if (cacheid) agent_put_cache (ctrl, cacheid, CACHE_MODE_USER, pi->pin, 0); rc = send_back_passphrase (ctx, opt_data, pi->pin); } } else { next_try: xfree (response); response = NULL; rc = agent_get_passphrase (ctrl, &response, desc, prompt, entry_errtext? entry_errtext:errtext, opt_qualbar, cacheid, CACHE_MODE_USER, NULL); xfree (entry_errtext); entry_errtext = NULL; if (!rc) { int i; if (opt_check && check_passphrase_constraints (ctrl, response,0,&entry_errtext)) { goto next_try; } for (i = 0; i < opt_repeat; i++) { if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK) break; xfree (response2); response2 = NULL; rc = agent_get_passphrase (ctrl, &response2, desc2, prompt, errtext, 0, cacheid, CACHE_MODE_USER, NULL); if (rc) break; if (strcmp (response2, response)) { entry_errtext = try_percent_escape (_("does not match - try again"), NULL); if (!entry_errtext) { rc = gpg_error_from_syserror (); break; } goto next_try; } } if (!rc) { if (cacheid) agent_put_cache (ctrl, cacheid, CACHE_MODE_USER, response, 0); rc = send_back_passphrase (ctx, opt_data, response); } } } leave: xfree (response); xfree (response2); xfree (entry_errtext); xfree (pi2); xfree (pi); return leave_cmd (ctx, rc); } static const char hlp_clear_passphrase[] = "CLEAR_PASSPHRASE [--mode=normal] \n" "\n" "may be used to invalidate the cache entry for a passphrase. The\n" "function returns with OK even when there is no cached passphrase.\n" "The --mode=normal option is used to clear an entry for a cacheid\n" "added by the agent. The --mode=ssh option is used for a cacheid\n" "added for ssh.\n"; static gpg_error_t cmd_clear_passphrase (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); char *cacheid = NULL; char *p; cache_mode_t cache_mode = CACHE_MODE_USER; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); if (has_option (line, "--mode=normal")) cache_mode = CACHE_MODE_NORMAL; else if (has_option (line, "--mode=ssh")) cache_mode = CACHE_MODE_SSH; line = skip_options (line); /* parse the stuff */ for (p=line; *p == ' '; p++) ; cacheid = p; p = strchr (cacheid, ' '); if (p) *p = 0; /* ignore garbage */ if (!*cacheid || strlen (cacheid) > 50) return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID"); agent_put_cache (ctrl, cacheid, cache_mode, NULL, 0); agent_clear_passphrase (ctrl, cacheid, cache_mode); return 0; } static const char hlp_get_confirmation[] = "GET_CONFIRMATION \n" "\n" "This command may be used to ask for a simple confirmation.\n" "DESCRIPTION is displayed along with a Okay and Cancel button. This\n" "command uses a syntax which helps clients to use the agent with\n" "minimum effort. The agent either returns with an error or with a\n" "OK. Note, that the length of DESCRIPTION is implicitly limited by\n" "the maximum length of a command. DESCRIPTION should not contain\n" "any spaces, those must be encoded either percent escaped or simply\n" "as '+'."; static gpg_error_t cmd_get_confirmation (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; char *desc = NULL; char *p; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); /* parse the stuff */ for (p=line; *p == ' '; p++) ; desc = p; p = strchr (desc, ' '); if (p) *p = 0; /* We ignore any garbage -may be later used for other args. */ if (!*desc) return set_error (GPG_ERR_ASS_PARAMETER, "no description given"); if (!strcmp (desc, "X")) desc = NULL; /* Note, that we only need to replace the + characters and should leave the other escaping in place because the escaped string is send verbatim to the pinentry which does the unescaping (but not the + replacing) */ if (desc) plus_to_blank (desc); rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0); return leave_cmd (ctx, rc); } static const char hlp_learn[] = "LEARN [--send] [--sendinfo] [--force]\n" "\n" "Learn something about the currently inserted smartcard. With\n" "--sendinfo information about the card is returned; with --send\n" "the available certificates are returned as D lines; with --force\n" "private key storage will be updated by the result."; static gpg_error_t cmd_learn (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; int send, sendinfo, force; send = has_option (line, "--send"); sendinfo = send? 1 : has_option (line, "--sendinfo"); force = has_option (line, "--force"); if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); err = agent_handle_learn (ctrl, send, sendinfo? ctx : NULL, force); return leave_cmd (ctx, err); } static const char hlp_passwd[] = "PASSWD [--cache-nonce=] [--passwd-nonce=] [--preset]\n" " [--verify] \n" "\n" "Change the passphrase/PIN for the key identified by keygrip in LINE. If\n" "--preset is used then the new passphrase will be added to the cache.\n" "If --verify is used the command asks for the passphrase and verifies\n" "that the passphrase valid.\n"; static gpg_error_t cmd_passwd (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; int c; char *cache_nonce = NULL; char *passwd_nonce = NULL; unsigned char grip[20]; gcry_sexp_t s_skey = NULL; unsigned char *shadow_info = NULL; char *passphrase = NULL; char *pend; int opt_preset, opt_verify; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); opt_preset = has_option (line, "--preset"); cache_nonce = option_value (line, "--cache-nonce"); opt_verify = has_option (line, "--verify"); if (cache_nonce) { for (pend = cache_nonce; *pend && !spacep (pend); pend++) ; c = *pend; *pend = '\0'; cache_nonce = xtrystrdup (cache_nonce); *pend = c; if (!cache_nonce) { err = gpg_error_from_syserror (); goto leave; } } passwd_nonce = option_value (line, "--passwd-nonce"); if (passwd_nonce) { for (pend = passwd_nonce; *pend && !spacep (pend); pend++) ; c = *pend; *pend = '\0'; passwd_nonce = xtrystrdup (passwd_nonce); *pend = c; if (!passwd_nonce) { err = gpg_error_from_syserror (); goto leave; } } line = skip_options (line); err = parse_keygrip (ctx, line, grip); if (err) goto leave; ctrl->in_passwd++; err = agent_key_from_file (ctrl, opt_verify? NULL : cache_nonce, ctrl->server_local->keydesc, grip, &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey, &passphrase); if (err) ; else if (shadow_info) { log_error ("changing a smartcard PIN is not yet supported\n"); err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); } else if (opt_verify) { /* All done. */ if (passphrase) { if (!passwd_nonce) { char buf[12]; gcry_create_nonce (buf, 12); passwd_nonce = bin2hex (buf, 12, NULL); } if (passwd_nonce && !agent_put_cache (ctrl, passwd_nonce, CACHE_MODE_NONCE, passphrase, CACHE_TTL_NONCE)) { assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce); xfree (ctrl->server_local->last_passwd_nonce); ctrl->server_local->last_passwd_nonce = passwd_nonce; passwd_nonce = NULL; } } } else { char *newpass = NULL; if (passwd_nonce) newpass = agent_get_cache (ctrl, passwd_nonce, CACHE_MODE_NONCE); err = agent_protect_and_store (ctrl, s_skey, &newpass); if (!err && passphrase) { /* A passphrase existed on the old key and the change was successful. Return a nonce for that old passphrase to let the caller try to unprotect the other subkeys with the same key. */ if (!cache_nonce) { char buf[12]; gcry_create_nonce (buf, 12); cache_nonce = bin2hex (buf, 12, NULL); } if (cache_nonce && !agent_put_cache (ctrl, cache_nonce, CACHE_MODE_NONCE, passphrase, CACHE_TTL_NONCE)) { assuan_write_status (ctx, "CACHE_NONCE", cache_nonce); xfree (ctrl->server_local->last_cache_nonce); ctrl->server_local->last_cache_nonce = cache_nonce; cache_nonce = NULL; } if (newpass) { /* If we have a new passphrase (which might be empty) we store it under a passwd nonce so that the caller may send that nonce again to use it for another key. */ if (!passwd_nonce) { char buf[12]; gcry_create_nonce (buf, 12); passwd_nonce = bin2hex (buf, 12, NULL); } if (passwd_nonce && !agent_put_cache (ctrl, passwd_nonce, CACHE_MODE_NONCE, newpass, CACHE_TTL_NONCE)) { assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce); xfree (ctrl->server_local->last_passwd_nonce); ctrl->server_local->last_passwd_nonce = passwd_nonce; passwd_nonce = NULL; } } } if (!err && opt_preset) { char hexgrip[40+1]; bin2hex(grip, 20, hexgrip); err = agent_put_cache (ctrl, hexgrip, CACHE_MODE_ANY, newpass, ctrl->cache_ttl_opt_preset); } xfree (newpass); } ctrl->in_passwd--; xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; leave: xfree (passphrase); gcry_sexp_release (s_skey); xfree (shadow_info); xfree (cache_nonce); xfree (passwd_nonce); return leave_cmd (ctx, err); } static const char hlp_preset_passphrase[] = "PRESET_PASSPHRASE [--inquire] []\n" "\n" "Set the cached passphrase/PIN for the key identified by the keygrip\n" "to passwd for the given time, where -1 means infinite and 0 means\n" "the default (currently only a timeout of -1 is allowed, which means\n" "to never expire it). If passwd is not provided, ask for it via the\n" "pinentry module unless --inquire is passed in which case the passphrase\n" "is retrieved from the client via a server inquire.\n"; static gpg_error_t cmd_preset_passphrase (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc; char *grip_clear = NULL; unsigned char *passphrase = NULL; int ttl; size_t len; int opt_inquire; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); if (!opt.allow_preset_passphrase) return set_error (GPG_ERR_NOT_SUPPORTED, "no --allow-preset-passphrase"); opt_inquire = has_option (line, "--inquire"); line = skip_options (line); grip_clear = line; while (*line && (*line != ' ' && *line != '\t')) line++; if (!*line) return gpg_error (GPG_ERR_MISSING_VALUE); *line = '\0'; line++; while (*line && (*line == ' ' || *line == '\t')) line++; /* Currently, only infinite timeouts are allowed. */ ttl = -1; if (line[0] != '-' || line[1] != '1') return gpg_error (GPG_ERR_NOT_IMPLEMENTED); line++; line++; while (!(*line != ' ' && *line != '\t')) line++; /* Syntax check the hexstring. */ len = 0; rc = parse_hexstring (ctx, line, &len); if (rc) return rc; line[len] = '\0'; /* If there is a passphrase, use it. Currently, a passphrase is required. */ if (*line) { if (opt_inquire) { rc = set_error (GPG_ERR_ASS_PARAMETER, "both --inquire and passphrase specified"); goto leave; } /* Do in-place conversion. */ passphrase = line; if (!hex2str (passphrase, passphrase, strlen (passphrase)+1, NULL)) rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring"); } else if (opt_inquire) { /* Note that the passphrase will be truncated at any null byte and the * limit is 480 characters. */ size_t maxlen = 480; rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen); if (!rc) rc = assuan_inquire (ctx, "PASSPHRASE", &passphrase, &len, maxlen); } else rc = set_error (GPG_ERR_NOT_IMPLEMENTED, "passphrase is required"); if (!rc) { rc = agent_put_cache (ctrl, grip_clear, CACHE_MODE_ANY, passphrase, ttl); if (opt_inquire) xfree (passphrase); } leave: return leave_cmd (ctx, rc); } static const char hlp_scd[] = "SCD \n" " \n" "This is a general quote command to redirect everything to the\n" "SCdaemon."; static gpg_error_t cmd_scd (assuan_context_t ctx, char *line) { int rc; #ifdef BUILD_WITH_SCDAEMON ctrl_t ctrl = assuan_get_pointer (ctx); if (ctrl->restricted) { const char *argv[5]; int argc; char *l; l = xtrystrdup (line); if (!l) return gpg_error_from_syserror (); argc = split_fields (l, argv, DIM (argv)); /* These commands are allowed. */ if ((argc == 1 && !strcmp (argv[0], "SERIALNO")) || (argc == 2 && !strcmp (argv[0], "GETINFO") && !strcmp (argv[1], "version")) || (argc == 2 && !strcmp (argv[0], "GETATTR") && !strcmp (argv[1], "KEY-FPR")) || (argc == 2 && !strcmp (argv[0], "KEYINFO") && !strcmp (argv[1], "--list=encr"))) xfree (l); else { xfree (l); return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); } } /* All SCD prefixed commands may change a key. */ eventcounter.maybe_key_change++; rc = divert_generic_cmd (ctrl, line, ctx); #else (void)ctx; (void)line; rc = gpg_error (GPG_ERR_NOT_SUPPORTED); #endif return rc; } static const char hlp_keywrap_key[] = "KEYWRAP_KEY [--clear] \n" "\n" "Return a key to wrap another key. For now the key is returned\n" "verbatim and thus makes not much sense because an eavesdropper on\n" "the gpg-agent connection will see the key as well as the wrapped key.\n" "However, this function may either be equipped with a public key\n" "mechanism or not used at all if the key is a pre-shared key. In any\n" "case wrapping the import and export of keys is a requirement for\n" "certain cryptographic validations and thus useful. The key persists\n" "until a RESET command but may be cleared using the option --clear.\n" "\n" "Supported modes are:\n" " --import - Return a key to import a key into gpg-agent\n" " --export - Return a key to export a key from gpg-agent"; static gpg_error_t cmd_keywrap_key (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int clearopt = has_option (line, "--clear"); if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); assuan_begin_confidential (ctx); if (has_option (line, "--import")) { xfree (ctrl->server_local->import_key); if (clearopt) ctrl->server_local->import_key = NULL; else if (!(ctrl->server_local->import_key = gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM))) err = gpg_error_from_syserror (); else err = assuan_send_data (ctx, ctrl->server_local->import_key, KEYWRAP_KEYSIZE); } else if (has_option (line, "--export")) { xfree (ctrl->server_local->export_key); if (clearopt) ctrl->server_local->export_key = NULL; else if (!(ctrl->server_local->export_key = gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM))) err = gpg_error_from_syserror (); else err = assuan_send_data (ctx, ctrl->server_local->export_key, KEYWRAP_KEYSIZE); } else err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for MODE"); assuan_end_confidential (ctx); return leave_cmd (ctx, err); } static const char hlp_import_key[] = "IMPORT_KEY [--unattended] [--force] [--timestamp=]\n" " []\n" "\n" "Import a secret key into the key store. The key is expected to be\n" "encrypted using the current session's key wrapping key (cf. command\n" "KEYWRAP_KEY) using the AESWRAP-128 algorithm. This function takes\n" "no arguments but uses the inquiry \"KEYDATA\" to ask for the actual\n" "key data. The unwrapped key must be a canonical S-expression. The\n" "option --unattended tries to import the key as-is without any\n" "re-encryption. An existing key can be overwritten with --force.\n" "If --timestamp is given its value is recorded as the key's creation\n" "time; the value is expected in ISO format (e.g. \"20030316T120000\")."; static gpg_error_t cmd_import_key (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; int opt_unattended; time_t opt_timestamp; int force; unsigned char *wrappedkey = NULL; size_t wrappedkeylen; gcry_cipher_hd_t cipherhd = NULL; unsigned char *key = NULL; size_t keylen, realkeylen; char *passphrase = NULL; unsigned char *finalkey = NULL; size_t finalkeylen; unsigned char grip[20]; gcry_sexp_t openpgp_sexp = NULL; char *cache_nonce = NULL; char *p; const char *s; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); if (!ctrl->server_local->import_key) { err = gpg_error (GPG_ERR_MISSING_KEY); goto leave; } opt_unattended = has_option (line, "--unattended"); force = has_option (line, "--force"); if ((s=has_option_name (line, "--timestamp"))) { if (*s != '=') { err = set_error (GPG_ERR_ASS_PARAMETER, "missing value for option"); goto leave; } opt_timestamp = isotime2epoch (s+1); if (opt_timestamp < 1) { err = set_error (GPG_ERR_ASS_PARAMETER, "invalid time value"); goto leave; } } else opt_timestamp = 0; line = skip_options (line); for (p=line; *p && *p != ' ' && *p != '\t'; p++) ; *p = '\0'; if (*line) cache_nonce = xtrystrdup (line); eventcounter.maybe_key_change++; assuan_begin_confidential (ctx); err = assuan_inquire (ctx, "KEYDATA", &wrappedkey, &wrappedkeylen, MAXLEN_KEYDATA); assuan_end_confidential (ctx); if (err) goto leave; if (wrappedkeylen < 24) { err = gpg_error (GPG_ERR_INV_LENGTH); goto leave; } keylen = wrappedkeylen - 8; key = xtrymalloc_secure (keylen); if (!key) { err = gpg_error_from_syserror (); goto leave; } err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_AESWRAP, 0); if (err) goto leave; err = gcry_cipher_setkey (cipherhd, ctrl->server_local->import_key, KEYWRAP_KEYSIZE); if (err) goto leave; err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen); if (err) goto leave; gcry_cipher_close (cipherhd); cipherhd = NULL; xfree (wrappedkey); wrappedkey = NULL; realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err); if (!realkeylen) goto leave; /* Invalid canonical encoded S-expression. */ err = keygrip_from_canon_sexp (key, realkeylen, grip); if (err) { /* This might be due to an unsupported S-expression format. Check whether this is openpgp-private-key and trigger that import code. */ if (!gcry_sexp_sscan (&openpgp_sexp, NULL, key, realkeylen)) { const char *tag; size_t taglen; tag = gcry_sexp_nth_data (openpgp_sexp, 0, &taglen); if (tag && taglen == 19 && !memcmp (tag, "openpgp-private-key", 19)) ; else { gcry_sexp_release (openpgp_sexp); openpgp_sexp = NULL; } } if (!openpgp_sexp) goto leave; /* Note that ERR is still set. */ } if (openpgp_sexp) { /* In most cases the key is encrypted and thus the conversion function from the OpenPGP format to our internal format will ask for a passphrase. That passphrase will be returned and used to protect the key using the same code as for regular key import. */ xfree (key); key = NULL; err = convert_from_openpgp (ctrl, openpgp_sexp, force, grip, ctrl->server_local->keydesc, cache_nonce, &key, opt_unattended? NULL : &passphrase); if (err) goto leave; realkeylen = gcry_sexp_canon_len (key, 0, NULL, &err); if (!realkeylen) goto leave; /* Invalid canonical encoded S-expression. */ if (passphrase) { log_assert (!opt_unattended); if (!cache_nonce) { char buf[12]; gcry_create_nonce (buf, 12); cache_nonce = bin2hex (buf, 12, NULL); } if (cache_nonce && !agent_put_cache (ctrl, cache_nonce, CACHE_MODE_NONCE, passphrase, CACHE_TTL_NONCE)) assuan_write_status (ctx, "CACHE_NONCE", cache_nonce); } } else if (opt_unattended) { err = set_error (GPG_ERR_ASS_PARAMETER, "\"--unattended\" may only be used with OpenPGP keys"); goto leave; } else { if (!force && !agent_key_available (grip)) err = gpg_error (GPG_ERR_EEXIST); else { char *prompt = xtryasprintf (_("Please enter the passphrase to protect the " "imported object within the %s system."), GNUPG_NAME); if (!prompt) err = gpg_error_from_syserror (); else err = agent_ask_new_passphrase (ctrl, prompt, &passphrase); xfree (prompt); } if (err) goto leave; } if (passphrase) { err = agent_protect (key, passphrase, &finalkey, &finalkeylen, ctrl->s2k_count, -1); if (!err) err = agent_write_private_key (grip, finalkey, finalkeylen, force, NULL, NULL, opt_timestamp); } else err = agent_write_private_key (grip, key, realkeylen, force, NULL, NULL, opt_timestamp); leave: gcry_sexp_release (openpgp_sexp); xfree (finalkey); xfree (passphrase); xfree (key); gcry_cipher_close (cipherhd); xfree (wrappedkey); xfree (cache_nonce); xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; return leave_cmd (ctx, err); } static const char hlp_export_key[] = "EXPORT_KEY [--cache-nonce=] [--openpgp] \n" "\n" "Export a secret key from the key store. The key will be encrypted\n" "using the current session's key wrapping key (cf. command KEYWRAP_KEY)\n" "using the AESWRAP-128 algorithm. The caller needs to retrieve that key\n" "prior to using this command. The function takes the keygrip as argument.\n" "\n" "If --openpgp is used, the secret key material will be exported in RFC 4880\n" "compatible passphrase-protected form. Without --openpgp, the secret key\n" "material will be exported in the clear (after prompting the user to unlock\n" "it, if needed).\n"; static gpg_error_t cmd_export_key (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char grip[20]; gcry_sexp_t s_skey = NULL; unsigned char *key = NULL; size_t keylen; gcry_cipher_hd_t cipherhd = NULL; unsigned char *wrappedkey = NULL; size_t wrappedkeylen; int openpgp; char *cache_nonce; char *passphrase = NULL; unsigned char *shadow_info = NULL; char *pend; int c; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); openpgp = has_option (line, "--openpgp"); cache_nonce = option_value (line, "--cache-nonce"); if (cache_nonce) { for (pend = cache_nonce; *pend && !spacep (pend); pend++) ; c = *pend; *pend = '\0'; cache_nonce = xtrystrdup (cache_nonce); *pend = c; if (!cache_nonce) { err = gpg_error_from_syserror (); goto leave; } } line = skip_options (line); if (!ctrl->server_local->export_key) { err = set_error (GPG_ERR_MISSING_KEY, "did you run KEYWRAP_KEY ?"); goto leave; } err = parse_keygrip (ctx, line, grip); if (err) goto leave; if (agent_key_available (grip)) { err = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } /* Get the key from the file. With the openpgp flag we also ask for the passphrase so that we can use it to re-encrypt it. */ err = agent_key_from_file (ctrl, cache_nonce, ctrl->server_local->keydesc, grip, &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey, openpgp ? &passphrase : NULL); if (err) goto leave; if (shadow_info) { /* Key is on a smartcard. */ err = gpg_error (GPG_ERR_UNUSABLE_SECKEY); goto leave; } if (openpgp) { /* The openpgp option changes the key format into the OpenPGP key transfer format. The result is already a padded canonical S-expression. */ if (!passphrase) { err = agent_ask_new_passphrase (ctrl, _("This key (or subkey) is not protected with a passphrase." " Please enter a new passphrase to export it."), &passphrase); if (err) goto leave; } err = convert_to_openpgp (ctrl, s_skey, passphrase, &key, &keylen); if (!err && passphrase) { if (!cache_nonce) { char buf[12]; gcry_create_nonce (buf, 12); cache_nonce = bin2hex (buf, 12, NULL); } if (cache_nonce && !agent_put_cache (ctrl, cache_nonce, CACHE_MODE_NONCE, passphrase, CACHE_TTL_NONCE)) { assuan_write_status (ctx, "CACHE_NONCE", cache_nonce); xfree (ctrl->server_local->last_cache_nonce); ctrl->server_local->last_cache_nonce = cache_nonce; cache_nonce = NULL; } } } else { /* Convert into a canonical S-expression and wrap that. */ err = make_canon_sexp_pad (s_skey, 1, &key, &keylen); } if (err) goto leave; gcry_sexp_release (s_skey); s_skey = NULL; err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_AESWRAP, 0); if (err) goto leave; err = gcry_cipher_setkey (cipherhd, ctrl->server_local->export_key, KEYWRAP_KEYSIZE); if (err) goto leave; wrappedkeylen = keylen + 8; wrappedkey = xtrymalloc (wrappedkeylen); if (!wrappedkey) { err = gpg_error_from_syserror (); goto leave; } err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen); if (err) goto leave; xfree (key); key = NULL; gcry_cipher_close (cipherhd); cipherhd = NULL; assuan_begin_confidential (ctx); err = assuan_send_data (ctx, wrappedkey, wrappedkeylen); assuan_end_confidential (ctx); leave: xfree (cache_nonce); xfree (passphrase); xfree (wrappedkey); gcry_cipher_close (cipherhd); xfree (key); gcry_sexp_release (s_skey); xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; xfree (shadow_info); return leave_cmd (ctx, err); } static const char hlp_delete_key[] = "DELETE_KEY [--force|--stub-only] \n" "\n" "Delete a secret key from the key store. If --force is used\n" "and a loopback pinentry is allowed, the agent will not ask\n" "the user for confirmation. If --stub-only is used the key will\n" "only be deleted if it is a reference to a token."; static gpg_error_t cmd_delete_key (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; int force, stub_only; unsigned char grip[20]; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); force = has_option (line, "--force"); stub_only = has_option (line, "--stub-only"); line = skip_options (line); eventcounter.maybe_key_change++; /* If the use of a loopback pinentry has been disabled, we assume * that a silent deletion of keys shall also not be allowed. */ if (!opt.allow_loopback_pinentry) force = 0; err = parse_keygrip (ctx, line, grip); if (err) goto leave; err = agent_delete_key (ctrl, ctrl->server_local->keydesc, grip, force, stub_only); if (err) goto leave; leave: xfree (ctrl->server_local->keydesc); ctrl->server_local->keydesc = NULL; return leave_cmd (ctx, err); } #if SIZEOF_TIME_T > SIZEOF_UNSIGNED_LONG #define KEYTOCARD_TIMESTAMP_FORMAT "(10:created-at10:%010llu))" #else #define KEYTOCARD_TIMESTAMP_FORMAT "(10:created-at10:%010lu))" #endif static const char hlp_keytocard[] = "KEYTOCARD [--force] []\n" "\n" "TIMESTAMP is required for OpenPGP and defaults to the Epoch. The\n" "SERIALNO is used for checking; use \"-\" to disable the check."; static gpg_error_t cmd_keytocard (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int force; gpg_error_t err = 0; const char *argv[5]; int argc; unsigned char grip[20]; const char *serialno, *timestamp_str, *keyref; gcry_sexp_t s_skey = NULL; unsigned char *keydata; size_t keydatalen; unsigned char *shadow_info = NULL; time_t timestamp; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); force = has_option (line, "--force"); line = skip_options (line); argc = split_fields (line, argv, DIM (argv)); if (argc < 3) { err = gpg_error (GPG_ERR_MISSING_VALUE); goto leave; } err = parse_keygrip (ctx, argv[0], grip); if (err) goto leave; if (agent_key_available (grip)) { err =gpg_error (GPG_ERR_NO_SECKEY); goto leave; } /* Note that checking of the s/n is currently not implemented but we * want to provide a clean interface if we ever implement it. */ serialno = argv[1]; if (!strcmp (serialno, "-")) serialno = NULL; keyref = argv[2]; /* FIXME: Default to the creation time as stored in the private * key. The parameter is here so that gpg can make sure that the * timestamp as used for key creation (and thus the openPGP * fingerprint) is used. */ timestamp_str = argc > 3? argv[3] : "19700101T000000"; if ((timestamp = isotime2epoch (timestamp_str)) == (time_t)(-1)) { err = gpg_error (GPG_ERR_INV_TIME); goto leave; } err = agent_key_from_file (ctrl, NULL, ctrl->server_local->keydesc, grip, &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey, NULL); if (err) goto leave; if (shadow_info) { /* Key is already on a smartcard - we can't extract it. */ err = gpg_error (GPG_ERR_UNUSABLE_SECKEY); goto leave; } /* Note: We can't use make_canon_sexp because we need to allocate a * few extra bytes for our hack below. */ keydatalen = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0); keydata = xtrymalloc_secure (keydatalen + 30); if (keydata == NULL) { err = gpg_error_from_syserror (); goto leave; } gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, keydata, keydatalen); gcry_sexp_release (s_skey); s_skey = NULL; keydatalen--; /* Decrement for last '\0'. */ /* Hack to insert the timestamp "created-at" into the private key. */ snprintf (keydata+keydatalen-1, 30, KEYTOCARD_TIMESTAMP_FORMAT, timestamp); keydatalen += 10 + 19 - 1; err = divert_writekey (ctrl, force, serialno, keyref, keydata, keydatalen); xfree (keydata); leave: gcry_sexp_release (s_skey); xfree (shadow_info); return leave_cmd (ctx, err); } static const char hlp_get_secret[] = "GET_SECRET \n" "\n" "Return the secret value stored under KEY\n"; static gpg_error_t cmd_get_secret (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; char *p, *key; char *value = NULL; size_t valuelen; /* For now we allow this only for local connections. */ if (ctrl->restricted) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } line = skip_options (line); for (p=line; *p == ' '; p++) ; key = p; p = strchr (key, ' '); if (p) { *p++ = 0; for (; *p == ' '; p++) ; if (*p) { err = set_error (GPG_ERR_ASS_PARAMETER, "too many arguments"); goto leave; } } if (!*key) { err = set_error (GPG_ERR_ASS_PARAMETER, "no key given"); goto leave; } value = agent_get_cache (ctrl, key, CACHE_MODE_DATA); if (!value) { err = gpg_error (GPG_ERR_NO_DATA); goto leave; } valuelen = percent_unescape_inplace (value, 0); err = assuan_send_data (ctx, value, valuelen); wipememory (value, valuelen); leave: xfree (value); return leave_cmd (ctx, err); } static const char hlp_put_secret[] = "PUT_SECRET [--clear] []\n" "\n" "This commands stores a secret under KEY in gpg-agent's in-memory\n" "cache. The TTL must be explicitly given by TTL and the options\n" "from the configuration file are not used. The value is either given\n" "percent-escaped as 3rd argument or if not given inquired by gpg-agent\n" "using the keyword \"SECRET\".\n" "The option --clear removes the secret from the cache." ""; static gpg_error_t cmd_put_secret (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int opt_clear; unsigned char *value = NULL; size_t valuelen = 0; size_t n; char *p, *key, *ttlstr; unsigned char *valstr; int ttl; char *string = NULL; /* For now we allow this only for local connections. */ if (ctrl->restricted) { err = gpg_error (GPG_ERR_FORBIDDEN); goto leave; } opt_clear = has_option (line, "--clear"); line = skip_options (line); for (p=line; *p == ' '; p++) ; key = p; ttlstr = NULL; valstr = NULL; p = strchr (key, ' '); if (p) { *p++ = 0; for (; *p == ' '; p++) ; if (*p) { ttlstr = p; p = strchr (ttlstr, ' '); if (p) { *p++ = 0; for (; *p == ' '; p++) ; if (*p) valstr = p; } } } if (!*key) { err = set_error (GPG_ERR_ASS_PARAMETER, "no key given"); goto leave; } if (!ttlstr || !*ttlstr || !(n = parse_ttl (ttlstr, &ttl))) { err = set_error (GPG_ERR_ASS_PARAMETER, "no or invalid TTL given"); goto leave; } if (valstr && opt_clear) { err = set_error (GPG_ERR_ASS_PARAMETER, "value not expected with --clear"); goto leave; } if (valstr) { valuelen = percent_unescape_inplace (valstr, 0); value = NULL; } else /* Inquire the value to store */ { err = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u",MAXLEN_PUT_SECRET); if (!err) err = assuan_inquire (ctx, "SECRET", &value, &valuelen, MAXLEN_PUT_SECRET); if (err) goto leave; } /* Our cache expects strings and thus we need to turn the buffer * into a string. Instead of resorting to base64 encoding we use a * special percent escaping which only quoted the Nul and the * percent character. */ string = percent_data_escape (0, NULL, value? value : valstr, valuelen); if (!string) { err = gpg_error_from_syserror (); goto leave; } err = agent_put_cache (ctrl, key, CACHE_MODE_DATA, string, ttl); leave: if (string) { wipememory (string, strlen (string)); xfree (string); } if (value) { wipememory (value, valuelen); xfree (value); } return leave_cmd (ctx, err); } static const char hlp_getval[] = "GETVAL \n" "\n" "Return the value for KEY from the special environment as created by\n" "PUTVAL."; static gpg_error_t cmd_getval (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc = 0; char *key = NULL; char *p; struct putval_item_s *vl; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); for (p=line; *p == ' '; p++) ; key = p; p = strchr (key, ' '); if (p) { *p++ = 0; for (; *p == ' '; p++) ; if (*p) return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments"); } if (!*key) return set_error (GPG_ERR_ASS_PARAMETER, "no key given"); for (vl=putval_list; vl; vl = vl->next) if ( !strcmp (vl->d, key) ) break; if (vl) /* Got an entry. */ rc = assuan_send_data (ctx, vl->d+vl->off, vl->len); else return gpg_error (GPG_ERR_NO_DATA); return leave_cmd (ctx, rc); } static const char hlp_putval[] = "PUTVAL []\n" "\n" "The gpg-agent maintains a kind of environment which may be used to\n" "store key/value pairs in it, so that they can be retrieved later.\n" "This may be used by helper daemons to daemonize themself on\n" "invocation and register them with gpg-agent. Callers of the\n" "daemon's service may now first try connect to get the information\n" "for that service from gpg-agent through the GETVAL command and then\n" "try to connect to that daemon. Only if that fails they may start\n" "an own instance of the service daemon. \n" "\n" "KEY is an arbitrary symbol with the same syntax rules as keys\n" "for shell environment variables. PERCENT_ESCAPED_VALUE is the\n" "corresponding value; they should be similar to the values of\n" "envronment variables but gpg-agent does not enforce any\n" "restrictions. If that value is not given any value under that KEY\n" "is removed from this special environment."; static gpg_error_t cmd_putval (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc = 0; char *key = NULL; char *value = NULL; size_t valuelen = 0; char *p; struct putval_item_s *vl, *vlprev; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); for (p=line; *p == ' '; p++) ; key = p; p = strchr (key, ' '); if (p) { *p++ = 0; for (; *p == ' '; p++) ; if (*p) { value = p; p = strchr (value, ' '); if (p) *p = 0; valuelen = percent_plus_unescape_inplace (value, 0); } } if (!*key) return set_error (GPG_ERR_ASS_PARAMETER, "no key given"); for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next) if ( !strcmp (vl->d, key) ) break; if (vl) /* Delete old entry. */ { if (vlprev) vlprev->next = vl->next; else putval_list = vl->next; xfree (vl); } if (valuelen) /* Add entry. */ { vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen); if (!vl) rc = gpg_error_from_syserror (); else { vl->len = valuelen; vl->off = strlen (key) + 1; strcpy (vl->d, key); memcpy (vl->d + vl->off, value, valuelen); vl->next = putval_list; putval_list = vl; } } return leave_cmd (ctx, rc); } static const char hlp_updatestartuptty[] = "UPDATESTARTUPTTY\n" "\n" "Set startup TTY and X11 DISPLAY variables to the values of this\n" "session. This command is useful to pull future pinentries to\n" "another screen. It is only required because there is no way in the\n" "ssh-agent protocol to convey this information."; static gpg_error_t cmd_updatestartuptty (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; session_env_t se; char *lc_ctype = NULL; char *lc_messages = NULL; int iterator; const char *name; (void)line; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); se = session_env_new (); if (!se) err = gpg_error_from_syserror (); iterator = 0; while (!err && (name = session_env_list_stdenvnames (&iterator, NULL))) { const char *value = session_env_getenv (ctrl->session_env, name); if (value) err = session_env_setenv (se, name, value); } if (!err && ctrl->lc_ctype) if (!(lc_ctype = xtrystrdup (ctrl->lc_ctype))) err = gpg_error_from_syserror (); if (!err && ctrl->lc_messages) if (!(lc_messages = xtrystrdup (ctrl->lc_messages))) err = gpg_error_from_syserror (); if (err) { session_env_release (se); xfree (lc_ctype); xfree (lc_messages); } else { session_env_release (opt.startup_env); opt.startup_env = se; xfree (opt.startup_lc_ctype); opt.startup_lc_ctype = lc_ctype; xfree (opt.startup_lc_messages); opt.startup_lc_messages = lc_messages; } return err; } static const char hlp_killagent[] = "KILLAGENT\n" "\n" "Stop the agent."; static gpg_error_t cmd_killagent (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)line; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); ctrl->server_local->stopme = 1; assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1); return 0; } static const char hlp_reloadagent[] = "RELOADAGENT\n" "\n" "This command is an alternative to SIGHUP\n" "to reload the configuration."; static gpg_error_t cmd_reloadagent (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)line; if (ctrl->restricted) return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN)); agent_sighup_action (); return 0; } static const char hlp_getinfo[] = "GETINFO \n" "\n" "Multipurpose function to return a variety of information.\n" "Supported values for WHAT are:\n" "\n" " version - Return the version of the program.\n" " pid - Return the process id of the server.\n" " socket_name - Return the name of the socket.\n" " ssh_socket_name - Return the name of the ssh socket.\n" " scd_running - Return OK if the SCdaemon is already running.\n" " s2k_time - Return the time in milliseconds required for S2K.\n" " s2k_count - Return the standard S2K count.\n" " s2k_count_cal - Return the calibrated S2K count.\n" " std_env_names - List the names of the standard environment.\n" " std_session_env - List the standard session environment.\n" " std_startup_env - List the standard startup environment.\n" " getenv NAME - Return value of envvar NAME.\n" " connections - Return number of active connections.\n" " jent_active - Returns OK if Libgcrypt's JENT is active.\n" " restricted - Returns OK if the connection is in restricted mode.\n" " cmd_has_option CMD OPT\n" " - Returns OK if command CMD has option OPT.\n"; static gpg_error_t cmd_getinfo (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); int rc = 0; if (!strcmp (line, "version")) { const char *s = VERSION; rc = assuan_send_data (ctx, s, strlen (s)); } else if (!strncmp (line, "cmd_has_option", 14) && (line[14] == ' ' || line[14] == '\t' || !line[14])) { char *cmd, *cmdopt; line += 14; while (*line == ' ' || *line == '\t') line++; if (!*line) rc = gpg_error (GPG_ERR_MISSING_VALUE); else { cmd = line; while (*line && (*line != ' ' && *line != '\t')) line++; if (!*line) rc = gpg_error (GPG_ERR_MISSING_VALUE); else { *line++ = 0; while (*line == ' ' || *line == '\t') line++; if (!*line) rc = gpg_error (GPG_ERR_MISSING_VALUE); else { cmdopt = line; if (!command_has_option (cmd, cmdopt)) rc = gpg_error (GPG_ERR_FALSE); } } } } else if (!strcmp (line, "s2k_count")) { char numbuf[50]; snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_count ()); rc = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "restricted")) { rc = ctrl->restricted? 0 : gpg_error (GPG_ERR_FALSE); } else if (ctrl->restricted) { rc = gpg_error (GPG_ERR_FORBIDDEN); } /* All sub-commands below are not allowed in restricted mode. */ else if (!strcmp (line, "pid")) { char numbuf[50]; snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ()); rc = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "socket_name")) { const char *s = get_agent_socket_name (); if (s) rc = assuan_send_data (ctx, s, strlen (s)); else rc = gpg_error (GPG_ERR_NO_DATA); } else if (!strcmp (line, "ssh_socket_name")) { const char *s = get_agent_ssh_socket_name (); if (s) rc = assuan_send_data (ctx, s, strlen (s)); else rc = gpg_error (GPG_ERR_NO_DATA); } else if (!strcmp (line, "scd_running")) { rc = agent_daemon_check_running (DAEMON_SCD)? 0:gpg_error (GPG_ERR_FALSE); } else if (!strcmp (line, "std_env_names")) { int iterator; const char *name; iterator = 0; while ((name = session_env_list_stdenvnames (&iterator, NULL))) { rc = assuan_send_data (ctx, name, strlen (name)+1); if (!rc) rc = assuan_send_data (ctx, NULL, 0); if (rc) break; } } else if (!strcmp (line, "std_session_env") || !strcmp (line, "std_startup_env")) { int iterator; const char *name, *value; char *string; iterator = 0; while ((name = session_env_list_stdenvnames (&iterator, NULL))) { value = session_env_getenv_or_default (line[5] == 't'? opt.startup_env:ctrl->session_env, name, NULL); if (value) { string = xtryasprintf ("%s=%s", name, value); if (!string) rc = gpg_error_from_syserror (); else { rc = assuan_send_data (ctx, string, strlen (string)+1); if (!rc) rc = assuan_send_data (ctx, NULL, 0); } if (rc) break; } } } else if (!strncmp (line, "getenv", 6) && (line[6] == ' ' || line[6] == '\t' || !line[6])) { line += 6; while (*line == ' ' || *line == '\t') line++; if (!*line) rc = gpg_error (GPG_ERR_MISSING_VALUE); else { const char *s = getenv (line); if (!s) rc = set_error (GPG_ERR_NOT_FOUND, "No such envvar"); else rc = assuan_send_data (ctx, s, strlen (s)); } } else if (!strcmp (line, "connections")) { char numbuf[20]; snprintf (numbuf, sizeof numbuf, "%d", get_agent_active_connection_count ()); rc = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "jent_active")) { #if GCRYPT_VERSION_NUMBER >= 0x010800 char *buf; const char *fields[5]; buf = gcry_get_config (0, "rng-type"); if (buf && split_fields_colon (buf, fields, DIM (fields)) >= 5 && atoi (fields[4]) > 0) rc = 0; else rc = gpg_error (GPG_ERR_FALSE); gcry_free (buf); #else rc = gpg_error (GPG_ERR_FALSE); #endif } else if (!strcmp (line, "s2k_count_cal")) { char numbuf[50]; snprintf (numbuf, sizeof numbuf, "%lu", get_calibrated_s2k_count ()); rc = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "s2k_time")) { char numbuf[50]; snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_time ()); rc = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT"); return rc; } /* This function is called by Libassuan to parse the OPTION command. It has been registered similar to the other Assuan commands. */ static gpg_error_t option_handler (assuan_context_t ctx, const char *key, const char *value) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; if (!strcmp (key, "agent-awareness")) { /* The value is a version string telling us of which agent version the caller is aware of. */ ctrl->server_local->allow_fully_canceled = gnupg_compare_version (value, "2.1.0"); } else if (ctrl->restricted) { err = gpg_error (GPG_ERR_FORBIDDEN); } /* All options below are not allowed in restricted mode. */ else if (!strcmp (key, "putenv")) { /* Change the session's environment to be used for the Pinentry. Valid values are: Delete envvar NAME = Set envvar NAME to the empty string = Set envvar NAME to VALUE */ err = session_env_putenv (ctrl->session_env, value); } else if (!strcmp (key, "display")) { err = session_env_setenv (ctrl->session_env, "DISPLAY", value); } else if (!strcmp (key, "ttyname")) { if (!opt.keep_tty) err = session_env_setenv (ctrl->session_env, "GPG_TTY", value); } else if (!strcmp (key, "ttytype")) { if (!opt.keep_tty) err = session_env_setenv (ctrl->session_env, "TERM", value); } else if (!strcmp (key, "lc-ctype")) { if (ctrl->lc_ctype) xfree (ctrl->lc_ctype); ctrl->lc_ctype = xtrystrdup (value); if (!ctrl->lc_ctype) return out_of_core (); } else if (!strcmp (key, "lc-messages")) { if (ctrl->lc_messages) xfree (ctrl->lc_messages); ctrl->lc_messages = xtrystrdup (value); if (!ctrl->lc_messages) return out_of_core (); } else if (!strcmp (key, "xauthority")) { err = session_env_setenv (ctrl->session_env, "XAUTHORITY", value); } else if (!strcmp (key, "pinentry-user-data")) { err = session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", value); } else if (!strcmp (key, "use-cache-for-signing")) ctrl->server_local->use_cache_for_signing = *value? !!atoi (value) : 0; else if (!strcmp (key, "allow-pinentry-notify")) ctrl->server_local->allow_pinentry_notify = 1; else if (!strcmp (key, "pinentry-mode")) { int tmp = parse_pinentry_mode (value); if (tmp == -1) err = gpg_error (GPG_ERR_INV_VALUE); else if (tmp == PINENTRY_MODE_LOOPBACK && !opt.allow_loopback_pinentry) err = gpg_error (GPG_ERR_NOT_SUPPORTED); else ctrl->pinentry_mode = tmp; } else if (!strcmp (key, "cache-ttl-opt-preset")) { ctrl->cache_ttl_opt_preset = *value? atoi (value) : 0; } else if (!strcmp (key, "s2k-count")) { ctrl->s2k_count = *value? strtoul(value, NULL, 10) : 0; if (ctrl->s2k_count && ctrl->s2k_count < 65536) { ctrl->s2k_count = 0; } } else if (!strcmp (key, "pretend-request-origin")) { log_assert (!ctrl->restricted); switch (parse_request_origin (value)) { case REQUEST_ORIGIN_LOCAL: ctrl->restricted = 0; break; case REQUEST_ORIGIN_REMOTE: ctrl->restricted = 1; break; case REQUEST_ORIGIN_BROWSER: ctrl->restricted = 2; break; default: err = gpg_error (GPG_ERR_INV_VALUE); /* Better pretend to be remote in case of a bad value. */ ctrl->restricted = 1; break; } } else err = gpg_error (GPG_ERR_UNKNOWN_OPTION); return err; } /* Called by libassuan after all commands. ERR is the error from the last assuan operation and not the one returned from the command. */ static void post_cmd_notify (assuan_context_t ctx, gpg_error_t err) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)err; /* Switch off any I/O monitor controlled logging pausing. */ ctrl->server_local->pause_io_logging = 0; } /* This function is called by libassuan for all I/O. We use it here to disable logging for the GETEVENTCOUNTER commands. This is so that the debug output won't get cluttered by this primitive command. */ static unsigned int io_monitor (assuan_context_t ctx, void *hook, int direction, const char *line, size_t linelen) { ctrl_t ctrl = assuan_get_pointer (ctx); (void) hook; /* We want to suppress all Assuan log messages for connections from * self. However, assuan_get_pid works only after * assuan_accept. Now, assuan_accept already logs a line ending with * the process id. We use this hack here to get the peers pid so * that we can compare it to our pid. We should add an assuan * function to return the pid for a file descriptor and use that to * detect connections to self. */ if (ctx && !ctrl->server_local->greeting_seen && direction == ASSUAN_IO_TO_PEER) { ctrl->server_local->greeting_seen = 1; if (linelen > 32 && !strncmp (line, "OK Pleased to meet you, process ", 32) && strtoul (line+32, NULL, 10) == getpid ()) return ASSUAN_IO_MONITOR_NOLOG; } /* Do not log self-connections. This makes the log cleaner because * we won't see the check-our-own-socket calls. */ if (ctx && ctrl->server_local->connect_from_self) return ASSUAN_IO_MONITOR_NOLOG; /* Note that we only check for the uppercase name. This allows the user to see the logging for debugging if using a non-upercase command name. */ if (ctx && direction == ASSUAN_IO_FROM_PEER && linelen >= 15 && !strncmp (line, "GETEVENTCOUNTER", 15) && (linelen == 15 || spacep (line+15))) { ctrl->server_local->pause_io_logging = 1; } return ctrl->server_local->pause_io_logging? ASSUAN_IO_MONITOR_NOLOG : 0; } /* Return true if the command CMD implements the option OPT. */ static int command_has_option (const char *cmd, const char *cmdopt) { if (!strcmp (cmd, "GET_PASSPHRASE")) { if (!strcmp (cmdopt, "repeat")) return 1; if (!strcmp (cmdopt, "newsymkey")) return 1; } return 0; } /* Tell Libassuan about our commands. Also register the other Assuan handlers. */ static int register_commands (assuan_context_t ctx) { static struct { const char *name; assuan_handler_t handler; const char * const help; } table[] = { { "GETEVENTCOUNTER",cmd_geteventcounter, hlp_geteventcounter }, { "ISTRUSTED", cmd_istrusted, hlp_istrusted }, { "HAVEKEY", cmd_havekey, hlp_havekey }, { "KEYINFO", cmd_keyinfo, hlp_keyinfo }, { "SIGKEY", cmd_sigkey, hlp_sigkey }, { "SETKEY", cmd_sigkey, hlp_sigkey }, { "SETKEYDESC", cmd_setkeydesc,hlp_setkeydesc }, { "SETHASH", cmd_sethash, hlp_sethash }, { "PKSIGN", cmd_pksign, hlp_pksign }, { "PKDECRYPT", cmd_pkdecrypt, hlp_pkdecrypt }, { "GENKEY", cmd_genkey, hlp_genkey }, { "READKEY", cmd_readkey, hlp_readkey }, { "GET_PASSPHRASE", cmd_get_passphrase, hlp_get_passphrase }, { "PRESET_PASSPHRASE", cmd_preset_passphrase, hlp_preset_passphrase }, { "CLEAR_PASSPHRASE", cmd_clear_passphrase, hlp_clear_passphrase }, { "GET_CONFIRMATION", cmd_get_confirmation, hlp_get_confirmation }, { "LISTTRUSTED", cmd_listtrusted, hlp_listtrusted }, { "MARKTRUSTED", cmd_marktrusted, hlp_martrusted }, { "LEARN", cmd_learn, hlp_learn }, { "PASSWD", cmd_passwd, hlp_passwd }, { "INPUT", NULL }, { "OUTPUT", NULL }, { "SCD", cmd_scd, hlp_scd }, { "KEYWRAP_KEY", cmd_keywrap_key, hlp_keywrap_key }, { "IMPORT_KEY", cmd_import_key, hlp_import_key }, { "EXPORT_KEY", cmd_export_key, hlp_export_key }, { "DELETE_KEY", cmd_delete_key, hlp_delete_key }, { "GET_SECRET", cmd_get_secret, hlp_get_secret }, { "PUT_SECRET", cmd_put_secret, hlp_put_secret }, { "GETVAL", cmd_getval, hlp_getval }, { "PUTVAL", cmd_putval, hlp_putval }, { "UPDATESTARTUPTTY", cmd_updatestartuptty, hlp_updatestartuptty }, { "KILLAGENT", cmd_killagent, hlp_killagent }, { "RELOADAGENT", cmd_reloadagent,hlp_reloadagent }, { "GETINFO", cmd_getinfo, hlp_getinfo }, { "KEYTOCARD", cmd_keytocard, hlp_keytocard }, { NULL } }; int i, rc; for (i=0; table[i].name; i++) { rc = assuan_register_command (ctx, table[i].name, table[i].handler, table[i].help); if (rc) return rc; } assuan_register_post_cmd_notify (ctx, post_cmd_notify); assuan_register_reset_notify (ctx, reset_notify); assuan_register_option_handler (ctx, option_handler); return 0; } /* Startup the server. If LISTEN_FD and FD is given as -1, this is a simple piper server, otherwise it is a regular server. CTRL is the control structure for this connection; it has only the basic initialization. */ void start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd) { int rc; assuan_context_t ctx = NULL; if (ctrl->restricted) { if (agent_copy_startup_env (ctrl)) return; } rc = assuan_new (&ctx); if (rc) { log_error ("failed to allocate assuan context: %s\n", gpg_strerror (rc)); agent_exit (2); } if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD) { assuan_fd_t filedes[2]; filedes[0] = assuan_fdopen (0); filedes[1] = assuan_fdopen (1); rc = assuan_init_pipe_server (ctx, filedes); } else if (listen_fd != GNUPG_INVALID_FD) { rc = assuan_init_socket_server (ctx, listen_fd, 0); /* FIXME: Need to call assuan_sock_set_nonce for Windows. But this branch is currently not used. */ } else { rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED); } if (rc) { log_error ("failed to initialize the server: %s\n", gpg_strerror(rc)); agent_exit (2); } rc = register_commands (ctx); if (rc) { log_error ("failed to register commands with Assuan: %s\n", gpg_strerror(rc)); agent_exit (2); } assuan_set_pointer (ctx, ctrl); ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local); ctrl->server_local->assuan_ctx = ctx; ctrl->server_local->use_cache_for_signing = 1; ctrl->digest.data = NULL; ctrl->digest.raw_value = 0; ctrl->digest.is_pss = 0; assuan_set_io_monitor (ctx, io_monitor, NULL); agent_set_progress_cb (progress_cb, ctrl); for (;;) { assuan_peercred_t client_creds; /* Note: Points into CTX. */ pid_t pid; rc = assuan_accept (ctx); if (gpg_err_code (rc) == GPG_ERR_EOF || rc == -1) { break; } else if (rc) { log_info ("Assuan accept problem: %s\n", gpg_strerror (rc)); break; } rc = assuan_get_peercred (ctx, &client_creds); if (rc) { if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD) ; else log_info ("Assuan get_peercred failed: %s\n", gpg_strerror (rc)); pid = assuan_get_pid (ctx); ctrl->client_uid = -1; } else { #ifdef HAVE_W32_SYSTEM pid = assuan_get_pid (ctx); ctrl->client_uid = -1; #else pid = client_creds->pid; ctrl->client_uid = client_creds->uid; #endif } ctrl->client_pid = (pid == ASSUAN_INVALID_PID)? 0 : (unsigned long)pid; ctrl->server_local->connect_from_self = (pid == getpid ()); rc = assuan_process (ctx); if (rc) { log_info ("Assuan processing failed: %s\n", gpg_strerror (rc)); continue; } } /* Clear the keyinfo cache. */ agent_card_free_keyinfo (ctrl->server_local->last_card_keyinfo.ki); /* Reset the nonce caches. */ clear_nonce_cache (ctrl); /* Reset the SCD if needed. */ agent_reset_daemon (ctrl); /* Reset the pinentry (in case of popup messages). */ agent_reset_query (ctrl); /* Cleanup. */ assuan_release (ctx); xfree (ctrl->server_local->keydesc); xfree (ctrl->server_local->import_key); xfree (ctrl->server_local->export_key); if (ctrl->server_local->stopme) agent_exit (0); xfree (ctrl->server_local); ctrl->server_local = NULL; } /* Helper for the pinentry loopback mode. It merely passes the parameters on to the client. */ gpg_error_t pinentry_loopback(ctrl_t ctrl, const char *keyword, unsigned char **buffer, size_t *size, size_t max_length) { gpg_error_t rc; assuan_context_t ctx = ctrl->server_local->assuan_ctx; rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", max_length); if (rc) return rc; assuan_begin_confidential (ctx); rc = assuan_inquire (ctx, keyword, buffer, size, max_length); assuan_end_confidential (ctx); return rc; } /* Helper for the pinentry loopback mode to ask confirmation or just to show message. */ gpg_error_t pinentry_loopback_confirm (ctrl_t ctrl, const char *desc, int ask_confirmation, const char *ok, const char *notok) { gpg_error_t err = 0; assuan_context_t ctx = ctrl->server_local->assuan_ctx; if (desc) err = print_assuan_status (ctx, "SETDESC", "%s", desc); if (!err && ok) err = print_assuan_status (ctx, "SETOK", "%s", ok); if (!err && notok) err = print_assuan_status (ctx, "SETNOTOK", "%s", notok); if (!err) err = assuan_inquire (ctx, ask_confirmation ? "CONFIRM 1" : "CONFIRM 0", NULL, NULL, 0); return err; } diff --git a/common/sysutils.c b/common/sysutils.c index 9926c0e52..25de374a3 100644 --- a/common/sysutils.c +++ b/common/sysutils.c @@ -1,1575 +1,1737 @@ /* 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 #include "util.h" #include "i18n.h" #include "sysutils.h" #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) + +/* The object used with our opendir functions. We need to define our + * own so that we can properly handle Unicode on Windows. */ +struct gnupg_dir_s +{ +#ifdef HAVE_W32_SYSTEM + _WDIR *dir; /* The system's DIR pointer. */ +#else + DIR *dir; /* The system's DIR pointer. */ +#endif + struct gnupg_dirent_s dirent; /* The current dirent. */ + size_t namesize; /* If not 0 the allocated size of dirent.d_name. */ + char name[256]; /* Only used if NAMESIZE is 0. */ +}; + + /* 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 } #ifdef HAVE_W32_SYSTEM static int any8bitchar (const char *string) { if (string) for ( ; *string; string++) if ((*string & 0x80)) return 1; return 0; } #endif /*HAVE_W32_SYSTEM*/ /* 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_W32_SYSTEM int rc; wchar_t *wfname; wfname = utf8_to_wchar (fname); if (!wfname) rc = 0; else { rc = DeleteFileW (wfname); xfree (wfname); } if (!rc) return -1; /* ERRNO is automagically provided by gpg-error.h. */ return 0; #else return remove (fname); #endif } /* Helper for gnupg_rename_file. */ #ifdef HAVE_W32_SYSTEM static int w32_rename (const char *oldname, const char *newname) { if (any8bitchar (oldname) || any8bitchar (newname)) { wchar_t *woldname, *wnewname; int ret; woldname = utf8_to_wchar (oldname); if (!woldname) return -1; wnewname = utf8_to_wchar (newname); if (!wnewname) { xfree (wnewname); return -1; } ret = _wrename (woldname, wnewname); xfree (wnewname); xfree (woldname); return ret; } else return rename (oldname, newname); } #endif /*HAVE_W32_SYSTEM*/ /* 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 (w32_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 } /* A wrapper around stat to handle Unicode file names under Windows. */ #ifdef HAVE_STAT int gnupg_stat (const char *name, struct stat *statbuf) { # ifdef HAVE_W32_SYSTEM if (any8bitchar (name)) { wchar_t *wname; struct _stat32 st32; int ret; wname = utf8_to_wchar (name); if (!wname) return -1; ret = _wstat (wname, &st32); xfree (wname); if (!ret) { statbuf->st_dev = st32.st_dev; statbuf->st_ino = st32.st_ino; statbuf->st_mode = st32.st_mode; statbuf->st_nlink = st32.st_nlink; statbuf->st_uid = st32.st_uid; statbuf->st_gid = st32.st_gid; statbuf->st_rdev = st32.st_rdev; statbuf->st_size = st32.st_size; statbuf->st_atime = st32.st_atime; statbuf->st_mtime = st32.st_mtime; statbuf->st_ctime = st32.st_ctime; } return ret; } else return stat (name, statbuf); # else return stat (name, statbuf); # endif } #endif /*HAVE_STAT*/ /* A wrapper around open to handle Unicode file names under Windows. */ int gnupg_open (const char *name, int flags, unsigned int mode) { #ifdef HAVE_W32_SYSTEM if (any8bitchar (name)) { wchar_t *wname; int ret; wname = utf8_to_wchar (name); if (!wname) return -1; ret = _wopen (wname, flags, mode); xfree (wname); return ret; } else return open (name, flags, mode); #else return open (name, flags, mode); #endif } +/* A wrapper around opendir to handle Unicode file names under + * Windows. This assumes the mingw toolchain. */ +gnupg_dir_t +gnupg_opendir (const char *name) +{ +#ifdef HAVE_W32_SYSTEM + _WDIR *dir; + wchar_t *wname; +#else + DIR *dir; +#endif + gnupg_dir_t gdir; + +#ifdef HAVE_W32_SYSTEM + /* Note: See gpgtar-create for an alternative implementation which + * could be used here to avoid a mingw dependency. */ + wname = utf8_to_wchar (name); + if (!wname) + return NULL; + dir = _wopendir (wname); + xfree (wname); +#else + dir = opendir (name); +#endif + + if (!dir) + return NULL; + + gdir = xtrymalloc (sizeof *gdir); + if (!gdir) + { + int save_errno = errno; +#ifdef HAVE_W32_SYSTEM + _wclosedir (dir); +#else + closedir (dir); +#endif + gpg_err_set_errno (save_errno); + return NULL; + } + gdir->dir = dir; + gdir->namesize = 0; + gdir->dirent.d_name = gdir->name; + + return gdir; +} + + +gnupg_dirent_t +gnupg_readdir (gnupg_dir_t gdir) +{ +#ifdef HAVE_W32_SYSTEM + char *namebuffer = NULL; + struct _wdirent *de; +#else + struct dirent *de; +#endif + size_t n; + gnupg_dirent_t gde; + const char *name; + + if (!gdir) + { + gpg_err_set_errno (EINVAL); + return 0; + } + +#ifdef HAVE_W32_SYSTEM + de = _wreaddir (gdir->dir); + if (!de) + return NULL; + namebuffer = wchar_to_utf8 (de->d_name); + if (!namebuffer) + return NULL; + name = namebuffer; +#else + de = readdir (gdir->dir); + if (!de) + return NULL; + name = de->d_name; +#endif + + gde = &gdir->dirent; + n = strlen (name); + if (gdir->namesize) + { + /* Use allocated buffer. */ + if (n+1 >= gdir->namesize || !gde->d_name) + { + gdir->namesize = n + 256; + xfree (gde->d_name); + gde->d_name = xtrymalloc (gdir->namesize); + if (!gde->d_name) + return NULL; /* ERRNO is already set. */ + } + strcpy (gde->d_name, name); + } + else if (n+1 >= sizeof (gdir->name)) + { + /* Switch to allocated buffer. */ + gdir->namesize = n + 256; + gde->d_name = xtrymalloc (gdir->namesize); + if (!gde->d_name) + return NULL; /* ERRNO is already set. */ + strcpy (gde->d_name, name); + } + else + { + /* Use static buffer. */ + gde->d_name = gdir->name; + strcpy (gde->d_name, name); + } + +#ifdef HAVE_W32_SYSTEM + xfree (namebuffer); +#endif + + return gde; +} + + +int +gnupg_closedir (gnupg_dir_t gdir) +{ +#ifdef HAVE_W32_SYSTEM + _WDIR *dir; +#else + DIR *dir; +#endif + + if (!gdir) + return 0; + dir = gdir->dir; + if (gdir->namesize) + xfree (gdir->dirent.d_name); + xfree (gdir); + +#ifdef HAVE_W32_SYSTEM + return _wclosedir (dir); +#else + return closedir (dir); +#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/common/sysutils.h b/common/sysutils.h index eee4cf5b6..13e781587 100644 --- a/common/sysutils.h +++ b/common/sysutils.h @@ -1,100 +1,118 @@ /* sysutils.h - System utility functions for Gnupg * Copyright (C) 2002 Free Software Foundation, Inc. * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef GNUPG_COMMON_SYSUTILS_H #define GNUPG_COMMON_SYSUTILS_H /* Because we use system handles and not libc low level file descriptors on W32, we need to declare them as HANDLE (which actually is a plain pointer). This is required to eventually support 64 bits Windows systems. */ #ifdef HAVE_W32_SYSTEM typedef void *gnupg_fd_t; #define GNUPG_INVALID_FD ((void*)(-1)) #define INT2FD(s) ((void *)(s)) #define FD2INT(h) ((unsigned int)(h)) #else typedef int gnupg_fd_t; #define GNUPG_INVALID_FD (-1) #define INT2FD(s) (s) #define FD2INT(h) (h) #endif #ifdef HAVE_STAT # include #endif +struct gnupg_dir_s; +typedef struct gnupg_dir_s *gnupg_dir_t; +struct gnupg_dirent_s +{ + /* We don't have a d_ino because that can't be used on Windows + * anyway. D_NAME is a pointer into the gnupg_dir_s which has a + * static buffer or allocates sufficient space as needed. This is + * only valid after gnupg_readdir. */ + char *d_name; +}; +typedef struct gnupg_dirent_s *gnupg_dirent_t; + + void trap_unaligned (void); int disable_core_dumps (void); int enable_core_dumps (void); void enable_special_filenames (void); const unsigned char *get_session_marker (size_t *rlen); unsigned int get_uint_nonce (void); /*int check_permissions (const char *path,int extension,int checkonly);*/ void gnupg_sleep (unsigned int seconds); void gnupg_usleep (unsigned int usecs); int translate_sys2libc_fd (gnupg_fd_t fd, int for_write); int translate_sys2libc_fd_int (int fd, int for_write); int check_special_filename (const char *fname, int for_write, int notranslate); FILE *gnupg_tmpfile (void); void gnupg_reopen_std (const char *pgmname); void gnupg_inhibit_set_foregound_window (int yes); void gnupg_allow_set_foregound_window (pid_t pid); int gnupg_remove (const char *fname); gpg_error_t gnupg_rename_file (const char *oldname, const char *newname, int *block_signals); int gnupg_mkdir (const char *name, const char *modestr); int gnupg_chdir (const char *name); int gnupg_chmod (const char *name, const char *modestr); char *gnupg_mkdtemp (char *template); int gnupg_setenv (const char *name, const char *value, int overwrite); int gnupg_unsetenv (const char *name); char *gnupg_getcwd (void); gpg_err_code_t gnupg_access (const char *name, int mode); #ifdef HAVE_STAT int gnupg_stat (const char *name, struct stat *statbuf); #endif /*HAVE_STAT*/ int gnupg_open (const char *name, int flags, unsigned int mode); + +gnupg_dir_t gnupg_opendir (const char *name); +gnupg_dirent_t gnupg_readdir (gnupg_dir_t gdir); +int gnupg_closedir (gnupg_dir_t gdir); + gpg_error_t gnupg_chuid (const char *user, int silent); char *gnupg_get_socket_name (int fd); int gnupg_fd_valid (int fd); gpg_error_t gnupg_inotify_watch_delete_self (int *r_fd, const char *fname); gpg_error_t gnupg_inotify_watch_socket (int *r_fd, const char *socket_name); int gnupg_inotify_has_name (int fd, const char *name); #ifdef HAVE_W32_SYSTEM void *w32_get_user_sid (void); #include "../common/w32help.h" #endif /*HAVE_W32_SYSTEM*/ #endif /*GNUPG_COMMON_SYSUTILS_H*/ diff --git a/dirmngr/certcache.c b/dirmngr/certcache.c index 04da510a0..9ca6069a2 100644 --- a/dirmngr/certcache.c +++ b/dirmngr/certcache.c @@ -1,1861 +1,1861 @@ /* certcache.c - Certificate caching * Copyright (C) 2004, 2005, 2007, 2008, 2017 g10 Code GmbH * * This file is part of DirMngr. * * DirMngr 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 2 of the License, or * (at your option) any later version. * * DirMngr 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 "dirmngr.h" #include "misc.h" #include "../common/ksba-io-support.h" #include "crlfetch.h" #include "certcache.h" #define MAX_NONPERM_CACHED_CERTS 1000 /* Constants used to classify search patterns. */ enum pattern_class { PATTERN_UNKNOWN = 0, PATTERN_EMAIL, PATTERN_EMAIL_SUBSTR, PATTERN_FINGERPRINT16, PATTERN_FINGERPRINT20, PATTERN_SHORT_KEYID, PATTERN_LONG_KEYID, PATTERN_SUBJECT, PATTERN_SERIALNO, PATTERN_SERIALNO_ISSUER, PATTERN_ISSUER, PATTERN_SUBSTR }; /* A certificate cache item. This consists of a the KSBA cert object and some meta data for easier lookup. We use a hash table to keep track of all items and use the (randomly distributed) first byte of the fingerprint directly as the hash which makes it pretty easy. */ struct cert_item_s { struct cert_item_s *next; /* Next item with the same hash value. */ ksba_cert_t cert; /* The KSBA cert object or NULL is this is not a valid item. */ unsigned char fpr[20]; /* The fingerprint of this object. */ char *issuer_dn; /* The malloced issuer DN. */ ksba_sexp_t sn; /* The malloced serial number */ char *subject_dn; /* The malloced subject DN - maybe NULL. */ /* If this field is set the certificate has been taken from some * configuration and shall not be flushed from the cache. */ unsigned int permanent:1; /* If this field is set the certificate is trusted. The actual * value is a (possible) combination of CERTTRUST_CLASS values. */ unsigned int trustclasses:4; }; typedef struct cert_item_s *cert_item_t; /* The actual cert cache consisting of 256 slots for items indexed by the first byte of the fingerprint. */ static cert_item_t cert_cache[256]; /* This is the global cache_lock variable. In general locking is not needed but it would take extra efforts to make sure that no indirect use of npth functions is done, so we simply lock it always. Note: We can't use static initialization, as that is not available through w32-pth. */ static npth_rwlock_t cert_cache_lock; /* Flag to track whether the cache has been initialized. */ static int initialization_done; /* Total number of non-permanent certificates. */ static unsigned int total_nonperm_certificates; /* For each cert class the corresponding bit is set if at least one * certificate of that class is loaded permanetly. */ static unsigned int any_cert_of_class; #ifdef HAVE_W32_SYSTEM /* We load some functions dynamically. Provide typedefs for tehse * functions. */ typedef HCERTSTORE (WINAPI *CERTOPENSYSTEMSTORE) (HCRYPTPROV hProv, LPCSTR szSubsystemProtocol); typedef PCCERT_CONTEXT (WINAPI *CERTENUMCERTIFICATESINSTORE) (HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext); typedef WINBOOL (WINAPI *CERTCLOSESTORE) (HCERTSTORE hCertStore,DWORD dwFlags); #endif /*HAVE_W32_SYSTEM*/ /* Helper to do the cache locking. */ static void init_cache_lock (void) { int err; err = npth_rwlock_init (&cert_cache_lock, NULL); if (err) log_fatal (_("can't initialize certificate cache lock: %s\n"), strerror (err)); } static void acquire_cache_read_lock (void) { int err; err = npth_rwlock_rdlock (&cert_cache_lock); if (err) log_fatal (_("can't acquire read lock on the certificate cache: %s\n"), strerror (err)); } static void acquire_cache_write_lock (void) { int err; err = npth_rwlock_wrlock (&cert_cache_lock); if (err) log_fatal (_("can't acquire write lock on the certificate cache: %s\n"), strerror (err)); } static void release_cache_lock (void) { int err; err = npth_rwlock_unlock (&cert_cache_lock); if (err) log_fatal (_("can't release lock on the certificate cache: %s\n"), strerror (err)); } /* Return false if both serial numbers match. Can't be used for sorting. */ static int compare_serialno (ksba_sexp_t serial1, ksba_sexp_t serial2 ) { unsigned char *a = serial1; unsigned char *b = serial2; return cmp_simple_canon_sexp (a, b); } /* Return a malloced canonical S-Expression with the serial number * converted from the hex string HEXSN. Return NULL on memory * error. */ ksba_sexp_t hexsn_to_sexp (const char *hexsn) { char *buffer, *p; size_t len; char numbuf[40]; len = unhexify (NULL, hexsn); snprintf (numbuf, sizeof numbuf, "(%u:", (unsigned int)len); buffer = xtrymalloc (strlen (numbuf) + len + 2 ); if (!buffer) return NULL; p = stpcpy (buffer, numbuf); len = unhexify (p, hexsn); p[len] = ')'; p[len+1] = 0; return buffer; } /* Compute the fingerprint of the certificate CERT and put it into the 20 bytes large buffer DIGEST. Return address of this buffer. */ unsigned char * cert_compute_fpr (ksba_cert_t cert, unsigned char *digest) { gpg_error_t err; gcry_md_hd_t md; err = gcry_md_open (&md, GCRY_MD_SHA1, 0); if (err) log_fatal ("gcry_md_open failed: %s\n", gpg_strerror (err)); err = ksba_cert_hash (cert, 0, HASH_FNC, md); if (err) { log_error ("oops: ksba_cert_hash failed: %s\n", gpg_strerror (err)); memset (digest, 0xff, 20); /* Use a dummy value. */ } else { gcry_md_final (md); memcpy (digest, gcry_md_read (md, GCRY_MD_SHA1), 20); } gcry_md_close (md); return digest; } /* Cleanup one slot. This releases all resourses but keeps the actual slot in the cache marked for reuse. */ static void clean_cache_slot (cert_item_t ci) { ksba_cert_t cert; if (!ci->cert) return; /* Already cleaned. */ ksba_free (ci->sn); ci->sn = NULL; ksba_free (ci->issuer_dn); ci->issuer_dn = NULL; ksba_free (ci->subject_dn); ci->subject_dn = NULL; cert = ci->cert; ci->cert = NULL; ci->permanent = 0; ci->trustclasses = 0; ksba_cert_release (cert); } /* Put the certificate CERT into the cache. It is assumed that the * cache is locked while this function is called. * * FROM_CONFIG indicates that CERT is a permanent certificate and * should stay in the cache. IS_TRUSTED requests that the trusted * flag is set for the certificate; a value of 1 indicates the * cert is trusted due to GnuPG mechanisms, a value of 2 indicates * that it is trusted because it has been taken from the system's * store of trusted certificates. If FPR_BUFFER is not NULL the * fingerprint of the certificate will be stored there. FPR_BUFFER * needs to point to a buffer of at least 20 bytes. The fingerprint * will be stored on success or when the function returns * GPG_ERR_DUP_VALUE. */ static gpg_error_t put_cert (ksba_cert_t cert, int permanent, unsigned int trustclass, void *fpr_buffer) { unsigned char help_fpr_buffer[20], *fpr; cert_item_t ci; fpr = fpr_buffer? fpr_buffer : &help_fpr_buffer; /* If we already reached the caching limit, drop a couple of certs * from the cache. Our dropping strategy is simple: We keep a * static index counter and use this to start looking for * certificates, then we drop 5 percent of the oldest certificates * starting at that index. For a large cache this is a fair way of * removing items. An LRU strategy would be better of course. * Because we append new entries to the head of the list and we want * to remove old ones first, we need to do this from the tail. The * implementation is not very efficient but compared to the long * time it takes to retrieve a certificate from an external resource * it seems to be reasonable. */ if (!permanent && total_nonperm_certificates >= MAX_NONPERM_CACHED_CERTS) { static int idx; cert_item_t ci_mark; int i; unsigned int drop_count; drop_count = MAX_NONPERM_CACHED_CERTS / 20; if (drop_count < 2) drop_count = 2; log_info (_("dropping %u certificates from the cache\n"), drop_count); assert (idx < 256); for (i=idx; drop_count; i = ((i+1)%256)) { ci_mark = NULL; for (ci = cert_cache[i]; ci; ci = ci->next) if (ci->cert && !ci->permanent) ci_mark = ci; if (ci_mark) { clean_cache_slot (ci_mark); drop_count--; total_nonperm_certificates--; } } if (i==idx) idx++; else idx = i; idx %= 256; } cert_compute_fpr (cert, fpr); for (ci=cert_cache[*fpr]; ci; ci = ci->next) if (ci->cert && !memcmp (ci->fpr, fpr, 20)) return gpg_error (GPG_ERR_DUP_VALUE); /* Try to reuse an existing entry. */ for (ci=cert_cache[*fpr]; ci; ci = ci->next) if (!ci->cert) break; if (!ci) { /* No: Create a new entry. */ ci = xtrycalloc (1, sizeof *ci); if (!ci) return gpg_error_from_errno (errno); ci->next = cert_cache[*fpr]; cert_cache[*fpr] = ci; } ksba_cert_ref (cert); ci->cert = cert; memcpy (ci->fpr, fpr, 20); ci->sn = ksba_cert_get_serial (cert); ci->issuer_dn = ksba_cert_get_issuer (cert, 0); if (!ci->issuer_dn || !ci->sn) { clean_cache_slot (ci); return gpg_error (GPG_ERR_INV_CERT_OBJ); } ci->subject_dn = ksba_cert_get_subject (cert, 0); ci->permanent = !!permanent; ci->trustclasses = trustclass; if (permanent) any_cert_of_class |= trustclass; else total_nonperm_certificates++; return 0; } /* Load certificates from the directory DIRNAME. All certificates matching the pattern "*.crt" or "*.der" are loaded. We assume that certificates are DER encoded and not PEM encapsulated. The cache should be in a locked state when calling this function. */ static gpg_error_t load_certs_from_dir (const char *dirname, unsigned int trustclass) { gpg_error_t err; - DIR *dir; - struct dirent *ep; + gnupg_dir_t dir; + gnupg_dirent_t ep; char *p; size_t n; estream_t fp; ksba_reader_t reader; ksba_cert_t cert; char *fname = NULL; - dir = opendir (dirname); + dir = gnupg_opendir (dirname); if (!dir) { return 0; /* We do not consider this a severe error. */ } - while ( (ep=readdir (dir)) ) + while ( (ep = gnupg_readdir (dir)) ) { p = ep->d_name; if (*p == '.' || !*p) continue; /* Skip any hidden files and invalid entries. */ n = strlen (p); if ( n < 5 || (strcmp (p+n-4,".crt") && strcmp (p+n-4,".der"))) continue; /* Not the desired "*.crt" or "*.der" pattern. */ xfree (fname); fname = make_filename (dirname, p, NULL); fp = es_fopen (fname, "rb"); if (!fp) { log_error (_("can't open '%s': %s\n"), fname, strerror (errno)); continue; } err = create_estream_ksba_reader (&reader, fp); if (err) { es_fclose (fp); continue; } err = ksba_cert_new (&cert); if (!err) err = ksba_cert_read_der (cert, reader); ksba_reader_release (reader); es_fclose (fp); if (err) { log_error (_("can't parse certificate '%s': %s\n"), fname, gpg_strerror (err)); ksba_cert_release (cert); continue; } err = put_cert (cert, 1, trustclass, NULL); if (gpg_err_code (err) == GPG_ERR_DUP_VALUE) log_info (_("certificate '%s' already cached\n"), fname); else if (!err) { if ((trustclass & CERTTRUST_CLASS_CONFIG)) http_register_cfg_ca (fname); if (trustclass) log_info (_("trusted certificate '%s' loaded\n"), fname); else log_info (_("certificate '%s' loaded\n"), fname); if (opt.verbose) { p = get_fingerprint_hexstring_colon (cert); log_info (_(" SHA1 fingerprint = %s\n"), p); xfree (p); cert_log_name (_(" issuer ="), cert); cert_log_subject (_(" subject ="), cert); } } else log_error (_("error loading certificate '%s': %s\n"), fname, gpg_strerror (err)); ksba_cert_release (cert); } xfree (fname); - closedir (dir); + gnupg_closedir (dir); return 0; } /* Load certificates from FILE. The certificates are expected to be * PEM encoded so that it is possible to load several certificates. * TRUSTCLASSES is used to mark the certificates as trusted. The * cache should be in a locked state when calling this function. * NO_ERROR repalces an error message when FNAME was not found by an * information message. */ static gpg_error_t load_certs_from_file (const char *fname, unsigned int trustclasses, int no_error) { gpg_error_t err; estream_t fp = NULL; gnupg_ksba_io_t ioctx = NULL; ksba_reader_t reader; ksba_cert_t cert = NULL; fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENONET && no_error) log_info (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); else log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } err = gnupg_ksba_create_reader (&ioctx, (GNUPG_KSBA_IO_AUTODETECT | GNUPG_KSBA_IO_MULTIPEM), fp, &reader); if (err) { log_error ("can't create reader: %s\n", gpg_strerror (err)); goto leave; } /* Loop to read all certificates from the file. */ do { ksba_cert_release (cert); cert = NULL; err = ksba_cert_new (&cert); if (!err) err = ksba_cert_read_der (cert, reader); if (err) { if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; else log_error (_("can't parse certificate '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } err = put_cert (cert, 1, trustclasses, NULL); if (gpg_err_code (err) == GPG_ERR_DUP_VALUE) log_info (_("certificate '%s' already cached\n"), fname); else if (err) log_error (_("error loading certificate '%s': %s\n"), fname, gpg_strerror (err)); else if (opt.verbose > 1) { char *p; log_info (_("trusted certificate '%s' loaded\n"), fname); p = get_fingerprint_hexstring_colon (cert); log_info (_(" SHA1 fingerprint = %s\n"), p); xfree (p); cert_log_name (_(" issuer ="), cert); cert_log_subject (_(" subject ="), cert); } ksba_reader_clear (reader, NULL, NULL); } while (!gnupg_ksba_reader_eof_seen (ioctx)); leave: ksba_cert_release (cert); gnupg_ksba_destroy_reader (ioctx); es_fclose (fp); return err; } #ifdef HAVE_W32_SYSTEM /* Load all certificates from the Windows store named STORENAME. All * certificates are considered to be system provided trusted * certificates. The cache should be in a locked state when calling * this function. */ static void load_certs_from_w32_store (const char *storename) { static int init_done; static CERTOPENSYSTEMSTORE pCertOpenSystemStore; static CERTENUMCERTIFICATESINSTORE pCertEnumCertificatesInStore; static CERTCLOSESTORE pCertCloseStore; gpg_error_t err; HCERTSTORE w32store; const CERT_CONTEXT *w32cert; ksba_cert_t cert = NULL; unsigned int count = 0; /* Initialize on the first use. */ if (!init_done) { static HANDLE hCrypt32; init_done = 1; hCrypt32 = LoadLibrary ("Crypt32.dll"); if (!hCrypt32) { log_error ("can't load Crypt32.dll: %s\n", w32_strerror (-1)); return; } pCertOpenSystemStore = (CERTOPENSYSTEMSTORE) GetProcAddress (hCrypt32, "CertOpenSystemStoreA"); pCertEnumCertificatesInStore = (CERTENUMCERTIFICATESINSTORE) GetProcAddress (hCrypt32, "CertEnumCertificatesInStore"); pCertCloseStore = (CERTCLOSESTORE) GetProcAddress (hCrypt32, "CertCloseStore"); if ( !pCertOpenSystemStore || !pCertEnumCertificatesInStore || !pCertCloseStore) { log_error ("can't load crypt32.dll: %s\n", "missing function"); pCertOpenSystemStore = NULL; } } if (!pCertOpenSystemStore) return; /* Not initialized. */ w32store = pCertOpenSystemStore (0, storename); if (!w32store) { log_error ("can't open certificate store '%s': %s\n", storename, w32_strerror (-1)); return; } w32cert = NULL; while ((w32cert = pCertEnumCertificatesInStore (w32store, w32cert))) { if (w32cert->dwCertEncodingType == X509_ASN_ENCODING) { ksba_cert_release (cert); cert = NULL; err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, w32cert->pbCertEncoded, w32cert->cbCertEncoded); if (err) { log_error (_("can't parse certificate '%s': %s\n"), storename, gpg_strerror (err)); break; } err = put_cert (cert, 1, CERTTRUST_CLASS_SYSTEM, NULL); if (!err) count++; if (gpg_err_code (err) == GPG_ERR_DUP_VALUE) { if (DBG_X509) log_debug (_("certificate '%s' already cached\n"), storename); } else if (err) log_error (_("error loading certificate '%s': %s\n"), storename, gpg_strerror (err)); else if (opt.verbose > 1) { char *p; log_info (_("trusted certificate '%s' loaded\n"), storename); p = get_fingerprint_hexstring_colon (cert); log_info (_(" SHA1 fingerprint = %s\n"), p); xfree (p); cert_log_name (_(" issuer ="), cert); cert_log_subject (_(" subject ="), cert); } } } ksba_cert_release (cert); pCertCloseStore (w32store, 0); if (DBG_X509) log_debug ("number of certs loaded from store '%s': %u\n", storename, count); } #endif /*HAVE_W32_SYSTEM*/ /* Load the trusted certificates provided by the system. */ static gpg_error_t load_certs_from_system (void) { #ifdef HAVE_W32_SYSTEM load_certs_from_w32_store ("ROOT"); load_certs_from_w32_store ("CA"); return 0; #else /*!HAVE_W32_SYSTEM*/ /* A list of certificate bundles to try. */ static struct { const char *name; } table[] = { #ifdef DEFAULT_TRUST_STORE_FILE { DEFAULT_TRUST_STORE_FILE } #else { "/etc/ssl/ca-bundle.pem" }, { "/etc/ssl/certs/ca-certificates.crt" }, { "/etc/pki/tls/cert.pem" }, { "/usr/local/share/certs/ca-root-nss.crt" }, { "/etc/ssl/cert.pem" } #endif /*!DEFAULT_TRUST_STORE_FILE*/ }; int idx; gpg_error_t err = 0; for (idx=0; idx < DIM (table); idx++) if (!gnupg_access (table[idx].name, F_OK)) { /* Take the first available bundle. */ err = load_certs_from_file (table[idx].name, CERTTRUST_CLASS_SYSTEM, 0); break; } return err; #endif /*!HAVE_W32_SYSTEM*/ } /* Initialize the certificate cache if not yet done. */ void cert_cache_init (strlist_t hkp_cacerts) { char *fname; strlist_t sl; if (initialization_done) return; init_cache_lock (); acquire_cache_write_lock (); load_certs_from_system (); fname = make_filename_try (gnupg_sysconfdir (), "trusted-certs", NULL); if (fname) load_certs_from_dir (fname, CERTTRUST_CLASS_CONFIG); xfree (fname); fname = make_filename_try (gnupg_sysconfdir (), "extra-certs", NULL); if (fname) load_certs_from_dir (fname, 0); xfree (fname); /* Put the special pool certificate into our store. This is * currently only used with ntbtls. For GnuTLS http_session_new * unfortunately loads that certificate directly from the file. */ fname = make_filename_try (gnupg_datadir (), "sks-keyservers.netCA.pem", NULL); if (fname) load_certs_from_file (fname, CERTTRUST_CLASS_HKPSPOOL, 1); xfree (fname); for (sl = hkp_cacerts; sl; sl = sl->next) load_certs_from_file (sl->d, CERTTRUST_CLASS_HKP, 0); initialization_done = 1; release_cache_lock (); cert_cache_print_stats (); } /* Deinitialize the certificate cache. With FULL set to true even the unused certificate slots are released. */ void cert_cache_deinit (int full) { cert_item_t ci, ci2; int i; if (!initialization_done) return; acquire_cache_write_lock (); for (i=0; i < 256; i++) for (ci=cert_cache[i]; ci; ci = ci->next) clean_cache_slot (ci); if (full) { for (i=0; i < 256; i++) { for (ci=cert_cache[i]; ci; ci = ci2) { ci2 = ci->next; xfree (ci); } cert_cache[i] = NULL; } } http_register_cfg_ca (NULL); total_nonperm_certificates = 0; any_cert_of_class = 0; initialization_done = 0; release_cache_lock (); } /* Print some statistics to the log file. */ void cert_cache_print_stats (void) { cert_item_t ci; int idx; unsigned int n_nonperm = 0; unsigned int n_permanent = 0; unsigned int n_trusted = 0; unsigned int n_trustclass_system = 0; unsigned int n_trustclass_config = 0; unsigned int n_trustclass_hkp = 0; unsigned int n_trustclass_hkpspool = 0; acquire_cache_read_lock (); for (idx = 0; idx < 256; idx++) for (ci=cert_cache[idx]; ci; ci = ci->next) if (ci->cert) { if (ci->permanent) n_permanent++; else n_nonperm++; if (ci->trustclasses) { n_trusted++; if ((ci->trustclasses & CERTTRUST_CLASS_SYSTEM)) n_trustclass_system++; if ((ci->trustclasses & CERTTRUST_CLASS_CONFIG)) n_trustclass_config++; if ((ci->trustclasses & CERTTRUST_CLASS_HKP)) n_trustclass_hkp++; if ((ci->trustclasses & CERTTRUST_CLASS_HKPSPOOL)) n_trustclass_hkpspool++; } } release_cache_lock (); log_info (_("permanently loaded certificates: %u\n"), n_permanent); log_info (_(" runtime cached certificates: %u\n"), n_nonperm); log_info (_(" trusted certificates: %u (%u,%u,%u,%u)\n"), n_trusted, n_trustclass_system, n_trustclass_config, n_trustclass_hkp, n_trustclass_hkpspool); } /* Return true if any cert of a class in MASK is permanently * loaded. */ int cert_cache_any_in_class (unsigned int mask) { return !!(any_cert_of_class & mask); } /* Put CERT into the certificate cache. */ gpg_error_t cache_cert (ksba_cert_t cert) { gpg_error_t err; acquire_cache_write_lock (); err = put_cert (cert, 0, 0, NULL); release_cache_lock (); if (gpg_err_code (err) == GPG_ERR_DUP_VALUE) log_info (_("certificate already cached\n")); else if (!err) log_info (_("certificate cached\n")); else log_error (_("error caching certificate: %s\n"), gpg_strerror (err)); return err; } /* Put CERT into the certificate cache and store the fingerprint of the certificate into FPR_BUFFER. If the certificate is already in the cache do not print a warning; just store the fingerprint. FPR_BUFFER needs to be at least 20 bytes. */ gpg_error_t cache_cert_silent (ksba_cert_t cert, void *fpr_buffer) { gpg_error_t err; acquire_cache_write_lock (); err = put_cert (cert, 0, 0, fpr_buffer); release_cache_lock (); if (gpg_err_code (err) == GPG_ERR_DUP_VALUE) err = 0; if (err) log_error (_("error caching certificate: %s\n"), gpg_strerror (err)); return err; } /* Return a certificate object for the given fingerprint. FPR is expected to be a 20 byte binary SHA-1 fingerprint. If no matching certificate is available in the cache NULL is returned. The caller must release a returned certificate. Note that although we are using reference counting the caller should not just compare the pointers to check for identical certificates. */ ksba_cert_t get_cert_byfpr (const unsigned char *fpr) { cert_item_t ci; acquire_cache_read_lock (); for (ci=cert_cache[*fpr]; ci; ci = ci->next) if (ci->cert && !memcmp (ci->fpr, fpr, 20)) { ksba_cert_ref (ci->cert); release_cache_lock (); return ci->cert; } release_cache_lock (); return NULL; } /* Return a certificate object for the given fingerprint. STRING is expected to be a SHA-1 fingerprint in standard hex notation with or without colons. If no matching certificate is available in the cache NULL is returned. The caller must release a returned certificate. Note that although we are using reference counting the caller should not just compare the pointers to check for identical certificates. */ ksba_cert_t get_cert_byhexfpr (const char *string) { unsigned char fpr[20]; const char *s; int i; if (strchr (string, ':')) { for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1);) { if (s[2] && s[2] != ':') break; /* Invalid string. */ fpr[i++] = xtoi_2 (s); s += 2; if (i!= 20 && *s == ':') s++; } } else { for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1); s+=2 ) fpr[i++] = xtoi_2 (s); } if (i!=20 || *s) { log_error (_("invalid SHA1 fingerprint string '%s'\n"), string); return NULL; } return get_cert_byfpr (fpr); } /* Return the certificate matching ISSUER_DN and SERIALNO. */ ksba_cert_t get_cert_bysn (const char *issuer_dn, ksba_sexp_t serialno) { /* Simple and inefficient implementation. fixme! */ cert_item_t ci; int i; acquire_cache_read_lock (); for (i=0; i < 256; i++) { for (ci=cert_cache[i]; ci; ci = ci->next) if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn) && !compare_serialno (ci->sn, serialno)) { ksba_cert_ref (ci->cert); release_cache_lock (); return ci->cert; } } release_cache_lock (); return NULL; } /* Return the certificate matching ISSUER_DN. SEQ should initially be set to 0 and bumped up to get the next issuer with that DN. */ ksba_cert_t get_cert_byissuer (const char *issuer_dn, unsigned int seq) { /* Simple and very inefficient implementation and API. fixme! */ cert_item_t ci; int i; acquire_cache_read_lock (); for (i=0; i < 256; i++) { for (ci=cert_cache[i]; ci; ci = ci->next) if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn)) if (!seq--) { ksba_cert_ref (ci->cert); release_cache_lock (); return ci->cert; } } release_cache_lock (); return NULL; } /* Return the certificate matching SUBJECT_DN. SEQ should initially be set to 0 and bumped up to get the next subject with that DN. */ ksba_cert_t get_cert_bysubject (const char *subject_dn, unsigned int seq) { /* Simple and very inefficient implementation and API. fixme! */ cert_item_t ci; int i; if (!subject_dn) return NULL; acquire_cache_read_lock (); for (i=0; i < 256; i++) { for (ci=cert_cache[i]; ci; ci = ci->next) if (ci->cert && ci->subject_dn && !strcmp (ci->subject_dn, subject_dn)) if (!seq--) { ksba_cert_ref (ci->cert); release_cache_lock (); return ci->cert; } } release_cache_lock (); return NULL; } /* Return a value describing the class of PATTERN. The offset of the actual string to be used for the comparison is stored at R_OFFSET. The offset of the serialnumer is stored at R_SN_OFFSET. */ static enum pattern_class classify_pattern (const char *pattern, size_t *r_offset, size_t *r_sn_offset) { enum pattern_class result; const char *s; int hexprefix = 0; int hexlength; *r_offset = *r_sn_offset = 0; /* Skip leading spaces. */ for(s = pattern; *s && spacep (s); s++ ) ; switch (*s) { case 0: /* Empty string is an error. */ result = PATTERN_UNKNOWN; break; case '.': /* An email address, compare from end. */ result = PATTERN_UNKNOWN; /* Not implemented. */ break; case '<': /* An email address. */ result = PATTERN_EMAIL; s++; break; case '@': /* Part of an email address. */ result = PATTERN_EMAIL_SUBSTR; s++; break; case '=': /* Exact compare. */ result = PATTERN_UNKNOWN; /* Does not make sense for X.509. */ break; case '*': /* Case insensitive substring search. */ result = PATTERN_SUBSTR; s++; break; case '+': /* Compare individual words. */ result = PATTERN_UNKNOWN; /* Not implemented. */ break; case '/': /* Subject's DN. */ s++; if (!*s || spacep (s)) result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */ else result = PATTERN_SUBJECT; break; case '#': /* Serial number or issuer DN. */ { const char *si; s++; if ( *s == '/') { /* An issuer's DN is indicated by "#/" */ s++; if (!*s || spacep (s)) result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */ else result = PATTERN_ISSUER; } else { /* Serialnumber + optional issuer ID. */ for (si=s; *si && *si != '/'; si++) if (!strchr("01234567890abcdefABCDEF", *si)) break; if (*si && *si != '/') result = PATTERN_UNKNOWN; /* Invalid digit in serial number. */ else { *r_sn_offset = s - pattern; if (!*si) result = PATTERN_SERIALNO; else { s = si+1; if (!*s || spacep (s)) result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */ else result = PATTERN_SERIALNO_ISSUER; } } } } break; case ':': /* Unified fingerprint. */ { const char *se, *si; int i; se = strchr (++s, ':'); if (!se) result = PATTERN_UNKNOWN; else { for (i=0, si=s; si < se; si++, i++ ) if (!strchr("01234567890abcdefABCDEF", *si)) break; if ( si < se ) result = PATTERN_UNKNOWN; /* Invalid digit. */ else if (i == 32) result = PATTERN_FINGERPRINT16; else if (i == 40) result = PATTERN_FINGERPRINT20; else result = PATTERN_UNKNOWN; /* Invalid length for a fingerprint. */ } } break; case '&': /* Keygrip. */ result = PATTERN_UNKNOWN; /* Not implemented. */ break; default: if (s[0] == '0' && s[1] == 'x') { hexprefix = 1; s += 2; } hexlength = strspn(s, "0123456789abcdefABCDEF"); /* Check if a hexadecimal number is terminated by EOS or blank. */ if (hexlength && s[hexlength] && !spacep (s+hexlength)) { /* If the "0x" prefix is used a correct termination is required. */ if (hexprefix) { result = PATTERN_UNKNOWN; break; /* switch */ } hexlength = 0; /* Not a hex number. */ } if (hexlength == 8 || (!hexprefix && hexlength == 9 && *s == '0')) { if (hexlength == 9) s++; result = PATTERN_SHORT_KEYID; } else if (hexlength == 16 || (!hexprefix && hexlength == 17 && *s == '0')) { if (hexlength == 17) s++; result = PATTERN_LONG_KEYID; } else if (hexlength == 32 || (!hexprefix && hexlength == 33 && *s == '0')) { if (hexlength == 33) s++; result = PATTERN_FINGERPRINT16; } else if (hexlength == 40 || (!hexprefix && hexlength == 41 && *s == '0')) { if (hexlength == 41) s++; result = PATTERN_FINGERPRINT20; } else if (!hexprefix) { /* The fingerprints used with X.509 are often delimited by colons, so we try to single this case out. */ result = PATTERN_UNKNOWN; hexlength = strspn (s, ":0123456789abcdefABCDEF"); if (hexlength == 59 && (!s[hexlength] || spacep (s+hexlength))) { int i, c; for (i=0; i < 20; i++, s += 3) { c = hextobyte(s); if (c == -1 || (i < 19 && s[2] != ':')) break; } if (i == 20) result = PATTERN_FINGERPRINT20; } if (result == PATTERN_UNKNOWN) /* Default to substring match. */ { result = PATTERN_SUBSTR; } } else /* A hex number with a prefix but with a wrong length. */ result = PATTERN_UNKNOWN; } if (result != PATTERN_UNKNOWN) *r_offset = s - pattern; return result; } /* Given PATTERN, which is a string as used by GnuPG to specify a certificate, return all matching certificates by calling the supplied function RETFNC. */ gpg_error_t get_certs_bypattern (const char *pattern, gpg_error_t (*retfnc)(void*,ksba_cert_t), void *retfnc_data) { gpg_error_t err = GPG_ERR_BUG; enum pattern_class class; size_t offset, sn_offset; const char *hexserialno; ksba_sexp_t serialno = NULL; ksba_cert_t cert = NULL; unsigned int seq; if (!pattern || !retfnc) return gpg_error (GPG_ERR_INV_ARG); class = classify_pattern (pattern, &offset, &sn_offset); hexserialno = pattern + sn_offset; pattern += offset; switch (class) { case PATTERN_UNKNOWN: err = gpg_error (GPG_ERR_INV_NAME); break; case PATTERN_FINGERPRINT20: cert = get_cert_byhexfpr (pattern); err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND); break; case PATTERN_SERIALNO_ISSUER: serialno = hexsn_to_sexp (hexserialno); if (!serialno) err = gpg_error_from_syserror (); else { cert = get_cert_bysn (pattern, serialno); err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND); } break; case PATTERN_ISSUER: for (seq=0,err=0; !err && (cert = get_cert_byissuer (pattern, seq)); seq++) { err = retfnc (retfnc_data, cert); ksba_cert_release (cert); cert = NULL; } if (!err && !seq) err = gpg_error (GPG_ERR_NOT_FOUND); break; case PATTERN_SUBJECT: for (seq=0,err=0; !err && (cert = get_cert_bysubject (pattern, seq));seq++) { err = retfnc (retfnc_data, cert); ksba_cert_release (cert); cert = NULL; } if (!err && !seq) err = gpg_error (GPG_ERR_NOT_FOUND); break; case PATTERN_EMAIL: case PATTERN_EMAIL_SUBSTR: case PATTERN_FINGERPRINT16: case PATTERN_SHORT_KEYID: case PATTERN_LONG_KEYID: case PATTERN_SUBSTR: case PATTERN_SERIALNO: /* Not supported. */ err = gpg_error (GPG_ERR_INV_NAME); } if (!err && cert) err = retfnc (retfnc_data, cert); ksba_cert_release (cert); xfree (serialno); return err; } /* Return the certificate matching ISSUER_DN and SERIALNO; if it is * not already in the cache, try to find it from other resources. */ ksba_cert_t find_cert_bysn (ctrl_t ctrl, const char *issuer_dn, ksba_sexp_t serialno) { gpg_error_t err; ksba_cert_t cert; cert_fetch_context_t context = NULL; char *hexsn, *buf; /* First check whether it has already been cached. */ cert = get_cert_bysn (issuer_dn, serialno); if (cert) return cert; /* Ask back to the service requester to return the certificate. * This is because we can assume that he already used the * certificate while checking for the CRL. */ hexsn = serial_hex (serialno); if (!hexsn) { log_error ("serial_hex() failed\n"); return NULL; } buf = strconcat ("#", hexsn, "/", issuer_dn, NULL); if (!buf) { log_error ("can't allocate enough memory: %s\n", strerror (errno)); xfree (hexsn); return NULL; } xfree (hexsn); cert = get_cert_local (ctrl, buf); xfree (buf); if (cert) { cache_cert (cert); return cert; /* Done. */ } if (DBG_LOOKUP) log_debug ("find_cert_bysn: certificate not returned by caller" " - doing lookup\n"); /* Retrieve the certificate from external resources. */ while (!cert) { ksba_sexp_t sn; char *issdn; if (!context) { err = ca_cert_fetch (ctrl, &context, issuer_dn); if (err) { log_error (_("error fetching certificate by S/N: %s\n"), gpg_strerror (err)); break; } } err = fetch_next_ksba_cert (context, &cert); if (err) { log_error (_("error fetching certificate by S/N: %s\n"), gpg_strerror (err) ); break; } issdn = ksba_cert_get_issuer (cert, 0); if (strcmp (issuer_dn, issdn)) { log_debug ("find_cert_bysn: Ooops: issuer DN does not match\n"); ksba_cert_release (cert); cert = NULL; ksba_free (issdn); break; } sn = ksba_cert_get_serial (cert); if (DBG_LOOKUP) { log_debug (" considering certificate (#"); dump_serial (sn); log_printf ("/"); dump_string (issdn); log_printf (")\n"); } if (!compare_serialno (serialno, sn)) { ksba_free (sn); ksba_free (issdn); cache_cert (cert); if (DBG_LOOKUP) log_debug (" found\n"); break; /* Ready. */ } ksba_free (sn); ksba_free (issdn); ksba_cert_release (cert); cert = NULL; } end_cert_fetch (context); return cert; } /* Return the certificate matching SUBJECT_DN and (if not NULL) * KEYID. If it is not already in the cache, try to find it from other * resources. Note, that the external search does not work for user * certificates because the LDAP lookup is on the caCertificate * attribute. For our purposes this is just fine. */ ksba_cert_t find_cert_bysubject (ctrl_t ctrl, const char *subject_dn, ksba_sexp_t keyid) { gpg_error_t err; int seq; ksba_cert_t cert = NULL; cert_fetch_context_t context = NULL; ksba_sexp_t subj; /* If we have certificates from an OCSP request we first try to use * them. This is because these certificates will really be the * required ones and thus even in the case that they can't be * uniquely located by the following code we can use them. This is * for example required by Telesec certificates where a keyId is * used but the issuer certificate comes without a subject keyId! */ if (ctrl->ocsp_certs && subject_dn) { cert_item_t ci; cert_ref_t cr; int i; /* For efficiency reasons we won't use get_cert_bysubject here. */ acquire_cache_read_lock (); for (i=0; i < 256; i++) for (ci=cert_cache[i]; ci; ci = ci->next) if (ci->cert && ci->subject_dn && !strcmp (ci->subject_dn, subject_dn)) for (cr=ctrl->ocsp_certs; cr; cr = cr->next) if (!memcmp (ci->fpr, cr->fpr, 20)) { ksba_cert_ref (ci->cert); release_cache_lock (); if (DBG_LOOKUP) log_debug ("%s: certificate found in the cache" " via ocsp_certs\n", __func__); return ci->cert; /* We use this certificate. */ } release_cache_lock (); if (DBG_LOOKUP) log_debug ("find_cert_bysubject: certificate not in ocsp_certs\n"); } /* Now check whether the certificate is cached. */ for (seq=0; (cert = get_cert_bysubject (subject_dn, seq)); seq++) { if (!keyid) break; /* No keyid requested, so return the first one found. */ if (!ksba_cert_get_subj_key_id (cert, NULL, &subj) && !cmp_simple_canon_sexp (keyid, subj)) { xfree (subj); if (DBG_LOOKUP) log_debug ("%s: certificate found in the cache" " via subject DN\n", __func__); break; /* Found matching cert. */ } xfree (subj); ksba_cert_release (cert); } if (cert) return cert; /* Done. */ /* If we do not have a subject DN but have a keyid, try to locate it * by keyid. */ if (!subject_dn && keyid) { int i; cert_item_t ci; ksba_sexp_t ski; acquire_cache_read_lock (); for (i=0; i < 256; i++) for (ci=cert_cache[i]; ci; ci = ci->next) if (ci->cert && !ksba_cert_get_subj_key_id (ci->cert, NULL, &ski)) { if (!cmp_simple_canon_sexp (keyid, ski)) { ksba_free (ski); ksba_cert_ref (ci->cert); release_cache_lock (); if (DBG_LOOKUP) log_debug ("%s: certificate found in the cache" " via ski\n", __func__); return ci->cert; } ksba_free (ski); } release_cache_lock (); } if (DBG_LOOKUP) log_debug ("find_cert_bysubject: certificate not in cache\n"); /* Ask back to the service requester to return the certificate. * This is because we can assume that he already used the * certificate while checking for the CRL. */ if (keyid) cert = get_cert_local_ski (ctrl, subject_dn, keyid); else { /* In contrast to get_cert_local_ski, get_cert_local uses any * passed pattern, so we need to make sure that an exact subject * search is done. */ char *buf; buf = strconcat ("/", subject_dn, NULL); if (!buf) { log_error ("can't allocate enough memory: %s\n", strerror (errno)); return NULL; } cert = get_cert_local (ctrl, buf); xfree (buf); } if (cert) { cache_cert (cert); return cert; /* Done. */ } if (DBG_LOOKUP) log_debug ("find_cert_bysubject: certificate not returned by caller" " - doing lookup\n"); /* Locate the certificate using external resources. */ while (!cert) { char *subjdn; if (!context) { err = ca_cert_fetch (ctrl, &context, subject_dn); if (err) { log_error (_("error fetching certificate by subject: %s\n"), gpg_strerror (err)); break; } } err = fetch_next_ksba_cert (context, &cert); if (err) { log_error (_("error fetching certificate by subject: %s\n"), gpg_strerror (err) ); break; } subjdn = ksba_cert_get_subject (cert, 0); if (strcmp (subject_dn, subjdn)) { log_info ("find_cert_bysubject: subject DN does not match\n"); ksba_cert_release (cert); cert = NULL; ksba_free (subjdn); continue; } if (DBG_LOOKUP) { log_debug (" considering certificate (/"); dump_string (subjdn); log_printf (")\n"); } ksba_free (subjdn); /* If no key ID has been provided, we return the first match. */ if (!keyid) { cache_cert (cert); if (DBG_LOOKUP) log_debug (" found\n"); break; /* Ready. */ } /* With the key ID given we need to compare it. */ if (!ksba_cert_get_subj_key_id (cert, NULL, &subj)) { if (!cmp_simple_canon_sexp (keyid, subj)) { ksba_free (subj); cache_cert (cert); if (DBG_LOOKUP) log_debug (" found\n"); break; /* Ready. */ } } ksba_free (subj); ksba_cert_release (cert); cert = NULL; } end_cert_fetch (context); return cert; } /* Return 0 if the certificate is a trusted certificate. Returns * GPG_ERR_NOT_TRUSTED if it is not trusted or other error codes in * case of systems errors. TRUSTCLASSES are the bitwise ORed * CERTTRUST_CLASS values to use for the check. */ gpg_error_t is_trusted_cert (ksba_cert_t cert, unsigned int trustclasses) { unsigned char fpr[20]; cert_item_t ci; cert_compute_fpr (cert, fpr); acquire_cache_read_lock (); for (ci=cert_cache[*fpr]; ci; ci = ci->next) if (ci->cert && !memcmp (ci->fpr, fpr, 20)) { if ((ci->trustclasses & trustclasses)) { /* The certificate is trusted in one of the given * TRUSTCLASSES. */ release_cache_lock (); return 0; /* Yes, it is trusted. */ } break; } release_cache_lock (); return gpg_error (GPG_ERR_NOT_TRUSTED); } /* Given the certificate CERT locate the issuer for this certificate * and return it at R_CERT. Returns 0 on success or * GPG_ERR_NOT_FOUND. */ gpg_error_t find_issuing_cert (ctrl_t ctrl, ksba_cert_t cert, ksba_cert_t *r_cert) { gpg_error_t err; char *issuer_dn; ksba_cert_t issuer_cert = NULL; ksba_name_t authid; ksba_sexp_t authidno; ksba_sexp_t keyid; *r_cert = NULL; issuer_dn = ksba_cert_get_issuer (cert, 0); if (!issuer_dn) { log_error (_("no issuer found in certificate\n")); err = gpg_error (GPG_ERR_BAD_CERT); goto leave; } /* First we need to check whether we can return that certificate using the authorithyKeyIdentifier. */ err = ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno); if (err) { log_info (_("error getting authorityKeyIdentifier: %s\n"), gpg_strerror (err)); } else { const char *s = ksba_name_enum (authid, 0); if (s && *authidno) { issuer_cert = find_cert_bysn (ctrl, s, authidno); } if (!issuer_cert && keyid) { /* Not found by issuer+s/n. Now that we have an AKI * keyIdentifier look for a certificate with a matching * SKI. */ issuer_cert = find_cert_bysubject (ctrl, issuer_dn, keyid); } /* 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 (!issuer_cert) { log_info ("issuer certificate "); if (keyid) { log_printf ("{"); dump_serial (keyid); log_printf ("} "); } if (authidno) { log_printf ("(#"); dump_serial (authidno); log_printf ("/"); dump_string (s); log_printf (") "); } log_printf ("not found using authorityKeyIdentifier\n"); } ksba_name_release (authid); xfree (authidno); xfree (keyid); } /* If this did not work, try just with the issuer's name and assume * that there is only one such certificate. We only look into our * cache then. */ if (err || !issuer_cert) { issuer_cert = get_cert_bysubject (issuer_dn, 0); if (issuer_cert) err = 0; } leave: if (!err && !issuer_cert) err = gpg_error (GPG_ERR_NOT_FOUND); xfree (issuer_dn); if (err) ksba_cert_release (issuer_cert); else *r_cert = issuer_cert; return err; } /* Read a list of certificates in PEM format from stream FP and store * them on success at R_CERTLIST. On error NULL is stored at R_CERT * list and an error code returned. Note that even on success an * empty list of certificates can be returned (i.e. NULL stored at * R_CERTLIST) iff the input stream has no certificates. */ gpg_error_t read_certlist_from_stream (certlist_t *r_certlist, estream_t fp) { gpg_error_t err; gnupg_ksba_io_t ioctx = NULL; ksba_reader_t reader; ksba_cert_t cert = NULL; certlist_t certlist = NULL; certlist_t cl, *cltail; *r_certlist = NULL; err = gnupg_ksba_create_reader (&ioctx, (GNUPG_KSBA_IO_PEM | GNUPG_KSBA_IO_MULTIPEM), fp, &reader); if (err) goto leave; /* Loop to read all certificates from the stream. */ cltail = &certlist; do { ksba_cert_release (cert); cert = NULL; err = ksba_cert_new (&cert); if (!err) err = ksba_cert_read_der (cert, reader); if (err) { if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; goto leave; } /* Append the certificate to the list. We also store the * fingerprint and check whether we have a cached certificate; * in that case the cached certificate is put into the list to * take advantage of a validation result which might be stored * in the cached certificate. */ cl = xtrycalloc (1, sizeof *cl); if (!cl) { err = gpg_error_from_syserror (); goto leave; } cert_compute_fpr (cert, cl->fpr); cl->cert = get_cert_byfpr (cl->fpr); if (!cl->cert) { cl->cert = cert; cert = NULL; } *cltail = cl; cltail = &cl->next; ksba_reader_clear (reader, NULL, NULL); } while (!gnupg_ksba_reader_eof_seen (ioctx)); leave: ksba_cert_release (cert); gnupg_ksba_destroy_reader (ioctx); if (err) release_certlist (certlist); else *r_certlist = certlist; return err; } /* Release the certificate list CL. */ void release_certlist (certlist_t cl) { while (cl) { certlist_t next = cl->next; ksba_cert_release (cl->cert); cl = next; } } diff --git a/dirmngr/crlcache.c b/dirmngr/crlcache.c index 88b07cd7a..9d18b721f 100644 --- a/dirmngr/crlcache.c +++ b/dirmngr/crlcache.c @@ -1,2761 +1,2757 @@ /* crlcache.c - LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2005, 2008 g10 Code GmbH * * This file is part of DirMngr. * * DirMngr 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 2 of the License, or * (at your option) any later version. * * DirMngr 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 . */ /* 1. To keep track of the CRLs actually cached and to store the meta information of the CRLs a simple record oriented text file is used. Fields in the file are colon (':') separated and values containing colons or linefeeds are percent escaped (e.g. a colon itself is represented as "%3A"). The first field is a record type identifier, so that the file is useful to keep track of other meta data too. The name of the file is "DIR.txt". 1.1. Comment record Field 1: Constant beginning with "#". Other fields are not defined and such a record is simply skipped during processing. 1.2. Version record Field 1: Constant "v" Field 2: Version number of this file. Must be 1. This record must be the first non-comment record and there shall only exist one record of this type. 1.3. CRL cache record Field 1: Constant "c", "u" or "i". A "c" or "u" indicate a valid cache entry, however "u" requires that a user root certificate check needs to be done. An "i" indicates an invalid cache entry which should not be used but still exists so that it can be updated at NEXT_UPDATE. Field 2: Hexadecimal encoded SHA-1 hash of the issuer DN using uppercase letters. Field 3: Issuer DN in RFC-2253 notation. Field 4: URL used to retrieve the corresponding CRL. Field 5: 15 character ISO timestamp with THIS_UPDATE. Field 6: 15 character ISO timestamp with NEXT_UPDATE. Field 7: Hexadecimal encoded MD-5 hash of the DB file to detect accidental modified (i.e. deleted and created) cache files. Field 8: optional CRL number as a hex string. Field 9: AuthorityKeyID.issuer, each Name separated by 0x01 Field 10: AuthorityKeyID.serial Field 11: Hex fingerprint of trust anchor if field 1 is 'u'. 2. Layout of the standard CRL Cache DB file: We use records of variable length with this structure n bytes Serialnumber (binary) used as key thus there is no need to store the length explicitly with DB2. 1 byte Reason for revocation (currently the KSBA reason flags are used) 15 bytes ISO date of revocation (e.g. 19980815T142000) Note that there is no terminating 0 stored. The filename used is the hexadecimal (using uppercase letters) SHA-1 hash value of the issuer DN prefixed with a "crl-" and suffixed with a ".db". Thus the length of the filename is 47. */ #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #endif -#ifdef MKDIR_TAKES_ONE_ARG -#undef mkdir -#define mkdir(a,b) mkdir(a) -#endif #include "dirmngr.h" #include "validate.h" #include "certcache.h" #include "crlcache.h" #include "crlfetch.h" #include "misc.h" #include "cdb.h" /* Change this whenever the format changes */ #define DBDIR_D "crls.d" #define DBDIRFILE "DIR.txt" #define DBDIRVERSION 1 /* The number of DB files we may have open at one time. We need to limit this because there is no guarantee that the number of issuers has a upper limit. We are currently using mmap, so it is a good idea anyway to limit the number of opened cache files. */ #define MAX_OPEN_DB_FILES 5 #ifndef O_BINARY # define O_BINARY 0 #endif static const char oidstr_crlNumber[] = "2.5.29.20"; /* static const char oidstr_issuingDistributionPoint[] = "2.5.29.28"; */ static const char oidstr_authorityKeyIdentifier[] = "2.5.29.35"; /* Definition of one cached item. */ struct crl_cache_entry_s { struct crl_cache_entry_s *next; int deleted; /* True if marked for deletion. */ int mark; /* Internally used by update_dir. */ unsigned int lineno;/* A 0 indicates a new entry. */ char *release_ptr; /* The actual allocated memory. */ char *url; /* Points into RELEASE_PTR. */ char *issuer; /* Ditto. */ char *issuer_hash; /* Ditto. */ char *dbfile_hash; /* MD5 sum of the cache file, points into RELEASE_PTR.*/ int invalid; /* Can't use this CRL. */ int user_trust_req; /* User supplied root certificate required. */ char *check_trust_anchor; /* Malloced fingerprint. */ ksba_isotime_t this_update; ksba_isotime_t next_update; ksba_isotime_t last_refresh; /* Use for the force_crl_refresh feature. */ char *crl_number; char *authority_issuer; char *authority_serialno; struct cdb *cdb; /* The cache file handle or NULL if not open. */ unsigned int cdb_use_count; /* Current use count. */ unsigned int cdb_lru_count; /* Used for LRU purposes. */ int dbfile_checked; /* Set to true if the dbfile_hash value has been checked one. */ }; /* Definition of the entire cache object. */ struct crl_cache_s { crl_cache_entry_t entries; }; typedef struct crl_cache_s *crl_cache_t; /* Prototypes. */ static crl_cache_entry_t find_entry (crl_cache_entry_t first, const char *issuer_hash); /* The currently loaded cache object. This is usually initialized right at startup. */ static crl_cache_t current_cache; /* Return the current cache object or bail out if it is has not yet been initialized. */ static crl_cache_t get_current_cache (void) { if (!current_cache) log_fatal ("CRL cache has not yet been initialized\n"); return current_cache; } /* Create ae directory if it does not yet exists. Returns on success, or -1 on error. */ static int create_directory_if_needed (const char *name) { - DIR *dir; + gnupg_dir_t dir; char *fname; fname = make_filename (opt.homedir_cache, name, NULL); - dir = opendir (fname); + dir = gnupg_opendir (fname); if (!dir) { log_info (_("creating directory '%s'\n"), fname); - if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR) ) + if (gnupg_mkdir (fname, "-rwx")) { int save_errno = errno; log_error (_("error creating directory '%s': %s\n"), fname, strerror (errno)); xfree (fname); gpg_err_set_errno (save_errno); return -1; } } else - closedir (dir); + gnupg_closedir (dir); xfree (fname); return 0; } /* Remove all files from the cache directory. If FORCE is not true, some sanity checks on the filenames are done. Return 0 if everything went fine. */ static int cleanup_cache_dir (int force) { char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL); - DIR *dir; - struct dirent *de; + gnupg_dir_t dir; + gnupg_dirent_t de; int problem = 0; if (!force) { /* Very minor sanity checks. */ if (!strcmp (dname, "~/") || !strcmp (dname, "/" )) { log_error (_("ignoring database dir '%s'\n"), dname); xfree (dname); return -1; } } - dir = opendir (dname); + dir = gnupg_opendir (dname); if (!dir) { log_error (_("error reading directory '%s': %s\n"), dname, strerror (errno)); xfree (dname); return -1; } - while ((de = readdir (dir))) + while ((de = gnupg_readdir (dir))) { if (strcmp (de->d_name, "." ) && strcmp (de->d_name, "..")) { char *cdbname = make_filename (dname, de->d_name, NULL); int okay; struct stat sbuf; if (force) okay = 1; else okay = (!gnupg_stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode)); if (okay) { log_info (_("removing cache file '%s'\n"), cdbname); if (gnupg_remove (cdbname)) { log_error ("failed to remove '%s': %s\n", cdbname, strerror (errno)); problem = -1; } } else log_info (_("not removing file '%s'\n"), cdbname); xfree (cdbname); } } xfree (dname); - closedir (dir); + gnupg_closedir (dir); return problem; } /* Read the next line from the file FP and return the line in an malloced buffer. Return NULL on error or EOF. There is no limitation os the line length. The trailing linefeed has been removed, the function will read the last line of a file, even if that is not terminated by a LF. */ static char * next_line_from_file (estream_t fp, gpg_error_t *r_err) { char buf[300]; char *largebuf = NULL; size_t buflen; size_t len = 0; unsigned char *p; int c; char *tmpbuf; *r_err = 0; p = buf; buflen = sizeof buf - 1; while ((c=es_getc (fp)) != EOF && c != '\n') { if (len >= buflen) { if (!largebuf) { buflen += 1024; largebuf = xtrymalloc ( buflen + 1 ); if (!largebuf) { *r_err = gpg_error_from_syserror (); return NULL; } memcpy (largebuf, buf, len); } else { buflen += 1024; tmpbuf = xtryrealloc (largebuf, buflen + 1); if (!tmpbuf) { *r_err = gpg_error_from_syserror (); xfree (largebuf); return NULL; } largebuf = tmpbuf; } p = largebuf; } p[len++] = c; } if (c == EOF && !len) return NULL; p[len] = 0; if (largebuf) tmpbuf = xtryrealloc (largebuf, len+1); else tmpbuf = xtrystrdup (buf); if (!tmpbuf) { *r_err = gpg_error_from_syserror (); xfree (largebuf); } return tmpbuf; } /* Release one cache entry. */ static void release_one_cache_entry (crl_cache_entry_t entry) { if (entry) { if (entry->cdb) { int fd = cdb_fileno (entry->cdb); cdb_free (entry->cdb); xfree (entry->cdb); if (close (fd)) log_error (_("error closing cache file: %s\n"), strerror(errno)); } xfree (entry->release_ptr); xfree (entry->check_trust_anchor); xfree (entry); } } /* Release the CACHE object. */ static void release_cache (crl_cache_t cache) { crl_cache_entry_t entry, entry2; if (!cache) return; for (entry = cache->entries; entry; entry = entry2) { entry2 = entry->next; release_one_cache_entry (entry); } cache->entries = NULL; xfree (cache); } /* Open the dir file FNAME or create a new one if it does not yet exist. */ static estream_t open_dir_file (const char *fname) { estream_t fp; fp = es_fopen (fname, "r"); if (!fp) { log_error (_("failed to open cache dir file '%s': %s\n"), fname, strerror (errno)); /* Make sure that the directory exists, try to create if otherwise. */ if (create_directory_if_needed (NULL) || create_directory_if_needed (DBDIR_D)) return NULL; fp = es_fopen (fname, "w"); if (!fp) { log_error (_("error creating new cache dir file '%s': %s\n"), fname, strerror (errno)); return NULL; } es_fprintf (fp, "v:%d:\n", DBDIRVERSION); if (es_ferror (fp)) { log_error (_("error writing new cache dir file '%s': %s\n"), fname, strerror (errno)); es_fclose (fp); return NULL; } if (es_fclose (fp)) { log_error (_("error closing new cache dir file '%s': %s\n"), fname, strerror (errno)); return NULL; } log_info (_("new cache dir file '%s' created\n"), fname); fp = es_fopen (fname, "r"); if (!fp) { log_error (_("failed to re-open cache dir file '%s': %s\n"), fname, strerror (errno)); return NULL; } } return fp; } /* Helper for open_dir. */ static gpg_error_t check_dir_version (estream_t *fpadr, const char *fname, unsigned int *lineno, int cleanup_on_mismatch) { char *line; gpg_error_t lineerr = 0; estream_t fp = *fpadr; int created = 0; retry: while ((line = next_line_from_file (fp, &lineerr))) { ++*lineno; if (*line == 'v' && line[1] == ':') break; else if (*line != '#') { log_error (_("first record of '%s' is not the version\n"), fname); xfree (line); return gpg_error (GPG_ERR_CONFIGURATION); } xfree (line); } if (lineerr) return lineerr; /* The !line catches the case of an empty DIR file. We handle this the same as a non-matching version. */ if (!line || strtol (line+2, NULL, 10) != DBDIRVERSION) { if (!created && cleanup_on_mismatch) { log_error (_("old version of cache directory - cleaning up\n")); es_fclose (fp); *fpadr = NULL; if (!cleanup_cache_dir (1)) { *lineno = 0; fp = *fpadr = open_dir_file (fname); if (!fp) { xfree (line); return gpg_error (GPG_ERR_CONFIGURATION); } created = 1; goto retry; } } log_error (_("old version of cache directory - giving up\n")); xfree (line); return gpg_error (GPG_ERR_CONFIGURATION); } xfree (line); return 0; } /* Open the dir file and read in all available information. Store that in a newly allocated cache object and return that if everything worked out fine. Create the cache directory and the dir if it does not yet exist. Remove all files in that directory if the version does not match. */ static gpg_error_t open_dir (crl_cache_t *r_cache) { crl_cache_t cache; char *fname; char *line = NULL; gpg_error_t lineerr = 0; estream_t fp; crl_cache_entry_t entry, *entrytail; unsigned int lineno; gpg_error_t err = 0; int anyerr = 0; cache = xtrycalloc (1, sizeof *cache); if (!cache) return gpg_error_from_syserror (); fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL); lineno = 0; fp = open_dir_file (fname); if (!fp) { err = gpg_error (GPG_ERR_CONFIGURATION); goto leave; } err = check_dir_version (&fp, fname, &lineno, 1); if (err) goto leave; /* Read in all supported entries from the dir file. */ cache->entries = NULL; entrytail = &cache->entries; xfree (line); while ((line = next_line_from_file (fp, &lineerr))) { int fieldno; char *p, *endp; lineno++; if ( *line == 'c' || *line == 'u' || *line == 'i' ) { entry = xtrycalloc (1, sizeof *entry); if (!entry) { err = gpg_error_from_syserror (); goto leave; } entry->lineno = lineno; entry->release_ptr = line; if (*line == 'i') { entry->invalid = atoi (line+1); if (entry->invalid < 1) entry->invalid = 1; } else if (*line == 'u') entry->user_trust_req = 1; for (fieldno=1, p = line; p; p = endp, fieldno++) { endp = strchr (p, ':'); if (endp) *endp++ = '\0'; switch (fieldno) { case 1: /* record type */ break; case 2: entry->issuer_hash = p; break; case 3: entry->issuer = unpercent_string (p); break; case 4: entry->url = unpercent_string (p); break; case 5: strncpy (entry->this_update, p, 15); entry->this_update[15] = 0; break; case 6: strncpy (entry->next_update, p, 15); entry->next_update[15] = 0; break; case 7: entry->dbfile_hash = p; break; case 8: if (*p) entry->crl_number = p; break; case 9: if (*p) entry->authority_issuer = unpercent_string (p); break; case 10: if (*p) entry->authority_serialno = unpercent_string (p); break; case 11: if (*p) entry->check_trust_anchor = xtrystrdup (p); break; default: if (*p) log_info (_("extra field detected in crl record of " "'%s' line %u\n"), fname, lineno); break; } } if (!entry->issuer_hash) { log_info (_("invalid line detected in '%s' line %u\n"), fname, lineno); xfree (entry); entry = NULL; } else if (find_entry (cache->entries, entry->issuer_hash)) { /* Fixme: The duplicate checking used is not very effective for large numbers of issuers. */ log_info (_("duplicate entry detected in '%s' line %u\n"), fname, lineno); xfree (entry); entry = NULL; } else { line = NULL; *entrytail = entry; entrytail = &entry->next; } } else if (*line == '#') ; else log_info (_("unsupported record type in '%s' line %u skipped\n"), fname, lineno); if (line) xfree (line); } if (lineerr) { err = lineerr; log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } if (es_ferror (fp)) { log_error (_("error reading '%s': %s\n"), fname, strerror (errno)); err = gpg_error (GPG_ERR_CONFIGURATION); goto leave; } /* Now do some basic checks on the data. */ for (entry = cache->entries; entry; entry = entry->next) { assert (entry->lineno); if (strlen (entry->issuer_hash) != 40) { anyerr++; log_error (_("invalid issuer hash in '%s' line %u\n"), fname, entry->lineno); } else if ( !*entry->issuer ) { anyerr++; log_error (_("no issuer DN in '%s' line %u\n"), fname, entry->lineno); } else if ( check_isotime (entry->this_update) || check_isotime (entry->next_update)) { anyerr++; log_error (_("invalid timestamp in '%s' line %u\n"), fname, entry->lineno); } /* Checks not leading to an immediate fail. */ if (strlen (entry->dbfile_hash) != 32) log_info (_("WARNING: invalid cache file hash in '%s' line %u\n"), fname, entry->lineno); } if (anyerr) { log_error (_("detected errors in cache dir file\n")); log_info (_("please check the reason and manually delete that file\n")); err = gpg_error (GPG_ERR_CONFIGURATION); } leave: es_fclose (fp); xfree (line); xfree (fname); if (err) { release_cache (cache); cache = NULL; } *r_cache = cache; return err; } static void write_percented_string (const char *s, estream_t fp) { for (; *s; s++) if (*s == ':') es_fputs ("%3A", fp); else if (*s == '\n') es_fputs ("%0A", fp); else if (*s == '\r') es_fputs ("%0D", fp); else es_putc (*s, fp); } static void write_dir_line_crl (estream_t fp, crl_cache_entry_t e) { if (e->invalid) es_fprintf (fp, "i%d", e->invalid); else if (e->user_trust_req) es_putc ('u', fp); else es_putc ('c', fp); es_putc (':', fp); es_fputs (e->issuer_hash, fp); es_putc (':', fp); write_percented_string (e->issuer, fp); es_putc (':', fp); write_percented_string (e->url, fp); es_putc (':', fp); es_fwrite (e->this_update, 15, 1, fp); es_putc (':', fp); es_fwrite (e->next_update, 15, 1, fp); es_putc (':', fp); es_fputs (e->dbfile_hash, fp); es_putc (':', fp); if (e->crl_number) es_fputs (e->crl_number, fp); es_putc (':', fp); if (e->authority_issuer) write_percented_string (e->authority_issuer, fp); es_putc (':', fp); if (e->authority_serialno) es_fputs (e->authority_serialno, fp); es_putc (':', fp); if (e->check_trust_anchor && e->user_trust_req) es_fputs (e->check_trust_anchor, fp); es_putc ('\n', fp); } /* Update the current dir file using the cache. */ static gpg_error_t update_dir (crl_cache_t cache) { char *fname = NULL; char *tmpfname = NULL; char *line = NULL; gpg_error_t lineerr = 0; estream_t fp; estream_t fpout = NULL; crl_cache_entry_t e; unsigned int lineno; gpg_error_t err = 0; fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL); /* Fixme: Take an update file lock here. */ for (e= cache->entries; e; e = e->next) e->mark = 1; lineno = 0; fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_errno (errno); log_error (_("failed to open cache dir file '%s': %s\n"), fname, strerror (errno)); goto leave; } err = check_dir_version (&fp, fname, &lineno, 0); if (err) goto leave; es_rewind (fp); lineno = 0; /* Create a temporary DIR file. */ { char *tmpbuf, *p; const char *nodename; #ifndef HAVE_W32_SYSTEM struct utsname utsbuf; #endif #ifdef HAVE_W32_SYSTEM nodename = "unknown"; #else if (uname (&utsbuf)) nodename = "unknown"; else nodename = utsbuf.nodename; #endif gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp", nodename, (unsigned int)getpid (), &tmpbuf); if (!tmpbuf) { err = gpg_error_from_errno (errno); log_error (_("failed to create temporary cache dir file '%s': %s\n"), tmpfname, strerror (errno)); goto leave; } for (p=tmpbuf; *p; p++) if (*p == '/') *p = '.'; tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL); xfree (tmpbuf); } fpout = es_fopen (tmpfname, "w"); if (!fpout) { err = gpg_error_from_errno (errno); log_error (_("failed to create temporary cache dir file '%s': %s\n"), tmpfname, strerror (errno)); goto leave; } while ((line = next_line_from_file (fp, &lineerr))) { lineno++; if (*line == 'c' || *line == 'u' || *line == 'i') { /* Extract the issuer hash field. */ char *fieldp, *endp; fieldp = strchr (line, ':'); endp = fieldp? strchr (++fieldp, ':') : NULL; if (endp) { /* There should be no percent within the issuer hash field, thus we can compare it pretty easily. */ *endp = 0; e = find_entry ( cache->entries, fieldp); *endp = ':'; /* Restore original line. */ if (e && e->deleted) { /* Marked for deletion, so don't write it. */ e->mark = 0; } else if (e) { /* Yep, this is valid entry we know about; write it out */ write_dir_line_crl (fpout, e); e->mark = 0; } else { /* We ignore entries we don't have in our cache because they may have been added in the meantime by other instances of dirmngr. */ es_fprintf (fpout, "# Next line added by " "another process; our pid is %lu\n", (unsigned long)getpid ()); es_fputs (line, fpout); es_putc ('\n', fpout); } } else { es_fputs ("# Invalid line detected: ", fpout); es_fputs (line, fpout); es_putc ('\n', fpout); } } else { /* Write out all non CRL lines as they are. */ es_fputs (line, fpout); es_putc ('\n', fpout); } xfree (line); } if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr) { /* Write out the remaining entries. */ for (e= cache->entries; e; e = e->next) if (e->mark) { if (!e->deleted) write_dir_line_crl (fpout, e); e->mark = 0; } } if (lineerr) { err = lineerr; log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } if (es_ferror (fp)) { err = gpg_error_from_errno (errno); log_error (_("error reading '%s': %s\n"), fname, strerror (errno)); } if (es_ferror (fpout)) { err = gpg_error_from_errno (errno); log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno)); } if (err) goto leave; /* Rename the files. */ es_fclose (fp); fp = NULL; if (es_fclose (fpout)) { err = gpg_error_from_errno (errno); log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno)); goto leave; } fpout = NULL; #ifdef HAVE_W32_SYSTEM /* No atomic mv on W32 systems. */ gnupg_remove (fname); #endif if (rename (tmpfname, fname)) { err = gpg_error_from_errno (errno); log_error (_("error renaming '%s' to '%s': %s\n"), tmpfname, fname, strerror (errno)); goto leave; } leave: /* Fixme: Relinquish update lock. */ xfree (line); es_fclose (fp); xfree (fname); if (fpout) { es_fclose (fpout); if (err && tmpfname) gnupg_remove (tmpfname); } xfree (tmpfname); return err; } /* Create the filename for the cache file from the 40 byte ISSUER_HASH string. Caller must release the return string. */ static char * make_db_file_name (const char *issuer_hash) { char bname[50]; assert (strlen (issuer_hash) == 40); memcpy (bname, "crl-", 4); memcpy (bname + 4, issuer_hash, 40); strcpy (bname + 44, ".db"); return make_filename (opt.homedir_cache, DBDIR_D, bname, NULL); } /* Hash the file FNAME and return the MD5 digest in MD5BUFFER. The caller must allocate MD%buffer wityh at least 16 bytes. Returns 0 on success. */ static int hash_dbfile (const char *fname, unsigned char *md5buffer) { estream_t fp; char *buffer; size_t n; gcry_md_hd_t md5; gpg_error_t err; buffer = xtrymalloc (65536); fp = buffer? es_fopen (fname, "rb") : NULL; if (!fp) { log_error (_("can't hash '%s': %s\n"), fname, strerror (errno)); xfree (buffer); return -1; } err = gcry_md_open (&md5, GCRY_MD_MD5, 0); if (err) { log_error (_("error setting up MD5 hash context: %s\n"), gpg_strerror (err)); xfree (buffer); es_fclose (fp); return -1; } /* We better hash some information about the cache file layout in. */ sprintf (buffer, "%.100s/%.100s:%d", DBDIR_D, DBDIRFILE, DBDIRVERSION); gcry_md_write (md5, buffer, strlen (buffer)); for (;;) { n = es_fread (buffer, 1, 65536, fp); if (n < 65536 && es_ferror (fp)) { log_error (_("error hashing '%s': %s\n"), fname, strerror (errno)); xfree (buffer); es_fclose (fp); gcry_md_close (md5); return -1; } if (!n) break; gcry_md_write (md5, buffer, n); } es_fclose (fp); xfree (buffer); gcry_md_final (md5); memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16); gcry_md_close (md5); return 0; } /* Compare the file FNAME against the dexified MD5 hash MD5HASH and return 0 if they match. */ static int check_dbfile (const char *fname, const char *md5hexvalue) { unsigned char buffer1[16], buffer2[16]; if (strlen (md5hexvalue) != 32) { log_error (_("invalid formatted checksum for '%s'\n"), fname); return -1; } unhexify (buffer1, md5hexvalue); if (hash_dbfile (fname, buffer2)) return -1; return memcmp (buffer1, buffer2, 16); } /* Open the cache file for ENTRY. This function implements a caching strategy and might close unused cache files. It is required to use unlock_db_file after using the file. */ static struct cdb * lock_db_file (crl_cache_t cache, crl_cache_entry_t entry) { char *fname; int fd; int open_count; crl_cache_entry_t e; if (entry->cdb) { entry->cdb_use_count++; return entry->cdb; } for (open_count = 0, e = cache->entries; e; e = e->next) { if (e->cdb) open_count++; /* log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */ /* e->cdb,e->cdb_use_count,e->cdb_lru_count); */ } /* If there are too many file open, find the least recent used DB file and close it. Note that for Pth thread safeness we need to use a loop here. */ while (open_count >= MAX_OPEN_DB_FILES ) { crl_cache_entry_t last_e = NULL; unsigned int last_lru = (unsigned int)(-1); for (e = cache->entries; e; e = e->next) if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru) { last_lru = e->cdb_lru_count; last_e = e; } if (!last_e) { log_error (_("too many open cache files; can't open anymore\n")); return NULL; } /* log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */ fd = cdb_fileno (last_e->cdb); cdb_free (last_e->cdb); xfree (last_e->cdb); last_e->cdb = NULL; if (close (fd)) log_error (_("error closing cache file: %s\n"), strerror(errno)); open_count--; } fname = make_db_file_name (entry->issuer_hash); if (opt.verbose) log_info (_("opening cache file '%s'\n"), fname ); if (!entry->dbfile_checked) { if (!check_dbfile (fname, entry->dbfile_hash)) entry->dbfile_checked = 1; /* Note, in case of an error we don't print an error here but let require the caller to do that check. */ } entry->cdb = xtrycalloc (1, sizeof *entry->cdb); if (!entry->cdb) { xfree (fname); return NULL; } fd = gnupg_open (fname, O_RDONLY | O_BINARY, 0); if (fd == -1) { log_error (_("error opening cache file '%s': %s\n"), fname, strerror (errno)); xfree (entry->cdb); entry->cdb = NULL; xfree (fname); return NULL; } if (cdb_init (entry->cdb, fd)) { log_error (_("error initializing cache file '%s' for reading: %s\n"), fname, strerror (errno)); xfree (entry->cdb); entry->cdb = NULL; close (fd); xfree (fname); return NULL; } xfree (fname); entry->cdb_use_count = 1; entry->cdb_lru_count = 0; return entry->cdb; } /* Unlock a cache file, so that it can be reused. */ static void unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry) { if (!entry->cdb) log_error (_("calling unlock_db_file on a closed file\n")); else if (!entry->cdb_use_count) log_error (_("calling unlock_db_file on an unlocked file\n")); else { entry->cdb_use_count--; entry->cdb_lru_count++; } /* If the entry was marked for deletion in the meantime do it now. We do this for the sake of Pth thread safeness. */ if (!entry->cdb_use_count && entry->deleted) { crl_cache_entry_t eprev, enext; enext = entry->next; for (eprev = cache->entries; eprev && eprev->next != entry; eprev = eprev->next) ; assert (eprev); if (eprev == cache->entries) cache->entries = enext; else eprev->next = enext; /* FIXME: Do we leak ENTRY? */ } } /* Find ISSUER_HASH in our cache FIRST. This may be used to enumerate the linked list we use to keep the CRLs of an issuer. */ static crl_cache_entry_t find_entry (crl_cache_entry_t first, const char *issuer_hash) { while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash))) first = first->next; return first; } /* Create a new CRL cache. This function is usually called only once. never fail. */ void crl_cache_init(void) { crl_cache_t cache = NULL; gpg_error_t err; if (current_cache) { log_error ("crl cache has already been initialized - not doing twice\n"); return; } err = open_dir (&cache); if (err) log_fatal (_("failed to create a new cache object: %s\n"), gpg_strerror (err)); current_cache = cache; } /* Remove the cache information and all its resources. Note that we still keep the cache on disk. */ void crl_cache_deinit (void) { if (current_cache) { release_cache (current_cache); current_cache = NULL; } } /* Delete the cache from disk and memory. Return 0 on success.*/ int crl_cache_flush (void) { int rc; crl_cache_deinit (); rc = cleanup_cache_dir (0)? -1 : 0; crl_cache_init (); return rc; } /* Check whether the certificate identified by ISSUER_HASH and SN/SNLEN is valid; i.e. not listed in our cache. With FORCE_REFRESH set to true, a new CRL will be retrieved even if the cache has not yet expired. We use a 30 minutes threshold here so that invoking this function several times won't load the CRL over and over. */ static crl_cache_result_t cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const unsigned char *sn, size_t snlen, int force_refresh) { crl_cache_t cache = get_current_cache (); crl_cache_result_t retval; struct cdb *cdb; int rc; crl_cache_entry_t entry; gnupg_isotime_t current_time; size_t n; (void)ctrl; entry = find_entry (cache->entries, issuer_hash); if (!entry) { log_info (_("no CRL available for issuer id %s\n"), issuer_hash ); return CRL_CACHE_DONTKNOW; } gnupg_get_isotime (current_time); if (strcmp (entry->next_update, current_time) < 0 ) { log_info (_("cached CRL for issuer id %s too old; update required\n"), issuer_hash); return CRL_CACHE_DONTKNOW; } if (force_refresh) { gnupg_isotime_t tmptime; if (*entry->last_refresh) { gnupg_copy_time (tmptime, entry->last_refresh); add_seconds_to_isotime (tmptime, 30 * 60); if (strcmp (tmptime, current_time) < 0 ) { log_info (_("force-crl-refresh active and %d minutes passed for" " issuer id %s; update required\n"), 30, issuer_hash); return CRL_CACHE_DONTKNOW; } } else { log_info (_("force-crl-refresh active for" " issuer id %s; update required\n"), issuer_hash); return CRL_CACHE_DONTKNOW; } } if (entry->invalid) { log_info (_("available CRL for issuer ID %s can't be used\n"), issuer_hash); return CRL_CACHE_CANTUSE; } cdb = lock_db_file (cache, entry); if (!cdb) return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */ if (!entry->dbfile_checked) { log_error (_("cached CRL for issuer id %s tampered; we need to update\n") , issuer_hash); unlock_db_file (cache, entry); return CRL_CACHE_DONTKNOW; } rc = cdb_find (cdb, sn, snlen); if (rc == 1) { n = cdb_datalen (cdb); if (n != 16) { log_error (_("WARNING: invalid cache record length for S/N ")); log_printf ("0x"); log_printhex (sn, snlen, ""); } else if (opt.verbose) { unsigned char record[16]; char *tmp = hexify_data (sn, snlen, 1); if (cdb_read (cdb, record, n, cdb_datapos (cdb))) log_error (_("problem reading cache record for S/N %s: %s\n"), tmp, strerror (errno)); else log_info (_("S/N %s is not valid; reason=%02X date=%.15s\n"), tmp, *record, record+1); xfree (tmp); } retval = CRL_CACHE_INVALID; } else if (!rc) { if (opt.verbose) { char *serialno = hexify_data (sn, snlen, 1); log_info (_("S/N %s is valid, it is not listed in the CRL\n"), serialno ); xfree (serialno); } retval = CRL_CACHE_VALID; } else { log_error (_("error getting data from cache file: %s\n"), strerror (errno)); retval = CRL_CACHE_DONTKNOW; } if (entry->user_trust_req && (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID)) { if (!entry->check_trust_anchor) { log_error ("inconsistent data on user trust check\n"); retval = CRL_CACHE_CANTUSE; } else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor)) { if (opt.verbose) log_info ("no system trust and client does not trust either\n"); retval = CRL_CACHE_CANTUSE; } else { /* Okay, the CRL is considered valid by the client and thus we can return the result as is. */ } } unlock_db_file (cache, entry); return retval; } /* Check whether the certificate identified by ISSUER_HASH and SERIALNO is valid; i.e. not listed in our cache. With FORCE_REFRESH set to true, a new CRL will be retrieved even if the cache has not yet expired. We use a 30 minutes threshold here so that invoking this function several times won't load the CRL over and over. */ crl_cache_result_t crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno, int force_refresh) { crl_cache_result_t result; unsigned char snbuf_buffer[50]; unsigned char *snbuf; size_t n; n = strlen (serialno)/2+1; if (n < sizeof snbuf_buffer - 1) snbuf = snbuf_buffer; else { snbuf = xtrymalloc (n); if (!snbuf) return CRL_CACHE_DONTKNOW; } n = unhexify (snbuf, serialno); result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh); if (snbuf != snbuf_buffer) xfree (snbuf); return result; } /* Check whether the certificate CERT is valid; i.e. not listed in our cache. With FORCE_REFRESH set to true, a new CRL will be retrieved even if the cache has not yet expired. We use a 30 minutes threshold here so that invoking this function several times won't load the CRL over and over. */ gpg_error_t crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert, int force_refresh) { gpg_error_t err; crl_cache_result_t result; unsigned char issuerhash[20]; char issuerhash_hex[41]; ksba_sexp_t serial; unsigned char *sn; size_t snlen; char *endp, *tmp; int i; /* Compute the hash value of the issuer name. */ tmp = ksba_cert_get_issuer (cert, 0); if (!tmp) { log_error ("oops: issuer missing in certificate\n"); return gpg_error (GPG_ERR_INV_CERT_OBJ); } gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp)); xfree (tmp); for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2) sprintf (tmp, "%02X", issuerhash[i]); /* Get the serial number. */ serial = ksba_cert_get_serial (cert); if (!serial) { log_error ("oops: S/N missing in certificate\n"); return gpg_error (GPG_ERR_INV_CERT_OBJ); } sn = serial; if (*sn != '(') { log_error ("oops: invalid S/N\n"); xfree (serial); return gpg_error (GPG_ERR_INV_CERT_OBJ); } sn++; snlen = strtoul (sn, &endp, 10); sn = endp; if (*sn != ':') { log_error ("oops: invalid S/N\n"); xfree (serial); return gpg_error (GPG_ERR_INV_CERT_OBJ); } sn++; /* Check the cache. */ result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh); switch (result) { case CRL_CACHE_VALID: err = 0; break; case CRL_CACHE_INVALID: err = gpg_error (GPG_ERR_CERT_REVOKED); break; case CRL_CACHE_DONTKNOW: err = gpg_error (GPG_ERR_NO_CRL_KNOWN); break; case CRL_CACHE_CANTUSE: err = gpg_error (GPG_ERR_NO_CRL_KNOWN); break; default: log_fatal ("cache_isvalid returned invalid status code %d\n", result); } xfree (serial); return err; } /* Return the hash algorithm's algo id from its name given in the * non-null termnated string in (buffer,buflen). Returns 0 on failure * or if the algo is not known. */ static int hash_algo_from_buffer (const void *buffer, size_t buflen) { char *string; int algo; string = xtrymalloc (buflen + 1); if (!string) { log_error (_("out of core\n")); return 0; } memcpy (string, buffer, buflen); string[buflen] = 0; algo = gcry_md_map_name (string); if (!algo) log_error ("unknown digest algorithm '%s' used in certificate\n", string); xfree (string); return algo; } /* Return an unsigned integer from the non-null termnated string * (buffer,buflen). Returns 0 on failure. */ static unsigned int uint_from_buffer (const void *buffer, size_t buflen) { char *string; unsigned int val; string = xtrymalloc (buflen + 1); if (!string) { log_error (_("out of core\n")); return 0; } memcpy (string, buffer, buflen); string[buflen] = 0; val = strtoul (string, NULL, 10); xfree (string); return val; } /* Prepare a hash context for the signature verification. Input is the CRL and the output is the hash context MD as well as the uses algorithm identifier ALGO. */ static gpg_error_t start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo, int *use_pss) { gpg_error_t err; const char *algoid; *use_pss = 0; algoid = ksba_crl_get_digest_algo (crl); if (algoid && !strcmp (algoid, "1.2.840.113549.1.1.10")) { /* Parse rsaPSS parameter. */ gcry_buffer_t ioarray[1] = { {0} }; ksba_sexp_t pssparam; size_t n; gcry_sexp_t psssexp; pssparam = ksba_crl_get_sig_val (crl); n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL); if (!n) { ksba_free (pssparam); log_error (_("got an invalid S-expression from libksba\n")); return gpg_error (GPG_ERR_INV_SEXP); } err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n); ksba_free (pssparam); if (err) { log_error (_("converting S-expression failed: %s\n"), gcry_strerror (err)); return err; } err = gcry_sexp_extract_param (psssexp, "sig-val", "&'hash-algo'", ioarray, NULL); gcry_sexp_release (psssexp); if (err) { log_error ("extracting params from PSS failed: %s\n", gpg_strerror (err)); return err; } *algo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len); xfree (ioarray[0].data); *use_pss = 1; } else *algo = gcry_md_map_name (algoid); if (!*algo) { log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?"); return gpg_error (GPG_ERR_DIGEST_ALGO); } err = gcry_md_open (md, *algo, 0); if (err) { log_error (_("gcry_md_open for algorithm %d failed: %s\n"), *algo, gcry_strerror (err)); return err; } if (DBG_HASHING) gcry_md_debug (*md, "hash.cert"); ksba_crl_set_hash_function (crl, HASH_FNC, *md); return 0; } /* Finish a hash context and verify the signature. This function should return 0 on a good signature, GPG_ERR_BAD_SIGNATURE if the signature does not verify or any other error code. CRL is the CRL object we are working on, MD the hash context and ISSUER_CERT the certificate of the CRL issuer. This function takes ownership of MD. */ static gpg_error_t finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo, ksba_cert_t issuer_cert, int use_pss) { gpg_error_t err; ksba_sexp_t sigval = NULL, pubkey = NULL; size_t n; gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL; unsigned int saltlen = 0; /* (used only with use_pss) */ /* This also stops debugging on the MD. */ gcry_md_final (md); /* Get and convert the signature value. */ sigval = ksba_crl_get_sig_val (crl); n = gcry_sexp_canon_len (sigval, 0, NULL, NULL); if (!n) { log_error (_("got an invalid S-expression from libksba\n")); err = gpg_error (GPG_ERR_INV_SEXP); goto leave; } err = gcry_sexp_sscan (&s_sig, NULL, sigval, n); if (err) { log_error (_("converting S-expression failed: %s\n"), gcry_strerror (err)); goto leave; } if (use_pss) { /* Parse rsaPSS parameter which we should find in S_SIG. */ gcry_buffer_t ioarray[2] = { {0}, {0} }; ksba_sexp_t pssparam; gcry_sexp_t psssexp; int hashalgo; pssparam = ksba_crl_get_sig_val (crl); n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL); if (!n) { ksba_free (pssparam); log_error (_("got an invalid S-expression from libksba\n")); err = gpg_error (GPG_ERR_INV_SEXP); goto leave; } err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n); ksba_free (pssparam); if (err) { log_error (_("converting S-expression failed: %s\n"), gcry_strerror (err)); goto leave; } err = gcry_sexp_extract_param (psssexp, "sig-val", "&'hash-algo''salt-length'", ioarray+0, ioarray+1, NULL); gcry_sexp_release (psssexp); if (err) { log_error ("extracting params from PSS failed: %s\n", gpg_strerror (err)); goto leave; } hashalgo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len); saltlen = uint_from_buffer (ioarray[1].data, ioarray[1].len); xfree (ioarray[0].data); xfree (ioarray[1].data); if (hashalgo != algo) { log_error ("hash algo mismatch: %d announced but %d used\n", algo, hashalgo); return gpg_error (GPG_ERR_INV_CRL); } /* Add some restrictions; see ../sm/certcheck.c for details. */ switch (algo) { case GCRY_MD_SHA1: case GCRY_MD_SHA256: case GCRY_MD_SHA384: case GCRY_MD_SHA512: case GCRY_MD_SHA3_256: case GCRY_MD_SHA3_384: case GCRY_MD_SHA3_512: break; default: log_error ("PSS hash algorithm '%s' rejected\n", gcry_md_algo_name (algo)); return gpg_error (GPG_ERR_DIGEST_ALGO); } if (gcry_md_get_algo_dlen (algo) != saltlen) { log_error ("PSS hash algorithm '%s' rejected due to salt length %u\n", gcry_md_algo_name (algo), saltlen); return gpg_error (GPG_ERR_DIGEST_ALGO); } } /* Get and convert the public key for the issuer certificate. */ if (DBG_X509) dump_cert ("crl_issuer_cert", issuer_cert); pubkey = ksba_cert_get_public_key (issuer_cert); n = gcry_sexp_canon_len (pubkey, 0, NULL, NULL); if (!n) { log_error (_("got an invalid S-expression from libksba\n")); err = gpg_error (GPG_ERR_INV_SEXP); goto leave; } err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n); if (err) { log_error (_("converting S-expression failed: %s\n"), gcry_strerror (err)); goto leave; } /* Create an S-expression with the actual hash value. */ if (use_pss) { err = gcry_sexp_build (&s_hash, NULL, "(data (flags pss)" "(hash %s %b)" "(salt-length %u))", hash_algo_to_string (algo), (int)gcry_md_get_algo_dlen (algo), gcry_md_read (md, algo), saltlen); } else { err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))", hash_algo_to_string (algo), (int)gcry_md_get_algo_dlen (algo), gcry_md_read (md, algo)); } if (err) { log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err)); goto leave; } /* Pass this on to the signature verification. */ err = gcry_pk_verify (s_sig, s_hash, s_pkey); if (DBG_X509) log_debug ("gcry_pk_verify: %s\n", gpg_strerror (err)); leave: xfree (sigval); xfree (pubkey); gcry_sexp_release (s_sig); gcry_sexp_release (s_hash); gcry_sexp_release (s_pkey); gcry_md_close (md); return err; } /* Call this to match a start_sig_check that can not be completed normally. Takes ownership of MD if MD is not NULL. */ static void abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md) { (void)crl; if (md) gcry_md_close (md); } /* Workhorse of the CRL loading machinery. The CRL is read using the CRL object and stored in the data base file DB with the name FNAME (only used for printing error messages). That DB should be a temporary one and not the actual one. If the function fails the caller should delete this temporary database file. CTRL is required to retrieve certificates using the general dirmngr callback service. R_CRLISSUER returns an allocated string with the crl-issuer DN, THIS_UPDATE and NEXT_UPDATE are filled with the corresponding data from the CRL. Note that these values might get set even if the CRL processing fails at a later step; thus the caller should free *R_ISSUER even if the function returns with an error. R_TRUST_ANCHOR is set on exit to NULL or a string with the hexified fingerprint of the root certificate, if checking this certificate for trustiness is required. */ static int crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl, struct cdb_make *cdb, const char *fname, char **r_crlissuer, ksba_isotime_t thisupdate, ksba_isotime_t nextupdate, char **r_trust_anchor) { gpg_error_t err; ksba_stop_reason_t stopreason; ksba_cert_t crlissuer_cert = NULL; gcry_md_hd_t md = NULL; int algo = 0; int use_pss = 0; size_t n; (void)fname; *r_crlissuer = NULL; *thisupdate = *nextupdate = 0; *r_trust_anchor = NULL; /* Start of the KSBA parser loop. */ do { err = ksba_crl_parse (crl, &stopreason); if (err) { log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) ); goto failure; } switch (stopreason) { case KSBA_SR_BEGIN_ITEMS: { err = start_sig_check (crl, &md, &algo, &use_pss); if (err) goto failure; err = ksba_crl_get_update_times (crl, thisupdate, nextupdate); if (err) { log_error (_("error getting update times of CRL: %s\n"), gpg_strerror (err)); err = gpg_error (GPG_ERR_INV_CRL); goto failure; } if (opt.verbose || !*nextupdate) log_info (_("update times of this CRL: this=%s next=%s\n"), thisupdate, nextupdate); if (!*nextupdate) { log_info (_("nextUpdate not given; " "assuming a validity period of one day\n")); gnupg_copy_time (nextupdate, thisupdate); add_seconds_to_isotime (nextupdate, 86400); } } break; case KSBA_SR_GOT_ITEM: { ksba_sexp_t serial; const unsigned char *p; ksba_isotime_t rdate; ksba_crl_reason_t reason; int rc; unsigned char record[1+15]; err = ksba_crl_get_item (crl, &serial, rdate, &reason); if (err) { log_error (_("error getting CRL item: %s\n"), gpg_strerror (err)); err = gpg_error (GPG_ERR_INV_CRL); ksba_free (serial); goto failure; } p = serial_to_buffer (serial, &n); if (!p) BUG (); record[0] = (reason & 0xff); memcpy (record+1, rdate, 15); rc = cdb_make_add (cdb, p, n, record, 1+15); if (rc) { err = gpg_error_from_errno (errno); log_error (_("error inserting item into " "temporary cache file: %s\n"), strerror (errno)); goto failure; } ksba_free (serial); } break; case KSBA_SR_END_ITEMS: break; case KSBA_SR_READY: { char *crlissuer; ksba_name_t authid; ksba_sexp_t authidsn; ksba_sexp_t keyid; /* We need to look for the issuer only after having read all items. The issuer itself comes before the items but the optional authorityKeyIdentifier comes after the items. */ err = ksba_crl_get_issuer (crl, &crlissuer); if( err ) { log_error (_("no CRL issuer found in CRL: %s\n"), gpg_strerror (err) ); err = gpg_error (GPG_ERR_INV_CRL); goto failure; } /* Note: This should be released by ksba_free, not xfree. May need a memory reallocation dance. */ *r_crlissuer = crlissuer; /* (Do it here so we don't need to free it later) */ if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn)) { const char *s; if (opt.verbose) log_info (_("locating CRL issuer certificate by " "authorityKeyIdentifier\n")); s = ksba_name_enum (authid, 0); if (s && *authidsn) crlissuer_cert = find_cert_bysn (ctrl, s, authidsn); if (!crlissuer_cert && keyid) crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, keyid); if (!crlissuer_cert) { log_info ("CRL issuer certificate "); if (keyid) { log_printf ("{"); dump_serial (keyid); log_printf ("} "); } if (authidsn) { log_printf ("(#"); dump_serial (authidsn); log_printf ("/"); dump_string (s); log_printf (") "); } log_printf ("not found\n"); } ksba_name_release (authid); xfree (authidsn); xfree (keyid); } else crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL); err = 0; if (!crlissuer_cert) { err = gpg_error (GPG_ERR_MISSING_CERT); goto failure; } err = finish_sig_check (crl, md, algo, crlissuer_cert, use_pss); md = NULL; /* Closed. */ if (err) { log_error (_("CRL signature verification failed: %s\n"), gpg_strerror (err)); goto failure; } err = validate_cert_chain (ctrl, crlissuer_cert, NULL, (VALIDATE_FLAG_TRUST_CONFIG | VALIDATE_FLAG_CRL | VALIDATE_FLAG_RECURSIVE), r_trust_anchor); if (err) { log_error (_("error checking validity of CRL " "issuer certificate: %s\n"), gpg_strerror (err)); goto failure; } } break; default: log_debug ("crl_parse_insert: unknown stop reason\n"); err = gpg_error (GPG_ERR_BUG); goto failure; } } while (stopreason != KSBA_SR_READY); assert (!err); failure: abort_sig_check (crl, md); ksba_cert_release (crlissuer_cert); return err; } /* Return the crlNumber extension as an allocated hex string or NULL if there is none. */ static char * get_crl_number (ksba_crl_t crl) { gpg_error_t err; ksba_sexp_t number; char *string; err = ksba_crl_get_crl_number (crl, &number); if (err) return NULL; string = serial_hex (number); ksba_free (number); return string; } /* Return the authorityKeyIdentifier or NULL if it is not available. The issuer name may consists of several parts - they are delimited by 0x01. */ static char * get_auth_key_id (ksba_crl_t crl, char **serialno) { gpg_error_t err; ksba_name_t name; ksba_sexp_t sn; int idx; const char *s; char *string; size_t length; *serialno = NULL; err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn); if (err) return NULL; *serialno = serial_hex (sn); ksba_free (sn); if (!name) return xstrdup (""); length = 0; for (idx=0; (s = ksba_name_enum (name, idx)); idx++) { char *p = ksba_name_get_uri (name, idx); length += strlen (p?p:s) + 1; xfree (p); } string = xtrymalloc (length+1); if (string) { *string = 0; for (idx=0; (s = ksba_name_enum (name, idx)); idx++) { char *p = ksba_name_get_uri (name, idx); if (*string) strcat (string, "\x01"); strcat (string, p?p:s); xfree (p); } } ksba_name_release (name); return string; } /* Insert the CRL retrieved using URL into the cache specified by CACHE. The CRL itself will be read from the stream FP and is expected in binary format. Called by: crl_cache_load cmd_loadcrl --load-crl crl_cache_reload_crl cmd_isvalid cmd_checkcrl cmd_loadcrl --fetch-crl */ gpg_error_t crl_cache_insert (ctrl_t ctrl, const char *url, ksba_reader_t reader) { crl_cache_t cache = get_current_cache (); gpg_error_t err, err2; ksba_crl_t crl; char *fname = NULL; char *newfname = NULL; struct cdb_make cdb; int fd_cdb = -1; char *issuer = NULL; char *issuer_hash = NULL; ksba_isotime_t thisupdate, nextupdate; crl_cache_entry_t entry = NULL; crl_cache_entry_t e; gnupg_isotime_t current_time; char *checksum = NULL; int invalidate_crl = 0; int idx; const char *oid; int critical; char *trust_anchor = NULL; /* FIXME: We should acquire a mutex for the URL, so that we don't simultaneously enter the same CRL twice. However this needs to be interweaved with the checking function.*/ err2 = 0; err = ksba_crl_new (&crl); if (err) { log_error (_("ksba_crl_new failed: %s\n"), gpg_strerror (err)); goto leave; } err = ksba_crl_set_reader (crl, reader); if ( err ) { log_error (_("ksba_crl_set_reader failed: %s\n"), gpg_strerror (err)); goto leave; } /* Create a temporary cache file to load the CRL into. */ { char *tmpfname, *p; const char *nodename; #ifndef HAVE_W32_SYSTEM struct utsname utsbuf; #endif #ifdef HAVE_W32_SYSTEM nodename = "unknown"; #else if (uname (&utsbuf)) nodename = "unknown"; else nodename = utsbuf.nodename; #endif gpgrt_asprintf (&tmpfname, "crl-tmp-%s-%u-%p.db.tmp", nodename, (unsigned int)getpid (), &tmpfname); if (!tmpfname) { err = gpg_error_from_syserror (); goto leave; } for (p=tmpfname; *p; p++) if (*p == '/') *p = '.'; fname = make_filename (opt.homedir_cache, DBDIR_D, tmpfname, NULL); xfree (tmpfname); if (!gnupg_remove (fname)) log_info (_("removed stale temporary cache file '%s'\n"), fname); else if (errno != ENOENT) { err = gpg_error_from_syserror (); log_error (_("problem removing stale temporary cache file '%s': %s\n"), fname, gpg_strerror (err)); goto leave; } } fd_cdb = gnupg_open (fname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644); if (fd_cdb == -1) { err = gpg_error_from_errno (errno); log_error (_("error creating temporary cache file '%s': %s\n"), fname, strerror (errno)); goto leave; } cdb_make_start(&cdb, fd_cdb); err = crl_parse_insert (ctrl, crl, &cdb, fname, &issuer, thisupdate, nextupdate, &trust_anchor); if (err) { log_error (_("crl_parse_insert failed: %s\n"), gpg_strerror (err)); /* Error in cleanup ignored. */ cdb_make_finish (&cdb); goto leave; } /* Finish the database. */ if (cdb_make_finish (&cdb)) { err = gpg_error_from_errno (errno); log_error (_("error finishing temporary cache file '%s': %s\n"), fname, strerror (errno)); goto leave; } if (close (fd_cdb)) { err = gpg_error_from_errno (errno); log_error (_("error closing temporary cache file '%s': %s\n"), fname, strerror (errno)); goto leave; } fd_cdb = -1; /* Create a checksum. */ { unsigned char md5buf[16]; if (hash_dbfile (fname, md5buf)) { err = gpg_error (GPG_ERR_CHECKSUM); goto leave; } checksum = hexify_data (md5buf, 16, 0); } /* Check whether that new CRL is still not expired. */ gnupg_get_isotime (current_time); if (strcmp (nextupdate, current_time) < 0 ) { if (opt.force) log_info (_("WARNING: new CRL still too old; it expired on %s " "- loading anyway\n"), nextupdate); else { log_error (_("new CRL still too old; it expired on %s\n"), nextupdate); if (!err2) err2 = gpg_error (GPG_ERR_CRL_TOO_OLD); invalidate_crl |= 1; } } /* Check for unknown critical extensions. */ for (idx=0; !(err=ksba_crl_get_extension (crl, idx, &oid, &critical, NULL, NULL)); idx++) { if (!critical || !strcmp (oid, oidstr_authorityKeyIdentifier) || !strcmp (oid, oidstr_crlNumber) ) continue; log_error (_("unknown critical CRL extension %s\n"), oid); if (!err2) err2 = gpg_error (GPG_ERR_INV_CRL); invalidate_crl |= 2; } if (gpg_err_code (err) == GPG_ERR_EOF || gpg_err_code (err) == GPG_ERR_NO_DATA ) err = 0; if (err) { log_error (_("error reading CRL extensions: %s\n"), gpg_strerror (err)); err = gpg_error (GPG_ERR_INV_CRL); } /* Create an hex encoded SHA-1 hash of the issuer DN to be used as the key for the cache. */ issuer_hash = hashify_data (issuer, strlen (issuer)); /* Create an ENTRY. */ entry = xtrycalloc (1, sizeof *entry); if (!entry) { err = gpg_error_from_syserror (); goto leave; } entry->release_ptr = xtrymalloc (strlen (issuer_hash) + 1 + strlen (issuer) + 1 + strlen (url) + 1 + strlen (checksum) + 1); if (!entry->release_ptr) { err = gpg_error_from_syserror (); xfree (entry); entry = NULL; goto leave; } entry->issuer_hash = entry->release_ptr; entry->issuer = stpcpy (entry->issuer_hash, issuer_hash) + 1; entry->url = stpcpy (entry->issuer, issuer) + 1; entry->dbfile_hash = stpcpy (entry->url, url) + 1; strcpy (entry->dbfile_hash, checksum); gnupg_copy_time (entry->this_update, thisupdate); gnupg_copy_time (entry->next_update, nextupdate); gnupg_copy_time (entry->last_refresh, current_time); entry->crl_number = get_crl_number (crl); entry->authority_issuer = get_auth_key_id (crl, &entry->authority_serialno); entry->invalid = invalidate_crl; entry->user_trust_req = !!trust_anchor; entry->check_trust_anchor = trust_anchor; trust_anchor = NULL; /* Check whether we already have an entry for this issuer and mark it as deleted. We better use a loop, just in case duplicates got somehow into the list. */ for (e = cache->entries; (e=find_entry (e, entry->issuer_hash)); e = e->next) e->deleted = 1; /* Rename the temporary DB to the real name. */ newfname = make_db_file_name (entry->issuer_hash); if (opt.verbose) log_info (_("creating cache file '%s'\n"), newfname); /* Just in case close unused matching files. Actually we need this only under Windows but saving file descriptors is never bad. */ { int any; do { any = 0; for (e = cache->entries; e; e = e->next) if (!e->cdb_use_count && e->cdb && !strcmp (e->issuer_hash, entry->issuer_hash)) { int fd = cdb_fileno (e->cdb); cdb_free (e->cdb); xfree (e->cdb); e->cdb = NULL; if (close (fd)) log_error (_("error closing cache file: %s\n"), strerror(errno)); any = 1; break; } } while (any); } #ifdef HAVE_W32_SYSTEM gnupg_remove (newfname); #endif if (rename (fname, newfname)) { err = gpg_error_from_syserror (); log_error (_("problem renaming '%s' to '%s': %s\n"), fname, newfname, gpg_strerror (err)); goto leave; } xfree (fname); fname = NULL; /*(let the cleanup code not try to remove it)*/ /* Link the new entry in. */ entry->next = cache->entries; cache->entries = entry; entry = NULL; err = update_dir (cache); if (err) { log_error (_("updating the DIR file failed - " "cache entry will get lost with the next program start\n")); err = 0; /* Keep on running. */ } leave: release_one_cache_entry (entry); if (fd_cdb != -1) close (fd_cdb); if (fname) { gnupg_remove (fname); xfree (fname); } xfree (newfname); ksba_crl_release (crl); xfree (issuer); xfree (issuer_hash); xfree (checksum); xfree (trust_anchor); return err ? err : err2; } /* Print one cached entry E in a human readable format to stream FP. Return 0 on success. */ static gpg_error_t list_one_crl_entry (crl_cache_t cache, crl_cache_entry_t e, estream_t fp) { struct cdb_find cdbfp; struct cdb *cdb; int rc; int warn = 0; const unsigned char *s; es_fputs ("--------------------------------------------------------\n", fp ); es_fprintf (fp, _("Begin CRL dump (retrieved via %s)\n"), e->url ); es_fprintf (fp, " Issuer:\t%s\n", e->issuer ); es_fprintf (fp, " Issuer Hash:\t%s\n", e->issuer_hash ); es_fprintf (fp, " This Update:\t%s\n", e->this_update ); es_fprintf (fp, " Next Update:\t%s\n", e->next_update ); es_fprintf (fp, " CRL Number :\t%s\n", e->crl_number? e->crl_number: "none"); es_fprintf (fp, " AuthKeyId :\t%s\n", e->authority_serialno? e->authority_serialno:"none"); if (e->authority_serialno && e->authority_issuer) { es_fputs (" \t", fp); for (s=e->authority_issuer; *s; s++) if (*s == '\x01') es_fputs ("\n \t", fp); else es_putc (*s, fp); es_putc ('\n', fp); } es_fprintf (fp, " Trust Check:\t%s\n", !e->user_trust_req? "[system]" : e->check_trust_anchor? e->check_trust_anchor:"[missing]"); if ((e->invalid & 1)) es_fprintf (fp, _(" ERROR: The CRL will not be used " "because it was still too old after an update!\n")); if ((e->invalid & 2)) es_fprintf (fp, _(" ERROR: The CRL will not be used " "due to an unknown critical extension!\n")); if ((e->invalid & ~3)) es_fprintf (fp, _(" ERROR: The CRL will not be used\n")); cdb = lock_db_file (cache, e); if (!cdb) return gpg_error (GPG_ERR_GENERAL); if (!e->dbfile_checked) es_fprintf (fp, _(" ERROR: This cached CRL may have been tampered with!\n")); es_putc ('\n', fp); rc = cdb_findinit (&cdbfp, cdb, NULL, 0); while (!rc && (rc=cdb_findnext (&cdbfp)) > 0 ) { unsigned char keyrecord[256]; unsigned char record[16]; int reason; int any = 0; cdbi_t n; cdbi_t i; rc = 0; n = cdb_datalen (cdb); if (n != 16) { log_error (_(" WARNING: invalid cache record length\n")); warn = 1; continue; } if (cdb_read (cdb, record, n, cdb_datapos (cdb))) { log_error (_("problem reading cache record: %s\n"), strerror (errno)); warn = 1; continue; } n = cdb_keylen (cdb); if (n > sizeof keyrecord) n = sizeof keyrecord; if (cdb_read (cdb, keyrecord, n, cdb_keypos (cdb))) { log_error (_("problem reading cache key: %s\n"), strerror (errno)); warn = 1; continue; } reason = *record; es_fputs (" ", fp); for (i = 0; i < n; i++) es_fprintf (fp, "%02X", keyrecord[i]); es_fputs (":\t reasons( ", fp); if (reason & KSBA_CRLREASON_UNSPECIFIED) es_fputs( "unspecified ", fp ), any = 1; if (reason & KSBA_CRLREASON_KEY_COMPROMISE ) es_fputs( "key_compromise ", fp ), any = 1; if (reason & KSBA_CRLREASON_CA_COMPROMISE ) es_fputs( "ca_compromise ", fp ), any = 1; if (reason & KSBA_CRLREASON_AFFILIATION_CHANGED ) es_fputs( "affiliation_changed ", fp ), any = 1; if (reason & KSBA_CRLREASON_SUPERSEDED ) es_fputs( "superseded", fp ), any = 1; if (reason & KSBA_CRLREASON_CESSATION_OF_OPERATION ) es_fputs( "cessation_of_operation", fp ), any = 1; if (reason & KSBA_CRLREASON_CERTIFICATE_HOLD ) es_fputs( "certificate_hold", fp ), any = 1; if (reason && !any) es_fputs( "other", fp ); es_fprintf (fp, ") rdate: %.15s\n", record+1); } if (rc) log_error (_("error reading cache entry from db: %s\n"), strerror (rc)); unlock_db_file (cache, e); es_fprintf (fp, _("End CRL dump\n") ); es_putc ('\n', fp); return (rc||warn)? gpg_error (GPG_ERR_GENERAL) : 0; } /* Print the contents of the CRL CACHE in a human readable format to stream FP. */ gpg_error_t crl_cache_list (estream_t fp) { crl_cache_t cache = get_current_cache (); crl_cache_entry_t entry; gpg_error_t err = 0; for (entry = cache->entries; entry && !entry->deleted && !err; entry = entry->next ) err = list_one_crl_entry (cache, entry, fp); return err; } /* Load the CRL containing the file named FILENAME into our CRL cache. */ gpg_error_t crl_cache_load (ctrl_t ctrl, const char *filename) { gpg_error_t err; estream_t fp; ksba_reader_t reader; fp = es_fopen (filename, "rb"); if (!fp) { err = gpg_error_from_errno (errno); log_error (_("can't open '%s': %s\n"), filename, strerror (errno)); return err; } err = create_estream_ksba_reader (&reader, fp); if (!err) { err = crl_cache_insert (ctrl, filename, reader); ksba_reader_release (reader); } es_fclose (fp); return err; } /* Locate the corresponding CRL for the certificate CERT, read and verify the CRL and store it in the cache. */ gpg_error_t crl_cache_reload_crl (ctrl_t ctrl, ksba_cert_t cert) { gpg_error_t err; ksba_reader_t reader = NULL; char *issuer = NULL; ksba_name_t distpoint = NULL; ksba_name_t issuername = NULL; char *distpoint_uri = NULL; char *issuername_uri = NULL; int any_dist_point = 0; int seq; /* Loop over all distribution points, get the CRLs and put them into the cache. */ if (opt.verbose) log_info ("checking distribution points\n"); seq = 0; while ( !(err = ksba_cert_get_crl_dist_point (cert, seq++, &distpoint, &issuername, NULL ))) { int name_seq; gpg_error_t last_err = 0; if (!distpoint && !issuername) { if (opt.verbose) log_info ("no issuer name and no distribution point\n"); break; /* Not allowed; i.e. an invalid certificate. We give up here and hope that the default method returns a suitable CRL. */ } xfree (issuername_uri); issuername_uri = NULL; /* Get the URIs. We do this in a loop to iterate over all names in the crlDP. */ for (name_seq=0; ksba_name_enum (distpoint, name_seq); name_seq++) { xfree (distpoint_uri); distpoint_uri = NULL; distpoint_uri = ksba_name_get_uri (distpoint, name_seq); if (!distpoint_uri) continue; if (!strncmp (distpoint_uri, "ldap:", 5) || !strncmp (distpoint_uri, "ldaps:", 6)) { if (opt.ignore_ldap_dp) continue; } else if (!strncmp (distpoint_uri, "http:", 5) || !strncmp (distpoint_uri, "https:", 6)) { if (opt.ignore_http_dp) continue; } else continue; /* Skip unknown schemes. */ any_dist_point = 1; if (opt.verbose) log_info ("fetching CRL from '%s'\n", distpoint_uri); err = crl_fetch (ctrl, distpoint_uri, &reader); if (err) { log_error (_("crl_fetch via DP failed: %s\n"), gpg_strerror (err)); last_err = err; continue; /* with the next name. */ } if (opt.verbose) log_info ("inserting CRL (reader %p)\n", reader); err = crl_cache_insert (ctrl, distpoint_uri, reader); if (err) { log_error (_("crl_cache_insert via DP failed: %s\n"), gpg_strerror (err)); last_err = err; continue; /* with the next name. */ } last_err = 0; break; /* Ready. */ } if (last_err) { err = last_err; goto leave; } ksba_name_release (distpoint); distpoint = NULL; /* We don't do anything with issuername_uri yet but we keep the code for documentation. */ issuername_uri = ksba_name_get_uri (issuername, 0); ksba_name_release (issuername); issuername = NULL; /* Close the reader. */ crl_close_reader (reader); reader = NULL; } if (gpg_err_code (err) == GPG_ERR_EOF) err = 0; /* If we did not found any distpoint, try something reasonable. */ if (!any_dist_point ) { if (opt.verbose) log_info ("no distribution point - trying issuer name\n"); crl_close_reader (reader); reader = NULL; issuer = ksba_cert_get_issuer (cert, 0); if (!issuer) { log_error ("oops: issuer missing in certificate\n"); err = gpg_error (GPG_ERR_INV_CERT_OBJ); goto leave; } if (opt.verbose) log_info ("fetching CRL from default location\n"); err = crl_fetch_default (ctrl, issuer, &reader); if (err) { log_error ("crl_fetch via issuer failed: %s\n", gpg_strerror (err)); goto leave; } if (opt.verbose) log_info ("inserting CRL (reader %p)\n", reader); err = crl_cache_insert (ctrl, "default location(s)", reader); if (err) { log_error (_("crl_cache_insert via issuer failed: %s\n"), gpg_strerror (err)); goto leave; } } leave: crl_close_reader (reader); xfree (distpoint_uri); xfree (issuername_uri); ksba_name_release (distpoint); ksba_name_release (issuername); ksba_free (issuer); return err; } diff --git a/dirmngr/dirmngr.c b/dirmngr/dirmngr.c index 838ab9487..06bb4bae6 100644 --- a/dirmngr/dirmngr.c +++ b/dirmngr/dirmngr.c @@ -1,2395 +1,2395 @@ /* dirmngr.c - Keyserver and X.509 LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003-2004, 2006-2007, 2008, 2010-2011, 2020 g10 Code GmbH * 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 #ifndef HAVE_W32_SYSTEM #include #include #endif #include #include #ifdef HAVE_SIGNAL_H # include #endif #ifdef HAVE_INOTIFY_INIT # include #endif /*HAVE_INOTIFY_INIT*/ #include #include "dirmngr-err.h" #if HTTP_USE_NTBTLS # include #elif HTTP_USE_GNUTLS # include #endif /*HTTP_USE_GNUTLS*/ #define INCLUDED_BY_MAIN_MODULE 1 #define GNUPG_COMMON_NEED_AFLOCAL #include "dirmngr.h" #include #include "certcache.h" #include "crlcache.h" #include "crlfetch.h" #include "misc.h" #if USE_LDAP # include "ldapserver.h" #endif #include "../common/asshelp.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "../common/init.h" #include "../common/gc-opt-flags.h" #include "dns-stuff.h" #include "http-common.h" #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aServer, aDaemon, aSupervised, aListCRLs, aLoadCRL, aFetchCRL, aShutdown, aFlush, aGPGConfList, aGPGConfTest, aGPGConfVersions, oOptions, oDebug, oDebugAll, oDebugWait, oDebugLevel, oGnutlsDebug, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oLogFile, oBatch, oDisableHTTP, oDisableLDAP, oDisableIPv4, oDisableIPv6, oIgnoreLDAPDP, oIgnoreHTTPDP, oIgnoreOCSPSvcUrl, oHonorHTTPProxy, oHTTPProxy, oLDAPProxy, oOnlyLDAPProxy, oLDAPFile, oLDAPTimeout, oLDAPAddServers, oOCSPResponder, oOCSPSigner, oOCSPMaxClockSkew, oOCSPMaxPeriod, oOCSPCurrentPeriod, oMaxReplies, oHkpCaCert, oFakedSystemTime, oForce, oAllowOCSP, oAllowVersionCheck, oSocketName, oLDAPWrapperProgram, oHTTPWrapperProgram, oIgnoreCertExtension, oUseTor, oNoUseTor, oKeyServer, oNameServer, oDisableCheckOwnSocket, oStandardResolver, oRecursiveResolver, oResolverTimeout, oConnectTimeout, oConnectQuickTimeout, oListenBacklog, aTest }; static gpgrt_opt_t opts[] = { ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"), ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ), ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ), #ifndef HAVE_W32_SYSTEM ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")), ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")), ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")), ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")), ARGPARSE_c (aFlush, "flush", N_("flush the cache")), ARGPARSE_header (NULL, N_("Options used for startup")), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_noconffile (oNoOptions, "no-options", "@"), ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"), ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write server mode logs to FILE")), ARGPARSE_header ("Configuration", N_("Options controlling the configuration")), ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check", N_("allow online software version check")), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), ARGPARSE_s_i (oMaxReplies, "max-replies", N_("|N|do not return more than N items in one query")), ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/ ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"), ARGPARSE_header ("Network", N_("Network related options")), ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")), ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"), ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"), ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"), ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"), ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"), ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"), ARGPARSE_s_s (oNameServer, "nameserver", "@"), ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"), ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"), ARGPARSE_header ("Keyserver", N_("Configuration for Keyservers")), ARGPARSE_s_s (oKeyServer, "keyserver", N_("|URL|use keyserver at URL")), ARGPARSE_s_s (oHkpCaCert, "hkp-cacert", N_("|FILE|use the CA certificates in FILE for HKP over TLS")), ARGPARSE_header ("HTTP", N_("Configuration for HTTP servers")), ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")), ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp", N_("ignore HTTP CRL distribution points")), ARGPARSE_s_s (oHTTPProxy, "http-proxy", N_("|URL|redirect all HTTP requests to URL")), ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", N_("use system's HTTP proxy setting")), ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"), ARGPARSE_header ("LDAP", N_("Configuration of LDAP servers to use")), ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")), ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp", N_("ignore LDAP CRL distribution points")), ARGPARSE_s_s (oLDAPProxy, "ldap-proxy", N_("|HOST|use HOST for LDAP queries")), ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy", N_("do not use fallback hosts with --ldap-proxy")), ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file", N_("|FILE|read LDAP server list from FILE")), ARGPARSE_s_n (oLDAPAddServers, "add-servers", N_("add new servers discovered in CRL distribution" " points to serverlist")), ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout", N_("|N|set LDAP timeout to N seconds")), ARGPARSE_header ("OCSP", N_("Configuration for OCSP")), ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")), ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url", N_("ignore certificate contained OCSP service URLs")), ARGPARSE_s_s (oOCSPResponder, "ocsp-responder", N_("|URL|use OCSP responder at URL")), ARGPARSE_s_s (oOCSPSigner, "ocsp-signer", N_("|FPR|OCSP response signed by FPR")), ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"), ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"), ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"), ARGPARSE_header (NULL, N_("Other options")), ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")), ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */ ARGPARSE_header (NULL, ""), /* Stop the header group. */ /* Not yet used options. */ ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"), ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing " "of all commands and options)\n")), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_X509_VALUE , "x509" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { DBG_DNS_VALUE , "dns" }, { DBG_NETWORK_VALUE, "network" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_MAX_REPLIES 10 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */ #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */ #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */ /* For the cleanup handler we need to keep track of the socket's name. */ static const char *socket_name; /* If the socket has been redirected, this is the name of the redirected socket.. */ static const char *redir_socket_name; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; /* Value for the listen() backlog argument. * Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Only if this flag has been set will we remove the socket file. */ static int cleanup_socket; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* Helper to implement --debug-level. */ static const char *debug_level; /* Helper to set the NTBTLS or GNUTLS log level. */ static int opt_gnutls_debug = -1; /* Flag indicating that a shutdown has been requested. */ static volatile int shutdown_pending; /* Flags to indicate that we shall not watch our own socket. */ static int disable_check_own_socket; /* Flag to control the Tor mode. */ static enum { TOR_MODE_AUTO = 0, /* Switch to NO or YES */ TOR_MODE_NEVER, /* Never use Tor. */ TOR_MODE_NO, /* Do not use Tor */ TOR_MODE_YES, /* Use Tor */ TOR_MODE_FORCE /* Force using Tor */ } tor_mode; /* Counter for the active connections. */ static int active_connections; /* This flag is set by any network access and used by the housekeeping * thread to run background network tasks. */ static int network_activity_seen; /* A list of filenames registered with --hkp-cacert. */ static strlist_t hkp_cacert_filenames; /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */ #define TIMERTICK_INTERVAL (60) #define TIMERTICK_INTERVAL_SHUTDOWN (4) /* How oft to run the housekeeping. */ #define HOUSEKEEPING_INTERVAL (600) /* This union is used to avoid compiler warnings in case a pointer is 64 bit and an int 32 bit. We store an integer in a pointer and get it back later (npth_getspecific et al.). */ union int_and_ptr_u { int aint; assuan_fd_t afd; void *aptr; }; /* The key used to store the current file descriptor in the thread local storage. We use this in conjunction with the log_set_pid_suffix_cb feature. */ #ifndef HAVE_W32_SYSTEM static npth_key_t my_tlskey_current_fd; #endif /* Prototypes. */ static void cleanup (void); #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent); #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string); static void netactivity_action (void); static void handle_connections (assuan_fd_t listen_fd); static void gpgconf_versions (void); /* NPth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; static const char * my_strusage( int level ) { const char *p; switch ( level ) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@DIRMNGR@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 49: p = PACKAGE_BUGREPORT; break; case 1: case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)"); break; case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n" "Keyserver, CRL, and OCSP access for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Callback from libksba to hash a provided buffer. Our current implementation does only allow SHA-1 for hashing. This may be extended by mapping the name, testing for algorithm availability and adjust the length checks accordingly. */ static gpg_error_t my_ksba_hash_buffer (void *arg, const char *oid, const void *buffer, size_t length, size_t resultsize, unsigned char *result, size_t *resultlen) { (void)arg; if (oid && strcmp (oid, "1.3.14.3.2.26")) return gpg_error (GPG_ERR_NOT_SUPPORTED); if (resultsize < 20) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); gcry_md_hash_buffer (2, result, buffer, length); *resultlen = 20; return 0; } /* GNUTLS log function callback. */ #ifdef HTTP_USE_GNUTLS static void my_gnutls_log (int level, const char *text) { int n; n = strlen (text); while (n && text[n-1] == '\n') n--; log_debug ("gnutls:L%d: %.*s\n", level, n, text); } #endif /*HTTP_USE_GNUTLS*/ /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE); else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); log_info (_("valid debug levels are: %s\n"), "none, basic, advanced, expert, guru"); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) { opt.verbose = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); } if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); #if HTTP_USE_NTBTLS if (opt_gnutls_debug >= 0) { ntbtls_set_debug (opt_gnutls_debug, NULL, NULL); } #elif HTTP_USE_GNUTLS if (opt_gnutls_debug >= 0) { gnutls_global_set_log_function (my_gnutls_log); gnutls_global_set_log_level (opt_gnutls_debug); } #endif /*HTTP_USE_GNUTLS*/ if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } static void set_tor_mode (void) { if (dirmngr_use_tor ()) { /* Enable Tor mode and when called again force a new circuit * (e.g. on SIGHUP). */ enable_dns_tormode (1); if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1)) { log_error ("error enabling Tor mode: %s\n", strerror (errno)); log_info ("(is your Libassuan recent enough?)\n"); } } else disable_dns_tormode (); } /* Return true if Tor shall be used. */ int dirmngr_use_tor (void) { if (tor_mode == TOR_MODE_AUTO) { /* Figure out whether Tor is running. */ assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) tor_mode = TOR_MODE_NO; else { tor_mode = TOR_MODE_YES; assuan_sock_close (sock); } } if (tor_mode == TOR_MODE_FORCE) return 2; /* Use Tor (using 2 to indicate force mode) */ else if (tor_mode == TOR_MODE_YES) return 1; /* Use Tor */ else return 0; /* Do not use Tor. */ } static void wrong_args (const char *text) { es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME); es_fputs (text, es_stderr); es_putc ('\n', es_stderr); dirmngr_exit (2); } /* Helper to stop the reaper thread for the ldap wrapper. */ static void shutdown_reaper (void) { #if USE_LDAP ldap_wrapper_wait_connections (); #endif } /* Handle options which are allowed to be reset after program start. Return true if the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (gpgrt_argparse_t *pargs, int reread) { if (!pargs) { /* Reset mode. */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.ldap_wrapper_program = NULL; opt.disable_http = 0; opt.disable_ldap = 0; opt.honor_http_proxy = 0; opt.http_proxy = NULL; opt.ldap_proxy = NULL; opt.only_ldap_proxy = 0; opt.ignore_http_dp = 0; opt.ignore_ldap_dp = 0; opt.ignore_ocsp_service_url = 0; opt.allow_ocsp = 0; opt.allow_version_check = 0; opt.ocsp_responder = NULL; opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */ opt.ocsp_max_period = 90 * 86400; /* 90 days. */ opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */ opt.max_replies = DEFAULT_MAX_REPLIES; while (opt.ocsp_signer) { fingerprint_list_t tmp = opt.ocsp_signer->next; xfree (opt.ocsp_signer); opt.ocsp_signer = tmp; } FREE_STRLIST (opt.ignored_cert_extensions); http_register_tls_ca (NULL); FREE_STRLIST (hkp_cacert_filenames); FREE_STRLIST (opt.keyserver); /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */ if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_AUTO; disable_check_own_socket = 0; enable_standard_resolver (0); set_dns_timeout (0); opt.connect_timeout = 0; opt.connect_quick_timeout = 0; return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break; case oLogFile: if (!reread) return 0; /* Not handled. */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oLDAPWrapperProgram: opt.ldap_wrapper_program = pargs->r.ret_str; break; case oHTTPWrapperProgram: opt.http_wrapper_program = pargs->r.ret_str; break; case oDisableHTTP: opt.disable_http = 1; break; case oDisableLDAP: opt.disable_ldap = 1; break; case oDisableIPv4: opt.disable_ipv4 = 1; break; case oDisableIPv6: opt.disable_ipv6 = 1; break; case oHonorHTTPProxy: opt.honor_http_proxy = 1; break; case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break; case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break; case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break; case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break; case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break; case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break; case oAllowOCSP: opt.allow_ocsp = 1; break; case oAllowVersionCheck: opt.allow_version_check = 1; break; case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break; case oOCSPSigner: opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str); break; case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break; case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break; case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break; case oMaxReplies: opt.max_replies = pargs->r.ret_int; break; case oHkpCaCert: { /* We need to register the filenames with gnutls (http.c) and * also for our own cert cache. */ char *tmpname; /* Do tilde expansion and make path absolute. */ tmpname = make_absfilename (pargs->r.ret_str, NULL); http_register_tls_ca (tmpname); add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str); xfree (tmpname); } break; case oIgnoreCertExtension: add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str); break; case oUseTor: tor_mode = TOR_MODE_FORCE; break; case oNoUseTor: if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_NEVER; break; case oStandardResolver: enable_standard_resolver (1); break; case oRecursiveResolver: enable_recursive_resolver (1); break; case oKeyServer: if (*pargs->r.ret_str) add_to_strlist (&opt.keyserver, pargs->r.ret_str); break; case oNameServer: set_dns_nameserver (pargs->r.ret_str); break; case oResolverTimeout: set_dns_timeout (pargs->r.ret_int); break; case oConnectTimeout: opt.connect_timeout = pargs->r.ret_ulong * 1000; break; case oConnectQuickTimeout: opt.connect_quick_timeout = pargs->r.ret_ulong * 1000; break; default: return 0; /* Not handled. */ } set_dns_verbose (opt.verbose, !!DBG_DNS); http_set_verbose (opt.verbose, !!DBG_NETWORK); set_dns_disable_ipv4 (opt.disable_ipv4); set_dns_disable_ipv6 (opt.disable_ipv6); return 1; /* Handled. */ } /* This function is called after option parsing to adjust some values * and call option setup functions. */ static void post_option_parsing (void) { /* It would be too surpirsing if the quick timeout is larger than * the standard value. */ if (opt.connect_quick_timeout > opt.connect_timeout) opt.connect_quick_timeout = opt.connect_timeout; set_debug (); } #ifndef HAVE_W32_SYSTEM static int pid_suffix_callback (unsigned long *r_suffix) { union int_and_ptr_u value; memset (&value, 0, sizeof value); value.aptr = npth_getspecific (my_tlskey_current_fd); *r_suffix = value.aint; return (*r_suffix != -1); /* Use decimal representation. */ } #endif /*!HAVE_W32_SYSTEM*/ #if HTTP_USE_NTBTLS static void my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv) { (void)opaque; if (level == -1) log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv); else { char prefix[10+20]; snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level); log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv); } } #endif static void thread_init (void) { npth_init (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now with NPth running we can set the logging callback. Our windows implementation does not yet feature the NPth TLS functions. */ #ifndef HAVE_W32_SYSTEM if (npth_key_create (&my_tlskey_current_fd, NULL) == 0) if (npth_setspecific (my_tlskey_current_fd, NULL) == 0) log_set_pid_suffix_cb (pid_suffix_callback); #endif /*!HAVE_W32_SYSTEM*/ } int main (int argc, char **argv) { enum cmd_and_opt_values cmd = 0; gpgrt_argparse_t pargs; int orig_argc; char **orig_argv; char *last_configname = NULL; const char *configname = NULL; const char *shell; int debug_argparser = 0; int greeting = 0; int nogreeting = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; #if USE_LDAP char *ldapfile = NULL; #endif /*USE_LDAP*/ int debug_wait = 0; int rc; struct assuan_malloc_hooks malloc_hooks; early_system_init (); gpgrt_set_strusage (my_strusage); log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* Check that the libraries are suitable. Do it here because the option parsing may need services of the libraries. */ if (!ksba_check_version (NEED_KSBA_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba", NEED_KSBA_VERSION, ksba_check_version (NULL) ); ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL); /* Init TLS library. */ #if HTTP_USE_NTBTLS if (!ntbtls_check_version (NEED_NTBTLS_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls", NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) ); #elif HTTP_USE_GNUTLS rc = gnutls_global_init (); if (rc) log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc)); #endif /*HTTP_USE_GNUTLS*/ /* Init Assuan. */ malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_assuan_log_prefix (log_get_prefix (NULL)); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor); setup_libgcrypt_logging (); #if HTTP_USE_NTBTLS ntbtls_set_log_handler (my_ntbtls_log_handler, NULL); #endif /* Setup defaults. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Reset rereadable options to default values. */ parse_rereadable_options (NULL, 0); /* Default TCP timeouts. */ opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT; opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT; /* LDAP defaults. */ opt.add_new_ldapservers = 0; opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT; /* Other defaults. */ /* Check whether we have a config file given on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); while (gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oDebug: case oDebugAll: debug_argparser++; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; } } /* Reset the flags. */ pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); socket_name = dirmngr_socket_name (); /* The configuraton directories for use by gpgrt_argparser. */ gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ()); gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ()); /* We are re-using the struct, thus the reset flag. We OR the * flags so that the internal intialized flag won't be cleared. */ argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags |= (ARGPARSE_FLAG_RESET | ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_SYS | ARGPARSE_FLAG_USER); while (gpgrt_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf")) { if (pargs.r_opt == ARGPARSE_CONFFILE) { if (debug_argparser) log_info (_("reading options from '%s'\n"), pargs.r_type? pargs.r.ret_str: "[cmdline]"); if (pargs.r_type) { xfree (last_configname); last_configname = xstrdup (pargs.r.ret_str); configname = last_configname; } else configname = NULL; continue; } if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aServer: case aDaemon: case aSupervised: case aShutdown: case aFlush: case aListCRLs: case aLoadCRL: case aFetchCRL: case aGPGConfList: case aGPGConfTest: case aGPGConfVersions: cmd = pargs.r_opt; break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: /* Ignore this option here. */; break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oLDAPFile: # if USE_LDAP ldapfile = pargs.r.ret_str; # endif /*USE_LDAP*/ break; case oLDAPAddServers: opt.add_new_ldapservers = 1; break; case oLDAPTimeout: opt.ldaptimeout = pargs.r.ret_int; break; case oFakedSystemTime: gnupg_set_time ((time_t)pargs.r.ret_ulong, 0); break; case oForce: opt.force = 1; break; case oSocketName: socket_name = pargs.r.ret_str; break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; default: if (configname) pargs.err = ARGPARSE_PRINT_WARNING; else pargs.err = ARGPARSE_PRINT_ERROR; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (!last_configname) opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (), DIRMNGR_NAME EXTSEP_S "conf", NULL); else { opt.config_filename = last_configname; last_configname = NULL; } if (log_get_errorcount(0)) exit(2); if (nogreeting ) greeting = 0; if (!opt.homedir_cache) opt.homedir_cache = xstrdup (gnupg_homedir ()); if (greeting) { es_fprintf (es_stderr, "%s %s; %s\n", gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14)); es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15)); } #ifdef IS_DEVELOPMENT_VERSION log_info ("NOTE: this is a development version!\n"); #endif /* 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]); } if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK) && !strncmp (gnupg_homedir (), "/etc/", 5)) log_info ("NOTE: DirMngr is now a proper part of %s. The configuration and" " other directory names changed. Please check that no other version" " of dirmngr is still installed. To disable this warning, remove the" " directory '/etc/dirmngr'.\n", GNUPG_NAME); if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } /* Note that we do not run set_tor_mode in --gpgconf-list mode * because it will attempt to connect to the tor client and that can * be time consuming. */ post_option_parsing (); if (cmd != aGPGConfTest && cmd != aGPGConfList && cmd != aGPGConfVersions) set_tor_mode (); /* Get LDAP server list from file. */ #if USE_LDAP if (!ldapfile) { ldapfile = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); opt.ldapservers = parse_ldapserver_file (ldapfile, 1); xfree (ldapfile); } else opt.ldapservers = parse_ldapserver_file (ldapfile, 0); #endif /*USE_LDAP*/ #ifndef HAVE_W32_SYSTEM /* We need to ignore the PIPE signal because the we might log to a socket and that code handles EPIPE properly. The ldap wrapper also requires us to ignore this silly signal. Assuan would set this signal to ignore anyway.*/ signal (SIGPIPE, SIG_IGN); #endif /* Ready. Now to our duties. */ if (!cmd) cmd = aServer; rc = 0; if (cmd == aServer) { /* Note that this server mode is mainly useful for debugging. */ if (argc) wrong_args ("--server"); if (logfile) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); start_command_handler (ASSUAN_INVALID_FD, 0); shutdown_reaper (); } #ifndef HAVE_W32_SYSTEM else if (cmd == aSupervised) { /* In supervised mode, we expect file descriptor 3 to be an already opened, listening socket. We will also not detach from the controlling process or close stderr; the supervisor should handle all of that. */ struct stat statbuf; if (fstat (3, &statbuf) == -1 && errno == EBADF) { log_error ("file descriptor 3 must be validin --supervised mode\n"); dirmngr_exit (1); } socket_name = gnupg_get_socket_name (3); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } else log_set_prefix (NULL, 0); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (3); shutdown_reaper (); } #endif /*HAVE_W32_SYSTEM*/ else if (cmd == aDaemon) { assuan_fd_t fd; pid_t pid; int len; struct sockaddr_un serv_addr; if (argc) wrong_args ("--daemon"); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } #ifndef HAVE_W32_SYSTEM if (strchr (socket_name, ':')) { log_error (_("colons are not allowed in the socket name\n")); dirmngr_exit (1); } #endif fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); cleanup (); dirmngr_exit (1); } { int redirected; if (assuan_sock_set_sockaddr_un (socket_name, (struct sockaddr*)&serv_addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), socket_name); else log_error ("error preparing socket '%s': %s\n", socket_name, gpg_strerror (gpg_error_from_syserror ())); dirmngr_exit (1); } if (redirected) { redir_socket_name = xstrdup (serv_addr.sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", socket_name, redir_socket_name); } } len = SUN_LEN (&serv_addr); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Fixme: We should test whether a dirmngr is already running. */ gnupg_remove (redir_socket_name? redir_socket_name : socket_name); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); } if (rc != -1 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { log_error (_("error binding socket to '%s': %s\n"), serv_addr.sun_path, - gpg_strerror (gpg_error_from_errno (errno))); + gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); dirmngr_exit (1); } cleanup_socket = 1; if (gnupg_chmod (serv_addr.sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), serv_addr.sun_path, strerror (errno)); if (listen (FD2INT (fd), listen_backlog) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); assuan_sock_close (fd); dirmngr_exit (1); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), serv_addr.sun_path); es_fflush (NULL); /* Note: We keep the dirmngr_info output only for the sake of existing scripts which might use this to detect a successful start of the dirmngr. */ #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; pid = getpid (); es_printf ("set %s=%s;%lu;1\n", DIRMNGR_INFO_NAME, socket_name, (ulong) pid); #else pid = fork(); if (pid == (pid_t)-1) { log_fatal (_("error forking process: %s\n"), strerror (errno)); dirmngr_exit (1); } if (pid) { /* We are the parent */ char *infostr; /* Don't let cleanup() remove the socket - the child is responsible for doing that. */ cleanup_socket = 0; close (fd); /* Create the info string: :: */ if (asprintf (&infostr, "%s=%s:%lu:1", DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0) { log_error (_("out of core\n")); kill (pid, SIGTERM); dirmngr_exit (1); } /* Print the environment string, so that the caller can use shell's eval to set it. But see above. */ if (csh_style) { *strchr (infostr, '=') = ' '; es_printf ( "setenv %s;\n", infostr); } else { es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME); } free (infostr); exit (0); /*NEVER REACHED*/ } /* end parent */ /* This is the child */ /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( !close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); dirmngr_exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); dirmngr_exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; } #endif if (!nodetach ) { if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); dirmngr_exit (1); } } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (fd); shutdown_reaper (); } else if (cmd == aListCRLs) { /* Just list the CRL cache and exit. */ if (argc) wrong_args ("--list-crls"); crl_cache_init (); crl_cache_list (es_stdout); } else if (cmd == aLoadCRL) { struct server_control_s ctrlbuf; memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); if (!argc) rc = crl_cache_load (&ctrlbuf, NULL); else { for (; !rc && argc; argc--, argv++) rc = crl_cache_load (&ctrlbuf, *argv); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFetchCRL) { ksba_reader_t reader; struct server_control_s ctrlbuf; if (argc != 1) wrong_args ("--fetch-crl URL"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); rc = crl_fetch (&ctrlbuf, argv[0], &reader); if (rc) log_error (_("fetching CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); else { rc = crl_cache_insert (&ctrlbuf, argv[0], reader); if (rc) log_error (_("processing CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); crl_close_reader (reader); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFlush) { /* Delete cache and exit. */ if (argc) wrong_args ("--flush"); rc = crl_cache_flush(); } else if (cmd == aGPGConfTest) dirmngr_exit (0); else if (cmd == aGPGConfList) { unsigned long flags = 0; char *filename_esc; es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT); es_printf ("ldaptimeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT); es_printf ("max-replies:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES); filename_esc = percent_escape (get_default_keyserver (0), NULL); es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); es_printf ("resolver-timeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, 0); } else if (cmd == aGPGConfVersions) gpgconf_versions (); cleanup (); return !!rc; } static void cleanup (void) { crl_cache_deinit (); cert_cache_deinit (1); reload_dns_stuff (1); #if USE_LDAP ldapserver_list_free (opt.ldapservers); #endif /*USE_LDAP*/ opt.ldapservers = NULL; if (cleanup_socket) { cleanup_socket = 0; if (redir_socket_name) gnupg_remove (redir_socket_name); else if (socket_name && *socket_name) gnupg_remove (socket_name); } } void dirmngr_exit (int rc) { cleanup (); exit (rc); } void dirmngr_init_default_ctrl (ctrl_t ctrl) { ctrl->magic = SERVER_CONTROL_MAGIC; if (opt.http_proxy) ctrl->http_proxy = xstrdup (opt.http_proxy); ctrl->http_no_crl = 1; ctrl->timeout = opt.connect_timeout; } void dirmngr_deinit_default_ctrl (ctrl_t ctrl) { if (!ctrl) return; ctrl->magic = 0xdeadbeef; xfree (ctrl->http_proxy); ctrl->http_proxy = NULL; } /* Create a list of LDAP servers from the file FILENAME. Returns the list or NULL in case of errors. The format of such a file is line oriented where empty lines and lines starting with a hash mark are ignored. All other lines are assumed to be colon seprated with these fields: 1. field: Hostname 2. field: Portnumber 3. field: Username 4. field: Password 5. field: Base DN */ #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename, int ignore_enoent) { char buffer[1024]; char *p; ldap_server_t server, serverstart, *serverend; int c; unsigned int lineno = 0; estream_t fp; fp = es_fopen (filename, "r"); if (!fp) { if (ignore_enoent && gpg_err_code_from_syserror () == GPG_ERR_ENOENT) ; else log_info ("failed to open '%s': %s\n", filename, strerror (errno)); return NULL; } serverstart = NULL; serverend = &serverstart; while (es_fgets (buffer, sizeof buffer, fp)) { lineno++; if (!*buffer || buffer[strlen(buffer)-1] != '\n') { if (*buffer && es_feof (fp)) ; /* Last line not terminated - continue. */ else { log_error (_("%s:%u: line too long - skipped\n"), filename, lineno); while ( (c=es_fgetc (fp)) != EOF && c != '\n') ; /* Skip until end of line. */ continue; } } /* Skip empty and comment lines.*/ for (p=buffer; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; /* Parse the colon separated fields. */ server = ldapserver_parse_one (buffer, filename, lineno); if (server) { *serverend = server; serverend = &server->next; } } if (es_ferror (fp)) log_error (_("error reading '%s': %s\n"), filename, strerror (errno)); es_fclose (fp); return serverstart; } #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string) { gpg_error_t err; char *fname; estream_t fp; char line[256]; char *p; fingerprint_list_t list, *list_tail, item; unsigned int lnr = 0; int c, i, j; int errflag = 0; /* Check whether this is not a filename and treat it as a direct fingerprint specification. */ if (!strpbrk (string, "/.~\\")) { item = xcalloc (1, sizeof *item); for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++) if ( string[i] != ':' ) item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (string+i) || !string[i])) { log_error (_("%s:%u: invalid fingerprint detected\n"), "--ocsp-signer", 0); xfree (item); return NULL; } return item; } /* Well, it is a filename. */ if (*string == '/' || (*string == '~' && string[1] == '/')) fname = make_filename (string, NULL); else { if (string[0] == '.' && string[1] == '/' ) string += 2; fname = make_filename (gnupg_homedir (), string, NULL); } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); xfree (fname); return NULL; } list = NULL; list_tail = &list; for (;;) { if (!es_fgets (line, DIM(line)-1, fp) ) { if (!es_feof (fp)) { err = gpg_error_from_syserror (); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; } es_fclose (fp); if (errflag) { while (list) { fingerprint_list_t tmp = list->next; xfree (list); list = tmp; } } xfree (fname); return list; /* Ready. */ } lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ while ( (c=es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG /* */: GPG_ERR_INCOMPLETE_LINE); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; continue; } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; item = xcalloc (1, sizeof *item); *list_tail = item; list_tail = &item->next; for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++) if ( p[i] != ':' ) item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (p+i) || p[i] == '\n')) { log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr); errflag = 1; } i++; while (spacep (p+i)) i++; if (p[i] && p[i] != '\n') log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr); } /*NOTREACHED*/ } /* Stuff used in daemon mode. */ /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the NPTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process's original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { gpgrt_argparse_t pargs; char *twopart; int dummy; if (!opt.config_filename) return; /* No config file. */ twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S, opt.config_filename, NULL); if (!twopart) return; /* Out of core. */ parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = (ARGPARSE_FLAG_KEEP |ARGPARSE_FLAG_SYS |ARGPARSE_FLAG_USER); while (gpgrt_argparser (&pargs, opts, twopart)) { if (pargs.r_opt == ARGPARSE_CONFFILE) { log_info (_("reading options from '%s'\n"), pargs.r_type? pargs.r.ret_str: "[cmdline]"); } else if (pargs.r_opt < -1) pargs.err = ARGPARSE_PRINT_WARNING; else /* Try to parse this option - ignore unchangeable ones. */ parse_rereadable_options (&pargs, 1); } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ xfree (twopart); post_option_parsing (); } /* A global function which allows us to trigger the reload stuff from other places. */ void dirmngr_sighup_action (void) { log_info (_("SIGHUP received - " "re-reading configuration and flushing caches\n")); reread_configuration (); set_tor_mode (); cert_cache_deinit (0); crl_cache_deinit (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); reload_dns_stuff (0); ks_hkp_reload (); } /* This function is called if some network activity was done. At this * point we know the we have a network and we can decide whether to * run scheduled background tasks soon. The function should return * quickly and only trigger actions for another thread. */ static void netactivity_action (void) { network_activity_seen = 1; } /* The signal handler. */ #ifndef HAVE_W32_SYSTEM static void handle_signal (int signo) { switch (signo) { case SIGHUP: dirmngr_sighup_action (); break; case SIGUSR1: cert_cache_print_stats (); domaininfo_print_stats (); break; case SIGUSR2: log_info (_("SIGUSR2 received - no action defined\n")); break; case SIGTERM: if (!shutdown_pending) log_info (_("SIGTERM received - shutting down ...\n")); else log_info (_("SIGTERM received - still %d active connections\n"), active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info (_("shutdown forced\n")); log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); cleanup (); dirmngr_exit (0); } break; case SIGINT: log_info (_("SIGINT received - immediate shutdown\n")); log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); cleanup (); dirmngr_exit (0); break; default: log_info (_("signal %d received - no action defined\n"), signo); } } #endif /*!HAVE_W32_SYSTEM*/ /* Thread to do the housekeeping. */ static void * housekeeping_thread (void *arg) { static int sentinel; time_t curtime; struct server_control_s ctrlbuf; (void)arg; curtime = gnupg_get_time (); if (sentinel) { log_info ("housekeeping is already going on\n"); return NULL; } sentinel++; if (opt.verbose > 1) log_info ("starting housekeeping\n"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); dns_stuff_housekeeping (); ks_hkp_housekeeping (curtime); if (network_activity_seen) { network_activity_seen = 0; if (opt.allow_version_check) dirmngr_load_swdb (&ctrlbuf, 0); workqueue_run_global_tasks (&ctrlbuf, 1); } else workqueue_run_global_tasks (&ctrlbuf, 0); dirmngr_deinit_default_ctrl (&ctrlbuf); if (opt.verbose > 1) log_info ("ready with housekeeping\n"); sentinel--; return NULL; } /* We try to enable correct overflow handling for signed int (commonly * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced * and used here as a pragma. Later gcc versions (gcc 6?) removed * this as a pragma and -fwrapv was then suggested as a replacement * for -fno-strict-overflow. */ #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC push_options # pragma GCC optimize ("wrapv") #endif static int time_for_housekeeping_p (time_t curtime) { static time_t last_housekeeping; if (!last_housekeeping) last_housekeeping = curtime; if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime || last_housekeeping > curtime /*(be prepared for y2038)*/) { last_housekeeping = curtime; return 1; } return 0; } #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC pop_options #endif /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { struct stat statbuf; if (time_for_housekeeping_p (gnupg_get_time ())) { npth_t thread; npth_attr_t tattr; int err; err = npth_attr_init (&tattr); if (err) log_error ("error preparing housekeeping thread: %s\n", strerror (err)); else { npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, housekeeping_thread, NULL); if (err) log_error ("error spawning housekeeping thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } } /* Check whether the homedir is still available. */ if (!shutdown_pending && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT (fd), strerror (errno)); assuan_sock_close (fd); return -1; } else return 0; } /* Helper to call a connection's main function. */ static void * start_connection_thread (void *arg) { static unsigned int last_session_id; unsigned int session_id; union int_and_ptr_u argval; gnupg_fd_t fd; memset (&argval, 0, sizeof argval); argval.aptr = arg; fd = argval.afd; if (check_nonce (fd, &socket_nonce)) { log_error ("handler nonce check FAILED\n"); return NULL; } #ifndef HAVE_W32_SYSTEM npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif active_connections++; if (opt.verbose) log_info (_("handler for fd %d started\n"), FD2INT (fd)); session_id = ++last_session_id; if (!session_id) session_id = ++last_session_id; start_command_handler (fd, session_id); if (opt.verbose) log_info (_("handler for fd %d terminated\n"), FD2INT (fd)); active_connections--; workqueue_run_post_session_tasks (session_id); #ifndef HAVE_W32_SYSTEM argval.afd = ASSUAN_INVALID_FD; npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif return NULL; } #ifdef HAVE_INOTIFY_INIT /* Read an inotify event and return true if it matches NAME. */ static int my_inotify_is_name (int fd, const char *name) { union { struct inotify_event ev; char _buf[sizeof (struct inotify_event) + 100 + 1]; } buf; int n; const char *s; s = strrchr (name, '/'); if (s && s[1]) name = s + 1; n = npth_read (fd, &buf, sizeof buf); if (n < sizeof (struct inotify_event)) return 0; if (buf.ev.len < strlen (name)+1) return 0; if (strcmp (buf.ev.name, name)) return 0; /* Not the desired file. */ return 1; /* Found. */ } #endif /*HAVE_INOTIFY_INIT*/ /* Main loop in daemon mode. Note that LISTEN_FD will be owned by * this function. */ static void handle_connections (assuan_fd_t listen_fd) { npth_attr_t tattr; #ifndef HAVE_W32_SYSTEM int signo; #endif struct sockaddr_un paddr; socklen_t plen = sizeof( paddr ); int nfd, ret; fd_set fdset, read_fdset; struct timespec abstime; struct timespec curtime; struct timespec timeout; int saved_errno; int my_inotify_fd = -1; npth_attr_init (&tattr); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM /* FIXME */ npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #endif #ifdef HAVE_INOTIFY_INIT if (disable_check_own_socket) my_inotify_fd = -1; else if ((my_inotify_fd = inotify_init ()) == -1) log_info ("error enabling fast daemon termination: %s\n", strerror (errno)); else { /* We need to watch the directory for the file because there * won't be an IN_DELETE_SELF for a socket file. */ char *slash = strrchr (socket_name, '/'); log_assert (slash && slash[1]); *slash = 0; if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1) { close (my_inotify_fd); my_inotify_fd = -1; } *slash = '/'; } #endif /*HAVE_INOTIFY_INIT*/ /* Setup the fdset. It has only one member. This is because we use pth_select instead of pth_accept to properly sync timeouts with to full second. */ FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); if (my_inotify_fd > nfd) nfd = my_inotify_fd; } npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; /* Main loop. */ for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (!active_connections) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ /* assuan_sock_close (listen_fd); */ /* listen_fd = -1; */ FD_ZERO (&fdset); nfd = -1; if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); nfd = my_inotify_fd; } } /* Take a copy of the fdset. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. When a shutdown is pending we use a shorter * interval to handle the shutdown more quickly. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += (shutdown_pending ? TIMERTICK_INTERVAL_SHUTDOWN : TIMERTICK_INTERVAL); } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask()); saved_errno = errno; while (npth_sigev_get_pending(&signo)) handle_signal (signo); #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL); saved_errno = errno; #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) { /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; } if (shutdown_pending) { /* Do not anymore accept connections. */ continue; } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset) && my_inotify_is_name (my_inotify_fd, socket_name)) { shutdown_pending = 1; log_info ("socket file has been removed - shutting down\n"); } #endif /*HAVE_INOTIFY_INIT*/ if (FD_ISSET (FD2INT (listen_fd), &read_fdset)) { gnupg_fd_t fd; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listen_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed: %s\n", strerror (errno)); } else { char threadname[50]; union int_and_ptr_u argval; npth_t thread; memset (&argval, 0, sizeof argval); argval.afd = fd; snprintf (threadname, sizeof threadname, "conn fd=%d", FD2INT(fd)); ret = npth_create (&thread, &tattr, start_connection_thread, argval.aptr); if (ret) { log_error ("error spawning connection handler: %s\n", strerror (ret) ); assuan_sock_close (fd); } npth_setname_np (thread, threadname); } } } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1) close (my_inotify_fd); #endif /*HAVE_INOTIFY_INIT*/ npth_attr_destroy (&tattr); if (listen_fd != GNUPG_INVALID_FD) assuan_sock_close (listen_fd); cleanup (); log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); } const char* dirmngr_get_current_socket_name (void) { if (socket_name) return socket_name; else return dirmngr_socket_name (); } /* Parse the revision part from the extended version blurb. */ static const char * get_revision_from_blurb (const char *blurb, int *r_len) { const char *s = blurb? blurb : ""; int n; for (; *s; s++) if (*s == '\n' && s[1] == '(') break; if (s) { s += 2; for (n=0; s[n] && s[n] != ' '; n++) ; } else { s = "?"; n = 1; } *r_len = n; return s; } /* Print versions of dirmngr and used libraries. This is used by * "gpgconf --show-versions" so that there is no need to link gpgconf * against all these libraries. This is an internal API and should * not be relied upon. */ static void gpgconf_versions (void) { const char *s; int n; /* Unfortunately Npth has no way to get the version. */ s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n); es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n", assuan_check_version (NULL), n, s); es_fprintf (es_stdout, "* KSBA %s \n\n", ksba_check_version (NULL)); #ifdef HTTP_USE_NTBTLS s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n); es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n", ntbtls_check_version (NULL), n, s); #elif HTTP_USE_GNUTLS es_fprintf (es_stdout, "* GNUTLS %s\n\n", gnutls_check_version (NULL)); #endif } diff --git a/tools/gpg-pair-tool.c b/tools/gpg-pair-tool.c index 4a9a6f56c..4054f5d19 100644 --- a/tools/gpg-pair-tool.c +++ b/tools/gpg-pair-tool.c @@ -1,1966 +1,1965 @@ /* gpg-pair-tool.c - The tool to run the pairing protocol. * Copyright (C) 2018 g10 Code GmbH * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU 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. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ /* Protocol: * * Initiator Responder * | | * | COMMIT | * |-------------------->| * | | * | DHPART1 | * |<--------------------| * | | * | DHPART2 | * |-------------------->| * | | * | CONFIRM | * |<--------------------| * | | * * The initiator creates a keypar (PKi,SKi) and sends this COMMIT * message to the responder: * * 7 byte Magic, value: "GPG-pa1" * 1 byte MessageType, value 1 (COMMIT) * 8 byte SessionId, value: 8 random bytes * 1 byte Realm, value 1 * 2 byte reserved, value 0 * 5 byte ExpireTime, value: seconds since Epoch as an unsigned int. * 32 byte Hash(PKi) * * The initiator also needs to locally store the sessionid, the realm, * the expiration time, the keypair and a hash of the entire message * sent. * * The responder checks that the received message has not expired and * stores sessionid, realm, expiretime and the Hash(PKi). The * Responder then creates and locally stores its own keypair (PKr,SKr) * and sends the DHPART1 message back: * * 7 byte Magic, value: "GPG-pa1" * 1 byte MessageType, value 2 (DHPART1) * 8 byte SessionId from COMMIT message * 32 byte PKr * 32 byte Hash(Hash(COMMIT) || DHPART1[0..47]) * * Note that Hash(COMMIT) is the hash over the entire received COMMIT * message. DHPART1[0..47] are the first 48 bytes of the created * DHPART1 message. * * The Initiator receives the DHPART1 message and checks that the hash * matches. Although this hash is easily malleable it is later in the * protocol used to assert the integrity of all messages. The * Initiator then computes the shared master secret from its SKi and * the received PKr. Using this master secret several keys are * derived: * * - HMACi-key using the label "GPG-pa1-HMACi-key". * - SYMx-key using the label "GPG-pa1-SYMx-key" * * For details on the KDF see the implementation of the function kdf. * The master secret is stored securily in the local state. The * DHPART2 message is then created and send to the Responder: * * 7 byte Magic, value: "GPG-pa1" * 1 byte MessageType, value 3 (DHPART2) * 8 byte SessionId from COMMIT message * 32 byte PKi * 32 byte MAC(HMACi-key, Hash(DHPART1) || DHPART2[0..47] || SYMx-key) * * The Responder receives the DHPART2 message and checks that the hash * of the received PKi matches the Hash(PKi) value as received earlier * with the COMMIT message. The Responder now also computes the * shared master secret from its SKr and the received PKi and derives * the keys: * * - HMACi-key using the label "GPG-pa1-HMACi-key". * - HMACr-key using the label "GPG-pa1-HMACr-key". * - SYMx-key using the label "GPG-pa1-SYMx-key" * - SAS using the label "GPG-pa1-SAS" * * With these keys the MAC from the received DHPART2 message is * checked. On success a SAS is displayed to the user and a CONFIRM * message send back: * * 7 byte Magic, value: "GPG-pa1" * 1 byte MessageType, value 4 (CONFIRM) * 8 byte SessionId from COMMIT message * 32 byte MAC(HMACr-key, Hash(DHPART2) || CONFIRM[0..15] || SYMx-key) * * The Initiator receives this CONFIRM message, gets the master shared * secrey from its local state and derives the keys. It checks the * the MAC in the received CONFIRM message and ask the user to enter * the SAS as displayed by the responder. Iff the SAS matches the * master key is flagged as confirmed and the Initiator may now use a * derived key to send encrypted data to the Responder. * * In case the Responder also needs to send encrypted data we need to * introduce another final message to tell the responder that the * Initiator validated the SAS. * * TODO: Encrypt the state files using a key stored in gpg-agent's cache. * */ #include #include #include #include #include #include #include #include #include #include "../common/util.h" #include "../common/status.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/init.h" #include "../common/name-value.h" /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oOutput = 'o', oArmor = 'a', aInitiate = 400, aRespond = 401, aGet = 402, aCleanup = 403, oDebug = 500, oStatusFD, oHomedir, oSAS, oDummy }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (300, ("@Commands:\n ")), ARGPARSE_c (aInitiate, "initiate", N_("initiate a pairing request")), ARGPARSE_c (aRespond, "respond", N_("respond to a pairing request")), ARGPARSE_c (aGet, "get", N_("return the keys")), ARGPARSE_c (aCleanup, "cleanup", N_("remove expired states etc.")), ARGPARSE_group (301, ("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")), ARGPARSE_s_s (oSAS, "sas", N_("|SAS|the SAS as shown by the peer")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write the request to FILE")), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_end () }; /* We keep all global options in the structure OPT. */ static struct { int verbose; unsigned int debug; int quiet; int armor; const char *output; estream_t statusfp; unsigned int ttl; const char *sas; } opt; /* Debug values and macros. */ #define DBG_MESSAGE_VALUE 2 /* Debug the messages. */ #define DBG_CRYPTO_VALUE 4 /* Debug low level crypto. */ #define DBG_MEMORY_VALUE 32 /* Debug memory allocation stuff. */ #define DBG_MESSAGE (opt.debug & DBG_MESSAGE_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_MESSAGE_VALUE, "message" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { 0, NULL } }; /* The directory name below the cache dir to store paring states. */ #define PAIRING_STATE_DIR "state" /* Message types. */ #define MSG_TYPE_COMMIT 1 #define MSG_TYPE_DHPART1 2 #define MSG_TYPE_DHPART2 3 #define MSG_TYPE_CONFIRM 4 /* Realm values. */ #define REALM_STANDARD 1 /* Local prototypes. */ static void wrong_args (const char *text) GPGRT_ATTR_NORETURN; static void xnvc_set_printf (nvc_t nvc, const char *name, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); static void *hash_data (void *result, size_t resultsize, ...) GPGRT_ATTR_SENTINEL(0); static void *hmac_data (void *result, size_t resultsize, const unsigned char *key, size_t keylen, ...) GPGRT_ATTR_SENTINEL(0); static gpg_error_t command_initiate (void); static gpg_error_t command_respond (void); static gpg_error_t command_cleanup (void); static gpg_error_t command_get (const char *sessionidstr); /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 9: p = "LGPL-2.1-or-later"; break; case 11: p = "gpg-pair-tool"; break; case 12: p = "@GNUPG@"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = ("Usage: gpg-pair-tool [command] [options] [args] (-h for help)"); break; case 41: p = ("Syntax: gpg-pair-tool [command] [options] [args]\n" "Client to run the pairing protocol\n"); break; default: p = NULL; break; } return p; } static void wrong_args (const char *text) { es_fprintf (es_stderr, _("usage: %s [options] %s\n"), gpgrt_strusage (11), text); exit (2); } /* Set the status FD. */ static void set_status_fd (int fd) { static int last_fd = -1; if (fd != -1 && last_fd == fd) return; if (opt.statusfp && opt.statusfp != es_stdout && opt.statusfp != es_stderr) es_fclose (opt.statusfp); opt.statusfp = NULL; if (fd == -1) return; if (fd == 1) opt.statusfp = es_stdout; else if (fd == 2) opt.statusfp = es_stderr; else opt.statusfp = es_fdopen (fd, "w"); if (!opt.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. */ static void write_status (int no, const char *format, ...) { va_list arg_ptr; if (!opt.statusfp) return; /* Not enabled. */ es_fputs ("[GNUPG:] ", opt.statusfp); es_fputs (get_status_string (no), opt.statusfp); if (format) { es_putc (' ', opt.statusfp); va_start (arg_ptr, format); es_vfprintf (opt.statusfp, format, arg_ptr); va_end (arg_ptr); } es_putc ('\n', opt.statusfp); } /* gpg-pair-tool main. */ int main (int argc, char **argv) { gpg_error_t err; gpgrt_argparse_t pargs = { &argc, &argv }; enum cmd_and_opt_values cmd = 0; opt.ttl = 8*3600; /* Default to 8 hours. */ gnupg_reopen_std ("gpg-pair-tool"); gpgrt_set_strusage (my_strusage); log_set_prefix ("gpg-pair-tool", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); /* Parse the command line. */ while (gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oArmor: opt.armor = 1; break; case oDebug: if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags)) { pargs.r_opt = ARGPARSE_INVALID_ARG; pargs.err = ARGPARSE_PRINT_ERROR; } break; case oOutput: opt.output = pargs.r.ret_str; break; case oStatusFD: set_status_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oSAS: opt.sas = pargs.r.ret_str; break; case aInitiate: case aRespond: case aGet: case aCleanup: if (cmd && cmd != pargs.r_opt) log_error (_("conflicting commands\n")); else cmd = pargs.r_opt; break; default: pargs.err = ARGPARSE_PRINT_WARNING; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ /* 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]); } gpgrt_argparse (NULL, &pargs, NULL); /* Free internal memory. */ if (opt.sas) { if (strlen (opt.sas) != 11 || !digitp (opt.sas+0) || !digitp (opt.sas+1) || !digitp (opt.sas+2) || opt.sas[3] != '-' || !digitp (opt.sas+4) || !digitp (opt.sas+5) || !digitp (opt.sas+6) || opt.sas[7] != '-' || !digitp (opt.sas+8) || !digitp (opt.sas+9) || !digitp (opt.sas+10)) log_error ("invalid formatted SAS\n"); } /* Stop if any error, inclduing ARGPARSE_PRINT_WARNING, occurred. */ if (log_get_errorcount (0)) exit (2); if (DBG_CRYPTO) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1|2); /* Now run the requested command. */ switch (cmd) { case aInitiate: if (argc) wrong_args ("--initiate"); err = command_initiate (); break; case aRespond: if (argc) wrong_args ("--respond"); err = command_respond (); break; case aGet: if (argc > 1) wrong_args ("--respond [sessionid]"); err = command_get (argc? *argv:NULL); break; case aCleanup: if (argc) wrong_args ("--cleanup"); err = command_cleanup (); break; default: gpgrt_usage (1); err = 0; break; } if (err) write_status (STATUS_FAILURE, "- %u", err); else if (log_get_errorcount (0)) write_status (STATUS_FAILURE, "- %u", GPG_ERR_GENERAL); else write_status (STATUS_SUCCESS, NULL); return log_get_errorcount (0)? 1:0; } /* Wrapper around nvc_new which terminates in the error case. */ static nvc_t xnvc_new (void) { nvc_t c = nvc_new (); if (!c) log_fatal ("error creating NVC object: %s\n", gpg_strerror (gpg_error_from_syserror ())); return c; } /* Wrapper around nvc_set which terminates in the error case. */ static void xnvc_set (nvc_t nvc, const char *name, const char *value) { gpg_error_t err = nvc_set (nvc, name, value); if (err) log_fatal ("error updating NVC object: %s\n", gpg_strerror (err)); } /* Call vnc_set with (BUFFER, BUFLEN) converted to a hex string as * value. Terminates in the error case. */ static void xnvc_set_hex (nvc_t nvc, const char *name, const void *buffer, size_t buflen) { char *hex; hex = bin2hex (buffer, buflen, NULL); if (!hex) xoutofcore (); strlwr (hex); xnvc_set (nvc, name, hex); xfree (hex); } /* Call nvc_set with a value created from the string generated using * the printf style FORMAT. Terminates in the error case. */ static void xnvc_set_printf (nvc_t nvc, const char *name, const char *format, ...) { va_list arg_ptr; char *buffer; va_start (arg_ptr, format); if (gpgrt_vasprintf (&buffer, format, arg_ptr) < 0) log_fatal ("estream_asprintf failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); va_end (arg_ptr); xnvc_set (nvc, name, buffer); xfree (buffer); } /* Return the string for the first entry in NVC with NAME. If NAME is * missing, an empty string is returned. The returned string is a * pointer into NVC. */ static const char * xnvc_get_string (nvc_t nvc, const char *name) { nve_t item; if (!nvc) return ""; item = nvc_lookup (nvc, name); if (!item) return ""; return nve_value (item); } /* Return a string for MSGTYPE. */ const char * msgtypestr (int msgtype) { switch (msgtype) { case MSG_TYPE_COMMIT: return "Commit"; case MSG_TYPE_DHPART1: return "DHPart1"; case MSG_TYPE_DHPART2: return "DHPart2"; case MSG_TYPE_CONFIRM: return "Confirm"; } return "?"; } /* Private to {get,set}_session_id(). */ static struct { int initialized; unsigned char sessid[8]; } session_id; /* Return the 8 octet session. */ static unsigned char * get_session_id (void) { if (!session_id.initialized) { session_id.initialized = 1; gcry_create_nonce (session_id.sessid, sizeof session_id.sessid); } return session_id.sessid; } static void set_session_id (const void *sessid, size_t len) { log_assert (!session_id.initialized); if (len > sizeof session_id.sessid) len = sizeof session_id.sessid; memcpy (session_id.sessid, sessid, len); if (len < sizeof session_id.sessid) memset (session_id.sessid+len, 0, sizeof session_id.sessid - len); session_id.initialized = 1; } /* Return a string with the hexified session id. */ static const char * get_session_id_hex (void) { static char hexstr[16+1]; bin2hex (get_session_id (), 8, hexstr); strlwr (hexstr); return hexstr; } /* Return a fixed string with the directory used to store the state of * pairings. On error a diagnostic is printed but the file name is * returned anyway. It is expected that the expected failure of the * following open is responsible for error handling. */ static const char * get_pairing_statedir (void) { static char *fname; gpg_error_t err = 0; char *tmpstr; struct stat statbuf; if (fname) return fname; fname = make_filename (gnupg_homedir (), GNUPG_CACHE_DIR, NULL); if (gnupg_stat (fname, &statbuf) && errno == ENOENT) { if (gnupg_mkdir (fname, "-rwx")) { err = gpg_error_from_syserror (); log_error (_("can't create directory '%s': %s\n"), fname, gpg_strerror (err) ); } else if (!opt.quiet) log_info (_("directory '%s' created\n"), fname); } tmpstr = make_filename (fname, PAIRING_STATE_DIR, NULL); xfree (fname); fname = tmpstr; if (gnupg_stat (fname, &statbuf) && errno == ENOENT) { if (gnupg_mkdir (fname, "-rwx")) { if (!err) { err = gpg_error_from_syserror (); log_error (_("can't create directory '%s': %s\n"), fname, gpg_strerror (err) ); } } else if (!opt.quiet) log_info (_("directory '%s' created\n"), fname); } return fname; } /* Open the pairing state file. SESSIONID is a 8 byte buffer with the * session-id. If CREATE_FLAG is set the file is created and will * always return a valid stream. If CREATE_FLAG is not set the file * is opened for reading and writing. If the file does not exist NULL * is return; in all other error cases the process is terminated. If * R_FNAME is not NULL the name of the file is stored there and the * caller needs to free it. */ static estream_t open_pairing_state (const unsigned char *sessionid, int create_flag, char **r_fname) { gpg_error_t err; char *fname, *tmpstr; estream_t fp; /* The filename is the session id with a "pa1" suffix. Note that * the state dir may eventually be used for other purposes as well * and thus the suffix identifies that the file belongs to this * tool. We use lowercase file names for no real reason. */ tmpstr = bin2hex (sessionid, 8, NULL); if (!tmpstr) xoutofcore (); strlwr (tmpstr); fname = xstrconcat (tmpstr, ".pa1", NULL); xfree (tmpstr); tmpstr = make_filename (get_pairing_statedir (), fname, NULL); xfree (fname); fname = tmpstr; fp = es_fopen (fname, create_flag? "wbx,mode=-rw": "rb+,mode=-rw"); if (!fp) { err = gpg_error_from_syserror (); if (create_flag) { /* We should always be able to create a file. Also we use a * 64 bit session id, it is theoretically possible that such * a session already exists. However, that is rare enough * and thus the fatal error message should still be okay. */ log_fatal ("can't create '%s': %s\n", fname, gpg_strerror (err)); } else if (gpg_err_code (err) == GPG_ERR_ENOENT) { /* That is an expected error; return NULL. */ } else { log_fatal ("can't open '%s': %s\n", fname, gpg_strerror (err)); } } if (r_fname) *r_fname = fname; else xfree (fname); return fp; } /* Write the state to a possible new state file. */ static void write_state (nvc_t state, int create_flag) { gpg_error_t err; char *fname = NULL; estream_t fp; fp = open_pairing_state (get_session_id (), create_flag, &fname); log_assert (fp); err = nvc_write (state, fp); if (err) { es_fclose (fp); gnupg_remove (fname); log_fatal ("error writing '%s': %s\n", fname, gpg_strerror (err)); } /* If we did not create the file, we need to truncate the file. */ if (!create_flag && ftruncate (es_fileno (fp), es_ftello (fp))) { err = gpg_error_from_syserror (); log_fatal ("error truncating '%s': %s\n", fname, gpg_strerror (err)); } if (es_ferror (fp) || es_fclose (fp)) { err = gpg_error_from_syserror (); es_fclose (fp); gnupg_remove (fname); log_fatal ("error writing '%s': %s\n", fname, gpg_strerror (err)); } } /* Read the state into a newly allocated state object and store that * at R_STATE. If no state is available GPG_ERR_NOT_FOUND is returned * and as with all errors NULL is tored at R_STATE. SESSIONID is an * input with the 8 session id. */ static gpg_error_t read_state (nvc_t *r_state) { gpg_error_t err; char *fname = NULL; estream_t fp; nvc_t state = NULL; nve_t item; const char *value; unsigned long expire; *r_state = NULL; fp = open_pairing_state (get_session_id (), 0, &fname); if (!fp) return gpg_error (GPG_ERR_NOT_FOUND); err = nvc_parse (&state, NULL, fp); if (err) { log_info ("failed to parse state file '%s': %s\n", fname, gpg_strerror (err)); goto leave; } /* Check whether the state already expired. */ item = nvc_lookup (state, "Expires:"); if (!item) { log_info ("invalid state file '%s': %s\n", fname, "field 'expire' not found"); goto leave; } value = nve_value (item); if (!value || !(expire = strtoul (value, NULL, 10))) { log_info ("invalid state file '%s': %s\n", fname, "field 'expire' has an invalid value"); goto leave; } if (expire <= gnupg_get_time ()) { es_fclose (fp); fp = NULL; if (gnupg_remove (fname)) { err = gpg_error_from_syserror (); log_info ("failed to delete state file '%s': %s\n", fname, gpg_strerror (err)); } else if (opt.verbose) log_info ("state file '%s' deleted\n", fname); err = gpg_error (GPG_ERR_NOT_FOUND); goto leave; } *r_state = state; state = NULL; leave: nvc_release (state); es_fclose (fp); return err; } /* Send (MSG,MSGLEN) to the output device. */ static void send_message (const unsigned char *msg, size_t msglen) { gpg_error_t err; if (opt.verbose) log_info ("session %s: sending %s message\n", get_session_id_hex (), msgtypestr (msg[7])); if (DBG_MESSAGE) log_printhex (msg, msglen, "send msg(%s):", msgtypestr (msg[7])); /* FIXME: For now only stdout. */ if (opt.armor) { gpgrt_b64state_t state; state = gpgrt_b64enc_start (es_stdout, ""); if (!state) log_fatal ("error setting up base64 encoder: %s\n", gpg_strerror (gpg_error_from_syserror ())); err = gpgrt_b64enc_write (state, msg, msglen); if (!err) err = gpgrt_b64enc_finish (state); if (err) log_fatal ("error writing base64 to stdout: %s\n", gpg_strerror (err)); } else { if (es_fwrite (msg, msglen, 1, es_stdout) != 1) log_fatal ("error writing to stdout: %s\n", gpg_strerror (gpg_error_from_syserror ())); } es_fputc ('\n', es_stdout); } /* Read a message from stdin and store it at the address (R_MSG, * R_MSGLEN). This function detects armoring and removes it. On * error NULL is stored at R_MSG, a diagnostic printed and an error * code returned. The returned message has a proper message type and * an appropriate length. The message type is stored at R_MSGTYPE and * if a state is available it is stored at R_STATE. */ static gpg_error_t read_message (unsigned char **r_msg, size_t *r_msglen, int *r_msgtype, nvc_t *r_state) { gpg_error_t err; unsigned char msg[128]; /* max msg size is 80 but 107 with base64. */ size_t msglen; size_t reqlen; *r_msg = NULL; *r_state = NULL; es_setvbuf (es_stdin, NULL, _IONBF, 0); es_set_binary (es_stdin); if (es_read (es_stdin, msg, sizeof msg, &msglen)) { err = gpg_error_from_syserror (); log_error ("error reading from message: %s\n", gpg_strerror (err)); return err; } if (msglen > 4 && !memcmp (msg, "R1BH", 4)) { /* This is base64 of the first 3 bytes. */ gpgrt_b64state_t state = gpgrt_b64dec_start (NULL); if (!state) log_fatal ("error setting up base64 decoder: %s\n", gpg_strerror (gpg_error_from_syserror ())); err = gpgrt_b64dec_proc (state, msg, msglen, &msglen); gpgrt_b64dec_finish (state); if (err) { log_error ("error decoding message: %s\n", gpg_strerror (err)); return err; } } if (msglen < 16 || memcmp (msg, "GPG-pa1", 7)) { log_error ("error parsing message: %s\n", msglen? "invalid header":"empty message"); return gpg_error (GPG_ERR_INV_RESPONSE); } switch (msg[7]) { case MSG_TYPE_COMMIT: reqlen = 56; break; case MSG_TYPE_DHPART1: reqlen = 80; break; case MSG_TYPE_DHPART2: reqlen = 80; break; case MSG_TYPE_CONFIRM: reqlen = 48; break; default: log_error ("error parsing message: %s\n", "invalid message type"); return gpg_error (GPG_ERR_INV_RESPONSE); } if (msglen < reqlen) { log_error ("error parsing message: %s\n", "message too short"); return gpg_error (GPG_ERR_INV_RESPONSE); } if (DBG_MESSAGE) log_printhex (msg, msglen, "recv msg(%s):", msgtypestr (msg[7])); /* Note that we ignore any garbage at the end of a message. */ msglen = reqlen; set_session_id (msg+8, 8); if (opt.verbose) log_info ("session %s: received %s message\n", get_session_id_hex (), msgtypestr (msg[7])); /* Read the state. */ err = read_state (r_state); if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND) return err; *r_msg = xmalloc (msglen); memcpy (*r_msg, msg, msglen); *r_msglen = msglen; *r_msgtype = msg[7]; return err; } /* Display the Short Authentication String (SAS). If WAIT is true the * function waits until the user has entered the SAS as seen at the * peer. * * To construct the SAS we take the 4 most significant octets of HASH, * interpret them as a 32 bit big endian unsigned integer, divide that * integer by 10^9 and take the remainder. The remainder is displayed * as 3 groups of 3 decimal digits delimited by a hyphens. This gives * a search space of close to 2^30 and is still easy to compare. */ static gpg_error_t display_sas (const unsigned char *hash, size_t hashlen, int wait) { gpg_error_t err = 0; unsigned long sas = 0; char sasbuf[12]; log_assert (hashlen >= 4); sas |= (unsigned long)hash[20] << 24; sas |= (unsigned long)hash[21] << 16; sas |= (unsigned long)hash[22] << 8; sas |= (unsigned long)hash[23]; sas %= 1000000000ul; snprintf (sasbuf, sizeof sasbuf, "%09lu", sas); memmove (sasbuf+8, sasbuf+6, 3); memmove (sasbuf+4, sasbuf+3, 3); sasbuf[3] = sasbuf[7] = '-'; sasbuf[11] = 0; if (wait) log_info ("Please check the SAS:\n"); else log_info ("Please note the SAS:\n"); log_info ("\n"); log_info (" %s\n", sasbuf); log_info ("\n"); if (wait) { if (!opt.sas || strcmp (sasbuf, opt.sas)) err = gpg_error (GPG_ERR_NOT_CONFIRMED); else log_info ("SAS confirmed\n"); } if (err) log_info ("checking SAS failed: %s\n", gpg_strerror (err)); return err; } static gpg_error_t create_dh_keypair (unsigned char *dh_secret, size_t dh_secret_len, unsigned char *dh_public, size_t dh_public_len) { gpg_error_t err; unsigned char *p; /* We need a temporary buffer for the public key. Check the length * for the later memcpy. */ if (dh_public_len < 32 || dh_secret_len < 32) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); if (gcry_ecc_get_algo_keylen (GCRY_ECC_CURVE25519) > dh_public_len) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); p = gcry_random_bytes (32, GCRY_VERY_STRONG_RANDOM); if (!p) return gpg_error_from_syserror (); memcpy (dh_secret, p, 32); xfree (p); err = gcry_ecc_mul_point (GCRY_ECC_CURVE25519, dh_public, dh_secret, NULL); if (err) return err; if (DBG_CRYPTO) { log_printhex (dh_secret, 32, "DH secret:"); log_printhex (dh_public, 32, "DH public:"); } return 0; } /* SHA256 the data given as varargs tuples of (const void*, size_t) * and store the result in RESULT. The end of the list is indicated * by a NULL element in a tuple. RESULTLEN gives the length of the * RESULT buffer which must be at least 32. Note that the second item * of the tuple is the length and it is a size_t. */ static void * hash_data (void *result, size_t resultsize, ...) { va_list arg_ptr; gpg_error_t err; gcry_md_hd_t hd; const void *data; size_t datalen; log_assert (resultsize >= 32); err = gcry_md_open (&hd, GCRY_MD_SHA256, 0); if (err) log_fatal ("error creating a Hash handle: %s\n", gpg_strerror (err)); /* log_printhex ("", 0, "Hash-256:"); */ va_start (arg_ptr, resultsize); while ((data = va_arg (arg_ptr, const void *))) { datalen = va_arg (arg_ptr, size_t); /* log_printhex (data, datalen, " data:"); */ gcry_md_write (hd, data, datalen); } va_end (arg_ptr); memcpy (result, gcry_md_read (hd, 0), 32); /* log_printhex (result, 32, " result:"); */ gcry_md_close (hd); return result; } /* HMAC-SHA256 the data given as varargs tuples of (const void*, * size_t) using (KEYLEN,KEY) and store the result in RESULT. The end * of the list is indicated by a NULL element in a tuple. RESULTLEN * gives the length of the RESULT buffer which must be at least 32. * Note that the second item of the tuple is the length and it is a * size_t. */ static void * hmac_data (void *result, size_t resultsize, const unsigned char *key, size_t keylen, ...) { va_list arg_ptr; gpg_error_t err; gcry_mac_hd_t hd; const void *data; size_t datalen; log_assert (resultsize >= 32); err = gcry_mac_open (&hd, GCRY_MAC_HMAC_SHA256, 0, NULL); if (err) log_fatal ("error creating a MAC handle: %s\n", gpg_strerror (err)); err = gcry_mac_setkey (hd, key, keylen); if (err) log_fatal ("error setting the MAC key: %s\n", gpg_strerror (err)); /* log_printhex (key, keylen, "HMAC-key:"); */ va_start (arg_ptr, keylen); while ((data = va_arg (arg_ptr, const void *))) { datalen = va_arg (arg_ptr, size_t); /* log_printhex (data, datalen, " data:"); */ err = gcry_mac_write (hd, data, datalen); if (err) log_fatal ("error writing to the MAC handle: %s\n", gpg_strerror (err)); } va_end (arg_ptr); err = gcry_mac_read (hd, result, &resultsize); if (err || resultsize != 32) log_fatal ("error reading MAC value: %s\n", gpg_strerror (err)); /* log_printhex (result, resultsize, " result:"); */ gcry_mac_close (hd); return result; } /* Key derivation function: * * FIXME(doc) */ static void kdf (unsigned char *result, size_t resultlen, const unsigned char *master, size_t masterlen, const unsigned char *sessionid, size_t sessionidlen, const unsigned char *expire, size_t expirelen, const char *label) { log_assert (masterlen == 32 && sessionidlen == 8 && expirelen == 5); log_assert (*label); log_assert (resultlen == 32); hmac_data (result, resultlen, master, masterlen, "\x00\x00\x00\x01", (size_t)4, /* Counter=1*/ label, strlen (label) + 1, /* Label, 0x00 */ sessionid, sessionidlen, /* Context */ expire, expirelen, /* Context */ "\x00\x00\x01\x00", (size_t)4, /* L=256 */ NULL); } static gpg_error_t compute_master_secret (unsigned char *master, size_t masterlen, const unsigned char *sk_a, size_t sk_a_len, const unsigned char *pk_b, size_t pk_b_len) { gpg_error_t err; log_assert (masterlen == 32); log_assert (sk_a_len == 32); log_assert (pk_b_len == 32); err = gcry_ecc_mul_point (GCRY_ECC_CURVE25519, master, sk_a, pk_b); if (err) log_error ("error computing DH: %s\n", gpg_strerror (err)); return err; } /* We are the Initiator: Create the commit message. This function * sends the COMMIT message and writes STATE. */ static gpg_error_t make_msg_commit (nvc_t state) { gpg_error_t err; uint64_t now, expire; unsigned char secret[32]; unsigned char public[32]; unsigned char *newmsg; size_t newmsglen; unsigned char tmphash[32]; err = create_dh_keypair (secret, sizeof secret, public, sizeof public ); if (err) log_error ("creating DH keypair failed: %s\n", gpg_strerror (err)); now = gnupg_get_time (); expire = now + opt.ttl; newmsglen = 7+1+8+1+2+5+32; newmsg = xmalloc (newmsglen); memcpy (newmsg+0, "GPG-pa1", 7); newmsg[7] = MSG_TYPE_COMMIT; memcpy (newmsg+8, get_session_id (), 8); newmsg[16] = REALM_STANDARD; newmsg[17] = 0; newmsg[18] = 0; newmsg[19] = expire >> 32; newmsg[20] = expire >> 24; newmsg[21] = expire >> 16; newmsg[22] = expire >> 8; newmsg[23] = expire; gcry_md_hash_buffer (GCRY_MD_SHA256, newmsg+24, public, 32); /* Create the state file. */ xnvc_set (state, "State:", "Commit-sent"); xnvc_set_printf (state, "Created:", "%llu", (unsigned long long)now); xnvc_set_printf (state, "Expires:", "%llu", (unsigned long long)expire); xnvc_set_hex (state, "DH-PKi:", public, 32); xnvc_set_hex (state, "DH-SKi:", secret, 32); gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, newmsg, newmsglen); xnvc_set_hex (state, "Hash-Commit:", tmphash, 32); /* Write the state. Note that we need to create it. The state * updating should in theory be done atomically with send_message. * However, we can't assure that the message will actually be * delivered and thus it doesn't matter whether we have an already * update state when we later fail in send_message. */ write_state (state, 1); /* Write the message. */ send_message (newmsg, newmsglen); xfree (newmsg); return err; } /* We are the Responder: Process a commit message in (MSG,MSGLEN) * which has already been validated to have a correct header and * message type. Sends the DHPart1 message and writes STATE. */ static gpg_error_t proc_msg_commit (nvc_t state, const unsigned char *msg, size_t msglen) { gpg_error_t err; uint64_t now, expire; unsigned char tmphash[32]; unsigned char secret[32]; unsigned char public[32]; unsigned char *newmsg = NULL; size_t newmsglen; log_assert (msglen >= 56); now = gnupg_get_time (); /* Check that the message has not expired. */ expire = (uint64_t)msg[19] << 32; expire |= (uint64_t)msg[20] << 24; expire |= (uint64_t)msg[21] << 16; expire |= (uint64_t)msg[22] << 8; expire |= (uint64_t)msg[23]; if (expire < now) { log_error ("received %s message is too old\n", msgtypestr (MSG_TYPE_COMMIT)); err = gpg_error (GPG_ERR_TOO_OLD); goto leave; } /* Create the response. */ err = create_dh_keypair (secret, sizeof secret, public, sizeof public ); if (err) { log_error ("creating DH keypair failed: %s\n", gpg_strerror (err)); goto leave; } newmsglen = 7+1+8+32+32; newmsg = xmalloc (newmsglen); memcpy (newmsg+0, "GPG-pa1", 7); newmsg[7] = MSG_TYPE_DHPART1; memcpy (newmsg+8, msg + 8, 8); /* SessionID. */ memcpy (newmsg+16, public, 32); /* PKr */ /* Hash(Hash(Commit) || DHPart1[0..47]) */ gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, msg, msglen); hash_data (newmsg+48, 32, tmphash, sizeof tmphash, newmsg, (size_t)48, NULL); /* Update the state. */ xnvc_set (state, "State:", "DHPart1-sent"); xnvc_set_printf (state, "Created:", "%llu", (unsigned long long)now); xnvc_set_printf (state, "Expires:", "%llu", (unsigned long long)expire); xnvc_set_hex (state, "Hash-PKi:", msg+24, 32); xnvc_set_hex (state, "DH-PKr:", public, 32); xnvc_set_hex (state, "DH-SKr:", secret, 32); gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, newmsg, newmsglen); xnvc_set_hex (state, "Hash-DHPart1:", tmphash, 32); /* Write the state. Note that we need to create it. */ write_state (state, 1); /* Write the message. */ send_message (newmsg, newmsglen); leave: xfree (newmsg); return err; } /* We are the Initiator: Process a DHPART1 message in (MSG,MSGLEN) * which has already been validated to have a correct header and * message type. Sends the DHPart2 message and writes STATE. */ static gpg_error_t proc_msg_dhpart1 (nvc_t state, const unsigned char *msg, size_t msglen) { gpg_error_t err; unsigned char hash[32]; unsigned char tmphash[32]; unsigned char pki[32]; unsigned char pkr[32]; unsigned char ski[32]; unsigned char master[32]; uint64_t expire; unsigned char expirebuf[5]; unsigned char hmacikey[32]; unsigned char symxkey[32]; unsigned char *newmsg = NULL; size_t newmsglen; log_assert (msglen >= 80); /* Check that the message includes the Hash(Commit). */ if (hex2bin (xnvc_get_string (state, "Hash-Commit:"), hash, sizeof hash) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'Hash-Commit' in our state file\n"); goto leave; } hash_data (tmphash, 32, hash, sizeof hash, msg, (size_t)48, NULL); if (memcmp (msg+48, tmphash, 32)) { err = gpg_error (GPG_ERR_BAD_DATA); log_error ("manipulation of received %s message detected: %s\n", msgtypestr (MSG_TYPE_DHPART1), "Bad Hash"); goto leave; } /* Check that the received PKr is different from our PKi and copy * PKr into PKR. */ if (hex2bin (xnvc_get_string (state, "DH-PKi:"), pki, sizeof pki) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'DH-PKi' in our state file\n"); goto leave; } if (!memcmp (msg+16, pki, 32)) { /* This can only happen if the state file leaked to the * responder. */ err = gpg_error (GPG_ERR_BAD_DATA); log_error ("received our own public key PKi instead of PKr\n"); goto leave; } memcpy (pkr, msg+16, 32); /* Put the expire value into a buffer. */ expire = string_to_u64 (xnvc_get_string (state, "Expires:")); if (!expire) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no 'Expire' in our state file\n"); goto leave; } expirebuf[0] = expire >> 32; expirebuf[1] = expire >> 24; expirebuf[2] = expire >> 16; expirebuf[3] = expire >> 8; expirebuf[4] = expire; /* Get our secret from the state. */ if (hex2bin (xnvc_get_string (state, "DH-SKi:"), ski, sizeof ski) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'DH-SKi' in our state file\n"); goto leave; } /* Compute the shared secrets. */ err = compute_master_secret (master, sizeof master, ski, sizeof ski, pkr, sizeof pkr); if (err) { log_error ("creating DH keypair failed: %s\n", gpg_strerror (err)); goto leave; } kdf (hmacikey, sizeof hmacikey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-HMACi-key"); kdf (symxkey, sizeof symxkey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-SYMx-key"); /* Create the response. */ newmsglen = 7+1+8+32+32; newmsg = xmalloc (newmsglen); memcpy (newmsg+0, "GPG-pa1", 7); newmsg[7] = MSG_TYPE_DHPART2; memcpy (newmsg+8, msg + 8, 8); /* SessionID. */ memcpy (newmsg+16, pki, 32); /* PKi */ /* MAC(HMACi-key, Hash(DHPART1) || DHPART2[0..47] || SYMx-key) */ gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, msg, msglen); hmac_data (newmsg+48, 32, hmacikey, sizeof hmacikey, tmphash, sizeof tmphash, newmsg, (size_t)48, symxkey, sizeof symxkey, NULL); /* Update the state. */ xnvc_set (state, "State:", "DHPart2-sent"); xnvc_set_hex (state, "DH-Master:", master, sizeof master); gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, newmsg, newmsglen); xnvc_set_hex (state, "Hash-DHPart2:", tmphash, 32); /* Write the state. */ write_state (state, 0); /* Write the message. */ send_message (newmsg, newmsglen); leave: xfree (newmsg); return err; } /* We are the Responder: Process a DHPART2 message in (MSG,MSGLEN) * which has already been validated to have a correct header and * message type. Sends the CONFIRM message and writes STATE. */ static gpg_error_t proc_msg_dhpart2 (nvc_t state, const unsigned char *msg, size_t msglen) { gpg_error_t err; unsigned char hash[32]; unsigned char tmphash[32]; uint64_t expire; unsigned char expirebuf[5]; unsigned char pki[32]; unsigned char pkr[32]; unsigned char skr[32]; unsigned char master[32]; unsigned char hmacikey[32]; unsigned char hmacrkey[32]; unsigned char symxkey[32]; unsigned char sas[32]; unsigned char *newmsg = NULL; size_t newmsglen; log_assert (msglen >= 80); /* Check that the PKi in the message matches the Hash(Pki) received * with the Commit message. */ memcpy (pki, msg + 16, 32); gcry_md_hash_buffer (GCRY_MD_SHA256, hash, pki, 32); if (hex2bin (xnvc_get_string (state, "Hash-PKi:"), tmphash, sizeof tmphash) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'Hash-PKi' in our state file\n"); goto leave; } if (memcmp (hash, tmphash, 32)) { err = gpg_error (GPG_ERR_BAD_DATA); log_error ("Initiator sent a different key in %s than announced in %s\n", msgtypestr (MSG_TYPE_DHPART2), msgtypestr (MSG_TYPE_COMMIT)); goto leave; } /* Check that the received PKi is different from our PKr. */ if (hex2bin (xnvc_get_string (state, "DH-PKr:"), pkr, sizeof pkr) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'DH-PKr' in our state file\n"); goto leave; } if (!memcmp (pkr, pki, 32)) { err = gpg_error (GPG_ERR_BAD_DATA); log_error ("Initiator sent our own PKr back\n"); goto leave; } /* Put the expire value into a buffer. */ expire = string_to_u64 (xnvc_get_string (state, "Expires:")); if (!expire) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no 'Expire' in our state file\n"); goto leave; } expirebuf[0] = expire >> 32; expirebuf[1] = expire >> 24; expirebuf[2] = expire >> 16; expirebuf[3] = expire >> 8; expirebuf[4] = expire; /* Get our secret from the state. */ if (hex2bin (xnvc_get_string (state, "DH-SKr:"), skr, sizeof skr) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'DH-SKr' in our state file\n"); goto leave; } /* Compute the shared secrets. */ err = compute_master_secret (master, sizeof master, skr, sizeof skr, pki, sizeof pki); if (err) { log_error ("creating DH keypair failed: %s\n", gpg_strerror (err)); goto leave; } kdf (hmacikey, sizeof hmacikey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-HMACi-key"); kdf (hmacrkey, sizeof hmacrkey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-HMACr-key"); kdf (symxkey, sizeof symxkey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-SYMx-key"); kdf (sas, sizeof sas, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-SAS"); /* Check the MAC from the message which is * MAC(HMACi-key, Hash(DHPART1) || DHPART2[0..47] || SYMx-key). * For that we need to fetch the stored hash from the state. */ if (hex2bin (xnvc_get_string (state, "Hash-DHPart1:"), tmphash, sizeof tmphash) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'Hash-DHPart1' in our state file\n"); goto leave; } hmac_data (hash, 32, hmacikey, sizeof hmacikey, tmphash, sizeof tmphash, msg, 48, symxkey, sizeof symxkey, NULL); if (memcmp (msg+48, hash, 32)) { err = gpg_error (GPG_ERR_BAD_DATA); log_error ("manipulation of received %s message detected: %s\n", msgtypestr (MSG_TYPE_DHPART2), "Bad MAC"); goto leave; } /* Create the response. */ newmsglen = 7+1+8+32; newmsg = xmalloc (newmsglen); memcpy (newmsg+0, "GPG-pa1", 7); newmsg[7] = MSG_TYPE_CONFIRM; memcpy (newmsg+8, msg + 8, 8); /* SessionID. */ /* MAC(HMACr-key, Hash(DHPART2) || CONFIRM[0..15] || SYMx-key) */ gcry_md_hash_buffer (GCRY_MD_SHA256, tmphash, msg, msglen); hmac_data (newmsg+16, 32, hmacrkey, sizeof hmacrkey, tmphash, sizeof tmphash, newmsg, (size_t)16, symxkey, sizeof symxkey, NULL); /* Update the state. */ xnvc_set (state, "State:", "Confirm-sent"); xnvc_set_hex (state, "DH-Master:", master, sizeof master); /* Write the state. */ write_state (state, 0); /* Write the message. */ send_message (newmsg, newmsglen); display_sas (sas, sizeof sas, 0); leave: xfree (newmsg); return err; } /* We are the Initiator: Process a CONFIRM message in (MSG,MSGLEN) * which has already been validated to have a correct header and * message type. Does not send anything back. */ static gpg_error_t proc_msg_confirm (nvc_t state, const unsigned char *msg, size_t msglen) { gpg_error_t err; unsigned char hash[32]; unsigned char tmphash[32]; unsigned char master[32]; uint64_t expire; unsigned char expirebuf[5]; unsigned char hmacrkey[32]; unsigned char symxkey[32]; unsigned char sas[32]; log_assert (msglen >= 48); /* Put the expire value into a buffer. */ expire = string_to_u64 (xnvc_get_string (state, "Expires:")); if (!expire) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no 'Expire' in our state file\n"); goto leave; } expirebuf[0] = expire >> 32; expirebuf[1] = expire >> 24; expirebuf[2] = expire >> 16; expirebuf[3] = expire >> 8; expirebuf[4] = expire; /* Get the master secret. */ if (hex2bin (xnvc_get_string (state, "DH-Master:"),master,sizeof master) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'DH-Master' in our state file\n"); goto leave; } kdf (hmacrkey, sizeof hmacrkey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-HMACr-key"); kdf (symxkey, sizeof symxkey, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-SYMx-key"); kdf (sas, sizeof sas, master, sizeof master, msg+8, 8, expirebuf, sizeof expirebuf, "GPG-pa1-SAS"); /* Check the MAC from the message which is */ /* MAC(HMACr-key, Hash(DHPART2) || CONFIRM[0..15] || SYMx-key). */ if (hex2bin (xnvc_get_string (state, "Hash-DHPart2:"), tmphash, sizeof tmphash) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("no or garbled 'Hash-DHPart2' in our state file\n"); goto leave; } hmac_data (hash, 32, hmacrkey, sizeof hmacrkey, tmphash, sizeof tmphash, msg, (size_t)16, symxkey, sizeof symxkey, NULL); if (!memcmp (msg+48, hash, 32)) { err = gpg_error (GPG_ERR_BAD_DATA); log_error ("manipulation of received %s message detected: %s\n", msgtypestr (MSG_TYPE_CONFIRM), "Bad MAC"); goto leave; } err = display_sas (sas, sizeof sas, 1); if (err) goto leave; /* Update the state. */ xnvc_set (state, "State:", "Confirmed"); /* Write the state. */ write_state (state, 0); leave: return err; } /* Expire old state files. This loops over all state files and remove * those which are expired. */ static void expire_old_states (void) { gpg_error_t err = 0; const char *dirname; - DIR *dir = NULL; - struct dirent *dir_entry; + gnupg_dir_t dir = NULL; + gnupg_dirent_t dir_entry; char *fname = NULL; estream_t fp = NULL; nvc_t nvc = NULL; nve_t item; const char *value; unsigned long expire; unsigned long now = gnupg_get_time (); dirname = get_pairing_statedir (); - dir = opendir (dirname); + dir = gnupg_opendir (dirname); if (!dir) { err = gpg_error_from_syserror (); goto leave; } - while ((dir_entry = readdir (dir))) + while ((dir_entry = gnupg_readdir (dir))) { if (strlen (dir_entry->d_name) != 16+4 || strcmp (dir_entry->d_name + 16, ".pa1")) continue; xfree (fname); fname = make_filename (dirname, dir_entry->d_name, NULL); es_fclose (fp); fp = es_fopen (fname, "rb"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) != GPG_ERR_ENOENT) log_info ("failed to open state file '%s': %s\n", fname, gpg_strerror (err)); continue; } nvc_release (nvc); /* NB.: The following is similar to code in read_state. */ err = nvc_parse (&nvc, NULL, fp); if (err) { log_info ("failed to parse state file '%s': %s\n", fname, gpg_strerror (err)); continue; /* Skip */ } item = nvc_lookup (nvc, "Expires:"); if (!item) { log_info ("invalid state file '%s': %s\n", fname, "field 'expire' not found"); continue; /* Skip */ } value = nve_value (item); if (!value || !(expire = strtoul (value, NULL, 10))) { log_info ("invalid state file '%s': %s\n", fname, "field 'expire' has an invalid value"); continue; /* Skip */ } if (expire <= now) { es_fclose (fp); fp = NULL; if (gnupg_remove (fname)) { err = gpg_error_from_syserror (); log_info ("failed to delete state file '%s': %s\n", fname, gpg_strerror (err)); } else if (opt.verbose) log_info ("state file '%s' deleted\n", fname); } } leave: if (err) log_error ("expiring old states in '%s' failed: %s\n", dirname, gpg_strerror (err)); - if (dir) - closedir (dir); + gnupg_closedir (dir); es_fclose (fp); xfree (fname); } /* Initiate a pairing. The output needs to be conveyed to the * peer */ static gpg_error_t command_initiate (void) { gpg_error_t err; nvc_t state; state = xnvc_new (); xnvc_set (state, "Version:", "GPG-pa1"); xnvc_set_hex (state, "Session:", get_session_id (), 8); xnvc_set (state, "Role:", "Initiator"); err = make_msg_commit (state); nvc_release (state); return err; } /* Helper for command_respond(). */ static gpg_error_t expect_state (int msgtype, const char *statestr, const char *expected) { if (strcmp (statestr, expected)) { log_error ("received %s message in %s state (should be %s)\n", msgtypestr (msgtype), statestr, expected); return gpg_error (GPG_ERR_INV_RESPONSE); } return 0; } /* Respond to a pairing intiation. This is used by the peer and later * by the original responder. Depending on the state the output needs * to be conveyed to the peer. */ static gpg_error_t command_respond (void) { gpg_error_t err; unsigned char *msg; size_t msglen = 0; /* In case that read_message returns an error. */ int msgtype = 0; /* ditto. */ nvc_t state; const char *rolestr; const char *statestr; err = read_message (&msg, &msglen, &msgtype, &state); if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND) goto leave; rolestr = xnvc_get_string (state, "Role:"); statestr = xnvc_get_string (state, "State:"); if (DBG_MESSAGE) { if (!state) log_debug ("no state available\n"); else log_debug ("we are %s, our current state is %s\n", rolestr, statestr); log_debug ("got message of type %s (%d)\n", msgtypestr (msgtype), msgtype); } if (!state) { if (msgtype == MSG_TYPE_COMMIT) { state = xnvc_new (); xnvc_set (state, "Version:", "GPG-pa1"); xnvc_set_hex (state, "Session:", get_session_id (), 8); xnvc_set (state, "Role:", "Responder"); err = proc_msg_commit (state, msg, msglen); } else { log_error ("%s message expected but got %s\n", msgtypestr (MSG_TYPE_COMMIT), msgtypestr (msgtype)); if (msgtype == MSG_TYPE_DHPART1) log_info ("the pairing probably took too long and timed out\n"); err = gpg_error (GPG_ERR_INV_RESPONSE); goto leave; } } else if (!strcmp (rolestr, "Initiator")) { if (msgtype == MSG_TYPE_DHPART1) { if (!(err = expect_state (msgtype, statestr, "Commit-sent"))) err = proc_msg_dhpart1 (state, msg, msglen); } else if (msgtype == MSG_TYPE_CONFIRM) { if (!(err = expect_state (msgtype, statestr, "DHPart2-sent"))) err = proc_msg_confirm (state, msg, msglen); } else { log_error ("%s message not expected by Initiator\n", msgtypestr (msgtype)); err = gpg_error (GPG_ERR_INV_RESPONSE); goto leave; } } else if (!strcmp (rolestr, "Responder")) { if (msgtype == MSG_TYPE_DHPART2) { if (!(err = expect_state (msgtype, statestr, "DHPart1-sent"))) err = proc_msg_dhpart2 (state, msg, msglen); } else { log_error ("%s message not expected by Responder\n", msgtypestr (msgtype)); err = gpg_error (GPG_ERR_INV_RESPONSE); goto leave; } } else log_fatal ("invalid role '%s' in state file\n", rolestr); leave: xfree (msg); nvc_release (state); return err; } /* Return the keys for SESSIONIDSTR or the last one if it is NULL. * Two keys are returned: The first is the one for sending encrypted * data and the second one for decrypting received data. The keys are * always returned hex encoded and both are terminated by a LF. */ static gpg_error_t command_get (const char *sessionidstr) { gpg_error_t err; unsigned char sessid[8]; nvc_t state; if (!sessionidstr) { log_error ("calling without session-id is not yet implemented\n"); err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); goto leave; } if (hex2bin (sessionidstr, sessid, sizeof sessid) < 0) { err = gpg_error (GPG_ERR_INV_VALUE); log_error ("invalid session id given\n"); goto leave; } set_session_id (sessid, sizeof sessid); err = read_state (&state); if (err) { log_error ("reading state of session %s failed: %s\n", sessionidstr, gpg_strerror (err)); goto leave; } leave: return err; } /* Cleanup command. */ static gpg_error_t command_cleanup (void) { expire_old_states (); return 0; } diff --git a/tools/gpg-wks-server.c b/tools/gpg-wks-server.c index 0cfe47fba..937479260 100644 --- a/tools/gpg-wks-server.c +++ b/tools/gpg-wks-server.c @@ -1,1991 +1,1989 @@ /* gpg-wks-server.c - A server for the Web Key Service protocols. * Copyright (C) 2016, 2018 Werner Koch * 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. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ /* The Web Key Service I-D defines an update protocol to store a * public key in the Web Key Directory. The current specification is * draft-koch-openpgp-webkey-service-05.txt. */ #include #include #include #include #include #include #include #include #define INCLUDED_BY_MAIN_MODULE 1 #include "../common/util.h" #include "../common/init.h" #include "../common/sysutils.h" #include "../common/userids.h" #include "../common/ccparray.h" #include "../common/exectool.h" #include "../common/zb32.h" #include "../common/mbox-util.h" #include "../common/name-value.h" #include "mime-maker.h" #include "send-mail.h" #include "gpg-wks.h" /* The time we wait for a confirmation response. */ #define PENDING_TTL (86400 * 3) /* 3 days. */ /* Constants to identify the commands and options. */ enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oOutput = 'o', oDirectory = 'C', oDebug = 500, aReceive, aCron, aListDomains, aInstallKey, aRevokeKey, aRemoveKey, aCheck, oGpgProgram, oSend, oFrom, oHeader, oWithDir, oWithFile, oDummy }; /* The list of commands and options. */ static gpgrt_opt_t opts[] = { ARGPARSE_group (300, ("@Commands:\n ")), ARGPARSE_c (aReceive, "receive", ("receive a submission or confirmation")), ARGPARSE_c (aCron, "cron", ("run regular jobs")), ARGPARSE_c (aListDomains, "list-domains", ("list configured domains")), ARGPARSE_c (aCheck, "check", ("check whether a key is installed")), ARGPARSE_c (aCheck, "check-key", "@"), ARGPARSE_c (aInstallKey, "install-key", "install a key from FILE into the WKD"), ARGPARSE_c (aRemoveKey, "remove-key", "remove a key from the WKD"), ARGPARSE_c (aRevokeKey, "revoke-key", "mark a key as revoked"), ARGPARSE_group (301, ("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", ("verbose")), ARGPARSE_s_n (oQuiet, "quiet", ("be somewhat more quiet")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_s (oGpgProgram, "gpg", "@"), ARGPARSE_s_n (oSend, "send", "send the mail using sendmail"), ARGPARSE_s_s (oOutput, "output", "|FILE|write the mail to FILE"), ARGPARSE_s_s (oDirectory, "directory", "|DIR|use DIR as top directory"), ARGPARSE_s_s (oFrom, "from", "|ADDR|use ADDR as the default sender"), ARGPARSE_s_s (oHeader, "header" , "|NAME=VALUE|add \"NAME: VALUE\" as header to all mails"), ARGPARSE_s_n (oWithDir, "with-dir", "@"), ARGPARSE_s_n (oWithFile, "with-file", "@"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_MIME_VALUE , "mime" }, { DBG_PARSER_VALUE , "parser" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_IPC_VALUE , "ipc" }, { DBG_EXTPROG_VALUE, "extprog" }, { 0, NULL } }; /* State for processing a message. */ struct server_ctx_s { char *fpr; uidinfo_list_t mboxes; /* List with addr-specs taken from the UIDs. */ unsigned int draft_version_2:1; /* Client supports the draft 2. */ }; typedef struct server_ctx_s *server_ctx_t; /* Flag for --with-dir. */ static int opt_with_dir; /* Flag for --with-file. */ static int opt_with_file; /* Prototypes. */ static gpg_error_t get_domain_list (strlist_t *r_list); static gpg_error_t command_receive_cb (void *opaque, const char *mediatype, estream_t fp, unsigned int flags); static gpg_error_t command_list_domains (void); static gpg_error_t command_revoke_key (const char *mailaddr); static gpg_error_t command_check_key (const char *mailaddr); static gpg_error_t command_cron (void); /* Print usage information and provide strings for help. */ static const char * my_strusage( int level ) { const char *p; switch (level) { case 9: p = "LGPL-2.1-or-later"; break; case 11: p = "gpg-wks-server"; break; case 12: p = "@GNUPG@"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = ("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = ("Usage: gpg-wks-server command [options] (-h for help)"); break; case 41: p = ("Syntax: gpg-wks-server command [options]\n" "Server for the Web Key Service protocol\n"); break; default: p = NULL; break; } return p; } static void wrong_args (const char *text) { es_fprintf (es_stderr, "usage: %s [options] %s\n", gpgrt_strusage (11), text); exit (2); } /* Command line parsing. */ static enum cmd_and_opt_values parse_arguments (gpgrt_argparse_t *pargs, gpgrt_opt_t *popts) { enum cmd_and_opt_values cmd = 0; int no_more_options = 0; while (!no_more_options && gpgrt_argparse (NULL, pargs, popts)) { switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: if (parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags)) { pargs->r_opt = ARGPARSE_INVALID_ARG; pargs->err = ARGPARSE_PRINT_ERROR; } break; case oGpgProgram: opt.gpg_program = pargs->r.ret_str; break; case oDirectory: opt.directory = pargs->r.ret_str; break; case oFrom: opt.default_from = pargs->r.ret_str; break; case oHeader: append_to_strlist (&opt.extra_headers, pargs->r.ret_str); break; case oSend: opt.use_sendmail = 1; break; case oOutput: opt.output = pargs->r.ret_str; break; case oWithDir: opt_with_dir = 1; break; case oWithFile: opt_with_file = 1; break; case aReceive: case aCron: case aListDomains: case aCheck: case aInstallKey: case aRemoveKey: case aRevokeKey: cmd = pargs->r_opt; break; default: pargs->err = ARGPARSE_PRINT_ERROR; break; } } return cmd; } /* gpg-wks-server main. */ int main (int argc, char **argv) { gpg_error_t err, firsterr; gpgrt_argparse_t pargs; enum cmd_and_opt_values cmd; gnupg_reopen_std ("gpg-wks-server"); gpgrt_set_strusage (my_strusage); log_set_prefix ("gpg-wks-server", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ init_common_subsystems (&argc, &argv); /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags = ARGPARSE_FLAG_KEEP; cmd = parse_arguments (&pargs, opts); gpgrt_argparse (NULL, &pargs, NULL); if (log_get_errorcount (0)) exit (2); /* 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]); } /* Set defaults for non given options. */ if (!opt.gpg_program) opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG); if (!opt.directory) opt.directory = "/var/lib/gnupg/wks"; /* Check for syntax errors in the --header option to avoid later * error messages with a not easy to find cause */ if (opt.extra_headers) { strlist_t sl; for (sl = opt.extra_headers; sl; sl = sl->next) { err = mime_maker_add_header (NULL, sl->d, NULL); if (err) log_error ("syntax error in \"--header %s\": %s\n", sl->d, gpg_strerror (err)); } } if (log_get_errorcount (0)) exit (2); /* Check that we have a working directory. */ #if defined(HAVE_STAT) { struct stat sb; if (gnupg_stat (opt.directory, &sb)) { err = gpg_error_from_syserror (); log_error ("error accessing directory '%s': %s\n", opt.directory, gpg_strerror (err)); exit (2); } if (!S_ISDIR(sb.st_mode)) { log_error ("error accessing directory '%s': %s\n", opt.directory, "not a directory"); exit (2); } if (sb.st_uid != getuid()) { log_error ("directory '%s' not owned by user\n", opt.directory); exit (2); } if ((sb.st_mode & (S_IROTH|S_IWOTH))) { log_error ("directory '%s' has too relaxed permissions\n", opt.directory); log_info ("Fix by running: chmod o-rw '%s'\n", opt.directory); exit (2); } } #else /*!HAVE_STAT*/ log_fatal ("program build w/o stat() call\n"); #endif /*!HAVE_STAT*/ /* Run the selected command. */ switch (cmd) { case aReceive: if (argc) wrong_args ("--receive"); err = wks_receive (es_stdin, command_receive_cb, NULL); break; case aCron: if (argc) wrong_args ("--cron"); err = command_cron (); break; case aListDomains: err = command_list_domains (); break; case aInstallKey: if (!argc) err = wks_cmd_install_key (NULL, NULL); else if (argc == 2) err = wks_cmd_install_key (*argv, argv[1]); else wrong_args ("--install-key [FILE|FINGERPRINT USER-ID]"); break; case aRemoveKey: if (argc != 1) wrong_args ("--remove-key USER-ID"); err = wks_cmd_remove_key (*argv); break; case aRevokeKey: if (argc != 1) wrong_args ("--revoke-key USER-ID"); err = command_revoke_key (*argv); break; case aCheck: if (!argc) wrong_args ("--check USER-IDs"); firsterr = 0; for (; argc; argc--, argv++) { err = command_check_key (*argv); if (!firsterr) firsterr = err; } err = firsterr; break; default: gpgrt_usage (1); err = gpg_error (GPG_ERR_BUG); break; } if (err) log_error ("command failed: %s\n", gpg_strerror (err)); return log_get_errorcount (0)? 1:0; } /* Take the key in KEYFILE and write it to OUTFILE in binary encoding. * If ADDRSPEC is given only matching user IDs are included in the * output. */ static gpg_error_t copy_key_as_binary (const char *keyfile, const char *outfile, const char *addrspec) { gpg_error_t err; ccparray_t ccp; const char **argv = NULL; char *filterexp = NULL; if (addrspec) { filterexp = es_bsprintf ("keep-uid=mbox = %s", 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, "--yes"); ccparray_put (&ccp, "--always-trust"); ccparray_put (&ccp, "--no-keyring"); ccparray_put (&ccp, "--output"); ccparray_put (&ccp, outfile); ccparray_put (&ccp, "--import-options=import-export"); if (filterexp) { ccparray_put (&ccp, "--import-filter"); ccparray_put (&ccp, filterexp); } ccparray_put (&ccp, "--import"); ccparray_put (&ccp, "--"); ccparray_put (&ccp, keyfile); 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, NULL, NULL, NULL, NULL, NULL); if (err) { log_error ("%s failed: %s\n", __func__, gpg_strerror (err)); goto leave; } leave: xfree (filterexp); xfree (argv); return err; } /* Take the key in KEYFILE and write it to DANEFILE using the DANE * output format. */ static gpg_error_t copy_key_as_dane (const char *keyfile, const char *danefile) { gpg_error_t err; ccparray_t ccp; const char **argv; 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, "--yes"); ccparray_put (&ccp, "--always-trust"); ccparray_put (&ccp, "--no-keyring"); ccparray_put (&ccp, "--output"); ccparray_put (&ccp, danefile); ccparray_put (&ccp, "--export-options=export-dane"); ccparray_put (&ccp, "--import-options=import-export"); ccparray_put (&ccp, "--import"); ccparray_put (&ccp, "--"); ccparray_put (&ccp, keyfile); 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, NULL, NULL, NULL, NULL, NULL); if (err) { log_error ("%s failed: %s\n", __func__, gpg_strerror (err)); goto leave; } leave: xfree (argv); return err; } static void encrypt_stream_status_cb (void *opaque, const char *keyword, char *args) { (void)opaque; if (DBG_CRYPTO) log_debug ("gpg status: %s %s\n", keyword, args); } /* Encrypt the INPUT stream to a new stream which is stored at success * at R_OUTPUT. Encryption is done for the key in file KEYFIL. */ static gpg_error_t encrypt_stream (estream_t *r_output, estream_t input, const char *keyfile) { gpg_error_t err; ccparray_t ccp; const char **argv; estream_t output; *r_output = NULL; output = es_fopenmem (0, "w+b"); if (!output) { 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, "--no-keyring"); ccparray_put (&ccp, "--armor"); ccparray_put (&ccp, "-z0"); /* No compression for improved robustness. */ ccparray_put (&ccp, "--recipient-file"); ccparray_put (&ccp, keyfile); ccparray_put (&ccp, "--encrypt"); ccparray_put (&ccp, "--"); 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, input, NULL, output, encrypt_stream_status_cb, NULL); if (err) { log_error ("encryption failed: %s\n", gpg_strerror (err)); goto leave; } es_rewind (output); *r_output = output; output = NULL; leave: es_fclose (output); xfree (argv); return err; } static void sign_stream_status_cb (void *opaque, const char *keyword, char *args) { (void)opaque; if (DBG_CRYPTO) log_debug ("gpg status: %s %s\n", keyword, args); } /* Sign the INPUT stream to a new stream which is stored at success at * R_OUTPUT. A detached signature is created using the key specified * by USERID. */ static gpg_error_t sign_stream (estream_t *r_output, estream_t input, const char *userid) { gpg_error_t err; ccparray_t ccp; const char **argv; estream_t output; *r_output = NULL; output = es_fopenmem (0, "w+b"); if (!output) { 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, "--armor"); ccparray_put (&ccp, "--local-user"); ccparray_put (&ccp, userid); ccparray_put (&ccp, "--detach-sign"); ccparray_put (&ccp, "--"); 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, input, NULL, output, sign_stream_status_cb, NULL); if (err) { log_error ("signing failed: %s\n", gpg_strerror (err)); goto leave; } es_rewind (output); *r_output = output; output = NULL; leave: es_fclose (output); xfree (argv); return err; } /* Get the submission address for address MBOX. Caller must free the * value. If no address can be found NULL is returned. */ static char * get_submission_address (const char *mbox) { gpg_error_t err; const char *domain; char *fname, *line, *p; size_t n; estream_t fp; domain = strchr (mbox, '@'); if (!domain) return NULL; domain++; fname = make_filename_try (opt.directory, domain, "submission-address", NULL); if (!fname) { err = gpg_error_from_syserror (); log_error ("make_filename failed in %s: %s\n", __func__, gpg_strerror (err)); return NULL; } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOENT) log_info ("Note: no specific submission address configured" " for domain '%s'\n", domain); else log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); return NULL; } line = NULL; n = 0; if (es_getline (&line, &n, fp) < 0) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); xfree (line); es_fclose (fp); xfree (fname); return NULL; } es_fclose (fp); xfree (fname); p = strchr (line, '\n'); if (p) *p = 0; trim_spaces (line); if (!is_valid_mailbox (line)) { log_error ("invalid submission address for domain '%s' detected\n", domain); xfree (line); return NULL; } return line; } /* Get the policy flags for address MBOX and store them in POLICY. */ static gpg_error_t get_policy_flags (policy_flags_t policy, const char *mbox) { gpg_error_t err; const char *domain; char *fname; estream_t fp; memset (policy, 0, sizeof *policy); domain = strchr (mbox, '@'); if (!domain) return gpg_error (GPG_ERR_INV_USER_ID); domain++; fname = make_filename_try (opt.directory, domain, "policy", NULL); if (!fname) { err = gpg_error_from_syserror (); log_error ("make_filename failed in %s: %s\n", __func__, gpg_strerror (err)); return err; } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOENT) err = 0; else log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); xfree (fname); return err; } err = wks_parse_policy (policy, fp, 0); es_fclose (fp); xfree (fname); return err; } /* We store the key under the name of the nonce we will then send to * the user. On success the nonce is stored at R_NONCE and the file * name at R_FNAME. */ static gpg_error_t store_key_as_pending (const char *dir, estream_t key, char **r_nonce, char **r_fname) { gpg_error_t err; char *dname = NULL; char *fname = NULL; char *nonce = NULL; estream_t outfp = NULL; char buffer[1024]; size_t nbytes, nwritten; *r_nonce = NULL; *r_fname = NULL; dname = make_filename_try (dir, "pending", NULL); if (!dname) { err = gpg_error_from_syserror (); goto leave; } /* Create the nonce. We use 20 bytes so that we don't waste a * character in our zBase-32 encoding. Using the gcrypt's nonce * function is faster than using the strong random function; this is * Good Enough for our purpose. */ log_assert (sizeof buffer > 20); gcry_create_nonce (buffer, 20); nonce = zb32_encode (buffer, 8 * 20); memset (buffer, 0, 20); /* Not actually needed but it does not harm. */ if (!nonce) { err = gpg_error_from_syserror (); goto leave; } fname = strconcat (dname, "/", nonce, NULL); if (!fname) { err = gpg_error_from_syserror (); goto leave; } /* With 128 bits of random we can expect that no other file exists * under this name. We use "x" to detect internal errors. */ outfp = es_fopen (fname, "wbx,mode=-rw"); if (!outfp) { err = gpg_error_from_syserror (); log_error ("error creating '%s': %s\n", fname, gpg_strerror (err)); goto leave; } es_rewind (key); for (;;) { if (es_read (key, buffer, sizeof buffer, &nbytes)) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", es_fname_get (key), gpg_strerror (err)); break; } if (!nbytes) { err = 0; goto leave; /* Ready. */ } if (es_write (outfp, buffer, nbytes, &nwritten)) { err = gpg_error_from_syserror (); log_error ("error writing '%s': %s\n", fname, gpg_strerror (err)); goto leave; } else if (nwritten != nbytes) { err = gpg_error (GPG_ERR_EIO); log_error ("error writing '%s': %s\n", fname, "short write"); goto leave; } } leave: if (err) { es_fclose (outfp); gnupg_remove (fname); } else if (es_fclose (outfp)) { err = gpg_error_from_syserror (); log_error ("error closing '%s': %s\n", fname, gpg_strerror (err)); } if (!err) { *r_nonce = nonce; *r_fname = fname; } else { xfree (nonce); xfree (fname); } xfree (dname); return err; } /* Send a confirmation request. DIR is the directory used for the * address MBOX. NONCE is the nonce we want to see in the response to * this mail. FNAME the name of the file with the key. */ static gpg_error_t send_confirmation_request (server_ctx_t ctx, const char *mbox, const char *nonce, const char *keyfile) { gpg_error_t err; estream_t body = NULL; estream_t bodyenc = NULL; estream_t signeddata = NULL; estream_t signature = NULL; mime_maker_t mime = NULL; char *from_buffer = NULL; const char *from; strlist_t sl; from = from_buffer = get_submission_address (mbox); if (!from) { from = opt.default_from; if (!from) { log_error ("no sender address found for '%s'\n", mbox); err = gpg_error (GPG_ERR_CONFIGURATION); goto leave; } log_info ("Note: using default sender address '%s'\n", from); } body = es_fopenmem (0, "w+b"); if (!body) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } if (!ctx->draft_version_2) { /* It is fine to use 8 bit encoding because that is encrypted and * only our client will see it. */ es_fputs ("Content-Type: application/vnd.gnupg.wks\n" "Content-Transfer-Encoding: 8bit\n" "\n", body); } es_fprintf (body, ("type: confirmation-request\n" "sender: %s\n" "address: %s\n" "fingerprint: %s\n" "nonce: %s\n"), from, mbox, ctx->fpr, nonce); es_rewind (body); err = encrypt_stream (&bodyenc, body, keyfile); if (err) goto leave; es_fclose (body); body = NULL; err = mime_maker_new (&mime, NULL); if (err) goto leave; err = mime_maker_add_header (mime, "From", from); if (err) goto leave; err = mime_maker_add_header (mime, "To", mbox); if (err) goto leave; err = mime_maker_add_header (mime, "Subject", "Confirm your key publication"); if (err) goto leave; err = mime_maker_add_header (mime, "Wks-Draft-Version", STR2(WKS_DRAFT_VERSION)); if (err) goto leave; /* Help Enigmail to identify messages. Note that this is in no way * secured. */ err = mime_maker_add_header (mime, "WKS-Phase", "confirm"); if (err) goto leave; for (sl = opt.extra_headers; sl; sl = sl->next) { err = mime_maker_add_header (mime, sl->d, NULL); if (err) goto leave; } if (!ctx->draft_version_2) { err = mime_maker_add_header (mime, "Content-Type", "multipart/encrypted; " "protocol=\"application/pgp-encrypted\""); if (err) goto leave; err = mime_maker_add_container (mime); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/pgp-encrypted"); if (err) goto leave; err = mime_maker_add_body (mime, "Version: 1\n"); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/octet-stream"); if (err) goto leave; err = mime_maker_add_stream (mime, &bodyenc); if (err) goto leave; } else { unsigned int partid; /* FIXME: Add micalg. */ err = mime_maker_add_header (mime, "Content-Type", "multipart/signed; " "protocol=\"application/pgp-signature\""); if (err) goto leave; err = mime_maker_add_container (mime); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "multipart/mixed"); if (err) goto leave; err = mime_maker_add_container (mime); if (err) goto leave; partid = mime_maker_get_partid (mime); err = mime_maker_add_header (mime, "Content-Type", "text/plain"); if (err) goto leave; err = mime_maker_add_body (mime, "This message has been send to confirm your request\n" "to publish your key. If you did not request a key\n" "publication, simply ignore this message.\n" "\n" "Most mail software can handle this kind of message\n" "automatically and thus you would not have seen this\n" "message. It seems that your client does not fully\n" "support this service. The web page\n" "\n" " https://gnupg.org/faq/wkd.html\n" "\n" "explains how you can process this message anyway in\n" "a few manual steps.\n"); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/vnd.gnupg.wks"); if (err) goto leave; err = mime_maker_add_stream (mime, &bodyenc); if (err) goto leave; err = mime_maker_end_container (mime); if (err) goto leave; /* mime_maker_dump_tree (mime); */ err = mime_maker_get_part (mime, partid, &signeddata); if (err) goto leave; err = sign_stream (&signature, signeddata, from); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/pgp-signature"); if (err) goto leave; err = mime_maker_add_stream (mime, &signature); if (err) goto leave; } err = wks_send_mime (mime); leave: mime_maker_release (mime); es_fclose (signature); es_fclose (signeddata); es_fclose (bodyenc); es_fclose (body); xfree (from_buffer); return err; } /* Store the key given by KEY into the pending directory and send a * confirmation requests. */ static gpg_error_t process_new_key (server_ctx_t ctx, estream_t key) { gpg_error_t err; uidinfo_list_t sl; const char *s; char *dname = NULL; char *nonce = NULL; char *fname = NULL; struct policy_flags_s policybuf; memset (&policybuf, 0, sizeof policybuf); /* First figure out the user id from the key. */ xfree (ctx->fpr); free_uidinfo_list (ctx->mboxes); err = wks_list_key (key, &ctx->fpr, &ctx->mboxes); if (err) goto leave; log_assert (ctx->fpr); log_info ("fingerprint: %s\n", ctx->fpr); for (sl = ctx->mboxes; sl; sl = sl->next) { if (sl->mbox) log_info (" addr-spec: %s\n", sl->mbox); } /* Walk over all user ids and send confirmation requests for those * we support. */ for (sl = ctx->mboxes; sl; sl = sl->next) { if (!sl->mbox) continue; s = strchr (sl->mbox, '@'); log_assert (s && s[1]); xfree (dname); dname = make_filename_try (opt.directory, s+1, NULL); if (!dname) { err = gpg_error_from_syserror (); goto leave; } if (gnupg_access (dname, W_OK)) { log_info ("skipping address '%s': Domain not configured\n", sl->mbox); continue; } if (get_policy_flags (&policybuf, sl->mbox)) { log_info ("skipping address '%s': Bad policy flags\n", sl->mbox); continue; } if (policybuf.auth_submit) { /* Bypass the confirmation stuff and publish the key as is. */ log_info ("publishing address '%s'\n", sl->mbox); /* FIXME: We need to make sure that we do this only for the * address in the mail. */ log_debug ("auth-submit not yet working!\n"); } else { log_info ("storing address '%s'\n", sl->mbox); xfree (nonce); xfree (fname); err = store_key_as_pending (dname, key, &nonce, &fname); if (err) goto leave; err = send_confirmation_request (ctx, sl->mbox, nonce, fname); if (err) goto leave; } } leave: if (nonce) wipememory (nonce, strlen (nonce)); xfree (nonce); xfree (fname); xfree (dname); wks_free_policy (&policybuf); return err; } /* Send a message to tell the user at MBOX that their key has been * published. FNAME the name of the file with the key. */ static gpg_error_t send_congratulation_message (const char *mbox, const char *keyfile) { gpg_error_t err; estream_t body = NULL; estream_t bodyenc = NULL; mime_maker_t mime = NULL; char *from_buffer = NULL; const char *from; strlist_t sl; from = from_buffer = get_submission_address (mbox); if (!from) { from = opt.default_from; if (!from) { log_error ("no sender address found for '%s'\n", mbox); err = gpg_error (GPG_ERR_CONFIGURATION); goto leave; } log_info ("Note: using default sender address '%s'\n", from); } body = es_fopenmem (0, "w+b"); if (!body) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } /* It is fine to use 8 bit encoding because that is encrypted and * only our client will see it. */ es_fputs ("Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "\n", body); es_fprintf (body, "Hello!\n\n" "The key for your address '%s' has been published\n" "and can now be retrieved from the Web Key Directory.\n" "\n" "For more information on this system see:\n" "\n" " https://gnupg.org/faq/wkd.html\n" "\n" "Best regards\n" "\n" " Gnu Key Publisher\n\n\n" "-- \n" "The GnuPG Project welcomes donations: %s\n", mbox, "https://gnupg.org/donate"); es_rewind (body); err = encrypt_stream (&bodyenc, body, keyfile); if (err) goto leave; es_fclose (body); body = NULL; err = mime_maker_new (&mime, NULL); if (err) goto leave; err = mime_maker_add_header (mime, "From", from); if (err) goto leave; err = mime_maker_add_header (mime, "To", mbox); if (err) goto leave; err = mime_maker_add_header (mime, "Subject", "Your key has been published"); if (err) goto leave; err = mime_maker_add_header (mime, "Wks-Draft-Version", STR2(WKS_DRAFT_VERSION)); if (err) goto leave; err = mime_maker_add_header (mime, "WKS-Phase", "done"); if (err) goto leave; for (sl = opt.extra_headers; sl; sl = sl->next) { err = mime_maker_add_header (mime, sl->d, NULL); if (err) goto leave; } err = mime_maker_add_header (mime, "Content-Type", "multipart/encrypted; " "protocol=\"application/pgp-encrypted\""); if (err) goto leave; err = mime_maker_add_container (mime); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/pgp-encrypted"); if (err) goto leave; err = mime_maker_add_body (mime, "Version: 1\n"); if (err) goto leave; err = mime_maker_add_header (mime, "Content-Type", "application/octet-stream"); if (err) goto leave; err = mime_maker_add_stream (mime, &bodyenc); if (err) goto leave; err = wks_send_mime (mime); leave: mime_maker_release (mime); es_fclose (bodyenc); es_fclose (body); xfree (from_buffer); return err; } /* Check that we have send a request with NONCE and publish the key. */ static gpg_error_t check_and_publish (server_ctx_t ctx, const char *address, const char *nonce) { gpg_error_t err; char *fname = NULL; char *fnewname = NULL; estream_t key = NULL; char *hash = NULL; const char *domain; const char *s; uidinfo_list_t sl; char shaxbuf[32]; /* Used for SHA-1 and SHA-256 */ /* FIXME: There is a bug in name-value.c which adds white space for * the last pair and thus we strip the nonce here until this has * been fixed. */ char *nonce2 = xstrdup (nonce); trim_trailing_spaces (nonce2); nonce = nonce2; domain = strchr (address, '@'); log_assert (domain && domain[1]); domain++; fname = make_filename_try (opt.directory, domain, "pending", nonce, NULL); if (!fname) { err = gpg_error_from_syserror (); goto leave; } /* Try to open the file with the key. */ key = es_fopen (fname, "rb"); if (!key) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOENT) { log_info ("no pending request for '%s'\n", address); err = gpg_error (GPG_ERR_NOT_FOUND); } else log_error ("error reading '%s': %s\n", fname, gpg_strerror (err)); goto leave; } /* We need to get the fingerprint from the key. */ xfree (ctx->fpr); free_uidinfo_list (ctx->mboxes); err = wks_list_key (key, &ctx->fpr, &ctx->mboxes); if (err) goto leave; log_assert (ctx->fpr); log_info ("fingerprint: %s\n", ctx->fpr); for (sl = ctx->mboxes; sl; sl = sl->next) if (sl->mbox) log_info (" addr-spec: %s\n", sl->mbox); /* Check that the key has 'address' as a user id. We use * case-insensitive matching because the client is expected to * return the address verbatim. */ for (sl = ctx->mboxes; sl; sl = sl->next) if (sl->mbox && !strcmp (sl->mbox, address)) break; if (!sl) { log_error ("error publishing key: '%s' is not a user ID of %s\n", address, ctx->fpr); err = gpg_error (GPG_ERR_NO_PUBKEY); goto leave; } /* Hash user ID and create filename. */ err = wks_compute_hu_fname (&fnewname, address); if (err) goto leave; /* Publish. */ err = copy_key_as_binary (fname, fnewname, address); if (err) { err = gpg_error_from_syserror (); log_error ("copying '%s' to '%s' failed: %s\n", fname, fnewname, gpg_strerror (err)); goto leave; } /* Make sure it is world readable. */ if (gnupg_chmod (fnewname, "-rwxr--r--")) log_error ("can't set permissions of '%s': %s\n", fnewname, gpg_strerror (gpg_err_code_from_syserror())); log_info ("key %s published for '%s'\n", ctx->fpr, address); send_congratulation_message (address, fnewname); /* Try to publish as DANE record if the DANE directory exists. */ xfree (fname); fname = fnewname; fnewname = make_filename_try (opt.directory, domain, "dane", NULL); if (!fnewname) { err = gpg_error_from_syserror (); goto leave; } if (!gnupg_access (fnewname, W_OK)) { /* Yes, we have a dane directory. */ s = strchr (address, '@'); log_assert (s); gcry_md_hash_buffer (GCRY_MD_SHA256, shaxbuf, address, s - address); xfree (hash); hash = bin2hex (shaxbuf, 28, NULL); if (!hash) { err = gpg_error_from_syserror (); goto leave; } xfree (fnewname); fnewname = make_filename_try (opt.directory, domain, "dane", hash, NULL); if (!fnewname) { err = gpg_error_from_syserror (); goto leave; } err = copy_key_as_dane (fname, fnewname); if (err) goto leave; log_info ("key %s published for '%s' (DANE record)\n", ctx->fpr, address); } leave: es_fclose (key); xfree (hash); xfree (fnewname); xfree (fname); xfree (nonce2); return err; } /* Process a confirmation response in MSG. */ static gpg_error_t process_confirmation_response (server_ctx_t ctx, estream_t msg) { gpg_error_t err; nvc_t nvc; nve_t item; const char *value, *sender, *address, *nonce; err = nvc_parse (&nvc, NULL, msg); if (err) { log_error ("parsing the WKS message failed: %s\n", gpg_strerror (err)); goto leave; } if (opt.debug) { log_debug ("response follows:\n"); nvc_write (nvc, log_get_stream ()); } /* Check that this is a confirmation response. */ if (!((item = nvc_lookup (nvc, "type:")) && (value = nve_value (item)) && !strcmp (value, "confirmation-response"))) { if (item && value) log_error ("received unexpected wks message '%s'\n", value); else log_error ("received invalid wks message: %s\n", "'type' missing"); err = gpg_error (GPG_ERR_UNEXPECTED_MSG); goto leave; } /* Get the sender. */ if (!((item = nvc_lookup (nvc, "sender:")) && (value = nve_value (item)) && is_valid_mailbox (value))) { log_error ("received invalid wks message: %s\n", "'sender' missing or invalid"); err = gpg_error (GPG_ERR_INV_DATA); goto leave; } sender = value; (void)sender; /* FIXME: Do we really need the sender?. */ /* Get the address. */ if (!((item = nvc_lookup (nvc, "address:")) && (value = nve_value (item)) && is_valid_mailbox (value))) { log_error ("received invalid wks message: %s\n", "'address' missing or invalid"); err = gpg_error (GPG_ERR_INV_DATA); goto leave; } address = value; /* Get the nonce. */ if (!((item = nvc_lookup (nvc, "nonce:")) && (value = nve_value (item)) && strlen (value) > 16)) { log_error ("received invalid wks message: %s\n", "'nonce' missing or too short"); err = gpg_error (GPG_ERR_INV_DATA); goto leave; } nonce = value; err = check_and_publish (ctx, address, nonce); leave: nvc_release (nvc); return err; } /* Called from the MIME receiver to process the plain text data in MSG . */ static gpg_error_t command_receive_cb (void *opaque, const char *mediatype, estream_t msg, unsigned int flags) { gpg_error_t err; struct server_ctx_s ctx; (void)opaque; memset (&ctx, 0, sizeof ctx); if ((flags & WKS_RECEIVE_DRAFT2)) ctx.draft_version_2 = 1; if (!strcmp (mediatype, "application/pgp-keys")) err = process_new_key (&ctx, msg); else if (!strcmp (mediatype, "application/vnd.gnupg.wks")) err = process_confirmation_response (&ctx, msg); else { log_info ("ignoring unexpected message of type '%s'\n", mediatype); err = gpg_error (GPG_ERR_UNEXPECTED_MSG); } xfree (ctx.fpr); free_uidinfo_list (ctx.mboxes); return err; } /* Return a list of all configured domains. Each list element is the * top directory for the domain. To figure out the actual domain * name strrchr(name, '/') can be used. */ static gpg_error_t get_domain_list (strlist_t *r_list) { gpg_error_t err; - DIR *dir = NULL; + gnupg_dir_t dir = NULL; char *fname = NULL; - struct dirent *dentry; + gnupg_dirent_t dentry; struct stat sb; strlist_t list = NULL; *r_list = NULL; - dir = opendir (opt.directory); + dir = gnupg_opendir (opt.directory); if (!dir) { err = gpg_error_from_syserror (); goto leave; } - while ((dentry = readdir (dir))) + while ((dentry = gnupg_readdir (dir))) { if (*dentry->d_name == '.') continue; if (!strchr (dentry->d_name, '.')) continue; /* No dot - can't be a domain subdir. */ xfree (fname); fname = make_filename_try (opt.directory, dentry->d_name, NULL); if (!fname) { err = gpg_error_from_syserror (); log_error ("make_filename failed in %s: %s\n", __func__, gpg_strerror (err)); goto leave; } if (gnupg_stat (fname, &sb)) { err = gpg_error_from_syserror (); log_error ("error accessing '%s': %s\n", fname, gpg_strerror (err)); continue; } if (!S_ISDIR(sb.st_mode)) continue; if (!add_to_strlist_try (&list, fname)) { err = gpg_error_from_syserror (); log_error ("add_to_strlist failed in %s: %s\n", __func__, gpg_strerror (err)); goto leave; } } err = 0; *r_list = list; list = NULL; leave: free_strlist (list); - if (dir) - closedir (dir); + gnupg_closedir (dir); xfree (fname); return err; } static gpg_error_t expire_one_domain (const char *top_dirname, const char *domain) { gpg_error_t err; char *dirname; char *fname = NULL; - DIR *dir = NULL; - struct dirent *dentry; + gnupg_dir_t dir = NULL; + gnupg_dirent_t dentry; struct stat sb; time_t now = gnupg_get_time (); dirname = make_filename_try (top_dirname, "pending", NULL); if (!dirname) { err = gpg_error_from_syserror (); log_error ("make_filename failed in %s: %s\n", __func__, gpg_strerror (err)); goto leave; } - dir = opendir (dirname); + dir = gnupg_opendir (dirname); if (!dir) { err = gpg_error_from_syserror (); log_error (("can't access directory '%s': %s\n"), dirname, gpg_strerror (err)); goto leave; } - while ((dentry = readdir (dir))) + while ((dentry = gnupg_readdir (dir))) { if (*dentry->d_name == '.') continue; xfree (fname); fname = make_filename_try (dirname, dentry->d_name, NULL); if (!fname) { err = gpg_error_from_syserror (); log_error ("make_filename failed in %s: %s\n", __func__, gpg_strerror (err)); goto leave; } if (strlen (dentry->d_name) != 32) { log_info ("garbage file '%s' ignored\n", fname); continue; } if (gnupg_stat (fname, &sb)) { err = gpg_error_from_syserror (); log_error ("error accessing '%s': %s\n", fname, gpg_strerror (err)); continue; } if (S_ISDIR(sb.st_mode)) { log_info ("garbage directory '%s' ignored\n", fname); continue; } if (sb.st_mtime + PENDING_TTL < now) { if (opt.verbose) log_info ("domain %s: removing pending key '%s'\n", domain, dentry->d_name); if (remove (fname)) { err = gpg_error_from_syserror (); /* In case the file has just been renamed or another * processes is cleaning up, we don't print a diagnostic * for ENOENT. */ if (gpg_err_code (err) != GPG_ERR_ENOENT) log_error ("error removing '%s': %s\n", fname, gpg_strerror (err)); } } } err = 0; leave: - if (dir) - closedir (dir); + gnupg_closedir (dir); xfree (dirname); xfree (fname); return err; } /* Scan spool directories and expire too old pending keys. */ static gpg_error_t expire_pending_confirmations (strlist_t domaindirs) { gpg_error_t err = 0; strlist_t sl; const char *domain; for (sl = domaindirs; sl; sl = sl->next) { domain = strrchr (sl->d, '/'); log_assert (domain); domain++; expire_one_domain (sl->d, domain); } return err; } /* List all configured domains. */ static gpg_error_t command_list_domains (void) { static struct { const char *name; const char *perm; } requireddirs[] = { { "pending", "-rwx" }, { "hu", "-rwxr-xr-x" } }; gpg_err_code_t ec; gpg_error_t err; strlist_t domaindirs; strlist_t sl; const char *domain; char *fname = NULL; int i; estream_t fp; err = get_domain_list (&domaindirs); if (err) { log_error ("error reading list of domains: %s\n", gpg_strerror (err)); return err; } for (sl = domaindirs; sl; sl = sl->next) { domain = strrchr (sl->d, '/'); log_assert (domain); domain++; if (opt_with_dir) es_printf ("%s %s\n", domain, sl->d); else es_printf ("%s\n", domain); /* Check that the required directories are there. */ for (i=0; i < DIM (requireddirs); i++) { xfree (fname); fname = make_filename_try (sl->d, requireddirs[i].name, NULL); if (!fname) { err = gpg_error_from_syserror (); goto leave; } if ((ec = gnupg_access (fname, W_OK))) { err = gpg_error (ec); if (gpg_err_code (err) == GPG_ERR_ENOENT) { if (gnupg_mkdir (fname, requireddirs[i].perm)) { err = gpg_error_from_syserror (); log_error ("domain %s: error creating subdir '%s': %s\n", domain, requireddirs[i].name, gpg_strerror (err)); } else log_info ("domain %s: subdir '%s' created\n", domain, requireddirs[i].name); } else if (err) log_error ("domain %s: problem with subdir '%s': %s\n", domain, requireddirs[i].name, gpg_strerror (err)); } } /* Print a warning if the submission address is not configured. */ xfree (fname); fname = make_filename_try (sl->d, "submission-address", NULL); if (!fname) { err = gpg_error_from_syserror (); goto leave; } if ((ec = gnupg_access (fname, F_OK))) { err = gpg_error (ec); if (gpg_err_code (err) == GPG_ERR_ENOENT) log_error ("domain %s: submission address not configured\n", domain); else log_error ("domain %s: problem with '%s': %s\n", domain, fname, gpg_strerror (err)); } /* Check the syntax of the optional policy file. */ xfree (fname); fname = make_filename_try (sl->d, "policy", NULL); if (!fname) { err = gpg_error_from_syserror (); goto leave; } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_ENOENT) { fp = es_fopen (fname, "w"); if (!fp) log_error ("domain %s: can't create policy file: %s\n", domain, gpg_strerror (err)); else es_fclose (fp); fp = NULL; } else log_error ("domain %s: error in policy file: %s\n", domain, gpg_strerror (err)); } else { struct policy_flags_s policy; err = wks_parse_policy (&policy, fp, 0); es_fclose (fp); wks_free_policy (&policy); } } err = 0; leave: xfree (fname); free_strlist (domaindirs); return err; } /* Run regular maintenance jobs. */ static gpg_error_t command_cron (void) { gpg_error_t err; strlist_t domaindirs; err = get_domain_list (&domaindirs); if (err) { log_error ("error reading list of domains: %s\n", gpg_strerror (err)); return err; } err = expire_pending_confirmations (domaindirs); free_strlist (domaindirs); return err; } /* Check whether the key with USER_ID is installed. */ static gpg_error_t command_check_key (const char *userid) { gpg_err_code_t ec; gpg_error_t err; char *addrspec = NULL; char *fname = NULL; err = wks_fname_from_userid (userid, 0, &fname, &addrspec); if (err) goto leave; if ((ec = gnupg_access (fname, R_OK))) { err = gpg_error (ec); if (opt_with_file) es_printf ("%s n %s\n", addrspec, fname); 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 stating '%s': %s\n", fname, gpg_strerror (err)); goto leave; } if (opt_with_file) es_printf ("%s i %s\n", addrspec, fname); if (opt.verbose) log_info ("key for '%s' is installed\n", addrspec); err = 0; leave: xfree (fname); xfree (addrspec); return err; } /* Revoke the key with mail address MAILADDR. */ static gpg_error_t command_revoke_key (const char *mailaddr) { /* Remove should be different from removing but we have not yet * defined a suitable way to do this. */ return wks_cmd_remove_key (mailaddr); } diff --git a/tools/gpgtar-create.c b/tools/gpgtar-create.c index d13b1dc7e..6114d68ff 100644 --- a/tools/gpgtar-create.c +++ b/tools/gpgtar-create.c @@ -1,1063 +1,1065 @@ /* gpgtar-create.c - Create a TAR archive * Copyright (C) 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # define WIN32_LEAN_AND_MEAN # include #else /*!HAVE_W32_SYSTEM*/ # include # include # include #endif /*!HAVE_W32_SYSTEM*/ #include #include "../common/i18n.h" #include "../common/exectool.h" #include "../common/sysutils.h" #include "../common/ccparray.h" #include "gpgtar.h" #ifndef HAVE_LSTAT #define lstat(a,b) gnupg_stat ((a), (b)) #endif /* Object to control the file scanning. */ struct scanctrl_s; typedef struct scanctrl_s *scanctrl_t; struct scanctrl_s { tar_header_t flist; tar_header_t *flist_tail; int nestlevel; }; /* On Windows convert name to UTF8 and return it; caller must release * the result. On Unix or if ALREADY_UTF8 is set, this function is a * mere xtrystrcopy. On failure NULL is returned and ERRNO set. */ static char * name_to_utf8 (const char *name, int already_utf8) { #ifdef HAVE_W32_SYSTEM wchar_t *wstring; char *result; if (already_utf8) result = xtrystrdup (name); else { wstring = native_to_wchar (name); if (!wstring) return NULL; result = wchar_to_utf8 (wstring); xfree (wstring); } return result; #else /*!HAVE_W32_SYSTEM */ (void)already_utf8; return xtrystrdup (name); #endif /*!HAVE_W32_SYSTEM */ } /* Given a fresh header object HDR with only the name field set, try to gather all available info. This is the W32 version. */ #ifdef HAVE_W32_SYSTEM static gpg_error_t fillup_entry_w32 (tar_header_t hdr) { char *p; wchar_t *wfname; WIN32_FILE_ATTRIBUTE_DATA fad; DWORD attr; for (p=hdr->name; *p; p++) if (*p == '/') *p = '\\'; wfname = utf8_to_wchar (hdr->name); for (p=hdr->name; *p; p++) if (*p == '\\') *p = '/'; if (!wfname) { log_error ("error converting '%s': %s\n", hdr->name, w32_strerror (-1)); return gpg_error_from_syserror (); } if (!GetFileAttributesExW (wfname, GetFileExInfoStandard, &fad)) { log_error ("error stat-ing '%s': %s\n", hdr->name, w32_strerror (-1)); xfree (wfname); return gpg_error_from_syserror (); } xfree (wfname); attr = fad.dwFileAttributes; if ((attr & FILE_ATTRIBUTE_NORMAL)) hdr->typeflag = TF_REGULAR; else if ((attr & FILE_ATTRIBUTE_DIRECTORY)) hdr->typeflag = TF_DIRECTORY; else if ((attr & FILE_ATTRIBUTE_DEVICE)) hdr->typeflag = TF_NOTSUP; else if ((attr & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_TEMPORARY))) hdr->typeflag = TF_NOTSUP; else hdr->typeflag = TF_REGULAR; /* Map some attributes to USTAR defined mode bits. */ hdr->mode = 0640; /* User may read and write, group only read. */ if ((attr & FILE_ATTRIBUTE_DIRECTORY)) hdr->mode |= 0110; /* Dirs are user and group executable. */ if ((attr & FILE_ATTRIBUTE_READONLY)) hdr->mode &= ~0200; /* Clear the user write bit. */ if ((attr & FILE_ATTRIBUTE_HIDDEN)) hdr->mode &= ~0707; /* Clear all user and other bits. */ if ((attr & FILE_ATTRIBUTE_SYSTEM)) hdr->mode |= 0004; /* Make it readable by other. */ /* Only set the size for a regular file. */ if (hdr->typeflag == TF_REGULAR) hdr->size = (fad.nFileSizeHigh * (unsigned long long)(MAXDWORD+1) + fad.nFileSizeLow); hdr->mtime = (((unsigned long long)fad.ftLastWriteTime.dwHighDateTime << 32) | fad.ftLastWriteTime.dwLowDateTime); if (!hdr->mtime) hdr->mtime = (((unsigned long long)fad.ftCreationTime.dwHighDateTime << 32) | fad.ftCreationTime.dwLowDateTime); hdr->mtime -= 116444736000000000ULL; /* The filetime epoch is 1601-01-01. */ hdr->mtime /= 10000000; /* Convert from 0.1us to seconds. */ return 0; } #endif /*HAVE_W32_SYSTEM*/ /* Given a fresh header object HDR with only the name field set, try to gather all available info. This is the POSIX version. */ #ifndef HAVE_W32_SYSTEM static gpg_error_t fillup_entry_posix (tar_header_t hdr) { gpg_error_t err; struct stat sbuf; if (lstat (hdr->name, &sbuf)) { err = gpg_error_from_syserror (); log_error ("error stat-ing '%s': %s\n", hdr->name, gpg_strerror (err)); return err; } if (S_ISREG (sbuf.st_mode)) hdr->typeflag = TF_REGULAR; else if (S_ISDIR (sbuf.st_mode)) hdr->typeflag = TF_DIRECTORY; else if (S_ISCHR (sbuf.st_mode)) hdr->typeflag = TF_CHARDEV; else if (S_ISBLK (sbuf.st_mode)) hdr->typeflag = TF_BLOCKDEV; else if (S_ISFIFO (sbuf.st_mode)) hdr->typeflag = TF_FIFO; else if (S_ISLNK (sbuf.st_mode)) hdr->typeflag = TF_SYMLINK; else hdr->typeflag = TF_NOTSUP; /* FIXME: Save DEV and INO? */ /* Set the USTAR defined mode bits using the system macros. */ if (sbuf.st_mode & S_IRUSR) hdr->mode |= 0400; if (sbuf.st_mode & S_IWUSR) hdr->mode |= 0200; if (sbuf.st_mode & S_IXUSR) hdr->mode |= 0100; if (sbuf.st_mode & S_IRGRP) hdr->mode |= 0040; if (sbuf.st_mode & S_IWGRP) hdr->mode |= 0020; if (sbuf.st_mode & S_IXGRP) hdr->mode |= 0010; if (sbuf.st_mode & S_IROTH) hdr->mode |= 0004; if (sbuf.st_mode & S_IWOTH) hdr->mode |= 0002; if (sbuf.st_mode & S_IXOTH) hdr->mode |= 0001; #ifdef S_IXUID if (sbuf.st_mode & S_IXUID) hdr->mode |= 04000; #endif #ifdef S_IXGID if (sbuf.st_mode & S_IXGID) hdr->mode |= 02000; #endif #ifdef S_ISVTX if (sbuf.st_mode & S_ISVTX) hdr->mode |= 01000; #endif hdr->nlink = sbuf.st_nlink; hdr->uid = sbuf.st_uid; hdr->gid = sbuf.st_gid; /* Only set the size for a regular file. */ if (hdr->typeflag == TF_REGULAR) hdr->size = sbuf.st_size; hdr->mtime = sbuf.st_mtime; return 0; } #endif /*!HAVE_W32_SYSTEM*/ /* Add a new entry. The name of a directory entry is ENTRYNAME; if that is NULL, DNAME is the name of the directory itself. Under Windows ENTRYNAME shall have backslashes replaced by standard slashes. */ static gpg_error_t add_entry (const char *dname, const char *entryname, scanctrl_t scanctrl) { gpg_error_t err; tar_header_t hdr; char *p; size_t dnamelen = strlen (dname); log_assert (dnamelen); hdr = xtrycalloc (1, sizeof *hdr + dnamelen + 1 + (entryname? strlen (entryname) : 0) + 1); if (!hdr) return gpg_error_from_syserror (); p = stpcpy (hdr->name, dname); if (entryname) { if (dname[dnamelen-1] != '/') *p++ = '/'; strcpy (p, entryname); } else { if (hdr->name[dnamelen-1] == '/') hdr->name[dnamelen-1] = 0; } #ifdef HAVE_DOSISH_SYSTEM err = fillup_entry_w32 (hdr); #else err = fillup_entry_posix (hdr); #endif if (err) xfree (hdr); else { if (opt.verbose) gpgtar_print_header (hdr, log_get_stream ()); *scanctrl->flist_tail = hdr; scanctrl->flist_tail = &hdr->next; } return 0; } static gpg_error_t scan_directory (const char *dname, scanctrl_t scanctrl) { gpg_error_t err = 0; #ifdef HAVE_W32_SYSTEM + /* Note that we introduced gnupg_opendir only after we had deployed + * this code and thus we don't change it for now. */ WIN32_FIND_DATAW fi; HANDLE hd = INVALID_HANDLE_VALUE; char *p; if (!*dname) return 0; /* An empty directory name has no entries. */ { char *fname; wchar_t *wfname; fname = xtrymalloc (strlen (dname) + 2 + 2 + 1); if (!fname) { err = gpg_error_from_syserror (); goto leave; } if (!strcmp (dname, "/")) strcpy (fname, "/*"); /* Trailing slash is not allowed. */ else if (!strcmp (dname, ".")) strcpy (fname, "*"); else if (*dname && dname[strlen (dname)-1] == '/') strcpy (stpcpy (fname, dname), "*"); else if (*dname && dname[strlen (dname)-1] != '*') strcpy (stpcpy (fname, dname), "/*"); else strcpy (fname, dname); for (p=fname; *p; p++) if (*p == '/') *p = '\\'; wfname = utf8_to_wchar (fname); xfree (fname); if (!wfname) { err = gpg_error_from_syserror (); log_error (_("error reading directory '%s': %s\n"), dname, gpg_strerror (err)); goto leave; } hd = FindFirstFileW (wfname, &fi); if (hd == INVALID_HANDLE_VALUE) { err = gpg_error_from_syserror (); log_error (_("error reading directory '%s': %s\n"), dname, w32_strerror (-1)); xfree (wfname); goto leave; } xfree (wfname); } do { char *fname = wchar_to_utf8 (fi.cFileName); if (!fname) { err = gpg_error_from_syserror (); log_error ("error converting filename: %s\n", w32_strerror (-1)); break; } for (p=fname; *p; p++) if (*p == '\\') *p = '/'; if (!strcmp (fname, "." ) || !strcmp (fname, "..")) err = 0; /* Skip self and parent dir entry. */ else if (!strncmp (dname, "./", 2) && dname[2]) err = add_entry (dname+2, fname, scanctrl); else err = add_entry (dname, fname, scanctrl); xfree (fname); } while (!err && FindNextFileW (hd, &fi)); if (err) ; else if (GetLastError () == ERROR_NO_MORE_FILES) err = 0; else { err = gpg_error_from_syserror (); log_error (_("error reading directory '%s': %s\n"), dname, w32_strerror (-1)); } leave: if (hd != INVALID_HANDLE_VALUE) FindClose (hd); #else /*!HAVE_W32_SYSTEM*/ DIR *dir; struct dirent *de; if (!*dname) return 0; /* An empty directory name has no entries. */ dir = opendir (dname); if (!dir) { err = gpg_error_from_syserror (); log_error (_("error reading directory '%s': %s\n"), dname, gpg_strerror (err)); return err; } while ((de = readdir (dir))) { if (!strcmp (de->d_name, "." ) || !strcmp (de->d_name, "..")) continue; /* Skip self and parent dir entry. */ err = add_entry (dname, de->d_name, scanctrl); if (err) goto leave; } leave: closedir (dir); #endif /*!HAVE_W32_SYSTEM*/ return err; } static gpg_error_t scan_recursive (const char *dname, scanctrl_t scanctrl) { gpg_error_t err = 0; tar_header_t hdr, *start_tail, *stop_tail; if (scanctrl->nestlevel > 200) { log_error ("directories too deeply nested\n"); return gpg_error (GPG_ERR_RESOURCE_LIMIT); } scanctrl->nestlevel++; assert (scanctrl->flist_tail); start_tail = scanctrl->flist_tail; scan_directory (dname, scanctrl); stop_tail = scanctrl->flist_tail; hdr = *start_tail; for (; hdr && hdr != *stop_tail; hdr = hdr->next) if (hdr->typeflag == TF_DIRECTORY) { if (opt.verbose > 1) log_info ("scanning directory '%s'\n", hdr->name); scan_recursive (hdr->name, scanctrl); } scanctrl->nestlevel--; return err; } /* Returns true if PATTERN is acceptable. */ static int pattern_valid_p (const char *pattern) { if (!*pattern) return 0; if (*pattern == '.' && pattern[1] == '.') return 0; if (*pattern == '/' #ifdef HAVE_DOSISH_SYSTEM || *pattern == '\\' #endif ) return 0; /* Absolute filenames are not supported. */ #ifdef HAVE_DRIVE_LETTERS if (((*pattern >= 'a' && *pattern <= 'z') || (*pattern >= 'A' && *pattern <= 'Z')) && pattern[1] == ':') return 0; /* Drive letter are not allowed either. */ #endif /*HAVE_DRIVE_LETTERS*/ return 1; /* Okay. */ } static void store_xoctal (char *buffer, size_t length, unsigned long long value) { char *p, *pend; size_t n; unsigned long long v; assert (length > 1); v = value; n = length; p = pend = buffer + length; *--p = 0; /* Nul byte. */ n--; do { *--p = '0' + (v % 8); v /= 8; n--; } while (v && n); if (!v) { /* Pad. */ for ( ; n; n--) *--p = '0'; } else /* Does not fit into the field. Store as binary number. */ { v = value; n = length; p = pend = buffer + length; do { *--p = v; v /= 256; n--; } while (v && n); if (!v) { /* Pad. */ for ( ; n; n--) *--p = 0; if (*p & 0x80) BUG (); *p |= 0x80; /* Set binary flag. */ } else BUG (); } } static void store_uname (char *buffer, size_t length, unsigned long uid) { static int initialized; static unsigned long lastuid; static char lastuname[32]; if (!initialized || uid != lastuid) { #ifdef HAVE_W32_SYSTEM mem2str (lastuname, uid? "user":"root", sizeof lastuname); #else struct passwd *pw = getpwuid (uid); lastuid = uid; initialized = 1; if (pw) mem2str (lastuname, pw->pw_name, sizeof lastuname); else { log_info ("failed to get name for uid %lu\n", uid); *lastuname = 0; } #endif } mem2str (buffer, lastuname, length); } static void store_gname (char *buffer, size_t length, unsigned long gid) { static int initialized; static unsigned long lastgid; static char lastgname[32]; if (!initialized || gid != lastgid) { #ifdef HAVE_W32_SYSTEM mem2str (lastgname, gid? "users":"root", sizeof lastgname); #else struct group *gr = getgrgid (gid); lastgid = gid; initialized = 1; if (gr) mem2str (lastgname, gr->gr_name, sizeof lastgname); else { log_info ("failed to get name for gid %lu\n", gid); *lastgname = 0; } #endif } mem2str (buffer, lastgname, length); } static gpg_error_t build_header (void *record, tar_header_t hdr) { gpg_error_t err; struct ustar_raw_header *raw = record; size_t namelen, n; unsigned long chksum; unsigned char *p; memset (record, 0, RECORDSIZE); /* Store name and prefix. */ namelen = strlen (hdr->name); if (namelen < sizeof raw->name) memcpy (raw->name, hdr->name, namelen); else { n = (namelen < sizeof raw->prefix)? namelen : sizeof raw->prefix; for (n--; n ; n--) if (hdr->name[n] == '/') break; if (namelen - n < sizeof raw->name) { /* Note that the N is < sizeof prefix and that the delimiting slash is not stored. */ memcpy (raw->prefix, hdr->name, n); memcpy (raw->name, hdr->name+n+1, namelen - n); } else { err = gpg_error (GPG_ERR_TOO_LARGE); log_error ("error storing file '%s': %s\n", hdr->name, gpg_strerror (err)); return err; } } store_xoctal (raw->mode, sizeof raw->mode, hdr->mode); store_xoctal (raw->uid, sizeof raw->uid, hdr->uid); store_xoctal (raw->gid, sizeof raw->gid, hdr->gid); store_xoctal (raw->size, sizeof raw->size, hdr->size); store_xoctal (raw->mtime, sizeof raw->mtime, hdr->mtime); switch (hdr->typeflag) { case TF_REGULAR: raw->typeflag[0] = '0'; break; case TF_HARDLINK: raw->typeflag[0] = '1'; break; case TF_SYMLINK: raw->typeflag[0] = '2'; break; case TF_CHARDEV: raw->typeflag[0] = '3'; break; case TF_BLOCKDEV: raw->typeflag[0] = '4'; break; case TF_DIRECTORY: raw->typeflag[0] = '5'; break; case TF_FIFO: raw->typeflag[0] = '6'; break; default: return gpg_error (GPG_ERR_NOT_SUPPORTED); } memcpy (raw->magic, "ustar", 6); raw->version[0] = '0'; raw->version[1] = '0'; store_uname (raw->uname, sizeof raw->uname, hdr->uid); store_gname (raw->gname, sizeof raw->gname, hdr->gid); #ifndef HAVE_W32_SYSTEM if (hdr->typeflag == TF_SYMLINK) { int nread; nread = readlink (hdr->name, raw->linkname, sizeof raw->linkname -1); if (nread < 0) { err = gpg_error_from_syserror (); log_error ("error reading symlink '%s': %s\n", hdr->name, gpg_strerror (err)); return err; } raw->linkname[nread] = 0; } #endif /*HAVE_W32_SYSTEM*/ /* Compute the checksum. */ memset (raw->checksum, ' ', sizeof raw->checksum); chksum = 0; p = record; for (n=0; n < RECORDSIZE; n++) chksum += *p++; store_xoctal (raw->checksum, sizeof raw->checksum - 1, chksum); raw->checksum[7] = ' '; return 0; } static gpg_error_t write_file (estream_t stream, tar_header_t hdr) { gpg_error_t err; char record[RECORDSIZE]; estream_t infp; size_t nread, nbytes; int any; err = build_header (record, hdr); if (err) { if (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED) { log_info ("skipping unsupported file '%s'\n", hdr->name); err = 0; } return err; } if (hdr->typeflag == TF_REGULAR) { infp = es_fopen (hdr->name, "rb"); if (!infp) { err = gpg_error_from_syserror (); log_error ("can't open '%s': %s - skipped\n", hdr->name, gpg_strerror (err)); return err; } } else infp = NULL; err = write_record (stream, record); if (err) goto leave; if (hdr->typeflag == TF_REGULAR) { hdr->nrecords = (hdr->size + RECORDSIZE-1)/RECORDSIZE; any = 0; while (hdr->nrecords--) { nbytes = hdr->nrecords? RECORDSIZE : (hdr->size % RECORDSIZE); if (!nbytes) nbytes = RECORDSIZE; nread = es_fread (record, 1, nbytes, infp); if (nread != nbytes) { err = gpg_error_from_syserror (); log_error ("error reading file '%s': %s%s\n", hdr->name, gpg_strerror (err), any? " (file shrunk?)":""); goto leave; } any = 1; err = write_record (stream, record); if (err) goto leave; } nread = es_fread (record, 1, 1, infp); if (nread) log_info ("note: file '%s' has grown\n", hdr->name); } leave: if (err) es_fclose (infp); else if ((err = es_fclose (infp))) log_error ("error closing file '%s': %s\n", hdr->name, gpg_strerror (err)); return err; } static gpg_error_t write_eof_mark (estream_t stream) { gpg_error_t err; char record[RECORDSIZE]; memset (record, 0, sizeof record); err = write_record (stream, record); if (!err) err = write_record (stream, record); return err; } /* Create a new tarball using the names in the array INPATTERN. If INPATTERN is NULL take the pattern as null terminated strings from stdin or from the file specified by FILES_FROM. If NULL_NAMES is set the filenames in such a file are delimited by a binary Nul and not by a LF. */ gpg_error_t gpgtar_create (char **inpattern, const char *files_from, int null_names, int encrypt, int sign) { gpg_error_t err = 0; struct scanctrl_s scanctrl_buffer; scanctrl_t scanctrl = &scanctrl_buffer; tar_header_t hdr, *start_tail; estream_t files_from_stream = NULL; estream_t outstream = NULL; estream_t cipher_stream = NULL; int eof_seen = 0; memset (scanctrl, 0, sizeof *scanctrl); scanctrl->flist_tail = &scanctrl->flist; if (!inpattern) { if (!files_from || !strcmp (files_from, "-")) { files_from = "-"; files_from_stream = es_stdin; if (null_names) es_set_binary (es_stdin); } else if (!(files_from_stream=es_fopen (files_from, null_names? "rb":"r"))) { err = gpg_error_from_syserror (); log_error ("error opening '%s': %s\n", files_from, gpg_strerror (err)); return err; } } if (opt.directory && gnupg_chdir (opt.directory)) { err = gpg_error_from_syserror (); log_error ("chdir to '%s' failed: %s\n", opt.directory, gpg_strerror (err)); return err; } while (!eof_seen) { char *pat, *p; int skip_this = 0; if (inpattern) { const char *pattern = *inpattern; if (!pattern) break; /* End of array. */ inpattern++; if (!*pattern) continue; pat = name_to_utf8 (pattern, 0); } else /* Read Nul or LF delimited pattern from files_from_stream. */ { int c; char namebuf[4096]; size_t n = 0; for (;;) { if ((c = es_getc (files_from_stream)) == EOF) { if (es_ferror (files_from_stream)) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", files_from, gpg_strerror (err)); goto leave; } c = null_names ? 0 : '\n'; eof_seen = 1; } if (n >= sizeof namebuf - 1) { if (!skip_this) { skip_this = 1; log_error ("error reading '%s': %s\n", files_from, "filename too long"); } } else namebuf[n++] = c; if (null_names) { if (!c) { namebuf[n] = 0; break; } } else /* Shall be LF delimited. */ { if (!c) { if (!skip_this) { skip_this = 1; log_error ("error reading '%s': %s\n", files_from, "filename with embedded Nul"); } } else if ( c == '\n' ) { namebuf[n] = 0; ascii_trim_spaces (namebuf); n = strlen (namebuf); break; } } } if (skip_this || n < 2) continue; pat = name_to_utf8 (namebuf, opt.utf8strings); } if (!pat) { err = gpg_error_from_syserror (); log_error ("memory allocation problem: %s\n", gpg_strerror (err)); goto leave; } for (p=pat; *p; p++) if (*p == '\\') *p = '/'; if (opt.verbose > 1) log_info ("scanning '%s'\n", pat); start_tail = scanctrl->flist_tail; if (skip_this || !pattern_valid_p (pat)) log_error ("skipping invalid name '%s'\n", pat); else if (!add_entry (pat, NULL, scanctrl) && *start_tail && ((*start_tail)->typeflag & TF_DIRECTORY)) scan_recursive (pat, scanctrl); xfree (pat); } if (files_from_stream && files_from_stream != es_stdin) es_fclose (files_from_stream); if (opt.outfile) { if (!strcmp (opt.outfile, "-")) outstream = es_stdout; else outstream = es_fopen (opt.outfile, "wb"); if (!outstream) { err = gpg_error_from_syserror (); goto leave; } } else { outstream = es_stdout; } if (outstream == es_stdout) es_set_binary (es_stdout); if (encrypt || sign) { cipher_stream = outstream; outstream = es_fopenmem (0, "rwb"); if (! outstream) { err = gpg_error_from_syserror (); goto leave; } } for (hdr = scanctrl->flist; hdr; hdr = hdr->next) { err = write_file (outstream, hdr); if (err) goto leave; } err = write_eof_mark (outstream); if (err) goto leave; if (encrypt || sign) { strlist_t arg; ccparray_t ccp; const char **argv; err = es_fseek (outstream, 0, SEEK_SET); if (err) goto leave; /* '--encrypt' may be combined with '--symmetric', but 'encrypt' is set either way. Clear it if no recipients are specified. XXX: Fix command handling. */ if (opt.symmetric && opt.recipients == NULL) encrypt = 0; ccparray_init (&ccp, 0); if (encrypt) ccparray_put (&ccp, "--encrypt"); if (sign) ccparray_put (&ccp, "--sign"); if (opt.user) { ccparray_put (&ccp, "--local-user"); ccparray_put (&ccp, opt.user); } if (opt.symmetric) ccparray_put (&ccp, "--symmetric"); for (arg = opt.recipients; arg; arg = arg->next) { ccparray_put (&ccp, "--recipient"); ccparray_put (&ccp, arg->d); } for (arg = opt.gpg_arguments; arg; arg = arg->next) ccparray_put (&ccp, arg->d); 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, outstream, NULL, cipher_stream, NULL, NULL); xfree (argv); if (err) goto leave; } leave: if (!err) { gpg_error_t first_err; if (outstream != es_stdout) first_err = es_fclose (outstream); else first_err = es_fflush (outstream); outstream = NULL; if (cipher_stream != es_stdout) err = es_fclose (cipher_stream); else err = es_fflush (cipher_stream); cipher_stream = NULL; if (! err) err = first_err; } if (err) { log_error ("creating tarball '%s' failed: %s\n", opt.outfile ? opt.outfile : "-", gpg_strerror (err)); if (outstream && outstream != es_stdout) es_fclose (outstream); if (cipher_stream && cipher_stream != es_stdout) es_fclose (cipher_stream); if (opt.outfile) gnupg_remove (opt.outfile); } scanctrl->flist_tail = NULL; while ( (hdr = scanctrl->flist) ) { scanctrl->flist = hdr->next; xfree (hdr); } return err; }