1 /* $OpenBSD: ssh.c,v 1.594 2023/09/03 23:59:32 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
77 #include <openssl/evp.h>
78 #include <openssl/err.h>
80 #include "openbsd-compat/openssl-compat.h"
81 #include "openbsd-compat/sys-queue.h"
95 #include "pathnames.h"
97 #include "clientloop.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
109 #include "myproposal.h"
113 #include "ssh-pkcs11.h"
116 extern char *__progname;
118 /* Saves a copy of argv for setproctitle emulation */
119 #ifndef HAVE_SETPROCTITLE
120 static char **saved_av;
123 /* Flag indicating whether debug mode is on. May be set on the command line. */
126 /* Flag indicating whether a tty should be requested */
130 * Flag indicating that the current process should be backgrounded and
131 * a new mux-client launched in the foreground for ControlPersist.
133 static int need_controlpersist_detach = 0;
135 /* Copies of flags for ControlPersist foreground mux-client */
136 static int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
137 static int ofork_after_authentication;
140 * General data structure for command line options and options configurable
141 * in configuration files. See readconf.h.
145 /* optional user configfile */
149 * Name of the host we are connecting to. This is the name given on the
150 * command line, or the Hostname specified for the user-supplied name in a
151 * configuration file.
156 * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
157 * not NULL, forward the socket at this path instead.
159 char *forward_agent_sock_path = NULL;
161 /* socket address the host resolves to */
162 struct sockaddr_storage hostaddr;
164 /* Private host keys. */
165 Sensitive sensitive_data;
167 /* command to be executed */
168 struct sshbuf *command;
170 /* # of replies received for global requests */
171 static int forward_confirms_pending = -1;
174 extern int muxserver_sock;
175 extern u_int muxclient_command;
177 /* Prints a help message to the user. This function never returns. */
183 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address]\n"
184 " [-c cipher_spec] [-D [bind_address:]port] [-E log_file]\n"
185 " [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]\n"
186 " [-J destination] [-L address] [-l login_name] [-m mac_spec]\n"
187 " [-O ctl_cmd] [-o option] [-P tag] [-p port] [-Q query_option]\n"
188 " [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
189 " destination [command [argument ...]]\n"
194 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
195 static void load_public_identity_files(const struct ssh_conn_info *);
196 static void main_sigchld_handler(int);
198 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
200 tilde_expand_paths(char **paths, u_int num_paths)
205 for (i = 0; i < num_paths; i++) {
206 cp = tilde_expand_filename(paths[i], getuid());
213 * Expands the set of percent_expand options used by the majority of keywords
214 * in the client that support percent expansion.
215 * Caller must free returned string.
218 default_client_percent_expand(const char *str,
219 const struct ssh_conn_info *cinfo)
221 return percent_expand(str,
222 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
227 * Expands the set of percent_expand options used by the majority of keywords
228 * AND perform environment variable substitution.
229 * Caller must free returned string.
232 default_client_percent_dollar_expand(const char *str,
233 const struct ssh_conn_info *cinfo)
237 ret = percent_dollar_expand(str,
238 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
241 fatal("invalid environment variable expansion");
246 * Attempt to resolve a host name / port to a set of addresses and
247 * optionally return any CNAMEs encountered along the way.
248 * Returns NULL on failure.
249 * NB. this function must operate with a options having undefined members.
251 static struct addrinfo *
252 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
254 char strport[NI_MAXSERV];
255 const char *errstr = NULL;
256 struct addrinfo hints, *res;
258 LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
261 port = default_ssh_port();
264 debug3_f("lookup %s:%d", name, port);
266 snprintf(strport, sizeof strport, "%d", port);
267 memset(&hints, 0, sizeof(hints));
268 hints.ai_family = options.address_family == -1 ?
269 AF_UNSPEC : options.address_family;
270 hints.ai_socktype = SOCK_STREAM;
272 hints.ai_flags = AI_CANONNAME;
273 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
274 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
275 loglevel = SYSLOG_LEVEL_ERROR;
276 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
277 __progname, name, ssh_gai_strerror(gaierr));
280 if (cname != NULL && res->ai_canonname != NULL) {
281 if (!valid_domain(res->ai_canonname, 0, &errstr)) {
282 error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
283 res->ai_canonname, name, errstr);
284 } else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
285 error_f("host \"%s\" cname \"%s\" too long (max %lu)",
286 name, res->ai_canonname, (u_long)clen);
294 /* Returns non-zero if name can only be an address and not a hostname */
296 is_addr_fast(const char *name)
298 return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
299 strspn(name, "0123456789.") == strlen(name));
302 /* Returns non-zero if name represents a valid, single address */
304 is_addr(const char *name)
306 char strport[NI_MAXSERV];
307 struct addrinfo hints, *res;
309 if (is_addr_fast(name))
312 snprintf(strport, sizeof strport, "%u", default_ssh_port());
313 memset(&hints, 0, sizeof(hints));
314 hints.ai_family = options.address_family == -1 ?
315 AF_UNSPEC : options.address_family;
316 hints.ai_socktype = SOCK_STREAM;
317 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
318 if (getaddrinfo(name, strport, &hints, &res) != 0)
320 if (res == NULL || res->ai_next != NULL) {
329 * Attempt to resolve a numeric host address / port to a single address.
330 * Returns a canonical address string.
331 * Returns NULL on failure.
332 * NB. this function must operate with a options having undefined members.
334 static struct addrinfo *
335 resolve_addr(const char *name, int port, char *caddr, size_t clen)
337 char addr[NI_MAXHOST], strport[NI_MAXSERV];
338 struct addrinfo hints, *res;
342 port = default_ssh_port();
343 snprintf(strport, sizeof strport, "%u", port);
344 memset(&hints, 0, sizeof(hints));
345 hints.ai_family = options.address_family == -1 ?
346 AF_UNSPEC : options.address_family;
347 hints.ai_socktype = SOCK_STREAM;
348 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
349 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
350 debug2_f("could not resolve name %.100s as address: %s",
351 name, ssh_gai_strerror(gaierr));
355 debug_f("getaddrinfo %.100s returned no addresses", name);
358 if (res->ai_next != NULL) {
359 debug_f("getaddrinfo %.100s returned multiple addresses", name);
362 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
363 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
364 debug_f("Could not format address for name %.100s: %s",
365 name, ssh_gai_strerror(gaierr));
368 if (strlcpy(caddr, addr, clen) >= clen) {
369 error_f("host \"%s\" addr \"%s\" too long (max %lu)",
370 name, addr, (u_long)clen);
381 * Check whether the cname is a permitted replacement for the hostname
382 * and perform the replacement if it is.
383 * NB. this function must operate with a options having undefined members.
386 check_follow_cname(int direct, char **namep, const char *cname)
389 struct allowed_cname *rule;
391 if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
392 strcmp(*namep, cname) == 0)
394 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
397 * Don't attempt to canonicalize names that will be interpreted by
398 * a proxy or jump host unless the user specifically requests so.
401 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
403 debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
404 for (i = 0; i < options.num_permitted_cnames; i++) {
405 rule = options.permitted_cnames + i;
406 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
407 match_pattern_list(cname, rule->target_list, 1) != 1)
409 verbose("Canonicalized DNS aliased hostname "
410 "\"%s\" => \"%s\"", *namep, cname);
412 *namep = xstrdup(cname);
419 * Attempt to resolve the supplied hostname after applying the user's
420 * canonicalization rules. Returns the address list for the host or NULL
421 * if no name was found after canonicalization.
422 * NB. this function must operate with a options having undefined members.
424 static struct addrinfo *
425 resolve_canonicalize(char **hostp, int port)
427 int i, direct, ndots;
428 char *cp, *fullhost, newname[NI_MAXHOST];
429 struct addrinfo *addrs;
432 * Attempt to canonicalise addresses, regardless of
433 * whether hostname canonicalisation was requested
435 if ((addrs = resolve_addr(*hostp, port,
436 newname, sizeof(newname))) != NULL) {
437 debug2_f("hostname %.100s is address", *hostp);
438 if (strcasecmp(*hostp, newname) != 0) {
439 debug2_f("canonicalised address \"%s\" => \"%s\"",
442 *hostp = xstrdup(newname);
448 * If this looks like an address but didn't parse as one, it might
449 * be an address with an invalid interface scope. Skip further
450 * attempts at canonicalisation.
452 if (is_addr_fast(*hostp)) {
453 debug_f("hostname %.100s is an unrecognised address", *hostp);
457 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
461 * Don't attempt to canonicalize names that will be interpreted by
462 * a proxy unless the user specifically requests so.
464 direct = option_clear_or_none(options.proxy_command) &&
465 option_clear_or_none(options.jump_host);
467 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
470 /* If domain name is anchored, then resolve it now */
471 if ((*hostp)[strlen(*hostp) - 1] == '.') {
472 debug3_f("name is fully qualified");
473 fullhost = xstrdup(*hostp);
474 if ((addrs = resolve_host(fullhost, port, 0,
475 newname, sizeof(newname))) != NULL)
481 /* Don't apply canonicalization to sufficiently-qualified hostnames */
483 for (cp = *hostp; *cp != '\0'; cp++) {
487 if (ndots > options.canonicalize_max_dots) {
488 debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
489 *hostp, options.canonicalize_max_dots);
492 /* Attempt each supplied suffix */
493 for (i = 0; i < options.num_canonical_domains; i++) {
494 if (strcasecmp(options.canonical_domains[i], "none") == 0)
496 xasprintf(&fullhost, "%s.%s.", *hostp,
497 options.canonical_domains[i]);
498 debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
499 if ((addrs = resolve_host(fullhost, port, 0,
500 newname, sizeof(newname))) == NULL) {
505 /* Remove trailing '.' */
506 fullhost[strlen(fullhost) - 1] = '\0';
507 /* Follow CNAME if requested */
508 if (!check_follow_cname(direct, &fullhost, newname)) {
509 debug("Canonicalized hostname \"%s\" => \"%s\"",
517 if (!options.canonicalize_fallback_local)
518 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
519 debug2_f("host %s not found in any suffix", *hostp);
524 * Check the result of hostkey loading, ignoring some errors and either
525 * discarding the key or fatal()ing for others.
528 check_load(int r, struct sshkey **k, const char *path, const char *message)
532 /* Check RSA keys size and discard if undersized */
533 if (k != NULL && *k != NULL &&
534 (r = sshkey_check_rsa_length(*k,
535 options.required_rsa_size)) != 0) {
536 error_r(r, "load %s \"%s\"", message, path);
541 case SSH_ERR_INTERNAL_ERROR:
542 case SSH_ERR_ALLOC_FAIL:
543 fatal_r(r, "load %s \"%s\"", message, path);
544 case SSH_ERR_SYSTEM_ERROR:
545 /* Ignore missing files */
550 error_r(r, "load %s \"%s\"", message, path);
556 * Read per-user configuration file. Ignore the system wide config
557 * file if the user specifies a config file on the command line.
560 process_config_files(const char *host_name, struct passwd *pw, int final_pass,
561 int *want_final_pass)
566 if (config != NULL) {
567 if (strcasecmp(config, "none") != 0 &&
568 !read_config_file(config, pw, host, host_name, &options,
569 SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
571 fatal("Can't open user config file %.100s: "
572 "%.100s", config, strerror(errno));
574 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
575 _PATH_SSH_USER_CONFFILE);
576 if (r > 0 && (size_t)r < sizeof(buf))
577 (void)read_config_file(buf, pw, host, host_name,
578 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
579 (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
581 /* Read systemwide configuration file after user config. */
582 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
583 host, host_name, &options,
584 final_pass ? SSHCONF_FINAL : 0, want_final_pass);
588 /* Rewrite the port number in an addrinfo list of addresses */
590 set_addrinfo_port(struct addrinfo *addrs, int port)
592 struct addrinfo *addr;
594 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
595 switch (addr->ai_family) {
597 ((struct sockaddr_in *)addr->ai_addr)->
598 sin_port = htons(port);
601 ((struct sockaddr_in6 *)addr->ai_addr)->
602 sin6_port = htons(port);
609 ssh_conn_info_free(struct ssh_conn_info *cinfo)
613 free(cinfo->conn_hash_hex);
614 free(cinfo->shorthost);
616 free(cinfo->keyalias);
617 free(cinfo->thishost);
618 free(cinfo->host_arg);
619 free(cinfo->portstr);
620 free(cinfo->remhost);
621 free(cinfo->remuser);
622 free(cinfo->homedir);
623 free(cinfo->locuser);
628 * Main program for the ssh client.
631 main(int ac, char **av)
633 struct ssh *ssh = NULL;
634 int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
635 int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
636 char *p, *cp, *line, *argv0, *logfile;
637 char cname[NI_MAXHOST], thishost[NI_MAXHOST];
640 extern int optind, optreset;
643 struct addrinfo *addrs = NULL;
646 struct ssh_conn_info *cinfo = NULL;
648 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
652 * Discard other fds that are hanging around. These can cause problem
653 * with backgrounded ssh processes started by ControlPersist.
655 closefrom(STDERR_FILENO + 1);
657 __progname = ssh_get_progname(av[0]);
659 #ifndef HAVE_SETPROCTITLE
660 /* Prepare for later setproctitle emulation */
661 /* Save argv so it isn't clobbered by setproctitle() emulation */
662 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
663 for (i = 0; i < ac; i++)
664 saved_av[i] = xstrdup(av[i]);
666 compat_init_setproctitle(ac, av);
673 pw = getpwuid(getuid());
675 logit("No user exists for uid %lu", (u_long)getuid());
678 /* Take a copy of the returned structure. */
682 * Set our umask to something reasonable, as some files are created
683 * with the default umask. This will make them world-readable but
684 * writable only by the owner, which is ok for all files for which we
685 * don't set the modes explicitly.
687 umask(022 | umask(077));
692 * Initialize option structure to indicate that no values have been
695 initialize_options(&options);
698 * Prepare main ssh transport/connection structures
700 if ((ssh = ssh_alloc_session_state()) == NULL)
701 fatal("Couldn't allocate session state");
702 channel_init_channels(ssh);
704 /* Parse command-line arguments. */
711 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
712 "AB:CD:E:F:GI:J:KL:MNO:P:Q:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
715 fatal("SSH protocol v.1 is no longer supported");
721 options.address_family = AF_INET;
724 options.address_family = AF_INET6;
727 options.stdin_null = 1;
730 options.fork_after_authentication = 1;
731 options.stdin_null = 1;
734 options.forward_x11 = 0;
737 options.forward_x11 = 1;
749 options.forward_x11 = 1;
750 options.forward_x11_trusted = 1;
753 options.fwd_opts.gateway_ports = 1;
756 if (options.stdio_forward_host != NULL)
757 fatal("Cannot specify multiplexing "
759 else if (muxclient_command != 0)
760 fatal("Multiplexing command already specified");
761 if (strcmp(optarg, "check") == 0)
762 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
763 else if (strcmp(optarg, "forward") == 0)
764 muxclient_command = SSHMUX_COMMAND_FORWARD;
765 else if (strcmp(optarg, "exit") == 0)
766 muxclient_command = SSHMUX_COMMAND_TERMINATE;
767 else if (strcmp(optarg, "stop") == 0)
768 muxclient_command = SSHMUX_COMMAND_STOP;
769 else if (strcmp(optarg, "cancel") == 0)
770 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
771 else if (strcmp(optarg, "proxy") == 0)
772 muxclient_command = SSHMUX_COMMAND_PROXY;
774 fatal("Invalid multiplex command.");
777 if (options.tag == NULL)
778 options.tag = xstrdup(optarg);
782 if (strcmp(optarg, "cipher") == 0 ||
783 strcasecmp(optarg, "Ciphers") == 0)
784 cp = cipher_alg_list('\n', 0);
785 else if (strcmp(optarg, "cipher-auth") == 0)
786 cp = cipher_alg_list('\n', 1);
787 else if (strcmp(optarg, "mac") == 0 ||
788 strcasecmp(optarg, "MACs") == 0)
789 cp = mac_alg_list('\n');
790 else if (strcmp(optarg, "kex") == 0 ||
791 strcasecmp(optarg, "KexAlgorithms") == 0)
792 cp = kex_alg_list('\n');
793 else if (strcmp(optarg, "key") == 0)
794 cp = sshkey_alg_list(0, 0, 0, '\n');
795 else if (strcmp(optarg, "key-cert") == 0)
796 cp = sshkey_alg_list(1, 0, 0, '\n');
797 else if (strcmp(optarg, "key-plain") == 0)
798 cp = sshkey_alg_list(0, 1, 0, '\n');
799 else if (strcmp(optarg, "key-ca-sign") == 0 ||
800 strcasecmp(optarg, "CASignatureAlgorithms") == 0)
801 cp = sshkey_alg_list(0, 1, 1, '\n');
802 else if (strcmp(optarg, "key-sig") == 0 ||
803 strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
804 strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
805 strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
806 strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
807 strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
808 strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
809 cp = sshkey_alg_list(0, 0, 1, '\n');
810 else if (strcmp(optarg, "sig") == 0)
811 cp = sshkey_alg_list(0, 1, 1, '\n');
812 else if (strcmp(optarg, "protocol-version") == 0)
814 else if (strcmp(optarg, "compression") == 0) {
815 cp = xstrdup(compression_alg_list(0));
817 for (n = 0; n < len; n++)
820 } else if (strcmp(optarg, "help") == 0) {
822 "cipher\ncipher-auth\ncompression\nkex\n"
823 "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
824 "protocol-version\nsig");
827 fatal("Unsupported query \"%s\"", optarg);
833 options.forward_agent = 0;
836 options.forward_agent = 1;
839 options.gss_deleg_creds = 0;
842 options.gss_authentication = 1;
843 options.gss_deleg_creds = 1;
846 p = tilde_expand_filename(optarg, getuid());
847 if (stat(p, &st) == -1)
848 fprintf(stderr, "Warning: Identity file %s "
849 "not accessible: %s.\n", p,
852 add_identity_file(&options, NULL, p, 1);
857 free(options.pkcs11_provider);
858 options.pkcs11_provider = xstrdup(optarg);
860 fprintf(stderr, "no support for PKCS#11.\n");
864 if (options.jump_host != NULL) {
865 fatal("Only a single -J option is permitted "
866 "(use commas to separate multiple "
869 if (options.proxy_command != NULL)
870 fatal("Cannot specify -J with ProxyCommand");
871 if (parse_jump(optarg, &options, 1) == -1)
872 fatal("Invalid -J argument");
873 options.proxy_command = xstrdup("none");
876 if (options.request_tty == REQUEST_TTY_YES)
877 options.request_tty = REQUEST_TTY_FORCE;
879 options.request_tty = REQUEST_TTY_YES;
882 if (debug_flag == 0) {
884 options.log_level = SYSLOG_LEVEL_DEBUG1;
886 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
893 fprintf(stderr, "%s, %s\n",
894 SSH_RELEASE, SSH_OPENSSL_VERSION);
898 if (options.tun_open == -1)
899 options.tun_open = SSH_TUNMODE_DEFAULT;
900 options.tun_local = a2tun(optarg, &options.tun_remote);
901 if (options.tun_local == SSH_TUNID_ERR) {
903 "Bad tun device '%s'\n", optarg);
908 if (options.stdio_forward_host != NULL)
909 fatal("stdio forward already specified");
910 if (muxclient_command != 0)
911 fatal("Cannot specify stdio forward with -O");
912 if (parse_forward(&fwd, optarg, 1, 0)) {
913 options.stdio_forward_host =
914 fwd.listen_port == PORT_STREAMLOCAL ?
915 fwd.listen_path : fwd.listen_host;
916 options.stdio_forward_port = fwd.listen_port;
917 free(fwd.connect_host);
920 "Bad stdio forwarding specification '%s'\n",
924 options.request_tty = REQUEST_TTY_NO;
925 options.session_type = SESSION_TYPE_NONE;
928 options.log_level = SYSLOG_LEVEL_QUIET;
931 if (optarg[0] == '^' && optarg[2] == 0 &&
932 (u_char) optarg[1] >= 64 &&
933 (u_char) optarg[1] < 128)
934 options.escape_char = (u_char) optarg[1] & 31;
935 else if (strlen(optarg) == 1)
936 options.escape_char = (u_char) optarg[0];
937 else if (strcmp(optarg, "none") == 0)
938 options.escape_char = SSH_ESCAPECHAR_NONE;
940 fprintf(stderr, "Bad escape character '%s'.\n",
946 if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
947 optarg + 1 : optarg)) {
948 fprintf(stderr, "Unknown cipher type '%s'\n",
952 free(options.ciphers);
953 options.ciphers = xstrdup(optarg);
956 if (mac_valid(optarg)) {
958 options.macs = xstrdup(optarg);
960 fprintf(stderr, "Unknown mac type '%s'\n",
966 if (options.control_master == SSHCTL_MASTER_YES)
967 options.control_master = SSHCTL_MASTER_ASK;
969 options.control_master = SSHCTL_MASTER_YES;
972 if (options.port == -1) {
973 options.port = a2port(optarg);
974 if (options.port <= 0) {
975 fprintf(stderr, "Bad port '%s'\n",
982 if (options.user == NULL)
983 options.user = optarg;
987 if (parse_forward(&fwd, optarg, 0, 0))
988 add_local_forward(&options, &fwd);
991 "Bad local forwarding specification '%s'\n",
998 if (parse_forward(&fwd, optarg, 0, 1) ||
999 parse_forward(&fwd, optarg, 1, 1)) {
1000 add_remote_forward(&options, &fwd);
1003 "Bad remote forwarding specification "
1010 if (parse_forward(&fwd, optarg, 1, 0)) {
1011 add_local_forward(&options, &fwd);
1014 "Bad dynamic forwarding specification "
1022 options.compression = 1;
1024 error("Compression not supported, disabling.");
1028 if (options.session_type != -1 &&
1029 options.session_type != SESSION_TYPE_NONE)
1030 fatal("Cannot specify -N with -s/SessionType");
1031 options.session_type = SESSION_TYPE_NONE;
1032 options.request_tty = REQUEST_TTY_NO;
1035 options.request_tty = REQUEST_TTY_NO;
1038 line = xstrdup(optarg);
1039 if (process_config_line(&options, pw,
1040 host ? host : "", host ? host : "", line,
1041 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1046 if (options.session_type != -1 &&
1047 options.session_type != SESSION_TYPE_SUBSYSTEM)
1048 fatal("Cannot specify -s with -N/SessionType");
1049 options.session_type = SESSION_TYPE_SUBSYSTEM;
1052 free(options.control_path);
1053 options.control_path = xstrdup(optarg);
1056 options.bind_address = optarg;
1059 options.bind_interface = optarg;
1069 if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1075 if (ac > 0 && !host) {
1078 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1083 if (options.user == NULL) {
1084 options.user = tuser;
1088 if (options.port == -1 && tport != -1)
1089 options.port = tport;
1093 cp = strrchr(p, '@');
1097 if (options.user == NULL) {
1108 if (ac > 1 && !opt_terminated) {
1109 optind = optreset = 1;
1115 /* Check that we got a host name. */
1119 options.host_arg = xstrdup(host);
1121 /* Initialize the command to execute on remote host. */
1122 if ((command = sshbuf_new()) == NULL)
1123 fatal("sshbuf_new failed");
1126 * Save the command to execute on the remote host in a buffer. There
1127 * is no limit on the length of the command, except by the maximum
1128 * packet size. Also sets the tty flag if there is no command.
1131 /* No command specified - execute shell on a tty. */
1132 if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1134 "You must specify a subsystem to invoke.\n");
1138 /* A command has been specified. Store it into the buffer. */
1139 for (i = 0; i < ac; i++) {
1140 if ((r = sshbuf_putf(command, "%s%s",
1141 i ? " " : "", av[i])) != 0)
1142 fatal_fr(r, "buffer error");
1146 ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1149 * Initialize "log" output. Since we are the client all output
1150 * goes to stderr unless otherwise specified by -y or -E.
1152 if (use_syslog && logfile != NULL)
1153 fatal("Can't specify both -y and -E");
1154 if (logfile != NULL)
1155 log_redirect_stderr_to(logfile);
1157 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1158 SYSLOG_LEVEL_INFO : options.log_level,
1159 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1160 SYSLOG_FACILITY_USER : options.log_facility,
1164 logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1166 /* Parse the configuration files */
1167 process_config_files(options.host_arg, pw, 0, &want_final_pass);
1168 if (want_final_pass)
1169 debug("configuration requests final Match pass");
1171 /* Hostname canonicalisation needs a few options filled. */
1172 fill_default_options_for_canonicalization(&options);
1174 /* If the user has replaced the hostname then take it into use now */
1175 if (options.hostname != NULL) {
1176 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1177 cp = percent_expand(options.hostname,
1178 "h", host, (char *)NULL);
1181 free(options.hostname);
1182 options.hostname = xstrdup(host);
1185 /* Don't lowercase addresses, they will be explicitly canonicalised */
1186 if ((was_addr = is_addr(host)) == 0)
1190 * Try to canonicalize if requested by configuration or the
1191 * hostname is an address.
1193 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1194 addrs = resolve_canonicalize(&host, options.port);
1197 * If CanonicalizePermittedCNAMEs have been specified but
1198 * other canonicalization did not happen (by not being requested
1199 * or by failing with fallback) then the hostname may still be changed
1200 * as a result of CNAME following.
1202 * Try to resolve the bare hostname name using the system resolver's
1203 * usual search rules and then apply the CNAME follow rules.
1205 * Skip the lookup if a ProxyCommand is being used unless the user
1206 * has specifically requested canonicalisation for this case via
1207 * CanonicalizeHostname=always
1209 direct = option_clear_or_none(options.proxy_command) &&
1210 option_clear_or_none(options.jump_host);
1211 if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1212 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1213 if ((addrs = resolve_host(host, options.port,
1214 direct, cname, sizeof(cname))) == NULL) {
1215 /* Don't fatal proxied host names not in the DNS */
1217 cleanup_exit(255); /* logged in resolve_host */
1219 check_follow_cname(direct, &host, cname);
1223 * If canonicalisation is enabled then re-parse the configuration
1224 * files as new stanzas may match.
1226 if (options.canonicalize_hostname != 0 && !want_final_pass) {
1227 debug("hostname canonicalisation enabled, "
1228 "will re-parse configuration");
1229 want_final_pass = 1;
1232 if (want_final_pass) {
1233 debug("re-parsing configuration");
1234 free(options.hostname);
1235 options.hostname = xstrdup(host);
1236 process_config_files(options.host_arg, pw, 1, NULL);
1238 * Address resolution happens early with canonicalisation
1239 * enabled and the port number may have changed since, so
1240 * reset it in address list
1242 if (addrs != NULL && options.port > 0)
1243 set_addrinfo_port(addrs, options.port);
1246 /* Fill configuration defaults. */
1247 if (fill_default_options(&options) != 0)
1250 if (options.user == NULL)
1251 options.user = xstrdup(pw->pw_name);
1254 * If ProxyJump option specified, then construct a ProxyCommand now.
1256 if (options.jump_host != NULL) {
1258 const char *jumpuser = options.jump_user, *sshbin = argv0;
1259 int port = options.port, jumpport = options.jump_port;
1262 port = default_ssh_port();
1264 jumpport = default_ssh_port();
1265 if (jumpuser == NULL)
1266 jumpuser = options.user;
1267 if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1268 strcmp(options.user, jumpuser) == 0)
1269 fatal("jumphost loop via %s", options.jump_host);
1272 * Try to use SSH indicated by argv[0], but fall back to
1273 * "ssh" if it appears unavailable.
1275 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1278 /* Consistency check */
1279 if (options.proxy_command != NULL)
1280 fatal("inconsistent options: ProxyCommand+ProxyJump");
1281 /* Never use FD passing for ProxyJump */
1282 options.proxy_use_fdpass = 0;
1283 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1284 xasprintf(&options.proxy_command,
1285 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1287 /* Optional "-l user" argument if jump_user set */
1288 options.jump_user == NULL ? "" : " -l ",
1289 options.jump_user == NULL ? "" : options.jump_user,
1290 /* Optional "-p port" argument if jump_port set */
1291 options.jump_port <= 0 ? "" : " -p ",
1292 options.jump_port <= 0 ? "" : port_s,
1293 /* Optional additional jump hosts ",..." */
1294 options.jump_extra == NULL ? "" : " -J ",
1295 options.jump_extra == NULL ? "" : options.jump_extra,
1296 /* Optional "-F" argument if -F specified */
1297 config == NULL ? "" : " -F ",
1298 config == NULL ? "" : config,
1299 /* Optional "-v" arguments if -v set */
1300 debug_flag ? " -" : "",
1302 /* Mandatory hostname */
1304 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1305 options.proxy_command);
1308 if (options.port == 0)
1309 options.port = default_ssh_port();
1310 channel_set_af(ssh, options.address_family);
1312 /* Tidy and check options */
1313 if (options.host_key_alias != NULL)
1314 lowercase(options.host_key_alias);
1315 if (options.proxy_command != NULL &&
1316 strcmp(options.proxy_command, "-") == 0 &&
1317 options.proxy_use_fdpass)
1318 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1319 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1320 if (options.control_persist && options.control_path != NULL) {
1321 debug("UpdateHostKeys=ask is incompatible with "
1322 "ControlPersist; disabling");
1323 options.update_hostkeys = 0;
1324 } else if (sshbuf_len(command) != 0 ||
1325 options.remote_command != NULL ||
1326 options.request_tty == REQUEST_TTY_NO) {
1327 debug("UpdateHostKeys=ask is incompatible with "
1328 "remote command execution; disabling");
1329 options.update_hostkeys = 0;
1330 } else if (options.log_level < SYSLOG_LEVEL_INFO) {
1331 /* no point logging anything; user won't see it */
1332 options.update_hostkeys = 0;
1335 if (options.connection_attempts <= 0)
1336 fatal("Invalid number of ConnectionAttempts");
1338 if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1339 fatal("Cannot execute command-line and remote command.");
1341 /* Cannot fork to background if no command. */
1342 if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1343 options.remote_command == NULL &&
1344 options.session_type != SESSION_TYPE_NONE)
1345 fatal("Cannot fork into background without a command "
1349 log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1350 for (j = 0; j < options.num_log_verbose; j++) {
1351 if (strcasecmp(options.log_verbose[j], "none") == 0)
1353 log_verbose_add(options.log_verbose[j]);
1356 if (options.request_tty == REQUEST_TTY_YES ||
1357 options.request_tty == REQUEST_TTY_FORCE)
1360 /* Allocate a tty by default if no command specified. */
1361 if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1362 tty_flag = options.request_tty != REQUEST_TTY_NO;
1365 if (options.request_tty == REQUEST_TTY_NO ||
1366 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1367 options.session_type == SESSION_TYPE_NONE)
1369 /* Do not allocate a tty if stdin is not a tty. */
1370 if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1371 options.request_tty != REQUEST_TTY_FORCE) {
1373 logit("Pseudo-terminal will not be allocated because "
1374 "stdin is not a terminal.");
1378 /* Set up strings used to percent_expand() arguments */
1379 cinfo = xcalloc(1, sizeof(*cinfo));
1380 if (gethostname(thishost, sizeof(thishost)) == -1)
1381 fatal("gethostname: %s", strerror(errno));
1382 cinfo->thishost = xstrdup(thishost);
1383 thishost[strcspn(thishost, ".")] = '\0';
1384 cinfo->shorthost = xstrdup(thishost);
1385 xasprintf(&cinfo->portstr, "%d", options.port);
1386 xasprintf(&cinfo->uidstr, "%llu",
1387 (unsigned long long)pw->pw_uid);
1388 cinfo->keyalias = xstrdup(options.host_key_alias ?
1389 options.host_key_alias : options.host_arg);
1390 cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1391 cinfo->portstr, options.user);
1392 cinfo->host_arg = xstrdup(options.host_arg);
1393 cinfo->remhost = xstrdup(host);
1394 cinfo->remuser = xstrdup(options.user);
1395 cinfo->homedir = xstrdup(pw->pw_dir);
1396 cinfo->locuser = xstrdup(pw->pw_name);
1398 /* Find canonic host name. */
1399 if (strchr(host, '.') == NULL) {
1400 struct addrinfo hints;
1401 struct addrinfo *ai = NULL;
1404 memset(&hints, 0, sizeof(hints));
1405 hints.ai_family = options.address_family;
1406 hints.ai_flags = AI_CANONNAME;
1407 hints.ai_socktype = SOCK_STREAM;
1408 errgai = getaddrinfo(host, NULL, &hints, &ai);
1410 if (ai->ai_canonname != NULL) {
1412 host = xstrdup(ai->ai_canonname);
1419 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1420 * after port-forwarding is set up, so it may pick up any local
1421 * tunnel interface name allocated.
1423 if (options.remote_command != NULL) {
1424 debug3("expanding RemoteCommand: %s", options.remote_command);
1425 cp = options.remote_command;
1426 options.remote_command = default_client_percent_expand(cp,
1428 debug3("expanded RemoteCommand: %s", options.remote_command);
1430 if ((r = sshbuf_put(command, options.remote_command,
1431 strlen(options.remote_command))) != 0)
1432 fatal_fr(r, "buffer error");
1435 if (options.control_path != NULL) {
1436 cp = tilde_expand_filename(options.control_path, getuid());
1437 free(options.control_path);
1438 options.control_path = default_client_percent_dollar_expand(cp,
1443 if (options.identity_agent != NULL) {
1444 p = tilde_expand_filename(options.identity_agent, getuid());
1445 cp = default_client_percent_dollar_expand(p, cinfo);
1447 free(options.identity_agent);
1448 options.identity_agent = cp;
1451 if (options.revoked_host_keys != NULL) {
1452 p = tilde_expand_filename(options.revoked_host_keys, getuid());
1453 cp = default_client_percent_dollar_expand(p, cinfo);
1455 free(options.revoked_host_keys);
1456 options.revoked_host_keys = cp;
1459 if (options.forward_agent_sock_path != NULL) {
1460 p = tilde_expand_filename(options.forward_agent_sock_path,
1462 cp = default_client_percent_dollar_expand(p, cinfo);
1464 free(options.forward_agent_sock_path);
1465 options.forward_agent_sock_path = cp;
1466 if (stat(options.forward_agent_sock_path, &st) != 0) {
1467 error("Cannot forward agent socket path \"%s\": %s",
1468 options.forward_agent_sock_path, strerror(errno));
1469 if (options.exit_on_forward_failure)
1474 if (options.num_system_hostfiles > 0 &&
1475 strcasecmp(options.system_hostfiles[0], "none") == 0) {
1476 if (options.num_system_hostfiles > 1)
1477 fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1478 "appears with other entries");
1479 free(options.system_hostfiles[0]);
1480 options.system_hostfiles[0] = NULL;
1481 options.num_system_hostfiles = 0;
1484 if (options.num_user_hostfiles > 0 &&
1485 strcasecmp(options.user_hostfiles[0], "none") == 0) {
1486 if (options.num_user_hostfiles > 1)
1487 fatal("Invalid UserKnownHostsFiles: \"none\" "
1488 "appears with other entries");
1489 free(options.user_hostfiles[0]);
1490 options.user_hostfiles[0] = NULL;
1491 options.num_user_hostfiles = 0;
1493 for (j = 0; j < options.num_user_hostfiles; j++) {
1494 if (options.user_hostfiles[j] == NULL)
1496 cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1497 p = default_client_percent_dollar_expand(cp, cinfo);
1498 if (strcmp(options.user_hostfiles[j], p) != 0)
1499 debug3("expanded UserKnownHostsFile '%s' -> "
1500 "'%s'", options.user_hostfiles[j], p);
1501 free(options.user_hostfiles[j]);
1503 options.user_hostfiles[j] = p;
1506 for (i = 0; i < options.num_local_forwards; i++) {
1507 if (options.local_forwards[i].listen_path != NULL) {
1508 cp = options.local_forwards[i].listen_path;
1509 p = options.local_forwards[i].listen_path =
1510 default_client_percent_expand(cp, cinfo);
1511 if (strcmp(cp, p) != 0)
1512 debug3("expanded LocalForward listen path "
1513 "'%s' -> '%s'", cp, p);
1516 if (options.local_forwards[i].connect_path != NULL) {
1517 cp = options.local_forwards[i].connect_path;
1518 p = options.local_forwards[i].connect_path =
1519 default_client_percent_expand(cp, cinfo);
1520 if (strcmp(cp, p) != 0)
1521 debug3("expanded LocalForward connect path "
1522 "'%s' -> '%s'", cp, p);
1527 for (i = 0; i < options.num_remote_forwards; i++) {
1528 if (options.remote_forwards[i].listen_path != NULL) {
1529 cp = options.remote_forwards[i].listen_path;
1530 p = options.remote_forwards[i].listen_path =
1531 default_client_percent_expand(cp, cinfo);
1532 if (strcmp(cp, p) != 0)
1533 debug3("expanded RemoteForward listen path "
1534 "'%s' -> '%s'", cp, p);
1537 if (options.remote_forwards[i].connect_path != NULL) {
1538 cp = options.remote_forwards[i].connect_path;
1539 p = options.remote_forwards[i].connect_path =
1540 default_client_percent_expand(cp, cinfo);
1541 if (strcmp(cp, p) != 0)
1542 debug3("expanded RemoteForward connect path "
1543 "'%s' -> '%s'", cp, p);
1549 dump_client_config(&options, host);
1553 /* Expand SecurityKeyProvider if it refers to an environment variable */
1554 if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1555 strlen(options.sk_provider) > 1) {
1556 if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1557 debug("Authenticator provider %s did not resolve; "
1558 "disabling", options.sk_provider);
1559 free(options.sk_provider);
1560 options.sk_provider = NULL;
1562 debug2("resolved SecurityKeyProvider %s => %s",
1563 options.sk_provider, cp);
1564 free(options.sk_provider);
1565 options.sk_provider = xstrdup(cp);
1569 if (muxclient_command != 0 && options.control_path == NULL)
1570 fatal("No ControlPath specified for \"-O\" command");
1571 if (options.control_path != NULL) {
1573 if ((sock = muxclient(options.control_path)) >= 0) {
1574 ssh_packet_set_connection(ssh, sock, sock);
1575 ssh_packet_set_mux(ssh);
1581 * If hostname canonicalisation was not enabled, then we may not
1582 * have yet resolved the hostname. Do so now.
1584 if (addrs == NULL && options.proxy_command == NULL) {
1585 debug2("resolving \"%s\" port %d", host, options.port);
1586 if ((addrs = resolve_host(host, options.port, 1,
1587 cname, sizeof(cname))) == NULL)
1588 cleanup_exit(255); /* resolve_host logs the error */
1591 if (options.connection_timeout >= INT_MAX/1000)
1592 timeout_ms = INT_MAX;
1594 timeout_ms = options.connection_timeout * 1000;
1596 /* Open a connection to the remote host. */
1597 if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1598 options.port, options.connection_attempts,
1599 &timeout_ms, options.tcp_keep_alive) != 0)
1603 freeaddrinfo(addrs);
1605 ssh_packet_set_timeout(ssh, options.server_alive_interval,
1606 options.server_alive_count_max);
1609 debug3("timeout: %d ms remain after connect", timeout_ms);
1612 * If we successfully made the connection and we have hostbased auth
1613 * enabled, load the public keys so we can later use the ssh-keysign
1614 * helper to sign challenges.
1616 sensitive_data.nkeys = 0;
1617 sensitive_data.keys = NULL;
1618 if (options.hostbased_authentication) {
1621 sensitive_data.nkeys = 10;
1622 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1623 sizeof(*sensitive_data.keys));
1625 /* XXX check errors? */
1626 #define L_PUBKEY(p,o) do { \
1627 if ((o) >= sensitive_data.nkeys) \
1628 fatal_f("pubkey out of array bounds"); \
1629 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1630 &(sensitive_data.keys[o]), p, "pubkey"); \
1631 if (sensitive_data.keys[o] != NULL) { \
1632 debug2("hostbased key %d: %s key from \"%s\"", o, \
1633 sshkey_ssh_name(sensitive_data.keys[o]), p); \
1637 #define L_CERT(p,o) do { \
1638 if ((o) >= sensitive_data.nkeys) \
1639 fatal_f("cert out of array bounds"); \
1640 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1641 &(sensitive_data.keys[o]), p, "cert"); \
1642 if (sensitive_data.keys[o] != NULL) { \
1643 debug2("hostbased key %d: %s cert from \"%s\"", o, \
1644 sshkey_ssh_name(sensitive_data.keys[o]), p); \
1649 if (options.hostbased_authentication == 1) {
1650 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1651 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1652 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1653 L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1654 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1655 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1656 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1657 L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1658 L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1659 L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1661 debug("HostbasedAuthentication enabled but no "
1662 "local public host keys could be loaded.");
1666 /* load options.identity_files */
1667 load_public_identity_files(cinfo);
1669 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1670 if (options.identity_agent &&
1671 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1672 if (strcmp(options.identity_agent, "none") == 0) {
1673 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1675 cp = options.identity_agent;
1676 /* legacy (limited) format */
1677 if (cp[0] == '$' && cp[1] != '{') {
1678 if (!valid_env_name(cp + 1)) {
1679 fatal("Invalid IdentityAgent "
1680 "environment variable name %s", cp);
1682 if ((p = getenv(cp + 1)) == NULL)
1683 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1685 setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1687 /* identity_agent specifies a path directly */
1688 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1693 if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1694 cp = options.forward_agent_sock_path;
1696 if (!valid_env_name(cp + 1)) {
1697 fatal("Invalid ForwardAgent environment variable name %s", cp);
1699 if ((p = getenv(cp + 1)) != NULL)
1700 forward_agent_sock_path = xstrdup(p);
1702 options.forward_agent = 0;
1705 forward_agent_sock_path = cp;
1709 /* Expand ~ in known host file names. */
1710 tilde_expand_paths(options.system_hostfiles,
1711 options.num_system_hostfiles);
1712 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1714 ssh_signal(SIGCHLD, main_sigchld_handler);
1716 /* Log into the remote system. Never returns if the login fails. */
1717 ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1718 options.port, pw, timeout_ms, cinfo);
1720 /* We no longer need the private host keys. Clear them now. */
1721 if (sensitive_data.nkeys != 0) {
1722 for (i = 0; i < sensitive_data.nkeys; i++) {
1723 if (sensitive_data.keys[i] != NULL) {
1724 /* Destroys contents safely */
1725 debug3("clear hostkey %d", i);
1726 sshkey_free(sensitive_data.keys[i]);
1727 sensitive_data.keys[i] = NULL;
1730 free(sensitive_data.keys);
1732 for (i = 0; i < options.num_identity_files; i++) {
1733 free(options.identity_files[i]);
1734 options.identity_files[i] = NULL;
1735 if (options.identity_keys[i]) {
1736 sshkey_free(options.identity_keys[i]);
1737 options.identity_keys[i] = NULL;
1740 for (i = 0; i < options.num_certificate_files; i++) {
1741 free(options.certificate_files[i]);
1742 options.certificate_files[i] = NULL;
1745 #ifdef ENABLE_PKCS11
1746 (void)pkcs11_del_provider(options.pkcs11_provider);
1750 exit_status = ssh_session2(ssh, cinfo);
1751 ssh_conn_info_free(cinfo);
1752 ssh_packet_close(ssh);
1754 if (options.control_path != NULL && muxserver_sock != -1)
1755 unlink(options.control_path);
1757 /* Kill ProxyCommand if it is running. */
1758 ssh_kill_proxy_command();
1764 control_persist_detach(void)
1768 debug_f("backgrounding master process");
1771 * master (current process) into the background, and make the
1772 * foreground process a client of the backgrounded master.
1774 switch ((pid = fork())) {
1776 fatal_f("fork: %s", strerror(errno));
1778 /* Child: master process continues mainloop */
1782 * Parent: set up mux client to connect to backgrounded
1785 debug2_f("background process is %ld", (long)pid);
1786 options.stdin_null = ostdin_null_flag;
1787 options.request_tty = orequest_tty;
1788 tty_flag = otty_flag;
1789 options.fork_after_authentication = ofork_after_authentication;
1790 options.session_type = osession_type;
1791 close(muxserver_sock);
1792 muxserver_sock = -1;
1793 options.control_master = SSHCTL_MASTER_NO;
1794 (void)muxclient(options.control_path);
1795 /* muxclient() doesn't return on success. */
1796 fatal("Failed to connect to new control master");
1798 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1799 error_f("stdfd_devnull failed");
1801 setproctitle("%s [mux]", options.control_path);
1804 /* Do fork() after authentication. Used by "ssh -f" */
1808 if (need_controlpersist_detach)
1809 control_persist_detach();
1810 debug("forking to background");
1811 options.fork_after_authentication = 0;
1812 if (daemon(1, 1) == -1)
1813 fatal("daemon() failed: %.200s", strerror(errno));
1814 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1815 error_f("stdfd_devnull failed");
1819 forwarding_success(void)
1821 if (forward_confirms_pending == -1)
1823 if (--forward_confirms_pending == 0) {
1824 debug_f("all expected forwarding replies received");
1825 if (options.fork_after_authentication)
1828 debug2_f("%d expected forwarding replies remaining",
1829 forward_confirms_pending);
1833 /* Callback for remote forward global requests */
1835 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1837 struct Forward *rfwd = (struct Forward *)ctxt;
1841 /* XXX verbose() on failure? */
1842 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1843 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1844 rfwd->listen_path ? rfwd->listen_path :
1845 rfwd->listen_host ? rfwd->listen_host : "",
1846 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1847 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1848 rfwd->connect_host, rfwd->connect_port);
1849 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1850 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1851 if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1852 fatal_fr(r, "parse packet");
1854 error("Invalid allocated port %u for remote "
1855 "forward to %s:%d", port,
1856 rfwd->connect_host, rfwd->connect_port);
1857 /* Ensure failure processing runs below */
1858 type = SSH2_MSG_REQUEST_FAILURE;
1859 channel_update_permission(ssh,
1862 rfwd->allocated_port = (int)port;
1863 logit("Allocated port %u for remote "
1865 rfwd->allocated_port, rfwd->connect_path ?
1866 rfwd->connect_path : rfwd->connect_host,
1867 rfwd->connect_port);
1868 channel_update_permission(ssh,
1869 rfwd->handle, rfwd->allocated_port);
1872 channel_update_permission(ssh, rfwd->handle, -1);
1876 if (type == SSH2_MSG_REQUEST_FAILURE) {
1877 if (options.exit_on_forward_failure) {
1878 if (rfwd->listen_path != NULL)
1879 fatal("Error: remote port forwarding failed "
1880 "for listen path %s", rfwd->listen_path);
1882 fatal("Error: remote port forwarding failed "
1883 "for listen port %d", rfwd->listen_port);
1885 if (rfwd->listen_path != NULL)
1886 logit("Warning: remote port forwarding failed "
1887 "for listen path %s", rfwd->listen_path);
1889 logit("Warning: remote port forwarding failed "
1890 "for listen port %d", rfwd->listen_port);
1893 forwarding_success();
1897 client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1899 debug("stdio forwarding: done");
1904 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1907 fatal("stdio forwarding failed");
1911 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1914 error("Tunnel forwarding failed");
1915 if (options.exit_on_forward_failure)
1919 debug_f("tunnel forward established, id=%d", id);
1920 forwarding_success();
1924 ssh_init_stdio_forwarding(struct ssh *ssh)
1929 if (options.stdio_forward_host == NULL)
1932 debug3_f("%s:%d", options.stdio_forward_host,
1933 options.stdio_forward_port);
1935 if ((in = dup(STDIN_FILENO)) == -1 ||
1936 (out = dup(STDOUT_FILENO)) == -1)
1937 fatal_f("dup() in/out failed");
1938 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1939 options.stdio_forward_port, in, out,
1940 CHANNEL_NONBLOCK_STDIO)) == NULL)
1941 fatal_f("channel_connect_stdio_fwd failed");
1942 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1943 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1947 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1952 char *addr, *arg, *oarg;
1953 int where = FORWARD_LOCAL;
1955 channel_clear_permission(ssh, FORWARD_ADM, where);
1957 return; /* permit any */
1959 /* handle keywords: "any" / "none" */
1960 if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1962 if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1963 channel_disable_admin(ssh, where);
1966 /* Otherwise treat it as a list of permitted host:port */
1967 for (i = 0; i < num_opens; i++) {
1968 oarg = arg = xstrdup(opens[i]);
1969 addr = hpdelim(&arg);
1971 fatal_f("missing host in %s", what);
1972 addr = cleanhostname(addr);
1973 if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1974 fatal_f("bad port number in %s", what);
1975 /* Send it to channels layer */
1976 channel_add_permission(ssh, FORWARD_ADM,
1983 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1988 ssh_init_forward_permissions(ssh, "permitremoteopen",
1989 options.permitted_remote_opens,
1990 options.num_permitted_remote_opens);
1992 if (options.exit_on_forward_failure)
1993 forward_confirms_pending = 0; /* track pending requests */
1994 /* Initiate local TCP/IP port forwardings. */
1995 for (i = 0; i < options.num_local_forwards; i++) {
1996 debug("Local connections to %.200s:%d forwarded to remote "
1997 "address %.200s:%d",
1998 (options.local_forwards[i].listen_path != NULL) ?
1999 options.local_forwards[i].listen_path :
2000 (options.local_forwards[i].listen_host == NULL) ?
2001 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
2002 options.local_forwards[i].listen_host,
2003 options.local_forwards[i].listen_port,
2004 (options.local_forwards[i].connect_path != NULL) ?
2005 options.local_forwards[i].connect_path :
2006 options.local_forwards[i].connect_host,
2007 options.local_forwards[i].connect_port);
2008 success += channel_setup_local_fwd_listener(ssh,
2009 &options.local_forwards[i], &options.fwd_opts);
2011 if (i > 0 && success != i && options.exit_on_forward_failure)
2012 fatal("Could not request local forwarding.");
2013 if (i > 0 && success == 0)
2014 error("Could not request local forwarding.");
2016 /* Initiate remote TCP/IP port forwardings. */
2017 for (i = 0; i < options.num_remote_forwards; i++) {
2018 debug("Remote connections from %.200s:%d forwarded to "
2019 "local address %.200s:%d",
2020 (options.remote_forwards[i].listen_path != NULL) ?
2021 options.remote_forwards[i].listen_path :
2022 (options.remote_forwards[i].listen_host == NULL) ?
2023 "LOCALHOST" : options.remote_forwards[i].listen_host,
2024 options.remote_forwards[i].listen_port,
2025 (options.remote_forwards[i].connect_path != NULL) ?
2026 options.remote_forwards[i].connect_path :
2027 options.remote_forwards[i].connect_host,
2028 options.remote_forwards[i].connect_port);
2029 if ((options.remote_forwards[i].handle =
2030 channel_request_remote_forwarding(ssh,
2031 &options.remote_forwards[i])) >= 0) {
2032 client_register_global_confirm(
2033 ssh_confirm_remote_forward,
2034 &options.remote_forwards[i]);
2035 forward_confirms_pending++;
2036 } else if (options.exit_on_forward_failure)
2037 fatal("Could not request remote forwarding.");
2039 logit("Warning: Could not request remote forwarding.");
2042 /* Initiate tunnel forwarding. */
2043 if (options.tun_open != SSH_TUNMODE_NO) {
2044 if ((*ifname = client_request_tun_fwd(ssh,
2045 options.tun_open, options.tun_local,
2046 options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2047 forward_confirms_pending++;
2048 else if (options.exit_on_forward_failure)
2049 fatal("Could not request tunnel forwarding.");
2051 error("Could not request tunnel forwarding.");
2053 if (forward_confirms_pending > 0) {
2054 debug_f("expecting replies for %d forwards",
2055 forward_confirms_pending);
2060 check_agent_present(void)
2064 if (options.forward_agent) {
2065 /* Clear agent forwarding if we don't have an agent. */
2066 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2067 options.forward_agent = 0;
2068 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2069 debug_r(r, "ssh_get_authentication_socket");
2075 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2077 extern char **environ;
2078 const char *display, *term;
2079 int r, interactive = tty_flag;
2080 char *proto = NULL, *data = NULL;
2083 return; /* No need for error message, channels code sends one */
2085 display = getenv("DISPLAY");
2086 if (display == NULL && options.forward_x11)
2087 debug("X11 forwarding requested but DISPLAY not set");
2088 if (options.forward_x11 && client_x11_get_proto(ssh, display,
2089 options.xauth_location, options.forward_x11_trusted,
2090 options.forward_x11_timeout, &proto, &data) == 0) {
2091 /* Request forwarding with authentication spoofing. */
2092 debug("Requesting X11 forwarding with authentication "
2094 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2096 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2097 /* XXX exit_on_forward_failure */
2101 check_agent_present();
2102 if (options.forward_agent) {
2103 debug("Requesting authentication agent forwarding.");
2104 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2105 if ((r = sshpkt_send(ssh)) != 0)
2106 fatal_fr(r, "send packet");
2109 /* Tell the packet module whether this is an interactive session. */
2110 ssh_packet_set_interactive(ssh, interactive,
2111 options.ip_qos_interactive, options.ip_qos_bulk);
2113 if ((term = lookup_env_in_list("TERM", options.setenv,
2114 options.num_setenv)) == NULL || *term == '\0')
2115 term = getenv("TERM");
2116 client_session2_setup(ssh, id, tty_flag,
2117 options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2118 NULL, fileno(stdin), command, environ);
2121 /* open new channel for a session */
2123 ssh_session2_open(struct ssh *ssh)
2126 int window, packetmax, in, out, err;
2128 if (options.stdin_null) {
2129 in = open(_PATH_DEVNULL, O_RDONLY);
2131 in = dup(STDIN_FILENO);
2133 out = dup(STDOUT_FILENO);
2134 err = dup(STDERR_FILENO);
2136 if (in == -1 || out == -1 || err == -1)
2137 fatal("dup() in/out/err failed");
2139 window = CHAN_SES_WINDOW_DEFAULT;
2140 packetmax = CHAN_SES_PACKET_DEFAULT;
2145 c = channel_new(ssh,
2146 "session", SSH_CHANNEL_OPENING, in, out, err,
2147 window, packetmax, CHAN_EXTENDED_WRITE,
2148 "client-session", CHANNEL_NONBLOCK_STDIO);
2150 debug3_f("channel_new: %d", c->self);
2152 channel_send_open(ssh, c->self);
2153 if (options.session_type != SESSION_TYPE_NONE)
2154 channel_register_open_confirm(ssh, c->self,
2155 ssh_session2_setup, NULL);
2161 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2163 int r, interactive, id = -1;
2164 char *cp, *tun_fwd_ifname = NULL;
2166 /* XXX should be pre-session */
2167 if (!options.control_persist)
2168 ssh_init_stdio_forwarding(ssh);
2170 ssh_init_forwarding(ssh, &tun_fwd_ifname);
2172 if (options.local_command != NULL) {
2173 debug3("expanding LocalCommand: %s", options.local_command);
2174 cp = options.local_command;
2175 options.local_command = percent_expand(cp,
2176 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2177 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2179 debug3("expanded LocalCommand: %s", options.local_command);
2183 /* Start listening for multiplex clients */
2184 if (!ssh_packet_get_mux(ssh))
2185 muxserver_listen(ssh);
2188 * If we are in control persist mode and have a working mux listen
2189 * socket, then prepare to background ourselves and have a foreground
2190 * client attach as a control client.
2191 * NB. we must save copies of the flags that we override for
2192 * the backgrounding, since we defer attachment of the client until
2193 * after the connection is fully established (in particular,
2194 * async rfwd replies have been received for ExitOnForwardFailure).
2196 if (options.control_persist && muxserver_sock != -1) {
2197 ostdin_null_flag = options.stdin_null;
2198 osession_type = options.session_type;
2199 orequest_tty = options.request_tty;
2200 otty_flag = tty_flag;
2201 ofork_after_authentication = options.fork_after_authentication;
2202 options.stdin_null = 1;
2203 options.session_type = SESSION_TYPE_NONE;
2205 if ((osession_type != SESSION_TYPE_NONE ||
2206 options.stdio_forward_host != NULL))
2207 need_controlpersist_detach = 1;
2208 options.fork_after_authentication = 1;
2211 * ControlPersist mux listen socket setup failed, attempt the
2212 * stdio forward setup that we skipped earlier.
2214 if (options.control_persist && muxserver_sock == -1)
2215 ssh_init_stdio_forwarding(ssh);
2217 if (options.session_type != SESSION_TYPE_NONE)
2218 id = ssh_session2_open(ssh);
2220 interactive = options.control_master == SSHCTL_MASTER_NO;
2221 /* ControlPersist may have clobbered ControlMaster, so check */
2222 if (need_controlpersist_detach)
2223 interactive = otty_flag != 0;
2224 ssh_packet_set_interactive(ssh, interactive,
2225 options.ip_qos_interactive, options.ip_qos_bulk);
2228 /* If we don't expect to open a new session, then disallow it */
2229 if (options.control_master == SSHCTL_MASTER_NO &&
2230 (ssh->compat & SSH_NEW_OPENSSH)) {
2231 debug("Requesting no-more-sessions@openssh.com");
2232 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2233 (r = sshpkt_put_cstring(ssh,
2234 "no-more-sessions@openssh.com")) != 0 ||
2235 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2236 (r = sshpkt_send(ssh)) != 0)
2237 fatal_fr(r, "send packet");
2240 /* Execute a local command */
2241 if (options.local_command != NULL &&
2242 options.permit_local_command)
2243 ssh_local_cmd(options.local_command);
2246 * stdout is now owned by the session channel; clobber it here
2247 * so future channel closes are propagated to the local fd.
2248 * NB. this can only happen after LocalCommand has completed,
2249 * as it may want to write to stdout.
2251 if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2252 error_f("stdfd_devnull failed");
2255 * If requested and we are not interested in replies to remote
2256 * forwarding requests, then let ssh continue in the background.
2258 if (options.fork_after_authentication) {
2259 if (options.exit_on_forward_failure &&
2260 options.num_remote_forwards > 0) {
2261 debug("deferring postauth fork until remote forward "
2262 "confirmation received");
2267 return client_loop(ssh, tty_flag, tty_flag ?
2268 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2271 /* Loads all IdentityFile and CertificateFile keys */
2273 load_public_identity_files(const struct ssh_conn_info *cinfo)
2275 char *filename, *cp;
2276 struct sshkey *public;
2278 u_int n_ids, n_certs;
2279 char *identity_files[SSH_MAX_IDENTITY_FILES];
2280 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2281 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2282 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2283 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2284 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2285 #ifdef ENABLE_PKCS11
2286 struct sshkey **keys = NULL;
2287 char **comments = NULL;
2291 n_ids = n_certs = 0;
2292 memset(identity_files, 0, sizeof(identity_files));
2293 memset(identity_keys, 0, sizeof(identity_keys));
2294 memset(identity_file_userprovided, 0,
2295 sizeof(identity_file_userprovided));
2296 memset(certificate_files, 0, sizeof(certificate_files));
2297 memset(certificates, 0, sizeof(certificates));
2298 memset(certificate_file_userprovided, 0,
2299 sizeof(certificate_file_userprovided));
2301 #ifdef ENABLE_PKCS11
2302 if (options.pkcs11_provider != NULL &&
2303 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2304 (pkcs11_init(!options.batch_mode) == 0) &&
2305 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2306 &keys, &comments)) > 0) {
2307 for (i = 0; i < nkeys; i++) {
2308 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2309 sshkey_free(keys[i]);
2313 identity_keys[n_ids] = keys[i];
2314 identity_files[n_ids] = comments[i]; /* transferred */
2320 #endif /* ENABLE_PKCS11 */
2321 for (i = 0; i < options.num_identity_files; i++) {
2322 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2323 strcasecmp(options.identity_files[i], "none") == 0) {
2324 free(options.identity_files[i]);
2325 options.identity_files[i] = NULL;
2328 cp = tilde_expand_filename(options.identity_files[i], getuid());
2329 filename = default_client_percent_dollar_expand(cp, cinfo);
2331 check_load(sshkey_load_public(filename, &public, NULL),
2332 &public, filename, "pubkey");
2333 debug("identity file %s type %d", filename,
2334 public ? public->type : -1);
2335 free(options.identity_files[i]);
2336 identity_files[n_ids] = filename;
2337 identity_keys[n_ids] = public;
2338 identity_file_userprovided[n_ids] =
2339 options.identity_file_userprovided[i];
2340 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2344 * If no certificates have been explicitly listed then try
2345 * to add the default certificate variant too.
2347 if (options.num_certificate_files != 0)
2349 xasprintf(&cp, "%s-cert", filename);
2350 check_load(sshkey_load_public(cp, &public, NULL),
2351 &public, filename, "pubkey");
2352 debug("identity file %s type %d", cp,
2353 public ? public->type : -1);
2354 if (public == NULL) {
2358 if (!sshkey_is_cert(public)) {
2359 debug_f("key %s type %s is not a certificate",
2360 cp, sshkey_type(public));
2361 sshkey_free(public);
2365 /* NB. leave filename pointing to private key */
2366 identity_files[n_ids] = xstrdup(filename);
2367 identity_keys[n_ids] = public;
2368 identity_file_userprovided[n_ids] =
2369 options.identity_file_userprovided[i];
2373 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2374 fatal_f("too many certificates");
2375 for (i = 0; i < options.num_certificate_files; i++) {
2376 cp = tilde_expand_filename(options.certificate_files[i],
2378 filename = default_client_percent_dollar_expand(cp, cinfo);
2381 check_load(sshkey_load_public(filename, &public, NULL),
2382 &public, filename, "certificate");
2383 debug("certificate file %s type %d", filename,
2384 public ? public->type : -1);
2385 free(options.certificate_files[i]);
2386 options.certificate_files[i] = NULL;
2387 if (public == NULL) {
2391 if (!sshkey_is_cert(public)) {
2392 debug_f("key %s type %s is not a certificate",
2393 filename, sshkey_type(public));
2394 sshkey_free(public);
2398 certificate_files[n_certs] = filename;
2399 certificates[n_certs] = public;
2400 certificate_file_userprovided[n_certs] =
2401 options.certificate_file_userprovided[i];
2405 options.num_identity_files = n_ids;
2406 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2407 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2408 memcpy(options.identity_file_userprovided,
2409 identity_file_userprovided, sizeof(identity_file_userprovided));
2411 options.num_certificate_files = n_certs;
2412 memcpy(options.certificate_files,
2413 certificate_files, sizeof(certificate_files));
2414 memcpy(options.certificates, certificates, sizeof(certificates));
2415 memcpy(options.certificate_file_userprovided,
2416 certificate_file_userprovided,
2417 sizeof(certificate_file_userprovided));
2421 main_sigchld_handler(int sig)
2423 int save_errno = errno;
2427 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2428 (pid == -1 && errno == EINTR))